Class: Cipher::StraddlingCheckerboard

Inherits:
Substitution show all
Defined in:
lib/cipher.rb

Overview

StraddlingCheckerboard

This is the Straddling Checkerboard system (intended as a first pass to the Nihilist cipher and possibly others).

Instance Attribute Summary

Attributes inherited from Substitution

#key

Instance Method Summary (collapse)

Constructor Details

- (StraddlingCheckerboard) initialize(key)

Returns a new instance of StraddlingCheckerboard



203
204
205
# File 'lib/cipher.rb', line 203

def initialize(key)
  @key = Key::SCKey.new(key)
end

Instance Method Details

- (Object) decode(cipher_text)

decode



222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/cipher.rb', line 222

def decode(cipher_text)
  plain_text = ""

  ct = cipher_text.dup
  in_numbers = false
  while ct.length != 0 do
    c = ct.slice!(0,1)
    #
    # XXX US-ASCII hack
    #
    d = c.ord - 48
    if @key.is_long?(d)
      c << ct.slice!(0,1)
    end
    pt = @key.decode(c)
    #
    # Number shift
    #
    if pt == '/' then
      if in_numbers then
        in_numbers = false
      else
        in_numbers = true
      end
    else
      if in_numbers then
        pt = ct.slice!(0,1)[0]
      end
      plain_text << pt
    end
  end
  return plain_text
end

- (Object) encode(plain_text)

encode



209
210
211
212
213
214
215
216
217
218
# File 'lib/cipher.rb', line 209

def encode(plain_text)
  cipher_text = plain_text.each_char.inject('') do |text, c|
    if c >= '0' and c <= '9' then
      text << @key.encode('/') << c + c << @key.encode('/')
    else
      text << @key.encode(c)
    end
  end
  return cipher_text
end