Skip to content

Unable to generate ECkey pair on PKCS11 token using libp11 API #617

@muraliselvaraj2020

Description

@muraliselvaraj2020

Hi Team,

I'm trying to generate a EC-keypair using libp11 API as follows but it is NOT working.
Getting result = -1 in the below code.

Cross checked and able to generate EC keypair using pkcs11-tool. So it indicates, the issue might NOT in pkcs11 TA.
Can you please help me out to review the code and suggest your inputs if I missed anything.

PKCS11_CTX *ctx;
PKCS11_SLOT *slots, *slot;
PKCS11_TOKEN *token;
unsigned int nslots;
int ret = -1;
unsigned int i;
char label[64];

snprintf(label, sizeof(label), "ECKeyPair_");
for (size_t j = 0; j < key_id_len; j++) {
    snprintf(label + strlen(label), sizeof(label) - strlen(label), "%02x", key_id[j]);
}

ctx = PKCS11_CTX_new();
if (!ctx) {
    printf("Failed to create PKCS#11 context\n");
    return -1;
}

if (PKCS11_CTX_load(ctx, module_path) < 0) {
    printf("Failed to load PKCS#11 module: %s\n", module_path);
    ERR_print_errors_fp(stderr);
    goto cleanup_ctx;
}

if (PKCS11_enumerate_slots(ctx, &slots, &nslots) < 0) {
    printf("Failed to enumerate slots\n");
    ERR_print_errors_fp(stderr);
    goto cleanup_ctx;
}

slot = NULL;
for (i = 0; i < nslots; i++) {
    if (slots[i].token) {
        slot = &slots[i];
        break;
    }
}

if (!slot) {
    printf("No slot with token found\n");
    goto cleanup_slots;
}

token = slot->token;
printf("Using token: %s\n", token->label);

if (PKCS11_open_session(slot, 1) < 0) {
    printf("Failed to open read-write session\n");
    ERR_print_errors_fp(stderr);
    goto cleanup_slots;
}

if (PKCS11_login(slot, 0, pin) < 0) {
    printf("User login failed, trying SO login\n");
    if (PKCS11_login(slot, 1, pin) < 0) {
        printf("Login failed\n");
        ERR_print_errors_fp(stderr);
        goto cleanup_session;
    }
}

int algorithm = EVP_PKEY_EC;
unsigned int curve_nid = NID_X9_62_prime256v1;
int result;

result = PKCS11_generate_key(
    token,
    algorithm,
    curve_nid,
    label,
    key_id,
    key_id_len
);

printf("result is %d \n", result);
return result;

Thankx
Murali.S

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions