日期:2014-05-18  浏览次数:20497 次

有志气不做分奴的高手请进!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
本人要用到DES加密技术,下了一个代码来看,没有多大难度,但是它把加密后的密文保存在生成的TXT文本里,而我需要的是把密文保存在数据库里.在这个环节我不知道在怎么改!
======================这是加密过程它把密文保存在TXT里
//初始序列化
FileStream   fs   =   new   FileStream( "D:\\target.txt ",   FileMode.OpenOrCreate,   FileAccess.Write);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter   br   =   new   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
  //显示密文
cbox.Text   =   System.Text.Encoding.Default.GetString(System.Text.Encoding.Default.GetBytes(cchar));
  //序列化密文到文件
br.Serialize(fs,   cchar);
fs.Close();
--------------------------这一步,我我把前面的步骤忽略掉,直接保存System.Text.Encoding.Default.GetString(System.Text.Encoding.Default.GetBytes(cchar));所得的结果
改后,执行时没有出什么问题
=======================这是解密时从TXT里取出密文
  //从文件反序列化或得密文char形式
  FileStream   fs   =   new   FileStream( "D:\\target.txt ",   FileMode.OpenOrCreate,   FileAccess.Read);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter   bf   =   new   System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
char[]   cchar   =   (char[])bf.Deserialize(fs);
----------------------------这一不,我把前面的步骤忽略掉,直接改最后一步
  char[]   cchar   =   [直接从数据库读取数据出来].ToCharArray();
改后,执行时总是出错
  divcchar[i][7]   =   cchar[i   *   8   +   7];索引超出了数组界限。  


不知道是什么原因,估计是我改错了吧.请问正确的改法该怎么改?
我就只剩10分了~~~~~~~~~

------解决方案--------------------
public string DesEncrypt(string strText,string strEncrKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(strEncrKey.Substring(0, strEncrKey.Length));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());


}
catch (System.Exception error)
{
return "error: " + error.Message + "\r ";
}

}
//解密
public string DesDecrypt(string strText, string sDecrKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] inputByteArray = new Byte[strText.Length];
try
{
byKey = System.Text.Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
System.Text.Encoding encoding = new System.Text.UTF8Encoding();
return encoding.GetString(ms.ToArray());
}
catch (System.Exception error)
{
return "error: " + error.Message + "\r ";
}
}