.net 下文件加密和解密

发布时间:2009年06月04日      浏览次数:565 次
关键词:.net 2005 Framework 加密解密文件
正文:
用XML文件记录配置信息时,有时候不希望别人看到配置信息的内容.怎么才能实现呢.这里介绍几种常见的加密和解密算法.这些算法Framework已经封装好了.我们不用理会具体的实现,只需要会用就行.下面给出一个源程序供大家参考.
using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
namespace coder
{
/// <summary>
/// SymmCrypto 的摘要说明。
/// SymmCrypto类实现.NET框架下的加密和解密服务。
/// 原作者: Frank Fang : fangfrank@hotmail.com
///改进者:ligang : nkligang@163.com
/// </summary>
public class SymmCrypto
{
public enum SymmProvEnum : int
{
DES, RC2, Rijndael
}
private SymmetricAlgorithm mobjCryptoService;
/// <remarks>
/// 使用.Net SymmetricAlgorithm 类的构造器.
/// </remarks>
public SymmCrypto(SymmProvEnum NetSelected)
{
switch (NetSelected)
{
case SymmProvEnum.DES:
mobjCryptoService = new DESCryptoServiceProvider();
break;
case SymmProvEnum.RC2:
mobjCryptoService = new RC2CryptoServiceProvider();
break;
case SymmProvEnum.Rijndael:
mobjCryptoService = new RijndaelManaged();
break;
}
}
/// <remarks>
/// 使用自定义SymmetricAlgorithm类的构造器.
/// </remarks>
public SymmCrypto(SymmetricAlgorithm ServiceProvider)
{
mobjCryptoService = ServiceProvider;
}
/// <remarks>
/// Depending on the legal key size limitations of
/// a specific CryptoService provider and length of
/// the private key provided, padding the secret key
/// with space character to meet the legal size of the algorithm.
/// </remarks>
private byte[] GetLegalKey(string Key)
{
string sTemp;
if (mobjCryptoService.LegalKeySizes.Length > 0)
{
int lessSize = 0, moreSize = mobjCryptoService.LegalKeySizes[0].MinSize;
// key sizes are in bits
while (Key.Length * 8 > moreSize)
{
lessSize = moreSize;
moreSize += mobjCryptoService.LegalKeySizes[0].SkipSize;
}
sTemp = Key.PadRight(moreSize / 8, ' ');
}
else
sTemp = Key;
// convert the secret key to byte array
return ASCIIEncoding.ASCII.GetBytes(sTemp);
}
public byte[] Encrypting(byte[] bytIn, string Key)
{
// create a MemoryStream so that the process can be done without I/O files
System.IO.MemoryStream ms = new System.IO.MemoryStream();
byte[] bytKey = GetLegalKey(Key);
// set the private key
mobjCryptoService.Key = bytKey;
mobjCryptoService.IV = bytKey;
// create an Encryptor from the Provider Service instance
ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
// create Crypto Stream that transforms a stream using the encryption
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
// write out encrypted content into MemoryStream
cs.Write(bytIn, 0, bytIn.Length);
cs.FlushFinalBlock();
// get the output and trim the '\0' bytes
byte[] bytOut = ms.GetBuffer();
return bytOut;
}
public byte[] Decrypting(byte[] bytIn, string Key)
{
// create a MemoryStream with the input
System.IO.MemoryStream ms = new System.IO.MemoryStream(bytIn, 0, bytIn.Length);
byte[] bytKey = GetLegalKey(Key);
// set the private key
mobjCryptoService.Key = bytKey;
mobjCryptoService.IV = bytKey;
// create a Decryptor from the Provider Service instance
ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
// create Crypto Stream that transforms a stream using the decryption
CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
// read out the result from the Crypto Stream
cs.Write(bytIn, 0, bytIn.Length);
cs.Flush();
return ms.ToArray();
}
}
}
下面给出具体使用的例子:
//编码
public bool Encoding(string inputfile,string outputfile)
{
byte[] buffer = new byte[1024];
byte[] buf = new byte[1032];
int temp;
coder.SymmCrypto coding = new SymmCrypto(coder.SymmCrypto.SymmProvEnum.DES);
if (System.IO.File.Exists(inputfile))
{
// 定义文件读取类
Stream inStream = File.Open(inputfile,FileMode.Open);
Stream outStream = File.Create(outputfile);
// 读取文件
do
{
temp = inStream.Read(buffer, 0, 1024);
buf = coding.Encrypting(buffer, "12345678");
if (temp > 0)
{
outStream.Write(buf, 0, temp+8);
}
else
break;
}
while (true);
// 释放流资源
inStream.Close();
outStream.Close();
}
return true;
}
//解码
public bool Decoding(string inputfile, string outputfile)
{
byte[] buffer = new byte[1032];
byte[] buf = new byte[1024];
int temp;
coder.SymmCrypto coding = new SymmCrypto(coder.SymmCrypto.SymmProvEnum.DES);
if (System.IO.File.Exists(inputfile))
{
Stream inStream = File.Open(inputfile, FileMode.Open);
Stream outStream = File.Create(outputfile);
do
{
temp = inStream.Read(buffer, 0, 1032);
buf = coding.Decrypting(buffer, "12345678");
if (temp > 0)
{
outStream.Write(buf, 0, temp-8);
}
else
break;
}
while (true);
inStream.Close();
outStream.Close();
}
return true;
}
需要说明的几点问题:
1.本程序适用于对文件的加密和解密.源作者的加密和解密程序对于二进制文件甚至文本文件的读写是存在问题的
2.本程序去掉了源程序中base64编码和解码过程.因为存在这样的问题,对于文件内容进行加密后可能会出现字符0(ASCII),而这个特殊字符在base64编码中会出问题.base64编码函数会认为0是结束并把以后的部分填充一些字符.
3.针对于文件输入输出缓冲区大小问题.考虑到加密后字符数目会增加8个.所以读入的缓冲区在加密时应当比写入的缓冲区小8,但是解密部分可以不采取读入缓冲区大小比写入缓冲区大小大8个字符的方案,但是建议按照这个方案进行.
免责声明:本站相关技术文章信息部分来自网络,目的主要是传播更多信息,如果您认为本站的某些信息侵犯了您的版权,请与我们联系,我们会即时妥善的处理,谢谢合作!