我正在尝试使用crypto-js库使用typescript对字符串客户端进行加密,然后使用PHP和libsodium对其进行解码。我这样加密:
/// <reference types="crypto-js" />
import * as CryptoJS from 'crypto-js';
const key = CryptoJS.enc.Utf8.parse('length 32 hex string here');
const iv = CryptoJS.enc.Utf8.parse('length 32 hex string here');
const encrypted = CryptoJS.AES.encrypt(CryptoJS.enc.Utf8.parse("..."), key, {
keySize: 32,
iv: iv
});
const base64 = btoa(encrypted.ciphertext);
我看到的许多示例都通过encrypted.ciphertext.toString(CryptoJS.enc.Base64)
转换为base 64,但由于toString
不带参数,因此我收到了编译器错误。
然后我尝试像这样在PHP中对其进行解码:
$key = pack("H*", "same length 32 hex string here");
$decoded = base64_decode("base 64 string here");
if (mb_strlen($decoded, '8bit') < (SODIUM_CRYPTO_SECRETBOX_NONCEBYTES + SODIUM_CRYPTO_SECRETBOX_MACBYTES)) {
throw new Exception('truncated');
}
$nonce = mb_substr($decoded, 0, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, '8bit');
$ciphertext = mb_substr($decoded, SODIUM_CRYPTO_SECRETBOX_NONCEBYTES, null, '8bit');
$plain = sodium_crypto_secretbox_open($ciphertext, $nonce, $key);
if ($plain === false) {
throw new Exception('the message was tampered with in transit');
}
sodium_memzero($ciphertext);
sodium_memzero($key);
当我运行该程序时,只要碰到对sodium_crypto_secretbox_open
的调用,就会得到此异常:
未捕获的SodiumException:密钥大小应为SODIUM_CRYPTO_SECRETBOX_KEYBYTES