当前位置:编程学习 > 网站相关 >>

C# RSA数据加密

对于今天,网络安全越来越重要。其中也在公司项目中看过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>

补充:综合编程 , 安全编程 ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,