Class: Cipher::Transposition
- Inherits:
-
SimpleCipher
- Object
- SimpleCipher
- Cipher::Transposition
- Defined in:
- lib/cipher.rb
Overview
Transposition
Plain Transposition aka transposition
Instance Method Summary (collapse)
-
- (Object) decode(cipher_text)
decode.
-
- (Object) encode(plain_text)
encode.
-
- (Transposition) initialize(key)
constructor
A new instance of Transposition.
Constructor Details
- (Transposition) initialize(key)
Returns a new instance of Transposition
20 21 22 |
# File 'lib/cipher.rb', line 20 def initialize(key) @key = Key::TKey.new(key) end |
Instance Method Details
- (Object) decode(cipher_text)
decode
51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 |
# File 'lib/cipher.rb', line 51 def decode(cipher_text) # # Look whether we are square or not # text = cipher_text.dup t_len = @key.length pad = text.length % t_len # # if pad is non-zero, last line is not finished by pad i.e. # columns pad-1 .. t_len-1 are shorter by 1 # t_height = (text.length / t_len) + 1 table = Array.new(t_len) { '' } plain_text = '' #puts "#{text.length} #{pad} #{t_height}" tkey = @key.to_numeric # # Fill in transposition board # for i in 0..(t_len - 1) do ind = tkey.index(i) how_many = t_height if ind > pad - 1 then how_many -= 1 end ct = text.slice!(0, how_many) table[ind] << ct #puts "#{ct} #{how_many} #{ind} #{i}" end # # Now take the plain text # for j in 0..(t_height - 1) do for i in 0..(t_len - 1) do col = table[i] plain_text << (col[j] || '') end end return plain_text end |
- (Object) encode(plain_text)
encode
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/cipher.rb', line 26 def encode(plain_text) # j = 0 t_len = @key.length table = Array.new(t_len) { '' } cipher_text = '' tkey = @key.to_numeric # # XXX String.scan in 1.9, #each_byte? # plain_text.scan(/./) do |pt| table[tkey[j]] << pt j = (j + 1) % t_len end # # Now take every column based upon key ordering # cipher_text = tkey.sort.each.inject('') do |text, t| text + table[t] end end |