decrypt/encrypt xor algorithm in C

hadeel Kh

Here, I'm trying to encrypt a message using XOR. However, when I run the program, I'm getting weird output (random outputs). I guess I'm missing something here.

enter image description here

my sample of code:

/*
* Description: Decipher the message using XOR and print it.
* Parameters:
*   cipher: The cipher of the message (With the key embedded at the start)
*   keyLength: The length of the key at the start of the message
*Return:
*   None.
*Note:
    Do not use any additional variables for this challenge.
*/

void print_cipher_message(unsigned char cipher[], int keyLength) {
    // TODO: complete the function
    //keyLength = 3;
    for (int i = 0; i < strlen(cipher) && i <= keyLength; i++) {
        
            i % keyLength;
    
        cipher[i] = cipher[i] ^ keyLength;
      // i% keyLength;// i % ;//cipher[i] % sizeof(keyLength);
        
        printf("%c", cipher);
    }

}


int main() {
    
    unsigned char cipher[] = "\x12\x56\xd4\x61\x26\xbb\x7b\x3a\xbd\x7c\x31\xf4\x61\x3e\xbb\x65\x25\xf4\x7b\x25\xf4\x73\x76\x97\x40\x1f\x99\x57";
    int keyLength = 3;


    //print the cipher message
    print_cipher_message(cipher, keyLength);
    
    return 0;
}

The expecting result is as the following:

/*
    EXAMPLE:
    cipher="\x31\xf4\x61\x7a\x33\xb8\x7e\x39\xf4\x65\x39\xa6\x7e\x32\xf5\x33"
    keyLength=3;

    then the cipher is:
    "\x31\xf4\x61\x7a\x33\xb8\x7e\x39\xf4\x65\x39\xa6\x7e\x32\xf5\x33"
    ^----Key-----^^-------------------Message------------------------^

    */

I Would appreciate your help. Thank you.

Afshin

At first, you need to understand question correctly. Your question states that key is embedded at start of your cipher and its length is keyLength. So you need to separate this part and xor it with the rest of cipher.

Code should be similar to this:

void print_cipher_message(unsigned char cipher[], int keyLength) {
    for (int i = 0; i < strlen((char*)cipher) - keyLength; i++) {
        cipher[i + keyLength] = cipher[i + keyLength] ^ cipher[i % keyLength];
    }

    printf("%s", cipher + keyLength);
}

I wrote it off top of head quickly without debugging, so it may have bugs. In addition, question is not correct itself. it needs length of cipher and we cannot really use strlen() for it.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related