ドキュメントに署名するために.pfxファイルを作成する方法はありますか?x509 Certificate Generateというプログラムを見つけましたが、c#を使用してコードで生成できるかどうかを知りたいです。
6 に答える
証明書の生成に使用できるMicrosoft コマンドライン ツールmakecertがあります。Windows SDK の一部です。私のマシンには、たとえばC:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\x64
. 次に、コード内で、適切なパラメーターを使用して実行可能ファイルを実行するプロセスを開始できます。
Bouncy Castle APIを確認できます。C# を使用して証明書を生成するために使用できます。
まず第一に、組織内にカスタム PKI 階層がない限り、自己署名証明書で文書に署名しても意味がありません (後者の場合、自分が何をしているのかをよく知る必要がありますが、そうではないようです)。
PFX は、関連付けられた秘密キーを持つ 1 つ以上の証明書のコンテナーです。したがって、「PFX ファイル」を生成しません。キーペアを生成し、証明書を作成します。証明書は、PFX ファイルまたは他の形式にエクスポートできます。
前述のように、BouncyCastle は証明書を生成できます。また、SecureBlackbox ライブラリも証明書を生成し、それらをさまざまな形式に保存およびロードできます。
これにはOpenSSL.NETライブラリを使用できます。
これを行う方法のコード例を次に示します。
public X509Certificate2 GeneratePfxCertificate(string certificatePath, string privateKeyPath,
string certificatePfxPath, string rootCertificatePath, string pkcs12Password)
{
string keyFileContent = File.ReadAllText(privateKeyPath);
string certFileContent = File.ReadAllText(certificatePath);
string rootCertFileContent = File.ReadAllText(rootCertificatePath);
var certBio = new BIO(certFileContent);
var rootCertBio = new BIO(rootCertFileContent);
CryptoKey cryptoKey = CryptoKey.FromPrivateKey(keyFileContent, string.Empty);
var certificate = new OpenSSL.X509.X509Certificate(certBio);
var rootCertificate = new OpenSSL.X509.X509Certificate(rootCertBio);
using (var certChain = new Stack<OpenSSL.X509.X509Certificate> { rootCertificate })
using (var p12 = new PKCS12(pkcs12Password, cryptoKey, certificate, certChain))
using (var pfxBio = BIO.MemoryBuffer())
{
p12.Write(pfxBio);
var pfxFileByteArrayContent =
pfxBio.ReadBytes((int)pfxBio.BytesPending).Array;
File.WriteAllBytes(certificatePfxPath, pfxFileByteArrayContent);
}
return new X509Certificate2(certificatePfxPath, pkcs12Password);
}
@David Clarkeの回答が参照しているようなmakecertについて読むと、要件を満たすことがわかります.NETで書かれた管理されたmakecertが必要です。
幸いなことに、Mono の連中はずっと前にこれを実装していました。
https://github.com/mono/mono/blob/master/mcs/tools/security/makecert.cs