Пример #1
0
        static void Main(string[] args)
        {
            // string accessKey = "AKIAJCRLXQX2J6OKN4GQ";
            // string seacretKey = "29XQBOyGZwkgXcW/4yylTdzWu2Hv95EyKq/lwmN0";
            // string keyID = "0022d1d9-f0c7-45e1-8f84-2b77c6fdcba9";
            // var kms = new AmazonKeyManagementServiceClient(accessKey, seacretKey, Amazon.RegionEndpoint.APNortheast1);
            // var encReq = new EncryptRequest();
            // encReq.KeyId = keyID;
            // encReq.Plaintext = new MemoryStream(Encoding.UTF8.GetBytes("19999-99999-46884-67157"));

            // var encrypt = kms.EncryptAsync(encReq);
            // System.Console.WriteLine(System.Convert.ToBase64String(encrypt.Result.CiphertextBlob.ToArray()));
            // var base64Str = System.Convert.ToBase64String(encrypt.Result.CiphertextBlob.ToArray());
            // var decReq = new DecryptRequest();
            // decReq.CiphertextBlob = new MemoryStream(System.Convert.FromBase64String(base64Str));
            // var decrypt = kms.DecryptAsync(decReq).Result;
            // System.Console.WriteLine(Encoding.UTF8.GetString(decrypt.Plaintext.ToArray()));

            string         accessKey      = "AKIAJCRLXQX2J6OKN4GQ";
            string         seacretKey     = "29XQBOyGZwkgXcW/4yylTdzWu2Hv95EyKq/lwmN0";
            string         keyID          = "0022d1d9-f0c7-45e1-8f84-2b77c6fdcba9";
            var            str            = "19185-57675-51957-67395";
            var            kmsc           = new AmazonKeyManagementServiceClient(accessKey, seacretKey, Amazon.RegionEndpoint.APNortheast1); //(アクセスキー、シークレットキー、リージョンよりクライアント作成)
            var            plaintext      = new MemoryStream(Encoding.UTF8.GetBytes(str));
            EncryptRequest encryptRequest = new EncryptRequest()                                                                             //(暗号化リクエストを作成)
            {
                KeyId     = keyID,                                                                                                           //(頂いたKeyId を代入 "0022d1d9-f0c7-45e1-8f84-2b77c6fdcba9")
                Plaintext = plaintext
            };
            var ciphertext = kmsc.EncryptAsync(encryptRequest).Result.CiphertextBlob; //(kmsc は上記クライアント)

            System.Console.WriteLine(Convert.ToBase64String(ciphertext.ToArray()));
        }
Пример #2
0
        // snippet-start:[KMS.dotnetv3.CreateGrantExample]
        public static async Task Main()
        {
            var client = new AmazonKeyManagementServiceClient();

            // The identity that is given permission to perform the operations
            // specified in the grant.
            var grantee = "arn:aws:iam::111122223333:role/ExampleRole";

            // The identifier of the AWS KMS key to which the grant applies. You
            // can use the key ID or the Amazon Resource Name (ARN) of the KMS key.
            var keyId = "7c9eccc2-38cb-4c4f-9db3-766ee8dd3ad4";

            var request = new CreateGrantRequest
            {
                GranteePrincipal = grantee,
                KeyId            = keyId,

                // A list of operations that the grant allows.
                Operations = new List <string>
                {
                    "Encrypt",
                    "Decrypt",
                },
            };

            var response = await client.CreateGrantAsync(request);

            string grantId    = response.GrantId;    // The unique identifier of the grant.
            string grantToken = response.GrantToken; // The grant token.

            Console.WriteLine($"Id: {grantId}, Token: {grantToken}");
        }
        /// <summary>
        /// Used to Decrypt any records that are Encrypted in AWS
        /// </summary>
        /// <param name="envVarName">The Enviroment Variable Name</param>
        /// <returns></returns>
        private static async Task <string> DecodeEnvVar(string envVarName)
        {
            // Retrieve env var text
            var encryptedBase64Text = Environment.GetEnvironmentVariable(envVarName);
            // Convert base64-encoded text to bytes
            var encryptedBytes = Convert.FromBase64String(encryptedBase64Text);
            // Set up encryption context
            var encryptionContext = new Dictionary <string, string>();

            encryptionContext.Add("LambdaFunctionName",
                                  Environment.GetEnvironmentVariable("AWS_LAMBDA_FUNCTION_NAME"));
            // Construct client
            using (var client = new AmazonKeyManagementServiceClient(RegionEndpoint.GetBySystemName("us-east-2")))
            {
                // Construct request
                var decryptRequest = new DecryptRequest
                {
                    CiphertextBlob    = new MemoryStream(encryptedBytes),
                    EncryptionContext = encryptionContext,
                };
                // Call KMS to decrypt data
                var response = await client.DecryptAsync(decryptRequest);

                using (var plaintextStream = response.Plaintext)
                {
                    // Get decrypted bytes
                    var plaintextBytes = plaintextStream.ToArray();
                    // Convert decrypted bytes to ASCII text
                    var plaintext = Encoding.UTF8.GetString(plaintextBytes);
                    return(plaintext);
                }
            }
        }
Пример #4
0
        static string GetKeyByAlias(string alias, AmazonKeyManagementServiceClient client)
        {
            //how does it know what credentials to use? - it first looks at app.config or webconfig,
            // then the profile in the SDK Store, then the local credentials file
            //then the environment variables AWS_ACCESS_KEY_ID & AWS_SECRET_KEY,
            // then finally it will look at the instance profile on an EC2 instance

            //since this is a demo / local we are going to use the default profile in the SDK store,
            // for production we would use the local store on the EC2 instance
            //this should be transparent and allow for definition by environment


            var aliasResponse = client.ListAliasesAsync(new ListAliasesRequest()
            {
                Limit = 1000
            }).GetAwaiter().GetResult();

            if (aliasResponse == null || aliasResponse.Aliases == null)
            {
                return(null);
            }

            var foundAlias = aliasResponse.Aliases.Where(r => r.AliasName == "alias/" + alias).FirstOrDefault();

            if (foundAlias != null)
            {
                return(foundAlias.TargetKeyId);
                //    var keyData = client.DescribeKeyAsync(keyID).GetAwaiter().GetResult();
                //    return keyData?;
                //
            }

            return(null);
        }
Пример #5
0
        public async Task <string> GetKeyAsync(string keyName)
        {
            try
            {
                var kmsClient = new AmazonKeyManagementServiceClient(_credentials, _region);

                var response = await kmsClient.ListAliasesAsync(new ListAliasesRequest
                {
                    Limit = 1000
                });

                var keyList = response.Aliases;

                var foundAlias = keyList.FirstOrDefault(r => r.AliasName == "alias/" + keyName);
                if (foundAlias != null)
                {
                    return(foundAlias.TargetKeyId);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
            return(string.Empty);
        }
Пример #6
0
        public static async Task Main()
        {
            // Note that if you need to create a Key in an AWS Region
            // other than the region defined for the default user, you need to
            // pass the region to the client constructor.
            var client = new AmazonKeyManagementServiceClient();

            // The call to CreateKeyAsync will create a symmetrical AWS KMS
            // key. For more information about symmetrical and asymmetrical
            // keys, see:
            //
            // https://docs.aws.amazon.com/kms/latest/developerguide/symm-asymm-choose.html
            var response = await client.CreateKeyAsync(new CreateKeyRequest());

            // The KeyMetadata object contains information about the new AWS KMS key.
            KeyMetadata keyMetadata = response.KeyMetadata;

            if (keyMetadata is not null)
            {
                Console.WriteLine($"KMS Key: {keyMetadata.KeyId} was successfully created.");
            }
            else
            {
                Console.WriteLine("Could not create KMS Key.");
            }
        }
Пример #7
0
        public EncryptionTests()
        {
            using (var kmsClient = new AmazonKeyManagementServiceClient())
            {
                var response = CallAsyncTask(
                    kmsClient.CreateKeyAsync(new CreateKeyRequest
                {
                    Description = "Key for .NET integration tests.",
                    Origin      = OriginType.AWS_KMS,
                    KeyUsage    = KeyUsageType.ENCRYPT_DECRYPT
                }));
                kmsKeyID = response.KeyMetadata.KeyId;
            }

            var encryptionMaterials    = new EncryptionMaterials(RSA.Create());
            var kmsEncryptionMaterials = new EncryptionMaterials(kmsKeyID);

            AmazonS3CryptoConfiguration config = new AmazonS3CryptoConfiguration()
            {
                StorageMode = CryptoStorageMode.InstructionFile
            };

            s3EncryptionClientMetadataMode    = new AmazonS3EncryptionClient(encryptionMaterials);
            s3EncryptionClientFileMode        = new AmazonS3EncryptionClient(config, encryptionMaterials);
            s3EncryptionClientMetadataModeKMS = new AmazonS3EncryptionClient(kmsEncryptionMaterials);
            s3EncryptionClientFileModeKMS     = new AmazonS3EncryptionClient(config, kmsEncryptionMaterials);

            using (StreamWriter writer = File.CreateText(filePath))
            {
                writer.Write(sampleContent);
            }
            bucketName = CallAsyncTask(UtilityMethods.CreateBucketAsync(s3EncryptionClientFileMode, GetType().Name));
        }
Пример #8
0
        public override void Invoke(AWSCredentials creds, RegionEndpoint region, int maxItems)
        {
            AmazonKeyManagementServiceConfig config = new AmazonKeyManagementServiceConfig();

            config.RegionEndpoint = region;
            ConfigureClient(config);
            AmazonKeyManagementServiceClient client = new AmazonKeyManagementServiceClient(creds, config);

            ListAliasesResponse resp = new ListAliasesResponse();

            do
            {
                ListAliasesRequest req = new ListAliasesRequest
                {
                    Marker = resp.NextMarker
                    ,
                    Limit = maxItems
                };

                resp = client.ListAliases(req);
                CheckError(resp.HttpStatusCode, "200");

                foreach (var obj in resp.Aliases)
                {
                    AddObject(obj);
                }
            }while (!string.IsNullOrEmpty(resp.NextMarker));
        }
Пример #9
0
        internal bool Encrypt(FileStream inputStream, out MemoryStream encStream)
        {
            bool isSuccess = false;

            var memoryStream = new MemoryStream();

            inputStream.CopyTo(memoryStream);

            var kmsClient = new AmazonKeyManagementServiceClient(this.awsCredentials, this.region);

            var encRequest = new EncryptRequest
            {
                KeyId = "Have to Insert KeyArn.."
                ,
                Plaintext = memoryStream
            };

            var encResponse = kmsClient.Encrypt(encRequest);

            if (encResponse.HttpStatusCode != System.Net.HttpStatusCode.OK)
            {
                isSuccess = true;
            }
            encStream = encResponse.CiphertextBlob;
            return(isSuccess);
        }
Пример #10
0
        private static async Task <string> DecodeEnvVarAsync(string envVarName)
        {
            // retrieve env var text
            var encryptedBase64Text = Environment.GetEnvironmentVariable(envVarName);
            // convert base64-encoded text to bytes
            var encryptedBytes = Convert.FromBase64String(encryptedBase64Text);

            // construct client
            using (var client = new AmazonKeyManagementServiceClient())
            {
                // construct request
                var decryptRequest = new DecryptRequest
                {
                    CiphertextBlob = new MemoryStream(encryptedBytes),
                };
                // call KMS to decrypt data
                var response = await client.DecryptAsync(decryptRequest);

                using (var plaintextStream = response.Plaintext)
                {
                    // get decrypted bytes
                    var plaintextBytes = plaintextStream.ToArray();
                    // convert decrypted bytes to ASCII text
                    var plaintext = Encoding.UTF8.GetString(plaintextBytes);
                    return(plaintext);
                }
            }
        }
Пример #11
0
        public async Task Run()
        {
            var awsCredentials = new BasicAWSCredentials(AwsAccessKeyId, AwsSecretAccessKey);
            var kmsClient      = new AmazonKeyManagementServiceClient(awsCredentials, s_awsKmsRegion);
            var encryptedKey   = Convert.FromBase64String(AwsKmsEncryptedKeyBase64);
            var decryptRequest = new DecryptRequest
            {
                KeyId          = AwsKmsMasterKeyIdArn,
                CiphertextBlob = new MemoryStream(encryptedKey)
            };
            var decryptResponse = await kmsClient.DecryptAsync(decryptRequest).ConfigureAwait(false);

            var secretKey   = new EncryptionKey(1, decryptResponse.Plaintext.ToArray());
            var secretsData = new SecretsData(new List <Secret> {
                secretKey
            }, secretKey);
            var config = new StorageConfig(EnvironmentId,
                                           clientId: ClientId,
                                           clientSecret: ClientSecret,
                                           secretKeyAccessor: () => secretsData);

            using var storage = Storage.NewStorage(config);
            var record = new Record("Record key AWS KMS example",
                                    "Test AWS KMS keys in C# SDK",
                                    key1: "<key1>",
                                    key2: "<key2>",
                                    key3: "<key3>",
                                    key10: "<key10>",
                                    profileKey: "<profile_key>",
                                    rangeKey1: 125L);
            const string country       = "US";
            var          writtenRecord = await storage.WriteAsync(country, record).ConfigureAwait(false);

            await storage.DeleteAsync(country, writtenRecord.RecordKey).ConfigureAwait(false);
        }
Пример #12
0
        public static async Task Main()
        {
            var client = new AmazonKeyManagementServiceClient();

            // The alias name must start with alias/ and can be
            // up to 256 alphanumeric characters long.
            var aliasName = "alias/ExampleAlias";

            // The value supplied as the TargetKeyId can be either
            // the key ID or key Amazon Resource Name (ARN) of the
            // AWS KMS key.
            var keyId = "1234abcd-12ab-34cd-56ef-1234567890ab";

            var request = new CreateAliasRequest
            {
                AliasName   = aliasName,
                TargetKeyId = keyId,
            };

            var response = await client.CreateAliasAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                Console.WriteLine($"Alias, {aliasName}, successfully created.");
            }
            else
            {
                Console.WriteLine($"Could not create alias.");
            }
        }
Пример #13
0
        public void Initialize()
        {
            kmsClient = new AmazonKeyManagementServiceClient(RegionEndpoint.USEast1);
            s3Client  = new AmazonS3Client(RegionEndpoint.USEast1);

            // Create a bucket to store objects related to this test.
            bucketName = GetOrCreateBucket(s3Client);
            // Create a KMS key, and an S3 object with the KMSKeyID.
            kmsKeyID = GetOrCreateKMSKey(s3Client, kmsClient, bucketName);
            // Create an S3 object with a symmetric key used for testing.
            symmetricAlgorithm = GetOrCreateSymmetricAlgorithm(s3Client, bucketName);

            var encryptionMaterials    = new EncryptionMaterials(symmetricAlgorithm);
            var kmsEncryptionMaterials = new EncryptionMaterials(kmsKeyID);

            AmazonS3CryptoConfiguration config = new AmazonS3CryptoConfiguration()
            {
                StorageMode = CryptoStorageMode.InstructionFile
            };

            s3EncryptionClientMetadataMode = new AmazonS3EncryptionClient(encryptionMaterials);
            RetryUtilities.ForceConfigureClient(s3EncryptionClientMetadataMode);

            s3EncryptionClientFileMode = new AmazonS3EncryptionClient(config, encryptionMaterials);
            RetryUtilities.ForceConfigureClient(s3EncryptionClientFileMode);

            s3EncryptionClientMetadataModeKMS = new AmazonS3EncryptionClient(kmsEncryptionMaterials);
            RetryUtilities.ForceConfigureClient(s3EncryptionClientMetadataModeKMS);

            s3EncryptionClientFileModeKMS = new AmazonS3EncryptionClient(config, kmsEncryptionMaterials);
            RetryUtilities.ForceConfigureClient(s3EncryptionClientFileModeKMS);
        }
Пример #14
0
        public static async Task Main()
        {
            // The identifier of the AWS KMS key to disable. You can use the
            // key Id or the Amazon Resource Name (ARN) of the AWS KMS key.
            var keyId   = "1234abcd-12ab-34cd-56ef-1234567890ab";
            var client  = new AmazonKeyManagementServiceClient();
            var request = new ListGrantsRequest
            {
                KeyId = keyId,
            };

            var response = new ListGrantsResponse();

            do
            {
                response = await client.ListGrantsAsync(request);

                response.Grants.ForEach(grant =>
                {
                    Console.WriteLine($"{grant.GrantId}");
                });

                request.Marker = response.NextMarker;
            }while (response.Truncated);
        }
Пример #15
0
        public static async Task Main()
        {
            var client = new AmazonKeyManagementServiceClient();

            // The identifier of the AWS KMS key to disable. You can use the
            // key Id or the Amazon Resource Name (ARN) of the AWS KMS key.
            var keyId = "1234abcd-12ab-34cd-56ef-1234567890ab";

            var request = new DisableKeyRequest
            {
                KeyId = keyId,
            };

            var response = await client.DisableKeyAsync(request);

            if (response.HttpStatusCode == System.Net.HttpStatusCode.OK)
            {
                // Retrieve information about the key to show that it has now
                // been disabled.
                var describeResponse = await client.DescribeKeyAsync(new DescribeKeyRequest
                {
                    KeyId = keyId,
                });

                Console.WriteLine($"{describeResponse.KeyMetadata.KeyId} - state: {describeResponse.KeyMetadata.KeyState}");
            }
        }
Пример #16
0
        public AwsKmsSignature(string keyId, Func <List <string>, string> selector)
        {
            this.keyId = keyId;
            using (var kmsClient = new AmazonKeyManagementServiceClient())
            {
                GetPublicKeyRequest getPublicKeyRequest = new GetPublicKeyRequest()
                {
                    KeyId = keyId
                };
                GetPublicKeyResponse getPublicKeyResponse = kmsClient.GetPublicKeyAsync(getPublicKeyRequest).Result;
                List <string>        signingAlgorithms    = getPublicKeyResponse.SigningAlgorithms;
                signingAlgorithm = selector.Invoke(signingAlgorithms);
                switch (signingAlgorithm)
                {
                case "ECDSA_SHA_256":
                case "ECDSA_SHA_384":
                case "ECDSA_SHA_512":
                case "RSASSA_PKCS1_V1_5_SHA_256":
                case "RSASSA_PKCS1_V1_5_SHA_384":
                case "RSASSA_PKCS1_V1_5_SHA_512":
                    break;

                case "RSASSA_PSS_SHA_256":
                case "RSASSA_PSS_SHA_384":
                case "RSASSA_PSS_SHA_512":
                    throw new ArgumentException(String.Format("Signing algorithm {0} not supported directly by iText", signingAlgorithm));

                default:
                    throw new ArgumentException(String.Format("Unknown signing algorithm: {0}", signingAlgorithm));
                }
            }
        }
        public static void UseAwsKeyManagementServiceSerializerWithCache(this IReceiveEndpointConfigurator configurator,
                                                                         RegionEndpoint region, string kmsKeyId, IDistributedCache distributedCache)
        {
            var amazonKeyManagementServiceClient = new AmazonKeyManagementServiceClient(region);

            configurator.UseAwsKeyManagementServiceSerializerWithCache(
                kmsKeyId, amazonKeyManagementServiceClient, distributedCache);
        }
 public KmsSecretManagementService(
     AmazonKeyManagementServiceClient kmsClient,
     ILogger <KmsSecretManagementService> logger)
 {
     _kmsClient = kmsClient;
     _logger    = logger;
     _logger.LogDebug("KMS secret management service built");
 }
        public static void UseAwsKeyManagementServiceSerializerWithCache(this IBusFactoryConfigurator configurator,
                                                                         string kmsKeyId, IDistributedCache distributedCache)
        {
            var amazonKeyManagementServiceClient = new AmazonKeyManagementServiceClient();

            configurator.UseAwsKeyManagementServiceSerializerWithCache(
                kmsKeyId, amazonKeyManagementServiceClient, distributedCache);
        }
Пример #20
0
        static void UploadManualEncrypt(string filePath)
        {
            string kmsKeyID  = "";
            var    objectKey = System.IO.Path.GetFileName(filePath);

            using (var aes = Aes.Create())
                using (var kmsClient = new AmazonKeyManagementServiceClient(defaultEndpoint))
                {
                    //Get the key from KMS
                    kmsKeyID = GetKeyByAlias(keyName, kmsClient);
                    //Generate a data key for the specific object
                    var dataKeyRequest = new GenerateDataKeyRequest();
                    dataKeyRequest.KeyId   = kmsKeyID;
                    dataKeyRequest.KeySpec = DataKeySpec.AES_256;
                    //Set the encryption context for your AAD
                    dataKeyRequest.EncryptionContext["MyContext"] = myContext;
                    var dataKeyResponse = kmsClient.GenerateDataKeyAsync(dataKeyRequest).GetAwaiter().GetResult();

                    var    fileData = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                    Stream output   = new MemoryStream();
                    //Write the length of the encrypted key first so we can retrieve it later
                    output.WriteByte((byte)dataKeyResponse?.CiphertextBlob?.Length);
                    //Write the encrypted key to next
                    dataKeyResponse.CiphertextBlob.CopyTo(output);
                    aes.Key = dataKeyResponse.Plaintext.ToArray();
                    //Then write the IV, since IV is fixed length we don't have to worry about storing the IV length
                    output.Write(aes.IV, 0, aes.IV.Length);
                    using (var cs = new CryptoStream(output, aes.CreateEncryptor(), CryptoStreamMode.Write))
                    {
                        //Now encrypt the file data into the stream
                        fileData.CopyTo(cs);
                        cs.FlushFinalBlock();


                        using (var s3client = new AmazonS3Client(defaultEndpoint))
                        {
                            var putRequest = new PutObjectRequest
                            {
                                BucketName  = bucketName,
                                Key         = objectKey,
                                InputStream = output
                            };


                            //All of this metadata is optional, you do not have to include any of this
                            //I am just putting it here if you want to store it in the metadata along with the object
                            //The encrypted data key and IV are already stored with the file, you will need a way to look up the context and keyid
                            putRequest.Metadata.Add("x-amz-meta-client-side-encryption-context", myContext);
                            putRequest.Metadata.Add("x-amz-meta-client-side-encryption-aws-kms-key-id", kmsKeyID);
                            putRequest.Metadata.Add("x-amz-meta-cipherblob", Convert.ToBase64String(dataKeyResponse.CiphertextBlob.ToArray()));
                            putRequest.Metadata.Add("x-amz-meta-x-amz-iv", Convert.ToBase64String(aes.IV));


                            s3client.PutObjectAsync(putRequest).GetAwaiter().GetResult();
                        }
                    }
                }
        }
        public static void UseAwsKeyManagementServiceSerializerWithMemoryCache(
            this IReceiveEndpointConfigurator configurator,
            RegionEndpoint region, string kmsKeyId, IOptions <MemoryDistributedCacheOptions> options)
        {
            var amazonKeyManagementServiceClient = new AmazonKeyManagementServiceClient(region);

            configurator.UseAwsKeyManagementServiceSerializerWithMemoryCache(kmsKeyId, amazonKeyManagementServiceClient,
                                                                             options);
        }
        public static void UseAwsKeyManagementServiceSerializerWithMemoryCache(
            this IBusFactoryConfigurator configurator,
            string kmsKeyId, IOptions <MemoryDistributedCacheOptions> options)
        {
            var amazonKeyManagementServiceClient = new AmazonKeyManagementServiceClient();

            configurator.UseAwsKeyManagementServiceSerializerWithMemoryCache(kmsKeyId, amazonKeyManagementServiceClient,
                                                                             options);
        }
Пример #23
0
        static async Task <CreateKeyResponse> MyCreateKeyAsync(string regionName)
        {
            RegionEndpoint region = RegionEndpoint.GetBySystemName(regionName);

            AmazonKeyManagementServiceClient kmsClient = new AmazonKeyManagementServiceClient(region);

            CreateKeyResponse response = await kmsClient.CreateKeyAsync(new CreateKeyRequest());

            return(response);
        }
Пример #24
0
        public void KeyManagementServiceDecrypt()
        {
            #region to-decrypt-data-1478281622886

            var client   = new AmazonKeyManagementServiceClient();
            var response = client.Decrypt(new DecryptRequest
            {
                CiphertextBlob = new MemoryStream(< binary data >),                                            // The encrypted data (ciphertext).
                KeyId          = "arn:aws:kms:us-west-2:111122223333:key/1234abcd-12ab-34cd-56ef-1234567890ab" // A key identifier for the KMS key to use to decrypt the data.
            });
Пример #25
0
        static void DownloadManualEncrypt(string filePath)
        {
            string objectKey = System.IO.Path.GetFileName(filePath);

            using (var s3c = new AmazonS3Client(defaultEndpoint))
                using (var aes = Aes.Create())
                    using (var kmsClient = new AmazonKeyManagementServiceClient(defaultEndpoint))
                    {
                        //Get the encrypted file
                        var getRequest = new GetObjectRequest();
                        getRequest.BucketName = bucketName;
                        getRequest.Key        = objectKey;
                        var s3Response = s3c.GetObjectAsync(getRequest).GetAwaiter().GetResult();


                        using (var algorithm = Aes.Create())
                        {
                            //Get the length of the encrypted key
                            var length = s3Response.ResponseStream.ReadByte();
                            //read in the encrypted key
                            var buffer = new byte[length];
                            s3Response.ResponseStream.Read(buffer, 0, length);

                            DecryptRequest decryptRequest = new DecryptRequest()
                            {
                                CiphertextBlob = new MemoryStream(buffer),
                            };
                            //All you need to supply is the context
                            decryptRequest.EncryptionContext["MyContext"] = myContext;

                            var decryptedData = kmsClient.DecryptAsync(decryptRequest).GetAwaiter().GetResult();
                            algorithm.Key = decryptedData.Plaintext.ToArray();
                            var iv = algorithm.IV;
                            //The IV is inbedded into the file when uploaded
                            s3Response.ResponseStream.Read(iv, 0, iv.Length);
                            algorithm.IV = iv;
                            string outputPath = System.IO.Path.Combine(System.IO.Path.GetDirectoryName(filePath), System.IO.Path.GetFileNameWithoutExtension(filePath) + "_" + new Random().Next(0, 1000).ToString() + System.IO.Path.GetExtension(filePath));

                            //decrypt and write to a local file
                            using (var cryptoStream = new CryptoStream(s3Response.ResponseStream,
                                                                       algorithm.CreateDecryptor(), CryptoStreamMode.Read))
                            {
                                using (var fileStream = new FileStream(outputPath, FileMode.Create, FileAccess.Write))
                                {
                                    cryptoStream.CopyTo(fileStream);
                                    fileStream.Flush();
                                    fileStream.Close();
                                }
                            }

                            Console.WriteLine($"Wrote file to {outputPath}");
                        }
                    }
        }
Пример #26
0
        public async Task <string> EncryptAsync(string keyId, string text)
        {
            var kmsClient = new AmazonKeyManagementServiceClient();
            var response  = await kmsClient.EncryptAsync(new EncryptRequest {
                KeyId             = keyId,
                Plaintext         = new MemoryStream(Encoding.UTF8.GetBytes(text)),
                EncryptionContext = null
            });

            return(Convert.ToBase64String(response.CiphertextBlob.ToArray()));
        }
Пример #27
0
        public static IConfigurationSourceConfigurator AddCredstash(this IConfigurationConfigurator configuration, Amazon.RegionEndpoint region)
        {
            var credstashOptions = new CredstashOptions()
            {
                Region = region
            };

            var amazonKeyManagementServiceClient = new AmazonKeyManagementServiceClient(region);
            var amazonDynamoDbClient             = new AmazonDynamoDBClient(region);

            return(AddCredstash(configuration, credstashOptions, amazonKeyManagementServiceClient, amazonDynamoDbClient));
        }
Пример #28
0
        private async Task <byte[]> DecryptSessionKey(byte[] encryptedSessionKey)
        {
            using AmazonKeyManagementServiceClient kmsClient = new AmazonKeyManagementServiceClient();
            DecryptRequest aesKeyDecryptionRequest = new DecryptRequest
            {
                EncryptionAlgorithm = EncryptionAlgorithmSpec.RSAES_OAEP_SHA_1,
                CiphertextBlob      = new MemoryStream(encryptedSessionKey),
                KeyId = this.keyId
            };
            DecryptResponse decryptionResponse = await kmsClient.DecryptAsync(aesKeyDecryptionRequest);

            return(decryptionResponse.Plaintext.ToArray());
        }
Пример #29
0
        public void KeyManagementServiceCreateKey()
        {
            #region to-create-a-cmk-1478028992966

            var client   = new AmazonKeyManagementServiceClient();
            var response = client.CreateKey(new CreateKeyRequest
            {
            });

            KeyMetadata keyMetadata = response.KeyMetadata; // Detailed information about the KMS key that this operation creates.

            #endregion
        }
Пример #30
0
        public AwsKeyManagementTests()
        {
            mConfiguration = new ConfigurationBuilder()
                             .AddJsonFile("settings.json")
                             .AddEnvironmentVariables().Build();

            var awsKey    = mConfiguration.GetValue <string>("KeyManagement:AwsKms:Key");
            var awsSecret = mConfiguration.GetValue <string>("KeyManagement:AwsKms:Secret");

            var kmsService = new AmazonKeyManagementServiceClient(awsKey, awsSecret, RegionEndpoint.USEast1);

            mAwsKeyManagement = new AwsKeyManagement(kmsService, new SymmetricKeyManagement());
        }