用c语言写一个rc4加密程序
时间: 2024-06-12 08:11:01 浏览: 110
好的,以下是用C语言实现RC4加密的代码:
```c
#include <stdio.h>
#include <string.h>
void rc4(unsigned char *key, unsigned long keylen, unsigned char *data, unsigned long datalen)
{
unsigned char s[256], k[256];
unsigned long i, j, t;
for (i = 0; i < 256; i++)
{
s[i] = i;
k[i] = key[i % keylen];
}
j = 0;
for (i = 0; i < 256; i++)
{
j = (j + s[i] + k[i]) % 256;
t = s[i];
s[i] = s[j];
s[j] = t;
}
i = j = 0;
for (unsigned long n = 0; n < datalen; n++)
{
i = (i + 1) % 256;
j = (j + s[i]) % 256;
t = s[i];
s[i] = s[j];
s[j] = t;
data[n] ^= s[(s[i] + s[j]) % 256];
}
}
int main()
{
unsigned char key[] = "this is a key";
unsigned char data[] = "hello world";
unsigned long keylen = strlen(key);
unsigned long datalen = strlen(data);
rc4(key, keylen, data, datalen);
printf("Encrypted data: ");
for (unsigned long i = 0; i < datalen; i++)
printf("%02x", data[i]);
printf("\n");
rc4(key, keylen, data, datalen);
printf("Decrypted data: %s\n", data);
return 0;
}
```
这个程序中,我们使用了一个 RC4 算法来加密和解密数据。RC4 算法是一种流加密算法,它使用一个密钥来生成一个伪随机流,然后将这个流与明文进行异或运算,从而得到密文。解密时,我们只需要再次使用相同的密钥来生成伪随机流,并将密文与这个流进行异或运算,就可以得到明文。
阅读全文