示例#1
0
        public static PgpPublicKeyEncryptedData ExtractPublicKeyEncryptedData(System.IO.Stream encodedFile)
        {
            PgpEncryptedDataList      encryptedDataList = GetEncryptedDataList(encodedFile);
            PgpPublicKeyEncryptedData publicKeyED       = ExtractPublicKey(encryptedDataList);

            return(publicKeyED);
        }
示例#2
0
        static void Decrypt(Stream encStream, Stream decryptStream)
        {
            PgpObjectFactory     pgpF = new PgpObjectFactory(PgpUtilities.GetDecoderStream(encStream));
            PgpObject            o    = pgpF.NextPgpObject();
            PgpEncryptedDataList enc;

            if (o is PgpEncryptedDataList)
            {
                enc = (PgpEncryptedDataList)o;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
            }
            PgpPublicKeyEncryptedData pbe = null;

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

            using (Stream clear = pbe.GetDataStream(PrivateKey))
            {
                plainFact = new PgpObjectFactory(clear);
            }
            PgpObject message = plainFact.NextPgpObject();

            if (message is PgpCompressedData)
            {
                var cData = (PgpCompressedData)message;
                PgpObjectFactory of;
                using (Stream compDataIn = cData.GetDataStream())
                {
                    of = new PgpObjectFactory(compDataIn);
                }
                message = of.NextPgpObject();
                if (message is PgpOnePassSignatureList)
                {
                    message = of.NextPgpObject();
                }
                PgpLiteralData Ld  = (PgpLiteralData)message;
                Stream         unc = Ld.GetInputStream();
                Streams.PipeAll(unc, decryptStream);
                return;
            }
            if (message is PgpLiteralData)
            {
                PgpLiteralData ld  = (PgpLiteralData)message;
                Stream         unc = ld.GetInputStream();
                Streams.PipeAll(unc, decryptStream);
                return;
            }
            if (message is PgpOnePassSignatureList)
            {
                throw new PgpException("PgpOnePassSignatureList");
            }
            throw new PgpException("Not a simple encrypted file");
        }
        public String DecryptKeycode(String privateKeyStr, String encryptedKeycode)
        {
            byte[] rawMessage = System.Text.Encoding.ASCII.GetBytes(encryptedKeycode);

            Stream inputStream = new MemoryStream(rawMessage);

            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory     pgpF = new PgpObjectFactory(inputStream);
            PgpEncryptedDataList enc  = null;
            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();
            }

            byte[]        decodedPrivateKey = System.Text.Encoding.ASCII.GetBytes(privateKeyStr);
            PgpPrivateKey key = null;

            Stream decodedStream             = PgpUtilities.GetDecoderStream(new MemoryStream(decodedPrivateKey));
            PgpSecretKeyRingBundle privRings = new PgpSecretKeyRingBundle(decodedStream);

            PgpPublicKeyEncryptedData dataObject = null;

            foreach (PgpPublicKeyEncryptedData encryptedData in enc.GetEncryptedDataObjects())
            {
                key        = FindKeyById(privRings, encryptedData.KeyId);
                dataObject = encryptedData;
            }

            if (key == null)
            {
                throw new SendSafely.Exceptions.InvalidKeyException("Can't find encryption key in key ring.");
            }

            Stream dataStream = dataObject.GetDataStream(key);

            PgpObjectFactory pgpFact = new PgpObjectFactory(dataStream);

            PgpLiteralData ld = (PgpLiteralData)pgpFact.NextPgpObject();

            Stream unc = ld.GetInputStream();

            String keycode;

            using (StreamReader reader = new StreamReader(unc, Encoding.UTF8))
            {
                keycode = reader.ReadToEnd();
            }

            return(keycode);
        }
示例#4
0
        public static Stream Decrypt(Stream inputStream, PgpPrivateKey privateKey)
        {
            using Stream decoderStream = PgpUtilities.GetDecoderStream(inputStream);
            PgpObjectFactory          decoderFactory = new(decoderStream);
            PgpEncryptedDataList      dataList       = decoderFactory.NextPgpObject() as PgpEncryptedDataList ?? (PgpEncryptedDataList)decoderFactory.NextPgpObject();
            PgpPublicKeyEncryptedData data           = dataList.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>().First();

            using Stream dataStream = data.GetDataStream(privateKey);
            PgpObjectFactory dataFactory = new(dataStream);

            if (dataFactory.NextPgpObject() is not PgpCompressedData compressedData)
            {
                throw new Exception();
            }
            using Stream compressedStream = compressedData.GetDataStream();
            PgpObjectFactory factory = new(compressedStream);
            PgpLiteralData   literal = factory.NextPgpObject() as PgpLiteralData ?? (PgpLiteralData)factory.NextPgpObject();
            MemoryStream     output  = new();

            using (Stream input = literal.GetInputStream())
            {
                Streams.PipeAll(input, output);
            }
            output.Seek(0L, SeekOrigin.Begin);
            return(output);
        }
示例#5
0
        private void TestDecrypt(PgpSecretKeyRing secretKeyRing)
        {
            PgpObjectFactory pgpF = new PgpObjectFactory(testMessage);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpF.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            PgpSecretKey secretKey = secretKeyRing.GetSecretKey(); // secretKeyRing.GetSecretKey(encP.KeyId);

            //        PgpPrivateKey pgpPrivKey = secretKey.extractPrivateKey(new JcePBESecretKeyEncryptorBuilder());

            //        clear = encP.getDataStream(pgpPrivKey, "BC");
            //
            //        bOut.reset();
            //
            //        while ((ch = clear.read()) >= 0)
            //        {
            //            bOut.write(ch);
            //        }
            //
            //        out = bOut.toByteArray();
            //
            //        if (!AreEqual(out, text))
            //        {
            //            fail("wrong plain text in Generated packet");
            //        }
        }
        private PgpObject getClearCompressedMessage(PgpPublicKeyEncryptedData publicKeyED)
        {
            PgpObjectFactory clearFactory = getClearDataStream(mEncryptionKeys.PrivateKey, publicKeyED);
            PgpObject        message      = clearFactory.NextPgpObject();

            return(message);
        }
示例#7
0
        private void DoTestEncMessage()
        {
            PgpObjectFactory pgpFact = new PgpObjectFactory(encMessage);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            PgpPublicKey publicKey = new PgpPublicKeyRing(testPubKey).GetPublicKey(encP.KeyId);

            PgpSecretKey secretKey = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeySub, false),
                                                                          "test".ToCharArray(), publicKey);

            Stream clear = encP.GetDataStream(secretKey.ExtractPrivateKey(null));

            PgpObjectFactory plainFact = new PgpObjectFactory(clear);

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

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

            PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject();

            if (!"test.txt".Equals(lData.FileName))
            {
                Fail("wrong file name detected");
            }
        }
        private static PgpObjectFactory getClearDataStream(PgpPrivateKey privateKey, PgpPublicKeyEncryptedData publicKeyED)
        {
            Stream           clearStream  = publicKeyED.GetDataStream(privateKey);
            PgpObjectFactory clearFactory = new PgpObjectFactory(clearStream);

            return(clearFactory);
        }
 public void decrypt(Stream input, string outputpath)
 {
     input = PgpUtilities.GetDecoderStream(input);
     try
     {
         PgpObjectFactory     pgpObjF = new PgpObjectFactory(input);
         PgpEncryptedDataList enc;
         PgpObject            obj = pgpObjF.NextPgpObject();
         if (obj is PgpEncryptedDataList)
         {
             enc = (PgpEncryptedDataList)obj;
         }
         else
         {
             enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject();
         }
         PgpPrivateKey             privKey = pgpKeys.PrivateKey;
         PgpPublicKeyEncryptedData pbe     = null;
         foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
         {
             if (privKey != null)
             {
                 pbe = pked;
                 break;
             }
         }
         Stream           clear     = pbe.GetDataStream(privKey);
         PgpObjectFactory plainFact = new PgpObjectFactory(clear);
         PgpObject        message   = plainFact.NextPgpObject();
         if (message is PgpCompressedData)
         {
             PgpCompressedData cData      = (PgpCompressedData)message;
             Stream            compDataIn = cData.GetDataStream();
             PgpObjectFactory  o          = new PgpObjectFactory(compDataIn);
             message = o.NextPgpObject();
             if (message is PgpOnePassSignatureList)
             {
                 message = o.NextPgpObject();
                 PgpLiteralData Ld = null;
                 Ld = (PgpLiteralData)message;
                 Stream output = File.Create(outputpath + "\\" + Ld.FileName);
                 Stream unc    = Ld.GetInputStream();
                 Streams.PipeAll(unc, output);
             }
             else
             {
                 PgpLiteralData Ld = null;
                 Ld = (PgpLiteralData)message;
                 Stream output = File.Create(outputpath + "\\" + Ld.FileName);
                 Stream unc    = Ld.GetInputStream();
                 Streams.PipeAll(unc, output);
             }
         }
     }
     catch (Exception e)
     {
         throw new Exception(e.Message);
     }
 }
示例#10
0
        public static PgpPublicKeyEncryptedData ExtractPublicKeyEncryptedData(System.IO.Stream inputStream)
        {
            System.IO.Stream          encodedFile       = PgpUtilities.GetDecoderStream(inputStream);
            PgpEncryptedDataList      encryptedDataList = GetEncryptedDataList(encodedFile);
            PgpPublicKeyEncryptedData publicKeyED       = ExtractPublicKey(encryptedDataList);

            return(publicKeyED);
        }
        private static PgpPublicKeyEncryptedData extractPublicKeyEncryptedData(Stream inputStream)
        {
            Stream encodedFile = PgpUtilities.GetDecoderStream(inputStream);
            PgpEncryptedDataList      encryptedDataList = getEncryptedDataList(encodedFile);
            PgpPublicKeyEncryptedData publicKeyED       = extractPublicKey(encryptedDataList);

            return(publicKeyED);
        }
示例#12
0
        public string DecryptKeycode(string privateKeyStr, string encryptedKeycode)
        {
            var rawMessage = Encoding.ASCII.GetBytes(encryptedKeycode);

            Stream inputStream = new MemoryStream(rawMessage);

            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 list)
            {
                enc = list;
            }
            else
            {
                enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
            }

            var           decodedPrivateKey = Encoding.ASCII.GetBytes(privateKeyStr);
            PgpPrivateKey key = null;

            var decodedStream = PgpUtilities.GetDecoderStream(new MemoryStream(decodedPrivateKey));
            var privRings     = new PgpSecretKeyRingBundle(decodedStream);

            PgpPublicKeyEncryptedData dataObject = null;

            foreach (PgpPublicKeyEncryptedData encryptedData in enc.GetEncryptedDataObjects())
            {
                key        = FindKeyById(privRings, encryptedData.KeyId);
                dataObject = encryptedData;
            }

            if (key == null)
            {
                throw new InvalidKeyException("Can't find encryption key in key ring.");
            }

            var dataStream = dataObject.GetDataStream(key);

            var pgpFact = new PgpObjectFactory(dataStream);

            var ld = (PgpLiteralData)pgpFact.NextPgpObject();

            var unc = ld.GetInputStream();

            using var reader = new StreamReader(unc, Encoding.UTF8);
            var keycode = reader.ReadToEnd();

            return(keycode);
        }
示例#13
0
        private PgpObject GetClearCompressedMessage(PgpPublicKeyEncryptedData publicKeyED, ChoPGPEncryptionKeys encryptionKeys)
        {
            PgpObjectFactory clearFactory = GetClearDataStream(encryptionKeys.PrivateKey, publicKeyED);
            PgpObject        message      = clearFactory.NextPgpObject();

            if (message is PgpOnePassSignatureList)
            {
                message = clearFactory.NextPgpObject();
            }
            return(message);
        }
示例#14
0
 private void VerifyEncryptedData(PgpPublicKeyEncryptedData encryptedData)
 {
     if (!encryptedData.IsIntegrityProtected())
     {
         return;
     }
     if (!encryptedData.Verify())
     {
         throw new PgpException("Message integrity check failed.");
     }
 }
示例#15
0
        private void DoTestSignedEncMessage()
        {
            PgpObjectFactory pgpFact = new PgpObjectFactory(signedEncMessage);

            PgpEncryptedDataList encList = (PgpEncryptedDataList)pgpFact.NextPgpObject();

            PgpPublicKeyEncryptedData encP = (PgpPublicKeyEncryptedData)encList[0];

            PgpPublicKeyRing publicKeyRing = new PgpPublicKeyRing(testPubKey);

            PgpPublicKey publicKey = publicKeyRing.GetPublicKey(encP.KeyId);

            PgpSecretKey secretKey = PgpSecretKey.ParseSecretKeyFromSExpr(new MemoryStream(sExprKeySub, false),
                                                                          "test".ToCharArray(), publicKey);

            Stream clear = encP.GetDataStream(secretKey.ExtractPrivateKey(null));

            PgpObjectFactory plainFact = new PgpObjectFactory(clear);

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

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

            PgpOnePassSignatureList sList = (PgpOnePassSignatureList)compFact.NextPgpObject();

            PgpOnePassSignature ops = sList[0];

            PgpLiteralData lData = (PgpLiteralData)compFact.NextPgpObject();

            if (!"test.txt".Equals(lData.FileName))
            {
                Fail("wrong file name detected");
            }

            Stream dIn = lData.GetInputStream();

            ops.InitVerify(publicKeyRing.GetPublicKey(ops.KeyId));

            int ch;

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

            PgpSignatureList p3 = (PgpSignatureList)compFact.NextPgpObject();

            if (!ops.Verify(p3[0]))
            {
                Fail("Failed signature check");
            }
        }
        private static PgpPublicKeyEncryptedData extractPublicKey(PgpEncryptedDataList encryptedDataList)
        {
            PgpPublicKeyEncryptedData publicKeyED = null;

            foreach (PgpPublicKeyEncryptedData privateKeyED in encryptedDataList.GetEncryptedDataObjects())
            {
                if (privateKeyED != null)
                {
                    publicKeyED = privateKeyED;
                    break;
                }
            }
            return(publicKeyED);
        }
        /// <summary>
        /// Process each message block type depending on the type.
        /// </summary>
        /// <param name="encryptedData">
        /// Encrypted data packets.
        /// </param>
        /// <param name="outputStream">
        /// Stream to write output.
        /// </param>
        /// <param name="publicKeyStream">
        /// Public key stream for validating signature.
        /// </param>
        /// <param name="privateKey">
        /// Private key for decrypting data.
        /// </param>
        /// <returns>
        /// Return true if the data is valid; false otherwise.
        /// </returns>
        private static bool ProcessDecryptionMessageBlocks(
            PgpPublicKeyEncryptedData encryptedData,
            Stream outputStream,
            Stream publicKeyStream,
            PgpPrivateKey privateKey)
        {
            var valid = true;
            PgpOnePassSignatureList onePassSignatureList = null;
            PgpOnePassSignature     onePassSignature     = null;
            PgpPublicKey            publicKey            = null;

            var clear     = encryptedData.GetDataStream(privateKey);
            var plainFact = new PgpObjectFactory(clear);
            var message   = plainFact.NextPgpObject();

            while (message != null)
            {
                Console.WriteLine(message.ToString());
                if (message is PgpCompressedData)
                {
                    var compressedData = (PgpCompressedData)message;
                    plainFact = new PgpObjectFactory(compressedData.GetDataStream());
                }
                else if (message is PgpLiteralData)
                {
                    onePassSignature = InitOnePassSignatureFromLiteral(
                        publicKeyStream,
                        onePassSignatureList,
                        ref publicKey);

                    ProcessDecryptionStreams(outputStream, message, onePassSignature);
                }
                else if (message is PgpOnePassSignatureList)
                {
                    onePassSignatureList = (PgpOnePassSignatureList)message;
                }
                else if (message is PgpSignatureList)
                {
                    valid = VerifyOnePassSignature(message, onePassSignature, publicKey, valid);
                }
                else
                {
                    throw new PgpException("message unknown message type.");
                }

                message = plainFact.NextPgpObject();
            }

            return(valid);
        }
示例#18
0
        private bool Verify(Stream inputStream, Stream publicKeyStream)
        {
            PgpPublicKeyEncryptedData publicKeyED = Utilities.ExtractPublicKeyEncryptedData(inputStream);
            PgpPublicKey publicKey = Utilities.ReadPublicKey(publicKeyStream);

            if (publicKeyED.KeyId == publicKey.KeyId)
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
示例#19
0
        private void decryptAndVerify(Stream inputStream, Stream outputStream)
        {
            PgpPublicKeyEncryptedData publicKeyED = extractPublicKeyEncryptedData(inputStream);
            PgpObject message = getClearCompressedMessage(publicKeyED);

            if (message is PgpCompressedData)
            {
                message = processCompressedMessage(message);
                PgpLiteralData literalData = (PgpLiteralData)message;
                using (Stream literalDataStream = literalData.GetInputStream())
                {
                    Streams.PipeAll(literalDataStream, outputStream);
                }
            }

            return;
        }
示例#20
0
        private static PgpObjectFactory RetrievePgpObjectFactory(PgpEncryptedDataList dataList, PgpSecretKeyRingBundle secretKeyRing, string passPhrase)
        {
            PgpPublicKeyEncryptedData publicKeyEncryptedData = dataList.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>()
                                                               .FirstOrDefault(dd => FindSecretKeyByKeyId(secretKeyRing, dd.KeyId, passPhrase.ToCharArray()) != null);

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

            PgpPrivateKey privateKey = FindSecretKeyByKeyId(secretKeyRing, publicKeyEncryptedData.KeyId, passPhrase.ToCharArray());

            using (Stream stream = publicKeyEncryptedData.GetDataStream(privateKey))
            {
                return(new PgpObjectFactory(stream));
            }
        }
        private string Decrypt(Stream input, PgpSecretKey secretKey, string passPhrase)
        {
            input = PgpUtilities.GetDecoderStream(input);

            PgpObjectFactory     pgpObjF = new PgpObjectFactory(input);
            PgpEncryptedDataList enc;
            PgpObject            obj = pgpObjF.NextPgpObject();

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

            PgpPublicKeyEncryptedData pbe = enc.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>().First();
            Stream        clear;
            PgpPrivateKey privateKey = secretKey.ExtractPrivateKey(passPhrase.ToCharArray());

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

            if (message is PgpCompressedData)
            {
                PgpCompressedData cData      = (PgpCompressedData)message;
                Stream            compDataIn = cData.GetDataStream();
                PgpObjectFactory  o          = new PgpObjectFactory(compDataIn);
                message = o.NextPgpObject();
                if (message is PgpOnePassSignatureList)
                {
                    message = o.NextPgpObject();
                }

                var ld     = (PgpLiteralData)message;
                var unc    = ld.GetInputStream();
                var reader = new StreamReader(unc);
                return(reader.ReadToEnd());
            }

            throw new NotImplementedException();
        }
 public PgpEncryptedDataList(BcpgInputStream bcpgInput)
 {
     while (bcpgInput.NextPacketTag() == PacketTag.PublicKeyEncryptedSession || bcpgInput.NextPacketTag() == PacketTag.SymmetricKeyEncryptedSessionKey)
     {
         list.Add(bcpgInput.ReadPacket());
     }
     data = (InputStreamPacket)bcpgInput.ReadPacket();
     for (int i = 0; i != list.Count; i++)
     {
         if (list[i] is SymmetricKeyEncSessionPacket)
         {
             list[i] = new PgpPbeEncryptedData((SymmetricKeyEncSessionPacket)list[i], data);
         }
         else
         {
             list[i] = new PgpPublicKeyEncryptedData((PublicKeyEncSessionPacket)list[i], data);
         }
     }
 }
        /// <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);
        }
示例#24
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);
            }
        }
        /*
         * decrypt a given stream.
         */

        public static void Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase, string outputFile)
        {
            try
            {
                PgpObjectFactory          pgpF   = null;
                PgpEncryptedDataList      enc    = null;
                PgpObject                 o      = null;
                PgpPrivateKey             sKey   = null;
                PgpPublicKeyEncryptedData pbe    = null;
                PgpSecretKeyRingBundle    pgpSec = null;

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

                if (pgpF != null)
                {
                    o = pgpF.NextPgpObject();
                }

                // the first object might be a PGP marker packet.
                if (o is PgpEncryptedDataList)
                {
                    enc = (PgpEncryptedDataList)o;
                }
                else
                {
                    enc = (PgpEncryptedDataList)pgpF.NextPgpObject();
                }

                // decrypt
                foreach (PgpPublicKeyEncryptedData pked in enc.GetEncryptedDataObjects())
                {
                    sKey = FindSecretKey(pgpSec, pked.KeyId, passPhrase.ToCharArray());

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

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

                PgpObjectFactory plainFact = null;

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

                PgpObject message = plainFact.NextPgpObject();

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

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

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

                    using (Stream fOut = File.Create(outputFile))
                    {
                        Stream unc = ld.GetInputStream();
                        Streams.PipeAll(unc, fOut);
                    }
                }
                else if (message is PgpOnePassSignatureList)
                {
                    throw new PgpException("Encrypted message contains a signed message - not literal data.");
                }
                else
                {
                    throw new PgpException("Message is not a simple encrypted file - type unknown.");
                }

                #region commented code

                //if (pbe.IsIntegrityProtected())
                //{
                //    if (!pbe.Verify())
                //        msg = "message failed integrity check.";
                //    //Console.Error.WriteLine("message failed integrity check");
                //    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");
                //}

                #endregion commented code
            }
            catch (PgpException ex)
            {
                throw;
            }
        }
示例#26
0
        /// <summary>
        /// Decrypt file
        /// </summary>
        /// <param name="inputStream">Encrypted file</param>
        /// <param name="privateKeyStream">Private key</param>
        /// <param name="passPhrase">Passphrase</param>
        /// <returns></returns>
        public PgpLiteralData Decrypt(Stream inputStream, Stream privateKeyStream, string passPhrase)
        {
            try
            {
                PgpObject pgpObj        = null;
                var       pgpObjFactory = new PgpObjectFactory(PgpUtilities.GetDecoderStream(inputStream));
                var       pgpScrKey     = new PgpSecretKeyRingBundle(PgpUtilities.GetDecoderStream(privateKeyStream));

                if (pgpObjFactory != null)
                {
                    pgpObj = pgpObjFactory.NextPgpObject();
                }

                PgpEncryptedDataList pgpEncrDataList = null;
                // the first object might be a PGP marker packet.
                if (pgpObj is PgpEncryptedDataList)
                {
                    pgpEncrDataList = (PgpEncryptedDataList)pgpObj;
                }
                else
                {
                    pgpEncrDataList = (PgpEncryptedDataList)pgpObjFactory.NextPgpObject();
                }

                PgpPrivateKey             pgpPrvtKey         = null;
                PgpPublicKeyEncryptedData pgpPblcKeyEncrData = null;
                // decrypt
                foreach (PgpPublicKeyEncryptedData pked in pgpEncrDataList.GetEncryptedDataObjects())
                {
                    pgpPrvtKey = FindSecretKey(pgpScrKey, pked.KeyId, passPhrase.ToCharArray());

                    if (pgpPrvtKey != null)
                    {
                        pgpPblcKeyEncrData = pked;
                        break;
                    }
                }

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


                using (Stream clear = pgpPblcKeyEncrData.GetDataStream(pgpPrvtKey))
                {
                    var plainFact = new PgpObjectFactory(clear);

                    PgpObject pgpFile = plainFact.NextPgpObject();

                    if (pgpFile is PgpCompressedData cData)
                    {
                        using (Stream compDataIn = cData.GetDataStream())
                        {
                            var of = new PgpObjectFactory(compDataIn);
                            pgpFile = of.NextPgpObject();
                            if (pgpFile is PgpOnePassSignatureList)
                            {
                                pgpFile = of.NextPgpObject();
                                return((PgpLiteralData)pgpFile);
                            }
                            else
                            {
                                return((PgpLiteralData)pgpFile);
                            }
                        }
                    }
                    else if (pgpFile is PgpLiteralData)
                    {
                        return((PgpLiteralData)pgpFile);
                    }
                    else if (pgpFile is PgpOnePassSignatureList)
                    {
                        throw new PgpException("Encrypted file contains a signed data - not literal data.");
                    }
                    else
                    {
                        throw new PgpException("File is not a simple encrypted file - type unknown.");
                    }
                }
            }
            catch (PgpException ex)
            {
                //TODO: Add log
                throw ex;
            }
        }
示例#27
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);
                }
            }
        }
        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;
            }
        }
示例#29
0
        public void DecryptFileAndVerify(string inputFilePath, string outputFilePath, string publicKeyFilePath, string privateKeyFilePath, string passPhrase)
        {
            if (String.IsNullOrEmpty(inputFilePath))
            {
                throw new ArgumentException(nameof(inputFilePath));
            }
            if (String.IsNullOrEmpty(outputFilePath))
            {
                throw new ArgumentException(nameof(outputFilePath));
            }
            if (String.IsNullOrEmpty(publicKeyFilePath))
            {
                throw new ArgumentException(nameof(publicKeyFilePath));
            }
            if (String.IsNullOrEmpty(privateKeyFilePath))
            {
                throw new ArgumentException(nameof(privateKeyFilePath));
            }
            if (passPhrase == null)
            {
                passPhrase = String.Empty;
            }

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

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

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

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

                PgpObject message = GetClearCompressedMessage(publicKeyED, encryptionKeys);

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

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

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

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

            PgpPublicKeyEncryptedData publicKeyED = ExtractPublicKeyEncryptedData(inputStream);

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

            PgpObject message = GetClearCompressedMessage(publicKeyED, encryptionKeys);

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

            return;
        }