I am having difficulties with decryption of a GPG file using Bouncy Castle. I have the encrypted file and I have a private key and the password for the private key. I can successfully decrypt the file using the desktop software GPG4win Kleopatra so I have the correct private key and the gpg file is valid.
However when our application reaches the line of code which attempts to decrypt the data with Bouncy Castle, I receive this error:
Unable to cast object of type 'Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters' to type 'Org.BouncyCastle.Crypto.Parameters.ElGamalKeyParameters'.
I am decrypting the same file using the same private key with Kleopatra so this has got to be something I can resolve by perhaps changing the private key file to the expected format or setting some options in Bouncy Castle.
The private key file is a plain text file beginning with the lines:
-----BEGIN PGP PRIVATE KEY BLOCK-----
Version: GnuPG v2.0.17 (MingW32)
Here is a flattened out version of the decryption code. Apologies if I have missed anything out:
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);
}
}
}
The exception occurs on this line:
Stream clearStream = myEncryptedData.GetDataStream(privateKey);
I hope you can suggest something for me to try. I can provide any further details I might have missed.
Thanks!