从 X509Certificate 对象导出私钥
我们使用 C# 代码使用 .p12 文件构建 X509Certificate2,在构造函数中插入证书路径、证书密码。我们还将其标记为可导出,如下所示:
X509Certificate2 x509Certificate2 = new X509Certificate2
("...\\MyCerificate.p12", "P@ssw0rd", X509KeyStorageFlags.Exportable);
我们通过以下方式获取非对称算法格式的私钥:
x509Certificate2.PrivateKey
现在,我们希望从证书中获取 Base64 格式的私钥 - 但我们不这样做知道如何去做,这对我们来说非常重要。
We use C# code we build X509Certificate2 with .p12 file, in the constructor we insert the path to certificate, certificate's password. We also marked it as Exportable as shown below:
X509Certificate2 x509Certificate2 = new X509Certificate2
("...\\MyCerificate.p12", "P@ssw0rd", X509KeyStorageFlags.Exportable);
we get the private key as AsymmetricAlgorithm format by the following:
x509Certificate2.PrivateKey
Now, we want to get the private key from the certificate as Base64 format - but we don't have any idea how to do it, and its so important for us.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
重要的问题是为什么要 base64 ?
如果这是您自己的应用程序,那么您可以将私钥保留为 XML 字符串(更容易:-)。
如果您想要base64(同样仅适用于您的应用程序),您可以导出密钥(RSAParameters),然后连接每个
byte[]
并将合并的输出转换为base64字符串。但是,如果您想与需要 base64 私钥的其他应用程序进行互操作,那么您需要知道格式(在 base64 字符串内)。例如,在许多情况下,私钥是 PEM 编码的(它是带有特殊标头的 base64 /footer,请参阅示例
X509证书
)。如果这就是您要寻找的,那么您需要在 PKCS#8结构,然后转入base64并添加页眉/页脚。您可以找到一些有用的代码来执行此操作 内部 Mono.Security.dll(来自 Mono 项目的 MIT.X11 许可代码)。
The important question is why base64 ?
If this is for your own application then you can keep the private key as an XML string (much easier :-).
If you want base64 (again just for your application) you can export the key (RSAParameters) then concat every
byte[]
and turn the merged output to a base64 string.But if you want to interop with other applications that requires a base64 private key then you need to know the format (inside the base64 string). E.g. in many case private keys are PEM encoded (which is base64 with a special header/footer, see an example for
X509Certificate
).If that what's you're looking for then you'll need to encode the private key within a PKCS#8 structure first, then turn in into base64 and add the header/footer. You can find some helpful code to do so inside Mono.Security.dll (MIT.X11 licensed code from the Mono project).
您可以简单地使用 X509Certificate2 的 PrivateKey 属性。
实际返回的私钥实现取决于证书中使用的算法 - 通常是 RSA:
之后您应该能够从其 ExportParameters 属性中获取 RSA 密钥信息。
You can simply use the PrivateKey property of X509Certificate2.
The actual returned private key implementation depends on the algorithm used in the certificate - usually this is RSA:
Afterwards you should be able to get the RSA key information from it's ExportParameters property.
您可以使用 OpenSSL Library for .NET 来做到这一点:
You can do that with OpenSSL Library for .NET:
如果您唯一的问题是获取私钥 Base64 编码,您可以简单地这样做:
If your only problem is to get the private key Base64 encoded, you can simply do like this: