All Downloads are FREE. Search and download functionalities are using the official Maven repository.

cn.bestwu.api.test.Sha1DigestUtil Maven / Gradle / Ivy

There is a newer version: 1.3.19
Show newest version
package cn.bestwu.api.test;

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

/**
 * Sha1加密工具类
 *
 * @author Peter Wu
 */
public class Sha1DigestUtil {

	/**
	 * Returns an SHA digest.
	 *
	 * @return An SHA digest instance.
	 * @throws RuntimeException when a {@link NoSuchAlgorithmException} is
	 *                          caught.
	 */
	private static MessageDigest getSha1Digest() {
		try {
			return MessageDigest.getInstance("SHA-1");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	/**
	 * Calculates the SHA digest and returns the value as a {@code byte[]}.
	 *
	 * @param data Data to digest
	 * @return SHA digest
	 */
	public static byte[] sha(byte[] data) {
		return getSha1Digest().digest(data);
	}

	/**
	 * Calculates the SHA digest and returns the value as a {@code byte[]}.
	 *
	 * @param data Data to digest
	 * @return SHA digest
	 */
	public static byte[] sha(String data) {
		return sha(data.getBytes());
	}

	/**
	 * Calculates the SHA digest and returns the value as a hex string.
	 *
	 * @param data Data to digest
	 * @return SHA digest as a hex string
	 */
	public static String shaHex(byte[] data) {
		return new String(Hex.encode(sha(data)));
	}

	/**
	 * Calculates the SHA digest and returns the value as a hex string.
	 *
	 * @param data Data to digest
	 * @return SHA digest as a hex string
	 */
	public static String shaHex(String data) {
		return new String(Hex.encode(sha(data)));
	}

	public static final class Hex {

		private static final char[] HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };

		public static char[] encode(byte[] bytes) {
			final int nBytes = bytes.length;
			char[] result = new char[2 * nBytes];

			int j = 0;
			for (byte aByte : bytes) {
				// Char for top 4 bits
				result[j++] = HEX[(0xF0 & aByte) >>> 4];
				// Bottom 4
				result[j++] = HEX[(0x0F & aByte)];
			}

			return result;
		}

		public static byte[] decode(CharSequence s) {
			int nChars = s.length();

			if (nChars % 2 != 0) {
				throw new IllegalArgumentException(
						"Hex-encoded string must have an even number of characters");
			}

			byte[] result = new byte[nChars / 2];

			for (int i = 0; i < nChars; i += 2) {
				int msb = Character.digit(s.charAt(i), 16);
				int lsb = Character.digit(s.charAt(i + 1), 16);

				if (msb < 0 || lsb < 0) {
					throw new IllegalArgumentException("Non-hex character in input: " + s);
				}
				result[i / 2] = (byte) ((msb << 4) | lsb);
			}
			return result;
		}

	}

}




© 2015 - 2025 Weber Informatics LLC | Privacy Policy