{"id":131562,"date":"2023-02-01T13:09:16","date_gmt":"2023-02-01T13:09:16","guid":{"rendered":"https:\/\/blog.finxter.com\/?p=1101975"},"modified":"2023-02-01T13:09:16","modified_gmt":"2023-02-01T13:09:16","slug":"two-easy-ways-to-encrypt-and-decrypt-python-strings","status":"publish","type":"post","link":"https:\/\/sickgaming.net\/blog\/2023\/02\/01\/two-easy-ways-to-encrypt-and-decrypt-python-strings\/","title":{"rendered":"Two Easy Ways to Encrypt and Decrypt Python Strings"},"content":{"rendered":"\n<div class=\"kk-star-ratings kksr-auto kksr-align-left kksr-valign-top\" data-payload='{&quot;align&quot;:&quot;left&quot;,&quot;id&quot;:&quot;1101975&quot;,&quot;slug&quot;:&quot;default&quot;,&quot;valign&quot;:&quot;top&quot;,&quot;ignore&quot;:&quot;&quot;,&quot;reference&quot;:&quot;auto&quot;,&quot;class&quot;:&quot;&quot;,&quot;count&quot;:&quot;1&quot;,&quot;legendonly&quot;:&quot;&quot;,&quot;readonly&quot;:&quot;&quot;,&quot;score&quot;:&quot;5&quot;,&quot;starsonly&quot;:&quot;&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;,&quot;font_factor&quot;:&quot;1.25&quot;}'>\n<div class=\"kksr-stars\">\n<div class=\"kksr-stars-inactive\">\n<div class=\"kksr-star\" data-star=\"1\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"2\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"3\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"4\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" data-star=\"5\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<div class=\"kksr-stars-active\" style=\"width: 142.5px;\">\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<div class=\"kksr-star\" style=\"padding-right: 5px\">\n<div class=\"kksr-icon\" style=\"width: 24px; height: 24px;\"><\/div>\n<\/p><\/div>\n<\/p><\/div>\n<\/div>\n<div class=\"kksr-legend\" style=\"font-size: 19.2px;\"> 5\/5 &#8211; (1 vote) <\/div>\n<\/p><\/div>\n<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 &#8212; and decrypt it again after the consultant is done? In this article, I&#8217;ll share my learnings! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f447.png\" alt=\"\ud83d\udc47\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/><\/em><\/p>\n<p class=\"has-base-background-color has-background\"><img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f510.png\" alt=\"\ud83d\udd10\" 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>\n<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>\n<h2>Method 1: Cryptography Library Fernet<\/h2>\n<div class=\"wp-block-image\">\n<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\/uploads\/2023\/02\/image-3-300x181.png 300w\" sizes=\"auto, (max-width: 627px) 100vw, 627px\" \/><\/figure>\n<\/div>\n<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>\n<p>If you haven&#8217;t already, you must first install the <code>cryptography<\/code> library using the <code>pip install cryptography<\/code> shell command or variants thereof. <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f449.png\" alt=\"\ud83d\udc49\" 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>\n<p>Here&#8217;s a minimal example where I&#8217;ve highlighted the encryption and decryption calls:<\/p>\n<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\nfrom cryptography.fernet import Fernet # Generate a Fernet key\nkey = Fernet.generate_key() # Create a Fernet object with that key\nf = Fernet(key) # Input string to be encrypted\ninput_string = \"Hello World!\" # Encrypt the string\nencrypted_string = f.encrypt(input_string.encode()) # Decrypt the encrypted string\ndecrypted_string = f.decrypt(encrypted_string) # Print the original and decrypted strings\nprint(\"Original String:\", input_string)\nprint(\"Decrypted String:\", decrypted_string.decode())<\/pre>\n<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>\n<ul>\n<li>symmetric encryption, <\/li>\n<li>public-key encryption, <\/li>\n<li>hashing, and <\/li>\n<li>digital signatures.<\/li>\n<\/ul>\n<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>\n<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>\n<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>\n<p>The output is as follows:<\/p>\n<pre class=\"wp-block-preformatted\"><code>Original String: Hello World!\nDecrypted String: Hello World!<\/code><\/pre>\n<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>\n<div class=\"wp-block-image\">\n<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\/uploads\/2023\/02\/image-300x223.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/02\/image-768x570.png 768w\" sizes=\"auto, (max-width: 895px) 100vw, 895px\" \/><\/a><\/figure>\n<\/div>\n<h2>Method 2: PyCrypto Cipher<\/h2>\n<div class=\"wp-block-image\">\n<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\/uploads\/2023\/02\/image-4-300x200.png 300w\" sizes=\"auto, (max-width: 627px) 100vw, 627px\" \/><\/figure>\n<\/div>\n<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 &#8220;password&#8221;. Finally, encrypt the string using the AES algorithm, which is a type of symmetric-key encryption. <\/p>\n<p>You can then decrypt the encrypted string again by using the same key.<\/p>\n<p>Here&#8217;s a small example:<\/p>\n<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\nimport Crypto # Input string to be encrypted (padding to adjust length)\ninput_string = \"Hello World!\".rjust(32) # Secret key (pw)\nkey = b'1234567890123456' # Encrypt the string\ncipher = Crypto.Cipher.AES.new(key)\nencrypted_string = cipher.encrypt(input_string.encode()) # Decrypt the encrypted string\ndecrypted_string = cipher.decrypt(encrypted_string) # Print the original and decrypted strings\nprint(\"Original String:\", input_string)\nprint(\"Decrypted String:\", decrypted_string.decode())<\/pre>\n<p>This code imports the PyCrypto library and uses it to encrypt and decrypt a string. <\/p>\n<p>The input string is <code>\"Hello World!\"<\/code>, which is padded to 32 characters to make sure it is the correct length.<\/p>\n<p>Then, a secret key (password) is defined. <\/p>\n<p>The string is encrypted using the AES algorithm, which is a type of symmetric-key encryption. <\/p>\n<p>The encrypted string is then decrypted using the same key and the original and decrypted strings are printed. Here&#8217;s the output:<\/p>\n<pre class=\"wp-block-preformatted\"><code>Original String: Hello World!\nDecrypted String: Hello World!<\/code><\/pre>\n<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>\n<div class=\"wp-block-image\">\n<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\/uploads\/2023\/02\/image-1-300x209.png 300w, https:\/\/blog.finxter.com\/wp-content\/uploads\/2023\/02\/image-1-768x535.png 768w\" sizes=\"auto, (max-width: 872px) 100vw, 872px\" \/><\/a><\/figure>\n<\/div>\n<h2>Thanks for Visiting! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/2665.png\" alt=\"\u2665\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <\/h2>\n<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> &#8212; we have cheat sheets too! <img decoding=\"async\" src=\"https:\/\/s.w.org\/images\/core\/emoji\/14.0.0\/72x72\/1f525.png\" alt=\"\ud83d\udd25\" class=\"wp-smiley\" style=\"height: 1em; max-height: 1em;\" \/> <\/p>\n","protected":false},"excerpt":{"rendered":"<p>5\/5 &#8211; (1 vote) 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 [&hellip;]<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[857],"tags":[73,468,528],"class_list":["post-131562","post","type-post","status-publish","format-standard","hentry","category-python-tut","tag-programming","tag-python","tag-tutorial"],"_links":{"self":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/131562","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/comments?post=131562"}],"version-history":[{"count":0,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/posts\/131562\/revisions"}],"wp:attachment":[{"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/media?parent=131562"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/categories?post=131562"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/sickgaming.net\/blog\/wp-json\/wp\/v2\/tags?post=131562"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}