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.amazonaws.services.ec2.util.S3UploadPolicy.java

private String signPolicy(String awsSecretKey, String base64EncodedPolicy)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    SecretKeySpec signingKey = new SecretKeySpec(awsSecretKey.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);
    return base64Encode(mac.doFinal(base64EncodedPolicy.getBytes()));
}

From source file:com.github.tojo.session.cookies.SignatureStrategyDefaultImpl.java

@Override
public byte[] sign(byte[] sessionData) {
    assertNotNullAndEmpty(sessionData);/*www . j  ava2 s . co m*/

    byte[] signature = null;
    try {
        Mac mac = Mac.getInstance(HMAC_SHA256);
        mac.init(key);
        signature = mac.doFinal(sessionData);
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new InitializationException(e);
    }

    byte[] signedSessionData = ArrayUtils.addAll(signature, sessionData);
    return signedSessionData;
}

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 a  va2s . c  o m*/
        //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:org.kaaproject.kaa.server.verifiers.twitter.verifier.OAuthHeaderBuilder.java

private String generateSignature(String signatureBase, String accessTokenSecret)
        throws InvalidKeyException, NoSuchAlgorithmException {

    Mac mac = Mac.getInstance(ENCRYPTION_ALGO);
    mac.init(new SecretKeySpec((CONSUMER_SECRET + "&" + accessTokenSecret).getBytes(), ENCRYPTION_ALGO));
    mac.update(signatureBase.getBytes());
    byte[] res = mac.doFinal();
    String signature = new String(Base64.encodeBase64(res)).trim();

    return signature;
}

From source file:org.springframework.social.facebook.web.SignedRequestDecoder.java

private byte[] encrypt(String base, String key) {
    try {//w w  w . j  a v  a 2  s  .c  o  m
        SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), HMAC_SHA256_MAC_NAME);
        Mac mac = Mac.getInstance(HMAC_SHA256_MAC_NAME);
        mac.init(secretKeySpec);
        return mac.doFinal(base.getBytes());
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e);
    }
}

From source file:com.spartan.springmvc.bean.FacebookSignatureBean.java

/**
 * Parses and verifies a Facebook signed_request parameter. The data of the signed request is returned on successful verification.
 *
 * @param signedRequest//from   w  w  w .  ja  va 2s. co  m
 * @param appSecret
 * @return 
 * @return
 * @throws FacebookSignatureVerificationFailedException
 */
@SuppressWarnings("unchecked")
public <T> T parseSignature(String signedRequest, String appSecret, Class<T> clazz)
        throws FacebookSignatureVerificationFailedException {

    String[] parts = signedRequest.split("\\.");
    if (parts.length != 2) {
        throw new FacebookSignatureVerificationFailedException("Invalid signature format.");
    }

    String encSig = parts[0];
    String encPayload = parts[1];
    Base64 decoder = new Base64(true);

    try {
        Mac mac = Mac.getInstance("HMACSHA256");
        mac.init(new SecretKeySpec(appSecret.getBytes(), mac.getAlgorithm()));
        byte[] calcSig = mac.doFinal(encPayload.getBytes());
        byte[] decodedSig = decoder.decode(encSig);
        boolean isVerified = Arrays.equals(decodedSig, calcSig);

        if (isVerified) {
            try {
                String unsignedData = new String(decoder.decode(encPayload));
                logger.debug("unsignedData: " + unsignedData);
                ObjectMapper mapper = new ObjectMapper();
                mapper.configure(DeserializationConfig.Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
                T data = mapper.readValue(unsignedData, (Class<T>) clazz);
                return data;
            } catch (IOException e) {
                throw new FacebookSignatureVerificationFailedException(
                        "Failed to parse JSON data: " + e.getMessage(), e);
            }
        } else {
            throw new FacebookSignatureVerificationFailedException("Signatures do not match.");
        }

    } catch (NoSuchAlgorithmException e) {
        throw new FacebookSignatureVerificationFailedException(e);
    } catch (InvalidKeyException e) {
        throw new FacebookSignatureVerificationFailedException(e);
    }
}

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;
    }/*from  w  w  w.ja va 2 s  . c  o  m*/

    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:edu.wfu.inotado.helper.EncryptionHelper.java

public String calculateHMAC(String data, String key) throws java.security.SignatureException {
    String result = "";
    try {//from  ww  w.  ja  v a2s .com

        if (!StringUtils.isBlank(data) && !StringUtils.isBlank(key)) {
            // 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 String(Base64.encodeBase64(rawHmac));
        } else {
            log.warn("data or key appears to be empty!");
        }
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}

From source file:org.gtri.totp.java

/** getCode
  *   Calculates the code for the provided time and shared secret.
  *//*  w  ww.  j a v  a2  s  .  c om*/
public int getCode(String sharedSecret, long time) throws NoSuchAlgorithmException, InvalidKeyException {
    byte[] secret = new Base32().decode(sharedSecret);
    SecretKeySpec signKey = new SecretKeySpec(secret, "HmacSHA1");
    ByteBuffer buffer = ByteBuffer.allocate(8);
    buffer.putLong(time);
    byte[] timeBytes = buffer.array();
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signKey);
    byte[] hash = mac.doFinal(timeBytes);
    int offset = hash[19] & 0xf;
    long truncatedHash = hash[offset] & 0x7f;
    for (int i = 1; i < 4; i++) {
        truncatedHash <<= 8;
        truncatedHash |= hash[offset + i] & 0xff;
    }
    return (int) (truncatedHash %= 1000000);
}

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

public void verify(String consumerSecret) {
    SecretKey hmacKey = null;//from  w  ww  .  j a  v  a 2  s  . 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);
    }
}