JWT使用PHP上的私钥进行签名

时间:2017-02-09 08:37:08

标签: php

我有以下示例:如何使用私钥对JWT密钥进行签名,然后使用PHP上的公共密钥对其进行解码

    $privKey = openssl_pkey_new(array('digest_alg' => 'sha256',
        'private_key_bits' => 1024,
        'private_key_type' => OPENSSL_KEYTYPE_RSA));
    $msg = JWT::encode('abc', $privKey, 'RS256');
    $pubKey = openssl_pkey_get_details($privKey);
    $pubKey = $pubKey['key'];
    $decoded = JWT::decode($msg, $pubKey, array('RS256'));
    $this->assertEquals($decoded, 'abc');

但是它在这里生成然后动态使用生成的密钥,如果我需要使用已经生成的私钥和公钥怎么办?是否有可能/足够使用file_get_contents

更新

我发现openssl_pkey_get_privateopenssl_pkey_get_public我会尝试使用此代码。

1 个答案:

答案 0 :(得分:0)

解决方案:

$private = openssl_pkey_get_private('file://key', 'keyphrase');
$token = \Firebase\JWT\JWT::encode('magic', $private, 'RS256');

$public = openssl_pkey_get_public('file://key.pub');
$data = \Firebase\JWT\JWT::decode($token, $public, ['RS256']);
相关问题