ccacic.cpp
10.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#include "ccacic.h"
CCacic::CCacic()
{
}
/* getValueFromFile
* Pega valor específico dentro de um arquivo
* @parameter QString sectionName: nome da seção onde estará a key)
* @parameter QString keyName: nome da key que está o valor)
* @parameter QString filePath: caminho do arquivo que será aberto;
*
* @return QString: "" (vazio) Caso não encontre,
* "0" caso não seja possível abrir o arquivo;
*/
QString CCacic::getValueFromFile(QString sectionName, QString keyName, QString filePath)
{
QFile file(filePath);
QString line = "";
sectionName = "[" + sectionName + "]";
keyName = keyName + "=";
int sizeKeyName = keyName.size();
if (!file.open(QIODevice::ReadOnly | QIODevice::Text))
return "0";
while (!file.atEnd()){
line = file.readLine();
if (line.contains(sectionName, Qt::CaseInsensitive)) {
do {
line = file.readLine();
if (line.contains(keyName, Qt::CaseInsensitive)) {
file.close();
return line.mid(sizeKeyName).trimmed();
}
} while (!file.atEnd());
}
}
file.close();
return "";
}
/*getValueFromTags
* @parameter QString sectionName: Grupo onde está a chave;
* @parameter QString keyName: chave que queremos para colocar o valor;
* @parameter QString value: valor para colocar dentro da chave;
* @parameter QString filePath: Local do arquivo;
*/
void CCacic::setValueToFile(QString sectionName, QString keyName, QString value, QString filePath)
{
QSettings settings(filePath, QSettings::IniFormat);
settings.beginGroup(sectionName);
settings.setValue(keyName, value);
settings.endGroup();
}
/*getValueFromTags
* @parameter QString fullString: string onde será pesquisado o valor desejado;
* @parameter QString tag: nome da tag onde estará o valor;
* @parameter QString tagType: padrão "[]", tipo da tag;
*
* @return: QString: valor entre as tags.
*/
QString CCacic::getValueFromTags(QString fullString, QString tag, QString tagType) {
QString tagFim = tagType.mid(0,1) + "/" + tag + tagType.mid(1);
int tagSize;
tag = tagType.mid(0,1) + tag + tagType.mid(1);
tagSize = tag.size();
return fullString.mid(fullString.indexOf(tag) + tagSize,
fullString.indexOf(tagFim) -
(fullString.indexOf(tag) + tagSize)).trimmed();
}
/*createFolder
* @parameter QString path: caminho onde será criado o diretório, sendo criado toda a árvore se necessário.
* @return bool: true se conseguir ou já existir, false se não.
*/
bool CCacic::createFolder(QString path)
{
QDir folder(path);
return folder.mkpath(path);
}
/*deleteFolder
* @parameter QString path: caminho do diretório;
* @return bool: true se conseguir ou já não existir, false se não conseguir.
*/
bool CCacic::deleteFolder(QString path)
{
QDir folder(path);
if (folder.exists())
return folder.removeRecursively();
else
return true;
}
/*deleteFile
* @parameter QString path: caminho do arquivo;
* @return bool: true se conseguir ou já não existir, false se não conseguir.
*/
bool CCacic::deleteFile(QString path)
{
QFile file(path);
if (file.exists())
return file.remove(path);
else
return true;
}
/*jsonValueFromJsonString
* Pega valor da chave desejada em um json em string;
* @parameter QString json: json onde será feita a busca;
* @parameter QString key: chave onde será pego o json;
* @return QJsonValue: valor solicitado;
*/
QJsonValue CCacic::jsonValueFromJsonString(QString json, QString key)
{
return QJsonDocument::fromJson(json.toUtf8()).object()[key];
}
/*setJsonToFile
* Grava json em um arquivo.
* IMPORTANTE: não parei pra olhar a fundo, mas a princípio é necessário ler o arquivo
* para pegar o json das informações anteriores, senão informações serão duplicadas ou
* excluidas;
* @parameter QJsonObject json: json que será gravado
* @parameter QString filepath: caminho do arquivo onde será gravado
*
*/
bool CCacic::setJsonToFile(QJsonObject json, QString filepath)
{
QFile configFile(filepath);
if (!configFile.open(QIODevice::WriteOnly)){
return false;
}
QJsonDocument docJson(json);
return (configFile.write(docJson.toJson()) != -1);
}
/*getJsonFromFile
* Carrega json de um arquivo.
* @return QJsonObject: json que será recuperado
* @parameter QString filepath: caminho do arquivo onde será recuperado
*/
QJsonObject CCacic::getJsonFromFile(QString filepath)
{
QFile configFile(filepath);
QJsonObject json;
if (!configFile.open(QIODevice::ReadOnly)){
return json;
}
json = QJsonDocument::fromJson(configFile.readAll()).object();
return json;
}
/*enCrypt
* @parameter std::string str_in: string que será encriptada (url).
* std::string key: chave utilizada na encriptação (32 caracteres) 32*8 = 256 bits
* *exemplo: qwertyuiopasdfghjklzxcvbnmqwerty
* std::string iv: IV (Vetor de Inicialização) deve ser aleatório.
* (http://pt.wikipedia.org/wiki/Modo_de_opera%C3%A7%C3%A3o_%28criptografia%29#Vetor_de_inicializa.C3.A7.C3.A3o_.28IV.29)
* exemplo de iv: 0123456789123456
* @return std:string: retorna a string encriptada convertida em base64.
* */
QString CCacic::enCrypt(std::string str_in, std::string iv) {
std::string str_out;
if ((!this->getChaveCrypt().isNull())){
std::string key = (!this->getChaveCrypt().isNull()) ? this->getChaveCrypt().toStdString() : "";
CryptoPP::CFB_Mode<CryptoPP::AES>::Encryption encryption((byte*)key.c_str(), key.length(), (byte*)iv.c_str());
CryptoPP::StringSource encryptor(str_in, true,
new CryptoPP::StreamTransformationFilter(encryption,
new CryptoPP::Base64Encoder(new CryptoPP::StringSink(str_out),
false // do not append a newline
)
)
);
}
// qDebug() << QString::fromStdString(str_out);
return QString::fromStdString(str_out);
}
/*deCrypt
// * @parameter std::string str_in: string encriptada convertida em base64.
// * std::string key: chave utilizada na encriptação (32 caracteres) 32*8 = 256 bits
// * *exemplo: qwertyuiopasdfghjklzxcvbnmqwerty
// * std::string iv: IV (Vetor de Inicialização) deve ser aleatório.
// * *Um IV jamais deve ser utilizado mais de uma vez com a mesma chave.
// * *(http://pt.wikipedia.org/wiki/Modo_de_opera%C3%A7%C3%A3o_%28criptografia%29#Vetor_de_inicializa.C3.A7.C3.A3o_.28IV.29)
// * *exemplo de iv: 0123456789123456
// * @return QString: retorna a string desencriptada convertida em base64.
// * */
QString CCacic::deCrypt(std::string str_in, std::string iv) {
std::string str_out;
if ((!this->getChaveCrypt().isNull())){
std::string key = this->getChaveCrypt().toStdString();
CryptoPP::CFB_Mode<CryptoPP::AES>::Decryption decryption((byte*)key.c_str(), key.length(), (byte*)iv.c_str());
CryptoPP::StringSource decryptor(str_in, true,
new CryptoPP::Base64Decoder(
new CryptoPP::StreamTransformationFilter(decryption,
new CryptoPP::StringSink(str_out))
)
);
}
return QString::fromStdString(str_out);
}
bool CCacic::Md5IsEqual(QVariant document01,QVariant document02){
QString file1 = QString(QCryptographicHash::hash(
(document01.toByteArray()),QCryptographicHash::Md5).toHex());
QString file2 = QString(QCryptographicHash::hash(
(document02.toByteArray()),QCryptographicHash::Md5).toHex());
return file1 == file2;
}
bool CCacic::Md5IsEqual(QVariant document01,QString document02){
QString file1 = QString(QCryptographicHash::hash(
(document01.toByteArray()),QCryptographicHash::Md5).toHex());
QString file2 = document02;
return file1 == file2;
}
QString CCacic::startProcess(QString pathprogram, bool wait, bool *ok, QStringList arguments)
{
QProcess process;
arguments.empty() ? process.start(pathprogram) : process.start(pathprogram, arguments);
*ok = wait ? process.waitForFinished() : process.waitForStarted();
return process.errorString();
}
void CCacic::setValueToRegistry(QString organization, QString application, QVariantMap values)
{
QSettings registry(organization, application);
for (QVariantMap::const_iterator i = values.constBegin(); i != values.constEnd(); i++)
registry.setValue(i.key(), i.value());
registry.sync();
}
QVariant CCacic::getValueFromRegistry(QString organization, QString application, QString key)
{
QSettings registry(organization, application);
return registry.value(key);
}
void CCacic::removeRegistry(QString organization, QString application)
{
QSettings registry(organization, application);
registry.clear();
registry.sync();
}
/*Getters/Setters
* Begin:
*/
QString CCacic::getCacicMainFolder() const
{
return cacicMainFolder;
}
void CCacic::setCacicMainFolder(const QString &value)
{
cacicMainFolder = value;
}
QString CCacic::getMainModuleName() const
{
return mainModuleName;
}
void CCacic::setMainModuleName(const QString &value)
{
mainModuleName = value;
}
QString CCacic::getUrlGerente() const
{
return urlGerente;
}
void CCacic::setUrlGerente(const QString &value)
{
urlGerente = value;
}
QString CCacic::getGerColsInfFilePath() const
{
return gerColsInfFilePath;
}
void CCacic::setGerColsInfFilePath(const QString &value)
{
gerColsInfFilePath = value;
}
QString CCacic::getChksisInfFilePath() const
{
return chksisInfFilePath;
}
void CCacic::setChksisInfFilePath(const QString &value)
{
chksisInfFilePath = value;
}
QString CCacic::getChaveCrypt() const
{
return chaveCrypt;
}
void CCacic::setChaveCrypt(const QString &value)
{
chaveCrypt = value;
}
QString CCacic::convertDouble(const double &number, const int &precision)
{
std::ostringstream ss;
ss.precision(precision);
ss << std::fixed << number;
return QString::fromStdString(ss.str());
}
std::string CCacic::genRandomString(const int &len)
{
char* s;
static const char alphanum[] =
"0123456789"
"ABCDEFGHIJKLMNOPQRSTUVWXYZ"
"abcdefghijklmnopqrstuvwxyz";
for (int i = 0; i < len; ++i) {
s[i] = alphanum[rand() % (sizeof(alphanum) - 1)];
}
s[len] = 0;
return std::string(s);
}
/*Getters/Setters
* End.
*/