blob: ca25bb487d1dc2e13bbf4181493e19a7f50111de [file] [log] [blame]
Gilles Peskinee59236f2018-01-27 23:32:46 +01001/*
2 * PSA crypto layer on top of Mbed TLS crypto
3 */
4/* Copyright (C) 2018, ARM Limited, All Rights Reserved
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * Licensed under the Apache License, Version 2.0 (the "License"); you may
8 * not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
10 *
11 * http://www.apache.org/licenses/LICENSE-2.0
12 *
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
15 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 *
19 * This file is part of mbed TLS (https://tls.mbed.org)
20 */
21
22#if !defined(MBEDTLS_CONFIG_FILE)
23#include "mbedtls/config.h"
24#else
25#include MBEDTLS_CONFIG_FILE
26#endif
27
28#if defined(MBEDTLS_PSA_CRYPTO_C)
29
30#include "psa/crypto.h"
31
32#include "mbedtls/ctr_drbg.h"
33#include "mbedtls/entropy.h"
34
35
36/* Implementation that should never be optimized out by the compiler */
37static void mbedtls_zeroize( void *v, size_t n )
38{
39 volatile unsigned char *p = v; while( n-- ) *p++ = 0;
40}
41
42typedef struct {
43 int initialized;
44 mbedtls_entropy_context entropy;
45 mbedtls_ctr_drbg_context ctr_drbg;
46} psa_global_data_t;
47
48static psa_global_data_t global_data;
49
50static psa_status_t mbedtls_to_psa_error( int ret )
51{
52 switch( ret )
53 {
54 case 0:
55 return( PSA_SUCCESS );
56 case MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED:
57 case MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE:
58 case MBEDTLS_ERR_ENTROPY_SOURCE_FAILED:
59 return( PSA_ERROR_INSUFFICIENT_ENTROPY );
60 default:
61 return( PSA_ERROR_UNKNOWN_ERROR );
62 }
63}
64
65void mbedtls_psa_crypto_free( void )
66{
67 mbedtls_ctr_drbg_free( &global_data.ctr_drbg );
68 mbedtls_entropy_free( &global_data.entropy );
69 mbedtls_zeroize( &global_data, sizeof( global_data ) );
70}
71
72psa_status_t psa_crypto_init( void )
73{
74 int ret;
75 const unsigned char drbg_seed[] = "PSA";
76
77 if( global_data.initialized != 0 )
78 return( PSA_SUCCESS );
79
80 mbedtls_zeroize( &global_data, sizeof( global_data ) );
81 mbedtls_entropy_init( &global_data.entropy );
82 mbedtls_ctr_drbg_init( &global_data.ctr_drbg );
83
84 ret = mbedtls_ctr_drbg_seed( &global_data.ctr_drbg,
85 mbedtls_entropy_func,
86 &global_data.entropy,
87 drbg_seed, sizeof( drbg_seed ) - 1 );
88 if( ret != 0 )
89 goto exit;
90
91exit:
92 if( ret != 0 )
93 mbedtls_psa_crypto_free( );
94 return( mbedtls_to_psa_error( ret ) );
95}
96
97#endif /* MBEDTLS_PSA_CRYPTO_C */