streams/Code/Lib/JSalmon.php

73 lines
2.1 KiB
PHP
Raw Normal View History

<?php
2022-02-16 04:08:28 +00:00
namespace Code\Lib;
2022-02-16 04:08:28 +00:00
use Code\Web\HTTPSig;
2021-12-02 23:02:31 +00:00
class JSalmon
{
2022-08-23 11:01:09 +00:00
public static function sign($data, $key_id, $key, $data_type = 'application/x-nomad+json'): array
2021-12-02 23:02:31 +00:00
{
2022-08-28 06:06:24 +00:00
$data = base64url_encode(json_encode($data, true)); // strip padding
2021-12-02 23:02:31 +00:00
$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
2022-08-28 06:06:24 +00:00
$precomputed = '.' . base64url_encode($data_type) . '.YmFzZTY0dXJs.UlNBLVNIQTI1Ng';
2022-08-28 06:06:24 +00:00
$signature = base64url_encode(Crypto::sign($data . $precomputed, $key));
2021-12-02 23:02:31 +00:00
return ([
'signed' => true,
'data' => $data,
'data_type' => $data_type,
'encoding' => $encoding,
'alg' => $algorithm,
'sigs' => [
'value' => $signature,
2022-08-28 06:06:24 +00:00
'key_id' => base64url_encode($key_id)
2021-12-02 23:02:31 +00:00
]
]);
}
2018-06-28 02:22:12 +00:00
2022-08-23 11:01:09 +00:00
public static function verify($x): array|bool
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']) . '.'
2022-08-28 06:06:24 +00:00
. base64url_encode($x['data_type']) . '.'
. base64url_encode($x['encoding']) . '.'
. base64url_encode($x['alg']);
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
}