Hassan Shahbazi
Hassan Shahbazi

Reputation: 1603

d2i_ECParameters Returns Null

I want to create a EC_Key from NSData, via OpenSSL. So I write the following:

- (void)setPrivateKey:(NSData *)privateKey {
      const unsigned char *bits = (unsigned char *) [privateKey bytes];
      eckey = EC_KEY_new_by_curve_name(NID_X9_62_prime256v1);
      ec_group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
      EC_KEY_set_group(eckey, ec_group);
      EC_KEY_generate_key(eckey);
      EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE);
      eckey = d2i_ECParameters(&eckey, &bits, privateKey.length);
}

but

eckey = d2i_ECParameters(&eckey, &bits, privateKey.length);

returns null.

What is the problem?

Upvotes: 1

Views: 301

Answers (1)

Hassan Shahbazi
Hassan Shahbazi

Reputation: 1603

Thanks to @jww for his great comments, finally, I succeed to solve this problem by the following code block

- (void)setPrivateKey:(NSData *)privateKey {
      const unsigned char *privateKeyBits = (unsigned char *) [privateKey bytes];

     ec_group = EC_GROUP_new_by_curve_name(NID_X9_62_prime256v1);
     eckey = EC_KEY_new();
     EC_KEY_set_group(eckey, ec_group);
     EC_KEY_generate_key(eckey);
     EC_KEY_set_asn1_flag(eckey, OPENSSL_EC_NAMED_CURVE);

     BIGNUM *prv = BN_bin2bn(privateKeyBits, sizeof(privateKeyBits), NULL);
     EC_KEY_set_private_key(eckey, prv);

     EC_POINT *pub = EC_POINT_new(ec_group);
     EC_POINT_mul(ec_group, pub, prv, NULL, NULL, NULL);
     EC_KEY_set_public_key(eckey, pub);

     pkey = EVP_PKEY_new();
     EVP_PKEY_set1_EC_KEY(pkey, eckey);
}

Although I had both public key and private key, but with above code I calculated the public key from private key.

Upvotes: 1

Related Questions