2015-04-11 23:52:45 +02:00
|
|
|
|
|
|
|
|
|
|
|
import java.security.MessageDigest;
|
|
|
|
import java.security.NoSuchAlgorithmException;
|
|
|
|
|
|
|
|
public class HexUtil
|
|
|
|
{
|
2015-04-13 22:42:16 +02:00
|
|
|
/**
|
|
|
|
* Print out a byte array in hexadecimal
|
|
|
|
* @param bytes array
|
|
|
|
*/
|
2015-04-11 23:52:45 +02:00
|
|
|
public static void printHex(byte[] bytes)
|
|
|
|
{
|
2015-04-13 22:42:16 +02:00
|
|
|
for(byte b : bytes) System.out.print(byteToHexString(b));
|
2015-04-11 23:52:45 +02:00
|
|
|
}
|
|
|
|
|
2015-04-13 22:42:16 +02:00
|
|
|
/**
|
|
|
|
* convert a byte to a hex string
|
|
|
|
* @param data array
|
|
|
|
* @return String representation in hex
|
|
|
|
*/
|
|
|
|
public static String byteToHexString(byte data) {
|
2015-04-11 23:52:45 +02:00
|
|
|
|
|
|
|
StringBuffer buf = new StringBuffer();
|
|
|
|
buf.append(toHexChar((data >>> 4) & 0x0F));
|
|
|
|
buf.append(toHexChar(data & 0x0F));
|
|
|
|
|
|
|
|
return buf.toString();
|
|
|
|
}
|
|
|
|
|
2015-04-13 22:42:16 +02:00
|
|
|
/**
|
|
|
|
* convert a integer into a hexadecimal character
|
|
|
|
* @param i integer
|
|
|
|
* @return hex char
|
|
|
|
*/
|
2015-04-11 23:52:45 +02:00
|
|
|
public static char toHexChar(int i) {
|
|
|
|
if ((0 <= i) && (i <= 9)) {
|
|
|
|
return (char) ('0' + i);
|
|
|
|
} else {
|
|
|
|
return (char) ('a' + (i - 10));
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2015-04-13 22:42:16 +02:00
|
|
|
/**
|
|
|
|
* Generate the md5 digest of the byte array data in hexadecimal
|
|
|
|
* @param data array
|
|
|
|
* @return byte array of the md5 digest in hex
|
|
|
|
*/
|
2015-04-11 23:52:45 +02:00
|
|
|
public static byte[] generateMD5(byte[] data)
|
|
|
|
{
|
|
|
|
try
|
|
|
|
{
|
|
|
|
byte[] md5 = MessageDigest.getInstance("MD5").digest(data);
|
|
|
|
String m="";
|
|
|
|
for(int i=0; i<md5.length; i++)
|
|
|
|
{
|
2015-04-13 22:42:16 +02:00
|
|
|
m = m + byteToHexString(md5[i]).toUpperCase();
|
2015-04-11 23:52:45 +02:00
|
|
|
}
|
|
|
|
return m.getBytes();
|
|
|
|
} catch (NoSuchAlgorithmException e)
|
|
|
|
{
|
|
|
|
// TODO Auto-generated catch block
|
|
|
|
e.printStackTrace();
|
|
|
|
return null;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|