当前位置: 首页 > news >正文

使用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();
            }
        }
    }
}

转载于:https://www.cnblogs.com/wanyakun/archive/2009/06/01/1494112.html

相关文章:

  • Sql Server函数全解(二)数学函数
  • IT维护部门的绩效考核怎么做?
  • cs20_8-1
  • 恢复Linux系统里被删除的 Ext3文件
  • Python基础之函数
  • Picturing virtual functions
  • C# 预处理指令
  • 安装Asp.net 2.0服务器出现Server Application Unavailabl --zt
  • 解决FirewallD is not running问题
  • 使用Collectd + InfluxDB + Grafana进行JMX监控
  • 通过自己的项目实际经验,阐述为什么“恶心玩技术”?玩Java技术的教训(一)...
  • centos 生成网卡UUID
  • repo源及yum的常用方法
  • Python Django 初试手记
  • 线性表-顺序存储
  • 9月CHINA-PUB-OPENDAY技术沙龙——IPHONE
  • 【笔记】你不知道的JS读书笔记——Promise
  • 【跃迁之路】【463天】刻意练习系列222(2018.05.14)
  • 【知识碎片】第三方登录弹窗效果
  • AngularJS指令开发(1)——参数详解
  • exif信息对照
  • HTTP中的ETag在移动客户端的应用
  • If…else
  • Octave 入门
  • SOFAMosn配置模型
  • Spark VS Hadoop:两大大数据分析系统深度解读
  • SpingCloudBus整合RabbitMQ
  • Zepto.js源码学习之二
  • 编写高质量JavaScript代码之并发
  • 深入 Nginx 之配置篇
  • 译米田引理
  • 用 Swift 编写面向协议的视图
  • 在 Chrome DevTools 中调试 JavaScript 入门
  • raise 与 raise ... from 的区别
  • ​LeetCode解法汇总2808. 使循环数组所有元素相等的最少秒数
  • ​软考-高级-信息系统项目管理师教程 第四版【第19章-配置与变更管理-思维导图】​
  • # 安徽锐锋科技IDMS系统简介
  • #include
  • #我与Java虚拟机的故事#连载02:“小蓝”陪伴的日日夜夜
  • ()、[]、{}、(())、[[]]命令替换
  • (arch)linux 转换文件编码格式
  • (DenseNet)Densely Connected Convolutional Networks--Gao Huang
  • (echarts)echarts使用时重新加载数据之前的数据存留在图上的问题
  • (java)关于Thread的挂起和恢复
  • (板子)A* astar算法,AcWing第k短路+八数码 带注释
  • (二十四)Flask之flask-session组件
  • (翻译)terry crowley: 写给程序员
  • (剑指Offer)面试题41:和为s的连续正数序列
  • (离散数学)逻辑连接词
  • (一)使用Mybatis实现在student数据库中插入一个学生信息
  • (原創) 如何刪除Windows Live Writer留在本機的文章? (Web) (Windows Live Writer)
  • (源码版)2024美国大学生数学建模E题财产保险的可持续模型详解思路+具体代码季节性时序预测SARIMA天气预测建模
  • .NET Core 实现 Redis 批量查询指定格式的Key
  • .NET delegate 委托 、 Event 事件,接口回调
  • .net 使用ajax控件后如何调用前端脚本