0

I am trying to encrypt a string in java with AES encryption using a password of any length. Here is my code so far but I do not understand it very well:

public static byte[] encrypt(String input, String salt) throws NoSuchAlgorithmException, NoSuchProviderException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
    SecretKeySpec key = new SecretKeySpec(salt.getBytes(), "AES");
    Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding", "SunJCE");
    cipher.init(Cipher.ENCRYPT_MODE, key);
    return cipher.doFinal(input.getBytes());
}

How can I make a method to encrypt and decrypt a string of any length using a password of any length it. Also what is salt? I have been using the salt name for the password which only allows me to use a password of 16 characters.

kzolp67
  • 193
  • 1
  • 2
  • 12
  • 1
    possible duplicate of [Java 256-bit AES Password-Based Encryption](http://stackoverflow.com/questions/992019/java-256-bit-aes-password-based-encryption) – Duncan Jones Dec 23 '13 at 08:22
  • 3
    Do you understand what `ECB` means and what its limitations are? If not, please stop writing code until you have a basic idea of what you are doing. There is no hope code written this way will be secure. – David Schwartz Dec 23 '13 at 08:22
  • Thanks for finding that for me @Duncan, I searched everywhere and couldn't find code like that – kzolp67 Dec 23 '13 at 08:29
  • No I do not know what ECB means and what its limitations are @David Schwartx I have never done anything security/crypto related in my life – kzolp67 Dec 23 '13 at 08:32
  • What is the meaning of ECB? @David Schwartz – kzolp67 Dec 23 '13 at 08:42
  • 1
    @kzolp67 Rather than asking David for that information, try a bit of online research. There is a lot of advice out there regarding ECB-mode and why it is nearly always an inferior option to other encryption modes. – Duncan Jones Dec 23 '13 at 09:10

1 Answers1

2

If you want to encrypt/decrypt some data from a password, you need to use an algorithm which can generate from this password a key which is suitable for the cipher you want to use.

Java provides an implementation of PBKDF2 (Password based key derivation function).

char[] password = /* ... */
byte[] salt = /* ... */
SecretKeyFactory kf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
PBEKeySpec spec = new PBEKeySpec(password, salt, 8192, 256);
SecretKey tmp = kf.generateSecret(spec);
SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES");

Note that:

The salt is a non secret random byte array. It is used to avoid dictonnary based attack (see wikipedia Rainbow tables article for more details)

The iteration counts makes a brute-force attack more complex since an attack requires more resources whan the iteration count is larger. Today the iteration count should not be below 5000.

Jcs
  • 13,279
  • 5
  • 53
  • 70