From 26c490f404731d053a6205719b6246502c07b449 Mon Sep 17 00:00:00 2001 From: Patrick Simianer Date: Sat, 14 Jun 2014 16:46:27 +0200 Subject: init --- algorithms/letter_substitution_cipher.rb | 67 ++++++++++++++++++++++++++++++++ 1 file changed, 67 insertions(+) create mode 100755 algorithms/letter_substitution_cipher.rb (limited to 'algorithms/letter_substitution_cipher.rb') 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 + -- cgit v1.2.3