ValueError: RSA key format is not supported
Делаю школьный проект (мессенджер с шифрованием) и возникла проблема. При получении публичного ключа с сервера вылезает ошибка RSA key format is not supported. Если считывать ключ с файла все работает. Код сервера и модуля шифрования прилагаю.
Шифрование:
import requests
from Cryptodome.PublicKey import RSA
from Cryptodome.Random import get_random_bytes
from Cryptodome.Cipher import AES, PKCS1_OAEP
code = 'nice'
receiver = 'alice'
def crypto():
# Генерация ключа RSA
RSA_key = RSA.generate(2048)
# Генерация приватного ключа
pr_key = RSA_key.exportKey(
passphrase=code,
pkcs=8,
protection="scryptAndAES128-CBC"
)
with open('key.bin', 'wb') as f:
f.write(pr_key)
# Генерация публичного ключа с помощью приватного
pu_key = RSA_key.public_key().exportKey()
response = requests.post(
'http://127.0.0.1:5000/change_key',
json={'login': receiver, 'key': str(pu_key)}
)
def encrypt(item):
response = ''
try:
response = requests.get(
'http://127.0.0.1:5000/send_key',
params={'receiver': receiver}
)
except:
pass
recipient_key = RSA.import_key(response.json()['key'], passphrase=code)
session_key = get_random_bytes(16)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(item)
return [cipher_rsa.encrypt(session_key), cipher_aes.nonce, tag, ciphertext]
def decrypt(enc_data):
private_key = RSA.import_key(
open('key.bin').read(),
passphrase=code
)
enc_session_key, nonce, tag, ciphertext = [
enc_data[x] for x in range(0, 4)
]
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
return data
crypto()
item = input().encode('UTF-8')
print(decrypt(encrypt(item)).decode('UTF-8'))
Сервер:
from datetime import datetime
from flask import Flask, request, abort
import json
import time
# БД пользователя в json вместо csv
file = 'users.json'
data = json.load(open(file))
app = Flask(__name__)
messages = []
@app.route("/")
def hello():
return 'Hello, World <a href="/status">Status</a>'
@app.route("/status")
def status_view():
return {
'status': True,
'name': 'NICE',
'time': datetime.now().strftime('%Y.%m.%d - %H:%M'),
'time_for_sort': time.time()
}
# Отправка публичного ключа по запросу
@app.route("/send_key", methods=['GET'])
def send_key():
login = request.args['receiver']
for i in range(len(data)):
if data[i]["login"] == login:
return {'key': data[i]['key']}
@app.route("/change_key", methods=['POST'])
def change_key():
login = request.json['login']
key = request.json['key']
for i in range(len(data)):
if data[i]["login"] == login:
data[i]["key"] = key
return {'ok': True}