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:org.bibsonomy.scraper.util.SignedRequestsHelper.java

/**
 * You must provide the three values below to initialize the helper.
 *  //from  w  w w.jav a 2 s . c o  m
 * @param endpoint          Destination for the requests.
 * @param awsAccessKeyId    Your AWS Access Key ID
 * @param awsSecretKey      Your AWS Secret Key
 * @throws ScrapingException 
 */
public static SignedRequestsHelper getInstance(URL url, String awsAccessKeyId, String awsSecretKey)
        throws IllegalArgumentException, UnsupportedEncodingException, NoSuchAlgorithmException,
        InvalidKeyException, ScrapingException {
    if (null == url) {
        throw new IllegalArgumentException("endpoint is null");
    }
    if (null == awsAccessKeyId || awsAccessKeyId.length() == 0) {
        throw new IllegalArgumentException("awsAccessKeyId is null or empty");
    }
    if (null == awsSecretKey || awsSecretKey.length() == 0) {
        throw new IllegalArgumentException("awsSecretKey is null or empty");
    }

    SignedRequestsHelper instance = new SignedRequestsHelper();
    instance.endpoint = getEndpointForLocale(url);
    instance.awsAccessKeyId = awsAccessKeyId;
    instance.awsSecretKey = awsSecretKey;

    byte[] secretyKeyBytes = instance.awsSecretKey.getBytes(UTF8_CHARSET);
    instance.secretKeySpec = new SecretKeySpec(secretyKeyBytes, HMAC_SHA256_ALGORITHM);
    instance.mac = Mac.getInstance(HMAC_SHA256_ALGORITHM);
    instance.mac.init(instance.secretKeySpec);

    return instance;
}

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 {//  ww  w. ja v  a 2 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:mecard.security.PAPISecurity.java

String getHash(String accessKey, String data) {
    String result = "";
    // Get an hmac_sha1 key from the raw key bytes
    byte[] secretBytes = accessKey.getBytes();
    SecretKeySpec signingKey = new SecretKeySpec(secretBytes, HMAC_SHA1_ALGORITHM);
    // Get an hmac_sha1 Mac instance and initialize with the signing key
    try {//from w ww  .  j  a  v a 2  s  .c o m
        Mac mac;
        mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes());
        // Convert raw bytes to Hex
        result = Base64.encodeBase64String(rawHmac);
    } catch (NoSuchAlgorithmException | InvalidKeyException e1) {
        System.out.println(new Date() + e1.getMessage());
        throw new ConfigurationException("The user key is invalid.");
    }
    return result;
}

From source file:com.nlworks.wowapi.util.ConnectionManager.java

private static String generateSignature(String key, String data) throws GeneralSecurityException, IOException {
    byte[] hmacData = null;
    SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(secretKey);/*from   w ww. ja  v a 2 s . co  m*/
    hmacData = mac.doFinal(data.getBytes("UTF-8"));
    return Base64.encodeBase64String(hmacData);
}

From source file:com.github.benyzhous.springboot.web.core.gateway.sign.backend.Sign.java

/**
 * HTTP??//from   w  w w.ja va2 s.  co m
 *
 * @param uri              HTTPPATH??Query
 * @param httpMethod       HTTP
 * @param headers          HTTP
 * @param paramsMap        HTTPQuery+Form?
 * @param inputStreamBytes HTTPBodyPOST/PUT????,????paramsMap
 * @return ??
 * @throws Exception
 */
public static String serviceSign(String uri, String httpMethod, Map<String, String> headers,
        Map<String, Object> paramsMap, byte[] inputStreamBytes) throws Exception {
    Map<String, String> headersToSign = buildHeadersToSign(headers);
    String bodyMd5 = buildBodyMd5(httpMethod, inputStreamBytes);
    String resourceToSign = buildResource(uri, paramsMap);
    String stringToSign = buildStringToSign(headersToSign, resourceToSign, httpMethod, bodyMd5);

    Mac hmacSha256 = Mac.getInstance(HMAC_SHA256);
    String secret = signSecretMap.get(headers.get(
            HTTP_HEADER_TO_LOWER_CASE ? CA_PROXY_SIGN_SECRET_KEY.toLowerCase() : CA_PROXY_SIGN_SECRET_KEY));

    byte[] keyBytes = secret.getBytes(ENCODING);
    hmacSha256.init(new SecretKeySpec(keyBytes, 0, keyBytes.length, HMAC_SHA256));

    return new String(Base64.encodeBase64(hmacSha256.doFinal(stringToSign.getBytes(ENCODING))), ENCODING);
}

From source file:com.jpeterson.littles3.bo.S3Authenticator.java

/**
 * Authenticate the request using the prescribed Amazon S3 authentication
 * mechanisms.//from  w w  w . j a va  2 s.c  o  m
 * 
 * @param req
 *            The original HTTP request.
 * @param s3Request
 *            The S3 specific information for authenticating the request.
 * @return The authenticated <code>CanonicalUser</code> making the request.
 * @throws RequestTimeTooSkewedException
 *             Thrown if the request timestamp is outside of the allotted
 *             timeframe.
 */
public CanonicalUser authenticate(HttpServletRequest req, S3ObjectRequest s3Request)
        throws AuthenticatorException {
    // check to see if anonymous request
    String authorization = req.getHeader(HEADER_AUTHORIZATION);

    if (authorization == null) {
        return new CanonicalUser(CanonicalUser.ID_ANONYMOUS);
    }

    // attempting to be authenticated request

    if (false) {
        // check timestamp of request
        Date timestamp = s3Request.getTimestamp();
        if (timestamp == null) {
            throw new RequestTimeTooSkewedException("No timestamp provided");
        }

        GregorianCalendar calendar = new GregorianCalendar();
        Date now = calendar.getTime();
        calendar.add(Calendar.MINUTE, 15);
        Date maximumDate = calendar.getTime();
        calendar.add(Calendar.MINUTE, -30);
        Date minimumDate = calendar.getTime();

        if (timestamp.before(minimumDate)) {
            throw new RequestTimeTooSkewedException(
                    "Timestamp [" + timestamp + "] too old. System time: " + now);
        }

        if (timestamp.after(maximumDate)) {
            throw new RequestTimeTooSkewedException(
                    "Timestamp [" + timestamp + "] too new. System time: " + now);
        }
    }

    // authenticate request
    String[] fields = authorization.split(" ");

    if (fields.length != 2) {
        throw new InvalidSecurityException("Unsupported authorization format");
    }

    if (!fields[0].equals(AUTHORIZATION_TYPE)) {
        throw new InvalidSecurityException("Unsupported authorization type: " + fields[0]);
    }

    String[] keys = fields[1].split(":");

    if (keys.length != 2) {
        throw new InvalidSecurityException("Invalid AWSAccesskeyId:Signature");
    }

    String accessKeyId = keys[0];
    String signature = keys[1];
    String secretAccessKey = userDirectory.getAwsSecretAccessKey(accessKeyId);
    String calculatedSignature;

    try {
        SecretKey key = new SecretKeySpec(secretAccessKey.getBytes(), "HmacSHA1");
        Mac m = Mac.getInstance("HmacSHA1");
        m.init(key);
        m.update(s3Request.getStringToSign().getBytes());
        byte[] mac = m.doFinal();
        calculatedSignature = new String(Base64.encodeBase64(mac));
    } catch (NoSuchAlgorithmException e) {
        throw new InvalidSecurityException(e);
    } catch (InvalidKeyException e) {
        throw new InvalidSecurityException(e);
    }

    System.out.println("-----------------");
    System.out.println("signature: " + signature);
    System.out.println("calculatedSignature: " + calculatedSignature);
    System.out.println("-----------------");

    if (calculatedSignature.equals(signature)) {
        // authenticated!
        return userDirectory.getCanonicalUser(secretAccessKey);
    } else {
        throw new SignatureDoesNotMatchException("Provided signature doesn't match calculated value");
    }
}

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);//from  www .j av  a2  s .  co  m
    byte[] rawHmac = mac.doFinal(data.getBytes());
    //String result = new String(Base64.encodeBase64(rawHmac));
    String result = bytesToHex(rawHmac);
    return result;
}

From source file:de.betterform.xml.xforms.xpath.saxon.function.Hmac.java

/**
 * Evaluate in a general context// w  ww .  j  a v  a2  s  .c  o m
 */
public Item evaluateItem(XPathContext xpathContext) throws XPathException {
    final String key = argument[0].evaluateAsString(xpathContext).toString();
    final String data = argument[1].evaluateAsString(xpathContext).toString();
    final String originalAlgorithmString = argument[2].evaluateAsString(xpathContext).toString();
    final String algorithm = "Hmac" + originalAlgorithmString.replaceAll("-", "");
    final String encoding = argument != null && argument.length >= 4
            ? argument[3].evaluateAsString(xpathContext).toString()
            : kBASE64;

    if (!kSUPPORTED_ALG.contains(originalAlgorithmString)) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(new XFormsComputeException(
                "Unsupported algorithm '" + originalAlgorithmString + "'", xformsElement.getTarget(), this));
    }

    if (!kSUPPORTED_ENCODINGS.contains(encoding)) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(new XFormsComputeException("Unsupported encoding '" + encoding + "'",
                xformsElement.getTarget(), this));
    }

    try {
        // Generate a key for the HMAC-MD5 keyed-hashing algorithm; see RFC 2104
        // In practice, you would save this key.
        SecretKey secretKey = new SecretKeySpec(key.getBytes("utf-8"), algorithm);

        // Create a MAC object using HMAC-MD5 and initialize with kesaxoniay
        Mac mac = Mac.getInstance(secretKey.getAlgorithm());
        mac.init(secretKey);
        mac.update(data.getBytes("utf-8"));

        byte[] digest = mac.doFinal();

        final BinaryEncoder encoder;
        if ("base64".equals(encoding)) {
            encoder = new Base64(digest.length, "".getBytes(), false);
        } else {
            encoder = new Hex();
        }

        return new StringValue(new String(encoder.encode(digest), "ASCII"));

    } catch (NoSuchAlgorithmException e) {
        throw new XPathException(e);
    } catch (UnsupportedEncodingException e) {
        throw new XPathException(e);
    } catch (EncoderException e) {
        XPathFunctionContext functionContext = getFunctionContext(xpathContext);
        XFormsElement xformsElement = functionContext.getXFormsElement();
        throw new XPathException(
                new XFormsComputeException("Encoder exception.", e, xformsElement.getTarget(), this));
    } catch (InvalidKeyException e) {
        throw new XPathException(e);
    }

}

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

/**
 * Helper function to build the token string
 *
 * @return Valid token string//from  w w  w  .j av  a  2 s  . c o  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:org.apache.abdera2.common.security.HashHelper.java

public static boolean hmacval(Key key, String alg, byte[] mat, byte[] dat) {
    try {//w  w  w  . jav  a2s.  c o m
        Mac mac = Mac.getInstance(alg);
        mac.init(key);
        byte[] sig = mac.doFinal(mat);
        return Arrays.equals(sig, dat);
    } catch (Throwable t) {
        throw ExceptionHelper.propogate(t);
    }
}