加密解密算法java实现(4)—MD5
程序员文章站
2024-03-20 13:29:46
...
import java.security.MessageDigest;
public class MD5Util {
/***
* MD5加码 生成32位md5码
* @throws Exception
*/
public static String string2MD5(String inStr) throws Exception{
MessageDigest md5 = null;
md5 = MessageDigest.getInstance("MD5");
char[] charArray = inStr.toCharArray();
byte[] byteArray = new byte[charArray.length];
for (int i = 0; i < charArray.length; i++)
byteArray[i] = (byte) charArray[i];
byte[] md5Bytes = md5.digest(byteArray);
StringBuffer hexValue = new StringBuffer();
for (int i = 0; i < md5Bytes.length; i++){
int val = ((int) md5Bytes[i]) & 0xff;
if (val < 16)
hexValue.append("0");
hexValue.append(Integer.toHexString(val));
}
return hexValue.toString();
}
/**
* 示例
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
String source = "12dfefDKLJKLKL464d中文f465as43f1a3 f46e353D1F34&*^$E65F46EF43456abcd54as56f00ef";
String result = MD5Util.string2MD5(source);
System.out.println("加密结果:\n" + result);
}
}
上一篇: 用session实现简单的购物车