我正在使用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類?如果我更瞭解這一點,我可能會更好地理解發生了什麼。
在某處會有一個名爲'HMAC'的函數/宏,它會告訴你這是幹什麼的。 –