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);
    }
}

 

posted on 2020-05-05 11:59  mrma1989  阅读(921)  评论(0编辑  收藏  举报