从Bouncy Castle C#

时间:2018-01-18 01:20:07

标签: c# bouncycastle

所以我有一个加密的私钥PEM。我可以阅读它并获得以下私钥:

AsymmetricKeyParameter key;
using (var sr = new StringReader(pem))
using (var pf = new PassowrdFinder { Password = password })
{
  var reader = new PemReader(sr, pf);
  key = (AsymmetricKeyParameter)reader.ReadObject();
}

我还需要公钥,以便稍后创建SPKI。我试过了

var keyPair = new AsymmetricCipherKeyPair(key, key);

哪个失败了System.ArgumentException: Expected a public key Parameter name: publicParameter

我的问题是:如何从私钥获取公钥?

3 个答案:

答案 0 :(得分:1)

我对Bouncycastle C#库有点笨拙,但我认为这样做的方法是使用私钥的适当组件显式创建一个新的密钥对象。实施例

// Make an rsa keypair for testing

var rand = new SecureRandom();
var keyGenParams = new RsaKeyGenerationParameters(
        new BigInteger("65537"), rand, 1024, 64
    );
var rsaKeyGen = new RsaKeyPairGenerator();
rsaKeyGen.Init(keyGenParams);
var rsaKeyPair = rsaKeyGen.GenerateKeyPair();
var rsaPriv = (RsaPrivateCrtKeyParameters)rsaKeyPair.Private;

// Make a public from the private

var rsaPub = new RsaKeyParameters(false, rsaPriv.Modulus, rsaPriv.PublicExponent);

// Try it out

var rsaKeyPair2 = new AsymmetricCipherKeyPair(rsaPub, rsaPriv);

这种方法的缺点是它需要特定种类的非对称密钥的具体实例;它不适用于抽象的非对称密钥类。

答案 1 :(得分:1)

应该很简单:

AsymmetricCipherKeyPair KeyPair = (AsymmetricCipherKeyPair)reader.ReadObject();

然后:

var pubKey = KeyPair.public;

答案 2 :(得分:0)

感谢James K Polk的帮助,这就是我的想法

    AsymmetricCipherKeyPair GetKeyPairFromPrivateKey(AsymmetricKeyParameter privateKey)
    {
        AsymmetricCipherKeyPair keyPair = null;
        if (privateKey is RsaPrivateCrtKeyParameters rsa)
        {
            var pub = new RsaKeyParameters(false, rsa.Modulus, rsa.PublicExponent);
            keyPair = new AsymmetricCipherKeyPair(pub, privateKey);
        }
        else if (privateKey is Ed25519PrivateKeyParameters ed)
        {
            var pub = ed.GeneratePublicKey();
            keyPair = new AsymmetricCipherKeyPair(pub, privateKey);
        }
        else if (privateKey is ECPrivateKeyParameters ec)
        {
            var q = ec.Parameters.G.Multiply(ec.D);
            var pub = new ECPublicKeyParameters(ec.AlgorithmName, q, ec.PublicKeyParamSet);
            keyPair = new AsymmetricCipherKeyPair(pub, ec);
        }
        if (keyPair == null)
            throw new NotSupportedException($"The key type {privateKey.GetType().Name} is not supported.");

        return keyPair;
    }