segunda-feira, 2 de abril de 2012

Segurança em login utilizando digest com MD5

String de hexadecimais válidos:
private static final String hexDigits = "0123456789abcdef";
Método Digest passando a string de login e o algoritmo utilizando como parâmetro na criptografia:
public static byte[] digest(byte[] input, String algoritmo) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance(algoritmo);
    md.reset();
    return md.digest(input);
}
Método que passa a string após o digest para o formato hexadeximal:
public static String byteArrayToHexString(byte[] b) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < b.length; i++) {
        int j = ((int) b[i]) & 0xFF;
        buf.append(hexDigits.charAt(j / 16));
        buf.append(hexDigits.charAt(j % 16));
   }
   return buf.toString();
}
Utilizando os métodos:
byte[] pass = CriptoUtils.digest(new String(jpSenha.getPassword()).getBytes(), "md5");
String passCrypt = CriptoUtils.byteArrayToHexString(pass);
usuario.setSenha(passCrypt);