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.apache.jackrabbit.oak.spi.blob.AbstractBlobStore.java

@Override
public String getReference(@Nonnull String blobId) {
    checkNotNull(blobId, "BlobId must be specified");
    try {//w  ww  .  j a  v  a  2s . com
        Mac mac = Mac.getInstance(ALGORITHM);
        mac.init(new SecretKeySpec(getReferenceKey(), ALGORITHM));
        byte[] hash = mac.doFinal(blobId.getBytes("UTF-8"));
        return blobId + ':' + BaseEncoding.base32Hex().encode(hash);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e);
    } catch (UnsupportedEncodingException e) {
        throw new IllegalStateException(e);
    }
}

From source file:org.linkdroid.PostJob.java

private static Mac initHmacSha1(String secretString, String nonce)
        throws NoSuchAlgorithmException, IOException, InvalidKeyException {
    SecretKey key = new SecretKeySpec(secretString.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(key);//from  ww  w  .  j  a  v a 2 s  . c o m
    if (nonce != null) {
        mac.update(nonce.getBytes(UTF8));
    }
    return mac;
}

From source file:de.burlov.ultracipher.core.mail.AuthenticatingSMTPClient.java

/**
 * Authenticate to the SMTP server by sending the AUTH command with the
 * selected mechanism, using the given username and the given password.
 * <p/>//from  www .j a  va  2 s.c  o m
 *
 * @return True if successfully completed, false if not.
 * @throws SMTPConnectionClosedException              If the SMTP server prematurely closes the connection as a
 *                                                    result of the client being idle or some other reason
 *                                                    causing the server to send SMTP reply code 421. This
 *                                                    exception may be caught either as an IOException or
 *                                                    independently as itself.
 * @throws java.io.IOException                        If an I/O error occurs while either sending a command to
 *                                                    the server or receiving a reply from the server.
 * @throws java.security.NoSuchAlgorithmException     If the CRAM hash algorithm cannot be instantiated by the
 *                                                    Java runtime system.
 * @throws java.security.InvalidKeyException          If the CRAM hash algorithm failed to use the given
 *                                                    password.
 * @throws java.security.spec.InvalidKeySpecException If the CRAM hash algorithm failed to use the given
 *                                                    password.
 *                                                    *
 */
public boolean auth(AUTH_METHOD method, String username, String password)
        throws IOException, NoSuchAlgorithmException, InvalidKeyException, InvalidKeySpecException {
    if (!SMTPReply.isPositiveIntermediate(sendCommand(SMTPCommand.AUTH, AUTH_METHOD.getAuthName(method)))) {
        return false;
    }

    if (method.equals(AUTH_METHOD.PLAIN)) {
        // the server sends an empty response ("334 "), so we don't have to
        // read it.
        return SMTPReply.isPositiveCompletion(sendCommand(
                new String(Base64.encodeBase64(("\000" + username + "\000" + password).getBytes()))));
    } else if (method.equals(AUTH_METHOD.CRAM_MD5)) {
        // get the CRAM challenge
        byte[] serverChallenge = Base64.decodeBase64(getReplyString().substring(4).trim());
        // get the Mac instance
        Mac hmac_md5 = Mac.getInstance("HmacMD5");
        hmac_md5.init(new SecretKeySpec(password.getBytes(), "HmacMD5"));
        // compute the result:
        byte[] hmacResult = _convertToHexString(hmac_md5.doFinal(serverChallenge)).getBytes();
        // join the byte arrays to form the reply
        byte[] usernameBytes = username.getBytes();
        byte[] toEncode = new byte[usernameBytes.length + 1 /* the space */ + hmacResult.length];
        System.arraycopy(usernameBytes, 0, toEncode, 0, usernameBytes.length);
        toEncode[usernameBytes.length] = ' ';
        System.arraycopy(hmacResult, 0, toEncode, usernameBytes.length + 1, hmacResult.length);
        // send the reply and read the server code:
        return SMTPReply.isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(toEncode))));
    } else if (method.equals(AUTH_METHOD.LOGIN)) {
        // the server sends fixed responses (base64("Username") and
        // base64("Password")), so we don't have to read them.
        if (!SMTPReply
                .isPositiveIntermediate(sendCommand(new String(Base64.encodeBase64(username.getBytes()))))) {
            return false;
        }
        return SMTPReply
                .isPositiveCompletion(sendCommand(new String(Base64.encodeBase64(password.getBytes()))));
    } else {
        return false; // safety check
    }
}

From source file:com.cloud.utils.SwiftUtil.java

static String calculateRFC2104HMAC(String data, String key)
        throws SignatureException, NoSuchAlgorithmException, InvalidKeyException {

    SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);/*from  w  w w.  jav  a 2s  .  c  o  m*/
    return toHexString(mac.doFinal(data.getBytes()));

}

From source file:com.terremark.handlers.CloudApiAuthenticationHandler.java

/**
 * Returns HMAC instance initialized with the private key.
 *
 * @return HMAC instance./*w  w  w. j a  v a  2  s.c o m*/
 * @throws NoSuchAlgorithmException If the HMAC algorithm is not available.
 * @throws InvalidKeyException If the private key is malformed.
 * @throws UnsupportedEncodingException If UTF-8 character encoding is not supported.
 */
private Mac getMac() throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    String algo;
    switch (algorithm) {
    case HMAC_SHA1:
        algo = "HmacSHA1";
        break;
    case HMAC_SHA256:
        algo = "HmacSHA256";
        break;
    case HMAC_SHA512:
        algo = "HmacSHA512";
        break;
    default:
        throw new UnsupportedOperationException("Not implemented: " + algorithm.toString());
    }

    final Mac mac = Mac.getInstance(algo);
    mac.init(new SecretKeySpec(privateKey.getBytes("UTF-8"), algo));

    return mac;
}

From source file:org.apache.nifi.web.security.jwt.JwtServiceTest.java

private String generateHMAC(String hmacSecret, String body)
        throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
    Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(hmacSecret.getBytes("UTF-8"), "HmacSHA256");
    hmacSHA256.init(secret_key);/*from  w  ww.  j  av a  2  s  .c o m*/
    return Base64.encodeBase64URLSafeString(hmacSHA256.doFinal(body.getBytes("UTF-8")));
}

From source file:org.akvo.flow.service.DataSyncService.java

private ZipFileData formZip(long surveyInstanceId) {
    ZipFileData zipFileData = new ZipFileData();
    StringBuilder surveyBuf = new StringBuilder();

    // Hold the responses in the StringBuilder
    String uuid = processSurveyData(surveyInstanceId, surveyBuf, zipFileData.imagePaths);

    // THe filename will match the Survey Instance UUID
    File zipFile = new File(FileUtil.getFilesDir(FileType.DATA), uuid + ConstantUtil.ARCHIVE_SUFFIX);

    // Write the data into the zip file
    try {/* ww w  . ja  v a 2  s  .com*/
        String fileName = zipFile.getAbsolutePath();// Will normalize filename.
        zipFileData.filename = fileName;
        Log.i(TAG, "Creating zip file: " + fileName);
        FileOutputStream fout = new FileOutputStream(zipFile);
        CheckedOutputStream checkedOutStream = new CheckedOutputStream(fout, new Adler32());
        ZipOutputStream zos = new ZipOutputStream(checkedOutStream);

        writeTextToZip(zos, surveyBuf.toString(), SURVEY_DATA_FILE);
        String signingKeyString = mProps.getProperty(SIGNING_KEY_PROP);
        if (!StringUtil.isNullOrEmpty(signingKeyString)) {
            MessageDigest sha1Digest = MessageDigest.getInstance("SHA1");
            byte[] digest = sha1Digest.digest(surveyBuf.toString().getBytes("UTF-8"));
            SecretKeySpec signingKey = new SecretKeySpec(signingKeyString.getBytes("UTF-8"), SIGNING_ALGORITHM);
            Mac mac = Mac.getInstance(SIGNING_ALGORITHM);
            mac.init(signingKey);
            byte[] hmac = mac.doFinal(digest);
            String encodedHmac = Base64.encodeBytes(hmac);
            writeTextToZip(zos, encodedHmac, SIG_FILE_NAME);
        }

        final String checksum = "" + checkedOutStream.getChecksum().getValue();
        zos.close();
        Log.i(TAG, "Closed zip output stream for file: " + fileName + ". Checksum: " + checksum);
    } catch (IOException e) {
        PersistentUncaughtExceptionHandler.recordException(e);
        Log.e(TAG, e.getMessage());
        zipFileData = null;
    } catch (NoSuchAlgorithmException e) {
        PersistentUncaughtExceptionHandler.recordException(e);
        Log.e(TAG, e.getMessage());
        zipFileData = null;
    } catch (InvalidKeyException e) {
        PersistentUncaughtExceptionHandler.recordException(e);
        Log.e(TAG, e.getMessage());
        zipFileData = null;
    }

    return zipFileData;
}

From source file:com.here.account.auth.OAuth1SignerTest.java

protected String HmacSHAN(String keyString, String algorithm, String baseString)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    /*/*from w w  w .  ja v a2s .  c o m*/
             byte[] keyBytes = (urlEncode(consumerSecret) + "&").getBytes(OAuthConstants.UTF_8_CHARSET);
    SecretKeySpec signingKey = new SecretKeySpec(keyBytes, signatureMethod);
            
    //generate signature based on the requested signature method
    Mac mac = Mac.getInstance(signatureMethod);
    mac.init(signingKey);
    byte[] signedBytes = mac.doFinal(bytesToSign);
    return Base64.encodeBase64String(signedBytes);
            
     */
    byte[] keyBytes = keyString.getBytes("UTF-8");
    Key signingKey = new SecretKeySpec(keyBytes, algorithm);
    Mac mac = Mac.getInstance(algorithm);
    mac.init(signingKey);

    //generate signature bytes
    byte[] signatureBytes = mac.doFinal(baseString.getBytes("UTF-8"));

    // base64-encode the hmac
    //return new Base64().encodeAsString(signatureBytes);
    return Base64.encodeBase64String(signatureBytes);
}

From source file:com.tripit.auth.OAuthCredential.java

private String generateSignature(String baseUrl, SortedMap<String, String> args)
        throws UnsupportedEncodingException, InvalidKeyException, NoSuchAlgorithmException {
    String encoding = "UTF-8";

    baseUrl = URLEncoder.encode(baseUrl, encoding);

    StringBuilder sb = new StringBuilder();
    boolean isFirst = true;
    for (Map.Entry<String, String> arg : args.entrySet()) {
        if (isFirst) {
            isFirst = false;//www  . j  a va 2 s  .c  om
        } else {
            sb.append('&');
        }
        sb.append(URLEncoder.encode(arg.getKey(), encoding));
        sb.append('=');
        sb.append(URLEncoder.encode(arg.getValue(), encoding));
    }
    String parameters = URLEncoder.encode(sb.toString(), encoding);

    String signatureBaseString = "GET&" + baseUrl + "&" + parameters;

    String key = (consumerSecret != null ? consumerSecret : "") + "&" + (userSecret != null ? userSecret : "");

    String macName = "HmacSHA1";
    Mac mac = Mac.getInstance(macName);
    mac.init(new SecretKeySpec(key.getBytes(encoding), macName));
    byte[] signature = mac.doFinal(signatureBaseString.getBytes(encoding));

    return new Base64().encodeToString(signature).trim();
}

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.
 *///from   www. j  ava 2  s .co  m
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.
}