Generating MD5 Hash with char []

How would I go about converting the char [] password obtained with this method:

char[] password = passwordInputField.getPassword();

      

To the MD5 hash? I would normally use the method below, but getBytes is only string compatible:

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
String hashedPass = new BigInteger(1, md.digest()).toString(16);

      

+3


source to share


1 answer


NOTE. The MD5 Hash Algorithm should never be used to store passwords, as hashes are easily cracked. However, I will use it for simplicity.

The quick / easy / UNSECURE fix is ​​for converting a char array to string. However, this is unsafe because strings are immutable and cannot be removed from memory.

String password = new String(passwordInputField.getPassword());

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(password.getBytes());
String hashedPass = new BigInteger(1, md.digest()).toString(16);

      

Safer solution: Convert char [] to byte [] and clear the arrays from memory.



private byte[] toBytes(char[] chars) {
    CharBuffer charBuffer = CharBuffer.wrap(chars);
    ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
    byte[] bytes = Arrays.copyOfRange(byteBuffer.array(),
            byteBuffer.position(), byteBuffer.limit());
    Arrays.fill(charBuffer.array(), '\u0000'); // clear sensitive data
    Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
    return bytes;
}

char[] passChars = passwordInputField.getPassword();
byte[] passBytes = toBytes(passChars);

MessageDigest md = MessageDigest.getInstance("MD5");
md.update(passBytes);
String hashedPass = new BigInteger(1, md.digest()).toString(16);

Arrays.fill(passChars, '\u0000'); // clear sensitive data
Arrays.fill(passBytes, (byte) 0); // clear sensitive data

      

EDIT:

Updated answer with safer solution (credit to user 2656928 for the idea).

char [] to byte [] method credit andreyne

+1


source







All Articles