HomeContact

Using hash functions in Java

Published in Java
January 30, 2023
1 min read

A hash function is a one-way function that maps arbitrary data of any length to data of a fixed length.

The unidirectional means that decoding is impossible. It is widely used for data and file integrity verification and encryption.

Types of hash functions mainly used include MD5, SHA-1, SHA-256, and SHA-512.


MD5

stringBuilder = new StringBuilder();
md5 = MessageDigest.getInstance("MD5");
md5.update(target.getBytes());
digest = md5.digest();
for (byte b : digest) {
stringBuilder.append(String.format("%02x", b));
}
result = stringBuilder.toString();


SHA-256

stringBuilder = new StringBuilder();
md = MessageDigest.getInstance("SHA-256");
md.update(target.getBytes());
digest = md.digest();
for (byte b : digest) {
stringBuilder.append(String.format("%02x", b));
}
result = stringBuilder.toString();


SHA-512

String data = "target_data";
String hex = null; //result data
try {
MessageDigest msg = MessageDigest.getInstance("SHA-512");
msg.update(data.getBytes());
hex = String.format("%128x", new BigInteger(1, msg.digest()));
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return hex;

Tags

#Java#encrypt

Share


Previous Article
Gradle install for windows users

Topics

Java
Other
Server

Related Posts

How to use BigInteger in Java - 2
May 31, 2023
1 min