首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >NodeJS加密+ pkcs7填充解密

NodeJS加密+ pkcs7填充解密
EN

Stack Overflow用户
提问于 2022-08-01 17:39:08
回答 1查看 158关注 0票数 1

我试图使用nodeJS或crypt将以下Go函数移植到Go,但我在试图找出问题所在时遇到了问题:

Go加密代码可在https://go.dev/play/p/O88Bslwd-qh上使用(加密和解密工作都可用)

目前nodejs的实现是:

代码语言:javascript
复制
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不需要填充,但我不能修改加密代码,它只是供参考。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-08-01 18:20:13

我不知道Go或aes.NewCipher(key)的具体内容,但从其文件上看,它似乎没有以任何方式散列密钥。链接到的Go代码也不散列,所以我不知道为什么要在Node.js代码中散列它。

这应足以:

代码语言:javascript
复制
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进行编码。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/73197571

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档