使用BouncyCastle读取C#中的DER私钥 [英] Read DER private key in C# using BouncyCastle

查看:136
本文介绍了使用BouncyCastle读取C#中的DER私钥的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用BouncyCastle将RSA私钥读入.Net,以测试我之前加密的数据.使用公共密钥和Bouncy Castle加密的数据可以正常工作,我还使用了以下相同的私有密钥(DER格式)在PHP应用程序中成功解密了我的数据,但是我不知道为什么不能在.Net中创建私钥以执行相同的操作:

I am trying to read an RSA private key into .Net using BouncyCastle to test data I have previously encrypted. The encrypted data is working fine using the public key and Bouncy Castle and I have also used the same private key as below (which is DER format) to successfully decrypt my data in a PHP application but I don't know why I can't create the private key in .Net to do the same thing:

byte[] privatekey = File.ReadAllBytes(@"C:\Users\Luke\privkey.der");
var rsaKeyParameters = (RsaKeyParameters)PrivateKeyFactory.CreateKey(privatekey);

第二行引发异常:

工厂中的未知对象:DerInteger \ r \ n参数名称:obj"

"unknown object in factory: DerInteger\r\nParameter name: obj"

我也尝试使用流而不是字节数组,并且发生相同的错误.密钥对是使用OpenSSL创建的,并且如上所述,解密在PHP中使用openssl_private_decrypt()和与.Net代码相同的密钥起作用.我还尝试了相同密钥的PEM格式,但也没有用(但是我不认为BC仍然直接支持PEM)

I also tried using a stream instead of a byte array and the same error occurs. The key pair was created using OpenSSL and as mentioned, decryption works in PHP using openssl_private_decrypt() and the same key as in the .Net code. I also tried a PEM format of the same key and that also didn't work (but I don't think BC supports PEM directly anyway)

有人做过吗?谢谢

推荐答案

问题是我假设PublicKeyFactory和PrivateKeyFactory是互补的,因为它们在同一个命名空间中.他们不是!

The problem was that I had assumed PublicKeyFactory and PrivateKeyFactory were complimentary since they are in the same namespace. They are not!

要解码私钥,我需要以下替代代码:

To decode the private key, I needed the following alternative code:

var privKeyObj = Asn1Object.FromStream(privatekey);
var privStruct = new RsaPrivateKeyStructure((Asn1Sequence)privKeyObj);

// Conversion from BouncyCastle to .Net framework types
var rsaParameters = new RSAParameters();
rsaParameters.Modulus = privStruct.Modulus.ToByteArrayUnsigned();
rsaParameters.Exponent = privStruct.PublicExponent.ToByteArrayUnsigned();
rsaParameters.D = privStruct.PrivateExponent.ToByteArrayUnsigned();
rsaParameters.P = privStruct.Prime1.ToByteArrayUnsigned();
rsaParameters.Q = privStruct.Prime2.ToByteArrayUnsigned();
rsaParameters.DP = privStruct.Exponent1.ToByteArrayUnsigned();
rsaParameters.DQ = privStruct.Exponent2.ToByteArrayUnsigned();
rsaParameters.InverseQ = privStruct.Coefficient.ToByteArrayUnsigned();
var rsa = new RSACryptoServiceProvider();
rsa.ImportParameters(rsaParameters);
return Encoding.UTF8.GetString(rsa.Decrypt(Convert.FromBase64String(ciphertext), true));

由衷的感谢owlstead的帮助.

A BIG thankyou to owlstead for their help.

这篇关于使用BouncyCastle读取C#中的DER私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆