📜  pycryptodome python - Shell-Bash (1)

📅  最后修改于: 2023-12-03 15:33:49.762000             🧑  作者: Mango

PyCryptodome Python - Shell-Bash

Introduction

PyCryptodome is a self-contained Python package of low-level cryptographic primitives that supports both Python 2.x and 3.x. It is a fork of the PyCrypto library and is designed to maintain active development and support.

Features

PyCryptodome offers a range of cryptographic primitives, including symmetric encryption algorithms (AES, DES, Blowfish, Twofish, ChaCha20), asymmetric encryption algorithms (RSA, DSA, ECDH, ECDSA), hash functions (SHA-1, SHA-2, and SHA-3), message authentication codes (HMAC), key derivation functions (PBKDF2, scrypt), and other cryptographic functions.

Additionally, PyCryptodome supports the following modes of operation for symmetric encryption:

  • Electronic Codebook Mode (ECB)
  • Cipher Block Chaining Mode (CBC)
  • Cipher Feedback Mode (CFB)
  • Output Feedback Mode (OFB)
  • Counter Mode (CTR)
Installation

You can install PyCryptodome using pip, the Python package manager:

pip install pycryptodome
Examples
Symmetric Encryption

The following code shows how to encrypt plaintext with AES-256 in CBC mode:

from Crypto.Cipher import AES
import os

key = os.urandom(32)
iv = os.urandom(16)
plaintext = b'This is a plaintext message.'

cipher = AES.new(key, AES.MODE_CBC, iv)
ciphertext = cipher.encrypt(plaintext)

print(ciphertext.hex())
Hash Function

The following code shows how to hash a message using SHA-256:

from Crypto.Hash import SHA256

message = b'This is a message'
h = SHA256.new()
h.update(message)
digest = h.digest()

print(digest.hex())
Message Authentication Code

The following code shows how to generate a HMAC using SHA-256:

from Crypto.Hash import SHA256
from Crypto.Hash import HMAC

key = os.urandom(32)
message = b'This is a message'

h = HMAC.new(key, message, digestmod=SHA256)
digest = h.digest()

print(digest.hex())
Key Derivation Function

The following code shows how to derive a key using PBKDF2:

from Crypto.Protocol.KDF import PBKDF2

password = b'This is a password'
salt = os.urandom(16)
key = PBKDF2(password, salt, dkLen=32, count=1000000)

print(key.hex())
Conclusion

PyCryptodome is a powerful and flexible cryptography library for Python that supports a wide range of cryptographic primitives and modes of operation. Its active development and support make it a reliable choice for cryptography in Python applications.