Error when trying to sign an email with DKIM in Python

Viewed 195

I'm trying to make a script with pyton to send emails, I'm new to python and followed a few articles on how to do it. It works for sending emails without signing them, but they go right to the spam box, so I'm trying to make them signed. The following script is what I'm trying to use:

def sendEmail():
    dkim_selector = 'default'
    domain = <mydomain>
    port = 465
    pw = input('insert password: ')
    smtp_server = 'smtp.terra.com.br'
    sender = <from-email>
    rec = <to-email>


    message = msg(sender, rec) #a function that creates the message

    # the dkim library uses regex on byte strings so everything
    # needs to be encoded from strings to bytes.
    with open(<private_key_path>) as fh:
        dkim_private_key = fh.read()
    headers = [b'To', b"From", b"Subject"]
    sig = dkim.sign(
        message=message.as_bytes(),
        selector=str(dkim_selector).encode(),
        domain=domain.encode(),
        privkey=dkim_private_key.encode(),
        include_headers=headers,
    )

    # add the dkim signature to the email message headers.
    # decode the signature back to string_type because later on
    # the call to msg.as_string() performs it's own bytes encoding...
    message["DKIM-Signature"] = sig[len("DKIM-Signature: "):].decode()

    # Create secure connection with server and send email
    context = ssl.create_default_context()
    with smtplib.SMTP_SSL(smtp_server, port, context=context) as server:
        server.login(sender, pw)
        server.sendmail(
            sender, rec, message.as_string()
        )

When I run the program I get the following error:

Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\dkim\crypto.py", line 140, in parse_private_key
    pka = asn1_parse(ASN1_RSAPrivateKey, data)
  File "C:\Python39\lib\site-packages\dkim\asn1.py", line 85, in asn1_parse
    r.append(asn1_parse(t[1], data[i:i+length]))
  File "C:\Python39\lib\site-packages\dkim\asn1.py", line 91, in asn1_parse
    raise ASN1FormatError(
dkim.asn1.ASN1FormatError: Unexpected tag (got 30, expecting 02)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python39\lib\site-packages\dkim\__init__.py", line 827, in sign
    pk = parse_pem_private_key(privkey)
  File "C:\Python39\lib\site-packages\dkim\crypto.py", line 170, in parse_pem_private_key
    return parse_private_key(pkdata)
  File "C:\Python39\lib\site-packages\dkim\crypto.py", line 142, in parse_private_key
    raise UnparsableKeyError('Unparsable private key: ' + str(e))
dkim.crypto.UnparsableKeyError: Unparsable private key: Unexpected tag (got 30, expecting 02)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "z:\main.py", line 44, in <module>
    sendEmail()
  File "z:\main.py", line 23, in sendEmail
    sig = dkim.sign(
  File "C:\Python39\lib\site-packages\dkim\__init__.py", line 1335, in sign
    return d.sign(selector, domain, privkey, identity=identity, canonicalize=canonicalize, include_headers=include_headers, length=length)
  File "C:\Python39\lib\site-packages\dkim\__init__.py", line 829, in sign
    raise KeyFormatError(str(e))
dkim.KeyFormatError: Unparsable private key: Unexpected tag (got 30, expecting 02)

I have created the keys using openssl from the following lines:

z:\> openssl genrsa -out privateKey.pem 1024
z:\> openssl rsa -in privateKey.pem -out publicKey.pub -pubout

What am I doing wrong?

1 Answers

It turns out it was a problem with the keys I was generating with OpenSSL. I used puTTy instead to generate a new pair of keys and it worked fine. Not really sure what the problem was with the keys (they look similar enough to me) but it works now!

Related