Home > Net >  Is there a way to prevent XOR encryption from becoming zero?
Is there a way to prevent XOR encryption from becoming zero?

Time:08-19

I want to encrypt data by XOR bit operation when socket communication

For example, if the key is "encrypt" and the data is "connect", then t will be 0 and the data will not be encrypted and decrypted correctly. Also, if the data and key values are the same in the middle, it becomes 0 and ends the function as it is. (data:connection, key:encrypt -> recv data is only connec)

How can I modify the function I used to eliminate this phenomenon?

char Encryption(char strEncordeData[])
{
    memset(m_socket_comm.encrypt, 0, BUF_SIZE);

    m_socket_comm.keycount = 0;
    int length = strlen(strEncordeData);
    for (int i = 0; i < length; i  )
    {
        m_socket_comm.encrypt[i] = strEncordeData[i] ^ m_socket_comm.key[m_socket_comm.keycount];
        if (m_socket_comm.keycount == strlen(m_socket_comm.key))
        {
            m_socket_comm.keycount = 0;
        }
        m_socket_comm.keycount  ;
    }
    return *strEncordeData;
}

CodePudding user response:

All strlen does is search for the \0, so why not write your own version that checks if the byte is \0 after decryption? (Note that this requires encrypting the \0 terminator):

size_t cipherlen(const char *ciphertext, const char *key) {
    size_t idx, keylen = strlen(key);
    for (idx = 0; 1; idx  ) {
        if (0 == (ciphertext[idx] ^ key[idx % keylen])) break;
    }
    return idx;
}

Or better yet, don't even bother with strlen. Just keep decrypting until you hit the \0:

// encrypt in place
void encrypt(char *s, const char *key) {
    size_t keylen = strlen(key);
    for (size_t idx = 0; 1; idx  ) {
        // We encrypt the \0 before terminating the loop
        char c = s[idx];
        s[idx] ^= key[idx % keylen];
        if (!c) break;
    }
}

// decrypt in place
void decrypt(char *s, const char *key) {
    /* Note that we compute strlen(key) *once* instead of recalculating
       it every iteration. Doing it the other way requires repeatedly
       scanning over the full key and turns an O(n) algorithm into O(n)O(m).
    */
    size_t keylen = strlen(key);
    for (size_t idx = 0; 1; idx  ) {
        s[idx] ^= key[idx % keylen];
        if ('\0' == s[idx]) break;// We check the value *after* decryption.
    }
}

Although personally, I'd store the plaintext and key lengths separately rather than using strlen, so as to permit arrays of char that contain \0.

  •  Tags:  
  • c
  • Related