MD5加密
2015-10-28 23:49
106 查看
因为md5加密后得到的数据是128位的字节数组,第一种方法把数组转换成16进制输出.
import java.security.MessageDigest;
public class MD5Utils {
public static String md5(String text, String encoding) throws Exception{
MessageDigest msgDigest = null;
msgDigest = MessageDigest.getInstance("MD5");
byte[] bytes = null;
if (encoding == null || encoding.equals("")) {
bytes = msgDigest.digest(text.getBytes());
} else {
bytes = msgDigest.digest(text.getBytes(encoding));
}
String md5Str = bytesToHex(bytes);
return md5Str;
}
private static String bytesToHex(byte[] paramArrayOfByte)
{
String str1 = "";
String str2 = "";
for (int i = 0; i < paramArrayOfByte.length; ++i)
{
str2 = Integer.toHexString(paramArrayOfByte[i] & 0xFF);
if (str2.length() == 1)
str1 = str1 + "0";
str1 = str1 + str2;
}
return str1;
}
}
第二种结合base64加密
public static String encrypt(String origStr) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] buf = md.digest(origStr.getBytes());
BASE64Encoder base = new BASE64Encoder();
String str = base.encode(buf);
return str;
}
import java.security.MessageDigest;
public class MD5Utils {
public static String md5(String text, String encoding) throws Exception{
MessageDigest msgDigest = null;
msgDigest = MessageDigest.getInstance("MD5");
byte[] bytes = null;
if (encoding == null || encoding.equals("")) {
bytes = msgDigest.digest(text.getBytes());
} else {
bytes = msgDigest.digest(text.getBytes(encoding));
}
String md5Str = bytesToHex(bytes);
return md5Str;
}
private static String bytesToHex(byte[] paramArrayOfByte)
{
String str1 = "";
String str2 = "";
for (int i = 0; i < paramArrayOfByte.length; ++i)
{
str2 = Integer.toHexString(paramArrayOfByte[i] & 0xFF);
if (str2.length() == 1)
str1 = str1 + "0";
str1 = str1 + str2;
}
return str1;
}
}
第二种结合base64加密
public static String encrypt(String origStr) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] buf = md.digest(origStr.getBytes());
BASE64Encoder base = new BASE64Encoder();
String str = base.encode(buf);
return str;
}
相关文章推荐
- 今天事都赶一起了
- [转载] Thrift-server与spring集成
- iOS中NSURLSession的使用
- 分布式系统中的CAP理论
- Java 多态机制专题
- Ext.extend 详解
- 5月编程语言排行榜:动态语言的前世今生
- GLOBAL_TXN_PROCESSES 参数与 分布式事务,DTP 属性
- Front-end Developer Handbook
- 彻底理解PHP的SESSION机制
- 高级学员:2015年10月26日作业
- 项目冲刺-第三天
- [LintCode] Permutations II
- 《Intel汇编第5版》 Mov指令
- [转载] Thrift-client与spring集成
- HDU - 5122 K.Bro Sorting(贪心)
- Spring官网改版后下载
- 教你简单玩转WebService -JAX-WS
- 传统的分布式应用集成技术(网摘)
- [LeetCode] Single Number III