如何用Qt实现对Google API的应用(2)-- OAuth的各步骤实现

    技术2022-05-20  27

    为了使用OAuth验证流程成功的调用Google API,需要先获取OAuth Access Token

    在OAuth Access Token的获取过程中,我们需要依次解决以下几个问题:

    1.为获取Access Token准备TimeStamp,Nonce和HMAC-SHA1签名

     

    a. TimeStamp的获取方法:

    简单的使用QDateTime::currentMSecsSinceEpoch()/1000可以获得

     

    b. Nonce的获取算法:

     

    Nonce,是单次值的意思,就是说在每一次Request请求发出时的随机32位值,以保证操作是单次的,用于避免多次重复的请求式攻击

    其实在很多应用中都会用到Nonce,nonce等于Universally Unique Identifier的概念,所以这里可以使用Qt的QUuid生成随机的nonce值。因为QUuid生成的随机样式为{67C8770B-44F1-410A-AB9A-F9B5446F13EE},所以我们需要将其中的“{”,“}”和“-”符号去掉

     

    QString nonce = QUuid::createUuid().toString().remove(QRegExp("[{,},-]"));

     

    c. HMAC-SHA1签名算法:

     

    含密钥的安全哈希算法,为加密算法的一种,在第三方应用请求时使用

    下面给出实现代码,具体算法请Google

     

     

    QString OAuthUtil::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 "/" // ascii characters 0x36 ("6") and 0x5c ("/") 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(); }

     

    2. 各步骤的Signature生成方式

    a. Request Token时的Signature生成:

    使用consumer key和consumer secret的组合作为Key,与baseString进行签名

    第三方应用使用anonymous作为其consumer key和consumer secret,生成的Key为“anonymous&”

     

    b. Request Authorize Token时的Signature生成:

     

    c. Reques tAccess Token时的Signature生成:

     

    d. 使用Access Token时的Signature生成

    使用 consumer key和consumer secret和token_secret组合作为Key与baseString进行签名

    token_secret为申请Access Token前Authorize Token授权后获得的,需要先保存起来并在这里应用

    如:token_secret=x1qzR2SBgH8waTVHvHS6jYNg

          consumer key和consumer secret为anonymous,生成的Key为

          Key = anonymous&x1qzR2SBgH8waTVHvHS6jYNg

     


    最新回复(0)