Java XML Data Type Converter calculateHMAC(final String secretKey, final String feedId)

Here you can find the source of calculateHMAC(final String secretKey, final String feedId)

Description

Calculate HMAC.

License

Open Source License

Parameter

Parameter Description
secretKey Secret key
feedId Feed Id

Exception

Parameter Description
NoSuchAlgorithmException an exception
InvalidKeyException an exception

Return

Hash key

Declaration

public static String calculateHMAC(final String secretKey, final String feedId)
        throws java.security.SignatureException, NoSuchAlgorithmException, InvalidKeyException,
        UnsupportedEncodingException 

Method Source Code


//package com.java2s;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.io.UnsupportedEncodingException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    private static final String HMAC_SHA1 = "HmacSHA1";
    public static final String UTF_8 = "UTF-8";

    /**//w  w w.j  av  a  2  s  . co  m
     * Calculate HMAC.
     *
     * @param secretKey Secret key
     * @param feedId    Feed Id
     * @return Hash key
     * @throws java.security.SignatureException
     *
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static String calculateHMAC(final String secretKey, final String feedId)
            throws java.security.SignatureException, NoSuchAlgorithmException, InvalidKeyException,
            UnsupportedEncodingException {
        SecretKeySpec signingKey = new SecretKeySpec(toSHA1(secretKey), HMAC_SHA1);
        Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
        return escapeDigest(DatatypeConverter.printBase64Binary(mac.doFinal(feedId.getBytes(UTF_8))));
    }

    private static byte[] toSHA1(final String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        return MessageDigest.getInstance("SHA-1").digest(key.getBytes(UTF_8));
    }

    private static String escapeDigest(final String digest) {
        return digest.replace("+", "-").replace("/", "_").replaceAll("^=+", "").replaceAll("=+$", "");
    }
}

Related

  1. addBasicAuthorization(String username, String password, HttpURLConnection connection)
  2. appendByteAsJavaByteInitializer(StringBuilder sb, byte b)
  3. byteArrayAsUrlString(byte[] bytes)
  4. calculateCR16(String value)
  5. compress(String string)
  6. compress(String string)
  7. convertBpmnVariableValueToXslParam(final Object bpmnVariableValue)
  8. convertToFourBytes(int numberToConvert)