Computes a HMAC-SHA1 message digest of a given message, appends it to the message, returns the output. - Java Security

Java examples for Security:SHA

Description

Computes a HMAC-SHA1 message digest of a given message, appends it to the message, returns the output.

Demo Code


//package com.java2s;

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

public class Main {
    /**/*from  ww  w.ja va  2 s .c  om*/
     * Computes a HMAC-SHA1 message digest of a given message, appends it to the 
     * message, returns the output.
     *
     * @param message  the message (in bytes)
     * @param keySpec  the secret key for HMAC-SHA1
     * @return message concatenated with the HMAC-SHA1 digest
     */
    public static byte[] append_hash(byte[] message, SecretKeySpec keySpec) {
        byte[] ret = null;

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

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

            // Append the MAC to the message
            ret = new byte[message.length + m.length];
            System.arraycopy(message, 0, ret, 0, message.length);
            System.arraycopy(m, 0, ret, message.length, m.length);

        } catch (Exception e) {
            e.printStackTrace();
        }

        return ret;
    }
}

Related Tutorials