Java SHA1 generateSHA1String(String stringToEncode)

Here you can find the source of generateSHA1String(String stringToEncode)

Description

Generates the SHA-1 digest for a given String based on UTF-8.

License

Apache License

Return

SHA-1 digest (40 characters).

Declaration

public static String generateSHA1String(String stringToEncode) 

Method Source Code


//package com.java2s;
/*//from  w ww .  j  a v a  2 s  .  c o m
 * Copyright (C) 2014 Markus Junginger, greenrobot (http://greenrobot.de)
 *
 * 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.io.UnsupportedEncodingException;
import java.math.BigInteger;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    /**
     * Generates the SHA-1 digest for a given String based on UTF-8. The digest is padded with zeroes in the front if
     * necessary. The SHA-1 algorithm is considers to produce less collisions than MD5.
     *
     * @return SHA-1 digest (40 characters).
     */
    public static String generateSHA1String(String stringToEncode) {
        return generateDigestString(stringToEncode, "SHA-1", "UTF-8", 40);
    }

    public static String generateDigestString(String stringToEncode, String digestAlgo, String encoding,
            int lengthToPad) {
        // Loosely inspired by http://workbench.cadenhead.org/news/1428/creating-md5-hashed-passwords-java
        MessageDigest digester;
        try {
            digester = MessageDigest.getInstance(digestAlgo);
        } catch (NoSuchAlgorithmException nsae) {
            throw new RuntimeException(nsae);
        }
        try {
            digester.update(stringToEncode.getBytes(encoding));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return toHexString(digester.digest(), lengthToPad);
    }

    public static String toHexString(byte[] bytes, int lengthToPad) {
        BigInteger hash = new BigInteger(1, bytes);
        String digest = hash.toString(16);

        while (digest.length() < lengthToPad) {
            digest = "0" + digest;
        }
        return digest;
    }
}

Related

  1. doSHA1(byte[] buf, int off, int len)
  2. generateSHA1(String message)
  3. generateSHA1ChecksumFile(String filename)
  4. generateSHA1Key(String input)
  5. generateSHA1RSASignature(RSAPrivateKey privKey, byte[] text)
  6. sha1(byte[] bytes)
  7. sha1(byte[] bytes)
  8. sha1(byte[] bytes)
  9. SHA1(byte[] bytes)