代码改变世界

C# 中如何用 RSA 加密算法 API 来加密和解密

2012-05-22 18:22  音乐让我说  阅读(841)  评论(0编辑  收藏  举报

直接贴代码了:

using System;
using System.Security.Cryptography;

namespace DearBruce.ConAppTest
{
    class Program
    {
        static void Main(string[] args)
        {
            // 用 RSA 加密算法 API 来加密和解密

            string word = "hello";

            string encryptWord = RSAEncryption(word);

            Console.WriteLine("{0} 加密后的密文为:{1}\n\n", word, encryptWord);

            string newWord = RSADecryption(encryptWord);

            Console.WriteLine("{0} 解密后的明文为:{1}\n\n", encryptWord, newWord);
        }

        /// <summary>
        /// 加密
        /// </summary>
        /// <param name="word">待加密的字符串</param>
        /// <returns></returns>
        static string RSAEncryption(string word)
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = "MyKeyContainer";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
            {
                byte[] plaindata = System.Text.Encoding.Default.GetBytes(word);
                byte[] encryptdata = rsa.Encrypt(plaindata, false);
                string encryptstring = Convert.ToBase64String(encryptdata);
                return encryptstring;
            }
        }

        /// <summary>
        /// 解密,当密文不正确时,可能会抛出异常
        /// </summary>
        /// <param name="encryptWord">待解密的密文字符串</param>
        /// <returns></returns>
        static string RSADecryption(string encryptWord)
        {
            CspParameters param = new CspParameters();
            param.KeyContainerName = "MyKeyContainer";
            using (RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(param))
            {
                byte[] encryptdata = Convert.FromBase64String(encryptWord);
                byte[] decryptdata = rsa.Decrypt(encryptdata, false);
                string plaindata = System.Text.Encoding.Default.GetString(decryptdata);
                return plaindata;
            }
        }
    }

}

 

运行效果图:

谢谢浏览!