Skip to content

Instantly share code, notes, and snippets.

@dedayoa
Forked from lmammino/gen_dkim.py
Created October 21, 2023 20:16
Show Gist options
  • Save dedayoa/25823c66c22afc27cbad974d9a3b583a to your computer and use it in GitHub Desktop.
Save dedayoa/25823c66c22afc27cbad974d9a3b583a to your computer and use it in GitHub Desktop.
Generate dkim keys and a TXT record file for AWS Route 53
#!/usr/bin/env python
# Usage
# ./gen_dkim.py mail.yourdomain.tld
import sys
from subprocess import call
from os import devnull
if len(sys.argv) < 2:
raise Exception('Missing domain parameter')
domain = sys.argv[1]
dev_null = open(devnull, 'w')
with dev_null:
print('Generating private DKIM key for %s' % domain)
command = ['openssl', 'genrsa', '-out', 'dkim_%s.priv' % domain, '2048']
call(command, stdout=dev_null)
output_file = open('dkim_%s.pub' % domain, 'w')
with output_file:
print('Generating public DKIM key for %s' % domain)
command = ['openssl', 'rsa', '-in', 'dkim_%s.priv' % domain, '-pubout']
call(command, stdout=output_file)
print('Generating txt record file for %s' % domain)
print('Generating %s' % 'dkim_%s.aws.txt' % domain)
pub_key_file = open('dkim_%s.pub' % domain, 'r')
with pub_key_file:
content = pub_key_file.read()
key_part = 'p=' + ''.join(content.split("\n")[1:-2]) # strips first and last lines (banners) and joins
# split the key part into blocks of 252 chars
key_part_size = 252
res = [key_part[y-key_part_size:y] for y in range(key_part_size, len(key_part)+key_part_size,key_part_size)]
public_key = ' '.join(map(lambda x: '"%s"' % x, res))
dkim = '"v=DKIM1; h=sha256; k=rsa; " %s' % public_key
dkim_file = open('dkim_%s.aws.txt' % domain, 'w')
with dkim_file:
dkim_file.write(dkim)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment