-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathEncrypt.cs
130 lines (102 loc) · 3.23 KB
/
Encrypt.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
using System.Text;
using System.Security.Cryptography;
using System.IO;
namespace TradeControl.Web.Mail
{
/// <summary>
/// Encrypts or decrypts strings according to passed keys/vectors using the RijndaelManaged algorithm
/// </summary>
public class Encrypt
{
readonly byte[] key;
readonly byte[] iv;
public Encrypt(byte[] _key, byte[] _iv)
{
key = _key;
iv = _iv;
}
public Encrypt(byte[] _fullKey)
{
key = new byte[16];
iv = new byte[16];
for (int i = 0; i < 16; i++)
{
key[i] = _fullKey[i];
iv[i + 16] = _fullKey[i + 16];
}
}
private byte[] ToByte(char[] _chars)
{
byte[] bytes = new byte[_chars.Length];
for (int i = 0; i < _chars.Length; i++)
bytes[i] = (byte)_chars[i];
return bytes;
}
private string ByteToString(byte[] _bytes)
{
string result = string.Empty;
for (int i = 0; i < _bytes.Length; i++)
result = result + (char)_bytes[i];
return result;
}
#region Encryption
private byte[] Key
{
get
{
return key;
}
}
private byte[] IV
{
get
{
return iv;
}
}
public string DecryptString(string _encrypted)
{
string decrypt;
try
{
ASCIIEncoding textConverter = new();
byte[] encrypted = ToByte(_encrypted.ToCharArray());
RijndaelManaged RMCrypto = new();
byte[] fromEncrypt;
ICryptoTransform decryptor = RMCrypto.CreateDecryptor(Key, IV);
MemoryStream msDecrypt = new(encrypted);
CryptoStream csDecrypt = new(msDecrypt, decryptor, CryptoStreamMode.Read);
fromEncrypt = new byte[encrypted.Length];
csDecrypt.Read(fromEncrypt, 0, fromEncrypt.Length);
decrypt = textConverter.GetString(fromEncrypt).Trim(new char[] { ' ', '\0' });
}
catch
{
decrypt = string.Empty;
}
return decrypt;
}
public string EncryptString(string _decrypted)
{
try
{
ASCIIEncoding textConverter = new();
RijndaelManaged RMCrypto = new();
byte[] toEncrypt;
ICryptoTransform encryptor = RMCrypto.CreateEncryptor(Key, IV);
MemoryStream msEncrypt = new();
CryptoStream csEncrypt = new(msEncrypt, encryptor, CryptoStreamMode.Write);
toEncrypt = textConverter.GetBytes(_decrypted);
csEncrypt.Write(toEncrypt, 0, toEncrypt.Length);
csEncrypt.FlushFinalBlock();
byte[] encrypted = msEncrypt.ToArray();
return ByteToString(encrypted) ;
}
catch
{
return string.Empty;
}
}
#endregion
}
}