private void test1() { //服务端生成好一对 公私钥 RSACryptoServiceProvider rsaServer = new RSACryptoServiceProvider(); //公钥给客户端,用来加密数据(内置,或第一次请求时下行给客户端) string clientPublicKey = rsaServer.ToXmlString(false); //私钥存在服务端,用来解密数据 string serverPrivateKey = rsaServer.ToXmlString(true); //客户端也生成一对 公私钥 RSACryptoServiceProvider rsaClient = new RSACryptoServiceProvider(); //公钥加密后上行给服务端,用来加密数据 string serverPublicKey = rsaClient.ToXmlString(false); //私钥存在客户端,用来解密下行数据 string clientPrivateKey = rsaClient.ToXmlString(true); //客户端请求登录 生成上行数据 string username = "******"; string password = "******"; login upPost = new login() { username = RSAManaged3.Encrypt(username, clientPublicKey), password = RSAManaged3.Encrypt(password, clientPublicKey), key = RSAManaged3.Encrypt(serverPublicKey, clientPublicKey), }; Console.WriteLine("上行数据:" + upPost.ToJson()); //服务端解密 生成下行数据 //解密 login userInfo = new login() { username = RSAManaged3.Decrypt(upPost.username, serverPrivateKey), password = RSAManaged3.Decrypt(upPost.password, serverPrivateKey), key = RSAManaged3.Decrypt(upPost.key, serverPrivateKey), }; Console.WriteLine("上行数据解密:" + userInfo.ToJson()); //生成下行告诉客户断是否登录成功 login downPost = new login() { username = RSAManaged3.Encrypt(userInfo.username, userInfo.key), message = RSAManaged3.Encrypt((username == "test01" && password == "111111") ? "登录成功!" : "登录失败", userInfo.key), }; Console.WriteLine("下行数据:" + downPost.ToJson()); //客户端取的下行数据,并解密 userInfo = new login() { username = RSAManaged3.Decrypt(downPost.username, clientPrivateKey), message = RSAManaged3.Decrypt(downPost.message, clientPrivateKey), }; Console.WriteLine("下行数据解密:" + userInfo.ToJson()); Console.WriteLine(userInfo.username); Console.WriteLine(userInfo.message); Console.WriteLine(); }
private void PublicKeyEncrypt(string input, RSAPublicKey _publicKey, RSAPrivateKey _privateKey) { byte[] inputData = Encoding.UTF8.GetBytes(input); DateTime d1 = DateTime.Now; byte[] inputDateEnc = RSAManaged3.Encrypt(inputData, _publicKey); TimeSpan t1 = DateTime.Now - d1; Console.WriteLine("公钥加密用时:{0}", t1); DateTime d2 = DateTime.Now; byte[] inputDataDec = RSAManaged3.Decrypt(inputDateEnc, _privateKey); TimeSpan t2 = DateTime.Now - d2; Console.WriteLine("私钥解密用时:{0}", t2); string inputDec = Encoding.UTF8.GetString(inputDataDec, 0, inputDataDec.Length); Console.WriteLine(string.Format("私钥解密结果:{0}", inputDec)); Console.WriteLine(); }