此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