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.auditmark.jscrambler.client.JScrambler.java

private String generateHMACSignature(String requestMethod, String resourcePath, Map<String, String> params)
        throws InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
    String data = hmacSignatureData(requestMethod, resourcePath, apiHost, params);
    try {/*w  w w .  j  a  va2  s. c  o m*/
        SecretKeySpec signingKey = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(signingKey);
        byte[] digest = mac.doFinal(data.getBytes());
        return new sun.misc.BASE64Encoder().encode(digest);

    } catch (InvalidKeyException e) {
        System.err.println("Invalid key: " + e.getMessage());
        throw e;
    } catch (NoSuchAlgorithmException e) {
        System.err.println("No such algorithm: " + e.getMessage());
        throw e;
    }
}

From source file:org.apache.myfaces.shared.util.StateUtils.java

public static byte[] encrypt(byte[] insecure, ExternalContext ctx) {

    if (ctx == null) {
        throw new NullPointerException("ExternalContext ctx");
    }/*w  w  w . jav a 2  s.c o m*/

    testConfiguration(ctx);

    SecretKey secretKey = (SecretKey) getSecret(ctx);
    String algorithm = findAlgorithm(ctx);
    String algorithmParams = findAlgorithmParams(ctx);
    byte[] iv = findInitializationVector(ctx);

    SecretKey macSecretKey = (SecretKey) getMacSecret(ctx);
    String macAlgorithm = findMacAlgorithm(ctx);

    try {
        // keep local to avoid threading issue
        Mac mac = Mac.getInstance(macAlgorithm);
        mac.init(macSecretKey);
        Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams);
        if (iv != null) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        }
        if (log.isLoggable(Level.FINE)) {
            log.fine("encrypting w/ " + algorithm + "/" + algorithmParams);
        }

        //EtM Composition Approach
        int macLenght = mac.getMacLength();
        byte[] secure = new byte[cipher.getOutputSize(insecure.length) + macLenght];
        int secureCount = cipher.doFinal(insecure, 0, insecure.length, secure);
        mac.update(secure, 0, secureCount);
        mac.doFinal(secure, secureCount);

        return secure;
    } catch (Exception e) {
        throw new FacesException(e);
    }
}

From source file:org.apache.myfaces.shared_ext202patch.util.StateUtils.java

public static byte[] encrypt(byte[] insecure, ExternalContext ctx) {

    if (ctx == null)
        throw new NullPointerException("ExternalContext ctx");

    testConfiguration(ctx);/*from   w w w  .  j  av  a 2 s .  co m*/

    SecretKey secretKey = (SecretKey) getSecret(ctx);
    String algorithm = findAlgorithm(ctx);
    String algorithmParams = findAlgorithmParams(ctx);
    byte[] iv = findInitializationVector(ctx);

    SecretKey macSecretKey = (SecretKey) getMacSecret(ctx);
    String macAlgorithm = findMacAlgorithm(ctx);

    try {
        // keep local to avoid threading issue
        Mac mac = Mac.getInstance(macAlgorithm);
        mac.init(macSecretKey);
        Cipher cipher = Cipher.getInstance(algorithm + "/" + algorithmParams);
        if (iv != null) {
            IvParameterSpec ivSpec = new IvParameterSpec(iv);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
        } else {
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        }
        if (log.isLoggable(Level.FINE)) {
            log.fine("encrypting w/ " + algorithm + "/" + algorithmParams);
        }

        //EtM Composition Approach
        int macLenght = mac.getMacLength();
        byte[] secure = new byte[cipher.getOutputSize(insecure.length) + macLenght];
        int secureCount = cipher.doFinal(insecure, 0, insecure.length, secure);
        mac.update(secure, 0, secureCount);
        mac.doFinal(secure, secureCount);

        return secure;
    } catch (Exception e) {
        throw new FacesException(e);
    }
}

From source file:org.dasein.cloud.azure.AzureStorageMethod.java

private String calculatedSharedKeyLiteSignature(@Nonnull HttpRequestBase method,
        @Nonnull Map<String, String> queryParams) throws CloudException, InternalException {
    fetchKeys();/*from ww w  .ja  va2 s  .  co  m*/

    ProviderContext ctx = provider.getContext();

    if (ctx == null) {
        throw new AzureConfigException("No context was specified for this request");
    }
    Header h = method.getFirstHeader("content-type");
    String contentType = (h == null ? null : h.getValue());

    if (contentType == null) {
        contentType = "";
    }
    StringBuilder stringToSign = new StringBuilder();

    stringToSign.append(method.getMethod().toUpperCase()).append("\n");
    stringToSign.append("\n"); // content-md5
    stringToSign.append(contentType).append("\n");
    stringToSign.append(method.getFirstHeader("date").getValue()).append("\n");

    Header[] headers = method.getAllHeaders();
    TreeSet<String> keys = new TreeSet<String>();

    for (Header header : headers) {
        if (header.getName().startsWith(Header_Prefix_MS)) {
            keys.add(header.getName().toLowerCase());
        }
    }

    for (String key : keys) {
        Header header = method.getFirstHeader(key);

        if (header != null) {
            Header[] all = method.getHeaders(key);

            stringToSign.append(key.toLowerCase().trim()).append(":");
            if (all != null && all.length > 0) {
                for (Header current : all) {
                    String v = (current.getValue() != null ? current.getValue() : "");

                    stringToSign.append(v.trim().replaceAll("\n", " ")).append(",");
                }
            }
            stringToSign.deleteCharAt(stringToSign.lastIndexOf(","));
        } else {
            stringToSign.append(key.toLowerCase().trim()).append(":");
        }
        stringToSign.append("\n");
    }

    stringToSign.append("/").append(getStorageAccount()).append(method.getURI().getPath());

    keys.clear();
    for (String key : queryParams.keySet()) {
        if (key.equalsIgnoreCase("comp")) {
            key = key.toLowerCase();
            keys.add(key);
        }
    }
    if (!keys.isEmpty()) {
        stringToSign.append("?");
        for (String key : keys) {
            String value = queryParams.get(key);

            if (value == null) {
                value = "";
            }
            stringToSign.append(key).append("=").append(value).append("&");
        }
        stringToSign.deleteCharAt(stringToSign.lastIndexOf("&"));
    }
    try {
        if (logger.isDebugEnabled()) {
            logger.debug("BEGIN STRING TO SIGN");
            logger.debug(stringToSign.toString());
            logger.debug("END STRING TO SIGN");
        }
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(new SecretKeySpec(Base64.decodeBase64(ctx.getStoragePrivate()), "HmacSHA256"));

        String signature = new String(
                Base64.encodeBase64(mac.doFinal(stringToSign.toString().getBytes("UTF-8"))));

        if (logger.isDebugEnabled()) {
            logger.debug("signature=" + signature);
        }
        return signature;
    } catch (UnsupportedEncodingException e) {
        logger.error("UTF-8 not supported: " + e.getMessage());
        throw new InternalException(e);
    } catch (NoSuchAlgorithmException e) {
        logger.error("No such algorithm: " + e.getMessage());
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        logger.error("Invalid key: " + e.getMessage());
        throw new InternalException(e);
    }
}

From source file:org.dasein.cloud.terremark.Terremark.java

private static String sign(byte[] key, String authString, String algorithm) throws InternalException {
    try {//from  www . j a v  a2  s.com
        Mac mac = Mac.getInstance(algorithm);

        mac.init(new SecretKeySpec(key, algorithm));
        return new String(Base64.encodeBase64(mac.doFinal(authString.getBytes("utf-8"))));
    } catch (NoSuchAlgorithmException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    } catch (IllegalStateException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
}

From source file:com.example.android.hawifi.MainActivity.java

public boolean throwCmd(String command) {
    final Charset asciiCs = Charset.forName("US-ASCII");
    long nonce = myTime();
    String HMAC_PASS = "password";
    String HMAC_KEY = "key";
    //String beforeHmac = "The quick brown fox jumps over the lazy dog";
    String beforeHmac = "/" + HMAC_PASS + "/" + command + "/" + nonce + "/";
    String result = "";
    try {//  ww w. j a  v  a  2 s  .c om
        final Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        final SecretKeySpec secret_key = new javax.crypto.spec.SecretKeySpec(asciiCs.encode(HMAC_KEY).array(),
                "HmacSHA256");
        sha256_HMAC.init(secret_key);
        final byte[] mac_data = sha256_HMAC.doFinal(asciiCs.encode(beforeHmac).array());
        for (final byte element : mac_data) {
            result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);
        }
    } catch (Exception e) {
        if (D)
            Log.e(TAG, "Crypto Exception");
    }

    DownloadTask dt;
    String url = null;
    if (((RadioButton) findViewById(R.id.radioButton0)).isChecked())
        url = myUrls[0].url;
    else if (((RadioButton) findViewById(R.id.radioButton1)).isChecked())
        url = myUrls[1].url;
    else if (((RadioButton) findViewById(R.id.radioButton2)).isChecked())
        url = myUrls[2].url;
    else if (((RadioButton) findViewById(R.id.radioButton3)).isChecked())
        url = myUrls[3].url;
    else if (((RadioButton) findViewById(R.id.radioButton4)).isChecked())
        url = myUrls[4].url;
    if (url != null) {
        //new DownloadTask().execute(url + command + "/" + nonce + "/" + result);
        dt = new DownloadTask();
        dt.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, url + command + "/" + nonce + "/" + result);
    }
    Log.e(TAG, url + command);
    return true;
}

From source file:org.apache.nifi.processors.standard.util.crypto.scrypt.Scrypt.java

/**
 * Implementation of PBKDF2 (RFC2898).//from   w ww.j a va 2  s .  co  m
 *
 * @param alg   the HMAC algorithm to use
 * @param p     the password
 * @param s     the salt
 * @param c     the iteration count
 * @param dkLen the intended length, in octets, of the derived key
 * @return The derived key
 */
private static byte[] pbkdf2(String alg, byte[] p, byte[] s, int c, int dkLen) throws GeneralSecurityException {
    Mac mac = Mac.getInstance(alg);
    mac.init(new SecretKeySpec(p, alg));
    byte[] dk = new byte[dkLen];
    pbkdf2(mac, s, c, dk, dkLen);
    return dk;
}

From source file:es.onebox.rest.utils.service.QueryService.java

/**
 * Signs a string with the given key./*from  w w  w  .j a va  2s.co  m*/
 *
 * @param data
 * @param key
 * @return
 * @throws SignatureException
 */
private String generate_HMAC_SHA1_Signature(String data, String key) throws SignatureException {
    String result;

    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(UTF_8), HMAC_SHA1_ALGORITHM);

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

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(data.getBytes(UTF_8));
        byte[] base64 = Base64.encodeBase64(rawHmac);

        // base64-encode the hmac
        result = new String(base64);
    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }

    return AUTHORIZATION_HEADER_HMAC_PREFIX + result;
}

From source file:com.diversityarrays.dalclient.DalUtil.java

/**
 * Calculate an RFC 2104 compliant HMAC signature.
 * @param key is the signing key/*from  ww w .jav  a  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(cryptCharsetName);
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, ALGORITHM_HMAC_SHA1);

        Mac mac = Mac.getInstance(ALGORITHM_HMAC_SHA1);
        mac.init(signingKey);

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

        byte[] hexBytes = new Hex().encode(rawHmac);

        return new String(hexBytes, cryptCharsetName);

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(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 {//w w w. j a v  a 2  s.  com
        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");
    }
}