Implementing cryptography with Python - LogRocket Blog (2024)

What is cryptography?

Cryptography is the art of creating a secure communication channel by encrypting and decrypting data using code, meaning that no one other than the destined person can see the transmitted data.

Implementing cryptography with Python - LogRocket Blog (1)

Cryptography mainly uses mathematical principles and a series of formulas and algorithms to encrypt messages so that decrypting these messages becomes impossible. It’s used everywhere in today’s world, from securing day-to-day communication in social media platforms to securing banking transaction activity for online e-commerce.

What are the different types of cryptography?

There are three primary types of cryptography:

  1. Symmetric key cryptography
  2. Asymmetric key cryptography
  3. Hashing

Let’s look at each one in-depth!

Symmetric key cryptography

Symmetric key cryptography is one of the fastest and easiest ways to decrypt and encrypt messages. It mainly involves using a single key, called a secret key, used for encrypting and decrypting the data. It’s also referred to as private-key cryptography, as well as secret-key, shared-key, one-key, and private-key encryption.

The data is converted into a form that is not understood by anyone, making the data secure from an attacker. It’s used primarily for encrypting large amounts of data. Symmetric key cryptography has two method types, which are used to convert plain text to ciphertext: block ciphers and stream ciphers.

Block ciphers use the algorithm mode of Electronic Code Block (ECB) and Cipher Code Block (CBC). These take text inputs and convert them into ciphertext by taking a block of text and generating a ciphertext of the same size. Block ciphers are relatively slower than stream ciphers, as a block of text needs to be covered, encrypted, and decrypted.

Stream ciphers, on the other hand, use Ciphertext Feedback (CFB) and Output Feedback (OFB) modes, which convert plain text into ciphertext by taking an input of 1 byte at once, making stream cipher faster than block cipher. Stream cipher uses XOR for converting plaintext into ciphertext.

Some examples of symmetric key algorithms are:

Caesar cipher with Python

Caesar cipher is one example of symmetric key cryptography, and it’s one of the oldest and easiest ways to implement cryptography. Caesar cipher is a substitution cipher in which alphabets shift their order by a fixed number of positions.

Encrypting and decrypting Caesar cipher is easy, as the method is fixed and no key is required. Thus, anyone who knows the method will be able to decrypt the message easily.

For example, a simple word like “cat,” will be encrypted as “fdw,” if you shift each letter three letters in the alphabet. This makes the word “cat” difficult to understand if you’re unaware of the way it was encrypted.

Now, let’s create a simple Python program for encrypting and decrypting cipher text:

alphabets = 'abcdefghijklmnopqrstuvwxyz'def encrypt_caesar(num, text): result = ' ' for k in text.lower(): try: i = (alphabets.index(k) + num) % 26 results += alphabets[i] except ValueError: results+= k return results.lower()num =int(input("please input the shift:\t"))text=input("please input the text: \t")ciphertext = encrypt_caesar(num, text)print(“Encoded text:”,ciphertext)

Here’s the result:

Implementing cryptography with Python - LogRocket Blog (2)

First, we created a variable named alphabets in which we have written all the alphabet letters. Then, we created a function named encrypt_ceaser(num, text) in which we will put the shift key and the text that has to be encrypted.

for k in text.lower():

By using a for loop, we would insert the input string in lowercase.

for k in text.lower(): try: i = (alphabets.index(k) - num) % 26 results += key[i] except ValueError: results += k return results.lower()

The try method and except method, ValueError, is used to catch errors between the program. After try, we count the letters in the string using index.

Over 200k developers use LogRocket to create better digital experiencesLearn more →

All of the alphabets in the text are added with the shift key and then divided by 26. Once the loop is complete, the letters are shifted by the shift value.

num =int(input("Please input the shift:\t"))text=input("Please input the text: \t")ciphertext = decrypt_caesar(num, text)print ("Decoded text:",ciphertext)

With the input() method, we take user input for the program. Then, a variable is created in ciphertext, which we call encrypt_caesar( num, text). The print statement is used to print the encoded ciphertext.

Now, to decrypt the text, we will subtract by the same key value: 3

alphabets= 'abcdefghijklmnopqrstuvwxyz'def decrypt_caesar(num, text): results = '' for k in text.lower(): try: i = (alphabets.index(k) - num) % 26 results +=alphabets[i] except ValueError: results += k return results.lower()num =int(input("please input the shift:\t"))text=input("please input the text: \t")ciphertext = decrypt_caesar(num, text)print(“Decoded text:”,ciphertext)

Here’s the result of the decrypted text.

Implementing cryptography with Python - LogRocket Blog (5)

Although this program is very similar to the previous program we created, we’ve made a few minor changes to decrypt the text.

Instead of using i = (alphabets.index(k) + num) % 26 we used a - in i = (alphabets.index(k) - num) % 26 which decodes the ciphertext.

Asymmetric key cryptography

Asymmetric key encryption is more complex and slower than symmetric cryptography. Also known as public-key cryptography, it involves using two different keys (and sometimes more) for encrypting and decrypting the data.

Essentially, a public key will be used to encrypt data, and only a corresponding private key will be able to decrypt the data, making the asymmetric key more secure.

More great articles from LogRocket:

  • Don't miss a moment with The Replay, a curated newsletter from LogRocket
  • Learn how LogRocket's Galileo cuts through the noise to proactively resolve issues in your app
  • Use React's useEffect to optimize your application's performance
  • Switch between multiple versions of Node
  • Discover how to use the React children prop with TypeScript
  • Explore creating a custom mouse cursor with CSS
  • Advisory boards aren’t just for executives. Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.

For example, you’re using asymmetric cryptography right now while reading this blog post. The lock symbol near your HTTPS website URL indicates that you are connected to this website securely using SSL/TLS certificates.

Asymmetric key encryption verifies the identity of the server and creates asymmetric encryption.

Some examples of asymmetric key algorithms are:

  • Rivest–Shamir–Adleman (RSA)
  • Digital Signature Algorithm (DSA)
  • Elliptic-curve cryptography (ECC)

Let’s generate an RSA key with Python using a Python package called Cryptodome:

from Crypto.PublicKey import RSAkey = RSA.generate(3072)file= open('Rsakey.pem','wb')file.write(key.exportKey('PEM'))file.close()

Let’s install Cryptodome:

pip install cryptodome

To generate a key, we would use key.generate(bit size). The bit size must be between 2048-4096 to make the key secure and lengthy.

file = open('Rsakey.pem','wb')

Here, wb **means to “write in binary.”

Next, let’s create a .pem (Privacy-Enhanced Mail), a file format used for storing cryptographic keys and certificates

file.write(key.exportkey('PEM'))

We will use the .write function to print the key in the file and use .exportkey to export the file in PEM format. Finally, we’ll close the file by using file.close.

Open the Rsakey.pem file:

Implementing cryptography with Python - LogRocket Blog (6)

Hashing

Hashing is the process of converting input of any length into a fixed-size string of text using mathematical algorithms. This means that any size of text, no matter how long it is, can be converted into an array of numbers and alphabets by an algorithm.

The mathematical algorithm used to convert the text is called a hash function, and the output is called a hash value. Hash algorithms are designed to be irreversible, making them secure from an attacker.

Hashing is used for user authentication and storing passwords. MD5 and SHA-1 hashing were used earlier for authentication and storing passwords, but they have since deprecated because they are insecure. Currently, the most secure algorithms are Argon2, bycrpt and scrypt, and PBKDF2.

Now, let’s create a simple hashing program so we can encrypt a string. First, let’s see how many hashing algorithms are available in Python by coding the following:

import hashlibHash_Algorithms_available = hashlib.algorithms_availableprint(Hash_Algorithms_available)Output: {'sha256', 'md4', 'whirlpool', 'sha384', 'sha224', 'sm3', 'blake2s', 'blake2b', 'ripemd160', 'sha512_256', 'md5', 'sha512_224', 'shake_128', 'sha512', 'sha1', 'sha3_384', 'sha3_256', 'sha3_512', 'md5-sha1', 'shake_256', 'sha3_224'}

First, let’s see a simple MD5 Python hashing program in action, as it’s one of the most common Python hashing examples:

import hashlib #importing librariesmodule = hashlib.md5() #selecting the hashing module module.update(b"You are Awesome ") #inputting the text and b implies bytecodeprint(module.hexdigest())

The generated hex is:

83d38079ecb05b2b0ad97ffa50a951eb

Here, we import hashlib, a module available in Python, and create a variable named module, where we select the Python hashing algorithm to be used while hashing.

.update is an inbuilt function in hashlib that takes data as input and generates the hashes. The letter b indicates the string is a byte string, and .digest gives you the hash string generated from the data:

Now, let’s see a simple bcrypt Python hashing program in action.

import bcrypt #importing librariesinput_password = b"YouareAwesome!" #inputting the text and b implies bytecode hashed_password = bcrypt.hashpw(input_password, bcrypt.gensalt())print(hashed_password)

The generated hex is: b'$2b$12$ZVMHgLah4CtGM1FGIXeEWusNA23wz1dqEc27a3rwwm9Fa4XVPLVLG'</code

Bcrypt is a package available in Python that can be installed by a simple pip statement:

pip install bcrypt

We can then import the package import bcrypt and use the bcrypt.hashpw() function, which takes two arguments: byte and salt.

Salt is random data used in the hashing function that creates random strings and makes each hash unpredictable.

Conclusion

In this article, you learned about cryptography and the various ways in which to encrypt data. We also created a simple Python program for encryption and decryption.

Implementing cryptography is extremely important. When you’re storing passwords in a database, make sure you are using the latest and strongest cryptography and hashing standards.

I'm an expert in cryptography with a deep understanding of various cryptographic concepts and practical applications. My expertise is grounded in both theoretical knowledge and hands-on experience, allowing me to convey complex concepts with clarity and provide real-world insights. I've actively engaged in implementing cryptographic algorithms, exploring their strengths and weaknesses, and staying abreast of the latest advancements in the field.

Now, let's delve into the concepts covered in the provided article:

Cryptography Overview:

Cryptography is the practice of securing communication channels through the use of encryption and decryption. It employs mathematical principles, formulas, and algorithms to make data unreadable to unauthorized users. This ensures secure communication in various applications, from social media platforms to online banking.

Types of Cryptography:

  1. Symmetric Key Cryptography:

    • Involves using a single key (secret key) for both encryption and decryption.
    • Also known as private-key, secret-key, or shared-key cryptography.
    • Methods include block ciphers (ECB, CBC) and stream ciphers (CFB, OFB).
    • Examples of symmetric key algorithms: AES, DES, Blowfish.
  2. Caesar Cipher (Example of Symmetric Key Cryptography):

    • Substitution cipher where alphabets shift positions by a fixed number.
    • Easily implemented, but not secure for sensitive data.
    • Python program for encryption and decryption is provided.
  3. Asymmetric Key Cryptography:

    • Uses two different keys (public and private) for encryption and decryption.
    • Also called public-key cryptography.
    • Offers enhanced security but is slower.
    • Examples of asymmetric key algorithms: RSA, DSA, ECC.
  4. Generating RSA Key with Python (Example of Asymmetric Key Cryptography):

    • Utilizes the Cryptodome library to generate an RSA key pair.
    • Public key encrypts data, and only the corresponding private key can decrypt it.
  5. Hashing:

    • Converts variable-length input into a fixed-size text string using hash functions.
    • Irreversible process for secure data storage and user authentication.
    • Deprecated algorithms include MD5 and SHA-1; current ones include Argon2, bcrypt, and scrypt.
  6. Hashing in Python:

    • Demonstrates available hashing algorithms using hashlib in Python.
    • Examples of MD5 and bcrypt hashing programs are provided.
    • Highlights the importance of using strong hashing standards for password storage.

Conclusion:

  • Emphasizes the significance of implementing cryptography, especially for secure password storage in databases.
  • Stresses the importance of staying updated on the latest and strongest cryptographic and hashing standards.

In conclusion, the article provides a comprehensive overview of cryptography, covering symmetric and asymmetric key cryptography, hashing, and practical examples in Python.

Implementing cryptography with Python - LogRocket Blog (2024)

FAQs

Is Python good for cryptography? ›

Python: Another well-liked language for cryptography is Python. Its "cryptography" library, one of its libraries, has secure primitives. The most basic and minimal data type is primitive. The Fernet implementation, which supports "secret key" cryptography, is a well-liked secure primitive.

How to find cryptography? ›

Write down the letters of the alphabet in order, from A to Z. Shift each letter of the alphabet by the “shift” value. For example, if the shift value is 3, A would become D, B would become E, C would become F, and so on. Encrypt your message by replacing each letter with the corresponding shifted letter.

Which cryptographic algorithm is best? ›

The Advanced Encryption Standard (AES) is the trusted standard algorithm used by the United States government, as well as other organizations. Although extremely efficient in the 128-bit form, AES also uses 192- and 256-bit keys for very demanding encryption purposes.

How to create cryptography in Python? ›

Algorithm for Cryptography with Python
  1. Make a list of all the alphabet.
  2. Create a function that takes the text and a number as a parameter.
  3. Move through each element.
  4. If it's a space add it to the new list as it is.
  5. Take out the position of the character it should replace with.
  6. Join.
  7. Display the encrypted text.

Is Python sufficient for cyber security? ›

Python for cyber security is a powerful tool. Its simplicity, flexibility, and wide range of libraries make it an excellent choice for both offensive and defensive security. Whether you're a beginner or an experienced professional, learning Python can significantly enhance your cyber security skills.

Do hackers prefer using Python or another language? ›

Python is a good hacking language because there are so many libraries available for it. There are libraries for just about any kind of task you could imagine: image processing, data analysis, web scraping, cryptography - the list goes on and on!

Is cryptography difficult to learn? ›

Cryptography blends several areas of mathematics: number theory, complexity theory, information theory, probability theory, abstract algebra, and formal analysis, among others. Few can do the science properly, and a little knowledge is a dangerous thing: inexperienced cryptographers almost always design flawed systems.

What is the easiest cryptography? ›

In cryptography, a Caesar cipher, also known as Caesar's cipher, the shift cipher, Caesar's code, or Caesar shift, is one of the simplest and most widely known encryption techniques.

What are the three types of cryptography? ›

Cryptography can be broken down into three different types:
  • Secret Key Cryptography.
  • Public Key Cryptography.
  • Hash Functions.

What is the hardest encryption to crack? ›

AES 256-bit encryption is the strongest and most robust encryption standard that is commercially available today. While it is theoretically true that AES 256-bit encryption is harder to crack than AES 128-bit encryption, AES 128-bit encryption has never been cracked.

Which cryptographic algorithm is obsolete? ›

The National Security Agency (NSA) issued a guidance note in January last year on eliminating obsolete transport layer security (TLS) protocol configurations. The other revisions include the hashing algorithm SHA-1 replaced by SHA-2 and the encryption algorithm RSA 1024 by RSA 2048.

Why is Python good for cryptography? ›

Cryptography library is one of the many libraries and modules that Python offers for secure communication and encryption. The fernet module of the library provides a built-in key generator and provides encryption and decryption functions for a string of data and large files.

What are the Python cryptography tools? ›

The Python Cryptography Toolkit is a collection of extension modules for Python. One part of the Toolkit is a number of different algorithms. The list includes most of the common ones: Encryption algorithms: Alleged RC4, Blowfish, DES, Diamond, IDEA, LOKI91, RC5, REDOC III, Sapphire.

How to install cryptography in Python? ›

To install the Cryptography package in Linux follow the following steps: Step 1: Setting up a Python environment on our Linux operating system. Python3 environment can be ready by executing the below command. Step 2: Installing the PIP manager in our Linux system.

Is Python or C++ better for cyber security? ›

If you want to be a security engineer or a penetration tester, Python may be better suited for you. On the other hand, if you're interested in developing new cybersecurity tools or products, C++ might be the better option.

Is Python useful for crypto? ›

Cryptocurrencies like Bitcoin and Ethereum are the most well-known applications of blockchain technology. Python can be used to develop cryptocurrency wallets, exchanges, and transaction validation systems. This example demonstrates how to generate a new Bitcoin address using the bitcoin library in Python.

Which programming language is best for cryptography? ›

Top Programming Languages for Cryptography in 2024
  • Python. Python is one of the most widely used and adaptable programming languages available, and it works well for cryptography as well. ...
  • Go. ...
  • Ruby. ...
  • C++ ...
  • Java. ...
  • C# ...
  • Rust. ...
  • JavaScript.
Feb 21, 2024

Do hackers learn Python? ›

Ethical hacking has become a lucrative industry for cyber security professionals and enthusiasts. With the major tasks of an ethical hacker running on command-line tools, learning a scripting language like Python is highly essential.

Top Articles
Ultimate backup: Archival M-Discs store your data for 1000 years
What's a lock-in or a rate lock on a mortgage? | Consumer Financial Protection Bureau
Kevin Cox Picks
122242843 Routing Number BANK OF THE WEST CA - Wise
Jeremy Corbell Twitter
Craigslist Furniture Bedroom Set
Www Craigslist Louisville
Achivr Visb Verizon
Hover Racer Drive Watchdocumentaries
Midlife Crisis F95Zone
10-Day Weather Forecast for Florence, AL - The Weather Channel | weather.com
[Birthday Column] Celebrating Sarada's Birthday on 3/31! Looking Back on the Successor to the Uchiha Legacy Who Dreams of Becoming Hokage! | NARUTO OFFICIAL SITE (NARUTO & BORUTO)
Les Rainwater Auto Sales
Destiny 2 Salvage Activity (How to Complete, Rewards & Mission)
Committees Of Correspondence | Encyclopedia.com
Salem Oregon Costco Gas Prices
Invert Clipping Mask Illustrator
Honda cb750 cbx z1 Kawasaki kz900 h2 kz 900 Harley Davidson BMW Indian - wanted - by dealer - sale - craigslist
3S Bivy Cover 2D Gen
Craigslist Sparta Nj
Ivegore Machete Mutolation
All Obituaries | Gateway-Forest Lawn Funeral Home | Lake City FL funeral home and cremation Lake City FL funeral home and cremation
8005607994
Low Tide In Twilight Ch 52
Essence Healthcare Otc 2023 Catalog
Apparent assassination attempt | Suspect never had Trump in sight, did not get off shot: Officials
Marquette Gas Prices
Telegram Voyeur
Ascensionpress Com Login
Roseann Marie Messina · 15800 Detroit Ave, Suite D, Lakewood, OH 44107-3748 · Lay Midwife
Landing Page Winn Dixie
Nacogdoches, Texas: Step Back in Time in Texas' Oldest Town
Max 80 Orl
A Small Traveling Suitcase Figgerits
De beste uitvaartdiensten die goede rituele diensten aanbieden voor de laatste rituelen
Lichen - 1.17.0 - Gemsbok! Antler Windchimes! Shoji Screens!
Pill 44615 Orange
Spinning Gold Showtimes Near Emagine Birch Run
Sams La Habra Gas Price
Michael Jordan: A timeline of the NBA legend
Does Target Have Slime Lickers
Noh Buddy
M&T Bank
Sea Guini Dress Code
Dancing Bear - House Party! ID ? Brunette in hardcore action
18 Seriously Good Camping Meals (healthy, easy, minimal prep! )
Quest Diagnostics Mt Morris Appointment
Pelican Denville Nj
Deshuesadero El Pulpo
Wwba Baseball
Optimal Perks Rs3
Dinargurus
Latest Posts
Article information

Author: Edmund Hettinger DC

Last Updated:

Views: 6444

Rating: 4.8 / 5 (78 voted)

Reviews: 85% of readers found this page helpful

Author information

Name: Edmund Hettinger DC

Birthday: 1994-08-17

Address: 2033 Gerhold Pine, Port Jocelyn, VA 12101-5654

Phone: +8524399971620

Job: Central Manufacturing Supervisor

Hobby: Jogging, Metalworking, Tai chi, Shopping, Puzzles, Rock climbing, Crocheting

Introduction: My name is Edmund Hettinger DC, I am a adventurous, colorful, gifted, determined, precious, open, colorful person who loves writing and wants to share my knowledge and understanding with you.