1using System;
2using System.Collections.Generic;
3using System.Text;
4using System.Security.Cryptography;
5using System.IO;
6
7namespace AjaxClassLibrary
8{
9 public class FileEncryptionClass
10 {
11 #region ClassProperties ...
12
13 string _password = "1234abcd";
14 #endregion ClassProperties
15 #region Private Properties ...
16
17
18 private byte[] EncryptionKey()
19 {
20 UnicodeEncoding aUE = new UnicodeEncoding();
21 byte[] keyBytes = aUE.GetBytes(_password);
22 return keyBytes;
23 }
24
25 private bool CheckSourceFile(String SourceFile)
26 {
27 if (File.Exists(SourceFile))
28 return true;
29 else
30 {
31 throw new ApplicationException("File does not Exist");
32 }
33 }
34 #endregion Private Properties
35
36 public FileEncryptionClass()
37 {
38 }
39
40 public void EncryptionofFileStream(FileStream Source, FileStream Destination)
41 {
42 CryptoStream aCryptoStream = null;
43 try
44 {
45 RijndaelManaged RMCrypto = new RijndaelManaged();
46 aCryptoStream = new CryptoStream(Destination, RMCrypto.CreateEncryptor(EncryptionKey(), EncryptionKey()), CryptoStreamMode.Write);
47
48 int data;
49 while ((data = Source.ReadByte()) != -1)
50 aCryptoStream.WriteByte((byte)data);
51
52 }
53 catch (Exception ex)
54 {
55 throw ex;
56 }
57 finally
58 {
59 if (aCryptoStream != null)
60 {
61 aCryptoStream.Close();
62 }
63 }
64 } // EncryptionofFileStream
65
66 public void EncryptionofFile(string FileSource, string FileDestination)
67 {
68 if (!CheckSourceFile(FileSource))
69 return;
70
71 FileStream fsIn = new FileStream(FileSource, FileMode.Open);
72 FileStream file1 = new FileStream(FileDestination, FileMode.OpenOrCreate, FileAccess.Write);
73 try
74 {
75 EncryptionofFileStream(fsIn, file1);
76 }
77 catch (Exception ex)
78 {
79 throw ex;
80 }
81 finally
82 {
83 fsIn.Close();
84 file1.Close();
85 }
86 } // EncryptionofFile
87
88 public void DecryptionofFile(string EncryptionFileSource, string DecryptionFileSource)
89 {
90 FileStream file1 = new FileStream(EncryptionFileSource, FileMode.OpenOrCreate, FileAccess.ReadWrite);
91 FileStream fsIn = new FileStream(DecryptionFileSource, FileMode.OpenOrCreate, FileAccess.Write);
92
93 CryptoStream aCryptoStream = null;
94 try
95 {
96 RijndaelManaged RMCrypto = new RijndaelManaged();
97 aCryptoStream = new CryptoStream(file1, RMCrypto.CreateDecryptor(EncryptionKey(), EncryptionKey()), CryptoStreamMode.Read);
98
99 StreamReader reader = new StreamReader(aCryptoStream);
100
101 string data = reader.ReadToEnd();
102 byte[] data1 = ASCIIEncoding.ASCII.GetBytes(data);
103
104 fsIn.Write(data1,0,data1.Length);
105 }
106 catch (Exception ex)
107 {
108 throw ex;
109 }
110 finally
111 {
112 if (aCryptoStream != null)
113 {
114 aCryptoStream.Close();
115 }
116 fsIn.Close();
117 file1.Close();
118 }
119
120 } // DecryptionofFile
121 }
122}