using system;
using system.security.cryptography;
using system.text;
using system.io;
using system.windows.forms;
namespace curllion
{
public class crypt
{
private byte[] key;
private byte[] iv;
private system.text.asciiencoding asciiencoding;
private system.text.unicodeencoding textconverter;
private rc2cryptoserviceprovider rc2csp;
public crypt()
{
initializecomponent();
}
private void initializecomponent()
{
key = new byte[]{106,51,25,141,157,142,23,111,234,159,187,154,215,34,37,204};
iv = new byte[]{135,186,133,136,184,149,153,144};
asciiencoding = new system.text.asciiencoding();
textconverter = new system.text.unicodeencoding();
rc2csp = new rc2cryptoserviceprovider();
}
/// <summary>
/// 新建一个大小为10261b的文件,以便将加密数据写入固定大小的文件。
/// </summary>
/// <param name="filepath">文件保存的地址,包含文件名</param>
public void initbinfile(string filepath)
{
byte[] tmp = new byte[10261];
try //创建文件流,将其内容全部写入0
{
system.io.filestream writefilestream = new filestream(filepath,
system.io.filemode.create,
system.io.fileaccess.write,
system.io.fileshare.none,512,false);
for(int i = 0 ;i< 10261;i++)
tmp[i] = 0;
writefilestream.write(tmp,0,10261);
writefilestream.flush();
writefilestream.close();
}
catch(system.io.ioexception)
{
messagebox.show("文件操作错误!","错误!",messageboxbuttons.ok,messageboxicon.error);
}
}
/// <summary>
/// 将文本数据加密后写入一个文件,其中,这个文件是用initbinfile建立的,这个文件将被分成十块,
/// 用来分别保存10组不同的数据,第一个byte位保留,第2位到第21位分别用来存放每块数据的长度,但
/// 一个byte的取值为0-127,所以,用两个byte来存放一个长度。
/// </summary>
/// <param name="toencrypttext">要加密的文本数据</param>
/// <param name="filepath">要写入的文件</param>
/// <param name="dataindex">写入第几块,取值为1--10</param>
/// <returns>是否操作成功</returns>
public bool encrypttofile(string toencrypttext,string filepath,int dataindex)
{
bool r = false;
if(dataindex > 10 && dataindex < 1)
{
messagebox.show("数据索引的取值范围在1至10之间!","错误!",
messageboxbuttons.ok,messageboxicon.error);
return r;
}
byte[] encrypted;
//打开要写入的文件,主要是为了保持原文件的内容不丢失
system.io.filestream tmpfilestream= new filestream(filepath,
system.io.filemode.open,
system.io.fileaccess.read,
system.io.fileshare.none,1024,true);