加密解密
程序员文章站
2024-03-14 17:10:13
...
加密解密
createCipheriv(algorithm, key, iv)
algorithm: 算法有很多,常用的里面,aes-256-cbc,rc4加密解密速度比较快
key: 加密解密公用的**,可以是字符串,可以是buffer
const keyString = 'c31d92f8a2e703711ac623aef687110a'
const securityKey = (keyString instanceof Buffer) ? keyString : new Buffer(keyString)
/**
* @param {string:require} data 要加密的字符串
* @return {string} 加密后的字符串
*/
export const encrypt = (data) => {
try {
const iv = new Buffer(16)
// 用aes-256-cbc算法生成cipher实例
const cipher = crypto.createCipheriv('aes-256-cbc', securityKey, iv)
// update待加密内容到cipher实例,编码格式为utf8,输出16进制格式
let crypted = cipher.update(data, 'utf8', 'hex')
// 通过final方法输出加密串
crypted += cipher.final('hex')
logger.info(`encrypt data[${data}] to crypted[${crypted}]`)
return crypted
} catch (err) {
logger.warn(`encrypt data[${data}] error`, err)
return null
}
}
/**
* @param {string:require} data 要解密的字符串
* @return {string} 解密后的字符串
*/
export const decrypt = (data) => {
try {
const iv = new Buffer(16)
// 用aes-256-cbc算法生成decipher实例
const decipher = crypto.createDecipheriv('aes-256-cbc', securityKey, iv)
// update待解密内容到decipher实例
let decoded = decipher.update(data, 'hex', 'utf8')
// 通过final方法输出解密串
decoded += decipher.final('utf8')
logger.info(`decrypt data[${data}] to decoded[${decoded}]`)
return decoded
} catch (err) {
logger.warn(`decrypt data[${data}] error`, err)
return null
}
}
常用的加密算法:
base64
aes-256-cbc: 108
blowfish: 96
rc4:92
转载于:https://www.jianshu.com/p/6534c642abb7