5

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();
    }
  }
}
6
  • 1
    As far as I can understand the code, the input and the output should be the same Commented Jan 19, 2015 at 13:34
  • In my programs output I tried to get encrypted and Decrypted text. My input is a string. What I want to become possible is to Decrypt the symbols instead of getting the string as an output. Accepting symbols as an input to get its equivalent text. Commented Jan 19, 2015 at 13:37
  • 2
    If the encrypted String contains characters which are not included in the font you are using to show them you will see a question mark ? symbol. Commented Jan 19, 2015 at 13:42
  • I don't understand. Your code works. The only thing is that you should fully specify your scheme: Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); depending on your default provider. Commented Jan 19, 2015 at 13:50
  • 1
    If you really want to output your encrypted data on screen to type it in, you need some additional encoding like base64 which allows you to recover the exact bytes. Simply outputting your byte array as string won't work because you loose some information. Commented Jan 19, 2015 at 13:58

3 Answers 3

7

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");
Sign up to request clarification or add additional context in comments.

6 Comments

What if if i want to input a set of symbols to decrypt?
What do you mean by "set of symbols"? What do you want to do with the set? It's entirely unclear. Please describe in detail, what you want to achieve.
I want to decrypt it to its equivalent word.
For example? With AES you get back what you've encrypted if you use the correct key. I don't understand what you're after then.
How to get back what you've encrypted in AES?
|
6

For some that is still having trouble to decrypt what you have encrypted, you have to decode it using Base 64. You can use apache commons codec dependency. Here is a working code copied from http://javapointers.com/tutorial/how-to-encrypt-and-decrypt-using-aes-in-java/

public class EncryptDecrypt {

private static final String SECRET_KEY_1 = "ssdkF$HUy2A#D%kd";
private static final String SECRET_KEY_2 = "weJiSEvR5yAC5ftB";

private IvParameterSpec ivParameterSpec;
private SecretKeySpec secretKeySpec;
private Cipher cipher;

public EncryptDecrypt() throws UnsupportedEncodingException, NoSuchPaddingException, NoSuchAlgorithmException {
    ivParameterSpec = new IvParameterSpec(SECRET_KEY_1.getBytes("UTF-8"));
    secretKeySpec = new SecretKeySpec(SECRET_KEY_2.getBytes("UTF-8"), "AES");
    cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
}


public String encrypt(String toBeEncrypt) throws NoSuchPaddingException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
    byte[] encrypted = cipher.doFinal(toBeEncrypt.getBytes());
    return Base64.encodeBase64String(encrypted);
}

public String decrypt(String encrypted) throws InvalidAlgorithmParameterException, InvalidKeyException,
        BadPaddingException, IllegalBlockSizeException {
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
    byte[] decryptedBytes = cipher.doFinal(Base64.decodeBase64(encrypted));
    return new String(decryptedBytes);
}

Comments

1

Not a Java developer but had to write a little Java code today at work, and I wasted a lot of time trying to get one of the examples above to work, so I wanted to go ahead and post a complete working example that you can pretty much copy and paste and get working. My plan was to just fix one of the examples above, but I found it was just easier to use this AI generated example from Google instead. I'm still used to looking up answers myself, and so in case someone else stumbles upon this Stack Overflow post, use this AI generated example as it's better than the other "answers" here on this page:

package com.yourpackagename.encryptdecrypt;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Scanner;

public class EncryptDecrypt {
    public static SecretKey generateKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(256);
        return keyGenerator.generateKey();
    }

    public static IvParameterSpec generateIv() {
        byte[] iv = new byte[16];
        new SecureRandom().nextBytes(iv);
        return new IvParameterSpec(iv);
    }

    public static String encrypt(String algorithm, String input, SecretKey key, IvParameterSpec iv) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.ENCRYPT_MODE, key, iv);
        byte[] cipherText = cipher.doFinal(input.getBytes());
        return Base64.getEncoder().encodeToString(cipherText);
    }

    public static String decrypt(String algorithm, String cipherText, SecretKey key, IvParameterSpec iv) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithm);
        cipher.init(Cipher.DECRYPT_MODE, key, iv);
        byte[] plainText = cipher.doFinal(Base64.getDecoder().decode(cipherText));
        return new String(plainText);
    }

    public static void main(String[] args) throws Exception {
        SecretKey key = generateKey();
        IvParameterSpec iv = generateIv();

        String algorithm = "AES/CBC/PKCS5Padding";
        
        try (Scanner scanner = new Scanner(System.in)) {
            System.out.println("Enter string to encrypt: ");
            String input = scanner.nextLine();  // Read user input
            String cipherText = encrypt(algorithm, input, key, iv);
            String plainText = decrypt(algorithm, cipherText, key, iv);
            System.out.println("Encrypted Text: " + cipherText);
            System.out.println("Decrypted Text: " + plainText);
        } catch (Exception e) {
            System.out.println("ERROR: " + e.getMessage());
        }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.