-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathCrypt.cs
More file actions
77 lines (67 loc) · 2.49 KB
/
Crypt.cs
File metadata and controls
77 lines (67 loc) · 2.49 KB
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
using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
using System.Globalization;
namespace App.Opayo
{
public static class Crypt
{
public static string Encrypt(string input, string password)
{
return ByteArrayToHexString(AesEncrypt(Encoding.UTF8.GetBytes(input), password));
}
public static string Decrypt(string input, string password)
{
return Encoding.UTF8.GetString(AESdecrypt(ConvertHexStringToByteArray(input.Replace("@", "")), password));
}
private static byte[] ConvertHexStringToByteArray(string hexString)
{
if (hexString.Length % 2 != 0)
{
throw new ArgumentException("Binary key must have even number of digits");
}
byte[] data = new byte[hexString.Length / 2];
for (int index = 0; index < data.Length; index++)
{
string byteValue = hexString.Substring(index * 2, 2);
data[index] = byte.Parse(byteValue, NumberStyles.HexNumber, CultureInfo.InvariantCulture);
}
return data;
}
private static string ByteArrayToHexString(byte[] value)
{
return BitConverter.ToString(value).Replace("-", "");
}
private static byte[] AesEncrypt(byte[] input, string key)
{
using MemoryStream ms = new MemoryStream();
var aes = GetAesManagedEncryption(key);
CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
private static byte[] AESdecrypt(byte[] input, string key)
{
using MemoryStream ms = new MemoryStream();
var aes = GetAesManagedEncryption(key);
CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(input, 0, input.Length);
cs.FlushFinalBlock();
return ms.ToArray();
}
private static AesManaged GetAesManagedEncryption(string key)
{
return new AesManaged
{
Padding = PaddingMode.PKCS7,
Mode = CipherMode.CBC,
KeySize = 128,
BlockSize = 128,
Key = Encoding.UTF8.GetBytes(key),
IV = Encoding.UTF8.GetBytes(key)
};
}
}
}