mirror of
https://github.com/hastagAB/Awesome-Python-Scripts.git
synced 2024-11-23 20:11:07 +00:00
Add asymmetric encryption in python
This commit is contained in:
parent
f2a4a5be6b
commit
02dfe28d4b
8
asymmetric_cryptography/README.md
Normal file
8
asymmetric_cryptography/README.md
Normal file
|
@ -0,0 +1,8 @@
|
|||
## Asymmetric Encryption in python
|
||||
|
||||
An example of asymmetric encryption in python using a public/private keypair - utilizes RSA from PyCrypto library
|
||||
|
||||
```bash
|
||||
pip install pycrypto
|
||||
python asymmetric.py
|
||||
```
|
34
asymmetric_cryptography/asymmetric.py
Normal file
34
asymmetric_cryptography/asymmetric.py
Normal file
|
@ -0,0 +1,34 @@
|
|||
from Crypto import Random
|
||||
from Crypto.PublicKey import RSA
|
||||
import base64
|
||||
|
||||
|
||||
def generate_keys(modulus_length=256*4):
|
||||
privatekey = RSA.generate(modulus_length, Random.new().read)
|
||||
publickey = privatekey.publickey()
|
||||
return privatekey, publickey
|
||||
|
||||
|
||||
def encryptit(message , publickey):
|
||||
encrypted_msg = publickey.encrypt(message, 32)[0]
|
||||
encoded_encrypted_msg = base64.b64encode(encrypted_msg)
|
||||
return encoded_encrypted_msg
|
||||
|
||||
|
||||
def decryptit(message, privatekey):
|
||||
decoded_encrypted_msg = base64.b64decode(message)
|
||||
decoded_decrypted_msg = privatekey.decrypt(decoded_encrypted_msg)
|
||||
return decoded_decrypted_msg
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
message = "This is a awesome message!"
|
||||
privatekey , publickey = generate_keys()
|
||||
encrypted_msg = encryptit(message.encode("utf-8"), publickey)
|
||||
decrypted_msg = decryptit(encrypted_msg, privatekey)
|
||||
|
||||
print(f'{privatekey.exportKey()} - ({len(privatekey.exportKey())})')
|
||||
print(f'{publickey.exportKey()} - ({len(publickey.exportKey())})')
|
||||
print(f'Original: {message} - ({len(message)})')
|
||||
print(f'Encrypted: {encrypted_msg} - ({len(encrypted_msg)})')
|
||||
print(f'Decrypted: {decrypted_msg} - ({len(decrypted_msg)})')
|
Loading…
Reference in New Issue
Block a user