QT为软件添加密匙

一、

1、添加运行截止时间点;

2、添加软件持续运行时间段;

3、限制软件最大运行设备数量:软件每当在设备上运行时,读取设备的CPU序列号,重新写回密匙文件。密匙文件中CPU序列号的个数不能超过允许运行的设备个数。

二、

(1)生成密匙:

#include "keywidget.h"
#include "ui_keywidget.h"
#include 
#include 
#include 

KeyWidget::KeyWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::KeyWidget)
{
    ui->setupUi(this);

    //初始化QCombox,dateEdit等控件的值,供用户选择
    initForm();

    //生成密匙按钮槽函数
    connect(ui->btnOk, &QPushButton::clicked, this, [=](){
        bool useDate = ui->ckDate->isChecked();
        bool useRun = ui->ckRun->isChecked();
        bool useCount = ui->ckCount->isChecked();

        if (!useDate && !useRun && !useCount) {
            QMessageBox::critical(this, "警告", "没有添加限制条件,生成密匙失败!");
            return;
        }

        QString strDate = ui->dateEdit->date().toString("yyyy-MM-dd");
        QString strRun = ui->cboxMin->currentText();
        QString strCount = ui->cboxCount->currentText();
        QString key = QString("%1|%2|%3|%4|%5|%6").arg(useDate).arg(strDate).arg(useRun).arg(strRun).arg(useCount).arg(strCount);

        QFile file(QApplication::applicationDirPath() + "/key.db");
        file.open(QFile::WriteOnly | QIODevice::Text);
        file.write(getXorEncryptDecrypt(key, 110).toLatin1());
        file.close();
        QMessageBox::information(this, "提示", "生成密钥成功,将 key.db 文件拷贝到对应目录即可!");
    });

    //关闭按钮槽函数
    connect(ui->btnClose, &QPushButton::clicked, this, [=](){
        close();
    });
}

KeyWidget::~KeyWidget()
{
    delete ui;
}

void KeyWidget::initForm()
{
    QStringList min;
    min << "1" << "5" << "10" << "20" << "30";
    for (int i = 1; i <= 24; i++) {
        min << QString::number(i * 60);
    }

    ui->cboxMin->addItems(min);
    ui->cboxMin->setCurrentIndex(1);
    ui->dateEdit->setDate(QDate::currentDate());

    for (int i = 5; i <= 150; i = i + 5) {
        ui->cboxCount->addItem(QString("%1").arg(i));
    }
}

//采用异或加密
QString KeyWidget::getXorEncryptDecrypt(const QString &data, char key)
{
    qDebug() << key;
    QByteArray buffer = data.toLatin1();
    int size = buffer.size();
    for (int i = 0; i < size; i++) {
        buffer[i] = buffer.at(i) ^ key;
    }

    return QLatin1String(buffer);
}



 

QT为软件添加密匙_第1张图片

(2)使用密匙举例:

#ifndef KEYCHECK_H
#define KEYCHECK_H

#include 
#include 
#include 
#include 

class KeyCheck : public QObject
{
    Q_OBJECT

public:
    explicit KeyCheck(QObject *parent = nullptr);

    //密匙检查类单例对象
    static KeyCheck *Instance();
    static KeyCheck *self;

    QString keyData;            //注册码密文
    bool keyUseDate;            //是否启用运行日期时间限制
    QString keyDate;            //到期时间字符串
    bool keyUseRun;             //是否启用可运行时间限制
    int keyRun;                 //可运行时间
    bool keyUseCount;           //是否启用设备数量限制
    int keyCount;               //设备限制数量
    QStringList keyCpuID;       //读出的CPU序列号

    QTimer *timer;              //定时器判断是否运行超时
    QDateTime startTime;        //程序启动时间

private:
    QString getWMIC(const QString &cmd);
    QString getCpuName();
    QString getCpuId();        //读取CPU序列号
    QString getDiskNum();      //读取硬盘序列号

private slots:
    void checkTime();
    QString getXorEncryptDecrypt(const QString &data, char key);
public slots:
    void start();
    void stop();
    bool checkCount(int count);

signals:

public slots:
};

#endif // KEYCHECK_H
#include "keycheck.h"
#include 
#include 
#include 
#include 
#include 

KeyCheck *KeyCheck::self = nullptr;
KeyCheck *KeyCheck::Instance()
{
    if (!self) {
        QMutex mutex;
        QMutexLocker locker(&mutex);
        if (!self) {
            self = new KeyCheck;
        }
    }

    return self;
}

KeyCheck::KeyCheck(QObject *parent) : QObject(parent)
{
    keyData = "";
    keyUseDate = false;
    keyDate = "2017-01-01";
    keyUseRun = false;
    keyRun = 1;
    keyUseCount = false;
    keyCount = 10;

    timer = new QTimer(this);
    timer->setInterval(1000);
    connect(timer, SIGNAL(timeout()), this, SLOT(checkTime()));

    //记录软件开始运行时间
    startTime = QDateTime::currentDateTime();
}

void KeyCheck::checkTime()
{
    QDateTime now = QDateTime::currentDateTime();
    if (startTime.secsTo(now) >= (keyRun * 60)) {
        QMessageBox::critical(nullptr, "错误", "试运行时间已到,请联系供应商更新注册码!");
        stop();
        exit(0);
    }
}

QString KeyCheck::getXorEncryptDecrypt(const QString &data, char key)
{
    QByteArray buffer = data.toLatin1();
    int size = buffer.size();
    for (int i = 0; i < size; i++) {
        buffer[i] = buffer.at(i) ^ key;
    }

    return QLatin1String(buffer);
}

//读取密匙进行时间判断
void KeyCheck::start()
{
    QString keyName = qApp->applicationDirPath() + "/key.db";
    QFile keyFile(keyName);
    if (!keyFile.exists() || keyFile.size() == 0) {
        QMessageBox::critical(nullptr, "错误", "密钥文件丢失,请联系供应商!");
        exit(0);
    }

    keyFile.open(QFile::ReadOnly);
    keyData = keyFile.readLine();
    keyFile.close();

    //将从注册码文件中的密文解密,与当前时间比较是否到期
    keyData = getXorEncryptDecrypt(keyData, 110);
    QStringList data = keyData.split("|");

    if (data.count() < 6 || data.count() > 6 + data.at(5).toInt()) {
        QMessageBox::critical(nullptr, "错误", "注册码文件已损坏,程序将自动关闭!");
        exit(0);
    }

    keyUseDate = (data.at(0) == "1" ? true : false);
    keyDate = data.at(1);
    keyUseRun = (data.at(2) == "1" ? true : false);
    keyRun = data.at(3).toInt();
    keyUseCount = (data.at(4) == "1" ? true : false);
    keyCount = data.at(5).toInt();

    //读取密匙中保存的cpu序列号,开始时密匙中是没有序列号的
    if(data.count() > 6)
    {
        for(int i = 6;i < data.count();++i)
        {
            keyCpuID << data.at(i);
            qDebug() << data.at(i);
        }
    }

    qDebug() << keyDate << keyRun << keyCount;

    if (keyUseDate) {
        QString nowDate = QDate::currentDate().toString("yyyy-MM-dd");
        if (nowDate > keyDate) {
            QMessageBox::critical(nullptr, "错误", "软件已到期,请联系供应商更新注册码!");
            exit(0);
        }
    }

    //如果启用了运行时间显示
    if (keyUseRun) {
        timer->start();
    }

    //运行个数限制
    if(false == checkCount(1))
    {
        QMessageBox::critical(nullptr, "错误", "当前设备已经达到最大,请联系供应商更新注册码!");
        exit(0);
    }
}

void KeyCheck::stop()
{
    timer->stop();
}

bool KeyCheck::checkCount(int count)
{
    Q_UNUSED(count)

    //本机CPU序列号
    QString strCpuID = getCpuId();

    //如果cpu序列号列表中没有包含当前电脑cpu,加入
    if(!keyCpuID.contains(strCpuID, Qt::CaseInsensitive))
    {
        keyCpuID << strCpuID;

        if(keyCpuID.size() > keyCount)
            return false;

        QString key = QString("%1|%2|%3|%4|%5|%6").arg(keyUseDate).arg(keyDate).arg(keyUseRun).arg(keyRun).arg(keyUseCount).arg(keyCount);
        for(int i = 0;i < keyCpuID.size(); ++i)
        {
            key += QString("|%1").arg(keyCpuID.at(i));
        }

        qDebug() << key;

        QFile file(qApp->applicationDirPath() + "/key.db");
        file.open(QFile::WriteOnly | QIODevice::Text);
        file.write(getXorEncryptDecrypt(key, 110).toLatin1());
        file.close();
    }

    return true;
}

QString KeyCheck::getWMIC(const QString &cmd)
{
    //获取cpu名称:wmic cpu get Name
    //获取cpu核心数:wmic cpu get NumberOfCores
    //获取cpu线程数:wmic cpu get NumberOfLogicalProcessors
    //查询cpu序列号:wmic cpu get processorid
    //查询主板序列号:wmic baseboard get serialnumber
    //查询BIOS序列号:wmic bios get serialnumber
    //查看硬盘:wmic diskdrive get serialnumber
    QProcess p;
    p.start(cmd);
    p.waitForFinished();
    QString result = QString::fromLocal8Bit(p.readAllStandardOutput());
    QStringList list = cmd.split(" ");
    result = result.remove(list.last(), Qt::CaseInsensitive);
    result = result.replace("\r", "");
    result = result.replace("\n", "");
    result = result.simplified();

    return result;
}

QString KeyCheck::getCpuName()
{
    return getWMIC("wmic cpu get name");
}

QString KeyCheck::getCpuId()
{
    return getWMIC("wmic cpu get processorid");
}

QString KeyCheck::getDiskNum()
{
    return getWMIC("wmic diskdrive where index=0 get serialnumber");
}

#include "usemykeywidget.h"
#include "keycheck.h"

#include 

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);

    //检查密匙
    KeyCheck::Instance()->start();

    UseMyKeyWidget w;
    w.show();
    return a.exec();
}

QT为软件添加密匙_第2张图片

QT为软件添加密匙_第3张图片

你可能感兴趣的:(QT)