关于加密:在RSA C#中使用AsymmetricAlgorithm私钥和公钥

Using AsymmetricAlgorithm Private and Public key with RSA C#

我有两个包含RSA私钥和RSA公钥的非对称算法对象。从Windows我的密钥库和用户证书中检索到私钥。如何将这些密钥与rsacryptoseServiceProvider一起使用c中的rsa算法加密数据?换句话说,我如何指定我要使用已经拥有的密钥?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#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)应如下所示:< RSAKEYVALY >yni8bvata77f+/6cu6z[…]9vulgu=aqab

私钥(arg)应如下所示:< RSAKEYVALY >yni8bvata77f+/6cu6z[…]9vulgu=aqab

8ZLZPMKO3SAM9PVD/L[…]BA0MWLJ9DYUMVMTQ6L8M9IQ==

1nghjxyea9sjuwy[…]v+op2yyyglmek/gt5sl0v6xqqzq==lpje/asknwzzbt1e[…]i5f63ak9wvg3zpnwvdwfnkmaq==qagb8agnijom[…]8x3qad3wx+ubnm5v3ae5q==fq4+7r3nmgvz113l[…]ujqegcnzw===b4n7jneghzhe/nqek[…]gaobtuzz0qtage=