Как преобразовать строку в закрытый ключ RSA в python
я создаю приложение для социальных сетей на django и пытаюсь добиться сквозного шифрования, используя ключи rsa. когда пользователь регистрируется, генерируется открытый/закрытый ключ RSA, затем закрытый ключ симметрично шифруется и хранится в базе данных. проблема в том, что когда я получаю закрытый ключ, его тип - str, который модуль rsa
не может прочитать. оригинальный тип, когда он был сгенерирован, был rsa.key.PrivateKey
вот фрагмент из models.py:
class Post(models.Model):
privatekey = models.BinaryField()
publickey = models.BinaryField()
и представление регистрации:
def register(request):
if request.method == 'POST':
form = UserRegister(request.POST)
ver = verification(request.POST)
if form.is_valid() and ver.is_valid():
form.username = request.POST.get('username')
form.password1 = request.POST.get('password1')
form.password2 = request.POST.get('password2')
try:
form.save()
except:
messages.warning(request, f'there is an error')
return render(request, 'users/register.html', {"form": form})
username = form.cleaned_data.get('username')
new_user = authenticate(username=form.cleaned_data['username'],password=form.cleaned_data['password1'],)
login(request, new_user)
publickey, privatekey = rsa.newkeys(2048)
profile = request.user.profile
profile.publickey = publickey
password = request.POST.get('password1')
profile.privatekey = encryption_decryption(str(privatekey), password, 'e')
profile.save()
response = redirect('complete-profile')
privkey = encryption_decryption(request.user.profile.privatekey, password, 'd')
response.set_cookie('key', privkey, max_age=None)
return response
else:
form = UserRegister()
ver = verification()
return render(request, 'users/register.html', {"form": form, 'ver': ver,})
проблема в функции encryption_decryption, она отвечает за шифрование закрытого ключа и его восстановление (расшифровку), когда пользователь входит в систему
import base64
from cryptography.exceptions import AlreadyFinalized
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from rsa.key import PrivateKey
def encryption_decryption(text, password, ed):
password_bytes = password.encode('utf-8')
salt = b"I\x84\xa0\x1bkg\xef,\x1b\xfb\xc9\xaf:\xb8'#\x92C0\xbaI\xab\xe6\x94^v+e\x96\xad\x1e\xccBg\xa1\xa2\x82\xe98HU\xb1v\x08\xb7\xea<\xc0\xb5\x0c\xc1\xaa\xea\xa4\xe9\xfb\xba\xc0A\xfd\x10\x99\x9d\x03"
kdf = PBKDF2HMAC(algorithm=hashes.SHA512(), length=32, salt=salt, iterations=10000, backend=default_backend())
key = kdf.derive(password_bytes)
nonce = b'\xaf\xfa\xed9\xb1\xd1\xc1N\xb1\x1c95'
aesgcm = AESGCM(key)
try:
if ed == 'e':
cipher_text_bytes = aesgcm.encrypt(nonce=nonce, data=text.encode('utf-8'), associated_data=None)
cipher_text = base64.urlsafe_b64encode(cipher_text_bytes)
return cipher_text
elif ed == 'd':
decrypted_cipher_text_bytes = aesgcm.decrypt(nonce=nonce, data=base64.urlsafe_b64decode(text), associated_data=None)
decrypted_cipher_text = decrypted_cipher_text_bytes.decode('utf-8')
return decrypted_cipher_text
except:
return False
значение, возвращаемое из decrypted_cipher_text - string
, как я могу сделать его типом rsa.key.PrivateKey
?