RSA的加解密过程--(转自CSDN,学习用)

ContractedBlock.gif ExpandedBlockStart.gif RSA的加解密过程
None.gif public void StartDemo()
ExpandedBlockStart.gifContractedBlock.gif 
dot.gif{
InBlock.gif  
//RSA的加解密过程:
InBlock.gif  
//  有 rsa1 和 rsa2 两个RSA对象。
InBlock.gif  
//  现在要 rsa2 发送一段信息给 rsa1, 则先由 rsa1 发送“公钥”给 rsa2
InBlock.gif  
//  rsa2 获取得公钥之后,用来加密要发送的数据内容。
InBlock.gif  
//  rsa1 获取加密后的内容后,用自己的私钥解密,得出原始的数据内容。
InBlock.gif

InBlock.gif  RSACryptoServiceProvider rsa1 
= new RSACryptoServiceProvider();
InBlock.gif  RSACryptoServiceProvider rsa2 
= new RSACryptoServiceProvider();
InBlock.gif
InBlock.gif  
string publickey;
InBlock.gif  publickey
=rsa1.ToXmlString(false);  //导出 rsa1 的公钥
InBlock.gif

InBlock.gif  
string plaintext;
InBlock.gif  plaintext
="你好吗?这是用于测试的字符串。";  //原始数据
InBlock.gif
  Console.WriteLine("原始数据是:\n{0}\n",plaintext);
InBlock.gif
InBlock.gif  rsa2.FromXmlString(publickey); 
//rsa2 导入 rsa1 的公钥,用于加密信息
InBlock.gif
InBlock.gif  
//rsa2开始加密
InBlock.gif
  byte[] cipherbytes;
InBlock.gif  cipherbytes
=rsa2.Encrypt(
InBlock.gif   Encoding.UTF8.GetBytes(plaintext),
InBlock.gif   
false);
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif  
/**//*//*/
InBlock.gif  Console.WriteLine(
"加密后的数据是:");
InBlock.gif  
for(int i=0; i< cipherbytes.Length; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif  
dot.gif{
InBlock.gif   Console.Write(
"{0:X2} ",cipherbytes[i]);
ExpandedSubBlockEnd.gif  }

InBlock.gif  Console.WriteLine(
"\n");
ExpandedSubBlockStart.gifContractedSubBlock.gif  
/**//*//*/
InBlock.gif
InBlock.gif  
//rsa1开始解密
InBlock.gif
  byte[] plaintbytes;
InBlock.gif  plaintbytes 
= rsa1.Decrypt(cipherbytes,false);
InBlock.gif
InBlock.gif  Console.WriteLine(
"解密后的数据是:");
InBlock.gif  Console.WriteLine(Encoding.UTF8.GetString(plaintbytes));
InBlock.gif
InBlock.gif  Console.ReadLine();
ExpandedBlockEnd.gif }

None.gif
None.gif}

转载于:https://www.cnblogs.com/hanguoji/archive/2006/12/04/581173.html

你可能感兴趣的:(RSA的加解密过程--(转自CSDN,学习用))