码迷,mamicode.com
首页 > Windows程序 > 详细

C#中RSA的简单使用

时间:2017-05-17 13:54:27      阅读:211      评论:0      收藏:0      [点我收藏+]

标签:钥匙   return   .com   blog   play   int   版本   ati   com   

        static void Main(string[] args)
        {
            try
            {
                //创建一个编码实例用来将字符串转换成byte数组
                UnicodeEncoding ByteConverter = new UnicodeEncoding();

                //Create byte arrays to hold original, encrypted, and decrypted data.
                byte[] dataToEncrypt = ByteConverter.GetBytes("Data to Encrypt");
                byte[] encryptedData;
                byte[] decryptedData;
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false);
                    decryptedData = RSADecrypt(encryptedData, RSA.ExportParameters(true), false);
                    Console.WriteLine("Decrypted plaintext: {0}", ByteConverter.GetString(decryptedData));
                }
            }
            catch (ArgumentNullException)
            {
                Console.WriteLine("Encryption failed.");

            }
            Console.Read();
        }

        static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                byte[] encryptedData;
                //创建一个RSACryptoServiceProvider实例.
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {

                    //指定共有钥匙
                    RSA.ImportParameters(RSAKeyInfo);
                    //加密,并且指定是否运行在XP更高的版本中
                    encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
                }
                return encryptedData;
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);

                return null;
            }

        }

        static public byte[] RSADecrypt(byte[] DataToDecrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                byte[] decryptedData;
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {
                    RSA.ImportParameters(RSAKeyInfo);
                    decryptedData = RSA.Decrypt(DataToDecrypt, DoOAEPPadding);
                }
                return decryptedData;
            }
            //Catch and display a CryptographicException  
            //to the console.
            catch (CryptographicException e)
            {
                Console.WriteLine(e.ToString());

                return null;
            }

        }

技术分享

 

C#中RSA的简单使用

标签:钥匙   return   .com   blog   play   int   版本   ati   com   

原文地址:http://www.cnblogs.com/student-note/p/6866561.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!