Проблема с расшифровкой PGP с помощью BouncyCastle.Cryptography 2.0.0 и более поздних версийC#

Место общения программистов C#
Ответить Пред. темаСлед. тема
Anonymous
 Проблема с расшифровкой PGP с помощью BouncyCastle.Cryptography 2.0.0 и более поздних версий

Сообщение Anonymous »

У меня как программиста нет большого опыта работы с PGP. Для работы я использовал, ни в коем случае не измененные, классы, найденные в верхнем ответе для https://stackoverflow.com/questions/102 ... nd-decrypt" М.Бабкока в течение многих лет всякий раз, когда Мне нужно расшифровать или зашифровать файл. До этого момента я регулярно обновлял BouncyCastle.Cryptography до последней версии. В настоящее время мой рабочий код использует BouncyCastle.Cryptography версии 1.9.0.
Когда я пытаюсь обновить 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();
//...
}
Исключение возникает в строке message = of.NextPgpObject(): "System.ObjectDisposeException: 'Невозможно получить доступ к закрытому потоку. Имя объекта: 'ZLibStream'."< /p>
Когда я возвращаюсь к версии 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);
}
}
Я не знаю, как перейти от простого факта к сохраненному текстовому файлу, не вызывая исключения, сгенерированного в строке «message = of.NextPgpObject();»


Подробнее здесь: https://stackoverflow.com/questions/767 ... -and-later
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение
  • Itext7 - «Pkcs12Store» существует в BouncyCastle.Crypto и BouncyCastle.Cryptography в С#
    Anonymous » » в форуме C#
    0 Ответы
    72 Просмотры
    Последнее сообщение Anonymous
  • Как использовать библиотеку BouncyCastle FIPS вместе с библиотекой BouncyCastle.Cryptography?
    Anonymous » » в форуме C#
    0 Ответы
    58 Просмотры
    Последнее сообщение Anonymous
  • Как разблокировать файлы PGP Self Decrypting Archive .exe (PGP SDA) в Python с помощью известной парольной фразы?
    Anonymous » » в форуме Python
    0 Ответы
    15 Просмотры
    Последнее сообщение Anonymous
  • Исключено: 'isopoh.cryptography.securearray.lockfailexception' in isopoh.cryptography.securearray.dll
    Anonymous » » в форуме C#
    0 Ответы
    8 Просмотры
    Последнее сообщение Anonymous
  • Исключено: 'isopoh.cryptography.securearray.lockfailexception' in isopoh.cryptography.securearray.dll
    Anonymous » » в форуме C#
    0 Ответы
    10 Просмотры
    Последнее сообщение Anonymous

Вернуться в «C#»