#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;
typedef unsigned long int WORD; /* Should be 32-bit = 4 bytes */
#define w 32 /* word size in bits */
#define r 12 /* number of rounds */
#define b 16 /* number of bytes in key */
#define c 4 /* number words in key */
/* c = max(1,ceil(8*b/w)) */
#define t 26 /* size of table S = 2*(r+1) words */
WORD S [t],L[c]; /* expanded key table */
WORD P = 0xb7e15163, Q = 0x9e3779b9; /* magic constants */
/* Rotation operators. x must be unsigned, to get logical right shift*/
#define ROTL(x,y) (((x)<<(y&(w-1))) | ((x)>>(w-(y&(w-1)))))
#define ROTR(x,y) (((x)>>(y&(w-1))) | ((x)<<(w-(y&(w-1)))))
void RC5_DECRYPT(WORD *ct, WORD *pt) /* 2 WORD input ct/output pt */
{
WORD i, B = ct[1], A = ct[0];
for (i = r; i > 0; i--)
{
B = ROTR(B - S[2 * i + 1], A)^A;
A = ROTR(A - S[2 * i], B)^B;
}
pt[1] = B - S[1]; pt[0] = A - S[0];
}
void RC5_SETUP(unsigned char *K) /* secret input key K 0...b-1] */
{
WORD i, j, k, u = w/8, A, B, L[c];
/* Initialize L, then S, then mix key into S */
for (i = b - 1, L[c - 1] = 0; i != -1; i--)
L[i/u] = (L[i/u] << 8) + K[i];
for (S[0] = P, i = 1; i < t; i++)
S[i] = S[i - 1] + Q;
for (A=B=i=j=k=0; k<3*t; k++,i=(i+1)%t,j=(j+1)%c) /* 3*t > 3*c */
{
A = S[i] = ROTL(S [i]+(A+B),3);
B = L[j] = ROTL(L[j]+(A+B),(A+B));
}
}
void printword(WORD A)
{
WORD k;
for (k=0 ;k<w; k+=8)
printf("%02.2lX",(A>>k)&0xFF);
}
int main()
{
WORD i, j, k, pt [2], pt2 [2], ct [2] = {0,0};
unsigned char key[b];
ofstream out("cpt.txt");
ifstream in("key.txt");
if (!in)
{
cout << "Cannot open file.\n";
return 1;
}
if (!out)
{
cout << "Cannot open file.\n";
return 1;
}
key="111111000001111";
RC5_SETUP(key);
ct[0]=2185970173;
ct[1]=3384368406;
for (i=1; i<2; i++)
{
RC5_DECRYPT(ct,pt2);
printf("\n plaintext ");
printword(pt[0]);
printword(pt[1]);
}
return 0;
}
当我编译这段代码时,我得到两个警告,还有一个错误,说我无法为我的角色数组分配一个char值。那是为什么?
答案 0 :(得分:2)
变化:
key="111111000001111";
到
strncpy((char *)key, "111111000001111", sizeof(key));
答案 1 :(得分:1)
您无法使用如下语句设置key
数组的值:
key = "111111000001111";
您需要使用strcpy()
或memcpy()
或其他类似内容(非标准,但可以说更不容易出错)strlcpy()
。
但是,可以初始化它,如下所示:
unsigned char key[b] = "111111000001111";
但是请注意,只要字符串比维度小一个字符就可以得到一个以空字符结尾的字符串,但如果字符数等于维度,你将获得一个字符数组不 null终止,没有错误(尽管你可能会收到警告)。在C ++中,该场景应该生成错误。有关详细信息,请参阅Why doesn't the compiler detect out-of-bounds in string constant initialization?。
答案 2 :(得分:0)
因为key = "111111000001111";
无论如何都无效。您无法在C或C ++中以这种方式为数组赋值。尝试将strcpy
或memcpy
与适当的演员阵容一起使用。