Click here to Skip to main content
15,896,557 members
Articles / Web Development / ASP.NET

Encryption and compression, native and managed

Rate me:
Please Sign up or sign in to vote.
4.74/5 (17 votes)
29 Jun 2012CPOL7 min read 111.2K   6.9K   92  
DLL for native encryption and compression (using Crypto++). Includes RSA Key Generator in C#, and encryption and compression in ASP.NET (C#).
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using NetCryptLib;
using System.IO;
using System.Diagnostics;
using NETPCryptLib;
using System.Net;

namespace NetCryptTest
{
    public partial class FrmTest : Form
    {

        CNETInfoFormat ObjCrypt;
        const string tempfile1 = "Temp.tmp";
        const string tempfile2 = "Temp1.tmp";
        CNETPInfoFormat ObjCryptMan;
        public FrmTest()
        {
            InitializeComponent();
        }
        private bool ValidOptions()
        {
            if (CboEncrypt.SelectedIndex == 1 && ChkPureManaged.Checked)
            {
                MessageBox.Show("Crypto++ DEM not implemented yet in pure managed code");
                return false;
            }
            if (CboOutput.SelectedIndex == 2 && ChkPureManaged.Checked)
            {
                MessageBox.Show("Output cannot be Octal. Not implemented in pure managed code");
                return false;
            }
            return true;

        }
        private void FrmTest_Load(object sender, EventArgs e)
        {
            InitCbos();
            ObjCrypt = new CNETInfoFormat();
            ObjCryptMan = new CNETPInfoFormat();

            TxtBuffer.Text = "8192";
        }
        private void InitCbos()
        {
            CboZip.Items.Add("None");
            CboZip.Items.Add("GZip");
            CboZip.Items.Add("ZLib");

            CboEncrypt.Items.Add("None");
            CboEncrypt.Items.Add("DEM");
            CboEncrypt.Items.Add("RSA");
            CboEncrypt.Items.Add("BlowFish");
            CboEncrypt.Items.Add("AES");

            CboOutput.Items.Add("Binary");
            CboOutput.Items.Add("Bits");
            CboOutput.Items.Add("Octal");
            CboOutput.Items.Add("Hex");
            CboOutput.Items.Add("B64");

            CboZip.SelectedIndex = 0;
            CboEncrypt.SelectedIndex = 0;
            CboOutput.SelectedIndex = 0;
        }
        private void InitCryptObjects(bool pencode)
        {
            //Managed
            if (!ObjCryptMan.IsInit)
            {
                ObjCryptMan.Initialize();
                AssignRSAToCryptoPlus();
            }
            ObjCryptMan.NETPBuf.optPNetencrypt = (NETPCryptLib.TNETPEnumEncrypt)CboEncrypt.SelectedIndex;
            ObjCryptMan.NETPBuf.optPNetoutput = (NETPCryptLib.TNETPEnumOutput)CboOutput.SelectedIndex;
            ObjCryptMan.NETPBuf.optPNetzip = (NETPCryptLib.TNETPEnumZip)CboZip.SelectedIndex;
            if (pencode)
                ObjCryptMan.NETPBuf.optPNetoper = NETPCryptLib.TNETPEnumOperation.TNETPOperEncode;
            else
                ObjCryptMan.NETPBuf.optPNetoper = NETPCryptLib.TNETPEnumOperation.TNETPOperDecode;

            //Native            
            ObjCrypt.NETbuf.optNetencrypt = (NetCryptLib.TNETEnumEncrypt)CboEncrypt.SelectedIndex;
            ObjCrypt.NETbuf.optNetoutput = (NetCryptLib.TNETEnumOutput)CboOutput.SelectedIndex;
            ObjCrypt.NETbuf.optNetzip = (NetCryptLib.TNETEnumZip)CboZip.SelectedIndex;
            if (pencode)
                ObjCrypt.NETbuf.optNetoper = NetCryptLib.TNETEnumOperation.TNETOperEncode;
            else
                ObjCrypt.NETbuf.optNetoper = NetCryptLib.TNETEnumOperation.TNETOperDecode;
            ObjCrypt.Initialize();
            ObjCrypt.NETbuf.AssignParams();

            SetManPWDFromCryptoPlus();

        }
        private void AssignRSAToCryptoPlus()
        {
            ObjCrypt.NETkeys.NETRSAd = GetArr(ObjCryptMan.NETPKeys.NETPRSAd, ObjCryptMan.NETPKeys.NETPRSAd.Length);
            ObjCrypt.NETkeys.NETRSAdp = GetArr(ObjCryptMan.NETPKeys.NETPRSAdp, ObjCryptMan.NETPKeys.NETPRSAdp.Length);
            ObjCrypt.NETkeys.NETRSAdq = GetArr(ObjCryptMan.NETPKeys.NETPRSAdq, ObjCryptMan.NETPKeys.NETPRSAdq.Length);
            ObjCrypt.NETkeys.NETRSAexponent = GetArr(ObjCryptMan.NETPKeys.NETPRSAexponent, ObjCryptMan.NETPKeys.NETPRSAexponent.Length);
            ObjCrypt.NETkeys.NETRSAinverseq = GetArr(ObjCryptMan.NETPKeys.NETPRSAinverseq, ObjCryptMan.NETPKeys.NETPRSAinverseq.Length);
            ObjCrypt.NETkeys.NETRSAmodulus = GetArr(ObjCryptMan.NETPKeys.NETPRSAmodulus, ObjCryptMan.NETPKeys.NETPRSAmodulus.Length);
            ObjCrypt.NETkeys.NETRSAp = GetArr(ObjCryptMan.NETPKeys.NETPRSAp, ObjCryptMan.NETPKeys.NETPRSAp.Length);
            ObjCrypt.NETkeys.NETRSAq = GetArr(ObjCryptMan.NETPKeys.NETPRSAq, ObjCryptMan.NETPKeys.NETPRSAq.Length);

            ObjCrypt.NETkeys.NETRSAd_size = ObjCryptMan.NETPKeys.NETPRSAd.Length;
            ObjCrypt.NETkeys.NETRSAdp_size = ObjCryptMan.NETPKeys.NETPRSAdp.Length;
            ObjCrypt.NETkeys.NETRSAdq_size = ObjCryptMan.NETPKeys.NETPRSAdq.Length;
            ObjCrypt.NETkeys.NETRSAexponent_size = ObjCryptMan.NETPKeys.NETPRSAexponent.Length;
            ObjCrypt.NETkeys.NETRSAinverseq_size = ObjCryptMan.NETPKeys.NETPRSAinverseq.Length;
            ObjCrypt.NETkeys.NETRSAmodulus_size = ObjCryptMan.NETPKeys.NETPRSAmodulus.Length;
            ObjCrypt.NETkeys.NETRSAp_size = ObjCryptMan.NETPKeys.NETPRSAp.Length;
            ObjCrypt.NETkeys.NETRSAq_size = ObjCryptMan.NETPKeys.NETPRSAq.Length;

            ObjCrypt.NETkeys.AssignObject();
        }
        private void CmdEncrypt_Click(object sender, EventArgs e)
        {
            if (!ValidOptions()) return;

            InitCryptObjects(true);

            byte[] res = Encoding.ASCII.GetBytes(TxtTextEncrypt.Text);
            byte[] a = ObjCryptMan.NETPKeys.NETPbfkey;
            byte[] b = ObjCrypt.NETkeys.NETbfkey;
            if (ChkPureManaged.Checked)
            {
                res.CopyTo(ObjCryptMan.NETPBuf.NETPbuffer, 0);
                ObjCryptMan.NETPBuf.NETPbufferlen = res.Length;
                ObjCryptMan.OpClose();

                TxtEncrypted.Text = Encoding.ASCII.GetString(ObjCryptMan.NETPBuf.NETPbuffer, 0, ObjCryptMan.NETPBuf.NETPbufferlen);

                ObjCryptMan.NETPBuf.optPNetoper = TNETPEnumOperation.TNETPOperDecode;
                ObjCryptMan.OpClose();

                TxtDecrypted.Text = Encoding.ASCII.GetString(ObjCryptMan.NETPBuf.NETPbuffer, 0, ObjCryptMan.NETPBuf.NETPbufferlen);
            }
            else
            {
                res.CopyTo(ObjCrypt.NETbuf.NETbuffer, 0);
                ObjCrypt.NETbuf.NETbufferlen = res.Length;
                ObjCrypt.OpClose();

                TxtEncrypted.Text = Encoding.ASCII.GetString(ObjCrypt.NETbuf.NETbuffer, 0, ObjCrypt.NETbuf.NETbufferlen);

                ObjCrypt.NETbuf.optNetoper = NetCryptLib.TNETEnumOperation.TNETOperDecode;
                ObjCrypt.NETbuf.AssignParams();
                ObjCrypt.OpClose();

                TxtDecrypted.Text = Encoding.ASCII.GetString(ObjCrypt.NETbuf.NETbuffer, 0, ObjCrypt.NETbuf.NETbufferlen);
            }


        }

        private void CmdSearch_Click(object sender, EventArgs e)
        {
            DialogResult res = OfdFileSearch.ShowDialog();
            if (res == System.Windows.Forms.DialogResult.Cancel) return;

            TxtFile.Text = OfdFileSearch.FileName;
        }

        private void CmdEncryptFile_Click(object sender, EventArgs e)
        {
            EncryptFile(true);
        }
        private void EncryptFile(bool pencrypt)
        {
            if (!ValidOptions()) return;

            if (!File.Exists(TxtFile.Text))
            {
                MessageBox.Show("The file does not exist");
                return;
            }
            //Initialize the object
            InitCryptObjects(pencrypt);

            FileInfo finfo = new FileInfo(TxtFile.Text);

            BinaryReader binReader = new BinaryReader(File.Open(TxtFile.Text, FileMode.Open));
            string strftemp = Application.StartupPath + "\\" + tempfile1;

            if (File.Exists(strftemp)) File.Delete(strftemp);
            BinaryWriter binWriter = new BinaryWriter(File.Open(strftemp, FileMode.Create));

            long totallen = binReader.BaseStream.Length;
            long counter = 0;
            long countoutput = 0;
            int bread;

            int bufferlen = Int32.Parse(TxtBuffer.Text);

            PrgFile.Maximum = (int)(finfo.Length / 1000);
            PrgFile.Value = 0;
            int countaux = 0;

            Stopwatch stwatch = new Stopwatch();
            stwatch.Start();

            while (counter < totallen)
            {
                if (ChkPureManaged.Checked)
                    bread = binReader.Read(ObjCryptMan.NETPBuf.NETPbuffer, 0, bufferlen);
                else
                    bread = binReader.Read(ObjCrypt.NETbuf.NETbuffer, 0, bufferlen);

                counter += bread;
                countaux += bread;

                if (ChkPureManaged.Checked)
                    ObjCryptMan.NETPBuf.NETPbufferlen = bread;
                else
                    ObjCrypt.NETbuf.NETbufferlen = bread;

                byte[] test = new byte[100];

                if (ChkPureManaged.Checked)
                {
                    if (counter == totallen)
                        ObjCryptMan.OpClose();
                    else
                        ObjCryptMan.OpOpen();

                    binWriter.Write(ObjCryptMan.NETPBuf.NETPbuffer, 0, ObjCryptMan.NETPBuf.NETPbufferlen);

                    countoutput += ObjCryptMan.NETPBuf.NETPbufferlen;
                }
                else
                {
                    if (counter == totallen)
                        ObjCrypt.OpClose();
                    else
                        ObjCrypt.OpOpen();
                    binWriter.Write(ObjCrypt.NETbuf.NETbuffer, 0, ObjCrypt.NETbuf.NETbufferlen);

                    countoutput += ObjCrypt.NETbuf.NETbufferlen;
                }

                if (countaux > 100000)
                {
                    countaux = 0;
                    PrgFile.Value = (int)(counter / 1000);
                    Application.DoEvents();
                }
            }

            binReader.Close();
            binWriter.Close();
            File.Delete(TxtFile.Text);
            File.Copy(strftemp, TxtFile.Text);
            File.Delete(strftemp);
            PrgFile.Value = 0;
            stwatch.Stop();
            MessageBox.Show("Finished + " + stwatch.ElapsedMilliseconds.ToString());
        }

        private void SetManPWDFromCryptoPlus()
        {
            Buffer.BlockCopy(ObjCrypt.NETkeys.NETAESiv, 0, ObjCryptMan.NETPKeys.NETPAESiv, 0, ObjCrypt.NETkeys.NETAESiv.Length);
            Buffer.BlockCopy(ObjCrypt.NETkeys.NETAESkey, 0, ObjCryptMan.NETPKeys.NETPAESkey, 0, ObjCrypt.NETkeys.NETAESkeylen);
            ObjCryptMan.NETPKeys.NETPAESkeylen = ObjCrypt.NETkeys.NETAESkeylen;

            Buffer.BlockCopy(ObjCrypt.NETkeys.NETbfiv, 0, ObjCryptMan.NETPKeys.NETPbfiv, 0, ObjCrypt.NETkeys.NETbfiv.Length);
            Buffer.BlockCopy(ObjCrypt.NETkeys.NETbfkey, 0, ObjCryptMan.NETPKeys.NETPbfkey, 0, ObjCrypt.NETkeys.NETbfkeylen);
            ObjCryptMan.NETPKeys.NETPbfkeylen = ObjCrypt.NETkeys.NETbfkeylen;

            ObjCryptMan.NETPKeys.NETPRSAKeySize = ObjCrypt.NETkeys.NETRSAKeySize;

            ObjCryptMan.NETPKeys.NETPRSAd = GetArr(ObjCrypt.NETkeys.NETRSAd, ObjCrypt.NETkeys.NETRSAd_size);
            ObjCryptMan.NETPKeys.NETPRSAdp = GetArr(ObjCrypt.NETkeys.NETRSAdp, ObjCrypt.NETkeys.NETRSAdp_size);
            ObjCryptMan.NETPKeys.NETPRSAdq = GetArr(ObjCrypt.NETkeys.NETRSAdq, ObjCrypt.NETkeys.NETRSAdq_size);
            ObjCryptMan.NETPKeys.NETPRSAexponent = GetArr(ObjCrypt.NETkeys.NETRSAexponent, ObjCrypt.NETkeys.NETRSAexponent_size);
            ObjCryptMan.NETPKeys.NETPRSAinverseq = GetArr(ObjCrypt.NETkeys.NETRSAinverseq, ObjCrypt.NETkeys.NETRSAinverseq_size);
            ObjCryptMan.NETPKeys.NETPRSAmodulus = GetArr(ObjCrypt.NETkeys.NETRSAmodulus, ObjCrypt.NETkeys.NETRSAmodulus_size);
            ObjCryptMan.NETPKeys.NETPRSAp = GetArr(ObjCrypt.NETkeys.NETRSAp, ObjCrypt.NETkeys.NETRSAp_size);
            ObjCryptMan.NETPKeys.NETPRSAq = GetArr(ObjCrypt.NETkeys.NETRSAq, ObjCrypt.NETkeys.NETRSAq_size);

            ObjCryptMan.InitKeysCrypt();
        }
        private byte[] GetArr(byte[] arr, int len)
        {
            byte[] res = arr.ToList<byte>().GetRange(0, len).ToArray();
            return res;
        }

        private void CmdDecryptFile_Click(object sender, EventArgs e)
        {
            EncryptFile(false);
        }

        private void cmdExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void CmdSendWeb_Click(object sender, EventArgs e)
        {
            if (!ValidSendWeb()) return;

            CGlobalKeys gkeys = new CGlobalKeys();
            CNETPInfoFormat info = gkeys.GetInfoFormat();

            StringBuilder str = new StringBuilder();
            str.Append("http://localhost:4792/TestForm.aspx?");
            str.Append("Zip=" + CboZip.SelectedIndex);
            str.Append("&Enc=" + CboEncrypt.SelectedIndex);
            str.Append("&Out=" + CboOutput.SelectedIndex);

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(str.ToString());
            req.Method = "POST";

            Stream dataStream = req.GetRequestStream();

            byte[] btext = Encoding.ASCII.GetBytes(TxtTextEncrypt.Text);

            info.NETPBuf.optPNetencrypt = (NETPCryptLib.TNETPEnumEncrypt)CboEncrypt.SelectedIndex;
            info.NETPBuf.optPNetoutput = (NETPCryptLib.TNETPEnumOutput)CboOutput.SelectedIndex;
            info.NETPBuf.optPNetzip = (NETPCryptLib.TNETPEnumZip)CboZip.SelectedIndex;
            info.NETPBuf.optPNetoper = TNETPEnumOperation.TNETPOperEncode;

            btext.CopyTo(info.NETPBuf.NETPbuffer, 0);
                        
            info.NETPBuf.NETPbufferlen = btext.Length;
            info.OpClose();

            String str1 = Encoding.ASCII.GetString(info.NETPBuf.NETPbuffer, 0, info.NETPBuf.NETPbufferlen);
            
            dataStream.Write(info.NETPBuf.NETPbuffer, 0, info.NETPBuf.NETPbufferlen);
            dataStream.Close();

            WebResponse res = req.GetResponse();
            Stream resdata = res.GetResponseStream();

            byte[] restext = new byte[1000];
            int n = resdata.Read(restext, 0, 1000);

            res.Close();

            CGlobalKeys gkeysres = new CGlobalKeys();
            CNETPInfoFormat infores = gkeysres.GetInfoFormat();
            infores.NETPBuf.optPNetencrypt = (NETPCryptLib.TNETPEnumEncrypt)CboEncrypt.SelectedIndex;
            infores.NETPBuf.optPNetoutput = (NETPCryptLib.TNETPEnumOutput)CboOutput.SelectedIndex;
            infores.NETPBuf.optPNetzip = (NETPCryptLib.TNETPEnumZip)CboZip.SelectedIndex;
            infores.NETPBuf.optPNetoper = TNETPEnumOperation.TNETPOperDecode;

            Buffer.BlockCopy(restext, 0, infores.NETPBuf.NETPbuffer, 0, n);
            infores.NETPBuf.NETPbufferlen = n;
            infores.OpClose();

            String strres = Encoding.ASCII.GetString(infores.NETPBuf.NETPbuffer, 0, infores.NETPBuf.NETPbufferlen);
            MessageBox.Show(strres);

        }
        private bool ValidSendWeb()
        {
            if (CboEncrypt.SelectedIndex == 1)
            {
                MessageBox.Show("Crypto++ DEM not implemented yet in pure managed code");
                return false;
            }
            if (CboOutput.SelectedIndex == 0)
            {
                MessageBox.Show("Output cannot be Binary. HTML cannot handle binary output");
                return false;
            }
            if (CboOutput.SelectedIndex == 2)
            {
                MessageBox.Show("Output cannot be Octal. Not implemented in pure managed code");
                return false;
            }
            return true;

        }

        private void CmdTestCLI_Click(object sender, EventArgs e)
        {
            //Key and CBC initial block
            byte[] BFKEY = { 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0xf3, 0x9f, 0x38, 0x2f, 0x01 }; 
            byte[] CBCIV = {0xaa, 0xbb, 0xcc, 0xdd,0xee, 0xff, 0x11, 0x22};

            //Create new object
            CNETInfoFormat infotest = new CNETInfoFormat();

            //Set conversion options
            infotest.NETbuf.optNetencrypt = TNETEnumEncrypt.TNETEncryptBlowFish;
            infotest.NETbuf.optNetzip = TNETEnumZip.TNETZipZLib;
            infotest.NETbuf.optNetoutput = TNETEnumOutput.TNETOutputBase64;

            //Set mode (encode/decode)
            infotest.NETbuf.optNetoper = TNETEnumOperation.TNETOperEncode;

            //Set Keys
            BFKEY.CopyTo(infotest.NETkeys.NETbfkey, 0);
            infotest.NETkeys.NETbfkeylen = BFKEY.Length;
            CBCIV.CopyTo(infotest.NETkeys.NETbfiv, 0);

            //Reinitialize encryption z with the new keys
            infotest.Initialize();

            //Assign the buffer a test string
            byte[] bres = Encoding.ASCII.GetBytes("Prueba");
            bres.CopyTo(infotest.NETbuf.NETbuffer, 0);
            infotest.NETbuf.NETbufferlen = bres.Length;

            //Assign unmanaged params from managed ones
            infotest.NETbuf.AssignParams();

            //Perform the conversion
            infotest.OpClose();

            //Assign the result to string
            string strenc = Encoding.ASCII.GetString(infotest.NETbuf.NETbuffer, 0, infotest.NETbuf.NETbufferlen);
            //Show result
            MessageBox.Show(strenc);

            //Set mode to decode
            infotest.NETbuf.optNetoper = TNETEnumOperation.TNETOperDecode;
            //Assign unmanaged params from managed ones
            infotest.NETbuf.AssignParams();
            //Decode the buffer which is already encrypted in the object
            infotest.OpClose();
            
            //Assign the result to string
            string strdec = Encoding.ASCII.GetString(infotest.NETbuf.NETbuffer, 0, infotest.NETbuf.NETbufferlen);
            //Show result
            MessageBox.Show(strdec);

        }

        private void cmdTestPureNET_Click(object sender, EventArgs e)
        {
            //Key and CBC initial block
            byte[] BFKEY = { 0xa1, 0xb2, 0xc3, 0xd4, 0xe5, 0xf6, 0xe1, 0xd2, 0xc3, 0xb4, 0xa5, 0xf3, 0x9f, 0x38, 0x2f, 0x01 };
            byte[] CBCIV = { 0xaa, 0xbb, 0xcc, 0xdd, 0xee, 0xff, 0x11, 0x22 };

            //Create new object
            CNETPInfoFormat infotest = new CNETPInfoFormat();

            //Initialize object
            infotest.Initialize();

            //Set conversion options
            infotest.NETPBuf.optPNetencrypt = TNETPEnumEncrypt.TNETPEncryptBlowFish;
            infotest.NETPBuf.optPNetzip = TNETPEnumZip.TNETPZipZLib;
            infotest.NETPBuf.optPNetoutput = TNETPEnumOutput.TNETPOutputBase64;

            //Set mode (encode/decode)
            infotest.NETPBuf.optPNetoper = TNETPEnumOperation.TNETPOperEncode;

            //Set Keys
            BFKEY.CopyTo(infotest.NETPKeys.NETPbfkey, 0);
            infotest.NETPKeys.NETPbfkeylen = BFKEY.Length;
            CBCIV.CopyTo(infotest.NETPKeys.NETPbfiv, 0);

            //Assign encryption objects the new keys
            infotest.InitKeysCrypt();

            //Assign the buffer a test string
            byte[] bres = Encoding.ASCII.GetBytes("Prueba");
            bres.CopyTo(infotest.NETPBuf.NETPbuffer, 0);
            infotest.NETPBuf.NETPbufferlen = bres.Length;

            //Perform the conversion
            infotest.OpClose();

            //Assign the result to string
            string strenc = Encoding.ASCII.GetString(infotest.NETPBuf.NETPbuffer, 0, infotest.NETPBuf.NETPbufferlen);
            //Show result
            MessageBox.Show(strenc);

            //Set mode to decode
            infotest.NETPBuf.optPNetoper = TNETPEnumOperation.TNETPOperDecode;
            //Decode the buffer which is already encrypted in the object
            infotest.OpClose();

            //Assign the result to string
            string strdec = Encoding.ASCII.GetString(infotest.NETPBuf.NETPbuffer, 0, infotest.NETPBuf.NETPbufferlen);
            //Show result
            MessageBox.Show(strdec);
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Argentina Argentina
System developer from Argentina.

Programmed in VB 5,6,.NET, C#, Java, PL-SQL, Transac-SQL, C, C++ and even some "calculator" language.

Love to build small, useful applications.
Usually building big and complicated apps based on solid, reliable components.

Hobbies: reading, photography, chess, paddle, running.

Comments and Discussions