c#实现文件加解密

None.gif using  System;
None.gif
using  System.IO;
None.gif
using  System.Data;
None.gif
using  System.Text;
None.gif
using  System.Windows.Forms;
None.gif
using  System.Collections;
None.gif
using  System.Collections.Generic;
None.gif
using  System.Security.Cryptography;
None.gif
using  System.Threading;
None.gif
using  System.ComponentModel;
None.gif
None.gif
namespace  aaa
ExpandedBlockStart.gifContractedBlock.gif
dot.gif {
InBlock.gif     
class En_Dn
ExpandedSubBlockStart.gifContractedSubBlock.gif    
dot.gif{
InBlock.gif     
InBlock.gif        
private Hashtable hs = new Hashtable();
InBlock.gif        
private RijndaelManaged myRijndael;
InBlock.gif        
private string Key = "";
InBlock.gif        
private string IV = "~!#@$%HGF^&%&^hggk)KJKL989#er345(&*(HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
InBlock.gif      
InBlock.gif        
private string 解密(string files, int a)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
int id = 0;
InBlock.gif                hs.Clear();
InBlock.gif                hs.Add(id
++, files);
InBlock.gif                
string CPath = Path.GetDirectoryName(files);
InBlock.gif                
string FileName = Path.GetFileName(files);
InBlock.gif
InBlock.gif                myRijndael 
= new RijndaelManaged();
InBlock.gif
InBlock.gif                
string inFileName = "";
InBlock.gif                
foreach (System.Collections.DictionaryEntry de in this.hs)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    inFileName 
= (string)de.Value;
ExpandedSubBlockEnd.gif                }

InBlock.gif                FileStream fin 
= new FileStream(inFileName, FileMode.Open, FileAccess.Read);
InBlock.gif                StreamReader sr 
= new StreamReader(fin);
InBlock.gif                
char[] infolengthchar = new char[5];//文件的最后五个字符代表加密后的文件信息长度
InBlock.gif
                fin.Seek(-5, SeekOrigin.End);
InBlock.gif                sr.Read(infolengthchar, 
05);
InBlock.gif                
string infolengthstr = new string(infolengthchar);
InBlock.gif                
int infolength = Convert.ToInt32(infolengthstr);//加密后的文件信息长度
InBlock.gif
                fin.Seek(-(5 + infolength), SeekOrigin.End);
InBlock.gif                
char[] Filedatachar = new char[infolength];
InBlock.gif                sr.Read(Filedatachar, 
0, infolength);
InBlock.gif                
string Filedatastr = new string(Filedatachar);
InBlock.gif                Filedatastr 
= this.Decrypt(Filedatastr);
InBlock.gif                
int count = Convert.ToInt32(Filedatastr.Substring(Filedatastr.Length - 55));
InBlock.gif                FileInfomation[] FI 
= new FileInfomation[count];
InBlock.gif                
for (int i = 0; i < count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    FI[i] 
= new FileInfomation();
InBlock.gif                    
// FI[i].Filename = Filedatastr.Substring(i * 150, 100).TrimStart(new char[] { ' ' });
ExpandedSubBlockStart.gifContractedSubBlock.gif
                    FI[i].Filename = "~" + Filedatastr.Substring(i * 150100).TrimStart(new char[] dot.gif' ' });
ExpandedSubBlockStart.gifContractedSubBlock.gif                    FI[i].Size 
= Convert.ToInt32(Filedatastr.Substring(i * 150 + 10050).TrimStart(new char[] dot.gif' ' }));
ExpandedSubBlockEnd.gif                }

InBlock.gif                fin.Close();
InBlock.gif                
//已得到该文件中包括的文件个数、文件名、长度。开始解密。
InBlock.gif
                long start = 0, currentlength = 0;
InBlock.gif
InBlock.gif                
string outFileName = CPath + "\\" + FI[0].Filename;
InBlock.gif                
for (int i = 0; i < count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    outFileName 
= CPath + "\\" + FI[i].Filename;
InBlock.gif                    File.Delete(outFileName);
InBlock.gif                    currentlength 
= FI[i].Size;
InBlock.gif
InBlock.gif                    fin 
= new FileStream(inFileName, FileMode.Open, FileAccess.Read);
InBlock.gif                    FileStream fout 
= new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
InBlock.gif                    fout.SetLength(
0);
InBlock.gif                    fin.Seek(start, SeekOrigin.Begin);
InBlock.gif                    
int cut = 100000;
InBlock.gif                    
byte[] bin = new byte[cut];
InBlock.gif                    
long rdlen = 0;
InBlock.gif                    
long totlen = currentlength;
InBlock.gif                    
int len;
InBlock.gif                    myRijndael.Key 
= GetLegalKey();
InBlock.gif                    myRijndael.IV 
= GetLegalIV();
InBlock.gif                    ICryptoTransform encrypto 
= myRijndael.CreateDecryptor();
InBlock.gif                    CryptoStream cs 
= new CryptoStream(fout, encrypto, CryptoStreamMode.Write);
InBlock.gif                    
while (rdlen < totlen)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
int report = (int)(((double)rdlen / totlen) * 1000);
InBlock.gif                        
if (totlen - rdlen < cut)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            cut 
= (int)(totlen - rdlen);
InBlock.gif                            rdlen 
= totlen;
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        len 
= fin.Read(bin, 0, cut);
InBlock.gif                        cs.Write(bin, 
0, len);
InBlock.gif                        rdlen 
= rdlen + len;
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    cs.Close();
InBlock.gif                    cs.Dispose();
InBlock.gif
InBlock.gif                    fout.Close();
InBlock.gif                    fout.Dispose();
InBlock.gif
InBlock.gif                    fin.Close();
ExpandedSubBlockEnd.gif                }

InBlock.gif
InBlock.gif                fin.Dispose();
InBlock.gif
InBlock.gif                
return outFileName;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
// MessageBox.Show("在文件解密的时候出现错误!错误提示: \n" + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
InBlock.gif
                return "";
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif        
private string 解密(string files)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
int id = 0;
InBlock.gif                hs.Clear();
InBlock.gif                hs.Add(id
++, files);
InBlock.gif                
string pw = "";
InBlock.gif                
string CPath = Path.GetDirectoryName(files);
InBlock.gif                
//FileName = Path.GetFileNameWithoutExtension(this.files) + "~.tif";
InBlock.gif
                string FileName = Path.GetFileName(files);
InBlock.gif
InBlock.gif                myRijndael 
= new RijndaelManaged();
InBlock.gif                Key 
= pw;
InBlock.gif                IV 
= "~!#@$%HGF^&%&^hggk)KJKL989#er345(&*(HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
InBlock.gif                
//Directory.CreateDirectory(CPath + "\\已解密的文件");
InBlock.gif

InBlock.gif                
string inFileName = "";
InBlock.gif                
foreach (System.Collections.DictionaryEntry de in this.hs)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    inFileName 
= (string)de.Value;
ExpandedSubBlockEnd.gif                }

InBlock.gif                FileStream fin 
= new FileStream(inFileName, FileMode.Open, FileAccess.Read);
InBlock.gif                StreamReader sr 
= new StreamReader(fin);
InBlock.gif                
char[] infolengthchar = new char[5];//文件的最后五个字符代表加密后的文件信息长度
InBlock.gif
                fin.Seek(-5, SeekOrigin.End);
InBlock.gif                sr.Read(infolengthchar, 
05);
InBlock.gif                
string infolengthstr = new string(infolengthchar);
InBlock.gif                
int infolength = Convert.ToInt32(infolengthstr);//加密后的文件信息长度
InBlock.gif
                fin.Seek(-(5 + infolength), SeekOrigin.End);
InBlock.gif                
char[] Filedatachar = new char[infolength];
InBlock.gif                sr.Read(Filedatachar, 
0, infolength);
InBlock.gif                
string Filedatastr = new string(Filedatachar);
InBlock.gif                Filedatastr 
= this.Decrypt(Filedatastr);
InBlock.gif                
int count = Convert.ToInt32(Filedatastr.Substring(Filedatastr.Length - 55));
InBlock.gif                FileInfomation[] FI 
= new FileInfomation[count];
InBlock.gif                
for (int i = 0; i < count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    FI[i] 
= new FileInfomation();
InBlock.gif                    
//FI[i].Filename = Filedatastr.Substring(i * 150, 100).TrimStart(new char[] { ' ' });
ExpandedSubBlockStart.gifContractedSubBlock.gif
                    FI[i].Filename = "~" + Filedatastr.Substring(i * 150100).TrimStart(new char[] dot.gif' ' });
ExpandedSubBlockStart.gifContractedSubBlock.gif                    FI[i].Size 
= Convert.ToInt32(Filedatastr.Substring(i * 150 + 10050).TrimStart(new char[] dot.gif' ' }));
ExpandedSubBlockEnd.gif                }

InBlock.gif                fin.Close();
InBlock.gif                
//已得到该文件中包括的文件个数、文件名、长度。开始解密。
InBlock.gif
                long start = 0, currentlength = 0;
InBlock.gif                
string outFileName = "";
InBlock.gif                
for (int i = 0; i < count; i++)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    
//string outFileName = CPath + @"\已解密的文件\" + FI[i].Filename;
InBlock.gif
                    outFileName = CPath + "\\" + FI[i].Filename;
InBlock.gif                    File.Delete(outFileName);
InBlock.gif                    currentlength 
= FI[i].Size;
InBlock.gif
InBlock.gif                    fin 
= new FileStream(inFileName, FileMode.Open, FileAccess.Read);
InBlock.gif                    FileStream fout 
= new FileStream(outFileName, FileMode.OpenOrCreate, FileAccess.Write);
InBlock.gif                    fout.SetLength(
0);
InBlock.gif                    fin.Seek(start, SeekOrigin.Begin);
InBlock.gif                    
int cut = 100000;
InBlock.gif                    
byte[] bin = new byte[cut];
InBlock.gif                    
long rdlen = 0;
InBlock.gif                    
long totlen = currentlength;
InBlock.gif                    
int len;
InBlock.gif                    myRijndael.Key 
= GetLegalKey();
InBlock.gif                    myRijndael.IV 
= GetLegalIV();
InBlock.gif                    ICryptoTransform encrypto 
= myRijndael.CreateDecryptor();
InBlock.gif                    CryptoStream cs 
= new CryptoStream(fout, encrypto, CryptoStreamMode.Write);
InBlock.gif                    
while (rdlen < totlen)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        
if (totlen - rdlen < cut)
ExpandedSubBlockStart.gifContractedSubBlock.gif                        
dot.gif{
InBlock.gif                            cut 
= (int)(totlen - rdlen);
InBlock.gif                            rdlen 
= totlen;
ExpandedSubBlockEnd.gif                        }

InBlock.gif                        len 
= fin.Read(bin, 0, cut);
InBlock.gif                        cs.Write(bin, 
0, len);
InBlock.gif                        rdlen 
= rdlen + len;
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    cs.Close();
InBlock.gif                    fout.Close();
InBlock.gif                    fin.Close();
ExpandedSubBlockEnd.gif                }

InBlock.gif                
return outFileName;
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                MessageBox.Show(
"在文件解密的时候出现错误!错误提示: \n" + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
InBlock.gif                
return "";
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif        
private void 加密(string files, string newname)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
int id = 0;
InBlock.gif                hs.Clear();
InBlock.gif                hs.Add(id
++, files);
InBlock.gif                
string pw = "";
InBlock.gif                
string CPath = Path.GetDirectoryName(files);
InBlock.gif                
//string FileName = "~" + Path.GetFileName(files);
InBlock.gif
                myRijndael = new RijndaelManaged();
InBlock.gif                Key 
= pw;
InBlock.gif                IV 
= "~!#@$%HGF^&%&^hggk)KJKL989#er345(&*(HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
InBlock.gif                
string outFileName = newname;
InBlock.gif
InBlock.gif                
string Filedata = "";//文件名(100字节)长度(50)个数(5)前补空格 加密后 长度(5)
InBlock.gif
                int count = 0;
InBlock.gif                
long curlength = -16;//这里是负16,我也不知道是为什么,第一次读fout长度时会少16,以后再读都正常
InBlock.gif
                foreach (System.Collections.DictionaryEntry de in this.hs)
ExpandedSubBlockStart.gifContractedSubBlock.gif                
dot.gif{
InBlock.gif                    FileStream fout 
= new FileStream(outFileName, FileMode.Append, FileAccess.Write);
InBlock.gif                    FileStream fin 
= new FileStream((string)de.Value, FileMode.Open, FileAccess.Read);
InBlock.gif                    myRijndael.Key 
= GetLegalKey();
InBlock.gif                    myRijndael.IV 
= GetLegalIV();
InBlock.gif
InBlock.gif                    
byte[] bin = new byte[100000];
InBlock.gif                    
long rdlen = 0;
InBlock.gif                    
long totlen = fin.Length;
InBlock.gif                    
int len;
InBlock.gif
InBlock.gif                    ICryptoTransform encrypto 
= myRijndael.CreateEncryptor();
InBlock.gif                    CryptoStream cs 
= new CryptoStream(fout, encrypto, CryptoStreamMode.Write);
InBlock.gif                    
while (rdlen < totlen)
ExpandedSubBlockStart.gifContractedSubBlock.gif                    
dot.gif{
InBlock.gif                        len 
= fin.Read(bin, 0100000);
InBlock.gif                        cs.Write(bin, 
0, len);
InBlock.gif                        rdlen 
= rdlen + len;
ExpandedSubBlockEnd.gif                    }

InBlock.gif                    
long foutlenth = fout.Length;
InBlock.gif                    Filedata 
+= Path.GetFileName((string)de.Value).PadLeft(100' '+ (foutlenth - curlength).ToString().PadLeft(50' ');
InBlock.gif                    curlength 
= foutlenth;
InBlock.gif                    count
++;
InBlock.gif                    cs.Close();
InBlock.gif                    fout.Close();
InBlock.gif                    fin.Close();
ExpandedSubBlockEnd.gif                }

InBlock.gif                Filedata 
+= count.ToString().PadLeft(5'0');
InBlock.gif                Filedata 
= this.Encrypt(Filedata);
InBlock.gif                Filedata 
+= Filedata.Length.ToString().PadLeft(5'0');
InBlock.gif                FileStream f 
= new FileStream(outFileName, FileMode.Append, FileAccess.Write);
InBlock.gif                StreamWriter sw 
= new StreamWriter(f);
InBlock.gif                sw.Write(Filedata);
InBlock.gif                sw.Close();
InBlock.gif                f.Close();
InBlock.gif
InBlock.gif                File.Delete(files);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                MessageBox.Show(
"在文件加密的时候出现错误!错误提示: \n" + ex.Message, "", MessageBoxButtons.OK, MessageBoxIcon.Error);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif
InBlock.gif
ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获得密钥
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns>密钥</returns>

InBlock.gif        private byte[] GetLegalKey()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string sTemp = Key;
InBlock.gif            myRijndael.GenerateKey();
InBlock.gif            
byte[] bytTemp = myRijndael.Key;
InBlock.gif            
int KeyLength = bytTemp.Length;
InBlock.gif            
if (sTemp.Length > KeyLength)
InBlock.gif                sTemp 
= sTemp.Substring(0, KeyLength);
InBlock.gif            
else if (sTemp.Length < KeyLength)
InBlock.gif                sTemp 
= sTemp.PadRight(KeyLength, ' ');
InBlock.gif            
return System.Text.ASCIIEncoding.ASCII.GetBytes(sTemp);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 获得初始向量IV
InBlock.gif        
/// </summary>
ExpandedSubBlockEnd.gif        
/// <returns>初试向量IV</returns>

InBlock.gif        private byte[] GetLegalIV()
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
string sTemp = IV;
InBlock.gif            myRijndael.GenerateIV();
InBlock.gif            
byte[] bytTemp = myRijndael.IV;
InBlock.gif            
int IVLength = bytTemp.Length;
InBlock.gif            
if (sTemp.Length > IVLength)
InBlock.gif                sTemp 
= sTemp.Substring(0, IVLength);
InBlock.gif            
else if (sTemp.Length < IVLength)
InBlock.gif                sTemp 
= sTemp.PadRight(IVLength, ' ');
InBlock.gif            
return System.Text.ASCIIEncoding.ASCII.GetBytes(sTemp);
ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 加密方法
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="Source">待加密的串</param>
ExpandedSubBlockEnd.gif        
/// <returns>经过加密的串</returns>

InBlock.gif        public string Encrypt(string Source)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
byte[] bytIn = System.Text.UTF8Encoding.UTF8.GetBytes(Source);
InBlock.gif                MemoryStream ms 
= new MemoryStream();
InBlock.gif                myRijndael.Key 
= GetLegalKey();
InBlock.gif                myRijndael.IV 
= GetLegalIV();
InBlock.gif                ICryptoTransform encrypto 
= myRijndael.CreateEncryptor();
InBlock.gif                CryptoStream cs 
= new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
InBlock.gif                cs.Write(bytIn, 
0, bytIn.Length);
InBlock.gif                cs.FlushFinalBlock();
InBlock.gif                ms.Close();
InBlock.gif                
byte[] bytOut = ms.ToArray();
InBlock.gif                
return Convert.ToBase64String(bytOut);
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw new Exception("在文件加密的时候出现错误!错误提示: \n" + ex.Message);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

ExpandedSubBlockStart.gifContractedSubBlock.gif        
/**//// <summary>
InBlock.gif        
/// 解密方法
InBlock.gif        
/// </summary>
InBlock.gif        
/// <param name="Source">待解密的串</param>
ExpandedSubBlockEnd.gif        
/// <returns>经过解密的串</returns>

InBlock.gif        public string Decrypt(string Source)
ExpandedSubBlockStart.gifContractedSubBlock.gif        
dot.gif{
InBlock.gif            
try
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
byte[] bytIn = Convert.FromBase64String(Source);
InBlock.gif                MemoryStream ms 
= new MemoryStream(bytIn, 0, bytIn.Length);
InBlock.gif                myRijndael.Key 
= GetLegalKey();
InBlock.gif                myRijndael.IV 
= GetLegalIV();
InBlock.gif                ICryptoTransform encrypto 
= myRijndael.CreateDecryptor();
InBlock.gif                CryptoStream cs 
= new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
InBlock.gif                StreamReader sr 
= new StreamReader(cs);
InBlock.gif                
return sr.ReadToEnd();
ExpandedSubBlockEnd.gif            }

InBlock.gif            
catch (Exception ex)
ExpandedSubBlockStart.gifContractedSubBlock.gif            
dot.gif{
InBlock.gif                
throw new Exception("在文件解密的时候出现错误!错误提示: \n" + ex.Message);
ExpandedSubBlockEnd.gif            }

ExpandedSubBlockEnd.gif        }

InBlock.gif     
ExpandedSubBlockEnd.gif    }

ExpandedBlockEnd.gif}

None.gif

转载于:https://www.cnblogs.com/dreign/archive/2007/05/18/751093.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值