-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathAES.cs
55 lines (52 loc) · 1.88 KB
/
AES.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
using System;
using System.IO;
using System.Security.Cryptography;
namespace Crypto
{
public class AesEncryption
{
public byte[] GenerateRandomNumber(int length)
{
using (var randomNumberGenerator = new RNGCryptoServiceProvider())
{
var random = new Byte[length];
randomNumberGenerator.GetBytes(random);
return random;
}
}
public byte[] Encrypt(byte[] dataToEncrypt, byte[] key, byte[] iv)
{
using (var des = new AesCryptoServiceProvider())
{
des.Mode = CipherMode.CBC;
des.Padding = PaddingMode.PKCS7;
des.Key = key;
des.IV = iv;
using (var memoryStream = new MemoryStream())
{
var cryptoStream = new CryptoStream(memoryStream, des.CreateEncryptor(), CryptoStreamMode.Write);
cryptoStream.Write(dataToEncrypt, 0, dataToEncrypt.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
public byte[] Decrypt(byte[] dataToDecrypt, byte[] key, byte[] iv)
{
using (var des = new AesCryptoServiceProvider())
{
des.Mode = CipherMode.CBC;
des.Padding = PaddingMode.PKCS7;
des.Key = key;
des.IV = iv;
using (var memoryStream = new MemoryStream())
{
var cryptoStream = new CryptoStream(memoryStream, des.CreateDecryptor(), CryptoStreamMode.Write);
cryptoStream.Write(dataToDecrypt, 0, dataToDecrypt.Length);
cryptoStream.FlushFinalBlock();
return memoryStream.ToArray();
}
}
}
}
}