node.js 实现国密算法
node.js 实现国密算法
搭建node环境
node.js下载
官网下载:http://nodejs.cn/download/
解压
tar -xvf node-v18.12.1-linux-x64.tar.xz
配环境变量
vi /etc/profile
最后加上这句话:export PATH=$PATH:/usr/local/node/bin
让新加的配置生效:source /etc/profile
配软连接
相当于全局变量,在任何文件夹都能查看版本信息
ln -s /usr/local/node/bin/node /usr/local/bin/
ln -s /usr/local/node/bin/npm /usr/local/bin/
成功搭建node.js环境
代码实现
通过gm-crypto密码算法库实现国密算法
安装gm-crypto
npm install gm-crypto
SM2
const { SM2 } = require('gm-crypto')
const { publicKey, privateKey } = SM2.generateKeyPair()
const originalData = '20201327ljm'
const encryptedData = SM2.encrypt(originalData, publicKey, {
inputEncoding: 'utf8',
outputEncoding: 'base64'
})
console.log(encryptedData)
const decryptedData = SM2.decrypt(encryptedData, privateKey, {
inputEncoding: 'base64',
outputEncoding: 'utf8'
})
console.log(decryptedData)
SM3
const { SM3 } = require('gm-crypto')
console.log(SM3.digest('20201327'))
console.log(SM3.digest('ljm', 'base64'))
console.log(SM3.digest('415', 'hex', 'base64'))
SM4
const { SM4 } = require('gm-crypto')
const key = '0123456789abcdeffedcba9876543210' // Any string of 32 hexadecimal digits
const originalData = '20201327ljm'
/**
* Block cipher modes:
* - ECB: electronic codebook
* - CBC: cipher block chaining
*/
let encryptedData, decryptedData
// ECB
encryptedData = SM4.encrypt(originalData, key, {
inputEncoding: 'utf8',
outputEncoding: 'base64'
})
console.log(encryptedData)
decryptedData = SM4.decrypt(encryptedData, key, {
inputEncoding: 'base64',
outputEncoding: 'utf8'
})
console.log(decryptedData)
console.log('\n')
// CBC
const iv = '0123456789abcdeffedcba9876543210' // Initialization vector(any string of 32 hexadecimal digits)
encryptedData = SM4.encrypt(originalData, key, {
iv,
mode: SM4.constants.CBC,
inputEncoding: 'utf8',
outputEncoding: 'hex'
})
console.log(encryptedData)
decryptedData = SM4.decrypt(encryptedData, key, {
iv,
mode: SM4.constants.CBC,
inputEncoding: 'hex',
outputEncoding: 'utf8'
})
console.log(decryptedData)
通过sm-crypto密码算法库实现国密算法
安装 sm-crypto
npm install --save miniprogram-sm-crypto
sm2
const sm2 = require("miniprogram-sm-crypto").sm2;
let keypair = sm2.generateKeyPairHex();
publicKey = keypair.publicKey; // 公钥
privateKey = keypair.privateKey; // 私钥
const cipherMode = 1; // 1 - C1C3C2,0 - C1C2C3,默认为1
let encryptData = sm2.doEncrypt('20201327', publicKey, cipherMode); // 加密结果
console.log(encryptData)
let decryptData = sm2.doDecrypt(encryptData, privateKey, cipherMode); // 解密结果
console.log(decryptData)
sm3
const sm3 = require("miniprogram-sm-crypto").sm3;
let hashData = sm3("20201327"); // 杂凑
console.log(hashData)
sm4
const sm4 = require("miniprogram-sm-crypto").sm4;
const key = [0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10];
let encryptData = sm4.encrypt("20201327", key); // 加密
console.log(encryptData)
let decryptData = sm4.decrypt(encrytData, key); // 解密
console.log(decryptData)