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.jenkinsci.plugins.karotz.KarotzUtil.java

/**
 * Creates HmacSha1.//from w  w w.  j av a2  s.  c  o  m
 *
 * @param secretKey SecretKey
 * @param data target data
 * @return HmacSha1
 * @throws KarotzException Illegal encoding.
 */
public static String doHmacSha1(String secretKey, String data) throws KarotzException {
    String hmacSha1;
    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec secret = new SecretKeySpec(secretKey.getBytes("ASCII"), "HmacSHA1");
        mac.init(secret);
        byte[] digest = mac.doFinal(data.getBytes("UTF-8"));
        hmacSha1 = new String(Base64.encodeBase64(digest), "ASCII");
    } catch (IllegalStateException e) {
        throw new KarotzException(e);
    } catch (InvalidKeyException e) {
        throw new KarotzException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new KarotzException(e);
    } catch (UnsupportedEncodingException e) {
        throw new KarotzException(e);
    }

    return hmacSha1;
}

From source file:com.the_incognito.darry.incognitochatmessengertest.BouncyCastleImplementation.java

public static boolean isValid(String plainText, String HMAC, String key) {
    try {/*from   w w  w  .j a v  a  2s .  c o  m*/
        System.out.println("HMAC on = " + plainText);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256",
                new BouncyCastleProvider());
        char password[] = key.toCharArray();
        byte salt[] = "salt".getBytes();
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "HmacSHA256");
        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider());
        mac.init(secret);
        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(plainText.getBytes());
        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);

        //  Covert array of Hex bytes to a String
        String check = new String(hexBytes, "UTF-8");
        System.out.println("Checking = " + check);
        return check.equals(HMAC);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.the_incognito.darry.incognitochatmessengertest.BouncyCastleImplementation.java

public static String hmacSha256(String key, String value) {
    try {/*  www  .  j a va 2s.  co  m*/
        //System.out.println(Base64.getEncoder().encodeToString(keyBytes));
        // Get an hmac_sha256 key from the raw key bytes
        System.out.println("First HMAC on = " + value);
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256",
                new BouncyCastleProvider());
        char password[] = key.toCharArray();
        byte salt[] = "salt".getBytes();
        KeySpec spec = new PBEKeySpec(password, salt, 65536, 256);
        SecretKey tmp = factory.generateSecret(spec);
        SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "HmacSHA256");

        // Get an hmac_sha256 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA256", new BouncyCastleProvider());
        mac.init(secret);

        // Compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(value.getBytes());

        // Convert raw bytes to Hex
        byte[] hexBytes = new Hex().encode(rawHmac);
        //  Covert array of Hex bytes to a String
        return new String(hexBytes, "UTF-8");
    } catch (Exception e) {
        throw new RuntimeException(e);
    }

}

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);
    byte[] result = mac.doFinal(message.getBytes());

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

From source file:main.java.com.amazonaws.cognito.devauthsample.Utilities.java

public static String sign(String content, String key) {
    try {//w  w w  . ja v  a 2 s  . co  m
        byte[] data = content.getBytes(Constants.ENCODING_FORMAT);
        Mac mac = Mac.getInstance(Constants.SIGNATURE_METHOD);
        mac.init(new SecretKeySpec(key.getBytes(Constants.ENCODING_FORMAT), Constants.SIGNATURE_METHOD));
        char[] signature = Hex.encodeHex(mac.doFinal(data));
        return new String(signature);
    } catch (Exception e) {
        log.log(Level.SEVERE, "Exception during sign", e);
    }
    return null;
}

From source file:org.apache.hadoop.mapred.PriorityAuthorization.java

/**
 * Adapted from AWS Query Authentication cookbook:
 * Computes RFC 2104-compliant HMAC signature.
 *
 * @param data//from w w w.  jav a2s.  c om
 *     The data to be signed.
 * @param key
 *     The signing key.
 * @return
 *     The base64-encoded RFC 2104-compliant HMAC signature.
 * @throws
 *     java.security.SignatureException when signature generation fails
 */
public static String hmac(String data, String key) throws java.security.SignatureException {
    String result;
    try {
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), 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());

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

From source file:kcb.billerengine.utils.Utils.java

public static String computeToken(String key, String data) {
    String token = null;/*from  w  w w . j a va 2 s. c  o  m*/
    try {
        SecretKey secretKey = null;
        byte[] keyBytes = key.getBytes("UTF-8");
        Mac mac = Mac.getInstance("HMACSHA256");
        secretKey = new SecretKeySpec(keyBytes, mac.getAlgorithm());
        mac.init(secretKey);
        byte[] text = data.getBytes("UTF-8");
        byte[] encodedText = mac.doFinal(text);

        token = new String(Base64.encodeBase64(encodedText)).trim();
    } catch (UnsupportedEncodingException | InvalidKeyException | NoSuchAlgorithmException ex) {
        LOG.error("ComputeToken error : " + ex);
    }

    return token;
}

From source file:com.cloud.sample.UserCloudAPIExecutor.java

/**
 * 1. Signs a string with a secret key using SHA-1 2. Base64 encode the result 3. URL encode the final result
 * //  w ww.  j  av  a 2s  .  c  om
 * @param request
 * @param key
 * @return
 */
public static String signRequest(String request, String key) {
    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(request.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        return URLEncoder.encode(Base64.encodeBase64String(encryptedBytes), "UTF-8");
    } catch (Exception ex) {
        System.out.println(ex);
    }
    return null;
}

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.  co  m

    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//from w w w  . j av a 2 s .  c o m
 * @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);
    }
}