C # Encrypt and decrypt source code, MD5, DES, RSA

Source: Internet
Author: User
Tags md5 encryption asymmetric encryption






From the Internet to find the code, easy to change, easier to use.









Thanks to the original author's generous code



Http://www.cnblogs.com/zhhh/archive/2013/04/13/3018437.html






Configuration file


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";//file name and path
                Using (Stream fStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    XmlSerializer xmlFormat = new XmlSerializer(typeof(Cfg));//Create an XML serializer that needs to specify the type of the object
                    xmlFormat.Serialize(fStream, this);
                    fStream.Close();
                }
            }
            Catch (Exception ex)
            {
                Throw ex;
            }
        }

        Public bool Read()
        {
            Try
            {
                String fileName = "cfg.txt";//file name and path
                Using (Stream fStream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                {
                    XmlSerializer xmlFormat = new XmlSerializer(typeof(Cfg));//Create an XML serializer that needs to specify the type of the object
                    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;

        }

    }
}





Generate key


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("Mr. into a key.");
                Return;
            }
            Cfg c = new Cfg();
            c.Pri = txtPrivateKey.Text;
            c.Pub = txtPublishKey.Text;
            Try
            {
            c.Save();
            MessageBox.Show("Saved successfully.");
            }
            Catch (Exception ex)
            {
                MessageBox.Show( "File save failed: "+ex.Message);
            }
        }

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


Encryption and decryption algorithm, I did not move oh


/**
 * Author: Zhang Haohua
 */

Using System;
Using System.Collections.Generic;
Using System.Text;
Using System.Security.Cryptography;
Using System.IO;
Namespace Encoder
{
    Public class Encoder
    {
        #region DES 加(解)密密. (Symmetric encryption)

        /// <summary>
        /// DES encryption (symmetric encryption). Encrypt the plaintext into ciphertext using a key
        /// </summary>
        /// <param name="code">clear text</param>
        /// <param name="sKey">key</param>
        /// <returns> ciphertext</returns>
        Public static string DESEncrypt(string code, string sKey)
        {
            /* Create a DES encryption service provider */
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            /* Converts the content to be encrypted into a Byte array */
            Byte[] inputByteArray = Encoding.Default.GetBytes(code);

            /* Set the key and initialization vector */
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            /* Create a memory stream object */
            MemoryStream ms = new MemoryStream();

            /* Create an encrypted stream object */
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);

            /* Writes the text to be encrypted to the encrypted stream */
            cs.Write(inputByteArray, 0, inputByteArray.Length);

            /* Update buffer */
            cs.FlushFinalBlock();

            /* Get encrypted text */
            StringBuilder ret = new StringBuilder();
            Foreach (byte b in ms.ToArray())
            {
                ret.AppendFormat("{0:X2}", b);
            }
            /* Release resources */
            cs.Close();
            ms.Close();

            /* Return result */
            Return ret.ToString();
        }

        /// <summary>
        /// DES decryption (symmetric encryption). Decode cipher text into plaintext using a key
        /// </summary>
        /// <param name="code">cryptotext</param>
        /// <param name="sKey">key</param>
        /// <returns>clear text</returns>
        Public static string DESDecrypt(string code, string sKey)
        {
            /* Create a DES encryption service provider */
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();

            /* Converts the content to be decrypted into a Byte array */
            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;
            }

            /* Set the key and initialization vector */
            des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

            /* Create a memory stream object */
            MemoryStream ms = new MemoryStream();

            /* Create an encrypted stream object */
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);

            /* Writes the text to be decrypted to the encrypted stream */
            cs.Write(inputByteArray, 0, inputByteArray.Length);

            /* Update buffer */
            cs.FlushFinalBlock();

            /* Return result */
            Return System.Text.Encoding.Default.GetString(ms.ToArray());
        }

        #endregion

        #region RSA Add (solution) secret. (Asymmetric encryption)
        /// <summary>
        /// Create a pair of RSA keys (public key & private key).
        /// </summary>
        /// <returns></returns>
        Public static RSAKey CreateRSAKey()
        {
            RSAKey rsaKey = new RSAKey(); //Declare an RSAKey object

            /* Create an RSA encryption service provider */
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsaKey.PrivateKey = rsa.ToXmlString(true); //Create a private key
            rsaKey.PublicKey = rsa.ToXmlString(false); //Create a public key

            Return rsaKey; / / return results
        }

        /// <summary>
        /// RSA encryption (asymmetric encryption). Encrypt the plaintext into ciphertext using the public key
        /// </summary>
        /// <param name="code">clear text</param>
        /// <param name="key">public key</param>
        /// <returns> ciphertext</returns>
        Public static string RSAEncrypt(string code, string key)
        {
            /* Convert text to a byte array */
            Byte[] source = Encoding.Default.GetBytes(code);
            Byte[] ciphertext; // cipher byte array

            /* Create an RSA encryption service provider */
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(key); //Set the public key
            Ciphertext = rsa.Encrypt(source, false); //encrypt, get the byte array

            /* Transcode character arrays */
            StringBuilder sb = new StringBuilder();
            Foreach (byte b in ciphertext)
            {
                sb.AppendFormat("{0:X2}", b);
            }
            Return sb.ToString(); //return result
        }

        /// <summary>
        /// RSA decryption (asymmetric encryption). Decrypt the ciphertext into plaintext using the private key
        /// </summary>
        /// <param name="code">cryptotext</param>
        /// <param name="key">private key</param>
        /// <returns>clear text</returns>
        Public static string RSADecrypt(string code, string key)
        {
            /* Convert text to a byte array */
            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; // original byte array

            /* Create an RSA encryption service provider */
            RSACryptoServiceProvider
Rsa = new RSACryptoServiceProvider();
            rsa.FromXmlString(key); //Set the private key
            Source = rsa.Decrypt(ciphertext, false); //decrypt, get the byte array

            Return Encoding.Default.GetString(source); //return results
        }

        #endregion

        #region MD5 Encryption (Hash Code Hash Encryption)
        /// <summary>
        /// MD5 encryption (hash code Hash encryption)
        /// </summary>
        /// <param name="code">clear text</param>
        /// <returns> ciphertext</returns>
        Public static string MD5Encrypt(string code)
        {
            /* Get the byte array of the original content */
            Byte[] sourceCode = Encoding.Default.GetBytes(code);
            Byte[] targetCode; //Declare the byte array used to get the target content

            /* Create an MD5 encryption service provider */
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            targetCode = md5.ComputeHash(sourceCode); //Execute encryption

            /* Transcode character arrays */
            StringBuilder sb = new StringBuilder();
            Foreach (byte b in targetCode)
            {
                sb.AppendFormat("{0:X2}", b);
            }

            Return sb.ToString();
        }
        #endregion
    }

    /// <summary>
    /// RSA key. Public key & private key
    /// </summary>
    Public class RSAKey
    {
        Public string PrivateKey { get; set; }
        Public string PublicKey { get; set; }
    }

} 


Release Notes



=====================================================
v0.2 June 18, 2016 11:52:47
by Zhengzhou Yu Te Intelligent Electric Co., Ltd. LI workers QQ 1222698
1. Increase RSA key generation, save, read
2, adjust the text and ciphertext box position.
3, add about, Release notes
4, has net3.5 changed into net2.0
5, thank the original author's generosity source code



=====================================================
v0.1 Original Zhang Haohua
: http://www.cnblogs.com/zhhh/archive/2013/04/13/3018437.html






Download this release:---------point here, OH----------



C # Encrypt and decrypt source code, MD5, DES, RSA


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.