C 位操作 DES 排列

标签 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(不知何故,这是一半正确的,半破)。到底是怎么回事?如何解决这个问题?

最佳答案

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

关于C 位操作 DES 排列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34687924/

相关文章:

C : Converting all special char to the equivalent (é => e)

c - 倾斜磁力计输出 - 俯仰和滚动倾斜补偿 - 我迷路了

c++ - 当您将位移超出变量的末尾时会发生什么?

c - 如何从预处理器启用内在函数

c - 用 C 中以秒为单位的时钟测量执行时间不起作用

c - 我无法将函数返回的字符数组作为另一个函数的参数传递

python - 以十六进制形式显示而不是特殊字符

security - RSA:使用多个 key 加密消息

c - 在 c 中预先计算 AES256 加密的 "buffer"的大小

c - 高效计算三个无符号整数的平均值(无溢出)