0
点赞
收藏
分享

微信扫一扫

Java加密之Mac(Message Authentication Code)

千行 2021-09-29 阅读 42

Mac算法是一种对称的加密技术,消息发送者和接收者拥有相同的密钥Key。Mac算法可以看做是消息摘要基础之上又做了一层加密处理。

参考:Java之消息摘要

使用

1 创建两方都要用的密钥Key。

// 支持的KeyGenerator类型。
KeyGenerator keyGen = KeyGenerator.getInstance("DES");

2 直接生成Key,如果觉得Key的安全性不够高,还可以再加入SecureRandom参数

// 设置SecureRandom为可选步骤
// keyGen.init(SecureRandom.getInstanceStrong());

// 生成Key
SecretKey secretKey = keyGen.generateKey();

3 获取Mac实例,根据生成的Key初始化

Mac mac = Mac.getInstance("HmacSHA256");
mac.init(secretKey);

4 进行加密

String clearText = "Hello Mac 加密.";
byte[] bytes = mac.doFinal(clearText.getBytes());
// 使用Hex打印出来是为了方便查看效果
System.out.println(Hex.encodeHexString(bytes));

完整代码

    @Test
    public void macCrypto() throws NoSuchAlgorithmException, InvalidKeyException {
        // 支持的KeyGenerator类型。
        // https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#KeyGenerator
        KeyGenerator keyGen = KeyGenerator.getInstance("DES");
        keyGen.init(SecureRandom.getInstanceStrong());
        SecretKey secretKey = keyGen.generateKey();

        // 支持的Mac类型
        // https://docs.oracle.com/javase/8/docs/technotes/guides/security/StandardNames.html#Mac
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKey);

        String clearText = "Hello Mac 加密.";
        byte[] bytes = mac.doFinal(clearText.getBytes());
        System.out.println(Hex.encodeHexString(bytes));
    }

最后

个人理解:Mac算法即首先对消息进行一次加密,然后对加密之后的消息,再次进行消息摘要处理。大大的增强了消息的安全性。

参考:

举报

相关推荐

0 条评论