簡體   English   中英

Google C ++代碼示例解釋,轉換為C#

[英]Google C++ code example explanation, translating to C#

我正在使用Google DoubleClick廣告交易平台API。 他們的例子都是用C ++編寫的,我在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類? 如果我對此了解得更多,我可能會更好地了解正在發生的事情。

該塊的等效C#代碼是:

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

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

HMAC功能實際上是OpenSSL的一個宏

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM