public async Task <Result <DecryptResponse> > Decrypt(DecryptRequest request) { const string api = "api/Document/Decrypt"; var result = await _owner.PostAsync <DecryptRequest, DecryptResponse>(api, request); return(result); }
public override DecryptResponse Decrypt(DecryptRequest request, CallSettings callSettings = null) { DecryptCalls++; return(new DecryptResponse { Plaintext = request.Ciphertext }); }
/// <summary> /// Decrypts data using the given [DecryptDataDetails](https://docs.cloud.oracle.com/api/#/en/key/latest/datatypes/DecryptDataDetails) resource. /// /// </summary> /// <param name="request">The request object containing the details to send. Required.</param> /// <param name="retryConfiguration">The retry configuration that will be used by to send this request. Optional.</param> /// <param name="cancellationToken">The cancellation token to cancel this operation. Optional.</param> /// <returns>A response object containing details about the completed operation</returns> /// <example>Click <a href="https://docs.cloud.oracle.com/en-us/iaas/tools/dot-net-examples/latest/keymanagement/Decrypt.cs.html">here</a> to see an example of how to use Decrypt API.</example> public async Task <DecryptResponse> Decrypt(DecryptRequest request, RetryConfiguration retryConfiguration = null, CancellationToken cancellationToken = default) { logger.Trace("Called decrypt"); Uri uri = new Uri(this.restClient.GetEndpoint(), System.IO.Path.Combine(basePathWithoutHost, "/20180608/decrypt".Trim('/'))); HttpMethod method = new HttpMethod("POST"); HttpRequestMessage requestMessage = Converter.ToHttpRequestMessage(uri, method, request); requestMessage.Headers.Add("Accept", "application/json"); GenericRetrier retryingClient = Retrier.GetPreferredRetrier(retryConfiguration, this.retryConfiguration); HttpResponseMessage responseMessage; try { if (retryingClient != null) { responseMessage = await retryingClient.MakeRetryingCall(this.restClient.HttpSend, requestMessage, cancellationToken).ConfigureAwait(false); } else { responseMessage = await this.restClient.HttpSend(requestMessage).ConfigureAwait(false); } this.restClient.CheckHttpResponseMessage(requestMessage, responseMessage); return(Converter.FromHttpResponseMessage <DecryptResponse>(responseMessage)); } catch (Exception e) { logger.Error($"Decrypt failed with error: {e.Message}"); throw; } }
internal DecryptResponse Decrypt(DecryptRequest request) { var marshaller = new DecryptRequestMarshaller(); var unmarshaller = DecryptResponseUnmarshaller.Instance; return(Invoke <DecryptRequest, DecryptResponse>(request, marshaller, unmarshaller)); }
public void DecryptKey_Ok() { var kmsClientMock = new Mock <IAmazonKeyManagementService>(); var provider = new KmsDataKeyProvider(kmsClientMock.Object, "myKey"); DecryptRequest sentRequest = null; kmsClientMock.Setup(x => x.Decrypt(It.IsAny <DecryptRequest>())) .Returns((DecryptRequest req) => { sentRequest = req; return(new DecryptResponse { Plaintext = DoubleValues(req.CiphertextBlob) }); }); var context = new Dictionary <string, string> { { "purpose", "doubling" } }; provider.DecryptKey(Bytes(1, 2, 3)).Should().Equal(Bytes(2, 4, 6)); sentRequest.CiphertextBlob.ToArray().Should().Equal(Bytes(1, 2, 3)); sentRequest.EncryptionContext.Should().BeEmpty(); provider.DecryptKey(Bytes(2, 3, 4)).Should().Equal(Bytes(4, 6, 8)); }
public async Task <string> DecryptValueAsync(string encryptedValue) { try { var ciphertestStream = new MemoryStream(Convert.FromBase64String(encryptedValue)) { Position = 0 }; var decryptRequest = new DecryptRequest { CiphertextBlob = ciphertestStream }; var response = await DecryptAsync(decryptRequest); var buffer = new byte[response.Plaintext.Length]; var bytesRead = response.Plaintext.Read(buffer, 0, (int)response.Plaintext.Length); return(Encoding.UTF8.GetString(buffer, 0, bytesRead)); } catch { return(encryptedValue); } }
public IActionResult Decrypt([FromBody] DecryptRequest request) { if (ModelState.IsValid) { try { string result = _cryptoOperation.Decrypt(request.CipherText); return(Ok(new DecryptResponse { PlainText = result })); } catch (Exception ex) { return(StatusCode(500, new { errorMessage = ex.Message })); } } else { return(BadRequest(new { errorMessage = "Invalid payload" })); } }
private async Task <SecureString> DecryptCryptoKeyAsync(string application, string tenantId, byte[] cipherTextBytes) { using (var scope = new ProfileContext($"Decrypting crypto key using kms for {application} {tenantId}")) { DecryptRequest request = null; DecryptResponse response = null; bool isSuccess = false; try { request = GetDecryptRequest(application, tenantId, cipherTextBytes); var client = await _kmsClientFactory.GetGlobalClientAsync(); response = await client.DecryptAsync(request); if (response == null || response.HttpStatusCode != HttpStatusCode.OK) { throw Errors.ServerSide.KMSCommunicationError(); } isSuccess = true; //PlaintText is Base64-encoded binary data return(ConvertStreamToSecureString(response.Plaintext)); } catch (Exception ex) { Platform.Common.ExceptionPolicy.HandleException(ex, Constants.LogOnlyPolicy); } finally { request.CiphertextBlob = null; await LogRQRS(request, SanitizedResponse(response), application, tenantId, "aws_kms_provider", "decrypt_key", isSuccess); } throw Errors.ServerSide.KMSCommunicationError(); } }
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); }
public DecryptResponse Decrypt(DecryptRequest request) { if (request == null) { throw new ArgumentNullException("request"); } if (request.DocumentId == null) { throw new ArgumentException("documentId must not be null"); } var cache = ServiceHelper.Cache; using (var document = DocumentFactory.LoadFromCache(cache, request.DocumentId)) { DocumentHelper.CheckLoadFromCache(document); if (!document.Decrypt(request.Password)) { throw new ServiceException("Incorrect Password", HttpStatusCode.Forbidden); } document.SaveToCache(); return(new DecryptResponse { Document = document }); } }
public async Task <string> DecryptString(string value) { _logger.LogDebug("Decrypting value..."); string decryptedString; using (var stream = new MemoryStream(Convert.FromBase64String(value))) { var decryptRequest = new DecryptRequest { CiphertextBlob = stream }; _logger.LogDebug("Decrypt request built"); DecryptResponse response = await _kmsClient.DecryptAsync(decryptRequest); _logger.LogDebug("Decryption response received."); using (var reader = new StreamReader(response.Plaintext)) { decryptedString = await reader.ReadToEndAsync(); } _logger.LogDebug("Decryption response read. Value decrypted."); } return(decryptedString); }
public string Decrypt(EncryptedValue encryptedValue, IIncomingLogicalMessageContext context) { if (encryptedValue == null || String.IsNullOrEmpty(encryptedValue.EncryptedBase64Value)) { return(null); } if (!context.Headers.ContainsKey(EncryptionHeaders.RijndaelKeyIdentifier)) { return(null); } var decryptlabel = context.Headers[EncryptionHeaders.RijndaelKeyIdentifier]; var decryptRequest = new DecryptRequest { KeyId = decryptlabel }; var value = Convert.FromBase64String(encryptedValue.EncryptedBase64Value); decryptRequest.CiphertextBlob = new System.IO.MemoryStream(value); var response = _client.DecryptAsync(decryptRequest).GetAwaiter().GetResult(); if (response != null) { return(Encoding.UTF8.GetString(response.Plaintext.ToArray())); } return(null); }
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); } } }
/// <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); } } }
public async Task <IActionResult> Decrypt(string id, [FromBody] DecryptRequest request) { var decrypted = await enclave.Decrypt <object>(enclave.ParseKeyId(id), request.Value); return(Ok(new DecryptResult { Value = decrypted.Serialize() })); }
/// <summary> /// Initiates the asynchronous execution of the Decrypt operation. /// </summary> /// /// <param name="request">Container for the necessary parameters to execute the Decrypt 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 <DecryptResponse> DecryptAsync(DecryptRequest request, System.Threading.CancellationToken cancellationToken = default(CancellationToken)) { var marshaller = new DecryptRequestMarshaller(); var unmarshaller = DecryptResponseUnmarshaller.Instance; return(InvokeAsync <DecryptRequest, DecryptResponse>(request, marshaller, unmarshaller, cancellationToken)); }
public override DecryptResponse Decrypt(DecryptRequest request, CallSettings callSettings = null) { byte xorOperand = (byte) request.Name.GetHashCode(); return new DecryptResponse { Plaintext = ByteString.CopyFrom(request.Ciphertext.Select(x => (byte) (x - 1)).Select(x => (byte) (x ^ xorOperand)).ToArray()) }; }
public override Task <DecryptResponse> DecryptAsync(DecryptRequest request, ServerCallContext context) { return(Task.FromResult(new DecryptResponse() { ReplicaId = _replicaId, Result = _Encrypt(request.Str, request.Shift) })); }
public ActionResult <DecryptResponse> Decrypt([FromBody] DecryptRequest request) { Rot13 cipher = new(); return(new DecryptResponse() { Plaintext = cipher.Decrypt(request.Ciphertext), }); }
public ActionResult <DecryptResponse> Decrypt(DecryptRequest request) { Atbash cipher = new(); return(new DecryptResponse() { Plaintext = cipher.Decrypt(request.Ciphertext), }); }
public byte[] DecryptKey(byte[] cipherText, IDictionary <string, string> context) { var req = new DecryptRequest { CiphertextBlob = new MemoryStream(cipherText), EncryptionContext = AsDictionary(context) }; return(_client.Decrypt(req).Plaintext.ToArray()); }
private async Task <byte[]> GetDecryptedDataKey() { var request = new DecryptRequest { CiphertextBlob = new MemoryStream(Convert.FromBase64String(encryptedDataKey)) }; var response = await kmsService.DecryptAsync(request); return(response.Plaintext.ToArray()); }
/// <inheritdoc/> protected override byte[] DecryptedEnvelopeKeyKms(byte[] encryptedKMSEnvelopeKey, Dictionary <string, string> encryptionContext) { var request = new DecryptRequest() { CiphertextBlob = new MemoryStream(encryptedKMSEnvelopeKey), EncryptionContext = encryptionContext }; var response = EncryptionClient.KMSClient.Decrypt(request); return(response.Plaintext.ToArray()); }
public void Construct() { var data = Encoding.UTF8.GetBytes("test"); var context = new Dictionary <string, string>(); var request = new DecryptRequest("abc", data, context); Assert.Equal("abc", request.KeyId); Assert.Null(request.GrantTokens); Assert.Equal(data, request.CiphertextBlob); Assert.Equal(context, request.EncryptionContext); }
/// <inheritdoc /> protected override async System.Threading.Tasks.Task <byte[]> DecryptedEnvelopeKeyKmsAsync(byte[] encryptedKMSEnvelopeKey, Dictionary <string, string> encryptionContext) { var request = new DecryptRequest() { CiphertextBlob = new MemoryStream(encryptedKMSEnvelopeKey), EncryptionContext = encryptionContext }; var response = await EncryptionClient.KMSClient.DecryptAsync(request).ConfigureAwait(false); return(response.Plaintext.ToArray()); }
private async Task <MemoryStream> DecryptDataKey(MemoryStream ciphertextBlob) { var decryptRequest = new DecryptRequest { CiphertextBlob = ciphertextBlob, KeyId = this.keyId }; var response = await client.DecryptAsync(decryptRequest); return(response.Plaintext); }
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}"); } } }
public override byte[] TransformFinalBlock(byte[] inputBuffer, int inputOffset, int inputCount) { var request = new DecryptRequest { CiphertextBlob = new MemoryStream(inputBuffer, inputOffset, inputCount) }; var task = _client.DecryptAsync(request); task.Wait(); return(task.Result.Plaintext.ToArray()); }
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()); }
public async Task <string> Decrypt(string data) { using var stream = GenerateStreamFromBase64String(data); var req = new DecryptRequest { KeyId = this.keyId, CiphertextBlob = stream }; var response = await client.DecryptAsync(req); var result = GetValueFromStream(response.Plaintext); return(result); }