where('domain_id', $domain->id) ->where('status', 'active') ->latest('id') ->first(); if ($existing) { return $existing; } $selectorPrefix = (string) config('mailinfra.dkim_selector_prefix', 'ladill'); $selector = Str::lower(trim($selectorPrefix)) ?: 'ladill'; $selector .= '1'; $publicKey = ''; $privateKey = null; if (function_exists('openssl_pkey_new')) { $resource = openssl_pkey_new([ 'private_key_bits' => 2048, 'private_key_type' => OPENSSL_KEYTYPE_RSA, ]); if ($resource !== false) { openssl_pkey_export($resource, $privateOut); $details = openssl_pkey_get_details($resource); $publicPem = (string) ($details['key'] ?? ''); $publicKey = preg_replace('/-----BEGIN PUBLIC KEY-----|-----END PUBLIC KEY-----|\s+/', '', $publicPem) ?: ''; $privateKey = $privateOut ?: null; } } if ($publicKey === '') { $publicKey = Str::upper(Str::random(360)); } $privatePath = null; if (is_string($privateKey) && trim($privateKey) !== '') { $safeHost = Str::slug($domain->host, '_'); $directory = storage_path('app/mail/dkim'); File::ensureDirectoryExists($directory); $privatePath = $directory.'/'.$safeHost.'_'.$selector.'.key'; File::put($privatePath, $privateKey); } $key = DomainDkimKey::query()->create([ 'domain_id' => $domain->id, 'selector' => $selector, 'public_key_txt' => $publicKey, 'private_key_path' => $privatePath, 'status' => 'active', 'generated_at' => now(), ]); Log::info('Generated DKIM key for domain', ['domain_id' => $domain->id, 'selector' => $selector]); return $key; } public function activeKey(Domain $domain): ?DomainDkimKey { return DomainDkimKey::query() ->where('domain_id', $domain->id) ->where('status', 'active') ->latest('id') ->first(); } }