Example using the JavaScript programming language. function xor_Encrypt(inputString, key) { let encrypted_Hex = ""; for (let i = 0; i "05") let hex = xor_Result.toString(16); if (hex.length 171) bytes.push(parseInt(hexa_Byte, 16)); } // Step 2: XOR each byte with the key and convert back to character for (let i = 0; i Another example using the
Python programming language. 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") A shorter example using the
R programming language, based on a puzzle posted on Instagram by
GCHQ. secret_key as.raw() secret_message charToRaw() |> xor(secret_key) |> base64enc::base64encode() secret_message_bytes base64enc::base64decode() xor(secret_message_bytes, secret_key) |> rawToChar() == See also ==