|
| 1 | +package com.bupin.frank; |
| 2 | + |
| 3 | +import java.io.ByteArrayOutputStream; |
| 4 | +import java.io.FileInputStream; |
| 5 | +import java.security.MessageDigest; |
| 6 | + |
| 7 | +public class HashDemo { |
| 8 | + public static void main(String[] args) throws Exception { |
| 9 | + String input = "frank"; |
| 10 | + String md5 = getDigest(input, "MD5"); |
| 11 | + System.out.println("md5:"+md5); |
| 12 | + String sha1 = getDigest(input, "SHA-1"); |
| 13 | + System.out.println("sha1:"+sha1); |
| 14 | + String sha256 = getDigest(input, "SHA-256"); |
| 15 | + System.out.println("sha256:"+sha256); |
| 16 | + String sha512 = getDigest(input, "SHA-512"); |
| 17 | + System.out.println("sha512:"+sha512); |
| 18 | + String fileSha1 = getDigestFile("a.txt", "SHA-1"); |
| 19 | + System.out.println("fileSha1:"+fileSha1); |
| 20 | + |
| 21 | + } |
| 22 | + |
| 23 | + /** |
| 24 | + * 获取消息摘要 |
| 25 | + * |
| 26 | + * @param input : 原文 |
| 27 | + * @param algorithm : 算法 |
| 28 | + * @return : 消息摘要 |
| 29 | + * @throws Exception |
| 30 | + */ |
| 31 | + public static String getDigest(String input, String algorithm) throws Exception { |
| 32 | + // 获取MessageDigest对象 |
| 33 | + MessageDigest messageDigest = MessageDigest.getInstance(algorithm); |
| 34 | + // 生成消息摘要 |
| 35 | + byte[] digest = messageDigest.digest(input.getBytes()); |
| 36 | + return toHex(digest); |
| 37 | + |
| 38 | + } |
| 39 | + |
| 40 | + /** |
| 41 | + * |
| 42 | + * @param filePath 文件路径 |
| 43 | + * @param algorithm 算法 |
| 44 | + * @return 返回对应的哈希值 |
| 45 | + * @throws Exception |
| 46 | + */ |
| 47 | + public static String getDigestFile(String filePath, String algorithm) throws Exception { |
| 48 | + FileInputStream fis = new FileInputStream(filePath); |
| 49 | + int len; |
| 50 | + byte[] buffer = new byte[1024]; |
| 51 | + ByteArrayOutputStream baos = new ByteArrayOutputStream(); |
| 52 | + while ((len = fis.read(buffer)) != -1) { |
| 53 | + baos.write(buffer, 0, len); |
| 54 | + } |
| 55 | + // 获取MessageDigest对象 |
| 56 | + MessageDigest messageDigest = MessageDigest.getInstance(algorithm); |
| 57 | + // 生成消息摘要 |
| 58 | + byte[] digest = messageDigest.digest(baos.toByteArray()); |
| 59 | + return toHex(digest); |
| 60 | + |
| 61 | + } |
| 62 | + |
| 63 | + // 将字节数组转为16进制字符串 |
| 64 | + public static String toHex(byte[] digest) { |
| 65 | + StringBuilder sb = new StringBuilder(); |
| 66 | + for (byte b : digest) { |
| 67 | + int i = b & 0xff; |
| 68 | + String s = Integer.toHexString(i); |
| 69 | + if (s.length() == 1) { |
| 70 | + s = "0" + s; |
| 71 | + } |
| 72 | + sb.append(s); |
| 73 | + } |
| 74 | + return sb.toString(); |
| 75 | + } |
| 76 | +} |
0 commit comments