Java SHA1 sha1hex(String source)

Here you can find the source of sha1hex(String source)

Description

Returns a hex string representing the SHA-1 encoded source.

License

Open Source License

Declaration

public static String sha1hex(String source) 

Method Source Code

//package com.java2s;

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

public class Main {
    /** Used by {@link #hexlate} and {@link #unhexlate}. */
    protected static final String XLATE = "0123456789abcdef";

    /**/*from w ww. j  a va  2  s  .c om*/
     * Returns a hex string representing the SHA-1 encoded source.
     *
     * @exception RuntimeException thrown if the SHA-1 codec was not available in this JVM.
     */
    public static String sha1hex(String source) {
        return hexlate(digest("SHA-1", source));
    }

    /**
     * Generates a string from the supplied bytes that is the HEX encoded representation of those
     * bytes.  Returns the empty string for a <code>null</code> or empty byte array.
     *
     * @param bytes the bytes for which we want a string representation.
     * @param count the number of bytes to stop at (which will be coerced into being <= the length
     * of the array).
     */
    public static String hexlate(byte[] bytes, int count) {
        if (bytes == null) {
            return "";
        }

        count = Math.min(count, bytes.length);
        char[] chars = new char[count * 2];

        for (int i = 0; i < count; i++) {
            int val = bytes[i];
            if (val < 0) {
                val += 256;
            }
            chars[2 * i] = XLATE.charAt(val / 16);
            chars[2 * i + 1] = XLATE.charAt(val % 16);
        }

        return new String(chars);
    }

    /**
     * Generates a string from the supplied bytes that is the HEX encoded representation of those
     * bytes.
     */
    public static String hexlate(byte[] bytes) {
        return (bytes == null) ? "" : hexlate(bytes, bytes.length);
    }

    /**
     * Helper function for {@link #md5hex} and {@link #sha1hex}.
     */
    protected static byte[] digest(String codec, String source) {
        try {
            MessageDigest digest = MessageDigest.getInstance(codec);
            return digest.digest(source.getBytes());
        } catch (NoSuchAlgorithmException nsae) {
            throw new RuntimeException(codec + " codec not available");
        }
    }
}

Related

  1. sha1Hash(String toHash)
  2. sha1HashHex(String data)
  3. sha1HashInt(String text)
  4. sha1Hex(byte[] bytes)
  5. sha1Hex(String data)
  6. sha1Java(String password)
  7. sha1Sum(byte[] ba)
  8. sha1sum(byte[] data, Integer startIdxInc, Integer stopIdxExc)
  9. sha1sum(byte[] input, int length)