JAVA单向加密(MD5,SHA,MAC)

public class MyEncrypt {
    /** *//** MD5 加密 */
    public static byte[] encryptMD5(byte[] data) throws Exception {
        MessageDigest md5 = MessageDigest.getInstance("MD5");
        md5.update(data);
        return md5.digest();
    }
    /** *//** SHA 加密 */
    public static byte[] encryptSHA(byte[] data) throws Exception {
        MessageDigest sha = MessageDigest.getInstance("SHA");
        sha.update(data);
        return sha.digest();
    }
    /** *//** 取得HMAC密钥 */
    public static String getMacKey() throws Exception {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("HmacMD5");
        SecretKey secretKey = keyGenerator.generateKey();
        return new BASE64Encoder().encode(secretKey.getEncoded());
    }
    /** *//** 执行加密 */
    public static byte[] encryptHMAC(byte[] data, String key) throws Exception {
        byte[] bkey = new BASE64Decoder().decodeBuffer(key);
        SecretKey secretKey = new SecretKeySpec(bkey, "HmacMD5");
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        return mac.doFinal(data);
    }
    private static String toHex(byte[] buffer) {
        StringBuffer sb = new StringBuffer(buffer.length * 3);
        for (int i = 0; i < buffer.length; i++) {
            sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
        }
        return sb.toString();
    }
    public static void main(String[] args) {
        String msg = "生活真好^_^";
        byte[] data = msg.getBytes();
        try {
            System.out.println("msg:" + msg);
            System.out.println("md5:" + toHex(encryptMD5(data)));
            System.out.println("sha:" + toHex(encryptSHA(data)));
            String key = getMacKey();
            System.out.println("mac key:" + key);
            System.out.println("mac:" + toHex(encryptHMAC(data, key)));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行效果如下:

msg:生活真好^_^
md5:e0649dfaef57789734e920c7ecb9c4ea
sha:a4bd855836de26b2323778b797629fed4416f12f
mac key:zBPe28oho2H84+Mg8mF4abpd0MQvdjgqgFdX4hmUQQbOGnX1aFq/oQnogsHVIczgx1AZ1s2/ncPz
tBQIGLZUnw==
mac:87f4140161ad43797059e85dd9962897

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值