如何用C语言为DES实现s-box?
我想使用数组形式创建查找表作为替代表。然后调用该函数

我使用的代码是:-

#include<stdio.h>
#include<stdint.h>
int main()
{
uint32_t x,y,a,b,c,p,q;
int mask1=1;
int mask2=32;
printf("enter any no.:",x);
scanf("%d",&x);
y=x&mask1;
printf("y=%d\n",y);
a=x&mask2;
printf("a=%d\n",a);
b=a>>4;
printf("b=%d\n",b);
c=y|b;
printf("row no :%d\n",c);
int mask3=0x1E;
p=x&mask3;
printf("p=%d\n",p);
q=p>>1;
printf("column no: %d\n",q);
static const uint32_t s[4][16] =
{
  14,  0,  4, 15, 13,  7,  1,  4,  2, 14, 15,  2, 11, 13,  8,  1,
   3, 10, 10,  6,  6, 12, 12, 11,  5,  9,  9,  5,  0,  3,  7,  8,
   4, 15,  1, 12, 14,  8,  8,  2, 13,  4,  6,  9,  2,  1, 11,  7,
  15,  5, 12, 11,  9,  3,  7, 14,  3, 10, 10,  0,  5,  6,  0, 13};
int i,j;
{
printf("SBox subsequent value[%d][%d]=%d\n",c,q,s[c][q]);
}
return(0);
}
)


现在我想将整个过程缩短一行,并通过引用调用该函数。请帮忙。

最佳答案

您可以将程序转换为函数:

#include <stdint.h>
#define BIT(x)  ((1 << x))
int sbox(int x) {
    static const uint32_t s[4][16] = {
      14,  0,  4, 15, 13,  7,  1,  4,  2, 14, 15,  2, 11, 13,  8,  1,
       3, 10, 10,  6,  6, 12, 12, 11,  5,  9,  9,  5,  0,  3,  7,  8,
       4, 15,  1, 12, 14,  8,  8,  2, 13,  4,  6,  9,  2,  1, 11,  7,
      15,  5, 12, 11,  9,  3,  7, 14,  3, 10, 10,  0,  5,  6,  0, 13
    };
    return (s[ (( x & BIT(5))?2:0) | ( x & BIT(0) ) ]   // c
            [(x >> 1) & 0xf]);                          // q
}


但是程序中存在一个缺陷,即索引机制与表组织不匹配。

我可以采用原始的sbox1代码:

#include <stdint.h>
static const uint32_t sbox1[64] = {
    14, 4,13, 1, 2,15,11, 8, 3,10, 6,12, 5, 9, 0, 7,
     0,15, 7, 4,14, 2,13, 1,10, 6,12,11, 9, 5, 3, 8,
     4, 1,14, 8,13, 6, 2,11,15,12, 9, 7, 3,10, 5, 0,
    15,12, 8, 2, 4, 9, 1, 7, 5,11, 3,14,10, 0, 6,13
};
#define BIT(x)  (1 << x)
#include <stdio.h>

int main() {
    int i;
    printf("    static const uint32_t s[64] = {\n");
    for (i = 0; i < 64; i++) {
        if ((i & 15 ) == 0)
            printf("       ");
        printf ("%3d%c",
            sbox1[(( i & BIT(5))?32:0) | ( i & BIT(0)?16:0 ) |
              ((i >> 1) & 0xf)],
              (i < 63)?',':' ');
        if ((i & 15) == 15)
            printf("\n");
    }
    printf("    };\n");
    return (0);
}


并生成您的表:

cc sbox1.c -o sbox1
邮箱1

static const uint32_t s[64] = {
    14,  0,  4, 15, 13,  7,  1,  4,  2, 14, 15,  2, 11, 13,  8,  1,
     3, 10, 10,  6,  6, 12, 12, 11,  5,  9,  9,  5,  0,  3,  7,  8,
     4, 15,  1, 12, 14,  8,  8,  2, 13,  4,  6,  9,  2,  1, 11,  7,
    15,  5, 12, 11,  9,  3,  7, 14,  3, 10, 10,  0,  5,  6,  0, 13
};


这里的好处是您的表行上有重复的值,这在DES标准中是不会发生的。

因此,小程序sbox1也证明了sbox已被线性索引,这意味着我在程序中需要做的就是s[x]返回已经线性索引的正确输出。

也就是说,假设您为八个方框创建了唯一的表,则不值得编写仅调用直接表查找的函数。

09-25 21:23