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:org.apache.qpid.systest.rest.SaslRestTest.java

private byte[] generateCramMD5ClientResponse(String userName, String userPassword, byte[] challengeBytes)
        throws Exception {
    String macAlgorithm = "HmacMD5";
    Mac mac = Mac.getInstance(macAlgorithm);
    mac.init(new SecretKeySpec(userPassword.getBytes("UTF-8"), macAlgorithm));
    final byte[] messageAuthenticationCode = mac.doFinal(challengeBytes);
    String responseAsString = userName + " " + toHex(messageAuthenticationCode);
    return responseAsString.getBytes();
}

From source file:org.apache.qpid.systest.rest.SaslRestTest.java

private byte[] generateCramMD5HexClientResponse(String userName, String userPassword, byte[] challengeBytes)
        throws Exception {
    String macAlgorithm = "HmacMD5";
    byte[] digestedPasswordBytes = MessageDigest.getInstance("MD5").digest(userPassword.getBytes("UTF-8"));
    byte[] hexEncodedDigestedPasswordBytes = toHex(digestedPasswordBytes).getBytes("UTF-8");
    Mac mac = Mac.getInstance(macAlgorithm);
    mac.init(new SecretKeySpec(hexEncodedDigestedPasswordBytes, macAlgorithm));
    final byte[] messageAuthenticationCode = mac.doFinal(challengeBytes);
    String responseAsString = userName + " " + toHex(messageAuthenticationCode);
    return responseAsString.getBytes();
}

From source file:com.stackmob.sdk.api.StackMobSession.java

public String generateMacToken(String method, String uri, String host, String port) {

    String ts = String.valueOf(new Date().getTime() / 1000);
    String nonce = String.format("n%d", Math.round(Math.random() * 10000));
    try {//from   www  . j  a  va  2 s. c o m
        String baseString = getNormalizedRequestString(ts, nonce, method, uri, host, port);
        Mac mac = Mac.getInstance(SIGNATURE_ALGORITHM);
        SecretKeySpec spec = new SecretKeySpec(oauth2MacKey.getBytes(), SIGNATURE_ALGORITHM);
        try {
            mac.init(spec);
        } catch (InvalidKeyException ike) {
            throw new IllegalStateException(ike);
        }
        byte[] rawMacBytes = mac.doFinal(baseString.getBytes());
        byte[] b64Bytes = Base64.encodeBase64(rawMacBytes);
        String calculatedMac = new String(b64Bytes);
        return String.format("MAC id=\"%s\",ts=\"%s\",nonce=\"%s\",mac=\"%s\"", oauth2Token, ts, nonce,
                calculatedMac);

    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("This device doesn't have SHA1");
    }
}

From source file:com.amazonaws.ipnreturnurlvalidation.SignatureUtilsForOutbound.java

private boolean validateSignatureV1(Map<String, String> parameters) throws SignatureException {

    if (this.awsSecretKey == null) {
        throw new SignatureException("Signature can not be verified without aws secret key.");
    }//from ww w . jav a 2 s.  c  om

    String stringToSign = calculateStringToSignV1(parameters);
    String signature = parameters.get(SIGNATURE_KEYNAME);

    String result;
    try {
        SecretKeySpec signingKey = new SecretKeySpec(this.awsSecretKey.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        byte[] rawHmac = mac.doFinal(stringToSign.getBytes("UTF-8"));
        result = new String(Base64.encodeBase64(rawHmac));
    } catch (NoSuchAlgorithmException e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    } catch (InvalidKeyException e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    } catch (UnsupportedEncodingException e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }

    return result.equals(signature);
}

From source file:com.cloud.bridge.util.RestAuth.java

/**
 * Create a signature by the following method:
 *     new String( Base64( SHA1( key, byte array )))
 * //  w w  w  .jav a2  s .c om
 * @param signIt    - the data to generate a keyed HMAC over
 * @param secretKey - the user's unique key for the HMAC operation
 * @return String   - the recalculated string
 * @throws SignatureException
 */
private String calculateRFC2104HMAC(String signIt, String secretKey) throws SignatureException {
    String result = null;
    try {
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac hmacSha1 = Mac.getInstance("HmacSHA1");
        hmacSha1.init(key);
        byte[] rawHmac = hmacSha1.doFinal(signIt.getBytes());
        result = new String(Base64.encodeBase64(rawHmac));
    } catch (InvalidKeyException e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request because key " + secretKey
                + " is invalid" + e.getMessage());
    } catch (Exception e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage());
    }
    return result.trim();
}

From source file:org.sharextras.webscripts.connector.HttpOAuthConnector.java

private String generateSignature(Map<String, String> authParams, Map<String, String> extraParams,
        String httpMethod, String url) {
    Map<String, String> sigParams = new HashMap<String, String>(authParams);
    if (extraParams != null)
        sigParams.putAll(extraParams);/*from   w  ww .j  a v a 2  s .  c  o m*/

    String sigMethod = sigParams.get(OAUTH_SIGNATURE_METHOD);

    if (sigMethod.equals(SIGNATURE_METHOD_PLAINTEXT)) {
        if (logger.isDebugEnabled())
            logger.debug("Generating PLAINTEXT signature");
        String tokenSecret = authParams.get(OAUTH_TOKEN_SECRET);
        StringBuffer signatureBuffer = new StringBuffer(getConsumerSecret()).append("&");
        signatureBuffer.append(tokenSecret != null ? tokenSecret : "");
        return signatureBuffer.toString();
    } else if (sigMethod.equals(SIGNATURE_METHOD_HMACSHA1)) {
        if (logger.isDebugEnabled())
            logger.debug("Generating HMAC-SHA1 signature");

        StringBuffer baseStrBuffer = new StringBuffer();

        baseStrBuffer.append(httpMethod).append("&");
        baseStrBuffer.append(encodeParameter(url));
        baseStrBuffer.append("&");

        // Add all request params to the list, combine request and auth params in a single map
        // as per http://tools.ietf.org/html/rfc5849#section-3.4.1.3.1
        // TODO Support multiple parameters with same name

        // Sort keys by param name
        // TODO Sort *after* encoding
        List<String> keys = new ArrayList<String>(sigParams.keySet());
        Collections.sort(keys);
        int i = 0;
        for (String key : keys) {
            if (!key.equals(OAUTH_REALM) && !key.equals(OAUTH_SIGNATURE) && !key.equals(OAUTH_TOKEN_SECRET)) {
                if (i > 0)
                    baseStrBuffer.append(encodeParameter("&"));
                baseStrBuffer.append(
                        encodeParameter(encodeParameter(key) + "=" + encodeParameter(sigParams.get(key))));
                i++;
            }
        }

        // Final base string
        String baseString = baseStrBuffer.toString();

        // Key to use for signing
        String tokenSecret = authParams.get(OAUTH_TOKEN_SECRET);
        String key = encodeParameter(getConsumerSecret()) + "&"
                + encodeParameter(tokenSecret != null ? tokenSecret : "");

        if (logger.isDebugEnabled())
            logger.debug("Generating signature with key '" + key + "', base string '" + baseString + "'");

        try {
            SecretKey keyStr = new SecretKeySpec(key.getBytes(), "HmacSHA1");
            Mac m = Mac.getInstance("HmacSHA1");
            m.init(keyStr);
            m.update(baseString.getBytes());
            byte[] mac = m.doFinal();
            return new String(Base64.encodeBytes(mac)).trim();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    } else {
        throw new UnsupportedOperationException();
    }
}

From source file:com.activecq.tools.auth.impl.CookieAuthenticationImpl.java

/**
 * Encrypt token data/*w w  w.j ava 2  s  . c o  m*/
 *
 * @param data
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 */
private String encryptData(String data) throws NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec keySpec = new SecretKeySpec(secret.getBytes(), encryptionType);

    Mac mac = Mac.getInstance(encryptionType);
    mac.init(keySpec);
    byte[] result = mac.doFinal(data.getBytes());
    return StringUtils.trim(new Base64(true).encodeToString(result));
}

From source file:cn.ctyun.amazonaws.auth.AbstractAWSSigner.java

protected byte[] sign(byte[] data, byte[] key, SigningAlgorithm algorithm) throws AmazonClientException {
    try {//from  www. j av a2  s.  c  o m
        Mac mac = Mac.getInstance(algorithm.toString());
        mac.init(new SecretKeySpec(key, algorithm.toString()));
        return mac.doFinal(data);
    } catch (Exception e) {
        throw new AmazonClientException("Unable to calculate a request signature: " + e.getMessage(), e);
    }
}

From source file:com.amazon.dtasdk.v2.signature.Signer.java

protected final byte[] sign(byte[] dataBytes, byte[] keyBytes) throws SigningException {
    try {/* ww w. j a  va  2 s .c o m*/
        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(new SecretKeySpec(keyBytes, ALGORITHM));
        return mac.doFinal(dataBytes);
    } catch (NoSuchAlgorithmException nsae) {
        throw new SigningException(nsae);
    } catch (InvalidKeyException ike) {
        throw new SigningException(ike);
    }
}

From source file:com.cloud.test.stress.StressTestDirectAttach.java

public static String signRequest(String request, String key) {
    try {//from   w  w  w  .jav a  2 s. c  om
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(request.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        return Base64.encodeBase64String(encryptedBytes);
    } catch (Exception ex) {
        s_logger.error("unable to sign request", ex);
    }
    return null;
}