一.RC4算法
参考RC4加密算法的过程 代入例子计算
二.c语言实现
#include <stdio.h>
#include <string.h>
unsigned char sbox[256] = { 0 };
void swap(unsigned char* a, unsigned char* b)
{
unsigned char tmp = *a;
*a = *b;
*b = tmp;
}
void init_sbox( unsigned char key[]) {
for (unsigned int i = 0; i < 256; i++)//赋值
sbox[i] = i;
unsigned int keyLen = strlen((char*)key);
unsigned char Ttable[256] = { 0 };
for (int i = 0; i < 256; i++)
Ttable[i] = key[i % keyLen];//根据初始化t表
for (int j = 0, i = 0; i < 256; i++)
{
j = (j + sbox[i] + Ttable[i]) % 256; //打乱s盒
swap(sbox[i], sbox[j]);
}
}
void RC4_enc_dec(unsigned char data[],unsigned char key[]){
unsigned char k, i = 0, j = 0, t;
init_sbox(key);
unsigned int dataLen = strlen((char*)data);
for (unsigned h = 0; h < dataLen; h++)
{
i = (i + 1) % 256;
j = (j + sbox[i]) % 256;
swap(sbox[i], sbox[j]);
t = (sbox[i] + sbox[j]) % 256;
k = sbox[t]; //求密钥流,并对明文加密
data[h] ^= k;
}
}
int main()
{
unsigned char data[1000] = { 0 };
unsigned char key[100] = { 0 };
printf("请输入需要加密的明文:\n");
scanf("%s", data);
printf("请输入密钥key:\n");
scanf("%s", key);
RC4_enc_dec(data, key);
printf("加密后的密文是:\n,%s",data);
RC4_enc_dec(data, key);
printf("解密后的明文是:\n%s", data);
return 0;
}
运行效果:
文章来源地址https://www.toymoban.com/news/detail-534231.html
三.c++实现
#include <iostream>
#include <string>
using namespace std;
class RC4 {
private:
unsigned char s[256];
void swap(unsigned char& a, unsigned char& b)
{
unsigned char tmp = a;
a = b;
b = tmp;
}
void init_sbox(string key)
{
for (unsigned int i = 0; i < 256; i++) //初始化s盒
s[i] = i;
unsigned char T[256] = { 0 };
unsigned keylen = key.length();
for (int i = 0; i < 256; i++)
T[i] = key[i % keylen]; //根据密钥初始化t表
for (int j = 0, i = 0; i < 256; i++)
{
j = (j + s[i] + T[i]) % 256; //打乱s盒
swap(s[i], s[j]);
}
}
public :
void enc_dec(string& data,string key) {
init_sbox(key);
unsigned int datalen = data.length();
unsigned char k, i = 0, j = 0, t;
for (unsigned int h = 0; h < datalen; h++)
{
i = (i + 1) % 256;
j = (j + s[i]) % 256;
swap(s[i], s[j]);
t = (s[i] + s[j]) % 256;
k = s[t];
data[h] ^= k;
}
}
};
int main()
{
RC4 rc4 ;
string data, key;
cout << "请输入需要加密的明文:" << endl;
cin >> data;
cout << "请输入密钥key:" << endl;
cin >> key;
rc4.enc_dec(data, key);
cout << "加密后的内容是:\n" << data << endl;
rc4.enc_dec(data, key);
cout << "解密后的内容是:\n" << data << endl;
return 0;
}
运行效果:
文章来源:https://www.toymoban.com/news/detail-534231.html
到了这里,关于RC4算法c/c++语言实现的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!