プライベートキーなしでX.509証明書のエクスポート
-
23-08-2019 - |
質問
私はこれは簡単だろうと思ったが、どうやらそうではありません。私は、エクスポート可能な秘密鍵を、持っているインストールされた証明書を持っている、と私はプログラム的に公開鍵のみでそれをエクスポートします。言い換えれば、私はCertMgrの通過エクスポートと.CERにエクスポートするとき、「秘密キーをエクスポートしないでください」。
を選択した場合と同じ結果が欲しいですそれが存在する場合X509Certificate2.Export方法のすべては、私が何をしたいの反対であるPKCS#12、として、秘密キーをエクスポートしますと思われます。
これを実現するためにC#を使用して任意の方法はありますか、私はCAPICOMを掘り下げる起動する必要がありますか?
解決
この上でつまずいたかもしれない他の誰のために、私はそれを考え出しました。あなたはX509ContentType.Cert
する最初の(そして唯一の)パラメータとしてX509Certificate.Export
を指定した場合、それが唯一の公開鍵をエクスポートします。 1が存在する一方、X509ContentType.Pfx
を指定すると、秘密鍵が含まれます。
私は先週、異なる振る舞いを見ていたことを誓ったかもしれないが、私はすでに私がテストした時にインストールされた秘密鍵を持っている必要があります。今日はその証明書を削除し、最初から再び始めたとき、私は、エクスポートした証明書には秘密鍵がなかったことを見ます。
他のヒント
私は(MSDNは、この上で不明である)証明書のRawData
プロパティは公開鍵のみが含まれていることを自分自身を安心させるために、次のプログラムが役に立ったと評価していて、X509ContentType.Cert
対X509ContentType.Pfx
に関する上記の答えは期待通りに動作する:
using System;
using System.Linq;
using System.IdentityModel.Tokens;
using System.Security.Cryptography.X509Certificates;
class Program
{
static void Main( string[] args )
{
var certPath = @"C:\blah\somecert.pfx";
var certPassword = "somepassword";
var orig = new X509Certificate2( certPath, certPassword, X509KeyStorageFlags.Exportable );
Console.WriteLine( "Orig : RawData.Length = {0}, HasPrivateKey = {1}", orig.RawData.Length, orig.HasPrivateKey );
var certBytes = orig.Export( X509ContentType.Cert );
var certA = new X509Certificate2( certBytes );
Console.WriteLine( "cert A : RawData.Length = {0}, HasPrivateKey = {1}, certBytes.Length = {2}", certA.RawData.Length, certA.HasPrivateKey, certBytes.Length );
// NOTE that this the only place the byte count differs from the others
certBytes = orig.Export( X509ContentType.Pfx );
var certB = new X509Certificate2( certBytes );
Console.WriteLine( "cert B : RawData.Length = {0}, HasPrivateKey = {1}, certBytes.Length = {2}", certB.RawData.Length, certB.HasPrivateKey, certBytes.Length );
var keyIdentifier = ( new X509SecurityToken( orig ) ).CreateKeyIdentifierClause<X509RawDataKeyIdentifierClause>();
certBytes = keyIdentifier.GetX509RawData();
var certC = new X509Certificate2( certBytes );
Console.WriteLine( "cert C : RawData.Length = {0}, HasPrivateKey = {1}, certBytes.Length = {2}", certC.RawData.Length, certC.HasPrivateKey, certBytes.Length );
Console.WriteLine( "RawData equals original RawData: {0}", certC.RawData.SequenceEqual( orig.RawData ) );
Console.ReadLine();
}
}
これは、次のように出力します:
Orig : RawData.Length = 1337, HasPrivateKey = True cert A : RawData.Length = 1337, HasPrivateKey = False, certBytes.Length = 1337 cert B : RawData.Length = 1337, HasPrivateKey = True, certBytes.Length = 3187 cert C : RawData.Length = 1337, HasPrivateKey = False, certBytes.Length = 1337 RawData equals original RawData: True