BCryptImportKeyPair returns STATUS_INVALID_PARAMETER 当我尝试导入 public 密钥时

BCryptImportKeyPair returns STATUS_INVALID_PARAMETER when i try to import public key

我关注了this example。我正在尝试将从服务器获得的 public 密钥添加到密钥对中,我得到 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 的字节。 public 键从第 8 个字节开始。前 8 个保留给 BCRYPT_DH_KEY_BLOB 。我不确定哪里出了问题。请建议我犯错误的地方。如果没有,请建议一个从字符串中导入 public 键的示例。提前致谢。

微软的示例代码省事;因为相同的 API 导出了密钥,所以它的格式已经正确。

为了自己构建有效的密钥 blob,您需要查找 the documentation for the BCRYPT_DH_KEY_BLOB structure:

A Diffie-Hellman public key BLOB (BCRYPT_DH_PUBLIC_BLOB) has the following format in contiguous memory. The Modulus, Generator, and Public numbers are in big-endian format.

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

看起来您的代码只包含三个组件之一。