summaryrefslogtreecommitdiff
path: root/algorithms/letter_substitution_cipher.rb
diff options
context:
space:
mode:
authorPatrick Simianer <p@simianer.de>2014-06-14 16:46:27 +0200
committerPatrick Simianer <p@simianer.de>2014-06-14 16:46:27 +0200
commit26c490f404731d053a6205719b6246502c07b449 (patch)
tree3aa721098f1251dfbf2249ecd2736434c13b1d48 /algorithms/letter_substitution_cipher.rb
init
Diffstat (limited to 'algorithms/letter_substitution_cipher.rb')
-rwxr-xr-xalgorithms/letter_substitution_cipher.rb67
1 files changed, 67 insertions, 0 deletions
diff --git a/algorithms/letter_substitution_cipher.rb b/algorithms/letter_substitution_cipher.rb
new file mode 100755
index 0000000..01bde9b
--- /dev/null
+++ b/algorithms/letter_substitution_cipher.rb
@@ -0,0 +1,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
+