Java SHA1 digestSHA1(String text)

Here you can find the source of digestSHA1(String text)

Description

Calculate the SHA-1 digest code for the text.

License

Open Source License

Parameter

Parameter Description
text Text to be digested.

Return

Digest text as by the SHA-1 code.

Declaration

public static String digestSHA1(String text) 

Method Source Code

//package com.java2s;
/*/*from ww w  .j av  a2s.co  m*/
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
    
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
    
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
    
Copyright (C) 2007 Marco Aurelio Graciotto Silva <magsilva@gmail.com>
 */

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

public class Main {
    /**
     * Calculate the SHA-1 digest code for the text.
     *
     * @param text Text to be digested.
     * @return Digest text as by the SHA-1 code.
     */
    public static String digestSHA1(String text) {
        return digest(text, "SHA1");
    }

    /**
     * Create the hash/digest code for a given text.
     *
     * @param text Text to be digested.
     * @param algorithm Digest code to be used (usually MD5 or SHA1).
     *
     * @return Digest code.
     * @throws IllegalArgumentException if an invalid text (null) is set.
     */
    public static String digest(String text, String algorithm) {
        if (text == null) {
            throw new IllegalArgumentException(new NullPointerException());
        }

        MessageDigest md;
        try {
            md = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IllegalArgumentException(e);
        }
        byte[] hash = md.digest(text.getBytes());
        StringBuilder sb = new StringBuilder();

        for (byte b : hash) {
            String hex = Integer.toHexString(b);
            int len = hex.length();
            if (len == 1) {
                sb.append("0" + hex);
            } else {
                sb.append(hex.substring(len - 2, len));
            }
        }

        return sb.toString();
    }
}

Related

  1. computeSha1AsHexString(String strToHash)
  2. computeSHA1Hash(byte[] data)
  3. digestSHA1(byte[] data)
  4. digestSHA1(String data)
  5. digestSHA1(String login, String pass)
  6. digestSha1Hex(String source)
  7. doSHA1(byte[] buf)
  8. doSHA1(byte[] buf, int off, int len)
  9. generateSHA1(String message)