package com.util.md5;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
*
* @describe 实现将生成的MD5码进行加密和解密,
* @author zhutianpeng
*
*/
public class UtilMD5 {
private UtilMD5(){} //避免生成对象,实现静态访问
/**
* @describe 实现MD5码进行二次加密后的编码
* @param str
* @return secondCode
*/
public static String getConcertCodeMD5(String str){
String firstCode = string2MD5(str);
String secondCode = convertMD5(firstCode);
return secondCode;
}
/**
* @describe 实现MD5码进行二次加密后的编码进行解密所生成的MD5码
* @param str
* @return secondCode
*/
public static String getConcertEncodeMD5(String str){
String firstCode = convertMD5(str);
String secondCode = string2MD5(firstCode);
return secondCode;
}
/***
* MD5加码 生成32位md5码
*/
private static String string2MD5(String str){
MessageDigest md5 = null;
try {
md5 = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
System.out.println("【MD5算法异常,生成MD5码失败...】");
return "";
}
char[] charArray = str.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();
}
/**
* 加密解密算法 执行一次加密,两次解密
*/
private static String convertMD5(String str){
char[] temp = str.toCharArray();
for (int i = 0; i < temp.length; i++){
temp[i] = (char) (temp[i] ^ 'z');
}
String myStr = new String(temp);
return myStr;
}
}
public class Test {
public static void main(String[] args) {
String a = "aaa";
System.out.println("MD5码加密:"+UtilMD5.getConcertCodeMD5(a));
System.out.println("MD5码加密后解密:"+UtilMD5.getConcertEncodeMD5(UtilMD5.getConcertCodeMD5(a)));
}
}
阅读(2872) | 评论(0) | 转发(0) |