public
Created

Encryption Library

  • Download Gist
crypto.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
module SimpleCrypt
class Map
attr_accessor :letters
def initialize
@letters = ('a'..'z').to_a
@letters << "_"
@letters.shuffle!
end
end
class Cipher
def initialize(map)
@letters = map.letters
end
def mapping(type, character)
matches(@letters, type, character)
end
def matches(letters, type, character)
letters_copy = letters.dup
encrypt = Proc.new{|letter| "#{letter}#{character}#{letters_copy.shift}" }
decrypt = Proc.new{|letter| "#{letters_copy.shift}#{character}#{letter}" }
if type == "encrypt"
encrypt_map = ('a'..'z').to_a.map{ |letter| encrypt[letter] }
encrypt_map << "_#{character}#{letters_copy.shift}"
else
encrypt_map = ('a'..'z').to_a.map{ |letter| decrypt[letter] }.sort
encrypt_map << "#{letters_copy.shift}#{character}_"
end
end
end
class Encrypter < Cipher
def mapping
super('encrypt', @character)
end
def initialize(map, character = "=>")
super(map)
@character = character
end
end
class Decrypter < Cipher
def mapping
super('decrypt', @character)
end
def initialize(map, character = "=>")
super(map)
@character = character
end
end
end
 
map = SimpleCrypt::Map.new
encrypter = SimpleCrypt::Encrypter.new(map)
puts encrypter.mapping
puts ""
decrypter = SimpleCrypt::Decrypter.new(map)
puts decrypter.mapping

Example Output

a=>p
b=>k
c=>z
d=>w
e=>o
f=>q
g=>s
h=>a
i=>j
j=>c
k=>l
l=>u
m=>d
n=>x
o=>b
p=>m
q=>r
r=>e
s=>t
t=>g
u=>y
v=>_
w=>f
x=>v
y=>i
z=>n
_=>h

_=>v
a=>h
b=>o
c=>j
d=>m
e=>r
f=>w
g=>t
i=>y
j=>i
k=>b
l=>k
m=>p
n=>z
o=>e
p=>a
q=>f
r=>q
s=>g
t=>s
u=>l
v=>x
w=>d
x=>n
y=>u
z=>c
h=>_

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.