|
|
|
@ -1,11 +1,20 @@ |
|
|
|
|
```js |
|
|
|
|
#### 签名/解密方法实现 |
|
|
|
|
```javascript |
|
|
|
|
// 安装包引用: |
|
|
|
|
import SHA1 from 'crypto-js/sha1' |
|
|
|
|
import { sm4 } from 'miniprogram-sm-crypto' |
|
|
|
|
|
|
|
|
|
// 接口签名 |
|
|
|
|
// 接口加密 |
|
|
|
|
export const genSign = params => { |
|
|
|
|
;(params || {}).timestamp = new Date().getTime() |
|
|
|
|
// 删除值为空以及为undefined的数据 |
|
|
|
|
let newParam = {} |
|
|
|
|
for (let key in params) { |
|
|
|
|
if (params[key] !== '' && typeof params[key] != 'undefined') |
|
|
|
|
newParam[key] = params[key] |
|
|
|
|
} |
|
|
|
|
params = newParam |
|
|
|
|
// 获取预先设置为环境变量的 APPKEY |
|
|
|
|
let key = '{your secreat-key}' |
|
|
|
|
let key = '6612af2ed3b6119792a7340f894f46124130ed62' |
|
|
|
|
let keys = [] |
|
|
|
|
for (let key in params) { |
|
|
|
|
keys.push(key) |
|
|
|
@ -26,14 +35,12 @@ export const genSign = params => { |
|
|
|
|
paramPair.push('key=' + key) |
|
|
|
|
// 拼接 |
|
|
|
|
let stringSignTemp = paramPair.join('&') |
|
|
|
|
|
|
|
|
|
console.log('stringSignTemp:' + stringSignTemp) |
|
|
|
|
let sign = SHA1(stringSignTemp).toString().toUpperCase() |
|
|
|
|
|
|
|
|
|
return sign |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
// 数据解密 |
|
|
|
|
// 解密 |
|
|
|
|
export const decodeData = data => { |
|
|
|
|
//字符串转byte数组 |
|
|
|
|
const stringToByte = function (str) { |
|
|
|
@ -60,8 +67,24 @@ export const decodeData = data => { |
|
|
|
|
} |
|
|
|
|
return bytes |
|
|
|
|
} |
|
|
|
|
const key = stringToByte('{your secreat-key1}') |
|
|
|
|
const key = stringToByte('1ba10d7bb99d9df8') |
|
|
|
|
return sm4.decrypt(data, key) |
|
|
|
|
} |
|
|
|
|
|
|
|
|
|
``` |
|
|
|
|
#### 使用示例 |
|
|
|
|
- 加密 : |
|
|
|
|
```javascript |
|
|
|
|
let signString =config.method == 'post' ? genSign(config.data) : genSign(config.params) |
|
|
|
|
``` |
|
|
|
|
- 解密: |
|
|
|
|
```javascript |
|
|
|
|
let data=JSON.parse(decodeData(response.data.data)) |
|
|
|
|
``` |
|
|
|
|
#### 注意 |
|
|
|
|
```javascript |
|
|
|
|
// 注意:因为浏览器会把get请求参数里面的空格用 '+'连接起来,这里需要引入qs包进行处理: |
|
|
|
|
import QS from 'qs' |
|
|
|
|
axios.defaults.paramsSerializer = function (params) { |
|
|
|
|
return QS.stringify(params, { arrayFormat: 'brackets' }) |
|
|
|
|
} |
|
|
|
|
``` |