2017-09-12 87 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. 

看起来像你的代码只包括三个组成部分之一。

相关问题