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:org.egov.collection.integration.pgi.AxisAdaptor.java

private String hashAllFields(final LinkedHashMap<String, String> fields) {

    final String axisSecureSecret = collectionApplicationProperties.axisSecureSecret();
    byte[] decodedKey;
    byte[] hashValue = null;
    // Sort list with field names ascending order
    final List<String> fieldNames = new ArrayList<>(fields.keySet());
    Collections.sort(fieldNames);

    // iterate through field name list and generate message for hashing. Format: fieldname1=fieldvale1?fieldname2=fieldvalue2
    final Iterator<String> itr = fieldNames.iterator();
    final StringBuilder hashingMessage = new StringBuilder();
    int i = 0;//  w  ww . j  a va2  s  .  com
    while (itr.hasNext()) {
        final String fieldName = itr.next();
        final String fieldValue = fields.get(fieldName);
        if (fieldValue != null && fieldValue.length() > 0) {
            if (i != 0)
                hashingMessage.append("&");
            hashingMessage.append(fieldName).append("=").append(fieldValue);
            i++;
        }
    }
    try {
        decodedKey = Hex.decodeHex(axisSecureSecret.toCharArray());
        SecretKeySpec keySpec = new SecretKeySpec(decodedKey, "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(keySpec);
        byte[] hashingMessageBytes = hashingMessage.toString().getBytes(UTF8);
        hashValue = mac.doFinal(hashingMessageBytes);
    } catch (DecoderException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return DatatypeConverter.printHexBinary(hashValue);
}

From source file:com.microsoft.windowsazure.messaging.Connection.java

/**
 * Generates an AuthToken/*from  w  w w . j av a2s.  co m*/
 * @param url   The target URL
 * @return   An AuthToken
 * @throws java.security.InvalidKeyException
 */
private String generateAuthToken(String url) throws InvalidKeyException {

    String keyName = mConnectionData.get(SHARED_ACCESS_KEY_NAME);
    if (isNullOrWhiteSpace(keyName)) {
        throw new AssertionError("SharedAccessKeyName");
    }

    String key = mConnectionData.get(SHARED_ACCESS_KEY);
    if (isNullOrWhiteSpace(key)) {
        throw new AssertionError("SharedAccessKey");
    }

    try {
        url = URLEncoder.encode(url, UTF8_ENCODING).toLowerCase(Locale.ENGLISH);
    } catch (UnsupportedEncodingException e) {
        // this shouldn't happen because of the fixed encoding
    }

    // Set expiration in seconds
    Calendar expireDate = Calendar.getInstance(TimeZone.getTimeZone(UTC_TIME_ZONE));
    expireDate.add(Calendar.MINUTE, EXPIRE_MINUTES);

    long expires = expireDate.getTimeInMillis() / 1000;

    String toSign = url + '\n' + expires;

    // sign

    byte[] bytesToSign = toSign.getBytes();
    Mac mac = null;
    try {
        mac = Mac.getInstance("HmacSHA256");
    } catch (NoSuchAlgorithmException e) {
        // This shouldn't happen because of the fixed algorithm
    }

    SecretKeySpec secret = new SecretKeySpec(key.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] signedHash = mac.doFinal(bytesToSign);
    String base64Signature = Base64.encodeToString(signedHash, Base64.DEFAULT);
    base64Signature = base64Signature.trim();
    try {
        base64Signature = URLEncoder.encode(base64Signature, UTF8_ENCODING);
    } catch (UnsupportedEncodingException e) {
        // this shouldn't happen because of the fixed encoding
    }

    // construct authorization string
    String token = "SharedAccessSignature sr=" + url + "&sig=" + base64Signature + "&se=" + expires + "&skn="
            + keyName;

    return token;
}

From source file:org.hoteia.qalingo.core.service.openid.OpenIdService.java

String getHmacSha1(String data, byte[] key) {
    SecretKeySpec signingKey = new SecretKeySpec(key, HMAC_SHA1_ALGORITHM);
    Mac mac = null;
    try {/*from   w w w . java  2  s.  co m*/
        mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
    } catch (NoSuchAlgorithmException e) {
        throw new OpenIdException(e);
    } catch (InvalidKeyException e) {
        throw new OpenIdException(e);
    }
    try {
        byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));
        return Base64.encodeBytes(rawHmac);
    } catch (IllegalStateException e) {
        throw new OpenIdException(e);
    } catch (UnsupportedEncodingException e) {
        throw new OpenIdException(e);
    }
}

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

/**
 * Create a signature by the following method:
 *     new String( Base64( SHA1 or SHA256 ( key, byte array )))
 * //from   ww  w  .  ja v 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
 * @param useSHA1   - if false use SHA256
 * @return String   - the recalculated string
 * @throws SignatureException
 */
private String calculateRFC2104HMAC(String signIt, String secretKey, boolean useSHA1)
        throws SignatureException {
    SecretKeySpec key = null;
    Mac hmacShaAlg = null;
    String result = null;

    try {
        if (useSHA1) {
            key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
            hmacShaAlg = Mac.getInstance("HmacSHA1");
        } else {
            key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
            hmacShaAlg = Mac.getInstance("HmacSHA256");
        }

        hmacShaAlg.init(key);
        byte[] rawHmac = hmacShaAlg.doFinal(signIt.getBytes());
        result = new String(Base64.encodeBase64(rawHmac));

    } catch (Exception e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage());
    }
    return result.trim();
}

From source file:com.zimbra.cs.account.ZimbraAuthToken.java

@Override
public String getCrumb() throws AuthTokenException {
    String authToken = getEncoded();
    try {//  w  ww. ja  v  a2 s. com
        ByteKey bk = new ByteKey(getCurrentKey().getKey());
        Mac mac = Mac.getInstance("HmacMD5");
        mac.init(bk);
        return new String(Hex.encodeHex(mac.doFinal(authToken.getBytes())));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("fatal error", e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("fatal error", e);
    }
}

From source file:com.wandisco.s3hdfs.auth.AWSAuthenticationHandler.java

/**
 * Create a signature by the following method:
 * new String( Base64( SHA1 or SHA256 ( key, byte array )))
 *
 * @param signIt    - the data to generate a keyed HMAC over
 * @param secretKey - the user's unique key for the HMAC operation
 * @param useSHA1   - if false use SHA256
 * @return String   - the recalculated string
 * @throws SignatureException/*from   w w w . j  a va2 s.c o m*/
 */
private String calculateRFC2104HMAC(String signIt, String secretKey, boolean useSHA1)
        throws SignatureException {
    SecretKeySpec key = null;
    Mac hmacShaAlg = null;
    String result = null;

    try {
        if (useSHA1) {
            key = new SecretKeySpec(secretKey.getBytes(DEFAULT_CHARSET), "HmacSHA1");
            hmacShaAlg = Mac.getInstance("HmacSHA1");
        } else {
            key = new SecretKeySpec(secretKey.getBytes(DEFAULT_CHARSET), "HmacSHA256");
            hmacShaAlg = Mac.getInstance("HmacSHA256");
        }

        hmacShaAlg.init(key);
        byte[] rawHmac = hmacShaAlg.doFinal(signIt.getBytes(DEFAULT_CHARSET));
        result = new String(Base64.encodeBase64(rawHmac), DEFAULT_CHARSET);

    } catch (Exception e) {
        throw new SignatureException("Failed to generate keyed HMAC on REST request: " + e.getMessage());
    }
    return result.trim();
}

From source file:com.telesign.util.TeleSignRequest.java

/**
 * Creates the Signature component for the Authorization header field.
 * Uses your Secret Key to encode the stringToSign.
 * This is a <em>helper method</em>, used internally by the {@link TeleSignRequest#executeRequest()} method.
 *
 * @param data//  w w w  .  j a  v  a 2 s .c om
 *         [Required] The stringToSign.
 * @param key
 *         [Required] Your TeleSign API Key. Also known as your Secret
 *         Key, and your Shared Cryptographic Key. It s a bese64-encoded
 *         string value.
 * @return A String containing the Base64-encoded hash-based message
 *       authentication code.
 * @throws java.security.SignatureException
 *          Failed to generate HMAC. IllegalArgumentException - if
 *          algorithm is null or key is null or empty.
 */
private String encode(String data, String key) throws java.security.SignatureException {

    String result;

    byte[] decoded_key = Base64.decodeBase64(key);

    try {
        // Get an hmac_sha key from the raw key bytes.
        SecretKeySpec signingKey = new SecretKeySpec(decoded_key, auth.value());

        // Get an hmac_sha Mac instance, and initialize it with the signing key.
        Mac mac = Mac.getInstance(auth.value());
        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));

    } catch (Exception e) {

        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }

    return result;
}

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 {/*from   www. j  ava2 s  . co  m*/
        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:org.killbill.billing.plugin.payeezy.client.PayeezyClientWrapper.java

private String getMacValue(final String nonce, final String timeStamp, @Nullable final String payload)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    final Mac mac = Mac.getInstance(HMAC_SHA_256);
    final Key secretKey = new SecretKeySpec(secret.getBytes(), HMAC_SHA_256);
    mac.init(secretKey);//from   w  w w.  j a v a  2s.co m

    final StringBuilder buff = new StringBuilder();
    buff.append(apiKey).append(nonce).append(timeStamp);
    if (token != null) {
        buff.append(token);
    }
    if (payload != null) {
        buff.append(payload);
    }

    final String bufferData = buff.toString();
    final byte[] macHash = mac.doFinal(bufferData.getBytes("UTF-8"));
    return new String(Base64.encodeBase64(toHex(macHash)));
}

From source file:org.dasein.cloud.virtustream.VirtustreamMethod.java

private byte[] calculateHmac(String data, String key) throws SignatureException {
    try {//from  w  ww  . j ava 2s .c  o m
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);

        return mac.doFinal(data.getBytes());
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
}