Com esses três métodos abaixo gera o seguinte hex “698dc19d489c4e4db73e28a713eab07b” para a String “teste” :
private static final String HEXDIGITS = "0123456789abcdef";
private 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();
}
- Método citado no artigo http://www.guj.com.br/articles/32
public static String toHex(byte[] a) {
StringBuilder sb = new StringBuilder(a.length * 2);
for (int i = 0; i < a.length; i++) {
sb.append(Character.forDigit((a[i] & 0xf0) >> 4, 16));
sb.append(Character.forDigit(a[i] & 0x0f, 16));
}
return sb.toString();
}
public static String toHex2(byte[] a) {
//convert the byte to hex format method 1
StringBuffer sb = new StringBuffer();
for (int i = 0; i < a.length; i++) {
sb.append(Integer.toString((a[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
Utilizando o DigestUtils do Apache Commons Codec (1.6), gera o seguinte hex para a mesma String: “504876f7eb0c1e0db0a1e92bcb7f49f9”
O interessante é que para o SHA1 acontece o mesmo problema.
Obs: Testei no console do linux utilizando o md5sum, e gera o mesmo hex gerado pelos três métodos citados. Comando: “echo -n ‘teste’ | md5sum”