Java HMAC hmacDigest(String message, String secretKey, String algorithm)

Here you can find the source of hmacDigest(String message, String secretKey, String algorithm)

Description

hmac Digest

License

Apache License

Declaration

public static String hmacDigest(String message, String secretKey, String algorithm) 

Method Source Code


//package com.java2s;
/*/* ww  w.  j  a  v  a2  s.  c  o m*/
 * Copyright (C) 2015 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

public class Main {
    public static String hmacDigest(String message, String secretKey, String algorithm) {
        String digest = null;
        try {
            SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(StandardCharsets.UTF_8), algorithm);
            Mac mac = Mac.getInstance(algorithm);
            mac.init(key);

            byte[] bytes = mac.doFinal(message.getBytes(StandardCharsets.US_ASCII));

            digest = toHex(bytes);
        } catch (InvalidKeyException e) {
        } catch (NoSuchAlgorithmException e) {
        }
        return digest;
    }

    public static String toHex(byte[] bytes) {
        StringBuilder hash = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                hash.append('0');
            }
            hash.append(hex);
        }
        return hash.toString();
    }
}

Related

  1. hmac(String hash, String data, String key)
  2. hmac(String msg, String keyString)
  3. HMAC(String username, BigInteger nonce, String hashedPassword)
  4. hmac_sha(String crypto, byte[] keyBytes, byte[] text)
  5. hmac_sha(String crypto, byte[] keyBytes, byte[] text)
  6. hmacEncode(String algorithm, String input, String privateKey)
  7. hmacHex(String keyString, String message, String hmac)
  8. hmacSha(byte[] keyBytes, byte[] text)
  9. hmacSha(String crypto, String key, String value)