Java SHA1 sha1(String s)

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

Description

sha

License

Apache License

Declaration

public static String sha1(String s) 

Method Source Code


//package com.java2s;
/*/*from w ww . j  av  a 2  s.co m*/
 * This file is provided to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 * 
 * (C) 2013 John Muellerleile @jrecursive
 *
 */

import java.io.*;
import java.security.MessageDigest;

public class Main {
    private static final byte[] HEX_CHAR_TABLE = { (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4',
            (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'a', (byte) 'b', (byte) 'c',
            (byte) 'd', (byte) 'e', (byte) 'f' };

    public static String sha1(String s) {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            md.update(s.getBytes());
            return bytes2hex(md.digest());
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return null;
    }

    private static String bytes2hex(byte[] raw) throws UnsupportedEncodingException {

        byte[] hex = new byte[2 * raw.length];
        int index = 0;

        for (byte b : raw) {
            int v = b & 0xFF;
            hex[index++] = HEX_CHAR_TABLE[v >>> 4];
            hex[index++] = HEX_CHAR_TABLE[v & 0xF];
        }
        return new String(hex, "ASCII");
    }
}

Related

  1. sha1(String input, String encoding)
  2. sha1(String message)
  3. sha1(String param)
  4. sha1(String raw)
  5. sha1(String s)
  6. sha1(String s)
  7. sha1(String s)
  8. sha1(String s)
  9. sha1(String s)