Java
SHA-256
String Hashing
Cryptography
Coding Tutorial

How to hash some String with SHA-256 in Java?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Hashing is a process to generate a fixed-size digital fingerprint from data of arbitrary size, using certain algorithms. In Java, one of the most commonly used hashing algorithms is SHA-256, which is part of the SHA-2 (Secure Hash Algorithm 2) family developed by the National Institute of Standards and Technology (NIST). Hashing is widely used for data integrity verification, storing sensitive information such as passwords securely, and supporting common security operations like generating digital signatures.

Understanding SHA-256

SHA-256 stands for Secure Hashing Algorithm - 256 bit and is a cryptographic hash function which means, it takes an input (or 'message') and returns a fixed-size string of bytes. The output is typically a 256-bit (32-byte) hash, and is unique for every unique input. It is nearly impossible to generate the same hash output from two different inputs (this property is known as collision resistance).

Implementing SHA-256 Hashing in Java

Java supports SHA-256 hashing through its standard library, specifically through classes in the java.security package.

Step-by-step Implementation

Here's how to hash a string using SHA-256 in Java:

  1. Import Necessary Classes: Start by importing the required classes from the Java security package.
java
1    import java.security.MessageDigest;
2    import java.security.NoSuchAlgorithmException;
3    import java.nio.charset.StandardCharsets;
4    import java.util.HexFormat;
  1. Create a MessageDigest instance: MessageDigest is the class that provides applications the functionality of a message digest algorithm, such as SHA-256.
java
    MessageDigest digest = MessageDigest.getInstance("SHA-256");

getInstance might throw a NoSuchAlgorithmException if the algorithm specified is not available in the environment.

  1. Prepare Input and Digest the Data: Convert the input string to bytes, then feed them to the digest instance.
java
    byte[] hashbytes = digest.digest("Your input string".getBytes(StandardCharsets.UTF_8));
  1. Converting the Byte Array to Hexadecimal: Post hashing, the data is in a byte array form which can be further converted into a readable hexadecimal value.
java
    String shaHex = HexFormat.of().formatHex(hashbytes);
  1. Use the Result: The resultant hexadecimal string is your SHA-256 hash which can be used as needed in your application.

Key Considerations and Best Practices

  • Security: While SHA-256 is good for integrity verification, it should not be used alone for storing passwords. Combining it with a salt (random data) that is unique for each password and using a key derivation function like PBKDF2, bcrypt or Argon2 are recommended practices.
  • Efficiency: Hash functions are designed to be fast, yet this makes them vulnerable to brute-force attacks. When security against such attacks is a concern, consider using rate limiting or more computationally intense hash functions.
  • Usage: Hashes are irreversible by design. This means, once you convert data into a hash, you cannot convert it back to the original data. Always store the original data securely if you might need it later.

Additional Topics

  • Collision Resistance in SHA-256: Though SHA-256 is designed to be collision-resistant, its efficacy depends on maintaining a hash function with fewer chances of different inputs producing the same output.
  • Comparative Analysis with Other Algorithms: Understanding how SHA-256 compares with other algorithms like MD5, or SHA-1 in terms of speed and security can be crucial in deciding which algorithm to use.

Summary Table

FeatureDetails
Algorithm TypeCryptographic Hash Function
Output Size256 bit (32 bytes)
Collision ResistanceHigh (Not absolute)
SpeedFast (suitable for many applications)
Primary UseData integrity, Secure storage

In conclusion, hashing with SHA-256 in Java is straightforward thanks to the built-in libraries. This provides developers a ready tool to integrate data integrity and security measures into their applications efficiently. However, the choice of using SHA-256 must be informed by the specific requirements and the security context of the application.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.