libmcrypt不可靠吗?

几天前,我在SO上提出了一个问题,没有任何有意义的答案。 贝娄简而言之:

我在C中有一个客户端服务器程序,用mcrypt C的库加密/解密数据。 客户端加密要发送到服务器的字符串,发送它,并在服务器读取后对其进行解密。 Bellow是我的加密和解密function:

加密function:

 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); } } 

解密function

 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速率)的情况。 任何人都可以建议我的问题出在哪里?

现在,当我遇到上述已经描述过的不良行为时,我设法抓住了一个场景。 贝娄是我的mainfunction:

 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); } 

Bellow是该mainfunction的输出:

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

问题:我做错了什么,或者图书馆有问题吗?

最后,我想出了问题的来源。 在main函数中,我有两行:

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

第一行是好的,只要s2是一个定义良好的char字符串。 但是在第二行中,如果生成的加密文本中包含'\0' ,则strlen(s2)可能会返回错误的结果。

我只想说@chrylis的评论给了我一个提示在哪里寻找问题的提示。

最后,根据经验,我会说: C ,你不得在加密文本上使用STRING的function。

感谢大家的帮助!