Md5 for file java

Java MD5 Hashing Example

The MD5, defined in RFC 1321, is a hash algorithm to turn inputs into a fixed 128-bit (16 bytes) length of the hash value.

Note
MD5 is not collision-resistant – Two different inputs may producing the same hash value. Read this MD5 vulnerabilities. There are many fast and secure hashing algorithms like SHA3-256 or BLAKE2; For password hashing, we can use Bcrypt or Argon2. If possible, do not use MD5 in any security-related cryptography tasks.

In Java, we can use MessageDigest to generate the MD5 algorithm.

 MessageDigest md = MessageDigest.getInstance("MD5"); byte[] result = md.digest(input); 

1. Java MD5 Hashing

This Java example uses MD5 to produce a hash value from a String.

 package com.mkyong.crypto.hash; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Utils < private static final Charset UTF_8 = StandardCharsets.UTF_8; private static final String OUTPUT_FORMAT = "%-20s:%s"; private static byte[] digest(byte[] input) < MessageDigest md; try < md = MessageDigest.getInstance("MD5"); >catch (NoSuchAlgorithmException e) < throw new IllegalArgumentException(e); >byte[] result = md.digest(input); return result; > private static String bytesToHex(byte[] bytes) < StringBuilder sb = new StringBuilder(); for (byte b : bytes) < sb.append(String.format("%02x", b)); >return sb.toString(); > public static void main(String[] args) < String pText = "Hello MD5"; System.out.println(String.format(OUTPUT_FORMAT, "Input (string)", pText)); System.out.println(String.format(OUTPUT_FORMAT, "Input (length)", pText.length())); byte[] md5InBytes = MD5Utils.digest(pText.getBytes(UTF_8)); System.out.println(String.format(OUTPUT_FORMAT, "MD5 (hex) ", bytesToHex(md5InBytes))); // fixed length, 16 bytes, 128 bits. System.out.println(String.format(OUTPUT_FORMAT, "MD5 (length)", md5InBytes.length)); >> 
 Input (string) :Hello MD5 Input (length) :9 MD5 (hex) :e5dadf6524624f79c3127e247f04b548 MD5 (length) :16 

Try another String, for example, Hello MD5 Hello MD5 . The input length varies, but the output of the MD5 hash value is still 128 bits, 16 bytes.

 Input (string) :Hello MD5 Hello MD5 Input (length) :19 MD5 (hex) :6219b1bc3542949e012616059409f1cc MD5 (length) :16 

2. Java MD5 File Checksum.

For the file checksum, the ideas are the same, but we need some extra IO classes to handle the input stream.

This Java program will generate an MD5 file checksum from a file.

 package com.mkyong.crypto.hash; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class MD5Utils < private static final Charset UTF_8 = StandardCharsets.UTF_8; private static final String OUTPUT_FORMAT = "%-20s:%s"; private static byte[] checksum(String filePath) < MessageDigest md; try < md = MessageDigest.getInstance("MD5"); >catch (NoSuchAlgorithmException e) < throw new IllegalArgumentException(e); >try (InputStream is = new FileInputStream(filePath); DigestInputStream dis = new DigestInputStream(is, md)) < while (dis.read() != -1) ; //empty loop to clear the data md = dis.getMessageDigest(); >catch (IOException e) < throw new IllegalArgumentException(e); >return md.digest(); > private static String bytesToHex(byte[] bytes) < StringBuilder sb = new StringBuilder(); for (byte b : bytes) < sb.append(String.format("%02x", b)); >return sb.toString(); > public static void main(String[] args) < String file = "c:\\test\\readme.txt"; System.out.println(String.format(OUTPUT_FORMAT, "Input (file) ", file)); System.out.println(String.format(OUTPUT_FORMAT, "MD5 (checksum hex) ", bytesToHex(checksum(file)))); >> 
 Input (file) :c:\test\readme.txt MD5 (checksum hex) :e5dadf6524624f79c3127e247f04b548 

3. Apache Commons Codec

This example uses the commons-codec library to generate the MD5 hash value.

  commons-codec commons-codec 1.14  

3.1 MD5 hash value from a String.

 import org.apache.commons.codec.digest.DigestUtils; String pText = "Hello MD5"; System.out.println(DigestUtils.md5Hex(password)); 
 e5dadf6524624f79c3127e247f04b548 

3.2 MD5 hash value from a File.

 try (InputStream is = new FileInputStream("c:\\test\\readme.txt")) < String checksum = DigestUtils.md5Hex(is); System.out.println(checksum); >catch (IOException e)
 e5dadf6524624f79c3127e247f04b548 

Источник

Читайте также:  Make list immutable java

Generate the MD5 Checksum for a File in Java

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

We rely on other people’s code in our own work. Every day.

It might be the language you’re writing in, the framework you’re building on, or some esoteric piece of software that does one thing so well you never found the need to implement it yourself.

The problem is, of course, when things fall apart in production — debugging the implementation of a 3rd party library you have no intimate knowledge of is, to say the least, tricky.

Lightrun is a new kind of debugger.

It’s one geared specifically towards real-life production environments. Using Lightrun, you can drill down into running applications, including 3rd party dependencies, with real-time logs, snapshots, and metrics.

Learn more in this quick, 5-minute Lightrun tutorial:

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

announcement - icon

DbSchema is a super-flexible database designer, which can take you from designing the DB with your team all the way to safely deploying the schema.

The way it does all of that is by using a design model, a database-independent image of the schema, which can be shared in a team using GIT and compared or deployed on to any database.

Читайте также:  Php global array null

And, of course, it can be heavily visual, allowing you to interact with the database using diagrams, visually compose queries, explore the data, generate random data, import data or build HTML5 database reports.

announcement - icon

The Kubernetes ecosystem is huge and quite complex, so it’s easy to forget about costs when trying out all of the exciting tools.

To avoid overspending on your Kubernetes cluster, definitely have a look at the free K8s cost monitoring tool from the automation platform CAST AI. You can view your costs in real time, allocate them, calculate burn rates for projects, spot anomalies or spikes, and get insightful reports you can share with your team.

Connect your cluster and start monitoring your K8s costs right away:

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

We’re looking for a new Java technical editor to help review new articles for the site.

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:

 commons-codec commons-codec 1.15 

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.

announcement - icon

Slow MySQL query performance is all too common. Of course it is. A good way to go is, naturally, a dedicated profiler that actually understands the ins and outs of MySQL.

The Jet Profiler was built for MySQL only, so it can do things like real-time query performance, focus on most used tables or most frequent queries, quickly identify performance issues and basically help you optimize your queries.

Читайте также:  Php post body data

Critically, it has very minimal impact on your server’s performance, with most of the profiling work done separately — so it needs no server changes, agents or separate services.

Basically, you install the desktop application, connect to your MySQL server, hit the record button, and you’ll have results within minutes:

Источник

Java File Checksum – MD5 and SHA-256 Hash Examples

A checksum hash is an encrypted sequence of characters obtained after applying specific algorithms and manipulations on user-provided content. In this Java hashing tutorial, we will learn to generate the checksum hash for the files.

1. Why Generate a File’s Checksum?

Any serious file provider provides a mechanism to have a checksum on their downloadable files. A checksum is a form of mechanism to ensure that the file we downloaded is correctly downloaded.

Checksum acts like a proof of the validity of a file so if a file gets corrupted this checksum will change and thus let us know that this file is not the same file or the file has been compromised between the transfer for any reason.

We can also create the file’s checksum to detect any possible change in the file by third parties e.g. license files. We provide licenses to clients which they may upload to their servers. We can cross-verify the file’s checksum to verify that the license file has not been modified after creation.

To create checksum for a file, we will need to read the file’s content, and then generate the hash for it using one of the following methods. Note that both approaches support all types of algorithms so we can use the same code for other algorithms such as HmacMd5, SHA, SHA-512 etc.

2. Generate File Checksum with MessageDigest

MessageDigest class provides applications with the functionality of a message digest algorithm, such as MD5 or SHA-256. Its getInstance() method returns a MessageDigest object that implements the specified digest algorithm.

Example 1: Generate MD5 Hash for a File in Java

Path filePath = Path.of("c:/temp/testOut.txt"); byte[] data = Files.readAllBytes(Paths.get(filePath)); byte[] hash = MessageDigest.getInstance("MD5").digest(data); String checksum = new BigInteger(1, hash).toString(16);

Example 2: Generate SHA-256 Hash for a File in Java

Path filePath = Path.of("c:/temp/testOut.txt"); byte[] data = Files.readAllBytes(Paths.get(filePath)); byte[] hash = MessageDigest.getInstance("SHA-256").digest(data); String checksum = new BigInteger(1, hash).toString(16);

3. Generate File Checksum with Guava

In Google Guava, ByteSource.hash() method hashes the contents with the specified hash function as method argument.

Start with adding the latest version of Guava to the project’s classpath.

 com.google.guava guava 31.1-jre  

Now we can use the hash() function as follows.

Example 1: Generate MD5 Hash for a File in Java

File file = new File("c:/temp/test.txt"); ByteSource byteSource = com.google.common.io.Files.asByteSource(file); HashCode hc = byteSource.hash(Hashing.md5()); String checksum = hc.toString();

Example 2: Generate SHA-256 Hash for a File in Java

File file = new File("c:/temp/test.txt"); ByteSource byteSource = com.google.common.io.Files.asByteSource(file); HashCode hc = byteSource.hash(Hashing.sha256()); String checksum = hc.toString();

Drop me a comment if something needs more explanation.

Источник

Оцените статью