<bdo id='IHmW9'></bdo><ul id='IHmW9'></ul>
    <i id='IHmW9'><tr id='IHmW9'><dt id='IHmW9'><q id='IHmW9'><span id='IHmW9'><b id='IHmW9'><form id='IHmW9'><ins id='IHmW9'></ins><ul id='IHmW9'></ul><sub id='IHmW9'></sub></form><legend id='IHmW9'></legend><bdo id='IHmW9'><pre id='IHmW9'><center id='IHmW9'></center></pre></bdo></b><th id='IHmW9'></th></span></q></dt></tr></i><div id='IHmW9'><tfoot id='IHmW9'></tfoot><dl id='IHmW9'><fieldset id='IHmW9'></fieldset></dl></div>

        <small id='IHmW9'></small><noframes id='IHmW9'>

        <legend id='IHmW9'><style id='IHmW9'><dir id='IHmW9'><q id='IHmW9'></q></dir></style></legend>
      1. <tfoot id='IHmW9'></tfoot>
      2. C# 将私有/公共 RSA 密钥从 RSACryptoServiceProvider 导出

        时间:2023-06-01

          <tbody id='8dgdI'></tbody>

          <legend id='8dgdI'><style id='8dgdI'><dir id='8dgdI'><q id='8dgdI'></q></dir></style></legend>
            • <bdo id='8dgdI'></bdo><ul id='8dgdI'></ul>

              <tfoot id='8dgdI'></tfoot>

            • <i id='8dgdI'><tr id='8dgdI'><dt id='8dgdI'><q id='8dgdI'><span id='8dgdI'><b id='8dgdI'><form id='8dgdI'><ins id='8dgdI'></ins><ul id='8dgdI'></ul><sub id='8dgdI'></sub></form><legend id='8dgdI'></legend><bdo id='8dgdI'><pre id='8dgdI'><center id='8dgdI'></center></pre></bdo></b><th id='8dgdI'></th></span></q></dt></tr></i><div id='8dgdI'><tfoot id='8dgdI'></tfoot><dl id='8dgdI'><fieldset id='8dgdI'></fieldset></dl></div>

                <small id='8dgdI'></small><noframes id='8dgdI'>

                  本文介绍了C# 将私有/公共 RSA 密钥从 RSACryptoServiceProvider 导出到 PEM 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

                  问题描述

                  限时送ChatGPT账号..

                  我有一个 System.Security.Cryptography.RSACryptoServiceProvider 的实例,我需要将它的密钥导出到 PEM 字符串 - 像这样:

                  I have an instance of System.Security.Cryptography.RSACryptoServiceProvider, i need to export it's key to a PEM string - like this:

                  -----BEGIN RSA PRIVATE KEY-----
                  MIICXAIBAAKBgQDUNPB6Lvx+tlP5QhSikADl71AjZf9KN31qrDpXNDNHEI0OTVJ1
                  OaP2l56bSKNo8trFne1NK/B4JzCuNP8x6oGCAG+7bFgkbTMzV2PCoDCRjNH957Q4
                  Gxgx1VoS6PjD3OigZnx5b9Hebbp3OrTuqNZaK/oLPGr5swxHILFVeHKupQIDAQAB
                  AoGAQk3MOZEGyZy0fjQ8eFKgRTfSBU1wR8Mwx6zKicbAotq0CBz2v7Pj3D+higlX
                  LYp7+rUOmUc6WoB8QGJEvlb0YZVxUg1yDLMWYPE7ddsHsOkBIs7zIyS6cqhn0yZD
                  VTRFjVST/EduvpUOL5hbyLSwuq+rbv0iPwGW5hkCHNEhx2ECQQDfLS5549wjiFXF
                  gcio8g715eMT+20we3YmgMJDcviMGwN/mArvnBgBQsFtCTsMoOxm68SfIrBYlKYy
                  BsFxn+19AkEA82q83pmcbGJRJ3ZMC/Pv+/+/XNFOvMkfT9qbuA6Lv69Z1yk7I1ie
                  FTH6tOmPUu4WsIOFtDuYbfV2pvpqx7GuSQJAK3SnvRIyNjUAxoF76fGgGh9WNPjb
                  DPqtSdf+e5Wycc18w+Z+EqPpRK2T7kBC4DWhcnTsBzSA8+6V4d3Q4ugKHQJATRhw
                  a3xxm65kD8CbA2omh0UQQgCVFJwKy8rsaRZKUtLh/JC1h1No9kOXKTeUSmrYSt3N
                  OjFp7OHCy84ihc8T6QJBANe+9xkN9hJYNK1pL1kSwXNuebzcgk3AMwHh7ThvjLgO
                  jruxbM2NyMM5tl9NZCgh1vKc2v5VaonqM1NBQPDeTTw=
                  -----END RSA PRIVATE KEY-----
                  

                  但是根据 MSDN 文档没有这样的选项,只有某种 XML 导出.我不能使用像 BouncyCastle 这样的任何第三方库.有没有办法生成这个字符串?

                  But there is no such option according to the MSDN documentation, there is only some kind of XML export. I can't use any third party libraries like BouncyCastle. Is there any way to generate this string?

                  推荐答案

                  请注意:以下代码用于导出 private 密钥.如果您要导出 public 密钥,请参考我给出的答案 这里.

                  Please note: The code below is for exporting a private key. If you are looking to export the public key, please refer to my answer given here.

                  PEM 格式只是密钥的 ASN.1 DER 编码(每 PKCS#1) 转换为 Base64.鉴于表示密钥所需的字段数量有限,创建快速而肮脏的 DER 编码器以输出适当的格式然后进行 Base64 编码非常简单.因此,下面的代码不是特别优雅,但可以完成工作:

                  The PEM format is simply the ASN.1 DER encoding of the key (per PKCS#1) converted to Base64. Given the limited number of fields needed to represent the key, it's pretty straightforward to create quick-and-dirty DER encoder to output the appropriate format then Base64 encode it. As such, the code that follows is not particularly elegant, but does the job:

                  private static void ExportPrivateKey(RSACryptoServiceProvider csp, TextWriter outputStream)
                  {
                      if (csp.PublicOnly) throw new ArgumentException("CSP does not contain a private key", "csp");
                      var parameters = csp.ExportParameters(true);
                      using (var stream = new MemoryStream())
                      {
                          var writer = new BinaryWriter(stream);
                          writer.Write((byte)0x30); // SEQUENCE
                          using (var innerStream = new MemoryStream())
                          {
                              var innerWriter = new BinaryWriter(innerStream);
                              EncodeIntegerBigEndian(innerWriter, new byte[] { 0x00 }); // Version
                              EncodeIntegerBigEndian(innerWriter, parameters.Modulus);
                              EncodeIntegerBigEndian(innerWriter, parameters.Exponent);
                              EncodeIntegerBigEndian(innerWriter, parameters.D);
                              EncodeIntegerBigEndian(innerWriter, parameters.P);
                              EncodeIntegerBigEndian(innerWriter, parameters.Q);
                              EncodeIntegerBigEndian(innerWriter, parameters.DP);
                              EncodeIntegerBigEndian(innerWriter, parameters.DQ);
                              EncodeIntegerBigEndian(innerWriter, parameters.InverseQ);
                              var length = (int)innerStream.Length;
                              EncodeLength(writer, length);
                              writer.Write(innerStream.GetBuffer(), 0, length);
                          }
                  
                          var base64 = Convert.ToBase64String(stream.GetBuffer(), 0, (int)stream.Length).ToCharArray();
                          outputStream.WriteLine("-----BEGIN RSA PRIVATE KEY-----");
                          // Output as Base64 with lines chopped at 64 characters
                          for (var i = 0; i < base64.Length; i += 64)
                          {
                              outputStream.WriteLine(base64, i, Math.Min(64, base64.Length - i));
                          }
                          outputStream.WriteLine("-----END RSA PRIVATE KEY-----");
                      }
                  }
                  
                  private static void EncodeLength(BinaryWriter stream, int length)
                  {
                      if (length < 0) throw new ArgumentOutOfRangeException("length", "Length must be non-negative");
                      if (length < 0x80)
                      {
                          // Short form
                          stream.Write((byte)length);
                      }
                      else
                      {
                          // Long form
                          var temp = length;
                          var bytesRequired = 0;
                          while (temp > 0)
                          {
                              temp >>= 8;
                              bytesRequired++;
                          }
                          stream.Write((byte)(bytesRequired | 0x80));
                          for (var i = bytesRequired - 1; i >= 0; i--)
                          {
                              stream.Write((byte)(length >> (8 * i) & 0xff));
                          }
                      }
                  }
                  
                  private static void EncodeIntegerBigEndian(BinaryWriter stream, byte[] value, bool forceUnsigned = true)
                  {
                      stream.Write((byte)0x02); // INTEGER
                      var prefixZeros = 0;
                      for (var i = 0; i < value.Length; i++)
                      {
                          if (value[i] != 0) break;
                          prefixZeros++;
                      }
                      if (value.Length - prefixZeros == 0)
                      {
                          EncodeLength(stream, 1);
                          stream.Write((byte)0);
                      }
                      else
                      {
                          if (forceUnsigned && value[prefixZeros] > 0x7f)
                          {
                              // Add a prefix zero to force unsigned if the MSB is 1
                              EncodeLength(stream, value.Length - prefixZeros + 1);
                              stream.Write((byte)0);
                          }
                          else
                          {
                              EncodeLength(stream, value.Length - prefixZeros);
                          }
                          for (var i = prefixZeros; i < value.Length; i++)
                          {
                              stream.Write(value[i]);
                          }
                      }
                  }
                  

                  这篇关于C# 将私有/公共 RSA 密钥从 RSACryptoServiceProvider 导出到 PEM 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

                  上一篇:如何从 .NET 读取 PEM RSA 私钥 下一篇:使用纯 .net 框架生成和签署证书请求

                  相关文章

                  最新文章

                  • <bdo id='kcXm5'></bdo><ul id='kcXm5'></ul>
                • <small id='kcXm5'></small><noframes id='kcXm5'>

                      <i id='kcXm5'><tr id='kcXm5'><dt id='kcXm5'><q id='kcXm5'><span id='kcXm5'><b id='kcXm5'><form id='kcXm5'><ins id='kcXm5'></ins><ul id='kcXm5'></ul><sub id='kcXm5'></sub></form><legend id='kcXm5'></legend><bdo id='kcXm5'><pre id='kcXm5'><center id='kcXm5'></center></pre></bdo></b><th id='kcXm5'></th></span></q></dt></tr></i><div id='kcXm5'><tfoot id='kcXm5'></tfoot><dl id='kcXm5'><fieldset id='kcXm5'></fieldset></dl></div>

                    1. <legend id='kcXm5'><style id='kcXm5'><dir id='kcXm5'><q id='kcXm5'></q></dir></style></legend>
                    2. <tfoot id='kcXm5'></tfoot>