struct key_container* import_keys (const char* filename) { assert (NULL != filename); FILE *fp; const char *key = NULL; struct key_container* keys = NULL; const unsigned int SIZE_OF_256_BITS_ASCII = 64; bool key_valid = true; fp = fopen (filename, "r"); if (NULL != fp) { if (0 == parse_file (fp)) { keys = make_key_container(); int x = 0; for (x = 0; x < MAX_NUM_DATA_SLOTS && key_valid; x++) { key = get_key (x); keys->keys[x] = ascii_hex_2_bin (key, SIZE_OF_256_BITS_ASCII); if (NULL == keys->keys[x].ptr || 32 != keys->keys[x].len) key_valid = false; } free_parsed_keys (); } fclose (fp); } return keys; }
bool write_keys (int fd, struct key_container *keys, struct octet_buffer *data_zone) { assert (NULL != data_zone); assert (STATE_INITIALIZED == get_device_state (fd)); bool free_keys = false; #define KEY_LEN 32 const unsigned int TEST_KEY_1 = 14; const unsigned int TEST_KEY_2 = 15; struct octet_buffer test_key_14 = make_buffer (KEY_LEN); memset(test_key_14.ptr, 0xAA, KEY_LEN); struct octet_buffer test_key_15 = make_buffer (KEY_LEN); memset(test_key_15.ptr, 0xBB, KEY_LEN); int x = 0; /* If there are no keys, which is the case when we are personalizing a device from scratch, create some new keys */ if (NULL == keys) { keys = make_key_container (); for (x=0; x < get_max_keys (); x++) { if (TEST_KEY_1 == x) { keys->keys[x] = test_key_14; } else if (TEST_KEY_2 == x) { keys->keys[x] = test_key_15; } else { keys->keys[x] = get_random (fd, false); } } free_keys = true; } bool status = true; for (x=0; x < get_max_keys () && status; x++) { const unsigned int WORD_OFFSET = 8; unsigned int addr = WORD_OFFSET * x; status = write32 (fd, DATA_ZONE, addr, keys->keys[x], NULL); } if (status) { data_zone->len = get_max_keys () * keys->keys[0].len; data_zone->ptr = malloc_wipe (data_zone->len); for (x=0; x < get_max_keys (); x++) { CTX_LOG(DEBUG, "Writing key %u", x); unsigned int offset = x * keys->keys[x].len; memcpy(data_zone->ptr + offset, keys->keys[x].ptr, keys->keys[x].len); } status = record_keys (keys); } if (free_keys) free_key_container (keys); return status; }