BouncyCastle update.

git-svn-id: svn://svn.code.sf.net/p/itextsharp/code/trunk@45 820d3149-562b-4f88-9aa4-a8e61a3485cf
master
psoares33 2009-07-01 15:07:44 +00:00
parent 1737ad65dd
commit 1ea1146eb1
14 changed files with 8317 additions and 8279 deletions

View File

@ -1,130 +1,130 @@
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Math;
namespace Org.BouncyCastle.Asn1.Pkcs
{
public class PrivateKeyInfo
: Asn1Encodable
{
private readonly Asn1Object privKey;
private readonly AlgorithmIdentifier algID;
private readonly Asn1Set attributes;
public static PrivateKeyInfo GetInstance(
object obj)
{
if (obj is PrivateKeyInfo || obj == null)
{
return (PrivateKeyInfo) obj;
}
if (obj is Asn1Sequence)
{
return new PrivateKeyInfo((Asn1Sequence) obj);
}
throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj");
}
public PrivateKeyInfo(
AlgorithmIdentifier algID,
Asn1Object privateKey)
: this(algID, privateKey, null)
{
}
public PrivateKeyInfo(
AlgorithmIdentifier algID,
Asn1Object privateKey,
Asn1Set attributes)
{
this.privKey = privateKey;
this.algID = algID;
this.attributes = attributes;
}
private PrivateKeyInfo(
Asn1Sequence seq)
{
IEnumerator e = seq.GetEnumerator();
e.MoveNext();
BigInteger version = ((DerInteger) e.Current).Value;
if (version.IntValue != 0)
{
throw new ArgumentException("wrong version for private key info");
}
e.MoveNext();
algID = AlgorithmIdentifier.GetInstance(e.Current);
try
{
e.MoveNext();
Asn1OctetString data = (Asn1OctetString) e.Current;
privKey = Asn1Object.FromByteArray(data.GetOctets());
}
catch (IOException)
{
throw new ArgumentException("Error recoverying private key from sequence");
}
if (e.MoveNext())
{
attributes = Asn1Set.GetInstance((Asn1TaggedObject) e.Current, false);
}
}
public AlgorithmIdentifier AlgorithmID
{
get { return algID; }
}
public Asn1Object PrivateKey
{
get { return privKey; }
}
public Asn1Set Attributes
{
get { return attributes; }
}
/**
* write out an RSA private key with it's asscociated information
* as described in Pkcs8.
* <pre>
* PrivateKeyInfo ::= Sequence {
* version Version,
* privateKeyAlgorithm AlgorithmIdentifier {{PrivateKeyAlgorithms}},
* privateKey PrivateKey,
* attributes [0] IMPLICIT Attributes OPTIONAL
* }
* Version ::= Integer {v1(0)} (v1,...)
*
* PrivateKey ::= OCTET STRING
*
* Attributes ::= Set OF Attr
* </pre>
*/
public override Asn1Object ToAsn1Object()
{
Asn1EncodableVector v = new Asn1EncodableVector(
new DerInteger(0),
algID,
new DerOctetString(privKey));
if (attributes != null)
{
v.Add(new DerTaggedObject(false, 0, attributes));
}
return new DerSequence(v);
}
}
}
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Math;
namespace Org.BouncyCastle.Asn1.Pkcs
{
public class PrivateKeyInfo
: Asn1Encodable
{
private readonly Asn1Object privKey;
private readonly AlgorithmIdentifier algID;
private readonly Asn1Set attributes;
public static PrivateKeyInfo GetInstance(
object obj)
{
if (obj is PrivateKeyInfo || obj == null)
{
return (PrivateKeyInfo) obj;
}
if (obj is Asn1Sequence)
{
return new PrivateKeyInfo((Asn1Sequence) obj);
}
throw new ArgumentException("Unknown object in factory: " + obj.GetType().FullName, "obj");
}
public PrivateKeyInfo(
AlgorithmIdentifier algID,
Asn1Object privateKey)
: this(algID, privateKey, null)
{
}
public PrivateKeyInfo(
AlgorithmIdentifier algID,
Asn1Object privateKey,
Asn1Set attributes)
{
this.privKey = privateKey;
this.algID = algID;
this.attributes = attributes;
}
private PrivateKeyInfo(
Asn1Sequence seq)
{
IEnumerator e = seq.GetEnumerator();
e.MoveNext();
BigInteger version = ((DerInteger) e.Current).Value;
if (version.IntValue != 0)
{
throw new ArgumentException("wrong version for private key info");
}
e.MoveNext();
algID = AlgorithmIdentifier.GetInstance(e.Current);
try
{
e.MoveNext();
Asn1OctetString data = (Asn1OctetString) e.Current;
privKey = Asn1Object.FromByteArray(data.GetOctets());
}
catch (IOException)
{
throw new ArgumentException("Error recoverying private key from sequence");
}
if (e.MoveNext())
{
attributes = Asn1Set.GetInstance((Asn1TaggedObject) e.Current, false);
}
}
public AlgorithmIdentifier AlgorithmID
{
get { return algID; }
}
public Asn1Object PrivateKey
{
get { return privKey; }
}
public Asn1Set Attributes
{
get { return attributes; }
}
/**
* write out an RSA private key with its associated information
* as described in Pkcs8.
* <pre>
* PrivateKeyInfo ::= Sequence {
* version Version,
* privateKeyAlgorithm AlgorithmIdentifier {{PrivateKeyAlgorithms}},
* privateKey PrivateKey,
* attributes [0] IMPLICIT Attributes OPTIONAL
* }
* Version ::= Integer {v1(0)} (v1,...)
*
* PrivateKey ::= OCTET STRING
*
* Attributes ::= Set OF Attr
* </pre>
*/
public override Asn1Object ToAsn1Object()
{
Asn1EncodableVector v = new Asn1EncodableVector(
new DerInteger(0),
algID,
new DerOctetString(privKey));
if (attributes != null)
{
v.Add(new DerTaggedObject(false, 0, attributes));
}
return new DerSequence(v);
}
}
}

View File

@ -1,106 +1,110 @@
using System;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* Implements the Segmented Integer Counter (SIC) mode on top of a simple
* block cipher.
*/
public class SicBlockCipher
: IBlockCipher
{
private readonly IBlockCipher cipher;
private readonly int blockSize;
private readonly byte[] IV;
private readonly byte[] counter;
private readonly byte[] counterOut;
/**
* Basic constructor.
*
* @param c the block cipher to be used.
*/
public SicBlockCipher(IBlockCipher cipher)
{
this.cipher = cipher;
this.blockSize = cipher.GetBlockSize();
this.IV = new byte[blockSize];
this.counter = new byte[blockSize];
this.counterOut = new byte[blockSize];
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
public void Init(
bool forEncryption, //ignored by this CTR mode
ICipherParameters parameters)
{
if (parameters is ParametersWithIV)
{
ParametersWithIV ivParam = (ParametersWithIV) parameters;
byte[] iv = ivParam.GetIV();
Array.Copy(iv, 0, IV, 0, IV.Length);
Reset();
cipher.Init(true, ivParam.Parameters);
}
}
public string AlgorithmName
{
get { return cipher.AlgorithmName + "/SIC"; }
}
public bool IsPartialBlockOkay
{
get { return true; }
}
public int GetBlockSize()
{
return cipher.GetBlockSize();
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
cipher.ProcessBlock(counter, 0, counterOut, 0);
//
// XOR the counterOut with the plaintext producing the cipher text
//
for (int i = 0; i < counterOut.Length; i++)
{
output[outOff + i] = (byte)(counterOut[i] ^ input[inOff + i]);
}
// Increment the counter
int j = counter.Length;
while (--j >= 0 && ++counter[j] == 0)
{
}
return counter.Length;
}
public void Reset()
{
Array.Copy(IV, 0, counter, 0, counter.Length);
cipher.Reset();
}
}
}
using System;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
namespace Org.BouncyCastle.Crypto.Modes
{
/**
* Implements the Segmented Integer Counter (SIC) mode on top of a simple
* block cipher.
*/
public class SicBlockCipher
: IBlockCipher
{
private readonly IBlockCipher cipher;
private readonly int blockSize;
private readonly byte[] IV;
private readonly byte[] counter;
private readonly byte[] counterOut;
/**
* Basic constructor.
*
* @param c the block cipher to be used.
*/
public SicBlockCipher(IBlockCipher cipher)
{
this.cipher = cipher;
this.blockSize = cipher.GetBlockSize();
this.IV = new byte[blockSize];
this.counter = new byte[blockSize];
this.counterOut = new byte[blockSize];
}
/**
* return the underlying block cipher that we are wrapping.
*
* @return the underlying block cipher that we are wrapping.
*/
public IBlockCipher GetUnderlyingCipher()
{
return cipher;
}
public void Init(
bool forEncryption, //ignored by this CTR mode
ICipherParameters parameters)
{
if (parameters is ParametersWithIV)
{
ParametersWithIV ivParam = (ParametersWithIV) parameters;
byte[] iv = ivParam.GetIV();
Array.Copy(iv, 0, IV, 0, IV.Length);
Reset();
cipher.Init(true, ivParam.Parameters);
}
else
{
throw new ArgumentException("SIC mode requires ParametersWithIV", "parameters");
}
}
public string AlgorithmName
{
get { return cipher.AlgorithmName + "/SIC"; }
}
public bool IsPartialBlockOkay
{
get { return true; }
}
public int GetBlockSize()
{
return cipher.GetBlockSize();
}
public int ProcessBlock(
byte[] input,
int inOff,
byte[] output,
int outOff)
{
cipher.ProcessBlock(counter, 0, counterOut, 0);
//
// XOR the counterOut with the plaintext producing the cipher text
//
for (int i = 0; i < counterOut.Length; i++)
{
output[outOff + i] = (byte)(counterOut[i] ^ input[inOff + i]);
}
// Increment the counter
int j = counter.Length;
while (--j >= 0 && ++counter[j] == 0)
{
}
return counter.Length;
}
public void Reset()
{
Array.Copy(IV, 0, counter, 0, counter.Length);
cipher.Reset();
}
}
}

View File

@ -1,92 +1,114 @@
using System;
using System.IO;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
namespace Org.BouncyCastle.Crypto.Tls
{
/// <remarks>
/// A manager for ciphersuite. This class does manage all ciphersuites
/// which are used by MicroTLS.
/// </remarks>
public class TlsCipherSuiteManager
{
private const int TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x000a;
private const int TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = 0x0013;
private const int TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016;
private const int TLS_RSA_WITH_AES_128_CBC_SHA = 0x002f;
private const int TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x0032;
private const int TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033;
private const int TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035;
private const int TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x0038;
private const int TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039;
internal static void WriteCipherSuites(
Stream outStr)
{
int[] suites = new int[]
{
TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
TLS_RSA_WITH_AES_256_CBC_SHA,
TLS_RSA_WITH_AES_128_CBC_SHA,
TLS_RSA_WITH_3DES_EDE_CBC_SHA,
};
TlsUtilities.WriteUint16(2 * suites.Length, outStr);
for (int i = 0; i < suites.Length; ++i)
{
TlsUtilities.WriteUint16(suites[i], outStr);
}
}
internal static TlsCipherSuite GetCipherSuite(
int number,
TlsProtocolHandler handler)
{
switch (number)
{
case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
return new TlsBlockCipherCipherSuite(new CbcBlockCipher(new DesEdeEngine()), new CbcBlockCipher(new DesEdeEngine()), new Sha1Digest(), new Sha1Digest(), 24, TlsCipherSuite.KE_RSA);
case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
return new TlsBlockCipherCipherSuite(new CbcBlockCipher(new DesEdeEngine()), new CbcBlockCipher(new DesEdeEngine()), new Sha1Digest(), new Sha1Digest(), 24, TlsCipherSuite.KE_DHE_DSS);
case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
return new TlsBlockCipherCipherSuite(new CbcBlockCipher(new DesEdeEngine()), new CbcBlockCipher(new DesEdeEngine()), new Sha1Digest(), new Sha1Digest(), 24, TlsCipherSuite.KE_DHE_RSA);
case TLS_RSA_WITH_AES_128_CBC_SHA:
return new TlsBlockCipherCipherSuite(new CbcBlockCipher(new AesFastEngine()), new CbcBlockCipher(new AesFastEngine()), new Sha1Digest(), new Sha1Digest(), 16, TlsCipherSuite.KE_RSA);
case TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
return new TlsBlockCipherCipherSuite(new CbcBlockCipher(new AesFastEngine()), new CbcBlockCipher(new AesFastEngine()), new Sha1Digest(), new Sha1Digest(), 16, TlsCipherSuite.KE_DHE_DSS);
case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
return new TlsBlockCipherCipherSuite(new CbcBlockCipher(new AesFastEngine()), new CbcBlockCipher(new AesFastEngine()), new Sha1Digest(), new Sha1Digest(), 16, TlsCipherSuite.KE_DHE_RSA);
case TLS_RSA_WITH_AES_256_CBC_SHA:
return new TlsBlockCipherCipherSuite(new CbcBlockCipher(new AesFastEngine()), new CbcBlockCipher(new AesFastEngine()), new Sha1Digest(), new Sha1Digest(), 32, TlsCipherSuite.KE_RSA);
case TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
return new TlsBlockCipherCipherSuite(new CbcBlockCipher(new AesFastEngine()), new CbcBlockCipher(new AesFastEngine()), new Sha1Digest(), new Sha1Digest(), 32, TlsCipherSuite.KE_DHE_DSS);
case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
return new TlsBlockCipherCipherSuite(new CbcBlockCipher(new AesFastEngine()), new CbcBlockCipher(new AesFastEngine()), new Sha1Digest(), new Sha1Digest(), 32, TlsCipherSuite.KE_DHE_RSA);
default:
handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_handshake_failure);
/*
* Unreachable Code, failWithError will always throw an exception!
*/
return null;
}
}
}
}
using System;
using System.IO;
using Org.BouncyCastle.Crypto.Digests;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
namespace Org.BouncyCastle.Crypto.Tls
{
/// <remarks>
/// A manager for ciphersuite. This class does manage all ciphersuites
/// which are used by MicroTLS.
/// </remarks>
public class TlsCipherSuiteManager
{
private const int TLS_RSA_WITH_3DES_EDE_CBC_SHA = 0x000a;
private const int TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA = 0x0013;
private const int TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA = 0x0016;
private const int TLS_RSA_WITH_AES_128_CBC_SHA = 0x002f;
private const int TLS_DHE_DSS_WITH_AES_128_CBC_SHA = 0x0032;
private const int TLS_DHE_RSA_WITH_AES_128_CBC_SHA = 0x0033;
private const int TLS_RSA_WITH_AES_256_CBC_SHA = 0x0035;
private const int TLS_DHE_DSS_WITH_AES_256_CBC_SHA = 0x0038;
private const int TLS_DHE_RSA_WITH_AES_256_CBC_SHA = 0x0039;
internal static void WriteCipherSuites(
Stream outStr)
{
int[] suites = new int[]
{
TLS_DHE_RSA_WITH_AES_256_CBC_SHA,
TLS_DHE_DSS_WITH_AES_256_CBC_SHA,
TLS_DHE_RSA_WITH_AES_128_CBC_SHA,
TLS_DHE_DSS_WITH_AES_128_CBC_SHA,
TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA,
TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA,
TLS_RSA_WITH_AES_256_CBC_SHA,
TLS_RSA_WITH_AES_128_CBC_SHA,
TLS_RSA_WITH_3DES_EDE_CBC_SHA,
};
TlsUtilities.WriteUint16(2 * suites.Length, outStr);
for (int i = 0; i < suites.Length; ++i)
{
TlsUtilities.WriteUint16(suites[i], outStr);
}
}
internal static TlsCipherSuite GetCipherSuite(
int number,
TlsProtocolHandler handler)
{
switch (number)
{
case TLS_RSA_WITH_3DES_EDE_CBC_SHA:
return createDesEdeCipherSuite(24, TlsCipherSuite.KE_RSA);
case TLS_DHE_DSS_WITH_3DES_EDE_CBC_SHA:
return createDesEdeCipherSuite(24, TlsCipherSuite.KE_DHE_DSS);
case TLS_DHE_RSA_WITH_3DES_EDE_CBC_SHA:
return createDesEdeCipherSuite(24, TlsCipherSuite.KE_DHE_RSA);
case TLS_RSA_WITH_AES_128_CBC_SHA:
return createAesCipherSuite(16, TlsCipherSuite.KE_RSA);
case TLS_DHE_DSS_WITH_AES_128_CBC_SHA:
return createAesCipherSuite(16, TlsCipherSuite.KE_DHE_DSS);
case TLS_DHE_RSA_WITH_AES_128_CBC_SHA:
return createAesCipherSuite(16, TlsCipherSuite.KE_DHE_RSA);
case TLS_RSA_WITH_AES_256_CBC_SHA:
return createAesCipherSuite(32, TlsCipherSuite.KE_RSA);
case TLS_DHE_DSS_WITH_AES_256_CBC_SHA:
return createAesCipherSuite(32, TlsCipherSuite.KE_DHE_DSS);
case TLS_DHE_RSA_WITH_AES_256_CBC_SHA:
return createAesCipherSuite(32, TlsCipherSuite.KE_DHE_RSA);
default:
handler.FailWithError(TlsProtocolHandler.AL_fatal, TlsProtocolHandler.AP_handshake_failure);
/*
* Unreachable Code, failWithError will always throw an exception!
*/
return null;
}
}
private static TlsCipherSuite createAesCipherSuite(int cipherKeySize, short keyExchange)
{
return new TlsBlockCipherCipherSuite(createAesCipher(), createAesCipher(),
new Sha1Digest(), new Sha1Digest(), cipherKeySize, keyExchange);
}
private static TlsCipherSuite createDesEdeCipherSuite(int cipherKeySize, short keyExchange)
{
return new TlsBlockCipherCipherSuite(createDesEdeCipher(), createDesEdeCipher(),
new Sha1Digest(), new Sha1Digest(), cipherKeySize, keyExchange);
}
private static CbcBlockCipher createAesCipher()
{
return new CbcBlockCipher(new AesFastEngine());
}
private static CbcBlockCipher createDesEdeCipher()
{
return new CbcBlockCipher(new DesEdeEngine());
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,211 +1,211 @@
using System;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Pkcs
{
public sealed class PrivateKeyInfoFactory
{
private PrivateKeyInfoFactory()
{
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
AsymmetricKeyParameter key)
{
if (key == null)
throw new ArgumentNullException("key");
if (!key.IsPrivate)
throw new ArgumentException("Public key passed - private key expected", "key");
if (key is ElGamalPrivateKeyParameters)
{
ElGamalPrivateKeyParameters _key = (ElGamalPrivateKeyParameters)key;
return new PrivateKeyInfo(
new AlgorithmIdentifier(
OiwObjectIdentifiers.ElGamalAlgorithm,
new ElGamalParameter(
_key.Parameters.P,
_key.Parameters.G).ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is DsaPrivateKeyParameters)
{
DsaPrivateKeyParameters _key = (DsaPrivateKeyParameters)key;
return new PrivateKeyInfo(
new AlgorithmIdentifier(
X9ObjectIdentifiers.IdDsa,
new DsaParameter(
_key.Parameters.P,
_key.Parameters.Q,
_key.Parameters.G).ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is DHPrivateKeyParameters)
{
/*
Process DH private key.
The value for L was set to zero implicitly.
This is the same action as found in JCEDHPrivateKey GetEncoded method.
*/
DHPrivateKeyParameters _key = (DHPrivateKeyParameters)key;
DHParameter withNewL = new DHParameter(
_key.Parameters.P, _key.Parameters.G, 0);
return new PrivateKeyInfo(
new AlgorithmIdentifier(
PkcsObjectIdentifiers.DhKeyAgreement,
withNewL.ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is RsaKeyParameters)
{
AlgorithmIdentifier algID = new AlgorithmIdentifier(
PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance);
RsaPrivateKeyStructure keyStruct;
if (key is RsaPrivateCrtKeyParameters)
{
RsaPrivateCrtKeyParameters _key = (RsaPrivateCrtKeyParameters)key;
keyStruct = new RsaPrivateKeyStructure(
_key.Modulus,
_key.PublicExponent,
_key.Exponent,
_key.P,
_key.Q,
_key.DP,
_key.DQ,
_key.QInv);
}
else
{
RsaKeyParameters _key = (RsaKeyParameters) key;
keyStruct = new RsaPrivateKeyStructure(
_key.Modulus,
BigInteger.Zero,
_key.Exponent,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero);
}
return new PrivateKeyInfo(algID, keyStruct.ToAsn1Object());
}
if (key is ECPrivateKeyParameters)
{
ECPrivateKeyParameters _key = (ECPrivateKeyParameters)key;
AlgorithmIdentifier algID;
if (_key.AlgorithmName == "ECGOST3410")
{
if (_key.PublicKeyParamSet == null)
throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
_key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);
algID = new AlgorithmIdentifier(
CryptoProObjectIdentifiers.GostR3410x2001,
gostParams.ToAsn1Object());
}
else
{
X9ECParameters ecP = new X9ECParameters(
_key.Parameters.Curve,
_key.Parameters.G,
_key.Parameters.N,
_key.Parameters.H,
_key.Parameters.GetSeed());
X962Parameters x962 = new X962Parameters(ecP);
algID = new AlgorithmIdentifier(
X9ObjectIdentifiers.IdECPublicKey,
x962.ToAsn1Object());
}
return new PrivateKeyInfo(algID, new ECPrivateKeyStructure(_key.D).ToAsn1Object());
}
if (key is Gost3410PrivateKeyParameters)
{
Gost3410PrivateKeyParameters _key = (Gost3410PrivateKeyParameters)key;
if (_key.PublicKeyParamSet == null)
throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
byte[] keyEnc = _key.X.ToByteArrayUnsigned();
byte[] keyBytes = new byte[keyEnc.Length];
for (int i = 0; i != keyBytes.Length; i++)
{
keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // must be little endian
}
Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
_key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet, null);
AlgorithmIdentifier algID = new AlgorithmIdentifier(
CryptoProObjectIdentifiers.GostR3410x94,
algParams.ToAsn1Object());
return new PrivateKeyInfo(algID, new DerOctetString(keyBytes));
}
throw new ArgumentException("Class provided is not convertible: " + key.GetType().FullName);
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
char[] passPhrase,
EncryptedPrivateKeyInfo encInfo)
{
return CreatePrivateKeyInfo(passPhrase, false, encInfo);
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
char[] passPhrase,
bool wrongPkcs12Zero,
EncryptedPrivateKeyInfo encInfo)
{
AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm;
IBufferedCipher cipher = PbeUtilities.CreateEngine(algID.ObjectID) as IBufferedCipher;
if (cipher == null)
{
// TODO Throw exception?
}
ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters(
algID.ObjectID, passPhrase, wrongPkcs12Zero, algID.Parameters);
cipher.Init(false, keyParameters);
byte[] keyBytes = encInfo.GetEncryptedData();
byte[] encoding = cipher.DoFinal(keyBytes);
Asn1Object asn1Data = Asn1Object.FromByteArray(encoding);
return PrivateKeyInfo.GetInstance(asn1Data);
}
}
}
using System;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities;
namespace Org.BouncyCastle.Pkcs
{
public sealed class PrivateKeyInfoFactory
{
private PrivateKeyInfoFactory()
{
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
AsymmetricKeyParameter key)
{
if (key == null)
throw new ArgumentNullException("key");
if (!key.IsPrivate)
throw new ArgumentException("Public key passed - private key expected", "key");
if (key is ElGamalPrivateKeyParameters)
{
ElGamalPrivateKeyParameters _key = (ElGamalPrivateKeyParameters)key;
return new PrivateKeyInfo(
new AlgorithmIdentifier(
OiwObjectIdentifiers.ElGamalAlgorithm,
new ElGamalParameter(
_key.Parameters.P,
_key.Parameters.G).ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is DsaPrivateKeyParameters)
{
DsaPrivateKeyParameters _key = (DsaPrivateKeyParameters)key;
return new PrivateKeyInfo(
new AlgorithmIdentifier(
X9ObjectIdentifiers.IdDsa,
new DsaParameter(
_key.Parameters.P,
_key.Parameters.Q,
_key.Parameters.G).ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is DHPrivateKeyParameters)
{
/*
Process DH private key.
The value for L was set to zero implicitly.
This is the same action as found in JCEDHPrivateKey GetEncoded method.
*/
DHPrivateKeyParameters _key = (DHPrivateKeyParameters)key;
DHParameter withNewL = new DHParameter(
_key.Parameters.P, _key.Parameters.G, 0);
return new PrivateKeyInfo(
new AlgorithmIdentifier(
PkcsObjectIdentifiers.DhKeyAgreement,
withNewL.ToAsn1Object()),
new DerInteger(_key.X));
}
if (key is RsaKeyParameters)
{
AlgorithmIdentifier algID = new AlgorithmIdentifier(
PkcsObjectIdentifiers.RsaEncryption, DerNull.Instance);
RsaPrivateKeyStructure keyStruct;
if (key is RsaPrivateCrtKeyParameters)
{
RsaPrivateCrtKeyParameters _key = (RsaPrivateCrtKeyParameters)key;
keyStruct = new RsaPrivateKeyStructure(
_key.Modulus,
_key.PublicExponent,
_key.Exponent,
_key.P,
_key.Q,
_key.DP,
_key.DQ,
_key.QInv);
}
else
{
RsaKeyParameters _key = (RsaKeyParameters) key;
keyStruct = new RsaPrivateKeyStructure(
_key.Modulus,
BigInteger.Zero,
_key.Exponent,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero,
BigInteger.Zero);
}
return new PrivateKeyInfo(algID, keyStruct.ToAsn1Object());
}
if (key is ECPrivateKeyParameters)
{
ECPrivateKeyParameters _key = (ECPrivateKeyParameters)key;
AlgorithmIdentifier algID;
if (_key.AlgorithmName == "ECGOST3410")
{
if (_key.PublicKeyParamSet == null)
throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
Gost3410PublicKeyAlgParameters gostParams = new Gost3410PublicKeyAlgParameters(
_key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet);
algID = new AlgorithmIdentifier(
CryptoProObjectIdentifiers.GostR3410x2001,
gostParams.ToAsn1Object());
}
else
{
X9ECParameters ecP = new X9ECParameters(
_key.Parameters.Curve,
_key.Parameters.G,
_key.Parameters.N,
_key.Parameters.H,
_key.Parameters.GetSeed());
X962Parameters x962 = new X962Parameters(ecP);
algID = new AlgorithmIdentifier(
X9ObjectIdentifiers.IdECPublicKey,
x962.ToAsn1Object());
}
return new PrivateKeyInfo(algID, new ECPrivateKeyStructure(_key.D).ToAsn1Object());
}
if (key is Gost3410PrivateKeyParameters)
{
Gost3410PrivateKeyParameters _key = (Gost3410PrivateKeyParameters)key;
if (_key.PublicKeyParamSet == null)
throw Platform.CreateNotImplementedException("Not a CryptoPro parameter set");
byte[] keyEnc = _key.X.ToByteArrayUnsigned();
byte[] keyBytes = new byte[keyEnc.Length];
for (int i = 0; i != keyBytes.Length; i++)
{
keyBytes[i] = keyEnc[keyEnc.Length - 1 - i]; // must be little endian
}
Gost3410PublicKeyAlgParameters algParams = new Gost3410PublicKeyAlgParameters(
_key.PublicKeyParamSet, CryptoProObjectIdentifiers.GostR3411x94CryptoProParamSet, null);
AlgorithmIdentifier algID = new AlgorithmIdentifier(
CryptoProObjectIdentifiers.GostR3410x94,
algParams.ToAsn1Object());
return new PrivateKeyInfo(algID, new DerOctetString(keyBytes));
}
throw new ArgumentException("Class provided is not convertible: " + key.GetType().FullName);
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
char[] passPhrase,
EncryptedPrivateKeyInfo encInfo)
{
return CreatePrivateKeyInfo(passPhrase, false, encInfo);
}
public static PrivateKeyInfo CreatePrivateKeyInfo(
char[] passPhrase,
bool wrongPkcs12Zero,
EncryptedPrivateKeyInfo encInfo)
{
AlgorithmIdentifier algID = encInfo.EncryptionAlgorithm;
IBufferedCipher cipher = PbeUtilities.CreateEngine(algID) as IBufferedCipher;
if (cipher == null)
{
// TODO Throw exception?
}
ICipherParameters keyParameters = PbeUtilities.GenerateCipherParameters(
algID, passPhrase, wrongPkcs12Zero);
cipher.Init(false, keyParameters);
byte[] keyBytes = encInfo.GetEncryptedData();
byte[] encoding = cipher.DoFinal(keyBytes);
Asn1Object asn1Data = Asn1Object.FromByteArray(encoding);
return PrivateKeyInfo.GetInstance(asn1Data);
}
}
}

View File

@ -1,215 +1,214 @@
using System;
using System.Collections;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Pkix
{
public class PkixAttrCertPathBuilder
{
/**
* Build and validate a CertPath using the given parameter.
*
* @param params PKIXBuilderParameters object containing all information to
* build the CertPath
*/
public virtual PkixCertPathBuilderResult Build(
PkixBuilderParameters pkixParams)
{
// search target certificates
IX509Selector certSelect = pkixParams.GetTargetConstraints();
if (!(certSelect is X509AttrCertStoreSelector))
{
throw new PkixCertPathBuilderException(
"TargetConstraints must be an instance of "
+ typeof(X509AttrCertStoreSelector).FullName
+ " for "
+ typeof(PkixAttrCertPathBuilder).FullName + " class.");
}
ICollection targets;
try
{
targets = PkixCertPathValidatorUtilities.FindCertificates(
(X509AttrCertStoreSelector)certSelect, pkixParams.GetStores());
}
catch (Exception e)
{
throw new PkixCertPathBuilderException("Error finding target attribute certificate.", e);
}
if (targets.Count == 0)
{
throw new PkixCertPathBuilderException(
"No attribute certificate found matching targetContraints.");
}
PkixCertPathBuilderResult result = null;
// check all potential target certificates
foreach (IX509AttributeCertificate cert in targets)
{
X509CertStoreSelector selector = new X509CertStoreSelector();
X509Name[] principals = cert.Issuer.GetPrincipals();
ISet issuers = new HashSet();
for (int i = 0; i < principals.Length; i++)
{
try
{
selector.Subject = principals[i];
issuers.AddAll(PkixCertPathValidatorUtilities.FindCertificates(selector, pkixParams.GetStores()));
issuers.AddAll(PkixCertPathValidatorUtilities.FindCertificates(selector, pkixParams.GetX509Stores()));
}
catch (Exception e)
{
throw new PkixCertPathBuilderException(
"Public key certificate for attribute certificate cannot be searched.",
e);
}
}
if (issuers.IsEmpty)
throw new PkixCertPathBuilderException("Public key certificate for attribute certificate cannot be found.");
IList certPathList = new ArrayList();
foreach (X509Certificate issuer in issuers)
{
result = Build(cert, issuer, pkixParams, certPathList);
if (result != null)
break;
}
if (result != null)
break;
}
if (result == null && certPathException != null)
{
throw new PkixCertPathBuilderException(
"Possible certificate chain could not be validated.",
certPathException);
}
if (result == null && certPathException == null)
{
throw new PkixCertPathBuilderException(
"Unable to find certificate chain.");
}
return result;
}
private Exception certPathException;
private PkixCertPathBuilderResult Build(
IX509AttributeCertificate attrCert,
X509Certificate tbvCert,
PkixBuilderParameters pkixParams,
IList tbvPath)
{
// If tbvCert is readily present in tbvPath, it indicates having run
// into a cycle in the
// PKI graph.
if (tbvPath.Contains(tbvCert))
return null;
// step out, the certificate is not allowed to appear in a certification
// chain
if (pkixParams.GetExcludedCerts().Contains(tbvCert))
return null;
// test if certificate path exceeds maximum length
if (pkixParams.MaxPathLength != -1)
{
if (tbvPath.Count - 1 > pkixParams.MaxPathLength)
return null;
}
tbvPath.Add(tbvCert);
PkixCertPathBuilderResult builderResult = null;
X509CertificateParser certParser = new X509CertificateParser();
PkixAttrCertPathValidator validator = new PkixAttrCertPathValidator();
try
{
// check whether the issuer of <tbvCert> is a TrustAnchor
if (PkixCertPathValidatorUtilities.FindTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()) != null)
{
PkixCertPath certPath = new PkixCertPath(tbvPath);
PkixCertPathValidatorResult result;
try
{
result = validator.Validate(certPath, pkixParams);
}
catch (Exception e)
{
throw new Exception("Certification path could not be validated.", e);
}
return new PkixCertPathBuilderResult(certPath, result.TrustAnchor,
result.PolicyTree, result.SubjectPublicKey);
}
else
{
// add additional X.509 stores from locations in certificate
try
{
PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(tbvCert, pkixParams);
}
catch (CertificateParsingException e)
{
throw new Exception("No additional X.509 stores can be added from certificate locations.", e);
}
// try to get the issuer certificate from one of the stores
ISet issuers = new HashSet();
try
{
issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams));
}
catch (Exception e)
{
throw new Exception("Cannot find issuer certificate for certificate in certification path.", e);
}
if (issuers.IsEmpty)
throw new Exception("No issuer certificate for certificate in certification path found.");
foreach (X509Certificate issuer in issuers)
{
// if untrusted self signed certificate continue
if (PkixCertPathValidatorUtilities.IsSelfIssued(issuer))
continue;
builderResult = Build(attrCert, issuer, pkixParams, tbvPath);
if (builderResult != null)
break;
}
}
}
catch (Exception e)
{
certPathException = new Exception("No valid certification path could be build.", e);
}
if (builderResult == null)
{
tbvPath.Remove(tbvCert);
}
return builderResult;
}
}
}
using System;
using System.Collections;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Pkix
{
public class PkixAttrCertPathBuilder
{
/**
* Build and validate a CertPath using the given parameter.
*
* @param params PKIXBuilderParameters object containing all information to
* build the CertPath
*/
public virtual PkixCertPathBuilderResult Build(
PkixBuilderParameters pkixParams)
{
// search target certificates
IX509Selector certSelect = pkixParams.GetTargetConstraints();
if (!(certSelect is X509AttrCertStoreSelector))
{
throw new PkixCertPathBuilderException(
"TargetConstraints must be an instance of "
+ typeof(X509AttrCertStoreSelector).FullName
+ " for "
+ typeof(PkixAttrCertPathBuilder).FullName + " class.");
}
ICollection targets;
try
{
targets = PkixCertPathValidatorUtilities.FindCertificates(
(X509AttrCertStoreSelector)certSelect, pkixParams.GetStores());
}
catch (Exception e)
{
throw new PkixCertPathBuilderException("Error finding target attribute certificate.", e);
}
if (targets.Count == 0)
{
throw new PkixCertPathBuilderException(
"No attribute certificate found matching targetContraints.");
}
PkixCertPathBuilderResult result = null;
// check all potential target certificates
foreach (IX509AttributeCertificate cert in targets)
{
X509CertStoreSelector selector = new X509CertStoreSelector();
X509Name[] principals = cert.Issuer.GetPrincipals();
ISet issuers = new HashSet();
for (int i = 0; i < principals.Length; i++)
{
try
{
selector.Subject = principals[i];
issuers.AddAll(PkixCertPathValidatorUtilities.FindCertificates(selector, pkixParams.GetStores()));
}
catch (Exception e)
{
throw new PkixCertPathBuilderException(
"Public key certificate for attribute certificate cannot be searched.",
e);
}
}
if (issuers.IsEmpty)
throw new PkixCertPathBuilderException("Public key certificate for attribute certificate cannot be found.");
IList certPathList = new ArrayList();
foreach (X509Certificate issuer in issuers)
{
result = Build(cert, issuer, pkixParams, certPathList);
if (result != null)
break;
}
if (result != null)
break;
}
if (result == null && certPathException != null)
{
throw new PkixCertPathBuilderException(
"Possible certificate chain could not be validated.",
certPathException);
}
if (result == null && certPathException == null)
{
throw new PkixCertPathBuilderException(
"Unable to find certificate chain.");
}
return result;
}
private Exception certPathException;
private PkixCertPathBuilderResult Build(
IX509AttributeCertificate attrCert,
X509Certificate tbvCert,
PkixBuilderParameters pkixParams,
IList tbvPath)
{
// If tbvCert is readily present in tbvPath, it indicates having run
// into a cycle in the
// PKI graph.
if (tbvPath.Contains(tbvCert))
return null;
// step out, the certificate is not allowed to appear in a certification
// chain
if (pkixParams.GetExcludedCerts().Contains(tbvCert))
return null;
// test if certificate path exceeds maximum length
if (pkixParams.MaxPathLength != -1)
{
if (tbvPath.Count - 1 > pkixParams.MaxPathLength)
return null;
}
tbvPath.Add(tbvCert);
PkixCertPathBuilderResult builderResult = null;
X509CertificateParser certParser = new X509CertificateParser();
PkixAttrCertPathValidator validator = new PkixAttrCertPathValidator();
try
{
// check whether the issuer of <tbvCert> is a TrustAnchor
if (PkixCertPathValidatorUtilities.FindTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()) != null)
{
PkixCertPath certPath = new PkixCertPath(tbvPath);
PkixCertPathValidatorResult result;
try
{
result = validator.Validate(certPath, pkixParams);
}
catch (Exception e)
{
throw new Exception("Certification path could not be validated.", e);
}
return new PkixCertPathBuilderResult(certPath, result.TrustAnchor,
result.PolicyTree, result.SubjectPublicKey);
}
else
{
// add additional X.509 stores from locations in certificate
try
{
PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(tbvCert, pkixParams);
}
catch (CertificateParsingException e)
{
throw new Exception("No additional X.509 stores can be added from certificate locations.", e);
}
// try to get the issuer certificate from one of the stores
ISet issuers = new HashSet();
try
{
issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams));
}
catch (Exception e)
{
throw new Exception("Cannot find issuer certificate for certificate in certification path.", e);
}
if (issuers.IsEmpty)
throw new Exception("No issuer certificate for certificate in certification path found.");
foreach (X509Certificate issuer in issuers)
{
// if untrusted self signed certificate continue
if (PkixCertPathValidatorUtilities.IsSelfIssued(issuer))
continue;
builderResult = Build(attrCert, issuer, pkixParams, tbvPath);
if (builderResult != null)
break;
}
}
}
catch (Exception e)
{
certPathException = new Exception("No valid certification path could be build.", e);
}
if (builderResult == null)
{
tbvPath.Remove(tbvCert);
}
return builderResult;
}
}
}

View File

@ -1,205 +1,204 @@
using System;
using System.Collections;
using System.Text;
using Org.BouncyCastle.Asn1.IsisMtt;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X500;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Pkix
{
/**
* Implements the PKIX CertPathBuilding algorithm for BouncyCastle.
*
* @see CertPathBuilderSpi
*/
public class PkixCertPathBuilder
// : CertPathBuilderSpi
{
/**
* Build and validate a CertPath using the given parameter.
*
* @param params PKIXBuilderParameters object containing all information to
* build the CertPath
*/
public virtual PkixCertPathBuilderResult Build(
PkixBuilderParameters pkixParams)
{
// search target certificates
IX509Selector certSelect = pkixParams.GetTargetCertConstraints();
if (!(certSelect is X509CertStoreSelector))
{
throw new PkixCertPathBuilderException(
"TargetConstraints must be an instance of "
+ typeof(X509CertStoreSelector).FullName + " for "
+ this.GetType() + " class.");
}
ISet targets = new HashSet();
try
{
targets.AddAll(PkixCertPathValidatorUtilities.FindCertificates((X509CertStoreSelector)certSelect, pkixParams.GetStores()));
targets.AddAll(PkixCertPathValidatorUtilities.FindCertificates((X509CertStoreSelector)certSelect, pkixParams.GetX509Stores()));
// TODO Should this include an entry for pkixParams.GetAdditionalStores() too?
}
catch (Exception e)
{
throw new PkixCertPathBuilderException(
"Error finding target certificate.", e);
}
if (targets.IsEmpty)
throw new PkixCertPathBuilderException("No certificate found matching targetContraints.");
PkixCertPathBuilderResult result = null;
IList certPathList = new ArrayList();
// check all potential target certificates
foreach (X509Certificate cert in targets)
{
result = Build(cert, pkixParams, certPathList);
if (result != null)
break;
}
if (result == null && certPathException != null)
{
throw new PkixCertPathBuilderException(certPathException.Message, certPathException.InnerException);
}
if (result == null && certPathException == null)
{
throw new PkixCertPathBuilderException("Unable to find certificate chain.");
}
return result;
}
private Exception certPathException;
protected virtual PkixCertPathBuilderResult Build(
X509Certificate tbvCert,
PkixBuilderParameters pkixParams,
IList tbvPath)
{
// If tbvCert is readily present in tbvPath, it indicates having run
// into a cycle in the PKI graph.
if (tbvPath.Contains(tbvCert))
return null;
// step out, the certificate is not allowed to appear in a certification
// chain.
if (pkixParams.GetExcludedCerts().Contains(tbvCert))
return null;
// test if certificate path exceeds maximum length
if (pkixParams.MaxPathLength != -1)
{
if (tbvPath.Count - 1 > pkixParams.MaxPathLength)
return null;
}
tbvPath.Add(tbvCert);
X509CertificateParser certParser = new X509CertificateParser();
PkixCertPathBuilderResult builderResult = null;
PkixCertPathValidator validator = new PkixCertPathValidator();
try
{
// check whether the issuer of <tbvCert> is a TrustAnchor
if (PkixCertPathValidatorUtilities.FindTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()) != null)
{
// exception message from possibly later tried certification
// chains
PkixCertPath certPath = null;
try
{
certPath = new PkixCertPath(tbvPath);
}
catch (Exception e)
{
throw new Exception(
"Certification path could not be constructed from certificate list.",
e);
}
PkixCertPathValidatorResult result = null;
try
{
result = (PkixCertPathValidatorResult)validator.Validate(
certPath, pkixParams);
}
catch (Exception e)
{
throw new Exception(
"Certification path could not be validated.", e);
}
return new PkixCertPathBuilderResult(certPath, result.TrustAnchor,
result.PolicyTree, result.SubjectPublicKey);
}
else
{
// add additional X.509 stores from locations in certificate
try
{
PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(
tbvCert, pkixParams);
}
catch (CertificateParsingException e)
{
throw new Exception(
"No additiontal X.509 stores can be added from certificate locations.",
e);
}
// try to get the issuer certificate from one of the stores
HashSet issuers = new HashSet();
try
{
issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams));
}
catch (Exception e)
{
throw new Exception(
"Cannot find issuer certificate for certificate in certification path.",
e);
}
if (issuers.IsEmpty)
throw new Exception("No issuer certificate for certificate in certification path found.");
foreach (X509Certificate issuer in issuers)
{
builderResult = Build(issuer, pkixParams, tbvPath);
if (builderResult != null)
break;
}
}
}
catch (Exception e)
{
certPathException = e;
}
if (builderResult == null)
{
tbvPath.Remove(tbvCert);
}
return builderResult;
}
}
}
using System;
using System.Collections;
using System.Text;
using Org.BouncyCastle.Asn1.IsisMtt;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Asn1.X500;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities.Collections;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Pkix
{
/**
* Implements the PKIX CertPathBuilding algorithm for BouncyCastle.
*
* @see CertPathBuilderSpi
*/
public class PkixCertPathBuilder
// : CertPathBuilderSpi
{
/**
* Build and validate a CertPath using the given parameter.
*
* @param params PKIXBuilderParameters object containing all information to
* build the CertPath
*/
public virtual PkixCertPathBuilderResult Build(
PkixBuilderParameters pkixParams)
{
// search target certificates
IX509Selector certSelect = pkixParams.GetTargetCertConstraints();
if (!(certSelect is X509CertStoreSelector))
{
throw new PkixCertPathBuilderException(
"TargetConstraints must be an instance of "
+ typeof(X509CertStoreSelector).FullName + " for "
+ this.GetType() + " class.");
}
ISet targets = new HashSet();
try
{
targets.AddAll(PkixCertPathValidatorUtilities.FindCertificates((X509CertStoreSelector)certSelect, pkixParams.GetStores()));
// TODO Should this include an entry for pkixParams.GetAdditionalStores() too?
}
catch (Exception e)
{
throw new PkixCertPathBuilderException(
"Error finding target certificate.", e);
}
if (targets.IsEmpty)
throw new PkixCertPathBuilderException("No certificate found matching targetContraints.");
PkixCertPathBuilderResult result = null;
IList certPathList = new ArrayList();
// check all potential target certificates
foreach (X509Certificate cert in targets)
{
result = Build(cert, pkixParams, certPathList);
if (result != null)
break;
}
if (result == null && certPathException != null)
{
throw new PkixCertPathBuilderException(certPathException.Message, certPathException.InnerException);
}
if (result == null && certPathException == null)
{
throw new PkixCertPathBuilderException("Unable to find certificate chain.");
}
return result;
}
private Exception certPathException;
protected virtual PkixCertPathBuilderResult Build(
X509Certificate tbvCert,
PkixBuilderParameters pkixParams,
IList tbvPath)
{
// If tbvCert is readily present in tbvPath, it indicates having run
// into a cycle in the PKI graph.
if (tbvPath.Contains(tbvCert))
return null;
// step out, the certificate is not allowed to appear in a certification
// chain.
if (pkixParams.GetExcludedCerts().Contains(tbvCert))
return null;
// test if certificate path exceeds maximum length
if (pkixParams.MaxPathLength != -1)
{
if (tbvPath.Count - 1 > pkixParams.MaxPathLength)
return null;
}
tbvPath.Add(tbvCert);
X509CertificateParser certParser = new X509CertificateParser();
PkixCertPathBuilderResult builderResult = null;
PkixCertPathValidator validator = new PkixCertPathValidator();
try
{
// check whether the issuer of <tbvCert> is a TrustAnchor
if (PkixCertPathValidatorUtilities.FindTrustAnchor(tbvCert, pkixParams.GetTrustAnchors()) != null)
{
// exception message from possibly later tried certification
// chains
PkixCertPath certPath = null;
try
{
certPath = new PkixCertPath(tbvPath);
}
catch (Exception e)
{
throw new Exception(
"Certification path could not be constructed from certificate list.",
e);
}
PkixCertPathValidatorResult result = null;
try
{
result = (PkixCertPathValidatorResult)validator.Validate(
certPath, pkixParams);
}
catch (Exception e)
{
throw new Exception(
"Certification path could not be validated.", e);
}
return new PkixCertPathBuilderResult(certPath, result.TrustAnchor,
result.PolicyTree, result.SubjectPublicKey);
}
else
{
// add additional X.509 stores from locations in certificate
try
{
PkixCertPathValidatorUtilities.AddAdditionalStoresFromAltNames(
tbvCert, pkixParams);
}
catch (CertificateParsingException e)
{
throw new Exception(
"No additiontal X.509 stores can be added from certificate locations.",
e);
}
// try to get the issuer certificate from one of the stores
HashSet issuers = new HashSet();
try
{
issuers.AddAll(PkixCertPathValidatorUtilities.FindIssuerCerts(tbvCert, pkixParams));
}
catch (Exception e)
{
throw new Exception(
"Cannot find issuer certificate for certificate in certification path.",
e);
}
if (issuers.IsEmpty)
throw new Exception("No issuer certificate for certificate in certification path found.");
foreach (X509Certificate issuer in issuers)
{
builderResult = Build(issuer, pkixParams, tbvPath);
if (builderResult != null)
break;
}
}
}
catch (Exception e)
{
certPathException = e;
}
if (builderResult == null)
{
tbvPath.Remove(tbvCert);
}
return builderResult;
}
}
}

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

File diff suppressed because it is too large Load Diff

View File

@ -67,9 +67,13 @@ namespace Org.BouncyCastle.Security
"1.2.840.113533.7.66.10");
AddKgAlgorithm("CAST6");
AddKgAlgorithm("DES",
OiwObjectIdentifiers.DesCbc);
OiwObjectIdentifiers.DesCbc,
OiwObjectIdentifiers.DesCfb,
OiwObjectIdentifiers.DesEcb,
OiwObjectIdentifiers.DesOfb);
AddKgAlgorithm("DESEDE",
"DESEDEWRAP",
OiwObjectIdentifiers.DesEde,
PkcsObjectIdentifiers.IdAlgCms3DesWrap);
AddKgAlgorithm("DESEDE3",
PkcsObjectIdentifiers.DesEde3Cbc);

View File

@ -1,318 +1,322 @@
using System;
using System.Collections;
using System.Globalization;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Kisa;
using Org.BouncyCastle.Asn1.Misc;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Ntt;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Security
{
public sealed class ParameterUtilities
{
private ParameterUtilities()
{
}
private static readonly Hashtable algorithms = new Hashtable();
static ParameterUtilities()
{
AddAlgorithm("AES",
"AESWRAP");
AddAlgorithm("AES128",
"2.16.840.1.101.3.4.2",
NistObjectIdentifiers.IdAes128Cbc,
NistObjectIdentifiers.IdAes128Cfb,
NistObjectIdentifiers.IdAes128Ecb,
NistObjectIdentifiers.IdAes128Ofb,
NistObjectIdentifiers.IdAes128Wrap);
AddAlgorithm("AES192",
"2.16.840.1.101.3.4.22",
NistObjectIdentifiers.IdAes192Cbc,
NistObjectIdentifiers.IdAes192Cfb,
NistObjectIdentifiers.IdAes192Ecb,
NistObjectIdentifiers.IdAes192Ofb,
NistObjectIdentifiers.IdAes192Wrap);
AddAlgorithm("AES256",
"2.16.840.1.101.3.4.42",
NistObjectIdentifiers.IdAes256Cbc,
NistObjectIdentifiers.IdAes256Cfb,
NistObjectIdentifiers.IdAes256Ecb,
NistObjectIdentifiers.IdAes256Ofb,
NistObjectIdentifiers.IdAes256Wrap);
AddAlgorithm("BLOWFISH");
AddAlgorithm("CAMELLIA",
"CAMELLIAWRAP");
AddAlgorithm("CAMELLIA128",
NttObjectIdentifiers.IdCamellia128Cbc,
NttObjectIdentifiers.IdCamellia128Wrap);
AddAlgorithm("CAMELLIA192",
NttObjectIdentifiers.IdCamellia192Cbc,
NttObjectIdentifiers.IdCamellia192Wrap);
AddAlgorithm("CAMELLIA256",
NttObjectIdentifiers.IdCamellia256Cbc,
NttObjectIdentifiers.IdCamellia256Wrap);
AddAlgorithm("CAST5",
"1.2.840.113533.7.66.10");
AddAlgorithm("CAST6");
AddAlgorithm("DES",
OiwObjectIdentifiers.DesCbc);
AddAlgorithm("DESEDE",
"DESEDEWRAP",
PkcsObjectIdentifiers.IdAlgCms3DesWrap);
AddAlgorithm("DESEDE3",
PkcsObjectIdentifiers.DesEde3Cbc);
AddAlgorithm("GOST28147",
"GOST",
"GOST-28147",
CryptoProObjectIdentifiers.GostR28147Cbc);
AddAlgorithm("HC128");
AddAlgorithm("HC256");
AddAlgorithm("IDEA",
"1.3.6.1.4.1.188.7.1.1.2");
AddAlgorithm("NOEKEON");
AddAlgorithm("RC2",
PkcsObjectIdentifiers.RC2Cbc,
PkcsObjectIdentifiers.IdAlgCmsRC2Wrap);
AddAlgorithm("RC4",
"ARC4",
"1.2.840.113549.3.4");
AddAlgorithm("RC5",
"RC5-32");
AddAlgorithm("RC5-64");
AddAlgorithm("RC6");
AddAlgorithm("RIJNDAEL");
AddAlgorithm("SALSA20");
AddAlgorithm("SEED",
KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap,
KisaObjectIdentifiers.IdSeedCbc);
AddAlgorithm("SERPENT");
AddAlgorithm("SKIPJACK");
AddAlgorithm("TEA");
AddAlgorithm("TWOFISH");
AddAlgorithm("VMPC");
AddAlgorithm("VMPC-KSA3");
AddAlgorithm("XTEA");
}
private static void AddAlgorithm(
string canonicalName,
params object[] aliases)
{
algorithms[canonicalName] = canonicalName;
foreach (object alias in aliases)
{
algorithms[alias.ToString()] = canonicalName;
}
}
public static string GetCanonicalAlgorithmName(
string algorithm)
{
return (string) algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];
}
public static KeyParameter CreateKeyParameter(
DerObjectIdentifier algOid,
byte[] keyBytes)
{
return CreateKeyParameter(algOid.Id, keyBytes, 0, keyBytes.Length);
}
public static KeyParameter CreateKeyParameter(
string algorithm,
byte[] keyBytes)
{
return CreateKeyParameter(algorithm, keyBytes, 0, keyBytes.Length);
}
public static KeyParameter CreateKeyParameter(
DerObjectIdentifier algOid,
byte[] keyBytes,
int offset,
int length)
{
return CreateKeyParameter(algOid.Id, keyBytes, offset, length);
}
public static KeyParameter CreateKeyParameter(
string algorithm,
byte[] keyBytes,
int offset,
int length)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
switch (canonical)
{
case "DES":
return new DesParameters(keyBytes, offset, length);
case "DESEDE":
case "DESEDE3":
return new DesEdeParameters(keyBytes, offset, length);
case "RC2":
return new RC2Parameters(keyBytes, offset, length);
default:
return new KeyParameter(keyBytes, offset, length);
}
}
public static ICipherParameters GetCipherParameters(
DerObjectIdentifier algOid,
ICipherParameters key,
Asn1Object asn1Params)
{
return GetCipherParameters(algOid.Id, key, asn1Params);
}
public static ICipherParameters GetCipherParameters(
string algorithm,
ICipherParameters key,
Asn1Object asn1Params)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
byte[] iv = null;
try
{
switch (canonical)
{
case "AES":
case "AES128":
case "AES192":
case "AES256":
case "BLOWFISH":
case "CAMELLIA":
case "CAMELLIA128":
case "CAMELLIA192":
case "CAMELLIA256":
case "DES":
case "DESEDE":
case "DESEDE3":
case "NOEKEON":
case "RIJNDAEL":
case "SEED":
case "SKIPJACK":
case "TWOFISH":
iv = ((Asn1OctetString) asn1Params).GetOctets();
break;
case "RC2":
iv = RC2CbcParameter.GetInstance(asn1Params).GetIV();
break;
case "IDEA":
iv = IdeaCbcPar.GetInstance(asn1Params).GetIV();
break;
case "CAST5":
iv = Cast5CbcParameters.GetInstance(asn1Params).GetIV();
break;
}
}
catch (Exception e)
{
throw new ArgumentException("Could not process ASN.1 parameters", e);
}
if (iv != null)
{
return new ParametersWithIV(key, iv);
}
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
}
public static Asn1Encodable GenerateParameters(
DerObjectIdentifier algID,
SecureRandom random)
{
return GenerateParameters(algID.Id, random);
}
public static Asn1Encodable GenerateParameters(
string algorithm,
SecureRandom random)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
switch (canonical)
{
// TODO These algorithms support an IV (see GetCipherParameters)
// but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
// case "BLOWFISH":
// case "RIJNDAEL":
// case "SKIPJACK":
// case "TWOFISH":
case "AES":
case "AES128":
case "AES192":
case "AES256":
return CreateIVOctetString(random, 16);
case "CAMELLIA":
case "CAMELLIA128":
case "CAMELLIA192":
case "CAMELLIA256":
return CreateIVOctetString(random, 16);
case "CAST5":
return new Cast5CbcParameters(CreateIV(random, 8), 128);
case "DES":
case "DESEDE":
case "DESEDE3":
return CreateIVOctetString(random, 8);
case "IDEA":
return new IdeaCbcPar(CreateIV(random, 8));
case "NOEKEON":
return CreateIVOctetString(random, 16);
case "RC2":
return new RC2CbcParameter(CreateIV(random, 8));
case "SEED":
return CreateIVOctetString(random, 16);
}
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
}
private static Asn1OctetString CreateIVOctetString(
SecureRandom random,
int ivLength)
{
return new DerOctetString(CreateIV(random, ivLength));
}
private static byte[] CreateIV(
SecureRandom random,
int ivLength)
{
byte[] iv = new byte[ivLength];
random.NextBytes(iv);
return iv;
}
}
}
using System;
using System.Collections;
using System.Globalization;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.CryptoPro;
using Org.BouncyCastle.Asn1.Kisa;
using Org.BouncyCastle.Asn1.Misc;
using Org.BouncyCastle.Asn1.Nist;
using Org.BouncyCastle.Asn1.Ntt;
using Org.BouncyCastle.Asn1.Oiw;
using Org.BouncyCastle.Asn1.Pkcs;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
namespace Org.BouncyCastle.Security
{
public sealed class ParameterUtilities
{
private ParameterUtilities()
{
}
private static readonly Hashtable algorithms = new Hashtable();
static ParameterUtilities()
{
AddAlgorithm("AES",
"AESWRAP");
AddAlgorithm("AES128",
"2.16.840.1.101.3.4.2",
NistObjectIdentifiers.IdAes128Cbc,
NistObjectIdentifiers.IdAes128Cfb,
NistObjectIdentifiers.IdAes128Ecb,
NistObjectIdentifiers.IdAes128Ofb,
NistObjectIdentifiers.IdAes128Wrap);
AddAlgorithm("AES192",
"2.16.840.1.101.3.4.22",
NistObjectIdentifiers.IdAes192Cbc,
NistObjectIdentifiers.IdAes192Cfb,
NistObjectIdentifiers.IdAes192Ecb,
NistObjectIdentifiers.IdAes192Ofb,
NistObjectIdentifiers.IdAes192Wrap);
AddAlgorithm("AES256",
"2.16.840.1.101.3.4.42",
NistObjectIdentifiers.IdAes256Cbc,
NistObjectIdentifiers.IdAes256Cfb,
NistObjectIdentifiers.IdAes256Ecb,
NistObjectIdentifiers.IdAes256Ofb,
NistObjectIdentifiers.IdAes256Wrap);
AddAlgorithm("BLOWFISH");
AddAlgorithm("CAMELLIA",
"CAMELLIAWRAP");
AddAlgorithm("CAMELLIA128",
NttObjectIdentifiers.IdCamellia128Cbc,
NttObjectIdentifiers.IdCamellia128Wrap);
AddAlgorithm("CAMELLIA192",
NttObjectIdentifiers.IdCamellia192Cbc,
NttObjectIdentifiers.IdCamellia192Wrap);
AddAlgorithm("CAMELLIA256",
NttObjectIdentifiers.IdCamellia256Cbc,
NttObjectIdentifiers.IdCamellia256Wrap);
AddAlgorithm("CAST5",
"1.2.840.113533.7.66.10");
AddAlgorithm("CAST6");
AddAlgorithm("DES",
OiwObjectIdentifiers.DesCbc,
OiwObjectIdentifiers.DesCfb,
OiwObjectIdentifiers.DesEcb,
OiwObjectIdentifiers.DesOfb);
AddAlgorithm("DESEDE",
"DESEDEWRAP",
OiwObjectIdentifiers.DesEde,
PkcsObjectIdentifiers.IdAlgCms3DesWrap);
AddAlgorithm("DESEDE3",
PkcsObjectIdentifiers.DesEde3Cbc);
AddAlgorithm("GOST28147",
"GOST",
"GOST-28147",
CryptoProObjectIdentifiers.GostR28147Cbc);
AddAlgorithm("HC128");
AddAlgorithm("HC256");
AddAlgorithm("IDEA",
"1.3.6.1.4.1.188.7.1.1.2");
AddAlgorithm("NOEKEON");
AddAlgorithm("RC2",
PkcsObjectIdentifiers.RC2Cbc,
PkcsObjectIdentifiers.IdAlgCmsRC2Wrap);
AddAlgorithm("RC4",
"ARC4",
"1.2.840.113549.3.4");
AddAlgorithm("RC5",
"RC5-32");
AddAlgorithm("RC5-64");
AddAlgorithm("RC6");
AddAlgorithm("RIJNDAEL");
AddAlgorithm("SALSA20");
AddAlgorithm("SEED",
KisaObjectIdentifiers.IdNpkiAppCmsSeedWrap,
KisaObjectIdentifiers.IdSeedCbc);
AddAlgorithm("SERPENT");
AddAlgorithm("SKIPJACK");
AddAlgorithm("TEA");
AddAlgorithm("TWOFISH");
AddAlgorithm("VMPC");
AddAlgorithm("VMPC-KSA3");
AddAlgorithm("XTEA");
}
private static void AddAlgorithm(
string canonicalName,
params object[] aliases)
{
algorithms[canonicalName] = canonicalName;
foreach (object alias in aliases)
{
algorithms[alias.ToString()] = canonicalName;
}
}
public static string GetCanonicalAlgorithmName(
string algorithm)
{
return (string) algorithms[algorithm.ToUpper(CultureInfo.InvariantCulture)];
}
public static KeyParameter CreateKeyParameter(
DerObjectIdentifier algOid,
byte[] keyBytes)
{
return CreateKeyParameter(algOid.Id, keyBytes, 0, keyBytes.Length);
}
public static KeyParameter CreateKeyParameter(
string algorithm,
byte[] keyBytes)
{
return CreateKeyParameter(algorithm, keyBytes, 0, keyBytes.Length);
}
public static KeyParameter CreateKeyParameter(
DerObjectIdentifier algOid,
byte[] keyBytes,
int offset,
int length)
{
return CreateKeyParameter(algOid.Id, keyBytes, offset, length);
}
public static KeyParameter CreateKeyParameter(
string algorithm,
byte[] keyBytes,
int offset,
int length)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
switch (canonical)
{
case "DES":
return new DesParameters(keyBytes, offset, length);
case "DESEDE":
case "DESEDE3":
return new DesEdeParameters(keyBytes, offset, length);
case "RC2":
return new RC2Parameters(keyBytes, offset, length);
default:
return new KeyParameter(keyBytes, offset, length);
}
}
public static ICipherParameters GetCipherParameters(
DerObjectIdentifier algOid,
ICipherParameters key,
Asn1Object asn1Params)
{
return GetCipherParameters(algOid.Id, key, asn1Params);
}
public static ICipherParameters GetCipherParameters(
string algorithm,
ICipherParameters key,
Asn1Object asn1Params)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
byte[] iv = null;
try
{
switch (canonical)
{
case "AES":
case "AES128":
case "AES192":
case "AES256":
case "BLOWFISH":
case "CAMELLIA":
case "CAMELLIA128":
case "CAMELLIA192":
case "CAMELLIA256":
case "DES":
case "DESEDE":
case "DESEDE3":
case "NOEKEON":
case "RIJNDAEL":
case "SEED":
case "SKIPJACK":
case "TWOFISH":
iv = ((Asn1OctetString) asn1Params).GetOctets();
break;
case "RC2":
iv = RC2CbcParameter.GetInstance(asn1Params).GetIV();
break;
case "IDEA":
iv = IdeaCbcPar.GetInstance(asn1Params).GetIV();
break;
case "CAST5":
iv = Cast5CbcParameters.GetInstance(asn1Params).GetIV();
break;
}
}
catch (Exception e)
{
throw new ArgumentException("Could not process ASN.1 parameters", e);
}
if (iv != null)
{
return new ParametersWithIV(key, iv);
}
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
}
public static Asn1Encodable GenerateParameters(
DerObjectIdentifier algID,
SecureRandom random)
{
return GenerateParameters(algID.Id, random);
}
public static Asn1Encodable GenerateParameters(
string algorithm,
SecureRandom random)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
string canonical = GetCanonicalAlgorithmName(algorithm);
if (canonical == null)
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
switch (canonical)
{
// TODO These algorithms support an IV (see GetCipherParameters)
// but JCE doesn't seem to provide an AlgorithmParametersGenerator for them
// case "BLOWFISH":
// case "RIJNDAEL":
// case "SKIPJACK":
// case "TWOFISH":
case "AES":
case "AES128":
case "AES192":
case "AES256":
return CreateIVOctetString(random, 16);
case "CAMELLIA":
case "CAMELLIA128":
case "CAMELLIA192":
case "CAMELLIA256":
return CreateIVOctetString(random, 16);
case "CAST5":
return new Cast5CbcParameters(CreateIV(random, 8), 128);
case "DES":
case "DESEDE":
case "DESEDE3":
return CreateIVOctetString(random, 8);
case "IDEA":
return new IdeaCbcPar(CreateIV(random, 8));
case "NOEKEON":
return CreateIVOctetString(random, 16);
case "RC2":
return new RC2CbcParameter(CreateIV(random, 8));
case "SEED":
return CreateIVOctetString(random, 16);
}
throw new SecurityUtilityException("Algorithm " + algorithm + " not recognised.");
}
private static Asn1OctetString CreateIVOctetString(
SecureRandom random,
int ivLength)
{
return new DerOctetString(CreateIV(random, ivLength));
}
private static byte[] CreateIV(
SecureRandom random,
int ivLength)
{
byte[] iv = new byte[ivLength];
random.NextBytes(iv);
return iv;
}
}
}

File diff suppressed because it is too large Load Diff