URL encoding, Base64, hexadecimal conversion, and hashing all transform data, but they solve different problems. This guide gives you a reusable decision process, practical code snippets, and a verification checklist so links remain valid, binary payloads survive transport, and sensitive values are handled safely.
Overview
The first question is whether you need to represent data, transport data, or verify data.
- URL encoding represents text safely inside a URL component. It converts characters such as spaces, ampersands, question marks, and non-ASCII characters into percent-encoded bytes.
- Base64 encoding represents arbitrary bytes as text. It is useful when a system accepts text but you need to carry binary data, such as a small file, certificate, or serialized message.
- Hexadecimal represents bytes using two hexadecimal characters per byte. It is common in logs, embedded systems, cryptographic output, memory inspection, and protocol documentation.
- Hashing creates a one-way digest intended for comparison or integrity checks. It is not a reversible encoding method.
These transformations are not interchangeable. URL-encoding a password does not protect it. Base64-encoding a secret does not make it confidential. Hashing a query parameter does not make it a valid URL value. Select the operation based on the receiving interface and the security requirement.
| Need | Use | Reversible? | Typical example |
|---|---|---|---|
| Put text in a query parameter | URL encoding | Yes | q=red%20shoes |
| Carry bytes through a text field | Base64 | Yes | JSON field containing an image fragment |
| Display or log bytes compactly | Hexadecimal | Yes | 48656c6c6f |
| Compare a value without storing it directly | Hashing | No | File integrity digest |
Checklist by scenario
Building a URL or query string
Encode each value according to its role as a URL component; do not manually replace spaces or punctuation. A query value such as red shoes & mugs must be encoded before it is joined to a URL:
const value = 'red shoes & mugs';
const url = new URL('https://example.com/search');
url.searchParams.set('q', value);
console.log(url.href);
// https://example.com/search?q=red+shoes+%26+mugsUsing URLSearchParams lets the platform handle delimiters and escaping. In Python, use urllib.parse.urlencode:
from urllib.parse import urlencode
query = urlencode({'q': 'red shoes & mugs', 'page': 2})
url = f'https://example.com/search?{query}'Do not encode the entire URL as one opaque string when only a parameter value needs encoding. Encoding the separators can turn ?, &, and = into data and produce a different request.
Sending JSON or ordinary text
JSON is already a text serialization format. Do not Base64-encode JSON unless the receiving protocol specifically requires a Base64 field. Send it with an appropriate content type and let the JSON serializer handle quoting and Unicode:
const payload = { message: 'café', enabled: true };
const body = JSON.stringify(payload);
fetch('/api/items', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body
});If a field contains binary data, encode only that field rather than wrapping the entire JSON document unnecessarily. This keeps the payload easier to inspect and reduces ambiguity about what must be decoded.
Moving binary data through a text-only channel
Use Base64 when the contract expects text but the source is bytes. In browsers, btoa and atob operate on byte-like strings, not arbitrary Unicode text. For Unicode text, first encode it as UTF-8:
const text = 'café';
const bytes = new TextEncoder().encode(text);
const binary = String.fromCodePoint(...bytes);
const encoded = btoa(binary);
const decodedBytes = Uint8Array.from(atob(encoded), c => c.charCodeAt(0));
const decoded = new TextDecoder().decode(decodedBytes);For a binary file in a server-side application, use the language's byte-oriented Base64 API. Standard Base64 uses +, /, and optional = padding. When the value will appear in a URL or filename, use the URL-safe alphabet, which substitutes - and _. Confirm whether the other side expects padding to remain or be removed.
Inspecting bytes or protocol values
Hexadecimal is often the clearest representation for debugging. For example, the UTF-8 bytes for Hello can be displayed as 48 65 6c 6c 6f. In Python:
data = 'Hello'.encode('utf-8')
hex_text = data.hex()
original = bytes.fromhex(hex_text).decode('utf-8')Hex is not compression and does not provide confidentiality. It normally doubles the number of characters needed to display a byte sequence, but its predictable format makes it useful in logs and low-level diagnostics.
Checking integrity or handling passwords
Use a cryptographic hash when you need a stable digest for comparison, such as detecting whether a downloaded artifact changed:
import hashlib
with open('artifact.bin', 'rb') as file:
digest = hashlib.sha256(file.read()).hexdigest()
print(digest)For passwords, do not use a single fast hash such as plain SHA-256 as a password-storage scheme. Use a password-hashing function designed to be slow and tunable, with a unique salt managed by a maintained library. Hashing also does not encrypt a value for later recovery; if the application must retrieve the original secret, use an appropriate encryption design and key-management process instead.
What to double-check
- Character encoding: Decide whether input is UTF-8 text or already-encoded bytes. Encoding a Unicode string as Base64 requires a defined byte encoding first.
- Encoding scope: URL-encode a component, not blindly the whole URL. In a path, query, fragment, form body, and HTTP header, escaping rules can differ.
- Spaces and plus signs: In form-style query encoding, a space may appear as
+. A literal plus sign must be escaped so it is not mistaken for a space by the decoder. - Base64 variant: Confirm standard versus URL-safe Base64, padding requirements, and whether line breaks are allowed.
- Whitespace: Remove accidental newlines or spaces only when the protocol says they are not meaningful. Some signed or encoded values are byte-sensitive.
- Round trips: Test encode-then-decode with empty input, ASCII, accented characters, emoji, reserved URL characters, and binary bytes including zero.
- Canonical form: If a signature or cache key depends on the transformed value, agree on parameter ordering, Unicode normalization, padding, and hex letter case.
- Secret exposure: Do not paste production tokens, passwords, private keys, or personal data into an online developer utility. A JWT decoder can inspect claims, but decoding is not verification; follow the verification workflow described in the JWT decoder guide.
For API failures, capture the exact outgoing URL, headers, and body in a safe test environment. The REST API debugging workflow can help separate an encoding error from an HTTP or authentication error.
Common mistakes
Confusing encoding with encryption
Anyone who can decode Base64 or hexadecimal can recover the original bytes. These formats make data transportable or readable; they do not restrict access. Treat a Base64 token as exposed if it contains sensitive information.
Hashing when decoding is required
A hash cannot be reversed through a decoder. If a service needs to recover the original value, hashing is the wrong transformation. If it only needs to compare a value or verify integrity, hashing may be appropriate.
Double-encoding values
Encoding an already encoded value can produce sequences such as %2520, where the percent sign itself was encoded. Define which layer owns encoding and decode exactly once at the corresponding boundary.
Using standard Base64 in a URL without checking
The standard alphabet includes characters that can have special meaning in URLs. Use a URL-safe variant when the protocol calls for it, and test padding behavior with the actual receiver.
Turning malformed input into silent data loss
Decoders should validate input and report errors rather than quietly discarding invalid characters. This matters especially for signed messages, identifiers, and binary protocols.
When to revisit
Return to this checklist whenever a workflow, library, runtime, or external API changes. Recheck the contract before switching languages, upgrading a serialization package, moving data from a request body into a URL, or replacing a standard Base64 helper with a URL-safe one. Also revisit it before seasonal planning or release cycles when integrations, deployment environments, and observability tools are reviewed.
A practical pre-release test should include:
- an ASCII value and a Unicode value;
- reserved URL characters such as
&,?,=,#, and+; - empty bytes, zero bytes, and a larger binary sample;
- standard and URL-safe Base64 cases if both appear in the system;
- known hash test vectors and a negative integrity test;
- an assertion that secrets never appear in URLs, logs, error messages, or third-party online tools.
When the result is unclear, write down the input type, the required output alphabet, the reversibility requirement, and the exact decoding owner. That small record usually reveals whether you need URL encoding, Base64, hexadecimal, hashing, or a different security mechanism altogether.