简单实现的MD5工具类
public class MD5Utils {
private MD5Utils(){}
public static final String ENCODE = "GBK";
//带key
public static String hmacSign(String aValue, String aKey) {
byte k_ipad[] = new byte[64];
byte k_opad[] = new byte[64];
byte keyb[];
byte value[];
try {
keyb = aKey.getBytes(ENCODE);
value = aValue.getBytes(ENCODE);
} catch (UnsupportedEncodingException e) {
keyb = aKey.getBytes();
value = aValue.getBytes();
}
Arrays.fill(k_ipad, keyb.length, 64, (byte) 54);
Arrays.fill(k_opad, keyb.length, 64, (byte) 92);
for (int i = 0; i < keyb.length; i++) {
k_ipad[i] = (byte) (keyb[i] ^ 0x36);
k_opad[i] = (byte) (keyb[i] ^ 0x5c);
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
md.update(k_ipad);
md.update(value);
byte dg[] = md.digest();
md.reset();
md.update(k_opad);
md.update(dg, 0, 16);
dg = md.digest();
return MD5.toHex(dg);
}
public static String digest(String aValue) {
aValue = aValue.trim();
byte value[];
try {
value = aValue.getBytes(ENCODE);
} catch (UnsupportedEncodingException e) {
value = aValue.getBytes();
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
return null;
}
return MD5.toHex(md.digest(value));
}
public static String toHex(byte input[]) {
if (input == null)
return null;
StringBuffer output = new StringBuffer(input.length * 2);
for (int i = 0; i < input.length; i++) {
int current = input[i] & 0xff;
if (current < 16)
output.append("0");
output.append(Integer.toString(current, 16));
}
return output.toString();
}
//不带key
public static String getMd5(String str) throws NoSuchAlgorithmException {
//获取实例
MessageDigest md=MessageDigest.getInstance ("MD5");//支持大小写
//处理数据
md.update(str.getBytes());
//通过执行诸如填充之类的最终操作完成哈希计算。
byte byt[]=md.digest();//为128位-->16个字节
StringBuilder sbu=new StringBuilder("");
int number=0;
for (int i = 0; i < byt.length; i++) {
number=byt[i];
if (number < 0) {
number += 256;
}if (number<16) {
sbu.append("0");
}
sbu.append(Integer.toHexString(number));
}
//加密为32个字符
// System.out.println(sbu.toString().length());//字符个数为32
return sbu.toString();
//加密为16个字符
//return buf.toString().substring(8, 24);
}
public static void main(String[] args) {
String inputStr = "加密前原码";
String md5edStr = MD5Utils.hmacSign(inputStr, "1234567890");
System.out.println(md5edStr);
}
}