Click here to Skip to main content
Licence CPOL
First Posted 14 Nov 2007
Views 52,343
Downloads 179
Bookmarked 15 times

Encryption Build From Scratch

By | 14 Nov 2007 | Article
A simple yet effective way of encrypting data
Screenshot - encryptionBuiltFromScratch.gif

Introduction

As a student, I was going through crypto streams and for some strange reason I couldn't get them to encrypt more than 16 characters at a time. I thought to myself, "How does this work exactly?" I set out to reinvent the wheel, if you will, and this is what I came up with.

Background

My first attempt at rewriting encryption from scratch was actually really simple. What I did was take each character of a string and get its ASCII value. Then I took this number and multiplied it by 2 before converting it back into a character. To decrypt, I did the exact same thing, but instead of multiplying, I divided by 2.

public string encrypt(string myString) 
{
    int currentCharNum = 0; 
    int encryptedCharNum = 0; 
    string encryptedText = ""; 

    foreach (char currentChar in myString) 
    {
        currentCharNum = currentChar; 
        //This implicitly converts the char to its ascii value 
        encryptedStringNum = currentCharNum * 2; 
        //multiplies the value with 2 
        encryptedText += (char)encryptedStringNum; 
        //explicitly converts the NEW ENCRYPTED value to a 
        //char and adds it to the final string 
    } 
    return encryptedText; 
}

Using this method, encrypting the string "Hello Harvey!!!" would return "ÊØØÞ@ÂäÊòBBB". Now this was awesome; I actually did it! However, there were some weaknesses. I noticed that the "!!!" at the end of the original string returned "BBB". This was a problem because if you noticed the patterns, you could crack this if you really wanted to.

Version 2 was another story. This time I implemented a key to be used with the encryption instead of just multiplying everything by 2! Let's say you wanted to encrypt the string "Hello Harvey!!!" with a key of "2 4 6".

The H is multiplied by 2,

The e is multiplied by 4,

The l is multiplied by 6,

The l is multiplied by 2,

The o is multiplied by 4 and so on...

The resulting encrypted string would now be "ưÊưʈÞ€ưÂLjɞò ÆB". Now the "!!!" at the end isn't all the same characters in the encrypted string!

Using the Code

The first major method I had to write was to get these key numbers out of the text box and into an array.

public ArrayList myKey = new ArrayList();

public void getKey(string keyString) 
{
    myKey.Clear();
    keyString.Trim(); 
    //trimming variable so no white space exists at front or back 
    
    myKey.AddRange(keyString.Split(new char[] {' '})); 
    //adding individual numbers to arrayList
    
    int[] key = new int[myKey.Count]; 
    //initializing an int array to put the individual numbers in
    
    int counter = 0; //initializing counter to 0 
    
    foreach (string item in myKey)
    {
        try 
        {
            key[counter] = Int32.Parse(item); 
            counter++;
        }
        catch (FormatException) 
        {
            MessageBox.Show("Characters Not Allowed As Key");
            textBox1.Text = ""; 
        }
        catch (Exception E) 
        {
            MessageBox.Show("Error: \n \n" + E);
        }    }
    counter = 0;
}

The 2nd method did the actual encrypting.

public string encrypt(string fileContents)
{
    lblCharCount.Text = fileContents.Length.ToString();
    
    int currentCharNum = 0;
    int encryptedStringNum = 0;
    int keyIndex = myKey.Count - 1;
    
    progressBar1.Maximum = fileContents.Length;
    progressBar1.Value = 0;
    
    string encryptedText = "";
    
    foreach (char currentChar in fileContents)
    {
        currentCharNum = currentChar;
        encryptedStringNum = 
            currentCharNum * Int32.Parse(myKey[keyIndex].ToString());
        encryptedText += (char)encryptedStringNum;
        
        progressBar1.Value += 1;
        
        if (keyIndex == myKey.Count - 1)
        {
            keyIndex = 0;
        }
        else
        {
            keyIndex++;
        }
    }
    
    try
    {
        FileStream writeEncryped = 
            new FileStream(txbTarget.Text, 
            FileMode.Create, FileAccess.Write);
        StreamWriter writeEncryptedWriter = new StreamWriter(writeEncryped);
        
        writeEncryptedWriter.Write(encryptedText);
        
        writeEncryped.Flush();
        writeEncryptedWriter.Close();
        writeEncryped.Close();
    }
    catch (FileNotFoundException)
    {
        MessageBox.Show("File Not Found");
    }
    catch (Exception E)
    {
        MessageBox.Show("Error: \n\n" + E);
    }
    return encryptedText;
}   

You might have noticed that the block has a file stream in it. I actually implemented my encryption model to encrypt entire text files.

Known Issues

This application is still a work in progress, so there are some issues I'll list here. The main setback is that I have no check to ensure that the encrypted character stays in the bounds of the ASCII table. So, if the final answer/encrypted character value is above 65535, it moans. The second issue is that when you're encrypting huge text files -- of 500000 characters, for example -- it takes some time to display the encrypted text in the text box. I'm not sure why it does this, but I think it's because of the high ASCII values.

Notes

I used sharpDevelop 2.2 to write this program, but it should work in 2.0 as well.

History

  • 14 November, 2007 -- Original version posted

License

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

About the Author

Harvey Saayman

Software Developer
Osiris Trading
South Africa South Africa

Member

Harvey is in the process of completing his BSc in Information Systems Engineering. He finished the 1st two years in less than a year, he is currently doing the last year part time over two years while working full time as a C# developer. The modules he is currently studying covers business & project management.
 
He is getting his degree from Cambridge university UK, all though hes studying at CTi South Africa.
 
He has been a programmer in professional capacity since Jan 2008, but has been exposed to programming from childhood.
 
He currently works for Uniclox Technologies (Pty) Ltd as the lead project developer. Hes a junior on paper, but more senior developers who has seen his work confirmed that his skill level is way beyond that of a junior.
 
Other interests include music, he has been playing guitar for about four years now. He wishes he can afford a proper 7 string ibanez.
 
Harvey's pet of choice isn't of your common 4 legged variety, he prefers reptiles and currently owns a South African brown house snake and an Australian breaded dragon.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralCrack this if you can [modified] PinmemberHarveySaayman6:27 15 Nov '07  
GeneralRe: Crack this if you can [modified] PinmemberDan Colasanti21:17 15 Nov '07  
GeneralRe: Crack this if you can PinmemberHarveySaayman20:38 16 Nov '07  
GeneralRe: Crack this if you can [modified] PinmemberDan Colasanti5:46 17 Nov '07  
GeneralRe: Crack this if you can PinmemberDan Colasanti8:04 17 Nov '07  
Regarding your question based on the idea of intercepting a message that was secretly encrypted with this method and how to decipher it...
 
Your encryption method has these apparent weaknesses:
 
(1) If I have your source code (or even just the executable - because I could easily disassemble it) that encrypts the data, I can reverse engineer the method that gives me the key that was used to encrypt any ciphertext created with it. This is what I have already shown. This is a major weakness of your algorithm, because if you can't distribute the software without compromising the ciphertext, nobody can use it but you.
 
(2) If I have your encryption executable but don't want to disassemble it, I can still create my own key to determine how the software works and determine the algorithm that way - or use this info to guess your key. Consider this 80-character string of plaintext and use your key (or any key) and your encryption executable to create the ciphertext:
 
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
 
The 21-character substring repetition in the ciphertext tells me that each character is being substituted for each character in the key. Then encrypt this 21-character string:
"BBBBBBBBBBBBBBBBBBBBB"
 
Then compare the first 21 characters (as numeric values) from each string - this shows the
relationship of each key byte to the ciphertext. In your algorithm's case, the relationship
becomes obvious when the key bytes used to try this are simple & sequential: "01 02 03 ...".
I think this is what some others were trying to tell you in their replies.
 
(3) If you are sending a secret message using this method to an intended recipient, he/she would have to know your secret key and have the software to decrypt it. How would they get the secret key and software without those things being intercepted in the first place? This risk is unavoidable and if an interceptor gets them, your messages are not private anymore (using the methods explained above). Because of this, using a single key for encryption and decryption isn't the best choice for encrypting transmitted messages.
 
Good luck...
Dan
 

GeneralCrypto PinmemberNoSpamYouFreakingMorons15:09 14 Nov '07  
GeneralRe: Crypto PinmemberHarveySaayman9:29 15 Nov '07  
QuestionHow cryptanalysis would work Pinmembercrypto102411:40 14 Nov '07  
GeneralKeep it up PinmemberBert delaVega11:08 14 Nov '07  
GeneralRe: Keep it up PinmemberHarveySaayman11:12 14 Nov '07  
GeneralTerrible Idea PinmemberNoSpamYouFreakingMorons10:10 14 Nov '07  
GeneralRe: Terrible Idea [modified] PinmemberHarveySaayman10:28 14 Nov '07  
GeneralRe: Terrible Idea PinmemberNoSpamYouFreakingMorons10:55 14 Nov '07  
GeneralRe: Terrible Idea PinmemberHarveySaayman11:09 14 Nov '07  
GeneralRe: Terrible Idea PinmemberGerard Nicol11:11 14 Nov '07  
GeneralRe: Terrible Idea PinmemberHarveySaayman11:22 14 Nov '07  
GeneralRe: Terrible Idea PinmemberGerard Nicol11:40 14 Nov '07  
GeneralRe: Terrible Idea Pinmemberoliverjenks11:46 14 Nov '07  
GeneralRe: Terrible Idea PinmemberHarveySaayman17:09 14 Nov '07  
GeneralRe: Terrible Idea PinmemberGerard Nicol20:36 14 Nov '07  
GeneralRe: Terrible Idea PinmemberHarveySaayman6:36 15 Nov '07  
GeneralRe: Terrible Idea PinmemberDan Colasanti17:17 16 Nov '07  
GeneralRe: Terrible Idea PinmemberPawJershauge11:25 14 Nov '07  
GeneralRe: Terrible Idea Pinmemberdimzon3:07 15 Nov '07  
GeneralRe: Terrible Idea PinmemberGlitchFreak4:27 15 Nov '07  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120529.1 | Last Updated 14 Nov 2007
Article Copyright 2007 by Harvey Saayman
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid