如何使用PGP,Bouncing Castle实现流(密码)加密

时间:2015-02-23 19:54:59

标签: c# encryption stream bouncycastle

我对我的特定要求提出了挑战...我希望在旅途中对流进行加密,将每个数据块(在缓冲区中)传递给下一个进程,直到它最终被关闭/处置在最后一个过程之后。

我已经有一个使用Rijndael的实现。代码的逻辑基于这篇优秀的文章(http://www.codeproject.com/Articles/356297/Copy-a-Stream-with-Progress-Reporting

形成基础的方法是这样的:

/// <summary>
/// Copies the source stream into the current
/// </summary>
/// <param name="stream">The current stream</param>
/// <param name="source">The source stream</param>
/// <param name="bufferSize">Optional the size of buffer used for copying bytes</param>
/// <returns>The number of bytes actually copied.</returns>
public static long CopyFrom(this Stream stream, Stream source, int bufferSize = 4096)
{
    int count = 0;
    byte[] buffer = new byte[bufferSize];
    long length = 0;

    while ((count = source.Read(buffer, 0, bufferSize)) != 0)
    {
        length += count;
        stream.Write(buffer, 0, count);
    }

    return length;
}

我已经看到Bouncy Castle代码在PgpLiteralDataGenerator类中有以下Open方法:

        // encrypt - partial packet style.
        //
        SecureRandom rand = new SecureRandom();
        byte[] test = new byte[1233];

        rand.NextBytes(test);

        bOut = new UncloseableMemoryStream();

        comData = new PgpCompressedDataGenerator(
            CompressionAlgorithmTag.Zip);
        comOut = comData.Open(new UncloseableStream(bOut));

        lData = new PgpLiteralDataGenerator();
        ldOut = lData.Open(
            new UncloseableStream(comOut),
            PgpLiteralData.Binary,
            PgpLiteralData.Console,
            TestDateTime,
            new byte[16]);

        ldOut.Write(test, 0, test.Length);
        lData.Close();

        comData.Close();
        cbOut = new UncloseableMemoryStream();
        cPk = new PgpEncryptedDataGenerator(
            SymmetricKeyAlgorithmTag.Cast5, rand);

        cPk.AddMethod(pass);

        cOut = cPk.Open(new UncloseableStream(cbOut), new byte[16]);
        {
            byte[] tmp = bOut.ToArray();
            cOut.Write(tmp, 0, tmp.Length);
        }

        cPk.Close();

如果我想在块中加密/解密流然后在很晚之后关闭/处理流,这是正确的使用方法吗?

以4K的字节加密并将其传递到下一个进程,然后获取下一个4K字节...依此类推......允许逐个字节地加密流而不是一次性加密(大小可以变化从500到4GB)?

我也看过课堂上的考试:&#34; Org.BouncyCastle.Bcp​​g.OpenPgp.Tests.PgpPbeTest&#34;

我可能错了,但我认为答案就在那附近。有人在乎帮忙吗?对不起,留言很长。

0 个答案:

没有答案