The key lines are the ord= and the tmp= lines. The first line converts the character returned by ${string:$index:1} into an ordinal number matching the ASCII chart. Note the use of the “‘…”” syntax. You need that leading single quote! The second line XORs the value of the ord variable with 90 and then converts the result back into a character.

This also works for ksh93 and should work for the zsh shell but I have not tested it.

March 15th, 2012

3 comments to Bash XOR A String

Line 7 should be: ciphertext=””
Otherwise the code does not work as written: if the plaintext contains letter Z (decimal 90), the letter is missing in the end.
For example:
Plaintext: aaZaa
Ciphertext: ;;;;
Plaintext: aaaa