|
本帖最后由 信息计算敖若瑶 于 2022-4-16 00:52 编辑
一、源代码
1.通过引用TripleDES-类中的加密方法Encrypt和解密方法Decrypt进行加密和解密
- /**//// <summary>
- /// 加密方法File to File
- /// </summary>
- /// <param name="inFileName">待加密文件的路径</param>
- /// <param name="outFileName">待加密后文件的输出路径</param>
- public void Encrypt(string inFileName, string outFileName)
- {
- try
- {
- FileStream fin = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
- FileStream fout = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
- fout.SetLength(0);
- mydes.Key = GetLegalKey();
- mydes.IV = GetLegalIV();
- byte[] bin = new byte[100];
- long rdlen = 0;
- long totlen = fin.Length;
- int len;
- ICryptoTransform encrypto = mydes.CreateEncryptor();
- CryptoStream cs = new CryptoStream(fout, encrypto, CryptoStreamMode.Write);
- while (rdlen < totlen)
- {
- len = fin.Read(bin, 0, 100);
- cs.Write(bin, 0, len);
- rdlen = rdlen + len;
- }
- cs.Close();
- fout.Close();
- fin.Close();
- }
- catch (Exception ex)
- {
- throw new Exception("在文件加密的时候出现错误!错误提示: " + ex.Message);
- }
- }
- /**//// <summary>
- /// 解密方法File to File
- /// </summary>
- /// <param name="inFileName">待解密文件的路径</param>
- /// <param name="outFileName">待解密后文件的输出路径</param>
- public void Decrypt(string inFileName, string outFileName)
- {
- try
- {
- FileStream fin = new FileStream(inFileName, FileMode.Open, FileAccess.Read);
- FileStream fout = new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
- fout.SetLength(0);
- byte[] bin = new byte[100];
- long rdlen = 0;
- long totlen = fin.Length;
- int len;
- mydes.Key = GetLegalKey();
- mydes.IV = GetLegalIV();
- ICryptoTransform encrypto = mydes.CreateDecryptor();
- CryptoStream cs = new CryptoStream(fout, encrypto, CryptoStreamMode.Write);
- while (rdlen < totlen)
- {
- len = fin.Read(bin, 0, 100);
- cs.Write(bin, 0, len);
- rdlen = rdlen + len;
- }
- cs.Close();
- fout.Close();
- fin.Close();
- }
- catch (Exception ex)
- {
- throw new Exception("在文件解密的时候出现错误!错误提示:" + ex.Message);
- }
- }
复制代码
2.主程序:通过创建txt文件,来对其进行加密、解密
- using System;
- using System.Text;
- using System.IO;
- using System.Security.Cryptography;
- namespace DES
- {
- class Program
- {
- static void Main(string[] args)
- {
- //待加密文件的路径
- string one = @"/Users/gesilasapple/Desktop/1.1.txt";
- //加密后文件的输出路径
- string two1 = @"/Users/gesilasapple/Desktop/1.2.txt";
- //待解密文件的路径
- string two2 = @"/Users/gesilasapple/Desktop/1.2.txt";
- //解密后文件的输出路径
- string three = @"/Users/gesilasapple/Desktop/1.3.txt";
- //密钥key
- string key = "220415@";
- //加/解密方法File to File
- TripleDES_ des = new TripleDES_(key);
- des.Encrypt(one, two1);
- des.Decrypt(two2, three);
- }
- }
复制代码
二、程序运行截图
1.实例一:
2.实例2:
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|