Java 使用 Bouncy Castle 生成密钥对

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22008337/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:03:08  来源:igfitidea点击:

Generating keyPair using Bouncy Castle

javac#-4.0windows-phone-8bouncycastle

提问by Vaibhav

I have Java code for generating keypair using BC as follows:

我有使用 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));

Now I want to do same in C# using BC. I have downloaded WP8BouncyCastle library via nuget package manager. I have written as:

现在我想在 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()));

But I need getEncoded()method available in Java which is not available in BC library in C#. This getEncoded()method is used to convert given key into X.509 encoded key.In case of Java, public key getting twice converted (getencoded()and getBytes()) ,I am not able to do same in C#.

但是我需要getEncoded()Java 中可用的方法,而 C# 中的 BC 库中没有该方法。此getEncoded()方法用于将给定的密钥转换为 X.509 编码的密钥。在 Java 的情况下,公钥被转换两次(getencoded()getBytes()),我无法在 C# 中做同样的事情。

Is there any solution to it?

有什么解决办法吗?

采纳答案by ikolomiyets

Use the following code for private key:

使用以下代码作为私钥:

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

and following for public:

并为公众提供以下内容:

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