Use Cloud KMS To Encrypt Passphrase Part 2
3 min readNov 19, 2021
Scenario: User requiring application to encrypt “passphrase” before it is stored in database
Step 5: Lets code
- Create empty “Profile” collection in Firestore.
- In VS Code select empty “KMSTEST” folder. Below diagram shows files in folder after completing code.
- Copy files “descrypt_symmetric.py” and “encrypt_symetric.py” from Public Python KMS repo inside samples/snippets
- Update requirements.txt as below
- At terminal within KMSTEST folder run below commands
> python -m venv env> env\Scripts\activate.bat> pip install -r requirements.txt
- Update Dockerfile and .dockerignore as below
- Update helper.py as below
- Update app.py — Import libraries and initialize app
- Code for “profile” collection in Firestore
- Code “add” method
Explanation: (1) encrypt_symmetric will encrypt “passphrase” using Cloud KMS API. (2) ciphertext is type “bytes”. Convert to text using base64 and save in Firestore.
- Code “list” method
Explanation: (1) passphraseplaintext method is in helper.py. Method will (a) convert passphrase text fetched from Database to bytes. (b) call Cloud KMS API to decrypt bytes into original text.
Step 6: Test Local with Postman
#Run below commands (if not already done)> python -m venv env> env\Scripts\activate.bat#start app.py> python app.py
- Add new profile document from Postman
- Confirm passphrase is encrypted in Firestore
- Fetch all user profiles in Postman
Deploy to Cloud Run => Continue to Part 3