]> gitweb.factorcode.org Git - factor.git/blob - basis/random/windows/windows.factor
fix error handling in random.windows if acquiring the crypto context fails
[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     0 (acquire-crypto-context)
29     0 = [
30         GetLastError NTE_BAD_KEYSET =
31         [ drop f ] [ win32-error-string throw ] if
32     ] [
33         *void*
34     ] if ;
35
36 : create-crypto-context ( provider type -- handle )
37     CRYPT_NEWKEYSET (acquire-crypto-context) win32-error=0/f *void* ;
38
39 ERROR: acquire-crypto-context-failed provider type ;
40
41 : attempt-crypto-context ( provider type -- handle )
42     {
43         [ acquire-crypto-context ] 
44         [ create-crypto-context ] 
45         [ acquire-crypto-context-failed ]
46     } 2|| ;
47
48 : windows-crypto-context ( provider type -- context )
49     acquire-crypto-context <windows-crypto-context> ;
50
51 M: windows-rng random-bytes* ( n tuple -- bytes )
52     [
53         [ provider>> ] [ type>> ] bi
54         windows-crypto-context &dispose
55         handle>> swap dup <byte-array>
56         [ CryptGenRandom win32-error=0/f ] keep
57     ] with-destructors ;
58
59 [
60     MS_DEF_PROV
61     PROV_RSA_FULL <windows-rng> system-random-generator set-global
62
63     MS_STRONG_PROV
64     PROV_RSA_FULL <windows-rng> secure-random-generator set-global
65
66     ! MS_ENH_RSA_AES_PROV
67     ! PROV_RSA_AES <windows-rng> secure-random-generator set-global
68 ] "random.windows" add-init-hook