0

I am having database credentials in my python code, which I would like to have it encrypted, use the value in run time by decrypting it.

I've found the below code with the help of stackoverflow and working as expected

from Crypto.Cipher import AES
import base64

msg_text = b'test some plain text here'.rjust(32)
secret_key = b'1234567890123456' # create new & store somewhere safe

cipher = AES.new(secret_key,AES.MODE_ECB) # never use ECB in strong systems obviously
encoded = base64.b64encode(cipher.encrypt(msg_text))
print(encoded)
# ...
decoded = cipher.decrypt(base64.b64decode(encoded))
print(decoded.strip())

Above code has secret_key and comment says to create new secret key.

  1. How can I create a secret key and from where it can be created?

  2. What would be the recommended place to store secret keys? Is there any structure/place that's recommended to save? I think it should be saved in database

  3. Is above code the strong way of encrypting and decrypting? If it can be tampered, what way should be approached? Providing sample link would be a great help

James Z
  • 12,209
  • 10
  • 24
  • 44
Karthick Raju
  • 757
  • 8
  • 29
  • Does the secret belong to who? users or to the system? If belongs to the user you can use PBKDF2 to generate from users passwords. – kelalaka Nov 28 '18 at 09:27
  • @kelalaka in the above code secret key value is `1234567890123456`. Is there a way I can create my own. Just now I read about os.urandom(16). Is this right way of doing? – Karthick Raju Nov 28 '18 at 09:31

1 Answers1

0
  1. Instead of hardcoding the password into source code, you can use a password and generate the keys by using PBKDF2 functions on the runtime.

  2. A password should not be saved in the database, or in a file. You must keep in the memory.

  3. The ECB mode is insecure, it leaks pattern on the data, see the penguin in Wikipedia. You should use CBC mode or CTR mode for encryption. However keep in mind that, while you can execute equality queries with ECB mode, you cannot execute with CBC or CTR mode. If the ECB mode suits your case, that is; the pattern is not a security issue, you can use ECB.

kelalaka
  • 5,064
  • 5
  • 27
  • 44