ASP.-EF link string Encryption in Mvc5+ef6+easyui admin system

Source: Internet
Author: User
Tags decrypt key string pkcs7 asymmetric encryption connectionstrings

Objective:

This section provides a simple feature that looks simple, finds an encrypted help document that does not find the EF link database string, and can only write on its own, which is more in line with its own encryption requirements

  • Sometimes we publish programs in order to avoid the outside of the program SQL link string explicit exposure, need to do some encryption means!
  • Encryption mainly divided into several categories: symmetric encryption, asymmetric encryption, hashing algorithm (Baidu's own brain repair, there is no more to say)
  • Here I choose AES 256-bit encryption, the main encryption speed algorithm fast, high security, low resource consumption.
  • The company has been using AES encryption to encrypt some small data volumes of data, comparison methods and security

This is the reason I choose to encrypt AES, of course you can choose other famous encryption algorithms, such as Md5,sha,3des. (Note: Large companies should be banned from writing algorithms to add decryption)

Knowledge Points:

The use of data is basically the same as our login process, get the encrypted link string, and then decrypt it using

So we need:

    1. Encryption class
    2. Encryption tools
    3. Where EF uses the link string
1. Encryption class
    Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks;  Using system.security.cryptography;using system.io;namespace apps.common{public class Aesencrypthelper {// <summary>///Get key//</summary> private static string key {get {RE        Turn @ ") O[nb]6,yf}+efcaj{+oesb9d8>z ' e9m";}            }///<summary>//Get vector//</summary> private static string IV { get {return @ "L+\~f4,ir) B$=PKF"; }} #region parameter is byte[] Type///<summary>//AES encryption//</summary>/// Lt;param name= "Data" > Encrypted plaintext </param>//<param name= "key" > Key </param>//<param name = "vector" > Vector </param>//<returns> redaction </returns> public static byte[] Aesencrypt (byte[] D ATA, String Key, String Vector) {byte[] BKey = new byte[32];            Array.copy (Encoding.UTF8.GetBytes (Key.padright (bkey.length)), Bkey, bkey.length);            byte[] Bvector = new BYTE[16];            Array.copy (Encoding.UTF8.GetBytes (Vector.padright (bvector.length)), Bvector, bvector.length); byte[] cryptograph = null;            Encrypted ciphertext Rijndael Aes = Rijndael.create ();                try {//open a memory stream using (MemoryStream memories = new MemoryStream ())                     {//wraps the memory stream object into an encrypted stream object using (CryptoStream encryptor = new CryptoStream (memory,                        Aes.createencryptor (Bkey, Bvector), CryptoStreamMode.Write)) {                        PlainText data is written to the encrypted stream Encryptor.write (data, 0, data.length);                        Encryptor.flushfinalblock ();                    Cryptograph = Memory.toarray ();       }}} catch     {cryptograph = null;        } return cryptograph; }///<summary>//AES decryption//</summary>/<param name= "Data" > Decrypted ciphertext </p        aram>//<param name= "key" > Key </param>//<param name= "vector" > Vector </param>        <returns> plaintext </returns> public static byte[] Aesdecrypt (byte[] Data, String Key, String Vector)            {byte[] bkey = new BYTE[32];            Array.copy (Encoding.UTF8.GetBytes (Key.padright (bkey.length)), Bkey, bkey.length);            byte[] Bvector = new BYTE[16];            Array.copy (Encoding.UTF8.GetBytes (Vector.padright (bvector.length)), Bvector, bvector.length); byte[] original = null;            decrypted plaintext Rijndael Aes = Rijndael.create ();                try {//open up a memory stream to store ciphertext using (MemoryStream memory = new MemoryStream (Data)) {//PutThe memory stream object is wrapped into an encrypted stream object using (CryptoStream decryptor = new CryptoStream (Memory, Aes.createdec                        Ryptor (Bkey, Bvector), CryptoStreamMode.Read)) {//plaintext Store                            using (MemoryStream originalmemory = new MemoryStream ()) {                            byte[] Buffer = new byte[1024];                            Int32 readbytes = 0;                                while ((Readbytes = Decryptor.read (Buffer, 0, buffer.length)) > 0) {                            Originalmemory.write (Buffer, 0, readbytes);                        } original = Originalmemory.toarray ();            }}}} catch {original = null;        } return original; #endregion #region parameter is String type//<summary>//AES encryption//</summary>//<param name= "Plainstr" > Clear text string </param> <returns> redaction </returns> public static string Aesencrypt (String plainstr) {byte[            ] Bkey = Encoding.UTF8.GetBytes (Key);            byte[] BIV = Encoding.UTF8.GetBytes (IV);            byte[] ByteArray = Encoding.UTF8.GetBytes (PLAINSTR);            string encrypt = null;            Rijndael AES = Rijndael.create (); using (MemoryStream mstream = new MemoryStream ()) {using (CryptoStream cstream = new Cryptostre AM (Mstream, AES. CreateEncryptor (Bkey, BIV), CryptoStreamMode.Write)) {cstream.write (ByteArray, 0, Bytea Rray.                    Length);                    Cstream.flushfinalblock ();                Encrypt = Convert.tobase64string (Mstream.toarray ()); }} AES.            Clear ();        return encrypt;    }//<summary>    AES encryption///</summary>//<param name= "Plainstr" > Clear text string </param>//<param        Name= "Returnnull" > whether to return Null,false when encryption fails string.empty</param>//<returns> redaction </returns> public static string Aesencrypt (string plainstr, bool returnnull) {String encrypt = Aesencrypt (plain            STR); Return returnnull? Encrypt: (encrypt = = null?)        String.Empty:encrypt); }//<summary>//AES decryption//</summary>/<param name= "Encryptstr" > Ciphertext string &        lt;/param>//<returns> plaintext </returns> public static string Aesdecrypt (String encryptstr)            {byte[] bkey = Encoding.UTF8.GetBytes (Key);            byte[] BIV = Encoding.UTF8.GetBytes (IV);            byte[] ByteArray = convert.frombase64string (ENCRYPTSTR);            string decrypt = null;            Rijndael AES = Rijndael.create (); using (MemoryStream MSTREAM = new MemoryStream ()) {using (CryptoStream cstream = new CryptoStream (Mstream, AES. CreateDecryptor (Bkey, BIV), CryptoStreamMode.Write)) {cstream.write (ByteArray, 0, Bytea Rray.                    Length);                    Cstream.flushfinalblock ();                Decrypt = Encoding.UTF8.GetString (Mstream.toarray ()); }} AES.            Clear ();        return decrypt; }//<summary>//AES decryption//</summary>/<param name= "Encryptstr" > Ciphertext string & lt;/param>//<param name= "Returnnull" > If decryption fails return null,false return string.empty</param>//<            returns> plaintext </returns> public static string Aesdecrypt (string encryptstr, bool returnnull) {            String decrypt = Aesdecrypt (ENCRYPTSTR); Return returnnull? Decrypt: (decrypt = = null?)        String.Empty:decrypt); } #endregion #region 256-bit AEs encryption algorithm///<summary>//256-bit AES encryption///</summary>//<param name= "Toencrypt"            ;</param>//<returns></returns> public static string Encrypt (String toencrypt) {            256-aes key byte[] Keyarray = UTF8Encoding.UTF8.GetBytes (key);            byte[] Toencryptarray = UTF8Encoding.UTF8.GetBytes (Toencrypt);            RijndaelManaged Rdel = new RijndaelManaged ();            Rdel.key = Keyarray;            Rdel.mode = CIPHERMODE.ECB;            rdel.padding = PADDINGMODE.PKCS7;            ICryptoTransform ctransform = Rdel.createencryptor ();            byte[] Resultarray = Ctransform.transformfinalblock (toencryptarray, 0, toencryptarray.length);        Return convert.tobase64string (resultarray, 0, resultarray.length); }///<summary>//256-bit AES decryption//</summary>//<param name= "Todecrypt" >&lt ;/param>//<returns></returns> public static string Decrypt (String todecrypt) {//256-aes key by            te[] Keyarray = UTF8Encoding.UTF8.GetBytes (Key);            byte[] Toencryptarray = convert.frombase64string (Todecrypt);            RijndaelManaged Rdel = new RijndaelManaged ();            Rdel.key = Keyarray;            Rdel.mode = CIPHERMODE.ECB;            rdel.padding = PADDINGMODE.PKCS7;            ICryptoTransform ctransform = Rdel.createdecryptor ();            byte[] Resultarray = Ctransform.transformfinalblock (toencryptarray, 0, toencryptarray.length);        Return UTF8Encoding.UTF8.GetString (resultarray); } #endregion}}

Catch a lot of online, you search for the encryption class you want!

2. Encryption Tools

Encryption tools This online can not grasp, need to combine the encryption class to develop, this does not need me to lead the development of the bar, okay

Create a new Winfrom program, name the Apps.encrypthelper, reference the class library where you encrypt the class, or drop it directly under Apps.encrypthelper.

Pull 2 textbox and 2 button layout from the toolbar, the basic page is finished, and then double-click the two button to enter the event implementation code.

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.linq;using system.text;using system.threading.tasks;using system.windows.forms;using Apps.Common; namespace apps.encrypthelper{public partial class Encrypt:form {public Encrypt () {Init        Ializecomponent (); }//Encrypt private void Btnencrypt_click (object sender, EventArgs e) {if (string.                IsNullOrEmpty (Txtsourcetext.text)) {MessageBox.Show ("No data plus densely-_-!");            Return            } else {txtresulttext.text = Aesencrypthelper.encrypt (Txtsourcetext.text); }}//Decrypt private void Btndecrypt_click (object sender, EventArgs e) {if (string.i                Snullorempty (Txtsourcetext.text)) {MessageBox.Show ("No Data Jiumaumi-_-!");            Return } else if(! Isbase64formatted (Txtsourcetext.text) {MessageBox.Show ("Don't tease me, I only know my secret?")                ");            Return            } else {txtresulttext.text = Aesencrypthelper.decrypt (Txtsourcetext.text);                }} public static bool Isbase64formatted (string input) {try {                Convert.frombase64string (input);            return true;            } catch {return false; }        }    }}

Dozens of lines of code, solve car room wife problem! Run....

.

3. Combine into EF

This one's still easier to handle.

First: Find the EF link string for the connectionstrings of the Web. config

Second: Change the value corresponding to the key string

  <connectionStrings>    <add name= "Dbcontainer" connectionstring= "ka7ocma8neypjbqyulvwbsmteidxkge+ zfxau3/0emhvrp+in+9ecpy/litoy9vfzvda9evgmmzh/ 8z0rxrihgprhvmfwlibuj9rdgthbqry02voylbrz7iixrnxyhllfsvgj23kxnhl8j6jxb1qnsmuuxplqnd6hp9y5rqq2ej//ot+ ukqhvc1quqvzdy+xr6hx/o5jgk6kjgk3nk83qo09eboundo7odxqg9sxpuynyzjhyx9yv2/1ubghuxhrxhrauxie4mjlqh/rusjay8d3ls/ Roiibszsy+i400ce4nigdwzag679yvbkbq5pg "providername=" System.Data.EntityClient "/>  </connectionstrings >

Third: Find the place where EF reads the string

This must read the decrypted string, so we'll write a method to get the decrypted string Configpara

Using system;using system.collections.generic;using system.linq;using system.text;using System.Threading.Tasks; namespace apps.common{public    class Configpara    {public        static string Efdbconnection {            get {                String connection = system.configuration.configurationmanager.connectionstrings["Dbcontainer"]. ConnectionString;                return Aesencrypthelper.decrypt (connection);}}}    

Note that the modification is also useless, will be back, because this class is generated according to T4, so we have to modify the T4

Modify the position of the corresponding red box!

Do you think you can understand my connection string now? :-)

Ok. Implement encryption, run normally

Let's get him into the system!

Thank you!

ASP.-EF link string Encryption in Mvc5+ef6+easyui admin system

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.