javaencryptionaes

Encrypt and decrypt a string with AES-128


I got it in encrypting 128-bit key. What can I do to reverse the process. I'm almost sitting here almost an hour to figure this but i cant. I'm new to this btw.

The sample input is:J§???????ÿK♥?{↕?

The output should be: hello

In this program:

The sample input is:hello

The output is: J§???????ÿK♥?{↕?...

public class en {
    public static void main(String[] args){
      ...
    try{
      System.out.print("Enter text: ");
        String text = dataIn.readLine();
        String key = "dAtAbAsE98765432"; // 128 bit key

     // Create key and cipher
     Key aesKey = new SecretKeySpec(key.getBytes(), "AES");
     Cipher cipher = Cipher.getInstance("AES");

     // encrypt the text
     cipher.init(Cipher.ENCRYPT_MODE, aesKey);
     byte[] encrypted = cipher.doFinal(text.getBytes());
     System.err.println("Encrypted: " + new String(encrypted));

     // Decrypt the text
     cipher.init(Cipher.DECRYPT_MODE, aesKey);
     String decrypted = new String(cipher.doFinal(encrypted));
     System.err.println("Decrypted: " + decrypted);
    }catch(Exception e){
      e.printStackTrace();
    }
  }
}

Solution

  • Ciphertext is composed of bytes and is supposed to look random. You will get unprintable characters which you also cannot type in. You have to use an encoding like Base64 to print your ciphertext after encryption and type in before decryption.

    During the encryption (Java 8):

    cipher.init(Cipher.ENCRYPT_MODE, aesKey);
    byte[] encrypted = cipher.doFinal(text.getBytes());
    System.err.println("Encrypted: " + new String(Base64.getEncoder().encodeToString(encrypted)));
    

    During the decryption (Java 8):

    System.out.print("Enter ciphertext: ");
    byte[] encrypted = Base64.getDecoder().decode(dataIn.readLine());
    ...
    cipher.init(Cipher.DECRYPT_MODE, aesKey);
    String decrypted = new String(cipher.doFinal(encrypted));
    System.err.println("Decrypted: " + decrypted);
    

    Encoding reference


    Apart from that you really should fully specify your scheme, because it might behave differently on another Java implementation.

    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");