QT HmacSHA1加密

最近在做onenet对接的时候要用qt去实现,看了一下官方文档,只有java相关文档,后面也是经过相关查询得出相关正确方法。

加密方法:

/**
 * @brief MainWindow::hmacSha1
 * @param key 加密key
 * @param baseString    加密内容
 * @return  返回加密结果
 */
QString MainWindow::hmacSha1(QByteArray key, QByteArray baseString)
{
    int blockSize = 64; // HMAC-SHA-1 block size, defined in SHA-1 standard
    if (key.length() > blockSize)
    { // if key is longer than block size (64), reduce key length with SHA-1 compression
        key = QCryptographicHash::hash(key, QCryptographicHash::Sha1);
    }

    QByteArray innerPadding(blockSize, char(0x36)); // initialize inner padding with char "6"
    QByteArray outerPadding(blockSize, char(0x5c)); // initialize outer padding with char "quot;
                                                    // ascii characters 0x36 ("6") and 0x5c ("quot;) are selected because they have large
                                                    // Hamming distance (http://en.wikipedia.org/wiki/Hamming_distance)

    for (int i = 0; i < key.length(); i++)
    {
        innerPadding[i] = innerPadding[i] ^ key.at(i); // XOR operation between every byte in key and innerpadding, of key length
        outerPadding[i] = outerPadding[i] ^ key.at(i); // XOR operation between every byte in key and outerpadding, of key length
    }

    // result = hash ( outerPadding CONCAT hash ( innerPadding CONCAT baseString ) ).toBase64
    QByteArray total = outerPadding;
    QByteArray part = innerPadding;
    part.append(baseString);
    total.append(QCryptographicHash::hash(part, QCryptographicHash::Sha1));
    QByteArray hashed = QCryptographicHash::hash(total, QCryptographicHash::Sha1);
    return hashed.toBase64();
}

测试加密:

    QString encryptText;
    encryptText.append(expirationTime);
    encryptText.append("\n");
    encryptText.append(signatureMethod);
    encryptText.append("\n");
    encryptText.append(resourceName);
    encryptText.append("\n");
    encryptText.append(version);
    QByteArray content = encryptText.toLatin1();
    QByteArray keyb = QByteArray::fromBase64(accessKey.toLatin1());
    QString sig = hmacSha1(keyb, content);

经过测试加密结果和java的加密结果一致

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值