> For the complete documentation index, see [llms.txt](https://alham-rizvi.gitbook.io/alhamrizvi/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://alham-rizvi.gitbook.io/alhamrizvi/cryptography/hashing/25.-base64.md).

# Base64 Encoding

## What is Base64?

**Base64** is a binary-to-text encoding scheme that represents binary data using 64 printable ASCII characters. It is used to safely transmit binary data over text-based protocols (email, HTTP headers, JSON, XML).

***

## Base64 Alphabet

```
A-Z = 0–25   (26 chars)
a-z = 26–51  (26 chars)
0-9 = 52–61  (10 chars)
+   = 62
/   = 63
=   = padding character
```

### Variants

| Variant    | Special chars | Use case               |
| ---------- | ------------- | ---------------------- |
| Standard   | `+` `/`       | MIME, PEM certificates |
| URL-safe   | `-` `_`       | URLs, JWTs, cookies    |
| No padding | no `=`        | Compact storage        |

***

## How Base64 Works

Base64 converts every **3 bytes** into **4 characters** (each character = 6 bits):

```
Input (3 bytes):   M          a          n
Binary:         01001101   01100001   01101110
                └──────────────────────────┘
                            24 bits
Group into 6:   010011  010110  000101  101110
Decimal:          19      22       5      46
Base64:           T       W       F      u

"Man" → "TWFu"
```

### Padding with `=`

* If input is not divisible by 3:
  * 1 extra byte → pad with `==`
  * 2 extra bytes → pad with `=`

```
"M"   → "TQ=="
"Ma"  → "TWE="
"Man" → "TWFu"
```

***

## Size Expansion

```
Every 3 bytes → 4 Base64 chars
Overhead: 4/3 ≈ 33.3% size increase

Formula: ceil(n / 3) × 4 characters
```

| Input size | Base64 size |
| ---------- | ----------- |
| 3 bytes    | 4 chars     |
| 9 bytes    | 12 chars    |
| 32 bytes   | 44 chars    |
| 1 KB       | \~1.37 KB   |
| 1 MB       | \~1.37 MB   |

***

## Implementation Examples

### Python

```python
import base64

# Encode
data = b"Hello, World!"
encoded = base64.b64encode(data)
print(encoded)  # b'SGVsbG8sIFdvcmxkIQ=='

# Decode
decoded = base64.b64decode(encoded)
print(decoded)  # b'Hello, World!'

# URL-safe variant
url_encoded = base64.urlsafe_b64encode(data)
print(url_encoded)  # b'SGVsbG8sIFdvcmxkIQ=='

# With strings
text = "Hello, World!"
encoded_str = base64.b64encode(text.encode()).decode()
decoded_str = base64.b64decode(encoded_str).decode()

# Encode file
with open("image.png", "rb") as f:
    img_base64 = base64.b64encode(f.read()).decode()
```

### JavaScript

```javascript
// Browser
const encoded = btoa("Hello, World!");        // "SGVsbG8sIFdvcmxkIQ=="
const decoded = atob("SGVsbG8sIFdvcmxkIQ=="); // "Hello, World!"

// Node.js (Buffer)
const encoded = Buffer.from("Hello, World!").toString('base64');
const decoded = Buffer.from(encoded, 'base64').toString('utf-8');

// URL-safe (replace + with - and / with _)
const urlSafe = Buffer.from(data).toString('base64url');

// Encode binary file
const fs = require('fs');
const fileData = fs.readFileSync('image.png');
const base64Image = fileData.toString('base64');
```

### Go

```go
import "encoding/base64"

// Standard
encoded := base64.StdEncoding.EncodeToString([]byte("Hello"))
decoded, _ := base64.StdEncoding.DecodeString(encoded)

// URL-safe
urlEncoded := base64.URLEncoding.EncodeToString([]byte("Hello"))

// No padding
rawEncoded := base64.RawStdEncoding.EncodeToString([]byte("Hello"))
```

### Rust

```rust
use base64::{Engine, engine::general_purpose};

let encoded = general_purpose::STANDARD.encode(b"Hello");
let decoded = general_purpose::STANDARD.decode(&encoded).unwrap();

// URL-safe
let url_encoded = general_purpose::URL_SAFE.encode(b"Hello");
```

***

## Common Use Cases in Cryptography & Security

### JWT (JSON Web Token)

```
eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJ1c2VyMTIzIn0.abc123
│                   │ │                        │ │     │
└── Header (Base64) ┘ └────── Payload (Base64) ┘ └─Sig─┘
```

### PEM Certificate

```
-----BEGIN CERTIFICATE-----
MIIDazCCAlOgAwIBAgIUYQ...   ← Base64-encoded DER certificate
-----END CERTIFICATE-----
```

### HTML Data URI

```html
<img src="data:image/png;base64,iVBORw0KGgo..." />
```

### Basic Auth HTTP Header

```
Authorization: Basic dXNlcjpwYXNzd29yZA==
                     └── base64("user:password")
```

***

## Security Considerations

| Misconception                | Reality                                |
| ---------------------------- | -------------------------------------- |
| Base64 is encryption         | ❌ It's encoding — trivially reversible |
| Base64 hides data            | ❌ Anyone can decode it instantly       |
| Base64 is compression        | ❌ It makes data 33% larger             |
| Base64 is safe for passwords | ❌ Never use Base64 alone for passwords |

```python
import base64
# "Decoding" Base64 is trivial:
base64.b64decode("dXNlcjpwYXNzd29yZA==")
# b'user:password'
```

***

## Base64 vs Alternatives

| Encoding       | Size overhead | Use case                 |
| -------------- | ------------- | ------------------------ |
| Hex            | 100%          | Debugging, checksums     |
| Base64         | 33%           | Files, binary in text    |
| Base85/Ascii85 | 25%           | PDF, git objects         |
| Base32         | 60%           | Case-insensitive systems |

***

## Best Practices

* Use **URL-safe Base64** (`-_` instead of `+/`) for URLs and JWTs
* Never use Base64 as a security measure — it's encoding, not encryption
* Strip or handle padding (`=`) carefully in URL contexts
* For binary comparison, always **decode first** then compare bytes
* Validate Base64 input before decoding (malformed input can cause errors)


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter, and the optional `goal` query parameter:

```
GET https://alham-rizvi.gitbook.io/alhamrizvi/cryptography/hashing/25.-base64.md?ask=<question>&goal=<endgoal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is optional and describes the broader end goal you are ultimately trying to accomplish on behalf of the user. GitBook uses it to tailor the answer towards what is most useful for that goal.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
