Example #1
0
        /// <summary>
        ///     Decrypts the Input File stream, given the Private Key File stream, to the specified Decrypted File Path.
        /// </summary>
        /// <param name="inputFileStream">File Stream of encrypted file.</param>
        /// <param name="privateKeyFileStream">File Stream of Private Key file.</param>
        /// <param name="password">Password that was used to encrypt the file.</param>
        /// <param name="decryptedFilePath">Full Path of the new decrypted file.</param>
        private static void DecryptFile(Stream inputFileStream, Stream privateKeyFileStream, string password, string decryptedFilePath)
        {
            inputFileStream = PgpUtilities.GetDecoderStream(inputFileStream);

            PgpObjectFactory     _pgpObjectFactory = new PgpObjectFactory(inputFileStream);
            PgpEncryptedDataList _pgpEncryptedDataList;

            PgpObject _pgpObject = _pgpObjectFactory.NextPgpObject();

            if (_pgpObject is PgpEncryptedDataList)
            {
                _pgpEncryptedDataList = (PgpEncryptedDataList)_pgpObject;
            }
            else
            {
                _pgpEncryptedDataList = (PgpEncryptedDataList)_pgpObjectFactory.NextPgpObject();
            }

            PgpPrivateKey             _pgpPrivateKey          = null;
            PgpPublicKeyEncryptedData _pgpPubKeyEncryptedData = null;
            PgpSecretKeyRingBundle    _pgpSecKeyRingBundle    = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyFileStream));

            foreach (PgpPublicKeyEncryptedData _pgpPubKeyEncData in _pgpEncryptedDataList.GetEncryptedDataObjects())
            {
                _pgpPrivateKey = PgpCustomUtilities.FindSecretKey(_pgpSecKeyRingBundle, _pgpPubKeyEncData.KeyId, password.ToCharArray());

                if (_pgpPrivateKey != null)
                {
                    _pgpPubKeyEncryptedData = _pgpPubKeyEncData;
                    break;
                }
            }

            if (_pgpPrivateKey == null)
            {
                throw new ArgumentException("Secret key for message not found.");
            }

            Stream _privateKeyFileStream = _pgpPubKeyEncryptedData.GetDataStream(_pgpPrivateKey);

            PgpObjectFactory _pgpObjectFactoryPrivateKey = new PgpObjectFactory(_privateKeyFileStream);

            //Unable to cast object of type 'Org.BouncyCastle.Bcpg.OpenPgp.PgpLiteralData' to type 'Org.BouncyCastle.Bcpg.OpenPgp.PgpCompressedData'
            //added in firstPgpObject so _pgpObjectMessage does not always default to compressed data type
            var       firstPgpObject    = _pgpObjectFactoryPrivateKey.NextPgpObject();
            PgpObject _pgpObjectMessage = null;

            if (firstPgpObject is PgpCompressedData)
            {
                PgpCompressedData _pgpCompressedData = (PgpCompressedData)_pgpObjectFactoryPrivateKey.NextPgpObject();
                PgpObjectFactory  _pgpObjectFactoryCompressedData = new PgpObjectFactory(_pgpCompressedData.GetDataStream());
                _pgpObjectMessage = _pgpObjectFactoryCompressedData.NextPgpObject();
            }
            else
            {
                _pgpObjectMessage = firstPgpObject;
            }


            if (_pgpObjectMessage is PgpLiteralData _pgpLiteralData)
            {
                FileInfo _decryptedFileInfo = new FileInfo(decryptedFilePath);

                string _outputFileName          = _decryptedFileInfo.Name;
                string _outputFileDirectoryPath = _decryptedFileInfo.DirectoryName;
                Stream _outputFileStream        = File.Create(Path.Combine(_outputFileDirectoryPath, _outputFileName));

                Stream _dataInputStream = _pgpLiteralData.GetInputStream();
                Streams.PipeAll(_dataInputStream, _outputFileStream);
                _outputFileStream.Dispose();
            }
            else if (_pgpObjectMessage is PgpCompressedData compressedData)
            {
                PgpObjectFactory of = null;

                using (Stream compressedDataInStream = compressedData.GetDataStream())
                {
                    of = new PgpObjectFactory(compressedDataInStream);
                }

                FileInfo _decryptedFileInfo = new FileInfo(decryptedFilePath);

                string _outputFileName          = _decryptedFileInfo.Name;
                string _outputFileDirectoryPath = _decryptedFileInfo.DirectoryName;
                Stream _outputFileStream        = File.Create(Path.Combine(_outputFileDirectoryPath, _outputFileName));

                _pgpObjectMessage = of.NextPgpObject();
                if (_pgpObjectMessage is PgpOnePassSignatureList)
                {
                    _pgpObjectMessage = of.NextPgpObject();
                    PgpLiteralData literalData = null;
                    literalData = (PgpLiteralData)_pgpObjectMessage;
                    Stream inputStream = literalData.GetInputStream();
                    Streams.PipeAll(inputStream, _outputFileStream);
                }
                else
                {
                    PgpLiteralData literalData = null;
                    literalData = (PgpLiteralData)_pgpObjectMessage;
                    Stream inputStream = literalData.GetInputStream();
                    Streams.PipeAll(inputStream, _outputFileStream);
                }
                _outputFileStream.Dispose();
            }
            else if (_pgpObjectMessage 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 (_pgpPubKeyEncryptedData.IsIntegrityProtected())
            {
                if (!_pgpPubKeyEncryptedData.Verify())
                {
                    throw new PgpException("Message failed integrity check.");
                }
            }
        }
    /**
     * Decrypt the byte array passed into inputData and return it as
     * another byte array.
     *
     * @param inputData - the data to decrypt
     * @param keyIn - a stream from your private keyring file
     * @param passCode - the password
     * @return - decrypted data as byte array
     */
    public static byte[] Decrypt(byte[] inputData, Stream keyIn, string passCode)
    {
        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(keyIn));
            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);
            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())
                {
                    MessageBox.Show(null, "Message failed integrity check.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                }
                else
                {
                    MessageBox.Show(null, "Message integrity check passed.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                }
            }
            else
            {
                MessageBox.Show(null, "No message integrity check.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return(error);
            }

            return(decoded.ToArray());
        }
        catch (Exception e)
        {
            if (e.Message.StartsWith("Checksum mismatch"))
            {
                MessageBox.Show(null, "Likely invalid passcode. Possible data corruption.", "Invalid Passcode", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (e.Message.StartsWith("Object reference not"))
            {
                MessageBox.Show(null, "PGP data does not exist.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else if (e.Message.StartsWith("Premature end of stream"))
            {
                MessageBox.Show(null, "Partial PGP data found.", "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            else
            {
                MessageBox.Show(null, e.Message, "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            Exception underlyingException = e.InnerException;
            if (underlyingException != null)
            {
                MessageBox.Show(null, underlyingException.Message, "PGP Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

            return(error);
        }
    }
        public static string DecryptPgpData(Stream inputStream, Stream privateKeyStream, string passPhrase)
        {
            string output;

            PgpObjectFactory pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
            // find secret key
            PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));

            PgpObject pgp = null;

            if (pgpFactory != null)
            {
                pgp = pgpFactory.NextPgpObject();
            }

            // the first object might be a PGP marker packet.
            PgpEncryptedDataList encryptedData = null;

            if (pgp is PgpEncryptedDataList)
            {
                encryptedData = (PgpEncryptedDataList)pgp;
            }
            else
            {
                encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject();
            }

            // decrypt
            PgpPrivateKey             privateKey = null;
            PgpPublicKeyEncryptedData pubKeyData = null;

            foreach (PgpPublicKeyEncryptedData pubKeyDataItem in encryptedData.GetEncryptedDataObjects())
            {
                privateKey = FindSecretKey(pgpKeyRing, pubKeyDataItem.KeyId, passPhrase.ToCharArray());

                if (privateKey != null)
                {
                    pubKeyData = pubKeyDataItem;
                    break;
                }
            }

            if (privateKey == null)
            {
                throw new ArgumentException("Secret key for message not found.");
            }

            PgpObjectFactory plainFact = null;

            using (Stream clear = pubKeyData.GetDataStream(privateKey))
            {
                plainFact = new PgpObjectFactory(clear);
            }

            PgpObject message = plainFact.NextPgpObject();

            if (message is PgpCompressedData)
            {
                PgpCompressedData compressedData       = (PgpCompressedData)message;
                PgpObjectFactory  pgpCompressedFactory = null;

                using (Stream compDataIn = compressedData.GetDataStream())
                {
                    pgpCompressedFactory = new PgpObjectFactory(compDataIn);
                }

                message = pgpCompressedFactory.NextPgpObject();
                PgpLiteralData literalData = null;
                if (message is PgpOnePassSignatureList)
                {
                    message = pgpCompressedFactory.NextPgpObject();
                }

                literalData = (PgpLiteralData)message;
                using (Stream unc = literalData.GetInputStream())
                {
                    output = IoHelper.GetString(unc);
                }
            }
            else if (message is PgpLiteralData)
            {
                PgpLiteralData literalData = (PgpLiteralData)message;
                using (Stream unc = literalData.GetInputStream())
                {
                    output = IoHelper.GetString(unc);
                }
            }
            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.");
            }

            return(output);
        }
Example #4
0
        /**
         * Decrypt the byte array passed into inputData and return it as
         * another byte array.
         *
         * @param inputData - the data to decrypt
         * @param keyIn - a stream from your private keyring file
         * @param passCode - the password
         * @return - decrypted data as byte array
         */

        public static byte[] Decrypt(byte[] inputData, Stream keyIn, string passCode)
        {
            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(keyIn));
                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);
                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())
                    {
                        Console.WriteLine("Message failed integrity check.", "PGP Error");
                    }
                    else
                    {
                        Console.WriteLine("Message integrity check passed.", "PGP Error");
                    }
                }
                else
                {
                    Console.WriteLine("No message integrity check.", "PGP Error");
                }

                return(decoded.ToArray());
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Example #5
0
        /*
         * decrypt a given stream.
         */

        public static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFile, Stream publicKeyStream)
        {
            try
            {
                bool deleteOutputFile = false;

                PgpEncryptedDataList      enc;
                PgpObject                 o    = null;
                PgpPrivateKey             sKey = null;
                PgpPublicKeyEncryptedData pbe  = null;

                var pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
                // find secret key
                var 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())
                {
                    sKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray());

                    if (sKey != null)
                    {
                        pbe = pked;
                        break;
                    }
                }

                if (sKey == null)
                {
                    throw new ArgumentException("Secret key for message not found.");
                }

                PgpObjectFactory plainFact = null;

                using (Stream clear = pbe.GetDataStream(sKey))
                {
                    plainFact = new PgpObjectFactory(clear);
                }

                PgpObject message = plainFact.NextPgpObject();

                if (message is PgpCompressedData)
                {
                    PgpCompressedData cData = (PgpCompressedData)message;
                    PgpObjectFactory  of    = null;

                    using (Stream compDataIn = cData.GetDataStream())
                    {
                        of = new PgpObjectFactory(compDataIn);
                    }

                    message = of.NextPgpObject();
                    if (message is PgpOnePassSignatureList)
                    {
                        PgpOnePassSignature ops = ((PgpOnePassSignatureList)message)[0];

                        PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream));

                        //USE THE BELOW TO CHECK FOR A FAILING SIGNATURE VERIFICATION.
                        //THE CERTIFICATE MATCHING THE KEY ID MUST BE IN THE PUBLIC KEY RING.
                        //long fakeKeyId = 3008998260528343108L;
                        //PgpPublicKey key = pgpRing.GetPublicKey(fakeKeyId);

                        PgpPublicKey key = pgpRing.GetPublicKey(ops.KeyId);

                        ops.InitVerify(key);

                        message = of.NextPgpObject();
                        PgpLiteralData Ld = null;
                        Ld = (PgpLiteralData)message;

                        //THE OUTPUT FILENAME WILL BE BASED ON THE INPUT PARAMETER VALUE TO THIS METHOD. IF YOU WANT TO KEEP THE
                        //ORIGINAL FILENAME, UNCOMMENT THE FOLLOWING LINE.
                        //if (!String.IsNullOrEmpty(Ld.FileName))
                        //    outputFile = Ld.FileName;

                        using (Stream output = File.Create(outputFile))
                        {
                            Stream dIn = Ld.GetInputStream();

                            int ch;
                            while ((ch = dIn.ReadByte()) >= 0)
                            {
                                ops.Update((byte)ch);
                                output.WriteByte((byte)ch);
                            }
                            output.Close();
                        }

                        PgpSignatureList p3       = (PgpSignatureList)of.NextPgpObject();
                        PgpSignature     firstSig = p3[0];
                        if (ops.Verify(firstSig))
                        {
                            Console.Out.WriteLine("signature verified.");
                        }
                        else
                        {
                            Console.Out.WriteLine("signature verification failed.");

                            //YOU MAY OPT TO DELETE THE OUTPUT FILE IN THE EVENT THAT VERIFICATION FAILS.
                            //FILE DELETION HAPPENS FURTHER DOWN IN THIS METHOD
                            //AN ALTERNATIVE IS TO LOG THESE VERIFICATION FAILURE MESSAGES, BUT KEEP THE OUTPUT FILE FOR FURTHER ANALYSIS
                            //deleteOutputFile = true;
                        }
                    }
                    else
                    {
                        PgpLiteralData Ld = null;
                        Ld = (PgpLiteralData)message;
                        using (Stream output = File.Create(outputFile))
                        {
                            Stream unc = Ld.GetInputStream();
                            Streams.PipeAll(unc, output);
                        }
                    }
                }
                else if (message is PgpLiteralData)
                {
                    PgpLiteralData ld          = (PgpLiteralData)message;
                    string         outFileName = ld.FileName;

                    using (Stream fOut = File.Create(outFileName))
                    {
                        Stream unc = ld.GetInputStream();
                        Streams.PipeAll(unc, fOut);
                    }
                }
                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.");
                }

                #region commented code

                if (pbe.IsIntegrityProtected())
                {
                    if (!pbe.Verify())
                    {
                        //msg = "message failed integrity check.";
                        Console.Error.WriteLine("message failed integrity check");

                        //YOU MAY OPT TO DELETE THE OUTPUT FILE IN THE EVENT THAT THE INTEGRITY PROTECTION CHECK FAILS.
                        //FILE DELETION HAPPENS FURTHER DOWN IN THIS METHOD.
                        //AN ALTERNATIVE IS TO LOG THESE VERIFICATION FAILURE MESSAGES, BUT KEEP THE OUTPUT FILE FOR FURTHER ANALYSIS
                        //deleteOutputFile = true;
                    }
                    else
                    {
                        //msg = "message integrity check passed.";
                        Console.Error.WriteLine("message integrity check passed");
                    }
                }
                else
                {
                    //msg = "no message integrity check.";
                    Console.Error.WriteLine("no message integrity check");
                }

                if (deleteOutputFile)
                {
                    File.Delete(outputFile);
                }

                #endregion commented code
            }
            catch (PgpException ex)
            {
                throw;
            }
        }
 /*
  * decrypt a given stream.
  */
 public static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFile)
 {
     try
     {
         PgpObjectFactory          pgpF   = null;
         PgpEncryptedDataList      enc    = null;
         PgpObject                 o      = null;
         PgpPrivateKey             sKey   = null;
         PgpPublicKeyEncryptedData pbe    = null;
         PgpSecretKeyRingBundle    pgpSec = null;
         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())
         {
             sKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray());
             if (sKey != null)
             {
                 pbe = pked;
                 break;
             }
         }
         if (sKey == null)
         {
             throw new ArgumentException("Secret key for message not found.");
         }
         PgpObjectFactory plainFact = null;
         using (Stream clear = pbe.GetDataStream(sKey))
         {
             plainFact = new PgpObjectFactory(clear);
         }
         PgpObject message = plainFact.NextPgpObject();
         if (message is PgpCompressedData)
         {
             PgpCompressedData cData = (PgpCompressedData)message;
             PgpObjectFactory  of    = null;
             using (Stream compDataIn = cData.GetDataStream())
             {
                 of = new PgpObjectFactory(compDataIn);
             }
             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);
                 }
             }
         }
         else if (message is PgpLiteralData)
         {
             PgpLiteralData ld          = (PgpLiteralData)message;
             string         outFileName = ld.FileName;
             using (Stream fOut = File.Create(outputFile))
             {
                 Stream unc = ld.GetInputStream();
                 Streams.PipeAll(unc, fOut);
             }
         }
         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.");
         }
     }
     catch (PgpException ex)
     {
         throw;
     }
 }
        public void Decrypt(Stream input, string outputPath)
        {
            input = PgpUtilities.GetDecoderStream(input);

            try {
                PgpObjectFactory     pgpObjFactory = new PgpObjectFactory(input);
                PgpEncryptedDataList enc;
                PgpObject            obj = pgpObjFactory.NextPgpObject();
                if (obj is PgpEncryptedDataList)
                {
                    enc = (PgpEncryptedDataList)obj;
                }
                else
                {
                    enc = (PgpEncryptedDataList)pgpObjFactory.NextPgpObject();
                }

                PgpPrivateKey             privKey = m_retrievePgpKeys.PrivateKey;
                PgpPublicKeyEncryptedData pbe     = null;

                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    if (privKey != null)
                    {
                        pbe = pked;
                        break;
                    }
                }
                Stream           clear        = pbe.GetDataStream(privKey);
                PgpObjectFactory plainFactory = new PgpObjectFactory(clear);
                PgpObject        message      = plainFactory.NextPgpObject();
                if (message is PgpCompressedData)
                {
                    PgpCompressedData compressedData = (PgpCompressedData)message;
                    Stream            compDataIn     = compressedData.GetDataStream();
                    PgpObjectFactory  objectFactory  = new PgpObjectFactory(compDataIn);
                    message = objectFactory.NextPgpObject();
                    if (message is PgpOnePassSignatureList)
                    {
                        message = objectFactory.NextPgpObject();
                    }
                    compDataIn.Close();
                }
                else
                {
                    message = plainFactory.NextPgpObject();
                }

                PgpLiteralData literalData    = (PgpLiteralData)message;
                Stream         output         = File.Create(Path.Combine(outputPath, literalData.FileName));
                Stream         uncompressData = literalData.GetInputStream();
                Org.BouncyCastle.Utilities.IO.Streams.PipeAll(uncompressData, output);

                clear.Close();
                uncompressData.Close();
                output.Close();
            }
            catch (Exception e) {
                throw new Exception(e.Message);
            }
        }
Example #8
0
        public void DecryptFileAndVerify(string inputFilePath, string outputFilePath, string publicKeyFilePath, string privateKeyFilePath, string passPhrase)
        {
            if (String.IsNullOrEmpty(inputFilePath))
            {
                throw new ArgumentException(nameof(inputFilePath));
            }
            if (String.IsNullOrEmpty(outputFilePath))
            {
                throw new ArgumentException(nameof(outputFilePath));
            }
            if (String.IsNullOrEmpty(publicKeyFilePath))
            {
                throw new ArgumentException(nameof(publicKeyFilePath));
            }
            if (String.IsNullOrEmpty(privateKeyFilePath))
            {
                throw new ArgumentException(nameof(privateKeyFilePath));
            }
            if (passPhrase == null)
            {
                passPhrase = String.Empty;
            }

            if (!File.Exists(inputFilePath))
            {
                throw new FileNotFoundException(String.Format("Encrypted File [{0}] not found.", inputFilePath));
            }
            if (!File.Exists(publicKeyFilePath))
            {
                throw new FileNotFoundException(String.Format("Public Key File [{0}] not found.", publicKeyFilePath));
            }
            if (!File.Exists(privateKeyFilePath))
            {
                throw new FileNotFoundException(String.Format("Private Key File [{0}] not found.", privateKeyFilePath));
            }

            ChoPGPEncryptionKeys encryptionKeys = new ChoPGPEncryptionKeys(publicKeyFilePath, privateKeyFilePath, passPhrase);

            if (encryptionKeys == null)
            {
                throw new ArgumentNullException("Encryption Key not found.");
            }

            using (Stream inputStream = File.OpenRead(inputFilePath))
            {
                PgpPublicKeyEncryptedData publicKeyED = ExtractPublicKeyEncryptedData(inputStream);
                if (publicKeyED.KeyId != encryptionKeys.PublicKey.KeyId)
                {
                    throw new PgpException(String.Format("Failed to verify file."));
                }

                PgpObject message = GetClearCompressedMessage(publicKeyED, encryptionKeys);

                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);
                        }
                    }
                }
                else if (message is PgpLiteralData)
                {
                    PgpLiteralData literalData = (PgpLiteralData)message;
                    using (Stream outputFile = File.Create(outputFilePath))
                    {
                        using (Stream literalDataStream = literalData.GetInputStream())
                        {
                            Streams.PipeAll(literalDataStream, outputFile);
                        }
                    }
                }
                else
                {
                    throw new PgpException("Message is not a simple encrypted file.");
                }
            }

            return;
        }
Example #9
0
        public void decrypt(Stream input)
        {
            input = PgpUtilities.GetDecoderStream(input);
            try
            {
                PgpObjectFactory     pgpObjF = new PgpObjectFactory(input);
                PgpEncryptedDataList enc;
                PgpObject            obj = pgpObjF.NextPgpObject();
                if (obj is PgpEncryptedDataList)
                {
                    enc = (PgpEncryptedDataList)obj;
                }
                else
                {
                    enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject();
                }
                PgpPrivateKey privKey = pgpKeys.PrivateKey;
                //PgpPublicKeyEncryptedData pbe = enc.GetEncryptedDataObjects().Cast<PgpPublicKeyEncryptedData>().First();
                PgpPublicKeyEncryptedData pbe = null;
                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    if (privKey != null)
                    {
                        pbe = pked;
                        break;
                    }
                }
                using (Stream clear = pbe.GetDataStream(privKey))
                {
                    PgpObjectFactory plainFact = new PgpObjectFactory(clear);
                    PgpObject        message   = plainFact.NextPgpObject();

                    if (message is PgpCompressedData)
                    {
                        PgpCompressedData cData      = (PgpCompressedData)message;
                        Stream            compDataIn = cData.GetDataStream();
                        PgpObjectFactory  o          = new PgpObjectFactory(compDataIn);
                        message = o.NextPgpObject();
                        if (message is PgpOnePassSignatureList)
                        {
                            message = o.NextPgpObject();
                        }
                        PgpLiteralData Ld = null;
                        Ld = (PgpLiteralData)message;
                        //  using (Stream output = File.Create(_outputPath + "\\" + Ld.FileName))
                        if (File.Exists(_outputPath))
                        {
                            File.Delete(_outputPath);
                        }
                        using (Stream output = File.Create(_outputPath))
                        {
                            Stream unc = Ld.GetInputStream();
                            Streams.PipeAll(unc, output);
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
        }
Example #10
0
        public string decryptToString(byte[] cipher)
        {
            string output = string.Empty;

            try
            {
                using (Stream cipherStream = new MemoryStream(cipher))
                {
                    Stream               input   = PgpUtilities.GetDecoderStream(cipherStream);
                    PgpObjectFactory     pgpObjF = new PgpObjectFactory(input);
                    PgpEncryptedDataList enc;
                    PgpObject            obj = pgpObjF.NextPgpObject();
                    if (obj is PgpEncryptedDataList)
                    {
                        enc = (PgpEncryptedDataList)obj;
                    }
                    else
                    {
                        enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject();
                    }
                    PgpPrivateKey privKey = pgpKeys.PrivateKey;
                    //PgpPublicKeyEncryptedData pbe = enc.GetEncryptedDataObjects().Cast<PgpPublicKeyEncryptedData>().First();
                    PgpPublicKeyEncryptedData pbe = null;
                    foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                    {
                        if (privKey != null)
                        {
                            pbe = pked;
                            break;
                        }
                    }
                    using (Stream clear = pbe.GetDataStream(privKey))
                    {
                        PgpObjectFactory plainFact = new PgpObjectFactory(clear);
                        PgpObject        message   = plainFact.NextPgpObject();

                        if (message is PgpCompressedData)
                        {
                            PgpCompressedData cData      = (PgpCompressedData)message;
                            Stream            compDataIn = cData.GetDataStream();
                            PgpObjectFactory  o          = new PgpObjectFactory(compDataIn);
                            message = o.NextPgpObject();
                            if (message is PgpOnePassSignatureList)
                            {
                                message = o.NextPgpObject();
                            }
                            PgpLiteralData Ld = null;
                            Ld = (PgpLiteralData)message;
                            using (MemoryStream decoded = new MemoryStream())
                            {
                                Stream unc = Ld.GetInputStream();
                                Streams.PipeAll(unc, decoded);
                                byte[] data = decoded.ToArray();
                                if (data != null)
                                {
                                    output = Encoding.UTF8.GetString(data);
                                }
                            }
                        }
                    }
                    input.Close();
                }

                return(output);
            }
            catch (Exception e)
            {
                throw e;
            }
        }
Example #11
0
        public static string DecryptKey(string encryptedAESKey, string privateKeyFilename, string passPhrase)
        {
            var inputStream   = new MemoryStream(Encoding.ASCII.GetBytes(encryptedAESKey));
            var armoredStream = new ArmoredInputStream(inputStream);

            //var decoderStream = PgpUtilities.GetDecoderStream(inputStream);

            try
            {
                PgpObjectFactory     pgpF = new PgpObjectFactory(armoredStream);
                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 = ReadPrivateKey(privateKeyFilename, passPhrase);

                if (sKey == null)
                {
                    throw new ArgumentException("secret key for message not found.");
                }

                PgpPublicKeyEncryptedData pbe = null;
                foreach (var pked in enc.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>())
                {
                    if (pked.KeyId == sKey.KeyId)
                    {
                        pbe = pked;
                        break;
                    }
                }
                if (pbe == null)
                {
                    Console.WriteLine("Invalid Key");
                    return("");
                }
                var cleartextStream = pbe.GetDataStream(sKey);

                var plainObjectFactory = new PgpObjectFactory(cleartextStream);

                var message = plainObjectFactory.NextPgpObject();
                var result  = "";
                if (message is PgpLiteralData)
                {
                    PgpLiteralData ld = (PgpLiteralData)message;

                    var output    = new MemoryStream();
                    var decrypted = ld.GetInputStream();
                    decrypted.CopyTo(output);
                    result = Encoding.ASCII.GetString(output.ToArray());
                }
                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");
                    }
                }
                return(result);
            }
            catch (PgpException e)
            {
                Console.Error.WriteLine(e);

                Exception underlyingException = e.InnerException;
                if (underlyingException != null)
                {
                    Console.Error.WriteLine(underlyingException.Message);
                    Console.Error.WriteLine(underlyingException.StackTrace);
                }
            }
            return("");
        }
Example #12
0
        public static byte[] Decrypt(byte[] encryptedData, RetrievePgpKeys keys, AlgorithmAgreement agreed)
        {
            Stream inputStream = new MemoryStream(encryptedData);

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory     pgpObjFactory = new PgpObjectFactory(inputStream);
            PgpEncryptedDataList enc;
            PgpObject            pgpObj = pgpObjFactory.NextPgpObject();

            if (pgpObj is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)pgpObj;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpObjFactory.NextPgpObject();
            }

            PgpPrivateKey             privKey = keys.PrivateKey;
            PgpPublicKeyEncryptedData pbe     = null;

            foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
            {
                if (privKey != null)
                {
                    pbe = pked;
                    break;
                }
            }
            PgpOnePassSignatureList onePassSigList = null;
            PgpSignatureList        signatureList  = null;
            PgpLiteralData          literalData    = null;

            byte[]           returnBytes  = null;
            Stream           clear        = pbe.GetDataStream(privKey);
            PgpObjectFactory plainFactory = new PgpObjectFactory(clear);

            for (; ;)
            {
                PgpObject message = plainFactory.NextPgpObject();
                if (message == null)
                {
                    break;
                }
                if (message is PgpCompressedData)
                {
                    PgpCompressedData compressedData = (PgpCompressedData)message;
                    plainFactory = new PgpObjectFactory(compressedData.GetDataStream());
                }
                else if (message is PgpLiteralData)
                {
                    literalData = (PgpLiteralData)message;
                    Stream unc = literalData.GetInputStream();
                    returnBytes = Org.BouncyCastle.Utilities.IO.Streams.ReadAll(unc);
                    unc.Close();
                }
                else if (message is PgpOnePassSignatureList)
                {
                    onePassSigList = (PgpOnePassSignatureList)message;
                }
                else if (message is PgpSignatureList)
                {
                    signatureList = (PgpSignatureList)message;
                }
                else if (message is PgpMarker)
                {
                }
                else
                {
                    throw new PgpException("message contains unknown message type.");
                }
            }
            //Stream unc = literalData.GetInputStream();

            //byte[] returnBytes = Org.BouncyCastle.Utilities.IO.Streams.ReadAll(unc);

            if ((onePassSigList != null) && (signatureList != null))
            {
                VerifySignature(onePassSigList, signatureList, keys.SecretKey.PublicKey, returnBytes);
            }

            //unc.Close();
            clear.Close();
            inputStream.Close();

            return(returnBytes);
        }
Example #13
0
        public static byte[] Decrypt2(byte[] encryptedData, RetrievePgpKeys keys, AlgorithmAgreement agreed)
        {
            Stream inputStream = new MemoryStream(encryptedData);

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory     pgpObjFactory = new PgpObjectFactory(inputStream);
            PgpEncryptedDataList enc;
            PgpObject            pgpObj = pgpObjFactory.NextPgpObject();

            if (pgpObj is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)pgpObj;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpObjFactory.NextPgpObject();
            }

            PgpPrivateKey             privKey = keys.PrivateKey;
            PgpPublicKeyEncryptedData pbe     = null;

            foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
            {
                if (privKey != null)
                {
                    pbe = pked;
                    break;
                }
            }
            PgpOnePassSignatureList onePassSigList = null;
            PgpSignatureList        signatureList  = null;
            PgpLiteralData          literalData    = null;
            Stream           clear        = pbe.GetDataStream(privKey);
            PgpObjectFactory plainFactory = new PgpObjectFactory(clear);
            PgpObject        message      = plainFactory.NextPgpObject();

            if (message is PgpCompressedData)
            {
                PgpCompressedData compressedData = (PgpCompressedData)message;
                Stream            compDataIn     = compressedData.GetDataStream();
                PgpObjectFactory  objectFactory  = new PgpObjectFactory(compDataIn);
                message = objectFactory.NextPgpObject();
                if (message is PgpOnePassSignatureList)
                {
                    onePassSigList = (message as PgpOnePassSignatureList);

                    message = objectFactory.NextPgpObject();
                    if (message is PgpLiteralData)
                    {
                        literalData = (PgpLiteralData)message;
                    }
                    message = objectFactory.NextPgpObject();
                    if (message is PgpSignatureList)
                    {
                        signatureList = (PgpSignatureList)message;
                    }
                }
                compDataIn.Close();
            }
            else
            {
                if (message is PgpOnePassSignatureList)
                {
                    onePassSigList = (message as PgpOnePassSignatureList);
                }
                message = plainFactory.NextPgpObject();
                if (message is PgpLiteralData)
                {
                    literalData = (PgpLiteralData)message;
                }
                message = plainFactory.NextPgpObject();
                if (message is PgpSignatureList)
                {
                    signatureList = (PgpSignatureList)message;
                }
            }

            Stream unc = literalData.GetInputStream();

            byte[] returnBytes = Org.BouncyCastle.Utilities.IO.Streams.ReadAll(unc);

            if (onePassSigList != null && signatureList != null)
            {
                VerifySignature(onePassSigList, signatureList, keys.SecretKey.PublicKey, returnBytes);
            }

            unc.Close();
            clear.Close();
            inputStream.Close();

            return(returnBytes);
        }
Example #14
0
        /*
         * 加密後的Session Key -> 私鑰(自己)解密 -> Session Key(對稱式)
         * 加密後的文章 - - - - - - - - - - - - - > Session Key(對稱式) -> 解密後的文章
         */


        private static void DecryptFile(
            Stream inputStream,    //欲解密之檔案之串流
            Stream keyIn,          //私鑰之串流
            char[] passwd,         //私鑰密碼
            string defaultFileName //解密後檔案名稱及位置
            )
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream); //資料流陣列化 byte Array

            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(keyIn)); //new 密鑰捆包 物件

                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    sKey = PgpExampleUtilities.FindSecretKey(pgpSec, pked.KeyId, passwd); //(密鑰捆包,identify,私鑰密碼),抓對稱加密的密鑰,密鑰

                    if (sKey != null)
                    {
                        pbe = pked;
                        break;
                    }
                }

                if (sKey == null)
                {
                    throw new ArgumentException("secret key for message not found.");
                }

                Stream clear = pbe.GetDataStream(sKey);                   //解碼

                PgpObjectFactory plainFact = new PgpObjectFactory(clear); // BcpgInputStream

                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; //內容

                    string outFileName = ld.FileName;
                    //if (outFileName.Length == 0)
                    //{
                    outFileName = defaultFileName;
                    //}

                    Stream fOut = File.Create(outFileName);
                    Stream unc  = ld.GetInputStream();
                    Streams.PipeAll(unc, fOut); //Pipe一種傳輸方式,存入匯出檔案
                    fOut.Close();
                    fOut.Dispose();
                }
                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())
                    {
                        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);
                }
            }
        }
Example #15
0
        /// <summary>
        /// Decrypts the Input File stream, given the Private Key File stream, to the specified Decrypted File Path.
        /// </summary>
        /// <param name="inputFileStream">File Stream of encrypted file.</param>
        /// <param name="privateKeyFileStream">File Stream of Private Key file.</param>
        /// <param name="password">Password that was used to encrypt the file.</param>
        /// <param name="decryptedFilePath">Path of the new decrypted file.</param>
        /// <exception cref="ArgumentException"></exception>
        /// <exception cref="PgpException"></exception>
        public static void DecryptFile(Stream inputFileStream, Stream privateKeyFileStream, string password, string decryptedFilePath, PgpSecretKeyRingBundle bundle = null)
        {
            // Parameter Checks
            if (String.IsNullOrEmpty(password))
            {
                throw new ArgumentException("Password Parameter is invalid.");
            }
            if (String.IsNullOrEmpty(decryptedFilePath))
            {
                throw new ArgumentException("Decrypted File Name Parameter is invalid.");
            }

            inputFileStream = PgpUtilities.GetDecoderStream(inputFileStream);

            PgpObjectFactory     _pgpObjectFactory = new PgpObjectFactory(inputFileStream);
            PgpEncryptedDataList _pgpEncryptedDataList;

            PgpObject _pgpObject = _pgpObjectFactory.NextPgpObject();

            if (_pgpObject is PgpEncryptedDataList)
            {
                _pgpEncryptedDataList = (PgpEncryptedDataList)_pgpObject;
            }
            else
            {
                _pgpEncryptedDataList = (PgpEncryptedDataList)_pgpObjectFactory.NextPgpObject();
            }

            PgpPrivateKey             _pgpPrivateKey          = null;
            PgpPublicKeyEncryptedData _pgpPubKeyEncryptedData = null;
            PgpSecretKeyRingBundle    _pgpSecKeyRingBundle    = bundle ?? new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyFileStream));

            foreach (PgpPublicKeyEncryptedData _pgpPubKeyEncData in _pgpEncryptedDataList.GetEncryptedDataObjects())
            {
                _pgpPrivateKey = PgpCustomUtilities.FindSecretKey(_pgpSecKeyRingBundle, _pgpPubKeyEncData.KeyId, password.ToCharArray());

                if (_pgpPrivateKey != null)
                {
                    _pgpPubKeyEncryptedData = _pgpPubKeyEncData;
                    break;
                }
            }

            if (_pgpPrivateKey == null)
            {
                throw new ArgumentException("secret key for message not found.");
            }

            Stream _privateKeyFileStream = _pgpPubKeyEncryptedData.GetDataStream(_pgpPrivateKey);

            PgpObjectFactory _pgpObjectFactoryPrivateKey = new PgpObjectFactory(_privateKeyFileStream);

            PgpObject _pgpObjectMessage = null;

            var po = _pgpObjectFactoryPrivateKey.NextPgpObject();

            if (po is PgpLiteralData)
            {
                _pgpObjectMessage = (PgpLiteralData)po;
            }
            else if (po is PgpCompressedData)
            {
                var _pgpCompressedData = (PgpCompressedData)po;

                var _pgpObjectFactoryCompressedData = new PgpObjectFactory(_pgpCompressedData.GetDataStream());

                _pgpObjectMessage = _pgpObjectFactoryCompressedData.NextPgpObject();
            }


            if (_pgpObjectMessage is PgpLiteralData)
            {
                PgpLiteralData _pgpLiteralData = (PgpLiteralData)_pgpObjectMessage;

                //                string _outputFileName = _pgpLiteralData.FileName;
                using (var st = _pgpLiteralData.GetInputStream())
                {
                    using (var dst = File.Create(decryptedFilePath))
                    {
                        st.CopyTo(dst);
                    }
                }

                /*
                 *  string _outputFileDirectoryPath;
                 * Stream _outputFileStream;
                 * if (_outputFileName.Length == 0)
                 * {
                 *  _outputFileName = decryptedFilePath;
                 *  _outputFileStream = File.Create(_outputFileName);
                 * }
                 * else
                 * {
                 *  FileInfo _decryptedFileInfo = new FileInfo(decryptedFilePath);
                 *  _outputFileDirectoryPath = _decryptedFileInfo.DirectoryName;
                 *  _outputFileStream = File.Create(Path.Combine(_outputFileDirectoryPath, _outputFileName));
                 * }
                 *
                 * Stream _dataInputStream = _pgpLiteralData.GetInputStream();
                 * _dataInputStream.CopyTo(_outputFileStream);
                 * //                Streams.PipeAll(_dataInputStream, _outputFileStream);
                 * _outputFileStream.Close();
                 */
            }
            else if (_pgpObjectMessage 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 (_pgpPubKeyEncryptedData.IsIntegrityProtected())
            {
                if (!_pgpPubKeyEncryptedData.Verify())
                {
                    throw new PgpException("Message failed integrity check.");
                }
            }
        }
Example #16
0
        private SignatureStatus DecryptFile()
        {
            if (InStream.CanSeek)
            {
                InStream.Seek(0, SeekOrigin.Begin);
            }
            var inputStream = PgpUtilities.GetDecoderStream(InStream);

            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();
                }


                var privateKeys = GetAllPrivateKeys();
                //
                // find the secret key
                //
                PgpPrivateKey             sKey = null;
                PgpPublicKeyEncryptedData pbe  = null;

                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    sKey = FindPrivateKey(privateKeys, pked.KeyId);

                    if (sKey != null)
                    {
                        pbe = pked;
                        break;
                    }
                }

                if (sKey == null)
                {
                    throw new SecretKeyNotFound("secret key for message not found.");
                }

                Stream clear = pbe.GetDataStream(sKey);

                PgpLiteralData          pgpLiteralData       = null;
                PgpOnePassSignatureList onePassSignatureList = null;
                PgpSignatureList        signatureList        = null;

                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(clear);
                var pgpObject = pgpObjectFactory.NextPgpObject();
                while (pgpObject != null)
                {
                    if (pgpObject is PgpCompressedData)
                    {
                        var compressedData = (PgpCompressedData)pgpObject;
                        pgpObjectFactory = new PgpObjectFactory(compressedData.GetDataStream());
                        pgpObject        = pgpObjectFactory.NextPgpObject();
                    }

                    if (pgpObject is PgpLiteralData)
                    {
                        pgpLiteralData = pgpObject as PgpLiteralData;
                        //must read directly to continue reading next pgp objects
                        Stream unc = pgpLiteralData.GetInputStream();
                        Streams.PipeAll(unc, OutStream);
                    }
                    else if (pgpObject is PgpOnePassSignatureList)
                    {
                        onePassSignatureList = pgpObject as PgpOnePassSignatureList;
                    }
                    else if (pgpObject is PgpSignatureList)
                    {
                        signatureList = pgpObject as PgpSignatureList;
                    }

                    pgpObject = pgpObjectFactory.NextPgpObject();
                }

                if (pgpLiteralData == null)
                {
                    throw new PgpLitralDataNotFound("couldn't find pgp literal data");
                }



                if (pbe.IsIntegrityProtected())
                {
                    if (!pbe.Verify())
                    {
                        throw new PgpIntegrityCheckFailed("message failed integrity check");
                    }
                }

                if (CheckSignature)
                {
                    if (onePassSignatureList == null || signatureList == null)
                    {
                        return(SignatureStatus.NoSignature);
                    }
                    else
                    {
                        return(VerifyFileSignature(OutStream, onePassSignatureList, signatureList));
                    }
                }
                else
                {
                    return(SignatureStatus.NotChecked);
                }
            }
            catch
            {
                throw;
            }
        }
Example #17
0
        /// <summary>
        /// Attempt to decrypt a PGP protected message using the matching private key.
        /// </summary>
        /// <param name="messageStream">Stream containing the message to decrypt.</param>
        /// <param name="decryptedMessageStream">Stream to write the decrypted message into.</param>
        /// <param name="recipientPrivateKey">The BouncyCastle private key to be used for decryption.</param>
        /// <remarks>The message should be passed in without ASCII Armor.</remarks>
        /// <returns>Whether the decryption completed successfully.</returns>
        public static bool Decrypt(Stream messageStream, Stream decryptedMessageStream, PgpPrivateKey recipientPrivateKey)
        {
            // Decode from Base-64.
            using (Stream decoderStream = PgpUtilities.GetDecoderStream(messageStream))
            {
                // Extract the encrypted data list.
                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream);
                PgpObject        pgpObject        = pgpObjectFactory.NextPgpObject();
                while (!(pgpObject is PgpEncryptedDataList))
                {
                    pgpObject = pgpObjectFactory.NextPgpObject();
                    if (pgpObject == null)
                    {
                        return(false);
                    }
                }
                PgpEncryptedDataList pgpEncryptedDataList = pgpObject as PgpEncryptedDataList;

                // Attempt to extract the encrypted data stream.
                Stream decryptedStream = null;
                foreach (PgpPublicKeyEncryptedData pgpEncryptedData in pgpEncryptedDataList.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>())
                {
                    if (pgpEncryptedData.KeyId == recipientPrivateKey.KeyId)
                    {
                        decryptedStream = pgpEncryptedData.GetDataStream(recipientPrivateKey);
                    }
                }

                // If we're unable to decrypt any of the streams, fail.
                if (decryptedStream == null)
                {
                    return(false);
                }

                PgpObjectFactory clearPgpObjectFactory = new PgpObjectFactory(decryptedStream);
                PgpObject        message = clearPgpObjectFactory.NextPgpObject();

                // Deal with compression.
                if (message is PgpCompressedData)
                {
                    PgpCompressedData compressedMessage = (PgpCompressedData)message;
                    using (Stream compressedDataStream = compressedMessage.GetDataStream())
                    {
                        PgpObjectFactory compressedPgpObjectFactory = new PgpObjectFactory(compressedDataStream);

                        pgpObject = compressedPgpObjectFactory.NextPgpObject();
                        while (!(pgpObject is PgpLiteralData))
                        {
                            pgpObject = compressedPgpObjectFactory.NextPgpObject();
                            if (pgpObject == null)
                            {
                                return(false);
                            }
                        }
                    }
                }
                else if (message is PgpLiteralData)
                {
                    pgpObject = message;
                }
                else
                {
                    // If not compressed and the following object isn't literal data, fail.
                    decryptedStream.Dispose();
                    return(false);
                }

                // If a literal data stream was found, extract the decrypted message.
                PgpLiteralData literalData = pgpObject as PgpLiteralData;
                if (literalData != null)
                {
                    using (Stream literalDataStream = literalData.GetDataStream())
                    {
                        literalDataStream.CopyTo(decryptedMessageStream);
                    }

                    decryptedStream.Dispose();
                    return(true);
                }
            }

            return(false);
        }
Example #18
0
        public void DecryptAndVerify(Stream inputStream, Stream outputStream, Stream publicKeyStream, Stream privateKeyStream, string passPhrase)
        {
            if (inputStream == null)
            {
                throw new ArgumentException(nameof(inputStream));
            }
            if (outputStream == null)
            {
                throw new ArgumentException(nameof(outputStream));
            }
            if (publicKeyStream == null)
            {
                throw new ArgumentException(nameof(publicKeyStream));
            }
            if (privateKeyStream == null)
            {
                throw new ArgumentException(nameof(privateKeyStream));
            }
            if (passPhrase == null)
            {
                passPhrase = String.Empty;
            }

            ChoPGPEncryptionKeys encryptionKeys = new ChoPGPEncryptionKeys(publicKeyStream, privateKeyStream, passPhrase);

            if (encryptionKeys == null)
            {
                throw new ArgumentNullException("Encryption Key not found.");
            }

            PgpPublicKeyEncryptedData publicKeyED = ExtractPublicKeyEncryptedData(inputStream);

            if (publicKeyED.KeyId != encryptionKeys.PublicKey.KeyId)
            {
                throw new PgpException(String.Format("Failed to verify file."));
            }

            PgpObject message = GetClearCompressedMessage(publicKeyED, encryptionKeys);

            if (message is PgpCompressedData)
            {
                message = ProcessCompressedMessage(message);
                PgpLiteralData literalData = (PgpLiteralData)message;
                using (Stream literalDataStream = literalData.GetInputStream())
                {
                    Streams.PipeAll(literalDataStream, outputStream);
                }
            }
            else if (message is PgpLiteralData)
            {
                PgpLiteralData literalData = (PgpLiteralData)message;
                using (Stream literalDataStream = literalData.GetInputStream())
                {
                    Streams.PipeAll(literalDataStream, outputStream);
                }
            }
            else
            {
                throw new PgpException("Message is not a simple encrypted file.");
            }

            return;
        }
Example #19
0
        /**
         * decrypt the passed in message stream
         */
        private static void DecryptFile(
            Stream inputStream,
            char[]      passPhrase)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory pgpF = new PgpObjectFactory(inputStream);
            PgpObject        o    = pgpF.NextPgpObject();

            //
            // the first object might be a PGP marker packet.
            //
            PgpEncryptedDataList enc = o as PgpEncryptedDataList;

            if (enc == null)
            {
                enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
            }

            PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0];

            Stream clear = pbe.GetDataStream(passPhrase);

            PgpObjectFactory pgpFact = new PgpObjectFactory(clear);

            //
            // if we're trying to read a file generated by someone other than us
            // the data might not be compressed, so we check the return type from
            // the factory and behave accordingly.
            //
            o = pgpFact.NextPgpObject();
            if (o is PgpCompressedData)
            {
                PgpCompressedData cData = (PgpCompressedData)o;
                pgpFact = new PgpObjectFactory(cData.GetDataStream());
                o       = pgpFact.NextPgpObject();
            }

            PgpLiteralData ld   = (PgpLiteralData)o;
            Stream         unc  = ld.GetInputStream();
            Stream         fOut = File.Create(ld.FileName);

            Streams.PipeAll(unc, fOut);
            fOut.Close();

            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");
            }
        }
Example #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="filename"></param>
        /// <param name="privateKeyStream"></param>
        /// <param name="passPhrase"></param>
        /// <returns></returns>
        public static IEnumerable <Tuple <string, Stream> > DecompressStreamFilesPGP(this Stream inputStream, string filename, Stream privateKeyStream, string passPhrase)
        {
            var response           = new List <Tuple <string, Stream> >();
            var outputMemoryStream = new MemoryStream();

            try {
                var pgpFactory        = default(PgpObjectFactory);
                var encryptedDataList = default(PgpEncryptedDataList);
                var obj           = default(PgpObject);
                var privateKey    = default(PgpPrivateKey);
                var encryptedData = default(PgpPublicKeyEncryptedData);
                var ringBundle    = default(PgpSecretKeyRingBundle);

                pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));

                // find secret key
                ringBundle = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));

                if (pgpFactory != null)
                {
                    obj = pgpFactory.NextPgpObject();
                }

                // the first object might be a PGP marker packet.
                if (obj is PgpEncryptedDataList)
                {
                    encryptedDataList = (PgpEncryptedDataList)obj;
                }
                else
                {
                    encryptedDataList = (PgpEncryptedDataList)pgpFactory.NextPgpObject();
                }

                // decrypt
                foreach (PgpPublicKeyEncryptedData pked in encryptedDataList.GetEncryptedDataObjects())
                {
                    privateKey = FindSecretKey(ringBundle, pked.KeyId, passPhrase.ToCharArray());

                    if (privateKey != null)
                    {
                        encryptedData = pked;
                        break;
                    }
                }

                if (privateKey == null)
                {
                    throw new ArgumentException("Secret key for message not found.");
                }

                PgpObjectFactory plainFact = null;

                using (Stream clear = encryptedData.GetDataStream(privateKey)) {
                    plainFact = new PgpObjectFactory(clear);
                }

                PgpObject message = plainFact.NextPgpObject();

                if (message is PgpCompressedData)
                {
                    PgpCompressedData cData = (PgpCompressedData)message;
                    PgpObjectFactory  of    = null;

                    using (Stream compDataIn = cData.GetDataStream()) {
                        of = new PgpObjectFactory(compDataIn);
                    }

                    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, outputMemoryStream);
                        //}
                    }
                    else
                    {
                        PgpLiteralData Ld = null;
                        Ld = (PgpLiteralData)message;
                        //using (Stream output = File.Create(outputFile))
                        //{
                        Stream unc = Ld.GetInputStream();
                        Streams.PipeAll(unc, outputMemoryStream);
                        //}
                    }
                }
                else if (message is PgpLiteralData)
                {
                    PgpLiteralData ld          = (PgpLiteralData)message;
                    string         outFileName = ld.FileName;

                    //using (Stream fOut = File.Create(outputFile))
                    //{
                    Stream unc = ld.GetInputStream();
                    Streams.PipeAll(unc, outputMemoryStream);
                    //}
                }
                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.");
                }
            }
            catch (PgpException ex) {
                throw ex;
            }

            response
            .Add(
                Tuple.Create <string, Stream>(
                    filename.Replace(@"\", " ").Replace(@"/", " "),
                    outputMemoryStream));

            return(response);
        }
Example #21
0
        /// <summary>
        /// Recursive PGP Object handler.
        /// </summary>
        /// <param name="obj">Object to handle</param>
        /// <returns>Returns decrypted data if any</returns>
        byte[] DecryptHandlePgpObject(PgpObject obj)
        {
            byte[] ret = null;

            if (obj is PgpEncryptedDataList)
            {
                Context.IsEncrypted = true;
                var dataList = obj as PgpEncryptedDataList;

                // Set once we have matched a keyid.
                bool secretKeyMatched = false;

                foreach (PgpPublicKeyEncryptedData encryptedData in dataList.GetEncryptedDataObjects())
                {
                    try
                    {
                        // NOTE: When content is encrypted to multiple recipients, only one of these blocks
                        //       will match a known KeyId.  If a match is never made, then there is a problem :)
                        Context.SecretKey = GetSecretKey(encryptedData.KeyId);
                        if (Context.SecretKey == null)
                        {
                            continue;
                        }

                        secretKeyMatched = true;

                        using (var cleartextIn = encryptedData.GetDataStream(Context.SecretKey.ExtractPrivateKey(Context.Password)))
                        {
                            var clearFactory = new PgpObjectFactory(cleartextIn);
                            var nextObj      = clearFactory.NextPgpObject();

                            var r = DecryptHandlePgpObject(nextObj);
                            if (r != null)
                            {
                                ret = r;
                            }
                        }

                        // This can fail due to integrity protection missing.
                        // Legacy systems to not have this protection
                        // Should make an option to ignore.
                        try
                        {
                            if (!encryptedData.Verify())
                            {
                                throw new VerifyException("Verify of encrypted data failed!");
                            }
                        }
                        catch (PgpException exx)
                        {
                            if (exx.Message == "data not integrity protected.")
                            {
                                Context.FailedIntegrityCheck = true;
                            }
                            else
                            {
                                throw;
                            }
                        }
                    }
                    catch (PgpException ex)
                    {
                        if (!(ex.InnerException is EndOfStreamException))
                        {
                            throw ex;
                        }
                    }
                }

                if (!secretKeyMatched)
                {
                    throw new SecretKeyNotFoundException("Error, unable to locate decryption key.");
                }
            }
            else if (obj is PgpCompressedData)
            {
                Context.IsCompressed = true;
                var compressedData = obj as PgpCompressedData;
                using (var compressedIn = compressedData.GetDataStream())
                {
                    var factory = new PgpObjectFactory(compressedIn);

                    do
                    {
                        var nextObj = factory.NextPgpObject();

                        if (nextObj == null)
                        {
                            break;
                        }

                        var r = DecryptHandlePgpObject(nextObj);
                        if (r != null)
                        {
                            ret = r;
                        }
                    }while (true);
                }
            }
            else if (obj is PgpOnePassSignatureList)
            {
                Context.IsSigned = true;
                var signatureList = obj as PgpOnePassSignatureList;

                if (signatureList.Count > 1)
                {
                    throw new CryptoException("Error, more than one signature present!");
                }

                Context.OnePassSignature = signatureList[0];
                var publicKey = GetPublicKey(Context.OnePassSignature.KeyId);
                if (publicKey == null)
                {
                    Context.OnePassSignature = null;
                }
                else
                {
                    Context.OnePassSignature.InitVerify(publicKey);
                }
            }
            else if (obj is PgpSignatureList)
            {
                var signatureList = obj as PgpSignatureList;

                if (signatureList.Count > 1)
                {
                    throw new CryptoException("Error, more than one signature present!");
                }

                Context.Signature = signatureList[0];

                if (Context.IsSigned && Context.OnePassSignature == null)
                {
                    // We don't have signature key for validation
                    Context.SignatureValidated = false;
                    Context.SignedBy           = null;
                }
                else if (Context.OnePassSignature == null)
                {
                    throw new CryptoException("Error, OnePassSignature was not found!");
                }
                else
                {
                    if (Context.OnePassSignature.Verify(Context.Signature))
                    {
                        Context.SignatureValidated = true;
                        Context.SignedBy           = GetPublicKey(Context.Signature.KeyId);
                    }
                }
            }
            else if (obj is PgpLiteralData)
            {
                var literalData = obj as PgpLiteralData;

                using (var dataOut = new MemoryStream())
                {
                    using (var dataIn = literalData.GetInputStream())
                        dataIn.CopyTo(dataOut);

                    dataOut.Position = 0;

                    ret = dataOut.ToArray();
                }

                if (Context.OnePassSignature != null)
                {
                    Context.OnePassSignature.Update(ret, 0, ret.Length);
                }
            }
            else if (obj is PgpMarker)
            {
                // Skip, These packets are used by PGP 5.x to signal to earlier
                // versions of PGP (eg. 2.6.x) that the message requires newer
                // software to be read and understood.
            }
            else
            {
                throw new CryptoException("Unknown Pgp Object: " + obj.GetType().ToString());
            }

            return(ret);
        }
        private static void DecryptFile(Stream inputStream, Stream keyIn, char[] passwd, string pathToSaveFile)
        {
            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;

                PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(

                    PgpUtilities.GetDecoderStream(keyIn));

                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    sKey = FindSecretKey(pgpSec, pked.KeyId, passwd);

                    if (sKey != null)
                    {
                        pbe = pked;

                        break;
                    }
                }

                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 PgpLiteralData)
                {
                    PgpLiteralData ld = (PgpLiteralData)message;

                    //string outFileName = ld.FileName;

                    //if (outFileName.Length == 0)
                    //{

                    // outFileName = defaultFileName;

                    //}

                    Stream fOut = File.Create(pathToSaveFile);

                    Stream unc = ld.GetInputStream();

                    Streams.PipeAll(unc, fOut);

                    fOut.Close();
                }

                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())
                    {
                        Console.WriteLine("message failed integrity check");
                    }

                    else
                    {
                        Console.WriteLine("message integrity check passed");
                    }
                }

                else
                {
                    Console.WriteLine("no message integrity check");
                }
            }

            catch (PgpException e)
            {
                Console.WriteLine(e);

                Exception underlyingException = e.InnerException;

                if (underlyingException != null)
                {
                    Console.WriteLine(underlyingException.Message);

                    Console.WriteLine(underlyingException.StackTrace);
                }//

                // System.Windows.Forms.MessageBox.Show(e.ToString());
            }
        }
Example #23
0
        /**
         * decrypt the passed in message stream
         */
        private static void DecryptFile(
            Stream inputStream,
            Stream keyIn,
            char[]  passwd,
            string pathToDecryptedFile)                         //DC
        {
            try
            {
                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;
                    PgpSecretKeyRingBundle    pgpSec = new PgpSecretKeyRingBundle(
                        PgpUtilities.GetDecoderStream(keyIn));

                    foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                    {
                        sKey = OpenPgp_HelperMethods.FindSecretKey(pgpSec, pked.KeyId, passwd);

                        if (sKey != null)
                        {
                            pbe = pked;
                            break;
                        }
                    }

                    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();

                    PgpObjectFactory pgpFact = null;

                    if (message is PgpCompressedData)
                    {
                        PgpCompressedData cData = (PgpCompressedData)message;
                        pgpFact = new PgpObjectFactory(cData.GetDataStream());

                        message = pgpFact.NextPgpObject();
                    }

                    if (message is PgpOnePassSignatureList)                             // DC
                    {                                                                   // DC
                        message = pgpFact.NextPgpObject();                              // DC
                    }                                                                   // DC

                    if (message is PgpLiteralData)
                    {
                        PgpLiteralData ld = (PgpLiteralData)message;

                        Stream fOut = File.Create(pathToDecryptedFile);                                 //DC (modified to use the name provided in pathToDecryptedFile
                        Stream unc  = ld.GetInputStream();
                        Streams.PipeAll(unc, fOut);
                        fOut.Close();
                    }
                    else if (message is PgpOnePassSignatureList)
                    {
                        "[API_OpenPgp][DecryptFile] encrypted message contains a signed message - not literal data.".error();
                        return;
                    }
                    else
                    {
                        "[API_OpenPgp][DecryptFile] message is not a simple encrypted file - type unknown.".error();
                        return;
                    }

                    if (pbe.IsIntegrityProtected())
                    {
                        if (!pbe.Verify())
                        {
                            "[API_OpenPgp][DecryptFile] message failed integrity check".error();
                        }
                        else
                        {
                            "[API_OpenPgp][DecryptFile] message integrity check passed".debug();
                        }
                    }
                    else
                    {
                        "[API_OpenPgp][DecryptFile] no message integrity check".error();
                    }
                }
                catch (PgpException e)
                {
                    e.log("[API_OpenPgp] in DecryptFile: " + e.StackTrace);

                    /*Console.Error.WriteLine(e);
                     *
                     * Exception underlyingException = e.InnerException;
                     * if (underlyingException != null)
                     * {
                     *  Console.Error.WriteLine(underlyingException.Message);
                     *  Console.Error.WriteLine(underlyingException.StackTrace);
                     * }*/
                }
            }
            catch (Exception ex)
            {
                ex.log("[API_OpenPgp] in DecryptFile  : " + ex.StackTrace);
            }
        }
Example #24
0
        /*
         * PGP decrypt a given stream.
         */
        private void Decrypt(Stream inputStream, Stream outputStream, Stream privateKeyStream, string passPhrase)
        {
            if (inputStream == null)
            {
                throw new ArgumentException("InputStream");
            }
            if (outputStream == null)
            {
                throw new ArgumentException("outputStream");
            }
            if (privateKeyStream == null)
            {
                throw new ArgumentException("privateKeyStream");
            }
            if (passPhrase == null)
            {
                passPhrase = String.Empty;
            }

            PgpObjectFactory objFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
            // find secret key
            PgpSecretKeyRingBundle pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));

            PgpObject obj = null;

            if (objFactory != null)
            {
                obj = objFactory.NextPgpObject();
            }

            // the first object might be a PGP marker packet.
            PgpEncryptedDataList enc = null;

            if (obj is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)obj;
            }
            else
            {
                enc = (PgpEncryptedDataList)objFactory.NextPgpObject();
            }

            // decrypt
            PgpPrivateKey             privateKey = null;
            PgpPublicKeyEncryptedData pbe        = null;

            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.");
            }

            PgpObjectFactory plainFact = null;

            using (Stream clear = pbe.GetDataStream(privateKey))
            {
                plainFact = new PgpObjectFactory(clear);
            }

            PgpObject message = plainFact.NextPgpObject();

            if (message is PgpOnePassSignatureList)
            {
                message = plainFact.NextPgpObject();
            }

            if (message is PgpCompressedData)
            {
                PgpCompressedData cData = (PgpCompressedData)message;
                PgpObjectFactory  of    = null;

                using (Stream compDataIn = cData.GetDataStream())
                {
                    of = new PgpObjectFactory(compDataIn);
                }

                message = of.NextPgpObject();
                if (message is PgpOnePassSignatureList)
                {
                    message = of.NextPgpObject();
                    PgpLiteralData Ld = null;
                    Ld = (PgpLiteralData)message;
                    Stream unc = Ld.GetInputStream();
                    Streams.PipeAll(unc, outputStream);
                }
                else
                {
                    PgpLiteralData Ld = null;
                    Ld = (PgpLiteralData)message;
                    Stream unc = Ld.GetInputStream();
                    Streams.PipeAll(unc, outputStream);
                }
            }
            else if (message is PgpLiteralData)
            {
                PgpLiteralData ld          = (PgpLiteralData)message;
                string         outFileName = ld.FileName;

                Stream unc = ld.GetInputStream();
                Streams.PipeAll(unc, outputStream);

                if (pbe.IsIntegrityProtected())
                {
                    if (!pbe.Verify())
                    {
                        throw new PgpException("Message failed integrity check.");
                    }
                }
            }
            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.");
            }
        }
        public static byte[] DecryptPgp(byte[] input, byte[] privateKeyStream, string passPhrase)
        {
            byte[] output;
            using (MemoryStream inputStream = new MemoryStream(input)) {
                inputStream.Position = 0;

                PgpObjectFactory pgpFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
                // find secret key
                PgpSecretKeyRingBundle pgpKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(new MemoryStream(privateKeyStream)));

                PgpObject pgp = null;
                if (pgpFactory != null)
                {
                    pgp = pgpFactory.NextPgpObject();
                }

                // the first object might be a PGP marker packet.
                PgpEncryptedDataList encryptedData = null;
                if (pgp is PgpEncryptedDataList)
                {
                    encryptedData = (PgpEncryptedDataList)pgp;
                }
                else
                {
                    encryptedData = (PgpEncryptedDataList)pgpFactory.NextPgpObject();
                }

                // decrypt
                PgpPrivateKey             privateKey = null;
                PgpPublicKeyEncryptedData pubKeyData = null;
                foreach (PgpPublicKeyEncryptedData pubKeyDataItem in encryptedData.GetEncryptedDataObjects())
                {
                    privateKey = FindSecretKey(pgpKeyRing, pubKeyDataItem.KeyId, passPhrase.ToCharArray());

                    if (privateKey != null)
                    {
                        pubKeyData = pubKeyDataItem;
                        break;
                    }
                }

                if (privateKey == null)
                {
                    throw new ArgumentException("Secret key for message not found.");
                }

                PgpObjectFactory plainFact = null;
                using (Stream clear = pubKeyData.GetDataStream(privateKey))
                {
                    plainFact = new PgpObjectFactory(clear);
                }

                PgpObject message = plainFact.NextPgpObject();

                if (message is PgpLiteralData)
                {
                    PgpLiteralData literalData = (PgpLiteralData)message;
                    using (Stream unc = literalData.GetInputStream())
                        using (MemoryStream outputStream = new MemoryStream())
                        {
                            unc.CopyTo(outputStream);
                            output = outputStream.ToArray();
                        }
                }
                else
                {
                    throw new PgpException("Message is not a simple encrypted file - type unknown.");
                }
            }
            return(output);
        }