此 Java 代码将加密/解密并产生与您的示例编码为十六进制相同的输出。输出看起来是相同的(并且应该是相同的),但要 100% 确定您需要在 C++ 示例中对输出进行十六进制编码。
请注意,您的示例只会加密和解密单个块(16 个字节)。如果您想要更多,则需要使用CRijndael
Encrypt
andDecrypt
方法(而不是EncryptBlock
and DecryptBlock
)。下面的 Java 代码适用于两者,无需修改。
public static void main(String[] args) throws DecoderException, InvalidKeyException,
NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException {
//Hex encoding/decoding done with Apache Codec
byte[] key = "abcdefghabcdefgh".getBytes();
String text = "Password12345678";
byte[] encrypted = encrypt(key, text.getBytes());
byte[] decrypted = decrypt(key, encrypted);
System.out.println("Text: " + text);
System.out.println("Encrypted: " + Hex.encodeHexString(encrypted));
System.out.println("Decrypted: " + new String(decrypted));
}
public static byte[] encrypt(byte[] key, byte[] unencrypted) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException{
//Set up the cipher and encrypt
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] encrypted = cipher.doFinal(unencrypted);
return encrypted;
}
public static byte[] decrypt(byte[] key, byte[] encrypted) throws NoSuchAlgorithmException,
NoSuchPaddingException, InvalidKeyException, InvalidAlgorithmParameterException,
IllegalBlockSizeException, BadPaddingException{
//Decrypt the encrypted text
Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(key, "AES"));
byte[] decrypted = cipher.doFinal(encrypted);
return decrypted;
}
输出
Text: Password12345678
Encrypted: 6c7d800fad2bb8593db92847bbbdbeff
Decrypted: Password12345678
不过,给你一个大警告,这种加密(ECB,无填充)非常不安全,你永远不应该在真实系统中使用它。您真的应该使用带有初始化向量和 PKCS5 填充的 CBC。