Java SHA1 SHA1(String text)

Here you can find the source of SHA1(String text)

Description

SHA

License

Open Source License

Parameter

Parameter Description
text a parameter

Exception

Parameter Description
NoSuchAlgorithmException an exception
UnsupportedEncodingException an exception

Return

The SHA1 hash of the input string

Declaration

public static String SHA1(String text) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    private static final String[] HEXES = { "0", "1", "2", "3", "4", "5",
            "6", "7", "8", "9", "A", "B", "C", "D", "E", "F" };

    /**//from   w w w  .  j  a v a  2s .  c  o  m
     * 
     * @param text
     * @return The SHA1 hash of the input string
     * @throws NoSuchAlgorithmException
     * @throws UnsupportedEncodingException
     */
    public static String SHA1(String text) {
        try {
            MessageDigest md;
            md = MessageDigest.getInstance("SHA-1");
            byte[] sha1hash = new byte[40];
            md.update(text.getBytes("iso-8859-1"), 0, text.length());
            sha1hash = md.digest();
            return convertToHex(sha1hash);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        throw new RuntimeException("Could not complete SHA1 hash!");
    }

    private static String convertToHex(byte[] raw) {
        if (raw == null) {
            return null;
        }
        final StringBuilder hex = new StringBuilder(2 * raw.length);
        for (final byte b : raw) {
            hex.append(HEXES[((b & 0xF0) >> 4)]).append(HEXES[b & 0x0F]);
        }
        return hex.toString();
    }
}

Related

  1. sha1(String str)
  2. sha1(String string)
  3. sha1(String string)
  4. SHA1(String strs)
  5. sha1(String text)
  6. sha1(String text)
  7. SHA1(String text)
  8. SHA1(String text)
  9. SHA1(String text)