Here you can find the source of sha1(final String str)
Parameter | Description |
---|---|
str | - Text to crypt in Sha1 |
public static String sha1(final String str)
//package com.java2s; //License from project: LGPL import java.nio.ByteBuffer; import java.nio.CharBuffer; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Main { /**/* w w w. ja va2 s . co m*/ * Creates the Sha1 representation of a given string * * @param str * - Text to crypt in Sha1 * @return Generated Sha1 hash */ public static String sha1(final String str) { byte[] sha1hash = new byte[40]; try { final MessageDigest md = MessageDigest.getInstance("SHA-1"); md.update(str.getBytes(StandardCharsets.UTF_8)); sha1hash = md.digest(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); } return toHex(sha1hash); } /** * Generates the Sha1 representation for the empty string * * @return empty string coded in sha1 */ public static String sha1() { return sha1(""); } /** * Generates the Sha1 representation of a character array * * @param charArray * - character array to crypt in sha1 * @return Generated sha1 hash */ public static String sha1(final char[] charArray) { byte[] sha1hash = new byte[40]; try { final MessageDigest md = MessageDigest.getInstance("SHA-1"); final ByteBuffer buf = StandardCharsets.UTF_8.encode(CharBuffer.wrap(charArray)); final byte[] utf8 = new byte[buf.limit()]; buf.get(utf8); md.update(utf8); sha1hash = md.digest(); } catch (final NoSuchAlgorithmException e) { e.printStackTrace(); } return toHex(sha1hash); } /** * Converts data to an hexadecimal string * * @param data * - Data to convert to hexadecimal * @return String in hexadecimal */ private static String toHex(final byte[] data) { final StringBuffer buf = new StringBuffer(); for (final byte element : data) { int halfbyte = (element >>> 4) & 0x0F; int two_halfs = 0; do { if ((0 <= halfbyte) && (halfbyte <= 9)) { buf.append((char) ('0' + halfbyte)); } else { buf.append((char) ('a' + (halfbyte - 10))); } halfbyte = element & 0x0F; } while (two_halfs++ < 1); } return buf.toString(); } }