rc4
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#ifndef RC4_H #define RC4_H #define KEYLEN256 256 class rc4 { public: rc4(); ~rc4(); void swap(unsigned char *a, unsigned char *b); //initial state int KSA(unsigned char *S, unsigned char *K, int keylen); int KSA(unsigned char *K, int keylen); //keystream gen void PGRA(unsigned char *key, int plainlen); //protected: unsigned char m_S[KEYLEN256]; }; #endif // RC4_H
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include <stdio.h> #include <string.h> #include <stdlib.h> #include "rc4.h" rc4::rc4() { memset(m_S, 0x00, sizeof(m_S)); printf("rc4::rc4()\n"); } rc4::~rc4() { printf("rc4::~rc4()\n"); } void rc4::swap(unsigned char *a, unsigned char *b) { unsigned char tmp; tmp = *a; *a = *b; *b = tmp; } int rc4::KSA(unsigned char *S, unsigned char *K, int keylen) { int i; //Temp is tmp vector unsigned char Temp[256] = {0}; //init for (i = 0; i < KEYLEN256; ++i) { S[i] = i; Temp[i] = K[i % keylen]; } //S initial seq int j=0; for (i = 0; i < KEYLEN256; ++i) { j = (j+S[i]+Temp[i]) % KEYLEN256; swap(&S[i], &S[j]); } return 0; } int rc4::KSA(unsigned char *K, int keylen) { int i; //T is tmp vector unsigned char Temp[256] = {0}; //init for (i = 0; i < KEYLEN256; ++i) { m_S[i] = i; Temp[i] = K[i % keylen]; } //S initial seq int j=0; for (i = 0; i < KEYLEN256; ++i) { j = (j+m_S[i]+Temp[i]) % KEYLEN256; swap(&m_S[i], &m_S[j]); } return 0; } void rc4::PGRA(unsigned char *key, int plainlen) { int i = 0, j = 0; int t=0; //*key = (uc *)malloc(sizeof(uc)*plainlen); for (int var = 0; var < plainlen; ++var) { i = (i+1) % KEYLEN256; j = (j+m_S[i]) % KEYLEN256; swap(&m_S[i], &m_S[j]); t=(m_S[i] + m_S[j]) % KEYLEN256; key[var]= m_S[t]; } }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//C v0.1 AC #include<stdio.h> #include <stdlib.h> #include <string.h> #include <alloca.h> #include "rc4.h" using namespace std; typedef unsigned char uc; int main(void) { rc4 r4; uc key[] = "123a7872bef214518908d"; uc buf[1024] = { 0 }; uc ts[256] = { 0 }; uc plain[] = "we are good friends"; int plen = sizeof(plain); uc *tmpk = (uc *) malloc(sizeof(uc) * plen); int keylen = sizeof(key); r4.KSA((uc *) key, keylen); for (int var = 0; var < KEYLEN256; ++var) { ts[var] = r4.m_S[var]; printf("%c", ts[var]); } printf("\ntmpk:\n"); r4.PGRA(tmpk, plen); for (int var = 0; var < plen; ++var) { printf("%c", tmpk[var]); } printf("\n"); printf("plain:%s\n", plain); printf("cipher:\n"); for (int var = 0; var < plen; ++var) { buf[var] = tmpk[var] ^ plain[var]; printf("%c", buf[var]); } printf("\n"); for (int var = 0; var < plen; ++var) { printf("%c", tmpk[var] ^ buf[var]); } printf("\n"); if (tmpk != NULL) { free(tmpk); tmpk = NULL; } return 0; }