zoukankan      html  css  js  c++  java
  • 使用TripleDES算法加密/解密

    程序运行效果

    ///*****************************************************///
    ///************使用TripleDES算法加密/解密****************///
    ///*****************************************************///
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Data;
    using System.Drawing;
    using System.Linq;
    using System.Text;
    using System.Windows.Forms;
    //
    using System.IO;
    using System.Security.Cryptography;

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

            private void buttonSave_Click(object sender, EventArgs e)
            {
                string str = textBox1.Text;
                if (str.Length == 0)
                {
                    MessageBox.Show("请输入被加密的字符串!");
                    return;
                }

                string path = Application.StartupPath + "\\Data.txt";
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
                FileStream fs = File.Create(path);
                fs.Close();

                StreamWriter sw;
                try
                {
                    sw = new StreamWriter(path);               
                }
                catch
                {
                    MessageBox.Show("文件打开失败!");
                    return;
                }
               
                //加密
                try
                {
                    TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
                    //随机生成密钥Key和初始化向量IV
                    tdes.GenerateKey();
                    tdes.GenerateIV();
                    string strKey = Convert.ToBase64String(tdes.Key);   //Encoding.UTF8.GetString(tdes.Key);
                    string strIV = Convert.ToBase64String(tdes.IV);     //Encoding.UTF8.GetString(tdes.IV);
                  
                    //得到加密后的字节流
                    byte[] encryptedBytes = EncryptText(str, tdes.Key, tdes.IV);
                    //得到加密后的字符串
                    string strEncrytedData = Convert.ToBase64String(encryptedBytes);  //Encoding.UTF8.GetString(encryptedBytes);
           
                    sw.WriteLine(strKey);
                    sw.WriteLine(strIV);
                    sw.WriteLine(strEncrytedData);
                }
                catch (Exception err)
                {
                    MessageBox.Show(err.Message, "出错");
                }
                finally
                {
                    sw.Close();               
                }
               
               
            }

            private byte[] EncryptText(string str, byte[] Key, byte[] IV)
            {
                //创建一个内存流
                MemoryStream memoryStream = new MemoryStream();
                //使用传递的私钥和IV创建加密流
                CryptoStream crytoStream = new CryptoStream(memoryStream, new TripleDESCryptoServiceProvider().CreateEncryptor(Key,

    IV), CryptoStreamMode.Write);
                //将传递的字符串转换为字节数组
                byte[] toEncrypt = Encoding.UTF8.GetBytes(str);
                try
                {
                    //将字节数组写入加密流,并清除缓冲区
                    crytoStream.Write(toEncrypt, 0, toEncrypt.Length);
                    crytoStream.FlushFinalBlock();
                    //得到加密后的字节数组
                    byte[] encryptedBytes = memoryStream.ToArray();
                    return encryptedBytes;
                }
                catch (CryptographicException err)
                {
                    throw new Exception("加密出错:" + err.Message);
                }
                finally
                {
                    crytoStream.Close();
                    memoryStream.Close();
                }

            }

     

            private void Form1_Load(object sender, EventArgs e)
            {
                DecrypFromFile();
            }

            private void buttonOpen_Click(object sender, EventArgs e)
            {
                DecrypFromFile();
            }

            private void DecrypFromFile()
            {
                string path = Application.StartupPath + "\\Data.txt";
                if (!File.Exists(path))
                {
                    MessageBox.Show("要解密的文件不存在!");
                    return;
                }
                StreamReader sr;
                try
                {
                    sr = new StreamReader(path);
                }
                catch
                {
                    MessageBox.Show("文件打开失败!");
                    return;
                }
                byte[] Key = Convert.FromBase64String(sr.ReadLine());
                byte[] IV = Convert.FromBase64String(sr.ReadLine());
                byte[] dataBytes = Convert.FromBase64String(sr.ReadLine());
                sr.Close();
                string strDecryptedData = DecryptText(dataBytes, Key, IV);
                //现实解密后的字符串
                textBox1.Text = strDecryptedData;
               

            }

            private string DecryptText(byte[] dataBytes, byte[] Key, byte[] IV)
            {
                //根据加密后字节数组创建一个内存流
                MemoryStream memoryStream = new MemoryStream(dataBytes);
                //使用传递的私钥,IV和内存流创建解密流
                CryptoStream cryptoStream = new CryptoStream(memoryStream, new TripleDESCryptoServiceProvider().CreateDecryptor(Key,

    IV), CryptoStreamMode.Read);
                //创建一个字节数组保存解密后的数据
                byte[] decryptBytes = new byte[dataBytes.Length];
                try
                {
                    //从解密流中将解密后的数据读到字节数组中
                    cryptoStream.Read(decryptBytes, 0, decryptBytes.Length);
                    //得到解密后的字符串
                    string decryptedString = Encoding.UTF8.GetString(decryptBytes);
                    return decryptedString;
                }
                catch (CryptographicException err)
                {
                    throw new Exception("解密出错:" + err.Message);
                }
                finally
                {
                    cryptoStream.Close();
                    memoryStream.Close();
                }
            }
        }
    }

  • 相关阅读:
    创建Variant数组
    ASP与存储过程(Stored Procedures)
    FileSystemObject对象成员概要
    Kotlin 朱涛9 委托 代理 懒加载 Delegate
    Kotlin 朱涛 思维4 空安全思维 平台类型 非空断言
    Kotlin 朱涛7 高阶函数 函数类型 Lambda SAM
    Kotlin 朱涛16 协程 生命周期 Job 结构化并发
    Proxy 代理模式 动态代理 cglib MD
    RxJava 设计理念 观察者模式 Observable lambdas MD
    动态图片 Movie androidgifdrawable GifView
  • 原文地址:https://www.cnblogs.com/wanyakun/p/1494112.html
Copyright © 2011-2022 走看看