The XOR Cipher in PowerShell

DISCLAIMER: This is presented for educational purposes only. It is not intended for use as production cryptography. The example here is not secure and is vulnerable to multiple attacks.

Inspired by my son’s recent interest in ciphers, I decided to write a basic XOR cipher in PowerShell. Given your plaintext and key, the script returns the ciphertext.

What does it do?
The plaintext and the key are strings. If the key is shorter then the plaintext, then we repeat the key until it’s as long as the plaintext. A string is made up of bytes. And bytes are made up bits. For each bit in the plaintext, we do an Exclusive Or (XOR) Operation with the coresponding bit in the repeated key. The result is stored in the ciphertext.

What is Exclusive Or?

Exclusive Or is an operation that outputs TRUE when the inputs differ.
For example:

Plaintext  01010000
Key        01101011
Ciphertext 00111011

A nice feature of XOR is that it is easly reversable. If we XOR the key with the ciphertext, we get the plaintext back.

The code:

function encode($plaintext, $key)
    $cyphertext = ""
    $keyposition = 0
    $KeyArray = $key.ToCharArray()
    $plaintext.ToCharArray() | foreach-object -process {
        $cyphertext += [char]([byte][char]$_ -bxor $KeyArray[$keyposition])
        $keyposition += 1
        if ($keyposition -eq $key.Length) {$keyposition = 0}
    return $cyphertext