-
Notifications
You must be signed in to change notification settings - Fork 0
/
FooCryptHelper.cs
293 lines (240 loc) · 11.8 KB
/
FooCryptHelper.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
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web.Security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
namespace FooBlog
{
public class FooCryptHelper
{
// AES256 (GCM) ENCRYPTION + PBKDF2 DERIVATION OPERATIONS.
private const string TokenPurpose = "Protected String";
private static readonly SecureRandom Random = new SecureRandom();
//Preconfigured Encryption Parameters
public static readonly int NonceBitSize = 128;
public static readonly int MacBitSize = 128;
public static readonly int KeyBitSize = 256;
//Preconfigured Password Key Derivation Parameters
public static readonly int SaltBitSize = 512;
public static readonly int Iterations = 10000;
public static readonly int MinPasswordLength = 12;
// AES256 GCM ENCRYPTION + HMAC MESSAGE VALIDATION
public static byte[] NewKey()
{
var key = new byte[KeyBitSize/8];
Random.NextBytes(key);
return key;
}
public static string SimpleEncrypt(string secretMessage, byte[] key, byte[] nonSecretPayload = null)
{
if (String.IsNullOrEmpty(secretMessage))
throw new ArgumentException(@"Secret Message Required!", "secretMessage");
byte[] plainText = Encoding.UTF8.GetBytes(secretMessage);
byte[] cipherText = SimpleEncrypt(plainText, key, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
public static string SimpleDecrypt(string encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)
{
if (String.IsNullOrEmpty(encryptedMessage))
throw new ArgumentException(@"Encrypted Message Required!", "encryptedMessage");
byte[] cipherText = Convert.FromBase64String(encryptedMessage);
byte[] plaintext = SimpleDecrypt(cipherText, key, nonSecretPayloadLength);
return Encoding.UTF8.GetString(plaintext);
}
public static string SimpleEncryptWithPassword(string secretMessage, string password,
byte[] nonSecretPayload = null)
{
if (String.IsNullOrEmpty(secretMessage))
throw new ArgumentException(@"Secret Message Required!", "secretMessage");
byte[] plainText = Encoding.UTF8.GetBytes(secretMessage);
byte[] cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload);
return Convert.ToBase64String(cipherText);
}
public static string SimpleDecryptWithPassword(string encryptedMessage, string password,
int nonSecretPayloadLength = 0)
{
if (String.IsNullOrWhiteSpace(encryptedMessage))
throw new ArgumentException(@"Encrypted Message Required!", "encryptedMessage");
byte[] cipherText = Convert.FromBase64String(encryptedMessage);
byte[] plaintext = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength);
return Encoding.UTF8.GetString(plaintext);
}
public static byte[] SimpleEncrypt(byte[] secretMessage, byte[] key, byte[] nonSecretPayload = null)
{
//User Error Checks
if (key == null || key.Length != KeyBitSize/8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");
if (secretMessage == null || secretMessage.Length == 0)
throw new ArgumentException(@"Secret Message Required!", "secretMessage");
//Non-secret Payload Optional
nonSecretPayload = nonSecretPayload ?? new byte[] {};
//Using random nonce large enough not to repeat
var nonce = new byte[NonceBitSize/8];
Random.NextBytes(nonce, 0, nonce.Length);
var cipher = new GcmBlockCipher(new AesFastEngine());
var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
cipher.Init(true, parameters);
//Generate Cipher Text With Auth Tag
var cipherText = new byte[cipher.GetOutputSize(secretMessage.Length)];
int len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0);
cipher.DoFinal(cipherText, len);
//Assemble Message
using (var combinedStream = new MemoryStream())
{
using (var binaryWriter = new BinaryWriter(combinedStream))
{
//Prepend Authenticated Payload
binaryWriter.Write(nonSecretPayload);
//Prepend Nonce
binaryWriter.Write(nonce);
//Write Cipher Text
binaryWriter.Write(cipherText);
}
return combinedStream.ToArray();
}
}
public static byte[] SimpleDecrypt(byte[] encryptedMessage, byte[] key, int nonSecretPayloadLength = 0)
{
//User Error Checks
if (key == null || key.Length != KeyBitSize/8)
throw new ArgumentException(String.Format("Key needs to be {0} bit!", KeyBitSize), "key");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException(@"Encrypted Message Required!", "encryptedMessage");
using (var cipherStream = new MemoryStream(encryptedMessage))
using (var cipherReader = new BinaryReader(cipherStream))
{
//Grab Payload
byte[] nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength);
//Grab Nonce
byte[] nonce = cipherReader.ReadBytes(NonceBitSize/8);
var cipher = new GcmBlockCipher(new AesFastEngine());
var parameters = new AeadParameters(new KeyParameter(key), MacBitSize, nonce, nonSecretPayload);
cipher.Init(false, parameters);
//Decrypt Cipher Text
byte[] cipherText =
cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length);
var plainText = new byte[cipher.GetOutputSize(cipherText.Length)];
try
{
int len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0);
cipher.DoFinal(plainText, len);
}
catch (InvalidCipherTextException)
{
//Return null if it doesn't authenticate
return null;
}
return plainText;
}
}
public static byte[] SimpleEncryptWithPassword(byte[] secretMessage, string password,
byte[] nonSecretPayload = null)
{
nonSecretPayload = nonSecretPayload ?? new byte[] {};
//User Error Checks
if (String.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
throw new ArgumentException(
String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
if (secretMessage == null || secretMessage.Length == 0)
throw new ArgumentException(@"Secret Message Required!", "secretMessage");
var generator = new Pkcs5S2ParametersGenerator();
//Use Random Salt to minimize pre-generated weak password attacks.
var salt = new byte[SaltBitSize/8];
Random.NextBytes(salt);
generator.Init(
PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),
salt,
Iterations);
//Generate Key
var key = (KeyParameter) generator.GenerateDerivedMacParameters(KeyBitSize);
//Create Full Non Secret Payload
var payload = new byte[salt.Length + nonSecretPayload.Length];
Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length);
Array.Copy(salt, 0, payload, nonSecretPayload.Length, salt.Length);
return SimpleEncrypt(secretMessage, key.GetKey(), payload);
}
public static byte[] SimpleDecryptWithPassword(byte[] encryptedMessage, string password,
int nonSecretPayloadLength = 0)
{
//User Error Checks
if (String.IsNullOrWhiteSpace(password) || password.Length < MinPasswordLength)
throw new ArgumentException(
String.Format("Must have a password of at least {0} characters!", MinPasswordLength), "password");
if (encryptedMessage == null || encryptedMessage.Length == 0)
throw new ArgumentException(@"Encrypted Message Required!", "encryptedMessage");
var generator = new Pkcs5S2ParametersGenerator();
//Grab Salt from Payload
var salt = new byte[SaltBitSize/8];
Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length);
generator.Init(
PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()),
salt,
Iterations);
//Generate Key
var key = (KeyParameter) generator.GenerateDerivedMacParameters(KeyBitSize);
return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength);
}
// ENCRYPTION OPERTAIONS.
public static string Encrypt(string plaintext, string key)
{
try
{
return SimpleEncryptWithPassword(plaintext, key);
}
catch (Exception ex)
{
FooLogging.WriteLog(ex.ToString());
return null;
}
}
public static string Decrypt(string encrypted, string key)
{
try
{
byte[] encryptedArray = Convert.FromBase64String(encrypted);
byte[] decryptedArray = SimpleDecryptWithPassword(encryptedArray, key);
return Encoding.UTF8.GetString(decryptedArray);
}
catch (Exception ex)
{
FooLogging.WriteLog(ex.ToString());
return null;
}
}
// HASHING OPERATIONS.
public static string CreateShaHash(string input)
{
var hasher = new SHA256Managed();
byte[] passwordAsByte = Encoding.UTF8.GetBytes(input);
byte[] encryptedBytes = hasher.ComputeHash(passwordAsByte);
hasher.Clear();
// Return as hex.
return BitConverter.ToString(encryptedBytes).Replace("-", string.Empty);
}
// MACHINE KEY OPERATIONS.
public static string MachineEncrypt(string input)
{
byte[] unprotectedBytes = Encoding.UTF8.GetBytes(input);
byte[] protectedBytes = MachineKey.Protect(unprotectedBytes, TokenPurpose);
string protectedText = Convert.ToBase64String(protectedBytes);
return protectedText;
}
public static string MachineDecrypt(string protectedText)
{
byte[] protectedBytes = Convert.FromBase64String(protectedText);
byte[] unprotectedBytes = MachineKey.Unprotect(protectedBytes, TokenPurpose);
if (unprotectedBytes != null)
{
string unprotectedText = Encoding.UTF8.GetString(unprotectedBytes);
return unprotectedText;
}
return null;
}
}
}