【问题标题】:AES128/CBC test not workingAES128/CBC 测试不工作
【发布时间】:2013-01-03 21:56:35
【问题描述】:

这是我的代码(为了代码的可读性,故意省略了错误检查):

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <gcrypt.h>

#define GCRYPT_VERSION "1.5.0"
#define GCRY_CIPHER GCRY_CIPHER_AES128

int main(void){
    if(!gcry_check_version(GCRYPT_VERSION)){
        fputs("libgcrypt version mismatch\n", stderr);
        exit(2);
    }
    gcry_control(GCRYCTL_SUSPEND_SECMEM_WARN);
    gcry_control(GCRYCTL_INIT_SECMEM, 16384, 0);
    gcry_control(GCRYCTL_RESUME_SECMEM_WARN);
    gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);

    int algo = -1;
    size_t i;
    const char *name = "aes128";
    char plain_text[16] = {0x80};
    char key[16] = {0};
    char iniVector[16] = {0};
    size_t txtLenght = strlen(plain_text);
    char *encBuffer = malloc(txtLenght);
    gcry_cipher_hd_t hd;
    algo = gcry_cipher_map_name(name);
    size_t blkLength = gcry_cipher_get_algo_blklen(GCRY_CIPHER);
    size_t keyLength = gcry_cipher_get_algo_keylen(GCRY_CIPHER);

    gcry_cipher_open(&hd, algo, GCRY_CIPHER_MODE_CBC, 0);
    gcry_cipher_setkey(hd, key, keyLength);
    gcry_cipher_setiv(hd, iniVector, blkLength);
    gcry_cipher_encrypt(hd, encBuffer, txtLenght, plain_text, txtLenght);

    printf("encBuffer = ");
    for(i = 0; i < txtLenght; i++){
        printf("%02x", (unsigned char) encBuffer[i]);
    }
    printf("\n");

    gcry_cipher_close(hd);
    free(encBuffer);
    return 0;
}

预期结果:
KEY = 00000000000000000000000000000000
IV = 00000000000000000000000000000000
明文 = 80000000000000000000000000000000
密文 = 3ad78e726c1ec02b7ebfe92b23d9ec34

我的结果:
KEY = 00000000000000000000000000000000
IV = 00000000000000000000000000000000
明文 = 80000000000000000000000000000000
密文 = 42

为什么我得到这个输出?我做错了什么?

【问题讨论】:

  • 您确定要包含结尾的空字符:size_t txtLenght = strlen(plain_text)+1; `?
  • 天哪!你是对的!我已经更新了我的代码!
  • 现在您确定您的纯文本、密钥和 iv 必须是 ascii 而不是十六进制?
  • 我想过这个,但我不知道如何声明“十六进制数据类型”...
  • 只需使用char *plain_text = "\x80\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00" 等等。

标签: c aes libgcrypt


【解决方案1】:

您使用的是 ASCII 值,但 AES 测试向量以十六进制值给出。

尝试使用十六进制值(数组的其余值由 C 中的 0 初始化):

char plain_text[16] = {0x80}; 
char key[16] = {0};
char iniVector[16] = {0};

size_t txtLenght =  sizeof plain_text;

【讨论】:

  • 你也必须更改txtLength
猜你喜欢
  • 2011-12-10
  • 1970-01-01
  • 2014-01-27
  • 2020-03-29
  • 1970-01-01
  • 1970-01-01
  • 2014-07-07
  • 2018-04-01
  • 2016-07-14
相关资源
最近更新 更多