Q:

Cannot get signed url to work with gcloud storage

Cannot get signed url to work with gcloud storage.
I know there is probably something simple that's missing here but I can't find it.
Trying to create a signed url to a file in a gcloud bucket following the directions here https://cloud.google.com/storage/docs/access-control/create-signed-urls-program
Created a servive account and downloaded the pk12 and converted p12 to pem to get the key.
Here is code:
$pkeyid = "-----BEGIN RSA PRIVATE KEY-----
[removed actual key]
-----END RSA PRIVATE KEY-----";
$secret = "notasecret";
$expires = time()+86400;
$http_method = "GET";
$bucketName = "mybucketname";
$stringtosign = "GET\n
\n
text/plain\n
".$expires."\n
\n
\n
\n
".$bucketName ."/mymediafile.mp4";

openssl_sign($stringtosign, $signature, $pkeyid);
$emailid="serviceaccount@[project].iam.gserviceaccount.com";    
$signature = urlencode(base64_encode($signature));
$gcloudloc = "https://storage.googleapis.com/".$bucketName ."/mymediafile.mp4?GoogleAccessId=".$emailid."&Expires=".$expires."&Signature=".$signature;

I get what looks like a valid signiture, but when I try to use the full url I get
The request signature we calculated does not match the signature you provided. Check your Google secret key and signing method.

A:

I had two issues:

Pasting in the Private Key.
Missing some parameters in the openssl_sign
Also my $stringtosign seems to mess it up. Changing to all one line fixed that part.

I found this "Google Cloud Storage Signed Url for media" and was able to use the function (below) from hdezela to get it working!
function storageURL($bucket,$archivo) {
    $expires = time()+60; 
    $to_sign = ("GET\n\n\n".$expires."\n/".$bucket.'/'.$archivo);
    $fp = fopen('/path/to/google.pem', 'r');
    $priv_key = fread($fp, 8192);
    fclose($fp);
    $pkeyid = openssl_get_privatekey($priv_key);
    if(!openssl_sign($to_sign,$signature,$pkeyid,'sha256')) {
        $signature = 'sinfirma';
    } else {
        $signature = urlencode(base64_encode($signature));
    }
    return ('https://'.$bucket.'.storage.googleapis.com/'.$archivo.'?GoogleAccessId=XXXXXXX@developer.gserviceaccount.com&Expires='.$expires.'&Signature='.$signature);
}

I originally thought it was the url but this works as well.
"https://storage.googleapis.com/".$bucketName ."/

