New test.
[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 NET_1_1
96                                 if (useMachineKeyStore)
97                                         parameters.Flags |= CspProviderFlags.UseMachineKeyStore;
98 #endif
99                                 store = new KeyPairPersistence (parameters);
100                                 // no need to load - it cannot exists
101                         }
102                         else {
103                                 store = new KeyPairPersistence (parameters);
104                                 store.Load ();
105                                 if (store.KeyValue != null) {
106                                         persisted = true;
107                                         this.FromXmlString (store.KeyValue);
108                                 }
109                         }
110                 }
111
112                 ~DSACryptoServiceProvider ()
113                 {
114                         Dispose (false);
115                 }
116
117                 // DSA isn't used for key exchange
118                 public override string KeyExchangeAlgorithm {
119                         get { return null; }
120                 }
121
122                 public override int KeySize {
123                         get { return dsa.KeySize; }
124                 }
125
126                 public bool PersistKeyInCsp {
127                         get { return persistKey; }
128                         set { persistKey = value; }
129                 }
130
131                 [ComVisible (false)]
132                 public bool PublicOnly {
133                         get { return dsa.PublicOnly; }
134                 }
135
136                 public override string SignatureAlgorithm {
137                         get { return "http://www.w3.org/2000/09/xmldsig#dsa-sha1"; }
138                 }
139
140 #if NET_1_1
141                 private static bool useMachineKeyStore = false;
142
143                 public static bool UseMachineKeyStore {
144                         get { return useMachineKeyStore; }
145                         set { useMachineKeyStore = value; }
146                 }
147 #endif
148
149                 public override DSAParameters ExportParameters (bool includePrivateParameters) 
150                 {
151                         if ((includePrivateParameters) && (!privateKeyExportable)) {
152                                 throw new CryptographicException (
153                                         Locale.GetText ("Cannot export private key"));
154                         }
155
156                         return dsa.ExportParameters (includePrivateParameters);
157                 }
158
159                 public override void ImportParameters (DSAParameters parameters) 
160                 {
161                         dsa.ImportParameters (parameters);
162                 }
163
164                 public override byte[] CreateSignature (byte[] rgbHash)
165                 {
166                         return dsa.CreateSignature (rgbHash);
167                 }
168
169                 public byte[] SignData (byte[] buffer)
170                 {
171                         // right now only SHA1 is supported by FIPS186-2
172                         HashAlgorithm hash = SHA1.Create ();
173                         byte[] toBeSigned = hash.ComputeHash (buffer);
174                         return dsa.CreateSignature (toBeSigned);
175                 }
176
177                 public byte[] SignData (byte[] buffer, int offset, int count)
178                 {
179                         // right now only SHA1 is supported by FIPS186-2
180                         HashAlgorithm hash = SHA1.Create ();
181                         byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
182                         return dsa.CreateSignature (toBeSigned);
183                 }
184
185                 public byte[] SignData (Stream inputStream)
186                 {
187                         // right now only SHA1 is supported by FIPS186-2
188                         HashAlgorithm hash = SHA1.Create ();
189                         byte[] toBeSigned = hash.ComputeHash (inputStream);
190                         return dsa.CreateSignature (toBeSigned);
191                 }
192
193                 public byte[] SignHash (byte[] rgbHash, string str)
194                 {
195                         // right now only SHA1 is supported by FIPS186-2
196                         if (String.Compare (str, "SHA1", true, CultureInfo.InvariantCulture) != 0) {
197                                 // not documented
198                                 throw new CryptographicException (Locale.GetText ("Only SHA1 is supported."));
199                         }
200
201                         return dsa.CreateSignature (rgbHash);
202                 }
203
204                 public bool VerifyData (byte[] rgbData, byte[] rgbSignature)
205                 {
206                         // right now only SHA1 is supported by FIPS186-2
207                         HashAlgorithm hash = SHA1.Create();
208                         byte[] toBeVerified = hash.ComputeHash (rgbData);
209                         return dsa.VerifySignature (toBeVerified, rgbSignature);
210                 }
211
212                 // LAMESPEC: MD5 isn't allowed with DSA
213                 public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature)
214                 {
215                         if (str == null)
216                                 str = "SHA1"; // default value
217                         if (String.Compare (str, "SHA1", true, CultureInfo.InvariantCulture) != 0) {
218                                 throw new CryptographicException (Locale.GetText ("Only SHA1 is supported."));
219                         }
220
221                         return dsa.VerifySignature (rgbHash, rgbSignature);
222                 }
223
224                 public override bool VerifySignature (byte[] rgbHash, byte[] rgbSignature)
225                 {
226                         return dsa.VerifySignature (rgbHash, rgbSignature);
227                 }
228
229                 protected override void Dispose (bool disposing) 
230                 {
231                         if (!m_disposed) {
232                                 // the key is persisted and we do not want it persisted
233                                 if ((persisted) && (!persistKey)) {
234                                         store.Remove ();        // delete the container
235                                 }
236                                 if (dsa != null)
237                                         dsa.Clear ();
238                                 // call base class 
239                                 // no need as they all are abstract before us
240                                 m_disposed = true;
241                         }
242                 }
243
244                 // private stuff
245
246                 private void OnKeyGenerated (object sender, EventArgs e) 
247                 {
248                         // the key isn't persisted and we want it persisted
249                         if ((persistKey) && (!persisted)) {
250                                 // save the current keypair
251                                 store.KeyValue = this.ToXmlString (!dsa.PublicOnly);
252                                 store.Save ();
253                                 persisted = true;
254                         }
255                 }
256                 // ICspAsymmetricAlgorithm
257
258                 [MonoTODO ("call into KeyPairPersistence to get details")]
259                 [ComVisible (false)]
260                 public CspKeyContainerInfo CspKeyContainerInfo {
261                         get { return null; }
262                 }
263
264                 [ComVisible (false)]
265                 public byte[] ExportCspBlob (bool includePrivateParameters)
266                 {
267                         byte[] blob = null;
268                         if (includePrivateParameters)
269                                 blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
270                         else
271                                 blob = CryptoConvert.ToCapiPublicKeyBlob (this);
272                         return blob;
273                 }
274
275                 [ComVisible (false)]
276                 public void ImportCspBlob (byte[] keyBlob)
277                 {
278                         if (keyBlob == null)
279                                 throw new ArgumentNullException ("keyBlob");
280                         DSA dsa = CryptoConvert.FromCapiKeyBlobDSA (keyBlob);
281                         if (dsa is DSACryptoServiceProvider) {
282                                 DSAParameters dsap = dsa.ExportParameters (!(dsa as DSACryptoServiceProvider).PublicOnly);
283                                 ImportParameters (dsap);
284                         } else {
285                                 // we can't know from DSA if the private key is available
286                                 try {
287                                         // so we try it...
288                                         DSAParameters dsap = dsa.ExportParameters (true);
289                                         ImportParameters (dsap);
290                                 }
291                                 catch {
292                                         // and fall back
293                                         DSAParameters dsap = dsa.ExportParameters (false);
294                                         ImportParameters (dsap);
295                                 }
296                         }
297                 }
298         }
299 }
300
301 #endif
302