0

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.

Dubs
  • 640
  • 5
  • 14

1 Answers1

1

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)
Dubs
  • 640
  • 5
  • 14
  • Just leaving the [Python Client for Cloud Key Management Service (KMS) API](https://googleapis.github.io/google-cloud-python/latest/kms/#python-client-for-cloud-key-management-service-kms-api) [reference](https://googleapis.dev/python/cloudkms/latest/gapic/v1/api.html#google.cloud.kms_v1.KeyManagementServiceClient). – fbraga Sep 16 '19 at 12:17