MD5加密
创建MD5Util类
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Util {
public static String encryptPassword(String password) {
return digest(password);
}
/**
* 设置编码并加密
* @param myInfo
* @param encoding
* @return
*/
public static String digest(String myInfo,String encoding) {
try {
if (myInfo == null) {
myInfo = "";
}
byte[] bin = new byte[0];
try {
bin = myInfo.getBytes(encoding);
} catch (UnsupportedEncodingException e) {
}
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(bin);
byte[] digest = md.digest();
return byte2hex(digest);
} catch (NoSuchAlgorithmException ex){
return null;
}
}
/**
*
* @param myinfo
* @return
*/
public static String digest(String myinfo){
return digest(myinfo,"utf-8");
}
/**
* 二进制转化为字符串
*/
private static String byte2hex(byte[] bytes){
String hs = "";
String stmp = "";
for (int i = 0; i < bytes.length; i++) {
stmp = (Integer.toHexString(bytes[i] & 0XFF));
if(stmp.length() == 1){
hs = hs + "0" + stmp;
}else{
hs = hs + stmp;
}
if(i<bytes.length - 1){
hs = hs + "";
}
}
return hs.toLowerCase();
}
}
调用示例
String tel = MD5Util.digest("18737621003");
还可参见DES加密方式