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:com.petercho.Encoder.java

public static byte[] getHmac(String secretKey, String payload, String hmacType) {
    final Mac mac;
    byte[] hmac;//from  w  ww.  ja  v  a 2  s  .c  om
    try {
        final byte[] secretKeyBytes;
        if (secretKey == null) {
            secretKeyBytes = new byte[] { 0 };
        } else {
            secretKeyBytes = secretKey.getBytes(DEFAULT_ENCODING);
        }
        if (payload == null) {
            payload = "";
        }
        SecretKeySpec keySpec = new SecretKeySpec(secretKeyBytes, hmacType);
        mac = Mac.getInstance(hmacType);
        mac.init(keySpec);
        hmac = mac.doFinal(payload.getBytes(DEFAULT_ENCODING));
    } catch (NoSuchAlgorithmException e) {
        String msg = "An error occurred initializing algorithm '" + hmacType + "', e: " + e;
        throw new IllegalStateException(msg, e);
    } catch (InvalidKeyException e) {
        String msg = "An error occurred initializing key, e: " + e;
        throw new IllegalStateException(msg, e);
    } catch (UnsupportedEncodingException e) {
        String msg = "Invalid encoding, e: " + e;
        throw new IllegalStateException(msg, e);
    }
    return hmac;
}

From source file:com.imaginary.home.controller.CloudService.java

static public String sign(byte[] key, String stringToSign) throws Exception {
    Mac mac = Mac.getInstance("HmacSHA256");

    mac.init(new SecretKeySpec(key, "HmacSHA256"));
    return new String(Base64.encodeBase64(mac.doFinal(stringToSign.getBytes("utf-8"))));
}

From source file:org.dasein.cloud.terremark.Terremark.java

private static String sign(byte[] key, String authString, String algorithm) throws InternalException {
    try {/*  w w w  .j av a  2  s .  co  m*/
        Mac mac = Mac.getInstance(algorithm);

        mac.init(new SecretKeySpec(key, algorithm));
        return new String(Base64.encodeBase64(mac.doFinal(authString.getBytes("utf-8"))));
    } catch (NoSuchAlgorithmException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    } catch (InvalidKeyException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    } catch (IllegalStateException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    } catch (UnsupportedEncodingException e) {
        logger.error(e);
        e.printStackTrace();
        throw new InternalException(e);
    }
}

From source file:com.eucalyptus.ws.util.HmacUtils.java

public static String getSignature(final String queryKey, final String subject, final Hmac mac)
        throws AuthenticationException {
    SecretKeySpec signingKey = new SecretKeySpec(queryKey.getBytes(), mac.toString());
    try {//from   www  . j  a  v  a  2s. c o m
        Mac digest = mac.getInstance();
        digest.init(signingKey);
        byte[] rawHmac = digest.doFinal(subject.getBytes());
        return Base64.encode(rawHmac).replaceAll("=", "");
    } catch (Exception e) {
        LOG.error(e, e);
        throw new AuthenticationException("Failed to compute signature");
    }
}

From source file:ac.elements.io.Signature.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 * //  w  ww  . j a v  a  2s  .co m
 * @param data
 *            the data
 * @param key
 *            the key
 * @param algorithm
 *            the algorithm
 * 
 * @return the string
 * @throws SignatureException
 */
private static String sign(String data, String key, String algorithm) throws SignatureException {
    if (key == null)
        throw new SignatureException("Encoding key is null.");
    byte[] signature = null;
    try {
        Mac mac = Mac.getInstance(algorithm);
        mac.init(new SecretKeySpec(key.getBytes(), algorithm));
        signature = Base64.encodeBase64(mac.doFinal(data.getBytes(DEFAULT_ENCODING)));
    } catch (Exception e) {
        log.error("Failed to generate signature: " + e.getMessage(), e);
    }

    return new String(signature);
}

From source file:uk.bowdlerize.API.java

private static String createSignatureHash(String value, String key)
        throws UnsupportedEncodingException, NoSuchAlgorithmException, InvalidKeyException {
    String type = "HmacSHA512";
    SecretKeySpec secret = new SecretKeySpec(key.getBytes(), type);
    Mac mac = Mac.getInstance(type);
    mac.init(secret);/*from w w  w .j av a  2s . co  m*/
    byte[] bytes = mac.doFinal(value.getBytes());
    return bytesToHex(bytes);
}

From source file:com.sangupta.jerry.oauth.OAuthUtils.java

/**
 * Generate the signature using the given signing method for the signable
 * using the key string. For OAuth the key string should already be
 * URI-percent-encoded if need be./*from   w  ww . j  ava2s.c  o  m*/
 * 
 * @param signable
 *            the string for which the signature needs to be generated
 * 
 * @param keyString
 *            the key string to be used
 * 
 * @param signingMethod
 *            the signing method to be used
 * 
 * @return the signature generated, or <code>null</code> if some exception
 *         occurs
 * 
 * @throws NullPointerException
 *             if the signable string is <code>null</code>/empty.
 */
public static String createSignature(String signable, String keyString, OAuthSignatureMethod signingMethod) {
    if (AssertUtils.isEmpty(signable)) {
        throw new IllegalArgumentException("Signable string cannot be null/empty");
    }

    if (signingMethod == OAuthSignatureMethod.PLAIN_TEXT) {
        return keyString;
    }

    SecretKeySpec key = new SecretKeySpec((keyString).getBytes(StringUtils.CHARSET_UTF8),
            signingMethod.getAlgorithmName());
    Mac mac;
    try {
        mac = Mac.getInstance(signingMethod.getAlgorithmName());
        mac.init(key);
        byte[] bytes = mac.doFinal(signable.getBytes(StringUtils.CHARSET_UTF8));
        return Base64Encoder.encodeToString(bytes, false);
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }

    return null;
}

From source file:ch.docbox.elexis.UserDocboxPreferences.java

public static String getSSOSignature(String ts) {

    String username = getDocboxLoginID(false);

    String sha1Password = getSha1DocboxPassword();
    String sha1SecretKey = getSha1DocboxSecretKey();

    String message = username + ":" + ts + ":" + sha1Password; //$NON-NLS-1$ //$NON-NLS-2$
    try {/*w  w w  .  j a  v a  2  s.co  m*/
        // get an hmac_sha1 key from the raw key bytes
        SecretKeySpec signingKey;
        signingKey = new SecretKeySpec(sha1SecretKey.getBytes("UTF-8"), "HmacSHA1"); //$NON-NLS-1$//$NON-NLS-2$

        // get an hmac_sha1 Mac instance and initialize with the signing key
        Mac mac = Mac.getInstance("HmacSHA1");//$NON-NLS-1$
        mac.init(signingKey);

        // compute the hmac on input data bytes
        byte[] rawHmac = mac.doFinal(message.getBytes("UTF-8")); //$NON-NLS-1$

        // base64-encode the hmac
        // If desired, convert the digest into a string
        byte[] base64 = Base64.encodeBase64(rawHmac);
        return new String(base64);
    } catch (java.security.NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    }
    return null;
}

From source file:org.wso2.carbon.appfactory.s4.integration.utils.CloudUtils.java

/**
 * Computes RFC 2104-compliant HMAC signature.
 * * @param data/*from   w w w . j  a va 2  s  . c o m*/
 * The data to be signed.
 * 
 * @param key
 *            The signing key.
 * @return
 *         The Base64-encoded RFC 2104-compliant HMAC signature.
 * @throws AppFactoryException
 * @throws java.security.SignatureException
 *             when signature generation fails
 */
public static String calculateRFC2104HMAC(String stringToSign, String secrectAccessKey)
        throws AppFactoryException {

    // get an hmac_sha1 key from the raw key bytes
    SecretKeySpec signingKey = new SecretKeySpec(secrectAccessKey.getBytes(), HMAC_SHA1_ALGORITHM);

    // get an hmac_sha1 Mac instance and initialize with the signing key
    Mac mac = null;
    try {
        mac = Mac.getInstance(HMAC_SHA1_ALGORITHM);
        mac.init(signingKey);
    } catch (NoSuchAlgorithmException e) {
        String msg = "Error occured while computing RFC 2104-compliant HMAC signature";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);

    } catch (InvalidKeyException e) {
        String msg = "Error occured while computing RFC 2104-compliant HMAC signature";
        log.error(msg, e);
        throw new AppFactoryException(msg, e);

    }

    // compute the hmac on input data bytes
    byte[] rawHmac = mac.doFinal(stringToSign.getBytes());

    // base64-encode the hmac
    return new String(Base64.encodeBase64(rawHmac));

}

From source file:example.DecrypterException.java

/**
 * Performs the decryption algorithm./*  w w w  .  ja  v a2 s. co  m*/
 *
 * This method decrypts the ciphertext using the encryption key and verifies
 * the integrity bits with the integrity key. The encrypted format is:
 * {initialization_vector (16 bytes)}{ciphertext}{integrity (4 bytes)}
 * https://developers.google.com/ad-exchange/rtb/response-guide/decrypt-
 * hyperlocal,
 * https://developers.google.com/ad-exchange/rtb/response-guide/decrypt
 * -price and https://support.google.com/adxbuyer/answer/3221407?hl=en have
 * more details about the encrypted format of hyperlocal, winning price,
 * IDFA, hashed IDFA and Android Advertiser ID.
 */
public static byte[] decrypt(byte[] ciphertext, SecretKey encryptionKey, SecretKey integrityKey)
        throws DecrypterException {
    try {
        // Step 1. find the length of initialization vector and clear text.
        final int plaintext_length = ciphertext.length - INITIALIZATION_VECTOR_SIZE - SIGNATURE_SIZE;
        if (plaintext_length < 0) {
            throw new RuntimeException("The plain text length can't be negative.");
        }
        System.out.println(Arrays.toString(ciphertext));
        System.out.println(byte2hex(ciphertext));
        System.out.println(ciphertext.length);
        System.out.println(plaintext_length);

        byte[] iv = Arrays.copyOf(ciphertext, INITIALIZATION_VECTOR_SIZE);

        // Step 2. recover clear text
        final Mac hmacer = Mac.getInstance("HmacSHA1");
        hmacer.init(encryptionKey);

        final int ciphertext_end = INITIALIZATION_VECTOR_SIZE + plaintext_length;
        final byte[] plaintext = new byte[plaintext_length];
        boolean add_iv_counter_byte = true;
        for (int ciphertext_begin = INITIALIZATION_VECTOR_SIZE, plaintext_begin = 0; ciphertext_begin < ciphertext_end;) {
            System.out.println("=====> FOR:");
            hmacer.reset();
            hmacer.init(encryptionKey);
            System.out.println("iv: " + byte2hex(iv));
            final byte[] pad = hmacer.doFinal(iv);
            System.out.println("pad: " + byte2hex(pad) + "  len(pad): " + pad.length);
            Base64 encoder = new Base64();
            String pad_base64 = new String(encoder.encode(pad));
            System.out.println("pad Base64: " + pad_base64);

            int i = 0;
            while (i < BLOCK_SIZE && ciphertext_begin != ciphertext_end) {
                plaintext[plaintext_begin++] = (byte) (ciphertext[ciphertext_begin++] ^ pad[i++]);
            }

            if (!add_iv_counter_byte) {
                final int index = iv.length - 1;
                add_iv_counter_byte = ++iv[index] == 0;
            }

            if (add_iv_counter_byte) {
                add_iv_counter_byte = false;
                iv = Arrays.copyOf(iv, iv.length + 1);
            }
        }
        System.out.println("plaintext: " + byte2hex(plaintext));

        // Step 3. Compute integrity hash. The input to the HMAC is
        // clear_text
        // followed by initialization vector, which is stored in the 1st
        // section
        // or ciphertext.
        hmacer.reset();
        hmacer.init(integrityKey);
        hmacer.update(plaintext);
        hmacer.update(Arrays.copyOf(ciphertext, INITIALIZATION_VECTOR_SIZE));
        final byte[] computedSignature = Arrays.copyOf(hmacer.doFinal(), SIGNATURE_SIZE);
        final byte[] signature = Arrays.copyOfRange(ciphertext, ciphertext_end,
                ciphertext_end + SIGNATURE_SIZE);
        if (!Arrays.equals(signature, computedSignature)) {
            throw new DecrypterException("Signature mismatch.");
        }
        return plaintext;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("HmacSHA1 not supported.", e);
    } catch (InvalidKeyException e) {
        throw new RuntimeException("Key is invalid for this purpose.", e);
    }
}