Monday 29 April 2019

MessageDigest.getInstance("SHA") is the same as MessageDigest.getInstance("SHA-1")

"SHA-1" is not recommended to be used to hash passwords, by the way. More advanced SHA algorithms such as 'SHA-256' should be used instead

import java.security.MessageDigest;

public final class PasswordHasher {
    
    private PasswordHasher() {
        throw new IllegalStateException("Utility class");
    }
    
    public static String hash(String plainPassword, String passwordSalt) {
        return hash("SHA", plainPassword, passwordSalt);
    }
    
    public static String hash(String algorithm, String plainPassword, String passwordSalt) {
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm) ;
            md.update(passwordSalt.getBytes()) ; 
            md.update(plainPassword.getBytes()) ;
            byte[] digest = md.digest() ;
            StringBuilder sb = new StringBuilder(500) ;
            for (int i=0;i<digest.length;i++) {
                sb.append(Integer.toHexString((digest[i]&0xFF) | 0x100).substring(1,3)) ;
            }
            return sb.toString() ;
        }catch(Exception e) {
            throw new IllegalArgumentException("Error occurred when hashing password ", e);
        }
    }
}

import static org.junit.Assert.*;

import org.junit.Test;

public class PasswordHasherTest {

    @Test
    public void hash() {
        String plainPassword = "password";
        String salt = "salty19143";
        assertEquals("0dd9e6d58f5316e828c352af8876143a61b291fc", PasswordHasher.hash(plainPassword, salt));
        plainPassword = "random123";
        assertEquals(PasswordHasher.hash("SHA-1", plainPassword, salt), PasswordHasher.hash(plainPassword, salt));
    }

}

No comments:

Post a Comment