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:main.java.com.amazonaws.cognito.devauthsample.Utilities.java

public static String sign(String content, String key) {
    try {//from   w  w w .  j a  v a2 s  . c om
        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 e) {
        log.log(Level.SEVERE, "Exception during sign", e);
    }
    return null;
}

From source file:com.scraper.SignedRequestsHelper.java

public SignedRequestsHelper()
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    byte[] secretyKeyBytes = awsSecretKey.getBytes(UTF8_CHARSET);
    secretKeySpec = new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM);
    mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
    mac.init(secretKeySpec);/*from  ww  w .j  ava2s.  co m*/
}

From source file:Models.UserModel.java

public static String HMAC_SHA256(String email, String password) {
    try {//  w w  w . j  a v  a 2 s.  c o  m

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(password.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        String auth = Base64.encodeBase64String(sha256_HMAC.doFinal(email.getBytes()));
        return auth;
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException e) {
        System.out.println("Error HS-256");
        return "";
    }
}

From source file:com.linecorp.platform.channel.sample.BusinessConnect.java

public boolean validateBCRequest(String httpRequestBody, String channelSecret, String channelSignature) {
    if (httpRequestBody == null || channelSecret == null || channelSignature == null) {
        return false;
    }/*w  ww .j a  v  a 2  s .  com*/

    String signature;
    SecretKeySpec key = new SecretKeySpec(channelSecret.getBytes(), "HmacSHA256");
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(key);
        byte[] source = httpRequestBody.getBytes("UTF-8");
        signature = Base64.encodeBase64String(mac.doFinal(source));
    } catch (NoSuchAlgorithmException | InvalidKeyException | UnsupportedEncodingException e) {
        e.printStackTrace();
        return false;
    }
    return channelSignature.equals(signature);
}

From source file:com.microsoft.azure.iothub.auth.SignatureHelper.java

/**
 * Encrypts the signature using HMAC-SHA256.
 *
 * @param sig the unencrypted signature.
 * @param deviceKey the Base64-decoded device key.
 *
 * @return the HMAC-SHA256 encrypted signature.
 *///from   w ww  . j  a v  a  2  s .c o  m
public static byte[] encryptSignatureHmacSha256(byte[] sig, byte[] deviceKey) {
    String hmacSha256 = "HmacSHA256";

    // Codes_SRS_SIGNATUREHELPER_11_005: [The function shall use the device key as the secret for the algorithm.]
    SecretKeySpec secretKey = new SecretKeySpec(deviceKey, hmacSha256);

    byte[] encryptedSig = null;
    try {
        // Codes_SRS_SIGNATUREHELPER_11_004: [The function shall encrypt the signature using the HMAC-SHA256 algorithm.]
        Mac hMacSha256 = Mac.getInstance(hmacSha256);
        hMacSha256.init(secretKey);
        encryptedSig = hMacSha256.doFinal(sig);
    } catch (NoSuchAlgorithmException e) {
        // should never happen, since the algorithm is hard-coded.
    } catch (InvalidKeyException e) {
        // should never happen, since the input key type is hard-coded.
    }

    return encryptedSig;
}

From source file:com.konakart.bl.modules.payment.barclaycardsmartpayhosted.BarclaycardSmartPayHostedHMACTools.java

/**
 * Verify the signature//from w w w  .  jav a  2s  .  c o  m
 * @param secret
 * @param sig
 * @param signedData
 * @return true if the signature is verified
 */
public static boolean verifyBase64EncodedSignature(String secret, String sig, String signedData) {
    if (secret == null || sig == null || signedData == null)
        return false;

    SecretKey key = getMacKey(secret);
    try {
        Mac mac = Mac.getInstance(key.getAlgorithm());
        mac.init(getMacKey(secret));
        byte[] digest = mac.doFinal(signedData.getBytes("UTF8"));
        return sig.equals(new String(Base64.encodeBase64(digest), "ASCII"));
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return false;
}

From source file:lti.oauth.OAuthMessageSigner.java

/**
 * This method double encodes the parameter keys and values.
 * Thus, it expects the keys and values contained in the 'parameters' SortedMap
 * NOT to be encoded.//from   w ww  .j  a  va  2  s. c o m
 * 
 * @param secret
 * @param algorithm
 * @param method
 * @param url
 * @param parameters
 * @return oauth signature
 * @throws Exception
 */
public String sign(String secret, String algorithm, String method, String url,
        SortedMap<String, String> parameters) throws Exception {
    SecretKeySpec secretKeySpec = new SecretKeySpec((secret.concat(OAuthUtil.AMPERSAND)).getBytes(), algorithm);
    Mac mac = Mac.getInstance(secretKeySpec.getAlgorithm());
    mac.init(secretKeySpec);

    StringBuilder signatureBase = new StringBuilder(OAuthUtil.percentEncode(method));
    signatureBase.append(OAuthUtil.AMPERSAND);

    signatureBase.append(OAuthUtil.percentEncode(url));
    signatureBase.append(OAuthUtil.AMPERSAND);

    int count = 0;
    for (String key : parameters.keySet()) {
        count++;
        signatureBase.append(OAuthUtil.percentEncode(OAuthUtil.percentEncode(key)));
        signatureBase.append(URLEncoder.encode(OAuthUtil.EQUAL, OAuthUtil.ENCODING));
        signatureBase.append(OAuthUtil.percentEncode(OAuthUtil.percentEncode(parameters.get(key))));

        if (count < parameters.size()) {
            signatureBase.append(URLEncoder.encode(OAuthUtil.AMPERSAND, OAuthUtil.ENCODING));
        }
    }

    if (log.isDebugEnabled()) {
        log.debug(signatureBase.toString());
    }

    byte[] bytes = mac.doFinal(signatureBase.toString().getBytes());
    byte[] encodedMacBytes = Base64.encodeBase64(bytes);

    return new String(encodedMacBytes);
}

From source file:com.javaps.springboot.LicenseController.java

@RequestMapping(value = "/public/license", produces = "text/plain", method = RequestMethod.GET)
public String licenseIssue(@RequestParam(value = "ip") String clientIp) throws Exception {
    SecretKeySpec signingKey = new SecretKeySpec(licenseSecretKey.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);/* w  w  w . java2s. c o m*/

    byte[] rawHmac = mac.doFinal(clientIp.getBytes());
    return Base64.encodeBase64String(rawHmac);
}

From source file:com.ait.tooling.server.core.security.SimpleKeyStringSigningProvider.java

private final String hmac(final String text) {
    try {//w  ww  . j  a v a  2  s  .  c  om
        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:com.twosigma.beakerx.security.HashedMessageAuthenticationCode.java

public String signBytes(List<byte[]> msg) {
    try {/*from w w w  . java 2  s  .c o  m*/
        final Mac mac = Mac.getInstance(TYPE);
        mac.init(spec);
        msg.forEach(it -> mac.update(it));
        byte[] digest = mac.doFinal();
        return toHex(digest);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(INVALID_HMAC_EXCEPTION, e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
}