A cipher is an algorithm that uses a secret key to transform a message into ciphertext and recover the message through decryption. Symmetric encryption uses the same key for both transformations. section 15.4
A secret key controls both encryption and decryption in symmetric encryption. section 15.4
Two exchangeable cipher designs illustrate different key representations:
- The Caesar cipher rotates an alphabetical inner dial; its key is the number of shifted positions. section 15.4
- The substitution cipher replaces the inner alphabet with a fixed ordering; its key is the mapping between alphabets. section 15.4
- An abstract Cipher interface lets a password-keeping service encrypt and decrypt without depending on a particular algorithm. section 15.6
A swappable Julia cipher
Define `abstract type Cipher end`, then dispatch `encrypt` and `decrypt` on concrete ciphers. `Vault(CaesarCipher(23))` encrypts `"BING"` as `"YFKD"` and retrieves the original password; replacing it with `SubstitutionCipher("CQPYXVFHRNZMWOITJSUBKLEGDA")` preserves the same vault operations. section 15.6
Listing 15.10 Defining an abstract cipher interface
abstract type Cipher end
function encrypt(cipher::Cipher, char::Char)
error("Implement encrypt(::", typeof(cipher), ", char)")
end
function decrypt(cipher::Cipher, char::Char)
error("Implement decrypt(::", typeof(cipher), ", char)")
end
function encrypt(cipher::Cipher, message::AbstractString)
map(ch -> encrypt(cipher, ch), message)
end
function decrypt(cipher::Cipher, ciphertext::AbstractString)
map(ch -> decrypt(cipher, ch), ciphertext)
end
The interface supplies character-level encryption and decryption with string methods built by mapping those operations across characters. section 15.6
