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 override DecodeTokenResponse Query(DecodeTokenRequest request, IServiceRouter router, RequestContext context) { DecodeTokenResponse response = new DecodeTokenResponse(); DecryptResponse decrypt = router.Query <DecryptRequest, DecryptResponse>(new DecryptRequest() { Key = request.Key, CipherText = request.Data, IV = request.IV, Algorithm = request.Algorithm }); string tokenStr = Encoding.ASCII.GetString(decrypt.ClearText); Dictionary <string, string> parts = tokenStr.Split('|').Select(x => x.Split(new[] { ':' }, 1)).ToDictionary(x => x[0], x => x[1]); Token token = new Token() { Type = (TokenType)Enum.Parse(typeof(TokenType), parts["type"], true), PrincipalId = Guid.Parse(parts["prin"]), Data = Convert.ToBase64String(request.Data), Expiration = DateTime.ParseExact(parts["expire"], "yyyyMMddHHmmss", CultureInfo.CurrentCulture), Issued = DateTime.ParseExact(parts["issued"], "yyyyMMddHHmmss", CultureInfo.CurrentCulture) }; response.Token = token; return(response); }
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 <IActionResult> Decrypt([Required] string cipherText) { ViewBag.Result = string.Empty; ViewBag.Success = false; if (ModelState.IsValid) { var client = await GetHttpClient(); var response = await client.PostAsync("/api/crypto/tdes/decrypt", new StringContent(JsonConvert.SerializeObject(new { cipherText = cipherText }), Encoding.UTF8, "application/json")); if (response.IsSuccessStatusCode) { string responseJson = await response.Content.ReadAsStringAsync(); DecryptResponse encryptResponse = JsonConvert.DeserializeObject <DecryptResponse>(responseJson); ViewBag.Result = encryptResponse.PlainText; ViewBag.Success = true; } else { ViewBag.Result = "An error occured"; } } else { ViewBag.Result = "Invalid body payload"; } return(View()); }
/// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public override AmazonWebServiceResponse Unmarshall(JsonUnmarshallerContext context) { DecryptResponse response = new DecryptResponse(); context.Read(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("EncryptionAlgorithm", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.EncryptionAlgorithm = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("KeyId", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; response.KeyId = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("Plaintext", targetDepth)) { var unmarshaller = MemoryStreamUnmarshaller.Instance; response.Plaintext = unmarshaller.Unmarshall(context); continue; } } return(response); }
public void ExpectDecryptToSucceed() { var myEncryptedString = "encrypted"; var myBase64EncryptedData = Convert.ToBase64String(Encoding.UTF8.GetBytes(myEncryptedString)); var myEncryptedXml = new XElement(ElementName, new XElement("value", myBase64EncryptedData)); var myOutputXml = new XElement(ElementName, "output"); using (var decryptedResponseStream = new MemoryStream()) { myOutputXml.Save(decryptedResponseStream); decryptedResponseStream.Seek(0, SeekOrigin.Begin); var decryptResponse = new DecryptResponse { KeyId = KeyId, Plaintext = decryptedResponseStream }; encryptConfig.Setup(x => x.EncryptionContext).Returns(encryptionContext); encryptConfig.Setup(x => x.GrantTokens).Returns(grantTokens); kmsClient.Setup(x => x.DecryptAsync(It.IsAny <DecryptRequest>(), CancellationToken.None)) .ReturnsAsync(decryptResponse) .Callback <DecryptRequest, CancellationToken>((dr, ct) => { Assert.Same(encryptionContext, dr.EncryptionContext); Assert.Same(grantTokens, dr.GrantTokens); Assert.Equal(myEncryptedString, Encoding.UTF8.GetString(dr.CiphertextBlob.ToArray())); }); var plaintextXml = decryptor.Decrypt(myEncryptedXml); Assert.True(XNode.DeepEquals(myOutputXml, plaintextXml)); } }
public void ExpectEncryptToSucceed(bool useAppId, bool hashAppId, string appId, string expectedAppId) { var myEncryptedString = "encrypted"; var myBase64EncryptedData = Convert.ToBase64String(Encoding.UTF8.GetBytes(myEncryptedString)); var myEncryptedXml = new XElement(ElementName, new XElement("value", myBase64EncryptedData)); var myOutputXml = new XElement(ElementName, "output"); using (var decryptedResponseStream = new MemoryStream()) { myOutputXml.Save(decryptedResponseStream); decryptedResponseStream.Seek(0, SeekOrigin.Begin); var decryptResponse = new DecryptResponse { KeyId = KeyId, Plaintext = decryptedResponseStream }; var actualConfig = new KmsXmlEncryptorConfig { EncryptionContext = encryptionContext, GrantTokens = grantTokens, KeyId = KeyId, DiscriminatorAsContext = useAppId, HashDiscriminatorContext = hashAppId }; var actualOptions = new DataProtectionOptions { ApplicationDiscriminator = appId }; encryptConfig.Setup(x => x.Value).Returns(actualConfig); dpOptions.Setup(x => x.Value).Returns(actualOptions); kmsClient.Setup(x => x.DecryptAsync(It.IsAny <DecryptRequest>(), CancellationToken.None)) .ReturnsAsync(decryptResponse) .Callback <DecryptRequest, CancellationToken>((dr, ct) => { if (appId != null && useAppId) { Assert.Contains(KmsConstants.ApplicationEncryptionContextKey, dr.EncryptionContext.Keys); Assert.Equal(expectedAppId, dr.EncryptionContext[KmsConstants.ApplicationEncryptionContextKey]); } else { Assert.Same(encryptionContext, dr.EncryptionContext); } Assert.Same(grantTokens, dr.GrantTokens); Assert.Equal(myEncryptedString, Encoding.UTF8.GetString(dr.CiphertextBlob.ToArray())); }); var plaintextXml = decryptor.Decrypt(myEncryptedXml); Assert.True(XNode.DeepEquals(myOutputXml, plaintextXml)); } }
public void ServiceReturnsFailCode() { _result = new DecryptResponse { HttpStatusCode = HttpStatusCode.BadRequest }; KmsService.DecryptAsync(Arg.Any <DecryptRequest>()) .Returns(_result); }
public static DecryptResponse Unmarshall(UnmarshallerContext context) { DecryptResponse decryptResponse = new DecryptResponse(); decryptResponse.HttpResponse = context.HttpResponse; decryptResponse.Plaintext = context.StringValue("Decrypt.Plaintext"); decryptResponse.KeyId = context.StringValue("Decrypt.KeyId"); decryptResponse.RequestId = context.StringValue("Decrypt.RequestId"); return(decryptResponse); }
private DecryptResponse SanitizedResponse(DecryptResponse response) { if (response == null) { return(response); } response.Plaintext = null; response.ResponseMetadata = null; return(response); }
public static DecryptResponse Unmarshall(UnmarshallerContext _ctx) { DecryptResponse decryptResponse = new DecryptResponse(); decryptResponse.HttpResponse = _ctx.HttpResponse; decryptResponse.Plaintext = _ctx.StringValue("Decrypt.Plaintext"); decryptResponse.KeyId = _ctx.StringValue("Decrypt.KeyId"); decryptResponse.RequestId = _ctx.StringValue("Decrypt.RequestId"); decryptResponse.KeyVersionId = _ctx.StringValue("Decrypt.KeyVersionId"); return(decryptResponse); }
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()); }
// [END kms_encrypt] // [START kms_decrypt] public static void Decrypt(string projectId, string locationId, string keyRingId, string cryptoKeyId, string ciphertextFile, string plaintextFile) { KeyManagementServiceClient client = KeyManagementServiceClient.Create(); CryptoKeyName cryptoKeyName = new CryptoKeyName(projectId, locationId, keyRingId, cryptoKeyId); byte[] ciphertext = File.ReadAllBytes(ciphertextFile); DecryptResponse result = client.Decrypt(cryptoKeyName, ByteString.CopyFrom(ciphertext)); // Output decrypted data to a file. File.WriteAllBytes(plaintextFile, result.Plaintext.ToByteArray()); Console.Write($"Decrypted file created: {plaintextFile}"); }
public static string Decrypt(string cipher) { KeyManagementServiceClient client = KeyManagementServiceClient.Create(); CryptoKeyName kn = CryptoKeyName.FromUnparsed( new Google.Api.Gax.UnparsedResourceName("projects/jurgen-cloud-project/locations/global/keyRings/pftckeyring/cryptoKeys/pftckeys")); byte[] cipherText = Convert.FromBase64String(cipher); DecryptResponse result = client.Decrypt(kn, ByteString.CopyFrom(cipherText)); byte[] bytes = result.Plaintext.ToByteArray(); string finalResult = Encoding.Default.GetString(bytes); return(finalResult); }
public string Decrypt(string cipher) { // Create the client. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // Build the key name. CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId); DecryptResponse result = client.Decrypt(keyName, ByteString.FromBase64(cipher)); //convert the result to byteArray byte[] plaintext = result.Plaintext.ToByteArray(); return(Encoding.UTF8.GetString(plaintext)); }
private static async Task Decrypt(KmsCryptoClient kmsCryptoClient, string keyId, string cipherText) { logger.Info("Decrypt"); DecryptDataDetails decryptDataDetails = new DecryptDataDetails { Ciphertext = cipherText, KeyId = keyId, LoggingContext = GetSampleLoggingContext() }; DecryptRequest decryptRequest = new DecryptRequest { DecryptDataDetails = decryptDataDetails }; DecryptResponse decryptResponse = await kmsCryptoClient.Decrypt(decryptRequest); logger.Info($"Decrypted text: {decryptResponse.DecryptedData.Plaintext}"); }
public override async Task <string> DecryptAsync(string initializationVector, string encryptedText) { var request = new DecryptRequest { Ciphertext = Convert.FromBase64String(encryptedText), InitializationVector = Encoding.UTF8.GetBytes(initializationVector) }; using (HttpClient httpClient = HttpClientHelper.GetHttpClient(this.WorkloadUri)) { var edgeletHttpClient = new HttpWorkloadClient(httpClient) { BaseUrl = HttpClientHelper.GetBaseUrl(this.WorkloadUri) }; DecryptResponse result = await this.Execute(() => edgeletHttpClient.DecryptAsync(this.Version.Name, this.ModuleId, this.ModuleGenerationId, request), "Decrypt"); return(Encoding.UTF8.GetString(result.Plaintext)); } }
public string DecryptSymmetric( string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring", string keyId = "my-key", byte[] ciphertext = null) { // Create the client. KeyManagementServiceClient client = KeyManagementServiceClient.Create(); // Build the key name. CryptoKeyName keyName = new CryptoKeyName(projectId, locationId, keyRingId, keyId); // Call the API. DecryptResponse result = client.Decrypt(keyName, ByteString.CopyFrom(ciphertext)); // Get the plaintext. Cryptographic plaintexts and ciphertexts are // always byte arrays. byte[] plaintext = result.Plaintext.ToByteArray(); // Return the result. return(Encoding.UTF8.GetString(plaintext)); }
public async Task <string> DecryptString(string value) { string decryptedString; using (var stream = new MemoryStream(Convert.FromBase64String(value))) { var decryptRequest = new DecryptRequest { CiphertextBlob = stream }; DecryptResponse response = await _kmsClient.DecryptAsync(decryptRequest); using (var reader = new StreamReader(response.Plaintext)) { decryptedString = await reader.ReadToEndAsync(); } } return(decryptedString); }