PHP 的 JWT/JWS/JWE 库

该软件包的官方仓库似乎已不存在,因此该软件包已被冻结。

0.0.1 2015-09-04 20:04 UTC

This package is not auto-updated.

Last update: 2024-08-03 17:43:43 UTC


README

License Latest Stable Version Latest Unstable Version

Build Status Scrutinizer Code Quality Coverage Status SensioLabsInsight

需求

PHP 版本 >= 5.4.8

php-json 扩展

php-hash 扩展

php-openssl 扩展

php-mbstring 扩展

提供的功能

*签名/验证

*加密/解密

*声明验证(可选)

如果需要,您可以在验证时使用声明集验证器。

您还可以添加您创建的另一个验证器。

它必须实现 Cyh\Jose\Validate\ValidateInterface 接口。

*已内置 exp、nbf、iss、aud 验证器。

支持算法

JWS 签名:HS256, HS384, HS512, RS256, RS384, RS512, ES256, ES384, ES512

JWE 密钥加密:RSA1_5, RSA-OAEP

JWE 内容加密:A128CBC-HS256, A256CBC-HS512

使用方法

<?php
require_once './vendor/autoload.php';

use Cyh\Jose\Jwt;
use Cyh\Jose\Signing\Signer\HS256;
use Cyh\Jose\Validate\Expiration;
use Cyh\Jose\Signing\Exception\InvalidSignatureException;
use Cyh\Jose\Validate\Exception\ExpiredException;
use Cyh\Jose\Jwe;
use Cyh\Jose\Encryption\Alg\RSA_OAEP;
use Cyh\Jose\Encryption\Enc\A128CBC_HS256;


// sign
$claims = array(
    'sub' => 'iamsubject',
    'exp' => (time() + 3600),
);
$secret_key = hash('sha256', 'secret_key');
$token_strings = Jwt::sign(new HS256(), $claims, $secret_key);

// verify
try {
    $verified_claims = Jwt::verify(
        new HS256(),
        $token_strings,
        $secret_key,
        array(new Expiration())
    );

    var_dump($verified_claims);

} catch (InvalidSignatureException $e) {
    // ...

} catch (ExpiredException $e) {
    // ...

} catch (\Exception $e) {
    // ...
}


// encrypt
$rsa_pub_key = 'file://' . dirname(__FILE__) . '/tests/keys/rsa_aes256_2048_public.pem';
$content = 'i am plain text content';
$encrypted = Jwe::encrypt(
    new RSA_OAEP(),
    new A128CBC_HS256(),
    $content,
    $rsa_pub_key
);

// decrypt
$rsa_prv_key = 'file://' . dirname(__FILE__) . '/tests/keys/rsa_aes256_2048_private.pem';
$decrypted = Jwe::decrypt(
    new RSA_OAEP(),
    new A128CBC_HS256(),
    $encrypted,
    $rsa_prv_key,
    'password'
);

var_dump($decrypted);