0

I'm new to Encryptions. I'm finding codes about encryption and i'm trying to know how it is working because it's interesting and I like to code it in the future.

Then I found this code:

  System.out.print("Enter text: ");
      String text = dataIn.readLine();
      String key = "Bar12345Bar12345"; // 128 bit key

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

Before I start working on it. I don't know how String = Bar12345Bar12345 works. It says that it is 128 bit key. Is the String constant? Is it okay to change it?

5
  • 1
    The string is 18 ASCII characters long, so the bit length is 18*8 bit = 128 bit. It's the secret key to encrypt/decrypt, so you should keep it secret. Commented Jan 19, 2015 at 11:49
  • So is it okay to change it as long as it's length is 16? Commented Jan 19, 2015 at 11:52
  • 1
    This is only simple example - you should use some hash function to generate key from password (not key.getBytes()). The hash will give you the key with correct length. Commented Jan 19, 2015 at 11:54
  • What do you mean by hash function? Sorry i'm beginner in Encryption. Commented Jan 19, 2015 at 11:56
  • en.wikipedia.org/wiki/PBKDF2 Commented Jan 19, 2015 at 12:00

1 Answer 1

3

To be precise, the string is not your key, but the bytes you get from key.getBytes(). While it may work for this sample, this is not something you should do in production code:

  • getBytes() may convert the string to different bytes if a different charset is used (unlikely for your specifc string, since it is ASCII only, but something you have to be aware of).
  • You need a string of correct length.
  • The quality of the generated key will be quite poor. For production code you should use a key derivation function like pbkdf2 to derive a key from something like a password.

There is another issue: Instead of just using "AES" you should also specify the mode of operation and padding when constructing your Cipher object (e.g. "AES/CBC/PKCS5Padding"). Otherwise the second and third parameter are provider dependent.

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.