Learn how you can become a Python programmer in just 12 weeks.

    We respect your privacy. Unsubscribe at anytime.

    Understand Caesar Cipher by Implementing it in Python

    What will we cover?

    • Understand what Caesar Cipher is
    • Implement Caesar Cipher in Python
    • Understand the weakness of Caesar Cipher

    What is Caesar Cipher

    Caesar Cipher is a simple substitution cipher, which is limited to only shift the characters by fix number.

    Imagine you got the message: BRX DUH DZHVRPH. What to make out of it. Makes no sense. Just ignore it, right?

    Well, for the untrained eye, yes, ignore it. But why would anyone bother sending you that message? Aren’t you curious?

    I would be. Let’s say your friend told you it was a Caesar Cipher with a 3-key shift. What does that mean?

    In the picture below, you can see how the letters are shifted from the green letters (plain text), to the encrypted red letters (cipher text). As an example, A is encrypted to D, and B is encrypted to E, and so forth.

    By using that strategy, you can also figure out that a cipher B (red letters) maps to the plain Y (green letters). A cipher R maps to the plain O. And so forth. That results in that your secret message decrypts to YOU ARE AWESOME.

    What a nice message to get.

    Implementation of Caesar Cipher in Python

    Below is an example of how you could implement the Caesar Cipher in Python.

    def generate_key(n):
        chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        key = {}
        cnt = 0
        for c in chars:
            key[c] = chars[(cnt + n) % len(chars)]
            cnt += 1
        return key
    
    def encrypt(key, message):
        cipher = ""
        for c in message:
            if c in key:
                cipher += key[c]
            else:
                cipher += c
        return cipher
    
    def get_decrypt_key(key):
        dkey = {}
        for k in key:
            dkey[key[k]] = k
        return dkey
    
    key = generate_key(3)
    dkey = generate_key(23)
    cipher = encrypt(key, "YOU ARE AWESOME")
    print(cipher)
    message = encrypt(dkey, cipher)
    print(message)
    dkey = get_decrypt_key(key)
    print(encrypt(dkey, cipher))
    

    There are some things to notice. First of all, the generate_key function comes in handy, when we extend our cipher function to the more general substitution cipher.

    Also, notice, that encryption and decryption are done with the same function, just different keys. The decryption key of key-3 is key-23.

    See that you can actually calculate the decryption key quite nice, as done in the get_decrypt_key function, which can be used if this is extended to a general substitution cipher.

    How to de-cipher a Caesar Cipher message

    Image you had received the message BRX DUH DZHVRPH, but didn’t know the key. What to do?

    No worries, there is a way to solve that problem efficiently.

    The scenario is that Alice wants to send Bob a secret message, but someone (you) get’s a copy of the message (and you are called Eve).

    The secrecy of the message was intended to be, that you (Eve) does not know the Algorithm (how the encryption is done). That might seems naive today, but back in the time of Caesar, this was the state of the art, and people were not that knowledgable about the art of cryptography.

    But you are in luck. Yes, I am talking to you Eve.

    You know the Algorithm and you are soon to figure out, that the key space is quite small. Actually it only contains 26 possible keys.

    That is in the reach of you manually trying out all possible keys.

    But you are in more luck, because you realised that you also have Python. So let’s try to fix it in Python.

    def generate_key(n):
        chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
        key = {}
        cnt = 0
        for c in chars:
            key[c] = chars[(cnt + n) % len(chars)]
            cnt += 1
        return key
    
    def encrypt(key, message):
        cipher = ""
        for c in message:
            if c in key:
                cipher += key[c]
            else:
                cipher += c
        return cipher
    
    cipher = "BRX DUH DZHVRPH"
    for i in range(26):
        key = generate_key(i)
        message = encrypt(key, cipher)
        print(message)
    

    That will generate the following output.

    CSY EVI EAIWSQI
    DTZ FWJ FBJXTRJ
    EUA GXK GCKYUSK
    FVB HYL HDLZVTL
    GWC IZM IEMAWUM
    HXD JAN JFNBXVN
    IYE KBO KGOCYWO
    JZF LCP LHPDZXP
    KAG MDQ MIQEAYQ
    LBH NER NJRFBZR
    MCI OFS OKSGCAS
    NDJ PGT PLTHDBT
    OEK QHU QMUIECU
    PFL RIV RNVJFDV
    QGM SJW SOWKGEW
    RHN TKX TPXLHFX
    SIO ULY UQYMIGY
    TJP VMZ VRZNJHZ
    UKQ WNA WSAOKIA
    VLR XOB XTBPLJB
    WMS YPC YUCQMKC
    XNT ZQD ZVDRNLD
    YOU ARE AWESOME
    ZPV BSF BXFTPNF
    AQW CTG CYGUQOG
    

    That was awesome right.

    Conclusion

    The security of Caesar Cipher was by keeping the Algorithm secret. That approach to security is not used anymore. Kerckhoffs’ Principle states that the adversary (Eve) should not be able to break the cipher even when she knows the Algorithm.

    Python for Finance: Unlock Financial Freedom and Build Your Dream Life

    Discover the key to financial freedom and secure your dream life with Python for Finance!

    Say goodbye to financial anxiety and embrace a future filled with confidence and success. If you’re tired of struggling to pay bills and longing for a life of leisure, it’s time to take action.

    Imagine breaking free from that dead-end job and opening doors to endless opportunities. With Python for Finance, you can acquire the invaluable skill of financial analysis that will revolutionize your life.

    Make informed investment decisions, unlock the secrets of business financial performance, and maximize your money like never before. Gain the knowledge sought after by companies worldwide and become an indispensable asset in today’s competitive market.

    Don’t let your dreams slip away. Master Python for Finance and pave your way to a profitable and fulfilling career. Start building the future you deserve today!

    Python for Finance a 21 hours course that teaches investing with Python.

    Learn pandas, NumPy, Matplotlib for Financial Analysis & learn how to Automate Value Investing.

    “Excellent course for anyone trying to learn coding and investing.” – Lorenzo B.

    2 thoughts on “Understand Caesar Cipher by Implementing it in Python”

    1. thank you so much Rune for your priceless effort in creating these awesome tutorials.. I am watching you all the series in python. you have lite the fire of passion for programming in me. you are so brilliant in explaining things in tutorial. God bliss you.

      Reply

    Leave a Comment