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:com.amazonaws.services.ec2.util.S3UploadPolicy.java

private String signPolicy(String awsSecretKey, String base64EncodedPolicy)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    SecretKeySpec signingKey = new SecretKeySpec(awsSecretKey.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
    mac.init(signingKey);//from   www .  j  ava 2  s .  c om
    return base64Encode(mac.doFinal(base64EncodedPolicy.getBytes()));
}

From source file:conexionSiabra.Oauth.java

private static String hmac_sha1(String value, String key) {
    try {//from   w ww.  j  av a 2  s . co m
        SecretKey secretKey = null;
        byte[] keyBytes = key.getBytes();
        secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] text = value.getBytes();
        return new String(Base64.encode(mac.doFinal(text), 0)).trim();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:lucee.commons.io.res.type.s3.S3.java

private static byte[] HMAC_SHA1(String key, String message, String charset)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {

    SecretKeySpec sks = new SecretKeySpec(key.getBytes(charset), "HmacSHA1");
    Mac mac = Mac.getInstance(sks.getAlgorithm());
    mac.init(sks);//from www  . j  av a  2s.  com
    mac.update(message.getBytes(charset));
    return mac.doFinal();

}

From source file:org.artifactory.repo.remote.browse.S3RepositorySecuredHelper.java

private static String signWithHmacSha1(String awsSecretKey, String canonicalString) throws Exception {
    try {/*from  www  .jav a  2 s . co m*/
        SecretKeySpec signingKey = new SecretKeySpec(awsSecretKey.getBytes(CharsetNames.UTF_8), HMAC_SHA1);
        Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
        byte[] b64 = Base64.encodeBase64(mac.doFinal(canonicalString.getBytes(CharsetNames.UTF_8)));
        return new String(b64, CharsetNames.UTF_8);
    } catch (Exception e) {
        throw new RuntimeException("Could not sign with " + HMAC_SHA1, e);
    }
}

From source file:com.QuarkLabs.BTCeClient.exchangeApi.AuthRequest.java

/**
 * Makes any request, which require authentication
 *
 * @param method    Method of Trade API//  ww w .  j a v  a  2s .co m
 * @param arguments Additional arguments, which can exist for this method
 * @return Response of type JSONObject
 * @throws JSONException
 */
@Nullable
public JSONObject makeRequest(@NotNull String method, Map<String, String> arguments) throws JSONException {

    if (key.length() == 0 || secret.length() == 0) {
        return new JSONObject("{success:0,error:'No key/secret provided'}");
    }

    if (arguments == null) {
        arguments = new HashMap<>();
    }

    arguments.put("method", method);
    arguments.put("nonce", "" + ++nonce);
    String postData = "";
    for (Iterator<Map.Entry<String, String>> it = arguments.entrySet().iterator(); it.hasNext();) {
        Map.Entry<String, String> ent = it.next();
        if (postData.length() > 0) {
            postData += "&";
        }
        postData += ent.getKey() + "=" + ent.getValue();
    }
    try {
        _key = new SecretKeySpec(secret.getBytes("UTF-8"), "HmacSHA512");
    } catch (UnsupportedEncodingException uee) {
        System.err.println("Unsupported encoding exception: " + uee.toString());
        return null;
    }

    try {
        mac = Mac.getInstance("HmacSHA512");
    } catch (NoSuchAlgorithmException nsae) {
        System.err.println("No such algorithm exception: " + nsae.toString());
        return null;
    }

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

    HttpURLConnection connection = null;
    BufferedReader bufferedReader = null;
    DataOutputStream wr = null;
    try {
        connection = (HttpURLConnection) (new URL(TRADE_API_URL)).openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        connection.setRequestProperty("Content-type", "application/x-www-form-urlencoded");
        connection.setRequestProperty("Key", key);
        byte[] array = mac.doFinal(postData.getBytes("UTF-8"));
        connection.setRequestProperty("Sign", byteArrayToHexString(array));
        wr = new DataOutputStream(connection.getOutputStream());
        wr.writeBytes(postData);
        wr.flush();
        InputStream response = connection.getInputStream();
        StringBuilder sb = new StringBuilder();
        if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) {
            String line;
            bufferedReader = new BufferedReader(new InputStreamReader(response));
            while ((line = bufferedReader.readLine()) != null) {
                sb.append(line);
            }
            return new JSONObject(sb.toString());
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (connection != null) {
            connection.disconnect();
        }
        if (bufferedReader != null) {
            try {
                bufferedReader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (wr != null) {
            try {
                wr.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    return null;
}

From source file:com.profesorfalken.payzen.webservices.sdk.handler.soap.HeaderHandler.java

private static byte[] encode256(byte[] keyBytes, byte[] text)
        throws NoSuchAlgorithmException, InvalidKeyException {

    Mac hmacSha1;//from   w w  w .  jav  a2 s.  c  o m
    try {
        hmacSha1 = Mac.getInstance("HmacSHA256");
    } catch (NoSuchAlgorithmException nsae) {
        hmacSha1 = Mac.getInstance("HMAC-SHA-256");
    }
    SecretKeySpec macKey = new SecretKeySpec(keyBytes, "RAW");
    try {
        hmacSha1.init(macKey);
    } catch (java.security.InvalidKeyException ex) {
        logger.error("Error encoding auth hash", ex);
    }

    return hmacSha1.doFinal(text);
}

From source file:com.cloud.stack.CloudStackCommand.java

private String calculateRFC2104HMAC(String signIt, String secretKey) throws SignatureException {
    String result = null;//from  w  w  w  .  ja va  2 s .co  m
    try {
        SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        Mac hmacSha1 = Mac.getInstance("HmacSHA1");
        hmacSha1.init(key);
        byte[] rawHmac = hmacSha1.doFinal(signIt.getBytes());
        result = new String(Base64.encodeBase64(rawHmac));
    } catch (Exception e) {
        throw new SignatureException("Failed to generate keyed HMAC on soap request: " + e.getMessage());
    }
    return result.trim();
}

From source file:com.siphyc.utils.Utilities.java

public static String getHMACSHA256(String secret, String message) {
    try {/*from  w ww. j  a  va2  s .c  o  m*/
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(secret.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        String hash = Base64.encodeBase64String(sha256_HMAC.doFinal(message.getBytes()));
        return hash;
    } catch (Exception e) {
        System.out.println("Error");
    }
    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 ww .j  a  va 2  s  .  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:com.ironchain.common.kits.DigestKit.java

/**
 * HMAC-SHA1???, ,20.//from  w  ww. ja v  a 2 s . c  om
 * 
 * @param input
 *            
 * @param key
 *            HMAC-SHA1
 */
public static byte[] hmacSha1(byte[] input, byte[] key) {
    try {
        SecretKey secretKey = new SecretKeySpec(key, HMACSHA1);
        Mac mac = Mac.getInstance(HMACSHA1);
        mac.init(secretKey);
        return mac.doFinal(input);
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    }
}