此Java代码将加密/解密并生成与编码为十六进制的示例相同的输出。输出看起来是相同的(也应该是),但要100%确定您需要在C++示例中对输出进行十六进制编码。
请注意,虽然您的示例只会加密和解密单个块(16个字节)。如果你想要更多,你需要使用CRijndael
Encrypt
和Decrypt
方法(而不是EncryptBlock
和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。
Rijndael也被称为AES。尽管您可能需要深入研究CRijndael以找出它正在使用的参数(比特,密码模式,填充,IV?)等等,但Java的AES还有很多实现。 – Rup