Logo
Published on

Hashing a password with MD5

Authors

To store in a database a password in a non-reversible encrypted way, it is possible to use the MD5 and SHA-x algorithms.

Here is a small example of encoding using the JCE

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import sun.misc.BASE64Encoder;

public class UserHash {

  /**
   * @param args
   */
  public static void main(String[] args) {

    final String userMail = "aferrand1.ext@franceevasion.com";
    System.out.println("MD2=" + getEncodedString(userMail, "MD2"));
    System.out.println("MD5=" + getEncodedString(userMail, "MD5"));
    System.out.println("SHA-1=" + getEncodedString(userMail, "SHA-1"));
    System.out.println("SHA-256=" + getEncodedString(userMail, "SHA-256"));
    System.out.println("SHA-384=" + getEncodedString(userMail, "SHA-384"));
    System.out.println("SHA-512=" + getEncodedString(userMail, "SHA-512"));

  }

  public static String getEncodedString(String key) {
    return getEncodedString(key, "MD5");
  }

  public static String getEncodedString(String key, String digest) {

    byte[] uniqueKey = key.getBytes();
    byte[] hash = null;

    try {

      hash = MessageDigest.getInstance(digest).digest(uniqueKey);

    } catch (NoSuchAlgorithmException e) {
      throw new Error("no "+ digest +" support in this VM");
    } catch (Exception e) {
      e.printStackTrace();
    }

    return (new BASE64Encoder()).encode(hash);
  }

}

Result is

MD2=abWmfCsNRTXOKvWKtDBalg==
MD5=WOY/DfvYDWhC1sdAijKGVQ==
SHA-1=TAXYB18o7K7fmh74x/Mss38HF9Y=
SHA-256=Vnpmj347XpI4XV6Zb7eAd4uKR62Tgo/r2tVaVR2+SGw=
SHA-384=h2rM7Hu6I8joG2chmP+2zPLFkxbFpJnwqXK8J4bAnSvkAm7G8uA1AS2PJXy0S12f
SHA-512=lpXw8sA14isPhf1EiXW/Uy8WNDYIHBlTo8iP5GINC9/eATQIybEf836yseOSkGeptQ3hZMy2B0nG neBeB+Y62g==