Class: Key::ChaoKey

Inherits:
Key
  • Object
show all
Defined in:
lib/key/chaokey.rb

Overview

ChaoKey

Setup key schedule & encode:decode methods for the Chaocipher algorithm. See www.mountainvistasoft.com/chaocipher/index.htm

Constant Summary

BASE =
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
ZENITH =
0
NADIR =
13

Instance Attribute Summary (collapse)

Attributes inherited from Key

#key

Instance Method Summary (collapse)

Methods inherited from Key

#condensed, #length, #to_s

Constructor Details

- (ChaoKey) initialize(pw, cw)

Returns a new instance of ChaoKey



25
26
27
28
29
30
31
# File 'lib/key/chaokey.rb', line 25

def initialize(pw, cw)
  @plain  = pw
  @cipher = cw
  [pw, cw].each do |e|
    raise DataError, "Bad #{e} length" if e.length != BASE.length
  end
end

Instance Attribute Details

- (Object) cipher (readonly)

Returns the value of attribute cipher



23
24
25
# File 'lib/key/chaokey.rb', line 23

def cipher
  @cipher
end

- (Object) plain (readonly)

Returns the value of attribute plain



23
24
25
# File 'lib/key/chaokey.rb', line 23

def plain
  @plain
end

Instance Method Details

- (Object) advance(idx)

advance

Permute the two alphabets, first ciphertext then plaintext We use the current plain & ciphertext characters (akin to autoclave)

Zenith is 0, Nadir is 13 (n/2 + 1 if 1-based) Steps for left:

  1. shift from idx to Zenith

  2. take Zenith+1 out

  3. shift left one position and insert back the letter from step2

Steps for right

  1. shift everything from plain to Zenith

  2. shift one more entire string

  3. extract Zenith+2

  4. shift from Zenith+3 to Nadir left

  5. insert letter from step 3 in place

Raises:



72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
# File 'lib/key/chaokey.rb', line 72

def advance(idx)
  if idx != 0 then
    cw = @cipher[idx..-1] + @cipher[ZENITH..(idx - 1)]
    pw = @plain[idx..-1] + @plain[ZENITH..(idx - 1)]
  else
    cw = @cipher
    pw = @plain
  end
  @cipher = cw[ZENITH].chr + cw[(ZENITH + 2)..NADIR] + \
          cw[ZENITH + 1].chr + cw[(NADIR + 1)..-1]
  raise DataError, 'cw length bad' if cw.length != BASE.length

  pw = pw[(ZENITH + 1)..-1] + pw[ZENITH].chr
  @plain = pw[ZENITH..(ZENITH + 1)] + pw[(ZENITH + 3)..NADIR] + \
         pw[ZENITH + 2].chr + pw[(NADIR + 1)..-1]
  raise DataError, 'pw length bad' if pw.length != BASE.length
end

- (Object) decode(c)

decode



41
42
43
# File 'lib/key/chaokey.rb', line 41

def decode(c)
  return encode_or_decode(cipher, plain, c)
end

- (Object) encode(c)

encode



35
36
37
# File 'lib/key/chaokey.rb', line 35

def encode(c)
  return encode_or_decode(plain, cipher, c)
end

- (Object) encode_or_decode(r1, r2, c)

encode_or_decode



47
48
49
50
51
52
# File 'lib/key/chaokey.rb', line 47

def encode_or_decode(r1, r2, c)
  idx = r1.index(c)
  pt = r2[idx]
  advance(idx)
  return pt.chr
end