Java provides the MessageDigest class to handle message digest algorithms, such as MD5, SHA-1 and SHA-256.
1. Java standard implementation
Use bit operations for the binary conversion.
import ; import ; public class Hash { private static final char[] hexCode = "0123456789ABCDEF".toCharArray(); public static String md5(String input) throws NoSuchAlgorithmException { byte[] bytes = ("MD5").digest(()); return printHexBinary(bytes); } public static String printHexBinary(byte[] data) { StringBuilder r = new StringBuilder( * 2); for (byte b : data) { (hexCode[(b >> 4) & 0xF]); (hexCode[(b & 0xF)]); } return (); } }
2. Use
Use for binary conversion.
import ; import ; public class Hash { public static String md5(String input) throws NoSuchAlgorithmException { byte[] bytes = ("MD5").digest(()); return printHexBinary(bytes); } public static String printHexBinary(byte[] data) { StringBuilder r = new StringBuilder( * 2); for (byte b : data) { (("%02X", new Integer(b & 0xFF))); } return (); } }
3. Kotlin's standard implementation
object Hash { private val HEX_CHARS = "0123456789ABCDEF".toCharArray() fun md5(input: String): String { val bytes = ("MD5").digest(()) return printHexBinary(bytes) } fun printHexBinary(data: ByteArray): String { val r = StringBuilder( * 2) { b -> val i = () (HEX_CHARS[i shr 4 and 0xF]) (HEX_CHARS[i and 0xF]) } return () } }
4. Kotlin extension function
fun String.md5(): String { val bytes = ("MD5").digest(()) return () } fun (): String { return joinToString("") { "%02X".format(it) } }
After defining the extension function, you can use the following syntax to calculate the MD5 value:
val hash = "foo-bar".md5()
This is the end of this article about several generation methods (summary) of MD5 in Android. For more information about Android MD5 generation, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!