首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#如何简单地使用PGP公钥加密文本文件?

C#如何简单地使用PGP公钥加密文本文件?
EN

Stack Overflow用户
提问于 2010-11-16 16:33:23
回答 4查看 63.8K关注 0票数 27

我研究了一下如何实现我在问题中所说的内容,找到了几个API,但它们中的大多数看起来都非常复杂,因为我在这方面只是一个新手,所以我只想要一个简单的方法,比如:

代码语言:javascript
复制
public String Encrypt(String message, PublicKey publicKey)

不知道这是不是可以做到?如果不是,请有人告诉我实现这一点的另一种方法:)

谢谢。

更新:

到目前为止,我只看到所有用于OpenPGP加密的库都需要公钥和私钥来进行加密,而我只想使用公钥进行加密(因为我没有私钥来使用它)!

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2010-11-17 14:41:45

我找到了一个教程here,但它同时需要私钥和公钥来加密数据。然而,我对代码做了一些修改,只需要公钥(不需要签名,不需要压缩),我想我应该在这里发布它,以防有人也在寻找这个问题的解决方案。下面是修改后的代码,所有的字幕都是作者- Kim先生的。

代码语言:javascript
复制
public class PgpEncrypt
    {
        private PgpEncryptionKeys m_encryptionKeys;
        private const int BufferSize = 0x10000; 
        /// <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 Encrypt(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 literalOut = ChainLiteralOut(encryptedOut, unencryptedFileInfo))
                using (FileStream inputFile = unencryptedFileInfo.OpenRead())
                {
                    WriteOutput(literalOut, inputFile);
                }
            }
        }

        private static void WriteOutput(Stream literalOut,
            FileStream inputFile)
        {
            int length = 0;
            byte[] buf = new byte[BufferSize];
            while ((length = inputFile.Read(buf, 0, buf.Length)) > 0)
            {
                literalOut.Write(buf, 0, length);
            }
        }

        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 ChainLiteralOut(Stream encryptedOut, FileInfo file)
        {
            PgpLiteralDataGenerator pgpLiteralDataGenerator = new PgpLiteralDataGenerator();
            return pgpLiteralDataGenerator.Open(encryptedOut, PgpLiteralData.Binary, 

file);
            } 
}

当然,要运行这些代码,您必须在项目中包含BouncyCastle library

我测试了加密和解密,它运行得很好:)

票数 13
EN

Stack Overflow用户

发布于 2010-11-16 17:43:26

你看过bouncycastle pgp了吗?http://www.bouncycastle.org/

这里有一个对取自BouncyCastle站点的文件进行加密的源代码示例:Need example for BouncyCastle PGP File encryption in C#

票数 7
EN

Stack Overflow用户

发布于 2020-06-10 21:35:27

如果您想在dotnet核心中进行加密和解密,这是我关注的文章:https://nightbaker.github.io/pgp/cryptography/.net/core/2019/02/08/pgp-encryption/

加密部分不需要私钥。

所有的作品都归原作者NightBaker所有。

代码语言:javascript
复制
Install-Package  BouncyCastle.NetCore
Install-Package  BouncyCastle.NetCoreSdk
代码语言:javascript
复制
public class Pgp
{
    public static void EncryptFile(
        string outputFileName,
        string inputFileName,
        string encKeyFileName,
        bool armor,
        bool withIntegrityCheck)
    {
        PgpPublicKey encKey = PgpExampleUtilities.ReadPublicKey(encKeyFileName);

        using (Stream output = File.Create(outputFileName))
        {
            EncryptFile(output, inputFileName, encKey, armor, withIntegrityCheck);
        }
    }

    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);
            }
        }
    }
}

public class PgpExampleUtilities
{
    internal static PgpPublicKey ReadPublicKey(string fileName)
    {
        using (Stream keyIn = File.OpenRead(fileName))
        {
            return ReadPublicKey(keyIn);
        }
    }

    internal static PgpPublicKey ReadPublicKey(Stream input)
    {
        PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(
            PgpUtilities.GetDecoderStream(input));

        //
        // we just loop through the collection till we find a key suitable for encryption, in the real
        // world you would probably want to be a bit smarter about this.
        //

        foreach (PgpPublicKeyRing keyRing in pgpPub.GetKeyRings())
        {
            foreach (PgpPublicKey key in keyRing.GetPublicKeys())
            {
                if (key.IsEncryptionKey)
                {
                    return key;
                }
            }
        }

        throw new ArgumentException("Can't find encryption key in key ring.");
    }


    internal static byte[] CompressFile(string fileName, CompressionAlgorithmTag algorithm)
    {
        MemoryStream bOut = new MemoryStream();
        PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(algorithm);
        PgpUtilities.WriteFileToLiteralData(comData.Open(bOut), PgpLiteralData.Binary,
            new FileInfo(fileName));
        comData.Close();
        return bOut.ToArray();
    }
}

用法:

代码语言:javascript
复制
Pgp.EncryptFile("Resources/output.txt", "Resources/input.txt", "Resources/publicKey.txt", true, true);
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/4192296

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档