1
votes

I tried to encrypt the contents of a file and to write the encrypted data to a cipher file with Google cloud KMS. But the php script shows a permission error. Here's the php script I tried

$cryptoKeyName = $kms->cryptoKeyName($projectId, $locationId, $keyRingId, $cryptoKeyId);
$plaintext = file_get_contents($plaintextFileName);

$response = $kms->encrypt($cryptoKeyName, $plaintext);
file_put_contents($ciphertextFileName, $response->getCiphertext());

I got this error

Fatal error: Uncaught Google\ApiCore\ApiException: { "message": "Permission 'cloudkms.cryptoKeyVersions.useToEncrypt' denied for resource 'projects/testproject/locations/global/keyRings/test/cryptoKeys/testkey'.", "code": 7, "status": "PERMISSION_DENIED", "details": [] } thrown in /home/xxxxx/xxx.com/vendor/google/gax/src/ApiException.php on line 139

When I print the user permission, it shows

Role: roles/cloudkms.admin Members: user:[email protected] Role: roles/cloudkms.cryptoKeyEncrypterDecrypter Members: user:[email protected]`
2
From where are you running this command? How have you authenticated? How did you print the users permissions? - sethvargo
Now I am testing the script from a test domain. To get authentication, I downloaded and included a json file containing a private key from console.cloud.google.com/iam-admin/serviceaccounts?project=xxxx . I used this script to display permission - $kms = new KeyManagementServiceClient(); $keyRingName = $kms->keyRingName($projectId, $locationId, $keyRingId); $keyRingPolicy = $kms->getIamPolicy($keyRingName); - Renjith
Where did you put the service account? From where are you running this code? - sethvargo
Hi sethvargo, sorry I didn't get what you mean by the service account. You mean the google account? If so it is [email protected]; the one shown in above comment. Running this code from a test domain as php file. - Renjith
Solved the issue. I was a permission issue with the json file I used to authenticate. The file should have enough permission. I had given Owner permission. You can see the file here - console.cloud.google.com/iam-admin - Renjith

2 Answers

2
votes

The Cloud KMS Admin role does not include the Encrypt/Decrypt permission. You'll need to grant those permissions to your user as well.

-1
votes

Solved the issue. It was a permission issue with the json file I used to authenticate (Something like projectname-bab93421213c2.json). The file should have enough permission. You can see the file here - console.cloud.google.com/iam-admin. I changed the permission from 'Viewer' to 'Owner' and it worked.