-->

是libmcrypt不可靠?(Is libmcrypt not reliable?)

2019-10-18 11:42发布

前几天我提出一个问题上的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速率)当一个字符串解密在服务器端,但在客户端加密是不一样的样原。 任何人都可以提出我的问题出在哪里可以从何而来?

现在,我设法抓住当我收到我已经描述的上述不良行为的情况。 贝娄是我的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

问:我是不是做错了什么,或者是该库有问题?

Answer 1:

最后,我想问题出在哪里得来的。 在main函数中,我有两条线路:

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

第一行是确定的,只要S2是良好限定的串char 。 但在第二行, strlen(s2)可以,如果导致加密文本包含返回错误结果'\0'的在它。

我只想说,@chrylis'评论给我提示到哪里寻找问题。

最后,作为一个经验法则,我会说:IN C ,你不能使用STRING的函数对加密的文本。

感谢所有的援助!



文章来源: Is libmcrypt not reliable?