Skip to content

How to create a cryptogram in python (random substitution cipher)

by mat on April 20th, 2010

Cryptograms are enjoyable puzzles created from a saying or phrase encrypted with a substitutional cipher. They can be fun to decipher by hand by looking for common letter combinations, doublets, guesswork, and other flaws in this encryption mechanism.

I wrote a quick python script which will accept an input text and create a random substitutional cipher and encrypt it. It then outputs the cipher alphabet and the encrypted text.

Source code:

# -*- coding: utf-8 -*-
import sys
from random import randint
from string import maketrans

if (len(sys.argv)>1):
	# Normal alphabet 
	alphabet="abcdefghijklmnopqrstuvwxyz"

	# Randomly create a new cipherbet
	cipherbet=""
	left=alphabet
	for i in range(0,len(alphabet)):
		x=randint(0,len(left)-1)
		cipherbet+=left[x]
		left=left[:x]+left[x+1:]
	
	# Get input text to translate  
	text=sys.argv[1].lower()

	trantab = maketrans(alphabet,cipherbet)
	text=text.translate(trantab)

	# Replace unused letters in cipherbet with _'s  
	for i in cipherbet:
		if i not in text:
			cipherbet=cipherbet.replace(i,"_")

	# Print cipherbet (solution) and the text (cryptogram) 
	print cipherbet
	print text

Example usage

python create_cipher.py “The Science gets done. And you make a neat gun. For the people who are still alive.”
b_lpievrm_acqxuj_fzdgwn_o_
dri zlmixli vidz puxi. bxp oug qbai b xibd vgx. euf dri jiujci nru bfi zdmcc bcmwi.

3 Comments
  1. For lines 11 – 16:

    from random import shuffle
    cypher = list(alphabet)
    cypher.shuffle
    cypherbet = “”.join(cypher)

    also for line 8:

    from string import ascii_lowercase as alphabet

  2. Ah yes, I was thinking there would be a better way than splicing arrays and I didn’t know about the ascii stuff, Thanks Michael!

Leave a Reply

Note: I am currently writing my thesis so probably wont have time to reply to your comment
Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS