Compute the SHA-1 digest of raw bytes and return the bytes in hexadecimal format. - Java java.lang

Java examples for java.lang:String Hex

Description

Compute the SHA-1 digest of raw bytes and return the bytes in hexadecimal format.

Demo Code


//package com.java2s;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] argv) {
        byte[] message = new byte[] { 34, 35, 36, 37, 37, 37, 67, 68, 69 };
        System.out.println(computeSha1OfByteArray(message));
    }//from w ww.  j ava  2  s . c o  m

    /**
     * Lower case Hex Digits.
     */
    private static final String HEX_DIGITS = "0123456789abcdef";
    /**
     * Byte mask.
     */
    private static final int BYTE_MSK = 0xFF;
    /**
     * Hex digit mask.
     */
    private static final int HEX_DIGIT_MASK = 0xF;
    /**
     * Number of bits per Hex digit (4).
     */
    private static final int HEX_DIGIT_BITS = 4;

    /**
     * Compute the SHA-1 digest of raw bytes and return the bytes in
     * hexadecimal format.
     *
     * @param message
     * the raw byte array to be encoded
     * @return a SHA-1 hash
     * @throws UnsupportedOperationException
     * in the case SHA-1 MessageDigest is not supported, you
     * shouldn't bother catching this exception
     */
    private static String computeSha1OfByteArray(final byte[] message)
            throws UnsupportedOperationException {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(message);
            byte[] res = md.digest();
            return toHexString(res);
        } catch (NoSuchAlgorithmException ex) {
            throw new UnsupportedOperationException(ex);
        }
    }

    /**
     * Compute a String in HexDigit from the input.
     *
     * @param byteArray
     * a row byte array
     * @return a hex String
     */
    private static String toHexString(final byte[] byteArray) {
        StringBuilder sb = new StringBuilder(byteArray.length * 2);
        for (int i = 0; i < byteArray.length; i++) {
            int b = byteArray[i] & BYTE_MSK;
            sb.append(HEX_DIGITS.charAt(b >>> HEX_DIGIT_BITS)).append(
                    HEX_DIGITS.charAt(b & HEX_DIGIT_MASK));
        }
        return sb.toString();
    }
}

Related Tutorials