Generate the mac based on HMAC_ALGORITHM - Android java.security

Android examples for java.security:MessageDigest

Description

Generate the mac based on HMAC_ALGORITHM

Demo Code

/**// w w w .  j  a va  2 s . c o  m
     * Fixes for the RNG as per
     * http://android-developers.blogspot.com/2013/08/some-securerandom-thoughts.html
     * <p/>
     * This software is provided 'as-is', without any express or implied
     * warranty. In no event will Google be held liable for any damages arising
     * from the use of this software.
     * <p/>
     * Permission is granted to anyone to use this software for any purpose,
     * including commercial applications, and to alter it and redistribute it
     * freely, as long as the origin is not misrepresented.
     * <p/>
     * Fixes for the output of the default PRNG having low entropy.
     * <p/>
     * The fixes need to be applied via {@link #apply()} before any use of Java
     * Cryptography Architecture primitives. A good place to invoke them is in
     * the application's {@code onCreate}.
     */
//package com.java2s;

import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

import javax.crypto.Mac;
import javax.crypto.SecretKey;

public class Main {
    private static final String HMAC_ALGORITHM = "HmacSHA256";

    /**
     * Generate the mac based on HMAC_ALGORITHM
     *
     * @param integrityKey   The key used for hmac
     * @param byteCipherText the cipher text
     * @return A byte array of the HMAC for the given key & ciphertext
     * @throws NoSuchAlgorithmException
     * @throws InvalidKeyException
     */
    public static byte[] generateMac(byte[] byteCipherText,
            SecretKey integrityKey) throws NoSuchAlgorithmException,
            InvalidKeyException {
        //Now compute the mac for later integrity checking
        Mac sha256_HMAC = Mac.getInstance(HMAC_ALGORITHM);
        sha256_HMAC.init(integrityKey);
        return sha256_HMAC.doFinal(byteCipherText);
    }
}

Related Tutorials