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 static async Task <IActionResult> Run( [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); string name = req.Query["name"]; //var credential = new ClientSecretCredential("231dd9cd-ddc7-4fba-ae78-9f4ac3c912e7", "5f43fe5c-1c2b-4afa-97e6-fda41302e28b", "5ZlLakKHA:DE.6Jq-GbJWF=icJaCwW32"); var credential = new ManagedIdentityCredential(); var kvUri = "https://kvswapana.vault.azure.net/"; var secretClient = new SecretClient(new Uri(kvUri), credential); var encryptedDEK = secretClient.GetSecret("DEK"); var keyClient = new KeyClient(new Uri(kvUri), credential); var encryptedKEY = keyClient.GetKey("KEK"); var cryptoClient = new CryptographyClient(encryptedKEY.Value.Id, credential); DecryptResult decryptDek = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep256, Convert.FromBase64String(encryptedDEK.Value.Value)); string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); dynamic data = JsonConvert.DeserializeObject(requestBody); name = name ?? data?.name; return(name != null // Create MemoryStream ? (ActionResult) new OkObjectResult($"Hello, {name}, {encryptedKEY.Value.Id}, {Encoding.UTF8.GetString(decryptDek.Plaintext)}") : new BadRequestObjectResult("Please pass a name on the query string or in the request body")); }
internal byte[] DecryptData(byte[] cipherText, RSAEncryptionPadding padding) { var algorithm = EncryptionPaddingTranslator.EncryptionPaddingToJwsAlgId(padding); var dataResult = cryptographyClient.Decrypt(algorithm, cipherText); return(dataResult.Plaintext); }
public override void Run(CancellationToken cancellationToken) { DecryptResult result = CryptographyClient.Decrypt(s_algorithm, _ciphertext); byte[] plaintext = result.Plaintext; #if DEBUG Assert.AreEqual(_plaintext, plaintext); #endif }
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 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 string Decode(string value) { if (string.IsNullOrEmpty(value)) { throw new ArgumentException("Value cannot be null or empty.", nameof(value)); } byte[] encryptedByteArray = Convert.FromBase64String(value); DecryptResult decryptResult = _cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptedByteArray); return(Encoding.Default.GetString(decryptResult.Plaintext)); }
static void Main(string[] args) { var credential = new InteractiveBrowserCredential(); var kvUri = "[key vault uri]"; var client = new KeyClient(new Uri(kvUri), credential); var key = client.GetKey("[kek key name]"); var cryptoClient = new CryptographyClient(key.Value.Id, credential); var secretClient = new SecretClient(new Uri(kvUri), credential); var encryptedDEK = secretClient.GetSecret("[dek key name]"); DecryptResult decryptDek = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep256, Convert.FromBase64String(encryptedDEK.Value.Value)); var keynew = decryptDek.Plaintext[0..16];
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); }
private PSKeyOperationResult Decrypt(CryptographyClient cryptographyClient, EncryptionAlgorithm keyEncryptAlgorithm, byte[] value) { return(new PSKeyOperationResult(cryptographyClient.Decrypt(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); }