Using Azure Key Vault RSA Key to encrypt and decrypt strings

回眸只為那壹抹淺笑 提交于 2020-02-06 08:30:32

问题


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!


回答1:


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.




回答2:


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;
        }
    }

}



来源:https://stackoverflow.com/questions/51103490/using-azure-key-vault-rsa-key-to-encrypt-and-decrypt-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!