Is there any method to generate MD5 hash of a string in Java?
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
The
MessageDigest
class can provide you with an instance of the MD5 digest.When working with strings and the crypto classes be sure to always specify the encoding you want the byte representation in. If you just use
string.getBytes()
it will use the platform default. (Not all platforms use the same defaults)If you have a lot of data take a look at the
.update(byte[])
method which can be called repeatedly. Then call.digest()
to obtain the resulting hash.Another option is to use the Guava Hashing methods:
Handy if you are already using Guava (which if you're not, you probably should be).
I have a Class (Hash) to convert plain text in hash in formats: md5 or sha1, simillar that php functions (md5, sha1):
Testing with JUnit and PHP
PHP Script:
Output PHP script:
Using example and Testing with JUnit:
Code in GitHub
For what it's worth, I stumbled upon this because I want to synthesize GUIDs from a natural key for a program that will install COM components; I want to syhthesize so as not to manage GUID lifecycle. I'll use MD5 and then use the UUID class to get a string out of it. (http://stackoverflow.com/questions/2190890/how-can-i-generate-guid-for-a-string-values/12867439 raises this issue).
In any case, java.util.UUID can get you a nice String from the MD5 bytes.
My not very revealing answer:
I do not know if this is relevant for anyone reading this, but I just had the problem that I wanted to
I wanted to do it with JRE classes only (no Apache Commons or similar). A quick web search did not show me sample code snippets doing both at the same time, only each task separately. Because this requires to read the same file twice, I figured it might be worth the while to write some code which unifies both tasks, calculating the checksum on the fly while downloading the file. This is my result (sorry if it is not perfect Java, but I guess you get the idea anyway):