private static void DecryptFile(
Stream inputStream,
Stream keyIn,
char[] passwd,
string tempDir)
{
inputStream = PgpUtilities.GetDecoderStream(inputStream);
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;
foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
{
sKey = FindSecretKey(keyIn, pked.KeyId, passwd);
if (sKey != null)
{
pbe = pked;
break;
}
}
// Iterator it = enc.GetEncryptedDataObjects();
//
// while (sKey == null && it.hasNext())
// {
// pbe = (PgpPublicKeyEncryptedData)it.next();
//
// sKey = FindSecretKey(keyIn, pbe.KeyID, passwd);
// }
if (sKey == null)
{
throw new ArgumentException("secret key for message not found.");
}
Stream clear = pbe.GetDataStream(sKey);
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 PgpOnePassSignatureList)
{
//throw new PgpException("encrypted message contains a signed message - not literal data.");
//
// file is signed!
//
// verify signature here if you want.
//
// PGPOnePassSignatureList p1 = (PGPOnePassSignatureList) message;
// PGPOnePassSignature ops = p1.get(0);
// etc…
message = plainFact.NextPgpObject();
}
if (message is PgpLiteralData)
{
PgpLiteralData ld = (PgpLiteralData)message;
//System.Diagnostics.EventLog.WriteEntry("PGPWrapper[Decrypt] DEBUG", "Decrypting to: " + ld.FileName);
using (FileStream fOut = File.Create(Path.Combine(tempDir, ld.FileName)))
{
//System.Diagnostics.EventLog.WriteEntry("PGPWrapper[Decrypt] DEBUG", "Decrypted to: " + fOut.Name);
Stream unc = ld.GetInputStream();
int ch;
while ((ch = unc.ReadByte()) >= 0)
{
fOut.WriteByte((byte)ch);
}
fOut.Close();
}
}
else
{
throw new PgpException("message is not a simple encrypted file - type unknown.");
}
if (pbe.IsIntegrityProtected())
{
if (!pbe.Verify())
{
Console.Error.WriteLine("message failed integrity check");
}
else
{
Console.Error.WriteLine("message integrity check passed");
}
}
else
{
Console.Error.WriteLine("no message integrity check");
}
}
catch (PgpException e)
{
Console.Error.WriteLine(e);
Exception underlyingException = e.InnerException;
if (underlyingException != null)
{
Console.Error.WriteLine(underlyingException.Message);
Console.Error.WriteLine(underlyingException.StackTrace);
}
}
}