在.NET中加载ECC私钥 [英] Loading an ECC private key in .NET
问题描述
我有一个ECC专用文件和一个包含公用密钥的证书文件。我可以使用PEM或DER格式获取它们。
I have an ECC private and a certificate file which includes the public key. I can get them in either PEM or DER formats.
我可以使用以下代码将证书读入 X509Certificate
:
I can read the certificate into an X509Certificate
with this code:
var certbytes = File.ReadAllBytes("certificate.pem");
var cert = new X509Certificate2(certbytes);
但是我无法加载私钥。我尝试了以下代码:
But I'm unable to load the private key. I've tried this code:
var keyContent = File.ReadAllBytes("certificate_private_key.pem");
var key = CngKey.Import(keyContent, CngKeyBlobFormat.EccPrivateBlob);
它抛出 Internal.Cryptography.CryptoThrowHelper.WindowsCryptographicException:'编码或解码操作'
。
我还尝试了 CngKeyBlobFormat
参数。
openssl可以读取文件,并输出有关该文件的以下信息:
openssl can read the file, and it outputs the following information about it:
openssl ec -in certificate_private_key.pem -text
read EC key
Private-Key: (256 bit)
priv:
44:<cut>:68
pub:
04:<cut>:13
ASN1 OID: prime256v1
NIST CURVE: P-256
writing EC key
-----BEGIN EC PRIVATE KEY-----
MHcC <cut here>
-----END EC PRIVATE KEY-----
是否已构建.NET或.NET Core中的内置API可以做到这一点?还是有第三方库可以做到这一点?怎么做?
Is there built-in API in .NET or .NET Core which can do this? Or are there 3rd party libraries that can do it, and how?
推荐答案
.NET Core 3.0(当前处于预览状态)具有 ECDsa.ImportECPrivateKey
, AsymmetricAlgorithm.ImportPkcs8PrivateKey
和 AsymmetricAlgorithm.ImportEncryptedPkcs8PrivateKey
,(并且RSA具有RSAPublicKey和RSAPrivateKey),对于当前文件( BEGIN EC私钥
),您需要第一个。
.NET Core 3.0 (currently in preview) has ECDsa.ImportECPrivateKey
, AsymmetricAlgorithm.ImportPkcs8PrivateKey
, and AsymmetricAlgorithm.ImportEncryptedPkcs8PrivateKey
, (and RSA has RSAPublicKey and RSAPrivateKey) and for the current file (BEGIN EC PRIVATE KEY
) you'd want the first one.
- 这些方法的好消息是:它们存在。
- 的坏消息是:它们是下一版本的一部分,而不是
- 好:下一个版本应尽快成为当前版本。
- 差:他们只了解BER / DER数据,而不了解PEM
- The good news of those methods is: they exist.
- The bad news is: They're part of the next version, not the current one.
- Good: The next version should be the current version soonishly.
- Bad: They only understand BER/DER data, not PEM.
最后一点意味着您当前必须在 ----之间找到base64内容。 -BEGIN EC私钥----- \n
和 \n ----- END EC私钥-----
并de-base64-it,然后将其传递给
The last point means that you currently would have to find the base64 content between the -----BEGIN EC PRIVATE KEY-----\n
and \n-----END EC PRIVATE KEY-----
and de-base64-it, then pass that into the methods.
我知道CNG导入支持的唯一私钥格式是PKCS8,加密的PKCS8和CNG私人格式。要使用CngKey.Import,您首先需要将密钥文件转换为PKCS#8,然后指定格式为 Pkcs8PrivateBlob
,如注释中所建议。
The only private key formats that I know that are supported by CNG import are PKCS8, encrypted PKCS8, and CNG private formats. To use CngKey.Import you'd first need to convert the keyfile to PKCS#8 then specify that the format is Pkcs8PrivateBlob
, as suggested in the comments.
这篇关于在.NET中加载ECC私钥的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!