Example usage for javax.crypto Mac init

List of usage examples for javax.crypto Mac init

Introduction

In this page you can find the example usage for javax.crypto Mac init.

Prototype

public final void init(Key key) throws InvalidKeyException 

Source Link

Document

Initializes this Mac object with the given key.

Usage

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;//from   w  ww .j  av a 2 s  .  co m
        } 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: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();//w w w. ja  v a 2  s  . co  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:mitm.application.djigzo.james.PortalInvitationValidator.java

private Mac createMAC(String key) throws ValidatorException {
    SecurityFactory securityFactory = SecurityFactoryFactory.getSecurityFactory();

    try {/* w w  w  .  j a  v a2s  . com*/
        Mac mac = securityFactory.createMAC(algorithm);

        SecretKeySpec keySpec = new SecretKeySpec(MiscStringUtils.toUTF8Bytes(key), "raw");

        mac.init(keySpec);

        return mac;
    } catch (NoSuchAlgorithmException e) {
        throw new ValidatorException(e);
    } catch (NoSuchProviderException e) {
        throw new ValidatorException(e);
    } catch (InvalidKeyException e) {
        throw new ValidatorException(e);
    }
}

From source file:org.davidmendoza.fileUpload.web.VideoController.java

private String sign(String toSign)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    Mac hmac = Mac.getInstance("HmacSHA1");
    hmac.init(new SecretKeySpec(awsSecretKey.getBytes("UTF-8"), "HmacSHA1"));

    String signature = DatatypeConverter.printBase64Binary(hmac.doFinal(toSign.getBytes("UTF-8")))
            .replaceAll("\n", "");

    return signature;
}

From source file:org.apache.hadoop.security.AccessTokenHandler.java

/** Initialize Mac function */
private synchronized void initMac(AccessKey key) throws IOException {
    try {/* ww w  .  j  a  v a  2 s.c  om*/
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(new SecretKeySpec(key.getKey().getBytes(), "HmacSHA1"));
        key.setMac(mac);
    } catch (GeneralSecurityException e) {
        throw (IOException) new IOException("Failed to initialize Mac for access key, keyID=" + key.getKeyID())
                .initCause(e);
    }
}

From source file:org.midonet.api.auth.cloudstack.CloudStackClient.java

private String generateBase64Sha1Digest(String command) throws CloudStackClientException {

    try {//w w  w. ja  v a2s . c o  m
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secret_key = new SecretKeySpec(secretKey.getBytes(), "HmacSHA1");
        mac.init(secret_key);
        byte[] digest = mac.doFinal(command.getBytes());
        return new String(Base64.encodeBase64(digest));
    } catch (NoSuchAlgorithmException e) {
        throw new CloudStackClientException("No algorithm found to do SHA-1: " + command, e);
    } catch (InvalidKeyException e) {
        throw new CloudStackClientException("Invalid secret key: " + secretKey, e);
    }
}

From source file:nl.nn.adapterframework.pipes.HashPipe.java

public PipeRunResult doPipe(Object input, IPipeLineSession session) throws PipeRunException {
    String message = (String) input;

    String authAlias = getAuthAlias();
    String secret = getSecret();/*ww w.  j  a v a 2s.co m*/
    try {
        ParameterList parameterList = getParameterList();
        ParameterResolutionContext prc = new ParameterResolutionContext(message, session);
        ParameterValueList pvl = prc.getValues(parameterList);
        if (pvl != null) {
            Parameter authAliasParam = parameterList.findParameter("authAlias");
            if (authAliasParam != null)
                authAlias = (String) authAliasParam.getValue(pvl, prc);

            Parameter secretParam = parameterList.findParameter("secret");
            if (secretParam != null)
                secret = (String) secretParam.getValue(pvl, prc);
        }
    } catch (Exception e) {
        throw new PipeRunException(this, getLogPrefix(session) + "exception extracting authAlias", e);
    }

    CredentialFactory accessTokenCf = new CredentialFactory(authAlias, "", secret);
    String cfSecret = accessTokenCf.getPassword();

    if (cfSecret == null || cfSecret.isEmpty())
        throw new PipeRunException(this, getLogPrefix(session) + "empty secret, unable to hash");

    try {
        Mac mac = Mac.getInstance(getAlgorithm());

        SecretKeySpec secretkey = new SecretKeySpec(cfSecret.getBytes(getEncoding()), "algorithm");
        mac.init(secretkey);

        String hash = Base64.encodeBase64String(mac.doFinal(message.getBytes()));
        return new PipeRunResult(getForward(), hash);
    } catch (Exception e) {
        throw new PipeRunException(this, getLogPrefix(session) + "error creating hash", e);
    }
}

From source file:ch.icclab.cyclops.client.CloudStackAuth.java

/**
 * Simple SHA1 implementation with Base64 encoding of message
 *
 * @param query header to be signed/*w  ww.  j a va  2  s  .c  o m*/
 * @return signed string
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 */
private String signRequest(String query)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    logger.trace("Signing the CloudStack API query");

    Mac sha1_HMAC = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(apiConnection.getCloudStackSecretKey().getBytes(), "HmacSHA1");
    sha1_HMAC.init(secret);

    // now sign it and return Base64 representation
    String signature = Base64.encodeBase64String(sha1_HMAC.doFinal(query.getBytes()));

    return URLEncoder.encode(signature, "UTF-8");
}

From source file:com.googlesource.gerrit.plugins.github.notification.WebhookServlet.java

/**
 * Calculates the expected signature of the payload
 *
 * @param payload payload to calculate a signature for
 * @return signature of the payload/*from   ww w  . ja  va 2  s. co m*/
 * @see <a href=
 *      "https://developer.github.com/webhooks/securing/#validating-payloads-from-github">
 *      Validating payloads from GitHub</a>
 */
private byte[] getExpectedSignature(byte[] payload) {
    SecretKeySpec key = new SecretKeySpec(config.webhookSecret.getBytes(), HMAC_SHA1_ALGORITHM);
    Mac hmac;
    try {
        hmac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        hmac.init(key);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException("Hmac SHA1 must be supported", e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException("Hmac SHA1 must be compatible to Hmac SHA1 Secret Key", e);
    }
    return hmac.doFinal(payload);
}

From source file:com.quantil.http.HttpProcessor.java

private String createKey() throws Exception {

    SimpleDateFormat formatter;//from   w w w  .  j a  v  a 2 s  . c  o  m

    formatter = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z");

    currentDate = formatter.format(new Date());

    SecretKeySpec signingKey = new SecretKeySpec(pass.getBytes(), "HmacSHA1");

    // get an hmac_sha1 Mac instance and initialize with the signing key
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signingKey);

    // compute the hmac on input data bytes
    byte[] rawHmac = mac.doFinal(currentDate.getBytes());
    Base64 b64 = new Base64();
    String pas = user + ":" + new String(b64.encode(rawHmac), "UTF-8");

    return new String(b64.encode(pas.getBytes()), "UTF-8");
}