Simple message encryption

This is a discussion on Simple message encryption within the C++ Programming forums, part of the General Programming Boards category; I thought this would be a good read for any people new to C++. I have made a simple xor ...

  1. #1
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200

    Simple message encryption

    I thought this would be a good read for any people new to C++. I have made a simple xor encryption program to encrypt simple oneline messages.

    I kept it as simple as possible so people new to C++ might could learn something from it. Then again as my programming skills arent exectly "good" I might learn something myself after a few of you see it .

    You simply give a file name a secret key and the message.

    Code:
    /******************************************************/
    /* This program will encrypt and decrypt messages. The*/
    /* user will simply have to remeber a secret key.     */
    /******************************************************/
    #include <iostream>
    #include <fstream>
    #include <string>
    using namespace std;
    
    // Function Prototypes ---------------------------------
    int GetUserChoice ();
    
    void Encryption ();
    void Decryption ();
    
    string XorString ( string source, int key );
    // -----------------------------------------------------
    
    // Main Function ---------------------------------------
    int main ()
    {
    	
    	// Variable to hold our choice
    	int choice;
    	
    	// Create an infinite loop -------------------------
    	while ( 1 ) {
    		
    		// GetUserChoice will return what the user wants to do
    		// We can assign the returned value to our variable
    		choice = GetUserChoice ();
    		
    		// Now we can check what the user wants
    		if ( choice == 1 ) Encryption ();
    		else if ( choice == 2 ) Decryption ();
    		
    		// If the choice was 3 that means we can break from our loop
    		else if ( choice == 3 ) break;
    		
    	}
    	// -------------------------------------------------
    		
    	return 0;
    	
    }
    
    // GetUserChoice Function ------------------------------
    int GetUserChoice ()
    {
    	
    	// Variable for the choice
    	int choice;
    	
    	// Here we will print our menu and prompt for a number
    	// This number will represent what the user wants to do
    	// Once we have the number this function will return it
    	cout << "Message Encryption" << endl;
    	cout << "----------------------" << endl;
    	cout << "1) Encrypt Message" << endl;
    	cout << "2) Decrypt Message" << endl;
    	cout << "3) Exit" << endl << endl;
    	cout << "Make a selection: ";
    	cin  >> choice;
    	
    	// Now we will check to make sure the choice was valid
    	if ( choice != 1 && choice != 2 && choice != 3 ) {
    		
    		cout << endl;
    		cout << "Please enter 1, 2, or 3" << endl;
    		cout << "Press enter to exit...";
    		
    		// Since the user entered an invalid selection we
    		// will just exit the program by returning our programs
    		// exit code.. 3
    		
    		cin.get ();
    		return 3;
    		
    	}
    	
    	// If it makes it to this point that means the input was valid so we can return it
    	return choice;
    	
    }
    // -----------------------------------------------------
    
    // Here is where we will encrypt the string ------------
    string XorString ( string source, int key )
    {
    	
    	// Here we loop through each character, using binary xor on it.
    	for ( unsigned int loop = 0; loop < source.size (); loop ++ ) {
    		
    		source [loop] ^= key;
    		
    	}
    	
    	return source;
    	
    }
    
    // Here we will get the file name, key, and message from the user ----
    void Encryption ()
    {
    	
    	// Variables for the file name, key and message ----
    	char file_name [255];
    	
    	string message;
    	string encrypted_message;
    	
    	int key;
    	// -------------------------------------------------
    	
    	cout << endl;
    	cout << "Enter file name: ";
    	cin  >> file_name;
    	
    	cout << "Enter secret key: ";
    	cin  >> key;
    	
    	cout << "Enter your secret message." << endl;
    	cout << "Message: ";
    	
    	// We need this to ignore anything that might be left over
    	// and ruin our message
    	cin.ignore ( 255, '\n' );
    	
    	getline ( cin, message );
    	
    	// Now we have all of the info we can encrypt and write --
    	// the string to the file --------------------------------
    	encrypted_message = XorString ( message, key );
    	
    	ofstream file ( file_name );
    	
    	file << encrypted_message;
    	
    	file.close ();
    	// -------------------------------------------------------
    	
    	cout << "Done..." << endl << endl;
    	
    }
    // -------------------------------------------------------------------
    
    // Decryption will work the same way. Instead of asking the user for the message, --- 
    // we print it out. -----------------------------------------------------------------
    void Decryption ()
    {
    	
    	// Variables for the file name, key and message ----
    	char file_name [255];
    	
    	string message;
    	
    	int key;
    	// -------------------------------------------------
    	
    	cout << endl;
    	cout << "Enter file name: ";
    	cin  >> file_name;
    	
    	cout << "Enter secret key: ";
    	cin  >> key;
    	
    	// Now we will check to see if the file exists -----
    	ifstream file ( file_name );
    	
    	if ( !file.is_open () ) {
    		
    		cout << "Failed to load " << file_name << "!" << endl;
    		cout << "Press enter to exit...";
    		
    		cin.get ();
    		
    		exit ( EXIT_FAILURE );
    		
    	}
    	// -----------------------------------------------
    	
    	getline ( file, message );
    	
    	file.close ();
    	
    	cout << "Message: " << XorString ( message, key ) << endl;
    	
    	cout << "Done..." << endl << endl;
    	
    }
    I am sure more experienced programmers will find several problems with my code . But if you see any really big nono's be sure to point them out! This was a quick little boredom project I did to kill a good 30 mins. ENJOY!

    EDIT:
    Sorry for the indention errors. Seems the boards code tags doesnt like MinGW Studios formatted code

    And I know its not extremely useful but hey you moght want to store a phone number or something
    Last edited by Vicious; 10-04-2004 at 12:34 AM.
    What is C++?

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >But if you see any really big nono's be sure to point them out!
    Check the return value of all stream input. You risk undefined behavior otherwise.

    >Seems the boards code tags doesnt like MinGW Studios formatted code
    Tabs are evil, replace them with the requisite number of spaces.
    My best code is written with the delete key.

  3. #3
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    >Check the return value of all stream input. You risk undefined behavior otherwise.

    Yes I just realized as I was testing it.

    I need to go back and fix some of this!
    What is C++?

  4. #4
    Registered User Elhaz's Avatar
    Join Date
    Sep 2004
    Posts
    32
    Hi Vicious,

    This is perfect timing. I just finished a chapter on binary operators. Thanks for posting this. I still haven't got to file input/output yet but I think I can follow what you've written.

    Much obliged.

  5. #5
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787
    there's already something on XOR encryption on cprogramming.com ... I don't know if they're still accepting resources or not, but they should be... that would be cool to get the main cprog site back to a good place to learn stuff...
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  6. #6
    i dont know Vicious's Avatar
    Join Date
    May 2002
    Posts
    1,200
    Thats what gets my goat.. im not any good at thinking up of amazing new ways to do things. I can only do things that have already been done and then I dont do them that well!

    Anywho.. I think that the stuff that is on cprog is amazing. If they would keep adding to it it would be the best place around.
    What is C++?

  7. #7
    the hat of redundancy hat nvoigt's Avatar
    Join Date
    Aug 2001
    Location
    Hannover, Germany
    Posts
    3,139
    We had a cprog challenge once, but I couldn't find the link...

    PHP Code:
    // 
    // **********************************************************************
    // *                           Code Challenge                           *
    // **********************************************************************
    //
    // Challenge:
    //
    //    Write an exclusive-OR encryption program.
    //    The program should take as input a filename that
    //    is then encrypted by the program.  The program
    //    should ask the user to input an encryption key,
    //    which should be used to encrypt the file.
    //    The output of the program should go into a file
    //    with the same filename but a .ENC extension
    //    (for simplicity sake).
    //    All programs should run under DOS. 
    //
    // Comments and voluntary changes:
    // 
    //    Added a second argument for output filename,
    //    as you cannot encrypt/decrypt a file that already
    //    is encrypted and has the .enc extension following
    //    the given guidelines. This change to the specifications
    //    is optional, so it works as per the specifications as
    //    well.
    //    The program encrypts the file, not the filename like 
    //    stated above, I think it's obvious that this passage 
    //    should not be taken by the word.
    //    This application uses ANSI commands and standard headers,
    //    it should be able to run as a .c file as well. However,
    //    I was too lazy to test it on anything but VC as a windows
    //    console application.
    //    My other programs would probably be commented differently,
    //    but as all of us are working at the same problem, much of
    //    it will be quite clear from own experience.
    //
    //    Edit: Tested ok as pure C.
    // 
    // Time:
    //
    //    I received the mail Tuesday, 08.01.2002 15:27.
    //  Started coding at roughly 18:00
    //  Finished coding at about 18:45, starting to write comment.
    //  Sent the reply mail: 19:30
    //
    // Facts:
    //
    //    Author:        Niels Voigt
    //    EMail:        [email]nvoigt@saz.net[/email] 
    //    Username:    nvoigt from cprogramming
    //    Compiler:    VC 6 SP 5
    //    Project:    Console Application, should be 100% DOS compatible
    //    Libraries:    ANSI C
    //
    // Testing:
    //  
    //  Encrypting a file twice and checking with the FC utility 
    //    gives a 100% match. So if there are still mistakes, at 
    //    least they are consistent ;-)
    //

    // standard includes for io and strings
    #include <stdio.h>
    #include <string.h>

    // constants
    #define MAX_PATH        1000
    #define MAX_ENCRYPT_KEY        100
    #define XOR_FILE_EXT        ".enc"
    #define ERROR_NOERROR        0
    #define ERROR_READERROR        1
    #define ERROR_WRITEERROR    2

    // prototypes, description see below
    int CreateFileName( const charszOldFilecharszNewFile );
    int RemoveUnwantedCharacterscharszBuffer );

    //
    // main
    //
    //    the encryption program itself
    //
    int mainint argccharargv[] ) 
    {
        
    // variable declaration
        
    FILE*    fpInput;
        
    FILE*    fpOutput;
        
    char    szFileName[MAX_PATH+1];
        
    char    szEncryptionKey[MAX_ENCRYPT_KEY+1];
        
    int        nEncryptKeyLength;
        
    int        nByte;
        
    int     nCount;
        
    int     nError;

        
    // check for arguments
        
    if( argc == )
        {
            
    // create filename if only source was given
            
    CreateFileNameargv[1], szFileName );
        }
        else if( 
    argc == )
        {
            
    // copy given destination 
            
    strcpyszFileNameargv[2] );
        }
        else
        {
            
    // print help if number of arguments are illegal
            
    printf"\nWrong number of arguments\n" );
            
    printf"USAGE: %s Source [Destination]\n\n"argv[0] );
            return 
    1;
        }

        
    // ask for encryption key
        
    do
        {
            
    printf"Please enter encryption key ( 1 - %d characters ):",MAX_ENCRYPT_KEY );
            
    memsetszEncryptionKeyMAX_ENCRYPT_KEY+1);
            
    fgetsszEncryptionKeyMAX_ENCRYPT_KEYstdin );
            
    RemoveUnwantedCharactersszEncryptionKey );
            
    nEncryptKeyLength strlenszEncryptionKey );
        }    
        while( 
    nEncryptKeyLength == );

        
    // print status and data
        
    printf"\n" );
        
    printf"Encrypting [%s]\n",argv[1] );
        
    printf"        to [%s]\n",szFileName );
        
    printf"     using [%s]\n",szEncryptionKey );
        
    printf"\n" );
        
        
    // open input file
        
    fpInput fopenargv[1], "rb" );
        if( 
    fpInput == NULL )
        {
            
    printf"Error: Unable to open %s for reading.\n\n"argv[1] );
            return 
    2;
        }

        
    // open output
        
    fpOutput fopenszFileName"wb" );
        if( 
    fpOutput == NULL )
        {
            
    printf"Error: Unable to open %s for writing.\n\n"szFileName );
            return 
    3;
        }

        
    nCount 0;
        
    nError ERROR_NOERROR;

        
    // encryption loop:
        // read a byte, encrypt, write, next until no more bytes
        // each byte is encrypted with one letter from the key,
        // when the end of the key is reached, the next byte is
        // encrypted with the first one again.
        
    while( ( nByte fgetcfpInput ) ) != EOF )
        {
            if( 
    fputcnByte szEncryptionKey[nCount], fpOutput ) == EOF )
            {
                
    nError ERROR_WRITEERROR;
                break;
            }

            
    nCount++;

            if( 
    nCount >= nEncryptKeyLength nCount 0;
        }

        
    // check if the loop terminated with an end-of-file.
        // after all, somebody may have pulled the
        // plug or the network cable, which will also result 
        // in an EOF condition for fgetc.
        
    if( ! feoffpInput ) ) nError ERROR_READERROR;

        
    // print end message
        
    switch( nError )
        {
            case 
    ERROR_NOERROR:
                
    printf"Encryption complete.\n\n" );
                break;
            case 
    ERROR_READERROR:
                
    printf"Error: unable to perform READ operation on file [%s]\n\n"argv[1] );
                break;
            case 
    ERROR_WRITEERROR:
                
    printf"Error: unable to perform WRITE operation on file [%s]\n\n"szFileName );
                break;
            default:
                
    printf"Error: Unknown Error, please contact your support.\n\n" );
                break;
        }

        
    // close files
        
    fclosefpInput );
        
    fclosefpOutput );

        
    // done ;-)
        
    return 0
    }

    //
    // CreateFileName
    //
    //    creates the destination filename from the source
    //    by replacing the file extension or adding it if
    //    no other extension is found.
    //
    int CreateFileName( const charszOldFilecharszNewFile )
    {
        
    charszReplace;

        
    strcpyszNewFileszOldFile );

        
    szReplace szNewFile strlenszNewFile );

        while( 
    szReplace szNewFile && *szReplace != '\\' && *szReplace != '/' )
        {
            if( *
    szReplace == '.' )
            {
                
    strcpyszReplaceXOR_FILE_EXT );
                return 
    0;
            }

            
    szReplace--;
        }

        
    strcatszNewFileXOR_FILE_EXT );

        return 
    1;
    }

    //
    // RemoveUnwantedCharacters
    //
    //    removes the 0D characters that are left in the buffer 
    //    when reading... I wish there was ONE out-of-the-box
    //    simple-to-use input function.
    //
    int RemoveUnwantedCharacterscharszBuffer )
    {
        while( *
    szBuffer != )
        {
            if( *
    szBuffer == 0x0a || *szBuffer == 0x0d ) *szBuffer 0;
            
    szBuffer++;
        }

        return 
    0;
    }

    //
    // END OF FILE
    // 
    hth
    -nv

    She was so Blonde, she spent 20 minutes looking at the orange juice can because it said "Concentrate."

    When in doubt, read the FAQ.
    Then ask a smart question.

  8. #8
    Registered User
    Join Date
    Oct 2004
    Posts
    13
    very cool program. i am new to c++ and i will be sure to look at this and learn from it.

  9. #9
    Registered User
    Join Date
    Jul 2004
    Posts
    98
    @ Vicious :

    May I ask you a little question?
    When I input "1.1" not "1" in your selection menu,
    ".1" be received by next cin,
    this is my problem:
    How to clear (or flush) no used input value (or number ,string..)?

  10. #10
    Registered User Elhaz's Avatar
    Join Date
    Sep 2004
    Posts
    32
    Hi toysoldier,

    I found this link quite useful. It really helped clear up a lot of my input woes.

    http://www.augustcouncil.com/~tgibso...al/iotips.html

    Hope it helps you.

  11. #11
    Registered User
    Join Date
    Jul 2004
    Posts
    98
    @ Elhaz :
    Thanks for your weblink, now I understand how to use cin.clear() and cin.ignore(),
    add this web to my bookmark.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Strange string behavior
    By jcafaro10 in forum C Programming
    Replies: 2
    Last Post: 04-07-2009, 07:38 PM
  2. Encryption program
    By zeiffelz in forum C Programming
    Replies: 1
    Last Post: 06-15-2005, 03:39 AM
  3. Architecture Question
    By Orborde in forum C++ Programming
    Replies: 1
    Last Post: 06-01-2005, 08:05 AM
  4. Dialog Box Problems
    By Morgul in forum Windows Programming
    Replies: 21
    Last Post: 05-31-2005, 05:48 PM
  5. RSA Encryption
    By minesweeper in forum Tech Board
    Replies: 6
    Last Post: 08-30-2003, 01:48 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21