Java 提供了 MessageDigest
类用来处理消息摘要算法,如 MD5
, SHA-1
和 SHA-256
等。
1. Java 的标准实现
使用位运算进行进制转换。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Hash {
private static final char[] hexCode = "0123456789ABCDEF".toCharArray();
public static String md5(String input) throws NoSuchAlgorithmException {
byte[] bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
return printHexBinary(bytes);
}
public static String printHexBinary(byte[] data) {
StringBuilder r = new StringBuilder(data.length * 2);
for (byte b : data) {
r.append(hexCode[(b >> 4) & 0xF]);
r.append(hexCode[(b & 0xF)]);
}
return r.toString();
}
}
2. 使用 String.format
使用 String.format
进行进制转换。
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Hash {
public static String md5(String input) throws NoSuchAlgorithmException {
byte[] bytes = MessageDigest.getInstance("MD5").digest(input.getBytes());
return printHexBinary(bytes);
}
public static String printHexBinary(byte[] data) {
StringBuilder r = new StringBuilder(data.length * 2);
for (byte b : data) {
r.append(String.format("%02X", new Integer(b & 0xFF)));
}
return r.toString();
}
}
3. Kotlin 的标准实现
object Hash {
private val HEX_CHARS = "0123456789ABCDEF".toCharArray()
fun md5(input: String): String {
val bytes = MessageDigest.getInstance("MD5").digest(input.toByteArray())
return printHexBinary(bytes)
}
fun printHexBinary(data: ByteArray): String {
val r = StringBuilder(data.size * 2)
data.forEach { b ->
val i = b.toInt()
r.append(HEX_CHARS[i shr 4 and 0xF])
r.append(HEX_CHARS[i and 0xF])
}
return r.toString()
}
}
4. Kotlin 扩展函数
fun String.md5(): String {
val bytes = MessageDigest.getInstance("MD5").digest(this.toByteArray())
return bytes.hex()
}
fun ByteArray.hex(): String {
return joinToString("") { "%02X".format(it) }
}
定义完扩展函数后,就可以使用下面的语法来计算MD5值:
val hash = "foo-bar".md5()
网友评论