异常使用BouncyCastle的PGP解密文件(Exception on decrypting f

2019-07-04 09:54发布

我试图解密客户端提供此示例文件,使用一个名为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。

任何想法来解决,这将是一个很大的帮助。 提前致谢!

Answer 1:

如果你按照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.");
}

^ _ ^



文章来源: Exception on decrypting file using BouncyCastle PGP