Last active
June 14, 2022 15:57
-
-
Save arviedelgado/0cf6f6064a2b2e18eefd468c3db4e2a3 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using System.Collections.Generic; | |
| using System.IO; | |
| using System.Linq; | |
| using System.Security.Cryptography; | |
| namespace SystemSecurityCryptography | |
| { | |
| /// <summary> | |
| /// https://docs.microsoft.com/en-us/dotnet/api/system.security.cryptography.aescryptoserviceprovider?view=netframework-4.8 | |
| /// </summary> | |
| public class AES | |
| { | |
| private readonly AesCryptoServiceProvider _aes; | |
| public AES() | |
| { | |
| _aes = new AesCryptoServiceProvider(); | |
| } | |
| public string Encrypt(string plain) | |
| { | |
| var encryptor = _aes.CreateEncryptor(); | |
| using (var memoryStream = new MemoryStream()) | |
| { | |
| using (var cryptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write)) | |
| { | |
| using (var streamWriter = new StreamWriter(cryptoStream)) | |
| { | |
| streamWriter.Write(plain); | |
| } | |
| var encryptedTextBytes = memoryStream.ToArray(); | |
| var encryptedText = Convert.ToBase64String(encryptedTextBytes); | |
| return encryptedText; | |
| } | |
| } | |
| } | |
| public string Decrypt(string encrypted) | |
| { | |
| var encryptedTextBytes = Convert.FromBase64String(encrypted); | |
| var decryptor = _aes.CreateDecryptor(); | |
| using (var memoryStream = new MemoryStream(encryptedTextBytes)) | |
| { | |
| using (var cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read)) | |
| { | |
| using (var streamReader = new StreamReader(cryptoStream)) | |
| { | |
| var plainText = streamReader.ReadToEnd(); | |
| return plainText; | |
| } | |
| } | |
| } | |
| } | |
| public List<string> Encrypt(List<string> plain) | |
| { | |
| return plain.Select(x => Encrypt(x)).ToList(); | |
| } | |
| public List<string> Decrypt(List<string> encrypted) | |
| { | |
| return encrypted.Select(x => Decrypt(x)).ToList(); | |
| } | |
| public Dictionary<string, string> Encrypt(IDictionary<string, string> plain) | |
| { | |
| return plain.ToDictionary(x => x.Key, x => Encrypt(x.Value)); | |
| } | |
| public Dictionary<string, string> Decrypt(IDictionary<string, string> encrypted) | |
| { | |
| return encrypted.ToDictionary(x => x.Key, x => Decrypt(x.Value)); | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment