几天前我在SO上提出了一个问题,没有任何有意义的答案。下面是简短的:
我在 C 中有一个客户端服务器程序,它使用 mcryptC
的库加密/解密数据。客户端加密想要发送到服务器的字符串,发送它,服务器读取后,解密它。下面是我的加密和解密功能:
加密功能:
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
问题: 我做错了什么,还是那个图书馆有问题?