Skip to content

stdlib: add width-parameterized words and hash/KDF primitives - #207

Merged
dslsdzc merged 1 commit into
developfrom
hash-kdf
Oct 26, 2026
Merged

dslsdzc merged 1 commit into
developfrom
hash-kdf

Conversation

@dslsdzc

@dslsdzc dslsdzc commented Oct 26, 2026

Copy link
Copy Markdown
Owner

概要

新增标准库内部字/字节层与公开哈希/KDF 面。

内部层(非 pub,用户不可见)

  • src/stdlib/internal/word.cr:任意宽度的 word 运算(wordAnd/Or/Xor/Not/Shl/Shr/Rotl/Rotr/Add/Sub/Mul)。
    宽度是算法参数(bits: int),用 /、%、* 与条件实现,不新增 IR opcode、不引入宽度类型。
  • src/stdlib/internal/bytes.cr:标准库唯一的 raw 字节边界。rawbuf.cr 改为委托这里,
    不再直接命名 load8/store8。

公开面(hash.cr)

  • CRC-32/ISO-HDLC:crc32 / crc32With(data, init, poly) / crc32Hex,
    以及增量 crc32Init / crc32Update / crc32Final。
  • SHA-256:sha256 / sha256Hex。
  • HMAC-SHA-256:hmacSha256 / hmacSha256Hex。
  • HKDF-SHA-256:hkdfSha256 / hkdfSha256Extract / hkdfSha256Expand / hkdfSha256Hex。
  • PBKDF2-HMAC-SHA-256:pbkdf2Sha256 / pbkdf2Sha256Hex。
  • 输出长度、迭代次数、CRC seed/多项式都是显式参数。

验证

  • selfhost-tests 全绿(新增 test_hash.py)
  • bootstrap-tests 全绿
  • check 全绿
  • canary 5/5,值不变
  • test_hash.py 用 Python hashlib/hmac + 第二份 CRC 实现对拍,覆盖:
    CRC-32 空串/标准向量/自定义 init/CRC-32C 多项式/增量;
    SHA-256 空串/abc/200B 跨块;
    HMAC RFC 4231 case 1/2;
    HKDF RFC 5869 test case 1(42B)与 64B 参数;
    PBKDF2 c=1/2/8,输出 20/32 字节。

备注

sha256Compress 的 K 常量表放在函数内:全局数组的动态下标目前读 0(既有后端缺陷,已在源码注释登记),
本批不改该路径,避免把哈希实现建立在未验证的行为上。

- internal/word.cr: fixed-width word arithmetic with an explicit width
  parameter. Width is an algorithm argument, not a type; operations use
  /, %, * and conditionals only (no new IR opcodes).
- internal/bytes.cr: the single stdlib boundary for raw byte access.
  rawbuf.cr now delegates to it instead of naming load8/store8.
- hash.cr: CRC-32/ISO-HDLC with configurable init and polynomial,
  SHA-256, HMAC-SHA256, HKDF-SHA256 and PBKDF2-HMAC-SHA256. Output
  lengths, iteration counts, seeds and polynomials are explicit.
- test_hash.py checks every primitive against hashlib/hmac and a second
  CRC implementation. The SHA-256 K table is function-local because
  dynamic subscript on a global array currently reads zero (noted in
  the source; separate defect).
@dslsdzc
dslsdzc merged commit 65d48c2 into develop Oct 26, 2026
4 checks passed
@dslsdzc
dslsdzc deleted the hash-kdf branch October 26, 2026 09:14
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant