Azure Key Vault -检索用于本地加密的RSA公钥



我正试图使用我已经在Azure密钥库上生成的RSA密钥,以以下方式:

  1. 检索公钥
  2. 用它加密一些文本数据(-local -)
  3. 使用Azure密钥库
  4. 解密它(在不同的应用程序中)

我已经做到的是:

string clientId = "XYZ";
string tenantId = "ABC";
string clientSecret = "123";
string keyVaultName = "kvn";
string keyVaultKeyName = "kvkn";
string textToEncrypt = "StuffIDoNotWantYouToKnow";
ClientSecretCredential clientSecretCredential = new ClientSecretCredential(
tenantId, // your tenant id
clientId, // your AD application appId
clientSecret // your AD application app secret
);

//get key
KeyClient keyClient = new KeyClient(new Uri($"https://{keyVaultName}.vault.azure.net/"), clientSecretCredential); ;
var key = keyClient.GetKey(keyVaultKeyName);

我目前正在努力理解的是如何使用检索到的密钥加密文本数据。

任何帮助将不胜感激!

p。S我使用。net framework 4.6.1

解决了

private static string clientId;
private static string tenantId;
private static string clientSecret;
private static string keyVaultName;
private static string keyVaultKeyName;
private static ClientSecretCredential clientSecretCredential;
public static void Main(string[] args)
{
PopulateParams();
KeyClient keyClient = new KeyClient(new Uri($"https://{keyVaultName}.vault.azure.net/"), clientSecretCredential); ;
var key = keyClient.GetKey(keyVaultKeyName);
byte[] N = key.Value.Key.N; //modulus
byte[] E = key.Value.Key.E; //exponent
string textToEncrypt = "StuffIDoNotWantYouToKnow";
byte[] encryptedData = EncryptLocally(textToEncrypt, N, E);
string res = DecryptRemotely(key.Value.Id, encryptedData);
Console.WriteLine(res);
}
public static void PopulateParams()
{
//TODO not hard coded
clientId = "XYZ";
tenantId = "ABC";
clientSecret = "123";
keyVaultName = "kvm";
keyVaultKeyName = "kvkm";
clientSecretCredential = new ClientSecretCredential(
tenantId,
clientId,
clientSecret
);
}
public static byte[] EncryptLocally(string data, byte[] N, byte[] E)
{
byte[] encryptedData = null;
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
RSAParameters RSAKeyInfo = new RSAParameters();
//Set RSAKeyInfo to the public key values. 
RSAKeyInfo.Modulus = N;
RSAKeyInfo.Exponent = E;
RSA.ImportParameters(RSAKeyInfo);
byte[] dataBytes = Encoding.ASCII.GetBytes(data);
encryptedData = RSA.Encrypt(dataBytes, true);
}
catch (CryptographicException e)
{
Console.WriteLine(e);
}
return encryptedData;
}
public static string DecryptRemotely(Uri keyId, byte[] encryptedData)
{
string decryptedText = null;
CryptographyClient cryptoClient = new CryptographyClient(keyId, clientSecretCredential);
var decryptedBytes = cryptoClient.Decrypt(EncryptionAlgorithm.RsaOaep, encryptedData);
decryptedText = System.Text.Encoding.UTF8.GetString(decryptedBytes.Plaintext);
return decryptedText;
}

最新更新