示例#1
0
        public async Task <object> Process(JsonDocument request, ILambdaContext context)
        {
            var s3 = new AmazonS3Client();

            // easier than doing math on the timestamps in logs
            var timer = new Stopwatch();

            timer.Start();

            context.Logger.LogLine($"{timer.Elapsed}: Getting started.");
            using var data = new SeekableS3Stream(s3, BUCKET, PGP_DATA, 5 * 1024 * 1024, 10);
            using var key  = new SeekableS3Stream(s3, BUCKET, PGP_PRIVATE_KEY, 32 * 1024);

            using var pgp = new PGP();
            using (var output = new S3UploadStream(s3, BUCKET, OUTPUT_KEY)) {
                await pgp.DecryptStreamAsync(data, output, key, PGP_PASSWORD);
            }

            context.Logger.LogLine($"{timer.Elapsed}: Done copying.");
            timer.Stop();

            return(new {
                PgpFile = $"s3://{BUCKET}/{PGP_DATA}",
                CsvFile = $"s3://{BUCKET}/{OUTPUT_KEY}",
                Status = "ok"
            });
        }
示例#2
0
        public async Task <KeyPair> GenerateKey(HandshakeMethod method)
        {
            var tmpFilePublic  = System.IO.Path.GetTempFileName();
            var tmpFilePrivate = System.IO.Path.GetTempFileName();

            using var pgp = new PGP();
            await pgp.GenerateKeyAsync(tmpFilePublic, tmpFilePrivate);

            var publicKey = await File.ReadAllTextAsync(tmpFilePublic);

            var privateKey = await File.ReadAllTextAsync(tmpFilePrivate);

            return(new KeyPair()
            {
                Private = new PrivateKey()
                {
                    Format = AuthKeyFormat.PEM,
                    Type = Type,
                    Value = privateKey,
                    WhenAdded = DateTime.UtcNow,
                },
                Public = new PublicKey()
                {
                    Format = AuthKeyFormat.PEM,
                    Type = Type,
                    Value = publicKey.Trim(),
                    WhenAdded = DateTime.UtcNow,
                },
            });
        }
示例#3
0
        public void EncryptFile_CreateEncryptedFileWithMultipleKeys(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory  = new TestFactory();
            TestFactory testFactory2 = new TestFactory();

            testFactory.Arrange(keyType, FileType.Known);
            testFactory2.Arrange(KeyType.Generated);

            PGP           pgp  = new PGP();
            List <string> keys = new List <string>()
            {
                testFactory.PublicKeyFilePath,
                testFactory2.PublicKeyFilePath
            };

            // Act
            pgp.EncryptFile(testFactory.ContentFilePath, testFactory.EncryptedContentFilePath, keys);

            // Assert
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));

            // Teardown
            testFactory.Teardown();
            testFactory2.Teardown();
        }
示例#4
0
  /// <summary>Begins a search on the given key server for the given search terms.</summary>
  public void BeginSearch(string terms, Uri keyServer)
  {
    if(terms == null || keyServer == null) throw new ArgumentNullException();
    if(PGP == null) throw new InvalidOperationException("The PGP property is not set.");
    if(TaskInProgress) throw new InvalidOperationException("A search or import is in progress.");

    terms = terms.Trim();
    if(string.IsNullOrEmpty(terms)) throw new ArgumentException("No search terms were provided.");

    progressBar.Style = ProgressBarStyle.Marquee;

    results.Items.Clear();
    searchServer = keyServer; // save the server used for the search so we know from what server to import the keys

    thread = new Thread(delegate()
    {
      try
      {
        PGP.FindKeysOnServer(keyServer, GotResults,
                             terms.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries));
        Invoke((ThreadStart)delegate { SearchSucceeded(); });
      }
      catch(Exception ex)
      {
        Invoke((ThreadStart)delegate { SearchFailed(ex); });
      }
    });

    UpdateButtons();

    thread.Start();
  }
示例#5
0
        public void DecryptStream_DecryptEncryptedStream(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory = new TestFactory();

            testFactory.Arrange(keyType, FileType.Known);
            PGP pgp = new PGP();

            // Act
            using (FileStream inputFileStream = new FileStream(testFactory.ContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream outputFileStream = File.Create(testFactory.EncryptedContentFilePath))
                    using (Stream publicKeyStream = new FileStream(testFactory.PublicKeyFilePath, FileMode.Open, FileAccess.Read))
                        pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream);

            using (FileStream inputFileStream = new FileStream(testFactory.EncryptedContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream outputFileStream = File.Create(testFactory.DecryptedContentFilePath))
                    using (Stream privateKeyStream = new FileStream(testFactory.PrivateKeyFilePath, FileMode.Open, FileAccess.Read))
                        pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, testFactory.Password);

            string decryptedContent = File.ReadAllText(testFactory.DecryptedContentFilePath);

            // Assert
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));
            Assert.True(File.Exists(testFactory.DecryptedContentFilePath));
            Assert.Equal(testFactory.Content, decryptedContent.Trim());

            // Teardown
            testFactory.Teardown();
        }
示例#6
0
        public static PgpProfile Generate(string email, string password = null)
        {
            if (password == null)
            {
                password = Internet.GetPassword();
            }

            var p = new PgpProfile();

            using (var pgp = new PGP())
            {
                const string publicFile  = "public.asc";
                const string privateFile = "private.asc";

                // Generate keys
                pgp.GenerateKey(publicFile, privateFile, email, password);

                p.Email      = email;
                p.Password   = password;
                p.PublicKey  = File.ReadAllText(publicFile);
                p.PrivateKey = File.ReadAllText(privateFile);

                File.Delete(publicFile);
                File.Delete(privateFile);
            }
            return(p);
        }
示例#7
0
        public void EncryptStream_CreateEncryptedStreamWithMultipleKeys(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory  = new TestFactory();
            TestFactory testFactory2 = new TestFactory();

            testFactory.Arrange(keyType, FileType.Known);
            testFactory2.Arrange(KeyType.Generated, FileType.Known);

            PGP pgp = new PGP();

            // Act
            using (FileStream inputFileStream = new FileStream(testFactory.ContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream outputFileStream = File.Create(testFactory.EncryptedContentFilePath))
                    using (Stream publicKeyStream1 = new FileStream(testFactory.PublicKeyFilePath, FileMode.Open, FileAccess.Read))
                        using (Stream publicKeyStream2 = new FileStream(testFactory2.PublicKeyFilePath, FileMode.Open, FileAccess.Read))
                            pgp.EncryptStream(inputFileStream, outputFileStream, new List <Stream>()
                            {
                                publicKeyStream1, publicKeyStream2
                            });

            // Assert
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));

            // Teardown
            testFactory.Teardown();
        }
示例#8
0
        public async Task EncryptStreamAndSignAsync_CreateEncryptedAndSignedStreamWithMultipleKeys(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory  = new TestFactory();
            TestFactory testFactory2 = new TestFactory();
            await testFactory.ArrangeAsync(keyType, FileType.Known);

            await testFactory2.ArrangeAsync(KeyType.Generated, FileType.Known);

            PGP pgp = new PGP();

            // Act
            using (FileStream inputFileStream = new FileStream(testFactory.ContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream outputFileStream = File.Create(testFactory.EncryptedContentFilePath))
                    using (Stream publicKeyStream1 = new FileStream(testFactory.PublicKeyFilePath, FileMode.Open, FileAccess.Read))
                        using (Stream publicKeyStream2 = new FileStream(testFactory2.PublicKeyFilePath, FileMode.Open, FileAccess.Read))
                            using (Stream privateKeyStream = new FileStream(testFactory.PrivateKeyFilePath, FileMode.Open, FileAccess.Read))
                                await pgp.EncryptStreamAndSignAsync(inputFileStream, outputFileStream, new List <Stream>() { publicKeyStream1, publicKeyStream2 }, privateKeyStream, testFactory.Password);

            // Assert
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));

            // Teardown
            testFactory.Teardown();
        }
示例#9
0
        public void DecryptFile_DecryptSignedAndEncryptedFileWithMultipleKeys(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory  = new TestFactory();
            TestFactory testFactory2 = new TestFactory();

            testFactory.Arrange(keyType, FileType.Known);
            testFactory2.Arrange(KeyType.Generated, FileType.Known);

            PGP           pgp  = new PGP();
            List <string> keys = new List <string>()
            {
                testFactory.PublicKeyFilePath,
                testFactory2.PublicKeyFilePath
            };

            // Act
            pgp.EncryptFileAndSign(testFactory.ContentFilePath, testFactory.EncryptedContentFilePath, keys, testFactory.PrivateKeyFilePath, testFactory.Password);
            pgp.DecryptFile(testFactory.EncryptedContentFilePath, testFactory.DecryptedContentFilePath, testFactory.PrivateKeyFilePath, testFactory.Password);
            pgp.DecryptFile(testFactory.EncryptedContentFilePath, testFactory2.DecryptedContentFilePath, testFactory2.PrivateKeyFilePath, testFactory2.Password);
            string decryptedContent1 = File.ReadAllText(testFactory.DecryptedContentFilePath);
            string decryptedContent2 = File.ReadAllText(testFactory2.DecryptedContentFilePath);

            // Assert
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));
            Assert.True(File.Exists(testFactory.DecryptedContentFilePath));
            Assert.True(File.Exists(testFactory2.DecryptedContentFilePath));
            Assert.Equal(testFactory.Content, decryptedContent1.Trim());
            Assert.Equal(testFactory.Content, decryptedContent2.Trim());

            // Teardown
            testFactory.Teardown();
        }
示例#10
0
        public async Task DecryptStreamAsync_DecryptSignedAndEncryptedStream(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory = new TestFactory();
            await testFactory.ArrangeAsync(keyType, FileType.Known);

            PGP pgp = new PGP();

            // Act
            using (FileStream inputFileStream = new FileStream(testFactory.ContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream outputFileStream = File.Create(testFactory.EncryptedContentFilePath))
                    using (Stream publicKeyStream = new FileStream(testFactory.PublicKeyFilePath, FileMode.Open, FileAccess.Read))
                        using (Stream privateKeyStream = new FileStream(testFactory.PrivateKeyFilePath, FileMode.Open, FileAccess.Read))
                            await pgp.EncryptStreamAndSignAsync(inputFileStream, outputFileStream, publicKeyStream, privateKeyStream, testFactory.Password);

            using (FileStream inputFileStream = new FileStream(testFactory.EncryptedContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream outputFileStream = File.Create(testFactory.DecryptedContentFilePath))
                    using (Stream privateKeyStream = new FileStream(testFactory.PrivateKeyFilePath, FileMode.Open, FileAccess.Read))
                        await pgp.DecryptStreamAsync(inputFileStream, outputFileStream, privateKeyStream, testFactory.Password);

            string decryptedContent = await File.ReadAllTextAsync(testFactory.DecryptedContentFilePath);

            bool verified = pgp.VerifyFile(testFactory.EncryptedContentFilePath, testFactory.PublicKeyFilePath);

            // Assert
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));
            Assert.True(File.Exists(testFactory.DecryptedContentFilePath));
            Assert.Equal(testFactory.Content, decryptedContent.Trim());
            Assert.True(verified);

            // Teardown
            testFactory.Teardown();
        }
示例#11
0
        public void Verify_VerifySignedStream(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory = new TestFactory();

            testFactory.Arrange(keyType, FileType.Known);
            PGP  pgp      = new PGP();
            bool verified = false;

            // Act
            using (FileStream inputFileStream = new FileStream(testFactory.ContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream outputFileStream = File.Create(testFactory.SignedContentFilePath))
                    using (Stream privateKeyStream = new FileStream(testFactory.PrivateKeyFilePath, FileMode.Open, FileAccess.Read))
                        pgp.SignStream(inputFileStream, outputFileStream, privateKeyStream, testFactory.Password);

            using (FileStream inputFileStream = new FileStream(testFactory.SignedContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream publicKeyStream = new FileStream(testFactory.PublicKeyFilePath, FileMode.Open, FileAccess.Read))
                    verified = pgp.VerifyStream(inputFileStream, publicKeyStream);

            // Assert
            Assert.True(File.Exists(testFactory.SignedContentFilePath));
            Assert.True(verified);

            // Teardown
            testFactory.Teardown();
        }
        /// <summary>
        /// Decrypts a stream using OpenPGP standards.  Only
        /// the organization holding the corresponding private key
        /// can decrypt the data.
        /// </summary>
        /// <param name="inStream">input stream to decrypt</param>
        /// <param name="outStream">decrypted output stream</param>
        /// <param name="privateKey">The name of the private key stored in a database</param>
        /// <param name="privateKeyName"></param>
        /// <param name="compressionType">none,gzip,zlib,bzip2,zip</param>
        public static void Decrypt(Stream inStream, Stream outStream,
                                   byte[] privateKey, string passphrase,
                                   CompressionType compressionType = CompressionType.None,
                                   bool armor = false)
        {
            var compressionAlgorithmTag = ParseCompressionAlgorithm(compressionType);

            using (var pgp = new PGP()) {
                using (var outputStream = new MemoryStream()) {
                    using (var privateKeyStream = new MemoryStream(privateKey)) {
                        pgp.CompressionAlgorithm = compressionAlgorithmTag;
                        pgp.DecryptStream(inStream, outputStream, privateKeyStream, passphrase);
                    }

                    outputStream.Seek(0, SeekOrigin.Begin);

                    if (compressionType == CompressionType.GZip)
                    {
                        UnGzip(outputStream, outStream);
                    }
                    else
                    {
                        outputStream.CopyTo(outStream);
                    }
                }
            }
        }
示例#13
0
        static void Main(string[] args)
        {
            var publicKey  = new EncryptionKeys(File.ReadAllText(Path.Combine(ROOT_KEYS, PUBLIC_KEY)));
            var privateKey = new EncryptionKeys(File.ReadAllText(Path.Combine(ROOT_KEYS, PRIVATE_KEY)), "Password1!");

            using (var publicPgp = new PGP(publicKey))
                using (var privatePgp = new PGP(privateKey))
                {
                    privatePgp.ClearSignFile(
                        Path.Combine(ROOT, UNENCRYPTED_FILE),
                        Path.Combine(ROOT, SIGNED_FILE));

                    publicPgp.EncryptFile(
                        Path.Combine(ROOT, SIGNED_FILE),
                        Path.Combine(ROOT, ENCRYPTED_FILE));

                    // Likely would want to use EncryptFileAndSign instead of two passes

                    privatePgp.DecryptFile(
                        Path.Combine(ROOT, ENCRYPTED_FILE),
                        Path.Combine(ROOT, DECRYPTED_FILE));

                    Console.WriteLine("It was me who signed the file: {0}", publicPgp.VerifyClearFile(Path.Combine(ROOT, DECRYPTED_FILE)));
                }

            using (var pgp = new PGP(new EncryptionKeys(File.ReadAllText(Path.Combine(ROOT_KEYS, RANDOM_PUBLIC_KEY)))))
            {
                Console.WriteLine("It was me who signed the file: {0}", pgp.VerifyClearFile(Path.Combine(ROOT, DECRYPTED_FILE)));
            }
        }
示例#14
0
        public void DecryptStream_DecryptSignedAndEncryptedStream(KeyType keyType)
        {
            // Arrange
            Arrange(keyType);
            PGP pgp = new PGP();

            // Act
            using (FileStream inputFileStream = new FileStream(contentFilePath, FileMode.Open))
                using (Stream outputFileStream = File.Create(encryptedContentFilePath))
                    using (Stream publicKeyStream = new FileStream(publicKeyFilePath1, FileMode.Open))
                        using (Stream privateKeyStream = new FileStream(privateKeyFilePath1, FileMode.Open))
                            pgp.EncryptStreamAndSign(inputFileStream, outputFileStream, publicKeyStream, privateKeyStream, password1);

            using (FileStream inputFileStream = new FileStream(encryptedContentFilePath, FileMode.Open))
                using (Stream outputFileStream = File.Create(decryptedContentFilePath1))
                    using (Stream privateKeyStream = new FileStream(privateKeyFilePath1, FileMode.Open))
                        pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, password1);

            string decryptedContent = File.ReadAllText(decryptedContentFilePath1);

            bool verified = pgp.VerifyFile(encryptedContentFilePath, publicKeyFilePath1);

            // Assert
            Assert.True(File.Exists(encryptedContentFilePath));
            Assert.True(File.Exists(decryptedContentFilePath1));
            Assert.Equal(content, decryptedContent.Trim());
            Assert.True(verified);

            // Teardown
            Teardown();
        }
        /// <summary>
        /// Encrypts a stream using OpenPGP standards.  Only
        /// the organization holding the corresponding private key
        /// can decrypt the data.
        /// </summary>
        /// <param name="inStream">input stream to encrypt</param>
        /// <param name="outStream">encrypted output stream</param>
        /// <param name="publicKeyName">The name of the public key stored in a database</param>
        /// <param name="compressionType">none,gzip,zlib,bzip2,zip</param>
        public static void Encrypt(Stream inStream, Stream outStream,
                                   byte[] publicKey,
                                   CompressionType compressionType = CompressionType.None,
                                   bool armor = false)
        {
            var compressionAlgorithmTag = ParseCompressionAlgorithm(compressionType);


            using (var inputStream = new MemoryStream()) {
                if (compressionType == CompressionType.GZip)
                {
                    Gzip(inStream, inputStream);
                }
                else
                {
                    inStream.CopyTo(inputStream);
                }

                inputStream.Seek(0, SeekOrigin.Begin);
                using (var pgp = new PGP()) {
                    using (var publicKeyStream = new MemoryStream(publicKey)) {
                        pgp.CompressionAlgorithm = compressionAlgorithmTag;
                        pgp.EncryptStream(inputStream, outStream, publicKeyStream, armor, true);
                    }
                }
            }
        }
示例#16
0
        public void DecryptFile_DecryptSignedAndEncryptedFileWithMultipleKeys(KeyType keyType)
        {
            // Arrange
            Arrange(keyType);
            PGP           pgp  = new PGP();
            List <string> keys = new List <string>()
            {
                publicKeyFilePath1,
                publicKeyFilePath2
            };

            // Act
            pgp.EncryptFileAndSign(contentFilePath, encryptedContentFilePath, keys, privateKeyFilePath1, password1);
            pgp.DecryptFile(encryptedContentFilePath, decryptedContentFilePath1, privateKeyFilePath1, password1);
            pgp.DecryptFile(encryptedContentFilePath, decryptedContentFilePath2, privateKeyFilePath2, password2);
            string decryptedContent1 = File.ReadAllText(decryptedContentFilePath1);
            string decryptedContent2 = File.ReadAllText(decryptedContentFilePath2);

            // Assert
            Assert.True(File.Exists(encryptedContentFilePath));
            Assert.True(File.Exists(decryptedContentFilePath1));
            Assert.True(File.Exists(decryptedContentFilePath2));
            Assert.Equal(content, decryptedContent1.Trim());
            Assert.Equal(content, decryptedContent2.Trim());

            // Teardown
            Teardown();
        }
示例#17
0
文件: Program.cs 项目: swalde/PgpCore
        static void Main(string[] args)
        {
            using (PGP pgp = new PGP())
            {
                // Generate keys
                pgp.GenerateKey(@"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\private.asc", "*****@*****.**", "password");
                // Encrypt file
                pgp.EncryptFile(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted.pgp", @"C:\TEMP\keys\public.asc", true, true);
                // Encrypt and sign file
                pgp.EncryptFileAndSign(@"C:\TEMP\keys\content.txt", @"C:\TEMP\keys\content__encrypted_signed.pgp", @"C:\TEMP\keys\public.asc", @"C:\TEMP\keys\private.asc", "password", true, true);
                // Decrypt file
                pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted.pgp", @"C:\TEMP\keys\content__decrypted.txt", @"C:\TEMP\keys\private.asc", "password");
                // Decrypt signed file
                pgp.DecryptFile(@"C:\TEMP\keys\content__encrypted_signed.pgp", @"C:\TEMP\keys\content__decrypted_signed.txt", @"C:\TEMP\keys\private.asc", "password");

                // Encrypt stream
                using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content.txt", FileMode.Open))
                    using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__encrypted2.pgp"))
                        using (Stream publicKeyStream = new FileStream(@"C:\TEMP\keys\public.asc", FileMode.Open))
                            pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true);

                // Decrypt stream
                using (FileStream inputFileStream = new FileStream(@"C:\TEMP\keys\content__encrypted2.pgp", FileMode.Open))
                    using (Stream outputFileStream = File.Create(@"C:\TEMP\keys\content__decrypted2.txt"))
                        using (Stream privateKeyStream = new FileStream(@"C:\TEMP\keys\private.asc", FileMode.Open))
                            pgp.DecryptStream(inputFileStream, outputFileStream, privateKeyStream, "password");
            }
        }
示例#18
0
 //TODO: PGP validator
 public bool IsValid(byte[] packageBytes, byte[] signatureBytes, string apiKey)
 {
     using (var pgp = new PGP())
     {
         return(signatureBytes != null && signatureBytes.Any());
     }
 }
示例#19
0
        public void Verify_DoNotVerifyEncryptedAndSignedStream(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory  = new TestFactory();
            TestFactory testFactory2 = new TestFactory();

            testFactory.Arrange(keyType, FileType.Known);
            testFactory2.Arrange(KeyType.Generated, FileType.Known);

            PGP pgp = new PGP();

            // Act
            using (FileStream inputFileStream = new FileStream(testFactory.ContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream outputFileStream = File.Create(testFactory.EncryptedContentFilePath))
                    using (Stream publicKeyStream = new FileStream(testFactory.PublicKeyFilePath, FileMode.Open, FileAccess.Read))
                        using (Stream privateKeyStream = new FileStream(testFactory.PrivateKeyFilePath, FileMode.Open, FileAccess.Read))
                            pgp.EncryptStreamAndSign(inputFileStream, outputFileStream, publicKeyStream, privateKeyStream, testFactory.Password);

            bool verified = pgp.VerifyFile(testFactory.EncryptedContentFilePath, testFactory2.PublicKeyFilePath);

            // Assert
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));
            Assert.False(verified);

            // Teardown
            testFactory.Teardown();
        }
示例#20
0
 public async Task EncryptStreamAndSignAsync(Stream inputStream, Stream outputStream, PrivateKey privateKey, PublicKey publicKey, Func <string> passwordFinder)
 {
     using var pgp              = new PGP();
     using var publicKeyStream  = GetPublicKey(publicKey);
     using var privateKeyStream = GetPrivateKey(privateKey);
     await pgp.EncryptStreamAndSignAsync(inputStream, outputStream, privateKeyStream, publicKeyStream, null);
 }
示例#21
0
        public async Task DecryptFileAndVerifyAsync_DecryptSignedAndEncryptedFileDifferentKeys(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory  = new TestFactory();
            TestFactory testFactory2 = new TestFactory();
            await testFactory.ArrangeAsync(keyType, FileType.Known);

            await testFactory2.ArrangeAsync(KeyType.Generated, FileType.Known);

            PGP pgp = new PGP();

            // Act
            await pgp.EncryptFileAndSignAsync(testFactory.ContentFilePath, testFactory.EncryptedContentFilePath, testFactory2.PublicKeyFilePath, testFactory.PrivateKeyFilePath, testFactory.Password);

            await pgp.DecryptFileAndVerifyAsync(testFactory.EncryptedContentFilePath, testFactory.DecryptedContentFilePath, testFactory.PublicKeyFilePath, testFactory2.PrivateKeyFilePath, testFactory2.Password);

            string decryptedContent = await File.ReadAllTextAsync(testFactory.DecryptedContentFilePath);

            // Assert
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));
            Assert.True(File.Exists(testFactory.DecryptedContentFilePath));
            Assert.Equal(testFactory.Content, decryptedContent.Trim());

            // Teardown
            testFactory.Teardown();
        }
示例#22
0
        public void DecryptFileAndVerify_DecryptUnsignedFile(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory  = new TestFactory();
            TestFactory testFactory2 = new TestFactory();

            testFactory.Arrange(keyType, FileType.Known);
            testFactory2.Arrange(KeyType.Generated, FileType.Known);

            PGP pgp = new PGP();

            // Act
            pgp.EncryptFile(testFactory.ContentFilePath, testFactory.EncryptedContentFilePath, testFactory2.PublicKeyFilePath);
            var ex = Assert.Throws <PgpException>(() => pgp.DecryptFileAndVerify(testFactory.EncryptedContentFilePath,
                                                                                 testFactory.DecryptedContentFilePath, testFactory.PublicKeyFilePath, testFactory2.PrivateKeyFilePath, testFactory2.Password));

            string decryptedContent = File.ReadAllText(testFactory.DecryptedContentFilePath);

            // Assert
            Assert.Equal("File was not signed.", ex.Message);
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));
            Assert.True(File.Exists(testFactory.DecryptedContentFilePath));
            Assert.Equal(string.Empty, decryptedContent.Trim());

            // Teardown
            testFactory.Teardown();
        }
示例#23
0
        public async Task DecryptFileAndVerifyAsync_DecryptWithWrongKey(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory  = new TestFactory();
            TestFactory testFactory2 = new TestFactory();
            await testFactory.ArrangeAsync(keyType, FileType.Known);

            await testFactory2.ArrangeAsync(KeyType.Generated, FileType.Known);

            PGP pgp = new PGP();

            // Act
            await pgp.EncryptFileAndSignAsync(testFactory.ContentFilePath, testFactory.EncryptedContentFilePath, testFactory.PublicKeyFilePath, testFactory.PrivateKeyFilePath, testFactory.Password);

            var ex = await Assert.ThrowsAsync <PgpException>(async() => await pgp.DecryptFileAndVerifyAsync(testFactory.EncryptedContentFilePath,
                                                                                                            testFactory.DecryptedContentFilePath, testFactory2.PublicKeyFilePath, testFactory.PrivateKeyFilePath, testFactory.Password));

            string decryptedContent = await File.ReadAllTextAsync(testFactory.DecryptedContentFilePath);

            // Assert
            Assert.Equal("Failed to verify file.", ex.Message);
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));
            Assert.True(File.Exists(testFactory.DecryptedContentFilePath));
            Assert.Equal(string.Empty, decryptedContent.Trim());

            // Teardown
            testFactory.Teardown();
        }
示例#24
0
        public async Task DecryptFileAsync_DecryptEncryptedFileWithDifferentHashAlgorithms(HashAlgorithmTag hashAlgorithmTag)
        {
            // Arrange
            TestFactory testFactory = new TestFactory();
            await testFactory.ArrangeAsync(KeyType.Known, FileType.Known);

            PGP pgp = new PGP();

            pgp.HashAlgorithmTag = hashAlgorithmTag;

            // Act
            await pgp.EncryptFileAsync(testFactory.ContentFilePath, testFactory.EncryptedContentFilePath, testFactory.PublicKeyFilePath);

            await pgp.DecryptFileAsync(testFactory.EncryptedContentFilePath, testFactory.DecryptedContentFilePath, testFactory.PrivateKeyFilePath, testFactory.Password);

            string decryptedContent = await File.ReadAllTextAsync(testFactory.DecryptedContentFilePath);

            // Assert
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));
            Assert.True(File.Exists(testFactory.DecryptedContentFilePath));
            Assert.Equal(testFactory.Content, decryptedContent.Trim());

            // Teardown
            testFactory.Teardown();
        }
示例#25
0
        public async Task EncryptFileAndSignAsync_CreateEncryptedAndSignedFileWithMultipleKeys(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory  = new TestFactory();
            TestFactory testFactory2 = new TestFactory();
            await testFactory.ArrangeAsync(keyType, FileType.Known);

            await testFactory2.ArrangeAsync(KeyType.Generated);

            PGP           pgp  = new PGP();
            List <string> keys = new List <string>()
            {
                testFactory.PublicKeyFilePath,
                testFactory2.PublicKeyFilePath
            };

            // Act
            await pgp.EncryptFileAndSignAsync(testFactory.ContentFilePath, testFactory.EncryptedContentFilePath, keys, testFactory.PrivateKeyFilePath, testFactory.Password);

            // Assert
            Assert.True(File.Exists(testFactory.EncryptedContentFilePath));

            // Teardown
            testFactory.Teardown();
            testFactory2.Teardown();
        }
示例#26
0
        public async Task VerifyAsync_DoNotVerifySignedStream(KeyType keyType)
        {
            // Arrange
            TestFactory testFactory  = new TestFactory();
            TestFactory testFactory2 = new TestFactory();
            await testFactory.ArrangeAsync(keyType, FileType.Known);

            await testFactory2.ArrangeAsync(KeyType.Generated, FileType.Known);

            PGP  pgp      = new PGP();
            bool verified = false;

            // Act
            using (FileStream inputFileStream = new FileStream(testFactory.ContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream outputFileStream = File.Create(testFactory.SignedContentFilePath))
                    using (Stream privateKeyStream = new FileStream(testFactory.PrivateKeyFilePath, FileMode.Open, FileAccess.Read))
                        await pgp.SignStreamAsync(inputFileStream, outputFileStream, privateKeyStream, testFactory.Password);

            using (FileStream inputFileStream = new FileStream(testFactory.SignedContentFilePath, FileMode.Open, FileAccess.Read))
                using (Stream publicKeyStream = new FileStream(testFactory2.PublicKeyFilePath, FileMode.Open, FileAccess.Read))
                    verified = await pgp.VerifyStreamAsync(inputFileStream, publicKeyStream);

            // Assert
            Assert.True(File.Exists(testFactory.SignedContentFilePath));
            Assert.False(verified);

            // Teardown
            testFactory.Teardown();
        }
示例#27
0
        public GpgAuth(ApiSession session, GpgKey clientKey, GpgKey serverKey)
        {
            _pgp       = new PGP();
            _clientKey = clientKey;
            _serverKey = serverKey;

            _session = session;
        }
示例#28
0
        static void Main(string[] args)
        {
            var pgp = new PGP();

            new WebClient().DownloadFile("https://github.com/mili-tan.gpg", "mili-tan.asc");
            var verify = pgp.VerifyFile("linux-arm64.zip.gpg", "mili-tan.asc");

            Console.WriteLine(verify);
        }
示例#29
0
        static void Main()
        {
            using (PGP pgp = new PGP())
            {
                Console.WriteLine($"Welcome to PGPEncryptConsoleApp!");

                string tempPath                 = Path.Combine(Path.GetTempPath(), "pgpcore");
                string publicKeyFilePath        = Path.Combine(tempPath, "public.asc");
                string publicKeyBase64FilePath  = Path.Combine(tempPath, "public_base64.asc");
                string privateKeyFilePath       = Path.Combine(tempPath, "private.asc");
                string privateKeyBase64FilePath = Path.Combine(tempPath, "private_base64.asc");
                string contentFilePath          = Path.Combine(tempPath, "content.txt");
                string encryptedFilePath        = Path.Combine(tempPath, "content_encrypted.pgp");
                string decryptedFilePath        = Path.Combine(tempPath, "content_decrypted.txt");
                string username                 = null;
                int    strength                 = 4096;
                int    certainty                = 8;

                //Create temp direcory and test file
                Directory.CreateDirectory(tempPath);
                Console.WriteLine($"Created temp directory: {tempPath}");
                File.WriteAllText(contentFilePath, "Hello World PGPCore!");
                Console.WriteLine($"Created test file: {contentFilePath}");

                // Create a password
                Console.WriteLine($"Enter a password or press enter to not use a password");
                string password = ReadLine.ReadPassword();

                // Generate keys
                Spinner.Start("Generating keys...", () =>
                {
                    pgp.GenerateKey(publicKeyFilePath, privateKeyFilePath, username, password, strength, certainty);
                });
                string publicKey = File.ReadAllText(publicKeyFilePath);
                File.WriteAllText(publicKeyBase64FilePath, Convert.ToBase64String(Encoding.UTF8.GetBytes(publicKey)));
                Console.WriteLine($"Created public key: {publicKeyFilePath}");
                Console.WriteLine($"Converted public key to base64: {publicKeyBase64FilePath}");

                Console.WriteLine($"Created private key: {privateKeyFilePath}");
                string privateKey = File.ReadAllText(privateKeyFilePath);
                File.WriteAllText(privateKeyBase64FilePath, Convert.ToBase64String(Encoding.UTF8.GetBytes(privateKey)));
                Console.WriteLine($"Created private key: {privateKeyFilePath}");
                Console.WriteLine($"Converted private key to base64: {privateKeyBase64FilePath}");

                // Encrypt file
                pgp.EncryptFile(contentFilePath, encryptedFilePath, publicKeyFilePath, true, true);
                Console.WriteLine($"Encrypted test file: {encryptedFilePath}");

                // Decrypt file
                pgp.DecryptFile(encryptedFilePath, decryptedFilePath, privateKeyFilePath, password);
                Console.WriteLine($"Decrypted test file: {decryptedFilePath}");

                Console.WriteLine("Press any key to exit");
                Console.ReadLine();
            }
        }
示例#30
0
 public void EncryptFile(string inputFilePath, string outputFilePath, string publicKey)
 {
     using (var pgp = new PGP())
     {
         using (FileStream inputFileStream = new FileStream(inputFilePath, FileMode.Open))
             using (Stream outputFileStream = File.Create(outputFilePath))
                 using (Stream publicKeyStream = GenerateStreamFromString(publicKey))
                     pgp.EncryptStream(inputFileStream, outputFileStream, publicKeyStream, true, true);
     }
 }