在“C”程序中,如何在字符串变量中存储十六进制值?

时间:2012-05-14 12:08:52

标签: c encryption des

我有一个程序,它将输入数据作为明文,然后在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 个答案:

答案 0 :(得分:2)

阅读C FAQ 20.10。十六进制是一种表示。所有数字都以二进制内部存储。对于(无符号,可能是!)整数类型,DES_cblock可能是typedef。所以,你实际上是一个整数数组。您可以将数字放在十进制,十六进制或二进制中 - 但它们都可以工作。密码学中的Hexadecimal is typically used,因为它具有一些符号优势。

答案 1 :(得分: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循环中做这件事。

答案 2 :(得分:0)

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

char* hexstr = itoa(back,16); 

// print out a string
printf("Decrypted Text: [%X]\n", back);

答案 3 :(得分: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,但你可能必须编写自己的二进制到十六进制函数。