Returns the SHA-1 of the specified string - Java Security

Java examples for Security:SHA

Description

Returns the SHA-1 of the specified string

Demo Code


//package com.java2s;

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

public class Main {
    public static void main(String[] argv) throws Exception {
        String data = "java2s.com";
        System.out.println(sha1(data));
    }//from   ww  w  .  j a  va  2 s .c  o  m

    /**
     * Returns the SHA-1 of the specified string
     *
     * @param data
     *            A string value
     * @return The SHA-1 value
     */
    public static final String sha1(final String data) {
        if (null == data) {
            throw new IllegalArgumentException("null string");
        }

        try {
            final MessageDigest md = MessageDigest.getInstance("SHA-1");
            return toHexString(md.digest(data.getBytes()));
        } catch (final NoSuchAlgorithmException e) {
            return null;
        }
    }

    /**
     * Returns the specified data as hex sequence
     *
     * @param data
     *            The data
     * @return a hex string
     */
    public static String toHexString(byte[] data) {
        final int n = data.length;
        final StringBuilder hex = new StringBuilder();

        for (int i = 0; i < n; i++) {
            final byte b = data[i];
            hex.append(String.format("%02x", b & 0xff));
        }

        return hex.toString();
    }
}

Related Tutorials