|
| 1 | +package MD5; |
| 2 | +import java.security.MessageDigest; |
| 3 | +/** |
| 4 | + * 采用MD5加密解密 |
| 5 | + * @author tfq |
| 6 | + * @datetime 2011-10-13 |
| 7 | + */ |
| 8 | +public class MD5Util { |
| 9 | + |
| 10 | + /*** |
| 11 | + * MD5加码 生成32位md5码 |
| 12 | + */ |
| 13 | + public static String string2MD5(String inStr){ |
| 14 | + MessageDigest md5 = null; |
| 15 | + try{ |
| 16 | + md5 = MessageDigest.getInstance("MD5"); |
| 17 | + }catch (Exception e){ |
| 18 | + System.out.println(e.toString()); |
| 19 | + e.printStackTrace(); |
| 20 | + return ""; |
| 21 | + } |
| 22 | + char[] charArray = inStr.toCharArray(); |
| 23 | + byte[] byteArray = new byte[charArray.length]; |
| 24 | + |
| 25 | + for (int i = 0; i < charArray.length; i++) |
| 26 | + byteArray[i] = (byte) charArray[i]; |
| 27 | + byte[] md5Bytes = md5.digest(byteArray); |
| 28 | + StringBuffer hexValue = new StringBuffer(); |
| 29 | + for (int i = 0; i < md5Bytes.length; i++){ |
| 30 | + int val = ((int) md5Bytes[i]) & 0xff; |
| 31 | + if (val < 16) |
| 32 | + hexValue.append("0"); |
| 33 | + hexValue.append(Integer.toHexString(val)); |
| 34 | + } |
| 35 | + return hexValue.toString(); |
| 36 | + |
| 37 | + } |
| 38 | + |
| 39 | + /** |
| 40 | + * 加密解密算法 执行一次加密,两次解密 |
| 41 | + */ |
| 42 | + public static String convertMD5(String inStr){ |
| 43 | + |
| 44 | + char[] a = inStr.toCharArray(); |
| 45 | + for (int i = 0; i < a.length; i++){ |
| 46 | + a[i] = (char) (a[i] ^ 't'); |
| 47 | + } |
| 48 | + String s = new String(a); |
| 49 | + return s; |
| 50 | + |
| 51 | + } |
| 52 | + |
| 53 | + // 测试主函数 |
| 54 | + public static void main(String args[]) { |
| 55 | + String s = new String("http://hao.360.cn/next.html?1006"); |
| 56 | + System.out.println("原始:" + s); |
| 57 | + System.out.println("MD5后:" + string2MD5(s)); |
| 58 | + System.out.println("加密的:" + convertMD5(s)); |
| 59 | + System.out.println("解密的:" + convertMD5(convertMD5(s))); |
| 60 | + |
| 61 | + } |
| 62 | +} |
0 commit comments