SHA and MD5 digests, HMAC signatures, secure random numbers and password hashing.
import crypto
This package has the basic cryptography tools, written in Salam: the SHA-1, SHA-2 and MD5 digests, HMAC, PBKDF2 password hashing, a constant time comparison and secure random bytes from the operating system. It covers hashing, signing and secrets; it does not encrypt. For encryption (AES-GCM, ChaCha20-Poly1305, key exchange) use tls, and for signed tokens that carry claims jwt.
Most functions come in three shapes: ...Hex takes a str and returns hex text, the simplest; ...Bytes and ...Raw write the raw digest into memory you allocate; and Sha256New, Sha256Update, Sha256Final hash data that arrives in pieces.
Things to get right:
•
HashPassword uses only 1000 PBKDF2 rounds. That is far below current advice (OWASP asks for 600,000 with SHA-256). For new systems build the same string with more rounds, as the second section shows; VerifyPassword reads the rounds from the stored string, so both kinds keep working.
•
Compare secrets with SecretEquals, never with ==.
•
A str stops at the first zero byte. For binary data or a binary key, use the ...Bytes and ...Raw forms with a pointer and a length; Sha256Hex of a buffer that contains a zero hashes only the part before it.
•
HashStr, HashBytes and HashInt are fast hash table hashes, not cryptographic ones; MD5 and SHA-1 are only for old systems that require them.
Storing passwords
A login system keeps one string per user: the output of HashPassword. It has four fields separated by $: the algorithm, the number of PBKDF2 rounds, a random salt and the derived key. Because the salt is new every time, two users with the same password get different strings, and a leaked table cannot be attacked with one precomputed list. At login, VerifyPassword reads the rounds and the salt back out of the stored string, so the stored value is all you need to keep.
stored fields: 4 algorithm: pbkdf2-sha256 rounds: 1000
same password, same hash? false
sara right password: true
sara wrong password: false
unknown user: false
Answer "wrong user" and "wrong password" with the same message, so that a visitor cannot use the login form to find out which accounts exist.
More rounds, and upgrading old hashes
The cost of a password hash is the number of rounds: every guess an attacker tries costs the same work as one login. Pbkdf2HmacSha256Hex takes the round count, so a stronger hash is the same four-field string as HashPassword writes, built by hand with 600,000 rounds. Existing users do not have to reset anything. At their next successful login the program sees that the stored hash has fewer rounds than the target and stores a new one, made from the password they just typed.
HashPassword uses 1000 rounds
upgraded the stored hash to 600000 rounds
login: true
login again: true
wrong password: false
600,000 rounds take a noticeable fraction of a second, which is the point, but it also means a login endpoint should be rate limited, or many parallel login attempts can keep the server busy.
Checking a webhook signature
Payment providers, GitHub and most other services sign the requests they send you. They compute an HMAC of the raw body with a secret you both know and put it in a header. To check it, compute the same HMAC over the body exactly as it arrived and compare. Compare with SecretEquals, never with ==: == stops at the first different character, and the time that takes tells an attacker how much of a forged signature was right.
Sign the bytes you received, not a version you decoded and encoded again: a JSON library may reorder keys or change spaces, and then the signature no longer matches.
Checksums of large data
Sha256Hex needs the whole text at once. For a file or a download that arrives in pieces, keep a running state: Sha256New starts it, Sha256Update feeds each piece and Sha256Final writes the 32 byte digest. The result is the same as hashing everything in one go, as the program shows.
crypto-checksum.salam
import crypto
import encoding
import mem
funcmain:
chunks := ["first block of the file, ", "second block, ", "and the last one."]
mut whole := ""mut h := crypto.Sha256New()
each c in chunks:
crypto.Sha256Update(h, c asvoid*, c.Len())
whole += c
end
out := mem.Allocate(32asu64)
crypto.Sha256Final(h, out)
streamed := encoding.Base64EncodeBytes(out, 32)
crypto.Sha256Bytes(whole asvoid*, whole.Len(), out)
oneshot := encoding.Base64EncodeBytes(out, 32)
mem.Free(out)
println"streamed: " + streamed
println"one shot: " + oneshot
println"match:", streamed == oneshot
println"hex form: " + crypto.Sha256Hex(whole)
end
Output
streamed: E+f0zAqMN9MLnvZXyBef5ki729TQh4fngTGDH5hLL1M=
one shot: E+f0zAqMN9MLnvZXyBef5ki729TQh4fngTGDH5hLL1M=
match: true
hex form: 13e7f4cc0a8c37d30b9ef657c8179fe648bbdbd4d08787e78131831f984b2f53
The ...Bytes and ...Final functions write raw bytes into memory you allocated; turn them into text with Base64EncodeBytes from encoding. The SHA-512 and SHA-384 states work the same way with Sha512New, Sha384New, Sha512Update and Sha512Final.
API keys and tokens
An API key, a password reset link or a session id must be impossible to guess, so make it with RandomToken, which reads the operating system's secure random source. RandomToken(n) returns n random bytes as 2n hex characters. Store only the SHA-256 digest of the key: a stolen database then gives no working keys, and checking a key that comes in with a request is one digest and one SecretEquals. A plain digest is enough here because the key is long and random; a password is short and chosen by a person, which is why it needs HashPassword instead.
Like BcryptHash, with your own 16 byte salt from a pointer instead of a random one, so the same input always gives the same string; for tests and known answers, not for storing real passwords.
Hashes the password with bcrypt and a random 16 byte salt, and returns the 60 character $2y$cost$salt+hash string that PHP password_hash also writes. The cost is the base 2 log of the rounds: each step up doubles the work; 10 is a common choice, and values are kept between 4 and 31. Only the first 72 bytes of the password count.
True when the string looks like a bcrypt hash: 60 characters starting with $2a$, $2b$ or $2y$. Useful when a database holds both bcrypt and HashPassword strings.
The cost written in a bcrypt hash, such as 10 for $2y$10$...; -1 when the string is not a bcrypt hash. Compare it with your target cost to know when to hash a password again.
Checks a password against a stored $2a$, $2b$ or $2y$ string, with the cost and salt it holds, in constant time; hashes from PHP and other bcrypt libraries work. False for any other format.
Hashes the password with PBKDF2-HMAC-SHA256, 1000 rounds and a random 16 byte salt, and returns pbkdf2-sha256$1000$salt$hash to keep in your database. The output is different every time. 1000 rounds is low by today's standards; see the guide for a stronger hash.
Compares two secrets in constant time, so the answer time gives nothing away about their contents (only whether the lengths differ); for tokens and signatures.
The HMAC-SHA256 signature of a message under a key, as hex; for checking that the message is untouched and comes from whoever holds the key. Key and message stop at a zero byte; use HmacSha256Raw for binary ones.
The example for this item is shown with the ones above: crypto-Hmac.salam