How to convert a JWK key into a pem key in PHP without using third-party libraries?
Example of JWK
{
"kty": "RSA",
"kid": "FftONTxoEg",
"use": "sig",
"alg": "RS256",
"n": "wio-SFzFvKKQ9vl5ctaYSi09o8k3Uh7r6Ht2eJv-hSaZ6A6xTXVIBVSm0KvPxaJlpjYPTCcl2sdEyXlD2Uh1khUKU7r9ON3rpN8pFHAere5ig_JGVEShxmt5E_jzMymYnSfkoSW44ulevQeUwP_MiC5VC1KJjTfD73ghX0tQ0-_RjTJJ2cLyFC4VFNboBMCVioUrz8IA3c0KIOl507qswQvMsh2vBTMDDSJfippAGLzUiWXxUlid-vyOC8GCtag61taSorxCw14irk-tsh7hWjDDkSTFn2gChPMfXXj10_lCv0UG29TVUVCAsay4pszzgmc4zwhgSsqQRd939BJexw",
"e": "AQAB"
}
Expected result
-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAwio+SFzFvKKQ9vl5ctaY
Si09o8k3Uh7r6Ht2eJv+hSaZ6A6xTXVIBVSm0KvPxaJlpjYPTCcl2sdEyXlD2Uh1
khUKU7r9ON3rpN8pFHAere5ig/JGVEShxmt5E/jzMymYnSfkoSW44ulevQeUwP/M
iC5VC1KJjTfD73ghX0tQ0+/RjTJJ2cLyFC4VFNboBMCVioUrz8IA3c0KIOl507qs
wQvMsh2vBTMDDSJfippAGLzUiWXxUlid+vyOC8GCtag61taSorxCw14irk+tsh7h
WjDDkSTFn2gChPMfXXj10/lCv0UG29TVUVCAsay4pszzgmc4zwhgSsqQRd939BJe
xwIDAQAB
-----END PUBLIC KEY-----
I try to convert with this code and the key is almost similar to the required result, but still differs from the signature required for verification. Can someone help me with this?
private function jwkToPem($jwk) {
$modulus = $this->base64UrlDecode($jwk['n']);
$exponent = $this->base64UrlDecode($jwk['e']);
if (ord($modulus[0]) > 0x7f) {
$modulus = "x00" . $modulus;
}
$modulus = "x02" . $this->asn1Length(strlen($modulus)) . $modulus;
$exponent = "x02" . $this->asn1Length(strlen($exponent)) . $exponent;
$rsaPublicKey = "x30" . $this->asn1Length(strlen($modulus . $exponent)) . $modulus . $exponent;
$rsaOID = "x30x0Dx06x09x2Ax86x48x86xF7x0Dx01x01x01x05x00";
$publicKeyBitString = "x03" . $this->asn1Length(strlen($rsaPublicKey) + 1) . "x00" . $rsaPublicKey;
$fullKey = "x30" . $this->asn1Length(strlen($rsaOID . $publicKeyBitString)) . $rsaOID . $publicKeyBitString;
return "-----BEGIN PUBLIC KEY-----n" . chunk_split(base64_encode($fullKey), 64) . "-----END PUBLIC KEY-----n";
}
private function asn1Length($length) {
if ($length <= 0x7F) {
return chr($length);
}
$temp = ltrim(pack('N', $length), " ");
return chr(0x80 | strlen($temp)) . $temp;
}