//异或计算加密
QByteArray CommWithPCLicense::getEncryptDecryptByte(const QByteArray &str, const char &key)
{
QByteArray bytes = str;
for(int i=0; i<bytes.size(); i++)
{
bytes[i] = bytes[i] ^ key;
}
return bytes;
}
//保存Xml
void SaveXml(const Struct mTime &time)
{
QFile fileDecrypt(DECRYPT_FILE_PATH);
QDomDocument doc;
//写入xml头部
QDomProcessingInstruction instruction; //添加处理命令
instruction=doc.createProcessingInstruction("xml","version=\"1.0\" encoding=\"UTF-8\"");
doc.appendChild(instruction);
//添加根节点
QDomElement root=doc.createElement("root");
//添加属性
root.setAttribute("year", time.year);//方式一:创建属性 其中键值对的值可以是各种类型
root.setAttribute("mounth", time.mounth);
root.setAttribute("day", time.day);
root.setAttribute("type", time.type);
QDomAttr reserved=doc.createAttribute("reserved"); //方式二:创建属性 值必须是字符串
reserved.setValue("00773516");
root.setAttributeNode(reserved);
doc.appendChild(root);
//加密
QByteArray byteArray = doc.toByteArray().toBase64();
//加入特殊字符,解密的时候必须按规则解密,否则就算知道Base64加密的也无法解密.
byteArray = byteArray.insert(10, "test");
byteArray = getEncryptDecryptByte(byteArray, 'm');//异或进行加密
if(!fileDecrypt.open(QIODevice::WriteOnly | QIODevice::Text))
{
std::cerr << " Cannot open file " << qPrintable(DECRYPT_FILE_PATH)
<< ": " << qPrintable(fileDecrypt.errorString())
<< std::endl;
return ;//文件打开失败
}
fileDecrypt.write(byteArray);
//关闭文件
fileDecrypt.flush();
fileDecrypt.close();
}
//读取xml
struct mTime ReadLicense()
{
QString filePath(DECRYPT_FILE_PATH);
struct mTime time;
QFile file(filePath);
if(!file.exists())
{
std::cerr << "Error: Read file not exist " << std::endl;
return time;
}
if (!file.open(QFile::ReadWrite | QFile::Text))
{
std::cerr << "Error: Open file fail" << qPrintable(filePath)
<< ": " << qPrintable(file.errorString())
<< std::endl;
file.close();
return time;
}
QString errorStr;
int errorLine;
int errorColumn;
QDomDocument doc;
QByteArray byteArray = file.readAll();
byteArray = getEncryptDecryptByte(byteArray, 'm');//异或解密
byteArray = byteArray.remove(10, 4);//按加密规则解密
byteArray = QByteArray::fromBase64(byteArray);
if (!doc.setContent(byteArray, false, &errorStr, &errorLine, &errorColumn))
{
std::cerr << "Error: Parse error at line " << errorLine << ", "
<< "column " << errorColumn << ": "
<< qPrintable(errorStr) << std::endl;
file.close();
return time;
}
file.close();
QDomElement root = doc.documentElement();
bool tmpBool;
time.year = root.attribute("year").toInt(&tmpBool, 10);
time.mounth = root.attribute("mounth").toInt(&tmpBool, 10);
time.day = root.attribute("day").toInt(&tmpBool, 10);
qDebug()<<QString(" Y%1 M%2 D%3 ")
.arg(readLicenseInfo.licenseInfo.year)
.arg(readLicenseInfo.licenseInfo.mounth)
.arg(readLicenseInfo.licenseInfo.day);
return time;
}