1. 下载依赖文件
2. 引入文件
<script src="sm-crypto-qbNh29hHpQvU.js"></script>
3. 浏览器兼容性
支持 Chrome、Firefox、Edge 的最新版本,支持 IE 10、IE 11,不支持 IE 9 及以下版本。
4. 对称密钥(SM4)加解密
//生成密钥
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. 非对称密钥(SM2)加解密
//生成密钥,返回数据格式:{ privkeyhex: 'hex编码的私钥', pubkeyhex: 'hex编码的公钥' }
SM2.generateKeyPairHex()
//用公钥加密
SM2.encrypt('公钥', '要加密的明文', '密文编码(缺省为base64)')
//用私钥解密
SM2.decrypt('私钥', '被公钥加密的密文', '密文编码(缺省为base64)')
6. 计算摘要(SM3)
SM3.hash('原文', '摘要编码(缺省为hex)')
7. 异常处理
以上所有方法均为同步方法,如遇到异常会抛出 Error 对象,可按需捕获并提示,例如:
try {
var encrypted = SM4.encrypt('123', 'hello world');
console.log('encrypted: ', encrypted);
}
catch (err) {
alert('加密失败:' + err.message);
}
8. 计算文件摘要(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. 密钥处理
该库中所有方法使用的是16进制密钥,如果后端提供的密钥是base64格式的,需要对密钥进行转换。
// 将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();
}