Encode and decode in CSharp – C#
Tuesday, April 4th, 2017
(0 Comment)
In here, we will do simple exercise about encode and decode in CSharp – C#.
We have two ways encode and decode a string in CSharp (simple and with key).
1) Encode and decode in CSharp without key
Encode function
1 2 3 4 5 |
static String Base64Encode(String textIn) { var _encode = Encoding.UTF8.GetBytes(textIn); return Convert.ToBase64String(_encode); } |
Decode function
1 2 3 4 5 |
static String Base64Decode(String encode) { var decode = Convert.FromBase64String(encode); return Encoding.UTF8.GetString(decode); } |
Run
1 2 3 4 5 6 7 8 9 10 11 12 |
static void Example1() { //Encode and decode in CSharp without key var text = "Hello Lvtutorial"; Console.WriteLine(text); Console.WriteLine("Start encoding..."); var encode = Base64Encode(text); Console.WriteLine("encode is : " + encode); var decode = Base64Decode(encode); Console.WriteLine("decode is : " + decode); } |
Output:
1 2 3 4 5 |
Hello Lvtutorial Start encoding... encode is : SGVsbG8gTHZ0dXRvcmlhbA== decode is : Hello Lvtutorial Press any key to continue . . . |
2) Encode and decode in CSharp with key
Encode function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
static String encodeWithKey(String textIn, String key) { var _crypt = new TripleDESCryptoServiceProvider(); var _hashmd5 = new MD5CryptoServiceProvider(); var _byteHash = _hashmd5.ComputeHash(Encoding.UTF8.GetBytes(key)); var _byteText = Encoding.UTF8.GetBytes(textIn); _crypt.Key = _byteHash; _crypt.Mode = CipherMode.ECB; var _encodeByte = _crypt.CreateEncryptor().TransformFinalBlock(_byteText, 0, _byteText.Length); return Convert.ToBase64String(_encodeByte) ; } |
Decode function
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
static String decodeWithKey(String encode, String key) { var _crypt = new TripleDESCryptoServiceProvider(); var _hashmd5 = new MD5CryptoServiceProvider(); var _byteHash = _hashmd5.ComputeHash(Encoding.UTF8.GetBytes(key)); var _byteText = Convert.FromBase64String(encode); _crypt.Key = _byteHash; _crypt.Mode = CipherMode.ECB; var decodeByte = _crypt.CreateDecryptor().TransformFinalBlock(_byteText, 0, _byteText.Length); return Encoding.UTF8.GetString(decodeByte); } |
Run
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
static void Example2() { //Encode and decode in CSharp with key var text = "Hello Lvtutorial"; var key = "Your Password"; Console.WriteLine("text: " + text); Console.WriteLine("key: " + key); Console.WriteLine("Start encoding with key..."); var encode = encodeWithKey(text, key); Console.WriteLine("encode is : " + encode); var decode = decodeWithKey(encode, key); Console.WriteLine("decode is : " + decode); } |
Output:
1 2 3 4 5 6 |
text: Hello Lvtutorial key: Your Password Start encoding with key... encode is : JB/ipdCvlX46cXRsnmoJsxrEiWvel+xf decode is : Hello Lvtutorial Press any key to continue . . . |
Tags: C#, CSharp, encode and decode in C#, encode C#, sample c# code