1.MD5
package com.ninemax.utils.tools;import java.math.BigInteger;import java.security.MessageDigest;/** * Created by AckMan on 2016/9/6. * * 源数据MD5加密比较,不可解密 * * MD5是一种不可逆的摘要算法 */public class MD5Utils { public static String md5Encode(String str){ byte [] result = null; if(str.isEmpty()){ return null; } try { System.out.println("加密前:" + str); result = MessageDigest.getInstance("md5").digest(str.getBytes("utf-8")); System.out.println("加密后:" + new BigInteger(1, result).toString(16)); } catch (Exception e) { e.printStackTrace(); } return new BigInteger(1, result).toString(16); } public static void main(String args[]){ md5Encode("darker"); }}
MD5运行结果
加密前:darker加密后:ea225ae75583177eba676db77e3af75d
2.Base64
package com.ninemax.utils.tools;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;import java.io.IOException;import java.io.UnsupportedEncodingException;/** * Created by AckMan on 2016/9/6. * * Base64是一种编码方式 */public class Base64Utils { public static String encode(String str){ if(str.isEmpty()){ return null; } BASE64Encoder encoder = new BASE64Encoder(); try { System.out.println("加密前:" + str); String result = encoder.encode(str.getBytes("utf-8")); System.out.println("加密后:" + result); return encoder.encode(str.getBytes("utf-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } return null; } public static String decode(String str){ if(str.isEmpty()){ return null; } BASE64Decoder decoder = new BASE64Decoder(); try { System.out.println("解密前:" + str); byte[] result = decoder.decodeBuffer(str); System.out.println("解密后:" + new String(result)); } catch (IOException e) { e.printStackTrace(); } return null; } public static void main(String args[]){ //encode("darker"); decode(encode("darker")); }}
Base64运行结果
加密前:darker加密后:ZGFya2Vy解密前:ZGFya2Vy解密后:darker