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.
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:
- Import Necessary Classes: Start by importing the required classes from the Java security package.
- Create a MessageDigest instance:
MessageDigestis the class that provides applications the functionality of a message digest algorithm, such as SHA-256.
getInstance might throw a NoSuchAlgorithmException if the algorithm specified is not available in the environment.
- Prepare Input and Digest the Data: Convert the input string to bytes, then feed them to the
digestinstance.
- 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.
- 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
| Feature | Details |
| Algorithm Type | Cryptographic Hash Function |
| Output Size | 256 bit (32 bytes) |
| Collision Resistance | High (Not absolute) |
| Speed | Fast (suitable for many applications) |
| Primary Use | Data 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
- How to have Android Service communicate with Activity
- How to have multiple cache manager configuration in spring cache java
- How to hot-reload properties in Java EE and Spring Boot?
- How to ignore SSL certificate errors in Apache HttpClient 4.0
- How to implement a distributed system using multiple ports with Java CORBA?
- How to implement a Kafka consumer in a Spring MVC web app (using Spring Boot)
- How to implement a microservice Event Driven architecture with Spring Cloud Stream Kafka and Database per service
- How to implement a stateful message listener using Spring Kafka?

OOD Fundamentals
Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.
View the courseTrack 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.