سؤال

I am trying to encrypt a plaintext string to ecncrypted string later to use it I am again revese-encrypting it. I am using arbitrary key manually and in most of the cases I am able to get plain string back. But specially if plain text is having "$" then encrypted text is not being re-encrypt(decrypt) to original;

char * xor(char * plain_text, char * key) {
    size_t plaintext_len = strlen(plain_text);
    size_t keylen = strlen(key);

    char * encrypted = malloc(plaintext_len+1);

    int i;
    for(i = 0; i < plaintext_len; i++) {
        encrypted[i] = plain_text[i] ^ key[i % keylen];
    }
    encrypted[plaintext_len] = '\0';

    return encrypted;
}

I am new to C and hence want to know why this '$' character is not being displayed back. OR Is there are any limititaion while selecting a plain text and key

Thanks

PS: now '$' is not the problem still want to know worst case for xor's fails

هل كانت مفيدة؟

المحلول

I think the fundamental problem you have here is that your encryption can produce a character array that contains '\0' characters. That character is then treated as the terminating character when you come to decrypt. What's more, why should your key be constrained not to contain '\0' characters?

To solve this you do need to get your functions to work with the lengths of the arrays. You cannot rely on strlen() to obtain the length. I suggest that you add extra parameters to the function to allow the caller to pass in the lengths of the two character arrays.

Your functions should also receive const char*. So I'd have it like this:

char *xor(
    const char *plain_text, size_t plaintext_len, 
    const char *key, size_t keylen
) 
{
    char *encrypted = malloc(plaintext_len+1);
    for(size_t i = 0; i < plaintext_len; i++) 
        encrypted[i] = plain_text[i] ^ key[i % keylen];
    encrypted[plaintext_len] = '\0';
    return encrypted;
}

It's plausible that the caller can use strlen() to calculate the lengths of the plain text and the key. But for the decrypt operation you must remember the length of the original plain text, and pass that to the function.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top