Encoding changes the representation of some data so a channel can carry it; it hides nothing. Encrypting makes it unreadable without a key. Confusing them is a very common security mistake.
import base64, html
from urllib.parse import quote, unquote, urlencode
data = "café ☕".encode("utf-8")
print(data) # b'caf\xc3\xa9 \xe2\x98\x95'
print(data.hex()) # 636166c3a920e29895
b64 = base64.b64encode(data).decode("ascii")
print(b64) # Y2Fmw6kg4piV
print(base64.b64decode(b64).decode("utf-8")) # café ☕
print(base64.urlsafe_b64encode(b"\xfb\xff\xfe").decode()) # -__- (without + or /)
print(quote("a b&c=ñ")) # a%20b%26c%3D%C3%B1
print(unquote("a%20b%26c")) # a b&c
print(urlencode({"q": "python 3", "n": 2})) # q=python+3&n=2
comment = '<script>alert("hello")</script>'
print(html.escape(comment)) # <script>alert("hello")</script>
print(html.unescape("<b> & é")) # <b> & é
| Technique | What it is for | Reverted with... |
|---|---|---|
Base64 (base64) | Putting bytes into text (JSON, email, URLs) | Anyone, no key |
Hexadecimal (.hex()) | Showing bytes readably | Anyone, no key |
Percent (urllib.parse.quote) | Special characters in URLs | Anyone, no key |
HTML escape (html.escape) | Inserting text in a page without it being code | html.unescape |
Encryption (cryptography library) | Hiding data | Only with the key |
- Base64 increases the size by 33%. The
urlsafe_b64encodevariant avoids+and/. - Always escape user text before inserting it into HTML (
html.escape) or into a URL (quote,urlencode): it prevents injections. - To analyze URLs use
urllib.parse.urlparseandparse_qsl, not home-made regular expressions. - XOR with a repeated key is a toy, not encryption. To really encrypt use proven libraries and never invent your own algorithm.
You practice it in Encode and decode in Base64, Toy XOR cipher, Take a URL apart and Escape HTML against injections.