0

我有一个程序,它将输入数据作为明文,然后在 CBC 模式下使用 3DES 方法解密消息。但是这些值在程序中是硬编码的,我想自己提供应该解密的加密值。如何在以下程序中执行此操作?

int main(void)
{
    unsigned char in[BUFSIZE], out[BUFSIZE], back[BUFSIZE];
    unsigned char *e = out;
    int len;

    DES_cblock key;
    DES_cblock seed = {0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10};
    DES_cblock ivsetup = {0xE1, 0xE2, 0xE3, 0xD4, 0xD5, 0xC6, 0xC7, 0xA8};
    DES_key_schedule keysched;
    DES_cblock ivec;

    memset(in, 0, sizeof(in));
    memset(out, 0, sizeof(out));
    memset(back, 0, sizeof(back));

    RAND_seed(seed, sizeof(DES_cblock));

    DES_random_key(&key);
    DES_set_odd_parity(&key);
    if (DES_set_key_checked((C_Block *)key, &keysched))
    {
        fprintf(stderr, "ERROR: Unable to set key schedule\n");
        exit(1);
    }

    /* 64 bytes of plaintext */

    /* From here, encryption starts for the plaintext below. */

    strcpy(in, "Now is the time for all men to stand up and be counted");

    printf("Plaintext: [%s]\n", in);

    len = strlen(in);
    memcpy(ivec, ivsetup, sizeof(ivsetup));
    DES_ncbc_encrypt(in, out, len, &keysched, &ivec, DES_ENCRYPT);

    printf("Ciphertext:");
    while (*e) printf(" [%02x]", *e++);
    printf("\n");

    /* Till here, encryption is over. After this we have to decrypt
     * the value which has been encoded, but I want to remove all this
     * part and to provide my own encrypted message, and get the
     * proper output.
     */

    memcpy(ivec, ivsetup, sizeof(ivsetup));

    /* The problem I am facing is how to provide the value properly
     * to the parameter "out" and "keysched", which should be of my
     * choice. For "out" I want to provide THIS value:
     * "2DC39619B4450A8C27A3976C50DE5799".
     */

    DES_ncbc_encrypt(out, back, len, &keysched, &ivec, DES_DECRYPT);

    printf("Decrypted Text: [%s]\n", back);

    exit(0);
}

阅读更多:http ://blog.fpmurphy.com/2010/04/openssl-des-api.html#ixzz1uqOp1Yhv

4

4 回答 4

2

阅读C 常见问题解答 20.10。十六进制是一种表示。所有数字都在内部以二进制形式存储。你DES_cblock可能是typedef一个(无符号,也许!)整数类型。所以,你实际上是一个整数数组。你可以用十进制、十六进制或二进制输入数字——但它们都可以。十六进制通常用于密码学,因为它具有一些符号优势。

于 2012-05-14T12:18:33.750 回答
1

我搞定了。我暂时以一种幼稚的方式做到了这一点,但它现在正在发挥作用。我是这样做的。

out[0]=0xA0; out[1]=0x69; out[2]=0x57; out[3]=0x3B;
out[4]=0x70; out[5]=0x26; out[6]=0x1C; out[7]=0xE8;
out[8]=0xEF; out[9]=0xF2; out[10]=0x9F;out[11]=0x60;
out[12]=0x80;out[13]=0x60;out[14]=0xB2;out[15]=0xE5;

稍后我将在 for 循环中执行此操作。

于 2012-05-15T10:07:40.643 回答
0

使用将值存储为字符串的非标准itoa函数,您可以执行以下操作:

char* hexstr = itoa(back,16); 

// print out a string
printf("Decrypted Text: [%X]\n", back);
于 2012-05-14T12:14:12.797 回答
0

像这样创建一个转储函数:

hexdump(char *buff, int len) { 
  int i,tmp;
  for(i=0; i < len; i++) {
    tmp = buff[i] & 0xff; /** to avoid sign extension */
    printf("%02x",tmp);
  }
} 

并使用它。

hexdump(back,len);

如果必须在内存中写入,可以使用 sprintf,但可能需要自己编写二进制转十六进制函数。

于 2012-05-14T12:15:38.900 回答