我们有一个加载Python应用程序config.yml与aumbry.出于生产目的,我们需要使用fernet加密此配置,aumbry可以无缝加载.
我们希望能够以透明方式加载未加密和加密,例如,如果找到则加载未加密,如果没有(生产)加载加密.到目前为止,我们已经实现了
import cryptography.Fernet as fn
from os.path import split, splitext
def _encrypt_file(path, key):
with open(path, 'rb') as infile:
file_data = infile.read()
nc_data= fn(key).encrypt(file_data)
infile.close()
base_path, filename = split(path)
name, _ = splitext(filename)
nc_name = "{}.{}".format(name, 'nc')
with open(join(base_path, nc_name), 'wb') as outfile:
outfile.write(nc_data)
outfile.close()
Run Code Online (Sandbox Code Playgroud)
from aumbry.errors import LoadError
def _get_configuration():
return aumbry.load(
aumbry.FILE,
AppConfig,
options={
'CONFIG_FILE_PATH': "config.yml"
}
)
def _get_encrypted_configuration():
return aumbry.load(
aumbry.FERNET,
AppConfig,
options={
'CONFIG_FILE_PATH': "config.nc",
'CONFIG_FILE_FERNET_KEY': 'bZhF6nN4A6fhVBPtru2dG1_6d7i0d_B2FxmsybjtE-g='
} …Run Code Online (Sandbox Code Playgroud) 我是 python 的新手,我正在开发一个加密文本字符串的程序,然后将其保存到一个文件中。当我在同一个会话中加密然后解密它时,我的程序运行良好。我想做的是:加密文件,然后关闭程序,稍后再返回并解密。我不知道密码学模块是如何工作的,但判断它是如何被称为“密钥”的,我认为这对安全很重要,但我不知道。当我尝试将 fernet 密钥保存到文本文件时,它会显示一条错误消息。当我尝试解密在前一个会话中加密的消息时,它显示 4 个引用加密模块的错误。最后,我想知道是否可以使用加密模块在会话之间解密数据。如果不,有没有其他方法可以完成这项任务?谢谢你的帮助。这是我的代码:
from cryptography.fernet import Fernet
key = Fernet.generate_key()
f = Fernet(key)
sel = input("Would you like to encrypt or decrypt? (1 = encrypt, 2 = decrypt) ")
if sel == 1:
inp = raw_input("Enter Text: ") # Type here
encoded = f.encrypt(inp)
a, b = encoded[:len(encoded)/2], encoded[len(encoded)/2:]
print ("YOUR PASSWORD: ")
print b
file = open('password.txt', 'w')
file.write(a)
elif sel == 2:
inp = raw_input("Enter Password: ")
file = open('password.txt', 'r')
a = file.readline() …Run Code Online (Sandbox Code Playgroud) python encryption cryptography python-2.7 python-cryptography
当我尝试poetry add cryptography在 Python 3.9.0 虚拟环境中使用 Python Poetry 1.1.4 包管理器 ( ) 安装加密模块时,我得到:
error: can't find Rust compiler
If you are using an outdated pip version, it is possible a prebuilt wheel is available for this package but pip is not able to install from it. Installing from the wheel would avoid the need for a Rust compiler.
To update pip, run:
pip install --upgrade pip
and then retry package installation.
If you did intend to build this …Run Code Online (Sandbox Code Playgroud) 目前,我使用EncryptedTypefromsqlalchemy_utils来自动加密进入表的数据,并在从表中检索数据时解密数据,使用一些预定义的字符串作为加密密钥。这工作正常,但现在需求发生了变化,虽然我仍然需要在进入表的路上加密数据,但我现在需要在检索数据时保持加密。我不确定这是否EncryptedType支持,或者是否有任何其他方法可以使用 SQLAlchemy 来做到这一点,而无需在我假设的密码库中使用我自己的方法。
我的表的例子:
class MyTable(db.Model):
__tablename__ = "my_table"
id = db.Column(db.Integer, primary_key=True, autoincrement="auto")
name = db.Column(db.String(50), nullable=False)
username = db.Column(EncryptedType(db.String, _key), nullable=True)
password = db.Column(EncryptedType(db.String, _key), nullable=True)
Run Code Online (Sandbox Code Playgroud) 使用 pip 版本 20.2.4、Python 3.8.2 和 Big Sur 11.0.1。
当我运行时pip install cryptography,我收到此错误:
Building wheels for collected packages: cffi
Building wheel for cffi (setup.py): started
Building wheel for cffi (setup.py): finished with status 'error'
ERROR: Command errored out with exit status 1:
command: /Users/xxx/projects/xxx/venv/bin/python -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/private/var/folders/g8/nj6ghjhgj11j84rsjmqqb00000gn/T/pip-install-aufpkz3c/cffi/setup.py'"'"'; __file__='"'"'/private/var/folders/g8/nj6ghjhgj11j84rsjmqqb00000gn/T/pip-install-aufpkz3c/cffi/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /private/var/folders/g8/nj6ghjhgj11j84rsjmqqb00000gn/T/pip-wheel-asotxqfl
cwd: /private/var/folders/g8/nj6ghjhgj11j84rsjmqqb00000gn/T/pip-install-aufpkz3c/cffi/
Complete output (42 lines):
running bdist_wheel
running build
running build_py
creating build
creating build/lib.macosx-10.14.6-x86_64-3.8
creating …Run Code Online (Sandbox Code Playgroud) 此链接中的文档表示不应使用 randint 来生成加密密钥: https: //docs.python.org/2/library/random.html
我试图了解攻击者为何以及如何破解基于此类密钥的加密系统。
我正在尝试按照本指南学习如何创建比特币地址。如果向下滚动,第一步(步骤 0)是拥有一个 256 位(64 十六进制)长的 ECDSA 密钥。我研究了 Python 密码学,并使用下面的代码来测试生成密钥,但保存的密钥始终是一个长(180 个字符)的 Base 64 字符串。
我尝试阅读文档并查看我在 Github 上调用的函数,但我看不到在哪里可以指定密钥应该有多长。在该文件的第 216 行,它表示 secp256k1 的密钥大小默认为 256 位。这是否意味着我导出错误?
0x1或者,我考虑过在 secp256k1,(到)的范围内生成一个长度为 64 个字符的随机十六进制字符串0xFFFF FFFF FFFF FFFF FFFF FFFF FFFF FFFE BAAE DCE6 AF48 A03B BFD2 5E8C D036 4140,但我不知道在哪里可以从字符串或十六进制值创建私钥实例
gentest.py
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives.asymmetric import ec
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.serialization import load_pem_private_key
def gen_key():
private_key = ec.generate_private_key(
ec.SECP256K1(), default_backend()
)
return private_key
def save_key(pk, filename):
pem = pk.private_bytes( …Run Code Online (Sandbox Code Playgroud) 我需要一个函数来生成一个新的 RSA 私钥,然后可以将其作为字符串存储在 Django 模型字段中。我正在使用密码学==2.1.4。
我想我已经通过以下方式实现了这一点:
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import rsa
from cryptography.hazmat.backends import default_backend
KEY_SIZE = 2048
PUBLIC_EXP = 65537
private_key = rsa.generate_private_key(
public_exponent=PUBLIC_EXP,
key_size=KEY_SIZE,
backend=default_backend()
)
private_key_str = private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.TraditionalOpenSSL,
encryption_algorithm=serialization.NoEncryption()
).decode()
Run Code Online (Sandbox Code Playgroud)
但显然我在这里遗漏了一些东西或一些步骤(尽管我应该知道为什么......)private_key_str始终具有相同的值。
这里有什么建议吗?
我正在开发一个部署到 AWS Lambda 的无服务器 Flask 应用程序。该程序使用密码学库(使用版本3.4.7)。在本地,程序运行良好,没有任何问题。但是,每当部署在 Lambda 上时,都会出现以下错误:
from cryptography.fernet import Fernet
File "/var/task/cryptography/fernet.py", line 16, in <module>
from cryptography.hazmat.primitives import hashes, padding
File "/var/task/cryptography/hazmat/primitives/padding.py", line 11, in <module>
from cryptography.hazmat.bindings._padding import lib
ImportError: /var/task/cryptography/hazmat/bindings/_padding.abi3.so: cannot open shared object file: No such file or directory
Run Code Online (Sandbox Code Playgroud)
当使用“危险材料”模块中的一些必需功能时,会出现非常相似的错误:
File "/var/task/cryptography/hazmat/primitives/kdf/pbkdf2.py", line 28, in __init__
backend = _get_backend(backend)
File "/var/task/cryptography/hazmat/backends/__init__.py", line 23, in _get_backend
return default_backend()
File "/var/task/cryptography/hazmat/backends/__init__.py", line 14, in default_backend
from cryptography.hazmat.backends.openssl.backend import backend
File "/var/task/cryptography/hazmat/backends/openssl/__init__.py", line 6, in <module>
from …Run Code Online (Sandbox Code Playgroud) python amazon-web-services aws-lambda serverless-framework python-cryptography
我正在使用该库开发带有 Firestore 实时数据库的 Python Web 应用程序firebase_admin。Firestore 密钥采用包含 10 个变量的 .json 文件形式。但是,我想将其中一些变量存储为环境变量,这样它们就不会公开可见。因此,我不使用 Firebase SDK .json 文件,而是使用该文件的元素创建自己的字典。字典看起来像这样,所有内容都是直接从 .json 文件复制的:
my_credentials = {
"type": "service_account",
"project_id": "bookclub-b2db5",
"private_key_id": os.environ.get("PRIVATE_KEY_ID"),
"private_key": os.environ.get("PRIVATE_KEY"),
"client_email": os.environ.get("CLIENT_EMAIL"),
"client_id": os.environ.get("CLIENT_ID"),
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": os.environ.get("AUTH_PROVIDER_X509_CERT_URL"),
"client_x509_cert_url": os.environ.get("AUTH_PROVIDER_X509_CERT_URL")
}
Run Code Online (Sandbox Code Playgroud)
我已将私钥设置为PRIVATE_KEY环境变量。私钥大致是这样的(这里的字符是组成的):
"-----BEGIN PRIVATE KEY-----\nEW8nYP9T840Sb8tQMi\nhZ(...MORE CHARACTERS HERE...)EW8nYP9T840Sb8tQMi/EW8nYP9T840Sb8tQMi\EW8nYP9T840Sb8tQMi/EW8nYP9T840Sb8tQMi=\n-----END PRIVATE KEY-----\n"
Run Code Online (Sandbox Code Playgroud)
然后,我尝试从这些凭据创建 Firebase 证书并初始化应用程序
cred = firebase_admin.credentials.Certificate(my_credentials)
firebase_admin.initialize_app(cred, {'databaseURL': 'https://myapp.firebasedatabase.app/'})
Run Code Online (Sandbox Code Playgroud)
然而,事实证明 PRIVATE_KEY 环境变量不可读(无法反序列化),并且会抛出错误:
Traceback (most recent call last):
File "C:\Users\jarem\Desktop\data_science\python-working-directory\_MyApps\BookClub2.0\venv\lib\site-packages\firebase_admin\credentials.py", line 96, in __init__
self._g_credential = …Run Code Online (Sandbox Code Playgroud) python ×8
cryptography ×3
encryption ×2
aumbry ×1
aws-lambda ×1
bitcoin ×1
firebase ×1
macos ×1
oauth ×1
pip ×1
python-2.7 ×1
python-3.x ×1
python-cffi ×1
random ×1
rsa ×1
sqlalchemy ×1