sjqtentacles/sml-crypto

GitHub: sjqtentacles/sml-crypto

为 Standard ML Web 栈提供基于 RFC 标准的 HMAC 消息认证与签名令牌原语,支持恒定时间比较以防止时序攻击。

Stars: 0 | Forks: 0

# sml-crypto [![CI](https://github.com/sjqtentacles/sml-crypto/actions/workflows/ci.yml/badge.svg)](https://github.com/sjqtentacles/sml-crypto/actions/workflows/ci.yml) 用于 Standard ML Web 栈的密钥认证原语:HMAC-SHA1 / HMAC-SHA256 / HMAC-SHA512、恒定时间比较,以及用于 cookie 和 CSRF 的签名 token。 基于 [`sml-codec`](https://github.com/sjqtentacles/sml-codec)(在 `lib/` 下作为 vendored 依赖),它为您提供了不带机密性的消息认证 -- 这正是您为 cookie 或 CSRF nonce 签名所必需的,确保在没有密钥的 情况下无法被伪造。基于 Basis 库的纯 Standard ML 实现。 已在 **MLton** 和 **Poly/ML** 上通过 RFC 2202 HMAC-SHA1 和 RFC 4231 HMAC-SHA256/512 测试向量验证。 ## 模块 | 结构 (Structure) | 规范 (Spec) | 用途 | | --- | --- | --- | | `Hmac` | RFC 2104 / 2202 / 4231 | `hmacSha1`, `hmacSha256`, `hmacSha512` (+`Hex`), `constantEq` | | `Token` | -- | 对 URL 安全的 `payload.signature` token 进行 `sign` / `verify` | ## API ``` structure Hmac : sig val hmacSha1 : string -> string -> string (* key -> msg -> 20 raw bytes *) val hmacSha1Hex : string -> string -> string val hmacSha256 : string -> string -> string (* key -> msg -> 32 raw bytes *) val hmacSha256Hex : string -> string -> string val hmacSha512 : string -> string -> string (* key -> msg -> 64 raw bytes *) val hmacSha512Hex : string -> string -> string val constantEq : string -> string -> bool (* timing-safe equality *) end structure Token : sig val sign : string -> string -> string (* key -> payload -> token *) val verify : string -> string -> string option (* SOME payload iff valid *) end ``` ### 示例 ``` val key = "server-secret" val tok = Token.sign key "uid=42" (* later, on the next request *) val uid = case Token.verify key tok of SOME payload => payload (* "uid=42" *) | NONE => raise Fail "forged or tampered token" ``` ## 构建与测试 ``` make test # MLton make test-poly # Poly/ML make all-tests # both make clean ``` ## 使用 smlpkg 安装 ``` smlpkg add github.com/sjqtentacles/sml-crypto smlpkg sync ``` 在您自己的 `.mlb` 中引用 `lib/github.com/sjqtentacles/sml-crypto/sml-crypto.mlb`, 或者将 `sources.mlb` 传给 `tools/polybuild` (Poly/ML)。 `sml-codec` 依赖项已作为 vendored 依赖存放在 `lib/` 下并已提交,因此构建无需 网络。 ## 测试 32 项确定性检查:针对七个 RFC 2202 用例的 HMAC-SHA1, 针对 RFC 4231 用例(包括长于 block 的密钥用例)的 HMAC-SHA256/512、PBKDF2 参考向量、恒定时间比较行为,以及包含 payload 篡改、签名篡改、密钥错误和垃圾 token 拒绝在内的 sign/verify 往返测试。运行 `make all-tests`。 ## 许可证 MIT。详见 [LICENSE](LICENSE)。
标签:HMAC, Standard ML, Web开发组件, 密码学, 手动系统调用, 签名校验