Extracts a HMAC-SHA1 message digest form the end of the given message and determines whether it is valid. - Java Security

Java examples for Security:SHA

Description

Extracts a HMAC-SHA1 message digest form the end of the given message and determines whether it is valid.

Demo Code


//package com.java2s;

import java.util.Arrays;

import javax.crypto.*;
import javax.crypto.spec.*;

public class Main {
    public static final int HMAC_SHA1_LEN = 20;

    /**//from   w ww .  j  a v  a2 s. c  om
     * Extracts a HMAC-SHA1 message digest form the end of the given message and
     * determines whether it is valid.
     *
     * @param messageHash  the message including digest (in bytes)
     * @param keySpec  the secret key for HMAC-SHA1
     * @return true if the extracted digest matches the computed digest
     */
    public static boolean verify_hash(byte[] messageHash,
            SecretKeySpec keySpec) {
        boolean ret = false;

        try {
            // Split the array into the message and the digest
            byte[] message = new byte[messageHash.length - HMAC_SHA1_LEN];
            byte[] hash = new byte[HMAC_SHA1_LEN];

            System.arraycopy(messageHash, 0, message, 0, message.length);
            System.arraycopy(messageHash, message.length, hash, 0,
                    hash.length);

            // Initialize the MAC with the given key
            Mac mac = Mac.getInstance("HmacSHA1");
            mac.init(keySpec);

            // Get the MAC of the message
            byte[] m = mac.doFinal(message);

            // compare the the MAC sent and the one calculated
            ret = Arrays.equals(m, hash);

        } catch (Exception e) {
            // if there is an error, we know that hash can't be correct
            ret = false;
        }

        return ret;
    }
}

Related Tutorials