/* * Copyright (c) 2022 Winsider Seminars & Solutions, Inc. All rights reserved. * * This file is part of System Informer. * * Authors: * * dmex * */ namespace CustomBuildTool { /// /// A signing context used for signing packages with Azure Key Vault Keys. /// public readonly struct KeyVaultContext { /// /// The access token used to authenticate with Azure Key Vault. /// private readonly string AccessToken; /// /// Gets the certificate used to validate the signature. May be null if /// Key isn't part of a certificate /// public X509Certificate2 Certificate { get; } /// /// Identifier of current key /// public Uri KeyIdentifier { get; } /// /// Returns true if properly constructed. If default, then false. /// public bool IsValid => !string.IsNullOrWhiteSpace(this.AccessToken) && this.KeyIdentifier != null; /// /// Creates a new Key Vault context using an access token and a public certificate. /// public KeyVaultContext(string AccessToken, Uri KeyId, X509Certificate2 PublicCertificate) { ArgumentNullException.ThrowIfNull(AccessToken); ArgumentNullException.ThrowIfNull(KeyId); ArgumentNullException.ThrowIfNull(PublicCertificate); this.AccessToken = AccessToken; this.Certificate = PublicCertificate; this.KeyIdentifier = KeyId; } /// /// Signs a digest using the specified hash algorithm and signature algorithm. /// /// The message digest to sign. /// The hash algorithm used to create the digest. /// The signature algorithm to use. /// The signature of the digest. internal byte[] SignDigest(byte[] Digest, HashAlgorithmName HashAlgorithm, KeyVaultSignatureAlgorithm SignatureAlgorithm) { if (HashAlgorithm == HashAlgorithmName.SHA1) { throw new InvalidOperationException("SHA1 algorithm is not supported for this signature algorithm."); } string signatureAlgorithmId = SignatureAlgorithmTranslator.SignatureAlgorithmToJwsAlgId(SignatureAlgorithm, HashAlgorithm); using KeyVaultRestClient keyVaultClient = new KeyVaultRestClient(this.AccessToken); // Block on the async call to provide a synchronous API expected by callers. return keyVaultClient.Sign(Digest, signatureAlgorithmId, this.KeyIdentifier, CancellationToken.None).GetAwaiter().GetResult(); } /// /// Verifies a signature over a digest using the specified hash algorithm and signature algorithm. /// /// The message digest that was signed. /// The signature to verify. /// The hash algorithm used to create the digest. /// The signature algorithm to use. /// True if the signature is valid; otherwise false. internal bool VerifyDigest(byte[] Digest, byte[] Signature, HashAlgorithmName HashAlgorithm, KeyVaultSignatureAlgorithm SignatureAlgorithm) { if (HashAlgorithm == HashAlgorithmName.SHA1) { throw new InvalidOperationException("SHA1 algorithm is not supported for this signature algorithm."); } string signatureAlgorithmId = SignatureAlgorithmTranslator.SignatureAlgorithmToJwsAlgId(SignatureAlgorithm, HashAlgorithm); using KeyVaultRestClient keyVaultClient = new KeyVaultRestClient(this.AccessToken); // Block on the async call to provide a synchronous API expected by callers. return keyVaultClient.Verify(Digest, Signature, signatureAlgorithmId, this.KeyIdentifier, CancellationToken.None).GetAwaiter().GetResult(); } /// /// Converts an instance to its corresponding JWS algorithm identifier. /// /// The RSA encryption padding. /// The JWS algorithm identifier as a string. /// Thrown when the specified padding is not supported. internal static string EncryptionPaddingToJwsAlgId(RSAEncryptionPadding Padding) { return Padding.Mode switch { RSAEncryptionPaddingMode.Pkcs1 => "RSA1_5", RSAEncryptionPaddingMode.Oaep when Padding.OaepHashAlgorithm == HashAlgorithmName.SHA1 => "RSA-OAEP", RSAEncryptionPaddingMode.Oaep when Padding.OaepHashAlgorithm == HashAlgorithmName.SHA256 => "RSA-OAEP-256", _ => throw new NotSupportedException("The padding specified is not supported.") }; } /// /// Decrypts cipher text using the specified RSA encryption padding. /// /// The cipher text to decrypt. /// The RSA encryption padding used. /// The decrypted plain text data. internal byte[] DecryptData(byte[] CipherText, RSAEncryptionPadding Padding) { string encryptionAlgorithmId = EncryptionPaddingToJwsAlgId(Padding); using KeyVaultRestClient keyVaultClient = new KeyVaultRestClient(this.AccessToken); // Block on the async call to provide a synchronous API expected by callers. return keyVaultClient.Decrypt(CipherText, encryptionAlgorithmId, this.KeyIdentifier, CancellationToken: CancellationToken.None).GetAwaiter().GetResult(); } /// /// Encrypts plain text using the specified RSA encryption padding. /// /// The plain text data to encrypt. /// The RSA encryption padding to use. /// The encrypted cipher text data. internal byte[] EncryptData(byte[] PlainText, RSAEncryptionPadding Padding) { string encryptionAlgorithmId = EncryptionPaddingToJwsAlgId(Padding); using KeyVaultRestClient keyVaultClient = new KeyVaultRestClient(this.AccessToken); // Block on the async call to provide a synchronous API expected by callers. return keyVaultClient.Encrypt(PlainText, encryptionAlgorithmId, this.KeyIdentifier, CancellationToken: CancellationToken.None).GetAwaiter().GetResult(); } /// /// Wraps key material using the specified RSA encryption padding. /// /// The key material to wrap. /// The RSA encryption padding to use. /// The wrapped key material. internal byte[] WrapKey(byte[] Key, RSAEncryptionPadding Padding) { string encryptionAlgorithmId = EncryptionPaddingToJwsAlgId(Padding); using KeyVaultRestClient keyVaultClient = new KeyVaultRestClient(this.AccessToken); // Block on the async call to provide a synchronous API expected by callers. return keyVaultClient.WrapKey(Key, encryptionAlgorithmId, this.KeyIdentifier, CancellationToken: CancellationToken.None).GetAwaiter().GetResult(); } /// /// Unwraps key material using the specified RSA encryption padding. /// /// The wrapped key material. /// The RSA encryption padding to use. /// The unwrapped key material. internal byte[] UnwrapKey(byte[] WrappedKey, RSAEncryptionPadding Padding) { string encryptionAlgorithmId = EncryptionPaddingToJwsAlgId(Padding); using KeyVaultRestClient keyVaultClient = new KeyVaultRestClient(this.AccessToken); // Block on the async call to provide a synchronous API expected by callers. return keyVaultClient.UnwrapKey(WrappedKey, encryptionAlgorithmId, this.KeyIdentifier, CancellationToken: CancellationToken.None).GetAwaiter().GetResult(); } } /// /// Minimal client for Azure Key Vault cryptography operations. /// Provides async Sign/Decrypt helpers and creates HttpClient instances as needed. /// internal sealed class KeyVaultRestClient : IDisposable { private readonly HttpClient HttpClient; private readonly string AccessToken; public KeyVaultRestClient(string AccessToken) { this.HttpClient = BuildHttpClient.CreateHttpClient(); this.AccessToken = AccessToken ?? throw new ArgumentNullException(nameof(AccessToken)); } public void Dispose() { this.HttpClient?.Dispose(); } /// /// Gets the public part and metadata of a stored key. /// public Task GetKey(Uri KeyId, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(KeyId); return this.SendJson( HttpMethod.Get, $"{KeyId.ToString().TrimEnd('/')}?api-version={AzureClient.ApiVersion}", null, AzureJsonContext.Default.KeyVaultKeyResponse, CancellationToken ); } /// /// Lists keys in a vault. /// public Task GetKeys(Uri VaultBaseUrl, int? MaxResults = null, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(VaultBaseUrl); return this.SendJson( HttpMethod.Get, CreateVaultRequestUrl(VaultBaseUrl, "keys", MaxResults), null, AzureJsonContext.Default.KeyVaultKeyListResponse, CancellationToken ); } /// /// Lists versions of a stored key. /// public Task GetKeyVersions(Uri KeyId, int? MaxResults = null, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(KeyId); return this.SendJson( HttpMethod.Get, CreateKeyRequestUrl(KeyId, "versions", MaxResults), null, AzureJsonContext.Default.KeyVaultKeyListResponse, CancellationToken ); } /// /// Creates a new key in a vault. /// public Task CreateKey(Uri VaultBaseUrl, string KeyName, KeyVaultKeyCreateRequest Request, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(VaultBaseUrl); ArgumentException.ThrowIfNullOrWhiteSpace(KeyName); ArgumentNullException.ThrowIfNull(Request); return this.SendJson( HttpMethod.Post, $"{VaultBaseUrl.ToString().TrimEnd('/')}/keys/{Uri.EscapeDataString(KeyName)}/create?api-version={AzureClient.ApiVersion}", CreateJsonContent(Request, AzureJsonContext.Default.KeyVaultKeyCreateRequest), AzureJsonContext.Default.KeyVaultKeyResponse, CancellationToken ); } /// /// Imports externally created key material into a vault. /// public Task ImportKey(Uri VaultBaseUrl, string KeyName, KeyVaultKeyImportRequest Request, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(VaultBaseUrl); ArgumentException.ThrowIfNullOrWhiteSpace(KeyName); ArgumentNullException.ThrowIfNull(Request); return this.SendJson( HttpMethod.Put, $"{VaultBaseUrl.ToString().TrimEnd('/')}/keys/{Uri.EscapeDataString(KeyName)}?api-version={AzureClient.ApiVersion}", CreateJsonContent(Request, AzureJsonContext.Default.KeyVaultKeyImportRequest), AzureJsonContext.Default.KeyVaultKeyResponse, CancellationToken ); } /// /// Updates attributes, operations, tags, or release policy for a stored key. /// public Task UpdateKey(Uri KeyId, KeyVaultKeyUpdateRequest Request, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(KeyId); ArgumentNullException.ThrowIfNull(Request); return this.SendJson( HttpMethod.Patch, $"{KeyId.ToString().TrimEnd('/')}?api-version={AzureClient.ApiVersion}", CreateJsonContent(Request, AzureJsonContext.Default.KeyVaultKeyUpdateRequest), AzureJsonContext.Default.KeyVaultKeyResponse, CancellationToken ); } /// /// Deletes a key from a vault. /// public Task DeleteKey(Uri VaultBaseUrl, string KeyName, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(VaultBaseUrl); ArgumentException.ThrowIfNullOrWhiteSpace(KeyName); return this.SendJson( HttpMethod.Delete, $"{VaultBaseUrl.ToString().TrimEnd('/')}/keys/{Uri.EscapeDataString(KeyName)}?api-version={AzureClient.ApiVersion}", null, AzureJsonContext.Default.KeyVaultKeyResponse, CancellationToken ); } /// /// Gets a deleted key from a vault. /// public Task GetDeletedKey(Uri VaultBaseUrl, string KeyName, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(VaultBaseUrl); ArgumentException.ThrowIfNullOrWhiteSpace(KeyName); return this.SendJson( HttpMethod.Get, $"{VaultBaseUrl.ToString().TrimEnd('/')}/deletedkeys/{Uri.EscapeDataString(KeyName)}?api-version={AzureClient.ApiVersion}", null, AzureJsonContext.Default.KeyVaultKeyResponse, CancellationToken ); } /// /// Lists deleted keys in a vault. /// public Task GetDeletedKeys(Uri VaultBaseUrl, int? MaxResults = null, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(VaultBaseUrl); return this.SendJson( HttpMethod.Get, CreateVaultRequestUrl(VaultBaseUrl, "deletedkeys", MaxResults), null, AzureJsonContext.Default.KeyVaultKeyListResponse, CancellationToken ); } /// /// Permanently deletes a deleted key. /// public Task PurgeDeletedKey(Uri VaultBaseUrl, string KeyName, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(VaultBaseUrl); ArgumentException.ThrowIfNullOrWhiteSpace(KeyName); return this.Send( HttpMethod.Delete, $"{VaultBaseUrl.ToString().TrimEnd('/')}/deletedkeys/{Uri.EscapeDataString(KeyName)}?api-version={AzureClient.ApiVersion}", null, CancellationToken ); } /// /// Recovers a deleted key to its latest version. /// public Task RecoverDeletedKey(Uri VaultBaseUrl, string KeyName, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(VaultBaseUrl); ArgumentException.ThrowIfNullOrWhiteSpace(KeyName); return this.SendJson( HttpMethod.Post, $"{VaultBaseUrl.ToString().TrimEnd('/')}/deletedkeys/{Uri.EscapeDataString(KeyName)}/recover?api-version={AzureClient.ApiVersion}", null, AzureJsonContext.Default.KeyVaultKeyResponse, CancellationToken ); } /// /// Backs up a key in protected Key Vault backup format. /// public async Task BackupKey(Uri KeyId, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(KeyId); KeyVaultBackupResponse backupResponse = null; try { backupResponse = await this.SendJson( HttpMethod.Post, $"{KeyId.ToString().TrimEnd('/')}/backup?api-version={AzureClient.ApiVersion}", null, AzureJsonContext.Default.KeyVaultBackupResponse, CancellationToken ); return Base64UrlDecode(backupResponse.Value); } finally { backupResponse?.ClearSensitiveData(); } } /// /// Restores a backed up key into a vault. /// public Task RestoreKey(Uri VaultBaseUrl, byte[] BackupBlob, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(VaultBaseUrl); ArgumentNullException.ThrowIfNull(BackupBlob); KeyVaultRestoreRequest request = new KeyVaultRestoreRequest { Value = Base64UrlEncode(BackupBlob) }; return this.SendJson( HttpMethod.Post, $"{VaultBaseUrl.ToString().TrimEnd('/')}/keys/restore?api-version={AzureClient.ApiVersion}", CreateJsonContent(request, AzureJsonContext.Default.KeyVaultRestoreRequest), AzureJsonContext.Default.KeyVaultKeyResponse, CancellationToken ); } /// /// Releases exportable key material to an attested target. /// public Task ReleaseKey(Uri KeyId, KeyVaultKeyReleaseRequest Request, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(KeyId); ArgumentNullException.ThrowIfNull(Request); return this.SendJson( HttpMethod.Post, $"{KeyId.ToString().TrimEnd('/')}/release?api-version={AzureClient.ApiVersion}", CreateJsonContent(Request, AzureJsonContext.Default.KeyVaultKeyReleaseRequest), AzureJsonContext.Default.KeyVaultKeyReleaseResponse, CancellationToken ); } /// /// Rotates a key by creating a new version based on its rotation policy. /// public Task RotateKey(Uri KeyId, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(KeyId); return this.SendJson( HttpMethod.Post, $"{KeyId.ToString().TrimEnd('/')}/rotate?api-version={AzureClient.ApiVersion}", null, AzureJsonContext.Default.KeyVaultKeyResponse, CancellationToken ); } /// /// Gets the rotation policy for a key. /// public Task GetKeyRotationPolicy(Uri KeyId, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(KeyId); return this.SendJson( HttpMethod.Get, $"{KeyId.ToString().TrimEnd('/')}/rotationpolicy?api-version={AzureClient.ApiVersion}", null, AzureJsonContext.Default.KeyVaultKeyRotationPolicy, CancellationToken ); } /// /// Updates the rotation policy for a key. /// public Task UpdateKeyRotationPolicy(Uri KeyId, KeyVaultKeyRotationPolicy Policy, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(KeyId); ArgumentNullException.ThrowIfNull(Policy); return this.SendJson( HttpMethod.Put, $"{KeyId.ToString().TrimEnd('/')}/rotationpolicy?api-version={AzureClient.ApiVersion}", CreateJsonContent(Policy, AzureJsonContext.Default.KeyVaultKeyRotationPolicy), AzureJsonContext.Default.KeyVaultKeyRotationPolicy, CancellationToken ); } /// /// Signs the specified digest using the given algorithm and key identifier, returning the resulting signature. /// /// The signing operation is performed remotely using the specified key in Azure Key /// Vault. The method ensures the request succeeds and throws an exception if the operation fails. The caller is /// responsible for providing a digest compatible with the chosen algorithm. /// The digest to be signed. Must not be null. /// The name of the signing algorithm to use. Must not be null. Supported algorithms depend on the key type and /// configuration. /// The identifier of the key to use for signing. Must not be null. /// A cancellation token that can be used to cancel the operation. /// A byte array containing the signature of the digest. The array will contain the signature in binary form. public async Task Sign(byte[] Digest, string Algorithm, Uri KeyId, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(Digest); ArgumentNullException.ThrowIfNull(Algorithm); ArgumentNullException.ThrowIfNull(KeyId); try { KeyVaultOperationRequest operationRequest = new KeyVaultOperationRequest { Algorithm = Algorithm, Value = Base64UrlEncode(Digest) }; KeyVaultOperationResponse operationResponse = await this.PostOperation( KeyId, "sign", operationRequest, CancellationToken ); char[] signatureValue = operationResponse?.Value ?? operationResponse?.Signature; ArgumentNullException.ThrowIfNull(signatureValue); try { return Base64UrlDecode(signatureValue); } finally { operationResponse.ClearSensitiveData(); } } catch (Exception) { Program.PrintColorMessage($"[StaticNativeSignDigestCallback] Exception", ConsoleColor.Red); return null; } } /// /// Verifies a signature over the specified digest using the given algorithm and key identifier. /// /// The digest that was signed. Must not be null. /// The signature to verify. Must not be null. /// The signing algorithm used to create the signature. Must not be null. /// The identifier of the key to use for verification. Must not be null. /// A cancellation token that can be used to cancel the operation. /// True if the signature is valid; otherwise false. public async Task Verify(byte[] Digest, byte[] Signature, string Algorithm, Uri KeyId, CancellationToken CancellationToken = default) { ArgumentNullException.ThrowIfNull(Digest); ArgumentNullException.ThrowIfNull(Signature); ArgumentNullException.ThrowIfNull(Algorithm); ArgumentNullException.ThrowIfNull(KeyId); try { KeyVaultVerifyRequest operationRequest = new KeyVaultVerifyRequest { Algorithm = Algorithm, Digest = Base64UrlEncode(Digest), Signature = Base64UrlEncode(Signature) }; KeyVaultVerifyResponse operationResponse = await this.PostVerifyOperation( KeyId, operationRequest, CancellationToken ); return operationResponse.Value; } catch (Exception) { Program.PrintColorMessage($"[KeyVaultRestClient.Verify] Exception", ConsoleColor.Red); return false; } } /// /// Encrypts data using the specified algorithm and key identifier. /// /// The plaintext to encrypt. Must not be null. /// The encryption algorithm to use. Must not be null. /// The identifier of the key to use for encryption. Must not be null. /// /// A cancellation token that can be used to cancel the operation. /// /// A byte array containing the encrypted ciphertext. public async Task Encrypt( byte[] PlainText, string Algorithm, Uri KeyId, byte[] AdditionalAuthenticatedData = null, byte[] InitializationVector = null, CancellationToken CancellationToken = default ) { ArgumentNullException.ThrowIfNull(PlainText); ArgumentNullException.ThrowIfNull(Algorithm); ArgumentNullException.ThrowIfNull(KeyId); try { KeyVaultOperationResponse operationResponse = await this.EncryptOperation( PlainText, Algorithm, KeyId, AdditionalAuthenticatedData, InitializationVector, CancellationToken ); char[] cipherTextValue = operationResponse?.Value; ArgumentNullException.ThrowIfNull(cipherTextValue); try { return Base64UrlDecode(cipherTextValue); } finally { operationResponse.ClearSensitiveData(); } } catch (Exception) { Program.PrintColorMessage($"[KeyVaultRestClient.Encrypt] Exception", ConsoleColor.Red); return null; } } /// /// Encrypts data and returns the full Key Vault operation response including authenticated encryption fields. /// public Task EncryptOperation( byte[] PlainText, string Algorithm, Uri KeyId, byte[] AdditionalAuthenticatedData = null, byte[] InitializationVector = null, CancellationToken CancellationToken = default ) { ArgumentNullException.ThrowIfNull(PlainText); ArgumentNullException.ThrowIfNull(Algorithm); ArgumentNullException.ThrowIfNull(KeyId); KeyVaultOperationRequest operationRequest = new KeyVaultOperationRequest { Algorithm = Algorithm, Value = Base64UrlEncode(PlainText), AdditionalAuthenticatedData = Base64UrlEncodeOrNull(AdditionalAuthenticatedData), InitializationVector = Base64UrlEncodeOrNull(InitializationVector) }; return this.PostOperation( KeyId, "encrypt", operationRequest, CancellationToken ); } /// /// Decrypts the specified ciphertext using the provided algorithm and key identifier. /// /// This method sends a request to the specified key vault endpoint to perform the /// decryption operation. The operation is asynchronous and may be canceled using the provided cancellation /// token. /// The ciphertext to decrypt, as a byte array. Cannot be null. /// The name of the decryption algorithm to use. Cannot be null or whitespace. /// The URI identifying the key to use for decryption. Cannot be null. /// /// A cancellation token that can be used to cancel the operation. /// /// /// A byte array containing the decrypted plaintext. The array will contain the original data if decryption /// succeeds. /// Thrown if , , or is null. public async Task Decrypt( byte[] Cipher, string Algorithm, Uri KeyId, byte[] AdditionalAuthenticatedData = null, byte[] InitializationVector = null, byte[] AuthenticationTag = null, CancellationToken CancellationToken = default ) { ArgumentNullException.ThrowIfNull(Cipher); ArgumentNullException.ThrowIfNull(Algorithm); ArgumentNullException.ThrowIfNull(KeyId); try { KeyVaultOperationResponse operationResponse = await this.DecryptOperation( Cipher, Algorithm, KeyId, AdditionalAuthenticatedData, InitializationVector, AuthenticationTag, CancellationToken ); char[] plaintextValue = operationResponse?.Plaintext ?? operationResponse?.Value; ArgumentNullException.ThrowIfNull(plaintextValue); try { return Base64UrlDecode(plaintextValue); } finally { operationResponse.ClearSensitiveData(); } } catch (Exception) { Program.PrintColorMessage($"[StaticNativeSignDigestCallback] Exception", ConsoleColor.Red); return null; } } /// /// Decrypts data and returns the full Key Vault operation response including authenticated encryption fields. /// public Task DecryptOperation( byte[] Cipher, string Algorithm, Uri KeyId, byte[] AdditionalAuthenticatedData = null, byte[] InitializationVector = null, byte[] AuthenticationTag = null, CancellationToken CancellationToken = default ) { ArgumentNullException.ThrowIfNull(Cipher); ArgumentNullException.ThrowIfNull(Algorithm); ArgumentNullException.ThrowIfNull(KeyId); KeyVaultOperationRequest operationRequest = new KeyVaultOperationRequest { Algorithm = Algorithm, Value = Base64UrlEncode(Cipher), AdditionalAuthenticatedData = Base64UrlEncodeOrNull(AdditionalAuthenticatedData), InitializationVector = Base64UrlEncodeOrNull(InitializationVector), AuthenticationTag = Base64UrlEncodeOrNull(AuthenticationTag) }; return this.PostOperation( KeyId, "decrypt", operationRequest, CancellationToken ); } /// /// Wraps key material using the specified algorithm and key identifier. /// /// The key material to wrap. Must not be null. /// The key wrapping algorithm to use. Must not be null. /// The identifier of the key encryption key. Must not be null. /// /// /// A cancellation token that can be used to cancel the operation. /// A byte array containing the wrapped key material. public async Task WrapKey( byte[] Key, string Algorithm, Uri KeyId, byte[] AdditionalAuthenticatedData = null, byte[] InitializationVector = null, CancellationToken CancellationToken = default ) { ArgumentNullException.ThrowIfNull(Key); ArgumentNullException.ThrowIfNull(Algorithm); ArgumentNullException.ThrowIfNull(KeyId); try { KeyVaultOperationResponse operationResponse = await this.WrapKeyOperation( Key, Algorithm, KeyId, AdditionalAuthenticatedData, InitializationVector, CancellationToken ); char[] wrappedKeyValue = operationResponse?.Value; ArgumentNullException.ThrowIfNull(wrappedKeyValue); try { return Base64UrlDecode(wrappedKeyValue); } finally { operationResponse.ClearSensitiveData(); } } catch (Exception) { Program.PrintColorMessage($"[KeyVaultRestClient.WrapKey] Exception", ConsoleColor.Red); return null; } } /// /// Wraps key material and returns the full Key Vault operation response including authenticated encryption fields. /// public Task WrapKeyOperation( byte[] Key, string Algorithm, Uri KeyId, byte[] AdditionalAuthenticatedData = null, byte[] InitializationVector = null, CancellationToken CancellationToken = default ) { ArgumentNullException.ThrowIfNull(Key); ArgumentNullException.ThrowIfNull(Algorithm); ArgumentNullException.ThrowIfNull(KeyId); KeyVaultOperationRequest operationRequest = new KeyVaultOperationRequest { Algorithm = Algorithm, Value = Base64UrlEncode(Key), AdditionalAuthenticatedData = Base64UrlEncodeOrNull(AdditionalAuthenticatedData), InitializationVector = Base64UrlEncodeOrNull(InitializationVector) }; return this.PostOperation( KeyId, "wrapkey", operationRequest, CancellationToken ); } /// /// Unwraps key material using the specified algorithm and key identifier. /// /// The wrapped key material. Must not be null. /// The key wrapping algorithm to use. Must not be null. /// The identifier of the key encryption key. Must not be null. /// /// A cancellation token that can be used to cancel the operation. /// /// /// A byte array containing the unwrapped key material. public async Task UnwrapKey( byte[] WrappedKey, string Algorithm, Uri KeyId, byte[] AdditionalAuthenticatedData = null, byte[] InitializationVector = null, byte[] AuthenticationTag = null, CancellationToken CancellationToken = default ) { ArgumentNullException.ThrowIfNull(WrappedKey); ArgumentNullException.ThrowIfNull(Algorithm); ArgumentNullException.ThrowIfNull(KeyId); try { KeyVaultOperationResponse operationResponse = await UnwrapKeyOperation( WrappedKey, Algorithm, KeyId, AdditionalAuthenticatedData, InitializationVector, AuthenticationTag, CancellationToken ); char[] unwrappedKeyValue = operationResponse?.Value; ArgumentNullException.ThrowIfNull(unwrappedKeyValue); try { return Base64UrlDecode(unwrappedKeyValue); } finally { operationResponse?.ClearSensitiveData(); } } catch (Exception) { Program.PrintColorMessage("[KeyVaultRestClient.UnwrapKey] Exception", ConsoleColor.Red); return null; } } /// /// Unwraps key material and returns the full Key Vault operation response including authenticated encryption fields. /// public Task UnwrapKeyOperation( byte[] WrappedKey, string Algorithm, Uri KeyId, byte[] AdditionalAuthenticatedData = null, byte[] InitializationVector = null, byte[] AuthenticationTag = null, CancellationToken CancellationToken = default ) { ArgumentNullException.ThrowIfNull(WrappedKey); ArgumentNullException.ThrowIfNull(Algorithm); ArgumentNullException.ThrowIfNull(KeyId); KeyVaultOperationRequest operationRequest = new KeyVaultOperationRequest { Algorithm = Algorithm, Value = Base64UrlEncode(WrappedKey), AdditionalAuthenticatedData = Base64UrlEncodeOrNull(AdditionalAuthenticatedData), InitializationVector = Base64UrlEncodeOrNull(InitializationVector), AuthenticationTag = Base64UrlEncodeOrNull(AuthenticationTag) }; return this.PostOperation( KeyId, "unwrapkey", operationRequest, CancellationToken ); } /// /// Sends a POST request to the specified Key Vault operation endpoint and returns the deserialized response. /// /// The URI identifying the Key Vault key to operate on. /// The name of the operation to perform on the Key Vault key. /// The request payload containing parameters for the operation. /// A cancellation token that can be used to cancel the operation. /// A task that represents the asynchronous operation. The task result contains the response from the Key Vault /// operation. private async Task PostOperation( Uri KeyId, string Operation, KeyVaultOperationRequest OperationRequest, CancellationToken CancellationToken ) { string requestUrl = $"{KeyId.ToString().TrimEnd('/')}/{Operation}?api-version={AzureClient.ApiVersion}"; using HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUrl); requestMessage.Content = CreateJsonContent(OperationRequest, AzureJsonContext.Default.KeyVaultOperationRequest); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken); using HttpResponseMessage responseMessage = await BuildHttpClient.SendWithRetry(this.HttpClient, requestMessage, CancellationToken); responseMessage.EnsureSuccessStatusCode(); Stream responseStream = await responseMessage.Content.ReadAsStreamAsync(CancellationToken); ArgumentNullException.ThrowIfNull(responseStream); KeyVaultOperationResponse keyVaultOperationResponse = await JsonSerializer.DeserializeAsync(responseStream, AzureJsonContext.Default.KeyVaultOperationResponse, CancellationToken); ArgumentNullException.ThrowIfNull(keyVaultOperationResponse); return keyVaultOperationResponse; } /// /// Sends a verify operation request to Azure Key Vault and returns the verification response. /// /// The URI of the Key Vault key to use for the verify operation. /// The request payload containing the parameters for the verify operation. /// A cancellation token that can be used to cancel the operation. /// A task that represents the asynchronous operation. The task result contains the response from the Key Vault /// verify operation. private async Task PostVerifyOperation( Uri KeyId, KeyVaultVerifyRequest OperationRequest, CancellationToken CancellationToken ) { string requestUrl = $"{KeyId.ToString().TrimEnd('/')}/verify?api-version={AzureClient.ApiVersion}"; using HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, requestUrl); requestMessage.Content = CreateJsonContent(OperationRequest, AzureJsonContext.Default.KeyVaultVerifyRequest); requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken); using HttpResponseMessage responseMessage = await BuildHttpClient.SendWithRetry(this.HttpClient, requestMessage, CancellationToken); responseMessage.EnsureSuccessStatusCode(); Stream responseStream = await responseMessage.Content.ReadAsStreamAsync(CancellationToken); ArgumentNullException.ThrowIfNull(responseStream); KeyVaultVerifyResponse keyVaultVerifyResponse = await JsonSerializer.DeserializeAsync(responseStream, AzureJsonContext.Default.KeyVaultVerifyResponse, CancellationToken); ArgumentNullException.ThrowIfNull(keyVaultVerifyResponse); return keyVaultVerifyResponse; } /// /// Sends an HTTP request using the specified method, URL, and content, and ensures a successful response status /// code. /// /// The request includes a bearer token for authorization. An exception is thrown if the /// response indicates an unsuccessful status code. /// The HTTP method to use for the request, such as GET or POST. /// The URL to which the HTTP request is sent. /// The HTTP content to include in the request body. Can be null for methods that do not send a body. /// A cancellation token that can be used to cancel the request operation. /// A task that represents the asynchronous send operation. private async Task Send( HttpMethod Method, string RequestUrl, HttpContent Content, CancellationToken CancellationToken ) { using HttpRequestMessage requestMessage = new HttpRequestMessage(Method, RequestUrl); requestMessage.Content = Content; requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken); using HttpResponseMessage responseMessage = await BuildHttpClient.SendWithRetry(this.HttpClient, requestMessage, CancellationToken); responseMessage.EnsureSuccessStatusCode(); } /// /// Sends an HTTP request with the specified method and content, and deserializes the JSON response to the /// specified type. /// /// The request includes a Bearer token for authorization. The method throws an exception /// if the HTTP response indicates failure or if deserialization fails. /// The type to which the JSON response will be deserialized. /// The HTTP method to use for the request, such as GET or POST. /// The URL to which the HTTP request is sent. /// The HTTP content to include in the request body. Can be null for methods that do not require a body. /// The metadata describing the type to use for deserializing the JSON response. /// A cancellation token that can be used to cancel the request. /// A task that represents the asynchronous operation. The task result contains the deserialized response of /// type TResponse. private async Task SendJson( HttpMethod Method, string RequestUrl, HttpContent Content, JsonTypeInfo ResponseTypeInfo, CancellationToken CancellationToken ) { using HttpRequestMessage requestMessage = new HttpRequestMessage(Method, RequestUrl); requestMessage.Content = Content; requestMessage.Headers.Authorization = new AuthenticationHeaderValue("Bearer", this.AccessToken); using HttpResponseMessage responseMessage = await BuildHttpClient.SendWithRetry(this.HttpClient, requestMessage, CancellationToken); responseMessage.EnsureSuccessStatusCode(); Stream responseStream = await responseMessage.Content.ReadAsStreamAsync(CancellationToken); ArgumentNullException.ThrowIfNull(responseStream); TResponse response = await JsonSerializer.DeserializeAsync(responseStream, ResponseTypeInfo, CancellationToken); ArgumentNullException.ThrowIfNull(response); return response; } /// /// Creates an HTTP content object containing the JSON representation of the specified request object. /// /// The type of the request object to serialize to JSON. /// The request object to serialize as JSON. Cannot be null. /// The metadata used to control JSON serialization for the request object. Cannot be null. /// An HttpContent instance that serializes the request object to the target stream as UTF-8 JSON. private static HttpContent CreateJsonContent( TRequest Request, JsonTypeInfo RequestTypeInfo ) { return new KeyVaultJsonContent(Request, RequestTypeInfo); } /// /// Constructs a request URL for accessing a vault resource, including the specified API version and optional /// maximum results parameter. /// /// The base URI of the vault service. Must not be null and should not include a trailing slash. /// The relative path to the specific vault resource to be accessed. /// The maximum number of results to request. If null, the parameter is omitted from the URL. /// A string containing the fully constructed request URL with the specified path, API version, and optional /// maximum results parameter. private static string CreateVaultRequestUrl(Uri VaultBaseUrl, string Path, int? MaxResults) { string requestUrl = $"{VaultBaseUrl.ToString().TrimEnd('/')}/{Path}?api-version={AzureClient.ApiVersion}"; if (MaxResults.HasValue) { requestUrl += $"&maxresults={MaxResults.Value}"; } return requestUrl; } /// /// Constructs a key request URL using the specified key identifier, path, and optional maximum results /// parameter. /// /// The resulting URL always includes the 'api-version=2025-07-01' query parameter. If /// is provided, the URL will also include a 'maxresults' query parameter with its /// value. /// The base URI representing the key identifier. Cannot be null. /// The relative path to append to the key identifier in the request URL. /// The optional maximum number of results to include in the request. If specified, adds a 'maxresults' query /// parameter to the URL. /// A string containing the constructed key request URL with the specified parameters. private static string CreateKeyRequestUrl(Uri KeyId, string Path, int? MaxResults) { string requestUrl = $"{KeyId.ToString().TrimEnd('/')}/{Path}?api-version={AzureClient.ApiVersion}"; if (MaxResults.HasValue) { requestUrl += $"&maxresults={MaxResults.Value}"; } return requestUrl; } /// /// Encodes the specified byte array into a Base64 URL-safe string without padding. /// /// This method produces a Base64-encoded string that is safe for use in URLs and /// filenames by replacing '+' with '-', '/' with '_', and omitting padding characters. The output conforms to /// RFC 4648, section 5. /// The byte array to encode as a Base64 URL-safe string. Cannot be null. /// A Base64 URL-safe encoded string representation of the input data, with padding characters removed. private static char[] Base64UrlEncode(byte[] Data) { int base64Length = ((Data.Length + 2) / 3) * 4; char[] base64Chars = new char[base64Length]; if (!Convert.TryToBase64Chars(Data, base64Chars, out int charsWritten)) { throw new InvalidOperationException("Unable to encode data as Base64."); } while (charsWritten != 0 && base64Chars[charsWritten - 1] == '=') { charsWritten--; } for (int i = 0; i < charsWritten; i++) { if (base64Chars[i] == '+') { base64Chars[i] = '-'; } else if (base64Chars[i] == '/') { base64Chars[i] = '_'; } } if (charsWritten != base64Chars.Length) { Array.Resize(ref base64Chars, charsWritten); } return base64Chars; } private static char[] Base64UrlEncodeOrNull(byte[] Data) { if (Data == null) { return null; } return Base64UrlEncode(Data); } /// /// Decodes a Base64URL-encoded string into its corresponding byte array. /// /// This method handles Base64URL encoding as defined in RFC 4648, Section 5, by /// converting URL-safe characters to standard Base64 and adding necessary padding. The input string must be a /// valid Base64URL-encoded value; otherwise, a FormatException may be thrown. /// The Base64URL-encoded string to decode. The string must use '-' and '_' in place of '+' and '/' and may omit /// padding characters. /// A byte array containing the decoded data represented by the input string. private static byte[] Base64UrlDecode(char[] Text) { int base64Length = Text.Length; switch (base64Length % 4) { case 2: base64Length += 2; break; case 3: base64Length++; break; } char[] base64Chars = new char[base64Length]; for (int i = 0; i < Text.Length; i++) { if (Text[i] == '-') { base64Chars[i] = '+'; } else if (Text[i] == '_') { base64Chars[i] = '/'; } else { base64Chars[i] = Text[i]; } } for (int i = Text.Length; i < base64Length; i++) { base64Chars[i] = '='; } return Convert.FromBase64CharArray(base64Chars, 0, base64Chars.Length); } } /// /// Converts character arrays representing base64url-encoded key material to and from JSON string values for use /// with Azure Key Vault integration. /// /// This converter enables secure handling of sensitive key material by using mutable character /// arrays instead of immutable strings, allowing callers to clear the contents after use and reduce the risk of /// leaving sensitive data in memory. It is intended for internal use when serializing or deserializing /// base64url-encoded secrets or keys in JSON payloads. internal sealed class KeyVaultBase64UrlCharArrayJsonConverter : JsonConverter { // Keep base64url key material in mutable char[] buffers instead of immutable strings // so callers can clear sensitive values and avoid leaving extra managed string copies. public override char[] Read(ref Utf8JsonReader Reader, Type TypeToConvert, JsonSerializerOptions Options) { if (Reader.TokenType == JsonTokenType.Null) { return null; } if (Reader.TokenType != JsonTokenType.String) { throw new JsonException(); } if (Reader.HasValueSequence) { return Reader.GetString()?.ToCharArray(); } char[] value = new char[Encoding.UTF8.GetCharCount(Reader.ValueSpan)]; Encoding.UTF8.GetChars(Reader.ValueSpan, value); return value; } /// /// Writes the specified character array value as a JSON string using the provided Utf8JsonWriter. /// /// The Utf8JsonWriter to which the value will be written. /// The character array to write as a JSON string. If null, a JSON null value is written. /// Options to control the behavior of the JSON serialization. public override void Write(Utf8JsonWriter Writer, char[] Value, JsonSerializerOptions Options) { if (Value == null) { Writer.WriteNullValue(); return; } Writer.WriteStringValue(Value); } } internal interface IKeyVaultSensitiveData { void ClearSensitiveData(); } /// /// Provides an HTTP content implementation for serializing a value of the specified type as JSON using a given /// serialization context. /// /// This class is intended for use with HTTP requests that require a JSON payload. It uses the /// provided JsonTypeInfo to control serialization behavior, enabling support for source-generated serializers and /// custom serialization options. /// The type of the value to serialize as JSON content. internal sealed class KeyVaultJsonContent : HttpContent { private readonly TValue Value; private readonly JsonTypeInfo TypeInfo; public KeyVaultJsonContent(TValue Value, JsonTypeInfo TypeInfo) { this.Value = Value; this.TypeInfo = TypeInfo; this.Headers.ContentType = new MediaTypeHeaderValue("application/json"); } protected override Task SerializeToStreamAsync(Stream Stream, TransportContext Context) { return JsonSerializer.SerializeAsync(Stream, this.Value, this.TypeInfo); } protected override Task SerializeToStreamAsync(Stream Stream, TransportContext Context, CancellationToken CancellationToken) { return JsonSerializer.SerializeAsync(Stream, this.Value, this.TypeInfo, CancellationToken); } protected override bool TryComputeLength(out long Length) { Length = -1; return false; } protected override void Dispose(bool Disposing) { if (Disposing && this.Value is IKeyVaultSensitiveData sensitiveData) { sensitiveData.ClearSensitiveData(); } base.Dispose(Disposing); } } /// /// Represents a minimal request payload for Azure Key Vault sign/decrypt operations. /// internal sealed class KeyVaultOperationRequest : IKeyVaultSensitiveData { [JsonPropertyName("alg")] public string Algorithm { get; set; } [JsonPropertyName("value")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] Value { get; set; } [JsonPropertyName("aad")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] AdditionalAuthenticatedData { get; set; } [JsonPropertyName("iv")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] InitializationVector { get; set; } [JsonPropertyName("tag")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] AuthenticationTag { get; set; } public void ClearSensitiveData() { CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.Value.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.AdditionalAuthenticatedData.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.InitializationVector.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.AuthenticationTag.AsSpan())); } } /// /// Represents a minimal request payload for Azure Key Vault verify operations. /// internal sealed class KeyVaultVerifyRequest : IKeyVaultSensitiveData { [JsonPropertyName("alg")] public string Algorithm { get; set; } [JsonPropertyName("digest")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] Digest { get; set; } [JsonPropertyName("signature")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] Signature { get; set; } public void ClearSensitiveData() { CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.Digest.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.Signature.AsSpan())); } } /// /// Represents a minimal response payload from Azure Key Vault verify operations. /// internal sealed class KeyVaultVerifyResponse { [JsonPropertyName("value")] public bool Value { get; set; } } /// /// Represents a Key Vault key response. /// internal sealed class KeyVaultKeyResponse { [JsonPropertyName("kid")] public string Kid { get; set; } [JsonPropertyName("key")] public KeyVaultJsonWebKey Key { get; set; } [JsonPropertyName("attributes")] public KeyVaultKeyAttributes Attributes { get; set; } [JsonPropertyName("tags")] public Dictionary Tags { get; set; } [JsonExtensionData] public Dictionary ExtensionData { get; set; } } /// /// Represents a paged Key Vault key list response. /// internal sealed class KeyVaultKeyListResponse { [JsonPropertyName("value")] public KeyVaultKeyResponse[] Value { get; set; } [JsonPropertyName("nextLink")] public string NextLink { get; set; } } /// /// Represents a JSON Web Key returned by Key Vault. /// internal sealed class KeyVaultJsonWebKey : IKeyVaultSensitiveData { [JsonPropertyName("kid")] public string Kid { get; set; } [JsonPropertyName("kty")] public string KeyType { get; set; } [JsonPropertyName("key_ops")] public string[] KeyOperations { get; set; } [JsonPropertyName("crv")] public string CurveName { get; set; } [JsonPropertyName("n")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] Modulus { get; set; } [JsonPropertyName("e")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] Exponent { get; set; } [JsonPropertyName("d")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] D { get; set; } [JsonPropertyName("dp")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] DP { get; set; } [JsonPropertyName("dq")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] DQ { get; set; } [JsonPropertyName("qi")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] QI { get; set; } [JsonPropertyName("p")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] P { get; set; } [JsonPropertyName("q")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] Q { get; set; } [JsonPropertyName("x")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] X { get; set; } [JsonPropertyName("y")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] Y { get; set; } [JsonPropertyName("k")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] K { get; set; } [JsonExtensionData] public Dictionary ExtensionData { get; set; } public void ClearSensitiveData() { CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.Modulus.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.Exponent.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.D.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.DP.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.DQ.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.QI.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.P.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.Q.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.X.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.Y.AsSpan())); CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.K.AsSpan())); } } /// /// Represents Key Vault key attributes. /// internal sealed class KeyVaultKeyAttributes { [JsonPropertyName("enabled")] public bool? Enabled { get; set; } [JsonPropertyName("nbf")] public long? NotBefore { get; set; } [JsonPropertyName("exp")] public long? Expires { get; set; } [JsonPropertyName("created")] public long? Created { get; set; } [JsonPropertyName("updated")] public long? Updated { get; set; } [JsonPropertyName("recoveryLevel")] public string RecoveryLevel { get; set; } [JsonPropertyName("recoverableDays")] public int? RecoverableDays { get; set; } [JsonPropertyName("exportable")] public bool? Exportable { get; set; } [JsonExtensionData] public Dictionary ExtensionData { get; set; } } /// /// Represents a Key Vault create key request. /// internal sealed class KeyVaultKeyCreateRequest { [JsonPropertyName("kty")] public string KeyType { get; set; } [JsonPropertyName("key_size")] public int? KeySize { get; set; } [JsonPropertyName("crv")] public string CurveName { get; set; } [JsonPropertyName("key_ops")] public string[] KeyOperations { get; set; } [JsonPropertyName("attributes")] public KeyVaultKeyAttributes Attributes { get; set; } [JsonPropertyName("tags")] public Dictionary Tags { get; set; } [JsonPropertyName("release_policy")] public KeyVaultKeyReleasePolicy ReleasePolicy { get; set; } } /// /// Represents a Key Vault import key request. /// internal sealed class KeyVaultKeyImportRequest : IKeyVaultSensitiveData { [JsonPropertyName("Hsm")] public bool? Hsm { get; set; } [JsonPropertyName("key")] public KeyVaultJsonWebKey Key { get; set; } [JsonPropertyName("attributes")] public KeyVaultKeyAttributes Attributes { get; set; } [JsonPropertyName("tags")] public Dictionary Tags { get; set; } [JsonPropertyName("release_policy")] public KeyVaultKeyReleasePolicy ReleasePolicy { get; set; } public void ClearSensitiveData() { this.Key?.ClearSensitiveData(); } } /// /// Represents a Key Vault update key request. /// internal sealed class KeyVaultKeyUpdateRequest { [JsonPropertyName("key_ops")] public string[] KeyOperations { get; set; } [JsonPropertyName("attributes")] public KeyVaultKeyAttributes Attributes { get; set; } [JsonPropertyName("tags")] public Dictionary Tags { get; set; } [JsonPropertyName("release_policy")] public KeyVaultKeyReleasePolicy ReleasePolicy { get; set; } } /// /// Represents a Key Vault key release policy. /// internal sealed class KeyVaultKeyReleasePolicy { [JsonPropertyName("contentType")] public string ContentType { get; set; } [JsonPropertyName("data")] public string Data { get; set; } [JsonExtensionData] public Dictionary ExtensionData { get; set; } } /// /// Represents a Key Vault backup response. /// internal sealed class KeyVaultBackupResponse : IKeyVaultSensitiveData { // Keep char[] buffers instead of string so callers can clear sensitive values. [JsonPropertyName("value")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] Value { get; set; } public void ClearSensitiveData() { CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.Value.AsSpan())); } } /// /// Represents a Key Vault restore request. /// internal sealed class KeyVaultRestoreRequest : IKeyVaultSensitiveData { // Keep char[] buffers instead of string so callers can clear sensitive values. [JsonPropertyName("value")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] Value { get; set; } public void ClearSensitiveData() { CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.Value.AsSpan())); } } /// /// Represents a Key Vault release key request. /// internal sealed class KeyVaultKeyReleaseRequest { [JsonPropertyName("target")] public string Target { get; set; } [JsonPropertyName("enc")] public string EncryptionAlgorithm { get; set; } [JsonPropertyName("nonce")] public string Nonce { get; set; } } /// /// Represents a Key Vault release key response. /// internal sealed class KeyVaultKeyReleaseResponse : IKeyVaultSensitiveData { [JsonPropertyName("value")] [JsonConverter(typeof(KeyVaultBase64UrlCharArrayJsonConverter))] public char[] Value { get; set; } public void ClearSensitiveData() { CryptographicOperations.ZeroMemory(MemoryMarshal.AsBytes(this.Value.AsSpan())); } } /// /// Represents a Key Vault key rotation policy. /// internal sealed class KeyVaultKeyRotationPolicy { [JsonPropertyName("id")] public string Id { get; set; } [JsonPropertyName("attributes")] public KeyVaultKeyRotationPolicyAttributes Attributes { get; set; } [JsonPropertyName("lifetimeActions")] public KeyVaultKeyLifetimeAction[] LifetimeActions { get; set; } } /// /// Represents Key Vault key rotation policy attributes. /// internal sealed class KeyVaultKeyRotationPolicyAttributes { [JsonPropertyName("expiryTime")] public string ExpiryTime { get; set; } [JsonPropertyName("created")] public long? Created { get; set; } [JsonPropertyName("updated")] public long? Updated { get; set; } } /// /// Represents a Key Vault key lifetime action. /// internal sealed class KeyVaultKeyLifetimeAction { [JsonPropertyName("trigger")] public KeyVaultKeyLifetimeActionTrigger Trigger { get; set; } [JsonPropertyName("action")] public KeyVaultKeyLifetimeActionType Action { get; set; } } /// /// Represents a Key Vault key lifetime action trigger. /// internal sealed class KeyVaultKeyLifetimeActionTrigger { [JsonPropertyName("timeAfterCreate")] public string TimeAfterCreate { get; set; } [JsonPropertyName("timeBeforeExpiry")] public string TimeBeforeExpiry { get; set; } } /// /// Represents a Key Vault key lifetime action type. /// internal sealed class KeyVaultKeyLifetimeActionType { [JsonPropertyName("type")] public string Type { get; set; } } }