|
本帖最后由 19-1-09陈佳怡 于 2022-4-15 22:15 编辑
一 思路
阅读代码后可知,TripleDES_类中构造了对称加密类函数,可获取密钥以及初始向量,已给出了一个文件加密,解密再写入另一个文件具体实现,而要进行程序的实现只需我们提供文件的对应路径,以及相应的密钥利用加解密方法即可实现。
main函数,提供文件的路径以及密钥
- static void Main(string[] args)
- {
- string infile = @"C:/Users/86137/Desktop/mima.txt";//密文路径
- string outfile = @"C:/Users/86137/Desktop/m.txt";//加密文件路径
- string outfile2 = @"C:/Users/86137/Desktop/m1.txt";//解密文件路径
- string key = "ascnfadna";//密钥
- TripleDES_ des = new TripleDES_(key);
- des.Encrypt(infile, outfile);
- des.Decrypt(outfile, outfile2);
- }
复制代码
利用文件加密部分(Encrypt)- 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);
- }
- }
复制代码
利用文件解密部分(Decrypt)
- 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);
- }
- }
复制代码
所需指令集:
- using System;
- using System.IO;
- using System.Security.Cryptography;
- using System.Text;
复制代码
二.运行结果
创建存放加解密信息的文档m.txt m1.txt
密文内容(mima.txt)
运行成功截图1
截图2
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|