-
-
[旧帖]
[求助]大家帮我看看什么地方出错了(RC5)
0.00雪花
-
发表于:
2010-5-24 14:29
2925
-
[旧帖] [求助]大家帮我看看什么地方出错了(RC5)
0.00雪花
加密后,解密出来的内容不是原文,找了好半天也不知道什么地出了。请高手指正,谢谢大侠了
void CRC5Base::InitialKeyAndRounds(unsigned char *key, int iKeyLength, int iRounds)
{
m_rc5Key.iKeyLong = iKeyLength;
this->iRounds = iRounds;
int T = 2 * iRounds + 2;
int i , j, c, t;
c = iKeyLength / 4;
RC5_WORD *S = new RC5_WORD[T];
S[0] = P32;
for (i = 1; i < T; i++)
{
S[i] = S[i-1] + Q32;
}
m_rc5Key.KeyExpanded = S;
RC5_WORD *L = new RC5_WORD[c];
for (i = 0;i< c; i++)
{
L[i] = 0;
}
for (i = 0; i < iKeyLength; i++)
{
t = (key[i] & 0xFF) << (8 * (i % 4));
L[i/4] = L[i/4] + t;
}
i = 0;
j = 0;
RC5_WORD X = 0;
RC5_WORD Y = 0;
int k = (T > c) ? 3 * T : 3 * c;
while ( k --)
{
m_rc5Key.KeyExpanded[i] = ROTL(m_rc5Key.KeyExpanded[i] + X + Y, 3);
X = m_rc5Key.KeyExpanded[i];
i = (i + 1) % T;
L[j] = ROTL(L[j] + X + Y, X + Y);
Y = L[j];
j = (j + 1) % c;
}
m_rc5Key.KeyExpanded[0] = m_rc5Key.KeyExpanded[0];
m_rc5Key.KeyExpanded[1] = m_rc5Key.KeyExpanded[1];
m_rc5Key.KeyExpanded[2] = m_rc5Key.KeyExpanded[2];
delete L;
}
RC5_WORD CRC5Base::ROTL(RC5_WORD s, RC5_WORD x)
{
RC5_WORD Temp = 0;
Temp = (s << x ) | (s >> (32 - x ));
return Temp;
}
RC5_WORD CRC5Base::ROTR(RC5_WORD s, RC5_WORD x)
{
RC5_WORD Temp = 0;
Temp = (s >> x ) | (s << (32 - x));
return Temp;
}
void CRC5Base::Encrypt(unsigned char *data)
{
RC5_WORD *S = m_rc5Key.KeyExpanded;
RC5_WORD A, B;
A = data[0] & 0xFF;
A += (data[1] & 0xFF) << 8;
A += (data[2] & 0xFF) << 16;
A += (data[3] & 0xFF) << 24;
B = data[4] & 0xFF;
B += (data[5] & 0xFF) << 8;
B += (data[6] & 0xFF) << 16;
B += (data[7] & 0xFF) << 24;
A = A + S[0];
B = B + S[1];
for (int i = 1; i <= iRounds; i++)
{
A = ROTL(A ^ B, B) + S[2 * i];
B = ROTL(B ^ A, A) + S[2 * i + 1];
}
data[0] = (A >> 0) & 0xFF;
data[1] = (A >> 8) & 0xFF;
data[2] = (A >> 16) & 0xFF;
data[3] = (A >> 24) & 0xFF;
data[4] = (B >> 0) & 0xFF;
data[5] = (B >> 8) & 0xFF;
data[6] = (B >> 16) & 0xFF;
data[7] = (B >> 24) & 0xFF;
}
void CRC5Base::Decrypt(unsigned char *data)
{
RC5_WORD *S = m_rc5Key.KeyExpanded;
RC5_WORD A, B;
A = data[0] & 0xFF;
A += (data[1] & 0xFF) << 8;
A += (data[2] & 0xFF) << 16;
A += (data[3] & 0xFF) << 24;
B = data[4] & 0xFF;
B += (data[5] & 0xFF) << 8;
B += (data[6] & 0xFF) << 16;
B += (data[7] & 0xFF) << 24;
for (int i = iRounds; i > 0; i--)
{
B = (ROTR(B - S[2 * iRounds + 1], A)) ^ A;
A = (ROTR(A - S[2 * iRounds], B)) ^ B;
}
B = B - S[1];
A = A - S[0];
data[0] = (A >> 0) & 0xFF;
data[1] = (A >> 8) & 0xFF;
data[2] = (A >> 16) & 0xFF;
data[3] = (A >> 24) & 0xFF;
data[4] = (B >> 0) & 0xFF;
data[5] = (B >> 8) & 0xFF;
data[6] = (B >> 16) & 0xFF;
data[7] = (B >> 24) & 0xFF;
}
[培训]内核驱动高级班,冲击BAT一流互联网大厂工作,每周日13:00-18:00直播授课