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.emc.vipr.ribbon.ViPRDataServicesServerList.java

protected String getSignature(String canonicalString, String secret) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA1"));
    String signature = new String(Base64.encodeBase64(mac.doFinal(canonicalString.getBytes("UTF-8"))));
    logger.debug("canonicalString:\n" + canonicalString);
    logger.debug("signature:\n" + signature);
    return signature;
}

From source file:com.tapcentive.minimalist.JWTHelper.java

/***
 * Generates a JSON Web Token. This token uses the supplied application key to sign the token
 * content which should uniquely identify the client's customer (e.g. a loyalty number, email
 * etc.) and contain any Tapcentive audience IDs assigned to this customer. This example does
 * not require that either parameter be present.
 * @param originalBody//from  w w  w .ja  va2s.c  om
 * @param audiences
 * @param customerId
 * @return
 */
public String createJWT(JSONObject originalBody, List<String> audiences, String customerId) {

    try {
        JSONObject header = new JSONObject();
        JSONObject body = new JSONObject(originalBody.toString());
        header.put("typ", "JWT");
        header.put("alg", "HS256");
        body.put("iss", _keyid);

        if ((audiences != null) && (audiences.size() > 0)) {
            JSONArray attrArray = new JSONArray(audiences);
            body.put("audiences", attrArray);
        }

        if (customerId != null) {
            body.put("customer_xid", customerId);
        }

        String signedContent = Base64.encodeToString(header.toString().getBytes("UTF-8"), Base64.NO_WRAP) + "."
                + Base64.encodeToString(body.toString().getBytes("UTF-8"), Base64.NO_WRAP);
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(_key.getBytes("UTF-8"), "HmacSHA256");
        sha256_HMAC.init(secret_key);
        String signature = Base64.encodeToString(sha256_HMAC.doFinal(signedContent.getBytes("UTF-8")),
                Base64.NO_WRAP);
        return signedContent + "." + signature;
    } catch (JSONException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.ecloudmanager.tmrk.cloudapi.CloudapiRequestAuhtorization.java

private String signature(HttpUriRequest request, String apiPrivateKey) {
    StringBuilder sb = new StringBuilder();
    String verb = request.getMethod().toUpperCase();
    String date = request.getFirstHeader(HttpHeaderNames.DATE).getValue();
    Header contentTypeHeader = request.getFirstHeader(HttpHeaderNames.CONTENT_TYPE);
    String contentType = contentTypeHeader != null ? contentTypeHeader.getValue() : null;
    Header contentLengthHeader = request.getFirstHeader(HttpHeaderNames.CONTENT_LENGTH);
    String contentLength = contentLengthHeader != null ? contentLengthHeader.getValue() : null;

    sb.append(verb).append("\n");
    sb.append(contentLength != null ? contentLength.trim() : "").append("\n");
    sb.append(contentType != null ? contentType.trim() : "").append("\n");
    sb.append(date).append("\n");
    HeaderIterator hit = request.headerIterator();
    Headers<Object> headers = new Headers<>();
    while (hit.hasNext()) {
        Header hdr = hit.nextHeader();//from  w w  w .j a v  a  2s. c o m
        headers.add(hdr.getName(), hdr.getValue());
    }
    sb.append(canonicalizedHeaders(headers));
    sb.append(canonicalizedResource(new ResteasyUriInfo(request.getURI())));

    String sigstr = sb.toString();
    try {
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(getBytes(apiPrivateKey), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        return Base64.encodeBytes(sha256_HMAC.doFinal(getBytes(sigstr)));
    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:hudson.plugins.sauce_ondemand.PluginImpl.java

/**
 * Creates a HMAC token which is used as part of the Javascript inclusion that embeds the Sauce results
 *
 * @param username  the Sauce user id//from w  w  w. j  av a2s .  co  m
 * @param accessKey the Sauce access key
 * @param jobId     the Sauce job id
 * @return the HMAC token
 * @throws java.security.NoSuchAlgorithmException
 *
 * @throws java.security.InvalidKeyException
 *
 * @throws java.io.UnsupportedEncodingException
 *
 */
public String calcHMAC(String username, String accessKey, String jobId)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    Calendar calendar = Calendar.getInstance();

    SimpleDateFormat format = new SimpleDateFormat(DATE_FORMAT);
    format.setTimeZone(TimeZone.getTimeZone("UTC"));
    String key = username + ":" + accessKey + ":" + format.format(calendar.getTime());
    byte[] keyBytes = key.getBytes();
    SecretKeySpec sks = new SecretKeySpec(keyBytes, HMAC_KEY);
    Mac mac = Mac.getInstance(sks.getAlgorithm());
    mac.init(sks);
    byte[] hmacBytes = mac.doFinal(jobId.getBytes());
    byte[] hexBytes = new Hex().encode(hmacBytes);
    return new String(hexBytes, "ISO-8859-1");
}

From source file:com.kolich.havalo.client.signing.algorithms.HMACSHA256Signer.java

/**
  * Returns a Base-64 encoded HMAC-SHA256 signature.
  *//*from   w w  w.j a  v a  2 s . com*/
@Override
public String sign(final HavaloCredentials credentials, final String input) {
    String result = null;
    try {
        // Get a new instance of the HMAC-SHA256 algorithm.
        final Mac mac = Mac.getInstance(HMAC_SHA256_ALGORITHM_NAME);
        // Init it with our secret and the secret-key algorithm.
        mac.init(new SecretKeySpec(getBytesUtf8(credentials.getSecret()), HMAC_SHA256_ALGORITHM_NAME));
        // Sign the input.
        result = newStringUtf8(encodeBase64(mac.doFinal(getBytesUtf8(input))));
    } catch (Exception e) {
        throw new HavaloClientException("Failed to SHA-256 sign input " + "string: " + input, e);
    }
    return result;
}

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 {//www. j  av  a2s.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:org.apache.qpid.server.security.auth.sasl.CRAMMD5HexServerTest.java

/**
 * Since we don't have a CRAM-MD5-HEX implementation client implementation in Java, this method
 * provides the implementation for first principals.
 *
 * @param userId user id/*  w w w. j  av a2s . c  o  m*/
 * @param clearTextPassword clear text password
 * @param serverChallenge challenge from server
 *
 * @return challenge response
 */
private byte[] generateClientResponse(final String userId, final String clearTextPassword,
        final byte[] serverChallenge) throws Exception {
    byte[] digestedPasswordBytes = MessageDigest.getInstance("MD5").digest(clearTextPassword.getBytes());
    char[] hexEncodedDigestedPassword = Hex.encodeHex(digestedPasswordBytes);
    byte[] hexEncodedDigestedPasswordBytes = new String(hexEncodedDigestedPassword).getBytes();

    Mac hmacMd5 = Mac.getInstance("HmacMD5");
    hmacMd5.init(new SecretKeySpec(hexEncodedDigestedPasswordBytes, "HmacMD5"));
    final byte[] messageAuthenticationCode = hmacMd5.doFinal(serverChallenge);

    // Build client response
    String responseAsString = userId + " " + new String(Hex.encodeHex(messageAuthenticationCode));
    byte[] resp = responseAsString.getBytes();
    return resp;
}

From source file:com.hp.autonomy.hod.client.util.Hmac.java

private byte[] hmacSha1(final String message, final String secret) {
    try {//  www .j a v  a 2  s .  c om
        final Mac mac = Mac.getInstance(HMAC_SHA1);
        final Key key = new SecretKeySpec(bytesFromString(secret), HMAC_SHA1);
        mac.init(key);
        return mac.doFinal(bytesFromString(message));
    } catch (final NoSuchAlgorithmException e) {
        // This should never happen on a sensible JVM
        throw new AssertionError("HMAC SHA1 is not supported", e);
    } catch (final InvalidKeyException e) {
        // In practice, this means that the token secret was invalid
        throw new IllegalArgumentException("Invalid token secret", e);
    }
}

From source file:com.microsoft.valda.oms.OmsAppender.java

private void sendLog(LoggingEvent event)
        throws NoSuchAlgorithmException, InvalidKeyException, IOException, HTTPException {
    //create JSON message
    JSONObject obj = new JSONObject();
    obj.put("LOGBACKLoggerName", event.getLoggerName());
    obj.put("LOGBACKLogLevel", event.getLevel().toString());
    obj.put("LOGBACKMessage", event.getFormattedMessage());
    obj.put("LOGBACKThread", event.getThreadName());
    if (event.getCallerData() != null && event.getCallerData().length > 0) {
        obj.put("LOGBACKCallerData", event.getCallerData()[0].toString());
    } else {/*from w w w.j  a  v  a2 s.  c om*/
        obj.put("LOGBACKCallerData", "");
    }
    if (event.getThrowableProxy() != null) {
        obj.put("LOGBACKStackTrace", ThrowableProxyUtil.asString(event.getThrowableProxy()));
    } else {
        obj.put("LOGBACKStackTrace", "");
    }
    if (inetAddress != null) {
        obj.put("LOGBACKIPAddress", inetAddress.getHostAddress());
    } else {
        obj.put("LOGBACKIPAddress", "0.0.0.0");
    }
    String json = obj.toJSONString();

    String Signature = "";
    String encodedHash = "";
    String url = "";

    // Todays date input for OMS Log Analytics
    Calendar calendar = Calendar.getInstance();
    SimpleDateFormat dateFormat = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z", Locale.US);
    dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
    String timeNow = dateFormat.format(calendar.getTime());

    // String for signing the key
    String stringToSign = "POST\n" + json.length() + "\napplication/json\nx-ms-date:" + timeNow + "\n/api/logs";
    byte[] decodedBytes = Base64.decodeBase64(sharedKey);
    Mac hasher = Mac.getInstance("HmacSHA256");
    hasher.init(new SecretKeySpec(decodedBytes, "HmacSHA256"));
    byte[] hash = hasher.doFinal(stringToSign.getBytes());

    encodedHash = DatatypeConverter.printBase64Binary(hash);
    Signature = "SharedKey " + customerId + ":" + encodedHash;

    url = "https://" + customerId + ".ods.opinsights.azure.com/api/logs?api-version=2016-04-01";
    URL objUrl = new URL(url);
    HttpsURLConnection con = (HttpsURLConnection) objUrl.openConnection();
    con.setDoOutput(true);
    con.setRequestMethod("POST");
    con.setRequestProperty("Content-Type", "application/json");
    con.setRequestProperty("Log-Type", logType);
    con.setRequestProperty("x-ms-date", timeNow);
    con.setRequestProperty("Authorization", Signature);

    DataOutputStream wr = new DataOutputStream(con.getOutputStream());
    wr.writeBytes(json);
    wr.flush();
    wr.close();

    int responseCode = con.getResponseCode();
    if (responseCode != 200) {
        throw new HTTPException(responseCode);
    }
}

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

private String generateSignature(String signatureBaseString, String signatureMethod) {
    try {/*from  ww  w .j a va 2  s.c  om*/
        //get the bytes from the signature base string
        byte[] bytesToSign = signatureBaseString.getBytes(OAuthConstants.UTF_8_CHARSET);

        //create the signing key from the clientSecret
        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);
    } catch (Exception e) {
        throw new IllegalArgumentException(e);
    }
}