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 = RSAManaged2.Encrypt(username, clientPublicKey), password = RSAManaged2.Encrypt(password, clientPublicKey), key = RSAManaged2.Encrypt(serverPublicKey, clientPublicKey), }; Console.WriteLine("上行数据:" + upPost.ToJson()); //服务端解密 生成下行数据 //解密 login userInfo = new login() { username = RSAManaged2.Decrypt(upPost.username, serverPrivateKey), password = RSAManaged2.Decrypt(upPost.password, serverPrivateKey), key = RSAManaged2.Decrypt(upPost.key, serverPrivateKey), }; Console.WriteLine("上行数据解密:" + userInfo.ToJson()); //生成下行告诉客户断是否登录成功 login downPost = new login() { username = RSAManaged2.Encrypt(userInfo.username, userInfo.key), message = RSAManaged2.Encrypt((username == "test01" && password == "111111") ? "登录成功!" : "登录失败", userInfo.key), }; Console.WriteLine("下行数据:" + downPost.ToJson()); //客户端取的下行数据,并解密 userInfo = new login() { username = RSAManaged2.Decrypt(downPost.username, clientPrivateKey), message = RSAManaged2.Decrypt(downPost.message, clientPrivateKey), }; Console.WriteLine("下行数据解密:" + userInfo.ToJson()); Console.WriteLine(userInfo.username); Console.WriteLine(userInfo.message); Console.WriteLine(); }
private void PublicKeySign(string input, RSAPublicKey _publicKey, RSAPrivateKey _privateKey) { byte[] inputData = Encoding.UTF8.GetBytes(input); SHA1Managed sha1 = new SHA1Managed(); DateTime d1 = DateTime.Now; byte[] signature = RSAManaged2.Sign(inputData, _publicKey, sha1); TimeSpan t1 = DateTime.Now - d1; Console.WriteLine("公钥签名用时:{0}", t1); DateTime d2 = DateTime.Now; bool result = RSAManaged2.Verify(inputData, _privateKey, sha1, signature); TimeSpan t2 = DateTime.Now - d2; Console.WriteLine("私钥验证用时:{0}", t2); sha1.Clear(); Console.WriteLine(string.Format("私钥验证结果:{0}", result)); Console.WriteLine(); }
private void PublicKeyEncrypt(string input, RSAPublicKey _publicKey, RSAPrivateKey _privateKey) { byte[] inputData = Encoding.UTF8.GetBytes(input); DateTime d1 = DateTime.Now; byte[] inputDateEnc = RSAManaged2.Encrypt(inputData, _publicKey); TimeSpan t1 = DateTime.Now - d1; Console.WriteLine("公钥加密用时:{0}", t1); DateTime d2 = DateTime.Now; byte[] inputDataDec = RSAManaged2.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(); }