Following is the helper class for encrypting or decrypting a string using TripleDES method.
You can use your own phrase as key.
Encrypt function will return a string contains A-Z, a-z, 0-9,+,/ and = only as we are converting the encrypted bytes array using Base64 encoding. Here last 3 characters (+,/,=) are not suitable for URLS. So I replaced them with !,@,$ respectively. While decrpting, I simply reverse the replacement.
using System; using System.Security.Cryptography; using System.Text; namespace CareerBox { public class CryptoHelper { static TripleDESCryptoServiceProvider cryptDES3 = new TripleDESCryptoServiceProvider(); static MD5CryptoServiceProvider cryptMD5Hash = new MD5CryptoServiceProvider(); static string key = "g0p!P0rt@L"; public static string Encrypt(string text) { try { cryptDES3.Key = cryptMD5Hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes (key)); cryptDES3.Mode = CipherMode.ECB; ICryptoTransform desdencrypt = cryptDES3.CreateEncryptor(); byte[] buff = ASCIIEncoding.ASCII.GetBytes(text); string Encrypt = Convert.ToBase64String (desdencrypt.TransformFinalBlock(buff, 0, buff.Length)); //Replace +,/,= with !,@,# for URL friendly Encrypt = Encrypt.Replace("+", "!").Replace("/", "@").Replace("=", "$"); return Encrypt; } catch { return ""; } } public static string Decyrpt(string text) { try { //Replace !,@,# with +,/,= text = text.Replace("$", "=").Replace("@", "/").Replace("!", "+"); byte[] buf = new byte[text.Length]; cryptDES3.Key = cryptMD5Hash.ComputeHash(ASCIIEncoding.ASCII.GetBytes (key)); cryptDES3.Mode = CipherMode.ECB; ICryptoTransform desdencrypt = cryptDES3.CreateDecryptor(); buf = Convert.FromBase64String(text); string Decrypt = ASCIIEncoding.ASCII.GetString (desdencrypt.TransformFinalBlock(buf, 0, buf.Length)); return Decrypt; } catch { return ""; } } } }
You can use your own phrase as key.
Encrypt function will return a string contains A-Z, a-z, 0-9,+,/ and = only as we are converting the encrypted bytes array using Base64 encoding. Here last 3 characters (+,/,=) are not suitable for URLS. So I replaced them with !,@,$ respectively. While decrpting, I simply reverse the replacement.
0 comments:
Post a Comment