简体   繁体   中英

Using Azure Key Vault RSA Key to encrypt and decrypt strings

I have setup Azure Key Vault to retrieve RSA Keys for encryption. Azure send me an object of type KeyBundle. This object contains a JsonWebKey of type RSA of size 2048 . Looking at my RSA Key, it has 2 methods called Encrypt(byte[] data, RSAEncryptionPadding padding) and Decrypt(byte[] data, RSAEncryptionPadding padding) . Now I am trying to encrypt and decrypt a simple string like this:

public EncryptionManager(KeyBundle encryptionKey)
{
    string test = "Hello World!";
    var key = encryptionKey.Key.ToRSA();
    var encryptedString = key.Encrypt(Encoding.UTF8.GetBytes(test), RSAEncryptionPadding.OaepSHA256);
    var decryptedString = key.Decrypt(encryptedString, RSAEncryptionPadding.OaepSHA256);
}

Encryption works, but decryption throws an exception with message:

Key does not exist.

Here is the StackTrace

at System.Security.Cryptography.RSAImplementation.RSACng.EncryptOrDecrypt(SafeNCryptKeyHandle key, ReadOnlySpan`1 input, AsymmetricPaddingMode paddingMode, Void* paddingInfo, Boolean encrypt) at System.Security.Cryptography.RSAImplementation.RSACng.EncryptOrDecrypt(Byte[] data, RSAEncryptionPadding padding, Boolean encrypt) at System.Security.Cryptography.RSAImplementation.RSACng.Decrypt(Byte[] data, RSAEncryptionPadding padding) at NxtUtils.Security.EncryptionManager..ctor(KeyBundle encryptionKey) in C:\\Repos\\Enigma\\EnigmaPrototype\\SharedLibaries\\NxtUtils\\Security\\EncryptionManager.cs:line 26

I am really not familiar with cryptographic algorithms. My question is: How can I encrypt and decrypt a simple strig using this RSA Key provided by Azure?

Thanks!

ToRSA has a default boolean parameter indicating if the private key should be available, or not.

Since you didn't explicitly say true it is implicitly false , therefore your key object is public-only. With a public RSA key you can encrypt data or verify a signature, but you cannot sign or decrypt.

I got the same issue, what I did is here although I searched from internet and got this from the Microsoft docs

so this is my working code below

public static class KeyVaultEncryptorDecryptor
{
    public static string KeyDecryptText(this string textToDecrypt , KeyVaultClient keyVaultClient, string keyidentifier)
    {
        var kv = keyVaultClient;
        try
        {
            var key = kv.GetKeyAsync(keyidentifier).Result;
            var publicKey = Convert.ToBase64String(key.Key.N);
            using var rsa = new RSACryptoServiceProvider();
            var p = new RSAParameters() {
                Modulus = key.Key.N, Exponent = key.Key.E
            };
            rsa.ImportParameters(p);
            var encryptedTextNew = Convert.FromBase64String(textToDecrypt);
            var decryptedData = kv.DecryptAsync(key.KeyIdentifier.Identifier.ToString(), JsonWebKeyEncryptionAlgorithm.RSAOAEP, encryptedTextNew).GetAwaiter().GetResult();
            var decryptedText = Encoding.Unicode.GetString(decryptedData.Result);
            return decryptedText;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            return default;
        }
    }

    public static string KeyEncryptText(this string textToEncrypt , KeyVaultClient keyVaultClient, string keyidentifier)
    {
        var kv = keyVaultClient;
        try
        {
            var key = kv.GetKeyAsync(keyidentifier).GetAwaiter().GetResult();
            var publicKey = Convert.ToBase64String(key.Key.N);
            using var rsa = new RSACryptoServiceProvider();
            var p = new RSAParameters() {
                Modulus = key.Key.N, Exponent = key.Key.E
            };
            rsa.ImportParameters(p);
            var byteData = Encoding.Unicode.GetBytes(textToEncrypt);
            var encryptedText = rsa.Encrypt(byteData, true);
            string encText = Convert.ToBase64String(encryptedText);
            return encText;
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
            return default;
        }
    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM