53 lines
1.4 KiB
C++
53 lines
1.4 KiB
C++
#ifndef FILEENCRYPTOR_H
|
|
#define FILEENCRYPTOR_H
|
|
|
|
#include <QByteArray>
|
|
#include <QFile>
|
|
#include <QIODevice>
|
|
#include <QDebug>
|
|
|
|
class FileEncryptor {
|
|
public:
|
|
FileEncryptor(const QByteArray& key) : m_key(key) {}
|
|
|
|
// 加密或解密文件
|
|
bool encryptDecryptFile(const QString& inputFilePath, const QString& outputFilePath) {
|
|
// 读取文件内容
|
|
QFile inputFile(inputFilePath);
|
|
if (!inputFile.open(QIODevice::ReadOnly)) {
|
|
qWarning() << "无法打开文件:" << inputFilePath;
|
|
return false;
|
|
}
|
|
|
|
QByteArray fileData = inputFile.readAll();
|
|
inputFile.close();
|
|
|
|
// 对文件内容进行加解密
|
|
xorEncryptDecrypt(fileData);
|
|
|
|
// 写入加解密后的文件
|
|
QFile outputFile(outputFilePath);
|
|
if (!outputFile.open(QIODevice::WriteOnly)) {
|
|
qWarning() << "无法写入文件:" << outputFilePath;
|
|
return false;
|
|
}
|
|
|
|
outputFile.write(fileData);
|
|
outputFile.close();
|
|
return true;
|
|
}
|
|
|
|
private:
|
|
// XOR 加密/解密
|
|
void xorEncryptDecrypt(QByteArray& data) const {
|
|
int keyLength = m_key.size();
|
|
for (int i = 0; i < data.size(); ++i) {
|
|
data[i] ^= m_key[i % keyLength]; // 使用密钥与数据进行XOR操作
|
|
}
|
|
}
|
|
|
|
QByteArray m_key; // 用于加密/解密的密钥
|
|
};
|
|
|
|
#endif // FILEENCRYPTOR_H
|