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.artifactory.repo.remote.browse.S3RepositorySecuredHelper.java

private static String signWithHmacSha1(String awsSecretKey, String canonicalString) throws Exception {
    try {//from w  ww .  j  a va  2  s. c o 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:org.brunocvcunha.instagram4j.util.InstagramHashUtil.java

/**
 * Generate a Hmac SHA-256 hash//from  w  w  w  .  j  a v  a 2 s  . c o  m
 * @param key key
 * @param string value
 * @return hashed
 */
public static String generateHash(String key, String string) {
    SecretKeySpec object = new SecretKeySpec(key.getBytes(), "HmacSHA256");
    try {
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init((Key) object);
        byte[] byteArray = mac.doFinal(string.getBytes("UTF-8"));
        return new String(new Hex().encode(byteArray), "ISO-8859-1");
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

From source file:net.foreworld.util.RestUtil.java

public static String genSignature(String data, String key) {
    byte[] byteHMAC = null;
    try {/* w  w  w . ja  va 2  s.com*/
        Mac mac = Mac.getInstance(ALGORITHM);
        SecretKeySpec spec = new SecretKeySpec(key.getBytes(), ALGORITHM);
        mac.init(spec);
        byteHMAC = mac.doFinal(data.toLowerCase(Locale.getDefault()).getBytes());
    } catch (InvalidKeyException ignore) {
        return null;
    } catch (NoSuchAlgorithmException ignore) {
        return null;
    } // END

    if (null == byteHMAC)
        return null;

    // String code = new BASE64Encoder().encode(byteHMAC);
    String code = Base64.encodeBase64String(byteHMAC);

    try {
        return URLEncoder.encode(code, ENC);
    } catch (UnsupportedEncodingException ignore) {
    }
    return null;
}

From source file:org.apache.hadoop.security.token.SecretManager.java

/**
 * Compute HMAC of the identifier using the secret key and return the 
 * output as password//  w w  w .  j  a v  a  2s  .  com
 * @param identifier the bytes of the identifier
 * @param key the secret key
 * @return the bytes of the generated password
 */
protected static byte[] createPassword(byte[] identifier, SecretKey key) {
    Mac mac = threadLocalMac.get();
    try {
        mac.init(key);
    } catch (InvalidKeyException ike) {
        throw new IllegalArgumentException("Invalid key to HMAC computation", ike);
    }
    return mac.doFinal(identifier);
}

From source file:com.alibaba.openapi.client.util.SignatureUtil.java

public static byte[] hmacSha1(String[] datas, SecretKeySpec signingKey) {
    Mac mac;
    try {/*from w  w w.  j av a2 s.  co  m*/
        mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    for (String data : datas) {
        mac.update(data.getBytes(CHARSET_UTF8));
    }
    return mac.doFinal();
}

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

public static String sign(String content, String key) {
    try {// w w  w . j  a va 2 s  .com
        byte[] data = content.getBytes(ENCODING_FORMAT);
        Mac mac = Mac.getInstance(SIGNATURE_METHOD);
        mac.init(new SecretKeySpec(key.getBytes(ENCODING_FORMAT), 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:com.miyue.util.Cryptos.java

/**
 * HMAC-SHA1???, ,20./* w w w  . ja  v  a 2 s  .c o m*/
 * 
 * @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 Exceptions.unchecked(e);
    }
}

From source file:com.alibaba.openapi.client.util.SignatureUtil.java

public static byte[] hmacSha1(String path, List<NameValuePair> parameters, SecretKeySpec signingKey) {
    Mac mac;
    try {//from w ww. ja v  a  2 s  . c  om
        mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    mac.update(path.getBytes(CHARSET_UTF8));
    Collections.sort(parameters, new NameValuePairComparator<NameValuePair>());
    for (NameValuePair parameter : parameters) {
        mac.update(parameter.getName().getBytes(CHARSET_UTF8));
        mac.update(parameter.getValue().getBytes(CHARSET_UTF8));
    }
    return mac.doFinal();
}

From source file:com.alibaba.openapi.client.util.SignatureUtil.java

public static byte[] hmacSha1(byte[] data, SecretKeySpec signingKey) {
    Mac mac = null;
    try {/*from   w w w . ja va2  s .c o  m*/
        mac = Mac.getInstance(HMAC_SHA1);
        mac.init(signingKey);
    } catch (NoSuchAlgorithmException e) {
        throw new IllegalStateException(e.getMessage(), e);
    } catch (InvalidKeyException e) {
        throw new IllegalStateException(e.getMessage(), e);
    }
    return mac.doFinal(data);
}

From source file:Main.java

public static String completeJweFromSIM(String jweSIM) {
    // android.os.Debug.waitForDebugger();

    try {//from   w w  w .j  a  va 2s. c  o  m
        if (jweSIM != null && jweSIM.length() > 0) {
            String parts[] = jweSIM.split("\\.");
            ;
            if (parts != null && parts.length == 5) {
                // retrieve hmac key
                byte hmac_key[] = Base64.decode(parts[4], Base64.URL_SAFE);
                if (hmac_key != null && hmac_key.length == 16) {
                    // init hash instance
                    Mac hmac = Mac.getInstance("HmacSHA256", "SC");
                    hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));

                    byte[] aad = parts[0].getBytes();
                    long al = aad.length * 8;
                    byte[] iv_key = decodeB64(parts[2]);
                    byte[] cryptedBytes = decodeB64(parts[3]);

                    // build data to hash
                    byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8];
                    int offset = 0;
                    System.arraycopy(aad, offset, hmacData, 0, aad.length);
                    offset += aad.length;
                    System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length);
                    offset += iv_key.length;
                    System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length);
                    offset += cryptedBytes.length;
                    ByteBuffer buffer = ByteBuffer.allocate(8);
                    buffer.putLong(al);
                    System.arraycopy(buffer.array(), 0, hmacData, offset, 8);

                    // compute hac value
                    byte[] hmacValue = hmac.doFinal(hmacData);
                    // authentication tag
                    byte[] auth_tag = Arrays.copyOf(hmacValue, 16);
                    String auth_tag64 = encodeB64(auth_tag);

                    // A.2.7. Complete Representation
                    String finalString = parts[0] + "." + parts[1] + "." + parts[2] + "." + parts[3] + "."
                            + auth_tag64;

                    //                  // just for verification
                    //                  byte jwt64 [] = decryptJWE(finalString, RsaKeyTim.privRsaKey);
                    //                  if(jwt64!=null) {
                    //                     String jws = new String(jwt64);
                    //                     Log.d("completeJweFromSIM", "jws verify Key TIM :"+verifyJWS(jws,RsaKeyTim.pubRsaKey));
                    //                  }

                    return finalString;
                }
            }
            // 
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}