我已经在Java上看到了几个有关关闭流的线程。我只是不明白他们在做什么。一旦发现问题,我将再次将所有内容转换为uses。
是否可能因为我将私钥存储为字符串然后进行了转换?
public static MemoryStream StringToStream(string toConvert)
{
// convert string to stream
var byteArray = Encoding.Default.GetBytes(toConvert);
//byte[] byteArray = Encoding.ASCII.GetBytes(contents);
var stream = new MemoryStream(byteArray);
return stream;
}
我打算对此做一些改进,但是当我无法正常使用时,我基本上回到了此处发布的版本Original Post
public static byte[] DecryptBytes(byte[] inputData)
{
if(!PrivateKeyPopulated)
{ throw new Exception("PrivateKey Must be populated!!!");}
if (String.IsNullOrWhiteSpace(_passcode))
{ throw new Exception("Passcode Must be populated!!!"); }
byte[] error = Encoding.ASCII.GetBytes("ERROR");
Stream inputStream = new MemoryStream(inputData);
inputStream = PgpUtilities.GetDecoderStream(inputStream);
MemoryStream decoded = new MemoryStream();
try
{
PgpObjectFactory pgpF = new PgpObjectFactory(inputStream);
PgpEncryptedDataList enc;
PgpObject o = pgpF.NextPgpObject();
//
// the first object might be a PGP marker packet.
//
if (o is PgpEncryptedDataList)
enc = (PgpEncryptedDataList)o;
else
enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
//
// find the secret key
//
PgpPrivateKey sKey = null;
PgpPublicKeyEncryptedData pbe = null;
PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(
PgpUtilities.GetDecoderStream(PSS_PGPEncrypt.StringToStream(_privateKey)));
foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
{
sKey = FindSecretKey(pgpSec, pked.KeyId, _passcode.ToCharArray());
if (sKey != null)
{
pbe = pked;
break;
}
}
if (sKey == null)
throw new ArgumentException("secret key for message not found.");
Stream clear = pbe.GetDataStream(sKey);<------ KABOOOM
PgpObjectFactory plainFact = new PgpObjectFactory(clear);
PgpObject message = plainFact.NextPgpObject();
if (message is PgpCompressedData)
{
PgpCompressedData cData = (PgpCompressedData)message;
PgpObjectFactory pgpFact = new PgpObjectFactory(cData.GetDataStream());
message = pgpFact.NextPgpObject();
}
if (message is PgpLiteralData)
{
PgpLiteralData ld = (PgpLiteralData)message;
Stream unc = ld.GetInputStream();
Streams.PipeAll(unc, decoded);
}
else if (message is PgpOnePassSignatureList)
throw new PgpException("encrypted message contains a signed message - not literal data.");
else
throw new PgpException("message is not a simple encrypted file - type unknown.");
if (pbe.IsIntegrityProtected())
{
if (!pbe.Verify())
throw new Exception("PGP Error - Message failed integrity check.");
//else
//"Message integrity check passed.", "PGP Error"
}
else
{
//MessageBox.Show(null, "No message integrity check.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
return decoded.ToArray();
}