{"id":2019,"date":"2020-05-09T22:35:09","date_gmt":"2020-05-09T14:35:09","guid":{"rendered":"https:\/\/www.techcoil.com\/blog\/?p=2019"},"modified":"2020-05-12T14:21:53","modified_gmt":"2020-05-12T06:21:53","slug":"how-to-encrypt-and-decrypt-data-in-python-3-using-pycrypto","status":"publish","type":"post","link":"https:\/\/www.techcoil.com\/blog\/how-to-encrypt-and-decrypt-data-in-python-3-using-pycrypto\/","title":{"rendered":"How to encrypt and decrypt data in Python 3 using pycrypto"},"content":{"rendered":"<p>When you wish to encrypt and decrypt data in your Python 3 application, you can take a look at <a href=\"https:\/\/pypi.org\/project\/pycrypto\/\" rel=\"noopener\" target=\"_blank\">pycrypto<\/a>. <\/p>\n<p>Given that, let us look at how we can encrypt and decrypt data in Python 3 using pycrpto.<\/p>\n<h2>Installing pycrypto into your Python 3 environment<\/h2>\n<p>In order to use pycrypto, we need to install it. <\/p>\n<p>Therefore, run the following command to install pycrypto into your Python 3 environment:<\/p>\n<pre class=\"brush: bash; title: ; notranslate\" title=\"\">\r\npip pycrypto\r\n<\/pre>\n<h2>Getting an instance of the AES to encrypt and decrypt data with the AES encryption algorithm<\/h2>\n<p>After you had installed pycrypto in your Python 3 environment, you can then choose an encryption algorithm to encrypt and decrypt your data.<\/p>\n<p>For example, you can write the following Python 3 codes to get an object to encrypt \/ decrypt data with the AES encryption algorithm:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom Crypto.Cipher import AES\r\n\r\n# AES key must be either 16, 24, or 32 bytes long\r\nCOMMON_ENCRYPTION_KEY='asdjk@15r32r1234asdsaeqwe314SEFT'\r\n# Make sure the initialization vector is 16 bytes\r\nCOMMON_16_BYTE_IV_FOR_AES='IVIVIVIVIVIVIVIV'\r\n\r\ndef get_common_cipher():\r\n    return AES.new(COMMON_ENCRYPTION_KEY,\r\n                   AES.MODE_CBC,\r\n                   COMMON_16_BYTE_IV_FOR_AES)\r\n<\/pre>\n<p>As shown above, we first import the <a href=\"https:\/\/www.dlitz.net\/software\/pycrypto\/api\/current\/Crypto.Cipher.AES-module.html\" rel=\"noopener\" target=\"_blank\">AES module<\/a>. After we had done so, we define an encryption key that is 32 bytes long. In case you are wondering, this key must be either 16, 24 or 32 bytes long. <\/p>\n<p>After that, we define an initialization vector that must be 16 bytes long.<\/p>\n<p>Once we have defined the key and initialization vector, we then define a function to get an AES cipher instance. <\/p>\n<p>Whenever we need to perform encryption or decryption, we can use the <code>get_common_cipher<\/code> function. <\/p>\n<p><strong>Since the cipher object is stateful, we should create a new AES cipher instance whenever we wish to encrypt or decrypt data<\/strong>. <\/p>\n<h2>How to encrypt string in Python 3 using pycrypto<\/h2>\n<p>When we represent our data as string or text, we can transfer our data easily with <a href=\"https:\/\/www.techcoil.com\/glossary\/http\/\" rel=\"noopener\" target=\"_blank\">HTTP<\/a>.<\/p>\n<p>Given that, let's look at how we can define a function to encrypt string:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport base64\r\nimport math\r\ndef encrypt_with_common_cipher(cleartext):\r\n    common_cipher = get_common_cipher()\r\n    cleartext_length = len(cleartext)\r\n    next_multiple_of_16 = 16 * math.ceil(cleartext_length\/16)\r\n    padded_cleartext = cleartext.rjust(next_multiple_of_16)\r\n    raw_ciphertext = common_cipher.encrypt(padded_cleartext)\r\n    return base64.b64encode(raw_ciphertext).decode('utf-8')\r\n<\/pre>\n<p>As shown above, we first import the <a href=\"https:\/\/docs.python.org\/3\/library\/base64.html\" rel=\"noopener\" target=\"_blank\"><code>base64<\/code><\/a> and <a href=\"https:\/\/docs.python.org\/3\/library\/math.html\" rel=\"noopener\" target=\"_blank\"><code>math<\/code><\/a> modules.<\/p>\n<p>Once we have done so, we define a function <code>encrypt_with_common_cipher<\/code> that takes a string as an input.<\/p>\n<p>When the function is called, we first get an instance of the AES cipher to perform the encryption.<\/p>\n<p>Since the cipher does not pad our data, we need to do that on our own. Therefore, we first get the length of the text data to compute the next multiple of 16. Once we get the next multiple of 16, we use the <a href=\"https:\/\/docs.python.org\/3\/library\/stdtypes.html#str.rjust\" rel=\"noopener\" target=\"_blank\"><code>rjust<\/code><\/a> method to pad the <code>cleartext<\/code> with spaces. <\/p>\n<p>Once we had padded our string data to make its size a multiple of 16, we then encrypt it with the AES cipher. When we do so, <strong>raw_ciphertext<\/strong> will contain the corresponding cipher text in bytes. <\/p>\n<p>In order to convert the <code>raw_ciphertext<\/code> to a string, we call <a href=\"https:\/\/docs.python.org\/3\/library\/base64.html#base64.b64encode\" rel=\"noopener\" target=\"_blank\"><code>base64.b64encode<\/code><\/a> on <code>raw_ciphertext<\/code>, followed by <a href=\"https:\/\/docs.python.org\/3\/library\/stdtypes.html?highlight=decode#bytearray.decode\" rel=\"noopener\" target=\"_blank\"><code>decode<\/code><\/a> before returning the result to the caller.<\/p>\n<h2>How to decrypt string in Python 3 using pycrypto <\/h2>\n<p>Whenever we encrypt our string data, there will be a point in time when we want to decrypt it.<\/p>\n<p>Given that, we can define a function to decrypt the cipher text that was created by <code>encrypt_with_common_cipher<\/code>:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\ndef decrypt_with_common_cipher(ciphertext):\r\n    common_cipher = get_common_cipher()\r\n    raw_ciphertext = base64.b64decode(ciphertext)\r\n    decrypted_message_with_padding = common_cipher.decrypt(raw_ciphertext)\r\n    return decrypted_message_with_padding.decode('utf-8').strip()\r\n<\/pre>\n<p>Similar to <code>encrypt_with_common_cipher<\/code>, we first get an instance of the AES cipher with the same key and initialization vector.<\/p>\n<p>Next, we take the <code>ciphertext<\/code>, convert it back to bytes and kept it as <code>raw_ciphertext<\/code>.<\/p>\n<p>Once we get back the cipher text in bytes, we use our AES cipher to decrypt it. <\/p>\n<p>When we do so, we will get the decrypted message with padding.<\/p>\n<p>Finally, we decode <code>decrypted_message_with_padding<\/code> as a string, call <a href=\"https:\/\/docs.python.org\/3\/library\/stdtypes.html#str.strip\" rel=\"noopener\" target=\"_blank\"><code>strip<\/code><\/a> to remove the spaces and return the result to the caller.<\/p>\n<h2>How to encrypt JSON data in Python 3 using pycrypto<\/h2>\n<p>At this point in time, encrypting JSON data will be straightforward:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport json\r\ndef encrypt_json_with_common_cipher(json_obj):\r\n    json_string = json.dumps(json_obj)\r\n    return encrypt_with_common_cipher(json_string)\r\n<\/pre>\n<p>As shown above, we can define a <code>encrypt_json_with_common_cipher<\/code> function that takes a JSON object as input.<\/p>\n<p>When the function is called, we use <a href=\"https:\/\/docs.python.org\/3\/library\/json.html#json.dumps\" rel=\"noopener\" target=\"_blank\"><code>json.dumps<\/code><\/a> to convert the JSON object into a JSON string.<\/p>\n<p>Once we have the JSON string, we pass it to the <code>encrypt_with_common_cipher<\/code> function and return the result back to the caller.<\/p>\n<h2>How to decrypt JSON data in Python 3 using pycrypto<\/h2>\n<p>When we want to get back the JSON data that we had encrypted, we can define the following function:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nimport json\r\ndef decrypt_json_with_common_cipher(json_ciphertext):\r\n    json_string = decrypt_with_common_cipher(json_ciphertext)\r\n    return json.loads(json_string)\r\n<\/pre>\n<p>As shown above, the <code>decrypt_json_with_common_cipher<\/code> function takes in a JSON cipher text as an input.<\/p>\n<p>When the function is called, we call the decrypt_with_common_cipher function to get back the JSON string.<\/p>\n<p>Once we have the JSON string, we use <a href=\"https:\/\/docs.python.org\/3\/library\/json.html#json.loads\" rel=\"noopener\" target=\"_blank\"><code>json.loads<\/code><\/a> to get back the JSON object and return it back to the caller.<\/p>\n<h2>Putting everything together<\/h2>\n<p>In case you want a running example of what was discussed, you can run the following script:<\/p>\n<pre class=\"brush: python; title: ; notranslate\" title=\"\">\r\nfrom Crypto.Cipher import AES\r\n\r\nimport base64, json, math\r\n\r\n# AES key must be either 16, 24, or 32 bytes long\r\nCOMMON_ENCRYPTION_KEY='asdjk@15r32r1234asdsaeqwe314SEFT'\r\n# Make sure the initialization vector is 16 bytes\r\nCOMMON_16_BYTE_IV_FOR_AES='IVIVIVIVIVIVIVIV'\r\n\r\ndef get_common_cipher():\r\n    return AES.new(COMMON_ENCRYPTION_KEY,\r\n                   AES.MODE_CBC,\r\n                   COMMON_16_BYTE_IV_FOR_AES)\r\n\r\ndef encrypt_with_common_cipher(cleartext):\r\n    common_cipher = get_common_cipher()\r\n    cleartext_length = len(cleartext)\r\n    nearest_multiple_of_16 = 16 * math.ceil(cleartext_length\/16)\r\n    padded_cleartext = cleartext.rjust(nearest_multiple_of_16)\r\n    raw_ciphertext = common_cipher.encrypt(padded_cleartext)\r\n    return base64.b64encode(raw_ciphertext).decode('utf-8')\r\n\r\n\r\ndef decrypt_with_common_cipher(ciphertext):\r\n    common_cipher = get_common_cipher()\r\n    raw_ciphertext = base64.b64decode(ciphertext)\r\n    decrypted_message_with_padding = common_cipher.decrypt(raw_ciphertext)\r\n    return decrypted_message_with_padding.decode('utf-8').strip()\r\n\r\n\r\ndef encrypt_json_with_common_cipher(json_obj):\r\n    json_string = json.dumps(json_obj)\r\n    return encrypt_with_common_cipher(json_string)\r\n\r\n\r\ndef decrypt_json_with_common_cipher(json_ciphertext):\r\n    json_string = decrypt_with_common_cipher(json_ciphertext)\r\n    return json.loads(json_string)\r\n\r\nmessage = 'This is obviously a secret message.'\r\n\r\nciphertext = encrypt_with_common_cipher(message)\r\nprint('Cipher text: %s' % ciphertext)\r\n\r\ndecrypted_message = decrypt_with_common_cipher(ciphertext)\r\nprint('Decrypted message: %s' % decrypted_message)\r\n\r\njson_obj = {\r\n    'fruits': &#x5B;'apple', 'pear', 'orange']\r\n}\r\n\r\njson_ciphertext = encrypt_json_with_common_cipher(json_obj)\r\nprint('JSON cipher text: ')\r\nprint(json_ciphertext)\r\n\r\ndecryped_json_obj = decrypt_json_with_common_cipher(json_ciphertext)\r\nprint('Decrypted JSON object: ')\r\nprint(decryped_json_obj)\r\n<\/pre>\n<p>After the function definition for <code>decrypt_json_with_common_cipher<\/code>, we proceeded to encrypt and decrypt a string and a JSON object.<\/p>\n<p>When you run the script, you should get the following output:<\/p>\n<pre class=\"brush: plain; title: ; notranslate\" title=\"\">\r\nCipher text: Qq3sD\/JX0M2Uo5anotgnBhZvyM\/KHGWc\/Eaoin1ocnoTrPNSZpKUUKtTuzW+ocJs\r\nDecrypted message: This is obviously a secret message.\r\nJSON cipher text: \r\nTj\/KLrTiFQfUJtQOe9FuUkHoMI4BKxjQAtrPyAYxGpDrlOvtcLIUKhVmRhloqNdm\r\nDecrypted JSON object: \r\n{'fruits': &#x5B;'apple', 'pear', 'orange']}\r\n<\/pre>\n\n      <ul id=\"social-sharing-buttons-list\">\n        <li class=\"facebook\">\n          <a href=\"https:\/\/www.facebook.com\/sharer\/sharer.php?u=https%3A%2F%2Fwp.me%2Fp245TQ-wz\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n            <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Facebook.png\" alt=\"Facebook icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"twitter\">\n          <a href=\"https:\/\/twitter.com\/intent\/tweet?text=&url=https%3A%2F%2Fwp.me%2Fp245TQ-wz&via=Techcoil_com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Twitter.png\" alt=\"Twitter icon\"> Tweet\n          <\/a>\n        <\/li>\n        <li class=\"linkedin\">\n          <a href=\"https:\/\/www.linkedin.com\/shareArticle?mini=1&title=&url=https%3A%2F%2Fwp.me%2Fp245TQ-wz&source=https:\/\/www.techcoil.com\" target=\"_blank\" role=\"button\" rel=\"nofollow\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/linkedin.png\" alt=\"Linkedin icon\"> Share\n          <\/a>\n        <\/li>\n        <li class=\"pinterest\">\n          <a href=\"https:\/\/pinterest.com\/pin\/create\/button\/?url=https%3A%2F%2Fwww.techcoil.com%2Fblog%2Fwp-json%2Fwp%2Fv2%2Fposts%2F2019&description=\" class=\"pin-it-button\" target=\"_blank\" role=\"button\" rel=\"nofollow\" count-layout=\"horizontal\">\n          <img decoding=\"async\" src=\"\/ph\/img\/3rd-party\/social-icons\/Pinterest.png\" alt=\"Pinterest icon\"> Save\n          <\/a>\n        <\/li>\n      <\/ul>\n    ","protected":false},"excerpt":{"rendered":"<p>When you wish to encrypt and decrypt data in your Python 3 application, you can take a look at <a href=\"https:\/\/pypi.org\/project\/pycrypto\/\" rel=\"noopener\" target=\"_blank\">pycrypto<\/a>. <\/p>\n<p>Given that, let us look at how we can encrypt and decrypt data in Python 3 using pycrpto.<\/p>\n","protected":false},"author":1,"featured_media":1244,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"advanced_seo_description":"","jetpack_seo_html_title":"","jetpack_seo_noindex":false,"jetpack_post_was_ever_published":false,"_jetpack_newsletter_access":"","_jetpack_dont_email_post_to_subs":false,"_jetpack_newsletter_tier_id":0,"footnotes":""},"categories":[375],"tags":[733,734,731,732,730,226,233],"jetpack_featured_media_url":"https:\/\/www.techcoil.com\/blog\/wp-content\/uploads\/Python-Logo.gif","jetpack_shortlink":"https:\/\/wp.me\/p245TQ-wz","jetpack-related-posts":[],"jetpack_likes_enabled":true,"jetpack_sharing_enabled":true,"_links":{"self":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/2019"}],"collection":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/comments?post=2019"}],"version-history":[{"count":0,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/posts\/2019\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media\/1244"}],"wp:attachment":[{"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/media?parent=2019"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/categories?post=2019"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.techcoil.com\/blog\/wp-json\/wp\/v2\/tags?post=2019"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}