Scala single line file to create MD5 hash from string

I am new to Scala and I found this interesting single line file for generating MD5 hexadecimal hash code from a string. I was hoping someone would 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("") {_ + _}
}

Thank.

+4
source share
1 answer

This is just an analog of this java code, but without StringBuilder (it is 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());

Consider the second line:

md.digest(inputStr.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft("") {_ + _}
  • md.digest (inputStr.getBytes ()) ---- take bytes from a string
  • md.digest (inputStr.getBytes ()). map (0xFF and _) --- bitwise and with each element of the array (the map returns a new array)
  • md.digest(inputStr.getBytes()). map (0xFF ). map { "% 02x".format()} .
  • md.digest(inputStr.getBytes()). map (0xFF ).map { "% 02x".format()}. foldLeft ( ") {_ + _} it , , " ", ( , " " StringBuilder, ). , .. scala. https://coderwall.com/p/4l73-a/scala-fold-foldleft-and-foldright
+1

Source: https://habr.com/ru/post/1650694/


All Articles