Когда я пытаюсь обновить BouncyCastle.Cryptography до версии 2.0.0 или более поздней в своем проекте (консольное приложение, .net 6.0), этот код выдает ошибку в классе PGPEncryptDecrypt этого решения Decrypt< /code> с использованием ввода Stream. В частности, он выдает ошибку в последней строке приведенного ниже фрагмента кода
.
Код: Выделить всё
if (message is PgpCompressedData)
{
PgpCompressedData cData = (PgpCompressedData)message;
PgpObjectFactory of = null;
using (Stream compDataIn = cData.GetDataStream())
{
of = new PgpObjectFactory(compDataIn);
}
message = of.NextPgpObject();
//...
}
Когда я возвращаюсь к версии 1.9.0, код снова работает как положено. Я искал примеры кода C#, использующие версию 2.0.0 или более позднюю, но не нашел ни одного. В ходе поиска я зашел на сайт jumpycastle.org и увидел в примечаниях к выпуску, что версия 2.0.0 и более поздние содержат критические изменения. Однако у меня недостаточно знаний, чтобы знать, как изменить класс PGPEncrtypDecrypt, чтобы он работал с версией 2.0.0 и более поздних версий.
Что необходимо изменить в классах, приведенных в верхний ответ для https://stackoverflow.com/questions/102 ... nd-decrypt", чтобы он работал с BouncyCastle.Cryptography 2.0.0. Я хотел бы использовать последнюю версию, которая на момент написания этого сообщения — 2.2.1.
Используя код из ответа Хамди, мой текущий тестовый код:
Код: Выделить всё
using Org.BouncyCastle.Bcpg.OpenPgp;
using Org.BouncyCastle.Utilities.IO;
using Org.BouncyCastle.Utilities.Zlib;
namespace TestingPGP
{
static class Program
{
string inputfile = @"d:\Testing\EncryptedFile.gpg";
string outputFile = @"d:\Testing\DecryptedFile.gpg";
string privateKeyFile = @"d:\Testing\MyPrivateKey.asc";
string passPhrase = "hereismypassphrase";
byte[] plainBytes = null;
PgpPublicKeyEncryptedData pbe = null;
PgpObjectFactory pgpF = null;
PgpEncryptedDataList enc = null;
PgpObject o = null;
PgpPrivateKey privateKey = null;
PgpSecretKeyRingBundle pgpSec = null;
PgpObjectFactory plainFact = null;
using (Stream inputStream = File.OpenRead(inputfile))
{
using (Stream privateKeyStream = File.OpenRead(privateKeyFile))
{
pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
// find secret key
pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));
if (pgpF != null)
{
o = pgpF.NextPgpObject();
}
// the first object might be a PGP marker packet.
if (o is PgpEncryptedDataList)
{
enc = (PgpEncryptedDataList)o;
}
else
{
enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
}
// decrypt
foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
{
privateKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray());
if (privateKey != null)
{
pbe = pked;
break;
}
}
if (privateKey == null)
{
throw new ArgumentException("Secret key for message not found.");
}
else
{
using (Stream stream = pbe.GetDataStream(privateKey))
{
// To avoid Cannot Access a closed stream
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
plainBytes = memoryStream.ToArray();
}
}
//plainFact = new PgpObjectFactory(stream);
plainFact = new PgpObjectFactory(plainBytes);
// how to uncompress plainFact and save in file here
PgpObject message = plainFact.NextPgpObject();
if (message is PgpCompressedData)
{
PgpCompressedData cData = (PgpCompressedData)message;
PgpObjectFactory of = null;
using (Stream compDataIn = cData.GetDataStream())
{
of = new PgpObjectFactory(compDataIn);
}
//The next line will generate an exception
message = of.NextPgpObject();
if (message is PgpOnePassSignatureList)
{
message = of.NextPgpObject();
PgpLiteralData Ld = null;
Ld = (PgpLiteralData)message;
using (Stream output = File.Create(outputFile))
{
Stream unc = Ld.GetInputStream();
Streams.PipeAll(unc, output);
}
}
else
{
PgpLiteralData Ld = null;
Ld = (PgpLiteralData)message;
using (Stream output = File.Create(outputFile))
{
Stream unc = Ld.GetInputStream();
Streams.PipeAll(unc, output);
}
}
}
}
}
}
}
}
private static PgpPrivateKey FindSecretKey(PgpSecretKeyRingBundle pgpSec, long keyId, char[] pass)
{
PgpSecretKey pgpSecKey = pgpSec.GetSecretKey(keyId);
if (pgpSecKey == null)
{
return null;
}
return pgpSecKey.ExtractPrivateKey(pass);
}
}
Подробнее здесь: https://stackoverflow.com/questions/767 ... -and-later