数据加密
crypto模块的目的是为了提供通用的加密和哈希算法。用纯JavaScript代码实现这些功能不是不可能,但速度会非常慢。Nodejs用C/C++实现这些算法后,通过cypto这个模块暴露为JavaScript接口,这样用起来方便,运行速度也快。
hash 加密
- hash.update(data[, input_encoding]):input_encoding可以是
utf8
、ascii
或者latin1
。如果data是字符串,且没有指定 input_encoding,则默认是utf8
。注意,hash.update()方法可以调用多次。
- hash.digest([encoding]):计算摘要。encoding可以是
hex
、latin1
或者base64
。如果声明了encoding,那么返回字符串。否则,返回Buffer实例。注意,调用hash.digest()后,hash对象就作废了,再次调用就会出错。
| const fs = require('fs') |
| const crypto = require('crypto') |
| |
| const content = fs.readFileSync('./crypto加密/index.txt','utf-8') |
| const md5 = crypto.createHash('md5') |
| hex1 = md5.update(content).digest('hex') |
| const sha1 = crypto.createHash('sha1') |
| hex2 = sha1.update(content).digest('hex') |
| |
| console.log(hex1,'----',hex2) |
| |
HMAC 加密
需要密钥,用随机数增强的hash算法
| const fs = require( 'fs') |
| const crypto = require('crypto') |
| |
| const content = fs.readFileSync('./crypto加密/index.txt','utf-8') |
| const key = 'wangjie' |
| const hash = crypto.createHmac('md5',key) |
| const word = hash.update(content).digest('hex') |
| console.log(word) |
| |
AES 加密/解密
| const fs = require('fs') |
| const crypto = require('crypto') |
| |
| let encrypt = (key,iv,data) => { |
| |
| let dep = crypto.createCipheriv('aes-128-cbc',key,iv) |
| |
| return dep.update(data,'binary','hex') + dep.final('hex') |
| } |
| let decrypt = (key,iv,crypted) => { |
| |
| let crypt = Buffer.from(crypted,'hex').toString('binary') |
| |
| let dep = crypto.createDecipheriv("aes-128-cbc",key,iv) |
| |
| return dep.update(crypt,'binary','utf8') + dep.final('utf8') |
| } |
| |
| let key = '1234567890qweasd' |
| let iv = 'qwertyuiop123456' |
| let data = fs.readFileSync('./crypto加密/index.txt','utf-8') |
| |
| let enc = encrypt(key,iv,data) |
| console.log('加密:',enc) |
| let dec = decrypt(key,iv,enc) |
| console.log('解密:',dec) |
| |
| |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具