简体   繁体   English

用于Python加密的AES密钥

[英]AES Secret key for the encryption for Python

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. 我的python代码中包含数据库凭据,我想对其进行加密,并在运行时通过解密对该值进行使用。

I've found the below code with the help of stackoverflow and working as expected 我已经在stackoverflow的帮助下找到了以下代码,并按预期工作

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. 上面的代码有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 提供示例链接将有很大帮助

  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. 您可以使用密码并通过在运行时使用PBKDF2函数生成密钥, 而不必将密码硬编码为源代码。

  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. ECB模式不安全,它会在数据上泄漏模式,请参阅Wikipedia中的企鹅 You should use CBC mode or CTR mode for encryption. 您应该使用CBC模式或CTR模式进行加密。 However keep in mind that, while you can execute equality queries with ECB mode, you cannot execute with CBC or CTR mode. 但是请记住,尽管您可以使用ECB模式执行平等查询,但是不能使用CBC或CTR模式执行。 If the ECB mode suits your case, that is; 如果ECB模式适合您的情况,那就是; the pattern is not a security issue, you can use ECB. 该模式不是安全问题,可以使用ECB。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM