加密器

 
///随机数加密
byte[] randomByte = new byte[16];//创建字节数组
            //实例化加密随机数生成器
           RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider();
           rng.GetBytes(randomByte);//随机数填充数组
           Guid randguid = new Guid(randomByte);//生成标识符
           this.txt.Text = randguid.ToString();//显示
 /// <summary>
        /// 字符串不对称加密和解密
        /// </summary>
       
        private RSACryptoServiceProvider rsa;//密码类
        RSAParameters para;//参数
        byte[] pridata;

        public Form1()
        {
            InitializeComponent();
            rsa = new RSACryptoServiceProvider();
            para = rsa.ExportParameters(true);
            rsa.Clear();
            rsa = new RSACryptoServiceProvider();
            rsa.ImportParameters(para);
        }

        private void Encrypt_Click(object sender, EventArgs e)
        {
            //转化加密文本
            byte[] dataEncrypt = Encoding.UTF8.GetBytes(txtPlainText.Text);
            byte[] encText = rsa.Encrypt(dataEncrypt, false);//加密
            txtCipherText.Text = Encoding.UTF8.GetString(encText);//产生加密文本
            pridata = encText;
        }

        private void Decrypt_Click(object sender, EventArgs e)
        {
            byte[] cyarray = rsa.Decrypt(pridata, false);
            txtResultText.Text = Encoding.UTF8.GetString(cyarray);//解密 
        }
        /// <summary>
        /// 对称加密算法加密数据到文件
        /// </summary>
        Rijndael rj = Rijndael.Create();//声明密码对象

        private void Encrypt_Click(object sender, EventArgs e)
        {
            //定义加密转换运算
            ICryptoTransform crt = rj.CreateEncryptor();
            //打开文件用于写数据
            FileStream fs = new FileStream(@"d:	estfile.bin", FileMode.Create);
            //创建加密数据流
            CryptoStream cs = new CryptoStream(fs, crt, CryptoStreamMode.Write);
            //创建写数据流
            StreamWriter sw = new StreamWriter(cs);
            sw.Write(PlainText.Text);//写入数据
            sw.Flush();//清理缓冲区
            cs.FlushFinalBlock();
            sw.Close(); 
        }
        private void Decrypt_Click(object sender, EventArgs e)
        {
            ICryptoTransform crt = rj.CreateDecryptor();//定义解密转换运算
            //打开文件读取数据
            FileStream fs = new FileStream(@"d:	estfile.bin", FileMode.Open);
            //创建解密转换流
            CryptoStream cs = new CryptoStream(fs, crt, CryptoStreamMode.Read);
            StreamReader sr = new StreamReader(cs);//创建读取数据流
            string text = sr.ReadToEnd();//读取数据
            sr.Close();
            PlainText.Text = text;
        }
 /// <summary>
        /// 图片用于解密加密文件
        /// </summary>

        private void Encrypt_Click(object sender, EventArgs e)
        {
            try
            {
                if (picFilePath.ImageLocation == null)
                { 
                    MessageBox.Show("请选择一幅图片用于加密"); 
                    return; 
                }
                if (txtFilePath.Text == "")
                { 
                    MessageBox.Show("请选择加密文件路径"); 
                    return; 
                }
                //图片流
                FileStream fsPic = new FileStream(picFilePath.ImageLocation, FileMode.Open, FileAccess.Read);
                //加密文件流
                FileStream fsText = new FileStream(txtFilePath.Text, FileMode.Open, FileAccess.Read);
                //初始化Key IV
                byte[] bykey = new byte[16];
                byte[] byIv = new byte[8];
                fsPic.Read(bykey, 0, 16);
                fsPic.Read(byIv, 0, 8);
                //临时加密文件
                string strPath = txtFilePath.Text;//加密文件的路径
                int intLent = strPath.LastIndexOf("\") + 1;
                int intLong = strPath.Length;
                string strName = strPath.Substring(intLent, intLong - intLent);//要加密的文件名称
                string strLinPath = "C:\" + strName;//临时加密文件路径
                FileStream fsOut = File.Open(strLinPath, FileMode.Create, FileAccess.Write);
                //开始加密
               
                RC2CryptoServiceProvider desc = new RC2CryptoServiceProvider();//des进行加密
                BinaryReader br = new BinaryReader(fsText);//从要加密的文件中读出文件内容
                CryptoStream cs = new CryptoStream(fsOut, desc.CreateEncryptor(bykey, byIv), CryptoStreamMode.Write);//写入临时加密文件
                cs.Write(br.ReadBytes((int)fsText.Length), 0, (int)fsText.Length);//写入加密流
                cs.FlushFinalBlock();
                cs.Flush();
                cs.Close();
                fsPic.Close();
                fsText.Close();
                fsOut.Close();
                File.Delete(txtFilePath.Text.TrimEnd());//删除原文件
                File.Copy(strLinPath, txtFilePath.Text);//复制加密文件
                File.Delete(strLinPath);//删除临时文件
                MessageBox.Show("加密成功");
                
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            } 
        }

        private void Decrypt_Click(object sender, EventArgs e)
        {
            try
            {
                //图片流
                FileStream fsPic = new FileStream(picFilePath.ImageLocation, FileMode.Open, FileAccess.Read);
                //解密文件流
                FileStream fsOut = File.Open(txtFilePath.Text, FileMode.Open, FileAccess.Read);
                //初始化Key IV
                byte[] bykey = new byte[16];
                byte[] byIv = new byte[8];
                fsPic.Read(bykey, 0, 16);
                fsPic.Read(byIv, 0, 8);
                //临时解密文件
                string strPath = txtFilePath.Text;//加密文件的路径
                int intLent = strPath.LastIndexOf("\") + 1;
                int intLong = strPath.Length;
                string strName = strPath.Substring(intLent, intLong - intLent);//要加密的文件名称
                string strLinPath = "C:\" + strName;//临时解密文件路径
                FileStream fs = new FileStream(strLinPath, FileMode.Create, FileAccess.Write);
                //开始解密
                RC2CryptoServiceProvider desc = new RC2CryptoServiceProvider();//des进行解
                CryptoStream csDecrypt = new CryptoStream(fsOut, desc.CreateDecryptor(bykey, byIv), CryptoStreamMode.Read);//读出加密文件
                BinaryReader sr = new BinaryReader(csDecrypt);//从要加密流中读出文件内容
                BinaryWriter sw = new BinaryWriter(fs);//写入解密流
                sw.Write(sr.ReadBytes(Convert.ToInt32(fsOut.Length)));//
                sw.Flush();
                sw.Close();
                sr.Close();
                fs.Close();
                fsOut.Close();
                fsPic.Close();
                csDecrypt.Flush();

                File.Delete(txtFilePath.Text.TrimEnd());//删除原文件
                File.Copy(strLinPath, txtFilePath.Text);//复制加密文件
                File.Delete(strLinPath);//删除临时文件
                MessageBox.Show("解密成功");
                picFilePath.ImageLocation = null;
                txtFilePath.Text = "";
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        /// <summary>
        /// 密钥对文件加密解密
        /// </summary>
        public Form1()
        {
            InitializeComponent();
            rij = new RijndaelManaged();
        }
        private RijndaelManaged rij;
        private void Encrypt_Click(object sender, EventArgs e)
        {
            if (txtFilePath.Text == "")
            { MessageBox.Show("请选择要加密的文件"); }
            else
            {
                try
                {
                    if (txtPK.Text.Length >= 8 && txtPK.Text.Length <= 16)
                    {
                        string strPath = txtFilePath.Text;//加密文件的路径
                        int intLent = strPath.LastIndexOf("\") + 1;
                        int intLong = strPath.Length;
                        string strName = strPath.Substring(intLent, intLong - intLent);//要加密的文件名称
                        int intTxt = strName.LastIndexOf(".");
                        int intTextLeng = strName.Length;
                        string strTxt = strName.Substring(intTxt, intTextLeng - intTxt);//取出文件的扩展名
                        strName = strName.Substring(0, intTxt);
                        //加密后的文件名及路径
                        string strOutName = strPath.Substring(0, strPath.LastIndexOf("\") + 1) + strName + "Out" + strTxt;
                        byte[] key = Encoding.Default.GetBytes(txtPK.Text);//获取密钥
                        byte[] IV = rij.IV;//获取分组长度
                        RijndaelManaged myRijndael = new RijndaelManaged();//加密对象
                        FileStream fsOut = File.Open(strOutName, FileMode.Create, FileAccess.Write);
                        FileStream fsIn = File.Open(strPath, FileMode.Open, FileAccess.Read);
                        //写入加密文本文件
                        CryptoStream csDecrypt = new CryptoStream(fsOut, myRijndael.CreateEncryptor(key, IV), CryptoStreamMode.Write);
                        //读加密文本
                        BinaryReader br = new BinaryReader(fsIn);
                        csDecrypt.Write(br.ReadBytes((int)fsIn.Length), 0, (int)fsIn.Length);
                        csDecrypt.FlushFinalBlock();
                        csDecrypt.Close();
                        fsIn.Close();
                        fsOut.Close();
                        if (MessageBox.Show(strOutName, "提示:加密成功!加密后的文件名及路径为:
" + "是否删除源文件", MessageBoxButtons.YesNo) == DialogResult.Yes)
                        {
                            File.Delete(strPath);
                            txtFilePath.Text = "";
                        }
                        else
                        { txtFilePath.Text = ""; }
                    }
                    else
                        MessageBox.Show("密码长度超出范围!");
                }
                catch (Exception ee)
                {
                    MessageBox.Show(ee.Message);
                }
            }
        }

        private void Decrypt_Click(object sender, EventArgs e)
        {
            if (txtFilePath.Text == "")
            {
                MessageBox.Show("请选择要解密的文件路径");
            }
            else
            {
                if (txtPK.Text.Length >= 8 && txtPK.Text.Length <= 16)
                {
                    string strPath = txtFilePath.Text;//加密文件的路径
                    int intLent = strPath.LastIndexOf("\") + 1;
                    int intLong = strPath.Length;
                    string strName = strPath.Substring(intLent, intLong - intLent);//要加密的文件名称
                    int intTxt = strName.LastIndexOf(".");
                    int intTextLeng = strName.Length;
                    strName = strName.Substring(0, intTxt);

                    if (strName.LastIndexOf("Out") != -1)
                    {
                        strName = strName.Substring(0, strName.LastIndexOf("Out"));

                    }
                    else
                    {
                        strName = strName + "In";
                    }
                    //加密后的文件名及路径
                    string strInName = strPath.Substring(0, strPath.LastIndexOf("\") + 1) + strName + ".txt";
                    byte[] key = Encoding.Default.GetBytes(txtPK.Text);
                    byte[] IV = rij.IV;
                    RijndaelManaged myRijndael = new RijndaelManaged();
                    FileStream fsOut = File.Open(strPath, FileMode.Open, FileAccess.Read);
                    CryptoStream csDecrypt = new CryptoStream(fsOut, myRijndael.CreateDecryptor(key, IV), CryptoStreamMode.Read);
                    StreamReader sr = new StreamReader(csDecrypt);//把文件读出来
                    StreamWriter sw = new StreamWriter(strInName);//解密后文件写入一个新的文件
                    sw.Write(sr.ReadToEnd());
                    sw.Flush();
                    sw.Close();
                    sr.Close();
                    fsOut.Close();
                    if (MessageBox.Show(strInName, "提示:解密成功!解密后的文件名及路径为:" + "是否删除源文件", MessageBoxButtons.YesNo) == DialogResult.Yes)
                    {
                        File.Delete(strPath);
                        txtFilePath.Text = "";
                    }
                    else
                    {
                        txtFilePath.Text = "";
                    }
                }
                else
                    MessageBox.Show("密码长度超出范围!");

            }
        }
       /// <summary>
        /// 数据加密为文件
        /// </summary>
        public Form1()
        {
            InitializeComponent();

            //创建DES密钥
            des = new DESCryptoServiceProvider();
            Key = "wjshan0808";
        }
         private DESCryptoServiceProvider des;//实例化DES对象
         private string Key;//密钥
        private void Encrypt_Click(object sender, EventArgs e)
        {
            byte[] privateKey1 = Encoding.Default.GetBytes(Key.Substring(0, 8));//对称算法的密钥
            byte[] privateKey2 = privateKey1;//初始向量

            byte[] data = Encoding.Default.GetBytes(txtPlainText.Text);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(privateKey1, privateKey2), CryptoStreamMode.Write);
            //将字节序列写入当前流,并将流的当前位置提升写入的字节数
            cs.Write(data, 0, data.Length);
            cs.FlushFinalBlock();
            StreamWriter sw = new StreamWriter("EncryptFile.txt");
            sw.WriteLine(Convert.ToBase64String(ms.ToArray()) + '
');
            sw.Close();
        }

        private void Decrypt_Click(object sender, EventArgs e)
        {
            byte[] privateKey1 = Encoding.Default.GetBytes(Key.Substring(0, 8));//对称算法的密钥
            byte[] privateKey2 = privateKey1;//初始向量
            StreamReader sr = new StreamReader("EncryptFile.txt");
            byte[] data = Convert.FromBase64String(sr.ReadToEnd());
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(privateKey1, privateKey2), CryptoStreamMode.Write);
            cs.Write(data, 0, data.Length);
            cs.FlushFinalBlock();
            StreamWriter sw = new StreamWriter("DecryptFile.txt");
            sw.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
            sw.Close();
        }
原文地址:https://www.cnblogs.com/wjshan0808/p/4220960.html