การเข้ารหัส string
แบบ Symmetric (SymmetricAlgorithm
) ด้วย TripleDESCryptoServiceProvider
RijndaelManaged, DESCryptoServiceProvider, RC2CryptoServiceProvider, and TripleDESCryptoServiceProvider are implementations of symmetric algorithms.
Crypto.cs
using System; using System.IO; using System.Security.Cryptography; using System.Text; namespace ConsoleApp { public class Crypto { SymmetricAlgorithm mCSP; #region "Constants" private object _key = "01234562d3dg"; string iv = "abcdeUCVF7s="; #endregion public Crypto() { } public bool HasKey() { return (!(_key == null || _key.ToString() == "")); } private string SetLengthString(string str, int length) { while (length > str.Length) { str += str; } if (str.Length > length) { str = str.Remove(length); } return str; } public string EncryptString(string Value) { mCSP = SetEnc(); mCSP.IV = Convert.FromBase64String(iv); string key = SetLengthString(_key.ToString(), 32); mCSP.Key = Convert.FromBase64String(key); ICryptoTransform ct; MemoryStream ms; CryptoStream cs; Byte[] byt = new byte[64]; try { ct = mCSP.CreateEncryptor(mCSP.Key, mCSP.IV); byt = Encoding.UTF8.GetBytes(Value); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); return Convert.ToBase64String(ms.ToArray()).Replace('/', '_').Replace('+', '-'); } catch (Exception Ex) { throw (new Exception("An error occurred while encrypting string")); } } public string DecryptString(string Value) { mCSP = SetEnc(); mCSP.IV = Convert.FromBase64String(iv); string key = SetLengthString(_key.ToString(), 32); mCSP.Key = Convert.FromBase64String(key); ICryptoTransform ct; MemoryStream ms; CryptoStream cs; Byte[] byt = new byte[64]; try { ct = mCSP.CreateDecryptor(mCSP.Key, mCSP.IV); byt = Convert.FromBase64String(Value.Replace('_', '/').Replace('-', '+')); ms = new MemoryStream(); cs = new CryptoStream(ms, ct, CryptoStreamMode.Write); cs.Write(byt, 0, byt.Length); cs.FlushFinalBlock(); cs.Close(); //string str = return Encoding.UTF8.GetString(ms.ToArray()); } catch (Exception ex) { throw (new Exception("An error occurred while decrypting string : " + ex.Message)); } } private SymmetricAlgorithm SetEnc() { return new TripleDESCryptoServiceProvider(); } } }
Program.cs
using System; namespace ConsoleApp { class Program { static void Main(string[] args) { string plainText = "Helo World!"; Crypto crypto = new Crypto(); string encrpytText = crypto.EncryptString(plainText); string decryptText= crypto.DecryptString(encrpytText); Console.WriteLine(string.Format("plainText = {0}", plainText)); Console.WriteLine(string.Format("encrpytText = {0}", encrpytText)); Console.WriteLine(string.Format("decryptText = {0}", decryptText)); } } }
ผลการรัน
plainText = Helo World! encrpytText = 27KmYMudRbIROkwfhlsPpA== decryptText = Helo World!