Mbed TLS中关于密钥的处理

使用过程中,我们可能会需要直接从二进制格式得到所需要的密钥。

 

 1 int binary_pk_get_public_key( mbedtls_pk_context *ctx, const unsigned char *pModulus, const unsigned char *pPublicExponent)
 2 {
 3     int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED;
 4     size_t n;
 5     mbedtls_rsa_context *pRSAKey;
 6 
 7     PK_VALIDATE_RET( ctx != NULL );
 8 
 9     mbedtls_pk_type_t pk_alg = MBEDTLS_PK_RSA;
10     const mbedtls_pk_info_t *pk_info;
11 
12     if( ( pk_info = mbedtls_pk_info_from_type( pk_alg ) ) == NULL )
13         return( MBEDTLS_ERR_PK_UNKNOWN_PK_ALG );
14 
15     if( ( ret = mbedtls_pk_setup( ctx, pk_info ) ) != 0 ) /* this will alloc the memory */
16         return( ret );
17 
18     pRSAKey = ctx->pk_ctx; /* manipulate the underlying key as RSA key */
19     pRSAKey->ver = 0; /* hard-coded */
20     pRSAKey->len = 256; /* hard-coded */
21 
22     ret = mbedtls_mpi_read_binary( &pRSAKey->N, pModulus, 257); /* please refer to public key format. */
23     ret = mbedtls_mpi_read_binary( &pRSAKey->E, pPublicExponent, 3); /* please refer to public key format. */
24 
25     memcpy(&g_TestRSAKey, ctx->pk_ctx, sizeof(g_TestRSAKey)); //xxx debug-purpose only.
26 
27     return( ret );
28 }

参考资料:《OpenSSL与网络信息安全》 王海志 编著 清华大学出版社 北京交通大学出版社

https://tls.mbed.org/

posted @ 2021-03-24 11:03  panrui  阅读(1002)  评论(0编辑  收藏  举报