且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用PGP和C#加密和解密文件

更新时间:2023-02-17 16:23:12

您看上去有多努力?您是否尝试过Google?一个用于"PGP c#"的快速Google提供了三个.NET程序包,几乎无需付出任何努力.也许自己尝试一下?
How hard did you look? Did you try Google for example? A quick google for "PGP c#" gave three .NET packages, with almost no effort. Try it yourself, perhaps?


首先,不要回答"您自己的问题.如果要添加信息,请编辑原始帖子.

其次,发布所有代码无济于事.您只想发布不起作用的代码.

第三,您没有告诉我们什么是行不通的.当您发布不起作用的代码时,请告诉我们哪一行引发了错误以及它引发了什么错误.我们不在乎读者,我们也不会为您尝试您的代码.

除此之外,您还发布了以下代码:
First of all, don''t "answer" your own question. Edit the original post if you want to add information.

Secondly, posting all of your code does not help. You only want to post the code that isn''t working.

Thirdly, you didn''t tell us what wasn''t working. When you post the code that doesn''t work, tell us which line is throwing an error and what error it is throwing. We''re not mind readers, and we''re not going to try out your code for you.

To add to that, you posted this code:
private static void EncryptAndSign(string strPublicKeyFileName, string strPrivateKeyFileName, 
                                   string strFileToEncrypt)
{
   string PublicKeyFileName = strPublicKeyFileName;
   string PrivateKeyFileName = strPrivateKeyFileName;
   string EncryptedFileName = "EncryptedFile.txt";
   string FileToEncrypt = strFileToEncrypt;
   PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(PublicKeyFileName, 
                                                            PrivateKeyFileName, 
                                                            "vergeet10191");
   PgpEncrypt encrypter = new PgpEncrypt(encryptionKeys);
   using (Stream outputStream = File.Create(FileToEncrypt))
   {
      encrypter.EncryptAndSign(outputStream, new FileInfo(FileToEncrypt));
   }
}



为什么要以两个字符串作为输入,然后将它们存储在两个完全不同的字符串中而不保存它们呢?我在说:



Why do you take two strings as input, and then store them in two completely different strings without saving them? I''m talking about:

string PublicKeyFileName = strPublicKeyFileName;
string PrivateKeyFileName = strPrivateKeyFileName;



那完全是浪费内存.

无论如何,您需要告诉我们哪些行引发了错误以及什么是错误.



That''s a total waste of memory.

Anyway, you need to tell us which lines are throwing errors and what the errors are.


以及 PgpEncryptionKeys 类:

And the PgpEncryptionKeys class:

using System;
using System.IO;
using Org.BouncyCastle.Bcpg;
using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Security;
namespace Renaissance.Common.Encryption
{
    /// <summary>
    /// Wrapper around Bouncy Castle OpenPGP library.
    /// Bouncy documentation can be found here: http://www.bouncycastle.org/docs/pgdocs1.6/index.html
    /// </summary>
    public class PgpEncrypt
    {
        private PgpEncryptionKeys m_encryptionKeys;
        private const int BufferSize = 0x10000; // should always be power of 2
        /// <summary>
        /// Instantiate a new PgpEncrypt class with initialized PgpEncryptionKeys.
        /// </summary>
        /// <param name="encryptionKeys"></param>
        /// <exception cref="ArgumentNullException">encryptionKeys is null</exception>
        public PgpEncrypt(PgpEncryptionKeys encryptionKeys)
        {
            if (encryptionKeys == null)
                throw new ArgumentNullException("encryptionKeys", "encryptionKeys is null.");
            m_encryptionKeys = encryptionKeys;
        }
        /// <summary>
        /// Encrypt and sign the file pointed to by unencryptedFileInfo and
        /// write the encrypted content to outputStream.
        /// </summary>
        /// <param name="outputStream">The stream that will contain the
        /// encrypted data when this method returns.</param>
        /// <param name="fileName">FileInfo of the file to encrypt</param>
        public void EncryptAndSign(Stream outputStream, FileInfo unencryptedFileInfo)
        {
            if (outputStream == null)
                throw new ArgumentNullException("outputStream", "outputStream is null.");
            if (unencryptedFileInfo == null)
                throw new ArgumentNullException("unencryptedFileInfo", "unencryptedFileInfo is null.");
            if (!File.Exists(unencryptedFileInfo.FullName))
                throw new ArgumentException("File to encrypt not found.");
            using (Stream encryptedOut = ChainEncryptedOut(outputStream))
            using (Stream compressedOut = ChainCompressedOut(encryptedOut))
            {
                PgpSignatureGenerator signatureGenerator = InitSignatureGenerator(compressedOut);
                using (Stream literalOut = ChainLiteralOut(compressedOut, unencryptedFileInfo))
                using (FileStream inputFile = unencryptedFileInfo.OpenRead())
                {
                    WriteOutputAndSign(compressedOut, literalOut, inputFile, signatureGenerator);
                }
            }

        }
        private static void WriteOutputAndSign(Stream compressedOut,
            Stream literalOut,
            FileStream inputFile,
            PgpSignatureGenerator signatureGenerator)
        {
            int length = 0;
            byte[] buf = new byte[BufferSize];
            while ((length = inputFile.Read(buf, 0, buf.Length)) > 0)
            {
                literalOut.Write(buf, 0, length);
                signatureGenerator.Update(buf, 0, length);
            }
            signatureGenerator.Generate().Encode(compressedOut);
        }
        private Stream ChainEncryptedOut(Stream outputStream)
        {
            PgpEncryptedDataGenerator encryptedDataGenerator;
            encryptedDataGenerator =
                new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes,
                                              new SecureRandom());
            encryptedDataGenerator.AddMethod(m_encryptionKeys.PublicKey);
            return encryptedDataGenerator.Open(outputStream, new byte[BufferSize]);
        }
        private static Stream ChainCompressedOut(Stream encryptedOut)
        {
            PgpCompressedDataGenerator compressedDataGenerator =
                new PgpCompressedDataGenerator(CompressionAlgorithmTag.Zip);
            return compressedDataGenerator.Open(encryptedOut);
        }
        private static Stream ChainLiteralOut(Stream compressedOut, FileInfo file)
        {
            PgpLiteralDataGenerator pgpLiteralDataGenerator = new PgpLiteralDataGenerator();
            return pgpLiteralDataGenerator.Open(compressedOut, PgpLiteralData.Binary, file);
        }
        private PgpSignatureGenerator InitSignatureGenerator(Stream compressedOut)
        {
            const bool IsCritical = false;
            const bool IsNested = false;
            PublicKeyAlgorithmTag tag = m_encryptionKeys.SecretKey.PublicKey.Algorithm;
            PgpSignatureGenerator pgpSignatureGenerator =
                new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha1);
            pgpSignatureGenerator.InitSign(PgpSignature.BinaryDocument, m_encryptionKeys.PrivateKey);
            foreach (string userId in m_encryptionKeys.SecretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator subPacketGenerator =
                   new PgpSignatureSubpacketGenerator();
                subPacketGenerator.SetSignerUserId(IsCritical, userId);
                pgpSignatureGenerator.SetHashedSubpackets(subPacketGenerator.Generate());
                // Just the first one!
                break;
            }
            pgpSignatureGenerator.GenerateOnePassVersion(IsNested).Encode(compressedOut);
            return pgpSignatureGenerator;
        }
    }
}