C# RSA加密解密

来源:互联网 发布:性能测试 知乎 编辑:程序博客网 时间:2024/05/22 11:47
using System;using System.Collections.Generic;using System.Linq;using System.Security.Cryptography;using System.Text;using System.Threading.Tasks;namespace ConsoleApplication2{    class RSACryption    {        static void Main(string[] args)        {            //产生一对公钥,私钥            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();            string xmlKeys = rsa.ToXmlString(true);   //私钥            string xmlPublicKey = rsa.ToXmlString(false);   //公钥            string EncryptString = RSAEncrypt(xmlPublicKey, "1223345611");            Console.WriteLine(EncryptString);            Console.WriteLine("------------------------------------");            string DecryptString = RSADecrypt(xmlKeys, EncryptString);            Console.WriteLine(DecryptString);            Console.ReadKey();        }        /// <summary>        /// RSA的加密函数        /// </summary>        /// <param name="xmlPublicKey">公钥</param>        /// <param name="encryptString">待加密的字符串</param>        /// <returns></returns>        public static string RSAEncrypt(string xmlPublicKey, string encryptString)        {            try            {                byte[] PlainTextBArray;                byte[] CypherTextBArray;                string Result;                RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();                rsa.FromXmlString(xmlPublicKey);                PlainTextBArray = (new UnicodeEncoding()).GetBytes(encryptString);                CypherTextBArray = rsa.Encrypt(PlainTextBArray, false);                Result = Convert.ToBase64String(CypherTextBArray);                return Result;            }            catch (Exception ex)            {                throw ex;            }        }        /// <summary>        /// RSA的解密函数        /// </summary>        /// <param name="xmlPrivateKey">私钥</param>        /// <param name="decryptString">待解密的字符串</param>        /// <returns></returns>        public static string RSADecrypt(string xmlPrivateKey, string decryptString)        {            try            {                byte[] PlainTextBArray;                byte[] DypherTextBArray;                string Result;                System.Security.Cryptography.RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();                rsa.FromXmlString(xmlPrivateKey);                PlainTextBArray = Convert.FromBase64String(decryptString);                DypherTextBArray = rsa.Decrypt(PlainTextBArray, false);                Result = (new UnicodeEncoding()).GetString(DypherTextBArray);                return Result;            }            catch (Exception ex)            {                throw ex;            }        }    }}
0 0
原创粉丝点击