Example usage for javax.crypto Mac getInstance

List of usage examples for javax.crypto Mac getInstance

Introduction

In this page you can find the example usage for javax.crypto Mac getInstance.

Prototype

public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Mac object that implements the specified MAC algorithm.

Usage

From source file:com.khipu.lib.java.KhipuService.java

public static String HmacSHA256(String secret, String data) {
    try {//  ww  w. ja v a 2  s. co  m
        SecretKeySpec secretKeySpec = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(secretKeySpec);
        byte[] digest = mac.doFinal(data.getBytes("UTF-8"));
        return byteArrayToString(digest);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Invalid key exception while converting to HMac SHA256");
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Algorithm not supported");
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException("Encoding not supported");
    }
}

From source file:com.amazonaws.tvm.Utilities.java

public static String sign(String content, String key) {
    try {/*from w  ww .  j a v a 2s. c  o m*/
        byte[] data = content.getBytes(Constants.ENCODING_FORMAT);
        Mac mac = Mac.getInstance(Constants.SIGNATURE_METHOD);
        mac.init(new SecretKeySpec(key.getBytes(Constants.ENCODING_FORMAT), Constants.SIGNATURE_METHOD));
        char[] signature = Hex.encodeHex(mac.doFinal(data));
        return new String(signature);
    } catch (Exception exception) {
        log.log(Level.SEVERE, "Exception during sign", exception);
    }
    return null;
}

From source file:com.eugene.fithealthmaingit.FatSecretSearchAndGet.FatSecretGetMethod.java

private static String sign(String method, String uri, String[] params) {
    String[] p = { method, Uri.encode(uri), Uri.encode(paramify(params)) };
    String s = join(p, "&");
    SecretKey sk = new SecretKeySpec(Globals.APP_SECRET.getBytes(), Globals.HMAC_SHA1_ALGORITHM);
    try {/* www  .j  a v  a 2 s.  c om*/
        Mac m = Mac.getInstance(Globals.HMAC_SHA1_ALGORITHM);
        m.init(sk);
        return Uri.encode(new String(Base64.encode(m.doFinal(s.getBytes()), Base64.DEFAULT)).trim());
    } catch (java.security.NoSuchAlgorithmException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    } catch (java.security.InvalidKeyException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    }
}

From source file:org.sentilo.common.rest.hmac.HMACBuilder.java

private static String calculateHMAC(final String secret, final String data) throws GeneralSecurityException {
    final SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), MAC_ALGORITHM);

    final Mac mac = Mac.getInstance(MAC_ALGORITHM);
    mac.init(signingKey);// ww w  . j a v  a  2 s  . c o  m

    final byte[] rawHmac = mac.doFinal(data.getBytes());
    return new String(Base64.encodeBase64(rawHmac));
}

From source file:Models.Geographic.Repository.RepositoryGoogle.java

/**
 * Create a string URL with the corresponding signature code and client id.
 * @param path/*from  w  w w .jav  a  2 s .  com*/
 * @param query
 * @return the specified String URL
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws URISyntaxException
 */
private static String signRequest(String path, String query) throws NoSuchAlgorithmException,
        InvalidKeyException, UnsupportedEncodingException, URISyntaxException, IOException {
    if (RepositoryGoogle.mac == null) {
        // key
        byte[] key = Base64
                .decode(Configuration.getParameter("geocoding_google_key").replace('-', '+').replace('_', '/'));
        // Get an HMAC-SHA1 signing key from the raw key bytes
        SecretKeySpec sha1Key = new SecretKeySpec(key, "HmacSHA1");
        // Get an HMAC-SHA1 Mac instance and initialize it with the HMAC-SHA1

        RepositoryGoogle.mac = Mac.getInstance("HmacSHA1");
        RepositoryGoogle.mac.init(sha1Key);
    }
    // Retrieve the proper URL components to sign
    String resource = path + '?' + query + "&client=" + Configuration.getParameter("geocoding_google_client");
    // compute the binary signature for the request
    byte[] sigBytes = RepositoryGoogle.mac.doFinal(resource.getBytes());
    // base 64 encode the binary signature
    String signature = Base64.encodeBytes(sigBytes);
    // convert the signature to 'web safe' base 64
    signature = signature.replace('+', '-').replace('/', '_');
    return resource + "&signature=" + signature;
}

From source file:com.twilio.sdk.TwilioUtils.java

public boolean validateRequest(String expectedSignature, String url, Map<String, String> params) {

    SecretKeySpec signingKey = new SecretKeySpec(this.authToken.getBytes(), "HmacSHA1");

    try {//  w  w  w  . j  av a 2s .  c  om
        //initialize the hash algortihm
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        //sort the params alphabetically, and append the key and value of each to the url
        StringBuffer data = new StringBuffer(url);
        if (params != null) {
            List<String> sortedKeys = new ArrayList<String>(params.keySet());
            Collections.sort(sortedKeys);

            for (String s : sortedKeys) {
                data.append(s);
                String v = "";
                if (params.get(s) != null) {
                    v = params.get(s);
                }
                data.append(v);
            }
        }

        //compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.toString().getBytes("UTF-8"));

        //base64-encode the hmac
        String signature = new String(Base64.encodeBase64(rawHmac));

        return signature.equals(expectedSignature);
    } catch (NoSuchAlgorithmException e) {

        return false;
    } catch (InvalidKeyException e) {

        return false;
    } catch (UnsupportedEncodingException e) {
        return false;
    }
}

From source file:ninja.utils.Crypto.java

private String signHmacSha1(String value, String key) {
    try {//from   w  w  w . java  2s  .co  m

        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        // Covert array of Hex bytes to a String
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.alibaba.openapi.client.util.SignatureUtil.java

public static byte[] hmacSha1(String[] datas, SecretKeySpec signingKey) {
    Mac mac;//w w w .  ja v  a  2s .co  m
    try {
        mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    for (String data : datas) {
        mac.update(data.getBytes(CHARSET_UTF8));
    }
    return mac.doFinal();
}

From source file:au.com.borner.salesforce.client.rest.domain.LoginResponse.java

public void verify(String consumerSecret) {
    SecretKey hmacKey = null;/*from  w  w w.j  a  v  a  2s. c o  m*/
    try {
        byte[] key = consumerSecret.getBytes();
        hmacKey = new SecretKeySpec(key, ALGORITHM);
        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(hmacKey);
        byte[] digest = mac.doFinal((getIdUrl() + getIssuedAt()).getBytes());
        byte[] decode_sig = new Base64(true).decode(getSignature());
        if (!Arrays.equals(digest, decode_sig)) {
            throw new SecurityException("Signature could not be verified!");
        }
    } catch (NoSuchAlgorithmException e) {
        throw new SecurityException(String.format(
                "Algorithm not found while trying to verifying signature: algorithm=%s; message=%s", ALGORITHM,
                e.getMessage()), e);
    } catch (InvalidKeyException e) {
        throw new SecurityException(
                String.format("Invalid key encountered while trying to verify signature: key=%s; message=%s",
                        hmacKey, e.getMessage()),
                e);
    }
}

From source file:net.bryansaunders.jee6divelog.util.HashUtils.java

/**
 * Generates a HMAC-SHA1 Hash of the given String using the specified key.
 * //from  ww  w  .j a  v a2s .  c o m
 * @param stringToHash
 *            String to Hash
 * @param key
 *            Key to Sign the String with
 * @return Hashed String
 */
public static String toHmacSha1(final String stringToHash, final String key) {
    String result = "";
    try {
        // Get an hmac_sha1 key from the raw key bytes
        final byte[] keyBytes = key.getBytes();
        final SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        final Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        final byte[] rawHmac = mac.doFinal(stringToHash.getBytes());

        // Convert raw bytes to Hex
        final byte[] base64 = Base64.encodeBase64(rawHmac);

        // Covert array of Hex bytes to a String
        result = new String(base64);
    } catch (GeneralSecurityException e) {
        HashUtils.LOGGER.error("An Error Occured Generating an HMAC-SHA1 Hash!", e);
    }

    return result;
}