Note that there are some explanatory texts on larger screens.

plurals
  1. POWhy doesn't this simple AES encryption work?
    text
    copied!<p>Why does not this AES encryption work? I've written it in Java to test, but I am not able to decrypt. I get garbage upon decryption. Why? Its so simple - In the main method, print plain text, encrypt, print cipher text, decrypt, print plain text again. Am I doing something wrong? Please help me figure out the problem.</p> <p><pre><code></p> import javax.crypto.Cipher; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.SecretKeySpec; public class AESTest { public static void main(String [] args) { try { String plainText = "Hello World!!!!!"; String encryptionKey = "E072EDF9534053A0B6C581C58FBF25CC"; System.out.println("Before encryption - " + plainText); String cipherText = encrypt(plainText, encryptionKey); System.out.println("After encryption - " + cipherText); String decrypted = decrypt(cipherText, encryptionKey); System.out.println("After decryption - " + decrypted); } catch (Exception e) { e.printStackTrace(); } } public static String encrypt(String plainText, String passkey) throws Exception { Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(hexStringToByteArray(passkey), "AES"); cipher.init(Cipher.ENCRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()])); String cipherText = new String(cipher.doFinal(plainText.getBytes())); return cipherText; } public static String decrypt(String cipherText, String passkey) throws Exception{ Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding", "SunJCE"); SecretKeySpec key = new SecretKeySpec(hexStringToByteArray(passkey), "AES"); cipher.init(Cipher.DECRYPT_MODE, key, new IvParameterSpec(new byte[cipher.getBlockSize()])); String plainText = new String(cipher.doFinal(cipherText.getBytes())); return plainText; } public static byte[] hexStringToByteArray(String s) { int len = s.length(); byte[] data = new byte[len / 2]; for (int i = 0; i &lt; len; i += 2) { data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) &lt;&lt; 4) + Character.digit(s.charAt(i+1), 16)); } return data; } } </code></pre>
 

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