Bouncycastle PGP 解密期间的 PartialInputStream

发布于 2024-11-01 01:47:33 字数 1917 浏览 4 评论 0原文

我正在尝试解密刚刚使用​​ bouncycastle 加密的文件,但出现此异常:

Premature end of stream in PartialInputStream

我正在使用 bouncycastle 中的示例代码,并且没有更改任何内容。

当我使用这段代码进行加密时,我得到了这个:

private static byte[] EncryptFile(byte[] clearData, string fileName, PgpPublicKey encKey, bool withIntegrityCheck)
{
    MemoryStream encOut = new MemoryStream();
    try
    {
        MemoryStream bOut = new MemoryStream();

        PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip );

        //PgpUtilities.WriteFileToLiteralData(
        //    comData.Open(bOut),
        //    PgpLiteralData.Binary,
        //    new FileInfo(fileName));
        Stream cos = comData.Open(bOut);
        PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();

        Stream pOut = lData.Open(
            cos,
            PgpLiteralData.Binary,
            fileName,
            clearData.Length,
            DateTime.UtcNow
            );

        lData.Close();
        comData.Close();

        PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom() );

        cPk.AddMethod(encKey);

        byte[] bytes = bOut.ToArray();

        Stream os = encOut;

        Stream cOut = cPk.Open(os, bytes.Length);
        cOut.Write(bytes, 0, bytes.Length);
        cOut.Close();

        encOut.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);
        }
    }
    return encOut.ToArray();
}

我认为它与 PgpLiteralDataGenerator 有关。 但我需要使用它,因为我想加密字节数组中的数据,而不是文件中的数据。还有其他方法可以做到这一点吗?

I am tryng to decrypt a file I just encrypted using bouncycastle, but im getting this exception:

Premature end of stream in PartialInputStream

I am using the example code from bouncycastle and haven't changed anything.

I'm getting this when I use this code for encryption:

private static byte[] EncryptFile(byte[] clearData, string fileName, PgpPublicKey encKey, bool withIntegrityCheck)
{
    MemoryStream encOut = new MemoryStream();
    try
    {
        MemoryStream bOut = new MemoryStream();

        PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator( CompressionAlgorithmTag.Zip );

        //PgpUtilities.WriteFileToLiteralData(
        //    comData.Open(bOut),
        //    PgpLiteralData.Binary,
        //    new FileInfo(fileName));
        Stream cos = comData.Open(bOut);
        PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();

        Stream pOut = lData.Open(
            cos,
            PgpLiteralData.Binary,
            fileName,
            clearData.Length,
            DateTime.UtcNow
            );

        lData.Close();
        comData.Close();

        PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator( SymmetricKeyAlgorithmTag.Cast5, withIntegrityCheck, new SecureRandom() );

        cPk.AddMethod(encKey);

        byte[] bytes = bOut.ToArray();

        Stream os = encOut;

        Stream cOut = cPk.Open(os, bytes.Length);
        cOut.Write(bytes, 0, bytes.Length);
        cOut.Close();

        encOut.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);
        }
    }
    return encOut.ToArray();
}

I think it has something to do with the PgpLiteralDataGenerator.
But I need to use it because I want to encrypt data from a byte array, not from a file. Is there some other way to do this?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

拧巴小姐 2024-11-08 01:47:33

任何正在努力的人都会收到一个工作代码:

using System;
using System.Xml;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Text;

using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Bcpg;

class Program
{
    private static PgpPublicKey ReadPublicKey(Stream inputStream)
    {

        inputStream = PgpUtilities.GetDecoderStream(inputStream);

        PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream);

        //
        // 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.
        //

        //
        // iterate through the key rings.
        //

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

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

    private static byte[] EncryptFile(byte[] clearData, string fileName, PgpPublicKey encKey, bool withIntegrityCheck)
    {

        MemoryStream bOut = new MemoryStream();

        PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
            CompressionAlgorithmTag.Zip);

        Stream cos = comData.Open(bOut); // open it with the final destination
        PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();

        // we want to Generate compressed data. This might be a user option later,
        // in which case we would pass in bOut.
        Stream pOut = lData.Open(
            cos,                    // the compressed output stream
            PgpLiteralData.Binary,
            fileName,               // "filename" to store
            clearData.Length,       // length of clear data
            DateTime.UtcNow         // current time
        );

        pOut.Write(clearData, 0, clearData.Length);

        lData.Close();
        comData.Close();

        PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());

        cPk.AddMethod(encKey);

        byte[] bytes = bOut.ToArray();

        MemoryStream encOut = new MemoryStream();
        Stream os = encOut;

        Stream cOut = cPk.Open(os, bytes.Length);
        cOut.Write(bytes, 0, bytes.Length);  // obtain the actual bytes from the compressed stream
        cOut.Close();

        encOut.Close();

        return encOut.ToArray();
    }

    static void Main(string[] args)
    {
        try
        {
            byte[] dataBytes = File.ReadAllBytes("test.xml");
            Stream keyIn = File.OpenRead("cert.asc");
            Stream outStream = File.Create("data.bpg");
            byte[] encrypted = EncryptFile(dataBytes, "data", ReadPublicKey(keyIn), false);
            outStream.Write(encrypted, 0, encrypted.Length);
            keyIn.Close();
            outStream.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.ReadLine();
    }
}

Anybody who is struggeling heres a working code:

using System;
using System.Xml;
using System.IO;
using System.Security.Cryptography;
using System.Security.Cryptography.Xml;
using System.Text;

using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Bcpg;

class Program
{
    private static PgpPublicKey ReadPublicKey(Stream inputStream)
    {

        inputStream = PgpUtilities.GetDecoderStream(inputStream);

        PgpPublicKeyRingBundle pgpPub = new PgpPublicKeyRingBundle(inputStream);

        //
        // 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.
        //

        //
        // iterate through the key rings.
        //

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

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

    private static byte[] EncryptFile(byte[] clearData, string fileName, PgpPublicKey encKey, bool withIntegrityCheck)
    {

        MemoryStream bOut = new MemoryStream();

        PgpCompressedDataGenerator comData = new PgpCompressedDataGenerator(
            CompressionAlgorithmTag.Zip);

        Stream cos = comData.Open(bOut); // open it with the final destination
        PgpLiteralDataGenerator lData = new PgpLiteralDataGenerator();

        // we want to Generate compressed data. This might be a user option later,
        // in which case we would pass in bOut.
        Stream pOut = lData.Open(
            cos,                    // the compressed output stream
            PgpLiteralData.Binary,
            fileName,               // "filename" to store
            clearData.Length,       // length of clear data
            DateTime.UtcNow         // current time
        );

        pOut.Write(clearData, 0, clearData.Length);

        lData.Close();
        comData.Close();

        PgpEncryptedDataGenerator cPk = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.Cast5, new SecureRandom());

        cPk.AddMethod(encKey);

        byte[] bytes = bOut.ToArray();

        MemoryStream encOut = new MemoryStream();
        Stream os = encOut;

        Stream cOut = cPk.Open(os, bytes.Length);
        cOut.Write(bytes, 0, bytes.Length);  // obtain the actual bytes from the compressed stream
        cOut.Close();

        encOut.Close();

        return encOut.ToArray();
    }

    static void Main(string[] args)
    {
        try
        {
            byte[] dataBytes = File.ReadAllBytes("test.xml");
            Stream keyIn = File.OpenRead("cert.asc");
            Stream outStream = File.Create("data.bpg");
            byte[] encrypted = EncryptFile(dataBytes, "data", ReadPublicKey(keyIn), false);
            outStream.Write(encrypted, 0, encrypted.Length);
            keyIn.Close();
            outStream.Close();
        }
        catch (Exception e)
        {
            Console.WriteLine(e.Message);
        }

        Console.ReadLine();
    }
}
泡沫很甜 2024-11-08 01:47:33

当我尝试从“流”中读取时,我遇到了同样的错误。

PgpLiteralData ld = (PgpLiteralData)message;
var stream = ld.GetInputStream(); // the stream to read form

我的解决方案是将流复制到新的 .net Stream 对象
就像MemoryStream。然后从内存流对象中读取。

因此,我的基本流类型与 Org.BouncyCastle.Bcp​​g 流类型无关。

I got the same error, when I tried to read from the 'stream'.

PgpLiteralData ld = (PgpLiteralData)message;
var stream = ld.GetInputStream(); // the stream to read form

A solution for me was to copy the stream to a new .net Stream object
like MemoryStream. And after that read from the memoryStream object.

So, my base stream type has nothing to do with Org.BouncyCastle.Bcpg stream types.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文