EaseFilter Demo Project
EncryptionHandler.cs
Go to the documentation of this file.
1 //
3 // (C) Copyright 2011 EaseFilter Technologies Inc.
4 // All Rights Reserved
5 //
6 // This software is part of a licensed software product and may
7 // only be used or copied in accordance with the terms of that license.
8 //
10 
11 using System;
12 using System.Text;
13 using System.IO;
14 using System.Collections;
15 using System.Collections.Generic;
16 using Microsoft.Win32.SafeHandles;
17 using System.Runtime.InteropServices;
18 using System.Security.Principal;
19 using System.Security.Cryptography;
20 
21 namespace EaseFilter.CommonObjects
22 {
23 
24 
25  public enum AESFlags : uint
26  {
27  Flags_Enabled_Expire_Time = 0x00000010,
29  Flags_Enabled_Check_UserName = 0x00000040,
32  Flags_Enabled_Request_AES_KEY = 0x00000200,
34 
35  }
36 
37 
38  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
39  public struct AESAccessPolicy
40  {
41  public uint AESVerificationKey;
42  public uint AESFlags;
43  public uint IVLength;
44  [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)]
45  public byte[] IV;
46  public long ExpireTime;
47  public uint AccessFlags;
48  public long FileSize;
57  public string IncludeProcessNames;
58  public string ExcludeProcessNames;
59  public string IncludeUserNames;
60  public string ExcludeUserNames;
61  public uint SizeOfAESData;
62 
63  }
64 
65  public class EncryptionHandler
66  {
67  public const uint AES_VERIFICATION_KEY = 0xccb76e80;
68  public static string WorkingFolder = string.Empty;
69  public static string PassPhrase = string.Empty;
70 
80  public static bool EncryptFileWithEmbeddedPolicy(string fileName, string passPhrase, AESAccessPolicy policy, out string lastError)
81  {
82  bool ret = false;
83  FileStream fs = null;
84  lastError = string.Empty;
85 
86  try
87  {
88  if (!File.Exists(fileName))
89  {
90  lastError = fileName + " doesn't exist.";
91  return false;
92  }
93 
94  FileAttributes attributes = File.GetAttributes(fileName);
95  attributes = (~FileAttributes.ReadOnly) & attributes;
96  File.SetAttributes(fileName, attributes);
97 
98  byte[] encryptionKey = Utils.GetKeyByPassPhrase(passPhrase);
99  byte[] iv = Utils.GetRandomIV();
100 
101  //encrypt the file with encryption key and a random iv key.
102  ret = FilterAPI.AESEncryptFile(fileName, (uint)encryptionKey.Length, encryptionKey, (uint)iv.Length, iv, false);
103  if (!ret)
104  {
105  lastError = "Encrypt file " + fileName + " failed with error:" + FilterAPI.GetLastErrorMessage();
106  return ret;
107  }
108 
109  fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Read);
110  long fileSize = fs.Length;
111 
112  MemoryStream ms = new MemoryStream();
113  BinaryWriter bw = new BinaryWriter(ms);
114  bw.Write(AES_VERIFICATION_KEY);
115  bw.Write(policy.AESFlags);
116  bw.Write(iv.Length);
117  bw.Write(iv);
118  bw.Write(policy.ExpireTime);
119 
120  bw.Write(policy.AccessFlags);
121  bw.Write(fileSize);
122  bw.Write(policy.LengthOfIncludeProcessNames);
123  policy.OffsetOfIncludeProcessNames = (uint)ms.Length + 7 * 4;
124  bw.Write(policy.OffsetOfIncludeProcessNames);
125  bw.Write(policy.LengthOfExcludeProcessNames);
127  bw.Write(policy.OffsetOfExcludeProcessNames);
128  bw.Write(policy.LengthOfIncludeUserNames);
130  bw.Write(policy.OffsetOfIncludeUserNames);
131  bw.Write(policy.LengthOfExcludeUserNames);
133  bw.Write(policy.OffsetOfExcludeUserNames);
134 
135  byte[] strBuffer;
136  if (policy.LengthOfIncludeProcessNames > 0)
137  {
138  strBuffer = UnicodeEncoding.Unicode.GetBytes(policy.IncludeProcessNames);
139  bw.Write(strBuffer);
140  }
141 
142  if (policy.LengthOfExcludeProcessNames > 0)
143  {
144  strBuffer = UnicodeEncoding.Unicode.GetBytes(policy.ExcludeProcessNames);
145  bw.Write(strBuffer);
146  }
147 
148  if (policy.LengthOfIncludeUserNames > 0)
149  {
150  strBuffer = UnicodeEncoding.Unicode.GetBytes(policy.IncludeUserNames);
151  bw.Write(strBuffer);
152  }
153 
154  if (policy.LengthOfExcludeUserNames > 0)
155  {
156  strBuffer = UnicodeEncoding.Unicode.GetBytes(policy.ExcludeUserNames);
157  bw.Write(strBuffer);
158  }
159 
160  uint sizeOfAESData = (uint)ms.Length + 4;
161 
162  byte[] AESBuffer = ms.ToArray();
163 
164  //encrypt the access policy except the sizeOfAESData;
165  FilterAPI.AESEncryptDecryptBuffer(AESBuffer, 0, encryptionKey, FilterAPI.DEFAULT_IV_TAG);
166 
167  //append the access policy to the encrypted file.
168  fs.Write(AESBuffer, 0, AESBuffer.Length);
169  fs.Write(BitConverter.GetBytes(sizeOfAESData), 0, 4);
170 
171  //set the encrypted file to readonly here.
172  attributes = File.GetAttributes(fileName) | FileAttributes.ReadOnly;
173  File.SetAttributes(fileName, attributes);
174  }
175  catch (Exception ex)
176  {
177  ret = false;
178  lastError = "EncryptFileAndEmbedExpireTime " + fileName + " failed with error:" + ex.Message;
179  }
180  finally
181  {
182  if (null != fs)
183  {
184  fs.Close();
185  }
186  }
187 
188  return ret;
189  }
190 
199  public static bool ConvertFileToFilterDriverAwareEncryptFile(string fileName, string passPhrase, out string lastError)
200  {
201  bool ret = false;
202  lastError = string.Empty;
203 
204  try
205  {
206  if (!File.Exists(fileName))
207  {
208  lastError = fileName + " doesn't exist.";
209  return false;
210  }
211 
212  FileAttributes attributes = File.GetAttributes(fileName);
213  attributes = (~FileAttributes.ReadOnly) & attributes;
214  File.SetAttributes(fileName, attributes);
215 
216  FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.ReadWrite, FileShare.Read);
217  long fileSize = fs.Length;
218 
219  //read the last 4 bytes data, it is the total size of the embedded data.
220 
221  fs.Position = fileSize - 4;
222  BinaryReader br = new BinaryReader(fs);
223  uint sizeOfAESData = br.ReadUInt32();
224 
225  if (sizeOfAESData >= fileSize)
226  {
227  lastError = fileName + " is not valid share encrypted file, the sizeOfAESData:" + sizeOfAESData + " >= file size:" + fileSize;
228  return false;
229  }
230 
231  fs.Position = fileSize - sizeOfAESData;
232 
233  //Read the embedded data
234  byte[] AESBuffer = new byte[sizeOfAESData];
235  fs.Read(AESBuffer, 0, (int)sizeOfAESData);
236 
237  //decrypt the embedded data, since the last 4 bytes is not encrypted, after decryption,need to write the clear size back.
238  byte[] encryptionKey = Utils.GetKeyByPassPhrase(passPhrase);
239  FilterAPI.AESEncryptDecryptBuffer(AESBuffer, 0, encryptionKey, FilterAPI.DEFAULT_IV_TAG);
240 
241  //since the last 4 bytes for sizeOfAESData is not encrypted, we need to put back the clear value back.
242  MemoryStream ms = new MemoryStream(AESBuffer);
243  ms.Position = 0;
244  br = new BinaryReader(ms);
245  uint verificationKey = br.ReadUInt32();
246 
247  //verify if this is the valid embedded data.
248  if (verificationKey != AES_VERIFICATION_KEY)
249  {
250  lastError = fileName + " is not valid share encrypted file, the encryption key:" + verificationKey + " is not valid.";
251  return false;
252  }
253 
254  //write back the size of embedded data here.
255  ms.Position = ms.Length - 4;
256  BinaryWriter bw = new BinaryWriter(ms);
257  bw.Write(sizeOfAESData);
258 
259  //Remove the embedded data, this is the original file size without the embedded information.
260  fs.SetLength(fileSize - sizeOfAESData);
261 
262  fs.Close();
263  fs = null;
264 
265  //add the embedded data to the tag data of the encrypted file.
266  ret = FilterAPI.AddAESData(fileName, AESBuffer, out lastError);
267 
268 
269  }
270  catch (Exception ex)
271  {
272  ret = false;
273  lastError = "EncryptFileAndEmbedExpireTime " + fileName + " failed with error:" + ex.Message;
274  }
275 
276 
277  return ret;
278  }
279 
280 
281  public static bool EncryptFileAndEmbedExpireTime(string fileName, string passPhrase, DateTime expireTimeUtc, out string lastError)
282  {
283  bool ret = false;
284  lastError = string.Empty;
285 
286  try
287  {
288  if (!File.Exists(fileName))
289  {
290  lastError = fileName + " doesn't exist.";
291  return false;
292  }
293 
294  byte[] encryptionKey = Utils.GetKeyByPassPhrase(passPhrase);
295  byte[] iv = Utils.GetRandomIV();
296 
297  ret = FilterAPI.AESEncryptFile(fileName, (uint)encryptionKey.Length, encryptionKey, (uint)iv.Length, iv, false);
298  if (!ret)
299  {
300  lastError = "Encrypt file " + fileName + " failed with error:" + FilterAPI.GetLastErrorMessage();
301  return ret;
302  }
303 
304  FileStream fs = new FileStream(fileName, FileMode.Append, FileAccess.Write, FileShare.Read);
305 
306  long fileSize = fs.Length;
307  BinaryWriter bw = new BinaryWriter(fs);
308  bw.Write(FilterAPI.MESSAGE_SEND_VERIFICATION_NUMBER);
309  bw.Write(fileSize);
310  bw.Write(iv);
311  bw.Write(expireTimeUtc.ToFileTimeUtc());
312 
313 
314  fs.Close();
315 
316  FileAttributes attributes = File.GetAttributes(fileName) | FileAttributes.ReadOnly;
317 
318  File.SetAttributes(fileName, attributes);
319  }
320  catch (Exception ex)
321  {
322  ret = false;
323  lastError = "EncryptFileAndEmbedExpireTime " + fileName + " failed with error:" + ex.Message;
324  }
325 
326  return ret;
327  }
328 
329  public static bool ProcessEncryptedFile(string sourceFileName, string destFileName, out string lastError)
330  {
331  bool ret = false;
332  lastError = string.Empty;
333 
334  try
335  {
336 
337  ret = FilterAPI.ProcessEncryptedFile(sourceFileName, destFileName);
338  if (!ret)
339  {
340  lastError = "ProcessEncryptedFile " + sourceFileName + ", destFileName " + destFileName + " failed with error:" + FilterAPI.GetLastErrorMessage();
341  return ret;
342  }
343 
344  File.SetAttributes(sourceFileName, FileAttributes.Normal);
345  File.Delete(sourceFileName);
346  }
347  catch (Exception ex)
348  {
349  ret = false;
350  lastError = "ProcessEncryptedFile " + sourceFileName + ", destFileName " + destFileName + " failed with error:" + ex.Message;
351  }
352 
353  return ret;
354  }
355  }
356 }
static byte [] GetRandomIV()
Definition: Utils.cs:229
static bool ConvertFileToFilterDriverAwareEncryptFile(string fileName, string passPhrase, out string lastError)
Process the encrypted file's embedded access policy, remove embedded information, add AESTagData to e...
enum _AESFlags AESFlags
ULONG PUCHAR encryptionKey
Definition: FilterAPI.h:561
LPCTSTR destFileName
Definition: FilterAPI.h:757
static bool EncryptFileWithEmbeddedPolicy(string fileName, string passPhrase, AESAccessPolicy policy, out string lastError)
Create an encrypted file with embedded access control policy, distribute the encrypted file via inter...
static bool EncryptFileAndEmbedExpireTime(string fileName, string passPhrase, DateTime expireTimeUtc, out string lastError)
static bool ProcessEncryptedFile(string sourceFileName, string destFileName, out string lastError)
unsigned char iv[]
LONGLONG fileSize
Definition: FilterAPI.h:684
static byte [] GetKeyByPassPhrase(string pwStr)
Generate 32 bytes key array by pass phrase string
Definition: Utils.cs:207

Social Network


Services Overview

Architect, implement and test file system filter drivers for a wide range of functionality. We can offer several levels of assistance to meet your specific.

Contact Us

You are welcome to contact us for salse or partnership.

Sales: sales@easefilter.com
Support: support@easefilter.com
Info: info@easefilter.com