Note that there are some explanatory texts on larger screens.

plurals
  1. POUnable to exchange data encrypted with AES-256 between Java and PHP
    primarykey
    data
    text
    <p>My problem is: what I encrypt in Java I can decrypt perfectly in Java, but PHP <code>mcrypt</code> can't decrypt. What I encrypt with <code>mcrypt</code> I can decrypt with <code>mcrypt</code>, but can't in Java.</p> <p>I want to send and receive encrypted data from a Java application to a PHP page, so I need it to be compatible.</p> <p>Here's what I have...</p> <p>JAVA...</p> <pre><code>public static String crypt(String input, String key){ byte[] crypted = null; try{ SecretKeySpec skey = new SecretKeySpec(Base64.decodeBase64(key), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, skey); crypted = cipher.doFinal(input.getBytes()); }catch(Exception e){ } return Base64.encodeBase64String(crypted); } public static String decrypt(String input, String key){ byte[] output = null; try{ SecretKeySpec skey = new SecretKeySpec(Base64.decodeBase64(key), "AES"); Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); cipher.init(Cipher.DECRYPT_MODE, skey); output = cipher.doFinal(Base64.decodeBase64(input)); }catch(Exception e){ } return new String(output); } </code></pre> <p>Running:</p> <pre><code>public static void main(String[] args) { String key = "Zvzpv8/PXbezPCZpxzQKzL/FeoPw68jIb+NONX/LIi8="; String data = "example"; System.out.println(Cpt.decrypt(Cpt.crypt(data, key), key)); } </code></pre> <p>Output:</p> <pre><code>example </code></pre> <p>PHP...</p> <pre><code>function getEncrypt($sStr, $sKey) { return base64_encode( mcrypt_encrypt( MCRYPT_RIJNDAEL_256, $sKey, $sStr, MCRYPT_MODE_ECB ) ); } function getDecrypt($sStr, $sKey) { return mcrypt_decrypt( MCRYPT_RIJNDAEL_256, $sKey, base64_decode($sStr), MCRYPT_MODE_ECB ); } </code></pre> <p>Running:</p> <pre><code>$crypt = getDecrypt(getEncrypt($str, $key), $key); echo "&lt;p&gt;Crypt: $crypt&lt;/p&gt;"; </code></pre> <p>Output:</p> <pre><code>Crypt: example������������������������� </code></pre> <p>Using PHP to crypt "example" with key "Zvzpv8/PXbezPCZpxzQKzL/FeoPw68jIb+NONX/LIi8=" I get "YTYhgp4zC+w5IsViTR5PUkHMX4i7JzvA6NJT1FqhoGY=". Using Java to crypt the same thing with the same key I get "+tdAZqTE7WAVPXhB3Tp5+g==".</p> <p>I'm encoding and decoding to base64 in the right order and I tested base64 encode and decode compatibility between Java and PHP and it's working.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload