generate 128 Bit Hash - Java Security

Java examples for Security:MD5

Description

generate 128 Bit Hash

Demo Code


//package com.java2s;

import javax.crypto.Mac;

import javax.crypto.spec.SecretKeySpec;

import java.security.InvalidKeyException;

import java.util.Arrays;

public class Main {
    private static final int oneHundredTwentyEightBitsInBytes = 16;

    public static byte[] generate128BitHash(byte[] valueToHash,
            SecretKeySpec key, Mac hmac) throws InvalidKeyException {
        hmac.init(key);//from ww w .  j  a  va 2s.c  om
        byte[] rawHashOutput = hmac.doFinal(valueToHash);
        if (rawHashOutput.length < oneHundredTwentyEightBitsInBytes) {
            throw new IllegalArgumentException(
                    "We got a hash function that didn't generate at least 128 bites of output");
        }
        return Arrays.copyOfRange(rawHashOutput, 0,
                oneHundredTwentyEightBitsInBytes);
    }
}

Related Tutorials