From c2816d47cba24a88315732d41467913c6e93a70e Mon Sep 17 00:00:00 2001 From: Marcus Bointon Date: Tue, 3 May 2016 10:06:15 +0200 Subject: [PATCH] Add DNS entry generator, fixes #644 --- examples/DKIM_gen_keys.phps | 63 ++++++++++++++++++++++++++++--------- 1 file changed, 48 insertions(+), 15 deletions(-) diff --git a/examples/DKIM_gen_keys.phps b/examples/DKIM_gen_keys.phps index cf3f58b8..efd9197d 100644 --- a/examples/DKIM_gen_keys.phps +++ b/examples/DKIM_gen_keys.phps @@ -21,24 +21,57 @@ * inserted there using the selector you want to use. */ +//Set these to match your domain and chosen DKIM selector +$domain = 'example.com'; +$selector = 'phpmailer'; + //Path to your private key: $privatekeyfile = 'dkim_private.pem'; //Path to your public key: $publickeyfile = 'dkim_public.pem'; -//Create a 2048-bit RSA key with an SHA256 digest -$pk = openssl_pkey_new( - [ - 'digest_alg' => 'sha256', - 'private_key_bits' => 2048, - 'private_key_type' => OPENSSL_KEYTYPE_RSA - ] -); -//Save private key -openssl_pkey_export_to_file($pk, $privatekeyfile); -//Save public key -$pubKey = openssl_pkey_get_details($pk); -file_put_contents($publickeyfile, $pubKey['key']); +if (file_exists($privatekeyfile)) { + echo "Using existing keys - if you want to generate new keys, delete old key files first.\n\n"; + $privatekey = file_get_contents($privatekeyfile); + $publickey = file_get_contents($publickeyfile); +} else { + //Create a 2048-bit RSA key with an SHA256 digest + $pk = openssl_pkey_new( + [ + 'digest_alg' => 'sha256', + 'private_key_bits' => 2048, + 'private_key_type' => OPENSSL_KEYTYPE_RSA + ] + ); + //Save private key + openssl_pkey_export_to_file($pk, $privatekeyfile); + //Save public key + $pubKey = openssl_pkey_get_details($pk); + $publickey = $pubKey['key']; + file_put_contents($publickeyfile, $publickey); + $privatekey = file_get_contents($privatekeyfile); +} +echo "Private key (keep this private!):\n\n" . $privatekey; +echo "\n\nPublic key:\n\n" . $publickey; -echo file_get_contents($privatekeyfile); -echo $pubKey['key']; +//Prep public key for DNS, e.g. +//phpmailer._domainkey.example.com IN TXT "v=DKIM1; h=sha256; t=s; p=" "MIIBIjANBg...oXlwIDAQAB"... +$dnskey = "$selector._domainkey.$domain IN TXT"; +//Some DNS server don't like ; chars unless backslash-escaped +$dnsvalue = '"v=DKIM1\; h=sha256\; t=s\; p=" '; + +//Strip and split the key into smaller parts and format for DNS +//Many DNS systems don't like long TXT entries +//but are OK if it's split into 255-char chunks +//Remove PEM wrapper +$publickey = preg_replace('/^-+.*?-+$/m', '' , $publickey); +//Strip line breaks +$publickey = str_replace(["\r", "\n"], '', $publickey); +//Split into chunks +$keyparts = str_split($publickey, 253); //Becomes 255 when quotes are included +//Quote each chunk +foreach($keyparts as $keypart) { + $dnsvalue .= '"'.trim($keypart).'" '; +} +echo "\n\nDNS key:\n\n" . trim($dnskey); +echo "\n\nDNS value:\n\n" . trim($dnsvalue);