#python #node.js #encryption #aes
#python #node.js #шифрование #aes
Вопрос:
Я пытаюсь зашифровать / расшифровать данные из python в node.js использование tcp-сервера. Сервер отправляет зашифрованное сообщение, когда клиент подключается к нему.
Кажется, что я хорошо отправляю данные, но кажется, что декодирование ключа неверно. Я несколько раз проверял свой код, но не нашел, что с ним не так. Я специально отправляю ключ, это просто тест, я зашифрую его другим ключом позже.
Вот мой код :
server.py
import socketserver
import json
from base64 import b64encode,b64decode
from Crypto.Cipher import AES
from Crypto.Random import get_random_bytes
class Handler_TCPServer(socketserver.BaseRequestHandler):
def handle(self):
data = "A random secret"
key = get_random_bytes(32)
cipher = AES.new(key, AES.MODE_CFB)
ct_bytes = cipher.encrypt(data.encode())
iv = b64encode(cipher.iv).decode('utf-8')
ct = b64encode(ct_bytes).decode('utf-8')
json_encode = json.dumps({'key':key.hex(),'iv':iv, 'ciphertext':ct},indent=2)
self.request.sendall(json_encode.encode())
json_decode = json.loads(json_encode)
iv = b64decode(json_decode['iv'])
ct = b64decode(json_decode['ciphertext'])
cipher = AES.new(bytes.fromhex(json_decode['key']), AES.MODE_CFB, iv=iv)
date_decrypted = cipher.decrypt(ct)
print("Secret was: ", date_decrypted.decode())
print(data.encode().hex())
if __name__ == "__main__":
HOST, PORT = "localhost", 9000
tcp_server = socketserver.TCPServer((HOST, PORT), Handler_TCPServer)
tcp_server.serve_forever()
client.js
var net = require('net');
var crypto = require('crypto');
var HOST = 'localhost';
var PORT = 9000;
var client = new net.Socket();
var buff = []
function decrypt(json) {
let iv = Buffer.from(json.iv,'base64');
let encryptedText = Buffer.from(json.ciphertext,'base64');
let key = Buffer.from(json.key,'hex')
let decipher = crypto.createDecipheriv('aes-256-cfb',key, iv);
decrypted = Buffer.concat([decipher.update(encryptedText), decipher.final()]);
return decrypted.toString();
}
client.on('data', function(data) {
console.log('Client received: ');
buff.push(data)
});
client.on('end', function(data) {
let concat = Buffer.concat(buff);
let json_decode = JSON.parse(concat);
let msg_decrypt = decrypt(json_decode)
});
client.connect(PORT, HOST, function() {
console.log('Client connected to: ' HOST ':' PORT);
});
client.on('timeout',function(){
console.log('timeout')
})
client.on('close', function() {
console.log('Client closed');
});
client.on('error', function(err) {
console.error('error',err);
});
Комментарии:
1. В коде Python CFB8 используется по умолчанию для
MODE_CFB
. Соответствующий аналог в коде NodeJSaes-256-cfb8
— s.crypto.getCiphers()
. При этом часть Python-encryption / NodeJS-decryption работает, по крайней мере, на моей машине.2. Просто измените на aes-256-cfb8. Это работает, спасибо.