c - 尝试生成线性近似表。输出中的值不正确

标签 c algorithm encryption cryptography des

这里是c语言给出的代码,s盒表为{0xE, 0x4, 0xD, 0x1, 0x2, 0xF, 0xB, 0x8, 0x3, 0xA, 0x6, 0xC, 0x5, 0x9, 0x0, 0x7 };,当我们运行这段代码时,我们得到了错误的输出。我们应该从这段代码中得到线性近似表。我认为我得到的错误是在 sbox 输出部分。

#include <stdio.h>
#include <stdlib.h>
typedef unsigned short int UINT16; 

UINT16  sbox_table[16] =  {0xE, 0x4, 0xD, 0x1, 0x2, 0xF, 0xB, 0x8, 0x3, 0xA, 0x6, 0xC, 0x5, 0x9, 0x0, 0x7}; 

int lin_appr_table[16][16];


void construct_lin_appr_table()
{
    UINT16 i, j, k;

    UINT16 X, Y, x;
    UINT16 X_xor, Y_xor;
    int counter;

    for (i=0 ; i<16 ; i++)//sbox input
    {
        
        for (j=0 ; j<16 ; j++)//sbox output
        {
            X=i;
            Y=j;
            
            counter=0;
            for (k=0;k<16;k++)
            {
              X_xor=X&k;
              Y_xor=Y&sbox_table[k];
              
              if(X_xor^Y_xor==0) counter++;
              
             
            }
            
            lin_appr_table[i][j]=counter-8;
            
            //Write the code that makes up the table

        }

    }

    //Write the code that printed the table on the screen
    
    
    for (i=0 ; i<16 ; i++)//sbox input
    {
        for (j=0 ; j<16 ; j++)//sbox output
        {
            printf("% d ", lin_appr_table[i][j]);
        }
        printf("\n");
    }
}  

int main()
{
    construct_lin_appr_table();
    
    getch();
    return 0;
}

预期输出: enter image description here

最佳答案

建议进行以下两项更改以生成下表:

      //if(X_xor^Y_xor==0) counter++;
      if((X_xor^Y_xor)==0) counter++;

注意:对于上述语句,打开警告应该会导致类似于以下内容的结果:

36, 19    warning: ^ has lower precedence than ==; == will be evaluated first   
      //X_xor=X&k;
      X_xor = X & (1 << k); //credit to Weather Vane in comments

结果如下表:

enter image description here

旁白:通常来说,在声明期间以及使用之前初始化变量也是一个好主意。例如:

int lin_appr_table[16][16] = {{0}};//initializes all locations to 0

如果可以的话,选择使用可移植 non-portable代码:

    getchar(); //portable
    //getch(); //not portable

关于c - 尝试生成线性近似表。输出中的值不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65330769/

相关文章:

c - 在位操作中使用 'char' 变量

c++ - OpenCV 错误 : Sizes of input arguments do not match (The operation is neither 'array op array' )

algorithm - 三面骰子的隐马尔可夫模型

sql-server - 将 VARBINARY 的字符串表示形式转换为 VARBINARY 值

c - 算术规则是否适用于 C 中的加法?

algorithm - 如果减少一条边的权重,则更新最短路径距离矩阵

algorithm - 如何对 n 元 Haskell 树的元素求和?

bash - 加密/解密存储在配置文件中的密码

php - 在 session 中存储密码是否安全?

c - 如何使用netlink进行IPC?