解密 NodeJS 中 AES-CFB + PKCS7 填充
时间:2024-03-13
浏览:341
作者:佚名
Golang小白一枚,正在不断学习积累知识,现将学习到的知识记录一下,也是将我的所得分享给大家!而今天这篇文章《解密 NodeJS 中 AES-CFB + PKCS7 填充》带大家来了解一下##content_title##,希望对大家的知识积累有所帮助,从而弥补自己的不足,助力实战开发!
问题内容
我正在尝试使用 crypt 或 crypt-js 将以下 go 函数移植到 nodejs,但在尝试找出问题所在时遇到问题:
go 加密代码可在 https://go.dev/play/p/o88bslwd-qh 获取(加密和解密均有效)
当前的nodejs实现是:
var decryptKey= "93D87FF936DAB334C2B3CC771C9DC833B517920683C63971AA36EBC3F2A83C24";
const crypto = require('crypto');
const algorithm = 'aes-256-cfb';
const BLOCK_SIZE = 16;
var message = "8a0f6b165236391ac081f5c614265b280f84df882fb6ee14dd8b0f7020962fdd"
function encryptText(keyStr, text) {
const hash = crypto.createHash('sha256');
//Decode hex key
keyStr = Buffer.from(keyStr, "hex")
hash.update(keyStr);
const keyBytes = hash.digest();
const iv = crypto.randomBytes(BLOCK_SIZE);
const cipher = crypto.createCipheriv(algorithm, keyBytes, iv);
cipher.setAutoPadding(true);
let enc = [iv, cipher.update(text,'latin1')];
enc.push(cipher.final());
return Buffer.concat(enc).toString('hex');
}
function decryptText(keyStr, text) {
const hash = crypto.createHash('sha256');
//Decode hex key
keyStr = Buffer.from(keyStr, "hex")
hash.update(keyStr);
const keyBytes = hash.digest();
const contents = Buffer.from(text, 'hex');
const iv = contents.slice(0, BLOCK_SIZE);
const textBytes = contents.slice(BLOCK_SIZE);
const decipher = crypto.createDecipheriv(algorithm, keyBytes, iv);
decipher.setAutoPadding(true);
let res = decipher.update(textBytes,'latin1');
res += decipher.final('latin1');
return res;
}
console.log(message)
result = decryptText(decryptKey,message);
console.log(result);
message = encryptText(decryptKey,'hola').toString();
console.log(message)
result = decryptText(decryptKey,message);
console.log(result);
知道为什么它没有按预期工作吗?
注意:我知道cfb不需要填充,但我无法修改加密代码,仅供参考。
正确答案
我不知道 go 或 aes.newcipher(key) 的细节,但从 its documentation 来看,它看起来并没有以任何方式对密钥进行哈希处理。您链接到的 go 代码也不会对其进行哈希处理,因此我不确定为什么您要在 node.js 代码中对它进行哈希处理。
这应该足够了:
function encryptText(keyStr, text) {
const keyBytes = Buffer.from(keyStr, "hex")
…
}
function decryptText(keyStr, text) {
const keyBytes = Buffer.from(keyStr, 'hex');
…
}
顺便说一句:看起来您可能正在使用这些函数加密 json 块。如果是这样,我建议在加密/解密过程中不要使用任何编码(例如 latin1),因为 json 文本必须使用 utf-8 进行编码。
文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《解密 NodeJS 中 AES-CFB + PKCS7 填充》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
11.30
11.30
11.30
11.30
热门专题
