Symmetric encryption: AES, compression, decompression, compression, encryption, decryption, and decompression

Source: Internet
Author: User
Tags pkcs7

Symmetric encryption: AES, compression, decompression, compression, encryption, decryption, and decompression

Symmetric encryption:

Both parties adopt this encryption method to use the same key for encryption and decryption. A key is a command used to control the encryption and decryption processes. An algorithm is a set of rules that define how to encrypt and decrypt data. Therefore, encryption security not only depends on the encryption algorithm itself, but also the security of key management. Because encryption and decryption both use the same key, it is necessary to solve how to securely transmit the key to the decrypted. It can be seen that key transmission is also an important part. Generally, the key transmission encryption is implemented through the secondary encryption of the key:  
        public static byte[] encryptStringToBytes_AES(byte[] fileContentBytes, byte[] Key, byte[] IV)        {            // Check arguments.            if (fileContentBytes == null || fileContentBytes.Length <= 0)                throw new ArgumentNullException("plainText");            if (Key == null || Key.Length <= 0)                throw new ArgumentNullException("Key");            if (IV == null || IV.Length <= 0)                throw new ArgumentNullException("IV");            MemoryStream msEncrypt = null;            AesCryptoServiceProvider aesAlg = null;            try            {                aesAlg = new AesCryptoServiceProvider();                aesAlg.Padding = PaddingMode.PKCS7;                aesAlg.Key = Key;                aesAlg.IV = IV;                ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);                msEncrypt = new MemoryStream();                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))                {                    csEncrypt.Write(fileContentBytes, 0, fileContentBytes.Length);                    csEncrypt.FlushFinalBlock();                }            }            catch (Exception ex)            {            }            finally            {                if (aesAlg != null)                    aesAlg.Clear();            }            return msEncrypt.ToArray();        }

 

Decryption code implementation:

 

        public static byte[] decryptBytes(byte[] cipherText, byte[] Key, byte[] IV)        {            if (cipherText == null || cipherText.Length <= 0)                throw new ArgumentNullException("cipherText");            if (Key == null || Key.Length <= 0)                throw new ArgumentNullException("Key");            if (IV == null || IV.Length <= 0)                throw new ArgumentNullException("IV");            AesCryptoServiceProvider aesAlg = null;            byte[] buffer = null;            try            {                using (aesAlg = new AesCryptoServiceProvider())                {                    aesAlg.Padding = PaddingMode.PKCS7;                    aesAlg.Key = Key;                    aesAlg.IV = IV;                    ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);                    using (MemoryStream msDecrypt = new MemoryStream(cipherText))                    {                        CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read);                        byte[] tempbuffer = new byte[cipherText.Length];                        int totalBytesRead = csDecrypt.Read(tempbuffer, 0, tempbuffer.Length);                        buffer = tempbuffer.Take(totalBytesRead).ToArray();                    }                }            }            catch (Exception ex)            {            }            finally            {                if (aesAlg != null)                    aesAlg.Clear();            }            return buffer;        }

 

Client-side encryption and decryption of text files:

 

/// <Summary> /// encryption and decryption /// </summary> private static void _ EncryptAndDecrypt () {ASCIIEncoding asciiEnc = new ASCIIEncoding (); byte [] initVectorBytes = asciiEnc. getBytes ("@ 1B2c3D4e5F6g7H8"); // Randomly generate or Book key-key K2-Key to encrypt xml content string keyK2 = Generator. randomString (10); // Generate the 128 bit string using MD5 for key K2 MD5 hashProvider = MD5.Create (); byte [] md5EncryptedKeyK2 = hashProvider. computeHash (asciiEnc. getBytes (keyK2); string filename = "NewTextDocument.txt"; string filepath = Environment. currentDirectory + "\" + filename; byte [] Content = Encryption. encryptStringToBytes_AES (File. readAllBytes (filepath), md5EncryptedKeyK2, initVectorBytes); string encryptfilepath = Environment. currentDirectory + "\ encrypt" + filename; File. writeAllBytes (encryptfilepath, Content); byte [] decryptContent = Encryption. decryptBytes (File. readAllBytes (encryptfilepath), md5EncryptedKeyK2, initVectorBytes); string decryptfilepath = Environment. currentDirectory + "\ decrypt" + filename; File. writeAllBytes (decryptfilepath, decryptContent );}

Compression and decompression:

 

String filename = "NewTextDocument.txt"; string filepath = Environment. currentDirectory + "\" + filename; string zipfilepath = Environment. currentDirectory + "\ NewTextDocument.zip"; using (ZipFile contentZip = new ZipFile () {// compress contentZip. alternateEncoding = Encoding. getEncoding ("iso-8859-1"); contentZip. alternateEncodingUsage = ZipOption. always; ZipEntry contentFile = contentZip. addEntry (filename, File. readAllBytes (filepath); contentZip. save (zipfilepath); // extract contentZip. extractAll (Environment. currentDirectory );}

Compression encryption, decryption, and decompression:

 

 string filename = "NewTextDocument.zip";            string filepath = Environment.CurrentDirectory + "\\" + filename;            string zipfilepath = Environment.CurrentDirectory + "\\" + filename;            ZipFile contentZip = new ZipFile();            contentZip.AlternateEncoding = Encoding.GetEncoding("iso-8859-1");            contentZip.AlternateEncodingUsage = ZipOption.Always;            var bytecontent = File.ReadAllBytes(Environment.CurrentDirectory + "\\NewTextDocument.txt");            ZipEntry contentFile = contentZip.AddEntry("NewTextDocument.txt", bytecontent);            contentZip.Save(zipfilepath);            ASCIIEncoding asciiEnc = new ASCIIEncoding();            byte[] initVectorBytes = asciiEnc.GetBytes("@1B2c3D4e5F6g7H8");            //Randomly generate or Book key - key K2 - Key to encrypt xml content            string keyK2 = Generator.RandomString(10);            //Generate the 128 bit string using MD5 for key K2            MD5 hashProvider = MD5.Create();            byte[] md5EncryptedKeyK2 = hashProvider.ComputeHash(asciiEnc.GetBytes(keyK2));            byte[] Content = Encryption.encryptStringToBytes_AES(File.ReadAllBytes(filepath), md5EncryptedKeyK2, initVectorBytes);            string encryptfilepath = Environment.CurrentDirectory + "\\encrypt" + filename;            File.WriteAllBytes(encryptfilepath, Content);            byte[] decryptContent = Encryption.decryptBytes(File.ReadAllBytes(encryptfilepath), md5EncryptedKeyK2, initVectorBytes);            string decryptfilepath = Environment.CurrentDirectory + "\\decrypt" + filename;            File.WriteAllBytes(decryptfilepath, decryptContent);            contentZip.ExtractAll(Environment.CurrentDirectory + "\\unzip\\decrypt");            string key = Convert.ToBase64String(md5EncryptedKeyK2);            string iv = Convert.ToBase64String(initVectorBytes);            Console.WriteLine(key);            Console.WriteLine(iv);            byte[] decryptContent1 = Encryption.decryptBytes(File.ReadAllBytes(encryptfilepath), Convert.FromBase64String(key), Convert.FromBase64String(iv));            string decryptfilepath1 = Environment.CurrentDirectory + "\\decrypt1" + filename;            contentZip.ExtractAll(Environment.CurrentDirectory + "\\unzip\\decrypt1");            File.WriteAllBytes(decryptfilepath1, decryptContent1);

 

Reference: NET symmetric encryption system

Related Article

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.