Ceaser Cipher#

The Caesar cipher is a type of substitution cipher in which each letter in the plaintext is shifted a certain number of places down the alphabet. For example, with a shift of \(1\), \(A\) would be replaced by \(B\), \(B\) would become \(C\), and so on. The method is named after Julius Caesar, who used it to communicate with his officials.

  • The encryption can be represented using modular arithmetic by first transforming the letters into numbers, according to the scheme: \(A = 0\), \(B = 1\), \(\ldots\), \(Z = 25\).

  • Encryption of a letter \(x\) by a shift \(k\) can be described mathematically as:

\[ E(x) = (x + k) \mod 26 \]

Algorithm 11 (Caesar Cipher Input)

Input:

  • Plaintext message \(M\).

  • Shift value \(k\).

Transformation of Letters to Numbers

  1. Assign Numbers to Letters:

    • Each letter in the alphabet is assigned a number:

    \[\begin{split} \begin{aligned} A & = 0, \\ B & = 1, \\ \vdots \\ Z & = 25. \end{aligned} \end{split}\]

Algorithm 12 (Caesar Cipher Encryption)

Encryption Process

  • Given a plaintext letter \(x\) (where \(x\) is its corresponding number), and a shift \(k\), the encryption function \(E(x)\) shifts the letter \(x\) by \(k\) positions down the alphabet:

\[ E(x) = (x + k) \mod 26 \]
  • Example: If \(x = 0\) (corresponding to \(A\)) and \(k = 3\), then:

\[ E(0) = (0 + 3) \mod 26 = 3 \]
  • The number 3 corresponds to the letter \(D\), so \(A\) encrypted with a shift of 3 becomes \(D\).

Algorithm 13 (Caesar Cipher Decryption)

Decryption Process

  • To decrypt a letter \(y\) (the encrypted letter) with a known shift \(k\), the decryption function \(D(y)\) shifts the letter \(y\) back by \(k\) positions up the alphabet:

\[ D(y) = (y - k) \mod 26 \]
  • Example: If \(y = 3\) (corresponding to \(D\)) and \(k = 3\), then:

\[ D(3) = (3 - 3) \mod 26 = 0 \]
  • The number 0 corresponds to the letter \(A\), so \(D\) decrypted with a shift of 3 becomes \(A\).

The Caesar cipher is easy to understand and implement but is also easy to break. It’s named after Julius Caesar, who used it for military communication. Despite its simplicity, it demonstrates the basic principles of substitution ciphers and modular arithmetic.

Ceaser Cipher Algorithm#

The following functions are used in the algorithm:

  • ceaser_cipher_encrypt: Encrypts the given text using the Caesar cipher with the specified shift value.

  • ceaser_cipher_decrypt: Decrypts the given text using the Caesar cipher with the specified shift value.

  • ceaser_cipher_brute_force: Brute forces the Caesar cipher by decrypting the given text for all possible shift values.

  • ceaser_cipher: Runs the calculation for the Caesar cipher algorithm and outputs the encrypted and decrypted text.

Hide code cell source
import random
import faker
def caesar_cipher_encrypt(plaintext, shift):
    ciphertext = ""
    for c in plaintext:
        if c.isalpha():
            if c.islower():
                ciphertext += chr((ord(c) - ord('a') + shift) % 26 + ord('a'))
            else:
                ciphertext += chr((ord(c) - ord('A') + shift) % 26 + ord('A'))
        else:
            ciphertext += c
    return ciphertext
def caesar_cipher_decrypt(ciphertext, shift):
    return caesar_cipher_encrypt(ciphertext, -shift)
def ceaser_cipher_brute_force(ciphertext):
    print(f"The encrypted message is: {ciphertext}")
    for shift in range(26):
        plaintext = caesar_cipher_decrypt(ciphertext, shift)      
        print(f"Shift: {shift} => {plaintext}")
# Function to do the whole cipher messages
def caesar_cipher(plaintext, shift):
    print(f"The shift is: {shift}")
    print(f"Original Message: {plaintext}")
    ciphertext = caesar_cipher_encrypt(plaintext, shift)
    print(f"Encrypted Message: {ciphertext}")
    plaintext = caesar_cipher_decrypt(ciphertext, shift)
    print(f"Decrypted Message: {plaintext}") 

Ceaser Cipher Example#


Example 1: Encryption and Decryption of a Message#

shift = random.randint(1, 25)
plaintext = "Hello World!"
caesar_cipher(plaintext, shift)
The shift is: 22
Original Message: Hello World!
Encrypted Message: Dahhk Sknhz!
Decrypted Message: Hello World!

Example 2: Encryption and Decryption of a Message#

shift = random.randint(1, 25)
plaintext = "Hello World!"
caesar_cipher(plaintext, shift)
The shift is: 10
Original Message: Hello World!
Encrypted Message: Rovvy Gybvn!
Decrypted Message: Hello World!

Brute Force Attack on the Cipher#

ciphertext = "Khoor Zruog!"
ceaser_cipher_brute_force(ciphertext)
The encrypted message is: Khoor Zruog!
Shift: 0 => Khoor Zruog!
Shift: 1 => Jgnnq Yqtnf!
Shift: 2 => Ifmmp Xpsme!
Shift: 3 => Hello World!
Shift: 4 => Gdkkn Vnqkc!
Shift: 5 => Fcjjm Umpjb!
Shift: 6 => Ebiil Tloia!
Shift: 7 => Dahhk Sknhz!
Shift: 8 => Czggj Rjmgy!
Shift: 9 => Byffi Qilfx!
Shift: 10 => Axeeh Phkew!
Shift: 11 => Zwddg Ogjdv!
Shift: 12 => Yvccf Nficu!
Shift: 13 => Xubbe Mehbt!
Shift: 14 => Wtaad Ldgas!
Shift: 15 => Vszzc Kcfzr!
Shift: 16 => Uryyb Jbeyq!
Shift: 17 => Tqxxa Iadxp!
Shift: 18 => Spwwz Hzcwo!
Shift: 19 => Rovvy Gybvn!
Shift: 20 => Qnuux Fxaum!
Shift: 21 => Pmttw Ewztl!
Shift: 22 => Olssv Dvysk!
Shift: 23 => Nkrru Cuxrj!
Shift: 24 => Mjqqt Btwqi!
Shift: 25 => Lipps Asvph!

Examples with longer Messages#


The following function is introduced using the faker library to generate a random message. The function generate_random_message generates a random message with a specified length.

def random_message():
    fake = faker.Faker()
    message = fake.text()
    return message
shift = random.randint(1, 25)
plaintext = random_message()
caesar_cipher(plaintext, shift)
The shift is: 10
Original Message: Only process those attention. Even college recent also. Toward evening size surface PM.
Father second country social west partner maintain. Huge your song prove.
Encrypted Message: Yxvi zbymocc dryco kddoxdsyx. Ofox myvvoqo bomoxd kvcy. Dygkbn ofoxsxq csjo cebpkmo ZW.
Pkdrob comyxn myexdbi cymskv gocd zkbdxob wksxdksx. Reqo iyeb cyxq zbyfo.
Decrypted Message: Only process those attention. Even college recent also. Toward evening size surface PM.
Father second country social west partner maintain. Huge your song prove.
plaintext = random_message()
ciphertext = caesar_cipher_encrypt(plaintext, shift)
ceaser_cipher_brute_force(ciphertext)
The encrypted message is: Qbyg knevd zsomo myxcewob loxopsd. Xokbvi wyfso gkdmr kbok bokvvi nsppsmevd.
Mvokb droi cdbkdoqi gri gsdr.
Sxfyvfo drowcovfoc sxcsno kxn. Kxn pkmo ofobi qykv.
Qy sxcdsdedsyx myxcewob vycc kbyexn.
Shift: 0 => Qbyg knevd zsomo myxcewob loxopsd. Xokbvi wyfso gkdmr kbok bokvvi nsppsmevd.
Mvokb droi cdbkdoqi gri gsdr.
Sxfyvfo drowcovfoc sxcsno kxn. Kxn pkmo ofobi qykv.
Qy sxcdsdedsyx myxcewob vycc kbyexn.
Shift: 1 => Paxf jmduc yrnln lxwbdvna knwnorc. Wnjauh vxern fjclq janj anjuuh mroorlduc.
Lunja cqnh bcajcnph fqh frcq.
Rwexuen cqnvbnuenb rwbrmn jwm. Jwm ojln nenah pxju.
Px rwbcrcdcrxw lxwbdvna uxbb jaxdwm.
Shift: 2 => Ozwe ilctb xqmkm kwvacumz jmvmnqb. Vmiztg uwdqm eibkp izmi zmittg lqnnqkctb.
Ktmiz bpmg abzibmog epg eqbp.
Qvdwtdm bpmuamtdma qvaqlm ivl. Ivl nikm mdmzg owit.
Ow qvabqbcbqwv kwvacumz twaa izwcvl.
Shift: 3 => Nyvd hkbsa wpljl jvuzbtly ilulmpa. Ulhysf tvcpl dhajo hylh ylhssf kpmmpjbsa.
Jslhy aolf zayhalnf dof dpao.
Pucvscl aoltzlsclz puzpkl huk. Huk mhjl lclyf nvhs.
Nv puzapabapvu jvuzbtly svzz hyvbuk.
Shift: 4 => Mxuc gjarz vokik iutyaskx hktkloz. Tkgxre subok cgzin gxkg xkgrre jolloiarz.
Irkgx znke yzxgzkme cne cozn.
Otburbk znksykrbky otyojk gtj. Gtj lgik kbkxe mugr.
Mu otyzozazout iutyaskx ruyy gxuatj.
Shift: 5 => Lwtb fizqy unjhj htsxzrjw gjsjkny. Sjfwqd rtanj bfyhm fwjf wjfqqd inkknhzqy.
Hqjfw ymjd xywfyjld bmd bnym.
Nsatqaj ymjrxjqajx nsxnij fsi. Fsi kfhj jajwd ltfq.
Lt nsxynyzynts htsxzrjw qtxx fwtzsi.
Shift: 6 => Kvsa ehypx tmigi gsrwyqiv firijmx. Rievpc qszmi aexgl evie vieppc hmjjmgypx.
Gpiev xlic wxvexikc alc amxl.
Mrzspzi xliqwipziw mrwmhi erh. Erh jegi izivc ksep.
Ks mrwxmxyxmsr gsrwyqiv psww evsyrh.
Shift: 7 => Jurz dgxow slhfh frqvxphu ehqhilw. Qhduob prylh zdwfk duhd uhdoob gliilfxow.
Fohdu wkhb vwudwhjb zkb zlwk.
Lqyroyh wkhpvhoyhv lqvlgh dqg. Dqg idfh hyhub jrdo.
Jr lqvwlwxwlrq frqvxphu orvv durxqg.
Shift: 8 => Itqy cfwnv rkgeg eqpuwogt dgpghkv. Pgctna oqxkg ycvej ctgc tgcnna fkhhkewnv.
Engct vjga uvtcvgia yja ykvj.
Kpxqnxg vjgougnxgu kpukfg cpf. Cpf hceg gxgta iqcn.
Iq kpuvkvwvkqp eqpuwogt nquu ctqwpf.
Shift: 9 => Hspx bevmu qjfdf dpotvnfs cfofgju. Ofbsmz npwjf xbudi bsfb sfbmmz ejggjdvmu.
Dmfbs uifz tusbufhz xiz xjui.
Jowpmwf uifntfmwft jotjef boe. Boe gbdf fwfsz hpbm.
Hp jotujuvujpo dpotvnfs mptt bspvoe.
Shift: 10 => Grow adult piece consumer benefit. Nearly movie watch area really difficult.
Clear they strategy why with.
Involve themselves inside and. And face every goal.
Go institution consumer loss around.
Shift: 11 => Fqnv zctks ohdbd bnmrtldq admdehs. Mdzqkx lnuhd vzsbg zqdz qdzkkx cheehbtks.
Bkdzq sgdx rsqzsdfx vgx vhsg.
Hmunkud sgdlrdkudr hmrhcd zmc. Zmc ezbd dudqx fnzk.
Fn hmrshstshnm bnmrtldq knrr zqntmc.
Shift: 12 => Epmu ybsjr ngcac amlqskcp zclcdgr. Lcypjw kmtgc uyraf ypcy pcyjjw bgddgasjr.
Ajcyp rfcw qrpyrcew ufw ugrf.
Gltmjtc rfckqcjtcq glqgbc ylb. Ylb dyac ctcpw emyj.
Em glqrgrsrgml amlqskcp jmqq ypmslb.
Shift: 13 => Dolt xariq mfbzb zlkprjbo ybkbcfq. Kbxoiv jlsfb txqze xobx obxiiv afccfzriq.
Zibxo qebv pqoxqbdv tev tfqe.
Fkslisb qebjpbisbp fkpfab xka. Xka cxzb bsbov dlxi.
Dl fkpqfqrqflk zlkprjbo ilpp xolrka.
Shift: 14 => Cnks wzqhp leaya ykjoqian xajabep. Jawnhu ikrea swpyd wnaw nawhhu zebbeyqhp.
Yhawn pdau opnwpacu sdu sepd.
Ejrkhra pdaioahrao ejoeza wjz. Wjz bwya aranu ckwh.
Ck ejopepqpekj ykjoqian hkoo wnkqjz.
Shift: 15 => Bmjr vypgo kdzxz xjinphzm wzizado. Izvmgt hjqdz rvoxc vmzv mzvggt ydaadxpgo.
Xgzvm oczt nomvozbt rct rdoc.
Diqjgqz oczhnzgqzn dindyz viy. Viy avxz zqzmt bjvg.
Bj dinodopodji xjinphzm gjnn vmjpiy.
Shift: 16 => Aliq uxofn jcywy wihmogyl vyhyzcn. Hyulfs gipcy qunwb ulyu lyuffs xczzcwofn.
Wfyul nbys mnlunyas qbs qcnb.
Chpifpy nbygmyfpym chmcxy uhx. Uhx zuwy ypyls aiuf.
Ai chmncnoncih wihmogyl fimm uliohx.
Shift: 17 => Zkhp twnem ibxvx vhglnfxk uxgxybm. Gxtker fhobx ptmva tkxt kxteer wbyybvnem.
Vextk maxr lmktmxzr par pbma.
Bgoheox maxflxeoxl bglbwx tgw. Tgw ytvx xoxkr zhte.
Zh bglmbmnmbhg vhglnfxk ehll tkhngw.
Shift: 18 => Yjgo svmdl hawuw ugfkmewj twfwxal. Fwsjdq egnaw osluz sjws jwsddq vaxxaumdl.
Udwsj lzwq kljslwyq ozq oalz.
Afngdnw lzwekwdnwk afkavw sfv. Sfv xsuw wnwjq ygsd.
Yg afklalmlagf ugfkmewj dgkk sjgmfv.
Shift: 19 => Xifn rulck gzvtv tfejldvi svevwzk. Evricp dfmzv nrkty rivr ivrccp uzwwztlck.
Tcvri kyvp jkirkvxp nyp nzky.
Zemfcmv kyvdjvcmvj zejzuv reu. Reu wrtv vmvip xfrc.
Xf zejkzklkzfe tfejldvi cfjj rifleu.
Shift: 20 => Whem qtkbj fyusu sedikcuh ruduvyj. Duqhbo celyu mqjsx qhuq huqbbo tyvvyskbj.
Sbuqh jxuo ijhqjuwo mxo myjx.
Ydleblu jxuciublui ydiytu qdt. Qdt vqsu uluho weqb.
We ydijyjkjyed sedikcuh beii qhekdt.
Shift: 21 => Vgdl psjai extrt rdchjbtg qtctuxi. Ctpgan bdkxt lpirw pgtp gtpaan sxuuxrjai.
Ratpg iwtn higpitvn lwn lxiw.
Xckdakt iwtbhtakth xchxst pcs. Pcs uprt tktgn vdpa.
Vd xchixijixdc rdchjbtg adhh pgdjcs.
Shift: 22 => Ufck orizh dwsqs qcbgiasf psbstwh. Bsofzm acjws kohqv ofso fsozzm rwttwqizh.
Qzsof hvsm ghfohsum kvm kwhv.
Wbjczjs hvsagszjsg wbgwrs obr. Obr toqs sjsfm ucoz.
Uc wbghwhihwcb qcbgiasf zcgg ofcibr.
Shift: 23 => Tebj nqhyg cvrpr pbafhzre orarsvg. Arneyl zbivr jngpu nern ernyyl qvssvphyg.
Pyrne gurl fgengrtl jul jvgu.
Vaibyir gurzfryirf vafvqr naq. Naq snpr rirel tbny.
Tb vafgvghgvba pbafhzre ybff nebhaq.
Shift: 24 => Sdai mpgxf buqoq oazegyqd nqzqruf. Zqmdxk yahuq imfot mdqm dqmxxk purruogxf.
Oxqmd ftqk efdmfqsk itk iuft.
Uzhaxhq ftqyeqxhqe uzeupq mzp. Mzp rmoq qhqdk samx.
Sa uzefufgfuaz oazegyqd xaee mdagzp.
Shift: 25 => Rczh lofwe atpnp nzydfxpc mpypqte. Yplcwj xzgtp hlens lcpl cplwwj otqqtnfwe.
Nwplc espj decleprj hsj htes.
Tygzwgp espxdpwgpd tydtop lyo. Lyo qlnp pgpcj rzlw.
Rz tydetefetzy nzydfxpc wzdd lczfyo.