File Encryption and Decryption in C#

http://www.codeproject.com/KB/files/encryption.aspx

 

    ///<summary>
        
/// Steve Lydford - 12/05/2008.
        
///
        
/// Encrypts a file using Rijndael algorithm.
        
///</summary>
        
///<param name="inputFile"></param>
        
///<param name="outputFile"></param>

         private   void  EncryptFile( string  inputFile,  string  outputFile)
        
{
 
            
try
            
{
                
string password = @"myKey123"// Your Key Here
                UnicodeEncoding UE = new UnicodeEncoding();
                
byte[] key = UE.GetBytes(password);
 
                
string cryptFile = outputFile;
                FileStream fsCrypt 
= new FileStream(cryptFile, FileMode.Create);
 
                RijndaelManaged RMCrypto 
= new RijndaelManaged();
 
                CryptoStream cs 
= new CryptoStream(fsCrypt,
                    RMCrypto.CreateEncryptor(key, key),
                    CryptoStreamMode.Write);
 
                FileStream fsIn 
= new FileStream(inputFile, FileMode.Open);
 
                
int data;
                
while ((data = fsIn.ReadByte()) != -1)
                    cs.WriteByte((
byte)data);
 
                
                fsIn.Close();
                cs.Close();
                fsCrypt.Close();
            }

            
catch
            
{
                MessageBox.Show(
"Encryption failed!""Error");
            }

        }

        
///<summary>
        
/// Steve Lydford - 12/05/2008.
        
///
        
/// Decrypts a file using Rijndael algorithm.
        
///</summary>
        
///<param name="inputFile"></param>
        
///<param name="outputFile"></param>

         private   void  DecryptFile( string  inputFile,  string  outputFile)
        
{
 
            
{
                
string password = @"myKey123"// Your Key Here
 
                UnicodeEncoding UE 
= new UnicodeEncoding();
                
byte[] key = UE.GetBytes(password);
 
                FileStream fsCrypt 
= new FileStream(inputFile, FileMode.Open);
 
                RijndaelManaged RMCrypto 
= new RijndaelManaged();
 
                CryptoStream cs 
= new CryptoStream(fsCrypt,
                    RMCrypto.CreateDecryptor(key, key),
                    CryptoStreamMode.Read);
 
                FileStream fsOut 
= new FileStream(outputFile, FileMode.Create);
 
                
int data;
                
while ((data = cs.ReadByte()) != -1)
                    fsOut.WriteByte((
byte)data);
 
                fsOut.Close();
                cs.Close();
                fsCrypt.Close();
 
            }

        }

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值