Hash值生成java算法

时间:2025-03-10 07:20:41
  • import ;
  • import ;
  • import ;
  • import .binary.Base64;
  • import .binary.Hex;
  • import ;
  • import ;
  • import ;
  • import ;
  • public class HMACUtils {
  • /**
  • * 默认的算法
  • */
  • private static final String DE_KEY_MAC = "HmacMD5";
  • /**
  • * 默认的字符集
  • */
  • private static final Charset DE_CHARSET = StandardCharsets.UTF_8;
  • /**
  • * 使用默认的算法(HmacMD5) 得到hmac 16进制字符串
  • * @param inputStr 需要加密的串
  • * @param key key
  • * @return 16进制字符串
  • * @throws Exception
  • */
  • public static String encryptHMAC(String inputStr, String key){
  • try{
  • return encryptHMAC(inputStr, key, DE_KEY_MAC);
  • }catch (Exception e){
  • ();
  • }
  • return null;
  • }
  • /**
  • * 使用指定的算法得到hmac 16进制字符串
  • * @param inputStr 需要加密的串
  • * @param key key
  • * @param keyMac hmac算法
  • * @return 16进制字符串
  • * @throws Exception
  • */
  • public static String encryptHMAC(String inputStr, String key, String keyMac) throws Exception {
  • // return (encryptHMAC((DE_CHARSET), key, keyMac));
  • return Base64.encodeBase64String(encryptHMAC((DE_CHARSET), key, keyMac));
  • }
  • public static String MD5Encode(String origin){
  • try{
  • MessageDigest md = ("MD5");
  • // return (((DE_CHARSET)));
  • return Base64.encodeBase64String(((DE_CHARSET)));
  • }catch(NoSuchAlgorithmException ex){
  • ();
  • }
  • return null;
  • }
  • private static byte[] encryptHMAC(byte[] data, String key, String keyMac) throws Exception {
  • SecretKey secretKey = new SecretKeySpec(key.getBytes(DE_CHARSET), keyMac);
  • Mac mac = (());
  • (secretKey);
  • return (data);
  • }
  • public static void main(String[] args) throws Exception{
  • ("HMACStr:\n" + encryptHMAC("a", "hank"));
  • }
  • }