2 // Mono.Security.Cryptography.CapiContext
5 // Sebastien Pouliot (sebastien@ximian.com)
7 // Copyright (C) 2003 Motus Technologies Inc. (http://www.motus.com)
8 // Copyright (C) 2004 Novell (http://www.novell.com)
12 using System.Security.Cryptography;
14 namespace Mono.Security.Cryptography {
16 // we deal with unmanaged resources - they MUST be released after use!
17 public class CapiContext : IDisposable {
19 // handles to CryptoAPI - they are
20 private IntPtr providerHandle;
22 private CspParameters cspParams;
24 // has the last call succeded ?
25 private bool lastResult;
27 // Create an instance using the default CSP
28 public CapiContext () : this (null)
32 // Create an instance using the specified CSP
33 public CapiContext (CspParameters csp)
35 providerHandle = IntPtr.Zero;
38 cspParams = new CspParameters ();
41 // keep of copy of the parameters
42 cspParams = new CspParameters (csp.ProviderType, csp.ProviderName, csp.KeyContainerName);
43 cspParams.KeyNumber = csp.KeyNumber;
44 cspParams.Flags = csp.Flags;
47 // do not show user interface (CRYPT_SILENT) - if UI is required then the function fails.
48 uint flags = CryptoAPI.CRYPT_SILENT;
49 if ((cspParams.Flags & CspProviderFlags.UseMachineKeyStore) == CspProviderFlags.UseMachineKeyStore) {
50 flags |= CryptoAPI.CRYPT_MACHINE_KEYSET;
53 lastResult = CryptoAPI.CryptAcquireContextA (ref providerHandle, cspParams.KeyContainerName,
54 cspParams.ProviderName, cspParams.ProviderType, flags);
56 // key container may not exist
57 flags |= CryptoAPI.CRYPT_NEWKEYSET;
58 lastResult = CryptoAPI.CryptAcquireContextA (ref providerHandle, cspParams.KeyContainerName,
59 cspParams.ProviderName, cspParams.ProviderType, flags);
69 get { return CryptoAPI.GetLastError (); }
72 public IntPtr Handle {
73 get { return providerHandle; }
77 get { return lastResult; }
80 internal bool InternalResult {
81 set { lastResult = value; }
84 // release unmanaged resources
85 public void Dispose ()
87 if (providerHandle != IntPtr.Zero) {
88 lastResult = CryptoAPI.CryptReleaseContext (providerHandle, 0);
90 providerHandle = IntPtr.Zero;
91 GC.SuppressFinalize (this);