Java SHA1 sha1(String str)

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

Description

sha

License

Apache License

Declaration

public static String sha1(String str) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.security.MessageDigest;

public class Main {

    public static String sha1(String str) {
        String sha1 = encode(str, "SHA-1");
        return sha1;
    }/*from  w w  w.  ja v a 2 s . c om*/

    private static String encode(String str, String type) {
        try {
            MessageDigest alga = MessageDigest.getInstance(type);
            alga.update(str.getBytes());
            byte digesta[] = alga.digest();
            String hex = byte2hex(digesta);
            // String hex2 = byte2hex2(digesta);
            // if (!hex.equals(hex2)) {
            // System.out.println("str:" + str);
            // }
            return hex;
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }

    private static String byte2hex(byte b[]) {
        StringBuilder sb = new StringBuilder();
        for (int n = 0; n < b.length; n++) {
            String stmp = Integer.toHexString(b[n] & 0xff);
            if (stmp.length() == 1) {
                // hs = hs + "0" + stmp;
                sb.append("0");
            }
            sb.append(stmp);
            // else {
            // // hs = hs + stmp;
            // }
        }

        return sb.toString().toUpperCase();
    }

    public static String toHexString(String s) {
        String str = "";
        for (int i = 0; i < s.length(); i++) {
            int ch = s.charAt(i);
            String s4 = Integer.toHexString(ch);
            str = str + s4;
        }
        return str;
    }
}

Related

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