Java SHA1 sha1(String message)

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

Description

sha

License

Apache License

Declaration

public static String sha1(String message) 

Method Source Code

//package com.java2s;
/*/*from   ww w  .ja  v  a  2s  .c om*/
 * Copyright 2008 Alberto Gimeno <gimenete at gmail.com>
 *
 *   Licensed 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.
 */

import java.security.MessageDigest;

public class Main {
    public static String sha1(String message) {
        try {
            byte[] buffer = message.getBytes("UTF-8");
            MessageDigest md = MessageDigest.getInstance("SHA1");
            md.update(buffer);
            byte[] digest = md.digest();
            char[] hash = new char[40];

            for (int i = 0, n = 0; i < digest.length; i++) {
                byte aux = digest[i];
                int b = aux & 0xff;
                String hex = Integer.toHexString(b);
                if (hex.length() == 1) {
                    hash[n++] = '0';
                    hash[n++] = hex.charAt(0);
                } else {
                    hash[n++] = hex.charAt(0);
                    hash[n++] = hex.charAt(1);
                }
            }
            return new String(hash);
        } catch (Exception e) {
            // should never happen. UTF-8 and SHA1 are constants
            throw new RuntimeException(e);
        }
    }
}

Related

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