import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.locks.ReentrantLock;
/**
*
* @author xsm
*
*/
public class MD5test {
/**
* 申明一个16进制char数组
* 把数组对象作为map集合的Key保存,Value对应int数值
*/
private static char[] HexNum={'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};
private static Map<Character,Integer> map=new HashMap<Character,Integer>(16);
static {
for(int i=0;i<HexNum.length;i++){
map.put(Character.valueOf(HexNum[i]), Integer.valueOf(i));
}
} private static MD5test md=new MD5test();//单例模式保证每次创建对象的唯一
private MessageDigest message;//得到一个信息摘要器
private final ReentrantLock lock=new ReentrantLock();//获得一个可重入锁,保证并发环境下加密的唯一性
MD5test(){
try {
this.message=MessageDigest.getInstance("md5");
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static MD5test getInstance(){
return md;
}
public String getMD5String(String content) {
return byteToString(hash(content));
}
public String getMD5String(byte[] content) {
return byteToString(hash(content));
}
public byte[] getMD5Bytes(byte[] content) {
return hash(content);
}
/**
*
* @return 返回散列后的byte 对象
*/
public byte[] hash(String str){
this.lock.lock();
try {
byte[] bt=this.message.digest(str.getBytes("GBK"));
if(null==bt||(bt.length!=16)){
throw new IllegalArgumentException("传入的字符串不合法");
}
return bt;
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
throw new RuntimeException("unsupported utf-8 encoding", e);
}finally{
lock.unlock();
}
}
/**
*
* @param b返回散列后的byte 数组
* @return
*/
public byte[] hash(byte[] bt){
this.lock.lock();
try{
byte[] btt=this.message.digest(bt);
if(null==btt||btt.length!=16){
throw new IllegalArgumentException("辣鸡,字符串也能输错");
}
return btt;
}finally{
this.lock.unlock();
}
}
/**
*
* @param byte转化为string对象
* @return
*/
public String byteToString(byte[] bt){
int L=bt.length;
char[] out=new char[L<<1];
int i=0;
for(int j=0;i<L;i++){
out[j++]=HexNum[((0xF0&bt[i])>>>4)];//0xF0与bt[i]与运算再右移四位,相当于取16位的首位数
out[j++]=HexNum[0xF&bt[i]];
}
return new String(out);
}
}
今天用到MD5加密发现网上的大多不怎么规范,索性请教师傅自己写了一个规范的Demo,这个Demo没有复杂的加盐操作,百分百会被http://www.cmd5.com/类似网站破解,仅供学习java实现MD5加密并考虑生产环境(一)
最新推荐文章于 2024-02-23 15:57:54 发布