-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathABPAES.cs
105 lines (91 loc) · 3.25 KB
/
ABPAES.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
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
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Crypto.Modes;
using System;
using System.Security.Cryptography;
using System.Text;
namespace ABPPack
{
public static class ABPAES
{
public const int macSize = 128;
public const int ivCount = 12;
public const int keyCount = 32;
public static byte[] MakeIV()
{
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] iv = new byte[ivCount];
rng.GetBytes(iv);
return iv;
}
}
public static KeyParameter MakeKey()
{
using (RNGCryptoServiceProvider rng = new RNGCryptoServiceProvider())
{
byte[] key = new byte[keyCount];
rng.GetBytes(key);
return MakeKey(key);
}
}
public static KeyParameter MakeKey(byte[] key)
{
return new KeyParameter(key);
}
public static byte[] Encrypt(byte[] data, KeyParameter key, byte[] iv)
{
try
{
var cipher = new GcmBlockCipher(new AesEngine());
var parameters = new AeadParameters(key, macSize, iv);
cipher.Init(true, parameters);
var output = new byte[cipher.GetOutputSize(data.Length)];
var len = cipher.ProcessBytes(data, 0, data.Length, output, 0);
cipher.DoFinal(output, len);
return output;
}
catch (Exception e)
{
Console.Error.WriteLine($"[ABPAES.Encrypt] {e}");
return null;
}
}
public static byte[] Decrypt(byte[] data, KeyParameter key, byte[] iv)
{
try
{
var cipher = new GcmBlockCipher(new AesEngine());
var parameters = new AeadParameters(key, macSize, iv);
cipher.Init(false, parameters);
var output = new byte[cipher.GetOutputSize(data.Length)];
var len = cipher.ProcessBytes(data, 0, data.Length, output, 0);
cipher.DoFinal(output, len);
return output;
}
catch (Exception e)
{
Console.Error.WriteLine($"[ABPAES.Decrypt] {e}");
return null;
}
}
public static bool SelfTest(KeyParameter key)
{
byte[] testIV = MakeIV();
string testInputStr = "Testing Testing 123!!!";
var testInput = Encoding.UTF8.GetBytes(testInputStr);
var encrypted = Encrypt(testInput, key, testIV);
var decrypted = Decrypt(encrypted, key, testIV);
var decryptedStr = Encoding.UTF8.GetString(decrypted);
if (decryptedStr != testInputStr)
{
Console.Error.WriteLine($"[ABPAES.SelfTest] Selftest failed: Decrypted doesn't match input!");
return false;
}
else
{
return true;
}
}
}
}