Blog | G5 Cyber Security

SHA256 Hash to Base64

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

  1. Generate the SHA256 Hash
  2. 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)
  • Bash (using openssl):
  • echo -n "your_data" | openssl dgst -sha256
  • JavaScript:
  • 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...).

  • Encode the Hash in Base64
  • 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)
  • Bash (using openssl):
  • echo -n "your_data" | openssl dgst -sha256 | base64
  • JavaScript:
  • 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...).

  • Decoding the Base64 Hash (Optional)
  • 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)
  • Bash:
  • echo "ZGVmYmVjYWQ..." | base64 -d
  • JavaScript:
  • const base64String = "ZGVmYmVjYWQ...";
    const decodedHash = Buffer.from(base64String, 'base64').toString('hex');
    console.log(decodedHash);
    Exit mobile version