Ejemplo n.º 1
0
        internal GenerateDataKeyResponse GenerateDataKey(GenerateDataKeyRequest request)
        {
            var marshaller   = new GenerateDataKeyRequestMarshaller();
            var unmarshaller = GenerateDataKeyResponseUnmarshaller.Instance;

            return(Invoke <GenerateDataKeyRequest, GenerateDataKeyResponse>(request, marshaller, unmarshaller));
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Generates a data key for the specified master key. This will return both
        /// the plaintext key that you can use for encryption/decryption and the
        /// same key as protected by the master key.
        /// </summary>
        /// <param name="keyId">The identifier of the key we should use to generate and protect the data key.</param>
        /// <returns>Result containing the plaintext representation of the generated data key
        /// which can be used for encryption/decryption, an encrypted version of the
        /// data key encrypted by the master key and the ID of the key that was used.</returns>
        /// <exception cref="KeyManagementServiceUnavailableException"></exception>
        public GenerateDataKeyResult GenerateDataKey(string keyId)
        {
            if (_disposed)
            {
                throw new ObjectDisposedException("AwsKmsKeyManager");
            }

            ValidateMasterKey(keyId);

            var res = RetryPolicy.ExecuteAndCapture(() =>
            {
                var req = new GenerateDataKeyRequest
                {
                    KeyId   = keyId,
                    KeySpec = DataKeySpec.AES_128
                };

                var t = _client.GenerateDataKeyAsync(req);
                t.ConfigureAwait(false);
                return(t.GetAwaiter().GetResult());
            });

            ValidateResponse(res);

            var result = (GenerateDataKeyResponse)res.Result;

            return(new GenerateDataKeyResult
            {
                KeyId = keyId,
                CipherTextKey = result.CiphertextBlob.ToArray(),
                PlainTextKey = result.Plaintext.ToArray()
            });
        }
Ejemplo n.º 3
0
        public void GenerateKey(int keyBits, out byte[] key, out byte[] encryptedKey, IDictionary <string, string> context)
        {
            DataKeySpec keySpec;

            if (keyBits == 128)
            {
                keySpec = DataKeySpec.AES_128;
            }
            else if (keyBits == 256)
            {
                keySpec = DataKeySpec.AES_256;
            }
            else
            {
                throw new ArgumentException("only 128 and 256 bit keys are supported", "keyBits");
            }
            var request = new GenerateDataKeyRequest
            {
                KeyId             = _keyId,
                KeySpec           = keySpec,
                EncryptionContext = AsDictionary(context)
            };
            GenerateDataKeyResponse response = _client.GenerateDataKey(request);

            key          = response.Plaintext.ToArray();
            encryptedKey = response.CiphertextBlob.ToArray();
        }
Ejemplo n.º 4
0
        public void GenerateKey_Ok(int bits, string keySpec, bool throws)
        {
            var kmsClientMock = new Mock <IAmazonKeyManagementService>();
            var provider      = new KmsDataKeyProvider(kmsClientMock.Object, "myKey");

            GenerateDataKeyRequest requestSent = null;

            kmsClientMock.Setup(x => x.GenerateDataKey(It.IsAny <GenerateDataKeyRequest>()))
            .Returns((GenerateDataKeyRequest req) =>
            {
                requestSent = req;
                return(new GenerateDataKeyResponse
                {
                    CiphertextBlob = new MemoryStream(Bytes(1, 2, 3)),
                    Plaintext = new MemoryStream(Bytes(4, 5, 6)),
                });
            });

            byte[] key        = null, encryptedKey = null;
            Action invocation = provider.Invoking(p => p.GenerateKey(bits, out key, out encryptedKey));

            if (throws)
            {
                invocation.ShouldThrow <ArgumentException>();
            }
            else
            {
                invocation.ShouldNotThrow();
                key.Should().Equal(Bytes(4, 5, 6));
                encryptedKey.Should().Equal(Bytes(1, 2, 3));
                requestSent.KeyId.Should().Be("myKey");
                requestSent.KeySpec.ToString().Should().Be(keySpec);
                requestSent.EncryptionContext.Should().BeEmpty();
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initiates the asynchronous execution of the GenerateDataKey operation.
        /// </summary>
        ///
        /// <param name="request">Container for the necessary parameters to execute the GenerateDataKey operation.</param>
        /// <param name="cancellationToken">
        ///     A cancellation token that can be used by other objects or threads to receive notice of cancellation.
        /// </param>
        /// <returns>The task object representing the asynchronous operation.</returns>
        public Task <GenerateDataKeyResponse> GenerateDataKeyAsync(GenerateDataKeyRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken))
        {
            var marshaller   = new GenerateDataKeyRequestMarshaller();
            var unmarshaller = GenerateDataKeyResponseUnmarshaller.Instance;

            return(InvokeAsync <GenerateDataKeyRequest, GenerateDataKeyResponse>(request, marshaller,
                                                                                 unmarshaller, cancellationToken));
        }
Ejemplo n.º 6
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();
                        }
                    }
                }
        }
Ejemplo n.º 7
0
        public void X2()
        {
            var request = new GenerateDataKeyRequest {
                KeyId   = "1",
                KeySpec = KeySpec.AES_128
            };

            Assert.Equal(
                @"{
  ""KeyId"": ""1"",
  ""KeySpec"": ""AES_128""
}", JsonObject.FromObject(request).ToString());
        }
        public void B()
        {
            var request = new GenerateDataKeyRequest {
                KeyId   = "1",
                KeySpec = KeySpec.AES_128
            };

            Assert.Equal(
                @"{
  ""KeyId"": ""1"",
  ""KeySpec"": ""AES_128""
}", JsonSerializer.Serialize(request, JSO.Default));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// 本接口生成一个数据密钥,您可以用这个密钥进行本地数据的加密。
        /// </summary>
        /// <param name="req"><see cref="GenerateDataKeyRequest"/></param>
        /// <returns><see cref="GenerateDataKeyResponse"/></returns>
        public GenerateDataKeyResponse GenerateDataKeySync(GenerateDataKeyRequest req)
        {
            JsonResponseModel <GenerateDataKeyResponse> rsp = null;

            try
            {
                var strResp = this.InternalRequestSync(req, "GenerateDataKey");
                rsp = JsonConvert.DeserializeObject <JsonResponseModel <GenerateDataKeyResponse> >(strResp);
            }
            catch (JsonSerializationException e)
            {
                throw new TencentCloudSDKException(e.Message);
            }
            return(rsp.Response);
        }
Ejemplo n.º 10
0
        public void A()
        {
            var request = new GenerateDataKeyRequest {
                KeyId         = "1",
                KeySpec       = KeySpec.AES_128,
                NumberOfBytes = 128 // 128, 256, 512, and 1024
            };

            Assert.Equal(
                @"{
  ""KeyId"": ""1"",
  ""KeySpec"": ""AES_128"",
  ""NumberOfBytes"": 128
}", JsonSerializer.Serialize(request, JSO.Default).ToString());
        }
        private SecureString GetDataKeyFromKms(string application, string tenantId, string keyIdentifier)
        {
            using (var scope = new ProfileContext($"Generating new crypto key using kms for {application} {tenantId}"))
            {
                GenerateDataKeyRequest  request  = null;
                GenerateDataKeyResponse response = null;
                bool isSuccess = false;
                try
                {
                    var client = _kmsClientFactory.GetGlobalClient();
                    request = GetGenerateDataKeyRequest(application, tenantId, keyIdentifier);
                    var waitHandle = new ManualResetEvent(false);

                    Task.Factory.StartNew(async() =>
                    {
                        try
                        {
                            response = await client.GenerateDataKeyAsync(request);
                        }
                        catch (Exception ex)
                        {
                            Platform.Common.ExceptionPolicy.HandleException(ex, Constants.LogOnlyPolicy);
                            throw Errors.ServerSide.KMSCommunicationError();
                        }
                        finally
                        {
                            waitHandle.Set();
                        }
                    });
                    waitHandle.WaitOne();
                    if (response == null || response.HttpStatusCode != HttpStatusCode.OK)
                    {
                        throw Errors.ServerSide.KMSCommunicationError();
                    }

                    //CiperTextBlob is Base64-encoded binary data
                    _cryptoKeyStore.Add(application, tenantId, keyIdentifier, response.CiphertextBlob.ToArray());
                    isSuccess = true;
                    //PlaintText is Base64-encoded binary data
                    return(ConvertStreamToSecureString(response.Plaintext));
                }
                finally
                {
                    LogRQRS(request, SanitizedResponse(response), application, tenantId, "aws_kms_provider", "generate_datakey", isSuccess);
                }
            }
        }
Ejemplo n.º 12
0
        public void X()
        {
            // 128, 256, 512, and 1024

            var request = new GenerateDataKeyRequest {
                KeyId         = "1",
                KeySpec       = KeySpec.AES_128,
                NumberOfBytes = 128
            };

            Assert.Equal(
                @"{
  ""KeyId"": ""1"",
  ""KeySpec"": ""AES_128"",
  ""NumberOfBytes"": 128
}", JsonObject.FromObject(request).ToString());
        }
Ejemplo n.º 13
0
        public async Task <CryptoData> EncryptWithKey(string data)
        {
            var keyReq = new GenerateDataKeyRequest
            {
                KeyId   = this.keyId,
                KeySpec = DataKeySpec.AES_256
            };
            var dataKeyResponse = await client.GenerateDataKeyAsync(keyReq);

            var key          = GetBase64StringFromStream(dataKeyResponse.CiphertextBlob);
            var plainTextKey = GetBase64StringFromStream(dataKeyResponse.Plaintext);
            var protector    = dataProtectionProvider.CreateProtector(plainTextKey);
            var result       = protector.Protect(data);

            return(new CryptoData
            {
                Encrypted = result,
                Key = key
            });
        }
Ejemplo n.º 14
0
        public static async Task <byte[]> EncryptData(string toEncrypt, AccountCredentials credentials, string region, CancellationToken token = default)
        {
            try
            {
                var jsonMemStream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(toEncrypt ?? ""));
                var cmk           = credentials.cmk;
                var kmsClient     = new AmazonKeyManagementServiceClient(credentials.AWSCredentials, RegionEndpoint.GetBySystemName(region));
                kmsClient.ExceptionEvent += KmsClient_ExceptionEvent;

                var dataKeyRequest = new GenerateDataKeyRequest()
                {
                    KeyId   = cmk, //"alias/console-test1846939174-user1846939660"
                    KeySpec = DataKeySpec.AES_128
                };


                GenerateDataKeyResponse dataKeyResponse = kmsClient.GenerateDataKey(dataKeyRequest);

                var plaintextKey = await StreamToByteArray(dataKeyResponse.Plaintext);

                var encryptedKey = await StreamToByteArray(dataKeyResponse.CiphertextBlob);

                var key = encryptedKey;

                var encryptedResponse = await kmsClient.EncryptAsync(new EncryptRequest()
                {
                    KeyId     = cmk,
                    Plaintext = jsonMemStream,
                }, token);

                var dataBytes = await GetByteDataPackage(encryptedResponse, key);

                //var dataBytes = Encoding.ASCII.GetBytes(dataPack);
                return(dataBytes);
            }
            catch (Exception exc)  //took just over 15 seconds
            {
            }
            return(null);
        }
Ejemplo n.º 15
0
 /// <summary>
 ///  从KMS中获取一对数据密钥的明文/密文
 /// </summary>
 /// <param name="request">请求参数信息</param>
 /// <returns>请求结果信息</returns>
 public async Task <GenerateDataKeyResponse> GenerateDataKey(GenerateDataKeyRequest request)
 {
     return(await new GenerateDataKeyExecutor().Client(this).Execute <GenerateDataKeyResponse, GenerateDataKeyResult, GenerateDataKeyRequest>(request).ConfigureAwait(false));
 }
Ejemplo n.º 16
0
 /// <summary>
 ///  从KMS中获取一对数据密钥的明文/密文
 /// </summary>
 /// <param name="request">请求参数信息</param>
 /// <returns>请求结果信息</returns>
 public GenerateDataKeyResponse GenerateDataKey(GenerateDataKeyRequest request)
 {
     return(new GenerateDataKeyExecutor().Client(this).Execute <GenerateDataKeyResponse, GenerateDataKeyResult, GenerateDataKeyRequest>(request));
 }