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.adyen.Util.HMACValidator.java

public String calculateHMAC(String data, String key) throws java.security.SignatureException {
    try {/*from   www . j  a v a 2s  .  c  o  m*/
        byte[] rawKey = Hex.decodeHex(key.toCharArray());
        // Create an hmac_sha256 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(rawKey, HMAC_SHA256_ALGORITHM);

        // Get an hmac_sha256 Mac instance and initialize with the signing
        // key
        Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);

        mac.init(signingKey);

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

        // Base64-encode the hmac
        return new String(Base64.encodeBase64(rawHmac));

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

From source file:com.eucalyptus.auth.login.Hmacv1LoginModule.java

public String getSignature(final String queryKey, final String subject, final Hmac mac)
        throws AuthenticationException {
    SecretKeySpec signingKey = new SecretKeySpec(queryKey.getBytes(), mac.toString());
    try {//from   w w w  . j  a  v a  2s. c o  m
        Mac digest = mac.getInstance();
        digest.init(signingKey);
        byte[] rawHmac = digest.doFinal(subject.getBytes());
        return sanitize(Base64.encode(rawHmac));
    } catch (Exception e) {
        LOG.error(e, e);
        throw new AuthenticationException("Failed to compute signature");
    }
}

From source file:org.apache.abdera2.common.security.KeyBase.java

protected byte[] hmac(byte[]... mat) {
    try {/*w w w . ja v a 2s  .  co  m*/
        Mac hmac = Mac.getInstance(alg);
        hmac.init(key);
        for (byte[] m : mat)
            hmac.update(m);
        return hmac.doFinal();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:com.k42b3.aletheia.oauth.HMACSHA1.java

public String build(String baseString, String consumerSecret, String tokenSecret) {
    try {// ww  w.  j  av a2 s.com
        String key = Oauth.urlEncode(consumerSecret) + "&" + Oauth.urlEncode(tokenSecret);

        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secret = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(secret);
        byte[] result = mac.doFinal(baseString.getBytes());

        return Base64.encodeBase64String(result);
    } catch (Exception e) {
        Aletheia.handleException(e);

        return null;
    }
}

From source file:net.webpasswordsafe.server.plugin.authentication.TwoStepTOTPAuthenticator.java

private int calculateCode(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {
    byte[] data = new byte[8];
    long value = t;
    for (int i = 8; i-- > 0; value >>>= 8) {
        data[i] = (byte) value;
    }//from   w  ww .j ava  2  s.c  om
    SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signKey);
    byte[] hash = mac.doFinal(data);
    int offset = hash[20 - 1] & 0xF;
    long truncatedHash = 0;
    for (int i = 0; i < 4; ++i) {
        truncatedHash <<= 8;
        truncatedHash |= (hash[offset + i] & 0xFF);
    }
    truncatedHash &= 0x7FFFFFFF;
    truncatedHash %= 1000000;
    return (int) truncatedHash;
}

From source file:com.microsoft.azure.iot.service.auth.IotHubServiceSasToken.java

/**
 * Helper function to build the token string
 *
 * @return Valid token string/*from w ww  .jav a2  s  .  co m*/
 */
private String buildToken() {
    String targetUri;
    try {
        // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_002: [The constructor shall create a target uri from the url encoded host name)]
        targetUri = URLEncoder.encode(this.resourceUri.toLowerCase(), String.valueOf(StandardCharsets.UTF_8));
        // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_003: [The constructor shall create a string to sign by concatenating the target uri and the expiry time string (one year)]
        String toSign = targetUri + "\n" + this.expiryTime;

        // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_004: [The constructor shall create a key from the shared access key signing with HmacSHA256]
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = Base64.decodeBase64(this.keyValue.getBytes("UTF-8"));
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA256");

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

        // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_005: [The constructor shall compute the final signature by url encoding the signed key]
        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(toSign.getBytes("UTF-8"));
        // Convert raw bytes to Hex
        String signature = URLEncoder.encode(Base64.encodeBase64String(rawHmac), "UTF-8");

        // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_006: [The constructor shall concatenate the target uri, the signature, the expiry time and the key name using the format: "SharedAccessSignature sr=%s&sig=%s&se=%s&skn=%s"]
        String token = String.format(TOKEN_FORMAT, targetUri, signature, this.expiryTime, this.keyName);

        return token;
    } catch (Exception e) {
        // Codes_SRS_SERVICE_SDK_JAVA_IOTHUBSERVICESASTOKEN_12_007: [The constructor shall throw Exception if building the token failed]
        throw new RuntimeException(e);
    }
}

From source file:com.mlohr.hvvgti.ApiClient.java

private String generateSignature(JSONObject data) {
    Charset passwordEncoding = Charset.forName("UTF-8");
    String algorithm = getSignatureAlgorithm().getAlgorithmString();
    byte[] key = authKey.getBytes(passwordEncoding);
    SecretKeySpec keySpec = new SecretKeySpec(key, algorithm);
    try {/*  w w w  .  ja  va2  s  .c  om*/
        Mac mac = Mac.getInstance(algorithm);
        mac.init(keySpec);
        byte[] signature = mac.doFinal(data.toString().getBytes());
        return new String(Base64.encodeBase64(signature));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.megam.api.APIContentBuilder.java

private String calculateHMAC(String secret, String data) throws NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), "RAW");
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    byte[] rawHmac = mac.doFinal(data.getBytes());
    //String result = new String(Base64.encodeBase64(rawHmac));
    String result = bytesToHex(rawHmac);
    return result;
}

From source file:cl.whyem.testsutilityproject.otpgenerator.KeyBase.java

protected byte[] hmac(byte[]... mat) {
    try {/*from   w  ww. j  a  v a 2 s  .  c  o m*/
        Mac hmac = Mac.getInstance(alg);
        hmac.init(key);
        for (byte[] m : mat) {
            hmac.update(m);
        }
        return hmac.doFinal();
    } catch (Throwable t) {
        throw new RuntimeException(t);
    }
}

From source file:com.kolich.aws.signing.impl.KolichAwsSigner.java

@Override
public final String sign(final AwsCredentials credentials, final String input) {
    try {/*  w  w w .ja va  2 s. c  o  m*/
        final String algoName = algorithm_.toString();
        // Get a new instance of the HMAC-SHA1 algorithm.
        final Mac mac = Mac.getInstance(algoName);
        // Init it with our secret and the secret-key algorithm.
        mac.init(new SecretKeySpec(credentials.getSecretBytes(), algoName));
        // Sign the input.
        return encodeBase64ToString(mac.doFinal(getBytesUtf8(input)));
    } catch (Exception e) {
        throw new KolichAwsException(
                "Failed to sign input " + "string (algorithm=" + algorithm_ + ", input=" + input + ")", e);
    }
}