Skip to content

Commit

Permalink
[for fleet provisioning with CSR to support write key and certificate…
Browse files Browse the repository at this point in the history
… to disk] support optional write generated private key (#183)

* added optional support for writing to disk GENERATED_PRIVATE_KEY_WRITE_PATH

* just moved include and define to top of C file

* Update source/portable/mbedtls/core_pkcs11_mbedtls.c

Co-authored-by: Soren Ptak <[email protected]>

* Update source/portable/mbedtls/core_pkcs11_mbedtls.c

Co-authored-by: Soren Ptak <[email protected]>

* added warning when GENERATED_PRIVATE_KEY_WRITE_PATH defined

* Uncrustify: triggered by comment.

* empty commit to trigger CI

---------

Co-authored-by: Giuseppe Penone <[email protected]>
Co-authored-by: Soren Ptak <[email protected]>
Co-authored-by: GitHub Action <[email protected]>
Co-authored-by: ActoryOu <[email protected]>
  • Loading branch information
5 people authored Nov 9, 2023
1 parent fd53f1b commit c671c11
Showing 1 changed file with 41 additions and 0 deletions.
41 changes: 41 additions & 0 deletions source/portable/mbedtls/core_pkcs11_mbedtls.c
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,12 @@
/* C runtime includes. */
#include <string.h>

#if defined( GENERATED_PRIVATE_KEY_WRITE_PATH )
#warning "GENERATED_PRIVATE_KEY_WRITE_PATH was defined. C_GenerateKeyPair will write generated private keys to that filepath"
#include <errno.h>
#define PRIV_KEY_BUFFER_LENGTH 2048
#endif /* defined( GENERATED_PRIVATE_KEY_WRITE_PATH ) */

/*-----------------------------------------------------------*/

/**
Expand Down Expand Up @@ -5676,6 +5682,41 @@ CK_DECLARE_FUNCTION( CK_RV, C_GenerateKeyPair )( CK_SESSION_HANDLE hSession,
mbedtlsLowLevelCodeOrDefault( lMbedTLSResult ) ) );
xResult = CKR_FUNCTION_FAILED;
}
else
{
#if defined( GENERATED_PRIVATE_KEY_WRITE_PATH )
char privatekey[ PRIV_KEY_BUFFER_LENGTH ];
lMbedTLSResult = mbedtls_pk_write_key_pem( &xCtx, privatekey, PRIV_KEY_BUFFER_LENGTH );

if( lMbedTLSResult == 0 )
{
size_t privatekeyLength = strlen( privatekey );
FILE * fp = fopen( GENERATED_PRIVATE_KEY_WRITE_PATH, "w" );

if( NULL != fp )
{
const size_t writtenBytes = fwrite( privatekey, 1u, privatekeyLength, fp );

if( writtenBytes == privatekeyLength )
{
LogInfo( ( "Wrote the generated private key to %s successfully.", GENERATED_PRIVATE_KEY_WRITE_PATH ) );
}
else
{
LogError( ( "Could not write to %s. Error: %s.", GENERATED_PRIVATE_KEY_WRITE_PATH, strerror( errno ) ) );
}

fclose( fp );
}
else
{
LogError( ( "Could not open %s. Error: %s.", GENERATED_PRIVATE_KEY_WRITE_PATH, strerror( errno ) ) );
}
}
#else /* if defined( GENERATED_PRIVATE_KEY_WRITE_PATH ) */
LogInfo( ( "NOTE: define GENERATED_PRIVATE_KEY_WRITE_PATH in order to have the private key written to disk." ) );
#endif // GENERATED_PRIVATE_KEY_WRITE_PATH
}
}

if( xResult == CKR_OK )
Expand Down

0 comments on commit c671c11

Please sign in to comment.