Java HMAC hmacsha256Representation(String data, String pusherApplicationSecret)

Here you can find the source of hmacsha256Representation(String data, String pusherApplicationSecret)

Description

Returns a HMAC/SHA256 representation of the given string

License

MIT License

Parameter

Parameter Description
data a parameter

Declaration

public static String hmacsha256Representation(String data, String pusherApplicationSecret) 

Method Source Code

//package com.java2s;
/**//from www.  j a  va 2 s. com
 * Static class to send messages to Pusher's REST API.
 * 
 * Please set pusherApplicationId, pusherApplicationKey, pusherApplicationSecret accordingly
 * before sending any request. 
 * 
 * @author Stephan Scheuermann
 * Copyright 2010. Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php
 */

import java.io.UnsupportedEncodingException;
import java.math.BigInteger;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;

public class Main {
    /**
     * Returns a HMAC/SHA256 representation of the given string
     * @param data
     * @return
     */
    public static String hmacsha256Representation(String data, String pusherApplicationSecret) {
        try {
            // Create the HMAC/SHA256 key from application secret
            final SecretKeySpec signingKey = new SecretKeySpec(pusherApplicationSecret.getBytes(), "HmacSHA256");

            // Create the message authentication code (MAC)
            final Mac mac = Mac.getInstance("HmacSHA256");
            mac.init(signingKey);

            //Process and return data
            byte[] digest = mac.doFinal(data.getBytes("UTF-8"));
            digest = mac.doFinal(data.getBytes());
            //Convert to string
            BigInteger bigInteger = new BigInteger(1, digest);
            return String.format("%0" + (digest.length << 1) + "x", bigInteger);
        } catch (NoSuchAlgorithmException nsae) {
            //We should never come here, because GAE has HMac SHA256
            throw new RuntimeException("No HMac SHA256 algorithm");
        } catch (UnsupportedEncodingException e) {
            //We should never come here, because UTF-8 should be available
            throw new RuntimeException("No UTF-8");
        } catch (InvalidKeyException e) {
            throw new RuntimeException("Invalid key exception while converting to HMac SHA256");
        }
    }
}

Related

  1. hmacSha1(String data, String key)
  2. hmacSha1(String input, byte[] keyBytes)
  3. hmacSha1(String input, byte[] keyBytes)
  4. hmacSHA256(byte[] secret, byte[] data)
  5. hmacSha256(String keyHex, String stringData)
  6. hmacSha512(byte[] key, byte[] message)
  7. hmacSign(String aValue, String aKey)
  8. hmacSign(String skey, String data)