我想知道如何使用一组数字作为rc4加密的密钥。根据互联网和维基百科的说法,密钥实际上是一个字母串,但使用的是字节。但在我的程序中,我需要使用一个6位数字作为密钥。我是否应该将其转换为字符串或如何转换。
关键的Sheudling算法如下所示。
void ksa(u_char *State, u_char *key) {
int byte, i, keylen, j=0;
keylen = (int) strlen((char *) key);
for(i=0; i<256; i++) {
j = (j + State[i] + key[i%keylen]) % 256;
swap(&State[i], &State[j]);
}我如何修改代码,或者我应该只将数字转换为字符串。
发布于 2013-05-01 19:29:48
字符串和数字都是字节。下面是一个可以正常工作的RC4代码,它接受无符号字符的键:
#include<stdio.h>
#include<string.h>
#define SIZE 256
unsigned char SBox[SIZE];
int i;
int j;
void initRC4(unsigned char Key[]);
unsigned char getByte(void);
void initRC4(unsigned char Key[])
{
unsigned char tmp;
unsigned char KBox[SIZE];
for(i=0;i<SIZE;i++)
SBox[i]=i;
for(i=0;i<SIZE;i++)
KBox[i]=Key[i % strnlen(Key,SIZE)];
for(j=0,i=0;i<SIZE;i++)
{
j=(j+SBox[i]+KBox[i]) % SIZE;
tmp=SBox[i];
SBox[i]=SBox[j];
SBox[j]=tmp;
}
}
unsigned char getByte(void)
{
unsigned char tmp;
i=(i+1)%SIZE;
j=(j+SBox[i])%SIZE;
tmp=SBox[i];
SBox[i]=SBox[j];
SBox[j]=tmp;
return SBox[(SBox[i]+SBox[j])%SIZE];
}首先,初始化RC4流:
initRC4(key);然后你就可以做到:
getByte()...which总是从你设置的RC4流中返回1个字节。
但有一件事要记住--字符串中的一个字母并不总是等于1个字节。字符串中的整数和数字符号也是如此。真的,在你摆弄密码之前,你必须先读一读计算机编程入门。
以下演示了整型字符串中字节的区别:
#include <string>
int main(int argc, char **argv) {
const int n=67898;
const std::string str = "67898";
const int arrayLength = sizeof(int);
const int stringArrayLength = str.size();
unsigned char *bytePtr=(unsigned char*)&n;
printf("Bytes for integer: ");
for(int i=0;i<arrayLength;i++)
{
printf("%X ", bytePtr[i]);
}
printf("\n");
printf("Bytes for string: ");
for(int i=0;i<stringArrayLength;i++)
{
printf("%X ", str.at(i));
}
printf("\n");
return 0;
}输出:
Bytes for integer: 3A 9 1 0
Bytes for string: 36 37 38 39 38通常在字符串的末尾会有一个终止字节,因此您可以在字符串大小上添加+1字节。
https://stackoverflow.com/questions/16316690
复制相似问题