欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

md5加密

程序员文章站 2024-03-19 09:29:46
...

package com.horizon.util;

import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
* 将字符串进行md5加密
* @author LIMENGCHENG292
*
*/
public class MD5 {
/**
*
* @param str 需要被加密的String
* @return 加密之后的String (32个16进制数 128位)
* 例如:A1234567890B1234567890C123456789
* @throws NoSuchAlgorithmException
*/
private static final String DEFAULTMD5String = "00000000000000000000000000000000";
public static String MD5Encoder(String str)
throws NoSuchAlgorithmException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
if (str == null) {
// 如果需要加密的String是null,返回默认的DEFAULTMD5String
return DEFAULTMD5String;
}
md5.update(str.getBytes());
byte[] b = md5.digest();
int i = 0;
StringBuffer buf = new StringBuffer("");
for (int offset=0; offset<b.length; offset++) {
i = b[offset];
if (i<0) {
i = i + 256;
}
if (i<16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
return buf.toString();
}

public static String MD5Encoder(Object obj)
throws NoSuchAlgorithmException, IOException {
MessageDigest md5 = MessageDigest.getInstance("MD5");
if (obj == null) {
// 如果需要加密的Object是null,返回默认的DEFAULTMD5String
return DEFAULTMD5String;
}
md5.update(DataUtil.objToBytes(obj));
byte[] b = md5.digest();
int i = 0;
StringBuffer buf = new StringBuffer("");
for (int offset=0; offset<b.length; offset++) {
i = b[offset];
if (i<0) {
i = i + 256;
}
if (i<16) {
buf.append("0");
}
buf.append(Integer.toHexString(i));
}
return buf.toString();
}
}


第二个方法中的参数obj,必须是可序列化的,否则会throw一个NotSerializableException
上类中用到的DataUtil类,代码如下

package com.horizon.util;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class DataUtil {

public static byte[] objToBytes(Object obj) throws IOException {
if (obj == null) {
return null;
}
ByteArrayOutputStream bo = null;
ObjectOutputStream oo = null;
try {
bo = new ByteArrayOutputStream();
oo = new ObjectOutputStream(bo);
oo.writeObject(obj);
oo.flush();
oo.close();
return bo.toByteArray();
} catch (IOException e) {
throw e;
} finally {
if (bo != null) {
bo.close();
bo = null;
}
}
}
}
相关标签: OO Java Security