how to get private key from PEM file?

后端 未结 6 763
迷失自我
迷失自我 2020-11-27 02:51

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
-----EN         


        
6条回答
  •  失恋的感觉
    2020-11-27 03:26

    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.

提交回复
热议问题