天天看点

Java 加密 MD5

版权声明:本文为博主原创文章,未经博主允许不得转载。

【md5】

md5是一种哈希算法,哈希算法是啥? 。。。

特点是不能解密。

[java] view plain copy

  1. package com.uikoo9.util.encrypt;  
  2. import java.math.BigInteger;  
  3. import java.security.MessageDigest;  
  4. import sun.misc.BASE64Decoder;  
  5. import sun.misc.BASE64Encoder;  
  6. import com.uikoo9.util.QStringUtil;  
  7. /** 
  8.  * 编码工具类 
  9.  * 1.将byte[]转为各种进制的字符串 
  10.  * 2.base 64 encode 
  11.  * 3.base 64 decode 
  12.  * 4.获取byte[]的md5值 
  13.  * 5.获取字符串md5值 
  14.  * 6.结合base64实现md5加密 
  15.  * @author uikoo9 
  16.  * @version 0.0.6.20140601 
  17.  */  
  18. public class QEncodeUtil {  
  19.     public static void main(String[] args) throws Exception {  
  20.         String msg = "我爱你";  
  21.         System.out.println("加密前:" + msg);  
  22.         String encrypt = md5Encrypt(msg);  
  23.         System.out.println("加密后:" + encrypt);  
  24.     }  
  25.     /** 
  26.      * 将byte[]转为各种进制的字符串 
  27.      * @param bytes byte[] 
  28.      * @param radix 可以转换进制的范围,从Character.MIN_RADIX到Character.MAX_RADIX,超出范围后变为10进制 
  29.      * @return 转换后的字符串 
  30.      */  
  31.     public static String binary(byte[] bytes, int radix){  
  32.         return new BigInteger(1, bytes).toString(radix);// 这里的1代表正数  
  33.      * base 64 encode 
  34.      * @param bytes 待编码的byte[] 
  35.      * @return 编码后的base 64 code 
  36.     public static String base64Encode(byte[] bytes){  
  37.         return new BASE64Encoder().encode(bytes);  
  38.      * base 64 decode 
  39.      * @param base64Code 待解码的base 64 code 
  40.      * @return 解码后的byte[] 
  41.      * @throws Exception 
  42.     public static byte[] base64Decode(String base64Code) throws Exception{  
  43.         return QStringUtil.isEmpty(base64Code) ? null : new BASE64Decoder().decodeBuffer(base64Code);  
  44.      * 获取byte[]的md5值 
  45.      * @return md5 
  46.     public static byte[] md5(byte[] bytes) throws Exception {  
  47.         MessageDigest md = MessageDigest.getInstance("MD5");  
  48.         md.update(bytes);  
  49.         return md.digest();  
  50.      * 获取字符串md5值 
  51.      * @param msg  
  52.     public static byte[] md5(String msg) throws Exception {  
  53.         return QStringUtil.isEmpty(msg) ? null : md5(msg.getBytes());  
  54.      * 结合base64实现md5加密 
  55.      * @param msg 待加密字符串 
  56.      * @return 获取md5后转为base64 
  57.     public static String md5Encrypt(String msg) throws Exception{  
  58.         return QStringUtil.isEmpty(msg) ? null : base64Encode(md5(msg));  
  59. }  
    1. 加密前:我爱你  
    2. 加密后:TyAWxrk01VvXEg5dDmLM4w==