Merge pull request #409 from Alkarex/patch-1
[mono.git] / mcs / class / corlib / System.Security.Cryptography / DSACryptoServiceProvider.cs
1 //
2 // System.Security.Cryptography.DSACryptoServiceProvider.cs
3 //
4 // Authors:
5 //      Dan Lewis (dihlewis@yahoo.co.uk)
6 //      Sebastien Pouliot <sebastien@ximian.com>
7 //      Ben Maurer (bmaurer@users.sf.net)
8 //
9 // (C) 2002
10 // Portions (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
11 // Portions (C) 2003 Ben Maurer
12 // Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
13 //
14 // Permission is hereby granted, free of charge, to any person obtaining
15 // a copy of this software and associated documentation files (the
16 // "Software"), to deal in the Software without restriction, including
17 // without limitation the rights to use, copy, modify, merge, publish,
18 // distribute, sublicense, and/or sell copies of the Software, and to
19 // permit persons to whom the Software is furnished to do so, subject to
20 // the following conditions:
21 // 
22 // The above copyright notice and this permission notice shall be
23 // included in all copies or substantial portions of the Software.
24 // 
25 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
26 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
28 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
29 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
30 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
31 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
32 //
33
34 #if !MOONLIGHT
35
36 using System.IO;
37 using System.Globalization;
38 using System.Runtime.InteropServices;
39
40 using Mono.Security.Cryptography;
41
42 namespace System.Security.Cryptography {
43
44         [ComVisible (true)]
45         public sealed class DSACryptoServiceProvider : DSA, ICspAsymmetricAlgorithm {
46                 private const int PROV_DSS_DH = 13;             // from WinCrypt.h
47
48                 private KeyPairPersistence store;
49                 private bool persistKey;
50                 private bool persisted;
51
52                 private bool privateKeyExportable = true;
53                 private bool m_disposed;
54
55                 private DSAManaged dsa;
56
57                 // MS implementation generates a keypair everytime a new DSA 
58                 // object is created (unless an existing key container is 
59                 // specified in the CspParameters).
60                 // However we:
61                 // (a) often use DSA to import an existing keypair.
62                 // (b) take a LOT of time to generate the DSA group
63                 // So we'll generate the keypair only when (and if) it's being
64                 // used (or exported). This should save us a lot of time (at
65                 // least in the unit tests).
66
67                 public DSACryptoServiceProvider ()
68                         : this (1024, null)
69                 {
70                 }
71
72                 public DSACryptoServiceProvider (CspParameters parameters)
73                         : this (1024, parameters)
74                 {
75                 }
76
77                 public DSACryptoServiceProvider (int dwKeySize)
78                         : this (dwKeySize, null)
79                 {
80                 }
81
82                 public DSACryptoServiceProvider (int dwKeySize, CspParameters parameters)
83                 {
84                         LegalKeySizesValue = new KeySizes [1];
85                         LegalKeySizesValue [0] = new KeySizes (512, 1024, 64);
86
87                         // will throw an exception is key size isn't supported
88                         KeySize = dwKeySize;
89                         dsa = new DSAManaged (dwKeySize);
90                         dsa.KeyGenerated += new DSAManaged.KeyGeneratedEventHandler (OnKeyGenerated);
91
92                         persistKey = (parameters != null);
93                         if (parameters == null) {
94                                 parameters = new CspParameters (PROV_DSS_DH);
95                                 if (useMachineKeyStore)
96                                         parameters.Flags |= CspProviderFlags.UseMachineKeyStore;
97                                 store = new KeyPairPersistence (parameters);
98                                 // no need to load - it cannot exists
99                         }
100                         else {
101                                 store = new KeyPairPersistence (parameters);
102                                 store.Load ();
103                                 if (store.KeyValue != null) {
104                                         persisted = true;
105                                         this.FromXmlString (store.KeyValue);
106                                 }
107                         }
108                 }
109
110                 ~DSACryptoServiceProvider ()
111                 {
112                         Dispose (false);
113                 }
114
115                 // DSA isn't used for key exchange
116                 public override string KeyExchangeAlgorithm {
117                         get { return null; }
118                 }
119
120                 public override int KeySize {
121                         get { return dsa.KeySize; }
122                 }
123
124                 public bool PersistKeyInCsp {
125                         get { return persistKey; }
126                         set { persistKey = value; }
127                 }
128
129                 [ComVisible (false)]
130                 public bool PublicOnly {
131                         get { return dsa.PublicOnly; }
132                 }
133
134                 public override string SignatureAlgorithm {
135                         get { return "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; }
136                 }
137
138                 private static bool useMachineKeyStore;
139
140                 public static bool UseMachineKeyStore {
141                         get { return useMachineKeyStore; }
142                         set { useMachineKeyStore = value; }
143                 }
144
145                 public override DSAParameters ExportParameters (bool includePrivateParameters) 
146                 {
147                         if ((includePrivateParameters) && (!privateKeyExportable)) {
148                                 throw new CryptographicException (
149                                         Locale.GetText ("Cannot export private key"));
150                         }
151
152                         return dsa.ExportParameters (includePrivateParameters);
153                 }
154
155                 public override void ImportParameters (DSAParameters parameters) 
156                 {
157                         dsa.ImportParameters (parameters);
158                 }
159
160                 public override byte[] CreateSignature (byte[] rgbHash)
161                 {
162                         return dsa.CreateSignature (rgbHash);
163                 }
164
165                 public byte[] SignData (byte[] buffer)
166                 {
167                         // right now only SHA1 is supported by FIPS186-2
168                         HashAlgorithm hash = SHA1.Create ();
169                         byte[] toBeSigned = hash.ComputeHash (buffer);
170                         return dsa.CreateSignature (toBeSigned);
171                 }
172
173                 public byte[] SignData (byte[] buffer, int offset, int count)
174                 {
175                         // right now only SHA1 is supported by FIPS186-2
176                         HashAlgorithm hash = SHA1.Create ();
177                         byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
178                         return dsa.CreateSignature (toBeSigned);
179                 }
180
181                 public byte[] SignData (Stream inputStream)
182                 {
183                         // right now only SHA1 is supported by FIPS186-2
184                         HashAlgorithm hash = SHA1.Create ();
185                         byte[] toBeSigned = hash.ComputeHash (inputStream);
186                         return dsa.CreateSignature (toBeSigned);
187                 }
188
189                 public byte[] SignHash (byte[] rgbHash, string str)
190                 {
191                         // right now only SHA1 is supported by FIPS186-2
192                         if (String.Compare (str, "SHA1", true, CultureInfo.InvariantCulture) != 0) {
193                                 // not documented
194                                 throw new CryptographicException (Locale.GetText ("Only SHA1 is supported."));
195                         }
196
197                         return dsa.CreateSignature (rgbHash);
198                 }
199
200                 public bool VerifyData (byte[] rgbData, byte[] rgbSignature)
201                 {
202                         // right now only SHA1 is supported by FIPS186-2
203                         HashAlgorithm hash = SHA1.Create();
204                         byte[] toBeVerified = hash.ComputeHash (rgbData);
205                         return dsa.VerifySignature (toBeVerified, rgbSignature);
206                 }
207
208                 // LAMESPEC: MD5 isn't allowed with DSA
209                 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature)
210                 {
211                         if (str == null)
212                                 str = "SHA1"; // default value
213                         if (String.Compare (str, "SHA1", true, CultureInfo.InvariantCulture) != 0) {
214                                 throw new CryptographicException (Locale.GetText ("Only SHA1 is supported."));
215                         }
216
217                         return dsa.VerifySignature (rgbHash, rgbSignature);
218                 }
219
220                 public override bool VerifySignature (byte[] rgbHash, byte[] rgbSignature)
221                 {
222                         return dsa.VerifySignature (rgbHash, rgbSignature);
223                 }
224
225                 protected override void Dispose (bool disposing) 
226                 {
227                         if (!m_disposed) {
228                                 // the key is persisted and we do not want it persisted
229                                 if ((persisted) && (!persistKey)) {
230                                         store.Remove ();        // delete the container
231                                 }
232                                 if (dsa != null)
233                                         dsa.Clear ();
234                                 // call base class 
235                                 // no need as they all are abstract before us
236                                 m_disposed = true;
237                         }
238                 }
239
240                 // private stuff
241
242                 private void OnKeyGenerated (object sender, EventArgs e) 
243                 {
244                         // the key isn't persisted and we want it persisted
245                         if ((persistKey) && (!persisted)) {
246                                 // save the current keypair
247                                 store.KeyValue = this.ToXmlString (!dsa.PublicOnly);
248                                 store.Save ();
249                                 persisted = true;
250                         }
251                 }
252                 // ICspAsymmetricAlgorithm
253
254                 [MonoTODO ("call into KeyPairPersistence to get details")]
255                 [ComVisible (false)]
256                 public CspKeyContainerInfo CspKeyContainerInfo {
257                         get { return null; }
258                 }
259
260                 [ComVisible (false)]
261                 public byte[] ExportCspBlob (bool includePrivateParameters)
262                 {
263                         byte[] blob = null;
264                         if (includePrivateParameters)
265                                 blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
266                         else
267                                 blob = CryptoConvert.ToCapiPublicKeyBlob (this);
268                         return blob;
269                 }
270
271                 [ComVisible (false)]
272                 public void ImportCspBlob (byte[] keyBlob)
273                 {
274                         if (keyBlob == null)
275                                 throw new ArgumentNullException ("keyBlob");
276                         DSA dsa = CryptoConvert.FromCapiKeyBlobDSA (keyBlob);
277                         if (dsa is DSACryptoServiceProvider) {
278                                 DSAParameters dsap = dsa.ExportParameters (!(dsa as DSACryptoServiceProvider).PublicOnly);
279                                 ImportParameters (dsap);
280                         } else {
281                                 // we can't know from DSA if the private key is available
282                                 try {
283                                         // so we try it...
284                                         DSAParameters dsap = dsa.ExportParameters (true);
285                                         ImportParameters (dsap);
286                                 }
287                                 catch {
288                                         // and fall back
289                                         DSAParameters dsap = dsa.ExportParameters (false);
290                                         ImportParameters (dsap);
291                                 }
292                         }
293                 }
294         }
295 }
296
297 #endif
298