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

ice*_*n31 3 c# encryption bouncycastle pgp console-application

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

Stream clear = pbe.GetDataStream(privKey);
Run Code Online (Sandbox Code Playgroud)

它返回一个错误: 异常解密密钥

这是我的解密代码:

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\");
Run Code Online (Sandbox Code Playgroud)

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

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

ice*_*n31 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);
}
Run Code Online (Sandbox Code Playgroud)

仍然在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.");
}
Run Code Online (Sandbox Code Playgroud)

^ _ ^