request-crypto-sm2
TypeScript icon, indicating that this package has built-in type declarations

1.1.11 • Public • Published

安装

npm install request-crypto-sm2 -S

使用

引入配置

// 引入配置
import { publicKey, privateKey, strKey, cipherMode } from '@/config'
import RequestCryptoSM2 from 'request-crypto-sm2'

初始化

// 初始化
const rcs2 = new RequestCryptoSM2(
  publicKey,
  privateKey,
  strKey,
  cipherMode,
  false // 调试,是否打印参数 默认fasle
)

加解密

// 加密
// 入参: obj对象 eg: { name: 'foo', age: 12 }
// 出参: params ajax的参数; sign 签名;
const { params, sign } = rcs2.encryptResult(data)

// 解密
// 入参: string
// 出参: string类型的json; 需要和后端约定返回数据为json类型的加密字符串;
const result = rcs2.decryptResult(data)
return result && JSON.parse(result) // 需要序列化

加密规则

params 对提交的参数进行SM2加密

sm2.doEncrypt(JSON.stringify({
  data // ajax提交的参数
  timestemp // 毫秒时间戳
  notice // 16位随机字符串 a-z0-9
}), privateKey, cipherMode)

sign

1、自然排序KEY, 按顺序取出value,用(-)分割。 会过滤掉null, '', undefined。

const data = {
  car: '鲁A12345',
  dog: true,
  cat: false,
  isNull: null,
  isEmpty: '',
  isUndefined: undefined,
  person: {
    name: '张三',
    age: 32,
    child: [{
      name: '张武',
      age: 12
    }, {
      name: '张燕',
      age: 6
    }]
  }
}
const a = _sortJsonByKeys(data)
console.log(a) // 鲁A12345-false-true-{"name":"张三","age":32,"child":[{"name":"张武","age":12},{"name":"张燕","age":6}]}

2、在末尾拼接上自定义的strKey用横线隔开

const strKey = '-auth'
// 即上一步的字符串变成
// 鲁A12345-false-true-{"name":"张三","age":32,"child":[{"name":"张武","age":12},{"name":"张燕","age":6}]}-auth

3、对此字符串进行MD5加密,即得到sign签名

Readme

Keywords

Package Sidebar

Install

npm i request-crypto-sm2

Weekly Downloads

1

Version

1.1.11

License

ISC

Unpacked Size

5.24 kB

Total Files

4

Last publish

Collaborators

  • 317401317m