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:edu.internet2.middleware.openid.security.SecurityUtils.java

/**
 * Calculate signature for specified data using an Association.
 * /*from w  w w.  j a va 2  s.  co m*/
 * @param association association
 * @param data data to calculate signature for
 * @return calculated signature
 * @throws SecurityException if unable to calculate the signature
 */
public static String calculateSignature(Association association, String data) throws SecurityException {
    log.debug("calculating signature using association: {}", association.getHandle());
    log.debug("signature data = {}", data);

    try {
        Mac mac = Mac.getInstance(association.getMacKey().getAlgorithm());
        mac.init(association.getMacKey());

        byte[] rawHmac = mac.doFinal(data.getBytes());
        return new String(Base64.encodeBase64(rawHmac));
    } catch (InvalidKeyException e) {
        log.error("Unable to generate MAC - " + e.getMessage());
        throw new SecurityException("Unable to generate MAC", e);
    } catch (NoSuchAlgorithmException e) {
        log.error("Unable to generate MAC - " + e.getMessage());
        throw new SecurityException("Unable to generate MAC", e);
    }
}

From source file:no.digipost.android.authentication.OAuth.java

private static String encryptHmacSHA256(final String data) {
    SecretKeySpec secretKey = new SecretKeySpec(Secret.CLIENT_SECRET.getBytes(),
            ApplicationConstants.HMACSHA256);
    Mac mac = null;
    try {//  w ww. j  a v  a2 s. c  o  m
        mac = Mac.getInstance(ApplicationConstants.HMACSHA256);
        mac.init(secretKey);
    } catch (Exception e) {
        // Ignore
    }

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

    return new String(hmacData);
}

From source file:com.amazonaws.tvm.Utilities.java

public static String sign(String content, String key) {
    try {//  w ww. j a v a  2  s. c o  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 exception) {
        log.log(Level.SEVERE, "Exception during sign", exception);
    }
    return null;
}

From source file:Main.java

private static String generateSignature(String base, String type, String nonce, String timestamp, String token,
        String tokenSecret, String verifier, ArrayList<String> parameters)
        throws NoSuchAlgorithmException, InvalidKeyException {
    String encodedBase = Uri.encode(base);

    StringBuilder builder = new StringBuilder();

    //Create an array of all the parameters
    //So that we can sort them
    //OAuth requires that we sort all parameters
    ArrayList<String> sortingArray = new ArrayList<String>();

    sortingArray.add("oauth_consumer_key=" + oauthConsumerKey);
    sortingArray.add("oauth_nonce=" + nonce);
    sortingArray.add("oauth_signature_method=HMAC-SHA1");
    sortingArray.add("oauth_timestamp=" + timestamp);
    sortingArray.add("oauth_version=1.0");

    if (parameters != null) {
        sortingArray.addAll(parameters);
    }/*  w  ww  . j  av  a  2  s . c  om*/

    if (token != "" && token != null) {
        sortingArray.add("oauth_token=" + token);
    }
    if (verifier != "" && verifier != null) {
        sortingArray.add("oauth_verifier=" + verifier);
    }

    Collections.sort(sortingArray);

    //Append all parameters to the builder in the right order
    for (int i = 0; i < sortingArray.size(); i++) {
        if (i > 0)
            builder.append("&" + sortingArray.get(i));
        else
            builder.append(sortingArray.get(i));

    }

    String params = builder.toString();
    //Percent encoded the whole url
    String encodedParams = Uri.encode(params);

    String completeUrl = type + "&" + encodedBase + "&" + encodedParams;

    String completeSecret = oauthSecretKey;

    if (tokenSecret != null && tokenSecret != "") {
        completeSecret = completeSecret + "&" + tokenSecret;
    } else {
        completeSecret = completeSecret + "&";
    }

    Log.v("Complete URL: ", completeUrl);
    Log.v("Complete Key: ", completeSecret);

    Mac mac = Mac.getInstance("HmacSHA1");
    SecretKeySpec secret = new SecretKeySpec(completeSecret.getBytes(), mac.getAlgorithm());
    mac.init(secret);
    byte[] sig = mac.doFinal(completeUrl.getBytes());

    String signature = Base64.encodeToString(sig, 0);
    signature = signature.replace("+", "%2b"); //Specifically encode all +s to %2b

    return signature;
}

From source file:Main.java

private static void derivePKCS5S2Helper(Mac hMac, byte[] P, byte[] S, int c, byte[] iBuf, byte[] out,
        int outOff) throws GeneralSecurityException {
    byte[] state = new byte[hMac.getMacLength()];
    SecretKeySpec param = new SecretKeySpec(P, "SHA1");
    hMac.init(param);
    if (S != null) {
        hMac.update(S, 0, S.length);//from www.  jav  a  2 s  .c o m
    }
    hMac.update(iBuf, 0, iBuf.length);
    hMac.doFinal(state, 0);
    System.arraycopy(state, 0, out, outOff, state.length);
    if (c == 0) {
        throw new IllegalArgumentException("iteration count must be at least 1.");
    }
    for (int count = 1; count < c; count++) {
        hMac.init(param);
        hMac.update(state, 0, state.length);
        hMac.doFinal(state, 0);
        for (int j = 0; j != state.length; j++) {
            out[outOff + j] ^= state[j];
        }
    }
}

From source file:com.amazon.pay.impl.Util.java

/**
 * Helper method to calculate base64 encoded signature using specified secret key
 *
 *//*w w  w. j a  v  a  2  s  . c  o m*/
public static String getSignature(String stringToSign, String secretKey) throws IllegalStateException,
        InvalidKeyException, NoSuchAlgorithmException, UnsupportedEncodingException {
    Mac mac = Mac.getInstance("HmacSHA256");
    mac.init(new SecretKeySpec(secretKey.getBytes("UTF-8"), "HmacSHA256"));
    byte[] signature = mac.doFinal(stringToSign.getBytes("UTF-8"));
    String signatureBase64 = new String(Base64.encodeBase64(signature), "UTF-8");
    return signatureBase64;
}

From source file:com.annuletconsulting.homecommand.node.AsyncSend.java

/**
 * Creates the signature from the timestamp using the sharedKey.  This same method will be used
 * on the server and the results compared to authenticate the request.
 * /*w w w .j  av a 2s .co m*/
 * @param timeStamp
 * @return
 */
private static String getSignature(String timeStamp) {
    if (sharedKey != null)
        try {
            byte[] data = timeStamp.getBytes(ENCODING_FORMAT);
            Mac mac = Mac.getInstance(SIGNATURE_METHOD);
            mac.init(new SecretKeySpec(sharedKey.getBytes(ENCODING_FORMAT), SIGNATURE_METHOD));
            char[] signature = Hex.encodeHex(mac.doFinal(data));
            return new String(signature);
        } catch (Exception exception) {
            exception.printStackTrace();
        }
    return "Error in getSignature()";
}

From source file:jp.co.opentone.bsol.linkbinder.util.ValueFormatter.java

/**
 * ??SHA256???/*  www.  j av  a2s  . co  m*/
 * @param value ??
 * @param key 
 * @return ??
 */
public static String formatValueToHash(String value, String key) {
    byte[] result;
    try {
        SecretKeySpec sk = new SecretKeySpec(key.getBytes("UTF-8"), "HmacSHA256");
        Mac mac = Mac.getInstance("HmacSHA256");
        mac.init(sk);
        result = mac.doFinal(value.getBytes("UTF-8"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
    return new String(Hex.encodeHex(result));

}

From source file:org.jahia.security.TOTP.java

private static int verify_code(byte[] key, long t) throws NoSuchAlgorithmException, InvalidKeyException {
    byte[] data = new byte[8];
    long value = t;
    for (int i = 8; i-- > 0; value >>>= 8) {
        data[i] = (byte) value;
    }//from  w  w w  .  ja v  a 2 s .c  o m

    SecretKeySpec signKey = new SecretKeySpec(key, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(signKey);
    byte[] hash = mac.doFinal(data);

    int offset = hash[20 - 1] & 0xF;

    // We're using a long because Java hasn't got unsigned int.
    long truncatedHash = 0;
    for (int i = 0; i < 4; ++i) {
        truncatedHash <<= 8;
        // We are dealing with signed bytes:
        // we just keep the first byte.
        truncatedHash |= (hash[offset + i] & 0xFF);
    }

    truncatedHash &= 0x7FFFFFFF;
    truncatedHash %= 1000000;

    return (int) truncatedHash;
}

From source file:za.co.bronkode.jwtbroker.Tokenizer.java

public static String GetSignature(String header, String claim) {
    try {/*  ww w .  ja  v a 2  s. c o  m*/

        StringBuilder sb = new StringBuilder(header);
        sb.append(".");
        sb.append(claim);
        Mac mac = Mac.getInstance("HmacSHA256");
        SecretKey key = new SecretKeySpec(privateKey.getBytes(), "HmacSHA256");

        mac.init(key);
        String signature = Base64.getEncoder().encodeToString(mac.doFinal(sb.toString().getBytes()));
        return signature;
    } catch (NoSuchAlgorithmException | InvalidKeyException ex) {
        Logger.getLogger(Tokenizer.class.getName()).log(Level.SEVERE, null, ex);
    }
    return "";
}