Ejemplo n.º 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"
            });
        }
Ejemplo n.º 2
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();
        }
Ejemplo n.º 3
0
        public async Task DecryptStreamAsync_DecryptEncryptedStreamWithMultipleKeys(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))
                            await pgp.EncryptStreamAsync(inputFileStream, outputFileStream, new List <Stream>() { publicKeyStream1, publicKeyStream2 });

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

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

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

            string decryptedContent2 = await File.ReadAllTextAsync(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();
        }
Ejemplo n.º 4
0
        internal static async Task <string> DecryptStringAsync(this PGP pgp, string data, byte[] key, SecureString password)
        {
            using (var ks = new MemoryStream(key))
                using (var ds = new MemoryStream(Encoding.UTF8.GetBytes(data)))
                    using (var os = new MemoryStream())
                    {
                        var bStrPtr      = Marshal.SecureStringToBSTR(password);
                        var decryptedStr = Marshal.PtrToStringBSTR(bStrPtr);
                        Marshal.ZeroFreeBSTR(bStrPtr);

                        await pgp.DecryptStreamAsync(ds, os, ks, decryptedStr);

                        return(Encoding.UTF8.GetString(os.ToArray()));
                    }
        }
Ejemplo n.º 5
0
        private static async Task <Stream> DecryptAsync(Stream inputStream, string privateKey, string passPhrase)
        {
            using (PGP pgp = new PGP())
            {
                Stream outputStream = new MemoryStream();

                using (inputStream)
                    using (Stream privateKeyStream = GenerateStreamFromString(privateKey))
                    {
                        await pgp.DecryptStreamAsync(inputStream, outputStream, privateKeyStream, passPhrase);

                        outputStream.Seek(0, SeekOrigin.Begin);
                        return(outputStream);
                    }
            }
        }
Ejemplo n.º 6
0
        public async Task <string> DecryptAsync(string data)
        {
            using (PGP pgp = new PGP())
            {
                var inputStream  = GenerateStreamFromString(data);
                var outputStream = new MemoryStream();
                var privateKey   = _config["PGP_PrivateKey"];
                var passphrase   = _config["PGP_Passphrase"];

                byte[] b = Convert.FromBase64String(privateKey);

                var strOriginal = System.Text.Encoding.UTF8.GetString(b);

                using (Stream privateKeyStream = GenerateStreamFromString(strOriginal))
                {
                    await pgp.DecryptStreamAsync(inputStream, outputStream, privateKeyStream, passphrase);

                    outputStream.Seek(0, SeekOrigin.Begin);
                    return(GenerateStringFromStream(outputStream));
                }
            }
        }
Ejemplo n.º 7
0
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello World!");

            X509Store certStore = new X509Store(StoreName.My, StoreLocation.CurrentUser);

            certStore.Open(OpenFlags.ReadOnly);
            X509Certificate2Collection certCollection = certStore.Certificates.Find(
                X509FindType.FindByThumbprint,
                // Replace below with your certificate's thumbprint
                Environment.GetEnvironmentVariable("WEBSITE_LOAD_CERTIFICATES"),
                false);

            // Get the first cert with the thumbprint
            Console.WriteLine($"cert collection count: {certCollection.Count}");
            if (certCollection.Count > 0)
            {
                X509Certificate2 rawCert = certCollection[0];
                // Use certificate
                Console.WriteLine($"friendly name: {rawCert.FriendlyName}");
                Console.WriteLine($"subject: {rawCert.Subject}");
                var appId = Environment.GetEnvironmentVariable("APPLICATION_ID");
                Cert = Cert ?? new ClientAssertionCertificate(appId, rawCert);

                var vaultKeyPrefix = Environment.GetEnvironmentVariable("VAULT_KEY_PREFIX");
                var vaultUrl       = Environment.GetEnvironmentVariable("VAULT_URL");
                Client = Client ?? new KeyVaultClient(GetAccessTokenAsync);

                var secret = new SecretBundle();
                secret = await Client.GetSecretAsync(vaultUrl, $"{vaultKeyPrefix}-public");

                var publicKey = Regex.Unescape(secret.Value);
                Console.WriteLine($"public fetched");
                secret = await Client.GetSecretAsync(vaultUrl, $"{vaultKeyPrefix}-private");

                var privateKey = Regex.Unescape(secret.Value);
                Console.WriteLine($"private fetched");
                secret = await Client.GetSecretAsync(vaultUrl, $"{vaultKeyPrefix}-pass");

                var PassPhrase = Regex.Unescape(secret.Value);
                Console.WriteLine($"passphrase fetched");

                try
                {
                    Console.WriteLine("Opening file streams");

                    /*
                     * Replace this PGP file with one you have encrypted with your private key already.
                     * It is unlikely that this key will work.
                     */
                    var inputStream = File.Open("./samplepgpfile.txt.txt.pgp", FileMode.Open, FileAccess.ReadWrite);
                    var outStream   = new MemoryStream();

                    Console.WriteLine("Creating Private Key Stream");
                    var privateKeyStream = new MemoryStream(Encoding.UTF8.GetBytes(privateKey));
                    PassPhrase = PassPhrase == "0" ? null : PassPhrase;

                    Console.WriteLine("decrypting");
                    await _pgp.DecryptStreamAsync(inputStream, outStream, privateKeyStream, PassPhrase);

                    Console.WriteLine("Decrypted");
                    using (var outputStream = File.Open("./output.txt", FileMode.Create, FileAccess.Write))
                        outStream.WriteTo(outputStream);
                    outStream.Dispose();
                    Console.WriteLine("File created");
                }
                catch (Exception ex)
                {
                    Console.WriteLine("Error");
                    Console.WriteLine(ex.Message); //A Message of No key found would indicate that we have the wrong key.
                }
            }
            else
            {
                Console.WriteLine("no certs fetched");
            }
            certStore.Close();

            Console.WriteLine("it's over");
        }
Ejemplo n.º 8
0
 public async Task DecryptStreamAsync(Stream inputStream, Stream outputStream, PrivateKey privateKey, Func <string> passwordFinder)
 {
     using var pgp = new PGP();
     using var privateKeyStream = GetPrivateKey(privateKey);
     await pgp.DecryptStreamAsync(inputStream, outputStream, privateKeyStream, null);
 }