繁体   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