/** 对文件进行散列, 支持md5与sha1算法. */ private static String digest(InputStream input, String algorithm) throws IOException { try { MessageDigest messageDigest = MessageDigest.getInstance(algorithm); int bufferLength = 1024; byte[] buffer = new byte[bufferLength]; int read = input.read(buffer, 0, bufferLength); while (read > -1) { messageDigest.update(buffer, 0, read); read = input.read(buffer, 0, bufferLength); } return EncodeUtil.hexEncode(messageDigest.digest()); } catch (GeneralSecurityException e) { throw new IllegalStateException("Security exception", e); } }
/** 对输入字符串进行sha1散列, 返回Base64编码的URL安全的结果. */ public static String sha1ToBase64UrlSafe(String input) { byte[] digestResult = digest(input, SHA1); return EncodeUtil.base64UrlSafeEncode(digestResult); }
/** 对输入字符串进行sha1散列, 返回Hex编码的结果. */ public static String sha1ToHex(String input) { byte[] digestResult = digest(input, SHA1); return EncodeUtil.hexEncode(digestResult); }