程序员的资源宝库

网站首页 > gitee 正文

crypto cryptology

sanyeah 2024-03-29 17:53:00 gitee 7 ℃ 0 评论

数据加密

crypto模块的目的是为了提供通用的加密和哈希算法。用纯JavaScript代码实现这些功能不是不可能,但速度会非常慢。Nodejs用C/C++实现这些算法后,通过cypto这个模块暴露为JavaScript接口,这样用起来方便,运行速度也快。

hash 加密

  • hash.update(data[, input_encoding]):input_encoding可以是utf8ascii或者latin1。如果data是字符串,且没有指定 input_encoding,则默认是utf8。注意,hash.update()方法可以调用多次。
  • hash.digest([encoding]):计算摘要。encoding可以是hexlatin1或者base64。如果声明了encoding,那么返回字符串。否则,返回Buffer实例。注意,调用hash.digest()后,hash对象就作废了,再次调用就会出错。
const fs = require('fs')
const crypto = require('crypto')
// md5 加密
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)
// 56901ccecb043f7b27dfcb835c80bcbd ---- 0cb6dd8449df8c0ffd829d5dc1efc51a88af66f7

HMAC 加密

需要密钥,用随机数增强的hash算法

const fs = require( 'fs')
const crypto = require('crypto')
// 需要密钥,用随机数增强的hash算法
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)
// cbb3c4e285a6c1a339f5b90c3f028e37

AES 加密/解密

const fs = require('fs')
const crypto = require('crypto')

let encrypt = (key,iv,data) => {
    // 创建一个密钥对象,包含两个属性 - key和iv - 分别是密钥和伪随机数种子。
    let dep = crypto.createCipheriv('aes-128-cbc',key,iv)
    // 将密文打包为字节数组。
    return dep.update(data,'binary','hex') + dep.final('hex')
}
let decrypt = (key,iv,crypted) => {
    // 将16进制的crypted转换成字节数组,然后再将其转换回字符串形式。
    let crypt = Buffer.from(crypted,'hex').toString('binary')
    // 创建一个aes加密对象,参数是当时加密的密钥和初始向量。可以参考MD5
    let dep = crypto.createDecipheriv("aes-128-cbc",key,iv)
    // 输出加密后的字节数组。
    return dep.update(crypt,'binary','utf8') + dep.final('utf8')
}
// 128 = 16 * 8
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)
// 加密: 24f03ccf55e997f5d3b8867f146e146ddf61eb985c7e263d496ff6e0c15b94e3
// 解密: qwertyuiop woshiwangjie

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表