02-02-2023, 12:29 PM
Two Easy Ways to Encrypt and Decrypt Python Strings
<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{"align":"left","id":"1101975","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","legendonly":"","readonly":"","score":"5","starsonly":"","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}'>
<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" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</p></div>
<p><em>Today I gave a service consultant access to one of my AWS servers. I have a few files on the server that I was reluctant to share with the service consultant because these files contain sensitive personal data. Python is my default way to solve these types of problems. Naturally, I wondered how to encrypt this data using Python — and decrypt it again after the consultant is done? In this article, I’ll share my learnings! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></em></p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f510.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: Given a Python string. How to encrypt the Python string using a password or otherwise and decrypt the encrypted phrase to obtain the initial cleartext again?</p>
<p>There are several ways to encrypt and decrypt Python strings. I decided to share only the top two ways (my personal preference is <strong>Method 1</strong>):</p>
<h2>Method 1: Cryptography Library Fernet</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="627" height="379" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-3.png" alt="" class="wp-image-1102005" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-3.png 627w, https://blog.finxter.com/wp-content/uplo...00x181.png 300w" sizes="(max-width: 627px) 100vw, 627px" /></figure>
</div>
<p class="has-global-color-8-background-color has-background">To encrypt and decrypt a Python string, install and import the <code>cryptography</code> library, generate a Fernet key, and create a <code>Fernet</code> object with it. You can then encrypt the string using the <code>Fernet.encrypt()</code> method and decrypt the encrypted string using the <code>Fernet.decrypt()</code> method.</p>
<p>If you haven’t already, you must first install the <code>cryptography</code> library using the <code>pip install cryptography</code> shell command or variants thereof. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-cryptography-in-python/" data-type="post" data-id="35850" target="_blank">See more here.</a></p>
<p>Here’s a minimal example where I’ve highlighted the encryption and decryption calls:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="14,17" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Import the cryptography library
from cryptography.fernet import Fernet # Generate a Fernet key
key = Fernet.generate_key() # Create a Fernet object with that key
f = Fernet(key) # Input string to be encrypted
input_string = "Hello World!" # Encrypt the string
encrypted_string = f.encrypt(input_string.encode()) # Decrypt the encrypted string
decrypted_string = f.decrypt(encrypted_string) # Print the original and decrypted strings
print("Original String:", input_string)
print("Decrypted String:", decrypted_string.decode())</pre>
<p>This small script first imports the <code>Fernet</code> class from the <code>cryptography</code> library that provides high-level cryptographic primitives and algorithms such as </p>
<ul>
<li>symmetric encryption, </li>
<li>public-key encryption, </li>
<li>hashing, and </li>
<li>digital signatures.</li>
</ul>
<p>A Fernet key is then generated and used to create a <code>Fernet</code> object. The input string to be encrypted is then provided as an argument to the <code>encrypt()</code> method of the <code>Fernet</code> object. This method encrypts the string using the Fernet key and returns an encrypted string.</p>
<p>The encrypted string is then provided as an argument to the <code>decrypt()</code> method of the <code>Fernet</code> object. This method decrypts the encrypted string using the Fernet key and returns a decrypted string.</p>
<p>Finally, the original string and the decrypted string are <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">printed</a> to the console.</p>
<p>The output is as follows:</p>
<pre class="wp-block-preformatted"><code>Original String: Hello World!
Decrypted String: Hello World!</code></pre>
<p>Try it yourself in our <a href="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" data-type="URL" data-id="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" target="_blank" rel="noreferrer noopener">Jupyter Notebook</a>:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" target="_blank" rel="noreferrer noopener"><img decoding="async" loading="lazy" width="895" height="664" src="https://blog.finxter.com/wp-content/uploads/2023/02/image.png" alt="" class="wp-image-1102001" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image.png 895w, https://blog.finxter.com/wp-content/uplo...00x223.png 300w, https://blog.finxter.com/wp-content/uplo...68x570.png 768w" sizes="(max-width: 895px) 100vw, 895px" /></a></figure>
</div>
<h2>Method 2: PyCrypto Cipher</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="627" height="418" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-4.png" alt="" class="wp-image-1102006" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-4.png 627w, https://blog.finxter.com/wp-content/uplo...00x200.png 300w" sizes="(max-width: 627px) 100vw, 627px" /></figure>
</div>
<p class="has-global-color-8-background-color has-background">Install and import the PyCrypto library to encrypt and decrypt a string. As preparation, you need to make sure to pad the input string to 32 characters using <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-rjust/" data-type="post" data-id="26089" target="_blank">string.rjust(32)</a></code> to make sure it is the correct length. Then, define a secret key, i.e., a “password”. Finally, encrypt the string using the AES algorithm, which is a type of symmetric-key encryption. </p>
<p>You can then decrypt the encrypted string again by using the same key.</p>
<p>Here’s a small example:</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=""># Import the PyCrypto library
import Crypto # Input string to be encrypted (padding to adjust length)
input_string = "Hello World!".rjust(32) # Secret key (pw)
key = b'1234567890123456' # Encrypt the string
cipher = Crypto.Cipher.AES.new(key)
encrypted_string = cipher.encrypt(input_string.encode()) # Decrypt the encrypted string
decrypted_string = cipher.decrypt(encrypted_string) # Print the original and decrypted strings
print("Original String:", input_string)
print("Decrypted String:", decrypted_string.decode())</pre>
<p>This code imports the PyCrypto library and uses it to encrypt and decrypt a string. </p>
<p>The input string is <code>"Hello World!"</code>, which is padded to 32 characters to make sure it is the correct length.</p>
<p>Then, a secret key (password) is defined. </p>
<p>The string is encrypted using the AES algorithm, which is a type of symmetric-key encryption. </p>
<p>The encrypted string is then decrypted using the same key and the original and decrypted strings are printed. Here’s the output:</p>
<pre class="wp-block-preformatted"><code>Original String: Hello World!
Decrypted String: Hello World!</code></pre>
<p>Try it yourself in our <a rel="noreferrer noopener" href="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" data-type="URL" data-id="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" target="_blank">Jupyter Notebook</a>:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" target="_blank" rel="noreferrer noopener"><img decoding="async" loading="lazy" width="872" height="608" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-1.png" alt="" class="wp-image-1102002" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-1.png 872w, https://blog.finxter.com/wp-content/uplo...00x209.png 300w, https://blog.finxter.com/wp-content/uplo...68x535.png 768w" sizes="(max-width: 872px) 100vw, 872px" /></a></figure>
</div>
<h2>Thanks for Visiting! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2665.png" alt="♥" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </h2>
<p>To keep learning Python in practical coding projects, check out our free <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank" rel="noreferrer noopener">email academy</a> — we have cheat sheets too! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f525.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>
</div>
https://www.sickgaming.net/blog/2023/02/...n-strings/
<div>
<div class="kk-star-ratings kksr-auto kksr-align-left kksr-valign-top" data-payload='{"align":"left","id":"1101975","slug":"default","valign":"top","ignore":"","reference":"auto","class":"","count":"1","legendonly":"","readonly":"","score":"5","starsonly":"","best":"5","gap":"5","greet":"Rate this post","legend":"5\/5 - (1 vote)","size":"24","width":"142.5","_legend":"{score}\/{best} - ({count} {votes})","font_factor":"1.25"}'>
<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" style="font-size: 19.2px;"> 5/5 – (1 vote) </div>
</p></div>
<p><em>Today I gave a service consultant access to one of my AWS servers. I have a few files on the server that I was reluctant to share with the service consultant because these files contain sensitive personal data. Python is my default way to solve these types of problems. Naturally, I wondered how to encrypt this data using Python — and decrypt it again after the consultant is done? In this article, I’ll share my learnings! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f447.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /></em></p>
<p class="has-base-background-color has-background"><img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f510.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <strong>Question</strong>: Given a Python string. How to encrypt the Python string using a password or otherwise and decrypt the encrypted phrase to obtain the initial cleartext again?</p>
<p>There are several ways to encrypt and decrypt Python strings. I decided to share only the top two ways (my personal preference is <strong>Method 1</strong>):</p>
<h2>Method 1: Cryptography Library Fernet</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img loading="lazy" decoding="async" width="627" height="379" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-3.png" alt="" class="wp-image-1102005" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-3.png 627w, https://blog.finxter.com/wp-content/uplo...00x181.png 300w" sizes="(max-width: 627px) 100vw, 627px" /></figure>
</div>
<p class="has-global-color-8-background-color has-background">To encrypt and decrypt a Python string, install and import the <code>cryptography</code> library, generate a Fernet key, and create a <code>Fernet</code> object with it. You can then encrypt the string using the <code>Fernet.encrypt()</code> method and decrypt the encrypted string using the <code>Fernet.decrypt()</code> method.</p>
<p>If you haven’t already, you must first install the <code>cryptography</code> library using the <code>pip install cryptography</code> shell command or variants thereof. <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f449.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> <a rel="noreferrer noopener" href="https://blog.finxter.com/how-to-install-cryptography-in-python/" data-type="post" data-id="35850" target="_blank">See more here.</a></p>
<p>Here’s a minimal example where I’ve highlighted the encryption and decryption calls:</p>
<pre class="EnlighterJSRAW" data-enlighter-language="python" data-enlighter-theme="" data-enlighter-highlight="14,17" data-enlighter-linenumbers="" data-enlighter-lineoffset="" data-enlighter-title="" data-enlighter-group=""># Import the cryptography library
from cryptography.fernet import Fernet # Generate a Fernet key
key = Fernet.generate_key() # Create a Fernet object with that key
f = Fernet(key) # Input string to be encrypted
input_string = "Hello World!" # Encrypt the string
encrypted_string = f.encrypt(input_string.encode()) # Decrypt the encrypted string
decrypted_string = f.decrypt(encrypted_string) # Print the original and decrypted strings
print("Original String:", input_string)
print("Decrypted String:", decrypted_string.decode())</pre>
<p>This small script first imports the <code>Fernet</code> class from the <code>cryptography</code> library that provides high-level cryptographic primitives and algorithms such as </p>
<ul>
<li>symmetric encryption, </li>
<li>public-key encryption, </li>
<li>hashing, and </li>
<li>digital signatures.</li>
</ul>
<p>A Fernet key is then generated and used to create a <code>Fernet</code> object. The input string to be encrypted is then provided as an argument to the <code>encrypt()</code> method of the <code>Fernet</code> object. This method encrypts the string using the Fernet key and returns an encrypted string.</p>
<p>The encrypted string is then provided as an argument to the <code>decrypt()</code> method of the <code>Fernet</code> object. This method decrypts the encrypted string using the Fernet key and returns a decrypted string.</p>
<p>Finally, the original string and the decrypted string are <a href="https://blog.finxter.com/python-print/" data-type="post" data-id="20731" target="_blank" rel="noreferrer noopener">printed</a> to the console.</p>
<p>The output is as follows:</p>
<pre class="wp-block-preformatted"><code>Original String: Hello World!
Decrypted String: Hello World!</code></pre>
<p>Try it yourself in our <a href="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" data-type="URL" data-id="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" target="_blank" rel="noreferrer noopener">Jupyter Notebook</a>:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" target="_blank" rel="noreferrer noopener"><img decoding="async" loading="lazy" width="895" height="664" src="https://blog.finxter.com/wp-content/uploads/2023/02/image.png" alt="" class="wp-image-1102001" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image.png 895w, https://blog.finxter.com/wp-content/uplo...00x223.png 300w, https://blog.finxter.com/wp-content/uplo...68x570.png 768w" sizes="(max-width: 895px) 100vw, 895px" /></a></figure>
</div>
<h2>Method 2: PyCrypto Cipher</h2>
<div class="wp-block-image">
<figure class="aligncenter size-full"><img decoding="async" loading="lazy" width="627" height="418" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-4.png" alt="" class="wp-image-1102006" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-4.png 627w, https://blog.finxter.com/wp-content/uplo...00x200.png 300w" sizes="(max-width: 627px) 100vw, 627px" /></figure>
</div>
<p class="has-global-color-8-background-color has-background">Install and import the PyCrypto library to encrypt and decrypt a string. As preparation, you need to make sure to pad the input string to 32 characters using <code><a rel="noreferrer noopener" href="https://blog.finxter.com/python-string-rjust/" data-type="post" data-id="26089" target="_blank">string.rjust(32)</a></code> to make sure it is the correct length. Then, define a secret key, i.e., a “password”. Finally, encrypt the string using the AES algorithm, which is a type of symmetric-key encryption. </p>
<p>You can then decrypt the encrypted string again by using the same key.</p>
<p>Here’s a small example:</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=""># Import the PyCrypto library
import Crypto # Input string to be encrypted (padding to adjust length)
input_string = "Hello World!".rjust(32) # Secret key (pw)
key = b'1234567890123456' # Encrypt the string
cipher = Crypto.Cipher.AES.new(key)
encrypted_string = cipher.encrypt(input_string.encode()) # Decrypt the encrypted string
decrypted_string = cipher.decrypt(encrypted_string) # Print the original and decrypted strings
print("Original String:", input_string)
print("Decrypted String:", decrypted_string.decode())</pre>
<p>This code imports the PyCrypto library and uses it to encrypt and decrypt a string. </p>
<p>The input string is <code>"Hello World!"</code>, which is padded to 32 characters to make sure it is the correct length.</p>
<p>Then, a secret key (password) is defined. </p>
<p>The string is encrypted using the AES algorithm, which is a type of symmetric-key encryption. </p>
<p>The encrypted string is then decrypted using the same key and the original and decrypted strings are printed. Here’s the output:</p>
<pre class="wp-block-preformatted"><code>Original String: Hello World!
Decrypted String: Hello World!</code></pre>
<p>Try it yourself in our <a rel="noreferrer noopener" href="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" data-type="URL" data-id="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" target="_blank">Jupyter Notebook</a>:</p>
<div class="wp-block-image">
<figure class="aligncenter size-full"><a href="https://colab.research.google.com/drive/1CMhBJQew2nrlHimvFmR26bULz5J1hknv?usp=sharing" target="_blank" rel="noreferrer noopener"><img decoding="async" loading="lazy" width="872" height="608" src="https://blog.finxter.com/wp-content/uploads/2023/02/image-1.png" alt="" class="wp-image-1102002" srcset="https://blog.finxter.com/wp-content/uploads/2023/02/image-1.png 872w, https://blog.finxter.com/wp-content/uplo...00x209.png 300w, https://blog.finxter.com/wp-content/uplo...68x535.png 768w" sizes="(max-width: 872px) 100vw, 872px" /></a></figure>
</div>
<h2>Thanks for Visiting! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/2665.png" alt="♥" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </h2>
<p>To keep learning Python in practical coding projects, check out our free <a href="https://blog.finxter.com/email-academy/" data-type="page" data-id="12278" target="_blank" rel="noreferrer noopener">email academy</a> — we have cheat sheets too! <img src="https://s.w.org/images/core/emoji/14.0.0/72x72/1f525.png" alt="?" class="wp-smiley" style="height: 1em; max-height: 1em;" /> </p>
</div>
https://www.sickgaming.net/blog/2023/02/...n-strings/