key_ladder_demo.c 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707
  1. /**
  2. * PSA API key derivation demonstration
  3. *
  4. * This program calculates a key ladder: a chain of secret material, each
  5. * derived from the previous one in a deterministic way based on a label.
  6. * Two keys are identical if and only if they are derived from the same key
  7. * using the same label.
  8. *
  9. * The initial key is called the master key. The master key is normally
  10. * randomly generated, but it could itself be derived from another key.
  11. *
  12. * This program derives a series of keys called intermediate keys.
  13. * The first intermediate key is derived from the master key using the
  14. * first label passed on the command line. Each subsequent intermediate
  15. * key is derived from the previous one using the next label passed
  16. * on the command line.
  17. *
  18. * This program has four modes of operation:
  19. *
  20. * - "generate": generate a random master key.
  21. * - "wrap": derive a wrapping key from the last intermediate key,
  22. * and use that key to encrypt-and-authenticate some data.
  23. * - "unwrap": derive a wrapping key from the last intermediate key,
  24. * and use that key to decrypt-and-authenticate some
  25. * ciphertext created by wrap mode.
  26. * - "save": save the last intermediate key so that it can be reused as
  27. * the master key in another run of the program.
  28. *
  29. * See the usage() output for the command line usage. See the file
  30. * `key_ladder_demo.sh` for an example run.
  31. */
  32. /*
  33. * Copyright The Mbed TLS Contributors
  34. * SPDX-License-Identifier: Apache-2.0
  35. *
  36. * Licensed under the Apache License, Version 2.0 (the "License"); you may
  37. * not use this file except in compliance with the License.
  38. * You may obtain a copy of the License at
  39. *
  40. * http://www.apache.org/licenses/LICENSE-2.0
  41. *
  42. * Unless required by applicable law or agreed to in writing, software
  43. * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  44. * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  45. * See the License for the specific language governing permissions and
  46. * limitations under the License.
  47. */
  48. /* First include Mbed TLS headers to get the Mbed TLS configuration and
  49. * platform definitions that we'll use in this program. Also include
  50. * standard C headers for functions we'll use here. */
  51. #if !defined(MBEDTLS_CONFIG_FILE)
  52. #include "mbedtls/config.h"
  53. #else
  54. #include MBEDTLS_CONFIG_FILE
  55. #endif
  56. #include <stdlib.h>
  57. #include <stdio.h>
  58. #include <string.h>
  59. #include "mbedtls/platform_util.h" // for mbedtls_platform_zeroize
  60. #include <psa/crypto.h>
  61. /* If the build options we need are not enabled, compile a placeholder. */
  62. #if !defined(MBEDTLS_SHA256_C) || !defined(MBEDTLS_MD_C) || \
  63. !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CCM_C) || \
  64. !defined(MBEDTLS_PSA_CRYPTO_C) || !defined(MBEDTLS_FS_IO) || \
  65. defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
  66. int main( void )
  67. {
  68. printf( "MBEDTLS_SHA256_C and/or MBEDTLS_MD_C and/or "
  69. "MBEDTLS_AES_C and/or MBEDTLS_CCM_C and/or "
  70. "MBEDTLS_PSA_CRYPTO_C and/or MBEDTLS_FS_IO "
  71. "not defined and/or MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER "
  72. "defined.\n" );
  73. return( 0 );
  74. }
  75. #else
  76. /* The real program starts here. */
  77. /* Run a system function and bail out if it fails. */
  78. #define SYS_CHECK( expr ) \
  79. do \
  80. { \
  81. if( ! ( expr ) ) \
  82. { \
  83. perror( #expr ); \
  84. status = DEMO_ERROR; \
  85. goto exit; \
  86. } \
  87. } \
  88. while( 0 )
  89. /* Run a PSA function and bail out if it fails. */
  90. #define PSA_CHECK( expr ) \
  91. do \
  92. { \
  93. status = ( expr ); \
  94. if( status != PSA_SUCCESS ) \
  95. { \
  96. printf( "Error %d at line %d: %s\n", \
  97. (int) status, \
  98. __LINE__, \
  99. #expr ); \
  100. goto exit; \
  101. } \
  102. } \
  103. while( 0 )
  104. /* To report operational errors in this program, use an error code that is
  105. * different from every PSA error code. */
  106. #define DEMO_ERROR 120
  107. /* The maximum supported key ladder depth. */
  108. #define MAX_LADDER_DEPTH 10
  109. /* Salt to use when deriving an intermediate key. */
  110. #define DERIVE_KEY_SALT ( (uint8_t *) "key_ladder_demo.derive" )
  111. #define DERIVE_KEY_SALT_LENGTH ( strlen( (const char*) DERIVE_KEY_SALT ) )
  112. /* Salt to use when deriving a wrapping key. */
  113. #define WRAPPING_KEY_SALT ( (uint8_t *) "key_ladder_demo.wrap" )
  114. #define WRAPPING_KEY_SALT_LENGTH ( strlen( (const char*) WRAPPING_KEY_SALT ) )
  115. /* Size of the key derivation keys (applies both to the master key and
  116. * to intermediate keys). */
  117. #define KEY_SIZE_BYTES 40
  118. /* Algorithm for key derivation. */
  119. #define KDF_ALG PSA_ALG_HKDF( PSA_ALG_SHA_256 )
  120. /* Type and size of the key used to wrap data. */
  121. #define WRAPPING_KEY_TYPE PSA_KEY_TYPE_AES
  122. #define WRAPPING_KEY_BITS 128
  123. /* Cipher mode used to wrap data. */
  124. #define WRAPPING_ALG PSA_ALG_CCM
  125. /* Nonce size used to wrap data. */
  126. #define WRAPPING_IV_SIZE 13
  127. /* Header used in files containing wrapped data. We'll save this header
  128. * directly without worrying about data representation issues such as
  129. * integer sizes and endianness, because the data is meant to be read
  130. * back by the same program on the same machine. */
  131. #define WRAPPED_DATA_MAGIC "key_ladder_demo" // including trailing null byte
  132. #define WRAPPED_DATA_MAGIC_LENGTH ( sizeof( WRAPPED_DATA_MAGIC ) )
  133. typedef struct
  134. {
  135. char magic[WRAPPED_DATA_MAGIC_LENGTH];
  136. size_t ad_size; /* Size of the additional data, which is this header. */
  137. size_t payload_size; /* Size of the encrypted data. */
  138. /* Store the IV inside the additional data. It's convenient. */
  139. uint8_t iv[WRAPPING_IV_SIZE];
  140. } wrapped_data_header_t;
  141. /* The modes that this program can operate in (see usage). */
  142. enum program_mode
  143. {
  144. MODE_GENERATE,
  145. MODE_SAVE,
  146. MODE_UNWRAP,
  147. MODE_WRAP
  148. };
  149. /* Save a key to a file. In the real world, you may want to export a derived
  150. * key sometimes, to share it with another party. */
  151. static psa_status_t save_key( psa_key_id_t key,
  152. const char *output_file_name )
  153. {
  154. psa_status_t status = PSA_SUCCESS;
  155. uint8_t key_data[KEY_SIZE_BYTES];
  156. size_t key_size;
  157. FILE *key_file = NULL;
  158. PSA_CHECK( psa_export_key( key,
  159. key_data, sizeof( key_data ),
  160. &key_size ) );
  161. SYS_CHECK( ( key_file = fopen( output_file_name, "wb" ) ) != NULL );
  162. SYS_CHECK( fwrite( key_data, 1, key_size, key_file ) == key_size );
  163. SYS_CHECK( fclose( key_file ) == 0 );
  164. key_file = NULL;
  165. exit:
  166. if( key_file != NULL)
  167. fclose( key_file );
  168. return( status );
  169. }
  170. /* Generate a master key for use in this demo.
  171. *
  172. * Normally a master key would be non-exportable. For the purpose of this
  173. * demo, we want to save it to a file, to avoid relying on the keystore
  174. * capability of the PSA crypto library. */
  175. static psa_status_t generate( const char *key_file_name )
  176. {
  177. psa_status_t status = PSA_SUCCESS;
  178. psa_key_id_t key = 0;
  179. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  180. psa_set_key_usage_flags( &attributes,
  181. PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT );
  182. psa_set_key_algorithm( &attributes, KDF_ALG );
  183. psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
  184. psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ) );
  185. PSA_CHECK( psa_generate_key( &attributes, &key ) );
  186. PSA_CHECK( save_key( key, key_file_name ) );
  187. exit:
  188. (void) psa_destroy_key( key );
  189. return( status );
  190. }
  191. /* Load the master key from a file.
  192. *
  193. * In the real world, this master key would be stored in an internal memory
  194. * and the storage would be managed by the keystore capability of the PSA
  195. * crypto library. */
  196. static psa_status_t import_key_from_file( psa_key_usage_t usage,
  197. psa_algorithm_t alg,
  198. const char *key_file_name,
  199. psa_key_id_t *master_key )
  200. {
  201. psa_status_t status = PSA_SUCCESS;
  202. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  203. uint8_t key_data[KEY_SIZE_BYTES];
  204. size_t key_size;
  205. FILE *key_file = NULL;
  206. unsigned char extra_byte;
  207. SYS_CHECK( ( key_file = fopen( key_file_name, "rb" ) ) != NULL );
  208. SYS_CHECK( ( key_size = fread( key_data, 1, sizeof( key_data ),
  209. key_file ) ) != 0 );
  210. if( fread( &extra_byte, 1, 1, key_file ) != 0 )
  211. {
  212. printf( "Key file too large (max: %u).\n",
  213. (unsigned) sizeof( key_data ) );
  214. status = DEMO_ERROR;
  215. goto exit;
  216. }
  217. SYS_CHECK( fclose( key_file ) == 0 );
  218. key_file = NULL;
  219. psa_set_key_usage_flags( &attributes, usage );
  220. psa_set_key_algorithm( &attributes, alg );
  221. psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
  222. PSA_CHECK( psa_import_key( &attributes, key_data, key_size, master_key ) );
  223. exit:
  224. if( key_file != NULL )
  225. fclose( key_file );
  226. mbedtls_platform_zeroize( key_data, sizeof( key_data ) );
  227. if( status != PSA_SUCCESS )
  228. {
  229. /* If the key creation hasn't happened yet or has failed,
  230. * *master_key is null. psa_destroy_key( 0 ) is
  231. * guaranteed to do nothing and return PSA_SUCCESS. */
  232. (void) psa_destroy_key( *master_key );
  233. *master_key = 0;
  234. }
  235. return( status );
  236. }
  237. /* Derive the intermediate keys, using the list of labels provided on
  238. * the command line. On input, *key is the master key identifier.
  239. * This function destroys the master key. On successful output, *key
  240. * is the identifier of the final derived key.
  241. */
  242. static psa_status_t derive_key_ladder( const char *ladder[],
  243. size_t ladder_depth,
  244. psa_key_id_t *key )
  245. {
  246. psa_status_t status = PSA_SUCCESS;
  247. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  248. psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
  249. size_t i;
  250. psa_set_key_usage_flags( &attributes,
  251. PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT );
  252. psa_set_key_algorithm( &attributes, KDF_ALG );
  253. psa_set_key_type( &attributes, PSA_KEY_TYPE_DERIVE );
  254. psa_set_key_bits( &attributes, PSA_BYTES_TO_BITS( KEY_SIZE_BYTES ) );
  255. /* For each label in turn, ... */
  256. for( i = 0; i < ladder_depth; i++ )
  257. {
  258. /* Start deriving material from the master key (if i=0) or from
  259. * the current intermediate key (if i>0). */
  260. PSA_CHECK( psa_key_derivation_setup( &operation, KDF_ALG ) );
  261. PSA_CHECK( psa_key_derivation_input_bytes(
  262. &operation, PSA_KEY_DERIVATION_INPUT_SALT,
  263. DERIVE_KEY_SALT, DERIVE_KEY_SALT_LENGTH ) );
  264. PSA_CHECK( psa_key_derivation_input_key(
  265. &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
  266. *key ) );
  267. PSA_CHECK( psa_key_derivation_input_bytes(
  268. &operation, PSA_KEY_DERIVATION_INPUT_INFO,
  269. (uint8_t*) ladder[i], strlen( ladder[i] ) ) );
  270. /* When the parent key is not the master key, destroy it,
  271. * since it is no longer needed. */
  272. PSA_CHECK( psa_destroy_key( *key ) );
  273. *key = 0;
  274. /* Derive the next intermediate key from the parent key. */
  275. PSA_CHECK( psa_key_derivation_output_key( &attributes, &operation,
  276. key ) );
  277. PSA_CHECK( psa_key_derivation_abort( &operation ) );
  278. }
  279. exit:
  280. psa_key_derivation_abort( &operation );
  281. if( status != PSA_SUCCESS )
  282. {
  283. psa_destroy_key( *key );
  284. *key = 0;
  285. }
  286. return( status );
  287. }
  288. /* Derive a wrapping key from the last intermediate key. */
  289. static psa_status_t derive_wrapping_key( psa_key_usage_t usage,
  290. psa_key_id_t derived_key,
  291. psa_key_id_t *wrapping_key )
  292. {
  293. psa_status_t status = PSA_SUCCESS;
  294. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  295. psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
  296. *wrapping_key = 0;
  297. /* Set up a key derivation operation from the key derived from
  298. * the master key. */
  299. PSA_CHECK( psa_key_derivation_setup( &operation, KDF_ALG ) );
  300. PSA_CHECK( psa_key_derivation_input_bytes(
  301. &operation, PSA_KEY_DERIVATION_INPUT_SALT,
  302. WRAPPING_KEY_SALT, WRAPPING_KEY_SALT_LENGTH ) );
  303. PSA_CHECK( psa_key_derivation_input_key(
  304. &operation, PSA_KEY_DERIVATION_INPUT_SECRET,
  305. derived_key ) );
  306. PSA_CHECK( psa_key_derivation_input_bytes(
  307. &operation, PSA_KEY_DERIVATION_INPUT_INFO,
  308. NULL, 0 ) );
  309. /* Create the wrapping key. */
  310. psa_set_key_usage_flags( &attributes, usage );
  311. psa_set_key_algorithm( &attributes, WRAPPING_ALG );
  312. psa_set_key_type( &attributes, PSA_KEY_TYPE_AES );
  313. psa_set_key_bits( &attributes, WRAPPING_KEY_BITS );
  314. PSA_CHECK( psa_key_derivation_output_key( &attributes, &operation,
  315. wrapping_key ) );
  316. exit:
  317. psa_key_derivation_abort( &operation );
  318. return( status );
  319. }
  320. static psa_status_t wrap_data( const char *input_file_name,
  321. const char *output_file_name,
  322. psa_key_id_t wrapping_key )
  323. {
  324. psa_status_t status;
  325. FILE *input_file = NULL;
  326. FILE *output_file = NULL;
  327. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  328. psa_key_type_t key_type;
  329. long input_position;
  330. size_t input_size;
  331. size_t buffer_size = 0;
  332. unsigned char *buffer = NULL;
  333. size_t ciphertext_size;
  334. wrapped_data_header_t header;
  335. /* Find the size of the data to wrap. */
  336. SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
  337. SYS_CHECK( fseek( input_file, 0, SEEK_END ) == 0 );
  338. SYS_CHECK( ( input_position = ftell( input_file ) ) != -1 );
  339. #if LONG_MAX > SIZE_MAX
  340. if( input_position > SIZE_MAX )
  341. {
  342. printf( "Input file too large.\n" );
  343. status = DEMO_ERROR;
  344. goto exit;
  345. }
  346. #endif
  347. input_size = input_position;
  348. PSA_CHECK( psa_get_key_attributes( wrapping_key, &attributes ) );
  349. key_type = psa_get_key_type( &attributes );
  350. buffer_size =
  351. PSA_AEAD_ENCRYPT_OUTPUT_SIZE( key_type, WRAPPING_ALG, input_size );
  352. /* Check for integer overflow. */
  353. if( buffer_size < input_size )
  354. {
  355. printf( "Input file too large.\n" );
  356. status = DEMO_ERROR;
  357. goto exit;
  358. }
  359. /* Load the data to wrap. */
  360. SYS_CHECK( fseek( input_file, 0, SEEK_SET ) == 0 );
  361. SYS_CHECK( ( buffer = calloc( 1, buffer_size ) ) != NULL );
  362. SYS_CHECK( fread( buffer, 1, input_size, input_file ) == input_size );
  363. SYS_CHECK( fclose( input_file ) == 0 );
  364. input_file = NULL;
  365. /* Construct a header. */
  366. memcpy( &header.magic, WRAPPED_DATA_MAGIC, WRAPPED_DATA_MAGIC_LENGTH );
  367. header.ad_size = sizeof( header );
  368. header.payload_size = input_size;
  369. /* Wrap the data. */
  370. PSA_CHECK( psa_generate_random( header.iv, WRAPPING_IV_SIZE ) );
  371. PSA_CHECK( psa_aead_encrypt( wrapping_key, WRAPPING_ALG,
  372. header.iv, WRAPPING_IV_SIZE,
  373. (uint8_t *) &header, sizeof( header ),
  374. buffer, input_size,
  375. buffer, buffer_size,
  376. &ciphertext_size ) );
  377. /* Write the output. */
  378. SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
  379. SYS_CHECK( fwrite( &header, 1, sizeof( header ),
  380. output_file ) == sizeof( header ) );
  381. SYS_CHECK( fwrite( buffer, 1, ciphertext_size,
  382. output_file ) == ciphertext_size );
  383. SYS_CHECK( fclose( output_file ) == 0 );
  384. output_file = NULL;
  385. exit:
  386. if( input_file != NULL )
  387. fclose( input_file );
  388. if( output_file != NULL )
  389. fclose( output_file );
  390. if( buffer != NULL )
  391. mbedtls_platform_zeroize( buffer, buffer_size );
  392. free( buffer );
  393. return( status );
  394. }
  395. static psa_status_t unwrap_data( const char *input_file_name,
  396. const char *output_file_name,
  397. psa_key_id_t wrapping_key )
  398. {
  399. psa_status_t status;
  400. FILE *input_file = NULL;
  401. FILE *output_file = NULL;
  402. psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
  403. psa_key_type_t key_type;
  404. unsigned char *buffer = NULL;
  405. size_t ciphertext_size = 0;
  406. size_t plaintext_size;
  407. wrapped_data_header_t header;
  408. unsigned char extra_byte;
  409. /* Load and validate the header. */
  410. SYS_CHECK( ( input_file = fopen( input_file_name, "rb" ) ) != NULL );
  411. SYS_CHECK( fread( &header, 1, sizeof( header ),
  412. input_file ) == sizeof( header ) );
  413. if( memcmp( &header.magic, WRAPPED_DATA_MAGIC,
  414. WRAPPED_DATA_MAGIC_LENGTH ) != 0 )
  415. {
  416. printf( "The input does not start with a valid magic header.\n" );
  417. status = DEMO_ERROR;
  418. goto exit;
  419. }
  420. if( header.ad_size != sizeof( header ) )
  421. {
  422. printf( "The header size is not correct.\n" );
  423. status = DEMO_ERROR;
  424. goto exit;
  425. }
  426. PSA_CHECK( psa_get_key_attributes( wrapping_key, &attributes) );
  427. key_type = psa_get_key_type( &attributes);
  428. ciphertext_size =
  429. PSA_AEAD_ENCRYPT_OUTPUT_SIZE( key_type, WRAPPING_ALG, header.payload_size );
  430. /* Check for integer overflow. */
  431. if( ciphertext_size < header.payload_size )
  432. {
  433. printf( "Input file too large.\n" );
  434. status = DEMO_ERROR;
  435. goto exit;
  436. }
  437. /* Load the payload data. */
  438. SYS_CHECK( ( buffer = calloc( 1, ciphertext_size ) ) != NULL );
  439. SYS_CHECK( fread( buffer, 1, ciphertext_size,
  440. input_file ) == ciphertext_size );
  441. if( fread( &extra_byte, 1, 1, input_file ) != 0 )
  442. {
  443. printf( "Extra garbage after ciphertext\n" );
  444. status = DEMO_ERROR;
  445. goto exit;
  446. }
  447. SYS_CHECK( fclose( input_file ) == 0 );
  448. input_file = NULL;
  449. /* Unwrap the data. */
  450. PSA_CHECK( psa_aead_decrypt( wrapping_key, WRAPPING_ALG,
  451. header.iv, WRAPPING_IV_SIZE,
  452. (uint8_t *) &header, sizeof( header ),
  453. buffer, ciphertext_size,
  454. buffer, ciphertext_size,
  455. &plaintext_size ) );
  456. if( plaintext_size != header.payload_size )
  457. {
  458. printf( "Incorrect payload size in the header.\n" );
  459. status = DEMO_ERROR;
  460. goto exit;
  461. }
  462. /* Write the output. */
  463. SYS_CHECK( ( output_file = fopen( output_file_name, "wb" ) ) != NULL );
  464. SYS_CHECK( fwrite( buffer, 1, plaintext_size,
  465. output_file ) == plaintext_size );
  466. SYS_CHECK( fclose( output_file ) == 0 );
  467. output_file = NULL;
  468. exit:
  469. if( input_file != NULL )
  470. fclose( input_file );
  471. if( output_file != NULL )
  472. fclose( output_file );
  473. if( buffer != NULL )
  474. mbedtls_platform_zeroize( buffer, ciphertext_size );
  475. free( buffer );
  476. return( status );
  477. }
  478. static psa_status_t run( enum program_mode mode,
  479. const char *key_file_name,
  480. const char *ladder[], size_t ladder_depth,
  481. const char *input_file_name,
  482. const char *output_file_name )
  483. {
  484. psa_status_t status = PSA_SUCCESS;
  485. psa_key_id_t derivation_key = 0;
  486. psa_key_id_t wrapping_key = 0;
  487. /* Initialize the PSA crypto library. */
  488. PSA_CHECK( psa_crypto_init( ) );
  489. /* Generate mode is unlike the others. Generate the master key and exit. */
  490. if( mode == MODE_GENERATE )
  491. return( generate( key_file_name ) );
  492. /* Read the master key. */
  493. PSA_CHECK( import_key_from_file( PSA_KEY_USAGE_DERIVE | PSA_KEY_USAGE_EXPORT,
  494. KDF_ALG,
  495. key_file_name,
  496. &derivation_key ) );
  497. /* Calculate the derived key for this session. */
  498. PSA_CHECK( derive_key_ladder( ladder, ladder_depth,
  499. &derivation_key ) );
  500. switch( mode )
  501. {
  502. case MODE_SAVE:
  503. PSA_CHECK( save_key( derivation_key, output_file_name ) );
  504. break;
  505. case MODE_UNWRAP:
  506. PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_DECRYPT,
  507. derivation_key,
  508. &wrapping_key ) );
  509. PSA_CHECK( unwrap_data( input_file_name, output_file_name,
  510. wrapping_key ) );
  511. break;
  512. case MODE_WRAP:
  513. PSA_CHECK( derive_wrapping_key( PSA_KEY_USAGE_ENCRYPT,
  514. derivation_key,
  515. &wrapping_key ) );
  516. PSA_CHECK( wrap_data( input_file_name, output_file_name,
  517. wrapping_key ) );
  518. break;
  519. default:
  520. /* Unreachable but some compilers don't realize it. */
  521. break;
  522. }
  523. exit:
  524. /* Destroy any remaining key. Deinitializing the crypto library would do
  525. * this anyway since they are volatile keys, but explicitly destroying
  526. * keys makes the code easier to reuse. */
  527. (void) psa_destroy_key( derivation_key );
  528. (void) psa_destroy_key( wrapping_key );
  529. /* Deinitialize the PSA crypto library. */
  530. mbedtls_psa_crypto_free( );
  531. return( status );
  532. }
  533. static void usage( void )
  534. {
  535. printf( "Usage: key_ladder_demo MODE [OPTION=VALUE]...\n" );
  536. printf( "Demonstrate the usage of a key derivation ladder.\n" );
  537. printf( "\n" );
  538. printf( "Modes:\n" );
  539. printf( " generate Generate the master key\n" );
  540. printf( " save Save the derived key\n" );
  541. printf( " unwrap Unwrap (decrypt) input with the derived key\n" );
  542. printf( " wrap Wrap (encrypt) input with the derived key\n" );
  543. printf( "\n" );
  544. printf( "Options:\n" );
  545. printf( " input=FILENAME Input file (required for wrap/unwrap)\n" );
  546. printf( " master=FILENAME File containing the master key (default: master.key)\n" );
  547. printf( " output=FILENAME Output file (required for save/wrap/unwrap)\n" );
  548. printf( " label=TEXT Label for the key derivation.\n" );
  549. printf( " This may be repeated multiple times.\n" );
  550. printf( " To get the same key, you must use the same master key\n" );
  551. printf( " and the same sequence of labels.\n" );
  552. }
  553. int main( int argc, char *argv[] )
  554. {
  555. const char *key_file_name = "master.key";
  556. const char *input_file_name = NULL;
  557. const char *output_file_name = NULL;
  558. const char *ladder[MAX_LADDER_DEPTH];
  559. size_t ladder_depth = 0;
  560. int i;
  561. enum program_mode mode;
  562. psa_status_t status;
  563. if( argc <= 1 ||
  564. strcmp( argv[1], "help" ) == 0 ||
  565. strcmp( argv[1], "-help" ) == 0 ||
  566. strcmp( argv[1], "--help" ) == 0 )
  567. {
  568. usage( );
  569. return( EXIT_SUCCESS );
  570. }
  571. for( i = 2; i < argc; i++ )
  572. {
  573. char *q = strchr( argv[i], '=' );
  574. if( q == NULL )
  575. {
  576. printf( "Missing argument to option %s\n", argv[i] );
  577. goto usage_failure;
  578. }
  579. *q = 0;
  580. ++q;
  581. if( strcmp( argv[i], "input" ) == 0 )
  582. input_file_name = q;
  583. else if( strcmp( argv[i], "label" ) == 0 )
  584. {
  585. if( ladder_depth == MAX_LADDER_DEPTH )
  586. {
  587. printf( "Maximum ladder depth %u exceeded.\n",
  588. (unsigned) MAX_LADDER_DEPTH );
  589. return( EXIT_FAILURE );
  590. }
  591. ladder[ladder_depth] = q;
  592. ++ladder_depth;
  593. }
  594. else if( strcmp( argv[i], "master" ) == 0 )
  595. key_file_name = q;
  596. else if( strcmp( argv[i], "output" ) == 0 )
  597. output_file_name = q;
  598. else
  599. {
  600. printf( "Unknown option: %s\n", argv[i] );
  601. goto usage_failure;
  602. }
  603. }
  604. if( strcmp( argv[1], "generate" ) == 0 )
  605. mode = MODE_GENERATE;
  606. else if( strcmp( argv[1], "save" ) == 0 )
  607. mode = MODE_SAVE;
  608. else if( strcmp( argv[1], "unwrap" ) == 0 )
  609. mode = MODE_UNWRAP;
  610. else if( strcmp( argv[1], "wrap" ) == 0 )
  611. mode = MODE_WRAP;
  612. else
  613. {
  614. printf( "Unknown action: %s\n", argv[1] );
  615. goto usage_failure;
  616. }
  617. if( input_file_name == NULL &&
  618. ( mode == MODE_WRAP || mode == MODE_UNWRAP ) )
  619. {
  620. printf( "Required argument missing: input\n" );
  621. return( DEMO_ERROR );
  622. }
  623. if( output_file_name == NULL &&
  624. ( mode == MODE_SAVE || mode == MODE_WRAP || mode == MODE_UNWRAP ) )
  625. {
  626. printf( "Required argument missing: output\n" );
  627. return( DEMO_ERROR );
  628. }
  629. status = run( mode, key_file_name,
  630. ladder, ladder_depth,
  631. input_file_name, output_file_name );
  632. return( status == PSA_SUCCESS ?
  633. EXIT_SUCCESS :
  634. EXIT_FAILURE );
  635. usage_failure:
  636. usage( );
  637. return( EXIT_FAILURE );
  638. }
  639. #endif /* MBEDTLS_SHA256_C && MBEDTLS_MD_C && MBEDTLS_AES_C && MBEDTLS_CCM_C && MBEDTLS_PSA_CRYPTO_C && MBEDTLS_FS_IO */