Question
How can I hash a String using SHA-256 in Java?
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashExample {
public static void main(String[] args) {
String input = "Hello, World!";
String hashedOutput = hashString(input);
System.out.println("Hashed Output: " + hashedOutput);
}
public static String hashString(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes());
return bytesToHex(hash);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
Answer
Hashing a string using SHA-256 in Java is straightforward with the built-in `MessageDigest` class. SHA-256 is a widely adopted hashing algorithm that produces a fixed-size (256-bit) hash value, primarily used for data integrity and password storage.
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class HashExample {
public static void main(String[] args) {
String input = "Hello, World!";
String hashedOutput = hashString(input);
System.out.println("Hashed Output: " + hashedOutput);
}
public static String hashString(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes());
return bytesToHex(hash);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder();
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
}
}
Causes
- Choosing the correct hashing algorithm: Ensure that SHA-256 is suitable for your use case as other algorithms may be more efficient.
- Handling exceptions properly: Not managing exceptions can lead to runtime errors.
Solutions
- Import the necessary `java.security.MessageDigest` class when implementing SHA-256 hashing.
- Use the right encoding to convert the input string to bytes, typically UTF-8.
- Implement a utility method to convert the resultant byte array to a hexadecimal string format for readability.
Common Mistakes
Mistake: Not using the correct character encoding when converting strings to bytes.
Solution: Always specify UTF-8 encoding to handle characters appropriately.
Mistake: Forgetting to handle exceptions may crash the application.
Solution: Wrap your code in try-catch blocks to manage `NoSuchAlgorithmException`.
Helpers
- Java SHA-256
- hash string in Java
- SHA-256 example Java
- Java security
- string hashing Java