加密后内容

代码

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. Swoole从入门到入土(16)——WebSocket服务器[事件]

    WIKI: 问:websocket协议虽然和http协议不同,但是兼容于http协议,如何判断客户端连接使用的是http协议? 答:通过使用 $server->connection_info($ ...

  2. 基于java的个人博客

    基于java的个人博客 效果预览 首页 详情 文章管理 文章发布 分类管理 访问地址 前台地址http://localhost:8080 后台地址:http://localhost/admin/ 开发 ...

  3. 老生常谈的iOS- weak原理,你真的懂得还是为了应付面试

    前言 weak对于iOS开发来说只要解决一些对象相互引用的时候,避免出现强强引用,对象不能被释放,出现内存泄露的问题. weak 关键字的作用域弱引用,所引用对象的计数器不会加一,并在引用对象被释放的 ...

  4. Swift高级进阶-Swift编译过程,”SIL代码“,“IR语法”

    swift编译过程 如果不懂LLVM,Clang的同学可以去了解下它的知识点  一些文章中有详细介绍 OC 的编译过程 ,本文来探索一下 Swift 的编译过程.Swift 的编译过程中使用 Swif ...

  5. Java 常见的两个错误 -------1.栈溢出 java.lang.StackOverflowError 2.堆溢出 java.lang.OutOfMemoryError /OOM

    1 package com.bytezero.exception; 2 3 /** 4 * 5 * @Description Error 6 * @author Bytezero·zhenglei! ...

  6. Java 封装性的四种权限测试 + 总结

    *    总结封装性:Java提供了4中权限修饰符来修饰类及类的内部结构,体现类及类的内部结构再被调用时的可见性的大小 1 package com.bytezero.circle; 2 3 publi ...

  7. 聊聊CWE 4.14 与 ISA/IEC 62443中,如何保障工业软件的安全性

    本文分享自华为云社区<CWE 4.14 与 ISA/IEC 62443>,作者:Uncle_Tom. 1. 序言 随着 5G 的应用,物联的网发展,越来越多的自动化控制系统.云服务在工业控 ...

  8. Lock wait timeout exceeded; try restarting transaction-Mysql报错

    一.问题由来 现在在做一个小程序的后台,使用Java写的,数据库使用的Mysql,之前一直调试的时候都好好的,今天在调试的时候突然就报一个错: ### Error updating database. ...

  9. iview 表单验证 爆红后,有某些组件现隐,爆红和必填会错位,解决方案 组件上加key

    iview 表单验证 爆红后,有某些组件现隐,爆红和必填会错位,解决方案 组件上加key

  10. 流数据库-RisingWave

    参考: https://docs.risingwave.com/docs/current/architecture/ https://www.risingwavetutorial.com/docs/i ...