Example #1
0
        public KmsManagerIntegrationTests(ConfigurationFixture fixture)
        {
            this.fixture = fixture;

            // Expectation that local SDK has been configured correctly, whether via VS Tools or user config files
            kmsClient = new AmazonKeyManagementServiceClient(RegionEndpoint.EUWest1);
        }
Example #2
0
        /// <summary>
        /// Generates an instruction that will be used to encrypt an object
        /// using materials with the KMSKeyID set.
        /// </summary>
        /// <param name="kmsClient">
        /// Used to call KMS to generate a data key.
        /// </param>
        /// <param name="materials">
        /// The encryption materials to be used to encrypt and decrypt data.
        /// </param>
        /// <returns>
        /// The instruction that will be used to encrypt an object.
        /// </returns>
        internal static EncryptionInstructions GenerateInstructionsForKMSMaterialsV2(IAmazonKeyManagementService kmsClient, EncryptionMaterialsV2 materials)
        {
            if (materials.KMSKeyID == null)
            {
                throw new ArgumentNullException(nameof(materials.KMSKeyID), KmsKeyIdNullMessage);
            }

            switch (materials.KmsType)
            {
            case KmsType.KmsContext:
            {
                var nonce = new byte[DefaultNonceSize];

                // Generate nonce, and get both the key and the encrypted key from KMS.
                RandomNumberGenerator.Create().GetBytes(nonce);
                var result = kmsClient.GenerateDataKey(materials.KMSKeyID, materials.MaterialsDescription, KMSKeySpec);

                var instructions = new EncryptionInstructions(materials.MaterialsDescription, result.KeyPlaintext, result.KeyCiphertext, nonce,
                                                              XAmzWrapAlgKmsContextValue, XAmzAesGcmCekAlgValue);
                return(instructions);
            }

            default:
                throw new NotSupportedException($"{materials.KmsType} is not supported for KMS Key Id {materials.KMSKeyID}");
            }
        }
 public CombinedManagerIntegrationTests()
 {
     // Expectation that local SDK has been configured correctly, whether via VS Tools or user config files
     s3Client  = new AmazonS3Client(RegionEndpoint.EUWest1);
     kmsClient = new AmazonKeyManagementServiceClient(RegionEndpoint.EUWest1);
     s3Cleanup = new CleanupS3(s3Client);
 }
        internal virtual Option <JObject> EncryptKeyAndBuildResult(
            IAmazonKeyManagementService kmsClient,
            string region,
            string arn,
            byte[] dataKeyPlainText)
        {
            try
            {
                TimerOptions encryptTimerOptions =
                    new TimerOptions {
                    Name = MetricsUtil.AelMetricsPrefix + ".kms.aws.encrypt." + region
                };
                using (MetricsUtil.MetricsInstance.Measure.Timer.Time(encryptTimerOptions))
                {
                    // Note we can't wipe plaintext key till end of calling method since underlying buffer shared by all requests
                    EncryptRequest encryptRequest = new EncryptRequest
                    {
                        KeyId     = arn,
                        Plaintext = new MemoryStream(dataKeyPlainText)
                    };
                    Task <EncryptResponse> encryptAsync = kmsClient.EncryptAsync(encryptRequest);

                    byte[] encryptedKeyEncryptionKey = encryptAsync.Result.CiphertextBlob.ToArray();

                    return(Option <JObject> .Some(BuildKmsRegionKeyJson(region, arn, encryptedKeyEncryptionKey)));
                }
            }
            catch (AggregateException e)
            {
                Logger.LogWarning(e, "Failed to encrypt generated data key via region {region} KMS", region);

                // TODO Consider adding notification/CW alert
                return(Option <JObject> .None);
            }
        }
 /// <summary>
 /// Creates a <see cref="KmsXmlDecryptor"/> for decrypting ASP.NET keys with a KMS master key
 /// </summary>
 /// <remarks>
 /// DataProtection has a fairly awful way of making the IXmlDecryptor that by default never just does
 /// <see cref="IServiceProvider.GetService"/>, instead calling the constructor that takes <see cref="IServiceProvider"/> directly.
 /// This means we have to do the resolution of needed objects via <see cref="IServiceProvider"/>.
 /// </remarks>
 /// <param name="services">A mandatory <see cref="IServiceProvider"/> to provide services</param>
 public KmsXmlDecryptor(IServiceProvider services)
 {
     kmsClient = services?.GetRequiredService <IAmazonKeyManagementService>() ?? throw new ArgumentNullException(nameof(services));
     config    = services.GetRequiredService <IOptions <KmsXmlEncryptorConfig> >();
     dpOptions = services.GetRequiredService <IOptions <DataProtectionOptions> >();
     logger    = services.GetService <ILoggerFactory>()?.CreateLogger <KmsXmlDecryptor>();
 }
        /// <summary>
        /// Attempt to generate a KMS datakey using the first successful response using a sorted dictionary of available KMS clients.
        /// </summary>
        /// <param name="sortedRegionToArnAndClientDictionary"> A sorted dictionary mapping regions and their arns and kms clients</param>
        /// <param name="dateKeyKeyId">The KMS arn used to generate the data key</param>
        /// <returns>A GenerateDataKeyResult object that contains the plain text key and the ciphertext for that key</returns>
        /// <exception cref="KeyManagementException">Throw an exception if we're unable to generate a datakey in any AWS region</exception>
        internal virtual GenerateDataKeyResult GenerateDataKey(OrderedDictionary sortedRegionToArnAndClientDictionary, out string dateKeyKeyId)
        {
            foreach (DictionaryEntry regionToArnAndClient in sortedRegionToArnAndClientDictionary)
            {
                try
                {
                    TimerOptions generateDataKeyTimerOptions = new TimerOptions
                    {
                        Name = MetricsUtil.AelMetricsPrefix + ".kms.aws.generatedatakey." + regionToArnAndClient.Key
                    };
                    using (MetricsUtil.MetricsInstance.Measure.Timer.Time(generateDataKeyTimerOptions))
                    {
                        IAmazonKeyManagementService client          = ((AwsKmsArnClient)regionToArnAndClient.Value).AwsKmsClient;
                        string keyIdForDataKeyGeneration            = ((AwsKmsArnClient)regionToArnAndClient.Value).Arn;
                        GenerateDataKeyResult generateDataKeyResult = client.GenerateDataKey(
                            keyIdForDataKeyGeneration,
                            null,
                            DataKeySpec.AES_256);
                        dateKeyKeyId = keyIdForDataKeyGeneration;
                        return(generateDataKeyResult);
                    }
                }
                catch (AmazonServiceException e)
                {
                    Logger.LogWarning(e, "Failed to generate data key via region {region}, trying next region", regionToArnAndClient.Key);

                    // TODO Consider adding notification/CW alert
                }
            }

            throw new KeyManagementException("could not successfully generate data key using any regions");
        }
Example #7
0
        //--- Constructors ---

        /// <summary>
        /// Create new instance of <see cref="LambdaFunctionDependencyProvider"/>, which provides the implementation for the required dependencies for <see cref="ALambdaFunction"/>.
        /// </summary>
        /// <param name="utcNowCallback">A function that return the current <c>DateTime</c> in UTC timezone. Defaults to <see cref="DateTime.UtcNow"/> when <c>null</c>.</param>
        /// <param name="logCallback">An action that logs a string message. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="configSource">A <see cref="ILambdaConfigSource"/> instance from which the Lambda function configuration is read. Defaults to <see cref="LambdaSystemEnvironmentSource"/> instance when <c>null</c>.</param>
        /// <param name="jsonSerializer">A <see cref="ILambdaSerializer"/> instance for serializing and deserializing JSON data. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="kmsClient">A <see cref="IAmazonKeyManagementService"/> client instance. Defaults to <see cref="AmazonKeyManagementServiceClient"/> when <c>null</c>.</param>
        /// <param name="sqsClient">A <see cref="IAmazonSQS"/> client instance. Defaults to <see cref="AmazonSQSClient"/> when <c>null</c>.</param>
        /// <param name="eventsClient">A <see cref="IAmazonCloudWatchEvents"/> client instance. Defaults to <see cref="AmazonCloudWatchEventsClient"/> when <c>null</c>.</param>
        /// <param name="debugLoggingEnabled">A boolean indicating if debug logging is enabled.</param>
        public LambdaFunctionDependencyProvider(
            Func <DateTime> utcNowCallback        = null,
            Action <string> logCallback           = null,
            ILambdaConfigSource configSource      = null,
            ILambdaSerializer jsonSerializer      = null,
            IAmazonKeyManagementService kmsClient = null,
            IAmazonSQS sqsClient = null,
            IAmazonCloudWatchEvents eventsClient = null,
            bool?debugLoggingEnabled             = null
            )
        {
            _nowCallback   = utcNowCallback ?? (() => DateTime.UtcNow);
            _logCallback   = logCallback ?? LambdaLogger.Log;
            ConfigSource   = configSource ?? new LambdaSystemEnvironmentSource();
            JsonSerializer = jsonSerializer ?? new LambdaJsonSerializer();
            KmsClient      = kmsClient ?? new AmazonKeyManagementServiceClient();
            SqsClient      = sqsClient ?? new AmazonSQSClient();
            EventsClient   = eventsClient ?? new AmazonCloudWatchEventsClient();

            // determine if debug logging is enabled
            if (debugLoggingEnabled.HasValue)
            {
                _debugLoggingEnabled = debugLoggingEnabled.Value;
            }
            else
            {
                // read environment variable to determine if request/response messages should be serialized to the log for debugging purposes
                var value = System.Environment.GetEnvironmentVariable("DEBUG_LOGGING_ENABLED") ?? "false";
                _debugLoggingEnabled = value.Equals("true", StringComparison.OrdinalIgnoreCase);
            }
        }
Example #8
0
 public MigrationV1Fixture()
 {
     // Expectation that local SDK has been configured correctly, whether via VS Tools or user config files
     S3Client            = new AmazonS3Client(RegionEndpoint.EUWest1);
     KmsClient           = new AmazonKeyManagementServiceClient(RegionEndpoint.EUWest1);
     s3Cleanup           = new CleanupS3(S3Client);
     ensureDataPopulated = new AsyncLazy <bool>(RunMigrationProcess);
 }
 public static void UseAwsKeyManagementServiceSerializerWithMemoryCache(
     this IReceiveEndpointConfigurator configurator,
     string kmsKeyId, IAmazonKeyManagementService amazonKeyManagementService,
     IOptions <MemoryDistributedCacheOptions> options)
 {
     configurator.UseAwsKeyManagementServiceSerializerWithCache(kmsKeyId, amazonKeyManagementService,
                                                                new MemoryDistributedCache(options));
 }
 public static void UseAwsKeyManagementServiceSerializerWithMemoryCache(
     this IBusFactoryConfigurator configurator,
     string kmsKeyId, IAmazonKeyManagementService amazonKeyManagementService,
     IOptions <MemoryDistributedCacheOptions> options, IDistributedCacheEntryOptionsFactory distributedCacheEntryOptionsFactory)
 {
     configurator.UseAwsKeyManagementServiceSerializerWithCache(kmsKeyId, amazonKeyManagementService,
                                                                new MemoryDistributedCache(options), distributedCacheEntryOptionsFactory);
 }
Example #11
0
 public AwsKeyManagement(
     IAmazonKeyManagementService amazonKeyManagementService,
     string cmkPrefix,
     bool enableAutomaticKeyRotation)
 {
     mAmazonKeyManagementService = amazonKeyManagementService;
     mCmkPrefix = cmkPrefix;
     mEnableAutomaticKeyRotation = enableAutomaticKeyRotation;
 }
Example #12
0
 protected ALambdaFunction(LambdaFunctionConfiguration configuration)
 {
     _now       = configuration.UtcNow ?? (() => DateTime.UtcNow);
     _kmsClient = configuration.KmsClient ?? throw new ArgumentNullException(nameof(configuration.KmsClient));
     _snsClient = configuration.SnsClient ?? throw new ArgumentNullException(nameof(configuration.SnsClient));
     _sqsClient = configuration.SqsClient ?? throw new ArgumentNullException(nameof(configuration.SqsClient));
     _envSource = configuration.EnvironmentSource ?? throw new ArgumentNullException(nameof(configuration.EnvironmentSource));
     _started   = UtcNow;
 }
Example #13
0
 public EncryptionService(IAmazonKeyManagementService kmsService,
                          IApiKeyRepository apiKeyRepository,
                          IOptions <AwsConfig> options)
 {
     this.apiKeyRepository = apiKeyRepository;
     this.kmsService       = kmsService ?? throw new ArgumentNullException(nameof(kmsService));
     this.kmsMasterKeyId   = options?.Value?.KmsMasterKeyId ?? throw new ArgumentNullException("KmsMasterKeyId");
     this.encryptedDataKey = options?.Value?.EncryptedDataKey ?? throw new ArgumentNullException("EncryptedDataKey");
 }
Example #14
0
        public MasterKeyStorage(IAmazonKeyManagementService kmsClient)
        {
            if (kmsClient == null)
            {
                throw new ArgumentNullException("kmsClient");
            }

            _kmsClient = kmsClient;
        }
Example #15
0
 public AwsKeyManagement(
     IAmazonKeyManagementService amazonKeyManagementService,
     string cmkPrefix,
     bool enableAutomaticKeyRotation)
 {
     mAmazonKeyManagementService = amazonKeyManagementService;
     mCmkPrefix = string.IsNullOrEmpty(mCmkPrefix) ? "" : $"{mCmkPrefix}-";
     mEnableAutomaticKeyRotation = enableAutomaticKeyRotation;
 }
 /// <summary>
 /// Creates a <see cref="KmsXmlEncryptor"/> for encrypting ASP.NET keys with a KMS master key
 /// </summary>
 /// <param name="kmsClient">The KMS client</param>
 /// <param name="config">The configuration object specifying which key data in KMS to use</param>
 /// <param name="dpOptions">Main data protection options</param>
 /// <param name="logger">An optional <see cref="ILogger"/> to provide logging.</param>
 public KmsXmlEncryptor(IAmazonKeyManagementService kmsClient,
                        IOptions <KmsXmlEncryptorConfig> config,
                        IOptions <DataProtectionOptions> dpOptions,
                        ILogger <KmsXmlEncryptor> logger)
 {
     this.kmsClient = kmsClient ?? throw new ArgumentNullException(nameof(kmsClient));
     this.config    = config ?? throw new ArgumentNullException(nameof(config));
     this.dpOptions = dpOptions ?? throw new ArgumentNullException(nameof(dpOptions));
     this.logger    = logger;
 }
Example #17
0
        //--- Constructors ---

        /// <summary>
        /// Creates new instance of <see cref="LambdaQueueFunctionDependencyProvider"/>, which provides the implementation for the required dependencies for <see cref="ALambdaQueueFunction{TMessage}"/>.
        /// </summary>
        /// <param name="utcNowCallback">A function that return the current <c>DateTime</c> in UTC timezone. Defaults to <see cref="DateTime.UtcNow"/> when <c>null</c>.</param>
        /// <param name="logCallback">An action that logs a string message. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="configSource">A <see cref="ILambdaConfigSource"/> instance from which the Lambda function configuration is read. Defaults to <see cref="LambdaSystemEnvironmentSource"/> instance when <c>null</c>.</param>
        /// <param name="jsonSerializer">A <see cref="ILambdaSerializer"/> instance for serializing and deserializing JSON data. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="kmsClient">A <see cref="IAmazonKeyManagementService"/> client instance. Defaults to <see cref="AmazonKeyManagementServiceClient"/> when <c>null</c>.</param>
        /// <param name="sqsClient">A <see cref="IAmazonSQS"/> client instance. Defaults to <see cref="AmazonSQSClient"/> when <c>null</c>.</param>
        public LambdaQueueFunctionDependencyProvider(
            Func <DateTime> utcNowCallback        = null,
            Action <string> logCallback           = null,
            ILambdaConfigSource configSource      = null,
            ILambdaSerializer jsonSerializer      = null,
            IAmazonKeyManagementService kmsClient = null,
            IAmazonSQS sqsClient = null
            ) : base(utcNowCallback, logCallback, configSource, jsonSerializer, kmsClient, sqsClient)
        {
        }
Example #18
0
        protected virtual void Dispose(bool disposing)
        {
            if (disposing)
            {
                _client?.Dispose();
                _client = null;
            }

            _disposed = true;
        }
Example #19
0
        /// <summary>
        /// Initializes a new instance of the <see cref="AwsKmsKeyManager"/> class.
        /// </summary>
        /// <param name="regionSystemName">Name of the region system i.e. eu-west-1 or us-west-2.</param>
        /// <exception cref="System.ArgumentException">You must provide a Region System Name (i.e. eu-west-1 or us-west-2; see http://docs.aws.amazon.com/general/latest/gr/rande.html for the full list)</exception>
        public AwsKmsKeyManager(string regionSystemName)
        {
            if (String.IsNullOrWhiteSpace(regionSystemName))
            {
                throw new ArgumentException("You must provide a Region System Name (i.e. eu-west-1 or us-west-2; see http://docs.aws.amazon.com/general/latest/gr/rande.html for the full list)");
            }

            var regionEndpoint = RegionEndpoint.GetBySystemName(regionSystemName.ToLowerInvariant());

            _client = new AmazonKeyManagementServiceClient(regionEndpoint);
        }
Example #20
0
        public static void UseAwsKeyManagementServiceSerializer(this IBusFactoryConfigurator configurator,
                                                                IAmazonKeyManagementService amazonKeyManagementService,
                                                                IEncryptionContextBuilder encryptionContextBuilder,
                                                                string kmsKeyId)
        {
            var amazonKeyManagementServiceWrapper =
                new AmazonKeyManagementServiceWrapper(amazonKeyManagementService);

            configurator.UseAwsKeyManagementServiceSerializer(amazonKeyManagementServiceWrapper,
                                                              encryptionContextBuilder, kmsKeyId);
        }
Example #21
0
        public CredStashReaderBuilder WithKeyManagementServiceClient(IAmazonKeyManagementService kmsClient)
        {
            if (kmsClient == null)
            {
                throw new ArgumentNullException("kmsClient");
            }

            _keyManagementServiceClient = kmsClient;

            return(this);
        }
Example #22
0
 /// <summary>
 /// Dispose this instance
 /// </summary>
 /// <param name="disposing"></param>
 protected override void Dispose(bool disposing)
 {
     lock (kmsClientLock)
     {
         if (kmsClient != null)
         {
             kmsClient.Dispose();
             kmsClient = null;
         }
     }
     base.Dispose(disposing);
 }
Example #23
0
        /// <summary>
        /// Generates an instruction that will be used to encrypt an object
        /// using materials with the KMSKeyID set.
        /// </summary>
        /// <param name="kmsClient">
        /// Used to call KMS to generate a data key.
        /// </param>
        /// <param name="materials">
        /// The encryption materials to be used to encrypt and decrypt data.
        /// </param>
        /// <returns>
        /// The instruction that will be used to encrypt an object.
        /// </returns>
        internal static EncryptionInstructions GenerateInstructionsForKMSMaterials(IAmazonKeyManagementService kmsClient, EncryptionMaterials materials)
        {
            if (materials.KMSKeyID == null)
            {
                throw new ArgumentNullException(nameof(materials.KMSKeyID), KmsKeyIdNullMessage);
            }

            var iv = new byte[IVLength];

            // Generate IV, and get both the key and the encrypted key from KMS.
            RandomNumberGenerator.Create().GetBytes(iv);
            var generateDataKeyResult = kmsClient.GenerateDataKey(materials.KMSKeyID, materials.MaterialsDescription, KMSKeySpec);

            return(new EncryptionInstructions(materials.MaterialsDescription, generateDataKeyResult.KeyPlaintext, generateDataKeyResult.KeyCiphertext, iv,
                                              XAmzWrapAlgKmsValue, XAmzAesCbcPaddingCekAlgValue));
        }
Example #24
0
        //--- Constructors ---

        /// <summary>
        /// Create new instance of <see cref="LambdaFunctionDependencyProvider"/>, which provides the implementation for the required dependencies for <see cref="ALambdaFunction"/>.
        /// </summary>
        /// <param name="utcNowCallback">A function that return the current <c>DateTime</c> in UTC timezone. Defaults to <see cref="DateTime.UtcNow"/> when <c>null</c>.</param>
        /// <param name="logCallback">An action that logs a string message. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="configSource">A <see cref="ILambdaConfigSource"/> instance from which the Lambda function configuration is read. Defaults to <see cref="LambdaSystemEnvironmentSource"/> instance when <c>null</c>.</param>
        /// <param name="jsonSerializer">A <see cref="ILambdaSerializer"/> instance for serializing and deserializing JSON data. Defaults to <see cref="LambdaLogger.Log"/> when <c>null</c>.</param>
        /// <param name="kmsClient">A <see cref="IAmazonKeyManagementService"/> client instance. Defaults to <see cref="AmazonKeyManagementServiceClient"/> when <c>null</c>.</param>
        /// <param name="sqsClient">A <see cref="IAmazonSQS"/> client instance. Defaults to <see cref="AmazonSQSClient"/> when <c>null</c>.</param>
        public LambdaFunctionDependencyProvider(
            Func <DateTime> utcNowCallback        = null,
            Action <string> logCallback           = null,
            ILambdaConfigSource configSource      = null,
            ILambdaSerializer jsonSerializer      = null,
            IAmazonKeyManagementService kmsClient = null,
            IAmazonSQS sqsClient = null
            )
        {
            _nowCallback   = utcNowCallback ?? (() => DateTime.UtcNow);
            _logCallback   = logCallback ?? LambdaLogger.Log;
            ConfigSource   = configSource ?? new LambdaSystemEnvironmentSource();
            JsonSerializer = jsonSerializer ?? new JsonSerializer();
            KmsClient      = kmsClient ?? new AmazonKeyManagementServiceClient();
            SqsClient      = sqsClient ?? new AmazonSQSClient();
        }
        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);
        }
        internal virtual CryptoKey DecryptKmsEncryptedKey(
            IAmazonKeyManagementService awsKmsClient,
            byte[] cipherText,
            DateTimeOffset keyCreated,
            byte[] kmsKeyEncryptionKey,
            bool revoked)
        {
            byte[] plaintextBackingBytes = awsKmsClient.Decrypt(kmsKeyEncryptionKey, null);

            try
            {
                return(crypto.DecryptKey(cipherText, keyCreated, crypto.GenerateKeyFromBytes(plaintextBackingBytes), revoked));
            }
            finally
            {
                ManagedBufferUtils.WipeByteArray(plaintextBackingBytes);
            }
        }
        public void RoundTrip_Ok()
        {
            // Depends on client being configured in app.config or ambient environment.
            IAmazonKeyManagementService client = AWSClientFactory.CreateAmazonKeyManagementServiceClient();

            string          keyid  = ConfigurationManager.AppSettings["kmsKeyId"];
            ICryptoProvider crypto = new EnvelopeCryptoProvider(client, keyid);

            const string plaintext = "Peek-a-boo!";
            string       dataKey;
            string       ciphertext = crypto.Encrypt(out dataKey, plaintext);

            dataKey.Should().NotBeEmpty();
            ciphertext.Should().NotBe(plaintext);

            string decrypted = crypto.Decrypt(dataKey, ciphertext);

            decrypted.Should().Be("Peek-a-boo!");
        }
Example #28
0
        public ICredStashReader Build()
        {
            if (_dynamoDbClient == null)
            {
                _dynamoDbClient = new AmazonDynamoDBClient();
            }
            if (_keyManagementServiceClient == null)
            {
                _keyManagementServiceClient = new AmazonKeyManagementServiceClient();
            }
            if (_credStashConfig == null)
            {
                _credStashConfig = CredStashConfig.Default();
            }

            var credentialStorage = new CredentialStorage(_credStashConfig, _dynamoDbClient);
            var masterKeyStorage  = new MasterKeyStorage(_keyManagementServiceClient);

            return(new CredStashReader(credentialStorage, masterKeyStorage, new HmacSha256Verifier(), new AesCrypto()));
        }
Example #29
0
        public async Task DecryptShouldDecryptTheCiphertext(
            [Frozen, Substitute] IAmazonKeyManagementService kmsClient,
            [Target] DefaultDecryptionService service
            )
        {
            var value         = "ZW5jcnlwdGVkIHZhcmlhYmxlCg==";
            var expectedValue = "decrypted variable";

            kmsClient
            .DecryptAsync(Any <DecryptRequest>())
            .Returns(new DecryptResponse
            {
                Plaintext = await CreateStreamFromString(expectedValue),
            });

            var cancellationToken = new CancellationToken(false);
            var response          = await service.Decrypt(value);

            response.Should().BeEquivalentTo(expectedValue);
            await kmsClient.Received().DecryptAsync(Is <DecryptRequest>(req => req.CiphertextBlob != null), Is(cancellationToken));
        }
        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);
        }
		public KmsDataKeyProvider(IAmazonKeyManagementService keyManagementService, string keyId)
		{
			_client = keyManagementService;
			_keyId = keyId;
		}
		/// <param name="keyService">An Amazon KMS service client</param>
		/// <param name="keyId">The id or alias of the KMS master key to use</param>
		/// <param name="cacheSize">The number of decrypted keys to cache in RAM</param>
		public EnvelopeCryptoProvider(IAmazonKeyManagementService keyService, string keyId, int cacheSize)
			: this(new CachingDataKeyProvider(new KmsDataKeyProvider(keyService, keyId), cacheSize)) {}
		/// <param name="keyService">An Amazon KMS service client</param>
		/// <param name="keyId">The id or alias of the KMS master key to use</param>
		public EnvelopeCryptoProvider(IAmazonKeyManagementService keyService, string keyId)
			: this(new KmsDataKeyProvider(keyService, keyId)) {}