DES算法中Sbox的C代码

时间:2015-01-06 19:20:08

标签: c des

如何用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);
}
)

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

1 个答案:

答案 0 :(得分: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
sbox1

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]返回正确的输出,已经线性索引。

这就是说,假设你为八个盒子制作了独特的桌子,那就不值得编写一个函数来调用直接查找表格。