XOR cipher

In cryptography, the simple XOR cipher is a type of additive cipher,[1] an encryption algorithm that operates according to the principles:

A 0 = A,
A A = 0,
(A B) C = A (B C),
(B A) A = B 0 = B,

where denotes the exclusive disjunction (XOR) operation. This operation is sometimes called modulus 2 addition (or subtraction, which is identical).[2] With this logic, a string of text can be encrypted by applying the bitwise XOR operator to every character using a given key. To decrypt the output, merely reapplying the XOR function with the key will remove the cipher.

Example

For example, the string "Wiki" (01010111 01101001 01101011 01101001 in 8-bit ASCII) can be encrypted with the repeating key 11110011 as follows:

01010111 01101001 01101011 01101001
11110011 11110011 11110011 11110011
=10100100 10011010 10011000 10011010

And conversely, for decryption:

10100100 10011010 10011000 10011010
11110011 11110011 11110011 11110011
=01010111 01101001 01101011 01101001

Use and security

The XOR operator is extremely common as a component in more complex ciphers. By itself, using a constant repeating key, a simple XOR cipher can trivially be broken using frequency analysis. If the content of any message can be guessed or otherwise known then the key can be revealed. Its primary merit is that it is simple to implement, and that the XOR operation is computationally inexpensive. A simple repeating XOR (i.e. using the same key for xor operation on the whole data) cipher is therefore sometimes used for hiding information in cases where no particular security is required. The XOR cipher is often used in computer malware to make reverse engineering more difficult.

If the key is random and is at least as long as the message, the XOR cipher is much more secure than when there is key repetition within a message.[3] When the keystream is generated by a pseudo-random number generator, the result is a stream cipher. With a key that is truly random, the result is a one-time pad, which is unbreakable in theory.

In any of these ciphers, the XOR operator is vulnerable to a known-plaintext attack, since plaintext ciphertext = key. It is also trivial to flip arbitrary bits in the decrypted plaintext by manipulating the ciphertext. This is called malleability.

Example implementation

Example using the Python programming language.[4]

from __future__ import print_function, unicode_literals
from os import urandom


def genkey(length: int) -> bytes:
    """Generate key."""
    return urandom(length)
    

def xor_strings(s, t) -> bytes:
    """xor two strings together."""
    if isinstance(s, str):
        # Text strings contain single characters
        return b"".join(chr(ord(a) ^ ord(b)) for a, b in zip(s, t))
    else:
        # Python 3 bytes objects contain integer values in the range 0-255
        return bytes([a ^ b for a, b in zip(s, t)])
        

message = 'This is a secret message'
print('Message:', message)

key = genkey(len(message))
print('Key:', key)

cipherText = xor_strings(message.encode('utf8'), key)
print('cipherText:', cipherText)
print('decrypted:', xor_strings(cipherText, key).decode('utf8'))

# Verify
if xor_strings(cipherText, key).decode('utf8') == message:
    print('Unit test passed')
else:
    print('Unit test failed')
gollark: The hilarity of a joke is directly proportional to the square of its length, you know.
gollark: (note: I like Linux and this is a joke, do not potato me)
gollark: What do Linux users do to change a lightbulb?First, a user creates a bug report, only for it to be closed with "could not reproduce" as the developers got to it in the day. Eventually, some nights later, someone realizes that it is actually a problem, and decides to start work on a fix, soliciting the help of other people.Debates soon break out on the architecture of the new lightbulb - should they replace it with an incandescent bulb (since the bulb which broke was one of those), try and upgrade it to a halogen or LED bulb, which are technically superior if more complex. or go to a simpler and perhaps more reliable solution such as a fire?While an LED bulb is decided on, they eventually, after yet more debate, deem off-the-shelf bulbs unsuitable, and decide to make their own using commercially available LED modules. However, some of the group working on this are unhappy with this, and splinter off, trying to set up their own open semiconductor production operation to produce the LEDs.Despite delays introduced by feature creep, as it was decided halfway through to also add RGB capability and wireless control, the main group still manages to produce an early alpha, and tests it as a replacement for the original bulb. Unfortunately it stops working after a few days of use, and debugging of the system suggests that the problem is because of their power supply - the bulb needs complex, expensive, and somewhat easily damaged circuitry to convert the mains AC power into DC suitable for the LEDs, and they got that bit a bit wrong.So they decide to launch their own power grid and lighting fixture standard, which is, although incompatible with every other device, technically superior, and integrates high-speed networking so they can improve the control hardware. Having completely retrofitted the house the original lightbulb failed in and put all their designs and code up on GitHub, they deem the project a success, and after only a year!
gollark: Minetest is already a thing.
gollark: It really isn't.

See also

References

  1. Tutte 1998, p. 3
  2. Churchhouse 2002, p. 11
  3. Churchhouse 2002, p. 68
  4. This was inspired by Richter, Wolfgang (August 3, 2012), "Unbreakable Cryptography in 5 Minutes", Crossroads: The ACM Magazine for Students, Association for Computing Machinery

Bibliography

This article is issued from Wikipedia. The text is licensed under Creative Commons - Attribution - Sharealike. Additional terms may apply for the media files.