3

How can I encrypt an entire string with AES. The code that I have below only encrypts up to the first space recognized :(. How can I fix this? Thanks

SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    String result = new String(cipher.doFinal(message.getBytes()));
    System.out.println("Encrypted:" + result);

EDIT OMG I CANT BELIEVE THIS, HOW COULD I MISS THIS :( ITS BECAUSE MY SCANNER WAS TAKING next instead of nextLine... how embarrassing this bugged me all day and only now did i actually think about checking that. Problem solved :) Thanks everyone

5
  • example the encrypted "hello world" and "hello" are both "sÀÊç$û?dgÞÏ┌q°(Ã" when the salt is "1111111111111111" Commented Oct 15, 2011 at 23:24
  • 3
    Don't treat encrypted string data as a string - it's not. If you want to get a human-readable representation, convert the string to base64 or a hex string, then print that. Commented Oct 15, 2011 at 23:28
  • is that the reason why im missing the rest of the message? and it doesnt affect me much if it's human readeble or not, in fact id probably prefer it more if it weren't :) Commented Oct 15, 2011 at 23:35
  • @Matt - d'oh. OK, I'll delete my comment and +1 your answer. Commented Oct 15, 2011 at 23:40
  • Don't use ECB mode. It's very weak. At least use CBC, or preferably an authenticated mode. Commented Oct 11, 2012 at 21:30

1 Answer 1

6

I don't see anything wrong with your code except trying to print an arbitrary byte[] using new String(byte[]). Try this on for size:

public static byte[] encrypt(String message) throws Exception
{
    String salt = "1111111111111111";
    SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return cipher.doFinal(message.getBytes());
}

public static void main (String[] args) throws Exception
{
    String hello = Arrays.toString(encrypt("hello"));
    System.out.println("hello:" + hello);
    String helloWorld = Arrays.toString(encrypt("hello world"));
    System.out.println("hello world:" + helloWorld);
}

Which prints:

hello:[115, -73, -46, -121, 36, -106, -99, 100, 103, -24, -40, -38, 113, -8, 40, -57]
hello world:[5, 88, -31, 115, 4, 48, -75, 44, 83, 21, 105, -67, 78, -53, -13, -28]

I think we can all agree that those are two different byte arrays.

Sign up to request clarification or add additional context in comments.

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.