PHP Encrypt Function
$privateKey = "1234567812345678";
$iv = "1234567812345678";
$data = "Test string";
$encrypted = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $privateKey, $data, MCRYPT_MODE_CBC, $iv);
echo(base64_encode($encrypted));
Result: iz1qFlQJfs6Ycp+gcc2z4w==
When I try to decrypt this result in Java using the function below, all I get back is ì�š@ÔBKxnfÈ~¯Ô'M while I am expecting "Test string". Any ideas where I am wrong? Thanks
public static String decrypt() throws Exception{
try{
String Base64EncodedText = "iz1qFlQJfs6Ycp+gcc2z4w==";
String decodedText = com.sun.xml.internal.messaging.saaj.util.Base64.base64Decode(Base64EncodedText);
String key = "1234567812345678";
String iv = "1234567812345678";
javax.crypto.spec.SecretKeySpec keyspec = new javax.crypto.spec.SecretKeySpec(key.getBytes(), "AES");
javax.crypto.spec.IvParameterSpec ivspec = new javax.crypto.spec.IvParameterSpec(iv.getBytes());
javax.crypto.Cipher cipher = javax.crypto.Cipher.getInstance("AES/CBC/NoPadding");
cipher.init(javax.crypto.Cipher.DECRYPT_MODE, keyspec, ivspec);
byte[] decrypted = cipher.doFinal(decodedText.getBytes());
String str = new String(decrypted);
return str;
}catch(Exception e){
return null;
}
}
EDIT: As of Java 8 Java now includes an acceptable Base64 class,
java.util.Base64
.This line
looks wrong. Instead, use the apache commons codec classes or the Harder base64 class. Also the default padding used by mcrypt, zero padding, is arguably wrong and makes it difficult to use the results in other languages. The users comments section for the mcrypt_encrypt web pages has examples of how to do this.
Here is small example that uses the apache commons classes to decrypt your string.
this produces the following output:
which when decoded as ASCII and removing the trailing zeros gives you
Test string