加密后内容

代码

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 FileEncryption
{
public partial class frmMain : Form
{
public frmMain()
{
InitializeComponent();
} string root = Application.StartupPath;
string inFile, outFile; private void button1_Click(object sender, EventArgs e)
{
inFile = root + @"\test.txt";
outFile = root + @"\test.txt.加密文件";
EncryptFile(inFile, outFile, password);//加密文件
File.Delete(inFile);
MessageBox.Show("加密成功");
} private void button2_Click(object sender, EventArgs e)
{
inFile = root + @"\test.txt.加密文件";
outFile = root + @"\test.txt";
DecryptFile(inFile, outFile, password);//解密文件
File.Delete(inFile);
MessageBox.Show("解密成功");
} string password = "test@2023"; private const ulong FC_TAG = 0xFC010203040506CF; private const int BUFFER_SIZE = 128 * 1024; /// <summary>
/// 加密文件随机数生成
/// </summary>
private RandomNumberGenerator rand = new RNGCryptoServiceProvider(); /// <summary>
/// 异常处理类
/// </summary>
public class CryptoHelpException : ApplicationException
{
public CryptoHelpException(string msg) : base(msg) { }
} /// <summary>
/// 生成指定长度的随机Byte数组
/// </summary>
/// <param name="count">Byte数组长度</param>
/// <returns>随机Byte数组</returns>
private byte[] GenerateRandomBytes(int count)
{
byte[] bytes = new byte[count];
rand.GetBytes(bytes);
return bytes;
} /// <summary>
/// 检验两个Byte数组是否相同
/// </summary>
/// <param name="b1">Byte数组</param>
/// <param name="b2">Byte数组</param>
/// <returns>true-相等</returns>
private bool CheckByteArrays(byte[] b1, byte[] b2)
{
if (b1.Length == b2.Length)
{
for (int i = 0; i < b1.Length; ++i)
{
if (b1[i] != b2[i])
return false;
}
return true;
}
return false;
} /// <summary>
/// 创建加密对象以执行Rijndael算法
/// </summary>
/// <param name="password">密码</param>
/// <param name="salt"></param>
/// <returns>加密对象</returns>
private SymmetricAlgorithm CreateRijndael(string password, byte[] salt)
{
PasswordDeriveBytes pdb = new PasswordDeriveBytes(password, salt, "SHA256", 1000);
SymmetricAlgorithm sma = Rijndael.Create();
sma.KeySize = 256;
sma.Key = pdb.GetBytes(32);
sma.Padding = PaddingMode.PKCS7;
return sma;
} /// <summary>
/// 加密文件
/// </summary>
/// <param name="inFile">待加密文件</param>
/// <param name="outFile">加密后输入文件</param>
/// <param name="password">加密密码</param>
public void EncryptFile(string inFile, string outFile, string password)
{
using (FileStream fin = File.OpenRead(inFile),
fout = File.OpenWrite(outFile))
{
long lSize = fin.Length; // 输入文件长度
int size = (int)lSize;
byte[] bytes = new byte[BUFFER_SIZE]; // 缓存
int read = -1; // 输入文件读取数量
int value = 0; // 获取IV和salt
byte[] IV = GenerateRandomBytes(16);
byte[] salt = GenerateRandomBytes(16); // 创建加密对象
SymmetricAlgorithm sma = CreateRijndael(password, salt);
sma.IV = IV; // 在输出文件开始部分写入IV和salt
fout.Write(IV, 0, IV.Length);
fout.Write(salt, 0, salt.Length); // 创建散列加密
HashAlgorithm hasher = SHA256.Create();
using (CryptoStream cout = new CryptoStream(fout, sma.CreateEncryptor(), CryptoStreamMode.Write),
chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
{
BinaryWriter bw = new BinaryWriter(cout);
bw.Write(lSize); bw.Write(FC_TAG); // 读写字节块到加密流缓冲区
while ((read = fin.Read(bytes, 0, bytes.Length)) != 0)
{
cout.Write(bytes, 0, read);
chash.Write(bytes, 0, read);
value += read;
}
// 关闭加密流
chash.Flush();
chash.Close(); // 读取散列
byte[] hash = hasher.Hash; // 输入文件写入散列
cout.Write(hash, 0, hash.Length); // 关闭文件流
cout.Flush();
cout.Close();
}
}
} /// <summary>
/// 解密文件
/// </summary>
/// <param name="inFile">待解密文件</param>
/// <param name="outFile">解密后输出文件</param>
/// <param name="password">解密密码</param>
public void DecryptFile(string inFile, string outFile, string password)
{
// 创建打开文件流
using (FileStream fin = File.OpenRead(inFile),
fout = File.OpenWrite(outFile))
{
int size = (int)fin.Length;
byte[] bytes = new byte[BUFFER_SIZE];
int read = -1;
int value = 0;
int outValue = 0; byte[] IV = new byte[16];
fin.Read(IV, 0, 16);
byte[] salt = new byte[16];
fin.Read(salt, 0, 16); SymmetricAlgorithm sma = CreateRijndael(password, salt);
sma.IV = IV; value = 32;
long lSize = -1; // 创建散列对象, 校验文件
HashAlgorithm hasher = SHA256.Create(); using (CryptoStream cin = new CryptoStream(fin, sma.CreateDecryptor(), CryptoStreamMode.Read),
chash = new CryptoStream(Stream.Null, hasher, CryptoStreamMode.Write))
{
// 读取文件长度
BinaryReader br = new BinaryReader(cin);
lSize = br.ReadInt64();
ulong tag = br.ReadUInt64(); if (FC_TAG != tag)
throw new CryptoHelpException("文件被破坏"); long numReads = lSize / BUFFER_SIZE; long slack = (long)lSize % BUFFER_SIZE; for (int i = 0; i < numReads; ++i)
{
read = cin.Read(bytes, 0, bytes.Length);
fout.Write(bytes, 0, read);
chash.Write(bytes, 0, read);
value += read;
outValue += read;
} if (slack > 0)
{
read = cin.Read(bytes, 0, (int)slack);
fout.Write(bytes, 0, read);
chash.Write(bytes, 0, read);
value += read;
outValue += read;
} chash.Flush();
chash.Close(); fout.Flush();
fout.Close(); byte[] curHash = hasher.Hash; // 获取比较和旧的散列对象
byte[] oldHash = new byte[hasher.HashSize / 8];
read = cin.Read(oldHash, 0, oldHash.Length);
if ((oldHash.Length != read) || (!CheckByteArrays(oldHash, curHash)))
throw new CryptoHelpException("文件被破坏");
} if (outValue != lSize)
throw new CryptoHelpException("文件大小不匹配");
}
} }
}

Demo下载

C#文件加密解密的更多相关文章

  1. linux环境下给文件加密/解密的方法

      原文地址:linix环境下给文件加密/解密的方法 作者:oracunix 一. 利用 vim/vi 加密:优点:加密后,如果不知道密码,就看不到明文,包括root用户也看不了:缺点:很明显让别人知 ...

  2. python-GUI-pyqt5之文件加密解密工具

    pyqt5的文件加密解密程序,用到base64,rsa和aes进行混合解密,代码比较杂乱,可自行整理,仅供学习参考之用,如需转载,请联系博主或附上博客链接,下面直接干货. 程序截图如下: # -*- ...

  3. android 中文件加密 解密 算法实战

    现在项目里面有一个需求,本项目里面下载的视频和文档都不允许通过其他的播放器播放,在培训机构里面这样的需求很多.防止有人交一份钱,把所有的课件就拷给了别人.这样的事情培训机构肯定是不愿意的.现在我项目里 ...

  4. linux 使用vim文件加密/解密的方法

    一. 利用 vim/vi 加密:优点:加密后,如果不知道密码,就看不到明文,包括root用户也看不了:缺点:很明显让别人知道加密了,容易让别人把加密的文件破坏掉,包括内容破坏和删除: vi编辑器相信大 ...

  5. Spring boot RSA 文件加密解密

    github项目地址 rsa_demo ##测试 加密D:/hello/test.pdf 文件,生成加密后的文件 testNeedDecode.pdf 对testNeedDecode.pdf 文件进行 ...

  6. 文件加密 解密 pdftk openssl gpg vim

    openssl加密和解密 . openssl des -salt -in file -out file.des openssl des -d -salt -in file.des -out file ...

  7. ABAP文件加密解密-PGP

    1.SM69创建命令 2.解密 DATA: lv_para = '--passphrase (key) -o /oracle/sfdata/sfdata.csv -d /oracle/sfdata/s ...

  8. php文件加密解密

    利用base64加解密 base64_encode是加密,而base64_decode是解密 语法:string base64_encode(string data);   语法:string bas ...

  9. C#做的一个加密/解密的类

    转自:http://www.16aspx.com/Article/3904 using System; using System.Security.Cryptography; using System ...

  10. DES加密解密帮助类

    public class DESCrypto { /// <summary> /// 初始化des实例秘钥及向量 /// </summary> /// <param na ...

随机推荐

  1. display的值及作用

    display的值及作用 display属性可以设置元素的内部和外部显示类型,元素的外部显示类型将决定该元素在流式布局中的表现,例如块级或内联元素,元素的内部显示类型可以控制其子元素的布局,例如gri ...

  2. Java设计模式-桥接模式Bridge

    传统模式 案例 要求对不同手机类型的不同品牌实现操作编程(比如:开机.关机.上网,打电话等),如图: 类图 问题 扩展性问题(类爆炸),如果我们再增加手机的样式(旋转式),就需要增加各个品牌手机的类, ...

  3. C++ 控制台程序的线程分析

    在无任何功能代码的情况下运行控制台,会发现有三个线程在运行 SO 的答案指出,在程序一开始运行时,为加快进程启动,windows 会利用多个 CPU 内核更快地初始化. ntdll.dll 线程实际上 ...

  4. 开源:Taurus.DistributedLock 分布式锁框架,支持 .Net 和 .Net Core 双系列版本

    前言: 在经过漫长的技术沉淀,终于又为 .Net 及 .Net Core 的微服务系列框架贡献当中的一个重要组件. Taurus.DistributedLock is a distributed lo ...

  5. golang常用库包:redis操作库go-redis使用(03)-高级数据结构和其它特性

    Redis 高级数据结构操作和其它特性 第一篇:go-redis使用,介绍Redis基本数据结构和其他特性,以及 go-redis 连接到Redis https://www.cnblogs.com/j ...

  6. android 逆向笔记

    壳检测工具 GDA 2. 逆向分析APP 一般流程 1. 使用自动化检测工具检测APP是否加壳,或者借助一些反编译工具依靠经验判断是否加壳 2. 如果apk加壳,则需要先对apk进行脱壳 3. 使用` ...

  7. python装饰器保留原有函数名称和属性functools.wraps()

    # python装饰器在实现的时候,被装饰后的函数其实已经是另外一个函数了(函数名等函数属性会发生改变),为了不影响,python的functools包中提供了一个叫wraps的decorator来消 ...

  8. zookeeper运行时dos窗口一闪而过

    错误:从官网下载zookeeper解压到本地之后,鼠标双击运行zkServer.cmd文件,dos窗口一闪而过,看不到错误原因: 解决方法:通过dos窗口执行zkServer.cmd文件,对应的错误信 ...

  9. 第一百零一篇:DOM节点类型

    好家伙,   DOM DOM是javascript操作网页的接口,全称为文档对象模型(Document Object Model).它的作用是将网页转为一个javascript对象, 从而可以使用ja ...

  10. Java 重写小练习

    1 package com.bytezero.inherit3; 2 3 public class CylinderTest 4 { 5 public static void main(String[ ...