| | | 1 | | // Copyright (c) Microsoft Corporation. All rights reserved. |
| | | 2 | | // Licensed under the MIT License. |
| | | 3 | | |
| | | 4 | | using System; |
| | | 5 | | using System.IO; |
| | | 6 | | using System.Threading.Tasks; |
| | | 7 | | using System.Xml.Linq; |
| | | 8 | | using Azure.Core.Cryptography; |
| | | 9 | | using Microsoft.AspNetCore.DataProtection.XmlEncryption; |
| | | 10 | | using Microsoft.Extensions.DependencyInjection; |
| | | 11 | | |
| | | 12 | | namespace Azure.Extensions.AspNetCore.DataProtection.Keys |
| | | 13 | | { |
| | | 14 | | #pragma warning disable CA1812 // False positive, AzureKeyVaultXmlDecryptor is used in AzureKeyVaultXmlEncryptor |
| | | 15 | | internal class AzureKeyVaultXmlDecryptor : IXmlDecryptor |
| | | 16 | | #pragma warning restore |
| | | 17 | | { |
| | | 18 | | private readonly IKeyEncryptionKeyResolver _client; |
| | | 19 | | |
| | 2 | 20 | | public AzureKeyVaultXmlDecryptor(IServiceProvider serviceProvider) |
| | | 21 | | { |
| | 2 | 22 | | _client = serviceProvider.GetService<IKeyEncryptionKeyResolver>(); |
| | 2 | 23 | | } |
| | | 24 | | |
| | | 25 | | public XElement Decrypt(XElement encryptedElement) |
| | | 26 | | { |
| | 4 | 27 | | return Task.Run(() => DecryptAsync(encryptedElement)).GetAwaiter().GetResult(); |
| | | 28 | | } |
| | | 29 | | |
| | | 30 | | private async Task<XElement> DecryptAsync(XElement encryptedElement) |
| | | 31 | | { |
| | 2 | 32 | | var kid = (string)encryptedElement.Element("kid"); |
| | 2 | 33 | | var symmetricKey = Convert.FromBase64String((string)encryptedElement.Element("key")); |
| | 2 | 34 | | var symmetricIV = Convert.FromBase64String((string)encryptedElement.Element("iv")); |
| | | 35 | | |
| | 2 | 36 | | var encryptedValue = Convert.FromBase64String((string)encryptedElement.Element("value")); |
| | | 37 | | |
| | 2 | 38 | | var key = await _client.ResolveAsync(kid).ConfigureAwait(false); |
| | 2 | 39 | | var result = await key.UnwrapKeyAsync(AzureKeyVaultXmlEncryptor.DefaultKeyEncryption, symmetricKey).Configur |
| | | 40 | | |
| | | 41 | | byte[] decryptedValue; |
| | 2 | 42 | | using (var symmetricAlgorithm = AzureKeyVaultXmlEncryptor.DefaultSymmetricAlgorithmFactory()) |
| | | 43 | | { |
| | 2 | 44 | | using (var decryptor = symmetricAlgorithm.CreateDecryptor(result, symmetricIV)) |
| | | 45 | | { |
| | 2 | 46 | | decryptedValue = decryptor.TransformFinalBlock(encryptedValue, 0, encryptedValue.Length); |
| | 2 | 47 | | } |
| | 2 | 48 | | } |
| | | 49 | | |
| | 2 | 50 | | using (var memoryStream = new MemoryStream(decryptedValue)) |
| | | 51 | | { |
| | 2 | 52 | | return XElement.Load(memoryStream); |
| | | 53 | | } |
| | 2 | 54 | | } |
| | | 55 | | } |
| | | 56 | | } |