summaryrefslogtreecommitdiff
path: root/algorithms/letter_substitution_cipher.rb
blob: 01bde9baef0d616608243fd281f2500030940092 (plain)
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
#!/usr/bin/env ruby


ALPHABET = ('a'..'z').to_a
ALPHABET << ' '
puts ALPHABET.to_s

def mklettersubstitioncipher
  cipher = {}
  ALPHABET.each { |i|
    while true
      c = ALPHABET[ Random.rand(ALPHABET.size) ]
      if not cipher.values.include? c
        cipher[i] = c
        break
      end
    end
  }
  return cipher
end

def encrypt(key, plaintext)
  s = ''
  plaintext.each_char { |i| s += key[i] }
  return s
end

def decrypt(key, ciphertext)
  s = ''
  ciphertext.each_char { |i|
    key.each_pair { |p|
      if p[1] == i
        s += p[0]
      end
    }
  }
  return s
end

def randomcipherstring(cipher)
  length = Random.rand(49)+1
  s = ''
  length.times {
    s += cipher[ ALPHABET[Random.rand(ALPHABET.size)] ]
  }
  return s
end

def sample(n, cipher)
  a = []
  n.times {
    a << randomcipherstring(cipher)
  }
  puts a.to_s
end

def test
  cipher = mklettersubstitioncipher
  s = "das ist das haus vom nikolaus"
  s_enc = encrypt(cipher, s)
  s_dec = decrypt(cipher, s_enc)
  puts "#{s}\n#{s_enc}\n#{s_dec}"
end


test