rot

Enables you to easily encrypt and decrypt from one alphabet to another, while being agnostinc and letting you define the translations.. it gives you the flexibility to use it for and with anything.

require 'rubygems'
require 'rot'

rot13_mappings = {"6"=>"6",
  "V"=>"I",
  "K"=>"X",
  "v"=>"i",
  "k"=>"x",
  "7"=>"7",
  "W"=>"J",
  "L"=>"Y",
  "A"=>"N",
  "w"=>"j",
  "l"=>"y",
  "a"=>"n",
  "8"=>"8",
  "X"=>"K",
  "M"=>"Z",
  "B"=>"O",
  "x"=>"k",
  "m"=>"z",
  "b"=>"o",
  "9"=>"9",
  "Y"=>"L",
  "N"=>"A",
  "C"=>"P",
  "y"=>"l",
  "n"=>"a",
  "c"=>"p",
  "Z"=>"M",
  "O"=>"B",
  "D"=>"Q",
  "z"=>"m",
  "o"=>"b",
  "d"=>"q",
  "P"=>"C",
  "E"=>"R",
  "p"=>"c",
  "e"=>"r",
  "1"=>"1",
  "Q"=>"D",
  "F"=>"S",
  "q"=>"d",
  "f"=>"s",
  "2"=>"2",
  "R"=>"E",
  "G"=>"T",
  "r"=>"e",
  "g"=>"t",
  "3"=>"3",
  "S"=>"F",
  "H"=>"U",
  "s"=>"f",
  "h"=>"u",
  "4"=>"4",
  "T"=>"G",
  "I"=>"V",
  "t"=>"g",
  "i"=>"v",
  "5"=>"5",
  "U"=>"H",
  "J"=>"W",
  "u"=>"h",
  "j"=>"w",
  " "=>" "
}

# Handle unknown chars like this.
unknown = '?'

# this defines how chars should be parsed
encryption_tokenizer, decryption_tokenizer = /./, /./

rot = Rot.new rot13_mappings, unknown, encryption_tokenizer, decryption_tokenizer

puts rot.encrypt('This is a rot13 string') #=> "Guvf vf n ebg13 fgevat"
puts rot.decrypt('Guvf vf n ebg13 fgevat') #=> "This is a rot13 string"

# Now lets do a different thing!

mappings = {
 '#' => 'd',
 '!' => 'i',
 '7' => 'f',
 '"' => 'e',
 '%' => 'r',
 '&' => 'n',
 '=' => 't',
}

rot.mappings = mappings

puts rot.encrypt('different') #=> '#!77"%"&='
puts rot.decrypt('#!77"%"&=') #=> 'different'

# Now something complex
complex = {
 '<img src="d.jpg"/>'     => 'd',
 '<img src="i.jpg"/>'     => 'i',
 '<img src="f.jpg"/>'     => 'f',
 '<img src="e.jpg"/>'     => 'e',
 '<img src="r.jpg"/>'     => 'r',
 '<img src="n.jpg"/>'     => 'n',
 '<img src="t.jpg"/>'     => 't',
 '<img src="T.jpg"/>'     => 'T',
 '<img src="h.jpg"/>'     => 'h',
 '<img src="space.jpg"/>' => ' ',
 '<img src="dot.jpg"/>'   => '.',
}

rot.mappings = complex
rot.encryption_tokenizer = /./
rot.decryption_tokenizer = /<[^\>]+>/

puts rot.encrypt('different')
# => <img src="d.jpg"/><img src="i.jpg"/><img src="f.jpg"/><img src="f.jpg"/><img src="e.jpg"/><img src="r.jpg"/><img src="e.jpg"/><img src="n.jpg"/><img src="t.jpg"/>

puts rot.decrypt('<img src="T.jpg"/><img src="h.jpg"/><img src="e.jpg"/><img src="space.jpg"/><img src="e.jpg"/><img src="n.jpg"/><img src="d.jpg"/><img src="dot.jpg"/>')
# => The end.

Copyright © 2011 kazuyoshi tlacaelel. See LICENSE for details.