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:net.unicon.cas.chalkwire.servlet.CasChalkWireHttpServlet.java

public static String generateMAC(final String sharedSecret, final String data) throws IOException {
    final Mac mac = setKey(sharedSecret);
    final byte[] signBytes = mac.doFinal(data.getBytes("UTF8"));
    final String signature = encodeBase64(signBytes);
    return signature;
}

From source file:com.scm.reader.livescanner.search.SearchRequestBuilder.java

private static String signHmacSha1(String key, String message)
        throws NoSuchAlgorithmException, InvalidKeyException, IllegalStateException {
    SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(keySpec);/* w ww.j  a  va 2 s.  co  m*/
    byte[] result = mac.doFinal(message.getBytes());

    return new String(Base64.encodeBase64(result));
}

From source file:io.cloudslang.content.azure.services.AuthorizationTokenImpl.java

@NotNull
public static String getToken(@NotNull final String identifier, @NotNull final String primaryOrSecondaryKey,
        @NotNull final Date expiryDate) {
    final Mac sha512Hmac = HmacUtils.getHmacSha512(primaryOrSecondaryKey.getBytes(UTF_8));
    final String dataToSign = String.format("%s\n%s", identifier, DateUtilities.formatDate(expiryDate));
    final byte[] encodedBytes = Base64.encodeBase64(sha512Hmac.doFinal(dataToSign.getBytes(UTF_8)));
    final String encodedString = new String(encodedBytes, UTF_8);
    return String.format(SHARED_ACCESS_SIGNATURE, identifier, DateUtilities.formatDate(expiryDate),
            encodedString);// w  ww  . j a v  a 2  s .c  om
}

From source file:org.mozilla.android.sync.crypto.Cryptographer.java

/**
 * Helper to generate HMAC/*  w ww  .  j av  a  2s.  c  o  m*/
 *
 * @param bundle CryptoInfo
 * @return a generated HMAC for given cipher text
 */
private static byte[] generateHMAC(CryptoInfo bundle) {
    try {
        Mac hmacHasher = HKDF.makeHMACHasher(bundle.getKeys().getHMACKey());
        return hmacHasher.doFinal(Base64.encodeBase64(bundle.getMessage()));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:org.innobuilt.fincayra.fps.SignatureUtils.java

public static String sign(String data, String key, String signatureMethod) throws SignatureException {
    String signature = "";
    try {/*from  www .jav a 2s.co m*/
        Mac mac = Mac.getInstance(signatureMethod);
        mac.init(new SecretKeySpec(key.getBytes(), signatureMethod));
        signature = new String(Base64.encodeBase64(mac.doFinal(data.getBytes(UTF_8_Encoding))));
    } catch (Exception e) {
        throw new SignatureException("Failed to generate signature: " + e.getMessage(), e);
    }
    return signature;
}

From source file:Main.java

private static String generateSignature(String base, String type, String nonce, String timestamp, String token,
        String tokenSecret, String verifier, ArrayList<String> parameters)
        throws NoSuchAlgorithmException, InvalidKeyException {
    String encodedBase = Uri.encode(base);

    StringBuilder builder = new StringBuilder();

    //Create an array of all the parameters
    //So that we can sort them
    //OAuth requires that we sort all parameters
    ArrayList<String> sortingArray = new ArrayList<String>();

    sortingArray.add("oauth_consumer_key=" + oauthConsumerKey);
    sortingArray.add("oauth_nonce=" + nonce);
    sortingArray.add("oauth_signature_method=HMAC-SHA1");
    sortingArray.add("oauth_timestamp=" + timestamp);
    sortingArray.add("oauth_version=1.0");

    if (parameters != null) {
        sortingArray.addAll(parameters);
    }/*from w  ww  . j  a v a2  s. c  o m*/

    if (token != "" && token != null) {
        sortingArray.add("oauth_token=" + token);
    }
    if (verifier != "" && verifier != null) {
        sortingArray.add("oauth_verifier=" + verifier);
    }

    Collections.sort(sortingArray);

    //Append all parameters to the builder in the right order
    for (int i = 0; i < sortingArray.size(); i++) {
        if (i > 0)
            builder.append("&" + sortingArray.get(i));
        else
            builder.append(sortingArray.get(i));

    }

    String params = builder.toString();
    //Percent encoded the whole url
    String encodedParams = Uri.encode(params);

    String completeUrl = type + "&" + encodedBase + "&" + encodedParams;

    String completeSecret = oauthSecretKey;

    if (tokenSecret != null && tokenSecret != "") {
        completeSecret = completeSecret + "&" + tokenSecret;
    } else {
        completeSecret = completeSecret + "&";
    }

    Log.v("Complete URL: ", completeUrl);
    Log.v("Complete Key: ", completeSecret);

    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(completeSecret.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] sig = mac.doFinal(completeUrl.getBytes());

    String signature = Base64.encodeToString(sig, 0);
    signature = signature.replace("+", "%2b"); //Specifically encode all +s to %2b

    return signature;
}

From source file:jp.co.opentone.bsol.linkbinder.util.ValueFormatter.java

/**
 * ??SHA256???/* w  ww.  ja  va  2  s  .  c  o  m*/
 * @param value ??
 * @param key 
 * @return ??
 */
public static String formatValueToHash(String value, String key) {
    byte[] result;
    try {
        SecretKeySpec sk = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(sk);
        result = mac.doFinal(value.getBytes("UTF-8"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new String(Hex.encodeHex(result));

}

From source file:Models.UserModel.java

public static String HMAC_SHA256(String email, String password) {
    try {/*  ww w  .  j  a  v  a2  s .  c  om*/

        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(password.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        String auth = Base64.encodeBase64String(sha256_HMAC.doFinal(email.getBytes()));
        return auth;
    } catch (NoSuchAlgorithmException | InvalidKeyException | IllegalStateException e) {
        System.out.println("Error HS-256");
        return "";
    }
}

From source file:com.lambdasoup.panda.PandaHttp.java

private static String generateSignature(String method, String url, String host, String secretKey,
        Map<String, String> params) {
    String queryString = canonicalQueryString(params);
    String stringToSign = method.toUpperCase() + "\n" + host + "\n" + url + "\n" + queryString;

    String signature = null;//from   ww  w .  ja v a 2  s .  com

    try {

        SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(stringToSign.getBytes());

        signature = new String(Base64.encodeBase64(rawHmac));

    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }

    return signature;
}

From source file:com.diversityarrays.dal.db.DalDatabaseUtil.java

/**
 * Calculate an RFC 2104 compliant HMAC signature.
 * @param key is the signing key//  w ww.ja  va 2 s .  c  om
 * @param data is the data to be signed 
 * @return the base64-encoded signature as a String
 */
public static String computeHmacSHA1(String key, String data) {
    try {
        byte[] keyBytes = key.getBytes("UTF-8");
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));

        // TODO Consider replacing with a simple hex encoder so we don't need commons-codec
        byte[] hexBytes = new Hex().encode(rawHmac);

        return new String(hexBytes, "UTF-8");

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}