谷歌C++;代码示例说明,翻译为C#

谷歌C++;代码示例说明,翻译为C#,c#,c++,C#,C++,我正在使用Google DoubleClick广告交换API。他们的例子是C++,我在C++上的情况很糟糕。我正试图将其转换为C#以用于我正在研究的某些东西,实际上,我想我只需要对某些代码块示例中实际发生的情况进行一些解释。老实说,我知道应该发生什么,但我不确定我是否“正确”,加密/解密没有“某种正确” 这是他们API站点的完整示例: bool DecryptByteArray( const string& ciphertext, const string& encryp

我正在使用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');
    }
  }
如果身体里到底发生了什么?在C#中会是什么样子?有很多参数可以做一些事情,但似乎在一个小地方塞满了很多。是否有一些stdlib HMAC课程?如果我知道的更多,我可能会更好地理解发生了什么

该块的等效C#代码为:

using (var hmac = new HMACSHA1(encryption_key))
{
    var encryption_pad = hmac.ComputeHash(iv);
}
它使用给定的加密密钥计算初始化向量(IV)的SHA1 HMAC

HMAC
功能实际上是


作为一个注释,我认为从他们的伪代码描述而不是从C++代码中实现这一点更容易。

将有一个函数/宏称为代码> HMAC某些地方,它们将告诉你们这是在做什么。绝对同意。我已经尝试过了,但是我正在调试它,希望通过检查C++代码来获得启示。这是一个让我无法确定是否有一些魔术对于一个不流畅的C++的人来说是不明显的。我来看看这和我现有的如何匹配。
using (var hmac = new HMACSHA1(encryption_key))
{
    var encryption_pad = hmac.ComputeHash(iv);
}