locked
Text Encryption

    Frage

  • Ok so I having been working on this project for days and have already been helped with part of my issues. Since I am again having a problem and it is a different topic all together I figured it best to do a new thread. 

    My problem is I took about a year off from using Visual express after only learning the basics so I am having a hard time with writing this program. Any help will be greatly appreciated; as youtube and my lost textbook is not helping matters. 

    Project: 

    I have two textboxes; textbox41, I type info into it. Textbox42, is to mirror textbox41. "textBox42.Text == textBox41.Text" 

    Simple enough! 

    The tricky part: 

    Although tb42 mirrors tb41 it needs to be cryptic. How I need it is, let's say I write, "Hello World, how are you today?" rather than encrypting and jumbling the words and letters, I need, take for instance the letter "O", it has to find the letter "O" in one of the 26 labels I have (one letter of the alphabet per label), then it has to use its matching textbox (one textbox per letter of the alpahet, ie. label4 matches up to textbox4), after which, textbox4's letter would be the new letter "O". This needs to be done for all letters of the alphabet. 

    The way in which I have set it up is that after I type into textbox41 I press a button which then creates the encryption into textbox42. 

    I do hope all this makes sense and that those of you who have more experience can assist me with my dilemma. 

    Thank you in advance. 

    John 


    Mittwoch, 17. Oktober 2012 12:03

Antworten

  • hi ya,

    Try this stuff for your form1.cs

    namespace WindowsFormsApplication2
    {
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Windows.Forms;
    
        public partial class Form1 : Form
        {
            Dictionary<char, char> cryptoMap = new Dictionary<char, char>();
    
            public Form1()
            {
                InitializeComponent();
                initMap(cryptoMap);
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                shuffleMap(cryptoMap);
            }
            private void initMap(Dictionary<char, char> cryptoMap)
            {
                cryptoMap.Add(' ', ' ');
                for (int i = 0; i < 26; i++) { cryptoMap.Add((char)('a' + i), (char)('a' + i)); }
    
                shuffleMap(cryptoMap);
            }
    
            private void shuffleMap(Dictionary<char, char> cryptoMap)
            {
                Random rnd = new Random();
    
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    int j = rnd.Next(cryptoMap.Count);
    
                    char tmp = cryptoMap[keys[j]];
                    cryptoMap[keys[j]] = cryptoMap[keys[i]];
                    cryptoMap[keys[i]] = tmp;
                }
    
                syncUIToMap(cryptoMap);
            }
    
            private void syncUIToMap(Dictionary<char, char> cryptoMap)
            {
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    ((TextBox)this.Controls.Find(String.Format("textBox{0}", i), true)[0]).Text = cryptoMap[keys[i]].ToString();
                }
            }
    
            private void syncMapToUI(Dictionary<char, char> cryptoMap)
            {
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    cryptoMap[keys[i]] = ((TextBox)this.Controls.Find(String.Format("textBox{0}", i), true)[0]).Text[0];
                }
            }
    
            private static string encrypt(string clearText, Dictionary<char, char> cryptoMap)
            {
                char[] clearToCrypto = clearText.ToCharArray();
    
                for (int i = 0; i < clearToCrypto.Length; i++)
                {
                    clearToCrypto[i] = cryptoMap[clearToCrypto[i]];
                }
    
                return String.Join(String.Empty, clearToCrypto);
            }
    
            private static string decrypt(string cryptoText, Dictionary<char, char> cryptoMap)
            {
                char[] crypoToClear = cryptoText.ToCharArray();
    
                for (int i = 0; i < crypoToClear.Length; i++)
                {
                    crypoToClear[i] = cryptoMap.FirstOrDefault(x => x.Value == crypoToClear[i]).Key;
                }
    
                return String.Join(String.Empty, crypoToClear);
            }
    
            private void clearBox_TextChanged(object sender, EventArgs e)
            {
                crytoBox.Text = encrypt(clearBox.Text, cryptoMap);
            }
    
        }
    }
    


    jon.stromer.galley

    • Als Antwort markiert J_Hopps Sonntag, 28. Oktober 2012 08:48
    Mittwoch, 24. Oktober 2012 02:04

Alle Antworten

  • From your description I think I would do something like this:

    1 Create a Dictionary<string, string> or <char, char>. The key would be letters of alphabet, the values the replacement letters e.g. ("O", "X") to replace O with X.

    2 Use the dictionary to set text for labels and textboxes (in form load to give initial replacements).

    3 Loop through tb41 Text and use matching dictionary value for tb42 Text.

    4 For the text boxes with replacements, if the user can change them you need to handle the text changed event to update dictionary values.


    Regards David R
    ---------------------------------------------------------------
    The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones.
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    • Als Antwort vorgeschlagen jgalley Freitag, 19. Oktober 2012 01:25
    Mittwoch, 17. Oktober 2012 17:41
  • From your description I think I would do something like this:

    1 Create a Dictionary<string, string> or <char, char>. The key would be letters of alphabet, the values the replacement letters e.g. ("O", "X") to replace O with X.

    2 Use the dictionary to set text for labels and textboxes (in form load to give initial replacements).

    3 Loop through tb41 Text and use matching dictionary value for tb42 Text.

    4 For the text boxes with replacements, if the user can change them you need to handle the text changed event to update dictionary values.


    Regards David R
    ---------------------------------------------------------------
    The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones.
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    As I understand what you are saying, I do not think it will work. The problem is, I am not just simply changing O with X; my labels, with each letter of the alphabet, are set and the texboxes (one tb for each letter of the alphabet), are randomized. so basically what is happening is I push a button and the tb's randomize the alphabet and are aligned with the labels.

    I do hope I am being clear; lack of sleep makes me write backwards. 

    Thank you for the help; anymore input and assistance will be greatly appreciated. 

    John 

    See image below of what it looks like. 

    Red Letters: Labels

    Black Letters: randomized alphabet

    Alpha button: randomizes alphabet

    Crypto Button: matches tb42 to tb41, then is suppose to find the given lettering in the labels and then match them to the randomized letters in the textboxes. 

      
    • Bearbeitet J_Hopps Mittwoch, 17. Oktober 2012 22:09 needed to add some stuff
    Mittwoch, 17. Oktober 2012 21:50
  • Dave has given you the answer.  The trick is applying it to your problem.

    Do you see how your collection of labels and text boxes (specifically the values of) might be represented as a Dictionary<char char>?  Each entry in the dictionary represents a label (key) and textbox (value);

    so, let's start with a:

    Dictionary<char, char> cryptoMap = new Dictionary<char,char>();
    

    Now we can:

      • Initialize the map with all our key / value pair defaults
      • Shuffle the map to create a simple cypher
      • Update our GUI textboxes with the newly shuffled values

    Now every time the text in the "quote" changes we can call an encrypt() method and use it to update the text in our "crypto" window

    private void quote_TextChanged(object sender, EventArgs e)
    {
        crypto.Text = encrypt(quote.Text, cryptoMap);
    }
    

    So, that leaves a bunch of stuff for you to fill in:

            private static void initMap(Dictionary<char, char> cryptoMap)
            {
                // your code here
            }
    
            private static void shuffleMap(Dictionary<char, char> cryptoMap)
            {
                // your code here
            }
    
            private static void syncUIToMap(Dictionary<char, char> cryptoMap)
            {
                // your code here
            }
    
            private static void syncMapToUI(Dictionary<char, char> cryptoMap)
            {
                // your code here
            }
    
            private static string encrypt(string clearText, Dictionary<char, char> cryptoMap)
            {
                // your code here
            }
    
            private static string decrypt(string cryptoText, Dictionary<char, char> cryptoMap)
            {
                // your code here
            }
    

    Dave has given you the high level implementation for encrypt().  Let me know if you would like any more to go on.


    jon.stromer.galley

    Freitag, 19. Oktober 2012 01:54
  • This is definitely a higher level implementation than my experience level. I greatly appreciate all Your's and David's help and patience. 

    I do need some more help: 

    You mentioned updating the dictionary when I change the letters that match up to the labels. I am using Random r = new Random(); and then the code for each letter. Therefore, I need to know where and how to apply the code I have. 

    public partial class FrMain : Form

        {

            Random r = new Random();

    private void button1_Click(object sender, EventArgs e)
            {
                List<char> l = new List<char>();
                for (int i = 65; i < 91; i++)
                    l.Add((char)i);
                int iSelect1 = r.Next(0, 26); textBox1.Text = l[iSelect1].ToString(); l.RemoveAt(iSelect1);
                int iSelect2 = r.Next(0, 25); textBox2.Text = l[iSelect2].ToString(); l.RemoveAt(iSelect2);
                int iSelect3 = r.Next(0, 24); textBox3.Text = l[iSelect3].ToString(); l.RemoveAt(iSelect3);
                int iSelect4 = r.Next(0, 23); textBox4.Text = l[iSelect4].ToString(); l.RemoveAt(iSelect4);

    }

    This has "int iSelect 1-26" I have only done the first 4 to give an idea. 

    Button 1 does the randomize; Button 2 is to update the Crypto textBox. 

    Also, so it is clear, I have the labels and texboxes lined up to each other and need a clear way to do "label1.Text == textBox1.Text". With this example it makes them match and I do not need it to regrading what I am trying to do. I know you have explained how to do it with the dictionary but I need a little more understanding as to how to do it. 

    Another thing, when I did, 

    private void quote_TextChanged(object sender, EventArgs e)
    {
        crypto.Text = encrypt(quote.Text, cryptoMap);
    }

    the "encrypt" was not recognized. How do I get it to be recognized? 

    I realize you are doing a lot to help me get this done, thank you; I also like that you are giving me things step-by-step so I am learning what I am doing, rather than just writing it all out for me. I have learned so much just from our little interaction. 

    Thanks again, 

    John 

    Sonntag, 21. Oktober 2012 03:47
  • These might help you get going again.

            private static void initMap(Dictionary<char, char> cryptoMap)
            {
                cryptoMap.Add(' ', ' ');
                for (int i = 0; i < 26; i++) { cryptoMap.Add((char)('a' + i), (char)('a' + i)); }
    
                shuffleMap(cryptoMap);
            }
    
            private static void shuffleMap(Dictionary<char, char> cryptoMap)
            {
                Random rnd = new Random();
    
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    int j = rnd.Next(cryptoMap.Count);
    
                    char tmp = cryptoMap[keys[j]];
                    cryptoMap[keys[j]] = cryptoMap[keys[i]];
                    cryptoMap[keys[i]] = tmp;
                }
    
                syncUIToMap(cryptoMap);
            }
    
            private static void syncUIToMap(Dictionary<char, char> cryptoMap)
            {
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    ((TextBox)this.Controls.Find(String.Format("textBox{0}", i), true)).Text = cryptoMap[keys[i]];
                }
            }
    
            private static void syncMapToUI(Dictionary<char, char> cryptoMap)
            {
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    cryptoMap[keys[i]] = ((TextBox)this.Controls.Find(String.Format("textBox{0}", i), true)).Text;
                }
            }
    
            private static string encrypt(string clearText, Dictionary<char, char> cryptoMap)
            {
                char[] clearToCrypto = clearText.ToCharArray();
    
                for (int i = 0; i < clearToCrypto.Length; i++)
                {
                    clearToCrypto[i] = cryptoMap[clearToCrypto[i]];
                }
    
                return String.Join(String.Empty, clearToCrypto);
            }
    
            private static string decrypt(string cryptoText, Dictionary<char, char> cryptoMap)
            {
                char[] crypoToClear = cryptoText.ToCharArray();
    
                for (int i = 0; i < crypoToClear.Length; i++)
                {
                    crypoToClear[i] = cryptoMap.FirstOrDefault(x => x.Value == crypoToClear[i]).Key;
                }
    
                return String.Join(String.Empty, crypoToClear);
            }

    I wrote some of this on the web page here so it might not even compile but it should give you a guide on how you might take the next step.  I'm not sure if your solution has a lavel and textbox for " " (blank space) or not as well so you might have to adjust.  My "sync" methods are looking for TextBox controls named textBox0 --> textBox26.  If you have different names then you might create a List<string> of these names to manage the sync loops.


    jon.stromer.galley


    • Bearbeitet jgalley Sonntag, 21. Oktober 2012 12:53
    Sonntag, 21. Oktober 2012 12:52
  • you will want to declare cryptoMap at the form level and init it.  You probably also want button click events to call the appropriate sync

    namespace WindowsFormsApplication1
    {
        using System;
        using System.Collections.Generic;
        using System.Windows.Forms;
    
        public partial class Form1 : Form
        {
            Dictionary<char, char> cryptoMap = new Dictionary<char,char>();
    
            public Form1()
            {
                InitializeComponent();
                initMap(cryptoMap);
            }
    
            private void quote_TextChanged(object sender, EventArgs e)
            {
                crypto.Text = encrypt(quote.Text, cryptoMap);
            }
        }
    }


    jon.stromer.galley


    • Bearbeitet jgalley Sonntag, 21. Oktober 2012 13:06
    Sonntag, 21. Oktober 2012 13:05
  • jgalley,

    So I am working on this and things were going smooth, momentarily; however, "this" is having an issue. 

    ((TextBox)this.Controls.Find(String.Format("textBox{0}", i), true)).Text = cryptoMap[keys[i]];

    cryptoMap[keys[i]] = ((TextBox)this.Controls.Find(String.Format("textBox{0}", i), true)).Text;

    It is saying, Keyword 'this' is not valid in a static property, static method, or static field initializer.

    How can I fix this? I am not understanding what it is saying. 

    Below is the code you provided and "this" placement. 

    Thank you again, and again. 

    John

    private static void syncUIToMap(Dictionary<char, char> cryptoMap)

            {
                // your code here
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    ((TextBox)this.Controls.Find(String.Format("textBox{0}", i), true)).Text = cryptoMap[keys[i]];
                }
            }

            private static void syncMapToUI(Dictionary<char, char> cryptoMap)
            {
                // your code here
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    cryptoMap[keys[i]] = ((TextBox)this.Controls.Find(String.Format("textBox{0}", i), true)).Text;
                }
            }

    Dienstag, 23. Oktober 2012 17:35
  • Hi ya,

    Are you running this code in a console app or a winforms app?


    jon.stromer.galley

    Dienstag, 23. Oktober 2012 20:46
  • The keyword this is used to refer to the current instance of an object. Hence it cannot be used in class (i.e. static) methods since there is no current object. The code Jon provided was example code. If you have it as code in a Windows form then removing static might work; if it is in a Console Program class then delete the this might do it. From the OP it looks like a WinForm so probably just delete static in all the method declarations.

    This is fairly basic stuff and indicates you might need to do a refresh of introductory C#.


    Regards David R
    ---------------------------------------------------------------
    The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones.
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    Dienstag, 23. Oktober 2012 21:54
  • I do realize I need a refresher, it has been a while since I've done any writing. Most of what I do is for hobby so I don't do it often enough; I usually refresh fairly easily but it seems I am trying to accomplish something quite advanced and needing the refresher in general isn't helping. For everyone's patience I have great appreciation. I have gotten a book to help, as in looking up the things that are being given. I have done this so getting help is not just a waist of people's time. I apologize for any irritation caused. To answer your question I am using a windows form application. Thank you, John

    The keyword this is used to refer to the current instance of an object. Hence it cannot be used in class (i.e. static) methods since there is no current object. The code Jon provided was example code. If you have it as code in a Windows form then removing static might work; if it is in a Console Program class then delete the this might do it. From the OP it looks like a WinForm so probably just delete static in all the method declarations.

    This is fairly basic stuff and indicates you might need to do a refresh of introductory C#.


    Regards David R
    ---------------------------------------------------------------
    The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones.
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.


    Mittwoch, 24. Oktober 2012 00:19
  • hi ya,

    Try this stuff for your form1.cs

    namespace WindowsFormsApplication2
    {
        using System;
        using System.Collections.Generic;
        using System.Linq;
        using System.Windows.Forms;
    
        public partial class Form1 : Form
        {
            Dictionary<char, char> cryptoMap = new Dictionary<char, char>();
    
            public Form1()
            {
                InitializeComponent();
                initMap(cryptoMap);
            }
    
            private void button1_Click(object sender, EventArgs e)
            {
                shuffleMap(cryptoMap);
            }
            private void initMap(Dictionary<char, char> cryptoMap)
            {
                cryptoMap.Add(' ', ' ');
                for (int i = 0; i < 26; i++) { cryptoMap.Add((char)('a' + i), (char)('a' + i)); }
    
                shuffleMap(cryptoMap);
            }
    
            private void shuffleMap(Dictionary<char, char> cryptoMap)
            {
                Random rnd = new Random();
    
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    int j = rnd.Next(cryptoMap.Count);
    
                    char tmp = cryptoMap[keys[j]];
                    cryptoMap[keys[j]] = cryptoMap[keys[i]];
                    cryptoMap[keys[i]] = tmp;
                }
    
                syncUIToMap(cryptoMap);
            }
    
            private void syncUIToMap(Dictionary<char, char> cryptoMap)
            {
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    ((TextBox)this.Controls.Find(String.Format("textBox{0}", i), true)[0]).Text = cryptoMap[keys[i]].ToString();
                }
            }
    
            private void syncMapToUI(Dictionary<char, char> cryptoMap)
            {
                var keys = cryptoMap.Keys.ToList();
                for (int i = 0; i < cryptoMap.Count; i++)
                {
                    cryptoMap[keys[i]] = ((TextBox)this.Controls.Find(String.Format("textBox{0}", i), true)[0]).Text[0];
                }
            }
    
            private static string encrypt(string clearText, Dictionary<char, char> cryptoMap)
            {
                char[] clearToCrypto = clearText.ToCharArray();
    
                for (int i = 0; i < clearToCrypto.Length; i++)
                {
                    clearToCrypto[i] = cryptoMap[clearToCrypto[i]];
                }
    
                return String.Join(String.Empty, clearToCrypto);
            }
    
            private static string decrypt(string cryptoText, Dictionary<char, char> cryptoMap)
            {
                char[] crypoToClear = cryptoText.ToCharArray();
    
                for (int i = 0; i < crypoToClear.Length; i++)
                {
                    crypoToClear[i] = cryptoMap.FirstOrDefault(x => x.Value == crypoToClear[i]).Key;
                }
    
                return String.Join(String.Empty, crypoToClear);
            }
    
            private void clearBox_TextChanged(object sender, EventArgs e)
            {
                crytoBox.Text = encrypt(clearBox.Text, cryptoMap);
            }
    
        }
    }
    


    jon.stromer.galley

    • Als Antwort markiert J_Hopps Sonntag, 28. Oktober 2012 08:48
    Mittwoch, 24. Oktober 2012 02:04
  • Jon, I will look at what you've done when I get Internet service and power; snow storm. I am using my phone to see you have emailed me. Thank you for looking at it so soon; I'll let you know how it is when I get a chance to. Thanks, John
    • Bearbeitet J_Hopps Donnerstag, 25. Oktober 2012 16:27
    Mittwoch, 24. Oktober 2012 17:30
  • Jon, 

    I took a look at the file and was able to get it to work. I tweaked a couple things with it and now I have what I need. I emailed you a couple questions to see if I could get it tweaked a little more. My main concern with it right now is that is recognized the encryption for lower case letters, however, if I do a capital letter (as in the beginning of a sentence) it does not encrypt it. I would also like for everything I type to be Upper case lettering. If this is something easily done your assistance would be helpful. For now what have done is added a 3rd button. What this does is makes everything in the quoteBox lower case when clicked; when I do this it then encrypts the letters that were Caps. 

    Thank you very much for all your assistance. 

    John

    Sonntag, 28. Oktober 2012 08:56
  • The map (i.e. dictionary) only has keys for lower case 'a' to 'z' so either convert to lower case in encrypt' or change 'a' to 'A' in map. If you convert to lower case you will only get lower case on decrypt. To have both you need to add the 'A' to 'Z' range to the dictionary.

    Regards David R
    ---------------------------------------------------------------
    The great thing about Object Oriented code is that it can make small, simple problems look like large, complex ones.
    Object-oriented programming offers a sustainable way to write spaghetti code. - Paul Graham.
    Every program eventually becomes rococo, and then rubble. - Alan Perlis
    The only valid measurement of code quality: WTFs/minute.

    Sonntag, 28. Oktober 2012 09:13
  • if you want to force your user to enter upper case characters you could do something lie this thread suggests:

    http://social.msdn.microsoft.com/Forums/en-US/windowsmobiledev/thread/2956b04c-7791-414a-aeda-2d8e0b6bac0c


    jon.stromer.galley

    Montag, 29. Oktober 2012 01:34