Java SHA1 sha1(String txt)

Here you can find the source of sha1(String txt)

Description

sha

License

Open Source License

Parameter

Parameter Description
txt a parameter

Return

SHA-1 hash of txt (40 characters)

Declaration

public static String sha1(String txt) 

Method Source Code

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

import java.io.UnsupportedEncodingException;

public class Main {
    public static final String ENCODING_UTF8 = "UTF8";

    /**// w w  w.ja v a 2 s. c  o  m
     * @param txt
     * @return SHA-1 hash of txt (40 characters)
     */
    public static String sha1(String txt) {
        return hash("SHA1", txt);
    }

    /**
     * 
     * @param hashAlgorithm e.g. "MD5"
     * @param txt
     * @return
     */
    public static String hash(String hashAlgorithm, String txt) {
        if ("SHA256".equals(hashAlgorithm))
            hashAlgorithm = "SHA-256";
        try {
            java.security.MessageDigest md = java.security.MessageDigest.getInstance(hashAlgorithm);
            StringBuilder result = new StringBuilder();
            try {
                for (byte b : md.digest(txt.getBytes(ENCODING_UTF8))) {
                    result.append(Integer.toHexString((b & 0xf0) >>> 4));
                    result.append(Integer.toHexString(b & 0x0f));
                }
            } catch (UnsupportedEncodingException e) {
                for (byte b : md.digest(txt.getBytes())) {
                    result.append(Integer.toHexString((b & 0xf0) >>> 4));
                    result.append(Integer.toHexString(b & 0x0f));
                }
            }
            return result.toString();
        } catch (java.security.NoSuchAlgorithmException ex) {
            throw new RuntimeException(ex);
        }
    }
}

Related

  1. SHA1(String text)
  2. SHA1(String text)
  3. SHA1(String text)
  4. sha1(String text)
  5. SHA1(String texto)
  6. sha1(String utf8)
  7. sha1(String value)
  8. sha1(String value)
  9. sha12String(MessageDigest messageDigest)