2017-09-12 76 views
0

我跟着this example。我正在嘗試將我從服務器獲得的公鑰添加到密鑰對中,並且正在獲取STATUS_INVALID_PARAMETER。當我嘗試導入公鑰時,BCryptImportKeyPair返回STATUS_INVALID_PARAMETER

BCRYPT_DH_KEY_BLOB header; 
    header.dwMagic = BCRYPT_DH_PUBLIC_MAGIC; 
    header.cbKey = (ULONG)(pub_key.size()); 
    cout << "header contents " << header.dwMagic << " : " << header.cbKey << endl; 
    memcpy(&pubKeyBlobFromServer[0], &header, sizeof(BCRYPT_DH_KEY_BLOB)); 
    // copy Public key 
    cout << "size of pub_key " << pub_key.size() << endl; 
    cout << "size of pubKeyBlobFromServer before :" << pubKeyBlobFromServer.size() << endl; 
    cout << "size of BCRYPT_DH_KEY_BLOB " << sizeof(BCRYPT_DH_KEY_BLOB) << endl; 
    pubKeyBlobFromServer.insert(pubKeyBlobFromServer.end(), pub_key.begin(), pub_key.end()); 
    cout << "size of pubKeyBlobFromServer after :" << pubKeyBlobFromServer.size() << endl; 
    Status = BCryptImportKeyPair(
             ExchAlgHandleB,    // Alg handle 
             nullptr,      // Parameter not used 
             BCRYPT_DH_PUBLIC_BLOB,  // Blob type (Null terminated unicode string) 
             &PubKeyHandleB,    // Key handle that will be recieved 
             const_cast<PUCHAR>(pubKeyBlobFromServer.data()),   // Buffer than points to the key blob 
             (ULONG)pubKeyBlobFromServer.size(),  // Buffer length in bytes 
             0);       // Flags 

我收到以下輸出。

header contents 1112557636 : 128 
size of pub_key 128 
size of pubKeyBlobFromServer before :8 
size of BCRYPT_DH_KEY_BLOB 8 
size of pubKeyBlobFromServer after :136 

我試着打印pubKeyBlobFromServer的字節。公鑰從第8個字節開始。第一個8保留給BCRYPT_DH_KEY_BLOB。我不知道什麼是錯的。請建議我犯錯的地方。如果沒有,請建議從字符串導入公鑰的樣本。提前致謝。

+1

[根據文檔](https://msdn.microsoft.com/en-us/library/windows/desktop/aa833125(v = vs.85).aspx)以及緩衝區通過的標頭到導入函數必須包含模數,生成器和公共數字,*每個*是'cbKey'字節長。假設這是一個1024位密鑰,則只包含三個組件中的一個。 –

+0

感謝@HarryJohnston工作。 –

回答

1

微軟的示例代碼很簡單,因爲相同的API導出了密鑰,所以它已經處於正確的格式。

爲了自己構造一個有效的密鑰團,你需要查找the documentation for the BCRYPT_DH_KEY_BLOB structure

一個Diffie-Hellman的公鑰BLOB(BCRYPT_DH_PUBLIC_BLOB)在連續的存儲格式如下:模數,發生器和公共數字採用大端格式。

BCRYPT_DH_KEY_BLOB 
Modulus[cbKey] // Big-endian. 
Generator[cbKey] // Big-endian. 
Public[cbKey] // Big-endian. 

看起來像你的代碼只包括三個組成部分之一。

相關問題