Java SHA1 sha1(String value)

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

Description

sha

License

Apache License

Declaration

public static String sha1(String value) 

Method Source Code


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

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

public class Main {
    private final static String SHA1 = "SHA1";
    private final static String CHARSET = "UTF-8";

    public static String sha1(String value) {
        return byte2hex(digest(value, SHA1));
    }/*from ww w  .  j ava  2s. c o  m*/

    public static String byte2hex(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(bytes[i] & 0xFF);
            if (hex.length() == 1) {
                sb.append("0");
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    private static byte[] digest(String value, String algorithm) {
        if (value == null || "".equals(value.trim())) {
            return null;
        }

        byte[] bytes = null;
        try {
            MessageDigest md = MessageDigest.getInstance(algorithm);
            bytes = md.digest(value.getBytes(CHARSET));
        } catch (NoSuchAlgorithmException e) {
            //NOP
        } catch (UnsupportedEncodingException e) {
            //NOP
        }

        return bytes;
    }
}

Related

  1. sha1(String text)
  2. SHA1(String texto)
  3. sha1(String txt)
  4. sha1(String utf8)
  5. sha1(String value)
  6. sha12String(MessageDigest messageDigest)
  7. sha1_b64(final String text)
  8. SHA1_HEX(byte[] bytes)
  9. sha1AsBytes(String input)