-
-
Save diddimar/52aeb7fe6d9613982ec592ae5dd0a1c7 to your computer and use it in GitHub Desktop.
EncryptionService
This file contains 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.IO; | |
using System.Security.Cryptography; | |
using System.Text; | |
namespace Demo | |
{ | |
public static class EncryptionService | |
{ | |
private static string EncryptionKey = "some-secret-key-longer-or-equal-to-128-bits"; | |
public static string Encrypt(string clearText) | |
{ | |
byte[] clearBytes = Encoding.UTF8.GetBytes(clearText); | |
using (Aes encryptor = Aes.Create()) | |
{ | |
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); | |
encryptor.Key = pdb.GetBytes(32); | |
encryptor.IV = pdb.GetBytes(16); | |
using (MemoryStream ms = new MemoryStream()) | |
{ | |
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write)) | |
{ | |
cs.Write(clearBytes, 0, clearBytes.Length); | |
cs.Close(); | |
} | |
clearText = Convert.ToBase64String(ms.ToArray()); | |
} | |
} | |
Console.WriteLine(clearText); | |
return clearText; | |
} | |
public static string Decrypt(string cipherText) | |
{ | |
cipherText = cipherText.Replace(" ", "+"); | |
byte[] cipherBytes = Convert.FromBase64String(cipherText); | |
try | |
{ | |
using (Aes encryptor = Aes.Create()) | |
{ | |
Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 }); | |
encryptor.Key = pdb.GetBytes(32); | |
encryptor.IV = pdb.GetBytes(16); | |
using (MemoryStream ms = new MemoryStream()) | |
{ | |
using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write)) | |
{ | |
cs.Write(cipherBytes, 0, cipherBytes.Length); | |
cs.Close(); | |
} | |
cipherText = Encoding.UTF8.GetString(ms.ToArray()); | |
} | |
} | |
return cipherText; | |
} | |
catch (Exception) | |
{ | |
return "Could not decrypt"; | |
throw; | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment