0

我正在尝试使用 wincrypt 使用 P 和 G 值生成私钥。我得到ERROR_INVALID_PARAMETER我不确定我的代码有什么问题。它与 microsoft 网站中给出的示例代码中的实现相同。 https://msdn.microsoft.com/en-us/library/aa381969(VS.85).aspx#exchangeing_diffie-hellman_keys

int err, gen_fld_sz, fld_sz, salt_len;
const char *generator = ""; // generator as string
const char *prime     = ""; // prime as string
 BYTE* g_rgbPrime = new BYTE[fld_sz+1];
 memcpy(g_rgbPrime, prime, fld_sz+1);  // Prime conta
  BYTE* g_rgbGenerator = new BYTE[gen_fld_sz+1];
  memcpy(g_rgbGenerator, generator, gen_fld_sz+1);
  BYTE* g_rgbData = new BYTE[key_len+1];
  memcpy(g_rgbData, str_server_pub_key, key_len);

  BOOL fReturn;
  HCRYPTPROV hProvParty1 = NULL;
  HCRYPTPROV hProvParty2 = NULL;
  DATA_BLOB P;
  DATA_BLOB G;
  DATA_BLOB S;
  HCRYPTKEY hPrivateKey1 = NULL;
  HCRYPTKEY hPrivateKey2 = NULL;
  PBYTE pbKeyBlob1 = NULL;
  PBYTE pbKeyBlob2 = NULL;
  HCRYPTKEY hSessionKey1 = NULL;
  HCRYPTKEY hSessionKey2 = NULL;
  PBYTE pbData = NULL;

  /************************
  Construct data BLOBs for the prime and generator. The P and G
  values, represented by the g_rgbPrime and g_rgbGenerator arrays
  respectively, are shared values that have been agreed to by both
  parties.
  ************************/
  P.cbData = fld_sz+1;
  P.pbData = (BYTE*)(g_rgbPrime);

  G.cbData = gen_fld_sz+1;
  G.pbData = (BYTE*)(g_rgbGenerator);
  // Acquire a provider handle for party 1.
  fReturn = CryptAcquireContext(
    &hProvParty1,
    NULL,
    MS_ENH_DSS_DH_PROV,
    PROV_DSS_DH,
    CRYPT_VERIFYCONTEXT);
  if (!fReturn)
  {
    log_error("error in setting CryptAcquireContext " << GetLastError());
    goto ErrorExit;
  }


  // Set the prime for party 1's private key.
  fReturn = CryptSetKeyParam(
    hPrivateKey1,
    KP_P,
    (PBYTE)&P,
    0);
  if (!fReturn)
  {
    log_error("error in setting CryptSetKeyParam " << GetLastError());
    goto ErrorExit;
  }

我在最后一个CryptSetKeyParam中遇到错误。请指教。

提前致谢。

4

1 回答 1

0

好吧,只需按照您链接的示例,还有一些步骤比您做的要多。例如,在 CryptAcquireContext 和 CryptSetKeyParam 之间,他调用 CryptGenKey,即给 hPrivateKey1 一个临时值。

// Create an ephemeral private key for party 1.
fReturn = CryptGenKey(
    hProvParty1, 
    CALG_DH_EPHEM, 
    DHKEYSIZE << 16 | CRYPT_EXPORTABLE | CRYPT_PREGEN,
    &hPrivateKey1);
if(!fReturn)
{
    goto ErrorExit;
}

在您的代码中,您使用 hPrivateKey1=NULL; 调用 CryptGenKey

于 2017-08-25T15:41:22.110 回答