diff options
Diffstat (limited to 'Gestor.Common/Gestor.Common.Helpers/EncryptionHelper.cs')
| -rw-r--r-- | Gestor.Common/Gestor.Common.Helpers/EncryptionHelper.cs | 77 |
1 files changed, 77 insertions, 0 deletions
diff --git a/Gestor.Common/Gestor.Common.Helpers/EncryptionHelper.cs b/Gestor.Common/Gestor.Common.Helpers/EncryptionHelper.cs new file mode 100644 index 0000000..5b982d0 --- /dev/null +++ b/Gestor.Common/Gestor.Common.Helpers/EncryptionHelper.cs @@ -0,0 +1,77 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace Gestor.Common.Helpers; + +public static class EncryptionHelper +{ + private static readonly byte[] Salt = new byte[16] + { + 38, 220, 255, 0, 173, 237, 122, 238, 197, 254, + 7, 175, 77, 8, 34, 60 + }; + + private static readonly string EncryptionKey = $"aGG3r{1012}#w3BDz$"; + + public static string Encrypt(this string plain) + { + return Convert.ToBase64String(Encoding.UTF8.GetBytes(plain).EncryptBytes()); + } + + public static byte[] EncryptBytes(this byte[] plainTextBytes) + { + using Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(EncryptionKey, Salt); + using Rijndael rijndael = Rijndael.Create(); + rijndael.Key = rfc2898DeriveBytes.GetBytes(32); + rijndael.IV = rfc2898DeriveBytes.GetBytes(16); + using MemoryStream memoryStream = new MemoryStream(); + using CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateEncryptor(), CryptoStreamMode.Write); + cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); + cryptoStream.FlushFinalBlock(); + return memoryStream.ToArray(); + } + + public static string Decrypt(this string cipher) + { + if (string.IsNullOrEmpty(cipher)) + { + return null; + } + try + { + byte[] array = Convert.FromBase64String(cipher); + if (array.Length < 16) + { + return cipher; + } + byte[] array2 = array.DecryptBytes(); + return (array2 == null) ? cipher : Encoding.UTF8.GetString(array2); + } + catch (Exception) + { + return cipher; + } + } + + public static byte[] DecryptBytes(this byte[] plainTextBytes) + { + try + { + using Rfc2898DeriveBytes rfc2898DeriveBytes = new Rfc2898DeriveBytes(EncryptionKey, Salt); + using Rijndael rijndael = Rijndael.Create(); + rijndael.Key = rfc2898DeriveBytes.GetBytes(32); + rijndael.IV = rfc2898DeriveBytes.GetBytes(16); + using MemoryStream memoryStream = new MemoryStream(); + using CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndael.CreateDecryptor(), CryptoStreamMode.Write); + cryptoStream.Write(plainTextBytes, 0, plainTextBytes.Length); + cryptoStream.FlushFinalBlock(); + return memoryStream.ToArray(); + } + catch (Exception) + { + return null; + } + } +} |