artaxerxe - 2013-08-08

Hello everyone!

I have a client server program in C that encrypts/decrypts data with libmcrypt. The client encrypts the string that wants to send to server, send it, and after the server reads, it decrypts. Bellow are my encrypt and decrypt functions:

encrypt function:

void encrypt(char es, char key, char *civ, size_t length) {//es - string to encrypt, length - the length of es

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

}

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

}

My problem:

There are cases when a string encrypted does not get the previous result when decrypted. Can anyone suggest my where the problem can come from?

Thanks in advance!