Used by the National Secret Library before making the wheel

1. Download dependent files

Download Document

2. Import files

<script src="sm-crypto-qbNh29hHpQvU.js"></script>

3. Browser Compatibility

Support the latest versions of Chrome, Firefox, Edge, IE 10, IE 11, IE 9 and below are not supported.

4. Symmetric key (SM4) encryption and decryption

//生成密钥
SM4.generateKey()
//SM4加密
SM4.encrypt('密钥', '原文', {
    
     mode: '加密模式(ecb或cbc)', iv: 'cbc模式iv', encoding: '密文编码(hex或base64)' })
//SM4解密
SM4.decrypt('密钥', '密文', {
    
     mode: '加密模式(ecb或cbc)', iv: 'cbc模式iv', encoding: '密文编码(hex或base64)' })

5. Asymmetric key (SM2) encryption and decryption

//生成密钥,返回数据格式:{ privkeyhex: 'hex编码的私钥', pubkeyhex: 'hex编码的公钥' }
SM2.generateKeyPairHex()
//用公钥加密
SM2.encrypt('公钥', '要加密的明文', '密文编码(缺省为base64)')
//用私钥解密
SM2.decrypt('私钥', '被公钥加密的密文', '密文编码(缺省为base64)')

6. Computing Summary (SM3)

SM3.hash('原文', '摘要编码(缺省为hex)')

7. Exception handling

All the above methods are synchronous methods. If an exception is encountered, an Error object will be thrown, which can be captured and prompted as needed, for example:

try {
    
    
  var encrypted = SM4.encrypt('123', 'hello world');
  console.log('encrypted: ', encrypted);
}
catch (err) {
    
    
  alert('加密失败:' + err.message);
}

8. Calculating document summaries (SM3)

// file 为 File 对象,可通过 <input type="file" /> 获取:input.onchange = (e) => console.log(e.target.files[0]);
// 或通过 Blob 对象转换:var file = new File([blob], filename, { type: contentType, lastModified: Date.now() });
SM3.fileHash(file, '摘要编码(缺省为hex)', function (err, hash) {
    
    
  if (err) {
    
    
    alert('计算摘要失败:' + err.message);
  } else {
    
    
    alert('文件SM3摘要:' + hash);
  }
})

9. Key handling

All methods in this library use hexadecimal keys. If the key provided by the backend is in base64 format, the key needs to be converted.

// 将base64字符串,转成16进制
const base64toHEX = (base64) => {
    
    
  const raw = atob(base64);
  let HEX = '';
  for ( let i = 0; i < raw.length; i++ ) {
    
    
    const  _hex = raw.charCodeAt(i).toString(16)
    HEX += (_hex.length === 2 ? _hex : '0' + _hex);
  }
  return HEX.toUpperCase();
}

Guess you like

Origin blog.csdn.net/qq_36968599/article/details/118998143