예제 #1
0
        public void PgpDecryptConstructorTest()
        {
            PgpEncryptionKeys encryptionKeys = null; // TODO: Initialize to an appropriate value
            PgpDecrypt        target         = new PgpDecrypt(encryptionKeys);

            Assert.Inconclusive("TODO: Implement code to verify target");
        }
예제 #2
0
        private static Stream ChainEncryptedOut(Stream outputStream, PgpEncryptionKeys m_encryptionKeys)
        {
            var encryptedDataGenerator = new PgpEncryptedDataGenerator(SymmetricKeyAlgorithmTag.TripleDes, new SecureRandom());

            encryptedDataGenerator.AddMethod(m_encryptionKeys.PublicKey);
            return(encryptedDataGenerator.Open(outputStream, new byte[BufferSize]));
        }
예제 #3
0
 /// <summary>
 /// Instantiate a new PgpEncrypt class with initialized PgpEncryptionKeys.
 /// </summary>
 /// <param name="encryptionKeys"></param>
 /// <exception cref="ArgumentNullException">encryptionKeys is null</exception>
 public PgpEncrypt(PgpEncryptionKeys encryptionKeys)
 {
     if (encryptionKeys == null)
     {
         throw new ArgumentNullException("encryptionKeys", "encryptionKeys is null.");
     }
     m_encryptionKeys = encryptionKeys;
 }
예제 #4
0
        private void add()
        {
            Product pro = new Product();

            Console.WriteLine("********* ADD ********");

            /*Console.Write("Enter Product ID: ");
             * pro.ProductID = Int16.Parse(Console.ReadLine());
             * string newURI = uri + "get-product/" + pro.ProductID.ToString();
             * if (client.GetAsync(newURI).Result.StatusCode == System.Net.HttpStatusCode.OK) {
             *  Console.WriteLine("ID existed!!!");
             *
             *  return;
             * }*/

            Console.Write("Enter Product Name: ");
            pro.ProductName = Console.ReadLine();

            Console.Write("Enter Product Price: ");
            pro.UnitPrice = Int16.Parse(Console.ReadLine());

            Console.Write("Enter Product Quantity: ");
            pro.Quantity = Int16.Parse(Console.ReadLine());

            #region get-public-key
            string newURI = baseURI + "get-public-key";
            //HttpResponseMessage response = await client.GetAsync(newURI);
            var response = client.GetStringAsync(newURI).Result.ToString();
            Obj obj      = JsonConvert.DeserializeObject <Obj>(response);
            PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(obj.file);
            #endregion

            #region add API
            newURI = uri + "create-product/";

            PgpEncrypt encrypter = new PgpEncrypt(encryptionKeys);
            string     s         = JsonConvert.SerializeObject(pro);

            System.IO.MemoryStream output = new System.IO.MemoryStream();
            encrypter.EncryptAndSign(output, s);
            output.Close();

            KeyObj newObj = new KeyObj();
            newObj.kByte = output.ToArray();

            HttpResponseMessage resp = client.PostAsJsonAsync(newURI, newObj).Result;
            #endregion

            if (resp.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Add successful!!!");
            }
            else
            {
                Console.WriteLine("Add fail!!!");
            }
        }
예제 #5
0
        public void DecryptAndVerifyTest()
        {
            PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys("..\\..\\..\\Misc\\keys\\viewpub.txt", "..\\..\\..\\Misc\\keys\\viewpriv.txt", ""); // TODO: Initialize to an appropriate value
            PgpDecrypt        target         = new PgpDecrypt(encryptionKeys);                                                                           // TODO: Initialize to an appropriate value
            Stream            inputStream    = null;                                                                                                     // TODO: Initialize to an appropriate value
            string            outputFile     = string.Empty;                                                                                             // TODO: Initialize to an appropriate value

            target.DecryptAndVerify(inputStream, outputFile);
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
예제 #6
0
        public void EncryptAndSignTest()
        {
            PgpEncryptionKeys encryptionKeys      = null;                           // TODO: Initialize to an appropriate value
            PgpEncrypt        target              = new PgpEncrypt(encryptionKeys); // TODO: Initialize to an appropriate value
            Stream            outputStream        = null;                           // TODO: Initialize to an appropriate value
            FileInfo          unencryptedFileInfo = null;                           // TODO: Initialize to an appropriate value

            target.EncryptAndSign(outputStream, unencryptedFileInfo);
            Assert.Inconclusive("A method that does not return a value cannot be verified.");
        }
예제 #7
0
        /// <summary>
        /// Handles the actions for the current working file for encryption and transmission
        /// </summary>
        /// <param name="workingFile"></param>
        private void HandleMovedVendorFile(VendorLite vl, int _count)
        {
            var source             = vl.filePath;
            var file               = Path.GetFileName(source);
            var dest               = String.Format(@"{0}\{1}", Server.MapPath(vl.workingPath), file);
            var PublicKeyFileName  = Server.MapPath(vl.publicKeyPath);
            var PrivateKeyFileName = Server.MapPath(appvars.SignPrivateKey);
            var vt             = (VendorType)Enum.Parse(typeof(VendorType), vl.VendorName, true);
            var EncryptionFile = String.Format("{0}{1}", dest.Replace(Path.GetFileName(dest), ""), appvars.ReturnNewFileName(vt));

            //Get the user info from their session var...
            SetUserInformation();
            vl.UserID = this.CurrentUser.UserObject.LoginID.ToLower();

            if (!File.Exists(dest))
            {
                FileStream fs = File.Create(dest);
                fs.Close();
            }

            File.Copy(source, dest, true);

            PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(PublicKeyFileName, PrivateKeyFileName, appvars.SignPassWord);
            PgpEncrypt        encrypter      = new PgpEncrypt(encryptionKeys);

            using (Stream outputStream = File.Create(EncryptionFile))
            {
                //build out the encypted file...
                encrypter.EncryptAndSign(outputStream, new FileInfo(dest));

                //Our file transfer class requires a fully qualified clean-up set...
                CleanUpFiles cuf = new CleanUpFiles();
                cuf.EncryptedFilePath  = EncryptionFile;
                cuf.TxtWorkingFilePath = dest;
                // we'll put in the script path later.... cuf.ClientScriptFilePath = "";
                //set the vL item's cleanupItems for the next routine..
                vl.cleanUpItems = cuf;
            }        //end using statement

            //construct the object and run it...
            FileTransfer fT = new FileTransfer(vl);

            fT.RunUpload();

            //File the report and store the files before clean-up...
            FileReport fr = new FileReport(vl);

            fr.SubmitReport();



            //clean up...
            FileCleanUp.CleanUpFileTransfer(vl.cleanUpItems);
        }    //handle the HandleMovedVendorFile
예제 #8
0
        public void Encryption()
        {
            PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(_keyRingHome + "\\" + publicKeyRingFilename, publicKeyEncryptionUserId, _keyRingHome + "\\" + secretKeyRingFilename, signatureKeyUserId, secretKeyRingPassphrase);

            PgpEncrypt encrypter = new PgpEncrypt(encryptionKeys, symmetricAlgorithm, compressionAlgorithm, sigHashAlgorithm);

            using (Stream outputStream = File.Create(filePath + "\\" + encryptedFile))
            {
                encrypter.EncryptAndSign(outputStream, new FileInfo(filePath + "\\" + originalInputFile), withArmor, withIntegrityCheck);
            }
            Console.WriteLine("Encryption Done !");
        }
예제 #9
0
        private const int BufferSize = 0x10000; // should always be power of 2

        /// <summary>

        /// Instantiate a new PgpEncrypt class with initialized PgpEncryptionKeys.

        /// </summary>

        /// <param name="encryptionKeys"></param>
        /// <param name="symmetricAlgorithm"></param>
        /// <param name="compressionAlgorithm"></param>
        /// <param name="sigHashAlgorithmTag"></param>

        /// <exception cref="ArgumentNullException">encryptionKeys is null</exception>

        public PgpEncrypt(PgpEncryptionKeys encryptionKeys, SymmetricKeyAlgorithmTag symmetricAlgorithm, CompressionAlgorithmTag compressionAlgorithm, HashAlgorithmTag sigHashAlgorithmTag)
        {
            if (encryptionKeys == null)
            {
                throw new ArgumentNullException("encryptionKeys", "encryptionKeys is null.");
            }

            _encryptionKeys       = encryptionKeys;
            _symmetricAlgorithm   = symmetricAlgorithm;
            _compressionAlgorithm = compressionAlgorithm;
            _sigHashAlgorithmTag  = sigHashAlgorithmTag;
        }
예제 #10
0
        public async void Encryption()
        {
            #region PGP Encryption

            PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(@"D:\Keys\PGPPublicKey.asc");
            PgpEncrypt        encrypter      = new PgpEncrypt(encryptionKeys);
            using (Stream outputStream = File.Create("D:\\Keys\\EncryptData.txt"))
            {
                encrypter.EncryptAndSign(outputStream, new FileInfo(@"D:\Keys\PlainText.txt"));
            }
            Console.WriteLine("Encryption Done !");

            #endregion
        }
예제 #11
0
        /// <summary>
        /// The encryption.
        /// </summary>
        private void Encryption()
        {
            #region PGP Encryption

            var encryptionKeys = new PgpEncryptionKeys(@"D:\Keys\PGPPublicKey.asc", @"D:\Keys\PGPPrivateKey.asc", "P@ll@m@lli");
            var encrypter      = new PgpEncrypt(encryptionKeys);
            using (Stream outputStream = File.Create(@"D:\Keys\EncryptData.txt"))
            {
                encrypter.EncryptAndSign(outputStream, new FileInfo(@"D:\Keys\PlainText.txt"));
            }

            this.InfoListBox.Items.Add("Encryption Done !");

            #endregion
        }
예제 #12
0
파일: PGPDecrypt.cs 프로젝트: CTKB1997/PGP
 private static void OutputEncrypted(string inputFile, Stream outputStream, PgpEncryptionKeys encryptionKeys)
 {
     using (Stream encryptedOut = ChainEncryptedOut(outputStream, encryptionKeys))
     {
         FileInfo unencryptedFileInfo = new FileInfo(inputFile);
         using (Stream compressedOut = ChainCompressedOut(encryptedOut))
         {
             using (Stream literalOut = ChainLiteralOut(compressedOut, unencryptedFileInfo))
             {
                 using (FileStream inputFileStream = unencryptedFileInfo.OpenRead())
                 {
                     WriteOutputAndSign(compressedOut, literalOut, inputFileStream);
                     inputFileStream.Close();
                 }
             }
         }
     }
 }
예제 #13
0
파일: PGPDecrypt.cs 프로젝트: CTKB1997/PGP
        /*
         * Encrypt and sign the file pointed to by unencryptedFileInfo and
         */

        public static void EncryptAndSign(string inputFile, string outputFile, string publicKeyFile, string privateKeyFile, string passPhrase, bool armor)
        {
            PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(publicKeyFile, privateKeyFile, passPhrase);

            if (!File.Exists(inputFile))
            {
                throw new FileNotFoundException(String.Format("Input file [{0}] does not exist.", inputFile));
            }

            if (!File.Exists(publicKeyFile))
            {
                throw new FileNotFoundException(String.Format("Public Key file [{0}] does not exist.", publicKeyFile));
            }

            if (!File.Exists(privateKeyFile))
            {
                throw new FileNotFoundException(String.Format("Private Key file [{0}] does not exist.", privateKeyFile));
            }

            if (String.IsNullOrEmpty(passPhrase))
            {
                throw new ArgumentNullException("Invalid Pass Phrase.");
            }

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

            using (Stream outputStream = File.Create(outputFile))
            {
                if (armor)
                {
                    using (ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(outputStream))
                    {
                        OutputEncrypted(inputFile, armoredOutputStream, encryptionKeys);
                    }
                }
                else
                {
                    OutputEncrypted(inputFile, outputStream, encryptionKeys);
                }
            }
        }
        /// <summary>
        /// Implements the SPL.Crypto DecryptAndVerify routine.
        /// </summary>
        /// <param name="encryptedFileName">Full path and file name for the ecrypted file.</param>
        /// <returns>True / False. True if the file was decrypted and written successfully.</returns>
        private bool decryptInputFile(string encryptedFileName)
        {
            bool   returnCode;
            string outputFile = extractOutputFileName(encryptedFileName);

            try
            {
                SPL.Crypto.PgpEncryptionKeys keys = new PgpEncryptionKeys(publicKeyRingPath, secretKeyRingPath, passPhrase);
                PgpDecrypt decryptor       = new PgpDecrypt(keys);
                Stream     encryptedStream = new StreamReader(encryptedFileName).BaseStream;
                decryptor.DecryptAndVerify(encryptedStream, outputFile);
                returnCode = true;
            }
            catch (Exception)
            {
                // If there was an error, we're going to eat it and just let the user know we failed.
                returnCode = false;
            }

            return(returnCode);
        }
예제 #15
0
        public byte[] Encrypt(byte[] data)
        {
            string tempDir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Temp");

            if (!Directory.Exists(tempDir))
            {
                Directory.CreateDirectory(tempDir);
            }

            string fileName = Path.Combine(tempDir, Guid.NewGuid().ToString() + ".txt");

            using (var stream = File.Create(fileName))
            {
                stream.Write(data, 0, data.Length);
                stream.Flush();
            }

            try
            {
                using (MemoryStream outputStream = new MemoryStream())
                {
                    PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(
                        GetPathToEncryptFile(),
                        GetPathToDecryptFile(),
                        _passPhrase);
                    PgpEncrypt encrypter = new PgpEncrypt(encryptionKeys);

                    encrypter.EncryptAndSign(outputStream, new FileInfo(fileName));

                    return(outputStream.ToArray());
                }
            }
            finally
            {
                if (File.Exists(fileName))
                {
                    File.Delete(fileName);
                }
            }
        }
        private static async Task <bool> EncryptExcelContentAndSendToSFTP(FileStream fs, FileInfo file)
        {
            try
            {
                var clientKey     = GetConfigValue("SFPublicKey");
                var pfsPrivateKey = GetConfigValue("PFSPrivateKey");
                var password      = GetConfigValue("PGPPassword");

                //encrypt the generated file
                var objPgpEncryptionKeys = new PgpEncryptionKeys(clientKey, pfsPrivateKey, password);
                var objPgpEncrypt        = new PgpEncrypt(objPgpEncryptionKeys);

                objPgpEncrypt.EncryptAndSign(fs, file);

                //UploadExcelToSFTP(sftpHost, sftpUsername, sftpPassword, file.FullName, sftpDestination, sftpPort);

                return(true);
            }
            catch (Exception ex)
            {
                throw new PlatformCustomException(ex.Message);
            }
        }
예제 #17
0
        /// <summary>
        /// Encrypt and sign the file pointed to by unencryptedFileInfo
        /// </summary>
        public static void EncryptAndSign(string inputFile, string outputFile, string publicKeyFile, string privateKeyFile, string passPhrase, bool armor)
        {
            var encryptionKeys = new PgpEncryptionKeys(publicKeyFile, privateKeyFile, passPhrase);

            Contract.Requires <FileNotFoundException>(File.Exists(inputFile), "Input file [" + inputFile + "] does not exist.");
            Contract.Requires <FileNotFoundException>(File.Exists(publicKeyFile), "Public Key file [" + publicKeyFile + "] does not exist.");
            Contract.Requires <FileNotFoundException>(File.Exists(privateKeyFile), "Private Key file [" + privateKeyFile + "] does not exist.");
            Contract.Requires <ArgumentNullException>(!string.IsNullOrEmpty(passPhrase), "Invalid Pass Phrase.");

            using (Stream outputStream = File.Create(outputFile))
            {
                if (armor)
                {
                    using (ArmoredOutputStream armoredOutputStream = new ArmoredOutputStream(outputStream))
                    {
                        OutputEncrypted(inputFile, armoredOutputStream, encryptionKeys);
                    }
                }
                else
                {
                    OutputEncrypted(inputFile, outputStream, encryptionKeys);
                }
            }
        }
예제 #18
0
파일: PGPDecrypt.cs 프로젝트: CTKB1997/PGP
        private static PgpSignatureGenerator InitSignatureGenerator(Stream compressedOut, PgpEncryptionKeys m_encryptionKeys)
        {
            const bool            IsCritical            = false;
            const bool            IsNested              = false;
            PublicKeyAlgorithmTag tag                   = m_encryptionKeys.SecretKey.PublicKey.Algorithm;
            PgpSignatureGenerator pgpSignatureGenerator = new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha1);

            pgpSignatureGenerator.InitSign(PgpSignature.BinaryDocument, m_encryptionKeys.PrivateKey);
            foreach (string userId in m_encryptionKeys.SecretKey.PublicKey.GetUserIds())
            {
                PgpSignatureSubpacketGenerator subPacketGenerator = new PgpSignatureSubpacketGenerator();
                subPacketGenerator.SetSignerUserId(IsCritical, userId);
                pgpSignatureGenerator.SetHashedSubpackets(subPacketGenerator.Generate());
                // Just the first one!
                break;
            }
            pgpSignatureGenerator.GenerateOnePassVersion(IsNested).Encode(compressedOut);
            return(pgpSignatureGenerator);
        }
예제 #19
0
        private void update()
        {
            Product pro = new Product();

            Console.WriteLine("********** UPDATE *********");
            Console.Write("Enter Product ID: ");
            pro.ProductID = Int16.Parse(Console.ReadLine());
            string newURI = uri + "get-product/" + pro.ProductID.ToString();

            //Console.WriteLine(newURI);
            if (client.GetAsync(newURI).Result.StatusCode == System.Net.HttpStatusCode.NotFound)
            {
                Console.WriteLine("ID not found!!");
                return;
            }


            Console.Write("Enter New Product Name: ");
            pro.ProductName = Console.ReadLine();
            Console.Write("Enter New Product Price: ");
            pro.UnitPrice = Int16.Parse(Console.ReadLine());
            Console.Write("Enter New Product Quantity: ");
            pro.Quantity = Int16.Parse(Console.ReadLine());


            #region get-public-key
            newURI = baseURI + "get-public-key";
            //HttpResponseMessage response = await client.GetAsync(newURI);
            var response = client.GetStringAsync(newURI).Result.ToString();
            Obj obj      = JsonConvert.DeserializeObject <Obj>(response);
            PgpEncryptionKeys encryptionKeys = new PgpEncryptionKeys(obj.file);
            #endregion

            #region update API
            newURI = uri + "update-product/" + pro.ProductID.ToString();

            PgpEncrypt encrypter = new PgpEncrypt(encryptionKeys);
            string     s         = JsonConvert.SerializeObject(pro);

            System.IO.MemoryStream output = new System.IO.MemoryStream();
            encrypter.EncryptAndSign(output, s);
            output.Close();

            //MemoryStream ms = new MemoryStream();
            //PGPHandler.GetInstance().EncryptAndSign(Encoding.UTF8.GetBytes(request), ms);
            //String encryptedData = Encoding.UTF8.GetString(ms.ToArray());

            KeyObj newObj = new KeyObj();
            newObj.kByte = output.ToArray();

            HttpResponseMessage resp = client.PutAsJsonAsync(newURI, newObj).Result;
            #endregion


            if (resp.StatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine("Update successful!!!");
            }
            else
            {
                Console.WriteLine("Update fail!!!");
            }
        }
예제 #20
0
        private static PgpSignatureGenerator InitSignatureGenerator(Stream compressedOut, PgpEncryptionKeys encryptionKeys)
        {
            const bool isCritical = false;
            const bool isNested   = false;

            PublicKeyAlgorithmTag tag = encryptionKeys.SecretKey.PublicKey.Algorithm;
            var pgpSignatureGenerator = new PgpSignatureGenerator(tag, HashAlgorithmTag.Sha1);

            pgpSignatureGenerator.InitSign(PgpSignature.BinaryDocument, encryptionKeys.PrivateKey);

            string firstUserId = encryptionKeys.SecretKey.PublicKey.GetUserIds().Cast <string>().First();
            PgpSignatureSubpacketGenerator subPacketGenerator = new PgpSignatureSubpacketGenerator();

            subPacketGenerator.SetSignerUserId(isCritical, firstUserId);
            pgpSignatureGenerator.SetHashedSubpackets(subPacketGenerator.Generate());

            pgpSignatureGenerator.GenerateOnePassVersion(isNested).Encode(compressedOut);
            return(pgpSignatureGenerator);
        }