/*文章 -> Session Key(對稱式) - > 文章加密 - - - - - -> 加密後的文章 * -> Session Key(對稱式) - > 公鑰(對方)加密 - - -> 加密後的Session Key */ //內部的實作參照官方範例 private static void EncryptFile( Stream outputStream, //加密後輸出檔案之資料流 string fileName, //欲加密檔案名稱位置 PgpPublicKey encKey, //接收方的公鑰(對方) bool armor, bool withIntegrityCheck /*完整性檢查*/) { if (armor) { outputStream = new ArmoredOutputStream(outputStream); //位置、headers、雜湊表 } try { byte[] bytes = PgpExampleUtilities.CompressFile(fileName, CompressionAlgorithmTag.Zip); //資料壓縮一個檔案 PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom()); //隨機產生Session Key(對稱-Cast5) encGen.AddMethod(encKey); Stream cOut = encGen.Open(outputStream, bytes.Length); //建立 todo 注意,RSA非對稱加密,公鑰加密私鑰解密,預設為SHA1,但可選擇 SHA256雜湊 cOut.Write(bytes, 0, bytes.Length); //加密及寫入 cOut.Close(); if (armor) { outputStream.Close(); outputStream.Dispose(); } } catch (PgpException e) { Console.Error.WriteLine(e); Exception underlyingException = e.InnerException; if (underlyingException != null) { Console.Error.WriteLine(underlyingException.Message); Console.Error.WriteLine(underlyingException.StackTrace); } } }
//內部的實作參照官方範例 private static void EncryptFile( Stream outputStream, string fileName, PgpPublicKey encKey, bool armor, bool withIntegrityCheck) { if (armor) { outputStream = new ArmoredOutputStream(outputStream); } try { byte[] bytes = PgpExampleUtilities.CompressFile(fileName, CompressionAlgorithmTag.Zip); PgpEncryptedDataGenerator encGen = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom()); encGen.AddMethod(encKey); Stream cOut = encGen.Open(outputStream, bytes.Length); cOut.Write(bytes, 0, bytes.Length); cOut.Close(); if (armor) { outputStream.Close(); } } catch (PgpException e) { Console.Error.WriteLine(e); Exception underlyingException = e.InnerException; if (underlyingException != null) { Console.Error.WriteLine(underlyingException.Message); Console.Error.WriteLine(underlyingException.StackTrace); } } }