61 public const BEDROCK_SIGNING_KEY_CURVE_NAME =
"secp384r1";
63 private const ASN1_INTEGER_TAG =
"\x02";
64 private const ASN1_SEQUENCE_TAG =
"\x30";
66 private const SIGNATURE_PART_LENGTH = 48;
67 private const SIGNATURE_ALGORITHM = OPENSSL_ALGO_SHA384;
74 public static function split(
string $jwt) : array{
75 $v = explode(
".", $jwt);
77 throw new JwtException(
"Expected exactly 3 JWT parts, got " . count($v));
79 return [$v[0], $v[1], $v[2]];
90 public static function parse(
string $token) : array{
91 $v = self::split($token);
92 $header = json_decode(self::b64UrlDecode($v[0]),
true);
93 if(!is_array($header)){
94 throw new JwtException(
"Failed to decode JWT header JSON: " . json_last_error_msg());
96 $body = json_decode(self::b64UrlDecode($v[1]),
true);
98 throw new JwtException(
"Failed to decode JWT payload JSON: " . json_last_error_msg());
100 $signature = self::b64UrlDecode($v[2]);
101 return [$header, $body, $signature];
104 private static function signaturePartToAsn1(
string $part) : string{
105 if(strlen($part) !== self::SIGNATURE_PART_LENGTH){
106 throw new JwtException(
"R and S for a SHA384 signature must each be exactly 48 bytes, but have " . strlen($part) .
" bytes");
108 $part = ltrim($part,
"\x00");
109 if(ord($part[0]) >= 128){
112 $part =
"\x00" . $part;
116 return self::ASN1_INTEGER_TAG . chr(strlen($part)) . $part;
119 private static function rawSignatureToDer(
string $rawSignature) : string{
120 if(strlen($rawSignature) !== self::SIGNATURE_PART_LENGTH * 2){
121 throw new JwtException(
"JWT signature has unexpected length, expected 96, got " . strlen($rawSignature));
124 [$rString, $sString] = str_split($rawSignature, self::SIGNATURE_PART_LENGTH);
125 $sequence = self::signaturePartToAsn1($rString) . self::signaturePartToAsn1($sString);
128 return self::ASN1_SEQUENCE_TAG . chr(strlen($sequence)) . $sequence;
131 private static function signaturePartFromAsn1(BinaryStream $stream) : string{
132 $prefix = $stream->get(1);
133 if($prefix !== self::ASN1_INTEGER_TAG){
134 throw new \InvalidArgumentException(
"Expected an ASN.1 INTEGER tag, got " . bin2hex($prefix));
137 $length = $stream->getByte();
138 if($length > self::SIGNATURE_PART_LENGTH + 1){
139 throw new \InvalidArgumentException(
"Expected at most 49 bytes for signature R or S, got $length");
141 $part = $stream->get($length);
142 return str_pad(ltrim($part,
"\x00"), self::SIGNATURE_PART_LENGTH,
"\x00", STR_PAD_LEFT);
145 private static function rawSignatureFromDer(
string $derSignature) : string{
146 if($derSignature[0] !== self::ASN1_SEQUENCE_TAG){
147 throw new \InvalidArgumentException(
"Invalid DER signature, expected ASN.1 SEQUENCE tag, got " . bin2hex($derSignature[0]));
151 $length = ord($derSignature[1]);
152 $parts = substr($derSignature, 2, $length);
153 if(strlen($parts) !== $length){
154 throw new \InvalidArgumentException(
"Invalid DER signature, expected $length sequence bytes, got " . strlen($parts));
157 $stream =
new BinaryStream($parts);
158 $rRaw = self::signaturePartFromAsn1($stream);
159 $sRaw = self::signaturePartFromAsn1($stream);
161 if(!$stream->feof()){
162 throw new \InvalidArgumentException(
"Invalid DER signature, unexpected trailing sequence data");
165 return $rRaw . $sRaw;
171 public static function verify(
string $jwt, \OpenSSLAsymmetricKey $signingKey) : bool{
172 [$header, $body, $signature] = self::split($jwt);
174 $rawSignature = self::b64UrlDecode($signature);
175 $derSignature = self::rawSignatureToDer($rawSignature);
178 $header .
'.' . $body,
181 self::SIGNATURE_ALGORITHM
184 case 0:
return false;
186 case -1:
throw new JwtException(
"Error verifying JWT signature: " . openssl_error_string());
195 public static function create(array $header, array $claims, \OpenSSLAsymmetricKey $signingKey) : string{
196 $jwtBody =
JwtUtils::b64UrlEncode(json_encode($header, JSON_THROW_ON_ERROR)) .
"." .
JwtUtils::b64UrlEncode(json_encode($claims, JSON_THROW_ON_ERROR));
202 self::SIGNATURE_ALGORITHM
205 $rawSignature = self::rawSignatureFromDer($derSignature);
206 $jwtSig = self::b64UrlEncode($rawSignature);
208 return "$jwtBody.$jwtSig";
211 public static function b64UrlEncode(
string $str) : string{
212 return rtrim(strtr(base64_encode($str),
'+/',
'-_'),
'=');
215 public static function b64UrlDecode(
string $str) : string{
216 if(($len = strlen($str) % 4) !== 0){
217 $str .= str_repeat(
'=', 4 - $len);
219 $decoded = base64_decode(strtr($str,
'-_',
'+/'),
true);
220 if($decoded ===
false){
221 throw new JwtException(
"Malformed base64url encoded payload could not be decoded");
226 public static function emitDerPublicKey(\OpenSSLAsymmetricKey $opensslKey) : string{
227 $details = Utils::assumeNotFalse(openssl_pkey_get_details($opensslKey),
"Failed to get details from OpenSSL key resource");
229 $pemKey = $details[
'key'];
230 if(preg_match(
"@^-----BEGIN[A-Z\d ]+PUBLIC KEY-----\n([A-Za-z\d+/\n]+)\n-----END[A-Z\d ]+PUBLIC KEY-----\n$@", $pemKey, $matches) === 1){
231 $derKey = base64_decode(str_replace("\n",
"", $matches[1]),
true);
232 if($derKey !==
false){
236 throw new AssumptionFailedError(
"OpenSSL resource contains invalid public key");
239 public static function parseDerPublicKey(
string $derKey) : \OpenSSLAsymmetricKey{
240 $signingKeyOpenSSL = openssl_pkey_get_public(sprintf(
"-----BEGIN PUBLIC KEY-----\n%s\n-----END PUBLIC KEY-----\n", base64_encode($derKey)));
241 if($signingKeyOpenSSL ===
false){
242 throw new JwtException(
"OpenSSL failed to parse key: " . openssl_error_string());
244 $details = openssl_pkey_get_details($signingKeyOpenSSL);
245 if($details ===
false){
246 throw new JwtException(
"OpenSSL failed to get details from key: " . openssl_error_string());
248 if(!isset($details[
'ec'][
'curve_name'])){
249 throw new JwtException(
"Expected an EC key");
251 $curve = $details[
'ec'][
'curve_name'];
252 if($curve !== self::BEDROCK_SIGNING_KEY_CURVE_NAME){
253 throw new JwtException(
"Key must belong to curve " . self::BEDROCK_SIGNING_KEY_CURVE_NAME .
", got $curve");
255 return $signingKeyOpenSSL;