1 USING: accessors alien.c-types alien.data byte-arrays
2 combinators.short-circuit continuations destructors init kernel
3 locals namespaces random windows.advapi32 windows.errors
4 windows.kernel32 windows.types math.bitwise sequences fry
8 TUPLE: windows-rng provider type ;
9 C: <windows-rng> windows-rng
11 TUPLE: windows-crypto-context handle ;
12 C: <windows-crypto-context> windows-crypto-context
14 M: windows-crypto-context dispose ( tuple -- )
15 handle>> 0 CryptReleaseContext win32-error=0/f ;
17 CONSTANT: factor-crypto-container "FactorCryptoContainer"
19 :: (acquire-crypto-context) ( provider type flags -- handle ret )
20 HCRYPTPROV <c-object> :> handle
22 factor-crypto-container
26 CryptAcquireContextW handle swap ;
28 : acquire-crypto-context ( provider type -- handle )
30 (acquire-crypto-context)
32 GetLastError NTE_BAD_KEYSET =
33 [ drop f ] [ win32-error-string throw ] if
38 : create-crypto-context ( provider type -- handle )
39 flags{ CRYPT_MACHINE_KEYSET CRYPT_NEWKEYSET }
40 (acquire-crypto-context) win32-error=0/f *void* ;
42 ERROR: acquire-crypto-context-failed provider type ;
44 : attempt-crypto-context ( provider type -- handle )
46 [ acquire-crypto-context ]
47 [ create-crypto-context ]
48 [ acquire-crypto-context-failed ]
51 : windows-crypto-context ( provider type -- context )
52 attempt-crypto-context <windows-crypto-context> ;
54 M: windows-rng random-bytes* ( n tuple -- bytes )
56 [ provider>> ] [ type>> ] bi
57 windows-crypto-context &dispose
58 handle>> swap dup <byte-array>
59 [ CryptGenRandom win32-error=0/f ] keep
62 ERROR: no-windows-crypto-provider error ;
64 : try-crypto-providers ( seq -- windows-rng )
65 [ first2 <windows-rng> ] attempt-all
66 dup windows-rng? [ no-windows-crypto-provider ] unless ;
70 ${ MS_ENHANCED_PROV PROV_RSA_FULL }
71 ${ MS_DEF_PROV PROV_RSA_FULL }
72 } try-crypto-providers
73 system-random-generator set-global
76 ${ MS_STRONG_PROV PROV_RSA_FULL }
77 ${ MS_ENH_RSA_AES_PROV PROV_RSA_AES }
78 } try-crypto-providers secure-random-generator set-global
79 ] "random.windows" add-startup-hook
83 ! system-random-generator get-global &dispose drop
84 ! secure-random-generator get-global &dispose drop
86 ] "random.windows" add-shutdown-hook