我有两个包含 RSA 私钥和 RSA 公钥的 AsymmetryAlgorithm 对象。私钥是从 Windows-MY 密钥库中检索的,公钥是从用户的证书中检索的。如何在 C# 中将这些密钥与 RSACryptoServiceProvider 一起使用 RSA 算法来加密数据?换句话说,我如何指定我想要使用我已经拥有的密钥?
#region "RSA Encrypt/Decrypt"
public string RSAEncrypt(string str, string publicKey)
{
//---Creates a new instance of RSACryptoServiceProvider---
try {
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//---Loads the public key---
RSA.FromXmlString(publicKey);
byte[] EncryptedStr = null;
//---Encrypts the string---
EncryptedStr = RSA.Encrypt(ASCII.GetBytes(str), false);
//---Converts the encrypted byte array to string---
int i = 0;
System.Text.StringBuilder s = new System.Text.StringBuilder();
for (i = 0; i <= EncryptedStr.Length - 1; i++) {
//Console.WriteLine(EncryptedStr(i))
if (i != EncryptedStr.Length - 1) {
s.Append(EncryptedStr[i] + " ");
} else {
s.Append(EncryptedStr[i]);
}
}
return s.ToString();
} catch (Exception err) {
Interaction.MsgBox(err.ToString());
}
}
public string RSADecrypt(string str, string privateKey)
{
try {
//---Creates a new instance of RSACryptoServiceProvider---
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//---Loads the private key---
RSA.FromXmlString(privateKey);
//---Decrypts the string---
byte[] DecryptedStr = RSA.Decrypt(HexToByteArr(str), false);
//---Converts the decrypted byte array to string---
System.Text.StringBuilder s = new System.Text.StringBuilder();
int i = 0;
for (i = 0; i <= DecryptedStr.Length - 1; i++) {
//Console.WriteLine(DecryptedStr(i))
s.Append(System.Convert.ToChar(DecryptedStr[i]));
}
//Console.WriteLine(s)
return s.ToString();
} catch (Exception err) {
Interaction.MsgBox(err.ToString());
}
}
#endregion
公钥 (arg) 应如下所示:
yNi8BvATA77f+/6cU6z[...]9VULgU=模数>
AQAB指数>
密钥值>
私钥 (arg) 应如下所示:
yNi8BvATA77f+/6cU6z[...]9VULgU=模数>
AQAB指数>
8ZlZPmko3sam9pvD/l[...]ba0MWLjj9dyUMvmTQ6L8m9IQ==
1NGHjXyEa9SjUwY[...]v+op2YyyglMeK/Gt5SL0v6xqQZQ==
LpjE/aSKnWzzBt1E[...]i5f63Ak9wVG3ZPnwVDwefNkMAQ==
qAgb8AGNiJom[...]8x3qaD3wx+UbnM5v3aE5Q==
fQ4+7r3Nmgvz113L[...]uJqEgCNzw==
B4n7JNeGHzHe/nqEK[...]GaOBtuz0QTgE=
密钥值>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)