Atbash Cipher Helper

Atbash is a mono-alphabetic substitution cipher originally used to encode the Hebrew alphabet. It can be modified for use with any known alphabet. Use: It works by substituting the first letter of an alphabet for the last letter, the second letter for the second to last and so on, effectively reversing the alphabet. An Atbash cipher for the Latin alphabet would be as follows: Examples: A few English words also 'Atbash' into other English words: "irk"="rip", "low"="old", "hob"="sly", "hold"="slow", "holy"="slob", "horn"="slim", "glow"="told", "grog"="tilt" and "zoo"="all". Some other English words 'Atbash' into their own reverses, e.g., "wizard" = "draziw."



									class AtbashCipher {
	private $abt;
	private $rev_abt;
	
	public function __construct($abt) {
		$this->abt = $abt;
		$this->rev_abt = strrev($abt);
	}
	
	public function encode($s) {
		$res='';
		foreach(str_split($s) as $char)
			$res .= $this->switchChar($char);
		return $res; 
	}
	
	public function decode($s) {
		return $this->encode($s);
	}
	
	private function switchChar($char) {
		$pos = strpos($this->abt, $char);
		if($pos !== false)
			return $this->rev_abt[$pos]; 
		return $char; 
	}
}
								


Example

									$text = "abcdefghijklmnopqrstuvwxyz";
$cipher = new AtbashCipher($text);
$cipherText = $cipher->encode($text);
$plainText = $cipher->decode($cipherText);
								


Output

									cipherText:	zyxwvutsrqponmlkjihgfedcba
plainText:	abcdefghijklmnopqrstuvwxyz
								

Vitaly Kopytich