C#Bouncy Castle Decrypt错误

时间:2016-06-30 16:02:52

标签: c# encryption bouncycastle

我从这个例子中取得了这一点。https://gist.github.com/dieseltravis/8323431

PgpObjectFactory中从不存在任何对象,不确定我的输入文件是否不正确?我不这么认为,因为如果我不压缩它,它看起来是加密的,文件大小是相同的。

//How I use it
DecryptPgpData(pathToFile.pgp);



public static string DecryptPgpData(string inputData)
    {
        string output;
        using (Stream inputStream = GetStream(inputData))
        {
            using (Stream keyIn = File.OpenRead(privateKeyFilePath))
            {
                output = DecryptPgpData(inputStream, keyIn, "thisisatest");
            }
        }
        return output;
    }


   public static Stream GetStream(string stringData)
    {
        MemoryStream stream = new MemoryStream();
        StreamWriter writer = new StreamWriter(stream);
        writer.Write(stringData);
        writer.Flush();
        stream.Position = 0;
        return stream;
    }


public static string DecryptPgpData(Stream inputStream, Stream privateKeyStream, string passPhrase)
    {
        string output;
 //This is factory object is not null
PgpObjectFactory pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
        // find secret key
        PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));

        //This always has a count of 0
        var all = pgpFactory.AllPgpObjects();
        //pgp object is always null
        PgpObject pgp = null;
        if (pgpFactory != null)
        {
            pgp = pgpFactory.NextPgpObject();
        }

        // the first object might be a PGP marker packet.
        PgpEncryptedDataList encryptedData = null;
        if (pgp is PgpEncryptedDataList)
        {
            encryptedData = (PgpEncryptedDataList)pgp;
        }
        else
        {
            encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject();
        }

       // encryptedData is always null at this point.Which causes exception at foreach
foreach (PgpPublicKeyEncryptedData pubKeyDataItem in encryptedData.GetEncryptedDataObjects())

我将阅读文件更改为流并且可以正常工作

public static string DecryptPgpData(string inputData)
{
    string output;
    using (Stream inputStream = File.OpenRead(inputData))//Changed This// GetStream(inputData))
    {
        using (Stream keyIn = File.OpenRead(privateKeyFilePath))
        {
            output = DecryptPgpData(inputStream, keyIn, "thisisatest");
        }
    }
    return output;
}

0 个答案:

没有答案