-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.sml
More file actions
48 lines (39 loc) · 1.97 KB
/
Copy pathdemo.sml
File metadata and controls
48 lines (39 loc) · 1.97 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
(* demo.sml -- generate an RSA key, export it as PEM, then sign and verify a
message with it. Deterministic (the randomness is a fixed SHA-256 counter
stream), so the output is byte-identical on every run and every compiler. *)
fun pr s = print (s ^ "\n")
(* a fixed, reproducible byte source: SHA-256(seed || counter), counter = 1.. *)
fun makeRng seed =
let
val counter = ref 0
val buf = ref ""
fun refill () = ( counter := !counter + 1
; buf := !buf ^ Sha256.digest (seed ^ Int.toString (!counter)) )
fun bytes n =
( while String.size (!buf) < n do refill ()
; let val out = String.substring (!buf, 0, n)
in buf := String.extract (!buf, n, NONE); out end )
in bytes end
val () = pr "sml-rsa demo"
val () = pr "============"
val { pub, priv } =
Rsa.generate { bits = 1024, e = BigInt.fromInt 65537, randomBytes = makeRng "sml-rsa demo seed" }
val () = pr ""
val () = pr "Generated a fresh 1024-bit key (deterministic seed). Public key:"
val () = print (Rsa.encodePublicPem pub)
val msg = "The quick brown fox jumps over the lazy dog"
(* PKCS#1 v1.5 signature over SHA-256 *)
val sgn = Rsa.sign { priv = priv, hash = Rsa.SHA256, msg = msg }
val ok = Rsa.verify { pub = pub, hash = Rsa.SHA256, msg = msg, sgn = sgn }
(* PSS signature over SHA-256 with a 32-byte salt *)
val pss = Rsa.signPss { priv = priv, hash = Rsa.SHA256
, salt = makeRng "salt" 32, msg = msg }
val pssOk = Rsa.verifyPss { pub = pub, hash = Rsa.SHA256, saltLen = 32, msg = msg, sgn = pss }
val () = pr ("message : " ^ msg)
val () = pr ("PKCS#1 v1.5 signature: " ^ Rsa.toHex sgn)
val () = pr (" verify : " ^ Bool.toString ok)
val () = pr ("PSS signature : " ^ Rsa.toHex pss)
val () = pr (" verify : " ^ Bool.toString pssOk)
val () = pr ("tampered signature : " ^
Bool.toString (Rsa.verify { pub = pub, hash = Rsa.SHA256, msg = "evil", sgn = sgn })
^ " (expected false)")