QT对字符串简单加、解密

使用按位异或^进行加、解密:

加、解密都是使用该函数:

void EncryptionStr(QByteArray &data)
{
    static QByteArray key = "MY_KEY";
    for (int i = 0; i < data.size(); i++)
    {
        data[i] = data[i] ^ key[i % key.size()];
    }
}

发现该加密函数无法对中文进行加密,原因是含有中文每个字符在不同编码格式所占字节数不同。所以将该字符串转为宽字节(每个字符占两个字节),处理后在转换utf8(我的项目使用utf8字符编码).

QString EncryptionStr(QString str)
{
    std::wstring wString = str.toStdWString();
    static QByteArray key = "MY_KEY";
    for (int i = 0; i < wString.size(); i++)
    {
        wString[i] = wString[i] ^ key[i % key.size()];
    }
    return QString::fromStdWString(wString).toUtf8();
}

备注:此处加密key中的字符在加密相同的字符时会产生异常,比如用key="MY_KEY" 来加密MY_KEY加密过后的密文是为空的,因为在异或操作的时候,相同的值结果为0,所以加密过后密文是“\0”为字符串的结束符,导致加密异常。

解决方法:就是将key中字符串的值设置为明文中没有的字符,比如¥~等特殊字符。

### 实现 QT4 中的 XOR 字符串解密 XOR 密是一种简单密方式,其基本原理是对明文中的每一个字符与给定的密钥进行按位异或操作。由于 XOR 的特性 `(A ^ B) ^ B = A`,因此相同的函数可以用于密和解密。 #### 使用 C++ 和 Qt4 进行 XOR 密/解密 下面是一个基于 Qt4 的简单实现: ```cpp #include <QString> #include <QByteArray> class XOREncryption { public: static QByteArray xorEncryptDecrypt(const QString& input, const QString& key) { QByteArray output; int keyIndex = 0; for (int i = 0; i < input.length(); ++i) { QChar ch = input[i]; char encryptedChar = ch.toLatin1() ^ key[keyIndex].toLatin1(); output.append(encryptedChar); // 循环使用密钥 if (++keyIndex >= key.length()) { keyIndex = 0; } } return output; } }; ``` 此代码片段定义了一个 `xorEncryptDecrypt` 方法来处理输入字符串并返回经过 XOR 处理后的字节数组[^1]。 为了展示如何调用这个类成员函数,在主程序中添如下测试代码: ```cpp #include <iostream> using namespace std; // 假设已经包含了上面定义的 XOREncryption 类 void testEncryption() { QString originalText = "HelloWorld"; QString secretKey = "mySecret"; // 密过程 QByteArray encryptedData = XOREncryption::xorEncryptDecrypt(originalText, secretKey); cout << "Encrypted data: "; for (char c : encryptedData) { printf("%02x", c & 0xFF); // 输出十六进制表示形式 } cout << endl; // 解密过程(再次应用相同的操作) QString decryptedText = QString::fromLatin1(XOREncryption::xorEncryptDecrypt(QString::fromLatin1(encryptedData), secretKey)); cout << "Decrypted text: " << qPrintable(decryptedText) << endl; } ``` 这段代码展示了完整的密到解密的过程,并打印出中间的结果以便观察。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值