JAVA数据加密——MD5加密,SHA加密,BASE64解密,BASE64加密,HMAC加密

31 篇文章 3 订阅
  1. 加密工具类
package com.xinrui.flower.util;

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;

/**
 * 
 * @ClassName: EncryptUtil
 * @Description: 加密工具类
 * @author 梁志成
 * @date 2016年3月19日 下午8:40:52
 *
 */
public class EncryptUtil {
    /**
     * 基础加密组件
     */
    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());
    }

    /**
     * HMAC加密
     * 
     * @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);

    }
}

2.字节数组转字符串工具类

package com.xinrui.flower.util;

/**
 * 
 * @ClassName: BytesToStringUtil
 * @Description: 字节数组转字符串工具类
 * @author 梁志成
 * @date 2016年3月19日 下午8:42:24
 *
 */
public class BytesToStringUtil {
    public static String fromBytesToString(byte[] resultBytes) {
        StringBuilder builder = new StringBuilder();
        for (int i = 0; i < resultBytes.length; i++) {
            if (Integer.toHexString(0xFF & resultBytes[i]).length() == 1) {
                builder.append("0").append(
                        Integer.toHexString(0xFF & resultBytes[i]));
            } else {
                builder.append(Integer.toHexString(0xFF & resultBytes[i]));
            }
        }
        return builder.toString();
    }

}

3.测试

package com.xinrui.flower.test;

import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertEquals;

import java.nio.charset.StandardCharsets;

import org.junit.Test;

import com.xinrui.flower.util.BytesToStringUtil;
import com.xinrui.flower.util.EncryptUtil;

/**
 * 
 * 创建时间:2016年3月9日 下午3:09:40 项目名称:Flower
 * 
 * @author 梁志成
 * @version 1.0
 * @since JDK 1.8.0_21 文件名称:TestEncrypt.java 类说明:
 */
public class TestEncrypt {

    @Test
    public void test() throws Exception {

        String inputStr = "12345";

        System.err.println("原文:" + inputStr);

        byte[] inputData = inputStr.getBytes();

        String code = EncryptUtil.encryptBASE64(inputData);

        System.err.println("BASE64加密后:" + code);

        byte[] output = EncryptUtil.decryptBASE64(code);

        String outputStr = new String(output);

        System.err.println("BASE64解密后:" + outputStr);

        // 验证BASE64加密解密一致性
        assertEquals(inputStr, outputStr);

        // 验证MD5对于同一内容加密是否一致
        assertArrayEquals(EncryptUtil.encryptMD5(inputData),
                EncryptUtil.encryptMD5(inputData));

        // 验证SHA对于同一内容加密是否一致
        assertArrayEquals(EncryptUtil.encryptSHA(inputData),
                EncryptUtil.encryptSHA(inputData));

        String key = EncryptUtil.initMacKey();
        System.err.println("Mac密钥:" + key);

        // 验证HMAC对于同一内容,同一密钥加密是否一致
        assertArrayEquals(EncryptUtil.encryptHMAC(inputData, key),
                EncryptUtil.encryptHMAC(inputData, key));

        String p = "12345";
        // 统一不同开发环境下的字符编码问题
        String md5 = BytesToStringUtil.fromBytesToString( EncryptUtil
                .encryptMD5( p.getBytes( StandardCharsets.UTF_8 ) ) );

        String sha = BytesToStringUtil.fromBytesToString( EncryptUtil
                .encryptSHA( p.getBytes( StandardCharsets.UTF_8 ) ) );

        String hmac = BytesToStringUtil.fromBytesToString( EncryptUtil
                .encryptHMAC( p.getBytes( StandardCharsets.UTF_8 ), p ) );

        String hmac1 = BytesToStringUtil.fromBytesToString( EncryptUtil
                .encryptHMAC( p.getBytes( ), p ) );

        System.err.println( "MD5:" + md5 );
        System.err.println( "SHA:" + sha );
        System.err.println( "HMAC:" + hmac );
        System.err.println( "HMAC1:" + hmac1 );

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

两只橙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值