C#如何使用PGP公钥简单加密文本文件? [英] C# How to simply encrypt a text file with a PGP Public Key?

查看:977
本文介绍了C#如何使用PGP公钥简单加密文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经研究了一些关于如何实现我在问题中所说的内容,并发现了几个API,但是大多数API看起来很复杂,而且由于我只是一个noobie在这个领域,我只想要一个简单的方法,如:

  public String Encrypt(String message,PublicKey publicKey)

不知道是否可以完成?如果没有,请有人开启我另一种方式来实现这一点:)



谢谢。



更新: / p>

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

解决方案

我发现了一个教程这里,但它需要密钥和公钥来加密数据。但是,我修改了一些代码,只需要公钥(无签名,不压缩),并认为我应该发布在这里,以防万一有人也在寻找这个问题的解决方案。 Belows是修改的代码,作者的所有学分 - Kim先生。

  public class PgpEncrypt 
{
private PgpEncryptionKeys m_encryptionKeys;
private const int BufferSize = 0x10000;
///< summary>
///使用初始化的PgpEncryptionKeys实例化一个新的PgpEncrypt类。
///< / summary>
///< param name =encryptionKeys>< / param>
///< exception cref =ArgumentNullException> encryptionKeys为null< / exception>
public PgpEncrypt(PgpEncryptionKeys encryptionKeys)
{
if(encryptionKeys == null)
{
throw new ArgumentNullException(encryptionKeys,encryptionKeys为null ;
}
m_encryptionKeys = encryptionKeys;
}
///< summary>
///加密并签名unencryptedFileInfo指向的文件,
///将加密内容写入outputStream。
///< / summary>
///< param name =outputStream>当此方法返回时,将包含
///加密数据的流。< / param>
///< param name =fileName>要加密的文件的FileInfo< / param>
public void Encrypt(Stream outputStream,FileInfo unencryptedFileInfo)
{
if(outputStream == null)
{
throw new ArgumentNullException(outputStream,outputStream is空值。);
}
if(unencryptedFileInfo == null)
{
throw new ArgumentNullException(unencryptedFileInfo,unencryptedFileInfo is null);
}
if(!File.Exists(unencryptedFileInfo.FullName))
{
throw new ArgumentException(File to encrypt not found。
使用(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();
返回pgpLiteralDataGenerator.Open(encryptedOut,PgpLiteralData.Binary,

文件);
}
}

当然要运行这些代码,你必须包括<您的项目中有一个href =http://www.bouncycastcast.org/csharp/ =noreferrer> BouncyCastle库。

我已经测试过加密然后再解密运行正常:)


I've researched a bit about how to achieve what I said in the question and found several APIs but most of them look very complicated and since I'm just a noobie in this area I just want a simple method like:

public String Encrypt(String message, PublicKey publicKey)

Don't know if this can be done? If not then please someone enlighten me another way to achieve this :)

Thank you.

UPDATE:

So far I have only seen that all of the library for OpenPGP encryption require both the public key and private key to do the encrypt while I only want to encrypt with the public key (because I don't have the private key to use it)!

解决方案

I found a tutorial here but it requires both Secret Key and Public Key to encrypt data. However I've modified the codes a bit to only require public key (no signing, no compress) and thought I should publish it here in case anyone also looking for a solution for this question. Belows is the modified codes, all the credits for the author - Mr. Kim.

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

Of course to run these codes you have to include BouncyCastle library in your project.
I've tested encrypting and then decrypting and it runs fine :)

这篇关于C#如何使用PGP公钥简单加密文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆