I follow this guide AES encryption on Java side - decryption on PHP side and selecting a single key but the accepted answer is not really working. I even hardcoded the KEY and IV values in java so that i am sure that i have the same values in PHP.
private static final byte[] keyValue =
new byte[] { 'T', 'h', 'e', 'B', 'e', 's', 't',
'S', 'e', 'c', 'r','e', 't', 'K', 'e', 'y' };
private static final byte[] ivValue =
new byte[] { '0', '1', '2', '3', '4', '5', '6',
'7', '8', '9', '0','1', '2', '3', '4', '5' };
JAVA (key) generation:
String ALGO = "AES/CBC/ZeroBytePadding";
Key key = new SecretKeySpec(keyValue, ALGO);
JAVA (iv) generation:
IvParameterSpec ivSpec = new IvParameterSpec(ivValue);
Then i use it to Encrypt / Decrypt in JAVA like this:
//ENCRYPTION
String encrypted = encrypt("Hello World!",key,ivSpec);
//DECRYPTION
String decrypted = decrypt(encrypted,key,ivSpec);
public static String encrypt(String Data, Key key, IvParameterSpec ivSpec) throws Exception {
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.ENCRYPT_MODE, key, ivSpec);
byte[] encVal = c.doFinal(Data.getBytes());
String encryptedValue = Base64.encodeToString(encVal, Base64.NO_WRAP);
return encryptedValue;
}
public static String decrypt(String encryptedData, Key key, IvParameterSpec ivSpec) throws Exception {
Cipher c = Cipher.getInstance(ALGO);
c.init(Cipher.DECRYPT_MODE, key, ivSpec);
byte[] decordedValue = Base64.decode(encryptedData,Base64.NO_WRAP);
byte[] decValue = c.doFinal(decordedValue);
String decryptedValue = new String(decValue);
return decryptedValue;
}
NOW, in PHP i get the encrypted value thru POST and i hardcoded the KEY and IV value:
$encrypted = $_POST["encrypted"];
$key = "TheBestSecretKey";
$iv = "0123456789012345";
$decrypted = decryptMessage($encrypted,$key,$iv);
function decryptMessage($encrypted,$key,$iv)
{
$ivNum = (int)$iv;
$ivIn = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), $ivNum);
$decrypted = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $encrypted, MCRYPT_MODE_CBC, $ivIn);
}
Encrypted Message: TXCv3f+r+h71y/NzCk08Hw==
Expected Result of (decrypted) variable: "Hellow World!"
Current Result of (decrypted) variable: �@����6�I��Ԗmݕ����WMu
Is there any other workaround to achieve my expected result. Thank you in advance.
$ivNum = (int)$iv;suspicious but then it has been decades since I used PHP.