Hi,
I’m already using
from smtplib import SMTP_SSL
from email.message import EmailMessage
To send emails.
Now I would like to be able to encrypt them with the public key of the recipient. ( PublicKey.asc
)
an A.I provide me this
import smtplib
from email.message import EmailMessage
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
# Load the ECC public key from the .asc file
with open('recipient_public_key.asc', 'rb') as key_file:
public_key_bytes = key_file.read()
public_key = ec.EllipticCurvePublicKey.from_public_bytes(
ec.SECP384R1(),
public_key_bytes
)
# Create the email message
msg = EmailMessage()
msg.set_content('This is the encrypted email.')
msg['Subject'] = 'Encrypted Email'
msg['From'] = 'you@example.com'
msg['To'] = 'recipient@example.com'
# Encrypt the email message using the ECC public key
nonce = bytes.fromhex('000102030405060708090a0b0c0d0e0f')
cipher = AESGCM(public_key.public_key().secret_key_bytes)
ciphertext = cipher.encrypt(nonce, msg.as_bytes(), None)
# Send the encrypted email
server = smtplib.SMTP('smtp.example.com')
server.send_message(msg, from_addr='you@example.com', to_addr='recipient@example.com')
server.quit()
# Save the encrypted email to a file
with open('encrypted_email.bin', 'wb') as f:
f.write(ciphertext)
I like the approach, only one “low level” import cryptography
but the code seem wrong.
if the body has been encrypted as ciphertext
I don’t see this one included while sending the email.
How are you doing it ? or do you have good tutorial, documentations ? because I found nothing “pure and simple” meaning not with of unnecessary stuff.
Thanks.
I finally manage to encrypt the body trough ptyhon-gnupg ( warning their documentation is still in alpha stage. )
now, remain to encrypt the subject (ThunderBird compatible) if you have any clues I’m all ears
When time permit I will publish my code in a pastbin.
Wubba Lubba dub-dub**
Removed by mod
You can use a gnupg library for python and then use the recipient’s public key to encrypt your email before sending it?
instead of using a library I can directly use subprocess with gnupg but in both case it seem gnupg require to import the public key to the keyring !? I don’t want that.
That assumes that the system has the gnupg utility.
indeed, but a lot of Linux distribution come with it :)
otherwise it’s installable.