Blog/activity_pub_php/2_sinadura.php
(Deskargatu)
<?php
function makeRequest($private_key_file, $actorInbox, $user, $message)
{
$publicKeyId = "https://".$_SERVER["HTTP_HOST"]."/activityPub/users/$user#main-key";
$date_gmt = new \DateTime();
$date = $date_gmt->format(DATE_RFC7231);
$message_str = json_encode($message);
$sha256 = hash('sha256', $message_str, true);
$digest = 'SHA-256=' . base64_encode($sha256);
$inboxUrl = parse_url($actorInbox);
$sigparts = [
'(request-target)' => 'post ' . $inboxUrl['path'],
'host' => $inboxUrl['host'],
'date' => $date,
'digest' => $digest,
];
$dataToSign = join("\n", array_map(
fn($k, $v) => "{$k}: {$v}",
array_keys($sigparts),
array_values($sigparts)
));
$privateKey = openssl_pkey_get_private(file_get_contents($private_key_file));
$signature = null; // mutated by openssl
$enodedSignature = null;
if (!openssl_sign($dataToSign, $signature, $privateKey, OPENSSL_ALGO_SHA256)) {
throw new Exception('Could not sign activityPub data');
}
$signatureHeader = sprintf( 'keyId="%s",algorithm="rsa-sha256",headers="(request-target) host date digest",signature="%s"', $publicKeyId, base64_encode($signature));
$headers = [
'accept: application/activity+json, text/json',
'host: '.$inboxUrl['host'],
'date: '.$date,
'digest: '.$digest,
'signature: '.$signatureHeader,
'content-type: application/activity+json',
];
$ch=curl_init($actorInbox);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_HEADER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $message_str);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($result, 0, $header_size);
$body = substr($result, $header_size);
curl_close($ch);
return json_decode($body,true);
}