Я копирую безопасное рукопожатие клиент-сервер TCP в Python с использованием модуля pycrypto. Когда «сервер» отправляет открытый ключ через сокет, я вынужден преобразовать открытый ключ в строку. Затем «клиент» получает открытый ключ в виде строки, которая не может быть зашифрована в соответствии с модулем pycrypto.
Я получаю сообщение об ошибке:
AttributeError: объект 'str' не имеет атрибута 'encrypt' в отношении enc_data = public_key.encrypt(secret_piece, 12) на стороне клиента.
Как преобразовать строку public_key обратно в исходное значение, когда она была впервые сгенерирована модулем RSA?
Код сервера:
def main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(1)
c, addr = s.accept()
print "Connection from: "+str(addr)
while True:
data = c.recv(1024)
if not data:
break
print "from connected user: "+str(data)
print "Start the SSL Handshake..."
a = raw_input('Press enter to generate the key pair. ')
key = RSA.generate(1024, random_generator)
public_key = key.publickey()
print "Key pair generated"
a = raw_input('Press enter to send public key to client ')
print "Sending key..."
if c.send(str(public_key)):
print "Public Key Sent"
print "Waiting for secret list..."
if c.recv(1024):
print "List received."
secret_list = c.recv(1024)
a = raw_input('Press enter to check the information from the list. ')
decrypted_info = key.decrypt(secret_list.enc_data)
match_or_not = SHA256.new(decrypted_info).digest() == secret_list.hash_value
if match_or_not:
print "Info Matches. Sending the ciphertext..."
info_to_be_encrypted = "It seems all secure. Let's talk!"
aes = AES.new(Random.get_random_bytes(16), AES.MODE_ECB)
cipher_text = aes.encrypt(info_to_be_encrypted)
if c.send(cipher_text):
print "Ciphertext sent."
Код клиента
def main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host,port))
message = raw_input("-> ")
while message != 'q':
s.send(message)
public_key = s.recv(1024)
print 'Received from server: '+str(public_key)
message = raw_input("->Press enter to verify the public key.")
print "Public Key verified!"
message = raw_input("-> Press enter to prepare the secret list.")
print "Client prepares the secret list."
secret_piece = Random.get_random_bytes(16)
enc_data = public_key.encrypt(secret_piece, 12)
hash_value = SHA256.new(secret_piece).digest()
L = [enc_data, hash_value]
print "List is ready."
message = raw_input("-> Press enter to send the list")
s.send(str(L))
print "List sent."
print "Waiting for ciphertext from the server..."
if s.recv(1024):
print "Ciphertext recieved."
cipher_text = s.recv(1024)
print "The encrypted message is: " + cipher_text
print "The decrypted message is: " + aes.decrypt(cipher_text)
s.close()
Подробнее здесь: https://stackoverflow.com/questions/497 ... ect-python
Как преобразовать строку ключа обратно в объект ключа pycrypto? (Питон) ⇐ Python
Программы на Python
1772183135
Anonymous
Я копирую безопасное рукопожатие клиент-сервер TCP в Python с использованием модуля pycrypto. Когда «сервер» отправляет открытый ключ через сокет, я вынужден преобразовать открытый ключ в строку. Затем «клиент» получает открытый ключ в виде строки, которая не может быть зашифрована в соответствии с модулем pycrypto.
Я получаю сообщение об ошибке:
[b]AttributeError: объект 'str' не имеет атрибута 'encrypt'[/b] в отношении [b]enc_data = public_key.encrypt(secret_piece, 12)[/b] на стороне клиента.
Как преобразовать строку public_key обратно в исходное значение, когда она была впервые сгенерирована модулем RSA?
[b]Код сервера:[/b]
def main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.bind((host,port))
s.listen(1)
c, addr = s.accept()
print "Connection from: "+str(addr)
while True:
data = c.recv(1024)
if not data:
break
print "from connected user: "+str(data)
print "Start the SSL Handshake..."
a = raw_input('Press enter to generate the key pair. ')
key = RSA.generate(1024, random_generator)
public_key = key.publickey()
print "Key pair generated"
a = raw_input('Press enter to send public key to client ')
print "Sending key..."
if c.send(str(public_key)):
print "Public Key Sent"
print "Waiting for secret list..."
if c.recv(1024):
print "List received."
secret_list = c.recv(1024)
a = raw_input('Press enter to check the information from the list. ')
decrypted_info = key.decrypt(secret_list.enc_data)
match_or_not = SHA256.new(decrypted_info).digest() == secret_list.hash_value
if match_or_not:
print "Info Matches. Sending the ciphertext..."
info_to_be_encrypted = "It seems all secure. Let's talk!"
aes = AES.new(Random.get_random_bytes(16), AES.MODE_ECB)
cipher_text = aes.encrypt(info_to_be_encrypted)
if c.send(cipher_text):
print "Ciphertext sent."
[b]Код клиента[/b]
def main():
host = '127.0.0.1'
port = 5000
s = socket.socket()
s.connect((host,port))
message = raw_input("-> ")
while message != 'q':
s.send(message)
public_key = s.recv(1024)
print 'Received from server: '+str(public_key)
message = raw_input("->Press enter to verify the public key.")
print "Public Key verified!"
message = raw_input("-> Press enter to prepare the secret list.")
print "Client prepares the secret list."
secret_piece = Random.get_random_bytes(16)
enc_data = public_key.encrypt(secret_piece, 12)
hash_value = SHA256.new(secret_piece).digest()
L = [enc_data, hash_value]
print "List is ready."
message = raw_input("-> Press enter to send the list")
s.send(str(L))
print "List sent."
print "Waiting for ciphertext from the server..."
if s.recv(1024):
print "Ciphertext recieved."
cipher_text = s.recv(1024)
print "The encrypted message is: " + cipher_text
print "The decrypted message is: " + aes.decrypt(cipher_text)
s.close()
Подробнее здесь: [url]https://stackoverflow.com/questions/49724789/how-to-convert-a-key-string-back-into-a-pycrypto-key-object-python[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия