Example usage for javax.crypto Mac init

List of usage examples for javax.crypto Mac init

Introduction

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

Prototype

public final void init(Key key) throws InvalidKeyException 

Source Link

Document

Initializes this Mac object with the given key.

Usage

From source file:com.runtimecollective.influence.metrics.Alexa.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 * /*from ww  w  .jav a2s.  c o m*/
 * @param data
 *     The data to be signed.
 * @param key
 *     The signing key.
 * @return
 *     The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws
 *     java.security.SignatureException when signature generation fails
 */
private String calculateRFC2104HMAC(String data, String key) throws java.security.SignatureException {
    String result;
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);

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

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

        // base64-encode the hmac
        result = new sun.misc.BASE64Encoder().encode(rawHmac);
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}

From source file:com.diversityarrays.dalclient.DalUtil.java

/**
 * Calculate an RFC 2104 compliant HMAC signature.
 * @param key is the signing key//from  w  ww . j  a  va2s.  c  o m
 * @param data is the data to be signed
 * @return the base64-encoded signature as a String
 */
public static String computeHmacSHA1(String key, String data) {
    try {
        byte[] keyBytes = key.getBytes(cryptCharsetName);
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, ALGORITHM_HMAC_SHA1);

        Mac mac = Mac.getInstance(ALGORITHM_HMAC_SHA1);
        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(data.getBytes(cryptCharsetName));

        byte[] hexBytes = new Hex().encode(rawHmac);

        return new String(hexBytes, cryptCharsetName);

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:fitmon.WorkoutApi.java

public StringBuilder apiGetInfo()
        throws ClientProtocolException, IOException, NoSuchAlgorithmException, InvalidKeyException {
    HttpClient client = new DefaultHttpClient();
    //HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api&"
    //                    + "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&oauth_signature_method=HMAC-SHA1&oauth_timestamp=1408230438&"
    //                     + "oauth_nonce=abc&oauth_version=1.0&method=food.get&food_id=4384");
    //HttpResponse response = client.execute(request);
    //BufferedReader rd = new BufferedReader (new InputStreamReader(response.getEntity().getContent()));
    //StringBuilder sb = new StringBuilder();
    String base = URLEncoder.encode("GET") + "&";
    base += "http%3A%2F%2Fplatform.fatsecret.com%2Frest%2Fserver.api&";

    String params;/*  w ww  .  j  ava 2s  .  c  o  m*/

    params = "format=json&";
    params += "method=exercises.get&";
    params += "oauth_consumer_key=5f2d9f7c250c4d75b9807a4f969363a7&"; // ur consumer key 
    params += "oauth_nonce=123&";
    params += "oauth_signature_method=HMAC-SHA1&";
    Date date = new java.util.Date();
    Timestamp ts = new Timestamp(date.getTime());
    params += "oauth_timestamp=" + ts.getTime() + "&";
    params += "oauth_version=1.0";
    //params += "search_expression=apple"; 

    String params2 = URLEncoder.encode(params);
    base += params2;
    //System.out.println(base);
    String line = "";

    String secret = "76172de2330a4e55b90cbd2eb44f8c63&";
    Mac sha256_HMAC = Mac.getInstance("HMACSHA1");
    SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HMACSHA1");
    sha256_HMAC.init(secret_key);
    String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(base.getBytes()));

    //$url = "http://platform.fatsecret.com/rest/server.api?".$params."&oauth_signature=".rawurlencode($sig); 
    HttpGet request = new HttpGet("http://platform.fatsecret.com/rest/server.api?" + params
            + "&oauth_signature=" + URLEncoder.encode(hash));
    HttpResponse response = client.execute(request);
    BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
    StringBuilder sb = new StringBuilder();

    //$url = "http://platform.fatsecret.com/rest/server.api?"+params+"&oauth_signature="+URLEncoder.encode(hash);
    //return url;

    while ((line = rd.readLine()) != null) {
        sb.append(line);
        //System.out.println(line);
    }
    //System.out.println(sb.toString());
    return sb;
}

From source file:fi.okm.mpass.shibboleth.authn.impl.BaseInitializeWilmaContextTest.java

/**
 * Validates the checksum of the given url. 
 * @param url The source for the checksum validation.
 * @param checksum The checksum.// www . j  a va  2s  .co m
 * @return true if valid, false otherwise.
 * @throws Exception
 */
protected boolean validateChecksum(final String url, final String checksum) throws Exception {
    SecretKey macKey = new SecretKeySpec(sharedSecret.getBytes("UTF-8"),
            WilmaAuthenticationContext.MAC_ALGORITHM);
    Mac mac = Mac.getInstance(WilmaAuthenticationContext.MAC_ALGORITHM);
    mac.init(macKey);
    byte[] digest = mac.doFinal(url.getBytes("UTF-8"));
    return Arrays.equals(DatatypeConverter.parseHexBinary(checksum), digest);
}

From source file:com.appdynamics.cloudstack.CloudStackApiClient.java

public String calculateRFC2104HMAC(String data, String key) throws Exception {
    String result;//  w w  w .  j  a v a  2  s  .co m
    try {

        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "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(data.getBytes());

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

        return result.trim();
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }

    // return encodeUrl(result);
}

From source file:org.cesecore.audit.impl.queued.entity.HmacLogManagementDataTest.java

@Test
public void test01LoadTokenConfigProps() throws Exception {

    AuditLogCryptoTokenConfigData tokenConfig = hmac.getTokenConfig();
    CryptoToken token = CryptoTokenFactory.createCryptoToken(tokenConfig.getClassname(),
            tokenConfig.getProperties(), tokenConfig.getTokenData(), 1);

    token.activate(/*from  w  w  w  . j  a  v a  2  s.c om*/
            ((String) tokenConfig.getProperties().get(CryptoToken.AUTOACTIVATE_PIN_PROPERTY)).toCharArray());
    Key hMacKey = token.getKey(keyAlias);

    Mac hMac = Mac.getInstance(hmac.getAlgorithm(), token.getEncProviderName());
    hMac.init(hMacKey);
    hMac.update(dataToBeSigned.getBytes());
    byte[] signedData = hMac.doFinal();

    assertTrue(ArrayUtils.isEquals(signedData, signed));

}

From source file:net.fenyo.mail4hotspot.web.GMailOAuthStep1Servlet.java

private String hmac(final String key, final String message)
        throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
    final Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1"));
    return org.apache.commons.codec.binary.Base64.encodeBase64String(mac.doFinal(message.getBytes("UTF-8")));
}

From source file:com.zimbra.common.auth.twofactor.TOTPAuthenticator.java

private byte[] calculateHash(byte[] K, byte[] C) throws ServiceException {
    try {//  www  . j  a  va 2  s .c o m
        Mac mac = Mac.getInstance(config.getHashAlgorithm().getLabel());
        mac.init(new SecretKeySpec(K, config.getHashAlgorithm().getLabel()));
        byte[] hash = mac.doFinal(C);
        return hash;
    } catch (NoSuchAlgorithmException e) {
        throw ServiceException.FAILURE("no such algorithm", e);
    } catch (InvalidKeyException e) {
        throw ServiceException.FAILURE("invalid key", e);
    }
}

From source file:net.shopxx.plugin.yeepayPayment.YeepayPaymentPlugin.java

private String hmacDigest(String value, String key) {
    try {//ww  w  .j  a va2 s  .c  o  m
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(new SecretKeySpec(key.getBytes("UTF-8"), "HmacMD5"));
        byte[] bytes = mac.doFinal(value.getBytes("UTF-8"));

        StringBuilder digest = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                digest.append("0");
            }
            digest.append(hex);
        }
        return digest.toString();
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:fr.Axeldu18.PterodactylAPI.PterodactylAPI.java

public String hmac(String url) throws Exception {
    try {/*  w  w  w .ja v  a  2s.com*/
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(url.getBytes()));
        return hash;
    } catch (Exception e) {
        log(Level.SEVERE, " HMAC Error");
        return null;
    }
}