【问题标题】:'Key not valid for use in specified state' when exporting X509Certificate2 in .Net 5在 .Net 5 中导出 X509Certificate2 时,“密钥在指定状态下无效”
【发布时间】:2021-10-09 12:29:30
【问题描述】:

我有一个应用程序可以执行以下操作...

  • 我创建了一个 RSACng 密钥并存储在内存中
  • 我使用创建的 rsa 密钥创建了一个 csr 并将其提交给公共 CA
var request = new CertificateRequest(
                distinguishedName,
                rsaKey,
                HashAlgorithmName.SHA384,
                RSASignaturePadding.Pkcs1);
  • 我取回证书文件并保存到磁盘
  • 然后我想为此证书和关联的私钥创建一个 pkcs12,如下所示,但出现“密钥无效..”错误
var cert = new X509Certificate2(certFile).CopyWithPrivateKey(rsaKey);
cert.Export(X509ContentType.Pkcs12, "somepassphrase")

尝试将私钥指定为可导出,但这没有帮助,不确定这是否是正确的方法,因为没有接受 rsa 对象的 X509Certificate2 构造函数

var cert = new X509Certificate2(certFile, "privateKeyPassphrase", X509KeyStorageFlags.Exportable).CopyWithPrivateKey(rsaKey);
cert.Export(X509ContentType.Pkcs12, "somepassphrase")

有谁知道可能是什么问题?

【问题讨论】:

    标签: export .net-5 x509certificate2 pfx pkcs#12


    【解决方案1】:

    由于您的私钥不可导出,因此引发错误。创建RSACng对象时必须指定导出策略(通过接受CngKey实例的构造函数)。

    【讨论】:

      【解决方案2】:

      我现在有 pcks12,里面有这个证书和它的证书链。

      var certsCollection = new X509Certificate2Collection();
      certsCollection.Add(cert);
      certsCollection.Add(rootCert);
      File.WriteAllBytes(pkcs12File, certsCollection.Export(X509ContentType.Pkcs12, "somepassphrase"));
      

      如果我然后按如下方式导入它并查看该证书的导出策略,它显示为无,这是为什么呢?

       var colCerts = new X509Certificate2Collection();
       colCerts.Import(pkcs12File, "somepassphrase");
      

      【讨论】:

      • 因为导入操作默认为不可导出键。您需要使用X509Certificate2Collection.Import(string, string?, X509KeyStorageFlags) 重载并在第三个参数中传递Exportable 标志。
      猜你喜欢
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 2012-03-10
      • 2017-10-03
      • 1970-01-01
      • 1970-01-01
      • 2013-09-11
      相关资源
      最近更新 更多