2


I'm trying to encrypt and decrypt String i got from my user.
I've done some searching on google and i found this piece of code.

   try{
        String text="";
        String key="Bar12345Bar12345";

        System.out.print("Input Text>>");
        text=sc.nextLine();
        Key aesKey = new SecretKeySpec(key.getBytes(),"AES");
        Cipher cipher = Cipher.getInstance("AES");

        cipher.init(Cipher.ENCRYPT_MODE, aesKey);
        byte[] encrypted = cipher.doFinal(text.getBytes());
        String encryptedValue = Base64.getEncoder().encodeToString(encrypted);
        System.out.println(encryptedValue);

        cipher.init(Cipher.DECRYPT_MODE, aesKey);
        String decrypted = new String(cipher.doFinal(encrypted));
        System.out.println(decrypted);
        }catch(Exception e){
            e.printStackTrace();
    }

But the String given is gibberish (some sort of symbol) which returned an error.
Is there any other method to encrypt and decrypt the text? Or maybe some changes needed for the code to works?

Thanks in advance!

Here is the referenced link in case you need it
http://www.software-architect.net/articles/using-strong-encryption-in-java/introduction.html

Edit: Thanks to @sgrillon for pointing out the link to the solution.

Karen
  • 122
  • 11

1 Answers1

1

Because System.out.println(new String(encrypted)); convert byte array into non ASCII format which is not readable. to make it readable need to convert this byte[] to ASCII format by using Base64 encoder.

i have converted your code output into Base64 Format output so you can able to read the output.

Scanner sc = new Scanner(System.in);
        try{
            String text="";
            String key="Bar12345Bar12345";

            System.out.print("Input Text>> ");
            text= sc.nextLine();
            java.security.Key aesKey = new SecretKeySpec(key.getBytes(),"AES");
            Cipher cipher = Cipher.getInstance("AES");

            cipher.init(Cipher.ENCRYPT_MODE, aesKey);
            byte[] encrypted = cipher.doFinal(text.getBytes());

            String outputString = Base64.getEncoder().encodeToString(encrypted);

            System.out.println(outputString);

            cipher.init(Cipher.DECRYPT_MODE, aesKey);

            String decrypted = new String(cipher.doFinal(Base64.getDecoder().decode(outputString.getBytes())));
                System.out.println(decrypted);
            }catch(Exception e){
                e.printStackTrace();
            }
Ajit Kamble
  • 153
  • 1
  • 12
  • Your `getBytes` and `new String` use the default character encoding, which can vary from system to system, user to user and time to time. When using character encodings, a fixed one is almost always what's needed. UTF-8 is very often a great choice, particularly where the character set is Unicode, as it is with Java `String`. – Tom Blodget Mar 21 '18 at 10:43