频道栏目
首页 > 程序开发 > 综合编程 > 安全编程 > 正文
C# RSA数据加密
2012-12-12 11:30:08           
收藏   我要投稿

对于今天,网络安全越来越重要。其中也在公司项目中看过RSA一些加密方法。不完整。

于是上查了一些资料,发现没有公钥和私钥的产生。所以我重密钥产生到加密,解密完整的步骤

第一步产生密钥类 CreateKey

View Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace RSA
{
    /// <summary>
    /// 创建公钥和私钥
    /// </summary>
    public static class CreateKey
    {
        #region GetPublicKey
        /// <summary>
        /// 产生公钥和私钥
        /// </summary>
        public static void GetPublicKey()
        {
            //RSA必须是一个对象,产生公钥和私钥
            using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {
                using (StreamWriter writer = new StreamWriter("PrivateKey.xml"))
                {
                    // ToXmlString中 true 表示同时包含 RSA 公钥和私钥;false 表示仅包含公钥。
                    writer.WriteLine(RSA.ToXmlString(true));
                }
                using (StreamWriter writer = new StreamWriter("PublicKey.xml"))
                {
                    writer.WriteLine(RSA.ToXmlString(false));
                }

            }

        }
        #endregion
      

    }
}

第二步是否含有公钥和密钥

View Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;


namespace RSA
{
    public static  class ContainsKey
    {
        #region Contain
        /// <summary>
        /// 是否含有文件名
        /// </summary>
        /// <param name="Name">传入的文件名</param>
        /// <returns></returns>
        public  static  bool Contain(string Name)
        {
            string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
            string full=path+Name;
            full = full.Replace("\\",System.IO.Path.DirectorySeparatorChar.ToString());
          
                if (!File.Exists(full))
                {
                    return false;
                }
                return true;
        }
        #endregion

        #region Create
        /// <summary>
        /// 判断是否含有,如果有返回true,如果没有创建返回true
        /// </summary>
        /// <returns></returns>
        public static bool Create()
        {
            try
            {
                if (Contain("PrivateKey.xml"))
                {
                    return true;
                }
                else
                {
                    CreateKey.GetPublicKey();
                    return true;
                }
            }
            catch
            {
                return false;
            }
           
        }
        #endregion
    }
}

 

第三步读取公钥和密钥

View Code
 

 第四步对加密数据的封装

View Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;

namespace RSA
{
    public static class SRSA
    {
        #region RSADeCrtypto
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="DataToDeCrypto">要解密的数据</param>
        /// <param name="RSAKeyInfo"></param>
        /// <param name="DoOAEPPadding"></param>
        /// <returns></returns>
        static public byte[] RSADeCrtypto(byte[] DataToDeCrypto, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                // System.Security.Cryptography.RSA 的参数。
                RSA.ImportParameters(RSAKeyInfo);
                //
                // 参数:
                //  
                //     要解密的数据。
                //
                //
                //     如果为 true,则使用 OAEP 填充(仅在运行 Microsoft Windows XP 或更高版本的计算机上可用)执行直接的 System.Security.Cryptography.RSA
                //     解密;否则,如果为 false,则使用 PKCS#1 1.5 版填充。
                return RSA.Decrypt(DataToDeCrypto, DoOAEPPadding);
            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
        #endregion

        #region RSAEnCrypto
        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="DataToEnCrypto"></param>
        /// <param name="RSAKeyInfo"></param>
        /// <param name="DoOAEPPadding"></param>
        /// <returns></returns>
        static public byte[] RSAEnCrypto(byte[] DataToEnCrypto, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSA.ImportParameters(RSAKeyInfo);
                return RSA.Encrypt(DataToEnCrypto, DoOAEPPadding);

            }
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);
                return null;
            }
        }
        #endregion

        #region Decrypt
        /// <summary>
        /// 解密数据
        /// </summary>
        /// <param name="base64code">传入加密数据</param>
        /// <returns>返回解密数据</returns>
        static public string Decrypt(string base64code)
        {
            try
            {
                UnicodeEncoding ByteConverter = new UnicodeEncoding();

                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSA.FromXmlString(ReadKey.privateKey);

                byte[] encryptedData;
                byte[] decryptedData;

                encryptedData = Convert.FromBase64String(base64code);

                decryptedData = RSADeCrtypto(encryptedData, RSA.ExportParameters(true), false);
                return ByteConverter.GetString(decryptedData);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }


        }
        #endregion

        #region Encrypt
        /// <summary>
        /// 加密数据
        /// </summary>
        /// <param name="toEncryptString">要解密的数据</param>
        /// <returns></returns>
        static public string Encrypt(string toEncryptString)
        {
            try
            {
                UnicodeEncoding ByteConverter = new UnicodeEncoding();


                byte[] encrypteData;
                byte[] decrypteData;
                decrypteData = ByteConverter.GetBytes(toEncryptString);

                RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
                RSA.FromXmlString(ReadKey.privateKey);
                encrypteData = RSAEnCrypto(decrypteData, RSA.ExportParameters(false), false);

                return Convert.ToBase64String(encrypteData);
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                return null;
            }
        }
        #endregion

    }
}

演示

View Code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml;
using System.IO;
using System.Security.Cryptography;

namespace RSA
{
    class Program
    {
        static void Main(string[] args)
        {
            //判断是否含有私钥,如果没有创建
            if (ContainsKey.Create())
            {
                Console.WriteLine("*********请输入输入要加密的数据************");
                string encryptData=   Console.ReadLine();
                Console.WriteLine("加密后的数据:{0}", SRSA.Encrypt(encryptData));
                Console.WriteLine("解密后的数据:{0}", SRSA.Decrypt(SRSA.Encrypt(encryptData)));
                Console.ReadLine();
            }
        }
    }
}

源码下载:http://up.2cto.com/2012/1212/20121212113243604.zip


这里没有详细的讲解希望大家耐性看
\

点击复制链接 与好友分享!回本站首页
相关TAG标签 数据
上一篇:checked_delete提升安全性
下一篇:Java MD5 加密类
相关文章
图文推荐
点击排行

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站