Caio Silva
Caio Silva

Reputation: 11

Using Key by Azure Key Vault to Encrypt and Decrypt text

I'm trying use a key from Azure Key Vault to Encrypt and Decrypt the cookies of a web API.

To encryption proccess I'm using the RSA, in that class:

    public class SimpleRSA
    {
        private RSA _rsa;

        public SimpleRSA(RSA rsa)
        {
            _rsa = rsa;
        }

        public string EncryptAsync(string value)
        {
            var byteData = Encoding.Unicode.GetBytes(value);
            var encryptedText = _rsa.Encrypt(byteData, RSAEncryptionPadding.OaepSHA1);
            var encodedText = Convert.ToBase64String(encryptedText);
            return encodedText;
        }


        public string DecryptAsync(string encryptedText)
        {
            var encryptedBytes = Convert.FromBase64String(encryptedText);
            var decryptionResult = _rsa.Decrypt(encryptedBytes, RSAEncryptionPadding.OaepSHA1);
            var decryptedText = Encoding.Unicode.GetString(decryptionResult);
            return decryptedText;
        }
    }

And I'm getting my RSA from the Key, using that code:

  public RSA GetRSA(string appId, string appSecret)
        {
            AuthenticationCallback callback = async (authority, resource, scope) =>
            {
                var authContext = new AuthenticationContext(authority);

                var credential = new ClientCredential(appId, appSecret);
                var authResult = await authContext.AcquireTokenAsync(resource, credential);
                return authResult.AccessToken;
            };

            var client = new KeyVaultClient(callback);

            var result = client.GetKeyAsync(_vaultBaseUrl, _keyId).Result;
            var key = result.Key;

            return key.ToRSA();
        }

I got the RSA from my Azure Key Vault and I managed encrypt my string. The problem is when I'm trying Decrypt the value. In that process I got that error:

System.Security.Cryptography.CryptographicException: 'Error decoding OAEP padding.'

I think that can be happening because I'm without the private keys in RSA, but I've tried use this method to get the RSA with private key::

key.ToRSA(true);

enter image description here

But a got that error:

enter image description here

So, I don't know how I can complete this process. Are there other way to do that? Or what's wrong?

Upvotes: 0

Views: 10463

Answers (2)

MichaelHoward-MSFT
MichaelHoward-MSFT

Reputation: 319

Key Vault can store three item types: Keys, Secrets and Certificates. Keys are always asymmetric - RSA or Elliptic Curve, and the private keys don't leave KV. What you need is to use a symmetric key, but you need to store that as a Secret, not a key.

So store a 256-bit random secret in KV, call it MyCoolCryptoKey, pull that symmetric key into your C# code and use that as a key for AES.

Upvotes: 5

Jim Xu
Jim Xu

Reputation: 23111

If you want to use Azure Key Vault to Encrypt and Decrypt text, you can use SDK Azure.Security.KeyVault.Keys to implement it.

For example

  1. Install SDK
Install-Package Azure.Security.KeyVault.Keys -Version 4.0.3
Install-Package Azure.Identity -Version 1.1.1
  1. Code
          ClientSecretCredential clientSecretCredential = new ClientSecretCredential(tenantId, // your tenant id
                           clientId, // your AD application appId
                           clientSecret // your AD application app secret
                       );

            //get key
            var KeyVaultName = "<your kay vault name>";
            KeyClient keyClient = new KeyClient(new Uri($"https://{KeyVaultName}.vault.azure.net/"), clientSecretCredential);;
            var keyName="<your key name>"
            var key = await keyClient.GetKeyAsync(keyName);

            // create CryptographyClient
            CryptographyClient cryptoClient = new CryptographyClient(key.Value.Id, clientSecretCredential);

            var str ="test"
            Console.WriteLine("The String used to be encrypted is :  " +str );

            Console.WriteLine("-------------encrypt---------------");
            var byteData = Encoding.Unicode.GetBytes(str);
            var encryptResult = await cryptoClient.EncryptAsync(EncryptionAlgorithm.RsaOaep, byteData);
            var encodedText = Convert.ToBase64String(encryptResult.Ciphertext);
            Console.WriteLine(encodedText);

            Console.WriteLine("-------------dencrypt---------------");
            var encryptedBytes = Convert.FromBase64String(encodedText);
            var dencryptResult = await cryptoClient.DecryptAsync(EncryptionAlgorithm.RsaOaep, encryptedBytes);
            var decryptedText = Encoding.Unicode.GetString(dencryptResult.Plaintext);
            Console.WriteLine(decryptedText);

enter image description here

Upvotes: 8

Related Questions