2014-02-14 39 views
0

我正在使用Google DoubleClick廣告交易API。他們的例子都是用C++編寫的,我在C++中非常糟糕。我試圖將它轉換爲C#來處理我正在處理的內容,並且真的,我想我只需要解釋一下this代碼示例的某些塊中實際發生的情況。老實說,我知道應該發生什麼事,但我不確定我是否正確,並且加密/解密沒有「正確」。Google C++代碼示例說明,翻譯爲C#

這是從他們的API的網站上的完整的例子:

bool DecryptByteArray(
    const string& ciphertext, const string& encryption_key, 
    const string& integrity_key, string* cleartext) { 
    // Step 1. find the length of initialization vector and clear text. 
    const int cleartext_length = 
    ciphertext.size() - kInitializationVectorSize - kSignatureSize; 
    if (cleartext_length < 0) { 
    // The length can't be correct. 
    return false; 
    } 

    string iv(ciphertext, 0, kInitializationVectorSize); 

    // Step 2. recover clear text 
    cleartext->resize(cleartext_length, '\0'); 
    const char* ciphertext_begin = string_as_array(ciphertext) + iv.size(); 
    const char* const ciphertext_end = ciphertext_begin + cleartext->size(); 
    string::iterator cleartext_begin = cleartext->begin(); 

    bool add_iv_counter_byte = true; 
    while (ciphertext_begin < ciphertext_end) { 
    uint32 pad_size = kHashOutputSize; 
    uchar encryption_pad[kHashOutputSize]; 

    if (!HMAC(EVP_sha1(), string_as_array(encryption_key), 
       encryption_key.length(), (uchar*)string_as_array(iv), 
       iv.size(), encryption_pad, &pad_size)) { 
     printf("Error: encryption HMAC failed.\n"); 
     return false; 
    } 

    for (int i = 0; 
     i < kBlockSize && ciphertext_begin < ciphertext_end; 
     ++i, ++cleartext_begin, ++ciphertext_begin) { 
     *cleartext_begin = *ciphertext_begin^encryption_pad[i]; 
    } 

    if (!add_iv_counter_byte) { 
     char& last_byte = *iv.rbegin(); 
     ++last_byte; 
     if (last_byte == '\0') { 
     add_iv_counter_byte = true; 
     } 
    } 

    if (add_iv_counter_byte) { 
     add_iv_counter_byte = false; 
     iv.push_back('\0'); 
    } 
    } 

第1步是相當明顯的。這塊是我真的不知道如何解釋:

if (!HMAC(EVP_sha1(), string_as_array(encryption_key), 
      encryption_key.length(), (uchar*)string_as_array(iv), 
      iv.size(), encryption_pad, &pad_size)) { 
    printf("Error: encryption HMAC failed.\n"); 
    return false; 
} 

究竟發生了什麼,如果身體?在C#中看起來像什麼?有很多參數可以做SOMETHING,但在一個小地方看起來像是一堆可怕的東西。是否有一些stdlib HMAC類?如果我更瞭解這一點,我可能會更好地理解發生了什麼。

+1

在某處會有一個名爲'HMAC'的函數/宏,它會告訴你這是幹什麼的。 –

回答

2

該塊的等效C#代碼是:

using (var hmac = new HMACSHA1(encryption_key)) 
{ 
    var encryption_pad = hmac.ComputeHash(iv); 
} 

它計算所述初始化向量(IV)的SHA1 HMAC,使用給定的加密密鑰。

HMAC功能實際上是a macro from OpenSSL

就像一個評論,我認爲從他們的僞代碼描述而不是從他們的C++代碼實現它會更容易。

+0

絕對同意。我做了這個嘗試,但是我正在調試它,希望通過檢查C++代碼來獲得啓示。那是讓我很大程度上不確定是否有某種魔法對於不熟悉C++的人來說不明顯的一塊。我會看到這與我所擁有的相匹配。 – Rig