2013年8月25日 星期日

[C#]Bouncy Castle C# API(一) 產生 PGP 的 Public 及 Private key 方法

Bouncy Castle C# API  提供免費的 PGP(Pretty Good Privacy) 加密、數位簽章、數位認證等功能。
我們就從最一開始如何產生  Bouncy Castle 公私鑰( Public 、 Private  key)並保存成檔案開始說起 。
本文是利用 Bouncy Castle官網 下載的 bccrypto-net-1.7-bin.zin 以及  bccrypto-net-1.7-src.zip 進行示範,src.zip 壓縮檔裡面包含官網的範例程式可提供給各位參考。
而此篇就是利用 官網範例 RsaKeyRingGenerator 改寫而成。
1.首先在專案的 Reference 下 滑鼠點選又見 add Reference ,點選 Browers 選擇  bccrypto-net-1.7-bin 解壓縮的資料夾下 BouncyCastle.Crypto.dll 按下確定。這樣即可使用 Bouncy Castle 的 API 了。
2. 接下來利用  bccrypto-net-1.7-src RsaKeyRingGenerator Example 撰寫的 Method 即可完成這次的功能。
3. 接著我們撰寫產生 PGP publica key 以及 private key 的檔案 method  ,程式如下:

 
   private static void ExportKeyPair(
       Stream secretOut,
       Stream publicOut,
       AsymmetricKeyParameter publicKey,
       AsymmetricKeyParameter privateKey,
       string identity,
       char[] passPhrase,
       bool armor)
   {
       if (armor)
       {
           secretOut = new ArmoredOutputStream(secretOut);
       }
       PgpSecretKey secretKey = new PgpSecretKey(
           PgpSignature.DefaultCertification,
           PublicKeyAlgorithmTag.RsaGeneral,
           publicKey,
           privateKey,
           DateTime.UtcNow,
           identity,
           SymmetricKeyAlgorithmTag.Cast5,
           passPhrase,
           null,
           null,
           new SecureRandom()
           );
       secretKey.Encode(secretOut);
       if (armor)
       {
           secretOut.Close();
           publicOut = new ArmoredOutputStream(publicOut);
       }
       PgpPublicKey key = secretKey.PublicKey;
       key.Encode(publicOut);
       if (armor)
       {
           publicOut.Close();
       }
   }
傳入參數依序如下
(1) Private key 的 FileStream ,
(2) Public key 的 FileStream, 
(3) 由  Bouncy Castle  產生的 publuic Key , 
(4) 由 Bouncy Castle產生的 private key , 
(5) 使用者名稱 String , 
(6) armor 不明.......範例設為true

4. 產生 Public Private Key 以及呼叫 ExportKeyPair 程式寫法如下:
static void Main(string[] args)
{
           //RSA密鑰產生器
           IAsymmetricCipherKeyPairGenerator kpg = GeneratorUtilities.GetKeyPairGenerator("RSA");
           //Key 構造使用參數        
           kpg.Init(new RsaKeyGenerationParameters(
                  BigInteger.ValueOf(0x10001), new SecureRandom(),
           1024,// key 的長度
            25));
           AsymmetricCipherKeyPair kp = kpg.GenerateKeyPair();
           char[] password = "123456".ToCharArray(); //私鑰的密碼
           Stream out1, out2;
           out1 = File.Create(@"D:\BC\priv.asc");//私鑰放置位置          
           out2 = File.Create(@"D:\BC\pub.asc"); //公鑰放置位置
           ExportKeyPair(out1, out2, kp.Public,                 
           kp.Private, "Jama", password, true);
}

這樣即可簡單產生一組 RSA 的公私鑰檔案 在 D:\BC 目錄下,方便以後專案使用了。

1 則留言:

  1. 想請問一下,如果是要做HSM的PKCS7有沒有什麼合適的資料可以參考?
    另外目前所知道的公私鑰檔案都是放在HSM內,Bouncy Castle要如何取得然後做PKCS7的加解密呢?
    謝謝

    回覆刪除