zoukankan      html  css  js  c++  java
  • 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
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Security.Cryptography;
    using System.IO;
    
    
    namespace RSA
    {
       
        public  static  class ReadKey
        {
            public static string publicKey = ReadPublicKey();
            public static string privateKey=ReadPrivateKey();
            #region ReadPublicKey
            /// <summary>
            /// 读取公钥的值
            /// </summary>
            /// <returns>公钥的值</returns>
            public static string  ReadPublicKey()
            {
                try
                {
                    using (StreamReader reader = new StreamReader("PublicKey.xml"))
                    {
                      return  reader.ReadToEnd();
                    }
    
                }
                catch
                {
                    return null;
                }
            }
            #endregion 
    
            #region ReadPrivateKey
            /// <summary>
            /// 读取私钥
            /// </summary>
            /// <returns>私钥字符串</returns>
            public static string ReadPrivateKey()
            {
                try
                {
                    using (StreamReader dr = new StreamReader("PrivateKey.xml"))
                    {
                        return dr.ReadToEnd();
                    }
                }
                catch
                {
                    return null;
                }
            }
    
            #endregion
        }
    }

     第四步对加密数据的封装

    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();
                }
            }
        }
    }

    源码下载https://files.cnblogs.com/tangdacheng/RSA.zip

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

  • 相关阅读:
    10.2 查找同一组或分区中行之间的差
    8.7 确定当前记录和下一条记录之间相差的天数
    8.6 计算一年中周内各日期的次数
    8.5 确定两个日期之间的秒、分、小时数
    8.4 确定两个日期之间的月份数或年数
    8.2 计算两个日期之间的天数
    8.3 确定两个日期之间的工作日数目
    8.1 加减日、月、年
    7.13 计算不包含最大值和最小值的均值
    第3章 Python的数据类型 第3.1节 功能强大的 Python序列概述
  • 原文地址:https://www.cnblogs.com/tangdacheng/p/2813525.html
Copyright © 2011-2022 走看看