C#winformの暗号化とソースコードの復号テストに成功しました

2571 ワード



using System;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using System.IO;


namespace WindowsFormsApplication1
{


    public partial class Form1 : Form
    {
        
        public Form1()
        {
            InitializeComponent();
        }


        private void button1_Click(object sender, EventArgs e)// 
        {
            DES desjiami = new DES();
           textBox2.Text =desjiami.Encrypt(textBox1.Text, "goodmany");
            
        }


        private void button2_Click(object sender, EventArgs e)// 
        {
            DES desjiami = new DES();
            textBox1.Text = desjiami.Decrypt(textBox2.Text, "goodmany");
        }
    }
    public class DES
    {
        public string Encrypt(string pToEncrypt, string sKey)// 
        {
            DESCryptoServiceProvider desCSP = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
            desCSP.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            desCSP.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, desCSP.CreateEncryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder SB= new StringBuilder();
            foreach (byte b in ms.ToArray())
            {
                SB.AppendFormat("{0:X2}", b);
            }
            SB.ToString();
            return SB.ToString();
        }
        public string Decrypt(string pToDecrypt, string sKey)// 
        {
            DESCryptoServiceProvider desCSP = new DESCryptoServiceProvider();
            byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
            for (int x = 0; x < pToDecrypt.Length / 2; x++)
            {
                int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
                inputByteArray[x] = (byte)i;
            }
            desCSP.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
            desCSP.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, desCSP.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            StringBuilder ret = new StringBuilder();
            return System.Text.Encoding.Default.GetString(ms.ToArray());
        }


    }
}