C位操作DES置换

时间:2016-01-08 23:40:48

标签: c cryptography bit-manipulation bit des

我在使用Python实现DES算法时遇到了麻烦,所以我想我会切换到C.但我遇到了一个问题,我几个小时都无法解决这个问题,希望你能提供帮助我。这是来源:

 int PI[64] = {58,50,42,34,26,18,10,2,
                    60,52,44,36,28,20,12,4,
                    62,54,46,38,30,22,14,6,
                    64,56,48,40,32,24,16,8,
                    57,49,41,33,25,17,9,1,
                    59,51,43,35,27,19,11,3,
                    61,53,45,37,29,21,13,5,
                    63,55,47,39,31,23,15,7};

 unsigned long getBit(unsigned long mot, unsigned long position)
{
  unsigned long temp = mot >> position;
  return temp & 0x1;
}

void setBit(unsigned long* mot, int position, unsigned long value)
{
 unsigned long code = *mot;
 code ^= (-value ^ code) & (1 << position);
 *mot = code;
}

void permute(  unsigned long * mot, int * ordre, int taille )
{
 unsigned long res;
 int i = 0;
 unsigned long bit;
 for (i = 0; i < taille; i++)
 { setBit(&res, i, getBit(*mot, ordre[i] - 1)); }
 *mot = res;
}

int main(int argc, char *argv[])
{
 unsigned long bloc = 0x0123456789ABCDEF;
 permute(&bloc, PI, 64);
 printf(" end %lx\n", bloc);

 return 1;
}

我手动和我的Python程序进行了这种排列,这种排列的结果应该是0xcc00ccfff0aaf0aa,但我得到0xffffffffcc00ccff(不知何故,这是一半正确,一半是坏的)。到底是怎么回事?如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

我在我的十六进制字的末尾添加了UL,并且使用了uint64_t而不是unsigned long int。当我更改-value时,我得到fffffffffffffff或0,但是使用UL和uint64_t我得到了正确的结果,这可能意味着,正如你们所建议的那样,我的无符号长度不是64位长。谢谢!