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(byte[] input) throws IllegalStateException 

Source Link

Document

Processes the given array of bytes and finishes the MAC operation.

Usage

From source file:Main.java

public static String getBytesMacEncrypt(byte[] bytes, SecretKey key) {
    String algorithm = key.getAlgorithm();
    if (algorithm.equals(HmacMD5) || algorithm.equals(HmacSHA1) || algorithm.equals(HmacSHA256)
            || algorithm.equals(HmacSHA384) || algorithm.equals(HmacSHA512)) {
        Mac mac = null;
        try {/*from   w w  w  .ja v a 2  s .c  o m*/
            mac = Mac.getInstance(algorithm);
            mac.init(key);
            return bytes2String(mac.doFinal(bytes));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        }
    }
    return null;
}

From source file:aaf.vhr.crypto.GoogleAuthenticator.java

private static int verifyCode(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   www .  j a v a2 s  .  c om

    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:de.desy.dcache.s3.Signature.java

/**
* Computes RFC 2104-compliant HMAC signature.
* * @param data/*from   w ww .j  av a 2 s.  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 calculateRFC2104HMAC(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.getMessage());
    }
    return result;
}

From source file:com.ec2box.manage.util.OTPUtil.java

/**
 * verifies code for OTP secret per time interval
 *
 * @param secret shared secret/*  w  w  w .ja v  a2 s  .c o m*/
 * @param token  verification token
 * @param time   time representation to calculate OTP
 * @return true if success
 */
private static boolean verifyToken(String secret, long token, long time) {

    long calculated = -1;

    byte[] key = new Base32().decode(secret);

    SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA1");

    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(time).array());

        int offset = hash[hash.length - 1] & 0xF;
        for (int i = 0; i < 4; ++i) {
            calculated <<= 8;
            calculated |= (hash[offset + i] & 0xFF);
        }

        calculated &= 0x7FFFFFFF;
        calculated %= 1000000;
    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    }

    return calculated != -1 && calculated == token;

}

From source file:com.keybox.manage.util.OTPUtil.java

/**
 * verifies code for OTP secret per time interval
 *
 * @param secret shared secret//from   www  . ja va2s  .c  o  m
 * @param token  verification token
 * @param time   time representation to calculate OTP
 * @return true if success
 */
private static boolean verifyToken(String secret, long token, long time) {

    long calculated = -1;

    byte[] key = new Base32().decode(secret);

    SecretKeySpec secretKey = new SecretKeySpec(key, "HmacSHA1");

    try {
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] hash = mac.doFinal(ByteBuffer.allocate(8).putLong(time).array());

        int offset = hash[hash.length - 1] & 0xF;
        for (int i = 0; i < 4; ++i) {
            calculated <<= 8;
            calculated |= (hash[offset + i] & 0xFF);
        }

        calculated &= 0x7FFFFFFF;
        calculated %= 1000000;
    } catch (Exception ex) {
        log.error(ex.toString(), ex);
    }

    return (calculated != -1 && calculated == token);

}

From source file:illab.nabal.util.SecurityHelper.java

/**
 * Get HMACSHA1-encoded OAuth 1.0a signature string.
 * /*from  ww  w.j  a v a2 s.  c  o  m*/
 * @param secretKey - secret key to encode basestring with
 * @param baseString - signature base string 
 * @return oauthSignature - HMAC-SHA1 encoded signature string
 * @throws Exception
 */
public static String getHmacSha1Signature(String secretKey, String baseString) throws Exception {
    String oauthSignature = null;

    // #################### IMPORTANT ####################
    // the secret key is the concatenated values (each first encoded per Parameter 
    // Encoding) of the Consumer Secret and Token Secret, separated by an '&' character 
    // (ASCII code 38) even if empty.

    if (StringHelper.isAllFull(secretKey, baseString) == true) {
        byte[] keyBytes = secretKey.getBytes(HTTP.UTF_8);
        SecretKey keySpec = new SecretKeySpec(keyBytes, HMAC_SHA1);
        Mac mac = Mac.getInstance(HMAC_SHA1);
        mac.init(keySpec);
        oauthSignature = new String(Base64.encode(mac.doFinal(baseString.getBytes(HTTP.UTF_8)), Base64.DEFAULT),
                HTTP.UTF_8).trim();
    }
    return oauthSignature;
}

From source file:org.egov.infra.security.utils.HMAC.java

public static String digest(String message, String privateKey) {
    try {/*from  ww w. ja  va 2s  .co m*/
        Mac hmac = Mac.getInstance(HMAC_SHA_256);
        hmac.init(new SecretKeySpec(privateKey.getBytes(UTF_8), HMAC_SHA_256));
        return Hex.encodeHexString(hmac.doFinal(privateKey.concat(message).getBytes(US_ASCII)));
    } catch (NoSuchAlgorithmException | InvalidKeyException e) {
        throw new ApplicationRuntimeException("Error occurred while hashing message", e);
    }
}

From source file:com.eugene.fithealthmaingit.FatSecretSearchAndGet.FatSecretGetMethod.java

private static String sign(String method, String uri, String[] params) {
    String[] p = { method, Uri.encode(uri), Uri.encode(paramify(params)) };
    String s = join(p, "&");
    SecretKey sk = new SecretKeySpec(Globals.APP_SECRET.getBytes(), Globals.HMAC_SHA1_ALGORITHM);
    try {/* ww w .j  a va2 s  .c  o m*/
        Mac m = Mac.getInstance(Globals.HMAC_SHA1_ALGORITHM);
        m.init(sk);
        return Uri.encode(new String(Base64.encode(m.doFinal(s.getBytes()), Base64.DEFAULT)).trim());
    } catch (java.security.NoSuchAlgorithmException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    } catch (java.security.InvalidKeyException e) {
        Log.w("FatSecret_TEST FAIL", e.getMessage());
        return null;
    }
}

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

public static String genSignature(String data, String key) {
    byte[] byteHMAC = null;
    try {/* ww  w.  j ava  2 s  .  c o m*/
        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:com.vab.iflex.gateway.paybillservice.Stub.java

private static String calculateRFC2104HMAC(String data, String key) throws Exception {
    String result;/*w w w.j  ava 2  s  . c  o m*/
    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 BASE64Encoder().encode(rawHmac);
        result = new Base64().encodeAsString(rawHmac);

    } catch (Exception e) {
        throw new SignatureException("Failed to generate HMAC : " + e.getMessage());
    }
    return result;
}