-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathUtilityTests.cs
84 lines (78 loc) · 2.95 KB
/
UtilityTests.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
using System;
using System.IO;
using System.Text.RegularExpressions;
using NUnit.Framework;
namespace Gaev.Blog.SecuredAppSettingsJson
{
public class UtilityTests
{
private static string CipherKey => "l8cpD27QcWDXjAg8ut+qH0IkWv/p38DrAst4Ee83jMg=";
[TestCase("This is kind of connection string ;)")]
public void Encrypt_value_and_print(string value)
{
var cipher = new Aes256Cipher(CipherKey);
Console.WriteLine(cipher.Encrypt(value));
}
[TestCase("09lXf8qen+mQJeAgl7lBcTIdCvpvDOQs7NL3oyiwOJpfqn26PWxkpEkS2+SAGf0BjCHT/uHfXzYZPQeyYyb+0A==")]
public void Decrypt_value_and_print(string value)
{
var cipher = new Aes256Cipher(CipherKey);
Console.WriteLine(cipher.Decrypt(value));
}
[Test]
public void Generate_new_key_and_print()
{
Console.WriteLine("Key: " + Aes256Cipher.GenerateNewKey());
}
[TestCase("../../../appsettings.json")]
public void Encrypt_secured_fields_in_json(string filename)
{
var cipher = new Aes256Cipher(CipherKey);
var jsonFile = new FileInfo(filename);
var json = File.ReadAllText(jsonFile.FullName);
json = Regex.Replace(
json,
@"""CipherText:(?<Text>[^""]+)""",
m =>
{
var text = m.Groups["Text"].Value;
try
{
var cipherText = cipher.Encrypt(text);
return $@"""CipherText:{cipherText}""";
}
catch (Exception)
{
Console.WriteLine($@"Failed encrypting ""{text}""");
return m.Value;
}
});
File.WriteAllText(jsonFile.FullName, json);
}
[TestCase("../../../appsettings.json")]
public void Decrypt_secured_fields_in_json(string filename)
{
var cipher = new Aes256Cipher(CipherKey);
var jsonFile = new FileInfo(filename);
var json = File.ReadAllText(jsonFile.FullName);
json = Regex.Replace(
json,
@"""CipherText:(?<CipherText>[^""]+)""",
m =>
{
var cipherText = m.Groups["CipherText"].Value;
try
{
var text = cipher.Decrypt(cipherText);
return $@"""CipherText:{text}""";
}
catch (Exception)
{
Console.WriteLine($@"Failed decrypting ""{cipherText}""");
return m.Value;
}
});
File.WriteAllText(jsonFile.FullName, json);
}
}
}