Search code examples
javastringencryptionpassword-hash

How to encrypt a string in Java by just using a password?


I'm developing an application where I need to encrypt text using a user-entered password (as a key) and store it. User can decrypt his data whenever he wants by entering the password. The security of the data should depend upon the complexity and length of the password.

I have used AES before but here I can't use it as the encryption key in AES has to be of a specific length. I want something where the encryption key could be of any length.

I just can't figure out which encryption method or algorithm to use.


Solution

  • Search for PBKDF - password based key derivation function. Please note - passwords are not keys (passwords are having different length and usually less entropy).

    Though you may derive a key from the password. Commonly used password-based key derivation functions used today are PBKDF2, Argon2, BCrypt or SCrypt. Just search for them.

    You may check some examples

    IvParameterSpec ivParamSpec = new IvParameterSpec(iv);
    
    PBEParameterSpec pbeParamSpec = new PBEParameterSpec(psswdSalt, PBKDF_INTERATIONS, ivParamSpec);
    PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
    SecretKeyFactory pbeKeyFactory = 
    SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128");
    SecretKey pbeKey = pbeKeyFactory.generateSecret(pbeKeySpec);
    
    Cipher cipher = Cipher.getInstance(PBE_CIPHER_NAME);
    cipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);
    

    In theory - you may use a simple hash (e.g. sha-256) and take only necessary number of bits to derive a key. The issue is that the password are usually not that random if it is easy for a human to remember; this means that they are vulnerable to brute-force attacks or dictionary attacks.