Hashing, encoding and basic security · 4 / 15 Theory

Encoding is not encryption

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))                   # &lt;script&gt;alert(&quot;hello&quot;)&lt;/script&gt;
print(html.unescape("&lt;b&gt; &amp; &eacute;")) # <b> & é
TechniqueWhat it is forReverted with...
Base64 (base64)Putting bytes into text (JSON, email, URLs)Anyone, no key
Hexadecimal (.hex())Showing bytes readablyAnyone, no key
Percent (urllib.parse.quote)Special characters in URLsAnyone, no key
HTML escape (html.escape)Inserting text in a page without it being codehtml.unescape
Encryption (cryptography library)Hiding dataOnly with the key
  • Base64 increases the size by 33%. The urlsafe_b64encode variant 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.urlparse and parse_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.