密钥流:算法的关键是根据明文和密钥生成相应的密钥流,密钥流的长度和明文的长度是对应的,也就是说明文的长度是字节,那么密钥流也是字节。当然,加密生成的密文也是字节,因为密文第字节=明文第字节异或密钥流第字节;
状态向量:长度为。每个单元都是一个字节,算法运行的任何时候,S都包括的比特数的排列组合,只不过值的位置发生了变换;
临时向量:长度也为,每个单元也是一个字节。如果密钥的长度是字节,就直接把密钥的值赋给,否则,轮转地将密钥的每个字节赋给;
密钥:长度为字节,注意密钥的长度与明文长度、密钥流的长度没有必然关系。
初始化S
void rc4_init(unsigned char*s, unsigned char*key, unsigned long Len) { int i = 0, j = 0; char k[256] = { 0 }; unsigned char tmp = 0; for (i = 0; i<256; i++) { s[i] = i; k[i] = key[i%Len]; } for (i = 0; i<256; i++) { j = (j + s[i] + k[i]) % 256; tmp = s[i]; s[i] = s[j];//交换s[i]和s[j] s[j] = tmp; } }
加解密
void RC4(unsigned char*s, unsigned char*Data, unsigned long Len) { int i = 0, j = 0, t = 0; unsigned long k = 0; unsigned char tmp; for (k = 0; k<Len; k++) { i = (i + 1) % 256; j = (j + s[i]) % 256; tmp = s[i]; s[i] = s[j]; s[j] = tmp; t = (s[i] + s[j]) % 256; Data[k] ^= s[t]; } }
主函数
int main() { unsigned char s[256] = { 0 }, s2[256] = { 0 }; char key[256]; printf("输入密钥:\n"); scanf("%s",key); char pData[512]; printf("输入明文:\n"); scanf("%s",pData); unsigned long len = strlen(pData); int i; rc4_init(s, (unsigned char*)key, strlen(key)); for (i = 0; i<256; i++) { s2[i] = s[i];//加密解密的初始化s要相同 } printf("加密密文:\n"); RC4(s, (unsigned char*)pData, len); printf("pData=%s\n", pData); printf("解密明文:\n"); RC4(s2, (unsigned char*)pData, len); printf("pData=%s\n", pData); return 0; }
本文参考博客
https://www.cnblogs.com/zibility/p/5404478.html
https://blog.csdn.net/lc_910927/article/details/37599161