public async Task ExpectProtectRoundTripToSucceed()
        {
            var s3Config = new S3XmlRepositoryConfig(S3IntegrationTests.BucketName)
            {
                KeyPrefix = "CombinedXmlKeyManager3/"
            };
            await s3Cleanup.ClearKeys(S3IntegrationTests.BucketName, s3Config.KeyPrefix);

            var kmsConfig = new KmsXmlEncryptorConfig(KmsIntegrationTests.KmsTestingKey);

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(s3Client);
            serviceCollection.AddSingleton(kmsClient);
            serviceCollection.AddDataProtection()
            .SetApplicationName(KmsIntegrationTests.ApplicationName)
            .PersistKeysToAwsS3(s3Config)
            .ProtectKeysWithAwsKms(kmsConfig);
            using (var serviceProvider = serviceCollection.BuildServiceProvider())
            {
                var prov = serviceProvider.GetRequiredService <IDataProtectionProvider>().CreateProtector("bob");

                var plaintext = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                var encrypted = prov.Protect(plaintext);
                var decrypted = prov.Unprotect(encrypted);
                Assert.Equal(plaintext, decrypted);
            }
        }
Exemple #2
0
        public void ExpectFullKeyManagerStoreRetrieveToSucceed()
        {
            var config = new KmsXmlEncryptorConfig(KmsIntegrationTests.KmsTestingKey);

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(kmsClient);
            serviceCollection.AddDataProtection()
            .PersistKeysToEphemeral()
            .ProtectKeysWithAwsKms(config);
            using (var serviceProvider = serviceCollection.BuildServiceProvider())
            {
                var keyManager = new XmlKeyManager(serviceProvider.GetRequiredService <IOptions <KeyManagementOptions> >(),
                                                   serviceProvider.GetRequiredService <IActivator>());

                var activationDate = new DateTimeOffset(new DateTime(1980, 1, 1));
                var expirationDate = new DateTimeOffset(new DateTime(1980, 6, 1));
                keyManager.CreateNewKey(activationDate, expirationDate);

                IReadOnlyCollection <IKey> keys = keyManager.GetAllKeys();

                Assert.Equal(1, keys.Count);
                Assert.Equal(activationDate, keys.Single().ActivationDate);
                Assert.Equal(expirationDate, keys.Single().ExpirationDate);
                Assert.NotNull(keys.Single().Descriptor);
            }
        }
        public void ExpectFullKeyManagerStoreRetrieveToSucceed()
        {
            var config = new KmsXmlEncryptorConfig(KmsIntegrationTests.ApplicationName, KmsIntegrationTests.KmsTestingKey);

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(kmsClient);
            serviceCollection.AddDataProtection()
            .ProtectKeysWithAwsKms(config);
            serviceCollection.AddSingleton <IXmlRepository, EphemeralXmlRepository>();
            var serviceProvider = serviceCollection.BuildServiceProvider();

            var keyManager = new XmlKeyManager(serviceProvider.GetRequiredService <IXmlRepository>(),
                                               serviceProvider.GetRequiredService <IAuthenticatedEncryptorConfiguration>(),
                                               serviceProvider);

            var activationDate = new DateTimeOffset(new DateTime(1980, 1, 1));
            var expirationDate = new DateTimeOffset(new DateTime(1980, 6, 1));

            keyManager.CreateNewKey(activationDate, expirationDate);

            IReadOnlyCollection <IKey> keys = keyManager.GetAllKeys();

            Assert.Equal(1, keys.Count);
            Assert.Equal(activationDate, keys.Single().ActivationDate);
            Assert.Equal(expirationDate, keys.Single().ExpirationDate);
        }
        public async Task ExpectFullKeyManagerStoreRetrieveToSucceed()
        {
            var s3Config = new S3XmlRepositoryConfig(S3IntegrationTests.BucketName)
            {
                KeyPrefix = "CombinedXmlKeyManager2/"
            };
            await s3Cleanup.ClearKeys(S3IntegrationTests.BucketName, s3Config.KeyPrefix);

            var kmsConfig = new KmsXmlEncryptorConfig(KmsIntegrationTests.KmsTestingKey);

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(s3Client);
            serviceCollection.AddSingleton(kmsClient);
            serviceCollection.AddDataProtection()
            .SetApplicationName(KmsIntegrationTests.ApplicationName)
            .PersistKeysToAwsS3(s3Config)
            .ProtectKeysWithAwsKms(kmsConfig);
            using (var serviceProvider = serviceCollection.BuildServiceProvider())
            {
                var keyManager = new XmlKeyManager(serviceProvider.GetRequiredService <IOptions <KeyManagementOptions> >(),
                                                   serviceProvider.GetRequiredService <IActivator>());

                var activationDate = new DateTimeOffset(new DateTime(1980, 1, 1));
                var expirationDate = new DateTimeOffset(new DateTime(1980, 6, 1));
                keyManager.CreateNewKey(activationDate, expirationDate);

                IReadOnlyCollection <IKey> keys = keyManager.GetAllKeys();

                Assert.Equal(1, keys.Count);
                Assert.Equal(activationDate, keys.Single().ActivationDate);
                Assert.Equal(expirationDate, keys.Single().ExpirationDate);
                Assert.NotNull(keys.Single().Descriptor);
            }
        }
        public void ExpectBuilderAdditions(bool withClient)
        {
            var services = new List <ServiceDescriptor>();

            builder.Setup(x => x.Services).Returns(svcCollection.Object);
            svcCollection.Setup(x => x.Count).Returns(() => services.Count);
            svcCollection.Setup(x => x.Add(It.IsAny <ServiceDescriptor>())).Callback <ServiceDescriptor>(sd => services.Add(sd));
            svcCollection.Setup(x => x[It.IsAny <int>()]).Returns <int>(index => services[index]);
            svcCollection.Setup(x => x.RemoveAt(It.IsAny <int>())).Callback <int>(index => services.RemoveAt(index));

            var config = new KmsXmlEncryptorConfig("appName", "keyId");

            // Repeat call to ensure cumulative calls work
            if (withClient)
            {
                builder.Object.ProtectKeysWithAwsKms(client.Object, config);
                builder.Object.ProtectKeysWithAwsKms(client.Object, config);
            }
            else
            {
                builder.Object.ProtectKeysWithAwsKms(config);
                builder.Object.ProtectKeysWithAwsKms(config);
            }

            Assert.Equal(withClient ? 6 : 5, services.Count);
            Assert.Equal(1, services.Count(x => x.ServiceType == typeof(IXmlEncryptor)));
            Assert.Equal(1, services.Count(x => x.ServiceType == typeof(IXmlDecryptor)));
            Assert.Equal(withClient ? 1 : 0, services.Count(x => x.ServiceType == typeof(IAmazonKeyManagementService)));
            Assert.Equal(1, services.Count(x => x.ServiceType == typeof(KmsXmlEncryptorConfig)));
            Assert.Equal(1, services.Count(x => x.ServiceType == typeof(IKmsXmlEncryptorConfig)));
            Assert.Equal(1, services.Count(x => x.ServiceType == typeof(KmsXmlDecryptor)));

            Assert.Equal(ServiceLifetime.Singleton, services.Single(x => x.ServiceType == typeof(IXmlEncryptor)).Lifetime);
            Assert.Equal(ServiceLifetime.Singleton, services.Single(x => x.ServiceType == typeof(IXmlDecryptor)).Lifetime);
            Assert.Equal(ServiceLifetime.Singleton, services.Single(x => x.ServiceType == typeof(KmsXmlEncryptorConfig)).Lifetime);
            Assert.Equal(ServiceLifetime.Singleton, services.Single(x => x.ServiceType == typeof(IKmsXmlEncryptorConfig)).Lifetime);
            Assert.Equal(ServiceLifetime.Singleton, services.Single(x => x.ServiceType == typeof(KmsXmlDecryptor)).Lifetime);

            provider.Setup(x => x.GetService(typeof(IAmazonKeyManagementService))).Returns(client.Object);
            if (withClient)
            {
                Assert.Equal(ServiceLifetime.Singleton, services.Single(x => x.ServiceType == typeof(IAmazonKeyManagementService)).Lifetime);
                Assert.Same(client.Object, services.Single(x => x.ServiceType == typeof(IAmazonKeyManagementService)).ImplementationInstance);
            }
            Assert.Same(config, services.Single(x => x.ServiceType == typeof(KmsXmlEncryptorConfig)).ImplementationInstance);
            Assert.Same(config, services.Single(x => x.ServiceType == typeof(IKmsXmlEncryptorConfig)).ImplementationInstance);

            provider.Setup(x => x.GetService(typeof(ILoggerFactory))).Returns(loggerFactory.Object);
            loggerFactory.Setup(x => x.CreateLogger(typeof(KmsXmlEncryptor).FullName)).Returns(repository.Create <ILogger <KmsXmlEncryptor> >().Object);
            loggerFactory.Setup(x => x.CreateLogger(typeof(KmsXmlDecryptor).FullName)).Returns(repository.Create <ILogger <KmsXmlDecryptor> >().Object);
            provider.Setup(x => x.GetService(typeof(IKmsXmlEncryptorConfig))).Returns(config);

            var decryptor = services.Single(x => x.ServiceType == typeof(KmsXmlDecryptor)).ImplementationFactory(provider.Object);

            provider.Setup(x => x.GetService(typeof(KmsXmlDecryptor))).Returns(decryptor);

            Assert.IsType <KmsXmlDecryptor>(decryptor);
            Assert.IsType <KmsXmlEncryptor>(services.Single(x => x.ServiceType == typeof(IXmlEncryptor)).ImplementationFactory(provider.Object));
            Assert.Same(decryptor, services.Single(x => x.ServiceType == typeof(IXmlDecryptor)).ImplementationFactory(provider.Object));
        }
        public void ExpectBuilderAdditions(bool withClient)
        {
            var services = new List <ServiceDescriptor>();

            builder.Setup(x => x.Services).Returns(svcCollection.Object);
            svcCollection.Setup(x => x.GetEnumerator()).Returns(() => services.GetEnumerator());
            svcCollection.Setup(x => x.Add(It.IsAny <ServiceDescriptor>()))
            .Callback <ServiceDescriptor>(sd => { services.Add(sd); });

            var config = new KmsXmlEncryptorConfig("keyId");

            // Repeat call to ensure cumulative calls work
            if (withClient)
            {
                builder.Object.ProtectKeysWithAwsKms(client.Object, config);
                builder.Object.ProtectKeysWithAwsKms(client.Object, config);
            }
            else
            {
                builder.Object.ProtectKeysWithAwsKms(config);
                builder.Object.ProtectKeysWithAwsKms(config);
            }

            Assert.Equal(withClient ? 1 : 0, services.Count(x => x.ServiceType == typeof(IAmazonKeyManagementService)));

            // IConfigureOptions is designed & expected to be present multiple times, so expect two after two calls
            Assert.Equal(2, services.Count(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>)));
            Assert.Equal(2, services.Count(x => x.ServiceType == typeof(IConfigureOptions <KmsXmlEncryptorConfig>)));

            Assert.Equal(ServiceLifetime.Singleton, services.First(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>)).Lifetime);
            Assert.Equal(ServiceLifetime.Singleton, services.First(x => x.ServiceType == typeof(IConfigureOptions <KmsXmlEncryptorConfig>)).Lifetime);

            provider.Setup(x => x.GetService(typeof(IAmazonKeyManagementService))).Returns(client.Object);
            if (withClient)
            {
                Assert.Equal(ServiceLifetime.Singleton, services.Single(x => x.ServiceType == typeof(IAmazonKeyManagementService)).Lifetime);
                Assert.Same(client.Object, services.Single(x => x.ServiceType == typeof(IAmazonKeyManagementService)).ImplementationInstance);
            }
            // Ensure we run equivalent config for the actual configuration object
            var configureObject = services.First(x => x.ServiceType == typeof(IConfigureOptions <KmsXmlEncryptorConfig>)).ImplementationInstance;
            var optionsObject   = new KmsXmlEncryptorConfig();

            ((IConfigureOptions <KmsXmlEncryptorConfig>)configureObject).Configure(optionsObject);

            provider.Setup(x => x.GetService(typeof(ILoggerFactory))).Returns(loggerFactory.Object);
            provider.Setup(x => x.GetService(typeof(IOptions <KmsXmlEncryptorConfig>))).Returns(snapshot.Object);
            provider.Setup(x => x.GetService(typeof(IOptions <DataProtectionOptions>))).Returns(dpSnapshot.Object);
            loggerFactory.Setup(x => x.CreateLogger(typeof(KmsXmlEncryptor).FullName)).Returns(repository.Create <ILogger <KmsXmlEncryptor> >().Object);
            snapshot.Setup(x => x.Value).Returns(optionsObject);
            var dbOptions = new DataProtectionOptions();

            dpSnapshot.Setup(x => x.Value).Returns(dbOptions);

            var configure = services.First(x => x.ServiceType == typeof(IConfigureOptions <KeyManagementOptions>)).ImplementationFactory(provider.Object);
            var options   = new KeyManagementOptions();

            ((IConfigureOptions <KeyManagementOptions>)configure).Configure(options);
            Assert.IsType <KmsXmlEncryptor>(options.XmlEncryptor);
        }
        public void ExpectEncryptToSucceed(bool useAppId, bool hashAppId, string appId, string expectedAppId)
        {
            var myEncryptedString     = "encrypted";
            var myBase64EncryptedData = Convert.ToBase64String(Encoding.UTF8.GetBytes(myEncryptedString));
            var myEncryptedXml        = new XElement(ElementName, new XElement("value", myBase64EncryptedData));
            var myOutputXml           = new XElement(ElementName, "output");

            using (var decryptedResponseStream = new MemoryStream())
            {
                myOutputXml.Save(decryptedResponseStream);
                decryptedResponseStream.Seek(0, SeekOrigin.Begin);

                var decryptResponse = new DecryptResponse
                {
                    KeyId     = KeyId,
                    Plaintext = decryptedResponseStream
                };

                var actualConfig = new KmsXmlEncryptorConfig
                {
                    EncryptionContext        = encryptionContext,
                    GrantTokens              = grantTokens,
                    KeyId                    = KeyId,
                    DiscriminatorAsContext   = useAppId,
                    HashDiscriminatorContext = hashAppId
                };

                var actualOptions = new DataProtectionOptions
                {
                    ApplicationDiscriminator = appId
                };

                encryptConfig.Setup(x => x.Value).Returns(actualConfig);
                dpOptions.Setup(x => x.Value).Returns(actualOptions);

                kmsClient.Setup(x => x.DecryptAsync(It.IsAny <DecryptRequest>(), CancellationToken.None))
                .ReturnsAsync(decryptResponse)
                .Callback <DecryptRequest, CancellationToken>((dr, ct) =>
                {
                    if (appId != null && useAppId)
                    {
                        Assert.Contains(KmsConstants.ApplicationEncryptionContextKey, dr.EncryptionContext.Keys);
                        Assert.Equal(expectedAppId, dr.EncryptionContext[KmsConstants.ApplicationEncryptionContextKey]);
                    }
                    else
                    {
                        Assert.Same(encryptionContext, dr.EncryptionContext);
                    }
                    Assert.Same(grantTokens, dr.GrantTokens);

                    Assert.Equal(myEncryptedString, Encoding.UTF8.GetString(dr.CiphertextBlob.ToArray()));
                });

                var plaintextXml = decryptor.Decrypt(myEncryptedXml);
                Assert.True(XNode.DeepEquals(myOutputXml, plaintextXml));
            }
        }
        public void ExpectValidationOfConfigToThrow()
        {
            var configObject = new KmsXmlEncryptorConfig();

            encryptConfig.Setup(x => x.Value).Returns(configObject);

            var altRepo = new KmsXmlEncryptor(kmsClient.Object, encryptConfig.Object, dpOptions.Object);

            Assert.Throws <ArgumentException>(() => altRepo.ValidateConfig());
        }
        public async Task ExpectApplicationIsolationToThrow(string app1, string app2, bool throws)
        {
            var s3Config = new S3XmlRepositoryConfig(S3IntegrationTests.BucketName)
            {
                KeyPrefix = "CombinedXmlKeyManager4/"
            };
            await s3Cleanup.ClearKeys(S3IntegrationTests.BucketName, s3Config.KeyPrefix);

            var kmsConfig = new KmsXmlEncryptorConfig(KmsIntegrationTests.KmsTestingKey);

            var plaintext = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            byte[] encrypted;

            {
                var serviceCollection = new ServiceCollection();
                serviceCollection.AddSingleton(s3Client);
                serviceCollection.AddSingleton(kmsClient);
                serviceCollection.AddDataProtection()
                .SetApplicationName(app1)
                .PersistKeysToAwsS3(s3Config)
                .ProtectKeysWithAwsKms(kmsConfig);
                using (var serviceProvider = serviceCollection.BuildServiceProvider())
                {
                    var prov = serviceProvider.GetRequiredService <IDataProtectionProvider>().CreateProtector("bob");

                    encrypted = prov.Protect(plaintext);
                }
            }

            {
                var serviceCollection = new ServiceCollection();
                serviceCollection.AddSingleton(s3Client);
                serviceCollection.AddSingleton(kmsClient);
                serviceCollection.AddDataProtection()
                .SetApplicationName(app2)
                .PersistKeysToAwsS3(s3Config)
                .ProtectKeysWithAwsKms(kmsConfig);
                using (var serviceProvider = serviceCollection.BuildServiceProvider())
                {
                    var prov = serviceProvider.GetRequiredService <IDataProtectionProvider>().CreateProtector("bob");

                    if (throws)
                    {
                        Assert.Throws <CryptographicException>(() => prov.Unprotect(encrypted));
                    }
                    else
                    {
                        Assert.NotNull(prov.Unprotect(encrypted));
                    }
                }
            }
        }
Exemple #10
0
        public void ExpectConstructorRoundTrip()
        {
            var config = new KmsXmlEncryptorConfig("keyId");

            Assert.Equal("keyId", config.KeyId);

            // strictly a List & Dictionary test, but validates the config doesn't really care about these entries as long as the user sets them up how they want
            config.GrantTokens.Add("token");
            Assert.Contains("token", config.GrantTokens);

            config.EncryptionContext.Add("myContext", "myValue");
            Assert.Contains("myContext", config.EncryptionContext.Keys);
            Assert.Contains("myValue", config.EncryptionContext.Values);
        }
        public KmsIntegrationTests()
        {
            // Expectation that local SDK has been configured correctly, whether via VS Tools or user config files
            kmsClient = new AmazonKeyManagementServiceClient(RegionEndpoint.EUWest1);
            var encryptConfig = new KmsXmlEncryptorConfig(ApplicationName, KmsTestingKey);

            var svcCollection = new ServiceCollection();

            svcCollection.AddSingleton <IKmsXmlEncryptorConfig>(sp => encryptConfig);
            svcCollection.AddSingleton(sp => kmsClient);
            var svcProvider = svcCollection.BuildServiceProvider();

            encryptor = new KmsXmlEncryptor(kmsClient, encryptConfig, svcProvider);

            decryptor = new KmsXmlDecryptor(svcProvider);
        }
Exemple #12
0
        public void ExpectApplicationIsolationToThrow(string app1, string app2, bool throws)
        {
            var config = new KmsXmlEncryptorConfig(KmsIntegrationTests.KmsTestingKey);

            var sharedStorage = new EphemeralXmlRepository();
            var plaintext     = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };

            byte[] encrypted;

            {
                var serviceCollection = new ServiceCollection();
                serviceCollection.AddSingleton(kmsClient);
                serviceCollection.AddDataProtection()
                .SetApplicationName(app1)
                .PersistKeysToEphemeral(sharedStorage)
                .ProtectKeysWithAwsKms(config);
                using (var serviceProvider = serviceCollection.BuildServiceProvider())
                {
                    var prov = serviceProvider.GetRequiredService <IDataProtectionProvider>().CreateProtector("bob");

                    encrypted = prov.Protect(plaintext);
                }
            }

            {
                var serviceCollection = new ServiceCollection();
                serviceCollection.AddSingleton(kmsClient);
                serviceCollection.AddDataProtection()
                .SetApplicationName(app2)
                .PersistKeysToEphemeral(sharedStorage)
                .ProtectKeysWithAwsKms(config);
                using (var serviceProvider = serviceCollection.BuildServiceProvider())
                {
                    var prov = serviceProvider.GetRequiredService <IDataProtectionProvider>().CreateProtector("bob");

                    if (throws)
                    {
                        Assert.Throws <CryptographicException>(() => prov.Unprotect(encrypted));
                    }
                    else
                    {
                        Assert.NotNull(prov.Unprotect(encrypted));
                    }
                }
            }
        }
Exemple #13
0
        public void ExpectProtectRoundTripToSucceed()
        {
            var config = new KmsXmlEncryptorConfig(KmsIntegrationTests.KmsTestingKey);

            var serviceCollection = new ServiceCollection();

            serviceCollection.AddSingleton(kmsClient);
            serviceCollection.AddDataProtection()
            .PersistKeysToEphemeral()
            .ProtectKeysWithAwsKms(config);
            using (var serviceProvider = serviceCollection.BuildServiceProvider())
            {
                var prov = serviceProvider.GetRequiredService <IDataProtectionProvider>().CreateProtector("bob");

                var plaintext = new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                var encrypted = prov.Protect(plaintext);
                var decrypted = prov.Unprotect(encrypted);
                Assert.Equal(plaintext, decrypted);
            }
        }
Exemple #14
0
        public void ExpectConstructorCopy()
        {
            var config = new KmsXmlEncryptorConfig {
                KeyId = "keyId"
            };

            config.EncryptionContext.Add("myContext", "myValue");
            config.GrantTokens.Add("token");
            config.DiscriminatorAsContext   = false;
            config.HashDiscriminatorContext = false;

            var copy = new KmsXmlEncryptorConfig();

            copy.CopyFrom(config);

            Assert.Equal(config.KeyId, copy.KeyId);
            Assert.Equal(config.EncryptionContext, copy.EncryptionContext);
            Assert.Equal(config.GrantTokens, copy.GrantTokens);
            Assert.Equal(config.DiscriminatorAsContext, copy.DiscriminatorAsContext);
            Assert.Equal(config.HashDiscriminatorContext, copy.HashDiscriminatorContext);
        }
        private static KmsXmlEncryptorConfig ToNewKmsConfig(JObject config)
        {
            var newConfig = new KmsXmlEncryptorConfig(config[nameof(KmsXmlEncryptorConfig.KeyId)].Value <string>());

            var appName    = config[MigrationV1Fixture.ApplicationNameKey].Value <string>();
            var kmsAppName = config[MigrationV1Fixture.KmsApplicationNameKey].Value <string>();

            if (appName == kmsAppName)
            {
                // Normal migration requires the following settings
                newConfig.DiscriminatorAsContext   = true;
                newConfig.HashDiscriminatorContext = false;
            }
            else
            {
                // If the app names differed, migration requires special contexts
                newConfig.DiscriminatorAsContext   = false;
                newConfig.HashDiscriminatorContext = false;
                newConfig.EncryptionContext[KmsConstants.ApplicationEncryptionContextKey] = kmsAppName;
            }

            return(newConfig);
        }
        public KmsIntegrationTests()
        {
            // Expectation that local SDK has been configured correctly, whether via VS Tools or user config files
            kmsClient = new AmazonKeyManagementServiceClient(RegionEndpoint.EUWest1);
            var encryptConfig = new KmsXmlEncryptorConfig(KmsTestingKey);

            dpOptions = new DataProtectionOptions {
                ApplicationDiscriminator = ApplicationName
            };
            var encryptSnapshot = new DirectOptions <KmsXmlEncryptorConfig>(encryptConfig);
            var dpSnapshot      = new DirectOptions <DataProtectionOptions>(dpOptions);

            var svcCollection = new ServiceCollection();

            svcCollection.AddSingleton <IOptions <KmsXmlEncryptorConfig> >(sp => encryptSnapshot);
            svcCollection.AddSingleton <IOptions <DataProtectionOptions> >(sp => dpSnapshot);
            svcCollection.AddSingleton(sp => kmsClient);
            svcProvider = svcCollection.BuildServiceProvider();

            encryptor = new KmsXmlEncryptor(kmsClient, encryptSnapshot, dpSnapshot);

            decryptor = new KmsXmlDecryptor(svcProvider);
        }
Exemple #17
0
#pragma warning disable S3242 // JObject is more descriptive than 'more general' IDictionary
        private static (string ControlValue, byte[] ToEncrypt, string Protector, string ApplicationName, S3XmlRepositoryConfig S3Config, KmsXmlEncryptorConfig KmsConfig) ToOldConfig(JObject config)
#pragma warning restore S3242
        {
            var controlValue   = config[ConfigType].Value <string>();
            var protectData    = Convert.FromBase64String(config[DataToProtect].Value <string>());
            var protectorValue = config[ProtectorKey].Value <string>();

            var old = new S3XmlRepositoryConfig(config[nameof(S3XmlRepositoryConfig.Bucket)].Value <string>());

            if (config.TryGetValue(nameof(S3XmlRepositoryConfig.KeyPrefix), out JToken keyprefix))
            {
                old.KeyPrefix = keyprefix.Value <string>();
            }

            if (config.TryGetValue(nameof(S3XmlRepositoryConfig.MaxS3QueryConcurrency), out JToken concurrency))
            {
                old.MaxS3QueryConcurrency = concurrency.Value <int>();
            }

            if (config.TryGetValue(nameof(S3XmlRepositoryConfig.StorageClass), out JToken storageClass))
            {
                old.StorageClass = S3StorageClass.FindValue(storageClass.Value <string>());
            }

            if (config.TryGetValue(nameof(S3XmlRepositoryConfig.ServerSideEncryptionMethod), out JToken serverSideEncryptionMethod))
            {
                old.ServerSideEncryptionMethod = ServerSideEncryptionMethod.FindValue(serverSideEncryptionMethod.Value <string>());
            }

            if (config.TryGetValue(nameof(S3XmlRepositoryConfig.ServerSideEncryptionCustomerMethod), out JToken serverSideEncryptionCustomerMethod))
            {
                old.ServerSideEncryptionCustomerMethod = ServerSideEncryptionCustomerMethod.FindValue(serverSideEncryptionCustomerMethod.Value <string>());
            }

            if (config.TryGetValue(nameof(S3XmlRepositoryConfig.ServerSideEncryptionCustomerProvidedKey), out JToken serverSideEncryptionCustomerProvidedKey))
            {
                old.ServerSideEncryptionCustomerProvidedKey = serverSideEncryptionCustomerProvidedKey.Value <string>();
            }

            if (config.TryGetValue(nameof(S3XmlRepositoryConfig.ServerSideEncryptionCustomerProvidedKeyMd5), out JToken serverSideEncryptionCustomerProvidedKeyMd5))
            {
                old.ServerSideEncryptionCustomerProvidedKeyMd5 = serverSideEncryptionCustomerProvidedKeyMd5.Value <string>();
            }

            if (config.TryGetValue(nameof(S3XmlRepositoryConfig.ServerSideEncryptionKeyManagementServiceKeyId), out JToken serverSideEncryptionKeyManagementServiceKeyId))
            {
                old.ServerSideEncryptionKeyManagementServiceKeyId = serverSideEncryptionKeyManagementServiceKeyId.Value <string>();
            }

            if (config.TryGetValue(nameof(S3XmlRepositoryConfig.ClientSideCompression), out JToken clientSideCompression))
            {
                old.ClientSideCompression = clientSideCompression.Value <bool>();
            }

            string applicationName = null;

            if (config.TryGetValue(ApplicationNameKey, out JToken appName))
            {
                applicationName = appName.Value <string>();
            }

            string kmsApplicationName = null;

            if (config.TryGetValue(KmsApplicationNameKey, out JToken kmsAppName))
            {
                kmsApplicationName = kmsAppName.Value <string>();
            }

            string keyIdentifier = null;

            if (config.TryGetValue(nameof(KmsXmlEncryptorConfig.KeyId), out JToken keyId))
            {
                keyIdentifier = keyId.Value <string>();
            }

            KmsXmlEncryptorConfig kmsConfig = null;

            if (!string.IsNullOrEmpty(kmsApplicationName) && !string.IsNullOrEmpty(keyIdentifier))
            {
                kmsConfig = new KmsXmlEncryptorConfig(kmsApplicationName, keyIdentifier);
            }

            return(controlValue, protectData, protectorValue, applicationName, old, kmsConfig);
        }
        public void ExpectEncryptToSucceed(bool useAppId, bool hashAppId, string appId, string expectedAppId)
        {
            var myInputXml = new XElement(ElementName, "input");

            byte[] myEncryptedData       = Encoding.UTF8.GetBytes("encrypted");
            var    myBase64EncryptedData = Convert.ToBase64String(myEncryptedData);

            using (var encryptedResponseStream = new MemoryStream())
            {
                encryptedResponseStream.Write(myEncryptedData, 0, myEncryptedData.Length);
                encryptedResponseStream.Seek(0, SeekOrigin.Begin);

                var encryptResponse = new EncryptResponse
                {
                    KeyId          = KeyId,
                    CiphertextBlob = encryptedResponseStream
                };

                var actualConfig = new KmsXmlEncryptorConfig
                {
                    EncryptionContext        = encryptionContext,
                    GrantTokens              = grantTokens,
                    KeyId                    = KeyId,
                    DiscriminatorAsContext   = useAppId,
                    HashDiscriminatorContext = hashAppId
                };

                var actualOptions = new DataProtectionOptions
                {
                    ApplicationDiscriminator = appId
                };

                encryptConfig.Setup(x => x.Value).Returns(actualConfig);
                dpOptions.Setup(x => x.Value).Returns(actualOptions);

                kmsClient.Setup(x => x.EncryptAsync(It.IsAny <EncryptRequest>(), CancellationToken.None))
                .ReturnsAsync(encryptResponse)
                .Callback <EncryptRequest, CancellationToken>((er, ct) =>
                {
                    if (appId != null && useAppId)
                    {
                        Assert.Contains(KmsConstants.ApplicationEncryptionContextKey, er.EncryptionContext.Keys);
                        Assert.Equal(expectedAppId, er.EncryptionContext[KmsConstants.ApplicationEncryptionContextKey]);
                    }
                    else
                    {
                        Assert.Same(encryptionContext, er.EncryptionContext);
                    }
                    Assert.Same(grantTokens, er.GrantTokens);

                    var body = XElement.Load(er.Plaintext);
                    Assert.True(XNode.DeepEquals(myInputXml, body));
                });

                var encryptedXml = encryptor.Encrypt(myInputXml);

                Assert.Equal(typeof(KmsXmlDecryptor), encryptedXml.DecryptorType);
                var encryptedBlob = (string)encryptedXml.EncryptedElement.Element("value");
                Assert.Equal(myBase64EncryptedData, encryptedBlob);
            }
        }
Exemple #19
0
        public byte[] CreateS3AndKms(byte[] toEncrypt, string protector, string applicationName, S3XmlRepositoryConfig s3Config, KmsXmlEncryptorConfig kmsConfig)
        {
            var serviceCollection = new ServiceCollection();

            serviceCollection.AddDataProtection()
            .SetApplicationName(applicationName)
            .ProtectKeysWithAwsKms(kmsClient, kmsConfig)
            .PersistKeysToAwsS3(s3Client, s3Config);

            var serviceProvider = serviceCollection.BuildServiceProvider();

            using (serviceProvider as IDisposable)
            {
                var prov = serviceProvider.GetRequiredService <IDataProtectionProvider>().CreateProtector(protector);

                return(prov.Protect(toEncrypt));
            }
        }