Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Generating a SHA-256 hash from the Linux command line
There are plenty of ways to generate a hash on any operating system, but when we talk about generating an almost-unique and fixed size bit hash, then nothing can replace the SHA algorithm.
Before making use of the Linux command to generate a SHA-256 hash, we must know what SHA actually is and what it is good for.
What is SHA-256?
SHA-256 in very simple terms is a cryptographic hash function that has a digest length of 256 bits. It is an algorithm that generates an almost-unique and fixed size 256-bit (32-byte) hash. This algorithm was developed by the NSA (National Security Agency) as part of the SHA-2 family of hash functions.
SHA-256 is widely used for data integrity verification, digital signatures, password storage, and blockchain technology. It produces a unique fingerprint for any input data, making it ideal for detecting data tampering or corruption.
Basic Example
Consider the following string −
I like Tutorialspoint
If we use the SHA-256 algorithm on the above string, we get the following hash −
1b2ca228e3847e330f006772aa0af2cd307f0ae92c6722cbb0c1533a84ba5339
Methods to Generate SHA-256 Hash
Linux provides two primary methods to generate SHA-256 hashes from the command line. Let's explore both approaches with examples.
Method 1 − Using OpenSSL
The first method uses the openssl command with the dgst (digest) option −
echo -n "TutorialPoint" | openssl dgst -sha256
Output −
(stdin)= 62e2de2644fa0987f79f54118c175d6a924e50aa60df1ff38e197eac0da8a963
Method 2 − Using sha256sum
The second method uses the dedicated sha256sum command, which is simpler and more direct −
echo -n "TutorialsPoint" | sha256sum
Output −
62e2de2644fa0987f79f54118c175d6a924e50aa60df1ff38e197eac0da8a963 -
Key Points
The
-nflag withechoprevents adding a newline character, ensuring accurate hash generation.Both methods produce the same hash value for identical input.
The
sha256summethod includes a dash (-) indicating input from stdin.You can also hash files directly using
sha256sum filename.
Comparison
| Method | Command | Advantages |
|---|---|---|
| OpenSSL | openssl dgst -sha256 |
Supports multiple hash algorithms, cleaner output format |
| sha256sum | sha256sum |
Simpler syntax, shows input source, widely available |
Conclusion
Both openssl dgst -sha256 and sha256sum commands effectively generate SHA-256 hashes in Linux. The choice between them depends on your specific needs and preference for output format. SHA-256 provides a reliable way to create unique fingerprints for data integrity and security purposes.
