1.  RSA加密与解密  --  使用公钥加密、私钥解密

    public class RSATool
    {
        public string Encrypt(string strText, string strPublicKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(strPublicKey);

            byte[] byteText = Encoding.UTF8.GetBytes(strText);
            byte[] byteEntry = rsa.Encrypt(byteText, false);

            return Convert.ToBase64String(byteEntry);
        }


        public string Decrypt(string strEntryText,string strPrivateKey)
        {
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(strPrivateKey);

            byte[] byteEntry = Convert.FromBase64String(strEntryText);
            byte[] byteText = rsa.Decrypt(byteEntry, false);

            return Encoding.UTF8.GetString(byteText);
        }

        public Dictionary<string,string> GetKey()
        {
            Dictionary<string, string> dictKey = new Dictionary<string, string>();
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

            dictKey.Add("PublicKey", rsa.ToXmlString(false));
            dictKey.Add("PrivateKey", rsa.ToXmlString(true));

            return dictKey;
        }
    }

测试:

            RSATool myRSA = new RSATool();
            Dictionary<string, string> dictK = new Dictionary<string, string>();
            dictK = myRSA.GetKey();

            string strText = "123456";
            Console.WriteLine("要加密的字符串是:{0}", strText);

            string str1 = myRSA.Encrypt("123456", dictK["PublicKey"]);
            Console.WriteLine("加密后的字符串:{0}", str1);

            string str2 = myRSA.Decrypt(str1, dictK["PrivateKey"]);
            Console.WriteLine("解密后的字符串:{0}", str2);
View Code

相关文章:

  • 2021-09-22
  • 2022-12-23
  • 2022-12-23
  • 2021-12-13
猜你喜欢
  • 2021-08-02
  • 2021-10-11
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-09-02
相关资源
相似解决方案