ECKeyPairGenerator
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Sec;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Math.EC;
using Org.BouncyCastle.Math.EC.Multiplier;
using Org.BouncyCastle.Security;
using System;
namespace Org.BouncyCastle.Crypto.Generators
{
public class ECKeyPairGenerator : IAsymmetricCipherKeyPairGenerator
{
private readonly string m_algorithm;
private ECDomainParameters m_parameters;
private SecureRandom m_random;
public ECKeyPairGenerator()
: this("EC")
{
}
public ECKeyPairGenerator(string algorithm)
{
if (algorithm == null)
throw new ArgumentNullException("algorithm");
m_algorithm = ECKeyParameters.VerifyAlgorithmName(algorithm);
}
public void Init(KeyGenerationParameters parameters)
{
ECKeyGenerationParameters eCKeyGenerationParameters = parameters as ECKeyGenerationParameters;
if (eCKeyGenerationParameters != null)
m_parameters = eCKeyGenerationParameters.DomainParameters;
else {
DerObjectIdentifier oid;
switch (parameters.Strength) {
case 192:
oid = X9ObjectIdentifiers.Prime192v1;
break;
case 224:
oid = SecObjectIdentifiers.SecP224r1;
break;
case 239:
oid = X9ObjectIdentifiers.Prime239v1;
break;
case 256:
oid = X9ObjectIdentifiers.Prime256v1;
break;
case 384:
oid = SecObjectIdentifiers.SecP384r1;
break;
case 521:
oid = SecObjectIdentifiers.SecP521r1;
break;
default:
throw new InvalidParameterException("unknown key size.");
}
m_parameters = ECNamedDomainParameters.LookupOid(oid);
}
m_random = CryptoServicesRegistrar.GetSecureRandom(parameters.Random);
}
public AsymmetricCipherKeyPair GenerateKeyPair()
{
BigInteger d = GeneratePrivateScalar(m_parameters.N, m_random);
ECPrivateKeyParameters eCPrivateKeyParameters = new ECPrivateKeyParameters(m_algorithm, d, m_parameters);
return new AsymmetricCipherKeyPair(GetCorrespondingPublicKey(eCPrivateKeyParameters, CreateBasePointMultiplier()), eCPrivateKeyParameters);
}
protected virtual ECMultiplier CreateBasePointMultiplier()
{
return new FixedPointCombMultiplier();
}
private static BigInteger GeneratePrivateScalar(BigInteger n, SecureRandom random)
{
int num = n.BitLength >> 2;
BigInteger bigInteger;
do {
bigInteger = new BigInteger(n.BitLength, random);
} while (bigInteger.CompareTo(BigInteger.One) < 0 || bigInteger.CompareTo(n) >= 0 || WNafUtilities.GetNafWeight(bigInteger) < num);
return bigInteger;
}
internal static ECPublicKeyParameters GetCorrespondingPublicKey(ECPrivateKeyParameters privateKey)
{
return GetCorrespondingPublicKey(privateKey, new FixedPointCombMultiplier());
}
private static ECPublicKeyParameters GetCorrespondingPublicKey(ECPrivateKeyParameters privateKey, ECMultiplier multiplier)
{
ECDomainParameters parameters = privateKey.Parameters;
ECPoint q = multiplier.Multiply(parameters.G, privateKey.D);
return new ECPublicKeyParameters(privateKey.AlgorithmName, q, parameters);
}
}
}