What's the equivalent of `crypto.sign` in Deno?

88 Views Asked by At

I have the following Node code that generates a Google Access Token.

const fetch = require('node-fetch');
const crypto = require('crypto');


function base64urlEncode(str) {
    let base64 = Buffer.from(str).toString('base64');
    return base64.replace('+', '-').replace('/', '_').replace(/=+$/, '');
}


function createJWT() {
    const iat = Math.floor(Date.now() / 1000);
    const exp = iat + 3600;  // Token valid for one hour

    const header = {
        alg: "RS256",
        typ: "JWT"
    };

    const claimSet = {
        iss: clientEmail,
        scope: "https://www.googleapis.com/auth/firebase.messaging",
        aud: "https://oauth2.googleapis.com/token",
        exp: exp,
        iat: iat
    };

    const unsignedJWT = `${base64urlEncode(JSON.stringify(header))}.${base64urlEncode(JSON.stringify(claimSet))}`;
    const signature = crypto.sign('sha256', Buffer.from(unsignedJWT, 'utf8'), privateKey);
    const signedJWT = `${unsignedJWT}.${base64urlEncode(signature)}`;

    return signedJWT;
}

privateKey is my private key as an environment variable in the form of

-----BEGIN PRIVATE KEY-----\nSTUFF\n-----END PRIVATE KEY-----\n

I now need to convert this to work in Deno but I'm having a hard time since deno doesn't have crypto.sign or Butter.from.

I can also convert the data stored in the environment variable to something else if that makes sense.

0

There are 0 best solutions below