diff --git a/src/pkcs11_store.c b/src/pkcs11_store.c index 636d70c19..d123a7b11 100644 --- a/src/pkcs11_store.c +++ b/src/pkcs11_store.c @@ -427,8 +427,11 @@ int wolfPKCS11_Store_Open(int type, CK_ULONG id1, CK_ULONG id2, int read, /* Set the 'readonly' flag in this handle if open with 'r' */ if (read) handle->flags |= STORE_FLAGS_READONLY; - else + else { handle->flags &= ~STORE_FLAGS_READONLY; + /* Truncate the slot when opening in write mode */ + update_store_size(handle->hdr, 2 * sizeof(uint32_t)); + } /* Set start of the buffer after the tok/obj id fields */ diff --git a/tools/unit-tests/unit-pkcs11_store.c b/tools/unit-tests/unit-pkcs11_store.c index c2f6aab44..ed205d433 100644 --- a/tools/unit-tests/unit-pkcs11_store.c +++ b/tools/unit-tests/unit-pkcs11_store.c @@ -84,6 +84,7 @@ START_TEST (test_store_and_load_objs) { void *store = NULL; const char secret1[] = "Everyone gets Friday off."; const char secret2[] = "This is just a test string."; + const char short_string[] = "Short string"; char secret_rd[KEYVAULT_OBJ_SIZE]; type = DYNAMIC_TYPE_ECC; @@ -247,6 +248,26 @@ START_TEST (test_store_and_load_objs) { fail_if(ret != KEYVAULT_OBJ_SIZE - 8); fail_if(strncmp(dante_filler, secret_rd, KEYVAULT_OBJ_SIZE - 8) != 0); wolfPKCS11_Store_Close(store); + + /* Reopen for writing, test truncate */ + readonly = 0; + ret = wolfPKCS11_Store_Open(type, id_tok, id_obj, readonly, &store); + fail_unless(ret == 0, "Failed to create vault: %d", ret); + fail_if(store == NULL, "Did not receive a store address for vault"); + fprintf(stderr, "open 3.33 successful\n"); + ret = wolfPKCS11_Store_Write(store, short_string, strlen(short_string) + 1); + wolfPKCS11_Store_Close(store); + + /* Reopen for reading */ + readonly = 1; + ret = wolfPKCS11_Store_Open(type, id_tok, id_obj, readonly, &store); + fail_if(ret != 0, "Failed to reopen the vault in read-only mode: %d", ret); + /* Read out the content */ + memset(secret_rd, 0, KEYVAULT_OBJ_SIZE); + ret = wolfPKCS11_Store_Read(store, secret_rd, KEYVAULT_OBJ_SIZE); + fail_if(ret != strlen(short_string) + 1); + fail_if(strcmp(short_string, secret_rd) != 0); + wolfPKCS11_Store_Close(store); } END_TEST