Possible Duplicate:
Generate MD5 hash in Java
Hi,
I want to compute the MD5 hash of a string in my scala code. Is there any scala or java library i can use to do this quickly, apart from the regular java.security.MessageDigest way ?
Please Help 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.
Generally, two files can have the same md5 hash only if their contents are exactly the same. Even a single bit of variation will generate a completely different hash value. There is one caveat, though: An md5 sum is 128 bits (16 bytes).
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.
You can check using the following function: function isValidMd5($md5 ='') { return preg_match('/^[a-f0-9]{32}$/', $md5); } echo isValidMd5('5d41402abc4b2a76b9719d911017c592'); The MD5 (Message-digest algorithm) Hash is typically expressed in text format as a 32 digit hexadecimal number.
You may be reinventing a very tiny wheel here, but just write a function to do what you want: take a string, use MessageDigest, and return whatever (hex string, byte array) you need.
import java.security.MessageDigest def md5(s: String) = { MessageDigest.getInstance("MD5").digest(s.getBytes) } md5("Hello")
P.S. I don't write Scala, but this works and it's left as an exercise to the reader to turn it into anything other than an Array[Byte]
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