Base64 Encoding of Hash Output

Learn when and how to Base64-encode hash digests instead of using hexadecimal. Covers Base64 vs hex trade-offs, URL-safe Base64, and use cases in JWTs, SRI, and CSP.

General

Detailed Explanation

While hexadecimal is the most common encoding for hash digests, Base64 encoding offers a more compact representation. Some protocols and standards specifically require Base64-encoded hashes, making it important to understand when and how to use this format.

Base64 encoding basics:

Base64 represents binary data using 64 ASCII characters (A-Z, a-z, 0-9, +, /) plus "=" for padding. Every 3 bytes of input become 4 Base64 characters, resulting in approximately 33% size increase (compared to hex's 100% increase). A SHA-256 hash (32 bytes) becomes 44 Base64 characters versus 64 hex characters. A SHA-512 hash (64 bytes) becomes 88 Base64 characters versus 128 hex characters.

URL-safe Base64:

Standard Base64 uses "+" and "/" which have special meanings in URLs. URL-safe Base64 (also called Base64url, defined in RFC 4648) replaces "+" with "-" and "/" with "_". This variant is used in JWTs, which encode header and payload as Base64url. When hashing for URL contexts, always use URL-safe Base64 to avoid encoding issues.

Standards requiring Base64 hashes:

Subresource Integrity (SRI) uses Base64-encoded SHA-256, SHA-384, or SHA-512 hashes in HTML: <script integrity="sha256-[base64hash]">. Content Security Policy (CSP) uses the same format for script and style hashes. JSON Web Tokens (JWT) encode the HMAC-SHA256 signature in Base64url. HTTP Digest authentication uses Base64. Amazon S3's Content-MD5 header requires Base64-encoded MD5.

Converting between formats:

In JavaScript: btoa(String.fromCharCode(...new Uint8Array(hashBuffer))) converts raw hash bytes to Base64. In Python: base64.b64encode(hashlib.sha256(data).digest()).decode() produces Base64 (note: .digest() returns raw bytes, not .hexdigest()). In command line: sha256sum file | xxd -r -p | base64 converts hex to binary then to Base64.

Choosing between hex and Base64:

Use hex when: displaying hashes to users, storing checksums in files (SHA256SUMS), comparing hashes in logs, or when the standard/protocol expects hex. Use Base64 when: the protocol requires it (SRI, JWT, CSP), space efficiency matters (databases, URLs), or when interoperating with systems that use Base64. Consistency within a system is more important than the absolute choice.

Use Case

Base64 hash encoding is required for Subresource Integrity (SRI) tags in HTML, JWT signatures, Content Security Policy hashes, and Amazon S3 content verification.

Try It — Hash Generator

Open full tool