Example usage for javax.crypto Mac doFinal

List of usage examples for javax.crypto Mac doFinal

Introduction

In this page you can find the example usage for javax.crypto Mac doFinal.

Prototype

public final byte[] doFinal(byte[] input) throws IllegalStateException 

Source Link

Document

Processes the given array of bytes and finishes the MAC operation.

Usage

From source file:com.MainFiles.Functions.java

public String encryptPin(String username, String plainPassword, String strKey) {
    String plainString = username + plainPassword;
    byte[] byteArray = Base64.encodeBase64(plainString.getBytes());
    String encodedString = new String(byteArray);
    String HMAC_SHA512 = "HmacSHA512";
    String DEFAULT_ENCODING = "UTF-8";
    byte[] result = null;

    //Hash Algorithm
    try {//  w w  w  .java2 s .  c  o m
        SecretKeySpec keySpec = new SecretKeySpec(strKey.getBytes(DEFAULT_ENCODING), HMAC_SHA512);
        Mac mac = Mac.getInstance(HMAC_SHA512);
        mac.init(keySpec);
        result = mac.doFinal(encodedString.getBytes(DEFAULT_ENCODING));

    } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException ex) {
        this.log("INFO strResponseFooter() ::" + ex.getMessage() + "\n" + this.StackTraceWriter(ex), "ERROR");
    }

    StringBuilder sb = new StringBuilder();
    for (byte b : result) {
        sb.append(String.format("%02X", b));
    }

    return sb.toString();
}

From source file:API.amazon.mws.feeds.service.MarketplaceWebServiceClient.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 *
 *///  w  w  w  .j  a  v  a 2s .c  o  m
private String sign(String data, String key, String algorithm) throws SignatureException {
    byte[] signature;
    try {
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key.getBytes(), algorithm));
        signature = Base64.encodeBase64(mac.doFinal(data.getBytes(DEFAULT_ENCODING)));
    } catch (Exception e) {
        throw new SignatureException("Failed to generate signature: " + e.getMessage(), e);
    }

    return new String(signature);
}

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Creates response for the second step of the SRP authentication.
 *
 * @param challenge REQUIRED: {@link InitiateAuthResult} contains next
 *            challenge./*ww  w.j  a  v a 2  s  .com*/
 * @param authenticationDetails REQUIRED: {@link AuthenticationDetails} user
 *            authentication details.
 * @param authenticationHelper REQUIRED: Internal helper class for SRP
 *            calculations.
 * @return {@link RespondToAuthChallengeRequest}.
 */
private RespondToAuthChallengeRequest userSrpAuthRequest(InitiateAuthResult challenge,
        AuthenticationDetails authenticationDetails, AuthenticationHelper authenticationHelper) {
    final String userIdForSRP = challenge.getChallengeParameters()
            .get(CognitoServiceConstants.CHLG_PARAM_USER_ID_FOR_SRP);
    this.usernameInternal = challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_USERNAME);
    this.deviceKey = CognitoDeviceHelper.getDeviceKey(usernameInternal, pool.getUserPoolId(), context);
    secretHash = CognitoSecretHash.getSecretHash(usernameInternal, clientId, clientSecret);

    final BigInteger srpB = new BigInteger(challenge.getChallengeParameters().get("SRP_B"), 16);
    if (srpB.mod(AuthenticationHelper.N).equals(BigInteger.ZERO)) {
        throw new CognitoInternalErrorException("SRP error, B cannot be zero");
    }

    final BigInteger salt = new BigInteger(challenge.getChallengeParameters().get("SALT"), 16);
    final byte[] key = authenticationHelper.getPasswordAuthenticationKey(userIdForSRP,
            authenticationDetails.getPassword(), srpB, salt);

    final Date timestamp = new Date();
    byte[] hmac;
    String dateString;
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        final SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256");
        mac.init(keySpec);
        mac.update(pool.getUserPoolId().split("_", 2)[1].getBytes(StringUtils.UTF8));
        mac.update(userIdForSRP.getBytes(StringUtils.UTF8));
        final byte[] secretBlock = Base64.decode(challenge.getChallengeParameters().get("SECRET_BLOCK"));
        mac.update(secretBlock);

        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        dateString = simpleDateFormat.format(timestamp);
        final byte[] dateBytes = dateString.getBytes(StringUtils.UTF8);

        hmac = mac.doFinal(dateBytes);
    } catch (final Exception e) {
        throw new CognitoInternalErrorException("SRP error", e);
    }

    final Map<String, String> srpAuthResponses = new HashMap<String, String>();
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SECRET_BLOCK,
            challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK));
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SIGNATURE,
            new String(Base64.encode(hmac), StringUtils.UTF8));
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_TIMESTAMP, dateString);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_USERNAME, usernameInternal);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_DEVICE_KEY, deviceKey);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_SECRET_HASH, secretHash);

    final RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest();
    authChallengeRequest.setChallengeName(challenge.getChallengeName());
    authChallengeRequest.setClientId(clientId);
    authChallengeRequest.setSession(challenge.getSession());
    authChallengeRequest.setChallengeResponses(srpAuthResponses);

    return authChallengeRequest;
}

From source file:com.amazonaws.mobileconnectors.cognitoidentityprovider.CognitoUser.java

/**
 * Creates request for device SRP verification.
 *
 * @param challenge REQUIRED: {@link RespondToAuthChallengeResult} contains
 *            next challenge./*from www. j a  v  a2  s.c  o m*/
 * @param deviceSecret REQUIRED: Device secret verifier.
 * @param authenticationHelper REQUIRED: Internal helper class for SRP
 *            calculations.
 * @param deviceGroupKey the device group key
 * @return {@link RespondToAuthChallengeRequest}.
 */
public RespondToAuthChallengeRequest deviceSrpAuthRequest(RespondToAuthChallengeResult challenge,
        String deviceSecret, String deviceGroupKey, AuthenticationHelper authenticationHelper) {
    this.usernameInternal = challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_USERNAME);

    final BigInteger srpB = new BigInteger(challenge.getChallengeParameters().get("SRP_B"), 16);
    if (srpB.mod(AuthenticationHelper.N).equals(BigInteger.ZERO)) {
        throw new CognitoInternalErrorException("SRP error, B cannot be zero");
    }

    final BigInteger salt = new BigInteger(challenge.getChallengeParameters().get("SALT"), 16);
    final byte[] key = authenticationHelper.getPasswordAuthenticationKey(deviceKey, deviceSecret, srpB, salt);

    final Date timestamp = new Date();
    byte[] hmac;
    String dateString;
    try {
        final Mac mac = Mac.getInstance("HmacSHA256");
        final SecretKeySpec keySpec = new SecretKeySpec(key, "HmacSHA256");
        mac.init(keySpec);
        mac.update(deviceGroupKey.getBytes(StringUtils.UTF8));
        mac.update(deviceKey.getBytes(StringUtils.UTF8));
        final byte[] secretBlock = Base64.decode(
                challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK));
        mac.update(secretBlock);

        final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("EEE MMM d HH:mm:ss z yyyy", Locale.US);
        simpleDateFormat.setTimeZone(TimeZone.getTimeZone("UTC"));
        dateString = simpleDateFormat.format(timestamp);
        final byte[] dateBytes = dateString.getBytes(StringUtils.UTF8);

        hmac = mac.doFinal(dateBytes);
    } catch (final Exception e) {
        throw new CognitoInternalErrorException("SRP error", e);
    }

    secretHash = CognitoSecretHash.getSecretHash(usernameInternal, clientId, clientSecret);

    final Map<String, String> srpAuthResponses = new HashMap<String, String>();
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SECRET_BLOCK,
            challenge.getChallengeParameters().get(CognitoServiceConstants.CHLG_PARAM_SECRET_BLOCK));
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_PASSWORD_CLAIM_SIGNATURE,
            new String(Base64.encode(hmac), StringUtils.UTF8));
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_TIMESTAMP, dateString);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_USERNAME, usernameInternal);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_DEVICE_KEY, deviceKey);
    srpAuthResponses.put(CognitoServiceConstants.CHLG_RESP_SECRET_HASH, secretHash);

    final RespondToAuthChallengeRequest authChallengeRequest = new RespondToAuthChallengeRequest();
    authChallengeRequest.setChallengeName(challenge.getChallengeName());
    authChallengeRequest.setClientId(clientId);
    authChallengeRequest.setSession(challenge.getSession());
    authChallengeRequest.setChallengeResponses(srpAuthResponses);

    return authChallengeRequest;
}

From source file:de.andreas_rueckert.trade.site.cryptsy.client.CryptsyClient.java

/**
 * Execute a authenticated query on cryptsy.
 *
 * @param method      The method to execute.
 * @param arguments   The arguments to pass to the server.
 * @param userAccount The user account on the exchange, or null if the default account should be used.
 * @return The returned data as JSON or null, if the request failed.
 *//*w  w  w.j a  va 2  s  . c om*/
private final JSON authenticatedHTTPRequest(String method, Map<String, String> arguments,
        TradeSiteUserAccount userAccount) {

    HashMap<String, String> headerLines = new HashMap<String, String>(); // Create a new map for the header lines.
    Mac mac;
    SecretKeySpec key = null;
    String accountKey = null; // The used key of the account.
    String accountSecret = null; // The used secret of the account.

    // Try to get an account key and secret for the request.
    if (userAccount != null) {

        accountKey = userAccount.getAPIkey();
        accountSecret = userAccount.getSecret();

    } else if (_defaultUserAccount != null) { // Use the default values from the API implementation.

        accountKey = _defaultUserAccount.getAPIkey();
        accountSecret = _defaultUserAccount.getSecret();
    }

    // Check, if account key and account secret are available for the request.
    if (accountKey == null) {
        throw new MissingAccountDataException("Public key not available for authenticated request to " + _name);
    }
    if (accountSecret == null) {
        throw new MissingAccountDataException(
                "Private key not available for authenticated request to " + _name);
    }

    if (arguments == null) { // If the user provided no arguments, just create an empty argument array.
        arguments = new HashMap<String, String>();
    }

    arguments.put("method", method); // Add the method to the post data.
    arguments.put("nonce", "" + ++_nonce); // Add the dummy nonce.

    // Convert the arguments into a string to post them.
    String postData = "";

    for (Iterator argumentIterator = arguments.entrySet().iterator(); argumentIterator.hasNext();) {
        Map.Entry argument = (Map.Entry) argumentIterator.next();

        if (postData.length() > 0) {
            postData += "&";
        }
        postData += argument.getKey() + "=" + argument.getValue();
    }

    // Create a new secret key
    try {

        key = new SecretKeySpec(accountSecret.getBytes("UTF-8"), "HmacSHA512");

    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    // Create a new mac
    try {

        mac = Mac.getInstance("HmacSHA512");

    } catch (NoSuchAlgorithmException nsae) {

        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    // Init mac with key.
    try {
        mac.init(key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }

    // Add the key to the header lines.
    headerLines.put("Key", accountKey);

    // Encode the post data by the secret and encode the result as base64.
    try {

        headerLines.put("Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8"))));
    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    // Now do the actual request
    String requestResult = HttpUtils.httpPost(_url, headerLines, postData);

    if (requestResult != null) { // The request worked

        try {
            // Convert the HTTP request return value to JSON to parse further.
            JSONObject jsonResult = JSONObject.fromObject(requestResult);

            // Check, if the request was successful
            int success = jsonResult.getInt("success");

            if (success == 0) { // The request failed.
                String errorMessage = jsonResult.getString("error");

                LogUtils.getInstance().getLogger().error(_name + " trade API request failed: " + errorMessage);

                return null;

            } else { // Request succeeded!

                // Try to figure, what the return actually is: json object or json array?

                // Test, if the return value is an JSONArray.
                JSONArray arrayReturn = jsonResult.optJSONArray("return");

                if (arrayReturn != null) { // Converting the result into a JSON array worked, so return it.

                    return arrayReturn;
                }

                // Now test, if the return value is a JSONObject.
                JSONObject objectReturn = jsonResult.optJSONObject("return");

                if (objectReturn != null) { // Converting the result into a JSON object worked, so return it.

                    return objectReturn;
                }

                if (!jsonResult.has("return")) { // Has this object no return value?

                    LogUtils.getInstance().getLogger()
                            .error(_name + " trade API request '" + method + "' has no return value.");

                    return null; // No reasonable return value possible.

                } else { // There is a return value, but it's neither an array or a object, so we cannot convert it.

                    LogUtils.getInstance().getLogger().error(_name + " trade API request '" + method
                            + "' has a return value, that is neither a JSONObject or a JSONArray. Don't know, what to do with it.");

                    return null; // Not much we can do here...
                }
            }

        } catch (JSONException je) {
            System.err.println("Cannot parse json request result: " + je.toString());

            return null; // An error occured...
        }
    }

    return null; // The request failed.
}

From source file:de.andreas_rueckert.trade.site.btc_e.client.BtcEClient.java

/**
 * Execute a authenticated query on btc-e.
 *
 * @param method The method to execute.//from   w  w  w  . jav a  2s  .co  m
 * @param arguments The arguments to pass to the server.
 * @param userAccount The user account on the exchange, or null if the default account should be used.
 *
 * @return The returned data as JSON or null, if the request failed.
 *
 * @see http://pastebin.com/K25Nk2Sv
 */
private final JSONObject authenticatedHTTPRequest(String method, Map<String, String> arguments,
        TradeSiteUserAccount userAccount) {
    HashMap<String, String> headerLines = new HashMap<String, String>(); // Create a new map for the header lines.
    Mac mac;
    SecretKeySpec key = null;
    String accountKey; // The used key of the account.
    String accountSecret; // The used secret of the account.

    // Try to get an account key and secret for the request.
    if (userAccount != null) {

        accountKey = userAccount.getAPIkey();
        accountSecret = userAccount.getSecret();

    } else { // Use the default values from the API implementation.

        accountKey = _key;
        accountSecret = _secret;
    }

    // Check, if account key and account secret are available for the request.
    if (accountKey == null) {
        throw new MissingAccountDataException("Key not available for authenticated request to btc-e");
    }
    if (accountSecret == null) {
        throw new MissingAccountDataException("Secret not available for authenticated request to btc-e");
    }

    if (arguments == null) { // If the user provided no arguments, just create an empty argument array.
        arguments = new HashMap<String, String>();
    }

    arguments.put("method", method); // Add the method to the post data.
    arguments.put("nonce", "" + ++_nonce); // Add the dummy nonce.

    // Convert the arguments into a string to post them.
    String postData = "";

    for (Iterator argumentIterator = arguments.entrySet().iterator(); argumentIterator.hasNext();) {
        Map.Entry argument = (Map.Entry) argumentIterator.next();

        if (postData.length() > 0) {
            postData += "&";
        }
        postData += argument.getKey() + "=" + argument.getValue();
    }

    // Create a new secret key
    try {

        key = new SecretKeySpec(accountSecret.getBytes("UTF-8"), "HmacSHA512");

    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    // Create a new mac
    try {

        mac = Mac.getInstance("HmacSHA512");

    } catch (NoSuchAlgorithmException nsae) {

        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

    // Init mac with key.
    try {
        mac.init(key);
    } catch (InvalidKeyException ike) {
        System.err.println("Invalid key exception: " + ike.toString());
        return null;
    }

    // Add the key to the header lines.
    headerLines.put("Key", accountKey);

    // Encode the post data by the secret and encode the result as base64.
    try {

        headerLines.put("Sign", Hex.encodeHexString(mac.doFinal(postData.getBytes("UTF-8"))));
    } catch (UnsupportedEncodingException uee) {

        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    // Now do the actual request
    String requestResult = HttpUtils.httpPost("https://" + DOMAIN + "/tapi", headerLines, postData);

    if (requestResult != null) { // The request worked

        try {
            // Convert the HTTP request return value to JSON to parse further.
            JSONObject jsonResult = JSONObject.fromObject(requestResult);

            // Check, if the request was successful
            int success = jsonResult.getInt("success");

            if (success == 0) { // The request failed.
                String errorMessage = jsonResult.getString("error");

                LogUtils.getInstance().getLogger().error("btc-e.com trade API request failed: " + errorMessage);

                return null;

            } else { // Request succeeded!

                return jsonResult.getJSONObject("return");
            }

        } catch (JSONException je) {
            System.err.println("Cannot parse json request result: " + je.toString());

            return null; // An error occured...
        }
    }

    return null; // The request failed.
}

From source file:carnero.cgeo.original.libs.Base.java

public static byte[] hashHmac(String text, String salt) {
    byte[] macBytes = {};

    try {//from   ww w .ja  v  a  2  s .  c o m
        SecretKeySpec secretKeySpec = new SecretKeySpec(salt.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKeySpec);
        macBytes = mac.doFinal(text.getBytes());
    } catch (Exception e) {
        Log.e(Settings.tag, "cgBase.hashHmac: " + e.toString());
    }

    return macBytes;
}

From source file:carnero.cgeo.cgBase.java

public static byte[] hashHmac(String text, String salt) {
    byte[] macBytes = {};

    try {//from   w  w w .j  a  v  a2 s. com
        SecretKeySpec secretKeySpec = new SecretKeySpec(salt.getBytes(), "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKeySpec);
        macBytes = mac.doFinal(text.getBytes());
    } catch (Exception e) {
        Log.e(cgSettings.tag, "cgBase.hashHmac: " + e.toString());
    }

    return macBytes;
}