内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用
PHP版本: 5.6.39
Node.js版本: 10.9.0
目标:使用PHP加密并使用Node.js解密
Stuck Point:我目前假设PHP和Node.js绑定到OpenSSL都使用了PKCS7填充。PHP和Node.js是否使用与OpenSSL不兼容的绑定?
示例PHP加密/解密代码:
class SymmetricEncryption {
public static function simpleEncrypt($key, $plaintext) {
$iv = openssl_random_pseudo_bytes(16);
$ciphertext = openssl_encrypt($plaintext, 'aes-256-cbc', $key, OPENSSL_RAW_DATA, $iv)
return base64_encode($iv) . "." . base64_encode($ciphertext);
}
public static function simpleDecrypt($key, $token) {
list($iv, $ciphertext) = explode(".", $token);
return openssl_decrypt(
base64_decode($ciphertext),
"aes-256-cbc",
$key,
OPENSSL_RAW_DATA,
base64_decode($iv)
);
}
}
示例Node.js加密/解密代码:
class SymmetricEncryption {
static simpleEncrypt(key: Buffer, plaintext: string): string {
const iv = randomBytes(16)
const cipher = createCipheriv('aes-256-cbc', key, iv)
const encrypted = cipher.update(plaintext)
const token = Buffer.concat([encrypted, cipher.final()])
return iv.toString('base64') + "." + token.toString('base64')
}
static simpleDecrypt(key: Buffer, token: string): string {
const [iv, ciphertext] = token.split(".").map(piece => Buffer.from(piece, 'base64'))
const decipher = createDecipheriv('aes-256-cbc', key, iv)
const output = decipher.update(ciphertext)
return Buffer.concat([output, decipher.final()]).toString('utf8')
}
}
我已经成功地独立测试了每个实现,但是当在PHP中加密并在node.js中解密时,我收到以下错误:
Error: error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt
堆栈跟踪指向我的那一行,这是decipher.final()
在simpleDecrypt
方法。
我正在使用以下(失败)单元测试来验证我的实现
it('should be able to decrypt values from php', () => {
const testAesKey = Buffer.from('9E9CEB8356ED0212C37B4D8CEA7C04B6239175420203AF7A345527AF9ADB0EB8', 'hex')
const phpToken = 'oMhL/oIPAGQdMvphMyWdJw==.bELyRSIwy+nQGIyLj+aN8A=='
const decrypted = SymmetricEncryption.simpleDecrypt(testAesKey, phpToken)
expect(decrypted).toBe('hello world')
})
在phpToken
我使用此变量是使用下面的代码创建的:
$testAesKey = "9E9CEB8356ED0212C37B4D8CEA7C04B6239175420203AF7A345527AF9ADB0EB8";
echo SymmetricEncryption::simpleEncrypt($testAesKey, "hello world");
我怀疑你的问题是由你在PHP中传递密钥的方式引起的。该文档openssl_encrypt
未指定将密钥解释为十六进制的任何位置。但是,它会截断太长的键。
这里可能发生的是PHP将64字符十六进制字符串截断为32字节,并使用密钥。hex2bin
在使用之前尝试使用您的PHP密钥 - 这应该可以解决您的问题!
$testAesKey = hex2bin("9E9CEB8356ED0212C37B4D8CEA7C04B6239175420203AF7A345527AF9ADB0EB8");