Пример #1
0
 private void VerifyEncryptedData(PgpPublicKeyEncryptedData encryptedData)
 {
     if (!encryptedData.IsIntegrityProtected())
     {
         return;
     }
     if (!encryptedData.Verify())
     {
         throw new PgpException("Message integrity check failed.");
     }
 }
        /// <summary>
        /// Decrypt file and verify file signature from stream.
        /// </summary>
        /// <param name="inputStream">
        /// The encrypted data input stream.
        /// </param>
        /// <param name="outputStream">
        /// The output stream.
        /// </param>
        /// <param name="privateKeyStream">
        /// The private key stream.
        /// </param>
        /// <param name="publicKeyStream">
        /// The public key stream.
        /// </param>
        /// <param name="passPhrase">
        /// The pass phrase.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/> value indicating whether or not the signature in
        /// the decrypted data is valid.
        /// </returns>
        public static bool DecryptAndVerifyStream(
            Stream inputStream,
            Stream outputStream,
            Stream privateKeyStream,
            Stream publicKeyStream,
            char[] passPhrase)
        {
            PgpPrivateKey             privateKey    = null;
            PgpPublicKeyEncryptedData encryptedData = null;
            var secretKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));

            var encryptedDataList = GetEncryptedDataListFromStream(inputStream);

            foreach (PgpPublicKeyEncryptedData dataObject in encryptedDataList.GetEncryptedDataObjects())
            {
                privateKey = PgpKeyHelper.FindSecretKey(secretKeyRing, dataObject.KeyId, passPhrase);
                if (privateKey == null)
                {
                    continue;
                }

                encryptedData = dataObject;
                break;
            }

            if (privateKey == null)
            {
                throw new Exception("Unable to find secret key to decrypt the message");
            }

            var valid = ProcessDecryptionMessageBlocks(encryptedData, outputStream, publicKeyStream, privateKey);

            if (encryptedData.IsIntegrityProtected() && !encryptedData.Verify())
            {
                throw new PgpException("Data is integrity protected but integrity is lost.");
            }

            return(valid);
        }
Пример #3
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())
                {
                    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(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 Decrypt(
            Stream inputStream,
            string privateKeyIn,
            string passPhrase,
            out Stream outputStream)
        {
            PgpObjectFactory objFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));

            outputStream = new MemoryStream();

            PgpObject obj = null;

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

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

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

            // If enc and message are null at this point, we failed to detect the contents of the encrypted stream.
            if (enc == null && message == null)
            {
                throw new ArgumentException($"Failed to detect encrypted content format.");
            }

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

            PgpSecretKeyRingBundle pgpSecret = null;

            byte[]       privateKeyBuffer = Encoding.ASCII.GetBytes(privateKeyIn);
            MemoryStream privateKeyStream = new MemoryStream(privateKeyBuffer);

            pgpSecret = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));
            if (enc != null)
            {
                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    privateKey = FindSecretKey(pgpSecret, 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);
                }

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

            byte[] outputBuffer = (outputStream as MemoryStream).ToArray();
            return(Encoding.ASCII.GetString(outputBuffer));
        }
Пример #5
0
        /// <summary>
        /// Decrypts a input stream into an output stream. The first argument is the stream off the private keyring.
        /// </summary>
        /// <param name="inputStream">The input stream to decrypt</param>
        /// <param name="outputStream">The decrypted output stream created by the method.</param>
        ///
        public void Decrypt(
            Stream inputStream,
            Stream outputStream)
        {
            /*
             * byte[] bytes = Encoding.UTF8.GetBytes(privateArmoredKeyring);
             * MemoryStream privateKeyring = new MemoryStream(bytes);
             */

            if (inputStream == null)
            {
                throw new ArgumentNullException("inputStream can not be null!");
            }

            if (outputStream == null)
            {
                throw new ArgumentNullException("outputStream can not be null!");
            }

            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(privateKeyring));
                 */

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

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

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

                Stream clear = pbe.GetDataStream(sKey);

                PgpObjectFactory plainFact = new PgpObjectFactory(clear);

                PgpCompressedData cData = (PgpCompressedData)plainFact.NextPgpObject();

                PgpObjectFactory pgpFact = new PgpObjectFactory(cData.GetDataStream());

                PgpObject message = pgpFact.NextPgpObject();

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

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

                    //string outFileName = defaultFileName;
                    //Stream fOut = File.Create(outFileName);

                    Stream unc = ld.GetInputStream();
                    Streams.PipeAll(unc, outputStream);
                }
                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())
                    {
                        Verify = false;
                    }
                    else
                    {
                        Verify = true;
                    }
                }
                else
                {
                    //Don't know what to doe
                    //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);
                 * }
                 */

                if (e.Message.Contains("Checksum mismatch at 0 of 20"))
                {
                    throw new PgpWrongPassphraseException("Wrong passphrase. Can not decrypt.");
                }

                throw e;
            }
            finally
            {
                inputStream.Dispose();

                //Because stream mut remain open fro string decryption
                if (outputStream.GetType() != typeof(MemoryStream))
                {
                    outputStream.Dispose(); // NO: to be done by caller.
                }
            }
        }
Пример #6
0
        public static GPGDecryptedDataReturn DecryptStream(Stream stream, PgpPrivateKey key)
        {
            var pgpF = new PgpObjectFactory(stream);
            var o    = pgpF.NextPgpObject();
            var enc  = o as PgpEncryptedDataList;

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

            PgpPublicKeyEncryptedData pbe = null;
            string lastFingerPrint        = "None";

            foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
            {
                if (pked.KeyId == key.KeyId)
                {
                    pbe = pked;
                    break;
                }
            }

            if (pbe == null)
            {
                throw new NoKeyAvailableException("There is no payload that matches loaded key.");
            }

            var clear     = pbe.GetDataStream(key);
            var plainFact = new PgpObjectFactory(clear);
            var message   = plainFact.NextPgpObject();
            var outData   = new GPGDecryptedDataReturn {
                FingerPrint = lastFingerPrint,
            };

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

            if (message is PgpLiteralData ld)
            {
                outData.Filename = ld.FileName;
                var    iss    = ld.GetInputStream();
                byte[] buffer = new byte[16 * 1024];
                using (var ms = new MemoryStream()) {
                    int read;
                    while ((read = iss.Read(buffer, 0, buffer.Length)) > 0)
                    {
                        ms.Write(buffer, 0, read);
                    }
                    outData.Base64Data = Convert.ToBase64String(ms.ToArray());
                }
            }
            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.");
            }

            outData.IsIntegrityProtected = pbe.IsIntegrityProtected();

            if (outData.IsIntegrityProtected)
            {
                outData.IsIntegrityOK = pbe.Verify();
            }

            return(outData);
        }
Пример #7
0
        private static void DecryptPgp(Stream input, Stream output, Stream key, char[] password)
        {
            try
            {
                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(input));
                PgpObject        pgpObject        = pgpObjectFactory.NextPgpObject();

                // The first object might be a PGP marker packet
                PgpEncryptedDataList pgpEncryptedDataList;
                if (pgpObject is PgpEncryptedDataList)
                {
                    pgpEncryptedDataList = (PgpEncryptedDataList)pgpObject;
                }
                else
                {
                    pgpEncryptedDataList = (PgpEncryptedDataList)pgpObjectFactory.NextPgpObject();
                }

                // Find private key for decryption
                PgpPrivateKey             privateKey                = null;
                PgpSecretKeyRingBundle    pgpSecretKeyRing          = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(key));
                PgpPublicKeyEncryptedData pgpPublicKeyEncryptedData = null;
                foreach (PgpPublicKeyEncryptedData pked in pgpEncryptedDataList.GetEncryptedDataObjects())
                {
                    PgpSecretKey pgpDescretKey = pgpSecretKeyRing.GetSecretKey(pked.KeyId);
                    privateKey = pgpDescretKey.ExtractPrivateKey(password);

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

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

                Stream decrypted = pgpPublicKeyEncryptedData.GetDataStream(privateKey);
                pgpObjectFactory = new PgpObjectFactory(decrypted);
                pgpObject        = pgpObjectFactory.NextPgpObject();

                if (pgpObject is PgpCompressedData)
                {
                    PgpCompressedData pgpCompressedData = (PgpCompressedData)pgpObject;
                    pgpObjectFactory = new PgpObjectFactory(pgpCompressedData.GetDataStream());
                    pgpObject        = pgpObjectFactory.NextPgpObject();
                }

                if (pgpObject is PgpLiteralData)
                {
                    PgpLiteralData pgpLiteralData = (PgpLiteralData)pgpObject;
                    Stream         literal        = pgpLiteralData.GetInputStream();
                    Streams.PipeAll(literal, output);
                }
                else if (pgpObject is PgpOnePassSignatureList)
                {
                    throw new PgpException("Encrypted message contains a signed message, not a literal data.");
                }
                else
                {
                    throw new PgpException("Message is not a simple encrypted file, type is unknown.");
                }

                if (pgpPublicKeyEncryptedData.IsIntegrityProtected())
                {
                    if (!pgpPublicKeyEncryptedData.Verify())
                    {
                        Console.Error.WriteLine("Message failed integrity check.");
                    }
                    else
                    {
                        Console.Error.WriteLine("Message integrity check passed.");
                    }
                }
                else
                {
                    Console.Error.WriteLine("No message integrity check.");
                }

                Console.WriteLine("OpenPGP decryption successfull.");
            }
            catch (PgpException ex)
            {
                Console.Error.WriteLine(ex);

                Exception pgpInnerException = ex.InnerException;
                if (pgpInnerException != null)
                {
                    Console.Error.WriteLine(pgpInnerException.Message);
                    Console.Error.WriteLine(pgpInnerException.StackTrace);
                }
            }
        }
Пример #8
0
        public byte[] Decrypt(byte[] cipherText)
        {
            MemoryStream ms          = new MemoryStream(cipherText);
            Stream       inputStream = PgpUtilities.GetDecoderStream(ms);

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

            PgpPublicKeyEncryptedData pbe = null;

            foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
            {
                pbe = pked;
                break;
            }

            Stream clear = pbe.GetDataStream(SecretKey.ExtractPrivateKey(password.ToCharArray()));

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

            MemoryStream clearStream = new MemoryStream();

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

                Stream unc    = ld.GetInputStream();
                byte[] buffer = new byte[4096];
                int    read;
                while ((read = unc.Read(buffer, 0, buffer.Length)) > 0)
                {
                    clearStream.Write(buffer, 0, read);
                }
            }
            else if (message is PgpOnePassSignatureList)
            {
                throw new PgpException("encrypted message contains a signed message - not literal data.");
            }
            else
            {
                throw new PgpException("message is not a simple encrypted file - type unknown.");
            }

            if (pbe.IsIntegrityProtected())
            {
                if (!pbe.Verify())
                {
                    throw new InvalidDataException("message failed integrity check");
                }
                else
                {
                    Console.Error.WriteLine("message integrity check passed");
                }
            }
            else
            {
                Console.Error.WriteLine("no message integrity check");
            }
            return(clearStream.ToArray());
        }
Пример #9
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);
            }
        }
Пример #10
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;
            }
        }
Пример #11
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);
                }
            }
        }
        /// <summary>
        /// Decrypt a stream using the private key stream.
        /// </summary>
        /// <param name="inputStream">
        /// The stream of the encrypted file.
        /// </param>
        /// <param name="privateKeyStream">
        /// The stream of the private key file.
        /// </param>
        /// <param name="passPhrase">
        /// The pass phrase protecting the secret key.
        /// </param>
        /// <param name="outputFile">
        /// The file path to write the decrypted output to.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/> flag indicating decryption success; false states
        /// decryption failed because of a data integrity check error.
        /// </returns>
        public static bool DecryptFileStream(
            Stream inputStream,
            Stream privateKeyStream,
            string passPhrase,
            string outputFile)
        {
            PgpPrivateKey privateKey = null;
            var           valid      = true;

            try
            {
                PgpEncryptedDataList      encryptedDataList;
                PgpPublicKeyEncryptedData encryptedData = null;

                var objectFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
                var secretKeyRing = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));

                var @object = objectFactory.NextPgpObject();
                if (@object is PgpEncryptedDataList)
                {
                    encryptedDataList = (PgpEncryptedDataList)@object;
                }
                else
                {
                    encryptedDataList = (PgpEncryptedDataList)objectFactory.NextPgpObject();
                }

                foreach (PgpPublicKeyEncryptedData pked in encryptedDataList.GetEncryptedDataObjects())
                {
                    privateKey = PgpKeyHelper.FindSecretKey(secretKeyRing, pked.KeyId, passPhrase.ToCharArray());

                    if (privateKey == null)
                    {
                        continue;
                    }

                    encryptedData = pked;
                    break;
                }

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

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

                var message = plainFact.NextPgpObject();
                if (message is PgpCompressedData)
                {
                    var data = (PgpCompressedData)message;
                    PgpObjectFactory of;

                    using (var compDataIn = data.GetDataStream())
                    {
                        of = new PgpObjectFactory(compDataIn);
                    }

                    message = of.NextPgpObject();
                    if (message is PgpOnePassSignatureList)
                    {
                        message = of.NextPgpObject();
                        var literalData = (PgpLiteralData)message;
                        using (Stream output = File.Create(outputFile))
                        {
                            var unc = literalData.GetInputStream();
                            Streams.PipeAll(unc, output);
                        }
                    }
                    else
                    {
                        var literalData = (PgpLiteralData)message;
                        using (Stream output = File.Create(outputFile))
                        {
                            Stream unc = literalData.GetInputStream();
                            Streams.PipeAll(unc, output);
                        }
                    }
                }
                else if (message is PgpLiteralData)
                {
                    PgpLiteralData literalData = (PgpLiteralData)message;
                    string         unused      = literalData.FileName;

                    using (Stream outputStream = File.Create(outputFile))
                    {
                        Stream unc = literalData.GetInputStream();
                        Streams.PipeAll(unc, outputStream);
                    }
                }
                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 (encryptedData.IsIntegrityProtected())
                {
                    if (!encryptedData.Verify())
                    {
                        Console.Error.WriteLine("Message failed integrity check");
                        valid = false;
                    }
                    else
                    {
                        Console.Error.WriteLine("Message integrity check passed");
                    }
                }
            }
            catch (PgpException exception)
            {
                PgpCommon.DumpException(exception);
                throw;
            }

            return(valid);
        }
        public static Stream DecryptStream(Stream inputStream, Stream keyIn, string password)
        {
            EventLog.Clear();

            if (inputStream == null)
            {
                throw new ArgumentNullException(nameof(inputStream));
            }
            if (keyIn == null)
            {
                throw new ArgumentNullException(nameof(keyIn));
            }

            inputStream = PgpUtilities.GetDecoderStream(inputStream);
            Stream decryptedStream;

            try
            {
                var objectFactory = new PgpObjectFactory(inputStream);

                PgpEncryptedDataList encryptedDataList;

                var pgpObject = objectFactory.NextPgpObject();

                // First object may be a PGP marker packet.  If so skip it.

                if (pgpObject is PgpEncryptedDataList list)
                {
                    encryptedDataList = list;
                }
                else
                {
                    encryptedDataList = (PgpEncryptedDataList)objectFactory.NextPgpObject();
                }

                if (encryptedDataList == null)
                {
                    throw new Exception("Cannot read encrypted data from input!!!  Unable to find PGP Data.  Are you sure this is encrypted?");
                }


                // Find secret key

                PgpPrivateKey privateKey = null;

                PgpPublicKeyEncryptedData encryptedData = null;

                var pgpSec = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn));

                foreach (PgpPublicKeyEncryptedData item in encryptedDataList.GetEncryptedDataObjects())
                {
                    privateKey = FindSecretKey(pgpSec, item.KeyId, password.ToCharArray());

                    if (privateKey == null)
                    {
                        continue;
                    }

                    encryptedData = item;
                    break;
                }

                if (privateKey == null)
                {
                    throw new ArgumentException("Unable to Decrypt - A Secret key for the message was not found.");
                }

                var clear = encryptedData.GetDataStream(privateKey);

                var plainFact = new PgpObjectFactory(clear);

                var message = plainFact.NextPgpObject();

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

                    message = pgpFact.NextPgpObject();
                }

                switch (message)
                {
                case PgpLiteralData ld:
                    decryptedStream = ld.GetInputStream();
                    break;

                case PgpOnePassSignatureList _:
                    throw new PgpException("The encrypted message contains a signed message - not literal data.");

                default:
                    throw new PgpException("The message is not a simple encrypted file - type unknown.");
                }

                if (encryptedData.IsIntegrityProtected())
                {
                    EventLog.Add(!encryptedData.Verify()
                        ? "Message Failed integrity check!!!"
                        : "Message Passed the integrity check.");
                }
                else
                {
                    EventLog.Add("There was no integrity check");
                }
            }
            catch (PgpException e)
            {
                throw (Exception)e;
                //Console.Error.WriteLine(e);

                //if (e.InnerException != null)
                //{
                //    Console.Error.WriteLine(e.InnerException.Message);
                //    Console.Error.WriteLine(e.InnerException.StackTrace);
                //}
            }

            return(decryptedStream);
        }
Пример #14
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.");
                }
            }
        }
Пример #15
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("");
        }
Пример #16
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);

            PgpCompressedData _pgpCompressedData = (PgpCompressedData)_pgpObjectFactoryPrivateKey.NextPgpObject();

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

            PgpObject _pgpObjectMessage = _pgpObjectFactoryCompressedData.NextPgpObject();

            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.");
                }
            }
        }
Пример #17
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="keyIn"></param>
        /// <param name="passwd"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        private static List <string> DecryptFileInAirPlus(Stream inputStream, Stream keyIn, char[] passwd, Encoding end)
        {
            List <string> result = new List <string>();

            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;

                    Stream unc = ld.GetInputStream();

                    result = ToolReadWriteFile.ReadFile(unc, end);
                }

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

                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(null);
            }
        }
Пример #18
0
        public GPGDecryptedDataReturn Decrypt(string data)
        {
            using (var stream = PgpUtilities.GetDecoderStream(Tools.GenerateStreamFromString(data))) {
                var pgpF = new PgpObjectFactory(stream);
                var o    = pgpF.NextPgpObject();
                var enc  = o as PgpEncryptedDataList;
                if (enc == null)
                {
                    enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
                }

                PgpPublicKeyEncryptedData pbe        = null;
                PgpPrivateKey             pgpPrivKey = null;
                PgpSecretKey pgpSec          = null;
                string       lastFingerPrint = "None";
                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    string keyId       = pked.KeyId.ToString("X").ToUpper();
                    string fingerPrint = keyId.Length < 16 ? FP8TO16[Tools.H8FP(keyId)] : Tools.H16FP(keyId);
                    lastFingerPrint = fingerPrint;
                    if (!decryptedKeys.ContainsKey(fingerPrint))
                    {
                        continue;
                    }

                    pgpSec     = privateKeys[fingerPrint];
                    pgpPrivKey = decryptedKeys[fingerPrint];
                    pbe        = pked;
                    break;
                }

                if (pbe == null)
                {
                    throw new KeyNotLoadedException(lastFingerPrint);
                }

                var clear     = pbe.GetDataStream(pgpPrivKey);
                var plainFact = new PgpObjectFactory(clear);
                var message   = plainFact.NextPgpObject();
                var outData   = new GPGDecryptedDataReturn {
                    FingerPrint = lastFingerPrint,
                };
                if (message is PgpCompressedData cData)
                {
                    var pgpFact = new PgpObjectFactory(cData.GetDataStream());
                    message = pgpFact.NextPgpObject();
                }

                if (message is PgpLiteralData ld)
                {
                    outData.Filename = ld.FileName;
                    var    iss    = ld.GetInputStream();
                    byte[] buffer = new byte[16 * 1024];
                    using (var ms = new MemoryStream()) {
                        int read;
                        while ((read = iss.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            ms.Write(buffer, 0, read);
                        }
                        outData.Base64Data = Convert.ToBase64String(ms.ToArray());
                    }
                }
                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.");
                }

                outData.IsIntegrityProtected = pbe.IsIntegrityProtected();

                if (outData.IsIntegrityProtected)
                {
                    outData.IsIntegrityOK = pbe.Verify();
                }

                return(outData);
            }
        }
Пример #19
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.");
            }
        }
        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;
            }
        }
        private static Stream DecryptFileAsStream(
            Stream inputStream,
            Stream keyIn,
            char[] passwd)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);
            MemoryStream outputStream = 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;

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

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

                //                Iterator                    it = enc.GetEncryptedDataObjects();
                //
                //                while (sKey == null && it.hasNext())
                //                {
                //                    pbe = (PgpPublicKeyEncryptedData)it.next();
                //
                //                    sKey = FindSecretKey(keyIn, pbe.KeyID, passwd);
                //                }

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

                Stream           clear     = pbe.GetDataStream(sKey);
                PgpObjectFactory plainFact = new PgpObjectFactory(clear);
                PgpObject        message   = plainFact.NextPgpObject();

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

                    message = pgpFact.NextPgpObject();

                    if (message is PgpOnePassSignatureList)
                    {
                        //throw new PgpException("encrypted message contains a signed message - not literal data.");
                        // file is signed!

                        // verify signature here if you want.
                        PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)message;
                        PgpOnePassSignature     ops = p1[0];
                        // etc…

                        message = pgpFact.NextPgpObject();
                    }
                }
                if (message is PgpLiteralData)
                {
                    PgpLiteralData ld  = (PgpLiteralData)message;
                    Stream         unc = ld.GetInputStream();

                    int ch;
                    while ((ch = unc.ReadByte()) >= 0)
                    {
                        outputStream.WriteByte((byte)ch);
                    }

                    outputStream.Seek(0, SeekOrigin.Begin);
                }
                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");
                }

                return(outputStream);
            }
            catch (PgpException e)
            {
                Console.Error.WriteLine(e);

                Exception underlyingException = e.InnerException;
                if (underlyingException != null)
                {
                    Console.Error.WriteLine(underlyingException.Message);
                    Console.Error.WriteLine(underlyingException.StackTrace);
                }

                throw;
            }
        }
Пример #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="inputStream"></param>
        /// <param name="pgpSecKey"></param>
        /// <param name="passwd"></param>
        /// <param name="pathToSaveFile"></param>
        public static void DecryptFile(
            Stream inputStream,
            PgpSecretKey pgpSecKey,
            char[] passwd,
            string pathToSaveFile)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            var pgpF = new PgpObjectFactory(inputStream);
            PgpEncryptedDataList enc;
            var o = pgpF.NextPgpObject();

            //
            // the first object might be a PGP marker packet.
            //

            if (o is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)o;
            }

            else
            {
                enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
            }

            //
            // find the secret key
            //

            PgpPrivateKey             sKey = null;
            PgpPublicKeyEncryptedData pbe  = null;


            foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
            {
                sKey = pgpSecKey.ExtractPrivateKey(passwd);

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

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

            var clear     = pbe.GetDataStream(sKey);
            var plainFact = new PgpObjectFactory(clear);
            var message   = plainFact.NextPgpObject();

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

            if (message is PgpLiteralData)
            {
                var    ld   = (PgpLiteralData)message;
                Stream fOut = File.Create(pathToSaveFile);
                var    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())
                {
                    throw new PgpException("message failed integrity check");
                }
            }
        }
Пример #23
0
        /**
         * decrypt the passed in message stream
         */
        private static String DecryptFile(
            Stream inputStream,
            Stream keyIn,
            char[] passwd,
            string defaultFileName)
        {
            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();
                }

                String decryptedstring;

                if (message is PgpLiteralData)
                {
                    PgpLiteralData ld  = (PgpLiteralData)message;
                    Stream         unc = ld.GetInputStream();

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

                    //Stream fos = File.Create("C:\\test.epdf");

                    //Streams.PipeAll(unc, fos);
                    //fos.Close();

                    StreamReader reader = new StreamReader(unc);
                    decryptedstring = reader.ReadToEnd();
                }
                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");
                }
                return(decryptedstring);
            }
            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(null);
            }
        }
Пример #24
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;
            }
        }