September 2017 Update

This commit is contained in:
Ingy döt Net 2017-09-23 10:01:46 +02:00
parent bba7bfd280
commit ba8067c3b7
14570 changed files with 153136 additions and 63871 deletions

View file

@ -1,27 +1,12 @@
module CaesarCipher
AtoZ = (0..25).each_with_object({}) do |key,h|
str = [*"A".."Z"].rotate(key).join
h[key] = str + str.downcase
class String
ALFABET = ("A".."Z").to_a
def caesar_cipher(num)
self.tr(ALFABET.join, ALFABET.rotate(num).join)
end
def encrypt(key, plaintext)
(1..25) === key or raise ArgumentError, "key not in 1..25"
plaintext.tr(AtoZ[0], AtoZ[key])
end
def decrypt(key, ciphertext)
(1..25) === key or raise ArgumentError, "key not in 1..25"
ciphertext.tr(AtoZ[key], AtoZ[0])
end
end
include CaesarCipher
original = "THEYBROKEOURCIPHEREVERYONECANREADTHIS"
en = encrypt(3, original)
de = decrypt(3, en)
[original, en, de].each {|e| puts e}
puts 'OK' if
(1..25).all? {|k| original == decrypt(k, encrypt(k, original))}
#demo:
encypted = "THEYBROKEOURCIPHEREVERYONECANREADTHIS".caesar_cipher(3)
decrypted = encypted.caesar_cipher(-3)