NodeJS 解密数据损坏原始数据
NodeJS Decrypt Data Corrupt Original Data
我使用 AES-266-CBC 加密数据:
const iv = crypto.randomBytes(8).toString('hex');
const encrypt = (text: string): string => {
log('encrypt');
const cipher = crypto.createCipheriv('aes-256-cbc', ENCRYPTION_KEY, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
};
const decrypt = (text: string): string => {
log('decrypt');
const decipher = crypto.createDecipheriv('aes-256-cbc', ENCRYPTION_KEY, iv);
let decrypted = decipher.update(text, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
};
一切都很完美,这意味着如果我使用这个:
const data = JSON.stringify({
user: 'MHF',
info: {
age: 23,
family: 'HF'
}
});
const encrypted = encrypt(data);
console.log('encrypted: %s', encrypted);
const decrypted = decrypt(encrypted);
console.log('decrypted: %s', decrypted);
问题是,当我通过 post 请求 http 发送我的加密字符串时,如下所示:
POST {{baseUrl}}/v1/user-register
Content-Type: application/json
Content-Encrypted: AES
{"payLoad": "3f1d1584b0e1976ccea311b5fbe0b2aee1034198a582a3b8bcc773c175e91bb0ceda6b9fb88aff11a892fa7adb83d432"}
我有一些像这样的不正确字符的解密数据:
'r!!(h\x7F!o#L\x19\x10~\x7F"jnfo":{"age":23,"family":"HF"}}'
为什么当我通过加密数据执行 post 请求时我得到这个结果?
这是什么:'r!!(h\x7F!o#L\x19\x10~\x7F"j'?
感谢@Topaco 和@Michael Fehr
生成和使用 IV
是我的大错
我使用 AES-266-CBC 加密数据:
const iv = crypto.randomBytes(8).toString('hex');
const encrypt = (text: string): string => {
log('encrypt');
const cipher = crypto.createCipheriv('aes-256-cbc', ENCRYPTION_KEY, iv);
let encrypted = cipher.update(text, 'utf8', 'hex');
encrypted += cipher.final('hex');
return encrypted;
};
const decrypt = (text: string): string => {
log('decrypt');
const decipher = crypto.createDecipheriv('aes-256-cbc', ENCRYPTION_KEY, iv);
let decrypted = decipher.update(text, 'hex', 'utf8');
decrypted += decipher.final('utf8');
return decrypted;
};
一切都很完美,这意味着如果我使用这个:
const data = JSON.stringify({
user: 'MHF',
info: {
age: 23,
family: 'HF'
}
});
const encrypted = encrypt(data);
console.log('encrypted: %s', encrypted);
const decrypted = decrypt(encrypted);
console.log('decrypted: %s', decrypted);
问题是,当我通过 post 请求 http 发送我的加密字符串时,如下所示:
POST {{baseUrl}}/v1/user-register
Content-Type: application/json
Content-Encrypted: AES
{"payLoad": "3f1d1584b0e1976ccea311b5fbe0b2aee1034198a582a3b8bcc773c175e91bb0ceda6b9fb88aff11a892fa7adb83d432"}
我有一些像这样的不正确字符的解密数据:
'r!!(h\x7F!o#L\x19\x10~\x7F"jnfo":{"age":23,"family":"HF"}}'
为什么当我通过加密数据执行 post 请求时我得到这个结果?
这是什么:'r!!(h\x7F!o#L\x19\x10~\x7F"j'?
感谢@Topaco 和@Michael Fehr
生成和使用 IV