-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEncryptionUtility.cs
59 lines (52 loc) · 2.2 KB
/
EncryptionUtility.cs
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
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace WIZEncrypt
{
internal class EncryptionUtility
{
public static void EncryptFile(string sourceFilePath, string targetFilePath, string password, string salt)
{
using (var aesAlg = Aes.Create())
{
aesAlg.Key = GenerateKey(password, salt);
aesAlg.IV = GenerateIV(salt);
using (var sourceStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
using (var targetStream = new FileStream(targetFilePath, FileMode.Create, FileAccess.Write))
using (var cryptoStream = new CryptoStream(targetStream, aesAlg.CreateEncryptor(), CryptoStreamMode.Write))
{
sourceStream.CopyTo(cryptoStream);
}
}
}
public static void DecryptFile(string sourceFilePath, string targetFilePath, string password, string salt)
{
using (var aesAlg = Aes.Create())
{
aesAlg.Key = GenerateKey(password, salt);
aesAlg.IV = GenerateIV(salt);
using (var sourceStream = new FileStream(sourceFilePath, FileMode.Open, FileAccess.Read))
using (var targetStream = new FileStream(targetFilePath, FileMode.Create, FileAccess.Write))
using (var cryptoStream = new CryptoStream(targetStream, aesAlg.CreateDecryptor(), CryptoStreamMode.Write))
{
sourceStream.CopyTo(cryptoStream);
}
}
}
private static byte[] GenerateKey(string password, string salt)
{
using (var keyGenerator = new Rfc2898DeriveBytes(password, Encoding.UTF8.GetBytes(salt), 10000))
{
return keyGenerator.GetBytes(256 / 8); // 256 bits for AES-256
}
}
private static byte[] GenerateIV(string salt)
{
using (var keyGenerator = new Rfc2898DeriveBytes(salt, Encoding.UTF8.GetBytes(salt), 10000))
{
return keyGenerator.GetBytes(128 / 8); // 128 bits for AES IV
}
}
}
}