1

Below is an example of how I am encrypting text in java, although the encryption works. I can't seem to figure out how I can modify the level of encryption i.e 128, 256, 512 etc.

Code:

byte keySelectedByUser[] = selectedKey.getBytes();
SecretKeySpec secretKey = new SecretKeySpec(keySelectedByUser, "AES");

Cipher cipher;

cipher = Cipher.getInstance("AES/CBC/PKCS7PADDING");

cipher.init(Cipher.ENCRYPT_MODE, secretKey);

byte[] encrypted = cipher.doFinal(stringToEncrypt.getBytes());

How can I do this in java?

Artjom B.
  • 61,146
  • 24
  • 125
  • 222
Screen
  • 11
  • 1
  • the x in AES-x is the key length: http://stackoverflow.com/questions/19061658/how-to-switch-from-aes-256-to-aes-128 - PBE makes keys of different length from passwords – zapl Dec 07 '15 at 13:06

2 Answers2

2

Use SecretKey. For example:

final int KEY_LENGTH = 256;
final SecretKeyFactory factory = SecretKeyFactory.getInstance("YourPreferredAlgorithm");
final SecretKey key = factory.generateSecret(new PBEKeySpec(pass, salt, iterations, KEY_LENGTH));

Then use the SecretKey to obtain your SecretKeySpec:

final SecretKeySpec keySpec = new SecretKeySpec(key.getEncoded(), "AES");
m0skit0
  • 25,268
  • 11
  • 79
  • 127
  • Can you explain your answer abit further i.e. pass, salt, iterations and factory. As I don't completely understand what you're referring to? – Screen Dec 07 '15 at 12:46
  • 2
    Iterations is the amount of times the password is hashed during the derivation of the (symmetric) key. A general rule of thumb is: more iterations = harder to bruteforce. The salt is a extra precaution to prevent bruteforce attacks: you need to know the salt and the password before you can check if your hash is valid. For more information, see: https://docs.oracle.com/javase/7/docs/api/javax/crypto/spec/PBEKeySpec.html#PBEKeySpec(char[],%20byte[],%20int,%20int) – nbokmans Dec 07 '15 at 12:53
  • See [here](http://stackoverflow.com/questions/6126061/pbekeyspec-what-do-the-iterationcount-and-keylength-parameters-influence). – m0skit0 Dec 07 '15 at 13:04
1

There is no AES-512. AES only supports key sizes of 128, 192 and 256 bit. In Java you select the appropriate key size by passing in a key of that size: byte[] of length 16, 24 or 32.

If you have a password and you want to stretch a key from that, then you need to use a password-based key derivation function such as PBKDF2, bcrypt, scrypt or Argon2. Be sure to adjust the iterations or the cost factor according to your needs: as high as possible without too much inconvenience for the user.

Artjom B.
  • 61,146
  • 24
  • 125
  • 222