一、node.js环境安装
1 去官网下载压缩包,并放置到/usr/local/bin文件夹下
2 进行环境变量配置
vim /etc/profile
在环境变量文件的末尾添加
export NODEJS=/usr/local/bin/node-v16.18.1-linux-x64
export PATH=$PATH:$NODEJS/bin
3 验证安装情况
node -v
npm -v
成功安装示例:
二、gm-crypto module下载
npm install gm-crypto
以下为正确示例:
三、代码调试
1 sm2
首先进入root目录,查看刚刚下载的工作环境node_modules
进入路径node_modules,并创建sm2.js文件,验证代码如下:
const { SM2 } = require('gm-crypto')
const { publicKey, privateKey } = SM2.generateKeyPair()
const originalData = '20201307lcy'
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)
编译指令:node sm2.js
2 sm3
创建验证文件sm3.js
vim sm3.js
const { SM3 } = require('gm-crypto')
console.log(SM3.digest('20201307'))
console.log(SM3.digest('lcy'))
console.log(SM3.digest('12345678'))
编译sm3.js
在线网站验证:http://lzltool.cn/SM3
3 sm4
vim sm4.js
const { SM4 } = require('gm-crypto')
const key = '0123456789abcdeffedcba9876543210' // Any string of 32 hexadecimal digits
const originalData = '20201307lcy'
/**
* 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)
node sm4.js
标签:Node,node,console,log,js,国密,encryptedData,const
From: https://www.cnblogs.com/yu15141310373/p/16950092.html