|
15 | 15 |
|
16 | 16 | use Base64Url\Base64Url;
|
17 | 17 | use Jose\Component\Core\Util\Ecc\NistCurve;
|
| 18 | +use Jose\Component\Core\Util\Ecc\Point; |
| 19 | +use Jose\Component\Core\Util\Ecc\PrivateKey; |
| 20 | +use Jose\Component\Core\Util\Ecc\PublicKey; |
18 | 21 |
|
19 | 22 | class Encryption
|
20 | 23 | {
|
@@ -52,8 +55,7 @@ public static function encrypt(string $payload, string $userPublicKey, string $u
|
52 | 55 | $curve = NistCurve::curve256();
|
53 | 56 |
|
54 | 57 | // get local key pair
|
55 |
| - $localPrivateKeyObject = $curve->createPrivateKey(); |
56 |
| - $localPublicKeyObject = $curve->createPublicKey($localPrivateKeyObject); |
| 58 | + list($localPublicKeyObject, $localPrivateKeyObject) = self::createLocalKey(); |
57 | 59 | $localPublicKey = hex2bin(Utils::serializePublicKey($localPublicKeyObject));
|
58 | 60 |
|
59 | 61 | // get user public key object
|
@@ -176,4 +178,56 @@ private static function createInfo(string $type, string $context): string
|
176 | 178 |
|
177 | 179 | return 'Content-Encoding: '.$type.chr(0).'P-256'.$context;
|
178 | 180 | }
|
| 181 | + |
| 182 | + /** |
| 183 | + * @return array |
| 184 | + */ |
| 185 | + private static function createLocalKey(): array |
| 186 | + { |
| 187 | + try { |
| 188 | + return self::createLocalKeyUsingOpenSSL(); |
| 189 | + } catch (\Exception $e) { |
| 190 | + return self::createLocalKeyUsingPurePhpMethod(); |
| 191 | + } |
| 192 | + } |
| 193 | + |
| 194 | + /** |
| 195 | + * @return array |
| 196 | + */ |
| 197 | + private static function createLocalKeyUsingPurePhpMethod(): array |
| 198 | + { |
| 199 | + $curve = NistCurve::curve256(); |
| 200 | + $privateKey = $curve->createPrivateKey(); |
| 201 | + |
| 202 | + return [ |
| 203 | + $curve->createPublicKey($privateKey), |
| 204 | + $privateKey, |
| 205 | + ]; |
| 206 | + } |
| 207 | + |
| 208 | + /** |
| 209 | + * @return array |
| 210 | + */ |
| 211 | + private static function createLocalKeyUsingOpenSSL(): array |
| 212 | + { |
| 213 | + $key = openssl_pkey_new([ |
| 214 | + 'curve_name' => 'prime256v1', |
| 215 | + 'private_key_type' => OPENSSL_KEYTYPE_EC, |
| 216 | + ]); |
| 217 | + $res = openssl_pkey_export($key, $out); |
| 218 | + if (false === $res) { |
| 219 | + throw new \RuntimeException('Unable to create the key'); |
| 220 | + } |
| 221 | + $res = openssl_pkey_get_private($out); |
| 222 | + |
| 223 | + $details = openssl_pkey_get_details($res); |
| 224 | + |
| 225 | + return [ |
| 226 | + PublicKey::create(Point::create( |
| 227 | + gmp_init(bin2hex($details['ec']['x']), 16), |
| 228 | + gmp_init(bin2hex($details['ec']['y']), 16) |
| 229 | + )), |
| 230 | + PrivateKey::create(gmp_init(bin2hex($details['ec']['d']), 16)) |
| 231 | + ]; |
| 232 | + } |
179 | 233 | }
|
0 commit comments