15:21 9nov

Dependencies:   mbed mbedtls

main.cpp

Committer:
kpan
Date:
2018-11-09
Revision:
5:cc8680cda38f
Parent:
4:98332985e06f
Child:
6:13ef02c7dd17

File content as of revision 5:cc8680cda38f:

#include "mbed.h"
#include "mbedtls/pk.h"
#include "mbedtls/ctr_drbg.h"
PwmOut r(LED_RED);
PwmOut g(LED_GREEN);
PwmOut b(LED_BLUE);
Serial pc(USBTX, USBRX);
int main()
{
    pc.printf("INITIALIZING...");
    wait(1);
    r = g = b = 1;
    g = 0;
    int ret = 0;
    char errbuf[] = "";
    mbedtls_pk_context pk;

    mbedtls_pk_init( &pk );
    const unsigned char key[]="-----BEGIN RSA PUBLIC KEY-----"
                              "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDMYfnvWtC8Id5bPKae5yXSxQTt"
                              "+Zpul6AnnZWfI2TtIarvjHBFUtXRo96y7hoL4VWOPKGCsRqMFDkrbeUjRrx8iL91"
                              "4/srnyf6sh9c8Zk04xEOpK1ypvBz+Ks4uZObtjnnitf0NBGdjMKxveTq+VE7BWUI"
                              "yQjtQ8mbDOsiLLvh7wIDAQAB"
                              "-----END RSA PUBLIC KEY-----";


    /*
     * Read the RSA public key
     */
    if( ( ret = mbedtls_pk_parse_public_key( &pk, key,sizeof(key)) ) != 0 ) {
        printf( " failed\n  ! mbedtls_pk_parse_public_key returned -0x%04x\n", -ret );
        g = b = 1;
        r = 0;
        goto exit;
    }

    unsigned char buf[MBEDTLS_MPI_MAX_SIZE];
    size_t olen = 0;

    /*
     * Calculate the RSA encryption of the data.
     */
    pc.printf("\n  . Generating the encrypted value" );
    fflush( stdout );
    const unsigned char to_encrypt[] = "HelloWorld";
    mbedtls_ctr_drbg_context ctr_drbg;

    if( ( ret = mbedtls_pk_encrypt( &pk, to_encrypt, sizeof(to_encrypt),
                                    buf, &olen, sizeof(buf),
                                    mbedtls_ctr_drbg_random, &ctr_drbg ) ) != 0 ) {
        mbedtls_strerror( ret, errbuf, 200 );
        pc.printf( " failed\n  ! mbedtls_pk_encrypt returned -0x%04x\n%s\n", -ret, errbuf );
        mbedtls_printf("Last error was: -0x%04x - %s\n\n", (int) -ret, errbuf );

        r = g = 1;
        b = 0;
        goto exit;
    }
exit:
    return 0;
}