RSA
From charlesreid1
<![CDATA[from Crypto.PublicKey import RSA from Crypto.Signature import pkcs1_15 from Crypto.Hash import SHA256 from Crypto.Cipher import PKCS1_OAEP
def generate_keys(bits=2048):
key_pair = RSA.generate(bits) return key_pair.export_key(), key_pair.publickey().export_key()
def encrypt(plaintext, public_key_pem):
recipient_key = RSA.import_key(public_key_pem)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
return cipher_rsa.encrypt(plaintext.encode('utf-8'))
def decrypt(ciphertext, private_key_pem):
private_key = RSA.import_key(private_key_pem)
cipher_rsa = PKCS1_OAEP.new(private_key)
return cipher_rsa.decrypt(ciphertext).decode('utf-8')
def sign(message, private_key_pem):
private_key = RSA.import_key(private_key_pem)
h = SHA256.new(message.encode('utf-8'))
return pkcs1_15.new(private_key).sign(h)
def verify(message, signature, public_key_pem):
public_key = RSA.import_key(public_key_pem)
h = SHA256.new(message.encode('utf-8'))
try:
pkcs1_15.new(public_key).verify(h, signature)
return True
except (ValueError, TypeError):
return False
if __name__ == '__main__':
private_key, public_key = generate_keys()
text = "This is a test"
ciphertext = encrypt(text, public_key)
plaintext = decrypt(ciphertext, private_key)
print("Plaintext was '%s'" % plaintext)
signature = sign(text, private_key)
valid = verify(text, signature, public_key)
print("Signature valid: %s" % valid)
tampered = verify("Tampered message", signature, public_key)
print("Tampered signature valid: %s" % tampered)
https://www.reddit.com/r/cryptography/comments/4yu7mh/code_review_of_aes_implementation_in_python/
| 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
|