Example usage for javax.crypto Mac getInstance

List of usage examples for javax.crypto Mac getInstance

Introduction

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

Prototype

public static final Mac getInstance(String algorithm) throws NoSuchAlgorithmException 

Source Link

Document

Returns a Mac object that implements the specified MAC algorithm.

Usage

From source file:co.mitro.twofactor.TwoFactorCodeChecker.java

public static int computeHash(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 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;
    long truncatedHash = 0;
    for (int i = 0; i < 4; ++i) {
        truncatedHash <<= 8;
        truncatedHash |= (hash[offset + i] & 0xFF);
    }
    truncatedHash &= 0x7FFFFFFF;
    truncatedHash %= 1000000;
    return (int) truncatedHash;
}

From source file:me.whitmarbut.mfa.TOTP.java

private byte[] getHmac(int timestamp, byte[] key) throws NoSuchAlgorithmException, InvalidKeyException {
    SecretKeySpec key_spec = new SecretKeySpec(key, "HmacSHA1");
    Mac mac = Mac.getInstance("HmacSHA1");
    mac.init(key_spec);/*  w  w  w .  j  a v  a 2s . c  o  m*/
    byte[] bin_timestamp = ByteBuffer.allocate(4).putInt(timestamp).array();

    ByteBuffer bbuff = ByteBuffer.allocate(8);
    bbuff.putInt(0); //Left pad 4 bytes to make a 64 bit int
    bbuff.putInt(timestamp);

    return mac.doFinal(bbuff.array());
}

From source file:com.vab.iflex.gateway.paybillservice.Stub.java

private static String calculateRFC2104HMAC(String data, String key) throws Exception {
    String result;/* w ww.ja v  a 2 s .c om*/
    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;
}

From source file:at.alladin.rmbt.shared.Helperfunctions.java

public static String calculateHMAC(final String secret, final String data) {
    try {/*  w  w w . ja v a  2  s.co m*/
        final SecretKeySpec signingKey = new SecretKeySpec(secret.getBytes(), "HmacSHA1");
        final Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);
        final byte[] rawHmac = mac.doFinal(data.getBytes());
        final String result = new String(Base64.encodeBytes(rawHmac));
        return result;
    } catch (final GeneralSecurityException e) {

        System.out.println("Unexpected error while creating hash: " + e.getMessage());
        return "";
    }
}

From source file:com.zimbra.cs.account.PreAuthKey.java

private static String getHmac(String data, byte[] key) {
    try {/*w  w w.  j a va  2s .  c  o m*/
        ByteKey bk = new ByteKey(key);
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(bk);
        return new String(Hex.encodeHex(mac.doFinal(data.getBytes())));
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("fatal error", e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("fatal error", e);
    }
}

From source file:com.diversityarrays.dal.db.DalDatabaseUtil.java

/**
 * Calculate an RFC 2104 compliant HMAC signature.
 * @param key is the signing key//from  w ww.ja  v a 2  s. c o  m
 * @param data is the data to be signed 
 * @return the base64-encoded signature as a String
 */
public static String computeHmacSHA1(String key, String data) {
    try {
        byte[] keyBytes = key.getBytes("UTF-8");
        SecretKeySpec signingKey = new SecretKeySpec(keyBytes, "HmacSHA1");

        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(signingKey);

        byte[] rawHmac = mac.doFinal(data.getBytes("UTF-8"));

        // TODO Consider replacing with a simple hex encoder so we don't need commons-codec
        byte[] hexBytes = new Hex().encode(rawHmac);

        return new String(hexBytes, "UTF-8");

    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException(e);
    } catch (UnsupportedEncodingException e) {
        throw new RuntimeException(e);
    }
}

From source file:org.esupportail.papercut.services.HashService.java

public String getHMac(String input) {
    try {//from   w  w w  .j a v  a  2 s. co  m
        Mac mac = Mac.getInstance("HmacSHA512");
        mac.init(secretKey);
        final byte[] macData = mac.doFinal(input.getBytes());
        byte[] hex = new Hex().encode(macData);
        String hmac = new String(hex, "ISO-8859-1").toUpperCase();
        log.debug(input);
        log.debug(hmac);
        return hmac;
    } catch (Exception e) {
        log.error("Error during encoding data ...");
        throw new RuntimeException(e);
    }
}

From source file:com.android.pwdhashandroid.sharp2java.HMACMD5.java

private void init(byte[] key) throws GeneralSecurityException {
    sk = new SecretKeySpec(key, HMAC_MD5_NAME);
    mac = Mac.getInstance(HMAC_MD5_NAME);
    mac.init(sk);//from www . ja  va  2 s. c  o  m
}

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

public static String sign(String content, String key) {
    try {//from   ww  w  .j ava2s  . c  o  m
        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:oauth.signpost.signature.HmacSha1MessageSigner.java

@Override
public String sign(HttpRequest request, Map<String, String> oauthParameters)
        throws OAuthMessageSignerException {
    try {/*from   ww  w  .ja va 2s.c  o m*/
        String keyString = OAuth.percentEncode(getConsumerSecret()) + '&'
                + OAuth.percentEncode(getTokenSecret());
        byte[] keyBytes = keyString.getBytes(OAuth.ENCODING);

        SecretKey key = new SecretKeySpec(keyBytes, MAC_NAME);
        Mac mac = Mac.getInstance(MAC_NAME);
        mac.init(key);

        String sbs = computeSignatureBaseString(request, oauthParameters);
        byte[] text = sbs.getBytes(OAuth.ENCODING);

        return base64Encode(mac.doFinal(text));
    } catch (GeneralSecurityException e) {
        throw new OAuthMessageSignerException(e);
    } catch (UnsupportedEncodingException e) {
        throw new OAuthMessageSignerException(e);
    }
}