Java字符串、文件MD5工具类
程序员文章站
2024-03-19 11:03:52
...
转载请标明出处:http://blog.csdn.net/zhaoyanjun6/article/details/120874209
本文出自【赵彦军的博客】
Hex
首先定义 Hex
工具类, 来源于 apache
开源工具类 https://commons.apache.org/proper/commons-codec/download_codec.cgi
/**
* @author : zhaoyanjun
* @time : 2021/6/8
* @desc : file md5值 https://commons.apache.org/proper/commons-codec/download_codec.cgi
*/
public class Hex {
/**
* Used to build output as hex.
*/
private static final char[] DIGITS_LOWER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd',
'e', 'f'};
/**
* Used to build output as hex.
*/
private static final char[] DIGITS_UPPER = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F'};
public Hex() {
// use default encoding
}
/**
* Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
* The returned array will be double the length of the passed array, as it takes two characters to represent any
* given byte.
*
* @param data a byte[] to convert to hex characters
* @return A char[] containing lower-case hexadecimal characters
* true:32位小写 718b6dd54c8d1d3ad19eb99cb12f13e2
* false:32位大写 718B6DD54C8D1D3AD19EB99CB12F13E2
*/
public static char[] encodeHex(final byte[] data) {
return encodeHex(data, true);
}
/**
* Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
* The returned array will be double the length of the passed array, as it takes two characters to represent any
* given byte.
*
* @param data a byte[] to convert to Hex characters
* @param toLowerCase {@code true} converts to lowercase, {@code false} to uppercase
* @return A char[] containing hexadecimal characters in the selected case
* @since 1.4
*/
public static char[] encodeHex(final byte[] data, final boolean toLowerCase) {
return encodeHex(data, toLowerCase ? DIGITS_LOWER : DIGITS_UPPER);
}
/**
* Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
* The returned array will be double the length of the passed array, as it takes two characters to represent any
* given byte.
*
* @param data a byte[] to convert to hex characters
* @param toDigits the output alphabet (must contain at least 16 chars)
* @return A char[] containing the appropriate characters from the alphabet For best results, this should be either
* upper- or lower-case hex.
* @since 1.4
*/
protected static char[] encodeHex(final byte[] data, final char[] toDigits) {
final int l = data.length;
final char[] out = new char[l << 1];
encodeHex(data, 0, data.length, toDigits, out, 0);
return out;
}
/**
* Converts an array of bytes into an array of characters representing the hexadecimal values of each byte in order.
*
* @param data a byte[] to convert to hex characters
* @param dataOffset the position in {@code data} to start encoding from
* @param dataLen the number of bytes from {@code dataOffset} to encode
* @param toDigits the output alphabet (must contain at least 16 chars)
* @param out a char[] which will hold the resultant appropriate characters from the alphabet.
* @param outOffset the position within {@code out} at which to start writing the encoded characters.
*/
private static void encodeHex(final byte[] data, final int dataOffset, final int dataLen, final char[] toDigits,
final char[] out, final int outOffset) {
// two characters form the hex value.
for (int i = dataOffset, j = outOffset; i < dataOffset + dataLen; i++) {
out[j++] = toDigits[(0xF0 & data[i]) >>> 4];
out[j++] = toDigits[0x0F & data[i]];
}
}
}
MD5Util
import java.io.File
import java.io.FileInputStream
import java.io.IOException
import java.io.InputStream
import java.security.MessageDigest
import java.security.NoSuchAlgorithmException
/**
* @author : zhaoyanjun
* @time : 2021/9/17
* @desc :
*/
object MD5Util {
/**
*文件Md5
*/
@Throws(NoSuchAlgorithmException::class, IOException::class)
fun md5(file: File): String {
FileInputStream(file).use { input ->
return md5(input)
}
}
/**
* 字符串字符串md5
*/
@Throws(NoSuchAlgorithmException::class, IOException::class)
fun md5(message: String): String {
message.byteInputStream().use { input ->
return md5(input)
}
}
/**
* 字节数组md5
*/
@Throws(NoSuchAlgorithmException::class, IOException::class)
fun md5(byteArray: ByteArray): String {
byteArray.inputStream().use { input ->
return md5(input)
}
}
/**
* InputStream md5
* 可处理大文件
*/
@Throws(NoSuchAlgorithmException::class, IOException::class)
private fun md5(input: InputStream): String {
val messageDigest = MessageDigest.getInstance("MD5")
val buffer = ByteArray(8192)
var length: Int
while (input.read(buffer).also { length = it } != -1) {
messageDigest.update(buffer, 0, length)
}
return String(Hex.encodeHex(messageDigest.digest()))
}
}
使用
//字符串md5
val message = "今天是周三"
val md5 = MD5Util.md5(message)
//文件md5
val file = File("")
val md5 = MD5Util.md5(file)
//字节数组md5
val byteArray = message.toByteArray()
val md5 = MD5Util.md5(byteArray)
其他实现方式
方式一
fun getFileMD5(file: File): String? {
val bufferSize = 4 * 1024
var fileInputStream: FileInputStream? = null
var digestInputStream: DigestInputStream? = null
try {
var messageDigest = MessageDigest.getInstance("MD5")
fileInputStream = FileInputStream(file)
digestInputStream = DigestInputStream(fileInputStream, messageDigest)
val buffer = ByteArray(bufferSize)
while (digestInputStream.read(buffer) > 0) messageDigest =
digestInputStream.messageDigest
val bigInt = BigInteger(1, messageDigest.digest())
return bigInt.toString(16)
} catch (e: Exception) {
return null
} finally {
try {
digestInputStream?.close()
} catch (e: Exception) {
}
try {
fileInputStream?.close()
} catch (e: Exception) {
}
}
}