neilxiao 2 years ago
parent bdeda904f3
commit 2529d6ba36
  1. 87
      README.md

@ -1,39 +1,46 @@
```js
#### 签名/解密方法实现
```javascript
// 安装包引用:
import SHA1 from 'crypto-js/sha1'
import { sm4 } from 'miniprogram-sm-crypto'
// 接口签名
// 接口加密
export const genSign = params => {
// 获取预先设置为环境变量的 APPKEY
let key = '{your secreat-key}'
let keys = []
for (let key in params) {
keys.push(key)
}
// 参数名 ASCII 码从小到大排序(字典序)
keys.sort()
// 转成键值对
let paramPair = []
for (let i = 0, len = keys.length; i < len; i++) {
let k = keys[i]
let itm = params[k]
if (typeof itm == 'object') {
itm = JSON.stringify(itm)
;(params || {}).timestamp = new Date().getTime()
// 删除值为空以及为undefined的数据
let newParam = {}
for (let key in params) {
if (params[key] !== '' && typeof params[key] != 'undefined')
newParam[key] = params[key]
}
paramPair.push(k + '=' + itm) // base64 编码
}
// 最后加上 key
paramPair.push('key=' + key)
// 拼接
let stringSignTemp = paramPair.join('&')
console.log('stringSignTemp:' + stringSignTemp)
let sign = SHA1(stringSignTemp).toString().toUpperCase()
return sign
params = newParam
// 获取预先设置为环境变量的 APPKEY
let key = '6612af2ed3b6119792a7340f894f46124130ed62'
let keys = []
for (let key in params) {
keys.push(key)
}
// 参数名 ASCII 码从小到大排序(字典序)
keys.sort()
// 转成键值对
let paramPair = []
for (let i = 0, len = keys.length; i < len; i++) {
let k = keys[i]
let itm = params[k]
if (typeof itm == 'object') {
itm = JSON.stringify(itm)
}
paramPair.push(k + '=' + itm) // base64 编码
}
// 最后加上 key
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' })
}
```
Loading…
Cancel
Save