具有ES256的php openssl_sign创建无效的签名

时间:2018-06-20 16:07:53

标签: php jwt

我正在尝试创建具有ES256签名的jwt令牌。这是代码的相关部分:

private function base64UrlEncode(string $data): string
{
    $urlSafeData = strtr(base64_encode($data), '+/', '-_');
    return rtrim($urlSafeData, '=');
}

public function token(Request $request):JsonResponse
{
   [...]

    $header = $this->base64UrlEncode(json_encode([
        "alg" => "ES256",
        "typ" => "JWT",
        "kty" => "EC"
    ]));

    $payload = $this->base64UrlEncode(json_encode($data));

    if (!\is_readable(__DIR__.'/private_key.pem'))
    {
        //create new private and public key
        $new_key_pair = openssl_pkey_new(array(
            "digest_alg" => \OPENSSL_ALGO_SHA256,
            "private_key_bits" => 2048,
            "private_key_type" => \OPENSSL_KEYTYPE_EC,
            "curve_name" => "prime256v1"
        ));
        openssl_pkey_export($new_key_pair, $private_key_pem);

        $details = openssl_pkey_get_details($new_key_pair);
        $public_key_pem = $details['key'];
        //save for later
        file_put_contents(__DIR__.'/private_key.pem', $private_key_pem);
        file_put_contents('public_key.pem', $public_key_pem);
    }
    $private_key_id = \openssl_pkey_get_private('file://'.__DIR__.'/private_key.pem');

    //create signature
    openssl_sign($header.'.'.$payload, $signature, $private_key_id, \OPENSSL_ALGO_SHA256);

    $token = $header.'.'.$payload.'.'.$this->base64UrlEncode($signature);
    [...]
}

但是在jwt.io上测试时,生成的签名无效。有什么建议我做错了吗?

0 个答案:

没有答案