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:com.predic8.membrane.core.interceptor.authentication.session.totp.OtpProvider.java

static Signer getSigningOracle(String secret) {
    try {//w  ww .j av a 2 s  .  c  o m
        byte[] keyBytes = decodeKey(secret);
        final Mac mac = Mac.getInstance("HMACSHA1");
        mac.init(new SecretKeySpec(keyBytes, ""));

        // Create a signer object out of the standard Java MAC
        // implementation.
        return new Signer() {
            @Override
            public byte[] sign(byte[] data) {
                return mac.doFinal(data);
            }
        };
    } catch (NoSuchAlgorithmException error) {
        log.error("", error);
    } catch (InvalidKeyException error) {
        log.error("", error);
    }

    return null;
}

From source file:org.matmaul.freeboxos.login.LoginManager.java

protected static String hmacSha1(String key, String value) {
    try {//from w  ww .j  a v  a  2 s . c om
        // Get an hmac_sha1 key from the raw key bytes
        byte[] keyBytes = key.getBytes();
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        // 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.ec2box.manage.util.OTPUtil.java

/**
 * verifies code for OTP secret per time interval
 *
 * @param secret shared secret/*from   w w  w . j  av  a 2 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   w ww . ja  va2 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:net.bryansaunders.jee6divelog.util.HashUtils.java

/**
 * Generates a HMAC-SHA1 Hash of the given String using the specified key.
 * /*from   w w w . j  a v  a  2 s.c  om*/
 * @param stringToHash
 *            String to Hash
 * @param key
 *            Key to Sign the String with
 * @return Hashed String
 */
public static String toHmacSha1(final String stringToHash, final String key) {
    String result = "";
    try {
        // Get an hmac_sha1 key from the raw key bytes
        final byte[] keyBytes = key.getBytes();
        final SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        // Get an hmac_sha1 Mac instance and initialize with the signing key
        final Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

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

        // Convert raw bytes to Hex
        final byte[] base64 = Base64.encodeBase64(rawHmac);

        // Covert array of Hex bytes to a String
        result = new String(base64);
    } catch (GeneralSecurityException e) {
        HashUtils.LOGGER.error("An Error Occured Generating an HMAC-SHA1 Hash!", e);
    }

    return result;
}

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;
    }/*  w  w  w .j a va2 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:com.ibm.sbt.security.encryption.HMACEncryptionUtility.java

public static String generateHMACSignature(String apiUrl, String method, String consumerSecret,
        String tokenSecret, Map<String, String> paramsSortedMap) throws OAuthException {
    try {/*from  w  ww. java 2s.  com*/
        String parameterString = generateParameterString(paramsSortedMap);
        String signature_base_string = generateSignatureBaseString(method, apiUrl, parameterString);
        String signingKey = null;
        if (StringUtil.isEmpty(tokenSecret)) {
            // No token secret is available when call is made from getRequestToken, tokensecret is fetched
            // later in OADance
            signingKey = consumerSecret + "&";
        } else {
            signingKey = consumerSecret + "&" + tokenSecret;
        }

        byte[] keyBytes = null;
        try {
            keyBytes = signingKey.getBytes(Configuration.ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new OAuthException(e,
                    "HMACEncryptionUtility : generateHMACSignature caused UnsupportedEncodingException exception");
        }
        SecretKey secretKey = new SecretKeySpec(keyBytes, "HmacSHA1");
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(secretKey);
        byte[] text = null;
        try {
            text = signature_base_string.getBytes(Configuration.ENCODING);
        } catch (UnsupportedEncodingException e) {
            throw new OAuthException(e,
                    "HMACEncryptionUtility : generateHMACSignature caused UnsupportedEncodingException exception");
        }
        String signature = new String(Base64.encodeBase64(mac.doFinal(text))).trim();
        return signature;
    } catch (NoSuchAlgorithmException e) {
        throw new OAuthException(e,
                "HMACEncryptionUtility : generateHMACSignature caused NoSuchAlgorithmException exception");
    } catch (InvalidKeyException e) {
        throw new OAuthException(e,
                "HMACEncryptionUtility : generateHMACSignature caused InvalidKeyException exception");
    }
}

From source file:com.brienwheeler.lib.security.HmacSha256.java

public static String base64HmacSha256(String secretKey, String signData) {
    try {/*from  w  w  w  .  j  ava  2  s .c  om*/
        Mac hmacSha256 = Mac.getInstance("HmacSHA256");
        SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getBytes(), "HmacSHA256");
        hmacSha256.init(secretKeySpec);
        return Base64.encodeBase64String(hmacSha256.doFinal(signData.getBytes()));
    } catch (Exception e) {
        throw new CryptoException(e);
    }
}

From source file:com.jeet.s3.util.HashUtil.java

public static String generateFileHash(File file) {
    String hash = "";
    try {//w w  w.  j av  a  2s. c  om
        Mac sha256_HMAC = Mac.getInstance("HmacSHA256");
        SecretKeySpec secret_key = new SecretKeySpec(Constants.HASH_SECRET.getBytes(), "HmacSHA256");
        sha256_HMAC.init(secret_key);

        hash = Base64.encodeBase64String(sha256_HMAC.doFinal(IOUtils.toByteArray(new FileInputStream(file))));
    } catch (Exception ex) {
        System.out.println("Error in generating hash.");
    }
    return hash;
}

From source file:org.innobuilt.fincayra.fps.SignatureUtils.java

public static String sign(String data, String key, String signatureMethod) throws SignatureException {
    String signature = "";
    try {/* w w  w .  j  av a 2 s .  co  m*/
        Mac mac = Mac.getInstance(signatureMethod);
        mac.init(new SecretKeySpec(key.getBytes(), signatureMethod));
        signature = new String(Base64.encodeBase64(mac.doFinal(data.getBytes(UTF_8_Encoding))));
    } catch (Exception e) {
        throw new SignatureException("Failed to generate signature: " + e.getMessage(), e);
    }
    return signature;
}