Created
January 2, 2015 19:30
-
-
Save sohjsolwin/9a0d1954b09f31d831f3 to your computer and use it in GitHub Desktop.
Easy Encryption/Decryption
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
private enum XcryptMode | |
{ | |
Encrypt, | |
Decrypt | |
} | |
private string XcryptString(XcryptMode mode, string message) | |
{ | |
byte[] results; | |
var returnValue = string.Empty; | |
var UTF8 = new System.Text.UTF8Encoding(); | |
var hashProvider = new System.Security.Cryptography.MD5CryptoServiceProvider(); | |
byte[] tdesKey = hashProvider.ComputeHash(UTF8.GetBytes(encryptKey)); | |
var tdesAlgorithm = new System.Security.Cryptography.TripleDESCryptoServiceProvider(); | |
tdesAlgorithm.Key = tdesKey; | |
tdesAlgorithm.Mode = System.Security.Cryptography.CipherMode.ECB; | |
tdesAlgorithm.Padding = System.Security.Cryptography.PaddingMode.PKCS7; | |
byte[] dataToCrypt = null; | |
if (mode == XcryptMode.Encrypt) | |
{ | |
dataToCrypt = UTF8.GetBytes(message); | |
} | |
else if (mode == XcryptMode.Decrypt) | |
{ | |
dataToCrypt = Convert.FromBase64String(message); | |
} | |
try | |
{ | |
System.Security.Cryptography.ICryptoTransform cryptor = null; | |
if (mode == XcryptMode.Encrypt) | |
{ | |
cryptor = tdesAlgorithm.CreateEncryptor(); | |
} | |
else if (mode == XcryptMode.Decrypt) | |
{ | |
cryptor = tdesAlgorithm.CreateDecryptor(); | |
} | |
results = cryptor.TransformFinalBlock(dataToCrypt, 0, dataToCrypt.Length); | |
} | |
finally | |
{ | |
tdesAlgorithm.Clear(); | |
hashProvider.Clear(); | |
} | |
if (mode == XcryptMode.Encrypt) | |
{ | |
returnValue = Convert.ToBase64String(results); | |
} | |
else if (mode == XcryptMode.Decrypt) | |
{ | |
returnValue = UTF8.GetString(results); | |
} | |
return returnValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment