This repository was archived by the owner on Jul 25, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEncryptionPackage.cs
More file actions
445 lines (396 loc) · 18.7 KB
/
Copy pathEncryptionPackage.cs
File metadata and controls
445 lines (396 loc) · 18.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System.Diagnostics;
namespace EncryptionPackage
{
public enum ErrorCode
{
InvaildKey,
InvaildFile,
InvaildEncryptionAlgorithm,
PathParametersIsInvalid,
EncryptionParametersIsInvalid,
}
public enum EncryptionAlgorithms
{
AES,
ChaCha20,
Camellia,
Twofish,
Blowfish,
TripleDES,
};
public class EncryptionAlgorithmsDetails
{
public EncryptionAlgorithmsDetails(string Name, byte BlockSize, short MaxKeyLength, byte IV_Length)
{
this.Name = Name;
this.BlockSize = BlockSize;
this.MaxKeyLength = MaxKeyLength;
this.IV_Length = IV_Length;
}
public string Name { get; }
public byte BlockSize { get; }
public short MaxKeyLength { get; }
public byte IV_Length { get; }
}
public class EncryptionParameters
{
public EncryptionAlgorithms EncryptionAlgorithm { get; set; }
public bool IfEncrypt { get; set; }
public byte[]? Key { get; set; }
public short KeyLength { get; set; }
public byte[]? ExtraEntropy { get; set; }
}
public class PathParameters
{
public string? Path { get; set; }
public bool IfUsePrefix { get; set; }
public bool IfDeleteOriginalPath { get; set; }
}
public interface IEncryptionService
{
void EncryptFile(PathParameters pathParameters);
void DecryptFile(PathParameters pathParameters);
}
// Class representing an encryption package
public class EncryptionService : IEncryptionService
{
private readonly SecureRandom randomGenerator = new SecureRandom();
private Dictionary<EncryptionAlgorithms, EncryptionAlgorithmsDetails> encryptionAlgorithmMap;
private IBufferedCipher cipher;
private EncryptionParameters encryptionParameters;
private class HeaderData
{
public byte EncryptionAlgorithm;
public bool FileEncryptionKeyLength; // false = 128, true = 256
public byte[] KeyVerifySalt = new byte[32];
public byte[] KeyDerivationSalt = new byte[32];
public byte[] KeyVerifyHash = new byte[32];
public byte[] IV = new byte[8];
public byte[]? EncryptedFileEncryptionKey;
// Override the ToString method to provide a string representation of the header data
public override string ToString()
{
return
$"KeyVerifySalt: {Convert.ToBase64String(KeyVerifySalt)}\n" +
$"KeyVerifyHash: {Convert.ToBase64String(KeyVerifyHash)}\n" +
$"KeyDerivationSalt: {Convert.ToBase64String(KeyDerivationSalt)}\n" +
$"IV: {Convert.ToBase64String(IV)}\n" +
$"EncryptedFileEncryptionKey: {Convert.ToBase64String(EncryptedFileEncryptionKey)}\n";
}
}
public EncryptionService(EncryptionParameters encryptionParameters)
{
this.encryptionParameters = encryptionParameters;
encryptionAlgorithmMap = new Dictionary<EncryptionAlgorithms, EncryptionAlgorithmsDetails>()
{
[EncryptionAlgorithms.AES] = new EncryptionAlgorithmsDetails("AES/CFB/PKCS7Padding", 128, 256, 128),
[EncryptionAlgorithms.ChaCha20] = new EncryptionAlgorithmsDetails("ChaCha20", 1, 256, 96),
[EncryptionAlgorithms.Camellia] = new EncryptionAlgorithmsDetails("Camellia/CFB/PKCS7Padding", 128, 256, 128),
[EncryptionAlgorithms.Twofish] = new EncryptionAlgorithmsDetails("Twofish/CFB/PKCS7Padding", 128, 256, 128),
[EncryptionAlgorithms.Blowfish] = new EncryptionAlgorithmsDetails("Blowfish/CFB/PKCS7Padding", 128, 256, 64),
[EncryptionAlgorithms.TripleDES] = new EncryptionAlgorithmsDetails("DESede/CFB/PKCS7Padding", 64, 192, 64),
};
randomGenerator.SetSeed(encryptionParameters.ExtraEntropy);
EncryptionParametersCheck(encryptionParameters);
}
private void EncryptionParametersCheck(EncryptionParameters parameters)
{
if (encryptionAlgorithmMap.ContainsKey(parameters.EncryptionAlgorithm) == false && parameters.IfEncrypt)
{
throw new ArgumentException(((int) ErrorCode.InvaildEncryptionAlgorithm).ToString());
}
if (parameters.Key == null || parameters.Key.Length == 0)
{
throw new ArgumentNullException(((int) ErrorCode.InvaildKey).ToString());
}
if (parameters.KeyLength != (short)128 && parameters.KeyLength != (short)256)
{
throw new ArgumentException(((int) ErrorCode.InvaildKey).ToString());
}
}
private void PathParametersCheck(PathParameters parameters)
{
if (parameters == null)
{
throw new ArgumentNullException(((int) ErrorCode.PathParametersIsInvalid).ToString());
}
if (string.IsNullOrEmpty(parameters.Path))
{
throw new ArgumentNullException(((int) ErrorCode.PathParametersIsInvalid).ToString());
}
}
void IEncryptionService.EncryptFile(PathParameters parameters)
{
PathParametersCheck(parameters);
cipher = CipherUtilities.GetCipher(encryptionAlgorithmMap[encryptionParameters.EncryptionAlgorithm].Name);
string encryptionFilePath = GetEncryptionPath(parameters);
byte[]? fileEncryptionKey = null;
byte[]? fileEncryptionIV = null;
HeaderData headerData = GenerateHeaderData(ref fileEncryptionKey, ref fileEncryptionIV);
byte[] writtenHeader = CreateWrittenHeader(headerData);
WriteHeader(writtenHeader, encryptionFilePath);
cipher.Init(true, new ParametersWithIV(new KeyParameter(fileEncryptionKey), fileEncryptionIV));
EncryptMainDataAndWrite(parameters.Path, encryptionFilePath);
if (parameters.IfDeleteOriginalPath)
{
File.Delete(parameters.Path);
string newPath = Path.Combine(Path.GetDirectoryName(parameters.Path), Path.GetFileName(encryptionFilePath));
File.Copy(encryptionFilePath, newPath);
File.Delete(encryptionFilePath);
}
}
private string GetEncryptionPath(PathParameters parameters)
{
string fileName = Path.GetFileName(parameters.Path);
if (fileName.StartsWith("DEC_"))
{
fileName = fileName.Substring(4);
}
string directoryPath = Path.GetDirectoryName(parameters.Path);
string encryptFileName = "ENC_" + fileName;
return Path.Combine
(
parameters.IfDeleteOriginalPath ? Path.GetTempPath() : directoryPath,
parameters.IfUsePrefix ? encryptFileName : fileName
);
}
private byte[] EncryptBytes(byte[] plainText, byte[] key, byte[] iv)
{
KeyParameter keyParameter = new KeyParameter(key);
ParametersWithIV parametersWithIV = new ParametersWithIV(keyParameter, iv);
cipher.Init(true, parametersWithIV);
byte[] cipherText = new byte[cipher.GetOutputSize(plainText.Length)];
cipher.DoFinal(plainText, 0, plainText.Length, cipherText, 0);
return cipherText;
}
private void EncryptMainDataAndWrite(string originalPath, string encryptPath)
{
using (FileStream originalFileStream = File.OpenRead(originalPath))
using (BinaryReader binaryReader = new BinaryReader(originalFileStream))
using (FileStream encryptFileStream = File.OpenWrite(encryptPath))
using (BinaryWriter binaryWriter = new BinaryWriter(encryptFileStream))
{
encryptFileStream.Seek(256 + 1, SeekOrigin.Begin);
byte[] buffer = new byte[4096];
int bytesRead;
while ((bytesRead = binaryReader.Read(buffer, 0, buffer.Length)) > 0)
{
byte[] cipherText = cipher.ProcessBytes(buffer, 0, buffer.Length);
binaryWriter.Write(cipherText);
}
binaryWriter.Flush();
}
}
private HeaderData GenerateHeaderData(ref byte[] fileEncryptionKey, ref byte[] IV)
{
HeaderData headerData = new HeaderData();
// encryption algorithm
headerData.EncryptionAlgorithm = ((byte)encryptionParameters.EncryptionAlgorithm);
// file encryption key length
headerData.FileEncryptionKeyLength = encryptionParameters.KeyLength == 256;
// salt
randomGenerator.NextBytes(headerData.KeyVerifySalt); // 32 bytes
randomGenerator.NextBytes(headerData.KeyDerivationSalt); // 32 bytes
// verify hash
headerData.KeyVerifyHash = KeyDerivation(encryptionParameters.Key, headerData.KeyVerifySalt, 256);
// protection key
EncryptionAlgorithmsDetails encryptionAlgorithmsDetails = encryptionAlgorithmMap[encryptionParameters.EncryptionAlgorithm];
byte[] protectionKey = KeyDerivation(encryptionParameters.Key, headerData.KeyDerivationSalt, encryptionAlgorithmsDetails.MaxKeyLength);
// Debug.WriteLine($"Protection Key: {Convert.ToBase64String(protectionKey)}");
// IV
IV = new byte[encryptionAlgorithmsDetails.IV_Length >> 3];
randomGenerator.NextBytes(IV);
headerData.IV = IV;
// file encryption key
if (encryptionParameters.KeyLength == 128)
{
fileEncryptionKey = new byte[16];
}
else
{
fileEncryptionKey = new byte[encryptionAlgorithmsDetails.MaxKeyLength >> 3];
}
randomGenerator.NextBytes(fileEncryptionKey);
headerData.EncryptedFileEncryptionKey = EncryptBytes(fileEncryptionKey, protectionKey, IV);
return headerData;
}
// Method to create the header data
private byte[] CreateWrittenHeader(HeaderData headerData)
{
using (MemoryStream memoryStream = new MemoryStream())
using (BinaryWriter binaryWriter = new BinaryWriter(memoryStream))
{
// encryption algorithm
binaryWriter.Write(headerData.EncryptionAlgorithm);
// file encryption key length
binaryWriter.Write(headerData.FileEncryptionKeyLength);
// salt
binaryWriter.Write((byte) headerData.KeyVerifySalt.Length);
binaryWriter.Write(headerData.KeyVerifySalt);
binaryWriter.Write((byte) headerData.KeyDerivationSalt.Length);
binaryWriter.Write(headerData.KeyDerivationSalt);
// hash
binaryWriter.Write((byte) headerData.KeyVerifyHash.Length);
binaryWriter.Write(headerData.KeyVerifyHash);
//iv
binaryWriter.Write((byte) headerData.IV.Length);
binaryWriter.Write(headerData.IV);
// encryption key
binaryWriter.Write((byte) headerData.EncryptedFileEncryptionKey.Length);
binaryWriter.Write(headerData.EncryptedFileEncryptionKey);
binaryWriter.Flush();
return memoryStream.ToArray();
}
}
private void WriteHeader(byte[] headerBytes, string encryptionFilePath)
{
using (FileStream fileStream = File.OpenWrite(encryptionFilePath))
using (BinaryWriter binaryWriter = new BinaryWriter(fileStream))
{
binaryWriter.Write(headerBytes);
binaryWriter.Write(new byte[256 - headerBytes.Length]);
binaryWriter.Flush();
}
}
void IEncryptionService.DecryptFile(PathParameters parameters)
{
PathParametersCheck(parameters);
byte[] readHeader = ReadHeader(parameters.Path);
HeaderData headerData = LoadHeaderData(readHeader);
// Verify the input key
if (!KeyVerify(headerData))
{
throw new ArgumentException(((int) ErrorCode.InvaildKey).ToString());
}
EncryptionAlgorithmsDetails encryptionAlgorithmsDetails = encryptionAlgorithmMap[(EncryptionAlgorithms) headerData.EncryptionAlgorithm];
cipher = CipherUtilities.GetCipher(encryptionAlgorithmsDetails.Name);
string decryptionPath = GetDecryptionPath(parameters);
byte[] protectionKey = KeyDerivation(encryptionParameters.Key, headerData.KeyDerivationSalt, encryptionAlgorithmsDetails.MaxKeyLength);
byte[] fileEncryptionKey = DecryptBytes(headerData.EncryptedFileEncryptionKey, protectionKey, headerData.IV);
if (!headerData.FileEncryptionKeyLength)
{
fileEncryptionKey = fileEncryptionKey.Take(16).ToArray();
}
else
{
fileEncryptionKey = fileEncryptionKey.Take(encryptionAlgorithmsDetails.MaxKeyLength >> 3).ToArray();
}
// Initialize the stream cipher and decrypt the main data
cipher.Init(false, new ParametersWithIV(new KeyParameter(fileEncryptionKey), headerData.IV));
DecryptMainDataAndWrite(parameters.Path, decryptionPath);
if (parameters.IfDeleteOriginalPath)
{
File.Delete(parameters.Path);
string newPath = Path.Combine(Path.GetDirectoryName(parameters.Path), Path.GetFileName(decryptionPath));
File.Copy(decryptionPath, newPath);
File.Delete(decryptionPath);
}
}
private string GetDecryptionPath(PathParameters pathParameters)
{
string fileName = Path.GetFileName(pathParameters.Path);
if (fileName.StartsWith("ENC_"))
{
fileName = fileName.Substring(4);
}
string directoryPath = Path.GetDirectoryName(pathParameters.Path);
string decryptFileName = "DEC_" + fileName;
return Path.Combine
(
pathParameters.IfDeleteOriginalPath ? Path.GetTempPath() : directoryPath,
pathParameters.IfUsePrefix ? decryptFileName : fileName
);
}
private byte[] DecryptBytes(byte[] cipherText, byte[] key, byte[] iv)
{
KeyParameter keyParameter = new KeyParameter(key);
ParametersWithIV parametersWithIV = new ParametersWithIV(keyParameter, iv);
cipher.Init(false, parametersWithIV);
byte[] plainText = new byte[cipher.GetOutputSize(cipherText.Length)];
cipher.DoFinal(cipherText, 0, cipherText.Length, plainText, 0);
return plainText;
}
private void DecryptMainDataAndWrite(string originalPath, string decryptPath)
{
using (FileStream originalFileStream = File.OpenRead(originalPath))
using (BinaryReader binaryReader = new BinaryReader(originalFileStream))
using (FileStream decryptFileStream = File.OpenWrite(decryptPath))
using (BinaryWriter binaryWriter = new BinaryWriter(decryptFileStream))
{
originalFileStream.Seek(256 + 1, SeekOrigin.Begin);
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = binaryReader.Read(buffer, 0, buffer.Length)) > 0)
{
byte[] plainText = cipher.ProcessBytes(buffer, 0, buffer.Length);
binaryWriter.Write(plainText);
}
binaryWriter.Flush();
}
}
private byte[] ReadHeader(string decryptionFilePath)
{
using (FileStream fileStream = File.OpenRead(decryptionFilePath))
using (BinaryReader binaryReader = new BinaryReader(fileStream))
{
return binaryReader.ReadBytes(256);
}
}
private HeaderData LoadHeaderData(byte[] headerBytes)
{
using (MemoryStream memoryStream = new MemoryStream(headerBytes))
using (BinaryReader binaryReader = new BinaryReader(memoryStream))
{
HeaderData headerData = new HeaderData();
// encryption algorithm
headerData.EncryptionAlgorithm = binaryReader.ReadByte();
// file encryption key length
headerData.FileEncryptionKeyLength = binaryReader.ReadBoolean();
// salt
byte byteRead = binaryReader.ReadByte();
headerData.KeyVerifySalt = binaryReader.ReadBytes(byteRead);
byteRead = binaryReader.ReadByte();
headerData.KeyDerivationSalt = binaryReader.ReadBytes(byteRead);
// hash
byteRead = binaryReader.ReadByte();
headerData.KeyVerifyHash = binaryReader.ReadBytes(byteRead);
// iv
byteRead = binaryReader.ReadByte();
headerData.IV = binaryReader.ReadBytes(byteRead);
// encrypted file encryption key
byteRead = binaryReader.ReadByte();
headerData.EncryptedFileEncryptionKey = binaryReader.ReadBytes(byteRead);
return headerData;
}
}
// Method to get the decryption path for an encrypted file
private byte[] KeyDerivation(byte[] key, byte[] salt, short KeyLength)
{
if (key == null)
{
throw new ArgumentNullException(((int) ErrorCode.InvaildKey).ToString());
}
Pkcs5S2ParametersGenerator generator = new Pkcs5S2ParametersGenerator();
generator.Init(key, salt, 10000);
KeyParameter derivedKey = (KeyParameter)generator.GenerateDerivedMacParameters(KeyLength);
return derivedKey.GetKey();
}
// Method to verify the input key
private bool KeyVerify(HeaderData headerData)
{
byte[] calculatedHash = KeyDerivation(encryptionParameters.Key, headerData.KeyVerifySalt, 256);
for (int i = 0; i < calculatedHash.Length; i++)
{
if (headerData.KeyVerifyHash[i] != calculatedHash[i])
{
return false;
}
}
return true;
}
}
}