We closed this forum 18 June 2010. It has served us well since 2005 as the ALPHA forum did before it from 2002 to 2005. New discussions are ongoing at the new URL http://forum.processing.org. You'll need to sign up and get a new user account. We're sorry about that inconvenience, but we think it's better in the long run. The content on this forum will remain online.
Page Index Toggle Pages: 1
RC4 (Read 332 times)
RC4
Mar 13th, 2009, 12:41pm
 
Hi
I try to write a simple RC4 code.
But after ca 500 calls of nextrc4() it makes something stupid?
The output of rc4test() should be the same every call, but it isn't.
What is the mistake?

thanks


int[] sbox=new int[256]; //RC4 S-Box
int rc4i;
int rc4j;
int[] rc4key={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17}; //RC4 Key


void setup()
 {
   //call it 4 times should be 4 times the same sbox
   rc4test();
   rc4test();
   rc4test();
   rc4test();
 }
 
void rc4init()
 {
   int rc4temp;
   rc4j=0;
   
   for(rc4i=0;rc4i<255;++rc4i)
     {
       sbox[rc4i]=rc4i;
     }
   for(rc4i=0;rc4i<255;++rc4i)
     {
      rc4j=(rc4j+sbox[rc4i]+rc4key[rc4i%rc4key.length])%256;
      rc4temp=sbox[rc4i];
      sbox[rc4i]=sbox[rc4j];
      sbox[rc4j]=rc4temp;
     }
   rc4i=0;
   rc4j=0;
 }
     
     
int nextrc4()
 {
   int rc4temp;
   
   rc4i=(rc4i+1)%256;
   rc4j=(rc4j+sbox[rc4i])%256;
   rc4temp=sbox[rc4i];
   sbox[rc4i]=sbox[rc4j];
   sbox[rc4j]=rc4i;
   
   return(sbox[(sbox[rc4i]+sbox[rc4j])%256]);
 }

 
void rc4test()
 {
   rc4init(); //initialising
   
   for(int i=0;i<2000;++i) //get 2000 times
   {
     nextrc4();    
   }
   
   for(int i=0;i<256;++i) // print the sbox
   {
    print(sbox[i]+" ");
   }
   
   println();
   println();
 }
Re: RC4
Reply #1 - Mar 13th, 2009, 2:15pm
 
You don't re-init the last element of the array: the init loops must be < 256, not < 255.
Re: RC4
Reply #2 - Mar 13th, 2009, 5:18pm
 
uups, i was blind. That was it. Now it works.
Many thanks

int[] sbox=new int[256]; //RC4 S-Box
int rc4i;
int rc4j;
int[] rc4key={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17}; //RC4 Key


void setup()
 {
   rc4test();
 }
 
void rc4init()
 {
   int rc4temp;
   rc4j=0;
   
   for(rc4i=0;rc4i<256;++rc4i)
     {
       sbox[rc4i]=rc4i;
     }
   for(rc4i=0;rc4i<256;++rc4i)
     {
      rc4j=(rc4j+sbox[rc4i]+rc4key[rc4i%rc4key.length])%256;
      rc4temp=sbox[rc4i];
      sbox[rc4i]=sbox[rc4j];
      sbox[rc4j]=rc4temp;
     }
   rc4i=0;
   rc4j=0;
 }
     
     
int nextrc4()
 {
   int rc4temp;
   
   rc4i=(rc4i+1)%256;
   rc4j=(rc4j+sbox[rc4i])%256;
   rc4temp=sbox[rc4i];
   sbox[rc4i]=sbox[rc4j];
   sbox[rc4j]=rc4i;
   
   return(sbox[(sbox[rc4i]+sbox[rc4j])%256]);
 }

 
void rc4test()
 {
   rc4init(); //initialising
   
   for(int i=0;i<2000;++i) //get 2000 times
   {
     nextrc4();    
   }
   
   for(int i=0;i<256;++i) // print the sbox
   {
    print(sbox[i]+" ");
   }
   
   println();
   println();
 }
 
Page Index Toggle Pages: 1