streams/Code/Lib/Keyutils.php

108 lines
2.4 KiB
PHP
Raw Normal View History

<?php
2022-02-16 04:08:28 +00:00
namespace Code\Lib;
2021-03-28 22:37:49 +00:00
use phpseclib\Crypt\RSA;
use phpseclib\Math\BigInteger;
/**
* Keyutils
* Convert RSA keys between various formats
*/
2021-12-03 03:01:39 +00:00
class Keyutils
{
/**
* @param string $m modulo
* @param string $e exponent
* @return string
*/
2022-08-23 11:01:09 +00:00
public static function meToPem(string $m, string $e): string
2021-12-03 03:01:39 +00:00
{
$rsa = new RSA();
$rsa->loadKey([
'e' => new BigInteger($e, 256),
'n' => new BigInteger($m, 256)
]);
return $rsa->getPublicKey();
}
/**
2022-08-23 11:01:09 +00:00
* @param string $key
2021-12-03 03:01:39 +00:00
* @return string
2022-10-09 11:04:11 +00:00
* @noinspection PhpUnused
2021-12-03 03:01:39 +00:00
*/
2022-08-23 11:01:09 +00:00
public static function rsaToPem(string $key): string
2021-12-03 03:01:39 +00:00
{
$rsa = new RSA();
$rsa->setPublicKey($key);
2022-10-09 11:04:11 +00:00
/** @noinspection PhpRedundantOptionalArgumentInspection */
2021-12-03 03:01:39 +00:00
return $rsa->getPublicKey(RSA::PUBLIC_FORMAT_PKCS8);
}
/**
2022-08-23 11:01:09 +00:00
* @param string $key
2021-12-03 03:01:39 +00:00
* @return string
2022-10-09 11:04:11 +00:00
* @noinspection PhpUnused
2021-12-03 03:01:39 +00:00
*/
2022-08-23 11:01:09 +00:00
public static function pemToRsa(string $key): string
2021-12-03 03:01:39 +00:00
{
$rsa = new RSA();
$rsa->setPublicKey($key);
return $rsa->getPublicKey(RSA::PUBLIC_FORMAT_PKCS1);
}
/**
* @param string $key key
* @param string $m reference modulo
* @param string $e reference exponent
*/
2022-08-23 11:01:09 +00:00
public static function pemToMe(string $key, string &$m, string &$e): void
2021-12-03 03:01:39 +00:00
{
$rsa = new RSA();
$rsa->loadKey($key);
$rsa->setPublicKey();
$m = $rsa->modulus->toBytes();
$e = $rsa->exponent->toBytes();
}
/**
* @param string $pubkey
* @return string
2022-10-09 11:04:11 +00:00
* @noinspection PhpUnused
2021-12-03 03:01:39 +00:00
*/
2022-08-23 11:01:09 +00:00
public static function salmonKey(string $pubkey): string
2021-12-03 03:01:39 +00:00
{
self::pemToMe($pubkey, $m, $e);
2022-10-09 11:04:11 +00:00
/** @noinspection PhpRedundantOptionalArgumentInspection */
2021-12-03 03:01:39 +00:00
return 'RSA' . '.' . base64url_encode($m, true) . '.' . base64url_encode($e, true);
}
/**
* @param string $key
* @return string
*/
2022-08-23 11:01:09 +00:00
public static function convertSalmonKey(string $key): string
2021-12-03 03:01:39 +00:00
{
2022-08-23 11:01:09 +00:00
if (str_contains($key, ',')) {
2021-12-03 03:01:39 +00:00
$rawkey = substr($key, strpos($key, ',') + 1);
} else {
$rawkey = substr($key, 5);
}
$key_info = explode('.', $rawkey);
$m = base64url_decode($key_info[1]);
$e = base64url_decode($key_info[2]);
return self::meToPem($m, $e);
}
}