/// <summary> /// Encrypts a single block of data. The amount of data that may be encrypted is determined /// by the target key type and the encryption algorithm. /// </summary> /// <param name="keyBundle">The key bundle to use for encryption</param> /// <param name="algorithm">The encryption algorithm. For more information on possible algorithm types, see JsonWebKeyEncryptionAlgorithm.</param> /// <param name="plaintext">The plain text to encrypt</param> /// <returns></returns> public static async Task<KeyOperationResult> EncryptDataAsync( this KeyVaultClient client, KeyBundle keyBundle, string algorithm, byte[] plaintext ) { if ( keyBundle == null ) throw new ArgumentNullException( "keyBundle" ); return await client.EncryptDataAsync( keyBundle.Key, algorithm, plaintext ).ConfigureAwait( false ); }
internal KeyVaultKey( KeyVaultClient client, KeyBundle keyBundle ) { switch ( keyBundle.Key.Kty ) { case JsonWebKeyType.Rsa: _implementation = new RsaKey( keyBundle.Key.Kid, keyBundle.Key.ToRSA() ); break; case JsonWebKeyType.RsaHsm: _implementation = new RsaKey( keyBundle.Key.Kid, keyBundle.Key.ToRSA() ); break; } if ( _implementation == null ) throw new ArgumentException( string.Format( CultureInfo.InvariantCulture, "The key type \"{0}\" is not supported", keyBundle.Key.Kty ) ); _client = client; }
public KeyBundle ImportKey(string vaultName, string keyName, KeyAttributes keyAttributes, JsonWebKey webKey, bool?importToHsm) { if (string.IsNullOrEmpty(vaultName)) { throw new ArgumentNullException("vaultName"); } if (string.IsNullOrEmpty(keyName)) { throw new ArgumentNullException("keyName"); } if (keyAttributes == null) { throw new ArgumentNullException("keyAttributes"); } if (webKey == null) { throw new ArgumentNullException("webKey"); } if (webKey.Kty == JsonWebKeyType.RsaHsm && (importToHsm.HasValue && !importToHsm.Value)) { throw new ArgumentException(KeyVaultProperties.Resources.ImportByokAsSoftkeyError); } string vaultAddress = this.vaultUriHelper.CreateVaultAddress(vaultName); webKey.KeyOps = keyAttributes.KeyOps; var keyBundle = new Microsoft.Azure.KeyVault.KeyBundle() { Attributes = (Microsoft.Azure.KeyVault.KeyAttributes)keyAttributes, Key = webKey, Tags = keyAttributes.TagsDirectionary }; try { keyBundle = this.keyVaultClient.ImportKeyAsync(vaultAddress, keyName, keyBundle, importToHsm).GetAwaiter().GetResult(); } catch (Exception ex) { throw GetInnerException(ex); } return(new KeyBundle(keyBundle, this.vaultUriHelper)); }
internal KeyVaultKey(KeyVaultClient client, KeyBundle keyBundle) { switch (keyBundle.Key.Kty) { case JsonWebKeyType.Rsa: _implementation = new RsaKey(keyBundle.Key.Kid, keyBundle.Key.ToRSA()); break; case JsonWebKeyType.RsaHsm: _implementation = new RsaKey(keyBundle.Key.Kid, keyBundle.Key.ToRSA()); break; } if (_implementation == null) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "The key type \"{0}\" is not supported", keyBundle.Key.Kty)); } _client = client; }
internal KeyBundle(Microsoft.Azure.KeyVault.KeyBundle keyBundle, VaultUriHelper vaultUriHelper) { if (keyBundle == null) { throw new ArgumentNullException("keyBundle"); } if (keyBundle.Key == null || keyBundle.Attributes == null) { throw new ArgumentException(KeyVaultProperties.Resources.InvalidKeyBundle); } SetObjectIdentifier(vaultUriHelper, keyBundle.KeyIdentifier); Key = keyBundle.Key; Attributes = new KeyAttributes( keyBundle.Attributes.Enabled, keyBundle.Attributes.Expires, keyBundle.Attributes.NotBefore, keyBundle.Key.Kty, keyBundle.Key.KeyOps, keyBundle.Attributes.Created, keyBundle.Attributes.Updated, keyBundle.Tags); }
/// <summary> /// Wraps a symmetric key and then unwrapps the wrapped key /// </summary> /// <param name="keyId"> a global key identifier of the key to get </param> private static void WrapUnwrap(KeyBundle key) { KeyOperationResult wrappedKey; var algorithm = inputValidator.GetEncryptionAlgorithm(); byte[] symmetricKey = inputValidator.GetSymmetricKey(); string keyVersion = inputValidator.GetKeyVersion(); if (keyVersion != string.Empty) { var vaultAddress = inputValidator.GetVaultAddress(); string keyName = inputValidator.GetKeyName(true); wrappedKey = keyVaultClient.WrapKeyAsync(vaultAddress, keyName, keyVersion, algorithm, symmetricKey).GetAwaiter().GetResult(); } else { // If the key ID is not initialized get the key id from args var keyId = (key != null) ? key.Key.Kid : inputValidator.GetKeyId(); // Wrap the symmetric key wrappedKey = keyVaultClient.WrapKeyAsync(keyId, algorithm, symmetricKey).GetAwaiter().GetResult(); } Console.Out.WriteLine(string.Format("The symmetric key is wrapped using key id {0} and algorithm {1}", wrappedKey.Kid, algorithm)); // Unwrap the symmetric key var unwrappedKey = keyVaultClient.UnwrapKeyAsync(wrappedKey.Kid, algorithm, wrappedKey.Result).GetAwaiter().GetResult(); Console.Out.WriteLine(string.Format("The unwrapped key is{0}the same as the original key!", symmetricKey.SequenceEqual(unwrappedKey.Result) ? " " : " not ")); }
/// <summary> /// Created the specified key /// </summary> /// <param name="keyBundle"> key bundle to create </param> /// <returns> created key bundle </returns> private static KeyBundle CreateKey(KeyBundle keyBundle, out string keyName) { // Get key bundle which is needed for creating a key keyBundle = keyBundle ?? inputValidator.GetKeyBundle(); var vaultAddress = inputValidator.GetVaultAddress(); keyName = inputValidator.GetKeyName(); var tags = inputValidator.GetTags(); // Create key in the KeyVault key vault var createdKey = keyVaultClient.CreateKeyAsync(vaultAddress, keyName, keyBundle.Key.Kty, keyAttributes: keyBundle.Attributes, tags: tags).GetAwaiter().GetResult(); Console.Out.WriteLine("Created key:---------------"); PrintoutKey(createdKey); // Store the created key for the next operation if we have a sequence of operations return createdKey; }
/// <summary> /// Gets the specified key /// </summary> /// <param name="keyId"> a global key identifier of the key to get </param> /// <returns> retrieved key bundle </returns> private static KeyBundle GetKey(KeyBundle key) { KeyBundle retrievedKey; string keyVersion = inputValidator.GetKeyVersion(); string keyName = inputValidator.GetKeyName(allowDefault: false); if (keyVersion != string.Empty || keyName != string.Empty) { var vaultAddress = inputValidator.GetVaultAddress(); if (keyVersion != string.Empty) { keyName = inputValidator.GetKeyName(true); retrievedKey = keyVaultClient.GetKeyAsync(vaultAddress, keyName, keyVersion).GetAwaiter().GetResult(); } else { retrievedKey = keyVaultClient.GetKeyAsync(vaultAddress, keyName).GetAwaiter().GetResult(); } } else { // If the key is not initialized get the key id from args var keyId = (key != null) ? key.Key.Kid : inputValidator.GetKeyId(); // Get the key using its ID retrievedKey = keyVaultClient.GetKeyAsync(keyId).GetAwaiter().GetResult(); } Console.Out.WriteLine("Retrived key:---------------"); PrintoutKey(retrievedKey); //store the created key for the next operation if we have a sequence of operations return retrievedKey; }
/// <summary> /// Imports a key into the specified vault /// </summary> /// <param name="vaultBaseUrl">The vault name, e.g. https://myvault.vault.azure.net</param> /// <param name="keyName">The key name</param> /// <param name="keyBundle"> Key bundle </param> /// <param name="importToHardware">Whether to import as a hardware key (HSM) or software key </param> /// <param name="cancellationToken">Optional cancellation token</param> /// <returns> Imported key bundle to the vault </returns> public static async Task <KeyBundle> ImportKeyAsync(this IKeyVaultClient operations, string vaultBaseUrl, string keyName, KeyBundle keyBundle, bool?importToHardware = null, CancellationToken cancellationToken = default(CancellationToken)) { if (string.IsNullOrEmpty(vaultBaseUrl)) { throw new ArgumentNullException(nameof(vaultBaseUrl)); } if (string.IsNullOrEmpty(keyName)) { throw new ArgumentNullException(nameof(keyName)); } if (keyBundle == null) { throw new ArgumentNullException(nameof(keyBundle)); } using (var _result = await operations.ImportKeyWithHttpMessagesAsync(vaultBaseUrl, keyName, keyBundle.Key, importToHardware, keyBundle.Attributes, keyBundle.Tags, null, cancellationToken).ConfigureAwait(false)) { return(_result.Body); } }
/// <summary> /// Encrypts a plain text and then decrypts the encrypted text /// </summary> /// <param name="keyId"> a global key identifier of the key to get </param> private static void EncryptDecrypt(KeyBundle key) { KeyOperationResult operationResult; var algorithm = inputValidator.GetEncryptionAlgorithm(); var plainText = inputValidator.GetPlainText(); string keyVersion = inputValidator.GetKeyVersion(); if (keyVersion != string.Empty) { var vaultAddress = inputValidator.GetVaultAddress(); string keyName = inputValidator.GetKeyName(true); // Encrypt the input data using the specified algorithm operationResult = keyVaultClient.EncryptAsync(vaultAddress, keyName, keyVersion, algorithm, plainText).GetAwaiter().GetResult(); } else { // If the key is not initialized get the key id from args var keyId = (key != null) ? key.Key.Kid : inputValidator.GetKeyId(); // Encrypt the input data using the specified algorithm operationResult = keyVaultClient.EncryptAsync(keyId, algorithm, plainText).GetAwaiter().GetResult(); } Console.Out.WriteLine(string.Format("The text is encrypted using key id {0} and algorithm {1}", operationResult.Kid, algorithm)); // Decrypt the encrypted data var decryptedText = keyVaultClient.DecryptAsync(operationResult.Kid, algorithm, operationResult.Result).GetAwaiter().GetResult(); Console.Out.WriteLine(string.Format("The decrypted text is {0}the same as the original key!", plainText.SequenceEqual(decryptedText.Result) ? "" : "not ")); Console.Out.WriteLine(string.Format("The decrypted text is {0}", Encoding.UTF8.GetString(decryptedText.Result))); }
/// <summary> /// Encrypts plaintext /// </summary> /// <param name="key"> key to use for the encryption </param> private static void Encrypt(KeyBundle key) { KeyOperationResult operationResult; var algorithm = inputValidator.GetEncryptionAlgorithm(); var plainText = inputValidator.GetPlainText(); string keyVersion = inputValidator.GetKeyVersion(); operationResult = _encrypt(key, keyVersion, algorithm, plainText); File.WriteAllText("cipherText.txt", Convert.ToBase64String(operationResult.Result)); Console.Out.WriteLine(string.Format("The text is encrypted using key id {0} and algorithm {1}", operationResult.Kid, algorithm)); Console.Out.WriteLine(string.Format("Encrypted text, base-64 encoded: {0}", Convert.ToBase64String(operationResult.Result))); }
/// <summary> /// Wraps a symmetric key using the specified wrapping key and algorithm. /// </summary> /// <param name="wrappingKey">The wrapping key</param> /// <param name="key">The key to wrap</param> /// <param name="algorithm">The algorithm to use. For more information on possible algorithm types, see JsonWebKeyEncryptionAlgorithm.</param> /// <returns>The wrapped key</returns> public static async Task<KeyOperationResult> WrapKeyAsync( this KeyVaultClient client, KeyBundle wrappingKey, byte[] key, string algorithm ) { if ( wrappingKey == null ) throw new ArgumentNullException( "keyBundle" ); return await client.WrapKeyAsync( wrappingKey.Key, key, algorithm ).ConfigureAwait( false ); }
/// <summary> /// Verifies a signature using the specified key. /// </summary> /// <param name="verifyKey">The verification key</param> /// <param name="algorithm">The signing algorithm. For more information on possible algorithm types, see JsonWebKeyEncryptionAlgorithm.</param> /// <param name="digest">The digest hash value</param> /// <param name="signature">The signature to verify</param> /// <returns>True if verification succeeds, false if verification fails</returns> public static async Task<bool> VerifyAsync( this KeyVaultClient client, KeyBundle verifyKey, string algorithm, byte[] digest, byte[] signature ) { return await client.VerifyAsync( verifyKey.Key, algorithm, digest, signature ).ConfigureAwait( false ); }
/// <summary> /// Encrypts a single block of data. The amount of data that may be encrypted is determined /// by the target key type and the encryption algorithm, e.g. RSA, RSA_OAEP /// </summary> /// <param name="keyBundle">The key bundle to use for encryption</param> /// <param name="algorithm">The encryption algorithm</param> /// <param name="plaintext">The plain text to encrypt</param> /// <returns></returns> public static async Task <KeyOperationResult> EncryptDataAsync(this KeyVaultClient client, KeyBundle keyBundle, string algorithm, byte[] plaintext) { if (keyBundle == null) { throw new ArgumentNullException("keyBundle"); } return(await client.EncryptDataAsync(keyBundle.Key, algorithm, plaintext).ConfigureAwait(false)); }
/// <summary> /// Wraps a symmetric key using the specified wrapping key and algorithm. /// </summary> /// <param name="wrappingKey">The wrapping key</param> /// <param name="key">The key to wrap</param> /// <param name="algorithm">The algorithm to use</param> /// <returns>The wrapped key</returns> public static async Task <KeyOperationResult> WrapKeyAsync(this KeyVaultClient client, KeyBundle wrappingKey, byte[] key, string algorithm) { if (wrappingKey == null) { throw new ArgumentNullException("keyBundle"); } return(await client.WrapKeyAsync(wrappingKey.Key, key, algorithm).ConfigureAwait(false)); }
/// <summary> /// Verifies a signature using the specified key /// </summary> /// <param name="verifyKey">The verification key</param> /// <param name="algorithm">The signing algorithm</param> /// <param name="digest">The digest hash value</param> /// <param name="signature">The signature to verify</param> /// <returns>true if verification succeeds, false if verification fails</returns> public static async Task <bool> VerifyAsync(this KeyVaultClient client, KeyBundle verifyKey, string algorithm, byte[] digest, byte[] signature) { return(await client.VerifyAsync(verifyKey.Key, algorithm, digest, signature).ConfigureAwait(false)); }
/// <summary> /// Encrypts a plain text and then decrypts the encrypted text /// </summary> /// <param name="key"> key to use for the encryption & decryption operations </param> private static void EncryptDecrypt(KeyBundle key) { KeyOperationResult operationResult; var algorithm = inputValidator.GetEncryptionAlgorithm(); var plainText = inputValidator.GetPlainText(); string keyVersion = inputValidator.GetKeyVersion(); operationResult = _encrypt(key, keyVersion, algorithm, plainText); Console.Out.WriteLine(string.Format("The text is encrypted using key id {0} and algorithm {1}", operationResult.Kid, algorithm)); // Decrypt the encrypted data var decryptedText = keyVaultClient.DecryptAsync(operationResult.Kid, algorithm, operationResult.Result).GetAwaiter().GetResult(); Console.Out.WriteLine(string.Format("The decrypted text is{0}the same as the original key!", plainText.SequenceEqual(decryptedText.Result) ? " " : " not ")); Console.Out.WriteLine(string.Format("The decrypted text is: {0}", Encoding.UTF8.GetString(decryptedText.Result))); }
private static KeyOperationResult _encrypt(KeyBundle key, string keyVersion, string algorithm, byte[] plainText) { KeyOperationResult operationResult; if (keyVersion != string.Empty) { var vaultAddress = inputValidator.GetVaultAddress(); string keyName = inputValidator.GetKeyName(true); // Encrypt the input data using the specified algorithm operationResult = keyVaultClient.EncryptAsync(vaultAddress, keyName, keyVersion, algorithm, plainText).GetAwaiter().GetResult(); } else { // If the key is not initialized get the key id from args var keyId = (key != null) ? key.Key.Kid : inputValidator.GetKeyId(); // Encrypt the input data using the specified algorithm operationResult = keyVaultClient.EncryptAsync(keyId, algorithm, plainText).GetAwaiter().GetResult(); } return operationResult; }
/// <summary> /// Signs a hash and then verifies the signature /// </summary> /// <param name="keyId"> a global key identifier of the key to get </param> private static void SignVerify(KeyBundle key) { KeyOperationResult signature; var algorithm = inputValidator.GetSignAlgorithm(); var digest = inputValidator.GetDigestHash(); string keyVersion = inputValidator.GetKeyVersion(); if (keyVersion != string.Empty) { var vaultAddress = inputValidator.GetVaultAddress(); string keyName = inputValidator.GetKeyName(true); signature = keyVaultClient.SignAsync(vaultAddress, keyName, keyVersion, algorithm, digest).GetAwaiter().GetResult(); } else { // If the key is not initialized get the key id from args var keyId = (key != null) ? key.Key.Kid : inputValidator.GetKeyId(); // Create a signature signature = keyVaultClient.SignAsync(keyId, algorithm, digest).GetAwaiter().GetResult(); } Console.Out.WriteLine(string.Format("The signature is created using key id {0} and algorithm {1} ", signature.Kid, algorithm)); // Verify the signature bool isVerified = keyVaultClient.VerifyAsync(signature.Kid, algorithm, digest, signature.Result).GetAwaiter().GetResult(); Console.Out.WriteLine(string.Format("The signature is {0} verified!", isVerified ? "" : "not ")); }
/// <summary> /// Decrypts cipherText /// </summary> /// <param name="key"> key to use for the decryption </param> private static void Decrypt(KeyBundle key) { KeyOperationResult operationResult; var algorithm = inputValidator.GetEncryptionAlgorithm(); var cipherText = inputValidator.GetCipherText(); KeyBundle localKey; localKey = (key ?? GetKey(null)); // Decrypt the encrypted data operationResult = keyVaultClient.DecryptAsync(localKey.KeyIdentifier.ToString(), algorithm, cipherText).GetAwaiter().GetResult(); Console.Out.WriteLine(string.Format("The decrypted text is: {0}", Encoding.UTF8.GetString(operationResult.Result))); }
public KeyBundle ImportKey(string vaultName, string keyName, KeyAttributes keyAttributes, JsonWebKey webKey, bool? importToHsm) { if (string.IsNullOrEmpty(vaultName)) throw new ArgumentNullException("vaultName"); if (string.IsNullOrEmpty(keyName)) throw new ArgumentNullException("keyName"); if (keyAttributes == null) throw new ArgumentNullException("keyAttributes"); if (webKey == null) throw new ArgumentNullException("webKey"); if (webKey.Kty == JsonWebKeyType.RsaHsm && (importToHsm.HasValue && !importToHsm.Value)) throw new ArgumentException(KeyVaultProperties.Resources.ImportByokAsSoftkeyError); string vaultAddress = this.vaultUriHelper.CreateVaultAddress(vaultName); webKey.KeyOps = keyAttributes.KeyOps; var keyBundle = new Microsoft.Azure.KeyVault.KeyBundle() { Attributes = (Microsoft.Azure.KeyVault.KeyAttributes)keyAttributes, Key = webKey, Tags = keyAttributes.TagsDirectionary }; try { keyBundle = this.keyVaultClient.ImportKeyAsync(vaultAddress, keyName, keyBundle, importToHsm).GetAwaiter().GetResult(); } catch (Exception ex) { throw GetInnerException(ex); } return new KeyBundle(keyBundle, this.vaultUriHelper); }
/// <summary> /// Prints out key bundle values /// </summary> /// <param name="keyBundle"> key bundle </param> private static void PrintoutKey(KeyBundle keyBundle) { Console.Out.WriteLine("Key: \n\tKey ID: {0}\n\tKey type: {1}", keyBundle.Key.Kid, keyBundle.Key.Kty); var expiryDateStr = keyBundle.Attributes.Expires.HasValue ? keyBundle.Attributes.Expires.ToString() : "Never"; var notBeforeStr = keyBundle.Attributes.NotBefore.HasValue ? keyBundle.Attributes.NotBefore.ToString() : UnixEpoch.EpochDate.ToString(); Console.Out.WriteLine("Key attributes: \n\tIs the key enabled: {0}\n\tExpiry date: {1}\n\tEnable date: {2}", keyBundle.Attributes.Enabled, expiryDateStr, notBeforeStr); }
public async Task<KeyBundle> CreateKey(string keyName, KeyBundle keyBundle, Dictionary<string, string> tags) { return await keyVaultClient.CreateKeyAsync(keyVaultUri, keyName, keyBundle.Key.Kty, keyAttributes: keyBundle.Attributes, tags: tags); }