我已经能够在客户端应用程序和服务器上加密和解密消息。从服务器发送消息并在客户端解密时遇到问题。
服务器
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 的倍数。否则我会得到一个无效的长度错误。我还注意到,如果尝试使用 AES128-ecb 加密字符串“test”,服务器会从客户端输出不同的十六进制加密。
//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;
}
在花了一整天的时间尝试修改代码并且没有运气之后,我来到这里寻求帮助。任何可以指导我正确方向的提示都值得赞赏。如果我需要提供更多代码,请告诉我。考虑到有 2 个应用程序正在运行,我尽了最大努力使它有点像 MCV。