|
本帖最后由 108林荟萃 于 2022-4-15 18:39 编辑
一、3DES加解密算法简介:
3DES是对称加密的一种,是DES向AES过渡的加密算法。它使用三个秘钥的三重DES加密方法,该算法执行三次DES算法,其加密的过程是加密-解密-加密。而3DES解密过程,与加密过程相反,即逆序使用秘钥并执行解密-加密-解密的过程。
二、利用所提供的TripleDES_类写一个文件加解密程序:
1.具体思路:
(1) 本次作业要求对文件进行读取加解密,阅读TripleDES_类的代码后可知,主要用到的部分是:
- 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);
- }
- }
复制代码
其中,第一个为加密方法,inFileName为待加密文件的路径,outFileName为待加密后文件的输出路径; 第二个为解密方法,inFileName为待解密文件的路径,outFileName为待解密后文件的输出路径;
3. 阅读分析代码后可知,只需在Main函数内提供各文件的路径并传入相关函数中运行即可。
4. 编写的Main函数以实现加解密方法:
- static void Main(string[] args)
- {
- string key = "123456789101223344556788";
- string inFileName =@"C:\Users\13337525256\Desktop\3DES\testIn.docx";
- string outFileName =@"C:\Users\13337525256\Desktop\3DES\testOut.docx";
- string FileName = @"C:\Users\13337525256\Desktop\3DES\testFinal.docx";
- TripleDES_ tripleDES_ = new TripleDES_(key);
- tripleDES_.Encrypt(inFileName, outFileName);
- tripleDES_.Decrypt(outFileName, FileName);
- }
复制代码
三、运行过程与结果:
1.在文件夹内创建三个文件,命名分别为testIn.docx(需要加密的文档)、testOut.docx(用于加密后的内容存放)、testFinal.docx(用于解密后的内容存放);
C:\Users\13337525256\Desktop\1.png
2.运行代码程序:
C:\Users\13337525256\Desktop\2.png
3.查看创建的三个文件:
C:\Users\13337525256\Desktop\4.png
|
本帖子中包含更多资源
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
|