Расшифровка сообщения от nodejs на c ++ libgcrypt - PullRequest
0 голосов
/ 21 декабря 2018

Мне удалось зашифровать и расшифровать сообщение как на клиентском приложении, так и на сервере.У меня возникают проблемы при отправке сообщения с сервера и расшифровке его на клиенте.

Сервер

const crypto = require('crypto');
server.listen({
    host: '0.0.0.0',
    port: PORT,
    exclusive: false
}, (err) => {
    if (err) {
        logger.error(`Error starting server ${err}`);
    }
    else console.log(`Server started on port ${PORT}`);
}).on('connection', (socket) => {
    socket.setTimeout(1500);
    socket.state = new ClientState(socket);
    clients.push(socket);
    logger.info(`${socket.state.name} connected `);
    // Handle incoming messages from clients.
    socket.on('data', async (data) => {
       let jsontString = encryptToken('test');
       console.log("Sending this to client: " + jsontString);
       socket.write(jsontString);
    });

function encryptToken(token){
    var key = 'one test AES key';

    token = "test";

    var cipher = crypto.createCipheriv("aes-128-ecb", key, '');

    let encrypted = cipher.update(token, 'utf8', 'hex');

    encrypted += cipher.final('hex');

    console.log("Encrypted token: "+ encrypted.toString('hex'));

    return encrypted.toString('hex'); 
}

// Вывод:

Encrypted token: 7876427539d4ea70f6a4aa20d247adcb

Это значение токена достигает клиентской стороны.Вот код клиента:

Клиент

// main.cpp

#include "aes.h"
#include <iostream>

int main()
{
   //socket code..
   aes rijndael_ = aes("one test AES key");
   serverAnswer = socket_.sendReceive(buf);   //buf = encrypted token that came from server

   std::vector<char> resp(serverAnswer.begin(), serverAnswer.end());

   std::string decryptAnswer = rijndael_.decrypt(resp);
   std::cout << "Decrypted: " << decryptAnswer << std::endl;
}

// вывод: расшифрован: ��wΓ��o @ ՛ B��% C��B�ƌ�ǝ] ��q

Функция дешифрования не дает мне никаких кодов ошибок .. Байты блока дополняются кратным 16 ... ещеЯ получил бы неверную ошибку длины.Я также заметил, что сервер выводит другое шестнадцатеричное шифрование от клиента, если пытается зашифровать строку 'test' с помощью AES128-ecb.

// aes.cpp

#include "aes.h"
#include <iostream>
#include <stdio.h>
#include <assert.h>
#include <sstream>
#include <algorithm>

#define GCRY_CIPHER GCRY_CIPHER_AES128   // Pick the cipher here
#define GCRY_MODE GCRY_CIPHER_MODE_ECB // Pick the cipher mode here

aes::aes(std::string k)
{
    key_ = k;
    keyLength_ = gcry_cipher_get_algo_keylen(GCRY_CIPHER);
    gcry_control (GCRYCTL_DISABLE_SECMEM, 0);
    gcry_control (GCRYCTL_INITIALIZATION_FINISHED, 0);
    gcry_cipher_open(&handle, GCRY_CIPHER, GCRY_MODE, 0);
    gcry_cipher_setkey(handle, key_.c_str(), keyLength_);
}

std::string aes::decrypt(std::vector<char> const& text) { 
    gcry_error_t gcryError;
    std::cout << "the size is " << text.size() << std::endl

    size_t textLength = text.size();

    std::cout << "textLength:: " << textLength << std::endl;

    gcry_cipher_final(handle); 
    char * decBuffer = new char[textLength];
    gcryError = gcry_cipher_decrypt(handle, decBuffer, textLength, text.data(), textLength);

    if(gcryError)
    {
        printf("gcry_cipher_decrypt failed: %s/%s\n", gcry_strsource(gcryError), gcry_strerror(gcryError));
    }

    printf("outtBuffer = %s\n", decBuffer);

    std::string ret (decBuffer);

    delete [] decBuffer;
    return ret;
}

Я пришелздесь просят помощи, потратив целый день на попытки повозиться с кодом и не повезло.Любые советы, которые помогут мне в правильном направлении, приветствуются.Дайте мне знать, если есть еще код, который мне нужно предоставить.Я приложил все усилия, чтобы сделать это в некотором роде MCV, учитывая тот факт, что работают 2 приложения.

...