导出或保存 CX509PrivateKey

2024-01-04

是否可以以某种方式保存或导出CX509PrivateKey。我的想法是,我创建一个 CSR 发送给 CA 获取证书,然后...不知何故我必须获取私钥,但不知道如何获取,不幸的是在谷歌上没有找到任何内容。

我的一段代码:

var objPrivateKey = new CX509PrivateKey();
objPrivateKey.Length = int.Parse(ConfigurationManager.AppSettings["objPrivateKeyLength"]);
objPrivateKey.KeySpec = X509KeySpec.XCN_AT_SIGNATURE;
objPrivateKey.KeyUsage = X509PrivateKeyUsageFlags.XCN_NCRYPT_ALLOW_ALL_USAGES;
objPrivateKey.MachineContext = false;
objPrivateKey.ExportPolicy = X509PrivateKeyExportFlags.XCN_NCRYPT_ALLOW_EXPORT_FLAG;
objPrivateKey.CspInformations = objCSPs;
objPrivateKey.Create();

其实我是这样解决这个任务的。 (这里有更多代码,这样您就可以理解我想要做什么)。

到这里所有的工作就完成了。

/*
    using CERTADMINLib;
    using CERTCLILib;
    using CertSevAPI.Core.Models;
    using CertSrvAPI.Core;
    using CertSrvAPI.Core.Models;
    using Org.BouncyCastle.Asn1;
    using Org.BouncyCastle.Asn1.Pkcs;
    using Org.BouncyCastle.Asn1.X509;
    using Org.BouncyCastle.Crypto;
    using Org.BouncyCastle.Crypto.Generators;
    using Org.BouncyCastle.Crypto.Prng;
    using Org.BouncyCastle.Pkcs;
    using Org.BouncyCastle.Security;
    using System;
*/

var caService = new CAService();

// Create a certificate request.
// The private key is here.
var caRequest = caService.CertRequest(subjectDN);

// Submit the certificate request and get the response.
var caResponse = caService.SendCertRequest(caRequest.Request);

// If certificated is not issued return null.
if (!caService.IsIssued(caResponse.Disposition))
{
    return null;
}

// Download the P7B file from CA.
var p7b = new WebClient().DownloadData(
    _appSettings.CERT_SRV + "/CertSrv/CertNew.p7b?ReqID=" + caResponse.CertRequest.GetRequestId() + "&Enc=bin");

try
{
    var certCollection = new X509Certificate2Collection();
    
    // Import the downloaded file.
    certCollection.Import(p7b);

    // Create a PKCS store.
    var pfx = new Pkcs12Store();
    
    // Insert root CA certificate into the PKCS store.
    pfx.SetCertificateEntry("rootCert",
        new X509CertificateEntry(DotNetUtilities.FromX509Certificate(certCollection[0])));

    // Get the second certificate from the downloaded file.
    // That one is the generated certificate for our request.
    var certificateEntry = new X509CertificateEntry[1];
    certificateEntry[0] = new X509CertificateEntry(DotNetUtilities.FromX509Certificate(certCollection[1]));
    
    // Insert our certificate with the private key
    // under the same alias so then we know that this private key
    // is for our certificate.
    pfx.SetKeyEntry("taxkey", new AsymmetricKeyEntry(caRequest.PrivateKey), certificateEntry);

    var memoryStream = new MemoryStream();
    
    // Stream PFX store using the desired password
    // for our file.
    pfx.Save(memoryStream, password.ToCharArray(), new SecureRandom());
   
    var pfxBytes = memoryStream.GetBuffer();
    pfxBytes = Pkcs12Utilities.ConvertToDefiniteLength(pfxBytes, password.ToCharArray());

    // Here you can save the pfxBytes to a file, if you want.
    // Actually I needed it to give as a response in MVC application.
    return File(pfxBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "NewCert.pfx");
}
catch (Exception ex)
{
    // If there is an error remove private key from
    // the memory.
    caRequest.PrivateKey = null;
    caRequest.Request = null;

    ErrorSignal.FromCurrentContext().Raise(ex);

    if (showError != null && showError.ToLower() == "true")
    {
        throw ex;
    }

    return null;
}

私钥位于CARequest.

/*
    using Org.BouncyCastle.Crypto;
*/

public class CARequestModel
{
    public AsymmetricKeyParameter PrivateKey { get; set; }
    public string Request { get; set; }
}

私钥一直保存在内存中,直到我们需要将其保存到 PFX 文件时为止,并在我们创建证书请求时生成。那么这里就是证书请求的生成方法。

public CARequestModel CertRequest(string subjectDN)
{
    var name = new X509Name(subjectDN);
    var rsaKeyPairGenerator = new RsaKeyPairGenerator();
    
    rsaKeyPairGenerator.Init(
        new KeyGenerationParameters(new SecureRandom(
                new CryptoApiRandomGenerator()), _appSettings.PRIVATE_KEY_LENGHT));

    // Generate key pair.
    var keyPair = rsaKeyPairGenerator.GenerateKeyPair();
    
    // Get the private key.
    var privateKey = keyPair.Private;
    
    // Get the public key.
    var publicKey = keyPair.Public;

    // Set the key usage scope.
    var keyUsage = new KeyUsage(KeyUsage.DigitalSignature);
    var extensionsGenerator = new X509ExtensionsGenerator();

    extensionsGenerator.AddExtension(X509Extensions.KeyUsage, true, keyUsage);

    var attribute = new AttributeX509(
        PkcsObjectIdentifiers.Pkcs9AtExtensionRequest, new DerSet(extensionsGenerator.Generate()));

    // Create the certificate request
    var csr = new Pkcs10CertificationRequest("SHA256withRSA", name, publicKey, new DerSet(attribute), privateKey);
    
    // Get it as DER, because then I have to submit it to the MS CA server.
    var csrBytes = csr.GetDerEncoded();

    // Return the Request and private key
    return
        new CARequestModel
        {
            Request = Convert.ToBase64String(csrBytes),
            PrivateKey = privateKey
        };
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

导出或保存 CX509PrivateKey 的相关文章

随机推荐

  • 独立运行 async while 循环

    是否可以独立于另一个循环运行异步 while 循环 我在以下示例代码中隔离了我遇到的问题 而不是实际的代码 import asyncio time class Time def init self self start time 0 asy
  • cecil:Instruction.OpCode.Code值对应的Instruction.Operand类型

    是否有任何文档或 cecil 源代码的一部分可供我查阅以全面了解其中的内容Operandcecil 将用于给定的类型Code价值 例如 我可以从MethodBodyRocks that Ldloc需要一个Operand类型的Variable
  • 使用 JavaScript 检测点击目标?

    如何检测右键单击的对象或 ID 或用户 我正在使用 onContextMenu 来触发函数 但我不知道如何检测目标
  • Bootstrap 的下拉菜单被数据表隐藏

    我正在使用 Twitter Bootstrap 为 DataTables 网格中的每一行创建一个带有 DropDown 菜单的按钮 但 DataTables 中的数据容器正在使用 overflow hidden 这使得 DropDown 被
  • 从一组中找到多个最大不同的二元向量

    考虑集合 S 所有长度的二进制向量n其中每个恰好包含m那些 所以有n m每个向量中的零 我的目标是构建一个数字 k 向量来自S使得这些向量彼此尽可能不同 举个简单的例子 n 4 m 2 and k 2 那么可能的解是 1 1 0 0 和 0
  • 设置/更改 iFrame 的 MIME 类型?

    是否可以使用 JavaScript 动态设置 iFrame 的 MIME 类型 DIV 有同样的问题吗 No MIME 类型由您加载的内容决定 对于一个无论什么框架src指定 Div 不加载外部内容 因此没有 MIME 类型
  • 如何设置 SPAN 的高度属性

    我需要使以下代码可拉伸并具有预定义的高度 span class title This is title span 但是由于span是内联元素 height 属性不起作用 我尝试使用div相反 它会扩展到上部元素的宽度 并且宽度要灵活 对此有
  • 如何在 Laravel 5 表单中使用 Markdown 作为文本区域输入字段?

    在我的基于 Laravel 5 的项目中 我使用的是 Markdown 包http packalyst com packages package graham campbell markdown http packalyst com pac
  • Python Sphinx 锚点在任意线上

    如何使用 Sphinx 在 ReST 中的任意行设置锚点引用 为了更清楚 这里有一个例子 A title with an anchor some stuff 这将创建一个标题A title with an anchor并添加一个额外的on
  • 如何为 CSS 垂直下拉菜单添加延迟

    我需要为下拉菜单的鼠标悬停事件添加延迟 这样如果有人将鼠标悬停在菜单上并转到页面上的另一个链接 菜单不会立即下拉 感谢您的帮助 http jsfiddle net cgagliardi NPVVQ http jsfiddle net cga
  • saltstack jinja 中的“json”和“tojson”过滤器有什么区别吗?

    根据 saltstack 文档 它是 json https docs saltstack com en latest ref renderers all salt renderers jinja html https docs saltst
  • 在字典中循环

    我用这个 foreach KeyValuePair
  • 过滤查询以填充 FirebaseRecyclerAdapter

    目前尚不清楚如何使用自定义查询填充 FirebaseRecyclerAdapter 定义一个参考 这里 DatabaseReference ref mDatabase getReference child users 将其发送到适配器 in
  • 保护HTML5游戏来源

    人们对 HTML5 赞不绝口 但我主要关心的问题之一是如何保护我的游戏源代码 本质上 如何防止别人使用我们自己开发的游戏引擎 那是一笔巨大的资产 如何防止他人下载游戏并将其托管在其他平台 如何隐藏源中的服务器 API 调用详细信息 例如我们
  • Ruby 相当于 PHP 的 ucfirst() 函数

    在 Ruby 使用 Rails 如果相关的话 中将字符串的第一个字母大写的最佳方法是什么 注意String capitalize不是我想要的 因为除了将字符串的第一个字母大写之外 此函数还使所有其他字符小写 我不想要 我想保持它们不变 gt
  • 如何在 bash 脚本中获取文件的第一行?

    我必须在文件的第一行放入 bash 变量 我猜是用grep命令 但是有什么方法可以限制行数吗 head从文件中获取第一行 然后 n参数可用于指定应提取多少行 line head n 1 filename
  • 尝试使用 conda 时出现“语法错误:生成器表达式必须带括号”

    每当我尝试访问任何 anaconda 命令时 我都会遇到这个问题 事实上 当我尝试打开我的虚拟环境时 它也显示在那里 我已经重新安装了 anaconda navigator 但仍然没有结果 C Users Gagan Singh gt ac
  • 如何通过 holoviz 和 NetworkX 渲染 GraphViz Dot 文件?

    所以我看着docs https hvplot holoviz org user guide NetworkX html并看到他们使用 Graphviz 但不使用任何文件 而且我有一个4mil dot 70mb 图形文件 https gith
  • 在 Ubuntu 上找不到 RODBC 包中的 odbcConnectExcel 函数

    在 Ubuntu 上安装 RODBC 包有点麻烦 首先我学会了安装以下内容 sudo apt get install r cran rodbc 这还不够好 因为包仍在寻找头文件 我通过以下方式解决了这个问题 sudo apt get ins
  • 导出或保存 CX509PrivateKey

    是否可以以某种方式保存或导出CX509PrivateKey 我的想法是 我创建一个 CSR 发送给 CA 获取证书 然后 不知何故我必须获取私钥 但不知道如何获取 不幸的是在谷歌上没有找到任何内容 我的一段代码 var objPrivate