使用Bouncy Castle生成keyPair

时间:2014-02-25 08:20:28

标签: java c#-4.0 windows-phone-8 bouncycastle

我有使用BC生成密钥对的Java代码,如下所示:

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(1024);
        KeyPair key = keyGen.generateKeyPair();
        PrivateKey priv = key.getPrivate();
        PublicKey pub = key.getPublic();
        String privateKey = new String(Base64.encode(priv.getEncoded(), 0,priv.getEncoded().length, Base64.NO_WRAP));
        String publicKey1 = new String(Base64.encode(pub.getEncoded(), 0,pub.getEncoded().length, Base64.NO_WRAP));
        String publicKey = new String(Base64.encode(publicKey1.getBytes(),0, publicKey1.getBytes().length, Base64.NO_WRAP));

现在我想在C#中使用BC做同样的事情。我已经通过nuget包管理器下载了WP8BouncyCastle库。我写的是:

var kpgen = new RsaKeyPairGenerator();

            kpgen.Init(new KeyGenerationParameters(new SecureRandom(new CryptoApiRandomGenerator()), 1024));

            var keyPair = kpgen.GenerateKeyPair();
            AsymmetricKeyParameter privateKey = keyPair.Private;
            AsymmetricKeyParameter publicKey = keyPair.Public;


            string prvKey = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(privateKey.ToString()));
            string pubKey = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(publicKey.ToString()));
            string pubKey1 = Convert.ToBase64String(UTF8Encoding.UTF8.GetBytes(pubKey.ToString()));

但是我需要Java中的getEncoded()方法,这在C#中的BC库中是不可用的。这个getEncoded()方法用于将给定密钥转换为X.509编码密钥。对于Java,公钥被转换两次(getencoded()getBytes()),我无法做到同样在C#中。

有什么解决方案吗?

1 个答案:

答案 0 :(得分:7)

将以下代码用于私钥:

PrivateKeyInfo pkInfo = PrivateKeyInfoFactory.CreatePrivateKeyInfo(keyPair.Private);
String privateKey = Convert.ToBase64String(pkInfo.GetDerEncoded());

并关注公众:

SubjectPublicKeyInfo info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keyPair.Public);
String publicKey = Convert.ToBase64String(info.GetDerEncoded());