md5加密
public static String toMD5(String s) {
if (s != null) {
try {
byte[] bs = s.getBytes("UTF-8");
return encrypt(bs);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
return null;
}
private synchronized static String encrypt(byte[] obj) {//保证只执行一次该方法
try {
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(obj);
byte[] bs = md5.digest();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bs.length; i++) {
sb.append(Integer.toHexString((0x000000ff & bs[i]) | 0xffffff00).substring(6));
}
return sb.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
SHA1 加密
public static String byte2hex(byte[] b) {
String hs = "";
String stmp = "";
for (int n = 0; n < b.length; n++) {
stmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
if (stmp.length() == 1) {
hs = hs + "0" + stmp;
} else {
hs = hs + stmp;
}
}
return hs;
}
public static String encryptToSHA(String info) {
byte[] digesta = null;
try {
// 得到一个SHA-1的消息摘要
MessageDigest alga = MessageDigest.getInstance("SHA-1");
// 添加要进行计算摘要的信息
alga.update(info.getBytes());
// 得到该摘要
digesta = alga.digest();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
// 将摘要转为字符串
String rs = byte2hex(digesta);
return rs;
}