Click here to Skip to main content
6,611,284 members and growing! (21,266 online)
Email Password   helpLost your password?
Languages » C# » General     Intermediate License: The Code Project Open License (CPOL)

Encryption Build From Scratch

By Harvey Saayman

A simple yet effective way of encrypting data
C#, Windows, .NET 2.0, ASP.NET, Visual Studio, GDI+, WebForms, Dev
Posted:14 Nov 2007
Views:26,502
Bookmarked:12 times
Announcements
Loading...
 
Search    
Advanced Search
Add to IE Search
printPrint   add Share
      Discuss Discuss   Broken Article?Report  
14 votes for this article.
Popularity: 2.67 Rating: 2.33 out of 5
7 votes, 50.0%
1
3 votes, 21.4%
2
1 vote, 7.1%
3
1 vote, 7.1%
4
2 votes, 14.3%
5
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


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.
Occupation: Software Developer
Company: Uniclox Technologies
Location: South Africa South Africa

Other popular C# articles:

Article Top
You must Sign In to use this message board.
FAQ FAQ 
 
Noise Tolerance  Layout  Per page   
 Msgs 1 to 25 of 30 (Total in Forum: 30) (Refresh)FirstPrevNext
GeneralCrack this if you can [modified] PinmemberHarveySaayman7:27 15 Nov '07  
GeneralRe: Crack this if you can [modified] PinmemberDan Colasanti22:17 15 Nov '07  
GeneralRe: Crack this if you can PinmemberHarveySaayman21:38 16 Nov '07  
GeneralRe: Crack this if you can [modified] PinmemberDan Colasanti6:46 17 Nov '07  
GeneralRe: Crack this if you can PinmemberDan Colasanti9:04 17 Nov '07  
GeneralCrypto PinmemberNoSpamYouFreakingMorons16:09 14 Nov '07  
GeneralRe: Crypto PinmemberHarveySaayman10:29 15 Nov '07  
GeneralHow cryptanalysis would work Pinmembercrypto102412:40 14 Nov '07  
GeneralKeep it up PinmemberBert delaVega12:08 14 Nov '07  
GeneralRe: Keep it up PinmemberHarveySaayman12:12 14 Nov '07  
GeneralTerrible Idea PinmemberNoSpamYouFreakingMorons11:10 14 Nov '07  
GeneralRe: Terrible Idea [modified] PinmemberHarveySaayman11:28 14 Nov '07  
GeneralRe: Terrible Idea PinmemberNoSpamYouFreakingMorons11:55 14 Nov '07  
GeneralRe: Terrible Idea PinmemberHarveySaayman12:09 14 Nov '07  
GeneralRe: Terrible Idea PinmemberGerard Nicol12:11 14 Nov '07  
GeneralRe: Terrible Idea PinmemberHarveySaayman12:22 14 Nov '07  
GeneralRe: Terrible Idea PinmemberGerard Nicol12:40 14 Nov '07  
GeneralRe: Terrible Idea Pinmemberoliverjenks12:46 14 Nov '07  
GeneralRe: Terrible Idea PinmemberHarveySaayman18:09 14 Nov '07  
GeneralRe: Terrible Idea PinmemberGerard Nicol21:36 14 Nov '07  
GeneralRe: Terrible Idea PinmemberHarveySaayman7:36 15 Nov '07  
GeneralRe: Terrible Idea PinmemberDan Colasanti18:17 16 Nov '07  
GeneralRe: Terrible Idea PinmemberPawJershauge12:25 14 Nov '07  
GeneralRe: Terrible Idea Pinmemberdimzon4:07 15 Nov '07  
GeneralRe: Terrible Idea PinmemberGlitchFreak5:27 15 Nov '07  

General General    News News    Question Question    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

PermaLink | Privacy | Terms of Use
Last Updated: 14 Nov 2007
Editor: Genevieve Sovereign
Copyright 2007 by Harvey Saayman
Everything else Copyright © CodeProject, 1999-2009
Web18 | Advertise on the Code Project