Search code examples
google-compute-enginegoogle-cloud-kms

Python auth for kms


I'm new to google cloud kms product, is there a tutorial on how to authenticate ( from third party server ) kms with python? The goal is to access the public key, encrypt the data ( async ). Another server will have more permissions and will be able to decrypt. I don't want to use gcloud shell client.


Solution

  • I solved it using the json file. I will post the code if it help someone in the future.

    def encrypt_rsa(plaintext, key_name):

    # get the public key credentials = service_account.Credentials.from_service_account_file( 'the_key_file_of_service_account.json') scoped_credentials = credentials.with_scopes( ['https://www.googleapis.com/auth/cloud-platform']) client = kms_v1.KeyManagementServiceClient(credentials=credentials) response = client.get_public_key(key_name) key_txt = response.pem.encode('ascii') public_key = serialization.load_pem_public_key(key_txt, default_backend()) # encrypt plaintext pad = padding.OAEP(mgf=padding.MGF1(algorithm=hashes.SHA256()), algorithm=hashes.SHA256(), label=None) plaintext = base64.urlsafe_b64encode(plaintext.encode("ascii")) return public_key.encrypt(plaintext, pad)