Thread: How to do encryption in C

  1. #16
    Registered User
    Join Date
    Sep 2006
    Posts
    16
    what i actually need is the c code for rsa algorithm. May be its of any of these examples in this topic....


    pls help....

  2. #17
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    You're looking at the code man.

    What the real problem will be for you is that RSA deals with much much bigger numbers than can be represented using normal C datatypes. For that you need a bignum package like GMP

    However, before you move up to that, you can at least prove to yourself that you UNDERSTAND the algorithms by practicing on the very small numbers used for examples.

    All you seem to be doing is whining about it.
    If you're not even going to post your attempt at using pow(), and showing the code / results you get, then forget about the crypto side.

    If you just want to download a lib to do it all for you, then do it and stop pretending that you can write it yourself.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  3. #18
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by sankarv
    what i actually need is the c code for rsa algorithm. May be its of any of these examples in this topic....


    pls help....
    I haven't been able to find exact code for RSA encryption, but this link should be enough to get you on the right path with it.

    Understand that as Salem mentioned, you'll HAVE to use a library or function to handle the HUGE numbers involved in working with RSA.

    Work through the examples by hand until you understand just what's going on with it. No one can just sit down and code up a program that they don't have a fair understanding of. The computer can give us great answers, but it doesn't give us great algorithmic inspirations.

    The link is:
    http://www.di-mgt.com.au/rsa_alg.html#simpleexample

    Adak

  4. #19
    Registered User
    Join Date
    Sep 2006
    Posts
    16
    Quote Originally Posted by Salem
    count = (count ^ 3) % 33
    Would be

    count = pow(count,3) % 33

    Its returning error as "invalid operands to binary %". What may be the reason for this?

    Anyway i will try with big num tools as u said...


    Thanks for the help.

  5. #20
    Registered User
    Join Date
    Sep 2006
    Posts
    16
    could anyone please suggest me antoher type of encryption which can be done without the libraries? basic XOR encryption i already done. other than that.


    pls help...

  6. #21
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,613
    > invalid operands to binary %
    You get this error because pow returns a double or float, and % only works with integers. Try using fmod instead.

  7. #22
    Registered User
    Join Date
    Sep 2006
    Posts
    16
    i corrected that and no error is coming but even then its not working . may be the problem with big numbers.

  8. #23
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by sankarv
    could anyone please suggest me antoher type of encryption which can be done without the libraries? basic XOR encryption i already done. other than that.


    pls help...
    There are MANY kinds of encryption.. Much more than could be run by you in a post.

    Why don't you google for "Mayfair encryption", and see if that doesn't help. Another one might be "Cyber Saber".

    Most of the newer one's do involve big numbers, because there is no known way to "hack" them, easily.

    ANY encryption system can be broken, given enough time and skilled resources working on it, with modern computers. An acceptable system will just make it impossible for the unskilled/less skilled to figure out, and difficult enough that the value of the message can't be broken out of the cypher text in a reasonable time, for the skilled cyptologist.

    The only totally secure possibility that I know of, is a one-time pad system, and that's so awkward to use it's usually not worth it, anyway.

    If you don't want to work with BIG BIG BIG numbers, then you don't want to mess further with RSA, because that's the heart of the whole RSA system.

    Adak

  9. #24
    Registered User
    Join Date
    Feb 2006
    Posts
    65
    You CAN do RSA with small numbers, too. What happens is that it's much easier to crack.

    In the heart of RSA is modular exponentation. You don't calculate it by first taking the exponent and then calculating its remainder because the numbers grow out of hands. Also you don't want to use floating point numbers because all calculations with them are inexact. Read this: http://en.wikipedia.org/wiki/Modular_exponentiation

  10. #25
    Registered User
    Join Date
    Mar 2006
    Posts
    725
    RSA with numbers smaller than say 20 digits are essentially useless and for illustration purposes only. The point is to use so many digits the additional polynomial cost outweighs the exponential factoring time. Say 256 bits.

    You could try simpler symmetric algorithms, like the Vinegere and Hill ciphers, for arithmetical manipulation practice.

    If all you want is the code, go download the SSL lib source or something. Have fun.
    Code:
    #include <stdio.h>
    
    void J(char*a){int f,i=0,c='1';for(;a[i]!='0';++i)if(i==81){
    puts(a);return;}for(;c<='9';++c){for(f=0;f<9;++f)if(a[i-i%27+i%9
    /3*3+f/3*9+f%3]==c||a[i%9+f*9]==c||a[i-i%9+f]==c)goto e;a[i]=c;J(a);a[i]
    ='0';e:;}}int main(int c,char**v){int t=0;if(c>1){for(;v[1][
    t];++t);if(t==81){J(v[1]);return 0;}}puts("sudoku [0-9]{81}");return 1;}

  11. #26
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    Code:
    #include <stdio.h>
    
    int iPower ( int n, int p ) {
        int result = 1, i = p;
        while ( i-- ) result *= n;
        return result;
    }
    
    int encrypt ( int ch, int n, int e ) {
        return iPower(ch,e) % n;
    }
    
    /* Use a = bc mod n = (b mod n).(c mod n) mod n */
    int decrypt ( int ch, int n, int d ) {
        /* This is hard-coded to assume d == 7 */
        /* in reality, use a loop to extract multiple factors */
        /* Yes, even with these small numbers, you can easily overflow an int! */
        int t1, t2, t3;
        t1 = iPower(ch,3) % n;
        t2 = iPower(ch,3) % n;
        t3 = iPower(ch,1) % n;
        return (t1 * t2 * t3) % n;
    }
    
    int main ( ) {
        char *msg = "hello";
        int n = 33, e = 3, d = 7;
        int ch;
    
        for ( ch = 0 ; ch < 26 ; ch++ ) {
            int enc, dec;
            enc = encrypt(ch,n,e);
            dec = decrypt(enc,n,d);
            printf( "Char %2d -> %2d -> %2d\n", ch, enc, dec );
        }
    
        while ( (ch=*msg++) != '\0' ) {
            int enc, dec;
            enc = encrypt(ch-'a',n,e);
            dec = decrypt(enc,n,d)+'a';
            printf( "Char %c -> %2d -> %c\n", ch, enc, dec );
        }
        return 0;
    }
    Easy, once I figured out decrypt() was overflowing.

    @sankarv - next time, try debugging it with a debugger, or printf() or at all.
    You have to be prepared to go through each line with a fine comb sometimes just to find the really obvious.

    It also helps if your code (like mine) uses the same terminology in the reference material.

    Also note that it's a complete waste of time trying to do things with files before you have the basic code sorted out. Simple test data embedded in the program is MUCH easier for others to help with.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  12. #27
    Registered User
    Join Date
    Sep 2006
    Posts
    16
    Thankx a lot. just want to know one thing.
    why u added '-a' in encrypt() function and +'a' in decrypt() function for encrypting strings?

  13. #28
    Registered User
    Join Date
    Sep 2006
    Posts
    16
    Hi. I done file encryption with the help of the code u gave .


    Code:
    #include <stdio.h>
    #include<stdlib.h>
    
    int iPower ( int n, int p ) {
        int result = 1, i = p;
        while ( i-- ) result *= n;
        return result;
    }
    
    int encrypt ( int ch, int n, int e ) {
        return iPower(ch,e) % n;
    }
    
    /* Use a = bc mod n = (b mod n).(c mod n) mod n */
    int decrypt ( int ch, int n, int d ) {
        /* This is hard-coded to assume d == 7 */
        /* in reality, use a loop to extract multiple factors */
        /* Yes, even with these small numbers, you can easily overflow an int! */
        int t1, t2, t3;
        t1 = iPower(ch,3) % n;
        t2 = iPower(ch,3) % n;
        t3 = iPower(ch,1) % n;
        return (t1 * t2 * t3) % n;
    }
    
    int main()
    {
       int n = 33, e = 3, d = 7;
       int ch,enc,dec;
       FILE *in,*out,*in2;   /* In and out FILE Streams to read/write data */
       
       
       if (( in = fopen("D:/cfiles/cfiles/cfiles/ss.txt", "r")) == NULL) /* Error Check File Streams */
       {
          printf("Error opening file for reading");
       }
       if (( out = fopen("D:/cfiles/cfiles/cfiles/ss.enc", "w")) == NULL)
       {
          printf("Error opening file for writing");;
       }
    
      while(( ch = getc(in)) != EOF) 
       {
             enc = encrypt(ch-'a',n,e); /* Decryption from the RSA */
             
          putc(enc, out);		/* Write new file */
       }
       
       fclose(in);
       fclose(out);
       printf("Encryption Success:n");
       printf("Encrypted  and stored data ");
       
       
       if (( in = fopen("D:/cfiles/cfiles/cfiles/ss.enc", "r")) == NULL) /* Error Check File Streams */
       {
          printf("Error opening file for reading");
       }
       
       if (( out = fopen("D:/cfiles/cfiles/cfiles/ss1.txt", "w")) == NULL) /* Error Check File Streams */
       {
          printf("Error opening file for writing");
                  
       }
       
        while(( ch = getc(in)) != EOF) 
       {
             dec = decrypt(ch,n,e)+'a'; /* Decryption from the RSA */
             
          putc(dec, out);		/* Write new file */
       }
       
       fclose(in);
       fclose(out);
       
       printf("Decryption done");
       
       system("PAUSE");
       return 0;
    }


    Still i face a problem in decryption. This program decrypts strings well but other charadcters are not outputted properly. I could nt figure out what may be the reason?

    The file for encyption is


    hello 101
    hi #here am i

    123456

    The encrypted file is

     à÷ü÷ë
    àþ
    à àëë÷ûíôõö

    The decrypted file is

    hellofzvzqhifxherefamfiqqz{hu|


    pls help what may be the reason...?

  14. #29
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    I'm not going to tell you - I'm going to see if you can debug a simple problem yourself.

    Once again, you've rushed for the finishing line by trying to encrypt a whole file without bothering to do any more testing!.

    Just rip out all that file reading and writing rubbish and study what it going on carefully for a while.
    Change the message to "hello world" and go through the code with the debugger ONE line at a time, and make damn sure it does what you want. Then try with a digit character then a symbol like # and a control like '\n'

    What I posted was a working hint. Not a complete answer you can just take, wrap a bit of file handling round then claim an easy victory.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

  15. #30
    Registered User
    Join Date
    Sep 2006
    Posts
    16
    sorry. i could nt figure out the poblem. i was debugging for long time and im vexed. i am getting awkward values in debugging. just i want this encryption logic common for strings,numbers and special characters since all occur in a file.
    pls help...

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 16
    Last Post: 11-23-2007, 01:48 PM
  2. help needed with edit control & encryption
    By willc0de4food in forum Windows Programming
    Replies: 2
    Last Post: 03-16-2006, 08:21 PM
  3. abt encryption algorithm
    By purIn in forum C Programming
    Replies: 9
    Last Post: 12-22-2003, 10:16 PM
  4. What's wrong with my Stream Cipher Encryption?
    By Davros in forum C++ Programming
    Replies: 3
    Last Post: 04-18-2002, 09:51 PM
  5. File Encryption & Read/Write in Binary Mode
    By kuphryn in forum C++ Programming
    Replies: 5
    Last Post: 11-30-2001, 06:45 PM