我有一个在端口 443 上提供 SSL 连接的 Apache (xampp/wamp) 服务器。 它使用两个证书文件:server.cert 和 server.key,后者包含私钥。
我将另一台服务器配置为监听端口 843 上的请求(flash 策略内容),并使用单独运行的 C# 编写的一些文本回复来响应特定请求。
为了实现 SSL 连接,我使用了一个名为 SecureSocket 的 flex 对象,它允许使用原始服务器证书来加密请求。
我的目标是教我的 843 C# 服务器解密发送的数据并加密回复,为此我在 C# 中使用 X509Certificate 对象。
但是,由于公钥和私钥位于不同的文件中,因此我在以下方面得到了 FALSE:
string text = System.IO.File.ReadAllText(@"C:\xampp\apache\conf\ssl.crt\server.crt");
UTF8Encoding encoding = new System.Text.UTF8Encoding();
byte[] byteCert = encoding.GetBytes(text);
X509Certificate2 uberCert = new X509Certificate2();
uberCert.Import(byteCert);
Console.WriteLine("Has privateKey:" + uberCert.HasPrivateKey.ToString());
Console.WriteLine("PrivateKey: \n" + uberCert.PrivateKey);
显然,uberCert.HasPrivateKey 上的 False 是因为私钥位于不同的文件中,所以我的问题是:
1.如何使用 X509CErtificate2 对象读取私钥? 2.如何使用公钥解密接收到的消息以及如何使用私钥对其重新加密(以便将加密的响应发回)?
提前致谢
迈克。
最佳答案
我创建了一个小的 NuGet 帮助程序包(基于 opensslkey )来创建基于公钥 和私有(private) (rsa) 的X509 证书键。
// Generate with: openssl req -x509 -sha256 -nodes -days 365 -newkey rsa:2048 -keyout private.key -out certificate_pub.crt
string certificateText = File.ReadAllText("certificate_pub.crt");
string privateKeyText = File.ReadAllText("private.key");
ICertificateProvider provider = new CertificateFromFileProvider(certificateText, privateKeyText);
X509Certificate2 certificate = provider.Certificate;
// Example: use the PrivateKey from the certificate above for signing a JWT token using Jose.Jwt:
string token = Jose.JWT.Encode(payload, certificate.PrivateKey, JwsAlgorithm.RS256);
参见 NuGet和 Github-project功能和代码示例。
关于c# - 如何从单独的文件中获取私钥?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9378150/