07200f28b4e90e0b126da82922e3c8aa6cbf1619
[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 using System.IO;
35 using System.Globalization;
36 using System.Runtime.InteropServices;
37
38 using Mono.Security.Cryptography;
39
40 namespace System.Security.Cryptography {
41
42         [ComVisible (true)]
43         public sealed class DSACryptoServiceProvider : DSA, ICspAsymmetricAlgorithm {
44                 private const int PROV_DSS_DH = 13;             // from WinCrypt.h
45
46                 private KeyPairPersistence store;
47                 private bool persistKey;
48                 private bool persisted;
49
50                 private bool privateKeyExportable = true;
51                 private bool m_disposed;
52
53                 private DSAManaged dsa;
54
55                 // MS implementation generates a keypair everytime a new DSA 
56                 // object is created (unless an existing key container is 
57                 // specified in the CspParameters).
58                 // However we:
59                 // (a) often use DSA to import an existing keypair.
60                 // (b) take a LOT of time to generate the DSA group
61                 // So we'll generate the keypair only when (and if) it's being
62                 // used (or exported). This should save us a lot of time (at
63                 // least in the unit tests).
64
65                 public DSACryptoServiceProvider ()
66                         : this (1024)
67                 {
68                 }
69
70                 public DSACryptoServiceProvider (CspParameters parameters)
71                         : this (1024, parameters)
72                 {
73                 }
74
75                 public DSACryptoServiceProvider (int dwKeySize)
76                 {
77                         Common (dwKeySize, false);
78                 }
79
80                 public DSACryptoServiceProvider (int dwKeySize, CspParameters parameters)
81                 {
82                         bool has_parameters = parameters != null;
83                         Common (dwKeySize, has_parameters);
84                         if (has_parameters)
85                                 Common (parameters);
86                 }
87
88                 void Common (int dwKeySize, bool parameters) 
89                 {
90                         LegalKeySizesValue = new KeySizes [1];
91                         LegalKeySizesValue [0] = new KeySizes (512, 1024, 64);
92
93                         // will throw an exception is key size isn't supported
94                         KeySize = dwKeySize;
95                         dsa = new DSAManaged (dwKeySize);
96                         dsa.KeyGenerated += new DSAManaged.KeyGeneratedEventHandler (OnKeyGenerated);
97
98                         persistKey = parameters;
99                         if (parameters)
100                                 return;
101
102                         var p = new CspParameters (PROV_DSS_DH);
103                         if (useMachineKeyStore)
104                                 p.Flags |= CspProviderFlags.UseMachineKeyStore;
105                         store = new KeyPairPersistence (p);
106                         // no need to load - it cannot exists
107                 }
108
109                 void Common (CspParameters parameters)
110                 {
111                         store = new KeyPairPersistence (parameters);
112                         store.Load ();
113                         if (store.KeyValue != null) {
114                                 persisted = true;
115                                 this.FromXmlString (store.KeyValue);
116                         }
117                         privateKeyExportable = (parameters.Flags & CspProviderFlags.UseNonExportableKey) == 0;
118                 }
119
120                 ~DSACryptoServiceProvider ()
121                 {
122                         Dispose (false);
123                 }
124
125                 // DSA isn't used for key exchange
126                 public override string KeyExchangeAlgorithm {
127                         get { return null; }
128                 }
129
130                 public override int KeySize {
131                         get { return dsa.KeySize; }
132                 }
133
134                 public bool PersistKeyInCsp {
135                         get { return persistKey; }
136                         set { persistKey = value; }
137                 }
138
139                 [ComVisible (false)]
140                 public bool PublicOnly {
141                         get { return dsa.PublicOnly; }
142                 }
143
144                 public override string SignatureAlgorithm {
145                         get { return "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; }
146                 }
147
148                 private static bool useMachineKeyStore;
149
150                 public static bool UseMachineKeyStore {
151                         get { return useMachineKeyStore; }
152                         set { useMachineKeyStore = value; }
153                 }
154
155                 public override DSAParameters ExportParameters (bool includePrivateParameters) 
156                 {
157                         if ((includePrivateParameters) && (!privateKeyExportable)) {
158                                 throw new CryptographicException (
159                                         Locale.GetText ("Cannot export private key"));
160                         }
161
162                         return dsa.ExportParameters (includePrivateParameters);
163                 }
164
165                 public override void ImportParameters (DSAParameters parameters) 
166                 {
167                         dsa.ImportParameters (parameters);
168                 }
169
170                 public override byte[] CreateSignature (byte[] rgbHash)
171                 {
172                         return dsa.CreateSignature (rgbHash);
173                 }
174
175                 public byte[] SignData (byte[] buffer)
176                 {
177                         // right now only SHA1 is supported by FIPS186-2
178                         HashAlgorithm hash = SHA1.Create ();
179                         byte[] toBeSigned = hash.ComputeHash (buffer);
180                         return dsa.CreateSignature (toBeSigned);
181                 }
182
183                 public byte[] SignData (byte[] buffer, int offset, int count)
184                 {
185                         // right now only SHA1 is supported by FIPS186-2
186                         HashAlgorithm hash = SHA1.Create ();
187                         byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
188                         return dsa.CreateSignature (toBeSigned);
189                 }
190
191                 public byte[] SignData (Stream inputStream)
192                 {
193                         // right now only SHA1 is supported by FIPS186-2
194                         HashAlgorithm hash = SHA1.Create ();
195                         byte[] toBeSigned = hash.ComputeHash (inputStream);
196                         return dsa.CreateSignature (toBeSigned);
197                 }
198
199                 public byte[] SignHash (byte[] rgbHash, string str)
200                 {
201                         // right now only SHA1 is supported by FIPS186-2
202                         if (String.Compare (str, "SHA1", true, CultureInfo.InvariantCulture) != 0) {
203                                 // not documented
204                                 throw new CryptographicException (Locale.GetText ("Only SHA1 is supported."));
205                         }
206
207                         return dsa.CreateSignature (rgbHash);
208                 }
209
210                 public bool VerifyData (byte[] rgbData, byte[] rgbSignature)
211                 {
212                         // right now only SHA1 is supported by FIPS186-2
213                         HashAlgorithm hash = SHA1.Create();
214                         byte[] toBeVerified = hash.ComputeHash (rgbData);
215                         return dsa.VerifySignature (toBeVerified, rgbSignature);
216                 }
217
218                 // LAMESPEC: MD5 isn't allowed with DSA
219                 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature)
220                 {
221                         if (str == null)
222                                 str = "SHA1"; // default value
223                         if (String.Compare (str, "SHA1", true, CultureInfo.InvariantCulture) != 0) {
224                                 throw new CryptographicException (Locale.GetText ("Only SHA1 is supported."));
225                         }
226
227                         return dsa.VerifySignature (rgbHash, rgbSignature);
228                 }
229
230                 public override bool VerifySignature (byte[] rgbHash, byte[] rgbSignature)
231                 {
232                         return dsa.VerifySignature (rgbHash, rgbSignature);
233                 }
234
235                 protected override byte[] HashData (byte[] data, int offset, int count, HashAlgorithmName hashAlgorithm)
236                 {
237                         if (hashAlgorithm != HashAlgorithmName.SHA1)
238                         {
239                                 throw new CryptographicException(Environment.GetResourceString("Cryptography_UnknownHashAlgorithm", hashAlgorithm.Name));
240                         }
241
242                         var hash = HashAlgorithm.Create (hashAlgorithm.Name);
243                         return hash.ComputeHash (data, offset, count);
244                 }
245
246                 protected override byte[] HashData (System.IO.Stream data, HashAlgorithmName hashAlgorithm)
247                 {
248                         if (hashAlgorithm != HashAlgorithmName.SHA1)
249                         {
250                                 throw new CryptographicException(Environment.GetResourceString("Cryptography_UnknownHashAlgorithm", hashAlgorithm.Name));
251                         }
252
253                         var hash = HashAlgorithm.Create (hashAlgorithm.Name);
254                         return hash.ComputeHash (data);
255                 }
256
257                 protected override void Dispose (bool disposing) 
258                 {
259                         if (!m_disposed) {
260                                 // the key is persisted and we do not want it persisted
261                                 if ((persisted) && (!persistKey)) {
262                                         store.Remove ();        // delete the container
263                                 }
264                                 if (dsa != null)
265                                         dsa.Clear ();
266                                 // call base class 
267                                 // no need as they all are abstract before us
268                                 m_disposed = true;
269                         }
270                 }
271
272                 // private stuff
273
274                 private void OnKeyGenerated (object sender, EventArgs e) 
275                 {
276                         // the key isn't persisted and we want it persisted
277                         if ((persistKey) && (!persisted)) {
278                                 // save the current keypair
279                                 store.KeyValue = this.ToXmlString (!dsa.PublicOnly);
280                                 store.Save ();
281                                 persisted = true;
282                         }
283                 }
284                 // ICspAsymmetricAlgorithm
285
286                 [MonoTODO ("call into KeyPairPersistence to get details")]
287                 [ComVisible (false)]
288                 public CspKeyContainerInfo CspKeyContainerInfo {
289                         get { return null; }
290                 }
291
292                 [ComVisible (false)]
293                 public byte[] ExportCspBlob (bool includePrivateParameters)
294                 {
295                         byte[] blob = null;
296                         if (includePrivateParameters)
297                                 blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
298                         else
299                                 blob = CryptoConvert.ToCapiPublicKeyBlob (this);
300                         return blob;
301                 }
302
303                 [ComVisible (false)]
304                 public void ImportCspBlob (byte[] keyBlob)
305                 {
306                         if (keyBlob == null)
307                                 throw new ArgumentNullException ("keyBlob");
308                         DSA dsa = CryptoConvert.FromCapiKeyBlobDSA (keyBlob);
309                         if (dsa is DSACryptoServiceProvider) {
310                                 DSAParameters dsap = dsa.ExportParameters (!(dsa as DSACryptoServiceProvider).PublicOnly);
311                                 ImportParameters (dsap);
312                         } else {
313                                 // we can't know from DSA if the private key is available
314                                 try {
315                                         // so we try it...
316                                         DSAParameters dsap = dsa.ExportParameters (true);
317                                         ImportParameters (dsap);
318                                 }
319                                 catch {
320                                         // and fall back
321                                         DSAParameters dsap = dsa.ExportParameters (false);
322                                         ImportParameters (dsap);
323                                 }
324                         }
325                 }
326         }
327 }