我试图使用nodeJS或crypt将以下Go函数移植到Go,但我在试图找出问题所在时遇到了问题:
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不需要填充,但我不能修改加密代码,它只是供参考。
发布于 2022-08-01 18:20:13
我不知道Go或aes.NewCipher(key)的具体内容,但从其文件上看,它似乎没有以任何方式散列密钥。链接到的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进行编码。
https://stackoverflow.com/questions/73197571
复制相似问题