TL;DR
This guide shows you how to take a SHA256 hash (a fingerprint of data) and encode it using Base64. This is useful for storing or transmitting the hash in systems that only support text-based formats.
Steps
- Generate the SHA256 Hash
- Python:
- Bash (using
openssl): - JavaScript:
- Encode the Hash in Base64
- Python:
- Bash (using
openssl): - JavaScript:
- Decoding the Base64 Hash (Optional)
- Python:
- Bash:
- JavaScript:
First, you need to create a SHA256 hash of your data. The method depends on what language or tool you’re using. Here are some examples:
import hashlib
data = "your_data"
sha256_hash = hashlib.sha256(data.encode('utf-8')).hexdigest()
print(sha256_hash)
echo -n "your_data" | openssl dgst -sha256
const crypto = require('crypto');
const data = "your_data";
const sha256Hash = crypto.createHash('sha256').update(data).digest('hex');
console.log(sha256Hash);
The output will be a long hexadecimal string (e.g., a1b2c3d4...).
Now, take that hex string and encode it using Base64.
import base64
data = "your_data"
sha256_hash = hashlib.sha256(data.encode('utf-8')).hexdigest()
base64_encoded = base64.b64encode(sha256_hash.encode('utf-8')).decode('utf-8')
print(base64_encoded)
echo -n "your_data" | openssl dgst -sha256 | base64
const crypto = require('crypto');
const data = "your_data";
const sha256Hash = crypto.createHash('sha256').update(data).digest('hex');
const base64Encoded = Buffer.from(sha256Hash, 'hex').toString('base64');
console.log(base64Encoded);
The output will be a Base64 encoded string (e.g., ZGVmYmVjYWQ...).
If you need to get back the original SHA256 hash from the Base64 string, you can decode it:
import base64
base64_string = "ZGVmYmVjYWQ..."
decoded_hash = base64.b64decode(base64_string).decode('utf-8')
print(decoded_hash)
echo "ZGVmYmVjYWQ..." | base64 -d
const base64String = "ZGVmYmVjYWQ...";
const decodedHash = Buffer.from(base64String, 'base64').toString('hex');
console.log(decodedHash);

