Security Top – Temp

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security 5:

>> CHECK OUT THE COURSE
Frontegg – Security – Text1
announcement - icon User management is very complex, when implemented properly. No surprise here.

Not having to roll all of that out manually, but instead integrating a mature, fully-fledged solution - yeah, that makes a lot of sense.
That's basically what Frontegg is - User Management for your application. It's focused on making your app scalable, secure and enjoyable for your users.
From signup to authentication, it supports simple scenarios all the way to complex and custom application logic.

Have a look:

>> Elegant User Management, Tailor-made for B2B SaaS

1. Overview

A checksum is a sequence of characters used to uniquely identify a file. It is most commonly used to verify if a copy of a file is identical to an original.

In this short tutorial, we'll see how to generate the MD5 checksum for a file in Java.

2. Use MessageDigest Class

We can easily use the MessageDigest class in the java.security package to generate the MD5 checksum for a file:

byte[] data = Files.readAllBytes(Paths.get(filePath));
byte[] hash = MessageDigest.getInstance("MD5").digest(data);
String checksum = new BigInteger(1, hash).toString(16);

3. Use Apache Commons Codec

We can also use the DigestUtils class from the Apache Commons Codec library to achieve the same goal.

Let's add a dependency to our pom.xml file:

<dependency>
    <groupId>commons-codec</groupId>
    <artifactId>commons-codec</artifactId>
    <version>1.15</version>
</dependency>

Now, we simply use the md5Hex() method to get the MD5 checksum of our file:

try (InputStream is = Files.newInputStream(Paths.get(filePath))) {
    String checksum = DigestUtils.md5Hex(is);
    // ....
}

Let's not forget to use try-with-resources so that we don't have to worry about closing streams.

4. Use Guava

Finally, we can use the hash() method of a Guava‘s ByteSource object:

File file = new File(filePath);
ByteSource byteSource = com.google.common.io.Files.asByteSource(file);
HashCode hc = byteSource.hash(Hashing.md5());
String checksum = hc.toString();

5. Conclusion

In this quick tutorial, we've shown different ways to generate the MD5 checksum for a file in Java.

As always, the example code from this article can be found over on GitHub.

Security bottom

I just announced the new Learn Spring Security course, including the full material focused on the new OAuth2 stack in Spring Security 5:

>> CHECK OUT THE COURSE
Security footer banner
guest
0 Comments
Inline Feedbacks
View all comments