NotNET中加密和解密的实现方法二
点击次数:23 次 发布日期:2008-11-27 02:17:44 作者:源代码网
|
源代码网推荐 使用私有密钥解密该文档,这是唯一可以解密的密钥,并且没有通过网络传递。 源代码网推荐 源代码网推荐 不对称算法比对称算法计算的花费多、速度慢。因此我们不希望在线对话中使用不对称算法加密所有信息。相反,我们使用对称算法。下面的例子中我们使用不对称加密来加密对称密钥。接着就使用对称算法加密了。实际上安全接口层(SSL)建立服务器和浏览器之间的安全对话使用的就是这种工作方式。 源代码网推荐 源代码网推荐 示例是一个TCP程序,分为服务器端和客户端。服务器端的工作流程是: 源代码网推荐 源代码网推荐 从客户端接收公共密钥。 源代码网推荐 源代码网推荐 使用公共密钥加密未来使用的对称密钥。 源代码网推荐 源代码网推荐 将加密了的对称密钥发送给客户端。 源代码网推荐 源代码网推荐 给客户端发送使用该对称密钥加密的信息。 源代码网推荐 源代码网推荐 代码如下: 源代码网推荐 源代码网推荐 namespace com.billdawson.crypto 源代码网推荐 { 源代码网推荐 public class CryptoServer 源代码网推荐 { 源代码网推荐 private const int RSA_KEY_SIZE_BITS = 1024; 源代码网推荐 private const int RSA_KEY_SIZE_BYTES = 252; 源代码网推荐 private const int TDES_KEY_SIZE_BITS = 192; 源代码网推荐 源代码网推荐 public static void Main(string[] args) 源代码网推荐 { 源代码网推荐 int port; 源代码网推荐 string msg; 源代码网推荐 TcpListener listener; 源代码网推荐 TcpClient client; 源代码网推荐 SymmetricAlgorithm symm; 源代码网推荐 RSACryptoServiceProvider rsa; 源代码网推荐 //获取端口 源代码网推荐 try 源代码网推荐 { 源代码网推荐 port = Int32.Parse(args[0]); 源代码网推荐 msg = args[1]; 源代码网推荐 } 源代码网推荐 catch 源代码网推荐 { 源代码网推荐 Console.WriteLine(USAGE); 源代码网推荐 return; 源代码网推荐 } 源代码网推荐 //建立监听 源代码网推荐 try 源代码网推荐 { 源代码网推荐 listener = new TcpListener(port); 源代码网推荐 listener.Start(); 源代码网推荐 Console.WriteLine("Listening on port {0}...",port); 源代码网推荐 源代码网推荐 client = listener.AcceptTcpClient(); 源代码网推荐 Console.WriteLine("connection...."); 源代码网推荐 } 源代码网推荐 catch (Exception e) 源代码网推荐 { 源代码网推荐 Console.WriteLine(e.Message); 源代码网推荐 Console.WriteLine(e.StackTrace); 源代码网推荐 return; 源代码网推荐 } 源代码网推荐 源代码网推荐 try 源代码网推荐 { 源代码网推荐 rsa = new RSACryptoServiceProvider(); 源代码网推荐 rsa.KeySize = RSA_KEY_SIZE_BITS; 源代码网推荐 源代码网推荐 // 获取客户端公共密钥 源代码网推荐 rsa.ImportParameters(getClientPublicKey(client)); 源代码网推荐 源代码网推荐 symm = new TripleDESCryptoServiceProvider(); 源代码网推荐 symm.KeySize = TDES_KEY_SIZE_BITS; 源代码网推荐 源代码网推荐 //使用客户端的公共密钥加密对称密钥并发送给客。 源代码网推荐 encryptAndSendSymmetricKey(client, rsa, symm); 源代码网推荐 源代码网推荐 //使用对称密钥加密信息并发送 源代码网推荐 encryptAndSendSecretMessage(client, symm, msg); 源代码网推荐 } 源代码网推荐 catch (Exception e) 源代码网推荐 { 源代码网推荐 Console.WriteLine(e.Message); 源代码网推荐 Console.WriteLine(e.StackTrace); 源代码网推荐 } 源代码网推荐 finally 源代码网推荐 { 源代码网推荐 try 源代码网推荐 { 源代码网推荐 client.Close(); 源代码网推荐 listener.Stop(); 源代码网推荐 } 源代码网推荐 catch 源代码网推荐 { 源代码网推荐 //错误 源代码网推荐 } 源代码网推荐 Console.WriteLine("Server exiting..."); 源代码网推荐 } 源代码网推荐 } 源代码网推荐 源代码网推荐 private static RSAParameters getClientPublicKey(TcpClient client) 源代码网推荐 { 源代码网推荐 // 从字节流获取串行化的公共密钥,通过串并转换写入类的实例 源代码网推荐 byte[] buffer = new byte[RSA_KEY_SIZE_BYTES]; 源代码网推荐 NetworkStream ns = client.GetStream(); 源代码网推荐 MemoryStream ms = new MemoryStream(); 源代码网推荐 BinaryFormatter bf = new BinaryFormatter(); 源代码网推荐 RSAParameters result; 源代码网推荐 源代码网推荐 int len = 0; 源代码网推荐 int totalLen = 0; 源代码网推荐 源代码网推荐 源代码网推荐 源代码网供稿. |
