导包:
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.10</version>
</dependency>
代码:
/**
* 计算字符串的摘要
*/
public void testMd5() {
throws NoSuchAlgorithmException,
UnsupportedEncodingException {
//计算字符串的摘要
String str = "123";
//创建消息摘要算法对象
//参数是算法名: MD5 sha1 sha256 等
//如果算法名错误,则抛出异常
MessageDigest md5=
MessageDigest.getInstance("MD5");
//将数据提交到md5进行计算
byte[] data = str.getBytes("UTF-8");
md5.update(data);
//md5.update(data);
//md5.update(data);
//....
//获取计算出的摘要
byte[] md = md5.digest();
//String hex = hex(md);
String hex=Hex.encodeHexString(md);
System.out.println(hex);
}
/**
* 将2进制转换为 16进制字符串
*/
public String hex(byte[] ary){
String digi="0123456789abcdef";
char[] hex = new char[ary.length*2];
int i=0;//代表 hex 数组的下标
for(int b:ary){
int b1 = (b>>>4) & 0xf;
int b2 = b & 0xf;
char c1 = digi.charAt(b1);
char c2 = digi.charAt(b2);
hex[i++]=c1;
hex[i++]=c2;
}
return new String(hex);
}
/**
* 计算文件的摘要
*/
public void testFileMd5()
throws Exception {
//计算文件的摘要
FileInputStream in =
new FileInputStream("install.log");
byte[] buf = new byte[1024];
MessageDigest md5 =
MessageDigest.getInstance("md5");
//多次调用 update
int n;
while((n=in.read(buf))!=-1){
md5.update(buf, 0, n);
}
in.close();
byte[] md=md5.digest();
String hex=Hex.encodeHexString(md);
System.out.println(hex);
}
/**
* 跟简单的字符串和文件摘要计算
*/
public void testMd52(){
String md5=DigestUtils.md5Hex("123");
System.out.println(md5);
}
spublic void testFileMd52()
throws Exception {
FileInputStream in =
new FileInputStream("install.log");
String hex=DigestUtils.md5Hex(in);
in.close();
System.out.println(hex);
}
/**
* 摘要加盐
*/
public void testSalt(){
//加盐摘要
String salt = "奇异博士";
String pwd = "123";
String hex = DigestUtils.md5Hex(pwd+salt);
System.out.println(hex);
}