streams/Zotlabs/Lib/JSalmon.php

74 lines
2.1 KiB
PHP
Raw Normal View History

<?php
namespace Zotlabs\Lib;
2018-06-28 02:22:12 +00:00
use Zotlabs\Web\HTTPSig;
2021-12-02 23:02:31 +00:00
class JSalmon
{
public static function sign($data, $key_id, $key, $data_type = 'application/x-nomad+json')
2021-12-02 23:02:31 +00:00
{
2021-12-02 23:02:31 +00:00
$data = base64url_encode(json_encode($data, true), true); // strip padding
$encoding = 'base64url';
$algorithm = 'RSA-SHA256';
2021-12-02 23:02:31 +00:00
$data = preg_replace('/\s+/', '', $data);
2021-12-02 23:02:31 +00:00
// precomputed base64url encoding of data_type, encoding, algorithm concatenated with periods
2021-12-02 23:02:31 +00:00
$precomputed = '.' . base64url_encode($data_type, true) . '.YmFzZTY0dXJs.UlNBLVNIQTI1Ng';
2021-12-02 23:02:31 +00:00
$signature = base64url_encode(Crypto::sign($data . $precomputed, $key), true);
2021-12-02 23:02:31 +00:00
return ([
'signed' => true,
'data' => $data,
'data_type' => $data_type,
'encoding' => $encoding,
'alg' => $algorithm,
'sigs' => [
'value' => $signature,
'key_id' => base64url_encode($key_id, true)
]
]);
}
2018-06-28 02:22:12 +00:00
2021-12-02 23:02:31 +00:00
public static function verify($x)
{
2018-06-28 02:22:12 +00:00
2021-12-02 23:02:31 +00:00
logger('verify');
$ret = ['results' => []];
2018-06-28 02:22:12 +00:00
2021-12-02 23:02:31 +00:00
if (!is_array($x)) {
return false;
}
if (!(array_key_exists('signed', $x) && $x['signed'])) {
return false;
}
2018-06-28 02:22:12 +00:00
2021-12-02 23:02:31 +00:00
$signed_data = preg_replace('/\s+/', '', $x['data']) . '.'
. base64url_encode($x['data_type'], true) . '.'
. base64url_encode($x['encoding'], true) . '.'
. base64url_encode($x['alg'], true);
2021-12-02 23:02:31 +00:00
$key = HTTPSig::get_key(EMPTY_STR, 'zot6', base64url_decode($x['sigs']['key_id']));
logger('key: ' . print_r($key, true));
if ($key['portable_id'] && $key['public_key']) {
if (Crypto::verify($signed_data, base64url_decode($x['sigs']['value']), $key['public_key'])) {
logger('verified');
$ret = ['success' => true, 'signer' => $key['portable_id'], 'hubloc' => $key['hubloc']];
}
}
2018-06-28 02:22:12 +00:00
2021-12-02 23:02:31 +00:00
return $ret;
}
2018-06-28 02:22:12 +00:00
2021-12-02 23:02:31 +00:00
public static function unpack($data)
{
return json_decode(base64url_decode($data), true);
}
2021-12-03 03:01:39 +00:00
}