美文网首页java 设计框架建设收集
Java加密之Mac(Message Authenticatio

Java加密之Mac(Message Authenticatio

作者: Real_man | 来源:发表于2019-11-23 14:36 被阅读0次

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

    参考:Java之消息摘要

    The Mac Class

    使用

    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算法即首先对消息进行一次加密,然后对加密之后的消息,再次进行消息摘要处理。大大的增强了消息的安全性。

    参考:

    相关文章

      网友评论

        本文标题:Java加密之Mac(Message Authenticatio

        本文链接:https://www.haomeiwen.com/subject/cyjhwctx.html