3 namespace Friendica\Util;
5 use Friendica\Util\JsonLD;
6 use Friendica\Util\DateTimeFormat;
7 use Friendica\Protocol\ActivityPub;
8 use Friendica\Model\APContact;
11 * @brief Implements JSON-LD signatures
13 * Ported from Osada: https://framagit.org/macgirvin/osada
17 public static function isSigned($data)
19 return !empty($data['signature']);
22 public static function getSigner($data)
24 if (!self::isSigned($data)) {
28 $actor = JsonLD::fetchElement($data, 'actor', 'id');
33 $profile = APContact::getByURL($actor);
34 if (empty($profile['pubkey'])) {
37 $pubkey = $profile['pubkey'];
39 $ohash = self::hash(self::signableOptions($data['signature']));
40 $dhash = self::hash(self::signableData($data));
42 $x = Crypto::rsaVerify($ohash . $dhash, base64_decode($data['signature']['signatureValue']), $pubkey);
43 logger('LD-verify: ' . intval($x));
52 public static function sign($data, $owner)
55 'type' => 'RsaSignature2017',
56 'nonce' => random_string(64),
57 'creator' => $owner['url'] . '#main-key',
58 'created' => DateTimeFormat::utcNow(DateTimeFormat::ATOM)
61 $ohash = self::hash(self::signableOptions($options));
62 $dhash = self::hash(self::signableData($data));
63 $options['signatureValue'] = base64_encode(Crypto::rsaSign($ohash . $dhash, $owner['uprvkey']));
65 return array_merge($data, ['signature' => $options]);
68 private static function signableData($data)
70 unset($data['signature']);
74 private static function signableOptions($options)
76 $newopts = ['@context' => 'https://w3id.org/identity/v1'];
78 unset($options['type']);
79 unset($options['id']);
80 unset($options['signatureValue']);
82 return array_merge($newopts, $options);
85 private static function hash($obj)
87 return hash('sha256', JsonLD::normalize($obj));