Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Caesar Cipher in Python

#1
Caesar Cipher in Python

<div><div class="kk-star-ratings kksr-valign-top kksr-align-left " data-payload="{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;356186&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;count&quot;:&quot;1&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;best&quot;:&quot;5&quot;,&quot;gap&quot;:&quot;5&quot;,&quot;greet&quot;:&quot;Rate this post&quot;,&quot;legend&quot;:&quot;5\/5 - (1 vote)&quot;,&quot;size&quot;:&quot;24&quot;,&quot;width&quot;:&quot;142.5&quot;,&quot;_legend&quot;:&quot;{score}\/{best} - ({count} {votes})&quot;}">
<div class="kksr-stars">
<div class="kksr-stars-inactive">
<div class="kksr-star" data-star="1" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="2" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="3" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="4" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" data-star="5" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
<div class="kksr-stars-active" style="width: 142.5px;">
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
<div class="kksr-star" style="padding-right: 5px">
<div class="kksr-icon" style="width: 24px; height: 24px;"></div>
</p></div>
</p></div>
</div>
<div class="kksr-legend"> 5/5 – (1 vote) </div>
</div>
<p class="has-global-color-8-background-color has-background">Caesar Cipher is a simple encryption and obfuscation method. It’s a straightforward substitution cipher that replaces each plain text character with the obfuscated character obtained by shifting the plain text character a fixed number of positions in the alphabet.</p>
<figure class="wp-block-embed is-type-video is-provider-youtube wp-block-embed-youtube wp-embed-aspect-16-9 wp-has-aspect-ratio">
<div class="wp-block-embed__wrapper">
<iframe loading="lazy" title="Caesar Cipher in Python - A Simple Guide" width="780" height="439" src="https://www.youtube.com/embed/kP5N_5fVXXY?feature=oembed" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>
</figure>
<h2>What is Cryptography?</h2>
<p>Before we introduce our first cryptographic algorithm, <em>Caesar’s cipher</em>, let’s first introduce cryptography as a scientific and industrial discipline. </p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Definition</strong>: Cryptography is the study of secure communications techniques that allow only the sender and recipient of a message to view its contents. The term is derived from the Greek word <em>kryptos</em>, which means <em>hidden</em>.</p>
<p><strong>Source</strong>: <a rel="noreferrer noopener" href="https://www.kaspersky.com/resource-center/definitions/what-is-cryptography" data-type="URL" data-id="https://www.kaspersky.com/resource-center/definitions/what-is-cryptography" target="_blank">Kaspersky</a></p>
<p>Here’s another less formal definition:</p>
<p class="has-global-color-8-background-color has-background"><img src="https://s.w.org/images/core/emoji/13.1.0/72x72/1f4a1.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Definition</strong>: Cryptography provides for secure communication in the presence of malicious third-parties – known as adversaries. Encryption uses an algorithm and a key to transform an input (i.e., plaintext) into an encrypted output (i.e., ciphertext).</p>
<p><strong>Source</strong>: <a href="https://www.synopsys.com/glossary/what-is-cryptography.html" data-type="URL" data-id="https://www.synopsys.com/glossary/what-is-cryptography.html" target="_blank" rel="noreferrer noopener">Synopsis</a></p>
<h2>Getting Acquainted With the Terms in Cryptography</h2>
<p>By this point, we begin to notice certain similarities or keywords. </p>
<p>(1) The first thing to notice is that both definitions emphasized <em>secure communication</em>, i.e. a communication whose content is unavailable to anyone other than the <em>sender</em> and <em>receiver</em>(s) of the <em>message</em>. The <em>content</em> is at the center of communication, as it is being carried in the form of a message. </p>
<p>(2) The second thing to notice is that we have the first party, i.e., the sender of the message; a second party (or more than one), i.e., the recipient(s) of the message; and possibly a <em>third party</em>, i.e., any unintended/uninvited recipient of the message, also known as an <em>adversary</em>. </p>
<p>An adversary is generally considered an unintended recipient of the message who might misuse the content of the message with any malicious intent. </p>
<p>(3) The third thing to notice from the definitions are mentions of a <em>key</em>, an <em>algorithm</em>, a <em>plaintext message</em>, and a <em>ciphertext message</em>. </p>
<p>A key is a changeable component, usually a number or a sequence of symbols that drive the encryption algorithm. </p>
<p>An encryption algorithm is represented as a series of computational steps which transform an input content (e.g., non-binary text or other binary content), by applying a key, to a secure ciphertext message. </p>
<p>The ciphered content is practically unreadable and, as such, suitable for transfer over an insecure information system to its intended recipient. The intended recipient holds a key that enables him to apply a reverse algorithm and decipher the ciphertext message back to the original, plaintext message. </p>
<p>It is assumed that a third party doesn’t hold the key and is unable to retrieve the plaintext message content in any other way, so the message is available only to the intended recipient and therefore secure. </p>
<p>From a practical point of view, absolute security may not be achieved as there are attack methods that might enable a third party to break the ciphered message and retrieve the original content, but their existence depends on the strength of a specific algorithm, which we will discuss at a later point.</p>
<h2>What is Caesar’s Cipher?</h2>
<p>Caesar’s cipher is a simple cryptographic algorithm that uses <em>substitution</em>, i.e., systematic replacement of each symbol from the original, plaintext message with another, predetermined symbol. </p>
<p>According to popular belief, it is said it was used by the Roman emperor Julius Caesar in his private correspondence. </p>
<p>Due to the algorithm’s simplicity, Caesar’s cipher in the modern era is not used as a standalone method of encryption but still finds its place as a <em>component</em> in more complex cryptographic systems, such as the <a href="https://blog.finxter.com/how-to-use-rot13-in-python/" data-type="post" data-id="1118" target="_blank" rel="noreferrer noopener">ROT13</a> system or Vigenere cipher. </p>
<p>Besides that, it is a nice and simple algorithm to start our journey into cryptography.</p>
<h2>How Does Caesar’s Cipher Work?</h2>
<p>Caesar’s cipher algorithm construction begins by defining a set of unique symbols, which we will refer to as the alphabet.</p>
<p class="has-global-color-8-background-color has-background"><strong>Note</strong>: if an alphabet is also defined by order of its symbols, which is not a common case with Caesar’s cipher, it is said that the cipher algorithm uses <em>monoalphabetic</em> substitution. </p>
<p>For example, alphabets a1 = {A, B, C} and a2 = {A, C, B} are treated as different alphabets because the algorithm would produce different outputs for each of them. </p>
<p>We’ll take a closer look at the effect of symbol ordering a bit later.</p>
<p>Besides the alphabet in Caesar’s cipher, we will also introduce a key, i.e., a number that represents an offset in the symbol substitution. </p>
<p>This might sound a bit complicated, but it’s very straightforward: it just means how many symbols in the alphabet we have to skip before reaching the corresponding output symbol. </p>
<p>It is always helpful to take a look at an example: with an alphabet defined as <em>al = {X, R, G, A, F, T, I}</em> and a key <em>k = 5</em>, a plaintext <em>pt = “GRAFITTIX”</em> would be encrypted to ciphertext <em>ct = “XIRGFAAFT”</em>. </p>
<p>For symbols closer to the end of the alphabet than the length of a key, we would just continue counting from the beginning of the alphabet. </p>
<p>Such example is a symbol <em>“F”</em> that reaches the end of the alphabet after three skips: <em>“F”</em>,<em> “T”</em>,<em> “I”</em>, and continues symbol skipping for two more symbols from the start of the alphabet: <em>“X”</em>, <em>“R”</em>, and finally lands on the symbol <em>“G”</em>. </p>
<p>We will see how to simplify the skipping process by a calculation in our source code.</p>
<p>Once we have defined and shared the key with our second parties (the recipients), we can start exchanging secret messages. </p>
<p>In the era of Julius Caesar, literacy was not widespread, and ciphertexts were not so easily deciphered. </p>
<p>However, now in the modern era, Caesar’s cipher is no longer considered strong enough. Therefore, we will take a slight detour and have a look at the cipher with a monoalphabetic ordering.</p>
<h2>Python Caesar Cipher</h2>
<p>Here we’ll take a look at our source code and see how the magic happens. The comments are here to help in understanding particular ideas and choices in each of the algorithm steps.</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">def caesars_cipher(message, key=3, operation='encrypt'): # Performs an operation, either 'encrypt' or 'decrypt'. if operation.lower() not in ('encrypt', 'decrypt'): return message # Constructs our alphabet of symbols. alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.' # Sets the encryption/decryption key. key = key % len(alphabet) # Initializes the store for encrypted/decrypted message. translated = '' # Processes each symbol in the message according to the operation and the alphabet. for symbol in message: # Just some housekeeping - the object initialization. shifted_index = -1 # Note: Only symbols in the 'alphabet' can be processed. if symbol in alphabet: symbol_index = alphabet.find(symbol) # Performs the actual operation. if operation == 'encrypt': shifted_index = symbol_index + key elif operation == 'decrypt': shifted_index = symbol_index - key # Handles possible overstepping. if shifted_index >= len(alphabet): shifted_index = shifted_index - len(alphabet) elif shifted_index &lt; 0: shifted_index = shifted_index + len(alphabet) translated = translated + alphabet[shifted_index] else: # Leaves the symbol untouched if it's outside the alphabet: translated = translated + symbol return translated original_message = 'Finxter rules!'
caesars_key = 55 print(f'Original message = {original_message}')
ciphertext = caesars_cipher('Finxter rules!', caesars_key, 'encrypt')
print(f'Ciphertext = {ciphertext}')
plaintext = caesars_cipher(ciphertext, caesars_key, 'decrypt')
print(f'Plaintext = {plaintext}')
</pre>
<h2>The Backstage Math</h2>
<p>If we consider an alphabet of a<sub>N</sub> symbols, the number of ordered alphabets is a<sub>N</sub>! (! is a <a href="https://blog.finxter.com/python-math-factorial/" data-type="post" data-id="37478" target="_blank" rel="noreferrer noopener">factorial</a> operation) and there is a<sub>N</sub>! possible ciphertexts of the same plaintext. </p>
<p>Here we have to notice that having a key with a monoalphabetic substitution would have no effect. This is because it is always possible to generate an alphabet with an ordering that would exactly match Caesar’s cipher with a key. </p>
<p>In other words, each Caesar’s cipher with a specific key can be generalized by exactly one monoalphabetic substitution. </p>
<p>If we take the regular English alphabet of 26 symbols, the number of possible alphabets with unique orderings would amount to 26! ≈ 4 * 10<sup>26</sup> possible ciphertexts (that’s 4 with 26 zeroes!).</p>
<p class="has-global-color-8-background-color has-background"><strong>Note</strong>: If you’re wondering why is this number so large, just consider the following: there are 26 letters in the English alphabet, hence 26 possibilities in picking the first letter. In the next round, for each of these possibilities, there are 25 possibilities in picking the second letter (since the first letter has already been picked). Going all the way, that’s 26 (first pick) * 25 (second pick) * 24 (third pick) * … * 1 (26<sup>th</sup> – last pick) = 26! ≈ 4 * 10<sup>26.</sup></p>
<p>Now we can see that monoalphabetic substitution represents a superset of Caesar’s cipher, and since Caesar’s cipher uses an alphabet with typical alphabetical ordering, it drastically reduces the number of possible ciphertexts to only a<sub>N</sub>-1, which is, in our case, only 25. </p>
<p>With that in mind, Caesar’s ciphertext can easily be attacked by several approaches, such as a brute-force attack or frequency analysis.</p>
<h2>Conclusion</h2>
<p>We learned about Caesar’s Cipher, a simple encryption and decryption algorithm, in this article.</p>
<ul>
<li>First, we made a gentle intro to cryptography.</li>
<li>Second, we encountered some of the fundamental terms in cryptography.</li>
<li>Third, we got acquainted with Caesar’s Cipher.</li>
<li>Fourth, we explained how Caesar’s Cipher works.</li>
<li>Fifth, we took a glance at the source code.</li>
<li>Sixth, we sneaked in the backstage and saw some traces of math behind the algorithm.</li>
</ul>
<h2>Learn More: ROT13 in Python</h2>
<p class="has-pale-cyan-blue-background-color has-background"><strong>ROT13</strong> is a simple <strong>encryption method</strong>. It shifts each character of the clear text string 13 positions forward in the alphabet. </p>
<div class="wp-block-image">
<figure class="aligncenter size-large"><img src="https://media.giphy.com/media/i93KCEDSgF78ngbmTm/source.gif" alt="ROT13 Explanation Gif"/></figure>
</div>
<p>This Python one-liner does ROT13 encryption for you:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="generic" data-enlighter-theme="" data-enlighter-highlight="" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group="">cleartxt = "berlin"
abc = "abcdefghijklmnopqrstuvwxyz"
secret = "".join([abc[(abc.find©+13)%26] for c in cleartxt])
print(secret)
# oreyva</pre>
<p>You can learn more in our full article here:</p>
<ul>
<li><a href="https://blog.finxter.com/how-to-use-rot13-in-python/" data-type="post" data-id="1118" target="_blank" rel="noreferrer noopener">ROT13 in Python – Simply Explained</a></li>
</ul>
<p>The article also comes with a video explanation of the one-liner—check it out!</p>
<hr class="wp-block-separator"/>
</div>


https://www.sickgaming.net/blog/2022/05/...in-python/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016