I'm new to Scala and I found this interesting one-liner to generate a hex-encoded MD5 hash from a string. I was hoping someone could help me understand this better.
private def getMd5(inputStr: String): String = {
val md: MessageDigest = MessageDigest.getInstance("MD5")
md.digest(inputStr.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft("") {_ + _}
}
Thanks.
Call MessageDigest. getInstance("MD5") to get a MD5 instance of MessageDigest you can use. The compute the hash by doing one of: Feed the entire input as a byte[] and calculate the hash in one operation with md.
What is an MD5 hash? An MD5 hash is created by taking a string of an any length and encoding it into a 128-bit fingerprint. Encoding the same string using the MD5 algorithm will always result in the same 128-bit hash output.
The hash size for the MD5 algorithm is 128 bits. The ComputeHash methods of the MD5 class return the hash as an array of 16 bytes. Note that some MD5 implementations produce a 32-character, hexadecimal-formatted hash.
How does MD5 work? MD5 runs entire files through a mathematical hashing algorithm to generate a signature that can be matched with an original file. That way, a received file can be authenticated as matching the original file that was sent, ensuring that the right files get where they need to go.
It's just a analogue to this java code but without StringBuilder (it's up to you)
MessageDigest messageDigest = MessageDigest.getInstance("SHA-512");
String password = "secret";
messageDigest.update(password.getBytes());
byte[] bytes = messageDigest.digest();
StringBuilder stringBuilder = new StringBuilder();
for (byte aByte : bytes) {
stringBuilder.append(Integer.toString((aByte & 0xff) + 0x100, 16).substring(1));
}
System.out.println(stringBuilder.toString());
Let's consider second line:
md.digest(inputStr.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft("") {_ + _}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With