项目中需要将字符串进行SHA-1加密,百度了一下整理出来的工具类: 附上代码如下:
package com.lc.util;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* SHA-1 加密
* @author lc
*/
public class AddSHA {
public static String SHA1(String inStr) {
MessageDigest md = null;
String outStr = null;
try {
md = MessageDigest.getInstance("SHA-1"); //选择SHA-1,也可以选择MD5
byte[] digest = md.digest(inStr.getBytes()); //返回的是byet[],要转化为String存储比较方便
outStr = bytetoString(digest);
}
catch (NoSuchAlgorithmException nsae) {
nsae.printStackTrace();
}
return outStr;
}
public static String bytetoString(byte[] digest) {
String str = "";
String tempStr = "";
for (int i = 0; i < digest.length; i++) {
tempStr = (Integer.toHexString(digest[i] & 0xff));
if (tempStr.length() == 1) {
str = str + "0" + tempStr;
}
else {
str = str + tempStr;
}
}
return str.toLowerCase();
}
}