4

How can I make SHA256withRSA in PHP?

example: https://developers.google.com/identity/protocols/OAuth2ServiceAccount

   {"alg":"RS256","typ":"JWT"}.
    {
    "iss":"761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com",
    "scope":"https://www.googleapis.com/auth/prediction",
    "aud":"https://www.googleapis.com/oauth2/v4/token",
    "exp":1328554385,
    "iat":1328550785
    }.
    [signature bytes]

Below is an example of a JWT that has been signed and is ready for transmission:

eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiI3NjEzMjY3OTgwNjktcjVtbGpsbG4xcmQ0bHJiaGc3NWVmZ2lncDM2bTc4ajVAZGV2ZWxvcGVyLmdzZXJ2aWNlYWNjb3VudC5jb20iLCJzY29wZSI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL2F1dGgvcHJlZGljdGlvbiIsImF1ZCI6Imh0dHBzOi8vd3d3Lmdvb2dsZWFwaXMuY29tL29hdXRoMi92NC90b2tlbiIsImV4cCI6MTMyODU1NDM4NSwiaWF0IjoxMzI4NTUwNzg1fQ.UFUt59SUM2_AW4cRU8Y0BYVQsNTo4n7AFsNrqOpYiICDu37vVt-tw38UKzjmUKtcRsLLjrR3gFW3dNDMx_pL9DVjgVHDdYirtrCekUHOYoa1CMR66nxep5q5cBQ4y4u2kIgSvChCTc9pmLLNoIem-ruCecAJYgI9Ks7pTnW1gkOKs0x3YpiLpzplVHAkkHztaXiJdtpBcY1OXyo6jTQCa3Lk2Q3va1dPkh_d--GU2M5flgd8xNBPYw4vxyt0mP59XZlHMpztZt0soSgObf7G3GXArreF_6tpbFsS3z2t5zkEiHuWJXpzcYr5zWTRPDEHsejeBSG8EgpLDce2380ROQ

How do I check what [signature bytes]? How do I make SHA256withRSA in PHP?:

Sign the UTF-8 representation of the input using SHA256withRSA (also known as RSASSA-PKCS1-V1_5-SIGN with the SHA-256 hash function)

2 Answers 2

10

You can use the PHP function openssl_sign():

//helper function
function base64url_encode($data) { 
    return rtrim(strtr(base64_encode($data), '+/', '-_'), '='); 
}

//Google's Documentation of Creating a JWT: https://developers.google.com/identity/protocols/OAuth2ServiceAccount#authorizingrequests

//{Base64url encoded JSON header}
$jwtHeader = base64url_encode(json_encode(array(
    "alg" => "RS256",
    "typ" => "JWT"
)));
//{Base64url encoded JSON claim set}
$now = time();
$jwtClaim = base64url_encode(json_encode(array(
    "iss" => "761326798069-r5mljlln1rd4lrbhg75efgigp36m78j5@developer.gserviceaccount.com",
    "scope" => "https://www.googleapis.com/auth/prediction",
    "aud" => "https://www.googleapis.com/oauth2/v4/token",
    "exp" => $now + 3600,
    "iat" => $now
)));
//The base string for the signature: {Base64url encoded JSON header}.{Base64url encoded JSON claim set}
openssl_sign(
    $jwtHeader.".".$jwtClaim,
    $jwtSig,
    $your_private_key_from_google_api_console,
    "sha256WithRSAEncryption"
);
$jwtSign = base64url_encode($jwtSig);

//{Base64url encoded JSON header}.{Base64url encoded JSON claim set}.{Base64url encoded signature}
$jwtAssertion = $jwtHeader.".".$jwtClaim.".".$jwtSign;
3
  • How can I get your_private_key_from_google_api_console from Google service account? The private file I've downloaded is a json with many info there
    – ytdm
    Dec 2, 2019 at 15:29
  • 1
    You should be able to find the "private_key" property in the JSON. "private_key": "-----BEGIN PRIVATE KEY-----. If it isn't there, try creating a "Service Account" in the Google IAM & Admin Console. Here is a guide on service account keys: cloud.google.com/iam/docs/… Dec 3, 2019 at 21:07
  • Make sure to click "+ Create Key" on the bottom after you click on or create your Service Account. Dec 3, 2019 at 21:10
0

According to the documentation, you need to add a code identifier in the header. Where is the problem in class?

JWT::createJWT();

class JWT
{
    public static function createJWT()
    {
        function base64url_encode($data)
        {
            return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
        };
        $json = file_get_contents(__DIR__ . '/secrets.json');
        $secret = json_decode($json, true);
        $headers = ['alg' => 'RS256', 'typ' => 'JWT', $secret['private_key_id']];
        $headers_encoded = base64url_encode(json_encode($headers));
        $time = time();
        $lastTime = time() + 3600;
        $payload = [
            'iss' => $secret['client_email'],
            'sub' => $secret['client_email'],
            'aud' => 'https://www.googleapis.com/',
            'iat' => $time,
            'exp' => $lastTime
        ];
        $payload_encoded = base64url_encode(json_encode($payload));
        $key = $secret['private_key'];
        openssl_sign(
            "$headers_encoded.$payload_encoded",
            $RSA256,
            $key,
            "sha256WithRSAEncryption"
        );
        $keyRSA256 = base64url_encode($RSA256);
        $JWT = "$headers_encoded.$payload_encoded.$keyRSA256";

        $token = [
            'access_token' => $JWT,
            'lastTime' => $lastTime,
            'dostup' => 'https://www.googleapis.com/auth/spreadsheets'
        ];

        $tokenJSON = json_encode($token, JSON_UNESCAPED_UNICODE);
        file_put_contents(__DIR__ . '/token.php', $tokenJSON, LOCK_EX);

        echo $tokenJSON;
    }
}

JSON

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.