Java實現 Base64、MD5、MAC、HMAC加密(轉)

來源:互聯網
上載者:User

標籤:

 

開始對那些基本的加密還不怎麼熟練,然後總結了些,寫了一個測試:支援 Base64、MD5、MAC、HMAC加密,長話短說,我們都比較喜歡自己理解,看代碼吧!

採用的輸UTF-8的格式...

package codec;import java.security.MessageDigest;import javax.crypto.KeyGenerator;import javax.crypto.Mac;import javax.crypto.SecretKey;import javax.crypto.spec.SecretKeySpec;import sun.misc.BASE64Decoder;import sun.misc.BASE64Encoder;/** * 基礎加密組件 *  * @author Visec·Dana * @version 1.0 * @since 1.0 */public abstract class Coder {    public static final String KEY_SHA = "SHA";    public static final String KEY_MD5 = "MD5";    /**     * MAC演算法可選以下多種演算法     *      * <pre>     * HmacMD5      * HmacSHA1      * HmacSHA256      * HmacSHA384      * HmacSHA512     * </pre>     */    public static final String KEY_MAC = "HmacMD5";    /**     * BASE64解密     *      * @param key     * @return     * @throws Exception     */    public static byte[] decryptBASE64(String key) throws Exception {        return (new BASE64Decoder()).decodeBuffer(key);    }    /**     * BASE64加密     *      * @param key     * @return     * @throws Exception     */    public static String encryptBASE64(byte[] key) throws Exception {        return (new BASE64Encoder()).encodeBuffer(key);    }    /**     * MD5加密     *      * @param data     * @return     * @throws Exception     */    public static byte[] encryptMD5(byte[] data) throws Exception {        MessageDigest md5 = MessageDigest.getInstance(KEY_MD5);        md5.update(data);        return md5.digest();    }    /**     * SHA加密     *      * @param data     * @return     * @throws Exception     */    public static byte[] encryptSHA(byte[] data) throws Exception {        MessageDigest sha = MessageDigest.getInstance(KEY_SHA);        sha.update(data);        return sha.digest();    }    /**     * 初始化HMAC密鑰     *      * @return     * @throws Exception     */    public static String initMacKey() throws Exception {        KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);        SecretKey secretKey = keyGenerator.generateKey();        return encryptBASE64(secretKey.getEncoded());    }    /**     * MAC加密     *      * @param data     * @param key     * @return     * @throws Exception     */    public static byte[] encryptHMAC(byte[] data, String key) throws Exception {        SecretKey secretKey = new SecretKeySpec(decryptBASE64(key), KEY_MAC);        Mac mac = Mac.getInstance(secretKey.getAlgorithm());        mac.init(secretKey);        return mac.doFinal(data);    }}

 

package codec;import java.math.BigInteger;public class CoderTest {    public static void main(String[] args) throws Exception {        CoderTest.test();    }    public static void test() throws Exception {        String inputStr = "這是一些簡單的加密測試";        System.err.println("原文:" + inputStr);        byte[] inputData = inputStr.getBytes();        String code = Coder.encryptBASE64(inputData);        System.err.println("BASE64加密後:" + code);        byte[] output = Coder.decryptBASE64(code);        String outputStr = new String(output);        System.err.println("BASE64解密後:" + outputStr);        // 單元測試 Junit4[暫時不用...]        /*         * // 驗證BASE64加密解密一致性 assertEquals(inputStr, outputStr);         *          * // 驗證MD5對於同一內容加密是否一致 assertArrayEquals(Coder.encryptMD5(inputData),         * Coder .encryptMD5(inputData));         *          * // 驗證SHA對於同一內容加密是否一致 assertArrayEquals(Coder.encryptSHA(inputData),         * Coder .encryptSHA(inputData));         *          * String key = Coder.initMacKey(); System.err.println("Mac密鑰:/n" +         * key);         *          * // 驗證HMAC對於同一內容,同一祕密金鑰加密是否一致         * assertArrayEquals(Coder.encryptHMAC(inputData, key),         * Coder.encryptHMAC( inputData, key));         */        BigInteger md5 = new BigInteger(Coder.encryptMD5(inputData));        System.err.println("MD5:" + md5.toString(16));        BigInteger sha = new BigInteger(Coder.encryptSHA(inputData));        System.err.println("SHA:" + sha.toString(32));        BigInteger mac = new BigInteger(Coder.encryptHMAC(inputData, inputStr));        System.err.println("HMAC:" + mac.toString(16));    }}

Output:

原文:這是一些簡單的加密測試BASE64加密後:6L+Z5piv5LiA5Lqb566A5Y2V55qE5Yqg5a+G5rWL6K+VBASE64解密後:這是一些簡單的加密測試MD5:76757e30d128e82b14488b115794d959SHA:6f7afslor1oev1k7k40um57cscuqkjtnHMAC:782313e944a28a55fc20507e50a9d470

 

Java實現 Base64、MD5、MAC、HMAC加密(轉)

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.