Hashes, passwords and encodings: crypto
crypto has what programs need for security from the start: hashes, keyed hashes (HMAC), secure random bytes, password hashing, and comparing secrets safely. The encodings hex, base64 and base64url, which are useful far beyond crypto, are methods of text and bytes.
print(crypto.sha256("hello"))
print("Hello".hex())
print("Hello".base64())Output:
2cf24dba5fb0a30e26e83b2ac5b9e29e1b161e5c1fa7425e73043362938b9824
48656c6c6f
SGVsbG8=Hashes
A hash turns any amount of data into a short fingerprint: the same data always gives the same one, and other data, in practice, another one.
| Function | Result |
|---|---|
crypto.md5(data) | 16 bytes; not secure, for checksums and old protocols |
crypto.sha1(data) | 20 bytes; not secure, for Git and old protocols |
crypto.sha224(data) | 28 bytes |
crypto.sha256(data) | 32 bytes; the usual choice |
crypto.sha384(data) | 48 bytes |
crypto.sha512(data) | 64 bytes |
crypto.crc32(data) | an int (0 to 4294967295): a quick checksum, not secure, the one zip, gzip and PNG files keep |
The data is a str, a [byte] or a buffer. What you get depends on the type it goes into: in a str, the hash is written in hex, which is what you print, store and compare; in a [byte] or a buffer, you get the bytes themselves:
text: str = crypto.sha256("hello") // 64 hex characters
raw: [byte] = crypto.sha256("hello") // 32 bytes
print(len(text))
print(len(raw))Output:
64
32Keys: HMAC
With a key as the second argument, the hash is an HMAC: only someone who knows the key can make it, so it proves where a message came from and that nobody changed it. Webhooks (GitHub, Stripe), API signatures and JWT (HS256) use it:
secret: str = "key"
signature: str = crypto.sha256("The quick brown fox jumps over the lazy dog", secret)
print(signature)Output:
f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8Every hash above has its HMAC: crypto.sha1(data, key), crypto.sha512(data, key), and so on. The key is a str, [byte] or buffer too.
Comparing secrets
crypto.equal(a, b) compares two signatures, tokens or hashes in a time that doesn’t depend on where they differ, so an attacker can’t guess them byte by byte by measuring. Use it instead of == for secrets:
expected: str = crypto.sha256("payload", "secret")
received: str = expected
if crypto.equal(expected, received) {
print("signature ok")
}Output:
signature okRandom bytes
crypto.random(n) gives n bytes from the system’s secure random source, good for keys, session IDs and tokens. (For dice, shuffling and games, random is simpler.) Into a str, they are written in hex:
token: str = crypto.random(16) // 32 hex characters
key: [byte] = crypto.random(32)
print(len(token))Output:
32Passwords
Never store passwords, or plain hashes of them. crypto.password makes what to store, and crypto.verify checks a password against it:
stored: str = crypto.password("s3cret")
print(crypto.verify("s3cret", stored))
print(crypto.verify("guess", stored))Output:
true
falseWhat it stores looks like pbkdf2-sha256$600000$<salt>$<hash>: PBKDF2 with SHA-256 and 600,000 rounds, as OWASP recommends, and a new random salt for each password. The rounds make guessing slow (about a quarter of a second for each try), and the salt makes the same password look different each time. Because the rounds and the salt are part of the text, they can change later without breaking what was stored before.
crypto.verify raises error 11 when the text isn’t one crypto.password made.
Encodings
hex, base64 and base64url write bytes as text, and read them back. They are methods of str, [byte] and buffer:
| Method | Gives |
|---|---|
x.hex() | the bytes in hex, lower case: "48656c6c6f" |
x.base64() | Base64 with = padding: "SGVsbG8=" |
x.base64url() | Base64 for URLs and file names (- and _), without padding, as JWT uses it |
text.unhex() | the bytes of hex text (upper or lower case) |
text.unbase64() | the bytes of Base64 text, with or without padding |
text.unbase64url() | the bytes of base64url text, with or without padding |
The decoding methods give a [byte], or a str or buffer where one is expected:
bytes: [byte] = "48656c6c6f".unhex()
text: str = "SGVsbG8=".unbase64()
print(bytes)
print(text)Output:
[72, 101, 108, 108, 111]
HelloText that isn’t such raises error 11: cannot convert "zz" from hex. Spaces and line breaks are not skipped.
Compression
gzip and deflate compress bytes; gunzip and inflate give them back. They are methods of str, [byte] and buffer, and give a [byte], or a str or buffer where one is expected:
lines: [str] = []
(1..100).walk(i) {
lines[] = "line ${i}: Luma compresses repeated text well"
}
text: str = lines.join("\n")
packed: [byte] = text.gzip()
back: str = packed.gunzip()
print("${len(buffer(text))} -> ${len(packed)} bytes")
print(back == text)Output:
4391 -> 307 bytes
true| Method | Gives |
|---|---|
x.gzip() | the data compressed in a gzip file’s format (RFC 1952): what gzip and .gz files are, and HTTP’s Content-Encoding: gzip |
x.gunzip() | the data of gzip bytes: from Luma, the gzip tool or any other |
x.deflate() | raw DEFLATE (RFC 1951), without gzip’s header and checksum |
x.inflate() | the data of raw DEFLATE bytes |
To read and write .gz files, use file: file("log.gz").write(text.gzip()) and log: str = file("log.gz").read().gunzip().
- Compressing looks for repeats 32 KB back, as
gzip -1to-6do: text usually shrinks to a fifth or less. Data that doesn’t shrink (already compressed, random) is stored as it is, a few bytes longer. - A program compressed with
luma runand compiled withluma buildgives the same bytes. - Broken data raises error 11:
invalid compressed data: gzip's CRC-32 doesn't match: the data changed.
Errors
| Message | When |
|---|---|
cannot convert "zz" from hex | unhex, unbase64 or unbase64url of text that isn’t that |
invalid compressed data: ... | gunzip or inflate of data that isn’t that, or was changed |
cannot make -1 random bytes | crypto.random with a negative count |
cannot verify a password with "...": it isn't what crypto.password gives | crypto.verify with another text |
All of them have code 11, like a convert that doesn’t fit. Hashes, HMAC, equal and password never fail.
Not available yet
- Encryption (AES, ChaCha20) and signatures (RSA, Ed25519): they come with TLS.
- Hashing data in parts (for files larger than memory); hash the whole
str,[byte]orbuffer. - bcrypt, scrypt and Argon2 password hashes.