Security one of the primary concern of any application. It should never be compromized. Recently I was working on project where I have to manage multiple keys and sensitive information. In most cases we save these information in settings or config files. In some cases people prefer to use enviromental variable and export keys before running application.
When sensitive information is saved in an unencrypted file or exported as environmental variable application become vulnerable to simple attacks. The problem is more severe when we are using source management and everyone in organization can access git repository of the application.
How to Secure Sensitive Information
There are different ways that can be used to secure sensitive information. Here is one of the way
Create a RSA key pair. Store key files in some secure place that can be accessed from only whitelisted IP addresses
Create an AES secret key, encrypt it with public key of RSA key pair and store the encrypted secret key in some persistent storage
Encrypt all sensitive information with AES secret key and then store them on any persistent storage
Whenever any piece of code need to access senstive information, load that information from storage decrypt the information using AES secret key and then use it.
With the aproach described above all sensitive information would be stored in encrypted format therefore they are secure and generally can’t be access from anywhere. So if you left your laptop on the subway or your laptop is stolen by a hacker, he would not be able to get credentials of application that you are working on provided that his IP address is not whitelisted to access RSA key pair
Implementation
Create an RSA key pair using following command and store it in some secure place
Let create skelton KeyManager python class that would manage all sensitive information
Now we would implement each method one by one. In constructor we would import RSA key that we have created, additionally we would load encrypted AES key and decrypt it with RSA key.
We would implement get method that would load encrypted data by id and return decrypted value and put method that would save sensitive data in encrypted format. Both methods have used AES encryption, therefore it could be helpful to note how AES can be used to encrypt data in python
I have included complete code here. Note that three method should be implemented carefully to make code functional and ensure security of RSA key. Additionally an AES key should be created and saved to key-value store so that everything work as expected