Sync
This commit is contained in:
parent
6f050a029e
commit
776bba907c
3887 changed files with 59894 additions and 7280 deletions
|
|
@ -1,3 +1,3 @@
|
|||
Implement a [[wp:Caesar cipher|Caesar cipher]], both encryption and decryption. The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z). The encryption replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "monoalphabetic substitution cipher" provides almost no security, because an attacker who has the encrypted message can either use frequency analysis to guess the key, or just try all 25 keys.
|
||||
Implement a [[wp:Caesar cipher|Caesar cipher]], both encoding and decoding. The key is an integer from 1 to 25. This cipher rotates the letters of the alphabet (A to Z). The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts "HI" to "JK", but key 20 encrypts "HI" to "BC". This simple "monoalphabetic substitution cipher" provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.
|
||||
|
||||
Caesar cipher is identical to [[Vigenère cipher]] with key of length 1. Also, [[Rot-13]] is identical to Caesar cipher with key 13.
|
||||
|
|
|
|||
|
|
@ -1,17 +1,21 @@
|
|||
@atoz = Hash.new do |hash, key|
|
||||
str = ('A'..'Z').to_a.rotate(key).join("")
|
||||
hash[key] = (str << str.downcase)
|
||||
module CaesarCipher
|
||||
AtoZ = (0..25).each_with_object({}) do |key,h|
|
||||
str = [*"A".."Z"].rotate(key).join
|
||||
h[key] = str + str.downcase
|
||||
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
|
||||
|
||||
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
|
||||
include CaesarCipher
|
||||
|
||||
original = "THEYBROKEOURCIPHEREVERYONECANREADTHIS"
|
||||
en = encrypt(3, original)
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue