Cryptography Reference
In-Depth Information
Appendix A
A Sample C Implementation of RC4
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
unsigned char key[256], K[256], S[256];
unsigned int key_len = 16, i, j;
// 128 bit key
void rc4_keygen() {
for(i = 0; i < key_len; i++) {
key[i] = (unsigned char) (256.0*rand()/(RAND_MAX+1.0));
}
}
void rc4_expandkey() {
for(i = 0; i < 256; i++) {
K[i] = key[i % key_len];
}
}
void swap(unsigned char *s, unsigned int i, unsigned int j) {
unsigned char temp = s[i];
s[i] = s[j];
s[j] = temp;
}
void rc4_ksa() {
for (i = 0; i < 256; i++) {
S[i] = i;
}
for (i = j = 0; i < 256; i++) {
j = (j + K[i] + S[i]) & 0xFF; // Fast modulo 256 operation
swap(S, i, j);
}
i = j = 0;
}
unsigned char rc4_prga() {
i = (i + 1) & 0xFF;
j = (j + S[i]) & 0xFF;
swap(S, i, j);
return(S[(S[i] + S[j]) & 0xFF]);
}
int main() {
int round, keystream_len = 1024;
srand(time(NULL));
rc4_keygen();
rc4_expandkey();
rc4_ksa();
for(round = 1; round <= keystream_len; round ++) {
printf("%x", rc4_prga());
}
}
 
 
Search WWH ::




Custom Search