1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435
|
//
// RSACryptoServiceProvider.cs: Handles an RSA implementation.
//
// Authors:
// Sebastien Pouliot <sebastien@ximian.com>
// Ben Maurer (bmaurer@users.sf.net)
//
// (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com)
// Portions (C) 2003 Ben Maurer
// Copyright (C) 2004-2005 Novell, Inc (http://www.novell.com)
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if !NET_2_1 || MONOTOUCH
using System.IO;
using System.Runtime.InteropServices;
using Mono.Security.Cryptography;
namespace System.Security.Cryptography {
#if NET_2_0
[ComVisible (true)]
public sealed class RSACryptoServiceProvider : RSA, ICspAsymmetricAlgorithm {
#else
public sealed class RSACryptoServiceProvider : RSA {
#endif
private const int PROV_RSA_FULL = 1; // from WinCrypt.h
private KeyPairPersistence store;
private bool persistKey;
private bool persisted;
private bool privateKeyExportable = true;
private bool m_disposed;
private RSAManaged rsa;
public RSACryptoServiceProvider ()
{
// Here it's not clear if we need to generate a keypair
// (note: MS implementation generates a keypair in this case).
// However we:
// (a) often use this constructor to import an existing keypair.
// (b) take a LOT of time to generate the RSA keypair
// So we'll generate the keypair only when (and if) it's being
// used (or exported). This should save us a lot of time (at
// least in the unit tests).
Common (1024, null);
}
public RSACryptoServiceProvider (CspParameters parameters)
{
Common (1024, parameters);
// no keypair generation done at this stage
}
public RSACryptoServiceProvider (int dwKeySize)
{
// Here it's clear that we need to generate a new keypair
Common (dwKeySize, null);
// no keypair generation done at this stage
}
public RSACryptoServiceProvider (int dwKeySize, CspParameters parameters)
{
Common (dwKeySize, parameters);
// no keypair generation done at this stage
}
private void Common (int dwKeySize, CspParameters p)
{
// Microsoft RSA CSP can do between 384 and 16384 bits keypair
LegalKeySizesValue = new KeySizes [1];
LegalKeySizesValue [0] = new KeySizes (384, 16384, 8);
base.KeySize = dwKeySize;
rsa = new RSAManaged (KeySize);
rsa.KeyGenerated += new RSAManaged.KeyGeneratedEventHandler (OnKeyGenerated);
persistKey = (p != null);
if (p == null) {
p = new CspParameters (PROV_RSA_FULL);
#if NET_1_1
if (useMachineKeyStore)
p.Flags |= CspProviderFlags.UseMachineKeyStore;
#endif
store = new KeyPairPersistence (p);
// no need to load - it cannot exists
}
else {
store = new KeyPairPersistence (p);
store.Load ();
if (store.KeyValue != null) {
persisted = true;
this.FromXmlString (store.KeyValue);
}
}
}
#if NET_1_1
private static bool useMachineKeyStore = false;
public static bool UseMachineKeyStore {
get { return useMachineKeyStore; }
set { useMachineKeyStore = value; }
}
#endif
~RSACryptoServiceProvider ()
{
// Zeroize private key
Dispose (false);
}
public override string KeyExchangeAlgorithm {
get { return "RSA-PKCS1-KeyEx"; }
}
public override int KeySize {
get {
if (rsa == null)
return KeySizeValue;
else
return rsa.KeySize;
}
}
public bool PersistKeyInCsp {
get { return persistKey; }
set {
persistKey = value;
if (persistKey)
OnKeyGenerated (rsa, null);
}
}
#if (NET_2_0)
[ComVisible (false)]
public
#else
internal
#endif
bool PublicOnly {
get { return rsa.PublicOnly; }
}
public override string SignatureAlgorithm {
get { return "http://www.w3.org/2000/09/xmldsig#rsa-sha1"; }
}
public byte[] Decrypt (byte[] rgb, bool fOAEP)
{
#if NET_1_1
if (m_disposed)
throw new ObjectDisposedException ("rsa");
#endif
// choose between OAEP or PKCS#1 v.1.5 padding
AsymmetricKeyExchangeDeformatter def = null;
if (fOAEP)
def = new RSAOAEPKeyExchangeDeformatter (rsa);
else
def = new RSAPKCS1KeyExchangeDeformatter (rsa);
return def.DecryptKeyExchange (rgb);
}
// NOTE: Unlike MS we need this method
// LAMESPEC: Not available from MS .NET framework but MS don't tell
// why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
// only encrypt/decrypt session (secret) key using asymmetric keys.
// Using this method to decrypt data IS dangerous (and very slow).
public override byte[] DecryptValue (byte[] rgb)
{
if (!rsa.IsCrtPossible)
throw new CryptographicException ("Incomplete private key - missing CRT.");
return rsa.DecryptValue (rgb);
}
public byte[] Encrypt (byte[] rgb, bool fOAEP)
{
// choose between OAEP or PKCS#1 v.1.5 padding
AsymmetricKeyExchangeFormatter fmt = null;
if (fOAEP)
fmt = new RSAOAEPKeyExchangeFormatter (rsa);
else
fmt = new RSAPKCS1KeyExchangeFormatter (rsa);
return fmt.CreateKeyExchange (rgb);
}
// NOTE: Unlike MS we need this method
// LAMESPEC: Not available from MS .NET framework but MS don't tell
// why! DON'T USE IT UNLESS YOU KNOW WHAT YOU ARE DOING!!! You should
// only encrypt/decrypt session (secret) key using asymmetric keys.
// Using this method to encrypt data IS dangerous (and very slow).
public override byte[] EncryptValue (byte[] rgb)
{
return rsa.EncryptValue (rgb);
}
public override RSAParameters ExportParameters (bool includePrivateParameters)
{
if ((includePrivateParameters) && (!privateKeyExportable))
throw new CryptographicException ("cannot export private key");
return rsa.ExportParameters (includePrivateParameters);
}
public override void ImportParameters (RSAParameters parameters)
{
rsa.ImportParameters (parameters);
}
private HashAlgorithm GetHash (object halg)
{
if (halg == null)
throw new ArgumentNullException ("halg");
HashAlgorithm hash = null;
if (halg is String)
hash = HashAlgorithm.Create ((String)halg);
else if (halg is HashAlgorithm)
hash = (HashAlgorithm) halg;
else if (halg is Type)
hash = (HashAlgorithm) Activator.CreateInstance ((Type)halg);
else
throw new ArgumentException ("halg");
return hash;
}
// NOTE: this method can work with ANY configured (OID in machine.config)
// HashAlgorithm descendant
public byte[] SignData (byte[] buffer, object halg)
{
#if NET_1_1
if (buffer == null)
throw new ArgumentNullException ("buffer");
#endif
return SignData (buffer, 0, buffer.Length, halg);
}
// NOTE: this method can work with ANY configured (OID in machine.config)
// HashAlgorithm descendant
public byte[] SignData (Stream inputStream, object halg)
{
HashAlgorithm hash = GetHash (halg);
byte[] toBeSigned = hash.ComputeHash (inputStream);
return PKCS1.Sign_v15 (this, hash, toBeSigned);
}
// NOTE: this method can work with ANY configured (OID in machine.config)
// HashAlgorithm descendant
public byte[] SignData (byte[] buffer, int offset, int count, object halg)
{
HashAlgorithm hash = GetHash (halg);
byte[] toBeSigned = hash.ComputeHash (buffer, offset, count);
return PKCS1.Sign_v15 (this, hash, toBeSigned);
}
private string GetHashNameFromOID (string oid)
{
switch (oid) {
case "1.3.14.3.2.26":
return "SHA1";
case "1.2.840.113549.2.5":
return "MD5";
default:
throw new NotSupportedException (oid + " is an unsupported hash algorithm for RSA signing");
}
}
// LAMESPEC: str is not the hash name but an OID
// NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0
// and 1.1 because there's no method to get a hash algorithm from an OID.
// However there's no such limit when using the [De]Formatter class.
public byte[] SignHash (byte[] rgbHash, string str)
{
if (rgbHash == null)
throw new ArgumentNullException ("rgbHash");
#if NET_2_0
// Fx 2.0 defaults to the SHA-1
string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
#else
if (str == null)
throw new CryptographicException (Locale.GetText ("No OID specified"));
string hashName = GetHashNameFromOID (str);
#endif
HashAlgorithm hash = HashAlgorithm.Create (hashName);
return PKCS1.Sign_v15 (this, hash, rgbHash);
}
// NOTE: this method can work with ANY configured (OID in machine.config)
// HashAlgorithm descendant
public bool VerifyData (byte[] buffer, object halg, byte[] signature)
{
#if NET_1_1
if (buffer == null)
throw new ArgumentNullException ("buffer");
#endif
if (signature == null)
throw new ArgumentNullException ("signature");
HashAlgorithm hash = GetHash (halg);
byte[] toBeVerified = hash.ComputeHash (buffer);
return PKCS1.Verify_v15 (this, hash, toBeVerified, signature);
}
// LAMESPEC: str is not the hash name but an OID
// NOTE: this method is LIMITED to SHA1 and MD5 like the MS framework 1.0
// and 1.1 because there's no method to get a hash algorithm from an OID.
// However there's no such limit when using the [De]Formatter class.
public bool VerifyHash (byte[] rgbHash, string str, byte[] rgbSignature)
{
if (rgbHash == null)
throw new ArgumentNullException ("rgbHash");
if (rgbSignature == null)
throw new ArgumentNullException ("rgbSignature");
#if NET_2_0
// Fx 2.0 defaults to the SHA-1
string hashName = (str == null) ? "SHA1" : GetHashNameFromOID (str);
#else
if (str == null)
throw new CryptographicException (Locale.GetText ("No OID specified"));
string hashName = GetHashNameFromOID (str);
#endif
HashAlgorithm hash = HashAlgorithm.Create (hashName);
return PKCS1.Verify_v15 (this, hash, rgbHash, rgbSignature);
}
protected override void Dispose (bool disposing)
{
if (!m_disposed) {
// the key is persisted and we do not want it persisted
if ((persisted) && (!persistKey)) {
store.Remove (); // delete the container
}
if (rsa != null)
rsa.Clear ();
// call base class
// no need as they all are abstract before us
m_disposed = true;
}
}
// private stuff
private void OnKeyGenerated (object sender, EventArgs e)
{
// the key isn't persisted and we want it persisted
if ((persistKey) && (!persisted)) {
// save the current keypair
store.KeyValue = this.ToXmlString (!rsa.PublicOnly);
store.Save ();
persisted = true;
}
}
#if NET_2_0
// ICspAsymmetricAlgorithm
[MonoTODO ("Always return null")]
// FIXME: call into KeyPairPersistence to get details
[ComVisible (false)]
public CspKeyContainerInfo CspKeyContainerInfo {
get { return null; }
}
[ComVisible (false)]
public byte[] ExportCspBlob (bool includePrivateParameters)
{
byte[] blob = null;
if (includePrivateParameters)
blob = CryptoConvert.ToCapiPrivateKeyBlob (this);
else
blob = CryptoConvert.ToCapiPublicKeyBlob (this);
// ALGID (bytes 4-7) - default is KEYX
// 00 24 00 00 (for CALG_RSA_SIGN)
// 00 A4 00 00 (for CALG_RSA_KEYX)
blob [5] = 0xA4;
return blob;
}
[ComVisible (false)]
public void ImportCspBlob (byte[] keyBlob)
{
if (keyBlob == null)
throw new ArgumentNullException ("keyBlob");
RSA rsa = CryptoConvert.FromCapiKeyBlob (keyBlob);
if (rsa is RSACryptoServiceProvider) {
// default (if no change are present in machine.config)
RSAParameters rsap = rsa.ExportParameters (!(rsa as RSACryptoServiceProvider).PublicOnly);
ImportParameters (rsap);
} else {
// we can't know from RSA if the private key is available
try {
// so we try it...
RSAParameters rsap = rsa.ExportParameters (true);
ImportParameters (rsap);
}
catch {
// and fall back
RSAParameters rsap = rsa.ExportParameters (false);
ImportParameters (rsap);
}
}
}
#endif
}
}
#endif
|