PHP İle PDF İmzalama
.P12 Uzantılı Sertifika
openssl genrsa -out private_key.pem 2048
# Self-signed sertifika oluştur (1 yıl geçerli)
openssl req -new -x509 -key private_key.pem -out public_cert.pem -days 365
Bu komutlarda:
-
private_key.pem
→ özel anahtar -
public_cert.pem
→ sertifika
Bu komut çalıştırıldığında senden bir şifre girmen istenir. Bu şifreyi PDF imzası eklerken PHP’de kullanacaksın.
-
Artık elinde:
-
private_key.pem
→ özel anahtar -
public_cert.pem
→ sertifika -
my_certificate.p12
→ şifreli PKCS#12 dosyası
-
Her Yerde Güvenli Gözüken Sertifika
Ancak Sertifika İmzasının tüm uygulamalarda Güvenli gözükmesi için şunarı yapmak gerek, adım adım her yerde güvenilir bir .p12 sertifika oluşturma süreci:
1.Özel Anahtar Oluştur
2. CSR (Certificate Signing Request) Oluştur
-
Bu işlem sırasında sana sertifika bilgileri sorulur (CN, O, C, vs.).
-
CSR içinde özel anahtar yok, güvenli.
3. CSR’ı Güvenilir CA’ya Gönder
-
Önerilen, tarayıcı ve işletim sistemlerinde önceden güvenilen bir CA:
-
DigiCert, Sectigo (Comodo), GlobalSign, Actalis, vs.
-
CA sertifikayı imzalayıp
.crt
veya.cer
formatında gönderir.
-
4.CA Sertifikasını .p12 ile Birleştir
PHP’de .p12
dosyasını şu şekilde kullanabilirsin:
require 'vendor/autoload.php'; // TCPDF + FPDI autoload
use setasignFpdiTcpdfFpdi;
function createSignedPdf($sourcePdf, $p12File, $p12Password, $outputPdf, $signatureInfo = []) {
// PDF sınıfı
class PDF extends Fpdi {}
$pdf = new PDF();
$pdf->SetCreator('PHP TCPDF');
$pdf->SetAuthor($signatureInfo['Name'] ?? 'Unknown');
$pdf->SetTitle($signatureInfo['Title'] ?? 'Dijital İmzalı PDF');
// Kaynak PDF'i yükle
$pageCount = $pdf->setSourceFile($sourcePdf);
for ($pageNo = 1; $pageNo <= $pageCount; $pageNo++) {
$tplId = $pdf->importPage($pageNo);
$size = $pdf->getTemplateSize($tplId);
$pdf->AddPage($size['orientation'], [$size['width'], $size['height']]);
$pdf->useTemplate($tplId);
}
// .p12 sertifikayı oku
$certData = file_get_contents($p12File);
$certs = [];
if (!openssl_pkcs12_read($certData, $certs, $p12Password)) {
throw new Exception("Sertifika okunamadı veya şifre yanlış.");
}
// Dijital imza ayarları
$pdf->setSignature(
$certs['cert'],
$certs['pkey'],
$p12Password,
'',
2,
[
'Name' => $signatureInfo['Name'] ?? 'Unknown',
'Location' => $signatureInfo['Location'] ?? '',
'Reason' => $signatureInfo['Reason'] ?? 'PDF İmzası',
'ContactInfo' => $signatureInfo['ContactInfo'] ?? ''
]
);
// İmzalı PDF’i kaydet
$pdf->Output($outputPdf, 'F');
return $outputPdf;
}
// Kullanım örneği
try {
$signedPdf = createSignedPdf(
__DIR__ . '/imzali1.pdf', // Kaynak PDF
__DIR__ . '/uracos.p12', // .p12 sertifika
'ada2Daw32A2+1!', // Sertifika şifresi
__DIR__ . '/imzali4.pdf', // Çıktı PDF
[ // İmza bilgileri
'Name' => 'Deneme',
'Location' => 'Türkiye',
'Reason' => 'Mevcut PDF İmzası',
'ContactInfo' => 'aykut@example.com'
]
);
echo "İmzalı PDF oluşturuldu: <a href='imzali4.pdf'>imzali4.pdf</a>";
} catch (Exception $e) {
echo "Hata: " . $e->getMessage();
}
?>
Kaynaklar