MCRYPT_RIJNDAEL_256 支持 16、24 和 32 字节的密钥。如果密钥大小介于两者之间,则使用 0 值完成填充,直到达到下一个有效密钥长度。
如果密钥长度是两位数字,则下一个有效密钥大小为 16 字节,因此完成填充具有 14 个 0 值。
这同样适用于 IV,其长度必须对应于块大小(Rijndael-256 为 32 个字节)。如果它更短,它也会用 0 值填充(尽管这里通常会显示警告)。
如果键太长(超过 32 个字节),它将被截断。这同样适用于 IV。
以下 PHP 代码演示了这一点:
function encrypt($key, $iv){
$mopen = mcrypt_module_open(MCRYPT_RIJNDAEL_256, '', 'cfb', '');
mcrypt_generic_init($mopen, $key, $iv);
$cipherText = mcrypt_generic($mopen, "The quick brown fox jumps over the lazy dog");
print(base64_encode($cipherText) . "\n");
}
$key = 32; // 0-padded to 16 bytes
$iv = 32; // 0-padded to 32 bytes (Rijndael-256 blocksize), mostly a warning is displayed
encrypt($key, $iv); // Dgfd2xT2NQ1ULob3mOX+JBPQo57JUIxabtt+TX8wnzYWhKtt/6ltY2Z/yA==
$key = "32";
$iv = "32";
encrypt($key, $iv); // Dgfd2xT2NQ1ULob3mOX+JBPQo57JUIxabtt+TX8wnzYWhKtt/6ltY2Z/yA==
$key = "32\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
$iv = "32\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0";
encrypt($key, $iv); // Dgfd2xT2NQ1ULob3mOX+JBPQo57JUIxabtt+TX8wnzYWhKtt/6ltY2Z/yA==
在 Java 代码中,必须指定 exact 键和 IV 大小。请注意,CFB 是一种流密码模式,因此不使用填充。 PHP 应用 CFB-8(8 位模式下的 CFB),必须在 Java 代码中相应地指定。以下 Java/BouncyCastle 代码解密密文:
import org.bouncycastle.crypto.BufferedBlockCipher;
import org.bouncycastle.crypto.CipherParameters;
import org.bouncycastle.crypto.engines.RijndaelEngine;
import org.bouncycastle.crypto.modes.CFBBlockCipher;
import org.bouncycastle.crypto.params.KeyParameter;
import org.bouncycastle.crypto.params.ParametersWithIV;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
...
String ciphertextB64 = "Dgfd2xT2NQ1ULob3mOX+JBPQo57JUIxabtt+TX8wnzYWhKtt/6ltY2Z/yA==";
byte[] ciphertext = Base64.getDecoder().decode(ciphertextB64);
byte[] key = "32\0\0\0\0\0\0\0\0\0\0\0\0\0\0".getBytes(StandardCharsets.UTF_8);
byte[] iv = "32\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0".getBytes(StandardCharsets.UTF_8);
BufferedBlockCipher bufferedBlockCipher = new BufferedBlockCipher(new CFBBlockCipher(new RijndaelEngine(256), 8)); // CFB in 8 bit mode
CipherParameters cipherParams = new ParametersWithIV(new KeyParameter(key), iv);
bufferedBlockCipher.init(false, cipherParams);
byte[] decryptedBuffer = new byte[bufferedBlockCipher.getOutputSize(ciphertext.length)];
int processed = bufferedBlockCipher.processBytes(ciphertext, 0, ciphertext.length, decryptedBuffer, 0);
processed += bufferedBlockCipher.doFinal(decryptedBuffer, processed);
System.out.println(new String(decryptedBuffer, 0, processed, StandardCharsets.UTF_8)); // The quick brown fox jumps over the lazy dog