Example usage for javax.crypto Mac doFinal

List of usage examples for javax.crypto Mac doFinal

Introduction

In this page you can find the example usage for javax.crypto Mac doFinal.

Prototype

public final byte[] doFinal() throws IllegalStateException 

Source Link

Document

Finishes the MAC operation.

Usage

From source file:org.apache.shindig.common.crypto.Crypto.java

/**
 * Verifies an HMAC SHA1 hash.  Throws if the verification fails.
 * /*  w ww.j av  a 2 s.  c o m*/
 * @param key
 * @param in
 * @param expected
 * @throws GeneralSecurityException
 */
public static void hmacSha1Verify(byte[] key, byte[] in, byte[] expected) throws GeneralSecurityException {
    Mac hmac = Mac.getInstance(HMAC_TYPE);
    Key hmacKey = new SecretKeySpec(key, HMAC_TYPE);
    hmac.init(hmacKey);
    hmac.update(in);
    byte actual[] = hmac.doFinal();
    if (actual.length != expected.length) {
        throw new GeneralSecurityException("HMAC verification failure");
    }
    for (int i = 0; i < actual.length; i++) {
        if (actual[i] != expected[i]) {
            throw new GeneralSecurityException("HMAC verification failure");
        }
    }
}

From source file:com.cloud.test.utils.UtilsForTest.java

public static String signRequest(String request, String key) {
    try {//from   ww w .j a  v a  2s.  c om
        Mac mac = Mac.getInstance("HmacSHA1");
        SecretKeySpec keySpec = new SecretKeySpec(key.getBytes(), "HmacSHA1");
        mac.init(keySpec);
        mac.update(request.getBytes());
        byte[] encryptedBytes = mac.doFinal();
        //System.out.println("HmacSHA1 hash: " + encryptedBytes);
        return Base64.encodeBase64String(encryptedBytes);
    } catch (Exception ex) {
        System.out.println("unable to sign request");
        ex.printStackTrace();
    }
    return null;
}

From source file:Main.java

public static String getFileMacEncrypt(File file, SecretKey key) throws IOException {
    String algorithm = key.getAlgorithm();
    Mac mac = null;
    try {//  www. j a  va  2  s  . com
        mac = Mac.getInstance(algorithm);
        mac.init(key);
        FileInputStream in = new FileInputStream(file);
        byte[] buffer = new byte[1024 * 1024];
        int len = 0;
        while ((len = in.read(buffer)) > 0) {
            mac.update(buffer, 0, len);
        }
        in.close();
        return bytes2String(mac.doFinal());
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.apache.abdera2.common.security.HashHelper.java

public static String hmac(Key key, String alg, byte[] mat) {
    try {/*from w w w .  ja  v  a  2 s. c  om*/
        Mac mac = Mac.getInstance(alg);
        mac.init(key);
        mac.update(mat, 0, mat.length);
        byte[] sig = mac.doFinal();
        return Base64.encodeBase64URLSafeString(sig);
    } catch (Throwable t) {
        throw ExceptionHelper.propogate(t);
    }
}

From source file:org.apache.cloudstack.region.RegionsApiUtil.java

/**
 * 1. Signs a string with a secret key using SHA-1 2. Base64 encode the result 3. URL encode the final result
 *
 * @param request//from  w ww  .j  a  va  2 s.  c  o m
 * @param key
 * @return
 */
private 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) {
        s_logger.error(ex.getMessage());
        return null;
    }
}

From source file:org.linkdroid.PostJob.java

private static String hmacSha1(InputStream plainText, String secretString, String nonce)
        throws IOException, InvalidKeyException, NoSuchAlgorithmException {
    Mac mac = initHmacSha1(secretString, nonce);

    // digest the content.
    byte[] bytes = new byte[1024];
    int count;/* w  w w .  j ava  2 s. co  m*/
    while ((count = plainText.read(bytes)) != -1) {
        mac.update(bytes, 0, count);
    }

    // Return the string digest
    return hmacDigestToHexString(mac.doFinal());
}

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

public static byte[] hmacSha1(String[] datas, SecretKeySpec signingKey) {
    Mac mac;
    try {//www  .  j a va  2s.  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);
    }
    for (String data : datas) {
        mac.update(data.getBytes(CHARSET_UTF8));
    }
    return mac.doFinal();
}

From source file:be.fedict.eid.applet.service.impl.UserIdentifierUtil.java

/**
 * Gives back a non-reversible citizen identifier (NRCID).
 * /*from ww  w  .  j a v  a  2s. co m*/
 * @param userId
 *            the primary user identifier, i.e. the national registry
 *            number.
 * @param orgId
 *            the optional organization identifier.
 * @param appId
 *            the optional application identifier.
 * @param secret
 *            the application specific secret. Should be at least 128 bit
 *            long. Encoded in hexadecimal format.
 * @return
 */
public static String getNonReversibleCitizenIdentifier(String userId, String orgId, String appId,
        String secret) {
    if (null == secret) {
        throw new IllegalArgumentException("secret key is null");
    }
    /*
     * Avoid XML formatting issues introduced by some web.xml XML editors.
     */
    secret = secret.trim();
    if (null != orgId) {
        orgId = orgId.trim();
    } else {
        LOG.warn("it is advised to use an orgId");
    }
    if (null != appId) {
        appId = appId.trim();
    } else {
        LOG.warn("it is advised to use an appId");
    }

    /*
     * Decode the secret key.
     */
    byte[] secretKey;
    try {
        secretKey = Hex.decodeHex(secret.toCharArray());
    } catch (DecoderException e) {
        LOG.error("secret is not hexadecimal encoded: " + e.getMessage());
        throw new IllegalArgumentException("secret is not hexadecimal encoded");
    }
    if ((128 / 8) > secretKey.length) {
        /*
         * 128 bit is seen as secure these days.
         */
        LOG.warn("secret key is too short");
        throw new IllegalArgumentException("secret key is too short");
    }

    /*
     * Construct the HMAC input sequence.
     */
    String input = userId;
    if (null != appId) {
        input += appId;
    }
    if (null != orgId) {
        input += orgId;
    }
    byte[] inputData = input.getBytes();

    SecretKey macKey = new SecretKeySpec(secretKey, HMAC_ALGO);
    Mac mac;
    try {
        mac = Mac.getInstance(macKey.getAlgorithm());
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("HMAC algo not available: " + e.getMessage());
    }
    try {
        mac.init(macKey);
    } catch (InvalidKeyException e) {
        LOG.error("invalid secret key: " + e.getMessage(), e);
        throw new RuntimeException("invalid secret");
    }
    mac.update(inputData);
    byte[] resultHMac = mac.doFinal();
    String resultHex = new String(Hex.encodeHex(resultHMac)).toUpperCase();
    return resultHex;
}

From source file:Main.java

/**
 * Compute the HMAC with SHA-256 of data, as defined in
 * http://tools.ietf.org/html/rfc2104#section-2 .
 * @param key The key byte array./*from  w  w  w  .j a v a 2 s .  c o  m*/
 * @param data The input byte buffer. This does not change the position.
 * @return The HMAC result.
 */
public static byte[] computeHmacWithSha256(byte[] key, ByteBuffer data) {
    final String algorithm = "HmacSHA256";
    Mac mac;
    try {
        mac = Mac.getInstance(algorithm);
    } catch (NoSuchAlgorithmException ex) {
        // Don't expect this to happen.
        throw new Error("computeHmac: " + algorithm + " is not supported: " + ex.getMessage());
    }

    try {
        mac.init(new SecretKeySpec(key, algorithm));
    } catch (InvalidKeyException ex) {
        // Don't expect this to happen.
        throw new Error("computeHmac: Can't init " + algorithm + " with key: " + ex.getMessage());
    }
    int savePosition = data.position();
    mac.update(data);
    data.position(savePosition);
    return mac.doFinal();
}

From source file:org.linkdroid.PostJob.java

private static final String calculateBundleExtrasHmac(Bundle data, String secretString)
        throws NoSuchAlgorithmException, IOException, InvalidKeyException {
    Mac mac = initHmacSha1(secretString, null);
    SortedSet<String> keys = new TreeSet<String>(data.keySet());
    for (String key : keys) {
        mac.update(key.getBytes(UTF8));//  w  w w  .ja v a  2 s  .  com
        Object value = data.get(key);
        // We only add the value to the hmac digest if it exists; the key is still
        // part of the digest calculation.
        if (value != null) {
            mac.update(value.toString().getBytes(UTF8));
        }
    }
    return hmacDigestToHexString(mac.doFinal());
}