【问题标题】:Is libmcrypt not reliable?libmcrypt 不可靠吗?
【发布时间】:2013-08-13 12:42:08
【问题描述】:

几天前我在SO上提出了一个问题,没有任何有意义的答案。下面是简短的:

我有一个 C 语言的客户端服务器程序,它使用 mcrypt C 的库加密/解密数据。客户端对要发送给服务器的字符串进行加密,发送,服务器读取后解密。下面是我的加密和解密功能:

加密功能:

void encrypt(char *es, char *key, char *civ, size_t  length) {

    MCRYPT td;
    int n;

    td = mcrypt_module_open(MCRYPT_TWOFISH, NULL, MCRYPT_CFB, NULL );
    if (td == MCRYPT_FAILED) {
        log_err(log_opts, strerror(errno));
        exit(1);
    }
    n = mcrypt_enc_get_iv_size(td);

    char iv[n + 1];
    strncpy(iv, civ, n);
    iv[n] = '\0';

    if ((mcrypt_generic_init(td, key, KEY_SIZE, iv)) < 0) {
        log_err(log_opts, "while trying to do mcrypt_generic_init.");
        exit(1);
    }
    mcrypt_generic(td, es, length);

    if (mcrypt_module_close(td) < 0) {
        log_err(log_opts, "while trying to close module.");
        exit(1);
    }

}

解密函数

void decrypt(char *ds, char *key, char *civ, size_t length) {
    MCRYPT td;
    int n;

    td = mcrypt_module_open(MCRYPT_TWOFISH, NULL, MCRYPT_CFB, NULL );
    n = mcrypt_enc_get_iv_size(td);

    char iv[n + 1];
    strncpy(iv, civ, n);
    iv[n] = '\0';

    if ((mcrypt_generic_init(td, key, KEY_SIZE, iv)) < 0) {
        log_err(log_opts, "trying to do mcrypt_generic_init.");
        exit(1);
    }

    mdecrypt_generic(td, ds, length);
    if (mcrypt_module_close(td) < 0) {
        log_err(log_opts, "while trying to close module.");
        exit(1);
    }

}

我的问题:

在服务器端解密但在客户端加密的字符串与原始字符串不同的情况下(1 到 10 倍率)。谁能建议我的问题出在哪里?

现在,当我遇到我已经描述的上述不良行为时,我设法捕捉到了一个场景。 Bellow 是我的main 函数:

int main(void) {

    char *newKey = "P1adEfRuPX0AP2UDmSWHhgS6DaIrE4eb5EEJudC";
    char *iv = "asdfkSSDFAEGasld3G9dkDF0";
    char *s1 = "XZH9ZYKQC9*NYSR6UDUII";
    char *s2 = malloc(STRING_SIZE * sizeof(char));

    strcpy(s2, s1);
    printf("%s - %s\n", s1, s2);

    encrypt(s2, newKey, iv, strlen(s2));
    decrypt(s2, newKey, iv, strlen(s2));

    if (strncmp(s1, s2, STRING_SIZE) != 0)
        printf("wrong encrypt-decrypt: %s %s\n", s1, s2);

    exit(0);

}

下面是 main 函数的输出:

XZH9ZYKQC9*NYSR6UDUII - XZH9ZYKQC9*NYSR6UDUII
wrong encrypt-decrypt: XZH9ZYKQC9*NYSR6UDUII XZH9ZYKQC

问题: 是我做错了什么,还是那个库有问题?

【问题讨论】:

  • 什么是STRING_SIZE
  • @ouah STRING_SIZE 是 40。
  • 还有KEY_SIZE?您的程序不完整,请提供所有缺失的信息。
  • @ouah KEY_SIZE 是 16。
  • 我会注意到在加密密钥、IV 和密文等原始二进制数据上使用strncpy 是一个错误;这些可能完全合法地包含'\0'。请改用memcpy。不过,我认为这不是造成问题的原因。

标签: c mcrypt reliability


【解决方案1】:

最后,我弄清楚问题出在哪里。 在main 函数中,我有两行:

encrypt(s2, newKey, iv, strlen(s2));
decrypt(s2, newKey, iv, strlen(s2));

第一行没问题,只要 s2 是明确定义的字符串char。但在第二行中,如果结果加密文本中包含'\0'strlen(s2) 会返回错误结果。

我只想说@chrylis 的评论给了我在哪里搜索问题的提示。

最后,根据经验,我会说:C,您不得在加密文本上使用字符串函数。

感谢大家的帮助!

【讨论】:

  • 更准确地说,你不能在不符合 C 对“字符串”定义的事物上使用字符串函数。 (例如,是的,加密过程的任意输出。)
猜你喜欢
  • 1970-01-01
  • 2012-03-05
  • 2013-01-18
  • 2011-08-26
  • 2011-01-08
  • 2021-04-02
  • 1970-01-01
  • 2013-08-03
相关资源
最近更新 更多