Java examples for Security:SHA
Calculates the SHA-1 digest and returns the value as a hex string.
//package com.java2s; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Main { public static void main(String[] argv) throws Exception { String data = "java2s.com"; System.out.println(shaHex(data)); }/* w w w. j a v a 2 s . com*/ /** * Calculates the SHA-1 digest and returns the value as a hex string. * * @param data Data to digest * @return SHA-1 digest as a hex string */ public static String shaHex(String data) { MessageDigest messageDigest = getMessageDigest("SHA-1"); byte[] digest = messageDigest.digest(data.getBytes()); StringBuffer hexString = new StringBuffer(); for (byte aDigest : digest) { hexString.append(Integer.toHexString(0x100 | 0xFF & aDigest) .substring(1)); } return hexString.toString(); } /** * Returns a MessageDigest for the given algorithm. * * @param algorithm the name of the algorithm requested. * @return A MessageDigest instance * @throws RuntimeException */ static MessageDigest getMessageDigest(String algorithm) { try { return MessageDigest.getInstance(algorithm); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e.getMessage()); } } }