Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
How to Convert Bytes to String in Python ?
Next article icon

How to Encrypt and Decrypt Strings in Python?

Last Updated : 14 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In this article, we will learn about Encryption, Decryption and implement them with Python. 

Encryption:

Encryption is the process of encoding the data. i.e converting plain text into ciphertext. This conversion is done with a key called an encryption key.

Decryption:

Decryption is the process of decoding the encoded data. Converting the ciphertext into plain text. This process requires a key that we used for encryption.

We require a key for encryption. There are two main types of keys used for encryption and decryption. They are Symmetric-key and Asymmetric-key.

Symmetric-key Encryption:

In symmetric-key encryption, the data is encoded and decoded with the same key. This is the easiest way of encryption, but also less secure. The receiver needs the key for decryption, so a safe way need for transferring keys. Anyone with the key can read the data in the middle.

Example:

Install the python cryptography library with the following command. 

pip install cryptography

Steps:

  • Import Fernet
  • Then generate an encryption key, that can be used for encryption and decryption.
  • Convert the string to a byte string, so that it can be encrypted.
  • Instance the Fernet class with the encryption key.
  • Then encrypt the string with the Fernet instance.
  • Then it can be decrypted with Fernet class instance and it should be instanced with the same key used for encryption.
Python
from cryptography.fernet import Fernet  # we will be encrypting the below string. message = "hello geeks"  # generate a key for encryption and decryption # You can use fernet to generate  # the key or use random key generator # here I'm using fernet to generate key  key = Fernet.generate_key()  # Instance the Fernet class with the key  fernet = Fernet(key)  # then use the Fernet class instance  # to encrypt the string string must # be encoded to byte string before encryption encMessage = fernet.encrypt(message.encode())  print("original string: ", message) print("encrypted string: ", encMessage)  # decrypt the encrypted string with the  # Fernet instance of the key, # that was used for encrypting the string # encoded byte string is returned by decrypt method, # so decode it to string with decode methods decMessage = fernet.decrypt(encMessage).decode()  print("decrypted string: ", decMessage) 

Output:

Asymmetric-key Encryption:

In Asymmetric-key Encryption, we use two keys a public key and a private key. The public key is used to encrypt the data and the private key is used to decrypt the data. By the name, the public key can be public (can be sent to anyone who needs to send data). No one has your private key, so no one in the middle can read your data.

Example:

Install the python rsa library with the following command. 

pip install rsa

Steps:

  • Import rsa library
  • Generate public and private keys with rsa.newkeys() method.
  • Encode the string to byte string.
  • Then encrypt the byte string with the public key.
  • Then the encrypted string can be decrypted with the private key.
  • The public key can only be used for encryption and the private can only be used for decryption.
Python
import rsa  # generate public and private keys with  # rsa.newkeys method,this method accepts  # key length as its parameter # key length should be atleast 16 publicKey, privateKey = rsa.newkeys(512)  # this is the string that we will be encrypting message = "hello geeks"  # rsa.encrypt method is used to encrypt  # string with public key string should be  # encode to byte string before encryption  # with encode method encMessage = rsa.encrypt(message.encode(),                           publicKey)  print("original string: ", message) print("encrypted string: ", encMessage)  # the encrypted message can be decrypted  # with ras.decrypt method and private key # decrypt method returns encoded byte string, # use decode method to convert it to string # public key cannot be used for decryption decMessage = rsa.decrypt(encMessage, privateKey).decode()  print("decrypted string: ", decMessage) 

Output:



Next Article
How to Convert Bytes to String in Python ?

K

kabilan
Improve
Article Tags :
  • Python
  • cryptography
Practice Tags :
  • python

Similar Reads

  • Encrypt and Decrypt Files using Python
    Encryption is the act of encoding a message so that only the intended users can see it. We encrypt data because we don't want anyone to see or access it. We will use the cryptography library to encrypt a file. The cryptography library uses a symmetric algorithm to encrypt the file. In the symmetric
    3 min read
  • Encrypt and Decrypt Image using Python
    In this article, we will encrypt/decrypt an image using simple mathematical logic. It requires two things, data, and key, and when XOR operation is applied on both the operands i.e data and key, the data gets encrypted but when the same process is done again with the same key-value data gets decrypt
    5 min read
  • How to Convert Bytes to String in Python ?
    We are given data in bytes format and our task is to convert it into a readable string. This is common when dealing with files, network responses, or binary data. For example, if the input is b'hello', the output will be 'hello'. This article covers different ways to convert bytes into strings in Py
    2 min read
  • Encrypt and Decrypt PDF using PyPDF2
    PDF (Portable Document Format) is one of the most used file formats for storing and sending documents. They are commonly used for many purposes such as eBooks, Resumes, Scanned documents, etc. But as we share pdf to many people, there is a possibility of its data getting leaked or stolen. So, it's n
    4 min read
  • Encrypt and Decrypt Using Rijndael Key in C#
    To keep data secure and protected it is necessary to keep the data encrypted. As we know that in C# and in other languages too there are many ways for encrypting data. The Data Encryption Standard method used for encryption was not promising good security that led to the invention of a highly secure
    7 min read
  • Convert Hex to String in Python
    Hexadecimal (base-16) is a compact way of representing binary data using digits 0-9 and letters A-F. It's commonly used in encoding, networking, cryptography and low-level programming. In Python, converting hex to string is straightforward and useful for processing encoded data. Using List Comprehen
    2 min read
  • Convert Hex String to Bytes in Python
    Hexadecimal strings are a common representation of binary data, especially in the realm of low-level programming and data manipulation. The task of converting a hex string to bytes in Python can be achieved using various methods. Below, are the ways to convert hex string to bytes in Python. Using by
    2 min read
  • How to use String Formatters in Python
    In Python, we use string formatting to control how text is displayed. It allows us to insert values into strings and organize the output in a clear and readable way. In this article, we’ll explore different methods of formatting strings in Python to make our code more structured and user-friendly. U
    3 min read
  • Encoding and Decoding Base64 Strings in Python
    The Base64 encoding is used to convert bytes that have binary or text data into ASCII characters. Encoding prevents the data from getting corrupted when it is transferred or processed through a text-only system. In this article, we will discuss about Base64 encoding and decoding and its uses to enco
    4 min read
  • How to Index and Slice Strings in Python?
    In Python, indexing and slicing are techniques used to access specific characters or parts of a string. Indexing means referring to an element of an iterable by its position whereas slicing is a feature that enables accessing parts of the sequence. Table of Content Indexing Strings in PythonAccessin
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences