Ошибка шифрования: StreamTransformationFilter: invalid PKCS #7 block padding found
h-ник сервера:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include <QtNetwork>
#include <QTextStream>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QFileDialog>
#include <QMessageBox>
#include <QProcessEnvironment>
#include <aes.h>
#include <modes.h>
#include <base64.h>
namespace Ui {
class MainWindow;
}
using namespace CryptoPP;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
QString valid_login = "admin", valid_password = "admin";
QJsonObject read_param;
QJsonDocument main_param_doc;
QString std_path = QCoreApplication::applicationDirPath() + "/standart_param.json";
QJsonArray main_param;
private slots:
void onClientConnected();
void onClientDisconnected();
void onClientReadData();
private:
void dispatchCommand(QJsonObject& json_cmd,
QTextStream& client_stream);
void command_getTime(QTextStream& client_stream);
void command_getFormatTime(QJsonObject& json_cmd,
QTextStream& client_stream);
void command_updateParam(QJsonObject& json_cmd, QTextStream& client_stream);
void command_takeStdParam(QJsonObject& json_cmd, QTextStream& client_stream);
void command_userAuth(QJsonObject& json_cmd, QTextStream& client_stream);
void sendCommand(QJsonDocument& json_cmd,
QTextStream& client_stream);
Ui::MainWindow *ui;
QTcpServer* m_tcpServer = nullptr;
};
#endif // MAINWINDOW_H
cpp-шник сервера:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
QFile file(std_path);
if (file.open(QFile::ReadOnly)) {
QByteArray qwerty = file.readAll();
main_param_doc = QJsonDocument::fromJson(qwerty);
if (!main_param_doc.isNull() && !main_param_doc.isEmpty()) {
QJsonObject tmp = main_param_doc.object();
main_param = tmp.value("param").toArray();
} else {
QMessageBox::warning(0, "Ошибка", "JSON-Документ пуст",0,0);
}
}
m_tcpServer = new QTcpServer(this);
m_tcpServer->setProxy(QNetworkProxy::NoProxy);
if (m_tcpServer->listen(QHostAddress::AnyIPv4, 5555))
ui->statusBar->showMessage("Сервер запущен");
else
ui->statusBar->showMessage("Ошибка запуска сервера");
connect(m_tcpServer, &QTcpServer::newConnection, this, &MainWindow::onClientConnected);
}
MainWindow::~MainWindow()
{
delete ui;
}
std::string encrypt(const std::string& str_in, const std::string& key)
{
std::string str_out;
CryptoPP::ECB_Mode<CryptoPP::AES>::Encryption encryption((byte*)key.c_str(), key.length());
CryptoPP::StringSource encryptor(str_in, true,
new CryptoPP::StreamTransformationFilter(encryption,
new CryptoPP::Base64Encoder(
new CryptoPP::StringSink(str_out),
false
)
)
);
return str_out;
}
std::string decrypt(const std::string& str_in, const std::string& key)
{
std::string str_out;
CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption decryption((byte*)key.c_str(), key.length());
CryptoPP::StringSource decryptor(str_in, true,
new CryptoPP::Base64Decoder(
new CryptoPP::StreamTransformationFilter(decryption,
new CryptoPP::StringSink(str_out)
)
)
);
return str_out;
}
void MainWindow::onClientConnected()
{
QTcpSocket* clientConnection = m_tcpServer->nextPendingConnection();
connect(clientConnection, &QTcpSocket::disconnected, this, &MainWindow::onClientDisconnected);
connect(clientConnection, &QTcpSocket::readyRead, this, &MainWindow::onClientReadData);
// QTextStream tcp_stream(clientConnection);
// tcp_stream << "Hello" << flush;
ui->listWidget->addItem("Подключился " + clientConnection->peerAddress().toString());
}
void MainWindow::onClientDisconnected()
{
QTcpSocket* clientConnection = qobject_cast<QTcpSocket*>(sender());
if (clientConnection) {
ui->listWidget->addItem("Отключился " + clientConnection->peerAddress().toString());
clientConnection->deleteLater();
}
}
void MainWindow::onClientReadData()
{
QTcpSocket* clientConnection = qobject_cast<QTcpSocket*>(sender());
QTextStream tcp_stream(clientConnection);
QString message = tcp_stream.readAll();
QString temp = QString::fromStdString(decrypt(message.toStdString(),"1357924680753951"));
QJsonDocument doc = QJsonDocument::fromJson(temp.toUtf8());
if (doc.isObject()) {
QJsonObject obj = doc.object();
if (obj.contains("command")) {
dispatchCommand(obj, tcp_stream);
}
else
ui->listWidget->addItem("Ошибка JSON");
}
else
ui->listWidget->addItem("Ошибка JSON");
}
void MainWindow::dispatchCommand(QJsonObject &json_cmd,
QTextStream &client_stream)
{
QJsonValue val = json_cmd["command"];
if (val.isString()) {
QString cmd = val.toString();
ui->listWidget->addItem("command: " + cmd);
if (cmd == "getTime") {
command_getTime(client_stream);
}
else if (cmd == "getFormatTime") {
command_getFormatTime(json_cmd, client_stream);
}
else if (cmd == "updateParam") {
command_updateParam(json_cmd, client_stream);
}
else if (cmd == "takeStdParam") {
command_takeStdParam(json_cmd, client_stream);
}
else if (cmd == "userAuth") {
command_userAuth(json_cmd, client_stream);
}
else
ui->listWidget->addItem("Неизвестная команда");
}
else
ui->listWidget->addItem("Ошибка JSON");
}
/*
* { "answer": "getTme",
* "data": "16.05.2022 12:10:05" }
*/
void MainWindow::command_getTime(QTextStream &client_stream)
{
QJsonDocument doc;
QJsonObject answer;
answer["answer"] = "getTime";
answer["data"] = QDateTime::currentDateTime().toString();
doc.setObject(answer);
sendCommand(doc, client_stream);
}
void MainWindow::command_getFormatTime(QJsonObject &json_cmd,
QTextStream &client_stream)
{
if (json_cmd.contains("params")) {
QJsonValue val = json_cmd["params"];
if (val.isObject()) {
QJsonObject ob = val.toObject();
if (ob.contains("timeFormat")) {
QJsonValue fmt_val = ob["timeFormat"];
if (fmt_val.isString()) {
QString tm_format = fmt_val.toString();
QJsonDocument doc;
QJsonObject answer;
answer["answer"] = "getFormatTime";
answer["data"] = QDateTime::currentDateTime().toString(tm_format);
doc.setObject(answer);
sendCommand(doc, client_stream);
}
else
ui->listWidget->addItem("Ошибка JSON");
}
else
ui->listWidget->addItem("Ошибка JSON");
}
else
ui->listWidget->addItem("Ошибка JSON");
}
else
ui->listWidget->addItem("Ошибка JSON");
}
void MainWindow::command_updateParam(QJsonObject& json_cmd, QTextStream& client_stream)
{
QProcessEnvironment env = QProcessEnvironment::systemEnvironment();
QJsonArray temp_arr;
QJsonObject temp_obj;
for (const QString &key: env.keys()) {
QJsonObject b;
b[key] = env.value(key);
temp_arr.append(b);
}
QJsonObject answer;
answer["answer"] = "updateParam";
answer["params"] = temp_arr;
QJsonDocument doc;
doc.setObject(answer);
sendCommand(doc, client_stream);
}
void MainWindow::command_takeStdParam(QJsonObject& json_cmd, QTextStream &client_stream)
{
QJsonObject answer;
answer["answer"] = "takeStdParam";
answer["result"] = main_param;
QJsonDocument doc;
doc.setObject(answer);
sendCommand(doc, client_stream);
}
void MainWindow::command_userAuth(QJsonObject &json_cmd, QTextStream &client_stream)
{
QJsonObject answer;
if (json_cmd.value("password").toString() == valid_password && json_cmd.value("login").toString() == valid_login)
answer["result"] = 1;
else
answer["result"] = 0;
answer["answer"] = "userAuth";
QJsonDocument doc;
doc.setObject(answer);
sendCommand(doc, client_stream);
}
void MainWindow::sendCommand(QJsonDocument &json_cmd,
QTextStream &client_stream)
{
QString msg(json_cmd.toJson());
ui->listWidget->addItem(msg);
QString str = QString::fromStdString(encrypt(msg.toStdString(),"1357924680753951"));
client_stream << str << flush;
}
h-ник клиента:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QDialog>
#include <QVBoxLayout>
#include <QLineEdit>
#include <QPushButton>
#include <QAuthenticator>
#include <QTimer>
#include <QMainWindow>
#include <QtNetwork>
#include <QTextStream>
#include <QJsonDocument>
#include <QJsonObject>
#include <QJsonArray>
#include <QJsonValue>
#include <QFileDialog>
#include <QAxObject>
#include <QMessageBox>
#include <cstdlib>
#include <QSet>
#include <QDialog>
#include <QVBoxLayout>
#include <aes.h>
#include <modes.h>
#include <base64.h>
class Timer;
class AuthDialog;
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
using namespace CryptoPP;
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
AuthDialog* authDialog_;
void sendCommand(QJsonDocument &json_cmd);
bool auth_status;
QJsonObject list_param;
QJsonDocument missmatches;
QString json_path = QCoreApplication::applicationDirPath() + "/missmatches.json";
private slots:
void on_connectButton_clicked();
void on_disconnectButton_clicked();
void onServerConnected();
void onServerDisconnected();
void onServerReadData();
void checkUser(QAuthenticator& tmp);
void on_getTime_clicked();
void on_getFormatTime_clicked();
void updateParam();
void on_compareButton_clicked();
void exit_app();
void on_pushButton_clicked();
void on_pushButton_2_clicked();
private:
void dispatchCommand(QJsonObject& json_cmd);
void answer_getTime(QJsonObject& json_cmd);
void answer_takeStdParam(QJsonObject& json_cmd);
void answer_updateParam(QJsonObject& json_cmd);
void answer_userAuth(QJsonObject& json_cmd);
void change_status();
Ui::MainWindow *ui;
QTimer *timer;
QTcpSocket* m_serverConnection = nullptr;
QTextStream m_tcpStream;
QJsonArray StdParam, UpdParam;
signals:
void success();
void tryAgain();
};
class Timer : public QObject {
Q_OBJECT
public:
private slots:
};
class AuthDialog : public QDialog {
Q_OBJECT
public:
int try_times = 5;
AuthDialog(QWidget *parent = nullptr);
QLineEdit *usernameEdit;
QLineEdit *passwordEdit;
void checkCredentials();
void yspex();
void neydacha();
QPushButton *cancelButton, *okButton;
signals:
void send(QAuthenticator& tmp);
void changeAuthStatus();
private:
};
#endif // MAINWINDOW_H
cpp-шник клиента:
#include "mainwindow.h"
#include "ui_mainwindow.h"
AuthDialog::AuthDialog(QWidget *parent) : QDialog(parent) {
QVBoxLayout *layout = new QVBoxLayout(this);
this->setFixedWidth(300);
this->setFixedHeight(200);
QLabel *usernameLabel = new QLabel("Логин:", this);
AuthDialog::usernameEdit = new QLineEdit(this);
layout->addWidget(usernameLabel);
layout->addWidget(AuthDialog::usernameEdit);
QLabel *passwordLabel = new QLabel("Пароль:", this);
AuthDialog::passwordEdit = new QLineEdit(this);
AuthDialog::passwordEdit->setEchoMode(QLineEdit::Password);
layout->addWidget(passwordLabel);
layout->addWidget(AuthDialog::passwordEdit);
QPushButton *okButton = new QPushButton("Авторизация", this);
layout->addWidget(okButton);
connect(okButton, &QPushButton::clicked, this, &AuthDialog::checkCredentials);
setWindowTitle("Окно авторизации");
setModal(true);
AuthDialog::show();
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
ui->tableWidget->setColumnCount(2);
ui->tableWidget_2->setColumnCount(2);
ui->statusbar->showMessage("Отключен");
m_serverConnection = new QTcpSocket(this);
m_serverConnection->setProxy(QNetworkProxy::NoProxy);
m_tcpStream.setDevice(m_serverConnection);
auth_status = false;
connect(m_serverConnection, &QTcpSocket::connected, this, &MainWindow::onServerConnected);
connect(m_serverConnection, &QTcpSocket::disconnected, this, &MainWindow::onServerDisconnected);
connect(m_serverConnection, &QTcpSocket::readyRead, this, &MainWindow::onServerReadData);
}
MainWindow::~MainWindow()
{
m_serverConnection->abort();
delete m_serverConnection;
delete ui;
}
void MainWindow::on_connectButton_clicked()
{
m_serverConnection->abort();
m_serverConnection->connectToHost(ui->ipAddr->text(), ui->portNum->value());
}
void MainWindow::on_disconnectButton_clicked()
{
m_serverConnection->close();
}
std::string encrypt(const std::string& str_in, const std::string& key)
{
std::string str_out;
CryptoPP::ECB_Mode<CryptoPP::AES>::Encryption encryption((byte*)key.c_str(), key.length());
CryptoPP::StringSource encryptor(str_in, true,
new CryptoPP::StreamTransformationFilter(encryption,
new CryptoPP::Base64Encoder(
new CryptoPP::StringSink(str_out),
false
)
)
);
return str_out;
}
std::string decrypt(const std::string& str_in, const std::string& key)
{
std::string str_out;
CryptoPP::ECB_Mode<CryptoPP::AES>::Decryption decryption((byte*)key.c_str(), key.length());
CryptoPP::StringSource decryptor(str_in, true,
new CryptoPP::Base64Decoder(
new CryptoPP::StreamTransformationFilter(decryption,
new CryptoPP::StringSink(str_out)
)
)
);
return str_out;
}
void MainWindow::onServerConnected()
{
ui->statusbar->showMessage("Подключен");
ui->connectButton->setEnabled(false);
ui->disconnectButton->setEnabled(true);
authDialog_ = new AuthDialog();
connect(authDialog_, &AuthDialog::send, this, &MainWindow::checkUser);
connect(this, &MainWindow::success, authDialog_, &AuthDialog::yspex);
connect(this, &MainWindow::tryAgain, authDialog_, &AuthDialog::neydacha);
connect(authDialog_, &AuthDialog::changeAuthStatus, this, &MainWindow::change_status);
ui->centralwidget->setVisible(false);
authDialog_->exec();
if (auth_status == false)
qApp->exit();
ui->centralwidget->setVisible(true);
timer = new QTimer(this);
connect(timer, &QTimer::timeout, this, &MainWindow::updateParam);
timer->start(5000);
QJsonObject cmd;
QJsonDocument doc;
cmd["command"] = "takeStdParam";
doc.setObject(cmd);
ui->getFormatTime->setEnabled(true);
ui->getTime->setEnabled(true);
// _sleep(4900);
sendCommand(doc);
}
void MainWindow::onServerDisconnected()
{
ui->statusbar->showMessage("Отключен");
ui->connectButton->setEnabled(true);
ui->disconnectButton->setEnabled(false);
timer->stop();
delete authDialog_;
}
void MainWindow::onServerReadData()
{
QString message = m_tcpStream.readAll();
try {
QString rty = QString::fromStdString(decrypt(message.toStdString(),"1357924680753951"));
ui->serverMessages->addItem(rty.trimmed());
QJsonDocument doc = QJsonDocument::fromJson(rty.toUtf8());
if (doc.isObject()) {
QJsonObject obj = doc.object();
if (obj.contains("answer")) {
dispatchCommand(obj);
}
else
ui->serverMessages->addItem("Ошибка JSON");
}
else
ui->serverMessages->addItem("Ошибка JSON");
} catch (const CryptoPP::Exception &error)
{
QMessageBox::critical(this, "Ошибка", "Ошибка шифрования: " + QString(error.what()));
ui->serverMessages->addItem("Ошибка шифрования: " + QString(error.what()));
}
}
void MainWindow::checkUser(QAuthenticator &tmp)
{
QJsonDocument doc;
QJsonObject command;
command["command"] = "userAuth";
command["password"] = tmp.password();
command["login"] = tmp.user();
doc.setObject(command);
sendCommand(doc);
}
/*
* { "command": "getTime" }
*/
void MainWindow::on_getTime_clicked()
{
QJsonDocument doc;
QJsonObject command;
command["command"] = "getTime";
doc.setObject(command);
sendCommand(doc);
}
void MainWindow::dispatchCommand(QJsonObject &json_cmd)
{
QJsonValue val = json_cmd["answer"];
if (val.isString()) {
QString cmd = val.toString();
ui->serverMessages->addItem("answer: " + cmd);
if (cmd == "getTime") {
// отправка текущего времени
answer_getTime(json_cmd);
}
else if (cmd == "getFormatTime") {
answer_getTime(json_cmd);
}
else if (cmd == "takeStdParam") {
answer_takeStdParam(json_cmd);
}
else if (cmd == "updateParam") {
answer_updateParam(json_cmd);
}
else if (cmd == "userAuth") {
answer_userAuth(json_cmd);
}
else {
ui->serverMessages->addItem("Неизвестная команда");
}
}
else
ui->serverMessages->addItem("Ошибка JSON");
}
void MainWindow::answer_getTime(QJsonObject &json_cmd)
{
if (json_cmd.contains("data")) {
QJsonValue val = json_cmd["data"];
if (val.isString()) {
QString time = val.toString();
QMessageBox::information(this, "Время на сервере", time);
}
else
ui->serverMessages->addItem("Ошибка JSON");
}
else
ui->serverMessages->addItem("Ошибка JSON");
}
void MainWindow::answer_takeStdParam(QJsonObject &json_cmd)
{
if (json_cmd.contains("result")) {
QJsonValue val = json_cmd.value("result");
if (val.isArray()) {
StdParam = val.toArray();
ui->serverMessages->addItem("эталонные параметры получены успешно");
int n = StdParam.size();
ui->tableWidget->setRowCount(n);
for (int i = 0; i < n; i++){
QJsonObject r = StdParam.at(i).toObject();
QString key = r.keys().at(0);
QString values = r.value(key).toString();
ui->tableWidget->setItem(i, 0, new QTableWidgetItem(key));
ui->tableWidget->setItem(i, 1, new QTableWidgetItem(values));
}
}
else
ui->serverMessages->addItem("Ошибка JSON");
}
else
ui->serverMessages->addItem("Ошибка JSON");
}
void MainWindow::answer_updateParam(QJsonObject &json_cmd)
{
if (json_cmd.contains("params"))
{
QJsonValue val = json_cmd.value("params");
UpdParam = val.toArray();
int n = UpdParam.size();
ui->tableWidget_2->setRowCount(n);
for (int i = 0; i < n; i++){
QJsonObject r = UpdParam.at(i).toObject();
QString key = r.keys().at(0);
QString values = r.value(key).toString();
ui->tableWidget_2->setItem(i, 0, new QTableWidgetItem(key));
ui->tableWidget_2->setItem(i, 1, new QTableWidgetItem(values));
}
}
ui->tableWidget_2->resizeColumnsToContents();
ui->compareButton->setEnabled(true);
ui->pushButton_2->setEnabled(true);
}
void MainWindow::answer_userAuth(QJsonObject &json_cmd)
{
if (json_cmd.value("result") == 1)
success();
else
tryAgain();
}
void MainWindow::change_status()
{
auth_status = true;
}
void MainWindow::sendCommand(QJsonDocument &json_cmd)
{
QString msg(json_cmd.toJson());
ui->serverMessages->addItem(msg);
if (m_serverConnection->isWritable()){
QString rty = QString::fromStdString(encrypt(msg.toStdString(),"1357924680753951"));
m_tcpStream << rty << flush;
}
}
/*
* { "command": "getFormatTime",
* "params": {
* "timeFormat": "hh:mm:ss"
* }
* }
*/
void MainWindow::on_getFormatTime_clicked()
{
QJsonDocument doc;
QJsonObject command;
command["command"] = "getFormatTime";
QJsonObject params;
params["timeFormat"] = ui->timeFormat->text();
command["params"] = params;
doc.setObject(command);
sendCommand(doc);
}
/*
* { "command": "updateParam"
* }
*/
void MainWindow::updateParam()
{
QJsonObject command;
QJsonDocument doc;
command["command"] = "updateParam";
doc.setObject(command);
sendCommand(doc);
}
QStringList find_mismatches(const QJsonArray& std_arr, const QJsonArray& upd_arr) {
QStringList miss;
QSet<QString> std_keys_set, upd_keys_set, temp;
for (auto tmp : std_arr) {
QJsonObject temp = tmp.toObject();
QString key = temp.keys().at(0);
std_keys_set.insert(key);
}
for (auto tmp : upd_arr) {
QJsonObject temp = tmp.toObject();
QString key = temp.keys().at(0);
upd_keys_set.insert(key);
}
temp = std_keys_set;
temp.subtract(upd_keys_set);
miss.append(temp.toList());
temp = upd_keys_set;
temp.subtract(std_keys_set);
miss.append(temp.toList());
return miss;
}
void MainWindow::on_compareButton_clicked()
{
QStringList final;
QAxObject *word = new QAxObject("Word.Application", this);
QAxObject *documents = word->querySubObject("Documents");
QAxObject *myDocuments = documents->querySubObject("Add()");
QAxObject *range = myDocuments->querySubObject("Range()");
QMap<QString, QString> std_map, upd_map;
for (auto temp : StdParam) {
QJsonObject obj = temp.toObject();
QString key = obj.keys().first();
QString val = obj.value(key).toString();
std_map[key] = val;
}
for (auto temp : UpdParam) {
QJsonObject obj = temp.toObject();
QString key = obj.keys().first();
QString val = obj.value(key).toString();
upd_map[key] = val;
}
for (auto key : std_map.keys()) {
if (upd_map.contains(key)) {
if (std_map[key]!= upd_map[key])
final.append("Найдено несоответствие: значение переменной под именем " + key + " было изменено\n");
}
}
QStringList mismatches = find_mismatches(StdParam, UpdParam);
for(auto tmp: mismatches)
{
final.append("Найдено несоответствие: переменная под именем '" + tmp + "' была добавлена/удалена \n");
}
if (!list_param.value("root").toObject().contains(ui->ipAddr->text())){
QString tmp;
for (QString line: final) {
line.resize(line.size() - 2);
tmp.append(line + ";");
}
QJsonObject miss, times, comp;
QJsonArray temp_arr, final_arr;
times["times"] = final.size();
miss["mismatches"] = tmp;
temp_arr.append(times);
temp_arr.append(miss);
comp[ui->ipAddr->text()] = temp_arr;
final_arr.append(comp);
list_param.insert("root", final_arr);
}
QJsonDocument temp_doc(list_param);
QFile file(json_path);
if (file.open(QFile::Append)) {
file.write(temp_doc.toJson());
file.close();
}
for (QString line: final) {
range->dynamicCall("InsertAfter(Text)", line);
line.resize(line.size() - 2);
QString str = line;
}
QString str = QFileDialog::getOpenFileName(0, "Выберите файл для сохранения отчёта", "", "*");
myDocuments->dynamicCall("SaveAs(Text)", str);
myDocuments->dynamicCall("Close()");
word->dynamicCall("Quit()");
ui->pushButton->setEnabled(true);
}
void MainWindow::exit_app()
{
this->destroy();
}
void AuthDialog::checkCredentials()
{
QAuthenticator authenticator;
authenticator.setUser(usernameEdit->text());
authenticator.setPassword(passwordEdit->text());
if (authenticator.user() == "")
QMessageBox::warning(0, "Ошибка авторизации", "Введите логин");
if (authenticator.password() == "")
QMessageBox::warning(0, "Ошибка авторизации", "Введите пароль");
if (authenticator.user() != "" && authenticator.password() != "")
{
send(authenticator);
}
}
void AuthDialog::yspex()
{
QMessageBox::information(0, "Успех", "Вход выполнен");
changeAuthStatus();
accept();
}
void AuthDialog::neydacha()
{
try_times--;
QString end_of_message;
if (try_times == 5)
end_of_message = " попыток";
if (try_times < 5 && try_times > 1)
end_of_message = " попытки";
if (try_times == 1)
end_of_message = " попытка";
if (try_times != 0) {
QMessageBox::warning(0, "Ошибка авторизации", "Логин или пароль не совпадают.\n Осталось " + QString::number(try_times) + end_of_message);
}
if (try_times == 0){
QMessageBox::critical(0, "Отказано в доступе", "Превышено количество попыток входа");
qApp->exit();
}
}
void MainWindow::on_pushButton_clicked()
{
QFile file(json_path);
QJsonObject zxc;
QJsonArray json_arr;
QJsonDocument json_doc;
if (file.open(QFile::ReadOnly)) {
QByteArray qwerty = file.readAll();
json_doc = QJsonDocument::fromJson(qwerty);
QJsonObject tmp = json_doc.object();
json_arr = tmp.value("root").toArray();
}
int max = json_arr.at(0).toObject().value("times").toInt();
QString ans = json_arr.at(0).toObject().begin().key();
for (auto temp: json_arr)
{
QJsonObject jobj = temp.toObject();
if (jobj.value("times").toInt() > max)
{
max = jobj.value("times").toInt();
ans = jobj.begin().key();
}
}
QMessageBox::information(0, "Результат", "ip-адрес клмпьютера с наибольшим количеством несоответствий:\n" + ans);
}
void MainWindow::on_pushButton_2_clicked()
{
bool flag = false;
for (auto temp : UpdParam)
{
QJsonObject obj = temp.toObject();
if (obj.begin().key() == ui->lineEdit->text())
{
QMessageBox::information(0, "Результат", "переменная под именем " + ui->lineEdit->text() + " со значением " + obj.value(ui->lineEdit->text()).toString() + " была найдена среди текущих переменных");
flag = true;
}
}
if (flag == false)
QMessageBox::information(0, "Результат", "переменная под именем " + ui->lineEdit->text() + " не найдена среди текущих переменных");
flag = false;
for (auto temp : StdParam)
{
QJsonObject obj = temp.toObject();
if (obj.begin().key() == ui->lineEdit->text())
{
QMessageBox::information(0, "Результат", "переменная под именем " + ui->lineEdit->text() + " со значением " + obj.value(ui->lineEdit->text()).toString() + " была найдена среди эталонных переменных");
flag = true;
}
}
if (flag == false)
QMessageBox::information(0, "Результат", "переменная под именем " + ui->lineEdit->text() + " не найдена среди эталонных переменных");
}
Я начинающий программист и время от времени код работает не совсем корректно, выдавая различные ошибки. Например, ошибка, которая возникает всегда - после 3-4 нажатий на кнопки "Время на сервере" и "Время в формате" возникает ошибка Ошибка шифрования: StreamTransformationFilter: invalid PKCS #7 block padding found. Помогите, пожалуйста, скорректировать код таким образом, чтобы он стал более стабильным. Скрин формы клиента прилагаю.