Class: Key::ChaoKey
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)
-
- (Object) cipher
readonly
Returns the value of attribute cipher.
-
- (Object) plain
readonly
Returns the value of attribute plain.
Attributes inherited from Key
Instance Method Summary (collapse)
-
- (Object) advance(idx)
advance.
-
- (Object) decode(c)
decode.
-
- (Object) encode(c)
encode.
-
- (Object) encode_or_decode(r1, r2, c)
encode_or_decode.
-
- (ChaoKey) initialize(pw, cw)
constructor
A new instance of ChaoKey.
Methods inherited from Key
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:
-
shift from idx to Zenith
-
take Zenith+1 out
-
shift left one position and insert back the letter from step2
Steps for right
-
shift everything from plain to Zenith
-
shift one more entire string
-
extract Zenith+2
-
shift from Zenith+3 to Nadir left
-
insert letter from step 3 in place
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 |