tc/jose

此包已被弃用且不再维护。未建议替代包。

JavaScript 对象签名和加密库

v1.0.1 2015-03-07 20:42 UTC

This package is not auto-updated.

Last update: 2022-12-05 18:30:04 UTC


README

Build Status SensioLabsInsight Latest Stable Version

JavaScript 对象签名和加密库

安装

使用 composer,将以下内容添加到您的 composer.json

"tc/jose": "dev-master"

您也可以运行

$ php composer.phar require tc/jose "dev-master"

支持的算法

  • HS256, HS384, HS512
  • RS256, RS384, RS512
  • ES256, ES384, ES512

创建一个 JWS

要创建一个 JWS,您可以这样做

<?php

use Tc\JOSE\JWS;

// ...

// Create a new JWS
$jws = new JWS();

// Add some data to the payload
$jws->setPayload(array(
    'user' => 'SomeUser'
));

// Set Issued At Claim
$jws->setIssuedAt();

// Set Expires for 1 hour
$jws->setExpires(3600);

// Sign the JWS (Can use any of the supported algorithms)
$jws->sign('HS256', 'SecretKeyHere');

// Serialize the JWS to be transported
$jwsSerialized = $jws->serialize();

// Should look like:
// eyJhbGciOiJIUzI1NiIsInR5cCI6IkpPU0UifQ.e30.ssb8sFTv7UK37oW395EUkSL9g8uNPDhMHFvRwcUenXo

// You could then return this token to the client normally or as a header/cookie

// ...

解码序列化的 JWT (JWS 或 JWE)

<?php

use Tc\JOSE\JWT;
use Tc\JOSE\JWS;

// ...

// The Serialized JWT (could be from a header/request parameter)
$jwt = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpPU0UifQ.e30.ssb8sFTv7UK37oW395EUkSL9g8uNPDhMHFvRwcUenXo';

// Try to decode the Serialized JWT
try {

    $decodedJWT = JWT::decode($jwt);
    
    // Check if the decoded JWT is a JWS (could potentially be a JWS or JWE)
    if ( $decodedJWT instanceof JWS ) {
    
        // is a JWS, we now check it is valid
        $isValid = $decodedJWT->validate('SecretKeyHere');
        
        if ($isValid) {
            // JWS is valid
        }
        
    }
} catch(InvalidArgumentException $e) {
    // Invalid JWT, handle here
}

// ...

使用 RS 或 ES 算法

使用 openssl 创建密钥

您可以调整创建密钥的格式以与 ES 或 RS 兼容。

$ openssl genrsa -out private.pem -aes256 4096
$ openssl rsa -pubout -in private.pem -out public.pem

签名 JWS

<?php

// ...
$jws = new JWS();
$jws->sign('RS256', openssl_pkey_get_private('path/to/privatekey.pem', 'passphrase'));
// ...

验证 JWS

<?php

// ...
$jws->validate(openssl_pkey_get_public('path/to/publickey.pem'));
// ...

待办事项

实现 JWE 和 JWK 规范。

许可

tc-jose 使用 MIT 许可证。

有关详细信息,请参阅 LICENSE。