-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAESHelper.cs
More file actions
48 lines (36 loc) · 1.64 KB
/
Copy pathAESHelper.cs
File metadata and controls
48 lines (36 loc) · 1.64 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
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Memoryboard
{
public class AESHelper
{
public static byte[] Encrypt(string plainText, byte[] keySourceBytes)
{
byte[] keyBytes = new byte[32];
Array.Copy(keySourceBytes, keyBytes, Math.Min(keyBytes.Length, keySourceBytes.Length));
using Aes aes = Aes.Create();
aes.Key = keyBytes;
aes.IV = new byte[16];
using MemoryStream memoryStream = new();
using CryptoStream cryptoStream = new(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write);
var plainTextBytes = Encoding.UTF8.GetBytes(plainText);
cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
public static string Decrypt(byte[] cipherText, byte[] keySourceBytes)
{
byte[] keyBytes = new byte[32];
Array.Copy(keySourceBytes, keyBytes, Math.Min(keyBytes.Length, keySourceBytes.Length));
using Aes aes = Aes.Create();
aes.Key = keyBytes;
aes.IV = new byte[16];
using MemoryStream memoryStream = new(cipherText);
using CryptoStream cryptoStream = new(memoryStream, aes.CreateDecryptor(), CryptoStreamMode.Read);
byte[] decryptedBytes = new byte[cipherText.Length];
int bytesRead = cryptoStream.Read(decryptedBytes, 0, decryptedBytes.Length);
return Encoding.UTF8.GetString(decryptedBytes, 0, bytesRead);
}
}
}