MD5和Base64

使用apache的commons-codec jar包進行Base64編碼/解碼,md5加密

package base64;

import java.io.UnsupportedEncodingException;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.digest.DigestUtils;

public class MD5Demo {
    public static void main(String[] args) {
        String str = "你好,很高興認識你!";
        try {
            String encode = Base64.encodeBase64String(str.getBytes("utf-8"));
            System.out.println(encode);
            String decode = new String(Base64.decodeBase64(encode), "utf-8");
            System.out.println(decode);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String code = Base64.encodeBase64String(DigestUtils.md5(str));
        System.out.println(code);
    }
}

輸出結果分別爲

5L2g5aW977yM5b6I6auY5YW06K6k6K+G5L2g77yB
你好,很高興認識你!
L9aMgawEobXiPtOoDBXsrg==

JDK本身也自帶Base64的類,不過並不太好找
com.sun.org.apache.xerces.internal.impl.dv.util.Base64是一個,好像還有其他的。JDK1.8則有個java.util.Base64類。

JDK本身也自帶MD5摘要算法功能,java.security.MessageDigest;

public static void main(String[] args) {
        String str = "你好,很高興認識你!";
        try {
            byte[] data = str.getBytes("utf-8");
            MessageDigest md = MessageDigest.getInstance("md5");
            byte[] md5 = md.digest(data);
//          md.update(data);
//          byte[] md5 = md.digest();
            String code = Base64.encodeBase64String(md5);
            System.out.println(code);
        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException("加密失敗", e);
        }
    }

其中md.digest(data);等同於md.update(data);md.digest();其內部調用關係如下:

public byte[] digest(byte[] input) {
        update(input);
        return digest();
}

另外不能連續調用update(byte[] input),會影響算法結果,即:

{   /*錯誤*/
    md.update(data);
    md.update(data);
    md.digest();
}
{   /*錯誤*/
    md.update(data);
    md.digest(data);
}
{   /*正確*/
    md.update(data);
    md.digest();
}
{   /*正確*/
    md.update(data);
}

MessageDigest源碼中有個state屬性,update會更改其屬性,digest後會改回默認,大概是因爲這個屬性的原因吧,engineUpdate()方法的源碼沒有找到,不清楚state是否真的對其造成影響,但是多次update後得到的md5並不一樣

// The state of this digest
private static final int INITIAL = 0;
private static final int IN_PROGRESS = 1;
private int state = INITIAL;

/**
* Updates the digest using the specified byte.
*
* @param input the byte with which to update the digest.
*/
public void update(byte input) {
   engineUpdate(input);
   state = IN_PROGRESS;
}

/**
* Completes the hash computation by performing final operations
* such as padding. The digest is reset after this call is made.
*
* @return the array of bytes for the resulting hash value.
*/
public byte[] digest() {
   /* Resetting is the responsibility of implementors. */
   byte[] result = engineDigest();
   state = INITIAL;
   return result;
}
發佈了31 篇原創文章 · 獲贊 29 · 訪問量 13萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章