Base64
From charlesreid1
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Signature import pkcs1_15
from Crypto.Hash import SHA256
def generate_keypair(bits=2048):
"""Generate an RSA public/private key pair."""
key = RSA.generate(bits)
return key
def encrypt(plaintext, public_key):
"""Encrypt data with RSA-OAEP."""
cipher = PKCS1_OAEP.new(public_key)
data = plaintext.encode() if isinstance(plaintext, str) else plaintext
return cipher.encrypt(data)
def decrypt(ciphertext, private_key):
"""Decrypt data with RSA-OAEP."""
cipher = PKCS1_OAEP.new(private_key)
return cipher.decrypt(ciphertext).decode()
def sign(data, private_key):
"""Sign data with RSA-PSS + SHA-256."""
h = SHA256.new(data.encode() if isinstance(data, str) else data)
return pkcs1_15.new(private_key).sign(h)
def verify(data, signature, public_key):
"""Verify an RSA-PSS + SHA-256 signature."""
h = SHA256.new(data.encode() if isinstance(data, str) else data)
try:
pkcs1_15.new(public_key).verify(h, signature)
return True
except (ValueError, TypeError):
return False
if __name__ == '__main__':
key = generate_keypair(2048)
private_key = key
public_key = key.publickey()
# --- Encryption / Decryption ---
message = "This is a secret message"
ciphertext = encrypt(message, public_key)
plaintext = decrypt(ciphertext, private_key)
print("Original: '%s'" % message)
print("Decrypted: '%s'" % plaintext)
# --- Signing / Verification ---
data = "This data needs signing"
signature = sign(data, private_key)
verified = verify(data, signature, public_key)
print("Signature verified: %s" % verified)
Practical RSA key generation, encryption, decryption, and digital signing in Python using PyCryptodome.
| Crypto cryptography-related resources on the wiki
Implementing AES Cipher in Python: AES
Category:Crypto · Category:Security · Category:Encryption
|
Red Links
- RSA
- GPG
- SHA
- Diffie-Hellman Key Exchange
- Password Hashing
- TLS
- One Time Pad
- HMAC
- Base64
- Elliptic Curve Cryptography
| Python a powerful programming language
Scientific Python: Data analysis libraries: Scipy · Numpy · Pandas · Statsmodel Machine learning libraries: Sklearn Neural network libraries: Tensorflow · Keras Plotting/viz: Matplotlib · Seaborn · Jupyter Solving partial differential equations and bessel functions: Fipy · Bessel Functions
Web and Networking Python: Web programming: Flask · Webapps · Mechanize · Scrapy · Gunicorn Wifi: Wireless/Python · Scapy IPython and Jupyter: Jupyter
Drawing, Geometry, and Shapes: Shapely (for drawing shapes): Shapely Geography library: Geos
General Useful Python Utilities: Python Remote Objects: Pyro Logging (create multi-channel log messages): Logging Keyboard (control keyboard from Python): Keyboard
Black Hat Python: Network scanning: Python/Scanner
|