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.ait.tooling.server.core.security.SimpleKeyStringSigningProvider.java

private final String hmac(final String text) {
    try {/*ww  w.  j a  v  a2 s  .c o  m*/
        final Mac hmac = Mac.getInstance(HMAC_ALGORITHM);

        hmac.init(m_secret);

        return Hex.encodeHexString(hmac.doFinal(text.getBytes(IHTTPConstants.CHARSET_UTF_8)));
    } catch (Exception e) {
        logger.error("hmac error", e);

        throw new IllegalArgumentException(e);
    }
}

From source file:io.pivotal.cla.security.GitHubSignature.java

private byte[] sign(String body, String token) throws NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec signingKey = new SecretKeySpec(token.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    byte[] expectedBytes = mac.doFinal(body.getBytes());
    return expectedBytes;
}

From source file:com.coinkite.CoinkiteSigningRequestInterceptor.java

public String[] createSigAndTimestamp(String url) throws NoSuchAlgorithmException, InvalidKeyException {
    String apiSecret = getApiSecret();
    SecretKeySpec signingKey = new SecretKeySpec(apiSecret.getBytes(StandardCharsets.UTF_8), HMAC_SHA512_ALG);

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

    String ts = getDateTime().format(ISO_DATE_TIME);

    byte[] bytes = mac.doFinal(getData(url, ts));
    String encoded = Hex.encodeHexString(bytes);

    return new String[] { encoded, ts };
}

From source file:ninja.utils.Crypto.java

private String signHmacSha1(String value, String key) {
    try {/*from   www . ja  va  2s  .  com*/

        // 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:org.animotron.bridge.Principal.java

private Mac getMac() {
    try {//from  w  ww.ja  v a 2s .co m
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(keySpec);
        return mac;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:com.parworks.androidlibrary.utils.HMacShaPasswordEncoder.java

public String encodePassword(String rawDataToBeEncrypted, Object salt) {
    byte[] hmacData = null;
    if (rawDataToBeEncrypted != null) {
        try {/*w w w .  jav  a 2 s.c om*/
            SecretKeySpec secretKey = new SecretKeySpec(rawDataToBeEncrypted.getBytes(ENCODING_FOR_ENCRYPTION),
                    this.algorithm);
            Mac mac = getMac();
            mac.init(secretKey);
            hmacData = mac.doFinal(salt.toString().getBytes(ENCODING_FOR_ENCRYPTION));

            if (isEncodeHashAsBas64()) {
                return new String(Base64.encode(hmacData), ENCODING_FOR_ENCRYPTION);
            } else {
                return new String(hmacData, ENCODING_FOR_ENCRYPTION);
            }

        } catch (InvalidKeyException ike) {
            throw new RuntimeException("Invalid Key while encrypting.", ike);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Unsupported Encoding while encrypting.", e);
        }
    }
    return "";

}

From source file:org.mayocat.webhooks.Webhooks.java

private String hmac(String secret, String message) throws GeneralSecurityException {
    SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA256);
    Mac mac = Mac.getInstance(HMAC_SHA256);
    mac.init(signingKey);
    byte[] rawHmac = mac.doFinal(message.getBytes(Charsets.UTF_8));
    String result = new String(Hex.encodeHexString(rawHmac));
    return result;
}

From source file:org.jets3t.service.utils.ServiceUtils.java

/**
 * Calculate the HMAC/SHA1 on a string.//from  w w  w . ja  va2 s  .  c  o m
 *
 * @param awsSecretKey
 * AWS secret key.
 * @param canonicalString
 * canonical string representing the request to sign.
 * @return Signature
 * @throws ServiceException
 */
public static String signWithHmacSha1(String awsSecretKey, String canonicalString) throws ServiceException {
    if (awsSecretKey == null) {
        if (log.isDebugEnabled()) {
            log.debug("Canonical string will not be signed, as no AWS Secret Key was provided");
        }
        return null;
    }

    // The following HMAC/SHA1 code for the signature is taken from the
    // AWS Platform's implementation of RFC2104 (amazon.webservices.common.Signature)
    //
    // Acquire an HMAC/SHA1 from the raw key bytes.
    SecretKeySpec signingKey = null;
    try {
        signingKey = new SecretKeySpec(awsSecretKey.getBytes(Constants.DEFAULT_ENCODING),
                Constants.HMAC_SHA1_ALGORITHM);
    } catch (UnsupportedEncodingException e) {
        throw new ServiceException("Unable to get bytes from secret string", e);
    }

    // Acquire the MAC instance and initialize with the signing key.
    Mac mac = null;
    try {
        mac = Mac.getInstance(Constants.HMAC_SHA1_ALGORITHM);
    } catch (NoSuchAlgorithmException e) {
        // should not happen
        throw new RuntimeException("Could not find sha1 algorithm", e);
    }
    try {
        mac.init(signingKey);
    } catch (InvalidKeyException e) {
        // also should not happen
        throw new RuntimeException("Could not initialize the MAC algorithm", e);
    }

    // Compute the HMAC on the digest, and set it.
    try {
        byte[] b64 = Base64.encodeBase64(mac.doFinal(canonicalString.getBytes(Constants.DEFAULT_ENCODING)));
        return new String(b64);
    } catch (UnsupportedEncodingException e) {
        throw new ServiceException("Unable to get bytes from canonical string", e);
    }
}

From source file:org.ksb.util.geo.G3UrlSigner.java

/**
 * Provide Google API Compatible URL signing (see https://developers.google.com/maps/documentation/business/webservices/auth)
 *
 * @param path URL path String// w w  w .j  av a 2 s.c  o m
 * @param query URL query String
 * @return String URL
 *
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 * @throws URISyntaxException
 */
public String signRequest(String path, String query)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException, URISyntaxException {

    // Retrieve the proper URL components to sign
    String resource = path + '?' + query;

    // 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 key
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(sha1Key);

    // compute the binary signature for the request
    byte[] sigBytes = mac.doFinal(resource.getBytes());

    // base 64 encode the binary signature
    //String signature = Base64.encodeBase64URLSafeString(sigBytes);
    String signature = Base64.encodeBase64String(sigBytes);

    // convert the signature to 'web safe' base 64
    signature = signature.replace('+', '-');
    signature = signature.replace('/', '_');

    return resource + "&signature=" + signature;
}

From source file:br.com.ingenieux.jenkins.plugins.codecommit.RequestSignerBase.java

protected byte[] hash(byte[] kSecret, String obj) {
    try {//from   w  w w  .j av  a 2 s .c  o m
        SecretKeySpec keySpec = new SecretKeySpec(kSecret, "HmacSHA256");

        Mac mac = Mac.getInstance("HmacSHA256");

        mac.init(keySpec);

        return mac.doFinal(obj.getBytes(DEFAULT_CHARSET));
    } catch (Exception exc) {
        throw new RuntimeException(exc);
    }
}