sha256.lua 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. --[[
  2. test_sha256.lua — Verify sha256 against openssl.
  3. Run: lua5.1 tests/test_sha256.lua
  4. ]]
  5. package.path = package.path .. ";./src/?.lua"
  6. local sha = require("balancerlite.sha256")
  7. local function assert_eq(a, b, msg)
  8. if a ~= b then
  9. error(((msg or "") .. "\n expected: " .. tostring(b)
  10. .. "\n got: " .. tostring(a)), 2)
  11. end
  12. end
  13. local function check(msg, expected_hex)
  14. local h = sha.hex(msg)
  15. local ok = (h == expected_hex)
  16. print((ok and "PASS" or "FAIL") .. " sha256("
  17. .. (msg == "" and '""' or string.format("%q", msg))
  18. .. ") = " .. (h or "nil"))
  19. if not ok then print(" EXPECTED: " .. expected_hex) end
  20. return ok
  21. end
  22. local function check_hmac(key, msg, expected_hex)
  23. local h = sha.hmac_hex(key, msg)
  24. local ok = (h == expected_hex)
  25. print((ok and "PASS" or "FAIL") .. " HMAC("
  26. .. string.format("%q", key) .. ", "
  27. .. string.format("%q", msg)
  28. .. ") = " .. (h or "nil"))
  29. if not ok then print(" EXPECTED: " .. expected_hex) end
  30. return ok
  31. end
  32. print("=== SHA-256 / HMAC test vectors ===")
  33. local all_ok = true
  34. -- SHA-256 (openssl verified)
  35. all_ok = check("", "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855") and all_ok
  36. all_ok = check("abc", "ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad") and all_ok
  37. -- HMAC-SHA256 (openssl verified)
  38. all_ok = check_hmac("key",
  39. "The quick brown fox jumps over the lazy dog",
  40. "f7bc83f430538424b13298e6aa6fb143ef4d59a14946175997479dbc2d1a3cd8") and all_ok
  41. print(all_ok and "PASS: sha256" or "FAIL: sha256")