我在使用 Bouncy Castle 解密 GPG 文件时遇到困难。我有加密的文件,我有一个私钥和私钥的密码。我可以使用桌面软件 GPG4win Kleopatra 成功解密文件,因此我拥有正确的私钥并且 gpg 文件有效。
但是,当我们的应用程序到达尝试使用 Bouncy Castle 解密数据的代码行时,我收到此错误:
Unable to cast object of type 'Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters' to type 'Org.BouncyCastle.Crypto.Parameters.ElGamalKeyParameters'.
我正在使用与 Kleopatra 相同的私钥解密同一个文件,所以这必须是我可以通过将私钥文件更改为预期格式或在 Bouncy Castle 中设置一些选项来解决的问题。
私钥文件是一个以以下行开头的纯文本文件:
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v2.0.17 (MingW32)
这是解密代码的扁平化版本。抱歉,如果我错过了什么:
PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(publicKey, privateKey, passPhrase);
Stream encryptedStream = new StreamReader(encryptedFileName).BaseStream;
Stream encodedFile = PgpUtilities.GetDecoderStream(inputStream);
PgpObjectFactory factory = new PgpObjectFactory(encodedFile);
PgpObject pgpObject = factory.NextPgpObject();
PgpEncryptedDataList encryptedDataList;
if (pgpObject is PgpEncryptedDataList)
{
encryptedDataList = (PgpEncryptedDataList)pgpObject;
}
else
{
encryptedDataList = (PgpEncryptedDataList)factory.NextPgpObject();
}
PgpPublicKeyEncryptedData myEncryptedData = null;
PgpPublicKeyEncryptedData publicKeyED = null;
foreach (PgpPublicKeyEncryptedData encryptedData in encryptedDataList.GetEncryptedDataObjects())
{
if (encryptedData != null)
{
myEncryptedData = encryptedData;
break;
}
}
Stream clearStream = myEncryptedData.GetDataStream(privateKey);
PgpObjectFactory clearFactory = new PgpObjectFactory(clearStream);
PgpObject message = clearFactory.NextPgpObject();
if (message is PgpCompressedData)
{
message = ProcessCompressedMessage(message);
PgpLiteralData literalData = (PgpLiteralData)message;
using (Stream outputFile = File.Create(outputFilePath))
{
using (Stream literalDataStream = literalData.GetInputStream())
{
Streams.PipeAll(literalDataStream, outputFile);
}
}
}
异常发生在这一行:
Stream clearStream = myEncryptedData.GetDataStream(privateKey);
我希望你能给我一些建议让我尝试。我可以提供我可能错过的任何进一步的细节。
谢谢!