The use of Python encryption library is as follows: 1. Symmetric encryption is recommended to use the Fernet module in the cryptography library. The key is generated by generate_key() and the data is encrypted and decrypted with encrypt()/decrypt(); 2. The hashlib library can be used for hash calculation, and the SHA256 algorithm is preferred and the hash value is obtained through hexdigest(). Be careful to avoid MD5 and SHA1; 3. Asymmetric encryption can use the RSA function of cryptography to generate key pairs through generate_private_key(), and encrypt with public and private keys. Note that filling schemes such as OAEP must be used and are only suitable for encrypting short content. The keys must be kept properly during use to ensure the security of transmission and follow standard encryption practices to improve security.
How to use Python encryption library? Actually, it’s not difficult, but you have to pay attention to a few key points.

Python has several commonly used encryption libraries, such as cryptography
, PyCrypto
(no longer maintained), hashlib
, hmac
, etc. Among them, cryptography
is currently officially recommended modern encryption library , with comprehensive functions and high security. The following starts with several common usage scenarios and talks about how to use this library to do basic encryption operations.
How to use cryptography to do symmetric encryption?
Symmetric encryption refers to the same key used for encryption and decryption. Common algorithms are AES (Advanced Encryption Standard).

In cryptography
, it is recommended to use the Fernet module to achieve simple symmetric encryption. It encapsulates AES-CBC and HMAC, which is simple and safe to use.
The sample code is as follows:

from cryptography.fernet import Fernet # Generate key = Fernet.generate_key() cipher = Fernet(key) # Encrypt token = cipher.encrypt(b"Secret message!") print(token) # The output is similar: gAAAAABl... # Decrypt plain_text = cipher.decrypt(token) print(plain_text.decode()) # Output: Secret message!
Some points to note:
- The key must be properly saved and cannot be disclosed;
- Fernet uses URL-safe Base64 encoding by default, so there is no problem when transmitting;
- If you want to control the key yourself, you can use
base64.urlsafe_b64encode()
to construct a key that meets the requirements.
How to use hashlib for hash calculation?
Hash functions are often used to generate data fingerprints or password storage. hashlib
in the Python standard library supports a variety of algorithms such as MD5, SHA1, SHA256, etc.
For example, generate a SHA256 hash of a string:
import hashlib data = "hello world".encode() sha256_hash = hashlib.sha256(data).hexdigest() print(sha256_hash)
Application scenarios include:
- Do not store the user password directly in plain text, but the hash value after adding salt;
- When verifying file integrity, you can compare hash values;
- Note: MD5 and SHA1 have proven unsafe, and it is recommended to use SHA256 or SHA3 first.
How to do asymmetric encryption? RSA Example
Asymmetric encryption uses public key encryption and private key decryption. Commonly used in digital signatures, HTTPS and other scenarios. cryptography
supports RSA generation, encryption and signature.
Example of generating an RSA key pair:
from cryptography.hazmat.primitives.asymmetric import rsa from cryptography.hazmat.primitives import serialization # Generate private_key = rsa.generate_private_key(public_exponent=65537, key_size=2048) public_key = private_key.public_key() # Serialize private key pem_private = private_key.private_bytes( encoding=serialization.Encoding.PEM, format=serialization.PrivateFormat.TraditionalOpenSSL, encryption_algorithm=serialization.NoEncryption() ) # Serialize public key pem_public = public_key.public_bytes( encoding=serialization.Encoding.PEM, format=serialization.PublicFormat.SubjectPublicKeyInfo )
In practice, please note:
- Private keys must be strictly confidential;
- Before encryption, fill processing (such as OAEP), otherwise it will be easily cracked;
- Asymmetric encryption is not suitable for large files, and usually only short content such as "session keys" are encrypted.
Basically that's it. Encryption seems complicated, but in fact, as long as you choose the right tool and follow the standard process, many problems can be avoided. A library like cryptography
that has active maintenance is more reliable to use.
The above is the detailed content of Python Cryptography Library Usage. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

The key to dealing with API authentication is to understand and use the authentication method correctly. 1. APIKey is the simplest authentication method, usually placed in the request header or URL parameters; 2. BasicAuth uses username and password for Base64 encoding transmission, which is suitable for internal systems; 3. OAuth2 needs to obtain the token first through client_id and client_secret, and then bring the BearerToken in the request header; 4. In order to deal with the token expiration, the token management class can be encapsulated and automatically refreshed the token; in short, selecting the appropriate method according to the document and safely storing the key information is the key.

Assert is an assertion tool used in Python for debugging, and throws an AssertionError when the condition is not met. Its syntax is assert condition plus optional error information, which is suitable for internal logic verification such as parameter checking, status confirmation, etc., but cannot be used for security or user input checking, and should be used in conjunction with clear prompt information. It is only available for auxiliary debugging in the development stage rather than substituting exception handling.

InPython,iteratorsareobjectsthatallowloopingthroughcollectionsbyimplementing__iter__()and__next__().1)Iteratorsworkviatheiteratorprotocol,using__iter__()toreturntheiteratorand__next__()toretrievethenextitemuntilStopIterationisraised.2)Aniterable(like

TypehintsinPythonsolvetheproblemofambiguityandpotentialbugsindynamicallytypedcodebyallowingdeveloperstospecifyexpectedtypes.Theyenhancereadability,enableearlybugdetection,andimprovetoolingsupport.Typehintsareaddedusingacolon(:)forvariablesandparamete

A common method to traverse two lists simultaneously in Python is to use the zip() function, which will pair multiple lists in order and be the shortest; if the list length is inconsistent, you can use itertools.zip_longest() to be the longest and fill in the missing values; combined with enumerate(), you can get the index at the same time. 1.zip() is concise and practical, suitable for paired data iteration; 2.zip_longest() can fill in the default value when dealing with inconsistent lengths; 3.enumerate(zip()) can obtain indexes during traversal, meeting the needs of a variety of complex scenarios.

To create modern and efficient APIs using Python, FastAPI is recommended; it is based on standard Python type prompts and can automatically generate documents, with excellent performance. After installing FastAPI and ASGI server uvicorn, you can write interface code. By defining routes, writing processing functions, and returning data, APIs can be quickly built. FastAPI supports a variety of HTTP methods and provides automatically generated SwaggerUI and ReDoc documentation systems. URL parameters can be captured through path definition, while query parameters can be implemented by setting default values ??for function parameters. The rational use of Pydantic models can help improve development efficiency and accuracy.

To test the API, you need to use Python's Requests library. The steps are to install the library, send requests, verify responses, set timeouts and retry. First, install the library through pipinstallrequests; then use requests.get() or requests.post() and other methods to send GET or POST requests; then check response.status_code and response.json() to ensure that the return result is in compliance with expectations; finally, add timeout parameters to set the timeout time, and combine the retrying library to achieve automatic retry to enhance stability.

A virtual environment can isolate the dependencies of different projects. Created using Python's own venv module, the command is python-mvenvenv; activation method: Windows uses env\Scripts\activate, macOS/Linux uses sourceenv/bin/activate; installation package uses pipinstall, use pipfreeze>requirements.txt to generate requirements files, and use pipinstall-rrequirements.txt to restore the environment; precautions include not submitting to Git, reactivate each time the new terminal is opened, and automatic identification and switching can be used by IDE.
