The line makes some function calls and an "xor" operation, using the operator ^
- and concatenates the result into a string he calls "xored".
we can unfold in parts to make it easier to understand:
xored += chr(ord(key[posiçãoDoChar%len(key)]) ^ ord(char))
is the same as:
posicao_da_letra_da_chave = posicaoDoChar % len(key)
# O "modulo" - "%" é o resto da divisão -entao
# se sua chave tem 4 letras, quando
# estiver na letra "5", 5%4 vale 1:
# a letra na posicao "1" da chave é reutilizada, e assim por diante.
letra_da_chave = key[posicao_da_letra_da_chave]
codigo_numerico_da_letra_da_chave = ord(letra_da_chave) # converte o caractere em seu código numérico UNICODE (se for um caractere ASCII, isso é equivalente ao código ASCII)
codigo_numerico_da_letra_da_mensagem = ord(char)
codigo_numerico_cifrado = codigo_numerico_da_letra_da_chave ^ codigo_numerico_da_letra_da_mensagem # Operação de transformação reversível usando 'xor'
nova_letra = chr(codigo_numerico_cifrado)
xored += nova_letra # contatena a nova letra na mensagem cifrada final
So, in fact, when we unfold, only that line makes 8 distinct operations.
The key of the process is the "xor", made with the operator " ": this is an operation made
bit by bit between the two values: if one of the two values is "1" and the other "0" the result is "1". If the two values are equal, the result is "0". This operation has an interesting property that it is reversible: if I make a "xor" of an X number that I have, with a Y number, the result is a different number "Z". If I take back Z with Y, the result is "X" - which is why this algorithm can retrieve the original message - in decryption, each encrypted character will undergo an xor with the same letter as the key with which it was "scanned" in the encryption operation.
Here the XOR working with numerical variables:
In [10]: x = 43254
In [11]: y = 64636
In [12]: z = x ^ y
In [13]: z
Out[13]: 21642
In [14]: y ^ z
Out[14]: 43254
In [15]: y ^ z == x
Out[15]: True
And again, but this time using the prefix 0b
and the call bin
to visualize the process by seeing the numbers in binary:
In [16]: x = 0b11110000
In [17]: y = 0b10101010
In [18]: z = x ^ y
In [19]: bin(z)
Out[19]: '0b1011010'
In [20]: bin(z ^ y)
Out[20]: '0b11110000'
Your question seems to have some problems and your experience here in Stack Overflow may not be the best because of it. We want you to do well here and get what you want, but for that we need you to do your part. Here are some guidelines that will help you: Stack Overflow Survival Guide in English (short version). If the solution is very simple it is still possible for someone to do so in the comments.
– Artur Brasil
@Arturbrasil - the question is good. It’s not "perfect"- there’s no way someone coming in the first time asking a question "perfect"- but there’s a question that’s well described and answers. Improvement advice and edits are cool things. Negative votes and closing the question do not make sense.
– jsbueno