## Secrets and hashing (#17): SHA-256 known answers, key format, normalization and comparison. import std/[unittest, strutils, sets] import crypto suite "sha256": test "FIPS 180-4 known answers": check sha256Hex("") == "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" check sha256Hex("abc") == "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad" check sha256Hex("abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq") == "248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1" test "padding boundaries: 55, 56 and 64 byte messages differ and are stable": let a = sha256Hex(repeat('a', 55)) let b = sha256Hex(repeat('a', 56)) let c = sha256Hex(repeat('a', 64)) check a.len == 64 check a != b check b != c # 56 bytes needs the extra block (length no longer fits in the first block's tail) check b == "b35439a4ac6f0948b6d6f9e3c6af0f5f590ce20f1bde7090ef7970686ec6738a" check sha256Hex(repeat('a', 64)) == "ffe054fe7ae0cb6dc65c3af9b61d5209f439851db43d0ba5997337df154668eb" suite "player keys": test "20 symbols in 5 groups of 4, no look-alike characters": let key = generatePlayerKey() check key.len == 24 let groups = key.split('-') check groups.len == 5 for g in groups: check g.len == 4 for c in g: check c in {'A'..'Z', '2'..'9'} check c notin {'0', 'O', '1', 'I', 'L'} test "100 generated keys are distinct": var seen = initHashSet[string]() for _ in 0 ..< 100: let k = normalizeKey(generatePlayerKey()) check k.len == 20 check k notin seen seen.incl k test "generator output is upper-case; normalization is case/dash/space insensitive": let key = generatePlayerKey() check key == key.toUpperAscii let norm = normalizeKey(key) check norm.len == 20 check normalizeKey(key.toLowerAscii) == norm check normalizeKey(key.replace("-", " ")) == norm check normalizeKey(" " & key & "\t\n") == norm check normalizeKey("ab cd-ef") == "abcdef" test "generated keys draw from the whole alphabet (uniform sampling sanity)": # 3000 draws over 31 symbols: every symbol must appear (probability of a miss ~ 0). var seen = initHashSet[char]() for _ in 0 ..< 150: for c in normalizeKey(generatePlayerKey()): seen.incl c check seen.len == KeyAlphabet.len for c in KeyAlphabet: check c.toLowerAscii in seen suite "session tokens": test "32 bytes hex encoded, distinct": let a = randomSessionToken() let b = randomSessionToken() check a.len == 64 check a.allCharsInSet({'0'..'9', 'a'..'f'}) check a != b check sha256Hex(a).len == 64 check sha256Hex(a) != a suite "constant-time compare": test "equal only for identical strings, including the empty case": check constantTimeEqual("abc", "abc") check not constantTimeEqual("abc", "abd") check not constantTimeEqual("abc", "abcd") check not constantTimeEqual("", "a") check constantTimeEqual("", "") let key = normalizeKey(generatePlayerKey()) check constantTimeEqual(key, normalizeKey(generatePlayerKey().toLowerAscii)) == false check constantTimeEqual(key, key)