]> gitweb.factorcode.org Git - factor.git/blob - basis/random/windows/windows.factor
fix random.windows -- use CRYPT_MACHINE_KEYSET
[factor.git] / basis / random / windows / windows.factor
1 USING: accessors alien.c-types byte-arrays
2 combinators.short-circuit continuations destructors init kernel
3 locals namespaces random windows.advapi32 windows.errors
4 windows.kernel32 ;
5 IN: random.windows
6
7 TUPLE: windows-rng provider type ;
8 C: <windows-rng> windows-rng
9
10 TUPLE: windows-crypto-context handle ;
11 C: <windows-crypto-context> windows-crypto-context
12
13 M: windows-crypto-context dispose ( tuple -- )
14     handle>> 0 CryptReleaseContext win32-error=0/f ;
15
16 CONSTANT: factor-crypto-container "FactorCryptoContainer"
17
18 :: (acquire-crypto-context) ( provider type flags -- handle ret )
19     "HCRYPTPROV" <c-object> :> handle
20     handle
21     factor-crypto-container
22     provider
23     type
24     flags
25     CryptAcquireContextW handle swap ;
26
27 : acquire-crypto-context ( provider type -- handle )
28     CRYPT_MACHINE_KEYSET
29     (acquire-crypto-context)
30     0 = [
31         GetLastError NTE_BAD_KEYSET =
32         [ drop f ] [ win32-error-string throw ] if
33     ] [
34         *void*
35     ] if ;
36
37 : create-crypto-context ( provider type -- handle )
38     { CRYPT_MACHINE_KEYSET CRYPT_NEWKEYSET } (acquire-crypto-context) win32-error=0/f *void* ;
39
40 ERROR: acquire-crypto-context-failed provider type ;
41
42 : attempt-crypto-context ( provider type -- handle )
43     {
44         [ acquire-crypto-context ] 
45         [ create-crypto-context ] 
46         [ acquire-crypto-context-failed ]
47     } 2|| ;
48
49 : windows-crypto-context ( provider type -- context )
50     attempt-crypto-context <windows-crypto-context> ;
51
52 M: windows-rng random-bytes* ( n tuple -- bytes )
53     [
54         [ provider>> ] [ type>> ] bi
55         windows-crypto-context &dispose
56         handle>> swap dup <byte-array>
57         [ CryptGenRandom win32-error=0/f ] keep
58     ] with-destructors ;
59
60 [
61     MS_DEF_PROV
62     PROV_RSA_FULL <windows-rng> system-random-generator set-global
63
64     [ MS_STRONG_PROV PROV_RSA_FULL <windows-rng> ]
65     [ drop MS_ENH_RSA_AES_PROV PROV_RSA_AES <windows-rng> ] recover
66     secure-random-generator set-global
67
68 ] "random.windows" add-init-hook