benshepherd icon

Encryption algorithm

benshepherd | PRO | 04/08/13 08:47:23 PM UTC | 0 ⭐ | 284 👁️ | Never ⏰ | []
C# |

12.6 KB

|

None

|

0 👍

/

0 👎

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
using System.Threading;
 
namespace BENcrypt
{
    public partial class Form1 : Form
    {
        public string charArray;
        public long KeyInt;
        public string input;
        public string output;
        XMLclass XmlClass;
 
        public Form1()
        {
            InitializeComponent();
        }
 
        private void Form1_Load(object sender, EventArgs e)
        {
            setCharArray();
            XmlClass = new XMLclass();
            XmlClass.XMLpath = Environment.SpecialFolder.ApplicationData + "\\BENcrypt\\config.xml";
 
 
            if (File.Exists(XmlClass.XMLpath))
            {
                string[] config = XmlClass.ConfigData;
 
                //input, ouput, key, log
                txtIn.Text = config[0];
                txtOut.Text = config[1];
                txtKey.Text = config[2];
                txtLog.Text = config[3];
            }
 
        }
 
        private void btnEn_Click(object sender, EventArgs e)
        {
            log("-------------------------\r\nEncryption event started");
            while (true)
            {
                if (txtKey.Text.Length == 0)
                {
                    log("Error: Key cannot be empty");
                    break;
                }
                else if (txtIn.Text.Length == 0)
                {
                    log("Error: Input cannot be empty");
                    break;
                }
                string result = encrypt(txtIn.Text, txtKey.Text);
                log("Encryption finished.");
                txtOut.Text = result;
                break;
            }
        }
 
        private void btnDe_Click(object sender, EventArgs e)
        {
            while (true)
            {
                //string pattern = "/^[(0-9]+[:.]+$/";
                //string str = txtIn.Text;
 
                /*if (!Regex.Match(str, pattern).Success)
                {
                    log("-------------------------\r\nCannot decrypt - Unrecognized format\r\nMust be like:\r\nxx:xxx:x:xxxxx:xxx\r\ne.t.c.");
                    break;
                }*/
                log("-------------------------\r\nDecryption event started");
                while (true)
                {
                    if (txtKey.Text.Length == 0)
                    {
                        log("Error: Key cannot be empty");
                        break;
                    }
                    else if (txtIn.Text.Length == 0)
                    {
                        log("Error: Input cannot be empty");
                        break;
                    }
                    string result = decrypt(txtIn.Text, txtKey.Text);
                    txtOut.Text = result;
                    break;
                }
 
                break;
            }
        }
 
        private long generateKey(string x)
        {
            log("Generating numeric key  (" + x + ")");
            int[] y = new int[x.Length];
            string z = "";
            for (int i = 0; i < x.Length; i++)
            {
                int bz = z.Length;
                y[i] = charArray.IndexOf(x[i]);
                z += y[i].ToString();
            }
 
            long kfinal = 0;
            try
            {
                kfinal = Convert.ToInt32(z) / z.Length / z.Length;
            }
            catch (Exception ex)
            {
                kfinal = 0;
                MessageBox.Show(ex.ToString(), "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
 
            log("Key generated");
            return kfinal;
        }
 
        private void setCharArray()
        {
            charArray = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890 !\"£$%^&*()_-+=[]{};:'@#~,<.>/?`¬|\\/";
        }
 
        private string decrypt(string str, string key)
        {
            log("Starting Decryption process...");
            KeyInt = generateKey(key);
            string output = "";
 
            if (str[str.Length - 1] != ':')
            {
                str = str + ':'.ToString();
            }
 
            // Get number sections, range of numbers before ':'
 
            int erl = 0;
 
            while (true)
            {
                string[] secRange = new string[str.Length];
                int seci = 0;
 
                for (int i = 0; i < str.Length; i++)
                {
                    if (str[i] != ':')
                    {
                        secRange[seci] += str[i];
                    }
                    else
                    {
                        seci++;
                    }
                }
 
                char[] dchars = new char[str.Length];
 
                for (int i = 0; i < seci; i++)
                {
                    int sr = 0;
                    try
                    {
                        sr = Convert.ToInt32(secRange[i]);
                    }
                    catch
                    {
                        log("Could not decrypt string");
                        erl++;
                        break;
                    }
 
                    int conv = 0;
                    try
                    {
                        conv = sr / Convert.ToInt32(KeyInt);
                    }
                    catch
                    {
                        log("Could not decrypt string");
                        erl++;
                        break;
                    }
 
                    try
                    {
                        output += charArray[conv];
                    }
                    catch
                    {
                        log("Could not decrypt string");
                        erl++;
                        break;
                    }
 
                    log("'" + sr.ToString() + "' => '" + charArray[conv] + "'");
                }
 
                if(erl==0)
                    log("Decrypted");
 
                break;
            }
 
            return output;
        }
 
        private string encrypt(string str, string key)
        {
            log("Starting Encryption process...");
            KeyInt = generateKey(key);
            string output = "";
 
            while (true)
            {
                if (str.Contains("\r\n"))
                {
                    str = str.Replace(Environment.NewLine,"");
                }
 
                for (int i = 0; i < str.Length; i++)
                {
                    int bl = output.Length;
 
                    output += (charArray.IndexOf(str[i]) * KeyInt).ToString() + ":";
 
                    log("'" + str[i] + "' => '" + (charArray.IndexOf(str[i]) * KeyInt).ToString() + "'");
                }
                break;
            }
            return output.TrimEnd(':');
        }
 
        private void log(string str)
        {
            txtLog.AppendText(str + "\r\n");
        }
 
        private void linkClear_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtLog.Clear();
        }
 
        private void linkSave_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (txtLog.Text.Length > 0)
            {
                SaveFileDialog sfd = new SaveFileDialog();
                sfd.DefaultExt = "txt";
                sfd.Filter = "Text File (*.txt)|*.txt";
                sfd.ShowDialog();
                if (sfd.FileName.Length > 0)
                {
                    System.IO.StreamWriter sw = new System.IO.StreamWriter(sfd.FileName);
                    sw.Write(txtLog.Text);
                    sw.Close();
                }
            }
        }
 
        private void linkPaste_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (Clipboard.ContainsText())
            {
                txtIn.Text = Clipboard.GetText();
                log("Pasted text");
                if (Clipboard.GetText().Contains(Environment.NewLine))
                {
                    log("Note: Line breaks will be removed");
                }
            }
            else
            {
                log("Clipboard data empty or not in text format");
            }
        }
 
        private void linkCopy_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (txtOut.Text.Length > 0)
            {
                Clipboard.SetText(txtOut.Text);
                log("Copied text");
            }
            else
            {
                log("Nothing to copy");
            }
        }
 
        private void linkClearIn_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtIn.Clear();
        }
 
        private void linkClearOut_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtOut.Clear();
        }
 
        private void linkLabel2_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            string a = txtIn.Text;
            string b = txtOut.Text;
 
            txtIn.Text = b;
            txtOut.Text = a;
        }
 
        private void newToolStripMenuItem_Click(object sender, EventArgs e)
        {
            //New
            foreach(Control c in this.Controls)
            {
                if (c is TextBox)
                {
                    ((TextBox)c).Clear();
                }
            }
        }
 
        private void loadLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            txtLog.Text = loadFile();
        }
 
        private void loadOutput_Click(object sender, EventArgs e)
        {
            txtOut.Text = loadFile();
        }
 
        private string loadFile()
        {
            string result_str = String.Empty;
 
            OpenFileDialog x = new OpenFileDialog();
            StreamReader y;
 
            while (true)
            {
                x.ShowDialog();
 
                if (x.FileName.Length == 0)
                    break;
                else
                    y = new StreamReader(x.FileName);
 
                if (File.Exists(x.FileName))
                    result_str = y.ReadToEnd();
                else
                    MessageBox.Show("Error loading file. File doesn't exist!", "Error");
 
                y.Close();
 
                break;
            }
 
            return result_str;
        }
 
        private bool saveFile(string x)
        {
            SaveFileDialog y = new SaveFileDialog();
            y.DefaultExt = "Text file (*.txt)|*.txt|Any file type (*.*)|*.*";
 
            StreamWriter w;
 
            while (true)
            {
                y.ShowDialog();
 
               if (y.FileName.Length != 0)
                {
                    try
                    {
                        w = new StreamWriter(y.FileName);
                        w.Write(x);
                        w.Close();
                    }
                    catch
                    {
                        return false;
                    }
                    return true;
                }
                else
                {
                    return true;
                }
            }
        }
 
        private void saveLogToolStripMenuItem_Click(object sender, EventArgs e)
        {
            bool save = saveFile(txtLog.Text);
 
            if (!save)
                MessageBox.Show("Error saving file", "Error");
            else
                MessageBox.Show("Saved successfully", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
 
        private void saveOut_Click(object sender, EventArgs e)
        {
            bool save = saveFile(txtOut.Text);
 
            if (!save)
                MessageBox.Show("Error saving file", "Error");
            else
                MessageBox.Show("Saved successfully", "", MessageBoxButtons.OK, MessageBoxIcon.Information);
        }
 
        private void exitToolStrip_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
 
        private void openHelpToolStripMenuItem_Click(object sender, EventArgs e)
        {
 
        }
 
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            XmlClass.saveConfig(txtIn.Text, txtOut.Text, txtKey.Text, txtLog.Text);
        }
    }
}

Comments