所以我有一个端点,我必须在其中解密密钥,并根据信息返回一些数据或不返回一些数据。问题是我总是得到这个错误:
TypeError: Invalid initialization vector
at Decipheriv.createCipherBase (node:internal/crypto/cipher:116:19)
at Decipheriv.createCipherWithIV (node:internal/crypto/cipher:135:3)
at new Decipheriv (node:internal/crypto/cipher:289:3)
at createDecipheriv (node:crypto:146:10)
这是我解密的功能。 Salt 和 IV 在密码的开头连接在一起。
import {
createDecipheriv,
pbkdf2Sync,
randomBytes,
createCipheriv,
} from 'crypto';
const keySize = 256;
const derivationIterations = 1000;
decrypt(cipherText: string, passPhrase: string): string {
// Get the complete stream of bytes that represent:
// [32 bytes of Salt] + [32 bytes of IV] + [n bytes of CipherText]
const cipherTextBytesWithSaltAndIv = Buffer.from(cipherText, 'base64');
// Get the saltbytes by extracting the first 32 bytes from the supplied cipherText bytes.
const saltStringBytes = cipherTextBytesWithSaltAndIv.slice(
0,
this.keySize / 8,
);
// Get the IV bytes by extracting the next 32 bytes from the supplied cipherText bytes.
const ivStringBytes = cipherTextBytesWithSaltAndIv.slice(
this.keySize / 8,
(this.keySize / 8) * 2,
);
// Get the actual cipher text bytes by removing the first 64 bytes from the cipherText string.
const cipherTextBytes = cipherTextBytesWithSaltAndIv.slice(
(this.keySize / 8) * 2,
);
const keyBytes = pbkdf2Sync(
passPhrase,
saltStringBytes,
this.derivationIterations,
this.keySize / 8,
'sha1',
);
const decipher = createDecipheriv('aes-256-cbc', keyBytes, ivStringBytes);
const plainTextBytes = Buffer.concat([
decipher.update(cipherTextBytes),
decipher.final(),
]);
return plainTextBytes.toString('utf8');
}
我尝试创建一种加密方法,因为我以为我会更好地理解这个问题,但我遇到了同样的错误
encrypt(plainText: string, passPhrase: string) {
// Salt and IV is randomly generated each time, but is preprended to encrypted cipher text
// so that the same Salt and IV values can be used when decrypting.
const saltStringBytes = randomBytes(this.keySize / 8);
const ivStringBytes = randomBytes(this.keySize / 8).toString('hex');
const plainTextBytes = Buffer.from(plainText, 'utf8');
const password = pbkdf2Sync(
passPhrase,
saltStringBytes,
this.derivationIterations,
this.keySize / 8,
'sha1',
);
const cipher = createCipheriv('aes-256-cbc', password, ivStringBytes);
const encrypted = Buffer.concat([
saltStringBytes,
Buffer.from(ivStringBytes, 'hex'),
cipher.update(plainTextBytes),
cipher.final(),
]);
return encrypted.toString('base64');
}
我实际上从 C# 代码“翻译”了这段代码,它使用 Rfc2898DeriveBytes 和 RijndaelManaged。
我发现 C# 代码取自这个post
我错过了什么?