zoukankan      html  css  js  c++  java
  • java HmacMd5 Hmacsha1 hmacsha256加密

    package com.demo;
    import javax.crypto.KeyGenerator;
    import javax.crypto.Mac;
    import javax.crypto.spec.SecretKeySpec;
    import java.math.BigInteger;
    import java.security.InvalidKeyException;
    import java.security.NoSuchAlgorithmException;
    import java.util.Base64;
    
    public class demoHmacMd5 {
        public static final String KEY_MAC = "HmacMD5";// "Hmacsha1"  ||  "Hmacsha256"
        public static void main(String[] args)  {
            String key=initKey();
            System.out.println(key);
            System.out.println(encryption("hello",key));
        }
        //初始化秘钥
       static String initKey(){
            try{
                KeyGenerator keyGenerator = KeyGenerator.getInstance(KEY_MAC);
                return Base64.getEncoder().encodeToString(keyGenerator.generateKey().getEncoded());//秘钥使用base64加密存储
            }catch (NoSuchAlgorithmException e) {
                e.printStackTrace();
            }
            return null;
        }
        //数据进行加密
        static  String encryption(String content,String key){
            try{
              SecretKeySpec  secretKey =new SecretKeySpec(Base64.getDecoder().decode(key),KEY_MAC);
                Mac mac=Mac.getInstance(KEY_MAC);
                mac.init(secretKey);
                mac.update(content.getBytes());
                return toHex(mac.doFinal()); //加密结果使用16进制字符串进行保存
            }catch (NoSuchAlgorithmException | InvalidKeyException ex){
                System.out.println(ex.getMessage());
            }
            return null;
        }
        //转16进制字符串
        static String toHex(byte[] bytes) {
            BigInteger bi = new BigInteger(1, bytes);
            return String.format("%0" + (bytes.length << 1) + "X", bi);
        }
    }
  • 相关阅读:
    选校总结
    位运算
    剑指
    机器学习之梯度下降法
    leetcode1348 Tweet Counts Per Frequency
    UVA10308 Roads in the North 树的最长路径
    负数的处理POJ1179Polygon
    Roadblocks
    Bus Stop
    蒜头君的城堡之旅(动态规划)
  • 原文地址:https://www.cnblogs.com/mrma/p/12830106.html
Copyright © 2011-2022 走看看