src/crypto/sha/sha256.bend
0x9ee2e9a299991dcc089fe22c7f3ceb5f · 45 lines · 0 definitions
1import Base
2import 0x9ee2e9a299991dcc089fe22c7f3ceb5f/src/crypto/sha/core.bend as Core
3
4# The core refinement theorem quantifies over every constant table.
5# Instantiate the verified core with the FIPS 180-4 constants.
6def constants() -> List<&2, U32>:
7 [1116352408, 1899447441, 3049323471, 3921009573,
8 961987163, 1508970993, 2453635748, 2870763221,
9 3624381080, 310598401, 607225278, 1426881987,
10 1925078388, 2162078206, 2614888103, 3248222580,
11 3835390401, 4022224774, 264347078, 604807628,
12 770255983, 1249150122, 1555081692, 1996064986,
13 2554220882, 2821834349, 2952996808, 3210313671,
14 3336571891, 3584528711, 113926993, 338241895,
15 666307205, 773529912, 1294757372, 1396182291,
16 1695183700, 1986661051, 2177026350, 2456956037,
17 2730485921, 2820302411, 3259730800, 3345764771,
18 3516065817, 3600352804, 4094571909, 275423344,
19 430227734, 506948616, 659060556, 883997877,
20 958139571, 1322822218, 1537002063, 1747873779,
21 1955562222, 2024104815, 2227730452, 2361852424,
22 2428436474, 2756734187, 3204031479, 3329325298]
23
24def sha256(bytes: List<&2, U32>) -> List<&2, U32>:
25 Core.sha256(bytes)
26
27def ascii(s: String) -> List<&2, U32>:
28 Core.ascii(s)
29
30def hex(ws: List<&2, U32>) -> String:
31 Core.hex(ws)
32
33# Big-endian octets, represented as U32 values in 0..255.
34def digest_bytes(ws: List<&2, U32>) -> List<&2, U32>:
35 match ws:
36 case Nil{}:
37 Nil{}
38 case +w <> tail:
39 U32.and(U32.shrn(w, 24n), 255) <>
40 U32.and(U32.shrn(w, 16n), 255) <>
41 U32.and(U32.shrn(w, 8n), 255) <>
42 U32.and(w, 255) <> digest_bytes(tail)
43
44def sha256_bytes(bytes: List<&2, U32>) -> List<&2, U32>:
45 digest_bytes(sha256(bytes))