天天看點

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==