static void Main(string[] args) { string keyVaultUrl = "https://demovault2090.vault.azure.net/"; var client = new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential()); // Getting the Encryption key from the key vault KeyVaultKey key = client.GetKey("newkey"); var cryptoClient = new CryptographyClient(keyId: key.Id, credential: new DefaultAzureCredential()); byte[] plaintext = Encoding.UTF8.GetBytes("This is sensitive data"); // Encrypting data EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep256, plaintext); //Decrypting data DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep256, encryptResult.Ciphertext); Console.WriteLine("Plain text"); string txt = Encoding.UTF8.GetString(decryptResult.Plaintext); Console.WriteLine(txt); Console.ReadLine(); }
public void EncryptDecryptSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); // Instantiate a key client that will be used to create a key. Notice that the client is using default Azure // credentials. To make default credentials work, ensure that environment variables 'AZURE_CLIENT_ID', // 'AZURE_CLIENT_KEY' and 'AZURE_TENANT_ID' are set with the service principal credentials. var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); // Let's create a RSA key which will be used to encrypt and decrypt string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, }; KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); // Let's create the CryptographyClient which can perform cryptographic operations with the key we just created. // Again we are using the default Azure credential as above. var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential()); // Next we'll encrypt some arbitrary plain text with the key using the CryptographyClient. Note that RSA encryption // algorithms have no chaining so they can only encrypt a single block of plaintext securely. For RSAOAEP this can be // calculated as (keysize / 8) - 42, or in our case (2048 / 8) - 42 = 214 bytes. byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext"); // First encrypt the data using RSAOAEP with the created key. EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext); Debug.WriteLine($"Encrypted data using the algorithm {encryptResult.Algorithm}, with key {encryptResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(encryptResult.Ciphertext)}"); // Now decrypt the encrypted data. Note that the same algorithm must always be used for both encrypt and decrypt DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext); Debug.WriteLine($"Decrypted data using the algorithm {decryptResult.Algorithm}, with key {decryptResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(decryptResult.Plaintext)}"); // The Cloud RSA Key is no longer needed, need to delete it from the Key Vault. DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName); // To ensure the key is deleted on server before we try to purge it. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); }
public void EncryptDecrypt() { #region Snippet:EncryptDecrypt byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext"); // encrypt the data using the algorithm RSAOAEP EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext); // decrypt the encrypted data. DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext); #endregion }
public string Encode(string value) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Value cannot be null or empty.", nameof(value)); } byte[] valueByteArray = Encoding.UTF8.GetBytes(value); EncryptResult encryptResult = _cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, valueByteArray); return(Convert.ToBase64String(encryptResult.Ciphertext)); }
public void OctEncryptDecryptSync() { TestEnvironment.AssertManagedHsm(); string managedHsmUrl = TestEnvironment.ManagedHsmUrl; #region Snippet:OctKeysSample4CreateKey var managedHsmClient = new KeyClient(new Uri(managedHsmUrl), new DefaultAzureCredential()); var octKeyOptions = new CreateOctKeyOptions($"CloudOctKey-{Guid.NewGuid()}") { KeySize = 256, }; KeyVaultKey cloudOctKey = managedHsmClient.CreateOctKey(octKeyOptions); #endregion #region Snippet:OctKeySample4Encrypt var cryptoClient = new CryptographyClient(cloudOctKey.Id, new DefaultAzureCredential()); byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext"); byte[] aad = Encoding.UTF8.GetBytes("additional authenticated data"); EncryptParameters encryptParams = EncryptParameters.A256GcmParameters(plaintext, aad); EncryptResult encryptResult = cryptoClient.Encrypt(encryptParams); #endregion #region Snippet:OctKeySample4Decrypt DecryptParameters decryptParams = DecryptParameters.A256GcmParameters( encryptResult.Ciphertext, encryptResult.Iv, encryptResult.AuthenticationTag, encryptResult.AdditionalAuthenticatedData); DecryptResult decryptResult = cryptoClient.Decrypt(decryptParams); #endregion Assert.AreEqual(plaintext, decryptResult.Plaintext); // Delete and purge the key. DeleteKeyOperation operation = managedHsmClient.StartDeleteKey(octKeyOptions.Name); // You only need to wait for completion if you want to purge or recover the key. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } managedHsmClient.PurgeDeletedKey(operation.Value.Name); }
public void EncryptDecryptSync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = Environment.GetEnvironmentVariable("AZURE_KEYVAULT_URL"); #region Snippet:KeysSample4KeyClient var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample4CreateKey // Let's create a RSA key which will be used to encrypt and decrypt string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, }; KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); #endregion #region Snippet:KeysSample4CryptographyClient var cryptoClient = new CryptographyClient(cloudRsaKey.Id, new DefaultAzureCredential()); #endregion #region Snippet:KeysSample4EncryptKey byte[] plaintext = Encoding.UTF8.GetBytes("A single block of plaintext"); EncryptResult encryptResult = cryptoClient.Encrypt(EncryptionAlgorithm.RsaOaep, plaintext); Debug.WriteLine($"Encrypted data using the algorithm {encryptResult.Algorithm}, with key {encryptResult.KeyId}. The resulting encrypted data is {Convert.ToBase64String(encryptResult.Ciphertext)}"); #endregion #region Snippet:KeysSample4DecryptKey DecryptResult decryptResult = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptResult.Ciphertext); Debug.WriteLine($"Decrypted data using the algorithm {decryptResult.Algorithm}, with key {decryptResult.KeyId}. The resulting decrypted data is {Encoding.UTF8.GetString(decryptResult.Plaintext)}"); #endregion #region Snippet:KeysSample4DeleteKey DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName); // You only need to wait for completion if you want to purge or recover the key. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } #endregion // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); }
static void Main(string[] args) { Console.WriteLine("Read from keyvault"); // Setup in Azure: // -> Create a Service Principal in Azure AD using Azure CLI // az ad sp create-for-rbac -n {keyvaultname} --skip-assignemtn // The above generates a result that should be set an environment variables // appId = AZURE_CLIENT_ID // password = AZURE_CLIENT_SECRET // tenant = AZURE_TENANT_ID // Set access policy on KeyVault // az keyvault set-policy --name {keyvaultname} --spn "{appId from above}" --secret-permissions get list delete (etc, etc) var keyVaultUrl = "https://trainingvaultdrb.vault.azure.net/"; // DefaultAzureCredentials will get the settings from above from the environment variables var secretClient = new SecretClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential()); // Get a Secret KeyVaultSecret secret = secretClient.GetSecret("apppwd"); Console.WriteLine($"{secret.Name}, {secret.Value}"); // Get a Key var keyClient = new KeyClient(vaultUri: new Uri(keyVaultUrl), credential: new DefaultAzureCredential()); KeyVaultKey key = keyClient.GetKey("drbenckey"); // Encrypts using the key - these are Azure libraries var cyptoClient = new CryptographyClient(key.Id, credential: new DefaultAzureCredential()); byte[] plaintext = Encoding.UTF8.GetBytes("text to encrypt"); EncryptResult result = cyptoClient.Encrypt(EncryptionAlgorithm.RsaOaep256, plaintext); Console.WriteLine(Encoding.UTF8.GetString(result.Ciphertext)); }
private PSKeyOperationResult Encrypt(CryptographyClient cryptographyClient, EncryptionAlgorithm keyEncryptAlgorithm, byte[] value) { return(new PSKeyOperationResult(cryptographyClient.Encrypt(keyEncryptAlgorithm, value))); }
public void SerializeJsonWebKeySync() { // Environment variable with the Key Vault endpoint. string keyVaultUrl = TestEnvironment.KeyVaultUrl; #region Snippet:KeysSample7KeyClient var keyClient = new KeyClient(new Uri(keyVaultUrl), new DefaultAzureCredential()); #endregion #region Snippet:KeysSample7CreateKey string rsaKeyName = $"CloudRsaKey-{Guid.NewGuid()}"; var rsaKey = new CreateRsaKeyOptions(rsaKeyName, hardwareProtected: false) { KeySize = 2048, }; KeyVaultKey cloudRsaKey = keyClient.CreateRsaKey(rsaKey); Debug.WriteLine($"Key is returned with name {cloudRsaKey.Name} and type {cloudRsaKey.KeyType}"); #endregion string dir = Path.Combine(TestContext.CurrentContext.WorkDirectory, "samples", nameof(Sample7_SerializeJsonWebKey)); Directory.CreateDirectory(dir); string path = Path.Combine(dir, $"{nameof(SerializeJsonWebKeySync)}.json"); // Use `using` expression for clean sample, but scope it to close and dispose immediately. { #region Snippet:KeysSample7Serialize using FileStream file = File.Create(path); using (Utf8JsonWriter writer = new Utf8JsonWriter(file)) { JsonSerializer.Serialize(writer, cloudRsaKey.Key); } Debug.WriteLine($"Saved JWK to {path}"); #endregion } #region Snippet:KeysSamples7Deserialize byte[] buffer = File.ReadAllBytes(path); JsonWebKey jwk = JsonSerializer.Deserialize <JsonWebKey>(buffer); Debug.WriteLine($"Read JWK from {path} with ID {jwk.Id}"); #endregion string content = "plaintext"; #region Snippet:KeysSample7Encrypt var encryptClient = new CryptographyClient(jwk); byte[] plaintext = Encoding.UTF8.GetBytes(content); EncryptResult encrypted = encryptClient.Encrypt(EncryptParameters.RsaOaepParameters(plaintext)); Debug.WriteLine($"Encrypted: {Encoding.UTF8.GetString(plaintext)}"); #endregion byte[] ciphertext = encrypted.Ciphertext; #region Snippet:KeysSample7Decrypt CryptographyClient decryptClient = keyClient.GetCryptographyClient(cloudRsaKey.Name, cloudRsaKey.Properties.Version); DecryptResult decrypted = decryptClient.Decrypt(DecryptParameters.RsaOaepParameters(ciphertext)); Debug.WriteLine($"Decrypted: {Encoding.UTF8.GetString(decrypted.Plaintext)}"); #endregion DeleteKeyOperation operation = keyClient.StartDeleteKey(rsaKeyName); // You only need to wait for completion if you want to purge or recover the key. while (!operation.HasCompleted) { Thread.Sleep(2000); operation.UpdateStatus(); } // If the keyvault is soft-delete enabled, then for permanent deletion, deleted key needs to be purged. keyClient.PurgeDeletedKey(rsaKeyName); }