You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
neilxiao
2529d6ba36
|
2 years ago | |
---|---|---|
README.md | 2 years ago |
README.md
签名/解密方法实现
// 安装包引用:
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 = '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) {
var bytes = new Array()
var len, c
len = str.length
for (var i = 0; i < len; i++) {
c = str.charCodeAt(i)
if (c >= 0x010000 && c <= 0x10ffff) {
bytes.push(((c >> 18) & 0x07) | 0xf0)
bytes.push(((c >> 12) & 0x3f) | 0x80)
bytes.push(((c >> 6) & 0x3f) | 0x80)
bytes.push((c & 0x3f) | 0x80)
} else if (c >= 0x000800 && c <= 0x00ffff) {
bytes.push(((c >> 12) & 0x0f) | 0xe0)
bytes.push(((c >> 6) & 0x3f) | 0x80)
bytes.push((c & 0x3f) | 0x80)
} else if (c >= 0x000080 && c <= 0x0007ff) {
bytes.push(((c >> 6) & 0x1f) | 0xc0)
bytes.push((c & 0x3f) | 0x80)
} else {
bytes.push(c & 0xff)
}
}
return bytes
}
const key = stringToByte('1ba10d7bb99d9df8')
return sm4.decrypt(data, key)
}
使用示例
- 加密 :
let signString =config.method == 'post' ? genSign(config.data) : genSign(config.params)
- 解密:
let data=JSON.parse(decodeData(response.data.data))
注意
// 注意:因为浏览器会把get请求参数里面的空格用 '+'连接起来,这里需要引入qs包进行处理:
import QS from 'qs'
axios.defaults.paramsSerializer = function (params) {
return QS.stringify(params, { arrayFormat: 'brackets' })
}