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