Dear All,
I have been stuck and confused while bringing changes in this program which i got from http://www.dreamincode.net/code/snippet76.htm

This program uses a simple 0xFACA character and adds and subtracts for doing encryption and decryption.

Now what i want to use is asymmetric encryption technique or we can say part of it.

let say we have a a plain text x= 88
for encryption we will use cipher text crypt =(x*37)%200, so the crypt will be = 56
now we want to decrypt it so decrypt = ( crypt*173) % 200, which will give 88, which is the plain text again,

37 and 173 are modular inverse base 200.

when apply the above formula in the above mentioned program it does work, please help me solve this issue.

Best Regards!

Recommended Answers

All 36 Replies

Can you show us the program with the changes you've made?

Member Avatar for leegeorg07

i dont know about a C++ method but perhaps you could use python's MD5 module, which handles most encryption methods besides MD5

adds and subtracts for doing encryption and decryption

If your program justs shifted character x units to the right for encryption then you need the same translation to the left for decryption

You cant use 2 different keys for simple shifting encrypt/decrypt

Unless for the decrypt, you have a formula that converts a
different key to the same key as the encrypt key.

Can you show us the program with the changes you've made?

#include <iostream.h>
#include <stdlib.h>
#include <fstream.h>
#include <stdio.h>


bool password();

void doCrypt(char *cool)
{
     int cryp;//the main int this function uses
    char x;//to get the chars from the file
    ifstream in;//the input stream
    ofstream out;//the output stream
    in.open(cool);//opening the input file
    if(in.fail()){//check if it's not there
         cout<<"Couldn't open the IN file\n";//if it's not, print
        return;
    }
    cout<<"enter the OUT file name: ";//enter the output filename
    cin>>cool;//get it
    out.open(cool);//open the output file
    in.get(x);//get the first char of input
    if(in.eof())//if read beyong end of file
         return;//quit
    while(x != EOF){//while x is not beyong End Of File
         cryp=x-0xFACA;//the crypting
        out<<(char)cryp;//print the crypted char
        in.get(x);//get another char
        if(in.eof())//if read beyong end of file
             break;
    }
    in.close();
    out.close();
    return;
}
void deCrypt(char *daf)
{
     int decr;//the main int
    char x;//the input char
    ifstream in;//input stream
    ofstream out;//output stream
    in.open(daf);//open the inout stream
    if(in.fail()){//see if it's not there
         cout<<"Error couldn't open the IN file\n";//print
        return;
    }
    cout<<"Enter the OUT file name: ";//ask for the out filename
    cin>>daf;
    out.open(daf);//open the outfile
    in.get(x);//get the input char
    if(in.eof())//if read beyong end of file
         return;
    while(x!=EOF){//while x is not beyong end of file
  decr=x+0xFACA;//the dectypring
        out<<(char)decr;
        in.get(x);//get the next char
        if(in.eof())//if read beyong the eon of file
             break;
    }
    return;
}
int main(void)
{
    if (password()) cout << "Access Granted: \n";
    else
    {
    cout << "You are not Authorized to use this program!\n";
    system("pause");
    return 0;
    }
    char *cool=new char[20];//the name pointer
    char nav;              //"navigation char"
    cout << "*---------------------------------------------*\n";
    cout << "| This is an encryption program.  I'm not     |\n";
    cout << "| taking credit for this.  This was a         |\n";
    cout << "| recent submission on planet-source-code     |\n";
    cout << "| I just added password protection to it.     |\n";
    cout << "*---------------------------------------------*\n\n";
    system("pause");
    cout << "\n\n";
    cout << "Use \"m\" for the Menu\n";//print instructions
     while(true){
         cin >> nav;
         switch(nav){
             case 'm':
                 cout << "COMMAND\tFUNCTION\n";
                cout << "e      \tencrypt\n"
                          "d      \tdecrypt\n"
                        "m      \t menu \n"
                        "q      \t quit \n";
                break;
             case 'e':
                 cout << "Enter the file name: \nExample: \"file\".txt\n";
                cin >> cool;
                doCrypt(cool);
                break;
            case 'd':
                 cout << "Enter the file name: ";
                cin >> cool;
                deCrypt(cool);
                break;
            case 'q':
                 exit(0);
                 break;
            default:
                 cout << "I do not understand you!\n";
                break;
        }
    }
}

bool password()
{
     char string1[50];
     cout << "Enter in the encryption password: \n";
     gets(string1);

     if (strcmp(string1, "outlaw")) return 0;
     return 1;
}

I changed the red to cryp=(x * 37)% 200; //the crypting


and the green to decr=(x * 173)% 200;//the dectypring


It encrypts fine but in decryption i think it gets confused.

I tested the program you posted, encrypting and decrypting is working fine, only one major remark I have is that the program hangs at the end of the encryption/decryption progress.

This:

in.get(x);//get the first char of input
if(in.eof())//if read beyong end of file
     return;//quit
while(x != EOF) {//while x is not beyong End Of File
    cryp=x-0xFACA;//the crypting
    out<<(char)cryp;//print the crypted char
    in.get(x);//get another char
    if(in.eof())//if read beyong end of file
         break;
}

should rather be changed to something like this (also change the other parts in your code which look like the above code):

if(!in.is_open())
   return;
while(in.get(x)) {//while x is not beyong End Of File
    cryp=x-0xFACA;//the crypting
    out<<(char)cryp;//print the crypted char
}

BTW, when I write encryption/decryption functions, I would let them return some value (for example bool, or the number of bytes encrypted/decrypted) in order to check whether the encrypting/decrypting went fine.
Also the use of old-style header files, and the mixing of two I/O libraries is annoying me:
Change this:

#include <iostream.h>
#include <stdlib.h>
#include <fstream.h>
#include <stdio.h>

to this:

#include <iostream>
#include <fstream>

(and update your code to not use the C style I/O), also read this which is about (standard) alternatives to system("pause"); .

Where are you freeing this memory? char *cool=new char[20]; This code fragment will allow an array overrun, when more than 19 characters are entered:

case 'e':
   cout << "Enter the file name: \nExample: \"file\".txt\n";
   cin >> cool;
   doCrypt(cool);
   break;

, so rather change cin >> cool; to: cin.getline(cool, 20); .

In your password function I see these lines:

cout << "Enter in the encryption password: \n";
gets(string1);

However the fist is correct, but the second is a bad coding practice, it allows (again) the array to be overrun, array overruns are bad, because your program just starts writing in some memory past the end of the array, which can cause (in the best case) your program to crash, or in a more worse case: the entire operating system to crash (though most operating systems today offer memory protection, you shouldn't rely on this when writing your program).
Quick fix: change gets(string1); to: cin.getline(string1, 50) .

Edit::

I changed the red to cryp=(x * 37)% 200; //the crypting
and the green to decr=(x * 173)% 200;//the dectypring
It encrypts fine but in decryption i think it gets confused.

Oops! I just checked the code you posted, because I asked you to post the changed code, but the encryption/decryption routines were not changed in the code, I'll change these and test the whole thing again.

Your encryption algorithm should work fine, I tested it using the following code:

#include <iostream>
#include <climits>

int main()
{
    int encrypt;
    int decrypt;
    
    for(int i=0; i<CHAR_MAX; ++i) {
        encrypt = (i * 37) % 200;
        decrypt = (encrypt * 173) % 200;
        
        if(decrypt != i)
            std::cout << "ASCII: " << i << ": NOT OK" << std::endl;
        else
            std::cout << "ASCII: " << i << ": OK" << std::endl;
    }
    
    return 0;
}

Your encryption algorithm should work fine, I tested it using the following code:

#include <iostream>
#include <climits>

int main()
{
    int encrypt;
    int decrypt;
    
    for(int i=0; i<CHAR_MAX; ++i) {
        encrypt = (i * 37) % 200;
        decrypt = (encrypt * 173) % 200;
        
        if(decrypt != i)
            std::cout << "ASCII: " << i << ": NOT OK" << std::endl;
        else
            std::cout << "ASCII: " << i << ": OK" << std::endl;
    }
    
    return 0;
}

Dear Sir,
I havent used C code for last 5 years, one of my friend helps me in solving the problem,

If possible kindly change my all program ( the deficiencies ) and put the new code that you made and tested in the old program so that i can see how it works, to embed the new code in old program is difficult then writing a new one,

Please put all the new code in the old program and a new program which will do enc dec with the different keys will be made,

Then i will be able to tet and verify.

I think most of the problem is solved.

But untill i see all the code in a program at its own place i cant say anything

Thanks in advance!

Dear Sir,
I want to get plain text from a file
then
encrypt it and save it in a file

and then
decrypt it and save in the file
and compare the decrypted text with the orignal plain text

so that i can check wether the program is working fine or not

please help me out of this big problem

Dear Sir,
I want to get plain text from a file
then
encrypt it and save it in a file

and then
decrypt it and save in the file
and compare the decrypted text with the orignal plain text

so that i can check wether the program is working fine or not

please help me out of this big problem

First of all I want you to NOT PM me with your questions to do it for you, it won't work, I'm a free person and I'm free to do what I want, and not to do what I don't want (let that be clear).
What I want is to help you, what I don't want is spend my time to create a full-fledged encryption solution for you (or in other words: I rather provide paths to the solution, not the entire solution itself), so that you can turn it in, and pass (or fail :P) using my work, that wouldn't be fair, not? The point of the assignments you get is to show off your knowledge, show what you can. This means that you have to do the work, passing using someone else's work won't get you far in real life. The point is that you do the entire thing yourself (with some small help and hints from the forum members (the so-called "gurus") here), and that you finally (when you finished the program) can say: I did it!

[edit]
So my immediate advice would be: go on and start to clean up and fix your current code using the tips I provided in my previous post.
If you're really lost, you will maybe want to consider to rewrite the whole program, but that should be the last option on your list (you can fix it, if you want it).
When you've fixed your code, post down your new code and come up with specific questions in case you got stuck at some point.
[/edit]

commented: Well said! +14

Dear Sir,
You are very right and i admit with the core of my heart what u said.


I am a Network/System Administrator and is far far away from the programming languages as my field of profession is different.


I tried to run your small program and it run successfuly

but the problem is that u r using oops object oriented programming and i told u sir that i m new to c basically a biginer.

So thats why i said that
I am thankful for your consideration thats why i m really obliged.


Thanks!

but the problem is that u r using oops object oriented programming and i told u sir that i m new to c basically a biginer.

As far as I know I only used cout, which you also did (you even mixed C with C++ I/O (which is also OOP), so I don't see where the problem is :)

Do you want to rewrite the whole program in C or what (as your thread seems to be in the C++ forum) ?

And I don't care you're a beginner, as long as you're willing to put effort in it I'm happy :)

[edit]
Just out of curiosity, you're a Network/System Administrator, but why is there need to write your own encryption program then?
Can't you just use something which you can safely rely on?
Maybe something like TrueCrypt ?
[/edit]

very right sir finally i will be running this program in linux
by now i m running this program in dev c++

very right sir finally i will be running this program in linux

Is that the only reason you want to undertake all the work to write an encryption program?
Even if TrueCrypt is available for Linux as well ?

yes sir u r very right there are may option as well
but i m working on ns2 for simulation wireless sensor network
i want to put this in n ode and base station algo
i want to use asymetric key end dec which is lesser used in researh work in wsn

by now i am using this program

#include <iostream.h>
#include <stdlib.h>
#include <fstream.h>
#include <stdio.h>


bool password();

void doCrypt(char *cool)
{
     int cryp;//the main int this function uses
    char x;//to get the chars from the file
    ifstream in;//the input stream
    ofstream out;//the output stream
    in.open(cool);//opening the input file
    if(in.fail()){//check if it's not there
         cout<<"Couldn't open the IN file\n";//if it's not, print
        return;
    }
    cout<<"enter the OUT file name: ";//enter the output filename
    cin>>cool;//get it
    out.open(cool);//open the output file
    in.get(x);//get the first char of input
    if(in.eof())//if read beyong end of file
         return;//quit
    while(x != EOF){//while x is not beyong End Of File
         cryp=(x*37)%200;//the crypting
        out<<(char)cryp;//print the crypted char
        in.get(x);//get another char
        if(in.eof())//if read beyong end of file
             break;
    }
    in.close();
    out.close();
    return;
}
void deCrypt(char *daf)
{
     int decr;//the main int
    char x;//the input char
    ifstream in;//input stream
    ofstream out;//output stream
    in.open(daf);//open the inout stream
    if(in.fail()){//see if it's not there
         cout<<"Error couldn't open the IN file\n";//print
        return;
    }
    cout<<"Enter the OUT file name: ";//ask for the out filename
    cin>>daf;
    out.open(daf);//open the outfile
    in.get(x);//get the input char
    if(in.eof())//if read beyong end of file
         return;
    while(x!=EOF){//while x is not beyong end of file
         decr=(x*173)%200;//the dectypring
        out<<(char)decr;
        in.get(x);//get the next char
        if(in.eof())//if read beyong the eon of file
             break;
    }
    return;
}
int main(void)
{
    if (password()) cout << "Access Granted: \n";
    else
    {
    cout << "You are not Authorized to use this program!\n";
    system("pause");
    return 0;
    }
    char *cool=new char[20];//the name pointer
    char nav;              //"navigation char"
    cout << "*---------------------------------------------*\n";
    cout << "| This is an encryption program.  I'm not     |\n";
    cout << "| taking credit for this.  This was a         |\n";
    cout << "| recent submission on planet-source-code     |\n";
    cout << "| I just added password protection to it.     |\n";
    cout << "*---------------------------------------------*\n\n";
    system("pause");
    cout << "\n\n";
    cout << "Use \"m\" for the Menu\n";//print instructions
     while(true){
         cin >> nav;
         switch(nav){
             case 'm':
                 cout << "COMMAND\tFUNCTION\n";
                cout << "e      \tencrypt\n"
                          "d      \tdecrypt\n"
                        "m      \t menu \n"
                        "q      \t quit \n";
                break;
             case 'e':
                 cout << "Enter the file name: \nExample: \"file\".txt\n";
                cin >> cool;
                doCrypt(cool);
                break;
            case 'd':
                 cout << "Enter the file name: ";
                cin >> cool;
                deCrypt(cool);
                break;
            case 'q':
                 exit(0);
                 break;
            default:
                 cout << "I do not understand you!\n";
                break;
        }
    }
}

bool password()
{
     char string1[50];
     cout << "Enter in the encryption password: \n";
     gets(string1);

     if (strcmp(string1, "outlaw")) return 0;
     return 1;
}

######################################

the plain test file contains line

i am new to c programming

after enc it gives

U¸½!¸F‰¸\k¸?¸k½!!UF

after decryting this enc file

it doesnt give req out put means the real plaint test which is

i am new to c programming
instead it gives
iÈAmÈnEwÈtoÈcÈProgrAmming

and this is the problem i m facing

please solve this for me
after that i will organize the program as u said earlier

my priority is the output is the result

which i am unable to get

Dear tux4life,
i have made changes u ssuggested i got error in some and confused about enc and dec as no output to file and also read my query number 16

best regards!

any help will be applreciated by helpers

How I would go trough the process of designing such a program:
Create a simple menu, which will allow the user to choose whether he wants to encrypt or decrypt. (you've done this)

Create two separate functions: one to encrypt and one to decrypt.
(you've done this)

But here's where my approach starts to differ from yours:
As I am, I first of all test it without all the file handling, this means that I would let the user enter a line of text on the keyboard, and print out the encrypted/decrypted sentence.
When this works correctly, I move on to writing/changing code to be able to operate (encrypt / decrypt) successfully on files.

Seems similar to this thread. Tux's advice is good. Split everything up into smaller tasks.

http://www.daniweb.com/forums/thread221572.html

I'll add the same advice that I gave the person in the thread I linked. Don't hard-code the keys (37, 173, 200). Have variables for them and give them descriptive names. And when you're debugging, make them easy.

37 * 173 = 6401.
6401 % 200 = 1

So that's good. But things are easier to check if you have something like (2, 3, 5):

2 * 3 = 6
6 % 5 = 1

The math is much easier to do in your head. Have a nice easy input file, where it's short enough and the math is easy enoguh to do on scratch paper. So encrypt "abc" or something, then check it, then decrypt it. It's easier to debug that way.

commented: superior advice :P +21

Very Right sir,
I can imagine that this will solve our problem easily.
tux4life send me the enc and dec code in reply #8 of this post/thread and i ranit successfully and it worked.

Mathematically its ok
now the problem that tux4life is saying that we use it without file handling
actually problem pop-ups when we use file handling, i will explain the reason.

let say in the input file written is "a"
the ASCII code of " a" is 97
according to our formula i m using 200 mod because 200 mod is sufficient for ASCII code correct me if i m wrong. and 37 and 173 are modulo multiplicative inverse of each other base 200.
so for enc
(97*37)%200 = 189
now dec
(189*173)%200=97
according to my program and tux4life program quoted in number 8 reply, works the same
now problem arises at the place which i m againand again trying to covince is
when it saves the enc data into file let say for 97 it stores 189 it saves some equivalent charater of 189

when it comes to decryption it cannot recognise whether it is 1 or 18 or 189, somebody told me the problem is here
for detail kindly look at the post number 16 of this thread.

hope this might help u get my problem

Best wishes!

It has nothing to do with files. It has to do with what a char can store versus what an integer can store. On my machine, a char is 8 bits and an int is 32 bits, thus a char ranges from -128 to 127. On my machine, it starts to go haywire when I try to encrypt 4. 4 * 37 = 148, the first number encountered that is over 127. All fine and good with integers. Now decrypt:

148 * 173 = 25, 604
25,604 % 200 = 4

which was the original number. All fine and good, except that isn't what's happening since it's treating 148 as -108 due to overflow. multiply -108 by 173 and you get -18,684. Take the mod of that by 200 and you get -84, which isn't 4. Post 7 tests it with integers, and there's no overflow. With a char, there's overflow, so everything gets screwed up. See the program below. The way it is, it doesn't deal with overflow and thus breaks. Comment the current functions out and uncomment the commented functions and compile/run it again and it should work. The commented functions do the math with integers rather than chars, so there's no overflow.

#include <iostream>
using namespace std;

/*
char encrypt (char c)
{
    int a = c;
    if (a < 0)
        a = a + 256;
    int b = a * 37;
    char d = b % 200;
    return d;
}

char decrypt (char c)
{
    int a = c;
    if (a < 0)
        a = a + 256;
    int b = a * 173;
    char d = b % 200;
    return d;
}
*/
char encrypt (char c)
{
    return (c * 37) % 200;
}

char decrypt (char c)
{
    return (c * 173) % 200;
}


int main ()
{
    for (int a = 0; a < 200; a++)
    {
      char c = a;
      char e = encrypt (c);
      char f = decrypt (e);
      cout << (int) c << " " <<  (int)e << " " <<  (int)f << endl;
      
      if (c != f)
      {
            cout << "Problem!!!\n";
            cin.get ();
      }
    }

    cin.get ();    
    return 0;
}

its working like a charm.

now if we have a file which contains charaters and numbers

e.g

i am trying to solve this problem dice 6 months, 6 months are equal to 30*6=189 days

will it enc and dec the input file successfully, if yes where shoud i put this code in my orignal program so that it work for me.

suggest the location where i put your code or please put the code in the program so that i can give input from the file, and also get output in the file just like my old program.

the code you have given , what i think will run in linux but my old program wasnot working in linux as header and syntax are different in linux c.

please help me out so that i can give inout from file and output to file as in my old program.

Regards!

its working like a charm.

now if we have a file which contains charaters and numbers

e.g

i am trying to solve this problem dice 6 months, 6 months are equal to 30*6=189 days

will it enc and dec the input file successfully, if yes where shoud i put this code in my orignal program so that it work for me.

suggest the location where i put your code or please put the code in the program so that i can give input from the file, and also get output in the file just like my old program.

the code you have given , what i think will run in linux but my old program wasnot working in linux as header and syntax are different in linux c.

please help me out so that i can give inout from file and output to file as in my old program.

Regards!

You don't have any Linux specific headers in the code you posted in post 5. You have C headers. Make them C++ headers (i.e. stdlib.h turns into cstdlib, time.h turns into ctime, etc.).


Your basic skeleton could be this:

char encrypt (char c);
char decrypt (char c);
// the above functions are the ones I wrote

string encryptString (string line);
string decryptString (string line);
// the above functions call the top functions a character at a time to encrypt an entire string.

void encryptFile (char* plainTextFileName, char* encryptedTextFileName);
void decryptFile (char* plainTextFileName, char* encryptedTextFileName);
// these functions open up the files, read a line at a time from the input file, call encryptString or decryptString for each line, and output the altered line to the output file.

Thanks Sir,

I tried to put this code in my program but lots of errors

Can u make these changes for me in the program that i send on number 16 reply of this thread.

I m zero level programmer in c,
as i worked mostly on linux,server and data comm.

looking forward to your possitive response.

we are near to the solution but unfortunatly i m layman in c language programing, i.e why i cannot cross the bridge.

is there anyone who can combine all this and edit the program, so that it may be a turn key solution.

i hace the code for RC4 algo which will be the next step after this program.

i will encrypt the enc file with rc4 algo which uses XOR

and send it to sensor node
the receing sensor node will xor again the file which will give the enc file
and the dec ot plaint text sended by the sender will be the output.

then i will put this code in NS2 simulator which is ready for just this program.

my 80% work is complete waiting for this program.

SOS please edit this program for me and give me a turn key solution.

means
the orignal program may be changed acording to the suggestions given by tux4life and VernonDozier

Go to post 5. Change your red line to:

cryp = encrypt (x);

Change your green line to:

decr = decrypt (x);

Where encrypt and decrypt are the functions I posted earlier.

If the original program works, then I would imagine that all that is needed is the above adjustment.

Okay, I really have enough of your double postings in your thread:

a) you won't get help faster by doing this
b) you just make your own thread unreadable
c) you waste your time, use that time to try figuring out the solution yourself
d) code tags seem useless to you, how did you miss using them?
Information about code tags is found all over Daniweb:

1) in the Rules you were asked to read when you registered
2) in the text at the top of this forum
3) in the announcement at the top of this forum titled Please use BB Code and Inlinecode tags
4) in the sticky post above titled Read Me: Read This Before Posting
5) any place CODE tags were used
6) Even on the background of the box you actually typed your message in!

e) several other reasons: like asking to create the code for you

I don't see any reason why I should help you, the reasons why I shouldn't help you are denoted above.

I'm going to quote what I already have said before in this thread:

First of all I want you to NOT PM me with your questions to do it for you, it won't work, I'm a free person and I'm free to do what I want, and not to do what I don't want (let that be clear).
What I want is to help you, what I don't want is spend my time to create a full-fledged encryption solution for you (or in other words: I rather provide paths to the solution, not the entire solution itself), so that you can turn it in, and pass (or fail :P) using my work, that wouldn't be fair, not? The point of the assignments you get is to show off your knowledge, show what you can. This means that you have to do the work, passing using someone else's work won't get you far in real life. The point is that you do the entire thing yourself (with some small help and hints from the forum members (the so-called "gurus") here), and that you finally (when you finished the program) can say: I did it!

P.S.: all your double postings are horrible, I would opt for an immediate thread lock.

If you don't agree with me, then please go on and double post until you get banned, I don't care about that.

And here, a bunch of links you should read (and agree with) before making your next reply to this thread:
http://www.daniweb.com/forums/faq.php?faq=daniweb_policies
http://www.daniweb.com/forums/thread78223.html
http://www.daniweb.com/forums/announcement8-2.html
http://www.daniweb.com/forums/announcement8-3.html
http://catb.org/~esr/faqs/smart-questions.html
http://cboard.cprogramming.com/c-programming/88495-development-process.html

Have a nice time reading them.

commented: Good comments, good links. +25

Dear Sir,
I am facing packet loss, in my connection, when i press the post quick reply button, the page didnt downloaded properly, so i refreshed it, i.e why it was posted double.

I wont PM you again, i m following you replies, sorry for that
i am new in this forum
and will learn slowly, yet i m trying to learn faster.

Thanks for your guidence :)

Dear Sir,
I am facing packet loss, in my connection, when i press the post quick reply button, the page didnt downloaded properly, so i refreshed it, i.e why it was posted double.

Oh yes, and how do you explain the several minutes difference between all those posts then?
The post above this one (if not already removed by a moderator) is just the evidence that it hasn't something to do with your connection (it just again demonstrates you haven't read my previous post(s), otherwise you should have known you should use code tags, but no, copy-paste seems easier to you).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.