Open main menu
Home
Random
Recent changes
Special pages
Community portal
Preferences
About Wikipedia
Disclaimers
Incubator escapee wiki
Search
User menu
Talk
Dark mode
Contributions
Create account
Log in
Editing
XOR cipher
(section)
Warning:
You are not logged in. Your IP address will be publicly visible if you make any edits. If you
log in
or
create an account
, your edits will be attributed to your username, along with other benefits.
Anti-spam check. Do
not
fill this in!
==Example implementation== Example using the [[Python (programming language)|Python]] programming language.{{efn|name=inspired}} <syntaxhighlight lang="python"> from os import urandom def generate_key(length: int) -> bytes: """Generate encryption key.""" return urandom(length) def xor_strings(s, t) -> bytes: """Concatenate xor two strings together.""" if isinstance(s, str): # Text strings contain single characters return "".join(chr(ord(a) ^ b) for a, b in zip(s, t)).encode("utf8") else: # 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 = generate_key(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") </syntaxhighlight> A shorter example using the [[R (programming language)|R]] programming language, based on a [https://www.instagram.com/p/CfcTwYYlnC9/ puzzle] posted on Instagram by [[GCHQ]]. <syntaxhighlight lang="R"> secret_key <- c(0xc6, 0xb5, 0xca, 0x01) |> as.raw() secret_message <- "I <3 Wikipedia" |> charToRaw() |> xor(secret_key) |> base64enc::base64encode() secret_message_bytes <- secret_message |> base64enc::base64decode() xor(secret_message_bytes, secret_key) |> rawToChar() </syntaxhighlight>
Edit summary
(Briefly describe your changes)
By publishing changes, you agree to the
Terms of Use
, and you irrevocably agree to release your contribution under the
CC BY-SA 4.0 License
and the
GFDL
. You agree that a hyperlink or URL is sufficient attribution under the Creative Commons license.
Cancel
Editing help
(opens in new window)