使用BouncyCastle PGP解密文件的例外情况

时间:2012-12-03 07:57:20

标签: c# console-application bouncycastle encryption pgp

我试图使用名为PgpDecrypt的类解密客户端提供的此示例文件。但是当代码出现在这一行时:

Stream clear = pbe.GetDataStream(privKey);

它会返回错误:异常解密密钥

这是我的解密代码:

PgpDecrypt test = new PgpDecrypt(string.Concat(pathh, "TestDecryptionFile"),
                                             string.Concat(pathh, "mypgpprivatekey.key"),
                                             "mypassphrase",
                                             @"d:/test/",
                                             string.Concat(pathh, "clientpublickey.key"));

FileStream fs = File.Open(string.Concat(pathh, "TestDecryptionFile"), FileMode.Open);
test.Decrypt(fs, @"d:\test\");

我使用BouncyCastle作为.NET的第三方库。

任何解决这个问题的想法都会有很大的帮助。提前谢谢!

1 个答案:

答案 0 :(得分:5)

如果您正在关注BouncyCastle类PGPEncrypt,PGPDecrypt和PGPEncryptionKeys ......

在PGPEncryptionKeys类下,添加此方法:

/// <summary>
/// Return the last key we can use to decrypt.
/// Note: A file can contain multiple keys (stored in "key rings")
/// </summary>
private PgpSecretKey GetLastSecretKey(PgpSecretKeyRingBundle secretKeyRingBundle)
{
    return (from PgpSecretKeyRing kRing in secretKeyRingBundle.GetKeyRings()
            select kRing.GetSecretKeys().Cast<PgpSecretKey>()
                                            .LastOrDefault(k => k.IsSigningKey))
                                            .LastOrDefault(key => key != null);
}

仍然在PgpEncryptionKeys类中,确保ReadSecretKey方法如下所示:

private PgpSecretKey ReadSecretKey(string privateKeyPath, bool toEncrypt)
{
    using (Stream keyIn = File.OpenRead(privateKeyPath))
    using (Stream inputStream = PgpUtilities.GetDecoderStream(keyIn))
    {
        PgpSecretKeyRingBundle secretKeyRingBundle = new PgpSecretKeyRingBundle(inputStream);
        PgpSecretKey foundKey = toEncrypt ? GetFirstSecretKey(secretKeyRingBundle) : GetLastSecretKey(secretKeyRingBundle);

        if (foundKey != null)
            return foundKey;
    }
    throw new ArgumentException("Can't find signing key in key ring.");
}

^ _ ^