Last active
September 27, 2021 08:07
-
-
Save shukebeta/780df627a3de55c848a800cfb242a276 to your computer and use it in GitHub Desktop.
a short & complete class for text encryption, grapped from https://stackoverflow.com/questions/165808/simple-insecure-two-way-data-obfuscation#comment1320154_212707 in Ashkan Sirous' answer
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.Security.Cryptography; | |
using System.Text; | |
namespace xxx.ClassLibrary | |
{ | |
public static class TextEncryption | |
{ | |
private static TripleDESCryptoServiceProvider GetCryproProvider(string keyStr) | |
{ | |
var md5 = new MD5CryptoServiceProvider(); | |
var key = md5.ComputeHash(Encoding.UTF8.GetBytes(keyStr)); | |
return new TripleDESCryptoServiceProvider() { Key = key, Mode = CipherMode.ECB, Padding = PaddingMode.PKCS7 }; | |
} | |
public static string Encrypt(string plainString, string keyStr) | |
{ | |
var data = Encoding.UTF8.GetBytes(plainString); | |
var tripleDes = GetCryproProvider(keyStr); | |
var transform = tripleDes.CreateEncryptor(); | |
var resultsByteArray = transform.TransformFinalBlock(data, 0, data.Length); | |
return Convert.ToBase64String(resultsByteArray); | |
} | |
public static string Decrypt(string encryptedString, string keyStr) | |
{ | |
var data = Convert.FromBase64String(encryptedString); | |
var tripleDes = GetCryproProvider(keyStr); | |
var transform = tripleDes.CreateDecryptor(); | |
var resultsByteArray = transform.TransformFinalBlock(data, 0, data.Length); | |
return Encoding.UTF8.GetString(resultsByteArray); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment