Exemplo n.º 1
0
 private static void Decrypt(PgpLiteralData objLiteral, Stream outputStream)
 {
     using (var ms = objLiteral.GetInputStream())
     {
         Org.BouncyCastle.Utilities.IO.Streams.PipeAll(ms, outputStream);
     }
 }
Exemplo n.º 2
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);
        }
Exemplo n.º 3
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");
        }
Exemplo n.º 4
0
        private void doSigVerifyTest(
            string publicKeyFile,
            string sigFile)
        {
            PgpPublicKeyRing publicKey = loadPublicKey(publicKeyFile);
            PgpObjectFactory pgpFact   = loadSig(sigFile);

            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

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

            PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops = p1[0];

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

            Stream dIn = p2.GetInputStream();

            ops.InitVerify(publicKey.GetPublicKey());

            int ch;

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

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

            Assert.IsTrue(ops.Verify(p3[0]));
        }
        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);
        }
Exemplo n.º 6
0
        /// <summary>
        ///     Verifies the specified signature using the specified public key.
        /// </summary>
        /// <param name="input">The signature to verify.</param>
        /// <param name="publicKey">The public key with which to decode the signature.</param>
        /// <returns>A byte array containing the message contained within the signature.</returns>
        /// <exception cref="PgpDataValidationException">
        ///     Thrown when the specified signature is invalid, or if an exception is encountered while validating.
        /// </exception>
        public static byte[] Verify(string input, string publicKey)
        {
            // create input streams from
            Stream inputStream     = new MemoryStream(Encoding.UTF8.GetBytes(input ?? string.Empty));
            Stream publicKeyStream = new MemoryStream(Encoding.UTF8.GetBytes(publicKey ?? string.Empty));

            // enclose all operations in a try/catch. if we encounter any exceptions verification fails.
            try
            {
                // lines taken pretty much verbatim from the bouncycastle example. not sure what it all does.
                inputStream = PgpUtilities.GetDecoderStream(inputStream);

                PgpObjectFactory  pgpFact = new PgpObjectFactory(inputStream);
                PgpCompressedData c1      = (PgpCompressedData)pgpFact.NextPgpObject();
                pgpFact = new PgpObjectFactory(c1.GetDataStream());

                PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
                PgpOnePassSignature     ops = p1[0];

                PgpLiteralData         p2      = (PgpLiteralData)pgpFact.NextPgpObject();
                Stream                 dIn     = p2.GetInputStream();
                PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(publicKeyStream));
                PgpPublicKey           key     = pgpRing.GetPublicKey(ops.KeyId);

                // set up a memorystream to contain the message contained within the signature
                MemoryStream memoryStream = new MemoryStream();

                ops.InitVerify(key);

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

                // save the contents of the memorystream to a byte array
                byte[] retVal = memoryStream.ToArray();

                memoryStream.Close();

                PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
                PgpSignature     firstSig = p3[0];

                // verify.
                if (ops.Verify(firstSig))
                {
                    return(retVal);
                }
                else
                {
                    throw new PgpDataValidationException();
                }
            }
            catch (Exception)
            {
                throw new PgpDataValidationException();
            }
        }
 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);
     }
 }
Exemplo n.º 8
0
        /// <summary>
        /// Verifies a PGP signature. See documentation at https://github.com/CommunityHiQ/Frends.Community.PgpVerifySignature Returns: Object {string FilePath, Boolean Verified}
        /// </summary>
        public static Result PGPVerifySignFile(Input input)
        {
            try
            {
                Stream inputStream = PgpUtilities.GetDecoderStream(File.OpenRead(input.InputFile));

                PgpObjectFactory        pgpFact = new PgpObjectFactory(inputStream);
                PgpOnePassSignatureList p1      = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
                PgpOnePassSignature     ops     = p1[0];

                PgpLiteralData         p2      = (PgpLiteralData)pgpFact.NextPgpObject();
                Stream                 dIn     = p2.GetInputStream();
                PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(File.OpenRead(input.PublicKeyFile)));
                PgpPublicKey           key     = pgpRing.GetPublicKey(ops.KeyId);

                string fosPath;
                if (String.IsNullOrWhiteSpace(input.OutputFolder))
                {
                    fosPath = Path.Combine(Path.GetDirectoryName(input.InputFile), p2.FileName);
                }
                else
                {
                    fosPath = Path.Combine(input.OutputFolder, p2.FileName);
                }
                Stream fos = File.Create(fosPath);

                ops.InitVerify(key);

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

                PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
                PgpSignature     firstSig = p3[0];
                bool             verified = ops.Verify(firstSig);

                Result ret = new Result
                {
                    FilePath = fosPath,
                    Verified = verified
                };

                return(ret);
            }
            catch (Exception e)
            {
                Result ret = new Result
                {
                    FilePath = input.OutputFolder,
                    Verified = false
                };

                return(ret);
            }
        }
Exemplo n.º 9
0
 private static void PipeStreamToFile(string outputFilePath, PgpLiteralData literalData)
 {
     using (Stream fileStream = File.Create(outputFilePath))
     {
         Stream decryptedStream = literalData.GetInputStream();
         Streams.PipeAll(decryptedStream, fileStream);
     }
 }
Exemplo n.º 10
0
        private void verifySignature(
            byte[] encodedSig,
            HashAlgorithmTag hashAlgorithm,
            PgpPublicKey pubKey,
            byte[] original)
        {
            PgpObjectFactory        pgpFact = new PgpObjectFactory(encodedSig);
            PgpOnePassSignatureList p1      = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops     = p1[0];
            PgpLiteralData          p2      = (PgpLiteralData)pgpFact.NextPgpObject();
            Stream dIn = p2.GetInputStream();

            ops.InitVerify(pubKey);

            int ch;

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

            PgpSignatureList p3  = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     sig = p3[0];

            DateTime creationTime = sig.CreationTime;

            // Check creationTime is recent
            if (creationTime.CompareTo(DateTime.UtcNow) > 0 ||
                creationTime.CompareTo(DateTime.UtcNow.AddMinutes(-10)) < 0)
            {
                Fail("bad creation time in signature: " + creationTime);
            }

            if (sig.KeyId != pubKey.KeyId)
            {
                Fail("key id mismatch in signature");
            }

            if (!ops.Verify(sig))
            {
                Fail("Failed generated signature check - " + hashAlgorithm);
            }

            sig.InitVerify(pubKey);

            for (int i = 0; i != original.Length; i++)
            {
                sig.Update(original[i]);
            }

            sig.Update(original);

            if (!sig.Verify())
            {
                Fail("Failed generated signature check against original data");
            }
        }
Exemplo n.º 11
0
        public static Stream Decrypt(Stream input, String privateKeyPath, String privateKeyPass)
        {
            input = PgpUtilities.GetDecoderStream(input);
            try
            {
                var pgpObjF = new PgpObjectFactory(input);
                PgpEncryptedDataList enc;
                var obj = pgpObjF.NextPgpObject();
                if (obj is PgpEncryptedDataList)
                {
                    enc = (PgpEncryptedDataList)obj;
                }
                else
                {
                    enc = (PgpEncryptedDataList)pgpObjF.NextPgpObject();
                }

                foreach (PgpPublicKeyEncryptedData pbe in enc.GetEncryptedDataObjects().Cast <PgpPublicKeyEncryptedData>())
                {
                    var privKey = GetPrivateKey(privateKeyPath, pbe.KeyId, privateKeyPass);
                    if (privKey == null)
                    {
                        continue;
                    }
                    Stream clear;
                    clear = pbe.GetDataStream(privKey);
                    var plainFact = new PgpObjectFactory(clear);
                    var message   = plainFact.NextPgpObject();
                    if (message is PgpCompressedData)
                    {
                        var cData      = (PgpCompressedData)message;
                        var compDataIn = cData.GetDataStream();
                        var o          = new PgpObjectFactory(compDataIn);
                        message = o.NextPgpObject();
                        if (message is PgpOnePassSignatureList)
                        {
                            message = o.NextPgpObject();
                            PgpLiteralData Ld = null;
                            Ld = (PgpLiteralData)message;
                            return(Ld.GetInputStream());
                        }
                        else
                        {
                            PgpLiteralData Ld = null;
                            Ld = (PgpLiteralData)message;
                            return(Ld.GetInputStream());
                        }
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            return(null);
        }
Exemplo n.º 12
0
        public static bool Verify(string hash, string signature, string publicKey)
        {
            try {
                var signatureStream = new MemoryStream(Encoding.ASCII.GetBytes(signature));
                var decoderStream   = PgpUtilities.GetDecoderStream(signatureStream);

                PgpObjectFactory pgpObjectFactory = new PgpObjectFactory(decoderStream);

                PgpOnePassSignatureList signatureList    = (PgpOnePassSignatureList)pgpObjectFactory.NextPgpObject();
                PgpOnePassSignature     onePassSignature = signatureList[0];

                PgpLiteralData         literalData   = (PgpLiteralData)pgpObjectFactory.NextPgpObject();
                Stream                 literalStream = literalData.GetInputStream();
                Stream                 keyFile       = new MemoryStream(Encoding.ASCII.GetBytes(publicKey));
                PgpPublicKeyRingBundle pgpRing       = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyFile));
                PgpPublicKey           key           = pgpRing.GetPublicKey(onePassSignature.KeyId);
                Stream                 outStream     = new MemoryStream();

                onePassSignature.InitVerify(key);

                int ch;
                while ((ch = literalStream.ReadByte()) >= 0)
                {
                    onePassSignature.Update((byte)ch);
                    outStream.WriteByte((byte)ch);
                }
                var hashStream = new MemoryStream(Encoding.ASCII.GetBytes(hash));
                outStream.Seek(0, SeekOrigin.Begin);
                if (hashStream.Length != outStream.Length)
                {
                    return(false);
                }
                int left, right;
                while ((left = hashStream.ReadByte()) >= 0 && (right = outStream.ReadByte()) >= 0)
                {
                    if (left != right)
                    {
                        return(false);
                    }
                }
                outStream.Dispose();

                PgpSignatureList signatureList2 = (PgpSignatureList)pgpObjectFactory.NextPgpObject();
                PgpSignature     firstSig       = signatureList2[0];
                if (onePassSignature.Verify(firstSig))
                {
                    return(true);
                }
                else
                {
                    return(false);
                }
            } catch {
                return(false);
            }
        }
Exemplo n.º 13
0
        public String DecryptMessage(String encryptedMessage, char[] passPhrase)
        {
            // Remove the Base64 encoding
            byte[] rawMessage = Convert.FromBase64String(encryptedMessage);

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

            PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0];

            Stream clear = pbe.GetDataStream(passPhrase);

            PgpObjectFactory pgpFact = new PgpObjectFactory(clear);

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

            Stream unc = ld.GetInputStream();

            String message;

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

            // Finally verify the integrity
            if (pbe.IsIntegrityProtected())
            {
                if (!pbe.Verify())
                {
                    throw new MessageVerificationException("Failed to verify the message. It might have been modified in transit.");
                }
            }

            return(message);
        }
Exemplo n.º 14
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");
            }
        }
Exemplo n.º 15
0
        public void DecryptFile(Stream outStream, Stream inputStream, char[] passPhrase)
        {
            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();
            }

            PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0];

            Stream clear = pbe.GetDataStream(passPhrase);

            PgpObjectFactory pgpFact = new PgpObjectFactory(clear);

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

            Stream unc = ld.GetInputStream();

            byte[] buf = new byte[1 << 16];
            int    len;

            while ((len = unc.Read(buf, 0, buf.Length)) > 0)
            {
                outStream.Write(buf, 0, len);
            }

            // Finally verify the integrity
            if (pbe.IsIntegrityProtected())
            {
                if (!pbe.Verify())
                {
                    throw new MessageVerificationException("Failed to verify the message. It might have been modified in transit.");
                }
            }
        }
        private byte[] DecryptMessageBuffered(
            byte[] message)
        {
            PgpObjectFactory     pgpF = new PgpObjectFactory(message);
            PgpEncryptedDataList enc  = (PgpEncryptedDataList)pgpF.NextPgpObject();
            PgpPbeEncryptedData  pbe  = (PgpPbeEncryptedData)enc[0];

            Stream clear = pbe.GetDataStream(pass);

            PgpObjectFactory  pgpFact = new PgpObjectFactory(clear);
            PgpCompressedData cData   = (PgpCompressedData)pgpFact.NextPgpObject();

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

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

            MemoryStream bOut = new MemoryStream();

            if (!ld.FileName.Equals("test.txt") &&
                !ld.FileName.Equals("_CONSOLE"))
            {
                Fail("wrong filename in packet");
            }
            if (!ld.ModificationTime.Equals(TestDateTime))
            {
                Fail("wrong modification time in packet: " + ld.ModificationTime.Ticks + " " + TestDateTime.Ticks);
            }

            Stream unc = ld.GetInputStream();

            byte[] buf = new byte[1024];

            int len;

            while ((len = unc.Read(buf, 0, buf.Length)) > 0)
            {
                bOut.Write(buf, 0, len);
            }

            if (pbe.IsIntegrityProtected() && !pbe.Verify())
            {
                Fail("integrity check failed");
            }

            return(bOut.ToArray());
        }
Exemplo n.º 17
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;
        }
Exemplo n.º 18
0
        /*.......................................................................檔案數認證開始*/

        /*首先傳送端將訊息經過雜湊演算法計算後得到一個雜湊值,再利用它的私有鑰匙向雜湊值加密成為一個數位簽章(DS),接著,再將數位簽章附加在訊息後面一併傳送出去;
         * 接收端收到訊息之後,以同樣的雜湊演算計算出雜湊值(H’),並利用傳送端的公開鑰匙將 DS 解密,得到另一端的雜湊值(H)。
         * 接著,比較兩個雜湊值,如果相同的話,則可以確定該訊息的『完整性』(雜湊值相同),此外也可以確定其『不可否認性』(私有鑰匙與公開鑰匙配對)。*/

        /*
         * 簽章後的hash值 -> 公鑰(對方)解密 -> hash值
         * 解密後的文章 -> hash -> 解密後文章的hash值
         */


        private static void VerifyFile(
            Stream inputStream,   //預計數位認證原始檔案的資料流
            Stream keyIn,         //簽名方(對方)公鑰的資料流
            string outputFileName //預計匯出(數位認證後檔案)的完整路徑
            )
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream); //串流陣列化 byte Array
            PgpObjectFactory pgpFact = new PgpObjectFactory(inputStream);

            PgpCompressedData c1 = (PgpCompressedData)pgpFact.NextPgpObject();

            pgpFact = new PgpObjectFactory(c1.GetDataStream()); //解壓縮
            PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops = p1[0];
            PgpLiteralData          p2  = (PgpLiteralData)pgpFact.NextPgpObject();
            Stream dIn = p2.GetInputStream();

            PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn));
            PgpPublicKey           key     = pgpRing.GetPublicKey(ops.KeyId); //取出公鑰

            Stream fileOutput = File.Create(outputFileName);                  //預計匯出檔案建立

            ops.InitVerify(key);                                              //驗證公鑰是否符合
            int ch;

            while ((ch = dIn.ReadByte()) >= 0)
            {
                ops.Update((byte)ch);           //進行解密
                fileOutput.WriteByte((byte)ch); //寫入預計匯出檔案
            }
            fileOutput.Close();
            fileOutput.Dispose();

            PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     firstSig = p3[0];

            if (ops.Verify(firstSig)) //Hash值比較
            {
                Console.Out.WriteLine("signature verified.");
            }
            else
            {
                Console.Out.WriteLine("signature verification failed.");
            }
        }
        /**
         * verify the passed in file as being correctly signed.
         */
        private static void VerifyFile(
            Stream inputStream,
            Stream keyIn)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);

            PgpObjectFactory  pgpFact = new PgpObjectFactory(inputStream);
            PgpCompressedData c1      = (PgpCompressedData)pgpFact.NextPgpObject();

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

            PgpOnePassSignatureList p1  = (PgpOnePassSignatureList)pgpFact.NextPgpObject();
            PgpOnePassSignature     ops = p1[0];

            PgpLiteralData         p2      = (PgpLiteralData)pgpFact.NextPgpObject();
            Stream                 dIn     = p2.GetInputStream();
            PgpPublicKeyRingBundle pgpRing = new PgpPublicKeyRingBundle(PgpUtilities.GetDecoderStream(keyIn));
            IPgpPublicKey          key     = pgpRing.GetPublicKey(ops.KeyId);
            Stream                 fos     = File.Create(p2.FileName);

            ops.InitVerify(key);

            int ch;

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

            PgpSignatureList p3       = (PgpSignatureList)pgpFact.NextPgpObject();
            PgpSignature     firstSig = p3[0];

            if (ops.Verify(firstSig))
            {
                Console.Out.WriteLine("signature verified.");
            }
            else
            {
                Console.Out.WriteLine("signature verification failed.");
            }
        }
Exemplo n.º 20
0
        /**
         * decrypt the passed in message stream
         *
         * @param encrypted  The message to be decrypted.
         * @param passPhrase Pass phrase (key)
         *
         * @return Clear text as a byte array.  I18N considerations are
         *         not handled by this routine
         * @exception IOException
         * @exception PgpException
         */
        public static byte[] Decrypt(
            byte[] encrypted,
            char[] passPhrase)
        {
            Stream inputStream = new MemoryStream(encrypted);

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

            PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0];

            Stream clear = pbe.GetDataStream(passPhrase);

            PgpObjectFactory pgpFact = new PgpObjectFactory(clear);

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

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

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

            Stream unc = ld.GetInputStream();

            return(Streams.ReadAll(unc));
        }
Exemplo n.º 21
0
        private void ReadBackTest(
            PgpLiteralDataGenerator generator)
        {
            Random rand = new Random();

            byte[] buf = new byte[MAX];

            rand.NextBytes(buf);

            for (int i = 1; i != MAX; i++)
            {
                MemoryStream bOut = new MemoryStream();

                Stream outputStream = generator.Open(
                    new UncloseableStream(bOut),
                    PgpLiteralData.Binary,
                    PgpLiteralData.Console,
                    i,
                    DateTime.UtcNow);

                outputStream.Write(buf, 0, i);

                generator.Close();

                PgpObjectFactory fact = new PgpObjectFactory(bOut.ToArray());

                PgpLiteralData data = (PgpLiteralData)fact.NextPgpObject();

                Stream inputStream = data.GetInputStream();

                for (int count = 0; count != i; count++)
                {
                    if (inputStream.ReadByte() != (buf[count] & 0xff))
                    {
                        Fail("failed readback test - length = " + i);
                    }
                }
            }
        }
        /**
         * decrypt the passed in message stream
         */
        private byte[] DecryptMessage(
            byte[] message)
        {
            PgpObjectFactory     pgpF = new PgpObjectFactory(message);
            PgpEncryptedDataList enc  = (PgpEncryptedDataList)pgpF.NextPgpObject();
            PgpPbeEncryptedData  pbe  = (PgpPbeEncryptedData)enc[0];
            Stream clear = pbe.GetDataStream(pass);

            PgpObjectFactory  pgpFact = new PgpObjectFactory(clear);
            PgpCompressedData cData   = (PgpCompressedData)pgpFact.NextPgpObject();

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

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

            if (!ld.FileName.Equals("test.txt") &&
                !ld.FileName.Equals("_CONSOLE"))
            {
                Fail("wrong filename in packet");
            }

            if (!ld.ModificationTime.Equals(TestDateTime))
            {
                Fail("wrong modification time in packet: " + ld.ModificationTime + " vs " + TestDateTime);
            }

            Stream unc = ld.GetInputStream();

            byte[] bytes = Streams.ReadAll(unc);

            if (pbe.IsIntegrityProtected() && !pbe.Verify())
            {
                Fail("integrity check failed");
            }

            return(bytes);
        }
Exemplo n.º 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);
            }
        }
Exemplo n.º 24
0
        /*
         * 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;
            }
        }
Exemplo n.º 25
0
        /*
         * PGP decrypt a given stream.
         */
        public void Decrypt(Stream inputStream, Stream outputStream, Stream privateKeyStream, string passPhrase)
        {
            if (inputStream == null)
            {
                throw new ArgumentException(nameof(inputStream));
            }
            if (outputStream == null)
            {
                throw new ArgumentException(nameof(outputStream));
            }
            if (privateKeyStream == null)
            {
                throw new ArgumentException(nameof(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);
            }
            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.");
            }
        }
Exemplo n.º 26
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;
        }
Exemplo n.º 27
0
        /**
         * decrypt the passed in message stream
         */
        private static void DecryptFile(
            Stream inputStream,
            char[]      passPhrase)
        {
            inputStream = PgpUtilities.GetDecoderStream(inputStream);

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

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

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

            PgpPbeEncryptedData pbe = (PgpPbeEncryptedData)enc[0];

            Stream clear = pbe.GetDataStream(passPhrase);

            PgpObjectFactory pgpFact = new PgpObjectFactory(clear);

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

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

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

            if (pbe.IsIntegrityProtected())
            {
                if (!pbe.Verify())
                {
                    Console.Error.WriteLine("message failed integrity check");
                }
                else
                {
                    Console.Error.WriteLine("message integrity check passed");
                }
            }
            else
            {
                Console.Error.WriteLine("no message integrity check");
            }
        }
Exemplo n.º 28
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;
            }
        }
Exemplo n.º 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;
        }