Question

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

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

}

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 + 1] = '\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 (1 to 10 rate) when a string decrypted on server side but encrypted on client side is not the same like original. Can anyone suggest my where the problem can come from?


EDIT

The response to this question, you can find here, where this issue is also detailed further, being pointed out the code that contains the bug.

Was it helpful?

Solution 2

The problem was that I used string functions on raw bytes array. Look at this link for more details.

OTHER TIPS

In decrypt function:

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

You have an off-by-one overflow in iv[n + 1] = '\0'; statement.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top