|
| 1 | +# base64hub |
| 2 | + |
| 3 | +Base64 encode, decode and validate from Python or the shell. One small package, standard library only, |
| 4 | +with a `b64` command that behaves the same as the base64hub CLI for Go and npm. |
| 5 | + |
| 6 | +- **Lenient decoding**: standard and URL-safe alphabets (even mixed), missing padding, spaces, tabs |
| 7 | + and line breaks, `data:...;base64,` prefixes. Errors name the problem and its position. |
| 8 | +- **Encoding options**: URL-safe alphabet (RFC 4648 §5), no padding, line wrapping (76 for MIME), |
| 9 | + data URIs with the MIME type sniffed from the bytes (PNG, JPEG, GIF, WebP, PDF, SVG, text). |
| 10 | +- **Validation** that tells you the variant, whether it is padded and how many bytes it holds. |
| 11 | +- Python 3.9 or newer, zero dependencies, type hints included. |
| 12 | + |
| 13 | +Home page: [base64hub.com/pypi](https://base64hub.com/pypi/) · Docs: [base64hub.com/docs/python](https://base64hub.com/docs/python/) · |
| 14 | +Online tools: [base64hub.com](https://base64hub.com/) |
| 15 | + |
| 16 | +## Install |
| 17 | + |
| 18 | +As a command-line tool (isolated environment, puts `b64` on your PATH): |
| 19 | + |
| 20 | +```sh |
| 21 | +pipx install base64hub |
| 22 | +``` |
| 23 | + |
| 24 | +As a library: |
| 25 | + |
| 26 | +```sh |
| 27 | +pip install base64hub |
| 28 | +``` |
| 29 | + |
| 30 | +## Command line |
| 31 | + |
| 32 | +``` |
| 33 | +b64 [flags] [TEXT] |
| 34 | +``` |
| 35 | + |
| 36 | +With TEXT, `b64` works on its UTF-8 bytes; without it, it reads stdin (or `-i FILE`). |
| 37 | + |
| 38 | +```console |
| 39 | +$ b64 "Hello, hub!" |
| 40 | +SGVsbG8sIGh1YiE= |
| 41 | +$ b64 -d SGVsbG8sIGh1YiE= |
| 42 | +Hello, hub! |
| 43 | +$ printf '\xfb\xff\xbf' | b64 --url |
| 44 | +-_-_ |
| 45 | +$ b64 --url --no-pad "Привет" |
| 46 | +0J_RgNC40LLQtdGC |
| 47 | +``` |
| 48 | + |
| 49 | +| Flag | Meaning | |
| 50 | +|---|---| |
| 51 | +| `-d`, `--decode` | decode (writes the raw bytes, nothing appended) | |
| 52 | +| `-u`, `--url` | URL-safe alphabet, `-` and `_` (encode) | |
| 53 | +| `-n`, `--no-pad` | no `=` padding (encode) | |
| 54 | +| `-w N`, `--wrap N` | wrap encoded output every N characters; 0 = no wrap, 76 = MIME | |
| 55 | +| `--data-uri` | output `data:<mime>;base64,...` (encode) | |
| 56 | +| `-m TYPE`, `--mime TYPE` | MIME type for `--data-uri` (default: sniffed) | |
| 57 | +| `--validate` | print `valid (<variant>, <bytes> bytes)`, or `invalid: <reason>` and exit 1 | |
| 58 | +| `-i FILE`, `--input FILE` | read FILE instead of stdin (`-` = stdin) | |
| 59 | +| `-o FILE`, `--output FILE` | write FILE instead of stdout (`-` = stdout) | |
| 60 | +| `-h`, `--help` | help | |
| 61 | +| `-v`, `--version` | print `b64 <version>` | |
| 62 | + |
| 63 | +More examples: |
| 64 | + |
| 65 | +```console |
| 66 | +$ b64 -w 76 -i photo.jpg -o photo.b64 |
| 67 | +$ b64 -d -i photo.b64 -o photo.jpg |
| 68 | +$ b64 --data-uri -i logo.png |
| 69 | +data:image/png;base64,iVBORw0KGgo... |
| 70 | +$ b64 --validate "SGVsbG8sIGh1YiE" |
| 71 | +valid (either, 11 bytes) |
| 72 | +$ b64 -d -- -_-_ | xxd -p |
| 73 | +fbffbf |
| 74 | +``` |
| 75 | + |
| 76 | +Flags may come before or after TEXT. Short flags can't be combined (`-d -n`, not `-dn`) and take |
| 77 | +their value as the next argument (`-w 76`, not `-w76`); long flags also accept `--wrap=76`. Use `--` |
| 78 | +before TEXT that starts with `-`, which URL-safe Base64 often does. A bare `-` as TEXT means stdin. |
| 79 | + |
| 80 | +These are usage errors: encoding flags (`-u`, `-n`, `-w`, `--data-uri`, `-m`) with `-d` or |
| 81 | +`--validate`; `-u`, `-n` or `-w` with `--data-uri` (data URIs are standard padded Base64 on one line); |
| 82 | +`--mime` without `--data-uri`; TEXT together with `-i`; the same file for `-i` and `-o`. |
| 83 | + |
| 84 | +Errors go to stderr as `b64: <message>`. Exit codes: `0` success, `1` invalid input or I/O error, |
| 85 | +`2` usage error. When a run fails, a file written with `-o` is removed, so no partial output is left. |
| 86 | +`b64` behaves exactly like the Go build of the command, the reference implementation. |
| 87 | + |
| 88 | +The package installs the same command under a second name, `base64hub`, and runs as |
| 89 | +`python -m base64hub` too. |
| 90 | + |
| 91 | +## Library |
| 92 | + |
| 93 | +```python |
| 94 | +from base64hub import encode, decode, validate, data_uri |
| 95 | + |
| 96 | +encode("Hello, hub!") # 'SGVsbG8sIGh1YiE=' |
| 97 | +encode(b"\xfb\xff\xbf", url=True) # '-_-_' |
| 98 | +encode("Привет", url=True, pad=False) # '0J_RgNC40LLQtdGC' |
| 99 | +encode(bytes(100), wrap=76) # MIME lines, no trailing newline |
| 100 | + |
| 101 | +decode("SGVsbG8sIGh1YiE") # b'Hello, hub!' (padding optional) |
| 102 | +decode("data:text/plain;base64,SGk=") # b'Hi' |
| 103 | +decode("a+b_") # b'k\xe6\xff' (mixed alphabets) |
| 104 | + |
| 105 | +validate("-_-_") |
| 106 | +# {'valid': True, 'variant': 'url', 'padded': True, 'bytes': 3} |
| 107 | +validate("Zm9v!") |
| 108 | +# {'valid': False, 'error': "invalid character '!' at position 4"} |
| 109 | + |
| 110 | +data_uri(b"hi") # 'data:text/plain;charset=utf-8;base64,aGk=' |
| 111 | +data_uri(png_bytes) # 'data:image/png;base64,...' |
| 112 | +data_uri(svg_bytes, "image/svg+xml") # MIME given explicitly |
| 113 | +``` |
| 114 | + |
| 115 | +- `encode(data: bytes | str, *, url=False, pad=True, wrap=0) -> str`. A `str` is encoded as UTF-8 first. |
| 116 | +- `decode(text: str | bytes) -> bytes` raises `base64hub.Base64Error`, a subclass of `ValueError`, |
| 117 | + for the first problem from the left. Its `position` attribute is the 0-based position in the |
| 118 | + cleaned input; for a bad character or a misplaced `=`, `char` is that character. |
| 119 | +- `validate(text) -> dict` never raises. Valid input gives |
| 120 | + `{"valid": True, "variant": ..., "padded": ..., "bytes": ...}`: `variant` is `standard` (`+` or `/` |
| 121 | + seen), `url` (`-` or `_`), `mixed` (both) or `either` (neither); `padded` means the length with `=` |
| 122 | + is a multiple of 4; `bytes` is the decoded length. Invalid input gives |
| 123 | + `{"valid": False, "error": "<message decode would raise>"}`. |
| 124 | +- `data_uri(data, mime=None) -> str` uses the standard alphabet with padding and never wraps. |
| 125 | + `sniff_mime(data)` returns the type it would pick. |
| 126 | + |
| 127 | +### How decoding works |
| 128 | + |
| 129 | +Whitespace means exactly space, tab, CR and LF; anything else, such as a no-break space, is an |
| 130 | +invalid character. |
| 131 | + |
| 132 | +1. Skip leading whitespace. If the input starts with `data:` (any case) and contains `;base64,` |
| 133 | + (lower case), drop everything up to and including `;base64,`. |
| 134 | +2. Remove every space, tab, CR and LF. |
| 135 | +3. Strip up to two trailing `=`; more, or `=` anywhere else, is an error. |
| 136 | +4. Accept both alphabets; any other character is an error with its position. |
| 137 | +5. A length that leaves one character over (length mod 4 = 1) is an error. |
| 138 | + |
| 139 | +Errors are found left to right, positions count characters of the cleaned input from 0, and the |
| 140 | +messages are exactly: |
| 141 | + |
| 142 | +- `invalid character '!' at position 4` |
| 143 | +- `unexpected '=' at position 2: padding is only allowed at the end` |
| 144 | +- `too much padding: 3 '=' at position 2, at most 2 are allowed` |
| 145 | +- `invalid length: 5 characters leave a single character in the last group` |
| 146 | + |
| 147 | +## Links |
| 148 | + |
| 149 | +- Package page: [base64hub.com/pypi](https://base64hub.com/pypi/) |
| 150 | +- Documentation: [base64hub.com/docs/python](https://base64hub.com/docs/python/) |
| 151 | +- Base64 tools in the browser: [base64hub.com](https://base64hub.com/) |
| 152 | +- Source and issues: [github.com/base64hub-com/base64hub-python](https://github.com/base64hub-com/base64hub-python) |
| 153 | + |
| 154 | +## License |
| 155 | + |
| 156 | +MIT |
0 commit comments