liveBook · Manning

Cipher

As explained in Julia as a Second Language

A cipher is a cryptographic algorithm that transforms plaintext into ciphertext and can provide a corresponding transformation for recovery.

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

Figure 15.3 Symmetric encryption using a secret key
15-03

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

How Julia as a Second Language covers it

How deep it goes
Explains keys, encryption, and decryption, then implements Caesar and substitution ciphers behind an abstract interface.
Examples
Uses rotated and substituted alphabets, Julia cipher types, and a Vault that stores and retrieves encrypted passwords.
What it assumes
Assumes basic Julia programming while teaching cipher terminology, symmetric keys, alphabet mappings, and abstract interfaces.
What you can do after
Build it from scratch by implementing encrypt and decrypt methods for interchangeable Julia cipher types.
How it connects
Connects symmetric encryption with Caesar cipher, substitution cipher, abstract types, object-oriented programming, and functional programming.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Julia as a Second Language. The section links point to the parts of the book it draws on.