Google C ++代码示例解释,转换为C#

时间:2014-02-14 02:19:29

标签: c# c++

我正在使用Google DoubleClick广告交易平台API。他们的例子都是用C ++编写的,我在C ++上非常糟糕。我正在尝试将此转换为C#以用于我正在处理的事情,而且我认为我只需要解释某些this代码示例块中实际发生的事情。老实说,我知道应该发生什么,但我不确定我是否正确“加密/解密”并没有“正确”。

这是其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 个答案:

答案 0 :(得分:2)

该块的等效C#代码是:

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

它使用给定的加密密钥计算初始化向量(IV)的SHA1 HMAC。

HMAC函数实际上是a macro from OpenSSL

正如评论一样,我认为从伪代码描述而不是从他们的C ++代码实现它会更容易。