.NET生成RSA公钥和私钥-加密解密示例

我们每一个人的一生中都会难免有缺憾和不如意,也许我们无力改变这个事实,而我们可以改变的只是看待这些事情的态度。用平和的态度去对待生活中的缺憾和苦难。


Form1.cs代码:

  public partial class Form1 : Form
    {
        private const int RsaKeySize = 2048;
        private const string publicKeyFileName = "RSA.Pub";
        private const string privateKeyFileName = "RSA.Private";

        private string basePathToStoreKeys;

        public Form1()
        {
            InitializeComponent();

            basePathToStoreKeys = Directory.GetCurrentDirectory();
        }

        //生成密钥
        private void button1_Click(object sender, EventArgs e)
        {
            GenerateKeys(basePathToStoreKeys);
        }

        //加密文本框内容
        private void button2_Click(object sender, EventArgs e)
        {
            var encryptedString = Encrypt(textBox1.Text, Path.Combine(basePathToStoreKeys, publicKeyFileName));

            textBox2.Text = encryptedString;
        }

        //解密文本框内容
        private void button3_Click(object sender, EventArgs e)
        {
            var decryptedString = Decrypt(textBox2.Text, Path.Combine(basePathToStoreKeys, privateKeyFileName));

            textBox2.Text = decryptedString;
        }

        /// 
        ///在给定路径中生成XML格式的私钥和公钥。
        /// 
        public void GenerateKeys(string path)
        {
            using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
            {
                try
                {
                    // 获取私钥和公钥。
                    var publicKey = rsa.ToXmlString(false);
                    var privateKey = rsa.ToXmlString(true);

                    // 保存到磁盘
                    File.WriteAllText(Path.Combine(path, publicKeyFileName), publicKey);
                    File.WriteAllText(Path.Combine(path, privateKeyFileName), privateKey);

                    MessageBox.Show(string.Format("生成的RSA密钥的路径: {0}\\ [{1}, {2}]", path, publicKeyFileName, privateKeyFileName));
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }

        /// 
        /// 用给定路径的RSA公钥文件加密纯文本。
        /// 
        /// 要加密的文本
        /// 用于加密的公钥路径.
        /// 表示加密数据的64位编码字符串.
        public string Encrypt(string plainText, string pathToPublicKey)
        {
            using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
            {
                try
                {
                    //加载公钥
                    var publicXmlKey = File.ReadAllText(pathToPublicKey);
                    rsa.FromXmlString(publicXmlKey);

                    var bytesToEncrypt = System.Text.Encoding.Unicode.GetBytes(plainText);

                    var bytesEncrypted = rsa.Encrypt(bytesToEncrypt, false);

                    return Convert.ToBase64String(bytesEncrypted);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }

        /// 
        /// Decrypts encrypted text given a RSA private key file path.给定路径的RSA私钥文件解密 加密文本
        /// 
        /// 加密的密文
        /// 用于加密的私钥路径.
        /// 未加密数据的字符串
        public string Decrypt(string encryptedText, string pathToPrivateKey)
        {
            using (var rsa = new RSACryptoServiceProvider(RsaKeySize))
            {
                try
                {
                    var privateXmlKey = File.ReadAllText(pathToPrivateKey);
                    rsa.FromXmlString(privateXmlKey);

                    var bytesEncrypted = Convert.FromBase64String(encryptedText);

                    var bytesPlainText = rsa.Decrypt(bytesEncrypted, false);

                    return System.Text.Encoding.Unicode.GetString(bytesPlainText);
                }
                finally
                {
                    rsa.PersistKeyInCsp = false;
                }
            }
        }
    }

生成的RSA.Private的内容:



<RSAKeyValue>
  <Modulus>veJTjzABfYl9/9YbOOw+EcfIZ1jajWiGPAXW+G/2uIUYh9L9WSyLPghl3oMZM2GDxp9f+chdc0k9lrNbJwsIaereleTiOcl2u/rq+jS8r2WhTfk8bIMWeAO/B5S0IjIbmKXdymRNZFw/KjuY99HdYk6nB1MZ1AJ/e3xJKwWJrXp55Y4DlX9sGTORS9kcy1q4fuxjJHUFAYsasV/vnsjlaau4sp6xBcDIfT1tRkxMZriDPW3J7qH7/qI2X4+iQZQIfAyFpSlqi+4GI9FajogEareCS7d1vc+OYdGc+jX1h0erHsRtlvFHzLcqBmZQ0Gz0XdZxOwJf5vhxUvvoK9BmBw==Modulus>
  <Exponent>AQABExponent>
  <P>9Dq9A5cVGeBKib4WNSUBQqp25J4p0IUX1foc+zrX6/ZuSgDeXxIKiFmQPcl9R2RTwXQxFYWSkGW4gQis+AMnQJL98kHJXnG2FAiEsEhY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wrGBU6IKqmgrMwgqHKMuSSuJ65UoHYp3RTG+ECmtAHTe7YBBNnjOo8QSCEtdUpSdfKtT5YjVJhOwQ==D>
RSAKeyValue>

生成的RSA.Pub的内容:



<RSAKeyValue>
  <Modulus>veJTjzABfYl9/9YbOOw+EcfIZ1jajWiGPAXW+G/2uIUYh9L9WSyLPghl3oMZM2GDxp9f+chdc0k9lrNbJwsIaereleTiOcl2u/rq+jS8r2WhTfk8bIMWeAO/B5S0IjIbmKXdymRNZFw/KjuY99HdYk6nB1MZ1AJ/e3xJKwWJrXp55Y4DlX9sGTORS9kcy1q4fuxjJHUFAYsasV/vnsjlaau4sp6xBcDIfT1tRkxMZriDPW3J7qH7/qI2X4+iQZQIfAyFpSlqi+4GI9FajogEareCS7d1vc+OYdGc+jX1h0erHsRtlvFHzLcqBmZQ0Gz0XdZxOwJf5vhxUvvoK9BmBw==Modulus>
  <Exponent>AQABExponent>
RSAKeyValue>

运行结果如图:

.NET生成RSA公钥和私钥-加密解密示例_第1张图片


.NET生成RSA公钥和私钥-加密解密示例_第2张图片

你可能感兴趣的:(.NET,Winform,加密解密)