我已设置Azure密钥保管库以检索RSA密钥以进行加密。 Azure向我发送了一个KeyBundle类型的对象。该对象包含类型为 RSA大小为的RSA JsonWebKey。查看我的RSA密钥,它有2种方法,分别称为Encrypt(byte[] data, RSAEncryptionPadding padding)
和Decrypt(byte[] data, RSAEncryptionPadding padding)
。现在,我正在尝试加密和解密像这样的简单字符串:
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);
}
加密有效,但是解密会引发异常消息:
键不存在。
这是StackTrace
在System.Security.Cryptography.RSAImplementation.RSACng.EncryptOrDecrypt(SafeNCryptKeyHandle 键,ReadOnlySpan`1输入,AsymmetricPaddingMode paddingMode,无效* paddingInfo,布尔加密) System.Security.Cryptography.RSAImplementation.RSACng.EncryptOrDecrypt(Byte [] 数据,RSAEncryptionPadding填充,布尔加密) System.Security.Cryptography.RSAImplementation.RSACng.Decrypt(Byte [] 数据,RSAEncryptionPadding填充) NxtUtils.Security.EncryptionManager..ctor(KeyBundle encryptionKey)在 C:\ Repos \ Enigma \ EnigmaPrototype \ SharedLibaries \ NxtUtils \ Security \ EncryptionManager.cs:line 26
我真的不熟悉加密算法。我的问题是:如何使用Azure提供的RSA密钥加密和解密简单的strig?
谢谢!
答案 0 :(得分:0)
ToRSA有一个默认的布尔参数,指示私钥是否应该可用。
由于您没有明确说出true
,所以它隐含了false
,因此您的密钥对象是仅公开的。使用公共RSA密钥,您可以加密数据或验证签名,但不能签名或解密。
答案 1 :(得分:0)
我遇到了同样的问题,尽管我从互联网上搜索并从Microsoft文档中获得了此信息
这是我下面的工作代码
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;
}
}
}