Creating Secure Passwords in Java

I found this gem on reddit a few days ago and spent 5 minutes playing around with the code.

Secure Password Storage Lots of Dont’s, a Few Dos, and a Concrete Java SE Example
By: Jeremiah Orr

Using Jeremiah’s code sample I only needed two lines to generate an encrypted password. One is for generating a salt and the other for generating an encrypted password. Pretty light weight but extremely useful. In this case the symbol encryption is a reference to the PasswordEncryptionService object. It could be rewritten as PasswordEncryptionServerice.generateSalt() but I’m lazy and don’t want to type all of that out each time.

byte[] salt = encryption.generateSalt();
byte[] encryptedPassword = encryption.getEncryptedPassword(password, salt);

Calling generateSalt will generate a random 8 byte value. The code makes use of the random number generator, SecureRandom, to create a unique salt.

With a unique salt we can generate a secure byte array from a given password. There is another method in Jeremiah’s sample worth taking a look at, authenticate(). The method authenticate takes in a potential match for a password along with the encrypted password with it’s salt to check if the validity of the potential password. The method generates a new encrypted password using the potential password and salt to compare to with the encrypted password. Only storing the salt and encrypted password we can remove the need for storing password in clear text or don’t and take Sony’s approach to user security.

Here is my full test harness.


public class Tester {
    private PasswordEncryptionService encryption = new PasswordEncryptionService();

    public Tester(String password){
        try {
            System.out.println("Password: " + password);

            byte[] salt = encryption.generateSalt();
            System.out.println("Salt: " + salt);

            byte[] encryptedPassword = encryption.getEncryptedPassword(password, salt);
            System.out.println("Encrypted Password: " + encryptedPassword + "\n" );

            System.out.println("Does it pass authentication?\n" + encryption.authenticate(password, encryptedPassword, salt) + "\n" );
            System.out.println("Sanity authentication check\n" + encryption.authenticate("Rawr", encryptedPassword, salt) );

        } catch (NoSuchAlgorithmException e) {
        } catch (InvalidKeySpecException e) {

Along with my main.

public class Run {
    public static void main(String[] args){
        Tester test = new Tester("password");

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s