简体   繁体   中英

Emit encrypted message to socket.io room

I try to send encrypted data by using AES encryption protocol (send AES-key by RSA to client) and after I emit data to the room with many users I'm unable to decrypt messages on client side. This connected with AES-key issue. Every time when I send message from client-side to server, server generate new AES-key, so each time messages which were emitted by client it use different keys. And after that I face with my problem. What should I do to send AES encrypted message to the socket.io room?

There is some code

Server:

socket.on('send', function (data) {
    // Data decryption using AES
    let decryptedMessage = aesWrapper.decrypt(aesKey, data.message);
    let decryptedRoom = aesWrapper.decrypt(aesKey, data.room);
    data['message'] = decryptedMessage;
    data['room'] = decryptedRoom;

    // Trying to parse each user with unique AES key
    io_s.in(decryptedRoom).clients((error, clients) => {
        if (error) {
            console.log(error);
        } else {
            clients.forEach(client => {
                    let ecryptedMessage = aesWrapper.createAesMessage(aesKey, data['message']);
                    let ecryptedRoom = aesWrapper.createAesMessage(aesKey, data['room']);

                    let dataNew = { type: data.type, message: ecryptedMessage, room: ecryptedRoom }
                    console.log(dataNew);
                    socket.to(client).emit('message', dataNew);
            });
        }
    })
    console.log(socket.id);
});

By this code I work only with one socket connection, so encryption work only for him and others couldn't decrypt it.

I also tried to use RSA encryption and send AES-key for every connected sockets to the room, but result was the same.

Code:

const newAesKey = aesWrapper.generateKey();
    let encryptedAesKey = rsaWrapper.encrypt(rsaWrapper.clientPub, (newAesKey.toString('base64')));
    socket.to(decryptedRoom).emit('send key from server to client', encryptedAesKey);

    socket.on('aes client encrypted message', () => {
        let ecryptedMessage = aesWrapper.createAesMessage(newAesKey, data['message']);
        console.log(ecryptedMessage);
        let ecryptedRoom = aesWrapper.createAesMessage(newAesKey, data['room']);
        let dataNew = { type: data.type, message: ecryptedMessage, room: ecryptedRoom, nickname: data.nickname }
        console.log(dataNew);
        socket.to(decryptedRoom).emit('message', dataNew);
    })

我已经通过添加数组变量解决了这个问题,在这里我为每个用户保存了aes-keys。

keysUsers[socket.id] = aesKey;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM