How to generate JWT for authenticating to the Google API?

I came accross this question and tried to change that solution to use C# instead of JavaScript, but I am getting an error of “ArgumentOutOfRangeException: Length cannot be less than zero.” when the X509Certificate2 is attmpted to be created.

Here is my code:

using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
using System.Text;
using System.Security.Cryptography.X509Certificates;
using System.Security.Cryptography;


public class JWTGenerator : MonoBehaviour
{
    private string header = "{\"alg\":\"RS256\",\"typ\":\"JWT\"}";
    private string claimset = "{\"iss\": \"unitygooglesheets@silken-eye-320803.iam.gserviceaccount.com\",\"scope\": \"https:\\/\\/www.googleapis.com\\/auth\\/devstorage.read_only\",\"aud\": \"https:\\/\\/oauth2.googleapis.com\\/token\",\"exp\": 1671132341,\"iat\": 1671128741}";
    private string google_pvt_key = "-----BEGIN PRIVATE KEY-----<Insert Private Key Here>

-----END PRIVATE KEY-----
";

    public string JWT = "";

    private void Start()
    {
        JWT = GetJWT();
    }
    public string GetJWT()
    {
        byte[] to_sign = Encoding.UTF8.GetBytes(Base64Encode(header) + "." + Base64Encode(claimset));
        X509Certificate2 cert = new X509Certificate2(Encoding.UTF8.GetBytes(google_pvt_key), "notasecret", X509KeyStorageFlags.DefaultKeySet);
        RSACryptoServiceProvider rsa  = (RSACryptoServiceProvider)cert.PrivateKey;
        string sgn = Base64Encode(rsa.SignData(to_sign, "SHA256"));

        string jwt = Base64Encode(header) + "." + Base64Encode(claimset) + "." + sgn;

        return jwt;
    }


    public string Base64Encode(byte[] b)
    {
        string s = Convert.ToBase64String(b);
        s = s.Replace("+", "-");
        s = s.Replace("/", "_");
        s = s.Split("="[0])[0]; // Remove any trailing '='s
        return s;
    }

    public string Base64Encode(string s)
    {
        return Base64Encode(Encoding.UTF8.GetBytes(s));
    }
}

Any help on this would be GREATLY appreciated!

A private key is not a certificate.

Given what This Stack Overflow thread says, i think you feed the wrong argument there. You are trying to create a certificate object, not a private key. I think what you want instead is to download the default google-api certificates (was called roots.pem for the services i worked with) , read the content on startup and give that into this instead of the private key.