푸터 콘텐츠로 바로가기
PYTHON 도움말

암호화 Python(개발자를 위한 작동 방식)

Cryptography is essential for securing data and communications in the digital age. This package, with its extensive libraries, makes implementing cryptographic techniques straightforward. One of the most popular libraries for cryptography in Python is the cryptography package, which provides cryptographic recipes with both high-level and low-level interfaces. Later in the article, we will also look into a versatile PDF generation library called IronPDF from Iron Software.

Key Features

  1. High-Level Recipes: Cryptography includes a high-level cryptographic recipes layer for common cryptographic tasks, such as symmetric encryption, symmetric ciphers, message digests, and key derivation functions. The high-level symmetric encryption recipes help implement complex algorithms quickly and in a simple way.
  2. Low-Level Interfaces: It also offers low-level interfaces to cryptographic algorithms, allowing for more granular control and customization.
  3. Symmetric and Asymmetric Encryption: The library supports common cryptographic algorithms including both symmetric encryption (e.g., AES) and asymmetric encryption (e.g., RSA) algorithms.
  4. Cryptographic Primitives: The Cryptographic standard library includes cryptographic recipes and primitives to Python developers which include primitives for hashing, key derivation, and message authentication codes (MACs).
  5. Developer Support: Developers can submit issue reports, and it also offers a mailing list for development discussion.

Installation

To install the cryptography package, you can use pip:

pip install cryptography
pip install cryptography
SHELL

Basic Usage

Here’s a simple example of how to use the cryptography library for symmetric encryption with the Fernet module:

from cryptography.fernet import Fernet

# Generate a key
key = Fernet.generate_key()
cipher_suite = Fernet(key)

# Encrypt a message
message = b"IronPDF is awesome"  # This must be a really secret message
cipher_text = cipher_suite.encrypt(message)
print(cipher_text)

# Decrypt the message
plain_text = cipher_suite.decrypt(cipher_text)
print(plain_text)
from cryptography.fernet import Fernet

# Generate a key
key = Fernet.generate_key()
cipher_suite = Fernet(key)

# Encrypt a message
message = b"IronPDF is awesome"  # This must be a really secret message
cipher_text = cipher_suite.encrypt(message)
print(cipher_text)

# Decrypt the message
plain_text = cipher_suite.decrypt(cipher_text)
print(plain_text)
PYTHON

In this example, we generate a key, encrypt a message, and then decrypt it using the Fernet module.

Output

cryptography Python (How It Works For Developers): Figure 1

Use Cases

  1. Data Encryption: Encrypt sensitive data before storing it in a database or transmitting it over a network.
  2. Secure Communication: Ensure that messages exchanged between parties are confidential and tamper-proof.
  3. Authentication: Verify the integrity and authenticity of data using cryptographic signatures.

Introducing IronPDF

cryptography Python (How It Works For Developers): Figure 2 - IronPDF: The Python PDF Library

IronPDF is a powerful Python library designed to create, edit, and sign PDFs using HTML, CSS, images, and JavaScript thanks to its support for modern web standards. It offers commercial-grade performance with a low memory footprint. Key features include:

HTML to PDF Conversion:
IronPDF can convert HTML files, HTML strings, and URLs to PDFs. For example, render a webpage as a PDF using the Chrome PDF renderer.

Cross-Platform Support:
IronPDF is designed for Python 3+ and also runs on Windows, Mac, Linux, or Cloud Platforms.
IronPDF is also available in .NET, Java, Python, and Node.js.

Editing and Signing:
Use IronPDF to set properties, add security with passwords and permissions, and apply digital signatures to your PDFs.

Page Templates and Settings:
You can customize PDFs with headers, footers, page numbers, and adjustable margins with IronPDF. It additionally supports custom paper sizes and responsive layouts.

Standards Compliance:
IronPDF complies with PDF standards, including PDF/A and PDF/UA, supports UTF-8 character encoding, and manages assets such as images, CSS, and fonts.

Installation

 pip install ironpdf

Generate PDF Documents using IronPDF and Cryptography.

Prerequisites

  1. Make sure Visual Studio Code is installed
  2. Python version 3 is installed

To start with, let us create a Python file to add our scripts.

Open Visual Studio Code and create a file, cryptographyDemo.py.

Install necessary libraries:

pip install cryptography
pip install ironpdf
pip install cryptography
pip install ironpdf
SHELL

Then add the below code to demonstrate the usage of IronPDF and cryptography Python packages:

from cryptography.fernet import Fernet
from ironpdf import ChromePdfRenderer, License

# Apply your license key
License.LicenseKey = "your key"

# Create a PDF from an HTML string using Python
content = "<h1>Awesome IronPDF with Cryptography</h1>"

# Generate a key
content += "<h2>Generate a key</h2>"
key = Fernet.generate_key()
cipher_suite = Fernet(key)
content += "<p>Fernet.generate_key() = " + str(key) + "</p>"

# Encrypt a message
content += "<h2>Encrypt a message</h2>"
message = b"IronPDF is awesome"
cipher_text = cipher_suite.encrypt(message)
content += "<p>cipher_suite.encrypt(message)</p>"
content += "<p>" + str(cipher_text) + "</p>"

# Decrypt the message
content += "<h2>Decrypt the message</h2>"
plain_text = cipher_suite.decrypt(cipher_text)
content += "<p>cipher_suite.decrypt(cipher_text)</p>"
content += "<p>" + plain_text.decode() + "</p>"

# Generate PDF using IronPDF
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(content)

# Export to a file or Stream
pdf.SaveAs("Demo-cryptography.pdf")
from cryptography.fernet import Fernet
from ironpdf import ChromePdfRenderer, License

# Apply your license key
License.LicenseKey = "your key"

# Create a PDF from an HTML string using Python
content = "<h1>Awesome IronPDF with Cryptography</h1>"

# Generate a key
content += "<h2>Generate a key</h2>"
key = Fernet.generate_key()
cipher_suite = Fernet(key)
content += "<p>Fernet.generate_key() = " + str(key) + "</p>"

# Encrypt a message
content += "<h2>Encrypt a message</h2>"
message = b"IronPDF is awesome"
cipher_text = cipher_suite.encrypt(message)
content += "<p>cipher_suite.encrypt(message)</p>"
content += "<p>" + str(cipher_text) + "</p>"

# Decrypt the message
content += "<h2>Decrypt the message</h2>"
plain_text = cipher_suite.decrypt(cipher_text)
content += "<p>cipher_suite.decrypt(cipher_text)</p>"
content += "<p>" + plain_text.decode() + "</p>"

# Generate PDF using IronPDF
renderer = ChromePdfRenderer()
pdf = renderer.RenderHtmlAsPdf(content)

# Export to a file or Stream
pdf.SaveAs("Demo-cryptography.pdf")
PYTHON

Code Explanation

This code snippet demonstrates how to use the cryptography library's Fernet module to perform encryption and decryption of messages, and then generate a PDF document using IronPDF. Here's an explanation of each part of the code:

  1. Imports and License Key Setup:

    • Imports the Fernet class from the cryptography.fernet module for encryption and decryption functionality.
    • Imports ChromePdfRenderer and License from IronPDF for PDF generation.
    • Sets the license key for IronPDF to enable its features.
  2. HTML Content Setup: Initializes the content variable with HTML markup to be included in the PDF document.

  3. Generate a Key: Generates a new key using Fernet.generate_key() and creates a Fernet cipher suite object (cipher_suite) with the generated key. Includes the generated key in the HTML content.

  4. Encrypt a Message: Defines a message (message) to be encrypted (b"IronPDF is awesome"). Encrypts the message using the cipher_suite.encrypt() method and includes the ciphertext in the HTML content.

  5. Decrypt a Message: Decrypts the encrypted cipher_text using cipher_suite.decrypt() and includes the decrypted plain text in the HTML content.

  6. PDF Generation: Uses ChromePdfRenderer to render the content HTML string into a PDF document. Saves the generated PDF file as "Demo-cryptography.pdf".

This setup allows for creating a PDF document that showcases the encryption and decryption functionalities provided by the cryptography library, combined with the PDF generation capabilities of IronPDF.

Output

cryptography Python (How It Works For Developers): Figure 3

PDF

cryptography Python (How It Works For Developers): Figure 4

IronPDF License

IronPDF offers a trial license key to allow users to check out its extensive features before purchase.

Place the License Key at the start of the script before using the IronPDF package:

from ironpdf import License

# Apply your license key
License.LicenseKey = "key"
from ironpdf import License

# Apply your license key
License.LicenseKey = "key"
PYTHON

Conclusion

The cryptography library in Python is a powerful tool for implementing secure data encryption and decryption. Its ease of use and comprehensive features make it an excellent choice for developers looking to enhance the security of their applications.

On the other hand, IronPDF is a versatile and feature-rich PDF generation library which will help document the results in a standard way. Both these libraries can work wonders for developers to improve their skill sets.

커티스 차우
기술 문서 작성자

커티스 차우는 칼턴 대학교에서 컴퓨터 과학 학사 학위를 취득했으며, Node.js, TypeScript, JavaScript, React를 전문으로 하는 프론트엔드 개발자입니다. 직관적이고 미적으로 뛰어난 사용자 인터페이스를 만드는 데 열정을 가진 그는 최신 프레임워크를 활용하고, 잘 구성되고 시각적으로 매력적인 매뉴얼을 제작하는 것을 즐깁니다.

커티스는 개발 분야 외에도 사물 인터넷(IoT)에 깊은 관심을 가지고 있으며, 하드웨어와 소프트웨어를 통합하는 혁신적인 방법을 연구합니다. 여가 시간에는 게임을 즐기거나 디스코드 봇을 만들면서 기술에 대한 애정과 창의성을 결합합니다.