-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathAesEncryption.cs
72 lines (62 loc) · 2.09 KB
/
AesEncryption.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
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using System.Threading.Tasks;
using System.Security.Cryptography;
public class AesCrypter
{
public Tuple<byte[], byte[]> KeyAndIv;
AesManaged myAes;
ICryptoTransform encryptor;
ICryptoTransform decryptor;
public AesCrypter(Tuple<byte[], byte[]> KeyAndIv)
{
myAes = new AesManaged();
myAes.Key = KeyAndIv.Item1;
myAes.IV = KeyAndIv.Item2;
encryptor = myAes.CreateEncryptor(KeyAndIv.Item1, KeyAndIv.Item2);
decryptor = myAes.CreateDecryptor(KeyAndIv.Item1, KeyAndIv.Item2);
}
public Stream Encrypt(Stream s)
{
CryptoStream cryptoStream = new CryptoStream(s, encryptor, CryptoStreamMode.Read);
return cryptoStream;
}
public byte[] Encrypt(byte[] inputBytes) // key and iv is in myAes
{
using (MemoryStream input = new MemoryStream(inputBytes))
using (CryptoStream cryptoStream = new CryptoStream(input, encryptor, CryptoStreamMode.Read))
using (MemoryStream output = new MemoryStream())
{
cryptoStream.CopyTo(output);
return output.ToArray();
}
}
public Stream Decrypt(Stream s)
{
CryptoStream cryptoStream = new CryptoStream(s, decryptor, CryptoStreamMode.Read);
return cryptoStream;
}
public byte[] Decrypt(byte[] inputBytes)
{
using (MemoryStream input = new MemoryStream(inputBytes))
using (CryptoStream cryptoStream = new CryptoStream(input, decryptor, CryptoStreamMode.Read))
using (MemoryStream output = new MemoryStream())
{
cryptoStream.CopyTo(output);
return output.ToArray();
}
}
static public Tuple<byte[], byte[]> GenerateNewKeyAndIV()
{
using (AesManaged myAse = new AesManaged())
{
Tuple<byte[], byte[]> keyAndIv;
myAse.GenerateKey();
myAse.GenerateIV();
keyAndIv = Tuple.Create<byte[], byte[]>(myAse.Key, myAse.IV);
return keyAndIv;
}
}
}