C#文件加密

neverhooder1234 2009-03-13 08:12:01
C#里面有一个DES类,专门加密的,MSDN上面用DES是对字符串加密,我想用这个对一个文件内容加密,有会的高手麻烦贴出代码,谢谢
...全文
533 19 打赏 收藏 转发到动态 举报
写回复
用AI写文章
19 条回复
切换为时间正序
请发表友善的回复…
发表回复
xiangsiqwxq 2012-05-05
  • 打赏
  • 举报
回复
新手 看的头大 学习了
lylbin 2012-04-10
  • 打赏
  • 举报
回复
不错,都全了
热学沸腾56 2009-04-02
  • 打赏
  • 举报
回复
进来学习。。顶!
  • 打赏
  • 举报
回复
/// <summary>
/// 解密文件
/// </summary>
/// <param name="srcFileName"></param>
/// <param name="objFileName"></param>
/// <param name="key"></param>
public static 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 Exception("文件被破坏");

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 Exception("文件被破坏");
}

if (outValue != lSize)
throw new Exception("文件大小不匹配");
}
}

/// <summary>
/// 加密二进制流,密钥传入

/// </summary>
/// <param name="original"></param>
/// <param name="key"></param>
/// <returns></returns>
public static byte[] Encrypt(byte[] original, byte[] key)
{
TripleDESCryptoServiceProvider provider = new TripleDESCryptoServiceProvider();
provider.Key = MakeMD5(key);
provider.Mode = CipherMode.ECB;
return provider.CreateEncryptor().TransformFinalBlock(original, 0, original.Length);
}

}
}

  • 打赏
  • 举报
回复
你不用去关注这个IV,事实上MSDN上例程给你造成误导了,你用我的这个类就行,其中给你隐藏了IV这个细节。你在一台机器上加密文件,在另外一台机器上解密文件就行。效率还行。
namespace cn.ccets.utility.DEncrypt
{
using System;
using System.Security.Cryptography;
using System.Text;
using System.IO;

/// <summary>
/// Module ID: COMMON Utility
/// Depiction: DES文件(二进制流)加解密
/// Author: lmj
/// Create Date: 2008-01-17
/// </summary>
public sealed class DEncrypt
{
private const ulong FC_TAG = 0xFC010203040506CF;
private const int BUFFER_SIZE = 128 * 1024;

/// <summary>
/// 检验两个Byte数组是否相同
/// </summary>
/// <param name="b1">Byte数组</param>
/// <param name="b2">Byte数组</param>
/// <returns>true-相等</returns>
private static 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 SymmetricAlgorithm
/// </summary>
/// <param name="password">密码</param>
/// <param name="salt"></param>
/// <returns>加密对象</returns>
private static 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>
private static RandomNumberGenerator rand = new RNGCryptoServiceProvider();

/// <summary>
/// 生成指定长度的随机Byte数组
/// </summary>
/// <param name="count">Byte数组长度</param>
/// <returns>随机Byte数组</returns>
private static byte[] GenerateRandomBytes(int count)
{
byte[] bytes = new byte[count];
rand.GetBytes(bytes);
return bytes;
}


/// <summary>
/// 加密文件
/// </summary>
/// <param name="srcFileName"></param>
/// <param name="objFileName"></param>
/// <param name="key"></param>
public static 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();
}
}
}
liuliyong106 2009-03-17
  • 打赏
  • 举报
回复
#region 对数据进行加密
/// <summary>
/// 对数据进行加密
/// </summary>
/// <param name="encryptstring">需要加密的数据</param>
/// <returns></returns>
public string DESEncrypt(string encryptstring)
{
string strRtn;
try
{
DESCryptoServiceProvider desc = new DESCryptoServiceProvider();//des进行加密
byte[] key = System.Text.Encoding.Unicode.GetBytes(encryptkey);
byte[] data = System.Text.Encoding.Unicode.GetBytes(encryptstring);
MemoryStream ms = new MemoryStream();//存储加密后的数据
CryptoStream cs = new CryptoStream(ms, desc.CreateEncryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);//进行加密
cs.FlushFinalBlock();
strRtn = Convert.ToBase64String(ms.ToArray());
return strRtn;
}

catch (Exception ex)
{
MessageBox.Show("错误:" + ex.Message, "错误消息提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
return null;
}
}
#endregion

#region 对数据进行解密
/// <summary>
/// 对数据进行解密
/// </summary>
/// <param name="decryptstring">需要解密的数据</param>
/// <returns></returns>
public string DESDecrypt(string decryptstring)
{
string strRtn;
try
{
DESCryptoServiceProvider desc = new DESCryptoServiceProvider();
byte[] key = System.Text.Encoding.Unicode.GetBytes(encryptkey);
byte[] data = Convert.FromBase64String(decryptstring);
MemoryStream ms = new MemoryStream();//存储解密后的数据
CryptoStream cs = new CryptoStream(ms, desc.CreateDecryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);//解密数据
cs.FlushFinalBlock();
strRtn = System.Text.Encoding.Unicode.GetString(ms.ToArray());
return strRtn;
}
catch (Exception ex)
{
MessageBox.Show("错误:" + ex.Message, "错误消息提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
return null;
}


看懂没有亚
}
#endregion
Rotel-刘志东 2009-03-17
  • 打赏
  • 举报
回复
#region   数据进行加密
/// <summary>
/// 数据进行加密
/// </summary>
/// <param name="encryptstring">加密数据</param>
///<param name="encryptstring">

public string DESEncrypt(string encryptstring)
{
string strRtn;
try
{
DESCryptoServiceProvider desc = new DESCryptoServiceProvider();//des进行加密
byte[] key = System.Text.Encoding.Unicode.GetBytes(encryptkey);
byte[] data = System.Text.Encoding.Unicode.GetBytes(encryptstring);
MemoryStream ms = new MemoryStream();//存储加密数据
CryptoStream cs = new CryptoStream(ms, desc.CreateEncryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);//进行加密
cs.FlushFinalBlock();
strRtn = Convert.ToBase64String(ms.ToArray());
return strRtn;
}

catch (Exception ex)
{
MessageBox.Show("错误:" + ex.Message, "错误消息提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
return null;
}
}
#endregion
Maroozaa 2009-03-17
  • 打赏
  • 举报
回复
前段时间写的加解密程序中利用DES加解密的函数

private static void EncryptData1(String inName, String outName, byte[] desKey, byte[] desIV)
{
//Create the file streams to handle the input and output files.
FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);

//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.

DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

// Console.WriteLine("Encrypting...");

//Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
long a = bin.Length;
encStream.Write(bin, 0, len);
rdlen = rdlen + a;
// Console.WriteLine("{0} bytes processed", rdlen);
}

encStream.Close();
fout.Close();
fin.Close();
}
private static void DecryptData1(String inName, String outName, byte[] desKey, byte[] desIV)
{
//Create the file streams to handle the input and output files.
FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);

//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.

DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);

// Console.WriteLine("Encrypting...");

//Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
long a = bin.Length;
encStream.Write(bin, 0, len);
rdlen = rdlen + a;
// Console.WriteLine("{0} bytes processed", rdlen);
}

encStream.Close();
fout.Close();
fin.Close();
}
lchh0917 2009-03-17
  • 打赏
  • 举报
回复
加密和解密是不可少的咯~

#region 对数据进行加密
/// <summary>
/// 对数据进行加密
/// </summary>
/// <param name="encryptstring">需要加密的数据</param>
/// <returns></returns>
public string DESEncrypt(string encryptstring)
{
string strRtn;
try
{
DESCryptoServiceProvider desc = new DESCryptoServiceProvider();//des进行加密
byte[] key = System.Text.Encoding.Unicode.GetBytes(encryptkey);
byte[] data = System.Text.Encoding.Unicode.GetBytes(encryptstring);
MemoryStream ms = new MemoryStream();//存储加密后的数据
CryptoStream cs = new CryptoStream(ms, desc.CreateEncryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);//进行加密
cs.FlushFinalBlock();
strRtn = Convert.ToBase64String(ms.ToArray());
return strRtn;
}

catch (Exception ex)
{
MessageBox.Show("错误:" + ex.Message, "错误消息提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
return null;
}
}
#endregion

#region 对数据进行解密
/// <summary>
/// 对数据进行解密
/// </summary>
/// <param name="decryptstring">需要解密的数据</param>
/// <returns></returns>
public string DESDecrypt(string decryptstring)
{
string strRtn;
try
{
DESCryptoServiceProvider desc = new DESCryptoServiceProvider();
byte[] key = System.Text.Encoding.Unicode.GetBytes(encryptkey);
byte[] data = Convert.FromBase64String(decryptstring);
MemoryStream ms = new MemoryStream();//存储解密后的数据
CryptoStream cs = new CryptoStream(ms, desc.CreateDecryptor(key, key), CryptoStreamMode.Write);
cs.Write(data, 0, data.Length);//解密数据
cs.FlushFinalBlock();
strRtn = System.Text.Encoding.Unicode.GetString(ms.ToArray());
return strRtn;
}
catch (Exception ex)
{
MessageBox.Show("错误:" + ex.Message, "错误消息提示框", MessageBoxButtons.OKCancel, MessageBoxIcon.Error);
return null;
}
}
#endregion
neverhooder1234 2009-03-17
  • 打赏
  • 举报
回复
搞了半天还是对字符串加密,要是文件里不是字符串看怎么办
neverhooder1234 2009-03-14
  • 打赏
  • 举报
回复
晕!MSDN上那段代码你用给我看看来!我不是不查MSDN
byte[] desKey, byte[] desIV
后面这两个鸟参数,你写个能用的给我看看来
柳晛 2009-03-14
  • 打赏
  • 举报
回复
[Quote=引用 3 楼 yeah86 的回复:]
文件里面的内容不就是一个很长的字符串么?
[/Quote]

是这样。

如果怕效率低,可以加密部分。
hechenqingtian 2009-03-14
  • 打赏
  • 举报
回复
using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Text;

/// <summary>
/// EncryptString 的摘要说明
/// </summary>
public class EncryptString
{
public EncryptString()
{
//
// TODO: 在此处添加构造函数逻辑
//
}

public string Access(string content, string password)
{
byte[] con = (new UnicodeEncoding()).GetBytes(content);
byte[] pass = (new UnicodeEncoding()).GetBytes(password);

for (int i = 0; i < con.Length; i += 2)
{
for (int j = 0; j < pass.Length; j += 2)
{
con[i] = Convert.ToByte(con[i]^pass[j]);
}
}

return (new UnicodeEncoding()).GetString(con).TrimEnd('\0');
}
}
hechenqingtian 2009-03-14
  • 打赏
  • 举报
回复
MD5 md5=new MD5CryptoServiceProvider();
byte[] data=System.Text.Encoding.Default.GetBytes(str);
byte[] result=md5.ComputeHash(data);
String ret="";
for(int i=0;i<result.Length;i++)
ret+=result[i].ToString("x").PadLeft(2,'0');
yeah86 2009-03-13
  • 打赏
  • 举报
回复
文件里面的内容不就是一个很长的字符串么?
八爪鱼-杭州 2009-03-13
  • 打赏
  • 举报
回复
现在人连msdn都懒得查了吗?

private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
{
//Create the file streams to handle the input and output files.
FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);

//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.

DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);

Console.WriteLine("Encrypting...");

//Read from the input file, then encrypt and write to the output file.
while(rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
Console.WriteLine("{0} bytes processed", rdlen);
}

encStream.Close();
fout.Close();
fin.Close();
}
麻子Mozart 2009-03-13
  • 打赏
  • 举报
回复
up

111,126

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Creator Browser
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧