如何从 PEM 文件中获取私钥? [英] how to get private key from PEM file?

查看:48
本文介绍了如何从 PEM 文件中获取私钥?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 .PEM 文件,其中包含用于 SSL 数据传输的公钥和私钥,如下所示:

-----开始RSA私钥--私钥数据-----结束RSA私钥----------开始认证-----公钥数据-----结束证书-----

当我想通过以下代码加载 .PEM 文件时:

X509Certificate2 xx = new X509Certificate2("c:\myKey.pem");

我收到一个异常消息:找不到请求的对象.", 全栈:

System.Security.Cryptography.CryptographicException 未处理Message=找不到请求的对象.源=mscorlib堆栈跟踪:在 System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 小时)在 System.Security.Cryptography.X509Certificates.X509Utils._QueryCertFileType(String fileName)在 System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags)在 System.Security.Cryptography.X509Certificates.X509Certificate..ctor(字符串文件名)在 System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(字符串文件名)在 DLLTest.SSL_Test.test() 在 E:ProjectsDLLTestDLLTestSSL_Test.cs:line 165在 DLLTest.SSL_Test.Run() 在 E:ProjectsDLLTestDLLTestSSL_Test.cs:line 21在 DLLTest.Program.Main(String[] args) 在 E:ProjectsDLLTestDLLTestProgram.cs:line 21在 System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()在 System.Threading.ThreadHelper.ThreadStart_Context(对象状态)在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)在 System.Threading.ThreadHelper.ThreadStart()内部异常:

如果我交换私钥部分和公钥部分的位置,代码将起作用并加载数据,并且我只能从对象中获取公钥信息,例如.发行人名称,并且它的 HasPrivateKey 是假的.为什么?我是不是被误解了,做错了什么?

解决方案

有一个 关于代码项目的文章,其中包含执行此操作所需的所有代码.这只是几个类,所以它是一个轻量级的解决方案.

要从 PEM 文件中获取证书或密钥的字节,无论密钥和证书在文件中的顺序如何,以下方法都有效.

 byte[] GetBytesFromPEM( string pemString, string section ){var header = String.Format("-----BEGIN {0}-----", section);var footer = String.Format("-----END {0}-----", section);var start= pemString.IndexOf(header, StringComparison.Ordinal);如果(开始 <0 )返回空;start += header.Length;var end = pemString.IndexOf(footer, start, StringComparison.Ordinal) - 开始;如果(结束 <0 )返回空;return Convert.FromBase64String(pemString.Substring(start, end));}

将PEM文件加载到字符串中,调用上面的方法获取代表证书的字节.接下来,您将获得的字节传递给 X509Certificate2 的构造函数:

 var pem = System.IO.File.ReadAllText( "c:\myKey.pem" );byte[] certBuffer = GetBytesFromPEM( pem, "CERTIFICATE" );var 证书 = 新 X509Certificate2( certBuffer );

从 PEM 文件加载 (RSA) 私钥有点复杂,但您会在上述文章中找到支持,也可以使用 Crypto.DecodeRsaPrivateKey 方法.>

i have a .PEM file that includes public key and a private key for SSL data transfer like this:

-----BEGIN RSA PRIVATE KEY-----
      private key data
-----END RSA PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
      public key data
-----END CERTIFICATE-----

when i want to load the .PEM file by the following code:

X509Certificate2 xx = new X509Certificate2("c:\myKey.pem");

i get an exception that says: "Cannot find the requested object." , with full stack:

System.Security.Cryptography.CryptographicException was unhandled
  Message=Cannot find the requested object.

  Source=mscorlib
  StackTrace:
       at System.Security.Cryptography.CryptographicException.ThrowCryptographicException(Int32 hr)
       at System.Security.Cryptography.X509Certificates.X509Utils._QueryCertFileType(String fileName)
       at System.Security.Cryptography.X509Certificates.X509Certificate.LoadCertificateFromFile(String fileName, Object password, X509KeyStorageFlags keyStorageFlags)
       at System.Security.Cryptography.X509Certificates.X509Certificate..ctor(String fileName)
       at System.Security.Cryptography.X509Certificates.X509Certificate2..ctor(String fileName)
       at DLLTest.SSL_Test.test() in E:ProjectsDLLTestDLLTestSSL_Test.cs:line 165
       at DLLTest.SSL_Test.Run() in E:ProjectsDLLTestDLLTestSSL_Test.cs:line 21
       at DLLTest.Program.Main(String[] args) in E:ProjectsDLLTestDLLTestProgram.cs:line 21
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

if i swap place of private key section and public key section, the code works and load data, and i can get just public key info from the object, eg. IssuerName, and its HasPrivateKey is false. why? am i misunderstood and doing wrong something?

解决方案

There's an article on the Code Project that has all the code you need to do this. It's just a couple of classes so it's a light-weight solution.

To get the bytes for either a certificate or a key from the PEM file the following method will work, regardless of the order of the key and certificate in the file.

 byte[] GetBytesFromPEM( string pemString, string section )
 {
     var header = String.Format("-----BEGIN {0}-----", section);
     var footer = String.Format("-----END {0}-----", section);

     var start= pemString.IndexOf(header, StringComparison.Ordinal);
     if( start < 0 )
        return null;

     start += header.Length;
     var end = pemString.IndexOf(footer, start, StringComparison.Ordinal) - start;

     if( end < 0 )
        return null;

     return Convert.FromBase64String( pemString.Substring( start, end ) );
 }

Load the PEM file into a string and call the method above to get the bytes that represent the certificate. Next you pass the obtained bytes to the constructor of an X509Certificate2 :

 var pem = System.IO.File.ReadAllText( "c:\myKey.pem" );
 byte[] certBuffer = GetBytesFromPEM( pem, "CERTIFICATE" );
 var certificate = new X509Certificate2( certBuffer );

Loading the (RSA) private key from the PEM file is a bit more complicated but you'll find support for that in the above mentioned article as well using the Crypto.DecodeRsaPrivateKey method.

这篇关于如何从 PEM 文件中获取私钥?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆