c#加密解密源碼,md5、des、rsa


 

從網上找來的代碼,順手改改,用起來更方便。

 

配置文件

using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using System.Xml.Serialization;


namespace Encoder
{
    [Serializable]
    public class Cfg
    {
        public string Pub = "";
        public string Pri = "";

        public void Creat()
        {
            RSAKey keys = Encoder.CreateRSAKey();
            Pub = keys.PrivateKey;
            Pri = keys.PublicKey;
        }

        public void Save()
        {
            try
            {
                string fileName = "cfg.txt";//文件名稱與路徑
                using (Stream fStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    XmlSerializer xmlFormat = new XmlSerializer(typeof(Cfg));//創建XML序列化器,需要指定對象的類型
                    xmlFormat.Serialize(fStream, this);
                    fStream.Close();
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public bool Read()
        {
            try
            {
                string fileName = "cfg.txt";//文件名稱與路徑
                using (Stream fStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    XmlSerializer xmlFormat = new XmlSerializer(typeof(Cfg));//創建XML序列化器,需要指定對象的類型
                    Cfg c = (Cfg)xmlFormat.Deserialize(fStream);
                    this.Pub = c.Pub;
                    this.Pri = c.Pri;
                    fStream.Close();
                }
            }
            catch (Exception ex)
            {
                //throw ex;
            }
            if (Pub != "" && Pri != "")
                return true;
            return false;

        }

    }
}

  

生成密鑰

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace Encoder
{
    public partial class CreateRSAKeysForm : Form
    {
        public CreateRSAKeysForm()
        {
            InitializeComponent();
        }

        private void CreateRSAKeysForm_Load(object sender, EventArgs e)
        {
            Cfg c = new Cfg();
            c.Read();
            txtPrivateKey.Text = c.Pri;
            txtPublishKey.Text = c.Pub;
        }

        private void button1_Click(object sender, EventArgs e)
        {
            RSAKey keys = Encoder.CreateRSAKey();
            this.txtPrivateKey.Text = keys.PrivateKey;
            this.txtPublishKey.Text = keys.PublicKey;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            if (txtPrivateKey.Text == "")
            {
                MessageBox.Show("先生成密鑰。");
                return;
            }
            Cfg c = new Cfg();
            c.Pri = txtPrivateKey.Text;
            c.Pub = txtPublishKey.Text;
            try
            {
            c.Save();
            MessageBox.Show("保存成功。");
            }
            catch (Exception ex)
            {
                MessageBox.Show( "文件保存失敗:"+ex.Message);
            }        
        }

        private void button3_Click(object sender, EventArgs e)
        {
            Cfg c = new Cfg();            
            c.Read();
            txtPrivateKey.Text=c.Pri;
            txtPublishKey.Text=c.Pub;
        }
    }
}

  加密解密算法,我沒動哦

/**
 * Author:張浩華
 */

using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace Encoder
{
    public class Encoder
    {
        #region DES 加(解)密。(對稱加密)

        /// <summary>
        /// DES 加密(對稱加密)。使用密鑰將明文加密成密文
        /// </summary>
        /// <param name="code">明文</param>
        /// <param name="sKey">密鑰</param>
        /// <returns>密文</returns>
        public static string DESEncrypt(string code, string sKey)
        {
            /* 創建一個DES加密服務提供者 */
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            /* 將要加密的內容轉換成一個Byte數組 */
            byte[] inputByteArray = Encoding.Default.GetBytes(code);

            /* 設置密鑰和初始化向量 */
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            /* 創建一個內存流對象 */
            MemoryStream ms = new MemoryStream();

            /* 創建一個加密流對象 */
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            /* 將要加密的文本寫到加密流中 */
            cs.Write(inputByteArray, 0, inputByteArray.Length);

            /* 更新緩沖 */
            cs.FlushFinalBlock();

            /* 獲取加密過的文本 */
            StringBuilder ret = new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            /* 釋放資源 */
            cs.Close();
            ms.Close();

            /* 返回結果 */
            return ret.ToString();
        }

        /// <summary>
        /// DES 解密(對稱加密)。使用密鑰將密文解碼成明文
        /// </summary>
        /// <param name="code">密文</param>
        /// <param name="sKey">密鑰</param>
        /// <returns>明文</returns>
        public static string DESDecrypt(string code, string sKey)
        {
            /* 創建一個DES加密服務提供者 */
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            /* 將要解密的內容轉換成一個Byte數組 */
            byte[] inputByteArray = new byte[code.Length / 2];

            for (int x = 0; x < code.Length / 2; x++)
            {
                int i = (Convert.ToInt32(code.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }

            /* 設置密鑰和初始化向量 */
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            /* 創建一個內存流對象 */
            MemoryStream ms = new MemoryStream();

            /* 創建一個加密流對象 */
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

            /* 將要解密的文本寫到加密流中 */
            cs.Write(inputByteArray, 0, inputByteArray.Length);

            /* 更新緩沖 */
            cs.FlushFinalBlock();

            /* 返回結果 */
            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }

        #endregion

        #region RSA 加(解)密。(不對稱加密)
        /// <summary>
        /// 創建一對 RSA 密鑰(公鑰&私鑰)。
        /// </summary>
        /// <returns></returns>
        public static RSAKey CreateRSAKey()
        {
            RSAKey rsaKey = new RSAKey();    //聲明一個RSAKey對象

            /* 創建一個RSA加密服務提供者 */
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsaKey.PrivateKey = rsa.ToXmlString(true);    //創建私鑰
            rsaKey.PublicKey = rsa.ToXmlString(false);    //創建公鑰

            return rsaKey;    //返回結果
        }

        /// <summary>
        /// RSA 加密(不對稱加密)。使用公鑰將明文加密成密文
        /// </summary>
        /// <param name="code">明文</param>
        /// <param name="key">公鑰</param>
        /// <returns>密文</returns>
        public static string RSAEncrypt(string code, string key)
        {
            /* 將文本轉換成byte數組 */
            byte[] source = Encoding.Default.GetBytes(code);
            byte[] ciphertext;    //密文byte數組

            /* 創建一個RSA加密服務提供者 */
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(key);    //設置公鑰
            ciphertext = rsa.Encrypt(source, false);    //加密,得到byte數組

            /* 對字符數組進行轉碼 */
            StringBuilder sb = new StringBuilder();
            foreach (byte b in ciphertext)
            {
                sb.AppendFormat("{0:X2}", b);
            }
            return sb.ToString();    //返回結果
        }

        /// <summary>
        /// RSA 解密(不對稱加密)。使用私鑰將密文解密成明文
        /// </summary>
        /// <param name="code">密文</param>
        /// <param name="key">私鑰</param>
        /// <returns>明文</returns>
        public static string RSADecrypt(string code, string key)
        {
            /* 將文本轉換成byte數組 */
            byte[] ciphertext = new byte[code.Length / 2];
            for (int x = 0; x < code.Length / 2; x++)
            {
                int i = (Convert.ToInt32(code.Substring(x * 2, 2), 16));
                ciphertext[x] = (byte)i;
            }
            byte[] source;    //原文byte數組

            /* 創建一個RSA加密服務提供者 */
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(key);    //設置私鑰
            source = rsa.Decrypt(ciphertext, false);    //解密,得到byte數組

            return Encoding.Default.GetString(source);    //返回結果
        }

        #endregion

        #region MD5 加密(散列碼 Hash 加密)
        /// <summary>
        /// MD5 加密(散列碼 Hash 加密)
        /// </summary>
        /// <param name="code">明文</param>
        /// <returns>密文</returns>
        public static string MD5Encrypt(string code)
        {
            /* 獲取原文內容的byte數組 */
            byte[] sourceCode = Encoding.Default.GetBytes(code);
            byte[] targetCode;    //聲明用於獲取目標內容的byte數組

            /* 創建一個MD5加密服務提供者 */
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            targetCode = md5.ComputeHash(sourceCode);    //執行加密

            /* 對字符數組進行轉碼 */
            StringBuilder sb = new StringBuilder();
            foreach (byte b in targetCode)
            {
                sb.AppendFormat("{0:X2}", b);
            }

            return sb.ToString();
        }
        #endregion
    }

    /// <summary>
    /// RSA 密鑰。公鑰&私鑰
    /// </summary>
    public class RSAKey
    {
        public string PrivateKey { get; set; }
        public string PublicKey { get; set; }
    }

}

版本說明

=====================================================
v0.2 2016年6月18日11:52:47
by  李工 qq 1222698
1、增加rsa的密鑰生成,保存,讀取
2、調整明文和密文的框位置。
3、增加關於,版本說明
4、有net3.5改成net2.0
5、感謝原作者的慷慨源代碼

=====================================================
v0.1 原作者:張浩華
下載地址:http://www.cnblogs.com/zhhh/archive/2013/04/13/3018437.html

 

本版本下載:---------點這里哦----------

 

未實現功能:aes加密,base64加密

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM