使用BouncyCastle PGP解密文件的异常 [英] Exception on decrypting file using BouncyCastle PGP

查看:395
本文介绍了使用BouncyCastle PGP解密文件的异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试解密由客户端给出的示例文件,使用一个名为PgpDecrypt的类。但是当代码到这一行时:

I was trying to decrypt this sample file given by the client, using a class called PgpDecrypt. But when the code comes to this line:

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的第三方库。

I am using BouncyCastle as my third party library for .NET.

解决这个问题的任何想法将是一个很大的帮助。感谢提前!

Any idea to solve this would be a great help. Thanks in advance!

推荐答案

如果您遵循BouncyCastle类PGPEncrypt,PGPDecrypt和PGPEncryptionKeys ...

If you're following the BouncyCastle classes PGPEncrypt, PGPDecrypt and PGPEncryptionKeys...

在PGPEncryptionKeys类下,添加以下方法:

Under the PGPEncryptionKeys class, add this method:

/// <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方法如下所示: / p>

still inside the PgpEncryptionKeys class, make sure the ReadSecretKey method looks like this:

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.");
}

^ _ ^

这篇关于使用BouncyCastle PGP解密文件的异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆