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:org.apache.nifi.web.security.jwt.JwtServiceTest.java

private String generateHMAC(String hmacSecret, String body)
        throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
    Mac hmacSHA256 = Mac.getInstance("HmacSHA256");
    SecretKeySpec secret_key = new SecretKeySpec(hmacSecret.getBytes("UTF-8"), "HmacSHA256");
    hmacSHA256.init(secret_key);
    return Base64.encodeBase64URLSafeString(hmacSHA256.doFinal(body.getBytes("UTF-8")));
}

From source file:be.cytomine.client.HttpClient.java

public void authorize(String action, String url, String contentType, String accept) throws IOException {
    url = url.replace(host, "");
    url = url.replace("http://" + host, "");
    url = url.replace("https://" + host, "");

    TreeMap<String, String> headers = new TreeMap<String, String>();
    headers.put("accept", accept);
    headers.put("date", getActualDateStr());

    log.debug("AUTHORIZE: " + action + "\\n\\n" + contentType + "\\n" + headers.get("date") + "\n");

    String canonicalHeaders = action + "\n\n" + contentType + "\n" + headers.get("date") + "\n";

    String messageToSign = canonicalHeaders + url;

    log.debug("publicKey=" + publicKey);
    log.debug("privateKey=" + privateKey);
    log.debug("messageToSign=" + messageToSign);

    SecretKeySpec privateKeySign = new SecretKeySpec(privateKey.getBytes(), "HmacSHA1");

    try {/*ww  w  . j a  v  a  2  s .  c o m*/
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(privateKeySign);
        byte[] rawHmac = mac.doFinal(new String(messageToSign.getBytes(), "UTF-8").getBytes());

        byte[] signatureBytes = Base64.encodeBase64(rawHmac);

        String signature = new String(signatureBytes);

        String authorization = "CYTOMINE " + publicKey + ":" + signature;

        log.debug("signature=" + signature);
        log.debug("authorization=" + authorization);

        headers.put("authorization", authorization);

        for (String key : headers.keySet()) {
            addHeader(key, headers.get(key));
        }

    } catch (GeneralSecurityException e) {
        throw new IOException(e);
    }

}

From source file:org.dasein.cloud.aws.AWSCloud.java

static public byte[] HmacSHA256(String data, byte[] key) throws InternalException {

    final String algorithm = "HmacSHA256";
    Mac mac;
    try {//w ww  . j ava  2  s . co  m
        mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key, algorithm));
        return mac.doFinal(data.getBytes("UTF-8"));
    } catch (NoSuchAlgorithmException e) {
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        throw new InternalException(e);
    } catch (UnsupportedEncodingException e) {
        throw new InternalException(e);
    }
}

From source file:com.mozilla.simplepush.simplepushdemoapp.MainActivity.java

private String genSignature(UrlEncodedFormEntity body) throws IOException {
    String content = EntityUtils.toString(body);
    SecretKeySpec key = new SecretKeySpec(this.SharedSecret.getBytes("UTF-8"), "HmacSHA256");
    try {/* ww w.  ja v  a2 s  . c  o  m*/
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(key);
        byte[] bytes = mac.doFinal(content.getBytes("UTF-8"));
        return bytesToHex(bytes);
    } catch (NoSuchAlgorithmException x) {
        this.err("Invalid hash algo specified, failing " + x.toString());
        throw new IOException("HmacSHA256 unavailable");
    } catch (InvalidKeyException x) {
        this.err("Invalid key specified, failing " + x.toString());
        throw new IOException("Invalid Key");
    }
}

From source file:com.playhaven.android.req.PlayHavenRequest.java

protected String createHmac(SharedPreferences pref, String content, boolean stripEquals)
        throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeyException {
    String secret = getString(pref, Secret);
    SecretKeySpec key = new SecretKeySpec(secret.getBytes(UTF8), HMAC);
    Mac hmac = Mac.getInstance(HMAC);
    hmac.init(key);
    hmac.update(content.getBytes(UTF8));
    byte[] bytes = hmac.doFinal();
    String derived = new String(Base64.encode(bytes, Base64.URL_SAFE), UTF8).trim();
    if (stripEquals)
        derived = derived.replaceAll("=", "");

    return derived;
}

From source file:org.soyatec.windowsazure.authenticate.SharedKeyCredentials.java

private String computeMacSha(String canonicalizedString) {
    Mac mac;
    try {// w w w  .  ja v a 2s. c  om
        if (getKey() == null) {
            throw new StorageClientException(StorageErrorCode.AccountNotFound,
                    "The Windows Azure storage account credentials contains invalid values.",
                    HttpStatusConstant.DEFAULT_STATUS, null, null);
        }
        mac = Mac.getInstance(HMACSHA256);
        mac.init(new SecretKeySpec(getKey(), mac.getAlgorithm()));
        byte[] dataToMAC = canonicalizedString.getBytes(UTF8_CHARSET);
        mac.update(dataToMAC);
        byte[] result = mac.doFinal();
        return Base64.encode(result);
    } catch (NoSuchAlgorithmException e) {
        Logger.error("NoSuchAlgorithmException", e);
    } catch (InvalidKeyException e) {
        Logger.error("InvalidKeyException", e);
    } catch (UnsupportedEncodingException e) {
        Logger.error("UnsupportedEncodingException", e);
    }
    return null;
}

From source file:org.hardisonbrewing.s3j.FileSyncer.java

private byte[] hmacSHA1(String key, byte[] data) throws NoSuchAlgorithmException, InvalidKeyException {

    SecretKey secretKeySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(secretKeySpec);
    mac.update(data);/*ww w. ja  v a 2s .  com*/
    return mac.doFinal();
}

From source file:org.apache.sling.discovery.base.connectors.ping.TopologyRequestValidator.java

/**
 * Get a Mac instance for the key number.
 *
 * @param keyNo the key number./*from   w w w.j  av a 2  s .com*/
 * @return the mac instance.
 * @throws NoSuchAlgorithmException
 * @throws InvalidKeyException
 * @throws UnsupportedEncodingException
 */
private Mac getMac(int keyNo)
        throws NoSuchAlgorithmException, InvalidKeyException, UnsupportedEncodingException {
    Mac m = Mac.getInstance("HmacSHA256");
    m.init(getKey(keyNo));
    return m;
}

From source file:com.example.android.vault.VaultProvider.java

/**
 * Load our symmetric secret key and use it to derive two different data and
 * MAC keys. The symmetric secret key is stored securely on disk by wrapping
 * it with a public/private key pair, possibly backed by hardware.
 */// w ww  .  j  a v a 2s  .c o  m
private void loadOrGenerateKeys(Context context, File keyFile) throws GeneralSecurityException, IOException {
    final SecretKeyWrapper wrapper = new SecretKeyWrapper(context, TAG);

    // Generate secret key if none exists
    if (!keyFile.exists()) {
        final byte[] raw = new byte[DATA_KEY_LENGTH];
        new SecureRandom().nextBytes(raw);

        final SecretKey key = new SecretKeySpec(raw, "AES");
        final byte[] wrapped = wrapper.wrap(key);

        writeFully(keyFile, wrapped);
    }

    // Even if we just generated the key, always read it back to ensure we
    // can read it successfully.
    final byte[] wrapped = readFully(keyFile);
    final SecretKey key = wrapper.unwrap(wrapped);

    final Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(key);

    // Derive two different keys for encryption and authentication.
    final byte[] rawDataKey = new byte[DATA_KEY_LENGTH];
    final byte[] rawMacKey = new byte[MAC_KEY_LENGTH];

    System.arraycopy(mac.doFinal(BLOB_DATA), 0, rawDataKey, 0, rawDataKey.length);
    System.arraycopy(mac.doFinal(BLOB_MAC), 0, rawMacKey, 0, rawMacKey.length);

    mDataKey = new SecretKeySpec(rawDataKey, "AES");
    mMacKey = new SecretKeySpec(rawMacKey, "HmacSHA256");
}

From source file:com.flozano.socialauth.util.OAuthConsumer.java

private String getHMACSHA1(final String method, final String url, final Map<String, String> args,
        final AccessGrant token) throws Exception {

    if (config.get_consumerSecret().length() == 0) {
        throw new SignatureException("Please check consumer secret");
    }/*from   ww  w .  j a v  a 2 s .c o m*/
    boolean valid = MethodType.GET.toString().equals(method) || MethodType.PUT.toString().equals(method)
            || MethodType.POST.toString().equals(method);
    if (!valid) {
        throw new SignatureException("Invalid method type :" + method);
    }
    if (url.length() == 0) {
        throw new SignatureException("Please check URL");
    }
    String key = HttpUtil.encodeURIComponent(config.get_consumerSecret()) + "&";
    if (token != null && token.getSecret() != null) {
        key += HttpUtil.encodeURIComponent(token.getSecret());
    }
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes("UTF-8"), "HMAC-SHA1");

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

        String data = HttpUtil.encodeURIComponent(method) + "&" + HttpUtil.encodeURIComponent(url) + "&"
                + HttpUtil.encodeURIComponent(HttpUtil.buildParams(args));
        LOG.debug("Signature data : " + data);
        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));

        // base64-encode the hmac
        LOG.debug("Encoding raw HMAC to Base64");
        String sig = Base64.encodeBytes(rawHmac);

        return sig;
    } catch (Exception e) {
        throw new SignatureException("Unable to generate HMAC-SHA1", e);
    }
}