前言
加密解密也是我们经常会使用的一个库,集中在 crypto 中:
import {...} from crypto
具体的一些应用场景
文档参考官方: https://nodejs.org/api/crypto.html
加密/解密分为:公私钥加密解密、对称加密/解密
摘要可用:MD5,SHA10
第一部分 摘要
import { createHash, createCipheriv,randomBytes,createDecipheriv } from "crypto"
const password ="123456"
// const md5Password = createHash("md5").update(password).digest("hex")
const shaPassword = createHash("sha256").update(password).digest("hex")
console.log(shaPassword)
第二部分 对称加解
const key = randomBytes(32)
const iv = randomBytes(16)
const chipher = createCipheriv("aes-256-gcm",key,iv)
const buffer = chipher .update("123456")
const dechipher = createDecipheriv("aes-256-gcm", key,iv)
const output = dechipher.update( buffer )
console.log(output.tostring('utf8'))
第三部分 非对称加解密(时间相对长一些)
const bobsPubKey = fs .readFileSync(resolve( dirname,"xxx_rsa.pub"),'utf8')
const bobsPrivKey = fs.readFileSync(resolve( dirname,"xxx_rsa"),'utf8')
const bob = new RSA(bobsPrivKey)
const alice = new RSA(bobsPubKey)
console.log( bob.decrypt( alice.encrypt("hi bob!") ).tostring("utf8"))
看需求取舍使用哪种加解密方式,目前前端对称加解密使用的还是多一些。
最后扩展阅读:对加解密有兴趣的也可以了解一下 数字签名
结束语:欢迎大家留言,点赞+收藏~~~~~