Archive for December 1st, 2022

pip3 install pyopenssl

pip3 install cryptography

============================================

[root@master-node encryption]# cat keygen.py
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.primitives import serialization
# Generate the RSA private key
key = rsa.generate_private_key(
public_exponent=65537,
key_size=2048,
)
pem = key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
)
print(pem)
public_key = key.public_key()
pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
print(pem)
===========================================
[root@master-node encryption]# cat encrypt.py
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
from cryptography.hazmat.primitives.serialization import load_pem_public_key
import sys
public_pem_data=b’—–BEGIN PUBLIC KEY—–\nMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA1ikdHKIUkRKKmxm5OMmH\nX8T2mx05ggDD7oEqZBd8×9lrzLOmADPoYT/qZGpFkXu6ys9IWlIqGp96qRsXQaRA\nO5EJziNdrCpMYGZFX5cxc8hnVh15h8DrvWj7pKoNmWkZhLiQ+vFsWLq3m41omQi/\ndhNMybPLsLGqS7EOO17z1VifSp33XOXLNZkrU3otItoqPPNq6nAXuINXZsPTdRY7\nk/ERmEXU2l6+GMKWnesRWm7txJSTgdpH8hjfoSZmJTHy7+uZqTdHC3PpCojZeIRw\ndgOEErYnKEHMQ6/4DV0a0tF5BzwXhrolSYkWmpt65pblbLQAzgR0KA91F8iJHp5Y\ncQIDAQAB\n—–END PUBLIC KEY—–\n’
key = load_pem_public_key(public_pem_data)
fi.open(sys.argv[1],’rb’)
message = fi.read()
fi.close()
ciphertext = key.encrypt(
message,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
fo=open(sys.argv[2],’wb’)
f.write(ciphertext)
f.close()
===========================================
[root@master-node encryption]# cat decrypt.py
from cryptography.hazmat.primitives.serialization import load_pem_private_key
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import rsa, padding
pem_data=b’—–BEGIN RSA PRIVATE KEY—–\nMIIEogIAdf8a1kupHcqgVHzcBlgBfRDBr\nEQyKr9JWXzLTwgbpft/7qvOkv4T0pOzhWBvKJaKvm1sY+4l+Z1g=\n—–END RSA PRIVATE KEY—–\n’

fi=open(sys.argv[1],’rb’)
ciphertext=fi.read()
fi.close()
key = load_pem_private_key(pem_data, password=None)
plaintext = key.decrypt(
ciphertext,
padding.OAEP(
mgf=padding.MGF1(algorithm=hashes.SHA256()),
algorithm=hashes.SHA256(),
label=None
)
)
print(plaintext)
fo=open(sys.argv[2],’wb’)
f.write(plaintext)
f.close()
==========================================
https://www.misterpki.com/python-public-private-key-encryption/