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