-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathAesEncryption.cs
305 lines (243 loc) · 9.56 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
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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Encrypt
{
public class AesEncryption
{
#region Properties
/// <summary>
/// For initial authentication it's APISecretKey
/// After authenticated - Session Key
/// </summary>
byte[] Key;
/// <summary>
/// Keep IV from EncryptStringToBytes to return in sIV
/// </summary>
byte[] IV;
/// <summary>
/// Return IV from EncryptStringToBytes
/// </summary>
public string sIV
{
get
{
if (IV == null)
return null;
return Convert.ToBase64String(IV);
}
}
#endregion Properties
#region Methods
/// <summary>
/// API key is HEX, but Session key is base64
/// For initial authentication it's APISecretKey
/// After authenticated - Session Key
/// </summary>
/// <param name="base64Key">Session Key</param>
/// <param name="APISecretKey">APISecretKey (HEX)</param>
/// <param name="APIAuthKey">APISecretKey</param>
public AesEncryption(string base64Key = null, string APISecretKey = null, string APIAuthKey = null)
{
if (base64Key != null)
{
this.Key = Convert.FromBase64String(base64Key);
}
else
{
this.Key = StringToByteArray(APISecretKey);
}
// Calculate HMAC-SHA256 using API Auth Key
this.APIAuthKey = APIAuthKey;
}
/// <summary>
/// Convert HEX string to byte[]
/// </summary>
/// <param name="hex"></param>
/// <returns></returns>
public static byte[] StringToByteArray(String hex)
{
if (String.IsNullOrEmpty(hex))
return null;
int NumberChars = hex.Length;
byte[] bytes = new byte[NumberChars / 2];
for (int i = 0; i < NumberChars; i += 2)
bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
return bytes;
}
#endregion Methods
#region HMAC
public string APIAuthKey;
/// <summary>
/// The MAC to calculate is a HMAC-SHA256 using API Auth Key
/// </summary>
/// <param name="paylaoad"></param>
/// <param name="Key"></param>
/// <returns></returns>
public string StringHash(string paylaoad)
{
return StringHash(paylaoad, APIAuthKey);
}
static public byte[] ByteHash(string paylaoad, byte[] Key)
{
if (Key == null)
return null;
HMACSHA256 hmac = new HMACSHA256(Key);
byte[] buffer = Encoding.ASCII.GetBytes(paylaoad);
return hmac.ComputeHash(buffer);
}
static public string StringHash(string paylaoad, string hexKey)
{
byte[] Key = StringToByteArray(hexKey);
byte[] bHash = ByteHash(paylaoad, Key);
return Convert.ToBase64String(bHash);
}
#endregion HMAC
#region Encrypt
/// <summary>
///
/// </summary>
/// <param name="plainText"></param>
/// <param name="Key"></param>
/// <param name="IV"></param>
/// <returns>Return the encrypted bytes from the memory stream</returns>
byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] iv = null)
{
// Check arguments.
if (plainText == null || plainText.Length <= 0)
throw new ArgumentNullException("plainText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
// Create an AesCryptoServiceProvider object
// with the specified key and IV.
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
if (iv != null)
aesAlg.IV = iv;
else
aesAlg.GenerateIV();
this.IV = aesAlg.IV;
//Console.WriteLine($"Encrypt: {plainText}, Key: {Convert.ToBase64String(Key)}, IV: {Convert.ToBase64String(IV)}");
// Create an encryptor to perform the stream transform.
ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for encryption.
using (MemoryStream msEncrypt = new MemoryStream())
{
using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
{
//Write all data to the stream.
swEncrypt.Write(plainText);
}
return msEncrypt.ToArray();
}
}
}
}
/// <summary>
///
/// </summary>
/// <param name="payload"></param>
/// <param name="sKey"></param>
/// <param name="sIV">optional, mostly for testing</param>
/// <returns></returns>
public string EncryptStringToBytes(string payload, string sKey = null, string sIV = null)
{
if(!String.IsNullOrEmpty(sKey))
Key = StringToByteArray(sKey);
byte[] iv = (!String.IsNullOrEmpty(sIV))? Convert.FromBase64String(sIV) : null;
byte[] encrypted = EncryptStringToBytes(payload, Key, iv);
//Console.WriteLine($"Unencrypted payload({payload.Length} bytes): {payload}, IV: '{this.sIV}'");
return Convert.ToBase64String(encrypted);
}
#endregion Encrypt
#region Decrypt
/// <summary>
///
/// </summary>
/// <param name="cipherText"></param>
/// <param name="IV"></param>
/// <returns></returns>
public string DecryptStringFromBytes(string cipherText, string IV)
{
byte[] byteCipherText = Convert.FromBase64String(cipherText);
byte[] byteIV = Convert.FromBase64String(IV);
return DecryptStringFromBytes_Aes(byteCipherText, this.Key, byteIV);
}
/// <summary>
/// Note: n exception handling
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="cipherText"></param>
/// <param name="IV"></param>
/// <returns></returns>
public T DecryptStringFromBytes<T>(string cipherText, string IV)
{
string json = DecryptStringFromBytes(cipherText, IV);
Console.WriteLine($"Decrypted payload: {json}, IV: '{IV}'");
return JsonConvert.DeserializeObject<T>(json);
}
/// <summary>
///
/// </summary>
/// <param name="cipherText"></param>
/// <param name="Key"></param>
/// <param name="IV"></param>
/// <returns></returns>
public static string DecryptStringFromBytes_Aes(string cipherText, string Key, string IV)
{
byte[] byteCipherText = Convert.FromBase64String(cipherText);
byte[] byteIV = Convert.FromBase64String(IV);
byte[] byteKey = StringToByteArray(Key);
return DecryptStringFromBytes_Aes(byteCipherText, byteKey, byteIV);
}
/// <summary>
///
/// </summary>
/// <param name="cipherText"></param>
/// <param name="Key"></param>
/// <param name="IV"></param>
/// <returns></returns>
static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV)
{
// Check arguments.
if (cipherText == null || cipherText.Length <= 0)
throw new ArgumentNullException("cipherText");
if (Key == null || Key.Length <= 0)
throw new ArgumentNullException("Key");
if (IV == null || IV.Length <= 0)
throw new ArgumentNullException("IV");
// Create an AesCryptoServiceProvider object
// with the specified key and IV.
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
aesAlg.Key = Key;
aesAlg.IV = IV;
// Create a decryptor to perform the stream transform.
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
// Create the streams used for decryption.
using (MemoryStream msDecrypt = new MemoryStream(cipherText))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
// Read the decrypted bytes from the decrypting stream
string payload = srDecrypt.ReadToEnd();
Console.WriteLine($"Decrypted payload({payload.Length} bytes): {payload}, IV: '{Convert.ToBase64String(IV)}'");
return payload;
}
}
}
}
}
#endregion Decrypt
}
}