Docsity

Lecture Notes on Substitution Ciphers in CPSC 121 (Fall 2011), Study notes of Computer Science

Partial preview of the text

Download Lecture Notes on Substitution Ciphers in CPSC 121 (Fall 2011) and more Study notes Computer Science in PDF only on Docsity!

Today ...

  • More basic cryptography

Encryption by Substitution

  • Instead of rearranging the letters in transposition
  • With substitution, you substitute letters for other letters
  • The original positions of letters don’t change

A simple example is rot

  • letters in alphabet are “rotated” 13 characters ...
  • so:
    • abcdefghijklmnopqrstuvwxyz ... originals
    • nopqrstuvwxyzabcdefghijklm ... substitutes
  • each letter in plaintext is substituted by rot13 character
  • for example ...
    • "spamhameggs" becomes
    • "fcnzunzrttf"
  • this is very similar to shifting!

Usually, the subsitution is given by a key

  • Key used to encrypt the plaintext message (via substitution)
  • Need the key to decrypt (or break) the cipher

Creating a Substitution Cipher

  • Use a 26-letter key (all in lower case and unique letters)

Exercise

Write a substitution encrypt(message, key) function

  • Loop through each character in the message and replace

def substitution_encrypt(message, alpha, key): cipher = "" for ch in message: if ch in alpha: cipher += key[alpha.find(ch)] else: cipher += ch return cipher

Q: Can we use this same function to decrypt?

  • Have to be careful ... since we map from alpha to key
  • Can call by flipping arguments ...
  • To decrypt: substitution encrypt(cipher, key, alpha)

Creating Keys from Passwords

A more common approach is to use passwords to generate keys

The basic idea:

  • Take a password (e.g., “spamham”)
  • Remove any duplicates from password (e.g., “spamh”)
    • This is now like a “mini” key
  • Remove password letters from alphabet
  • Combine password and alphabet

Combining a password and alphabet

  • Password is start of the key
  • Add all letters in alphabet after last letter in password up to "z"
    • E.g., "spamhijklnoqrtuvwxyz"
  • add the rest of the letters
    • E.g., "spamhijklnoqrtuvwxyzbcdefg"

Typically consider all printable characters ...

  • Notice alpha is used in a number of places ...
  • A more modular way to generate the alphabet:

def generate_alpha(): alpha = "" for x in range(32, 127): # printable from 32 to 126 alpha += chr(x) return alpha