中级
30 分钟

使用 SE050 Plug&Trust 和 TM4C1294NCPDT 提升物联网安全性

释放每个字节的信任

Plug&Trust Click with Fusion for Tiva v8

已发布 6月 24, 2024

点击板

Plug&Trust Click

开发板

Fusion for Tiva v8

编译器

NECTO Studio

微控制器单元

TM4C1294NCPDT

为您的物联网设备建立牢不可破的防护屏障,确保敏感数据、交易和通信免受威胁。

A

A

硬件概览

它是如何工作的?

Plug&Trust Click基于SE050C,这是一个即用型物联网安全元件解决方案,提供IC级别的信任根,为物联网系统提供NXP Semiconductors最新的边缘到云端安全能力。它设计用于作为物联网系统的一部分,作为附加到主MCU的辅助安全设备。它提供增强的通用标准EAL 6+安全认证,支持RSA和ECC非对称加密算法,具有高密钥长度和面向未来的ECC曲线。最新的安全措施保护IC免受复杂的非侵入性和侵入性攻击场景的影响。SE050C是一个即插即用的解决方案,带有JavaCard操作系统和优化的预安装物联网安全应用小程序。为了支持在物联网应用中服务最广泛

的用例范围,SE050C有多种针对针兼容的配置,包括支持直接连接到设备的传感器、I2C控制器或非接触接口的版本。Plug&Trust Click通过标准I2C 2线接口与MCU通信,其中主控制器表示控制器,Click板表示目标设备。除了与主控制器的强制连接外,这个Click板™还可以通过标有I2C Master的1x4公头上的独立I2C接口引脚连接到传感器节点或类似元素。在这种情况下,SE050C设备是控制器设备,而传感器节点表示目标设备。此外,这个Click板™允许用户通过板载SMD跳线选择适当的I2C通信速度,跳线标有I2C SPEED,正确位置标有400Kb和3.4Mb。

注意,所有跳线必须对齐到同一侧,否则Click板™可能会无响应。另一方面,标有EN并连接到mikroBUS™插座CS引脚的关闭引脚优化了功耗,用于电源开/关,而RST引脚在I2C模式下无功能。这个Click板还配有板载天线,通过标有ANTENNA和SE050C的开关提供与外部设备(如智能手机)的无线接口,通过将其设置为ON或OFF位置来激活天线本身。这个Click板™只能在3.3V逻辑电压下工作。在使用不同逻辑电平的MCU之前,板子必须进行适当的逻辑电平转换。此外,它配备了包含函数和示例代码的库,可用作进一步开发的参考。

Plug&Trust Click hardware overview image

功能概述

开发板

Fusion for TIVA v8 是一款专为快速开发嵌入式应用的需求而特别设计的开发板。它支持广泛的微控制器,如不同的32位ARM® Cortex®-M基础MCUs,来自Texas Instruments,无论它们的引脚数量如何,并且具有一系列独特功能,例如首次通过WiFi网络实现的嵌入式调试器/程序员。开发板布局合理,设计周到,使得最终用户可以在一个地方找到所有必要的元素,如开关、按钮、指示灯、连接器等。得益于创新的制造技术,Fusion for TIVA v8 提供了流畅而沉浸式的工作体验,允许在任何情况下、任何地方、任何

时候都能访问。Fusion for TIVA v8开发板的每个部分都包含了使同一板块运行最高效的必要组件。一个先进的集成CODEGRIP程序/调试模块提供许多有价值的编程/调试选项,包括对JTAG、SWD和SWO Trace(单线输出)的支持,并与Mikroe软件环境无缝集成。此外,它还包括一个干净且调节过的开发板电源供应模块。它可以使用广泛的外部电源,包括电池、外部12V电源供应和通过USB Type-C(USB-C)连接器的电源。通信选项如USB-UART、USB HOST/DEVICE、CAN(如果MCU卡支持的话)和以

太网也包括在内。此外,它还拥有广受好评的 mikroBUS™标准,为MCU卡提供了标准化插座(SiBRAIN标准),以及两种显示选项,用于TFT板线产品和基于字符的LCD。Fusion for TIVA v8 是Mikroe快速开发生态系统的一个组成部分。它由Mikroe软件工具原生支持,得益于大量不同的Click板™(超过一千块板),其数量每天都在增长,它涵盖了原型制作和开发的许多方面。

Fusion for Tiva v8 horizontal image

微控制器概述 

MCU卡片 / MCU

default

类型

8th Generation

建筑

ARM Cortex-M4

MCU 内存 (KB)

1024

硅供应商

Texas Instruments

引脚数

128

RAM (字节)

262144

使用的MCU引脚

mikroBUS™映射器

NC
NC
AN
Reset
PK3
RST
Enable
PH0
CS
NC
NC
SCK
NC
NC
MISO
NC
NC
MOSI
Power Supply
3.3V
3.3V
Ground
GND
GND
NC
NC
PWM
NC
NC
INT
NC
NC
TX
NC
NC
RX
I2C Clock
PD2
SCL
I2C Data
PD3
SDA
NC
NC
5V
Ground
GND
GND
1

“仔细看看!”

Click board™ 原理图

Plug&Trust Click Schematic schematic

一步一步来

项目组装

Fusion for PIC v8 front image hardware assembly

从选择您的开发板和Click板™开始。以Fusion for Tiva v8作为您的开发板开始

Fusion for PIC v8 front image hardware assembly
GNSS2 Click front image hardware assembly
SiBRAIN for PIC32MZ1024EFK144 front image hardware assembly
v8 SiBRAIN Access MB 1 - upright/background hardware assembly
Necto image step 2 hardware assembly
Necto image step 3 hardware assembly
Necto image step 4 hardware assembly
NECTO Compiler Selection Step Image hardware assembly
NECTO Output Selection Step Image hardware assembly
Necto image step 6 hardware assembly
Necto image step 7 hardware assembly
Necto image step 8 hardware assembly
Necto image step 9 hardware assembly
Necto image step 10 hardware assembly
Necto PreFlash Image hardware assembly

实时跟踪您的结果

应用程序输出

1. 应用程序输出 - 在调试模式下,“应用程序输出”窗口支持实时数据监控,直接提供执行结果的可视化。请按照提供的教程正确配置环境,以确保数据正确显示。

2. UART 终端 - 使用UART Terminal通过USB to UART converter监视数据传输,实现Click board™与开发系统之间的直接通信。请根据项目需求配置波特率和其他串行设置,以确保正常运行。有关分步设置说明,请参考提供的教程

3. Plot 输出 - Plot功能提供了一种强大的方式来可视化实时传感器数据,使趋势分析、调试和多个数据点的对比变得更加直观。要正确设置,请按照提供的教程,其中包含使用Plot功能显示Click board™读数的分步示例。在代码中使用Plot功能时,请使用以下函数:plot(insert_graph_name, variable_name);。这是一个通用格式,用户需要将“insert_graph_name”替换为实际图表名称,并将“variable_name”替换为要显示的参数。

软件支持

库描述

该库包含 Plug&Trust Click 驱动程序的 API。

关键功能:

  • plugntrust_apdu_transfer - 写-读帧数据功能

  • plugntrust_select_card_manager - 选择卡管理器

  • plugntrust_select_applet - 选择Clicks Applet并返回设备发送回主机的信息

开源

代码示例

完整的应用程序代码和一个现成的项目可以通过NECTO Studio包管理器直接安装到NECTO Studio 应用程序代码也可以在MIKROE的GitHub账户中找到。

/*!
 * @file main.c
 * @brief PlugnTrust Click example
 *
 * # Description
 * This application is showcasing basic functionality of Plug&Trust
 * click board. It gets identify data from device, selects card 
 * manager and applet. Then checks free memory, reads all objects and 
 * deletes not reserved ones. After that showcases a few of functionality: 
 *      - Generating random data, 
 *      - Creating, reading and deleteing binary objects, 
 *      - Creating AES symmetrical key and cipher with it;
 * In the end it is showcasing funcionality in the endless loop.
 * 
 *
 * The demo application is composed of two sections :
 *
 * ## Application Init
 * At the start it sets comunication interface from default
 * configuration[I2C]. Reads indetifing data from device, 
 * and then selects Card manager and applet. After that it 
 * reads free presistant memory, reads all objects and deletes
 * objects that are not reserved by the Applet. Then it generates
 * 2 byte of random data, and gets the version information 
 * from the Applet. Thtas followed up with creating binary
 * object and 'MikroE' data is wrriten in it. Then its checked
 * it object is created, and reads data back, in the end its 
 * deleted and checked if it still exists. Finally it creates
 * 128AES key (16bytes), and then it encrypts and then decrypts
 * data with that key, and in the end it deletes that key object.
 *
 * ## Application Task
 * It generates 16bytes of data, writes it in binary object and
 * then reads it and logs it. Then creates AES key and encrypts
 * that random data with it, and then decrypts it. In the end it
 * deletes both AES key object and binary object thats created 
 * at the start of task.
 *
 * @note
 * For more informations and explanations refer to documents 
 * from NXP->AN12413 and UM11225.
 *
 * @author Luka Filipovic
 *
 */

#include "board.h"
#include "log.h"
#include "plugntrust.h"

//Library and log objects
static plugntrust_t plugntrust;
static log_t logger;

//Communication objects
static plugntrust_apdu_t apdu_data;
static plugntrust_frame_data_t frame_data;

//Parsing parameters
#define PARSE_BUF_LEN 0xFF
static uint32_t parse_index = 0;
static uint32_t parse_len = PARSE_BUF_LEN;
static uint8_t parse_data[ PARSE_BUF_LEN ] = { 0 };

/**
 * @brief Reset parse data.
 * @details Clears parse index, buffer and resets @b parse_len.
 * @return Nothing.
 * @note None.
 */
static void reset_parse ( void );

/**
 * @brief Log buffer data to .
 * @details Logs buffer data to UART Terminal
 * @param[in] buf : Buffer to log.
 * @param[in] buf_len : Length of buffer to log.
 * @return Nothing.
 * @note None.
 */
static void log_buf_hex ( uint8_t *buf, uint8_t buf_len );

/**
 * @brief Log status data.
 * @details Log status data from @b apdu_data.
 * @return Nothing.
 * @note None.
 */
static void log_status ( void );

/**
 * @brief Log frame data.
 * @details Logs data from @b frame_data.
 * @return Nothing.
 * @note None.
 */
static void log_rsp_data_default ( void );

/**
 * @brief End APDU session.
 * @details Sends request to end APDU session.
 * @return Nothing.
 * @note None.
 */
static void end_apdu_session ( void );

/**
 * @brief Send request to reset device.
 * @details Sends request to reset device and logs ATR data.
 * @return Nothing.
 * @note None.
 */
static void soft_reset( void );

/**
 * @brief Check presistant free memory.
 * @details Sends request to check presistant free
 * memory from Applet, and logs it.
 * @return Nothing.
 * @note None.
 */
static void check_free_memory ( void );

/**
 * @brief Reads 2 bytes of random data from Applet.
 * @details Sends request to Applet to get 2 bytes of 
 * random data, and logs it.
 * @return Nothing.
 * @note None.
 */
static void get_random ( void );

/**
 * @brief Read Object with UID.
 * @details Checks if Object with UID exists and then
 * reads its data, and logs it.
 * @return Nothing.
 * @note None.
 */
static void read_uid_object ( void );

/**
 * @brief Checks the current version of the Applet.
 * @details Send request to check the current version 
 * of Applet and logs return data.
 * @return Nothing.
 * @note None.
 */
static void get_version ( void );

/**
 * @brief Get identify data from device.
 * @details Sends request to get identification data 
 * from device, and logs data.
 * @return Nothing.
 * @note None.
 */
static void get_data_identify ( void );

/**
 * @brief Create, write, read, and delete binary object.
 * @details Creates and writes data to binary object. 
 * Checks if that object exists. Reads that binary object,
 * and then delets it, and checks if its deleted. 
 * Every step and status will be logged.
 * @return Nothing.
 * @note None.
 */
static void create_check_delete ( void );

/**
 * @brief List of all Applet objects and delete if not reserved.
 * @details Create one random object and then lists all objects
 * and delete ones that are not reserved.
 * @return Nothing.
 * @note None.
 */
static void list_and_delete_objects ( void );

/**
 * @brief Select Applet.
 * @details Select applet and log version info.
 * @return Nothing.
 * @note None.
 */
static void select_applet ( void );

/**
 * @brief Create AES key, Encrypt and Decrypt data, and delete AES key.
 * @details Creates 128AES Symmetrical key. 
 * Encrypts data with it. Decrypt data with that key. 
 * and in the end delete that AES key. Logs every status in the process.
 * @return Nothing.
 * @note None.
 */
static void aes_cipher ( void );

/**
 * @brief Select Card manager.
 * @details Select Card manager without return value request
 * @return Nothing.
 * @note None.
 */
static void select_card_manger ( void );

/**
 * @brief Create 128 AES symmetrical key.
 * @details Create 128 AES symetrical key and sets its value.
 * @param[in] aes_id : Object ID.
 * @param[in] aes_key : AES key value.
 * @return Nothing.
 * @note AES key value because it's 128 key should be 16 bytes of data.
 */
static void create_128_aes_key ( uint32_t aes_id, uint8_t *aes_key );

/**
 * @brief Encrypt or decrypt data with AES key.
 * @details Encrypt or decrypt data with AES key.
 * @param[in] aes_id : Object ID.
 * @param[in] cipher_type : Encrypt or decrypt macro @b[PLUGNTRUST_P2_ENCRYPT_ONESHOT] || @b[PLUGNTRUST_P2_DECRYPT_ONESHOT].
 * @param[in] data_in : Input buffer.
 * @param[out] data_out : Output buffer.
 * @return @li @c  0 - Success,
 *         @li @c -1 - Error.
 * @note None.
 */
static err_t cipher_data_with_aes_key ( uint32_t aes_id, uint8_t cipher_type, uint8_t *data_in, uint8_t *data_out );

void application_init ( void ) 
{
    log_cfg_t log_cfg;  /**< Logger config object. */
    plugntrust_cfg_t plugntrust_cfg;  /**< Click config object. */
    /** 
     * Logger initialization.
     * Default baud rate: 115200
     * Default log level: LOG_LEVEL_DEBUG
     * @note If USB_UART_RX and USB_UART_TX 
     * are defined as HAL_PIN_NC, you will 
     * need to define them manually for log to work. 
     * See @b LOG_MAP_USB_UART macro definition for detailed explanation.
     */
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, " Application Init " );
    // Click initialization.
    plugntrust_cfg_setup( &plugntrust_cfg );
    PLUGNTRUST_MAP_MIKROBUS( plugntrust_cfg, MIKROBUS_1 );
    err_t init_flag = plugntrust_init( &plugntrust, &plugntrust_cfg );
    if ( init_flag == I2C_MASTER_ERROR ) 
    {
        log_error( &logger, " Application Init Error. " );
        log_info( &logger, " Please, run program again... " );

        for ( ; ; );
    } 
    
    frame_data.apdu = &apdu_data;
    
    plugntrust_default_cfg ( &plugntrust );
    
    if ( PLUGNTRUST_INTERFACE_ISO14443 == plugntrust.interface )
    {
        log_info( &logger, " ISO14443 Interface active..." );
        for ( ; ; );
    }
    
    soft_reset( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    get_data_identify( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    select_card_manger( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    select_applet( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    check_free_memory( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    list_and_delete_objects( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    get_random( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    read_uid_object( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    get_version(  );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    create_check_delete( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    aes_cipher( );
    
    log_info( &logger, " Application Task " );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
}

void application_task ( void ) 
{
    #define DATA_LEN 16
    static uint8_t aes_value[ DATA_LEN ]    = { 0x40, 0x41, 0x42, 0x43,0x44, 0x45, 0x46, 0x47,
                                                0x48, 0x49, 0x4A, 0x4B,0x4C, 0x4D, 0x4E, 0x4F };
    static uint32_t binary_id               = 0xBBBBBBBBul;
    static uint32_t aes_id                  = 0xCCCCCCCCul;
    uint8_t random_data[ DATA_LEN ]         = { 0 };
    uint8_t read_data[ DATA_LEN ]           = { 0 };
    uint8_t encrypted_data[ DATA_LEN ]      = { 0 };
    uint32_t read_len = DATA_LEN;
    
    if ( PLUGNTRUST_OK == plugntrust_get_random_numbers( &plugntrust, random_data, DATA_LEN ) )
    {
        log_printf( &logger, " > Generated random data: 0x" );
        log_buf_hex( random_data, DATA_LEN );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Random" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OBJECT_DOESNT_EXIST == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " Write random data to binary object...\r\n" );
        if ( PLUGNTRUST_OK != plugntrust_write_binary_object( &plugntrust, binary_id, 0, DATA_LEN, random_data ) )
        {
            log_error( &logger, " Write Binary" );
        }
        else
        {
            log_info( &logger, " Status OK" );
        }
    }
    else
    {
        log_error( &logger, " Binary object already exist" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        if ( PLUGNTRUST_OK == plugntrust_read_object( &plugntrust, binary_id, 0, 0, read_data, &read_len ) )
        {
            log_printf( &logger, " > Read data from binary object: 0x" );
            log_buf_hex( read_data, read_len );
            log_printf( &logger, "\r\n" );
        }
        else
        {
            log_error( &logger, " Read binray object" );
        } 
    }
    else
    {
        log_error( &logger, " Binary object doesn't exist" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    log_printf( &logger, " Create AES key...\r\n" );
    create_128_aes_key( aes_id, aes_value );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OK == cipher_data_with_aes_key( aes_id, PLUGNTRUST_P2_ENCRYPT_ONESHOT, read_data, encrypted_data ) )
    {
        log_printf( &logger, " > Encrypted data: 0x" );
        log_buf_hex( encrypted_data, DATA_LEN );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Encrypting data" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OK == cipher_data_with_aes_key( aes_id, PLUGNTRUST_P2_DECRYPT_ONESHOT, encrypted_data, read_data ) )
    {
        log_printf( &logger, " > Decrypted data: 0x" );
        log_buf_hex( read_data, DATA_LEN );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Decrypting data" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    log_printf( &logger, " Delete Binary and AES object...\r\n" );
    if ( ( PLUGNTRUST_OK != plugntrust_delete_object( &plugntrust, binary_id ) ) || ( PLUGNTRUST_OK != plugntrust_delete_object( &plugntrust, aes_id ) ) )
    {
        log_error( &logger, " Deleting objects" );
    }
    log_printf( &logger, "*****************************************************************************\r\n" );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
}

int main ( void ) 
{
    /* Do not remove this line or clock might not be set correctly. */
    #ifdef PREINIT_SUPPORTED
    preinit();
    #endif
    
    application_init( );
    
    for ( ; ; ) 
    {
        application_task( );
    }

    return 0;
}

static void reset_parse ( void )
{
    parse_index = 0;
    parse_len = PARSE_BUF_LEN;
    memset( parse_data, 0, parse_len );
}

static void log_buf_hex ( uint8_t *buf, uint8_t buf_len )
{
    for ( uint8_t i = 0; i < buf_len; i++ )
    {
        log_printf( &logger, "%0.2X", ( uint16_t )buf[ i ] );
    }
}

static void log_status ( void )
{
    if ( ( ( frame_data.pcb & PLUGNTRUST_PCB_BLOCK_R ) != PLUGNTRUST_PCB_BLOCK_R ) && 
         ( ( frame_data.pcb & PLUGNTRUST_PCB_BLOCK_S ) != PLUGNTRUST_PCB_BLOCK_S ) )
    {
        switch ( frame_data.apdu->status )
        {
            case PLUGNTRUST_SW_NOERROR:
            {
                log_info( &logger, " Status OK" );
                break;
            }
            default:
            {
                log_error( &logger, " Status: 0x%.4X", frame_data.apdu->status );
            }
        }
    }
}

static void log_rsp_data_default ( void )
{
    log_printf( &logger, " >NAD: 0x%0.2X \r\n", ( uint16_t )frame_data.nad );
    log_printf( &logger, " >PCB: 0x%0.2X \r\n", ( uint16_t )frame_data.pcb );
    log_printf( &logger, " >LEN: 0x%0.2X \r\n", ( uint16_t )frame_data.len );
    if ( frame_data.len > 0 )
    {
        log_printf( &logger, " >APDU: 0x" );
    }
    log_buf_hex( frame_data.apdu->payload, frame_data.len );
    if ( frame_data.len > 0 )
    {
        log_printf( &logger, " \r\n" );
    }
    log_printf( &logger, " >CRC: 0x%0.4X \r\n", frame_data.crc16 );
    log_printf( &logger, "************************************************************************\r\n" );
}

static void soft_reset( void )
{       
    log_info( &logger, " Resetting device..." );
    plugntrust_atr_t atr_data;
    if ( PLUGNTRUST_OK == plugntrust_sw_reset( &plugntrust, &atr_data ) )
    {
        log_printf( &logger, " > Protocol version: %d\r\n", ( uint16_t )atr_data.protocol_version );
        log_printf( &logger, " > Length of Data Link Layer Parameters value: %d\r\n", 
                    ( uint16_t ) atr_data.data_link_layer_parameters_len );
        log_printf( &logger, " > Data Link Layer Parameters: 0x" );
        log_buf_hex( atr_data.data_link_layer_parameters, atr_data.data_link_layer_parameters_len );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Physical Layer ID: %d\r\n", ( uint16_t )atr_data.physical_layer_id );
        log_printf( &logger, " > Length of Physical Layer Parameters value: %d\r\n", 
                    ( uint16_t ) atr_data.physical_layer_parameters_len );
        log_printf( &logger, " > Physical Layer Parameters: 0x" );
        log_buf_hex( atr_data.physical_layer_parameters, atr_data.physical_layer_parameters_len );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Length of Historical Bytes value: %d\r\n", ( uint16_t ) atr_data.historical_len );
        log_printf( &logger, " > Historical Bytes: 0x" );
        log_buf_hex( atr_data.historical, atr_data.historical_len );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Resetting..." );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void check_free_memory ( void )
{
    log_info( &logger, " Check free memory" );
    uint16_t free_memory = 0;
    if ( PLUGNTRUST_OK == plugntrust_get_free_memory( &plugntrust, PLUGNTRUST_MEM_TRANSIENT_DESELECT, &free_memory ) )
    {
        log_printf( &logger, " > Free Memory: %d\r\n", free_memory );
    }
    else
    {
        log_error( &logger, " Reading Memory" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void get_random ( void )
{
    log_info( &logger, " Get Random" );
    if ( PLUGNTRUST_OK == plugntrust_get_random_numbers( &plugntrust, parse_data, 2 ) )
    {
        log_printf( &logger, " > Random data: 0x" );
        log_buf_hex( parse_data, 2 );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Random" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void read_uid_object ( void )
{
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, PLUGNTRUST_APPLET_RES_ID_UNIQUE_ID ) )
    {
        log_info( &logger, " Read object with Unique ID" );
        
        if ( PLUGNTRUST_OK == plugntrust_read_object( &plugntrust, 
            PLUGNTRUST_APPLET_RES_ID_UNIQUE_ID, 0, 0, parse_data, &parse_len ) )
        {
            log_printf( &logger, " > Object data: 0x" );
            log_buf_hex( parse_data, parse_len );
            log_printf( &logger, "\r\n" );
        }
        else
        {
            log_error( &logger, " Read object with Unique ID" );
        } 
        log_printf( &logger, "************************************************************************\r\n" );
    }
}

static void get_version ( void )
{
    log_info( &logger, " Get Version" );
    plugntrust_version_info_t ver_info;
    if ( PLUGNTRUST_OK == plugntrust_get_applet_info( &plugntrust, &ver_info ) )
    {
        log_printf( &logger, " > Applet Version = %d.%d.%d\r\n", ( uint16_t )ver_info.major_version, 
                                                                 ( uint16_t )ver_info.minor_version, 
                                                                 ( uint16_t )ver_info.patch_version );
        log_printf( &logger, " > AppletConfig = 0x%0.4X\r\n", ver_info.applet_config );
        log_printf( &logger, " > SecureBox = 0x%0.4X\r\n", ver_info.secure_box );
    }
    else
    {
        log_error( &logger, " Version Info" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void get_data_identify ( void )
{
    //select card
    select_card_manger( );
    end_apdu_session( );
    //get data identify
    typedef struct
    {
        uint8_t tag_value_proprietary_data;//0xFE Tag value - proprietary data Only present if class byte is 0x80
        uint8_t length_of_following_data;//0x49 / 0x45 Length of following data Only present if class byte is 0x80
        uint8_t tag_card_identification_data[0x02];//0xDF28 Tag card identification data Only present if class byte is 0x80
        uint8_t length_of_card_identification_data;//0x46 Length of card identification data Only present if class byte is 0x80
        
        uint8_t tag_configuration_id;//0x01 Tag configuration ID Identifies the configuration content
        uint8_t length_configuration_id; //0x0C Length configuration ID
        uint8_t configuration_id[ 0x0C ];  //var Configuration ID
        
        uint8_t tag_patch_id;    //0x02 Tag patch ID Identifies the patch level
        uint8_t length_patch_id; //0x08 Length patch ID
        uint8_t patch_id[ 0x08 ];  //var Patch ID
        
        uint8_t tag_platform_build_id1;//0x03 Tag platform build ID1 Identifies the JCOP platform
        uint8_t length_platform_build_id; //0x18 Length platform build ID
        uint8_t platform_build_id[ 0x18 ];  //var Platform build ID
        
        uint8_t tag_fips_mode;    //0x052 Tag FIPS mode FIPS mode active
        uint8_t length_fips_mode; //0x01 Length FIPS mode
        uint8_t fips_mode;//var FIPS mode 0x00 - FIPS mode not active, 0x01 - FIPS mode active
        
        uint8_t tag_pre_perso_state;//0x07 Tag pre-perso state Lists pre-perso state
        uint8_t length_pre_perso_state;//0x01 Length pre-perso state
        //var Bit mask of pre-perso state bit0 = 1 = config module available,
        //  bit1 = 1 = transport state is active.
        //  Unused bits are set to 0x0.
        uint8_t bit_mask_of_pre_perso_state;

        uint8_t tag_rom_id;    //'08' Tag ROM ID Indentifies the ROM content
        uint8_t length_rom_id; //'08' Length ROM ID Normal ending
        uint8_t rom_id[ 0x08 ];  //var ROM ID
        uint8_t status_word_sw[ 0x02 ]; //9000h Status Word (SW)
    } identify_rsp_t;
    
    identify_rsp_t identify_rsp = {0};
    uint32_t prsp_len = sizeof(identify_rsp_t);
    log_info( &logger, " Get data identify" );
    frame_data.pcb = PLUGNTRUST_PCB_BLOCK_I;
    frame_data.len = 8;
    frame_data.apdu->cla = PLUGNTRUST_CLA_NOT_SECURE;
    frame_data.apdu->ins = 0xCA;
    frame_data.apdu->p1 = 0x00;
    frame_data.apdu->p2 = 0xFE;
    frame_data.apdu->payload_len = 0x02;
    frame_data.apdu->rsp_len = 0x00;
    uint8_t df28[ 2 ] = { 0xDF, 0x28 };
    memcpy( frame_data.apdu->payload, df28, 2 );
    plugntrust_apdu_transfer( &plugntrust, &frame_data );
    if ( frame_data.len == prsp_len )
    {
        memcpy( (uint8_t *)&identify_rsp, frame_data.apdu->payload, prsp_len );
        log_printf( &logger, " > Tag value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_value_proprietary_data );
        log_printf( &logger, " > Length value: %d\r\n", ( uint16_t ) identify_rsp.length_of_following_data );
        log_printf( &logger, " > Tag Card ID value: 0x" );
        log_buf_hex( identify_rsp.tag_card_identification_data, 2 );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Length of Card ID value: %d\r\n", ( uint16_t ) identify_rsp.length_of_card_identification_data );
        log_printf( &logger, " > Tag of Configuration ID value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_configuration_id );
        log_printf( &logger, " > Length of Configuration ID value: %d\r\n", ( uint16_t ) identify_rsp.length_configuration_id );
        log_printf( &logger, " > Configuration ID: 0x" );
        log_buf_hex( identify_rsp.configuration_id, identify_rsp.length_configuration_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of Patch ID value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_patch_id );
        log_printf( &logger, " > Length of Patch ID value: %d\r\n", ( uint16_t ) identify_rsp.length_patch_id );
        log_printf( &logger, " > Patch ID: 0x" );
        log_buf_hex( identify_rsp.patch_id, identify_rsp.length_patch_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of Platform Build ID1 value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_platform_build_id1 );
        log_printf( &logger, " > Length of Platform Build ID1 value: %d\r\n", ( uint16_t ) identify_rsp.length_platform_build_id );
        log_printf( &logger, " > Platform Build ID1: 0x" );
        log_buf_hex( identify_rsp.platform_build_id, identify_rsp.length_platform_build_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of FIPS Mode value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_fips_mode );
        log_printf( &logger, " > Length of FIPS Mode value: %d\r\n", ( uint16_t ) identify_rsp.length_fips_mode );
        log_printf( &logger, " > FIPS Mode: 0x" );
        log_buf_hex( &identify_rsp.fips_mode, identify_rsp.length_fips_mode );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of Pre-Preso State value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_pre_perso_state );
        log_printf( &logger, " > Length of Pre-Preso State value: %d\r\n", ( uint16_t ) identify_rsp.length_pre_perso_state );
        log_printf( &logger, " > Pre-Preso State: 0x" );
        log_buf_hex( &identify_rsp.bit_mask_of_pre_perso_state, identify_rsp.length_pre_perso_state );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of ROM ID value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_rom_id );
        log_printf( &logger, " > Length of ROM ID value: %d\r\n", ( uint16_t ) identify_rsp.length_rom_id );
        log_printf( &logger, " > ROM ID: 0x" );
        log_buf_hex( identify_rsp.rom_id, identify_rsp.length_rom_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Status Word: 0x" );
        log_buf_hex( identify_rsp.status_word_sw, 2 );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Size Error" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
    end_apdu_session( );
}

static void end_apdu_session ( void )
{
    if ( PLUGNTRUST_OK != plugntrust_end_apdu_session( &plugntrust ) )
    {
        log_error( &logger, " End APDU session" );
    }
}

static void create_check_delete ( void )
{    
    //create binary object
    log_info( &logger, " Write Binary" );
    uint8_t data_buf[ 7 ] = "MikroE";
    uint32_t binary_id = 0xAAAAAAAAul;

    if ( PLUGNTRUST_OK != plugntrust_write_binary_object( &plugntrust, 
            binary_id, 0, 6, data_buf ) )
    {
        log_error( &logger, " Write Binary" );
    }
    log_printf( &logger, "************************************************************************\r\n" );

    //check if object exists
    log_info( &logger, " Check object exists" );
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " > Object exist\r\n" );
    }
    else
    {
        log_printf( &logger, " > Object doesn't exist\r\n" );
    } 
    log_printf( &logger, "************************************************************************\r\n" );
    
    //read binary object
    log_info( &logger, " Read object" );
    reset_parse();
    if ( PLUGNTRUST_OK == plugntrust_read_object( &plugntrust, 
            binary_id, 0, 0, parse_data, &parse_len ) )
    {
        log_printf( &logger, " > Object data: %s\r\n", parse_data );
    }
    else
    {
        log_error( &logger, " Read binary object" );
    } 
    log_printf( &logger, "************************************************************************\r\n" );
    //delete object
    log_info( &logger, " Delete Secure Object" );
    if ( PLUGNTRUST_OK == plugntrust_delete_object( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " Object 0x%0.8LX deleted\r\n", binary_id );
    }
    else
    {
        log_error( &logger, " Delete Object"  );
    }
    log_printf( &logger, "************************************************************************\r\n" );
    //check if object exists
    log_info( &logger, " Check object exists" );
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " > Object exist\r\n" );
    }
    else
    {
        log_printf( &logger, " > Object doesn't exist\r\n" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void list_and_delete_objects( void )
{     
    plugntrust_write_binary_object( &plugntrust, 0xAABBCCDDul, 0, 4, "Data" );
    
    log_info( &logger, " Get Object list" );  
    uint32_t ids[ 30 ] = { 0 };
    uint8_t len = 0;
    if ( PLUGNTRUST_OK == plugntrust_object_id_list( &plugntrust, ids, &len ) )
    {
        log_info( &logger, " List len: %d", ( uint16_t )len );
        for ( uint8_t cnt = 0; cnt < len; cnt++ )
        {   //if not NXP defined objectect delete that object
            if ( ( PLUGNTRUST_OBJID_SE05X_APPLET_RES_START != ( PLUGNTRUST_OBJID_APPLET_MASK & ids[ cnt ] ) ) &&
                 ( PLUGNTRUST_SSS_OBJID_DEMO_AUTH_START != ( PLUGNTRUST_OBJID_APPLET_MASK & ids[ cnt ] ) ) &&
                 ( PLUGNTRUST_SSS_OBJID_IOT_HUB_A_START != ( PLUGNTRUST_OBJID_IOT_MASK & ids[ cnt ] ) ) )
            {
                if ( PLUGNTRUST_OK == plugntrust_delete_object( &plugntrust, ids[ cnt ] ) )
                {
                    log_printf( &logger, " > Object Deleted 0x%.8LX\r\n", ids[ cnt ] );
                }
                else
                {
                    log_error( &logger, " Delecte Object  0x%.8LX", ids[ cnt ] );
                }
            }
            else
            {
                log_printf( &logger, " > Object ID: 0x%.8LX\r\n", ids[ cnt ] );
            }
        }
    }
    else
    {
        log_error( &logger, " Object ID List" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void select_applet ( void )
{
    log_info( &logger, " Select SE050 Applet" );
    plugntrust_version_info_t ver_info;
    plugntrust_select_applet( &plugntrust, PLUGNTRUST_PCB_BLOCK_I_NS_ENCODE, &ver_info );
    log_printf( &logger, " > Applet Version = %d.%d.%d\r\n", ( uint16_t )ver_info.major_version, 
                                                             ( uint16_t )ver_info.minor_version, 
                                                             ( uint16_t )ver_info.patch_version );
    log_printf( &logger, " > AppletConfig = 0x%0.4X\r\n", ver_info.applet_config );
    log_printf( &logger, " > SecureBox = 0x%0.4X\r\n", ver_info.secure_box );
    log_printf( &logger, "************************************************************************\r\n" );
}

static void aes_cipher ( void )
{
    //Create AES Key
    log_info( &logger, " Write AES Key" );
    #define AES_DATA_SIZE 16
    uint8_t aes_value[ AES_DATA_SIZE ] = { 0x40, 0x41, 0x42, 0x43,0x44, 0x45, 0x46, 0x47,
                                           0x48, 0x49, 0x4A, 0x4B,0x4C, 0x4D, 0x4E, 0x4F };
    uint32_t symm_id = 0x12345678ul;
    create_128_aes_key( symm_id, aes_value );
    
    //Encrypt Data
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, symm_id ) )
    {
        log_info( &logger, " Encrypt Data" );
        uint8_t data_value[ 16 ] = { ' ', '>', 'P', 'l', 'u', 'g', ' ', '&', ' ', 'T', 'r', 'u', 's', 't', '<', ' ' };
        reset_parse( );
        if ( PLUGNTRUST_OK == cipher_data_with_aes_key( symm_id, PLUGNTRUST_P2_ENCRYPT_ONESHOT, data_value, parse_data ) )
        {
            log_printf( &logger, " > Encrypted data hex: 0x" );
            log_buf_hex( parse_data, AES_DATA_SIZE );
            log_printf( &logger, "\r\n" );
            log_printf( &logger, " > Encrypted data string: %s\r\n", parse_data );
        }
        else
        {
            log_error( &logger, " Parse error" );
        }
    }
    else
    {
        log_printf( &logger, " > Object doesn't exist\r\n" );
    } 
    log_printf( &logger, "************************************************************************\r\n" );

    //Decrypt Data
    log_info( &logger, " Decrypt Data" );
    if ( PLUGNTRUST_OK == cipher_data_with_aes_key( symm_id, PLUGNTRUST_P2_DECRYPT_ONESHOT, parse_data, parse_data ) )
    {
        log_printf( &logger, " > Decrypted data hex: 0x" );
        log_buf_hex( parse_data, parse_len );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Decrypted data string: %s\r\n", parse_data );
    }
    else
    {
        log_error( &logger, " Parse error" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
    
    //Delete Object
    log_info( &logger, " Delete Secure Object" );
    if ( PLUGNTRUST_OK == plugntrust_delete_object( &plugntrust, symm_id ) )
    {
        log_printf( &logger, " Object 0x%0.8LX deleted\r\n", symm_id );
    }
    else
    {
        log_error( &logger, " Delete Object"  );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void select_card_manger ( void )
{
    log_info( &logger, " Select the card manager " );
    if ( PLUGNTRUST_OK != plugntrust_select_card_manager( &plugntrust, PLUGNTRUST_CARD_MANAGER_WITHOUT_RSP, 0, 0 ) )
    {
        log_error( &logger, " Card manager"  );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void create_128_aes_key ( uint32_t aes_id, uint8_t *aes_key )
{
    #define AES_KEY_SIZE 16
    frame_data.pcb = PLUGNTRUST_PCB_BLOCK_I;
    frame_data.apdu->cla = PLUGNTRUST_CLA_NOT_SECURE;
    frame_data.apdu->ins = PLUGNTRUST_INS_WRITE | PLUGNTRUST_INS_TRANSIENT;
    frame_data.apdu->p1 = PLUGNTRUST_P1_AES;
    frame_data.apdu->p2 = PLUGNTRUST_P2_DEFAULT;
    frame_data.apdu->payload_len = 0;//reset apdu payload_len
    frame_data.apdu->rsp_len = 0;//reset apdu le value
    plugntrust_set_tlv_u32( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                            PLUGNTRUST_TLV_TAG_1, aes_id ); //AES key ID
    plugntrust_set_tlv_u8buf( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                            PLUGNTRUST_TLV_TAG_3, aes_key, AES_KEY_SIZE ); //AES key value
    frame_data.len = plugntrust_calculate_apdu_size( frame_data.apdu ); //calculate apdu size
    plugntrust_apdu_transfer( &plugntrust, &frame_data );
    log_status();
    end_apdu_session( );
}

static err_t cipher_data_with_aes_key ( uint32_t aes_id, uint8_t cipher_type, uint8_t *data_in, uint8_t *data_out )
{
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, aes_id ) )//check if object with aes_id exists
    {
        frame_data.pcb = PLUGNTRUST_PCB_BLOCK_I;
        frame_data.apdu->cla = PLUGNTRUST_CLA_NOT_SECURE;
        frame_data.apdu->ins = PLUGNTRUST_INS_CRYPTO;
        frame_data.apdu->p1 = PLUGNTRUST_P1_CIPHER;
        frame_data.apdu->p2 = cipher_type;//PLUGNTRUST_P2_ENCRYPT_ONESHOT || PLUGNTRUST_P2_DECRYPT_ONESHOT
        frame_data.apdu->payload_len = 0;
        frame_data.apdu->rsp_len = 0;
        frame_data.len = 0;
        plugntrust_set_tlv_u32( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                                PLUGNTRUST_TLV_TAG_1, aes_id );//set aes key to be used
        plugntrust_set_tlv_u8( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                                PLUGNTRUST_TLV_TAG_2, PLUGNTRUST_CIPHER_AES_CTR );//set ae cipher type to be used
        plugntrust_set_tlv_u8buf( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                                PLUGNTRUST_TLV_TAG_3, data_in, 16 );//set data to encrypt/decrypt
        frame_data.len = plugntrust_calculate_apdu_size( frame_data.apdu );//calculate apdu data
        frame_data.len++;//increment data
        plugntrust_apdu_transfer( &plugntrust, &frame_data );
        reset_parse( );//reset prase data
        if ( PLUGNTRUST_OK == plugntrust_get_tlv_u8buf( frame_data.apdu->payload, &parse_index, frame_data.len, 
                                                        PLUGNTRUST_TLV_TAG_1, data_out, &parse_len ) )//get encryted/decrypted data
        {
            end_apdu_session( );
            return PLUGNTRUST_OK;
        }
        else
        {
            end_apdu_session( );
            return PLUGNTRUST_ERROR;
        }
    }
    else
    {
        return PLUGNTRUST_ERROR;
    }
}

// ------------------------------------------------------------------------ END
/*!
 * @file main.c
 * @brief PlugnTrust Click example
 *
 * # Description
 * This application is showcasing basic functionality of Plug&Trust
 * click board. It gets identify data from device, selects card 
 * manager and applet. Then checks free memory, reads all objects and 
 * deletes not reserved ones. After that showcases a few of functionality: 
 *      - Generating random data, 
 *      - Creating, reading and deleteing binary objects, 
 *      - Creating AES symmetrical key and cipher with it;
 * In the end it is showcasing funcionality in the endless loop.
 * 
 *
 * The demo application is composed of two sections :
 *
 * ## Application Init
 * At the start it sets comunication interface from default
 * configuration[I2C]. Reads indetifing data from device, 
 * and then selects Card manager and applet. After that it 
 * reads free presistant memory, reads all objects and deletes
 * objects that are not reserved by the Applet. Then it generates
 * 2 byte of random data, and gets the version information 
 * from the Applet. Thtas followed up with creating binary
 * object and 'MikroE' data is wrriten in it. Then its checked
 * it object is created, and reads data back, in the end its 
 * deleted and checked if it still exists. Finally it creates
 * 128AES key (16bytes), and then it encrypts and then decrypts
 * data with that key, and in the end it deletes that key object.
 *
 * ## Application Task
 * It generates 16bytes of data, writes it in binary object and
 * then reads it and logs it. Then creates AES key and encrypts
 * that random data with it, and then decrypts it. In the end it
 * deletes both AES key object and binary object thats created 
 * at the start of task.
 *
 * @note
 * For more informations and explanations refer to documents 
 * from NXP->AN12413 and UM11225.
 *
 * @author Luka Filipovic
 *
 */

#include "board.h"
#include "log.h"
#include "plugntrust.h"

//Library and log objects
static plugntrust_t plugntrust;
static log_t logger;

//Communication objects
static plugntrust_apdu_t apdu_data;
static plugntrust_frame_data_t frame_data;

//Parsing parameters
#define PARSE_BUF_LEN 0xFF
static uint32_t parse_index = 0;
static uint32_t parse_len = PARSE_BUF_LEN;
static uint8_t parse_data[ PARSE_BUF_LEN ] = { 0 };

/**
 * @brief Reset parse data.
 * @details Clears parse index, buffer and resets @b parse_len.
 * @return Nothing.
 * @note None.
 */
static void reset_parse ( void );

/**
 * @brief Log buffer data to .
 * @details Logs buffer data to UART Terminal
 * @param[in] buf : Buffer to log.
 * @param[in] buf_len : Length of buffer to log.
 * @return Nothing.
 * @note None.
 */
static void log_buf_hex ( uint8_t *buf, uint8_t buf_len );

/**
 * @brief Log status data.
 * @details Log status data from @b apdu_data.
 * @return Nothing.
 * @note None.
 */
static void log_status ( void );

/**
 * @brief Log frame data.
 * @details Logs data from @b frame_data.
 * @return Nothing.
 * @note None.
 */
static void log_rsp_data_default ( void );

/**
 * @brief End APDU session.
 * @details Sends request to end APDU session.
 * @return Nothing.
 * @note None.
 */
static void end_apdu_session ( void );

/**
 * @brief Send request to reset device.
 * @details Sends request to reset device and logs ATR data.
 * @return Nothing.
 * @note None.
 */
static void soft_reset( void );

/**
 * @brief Check presistant free memory.
 * @details Sends request to check presistant free
 * memory from Applet, and logs it.
 * @return Nothing.
 * @note None.
 */
static void check_free_memory ( void );

/**
 * @brief Reads 2 bytes of random data from Applet.
 * @details Sends request to Applet to get 2 bytes of 
 * random data, and logs it.
 * @return Nothing.
 * @note None.
 */
static void get_random ( void );

/**
 * @brief Read Object with UID.
 * @details Checks if Object with UID exists and then
 * reads its data, and logs it.
 * @return Nothing.
 * @note None.
 */
static void read_uid_object ( void );

/**
 * @brief Checks the current version of the Applet.
 * @details Send request to check the current version 
 * of Applet and logs return data.
 * @return Nothing.
 * @note None.
 */
static void get_version ( void );

/**
 * @brief Get identify data from device.
 * @details Sends request to get identification data 
 * from device, and logs data.
 * @return Nothing.
 * @note None.
 */
static void get_data_identify ( void );

/**
 * @brief Create, write, read, and delete binary object.
 * @details Creates and writes data to binary object. 
 * Checks if that object exists. Reads that binary object,
 * and then delets it, and checks if its deleted. 
 * Every step and status will be logged.
 * @return Nothing.
 * @note None.
 */
static void create_check_delete ( void );

/**
 * @brief List of all Applet objects and delete if not reserved.
 * @details Create one random object and then lists all objects
 * and delete ones that are not reserved.
 * @return Nothing.
 * @note None.
 */
static void list_and_delete_objects ( void );

/**
 * @brief Select Applet.
 * @details Select applet and log version info.
 * @return Nothing.
 * @note None.
 */
static void select_applet ( void );

/**
 * @brief Create AES key, Encrypt and Decrypt data, and delete AES key.
 * @details Creates 128AES Symmetrical key. 
 * Encrypts data with it. Decrypt data with that key. 
 * and in the end delete that AES key. Logs every status in the process.
 * @return Nothing.
 * @note None.
 */
static void aes_cipher ( void );

/**
 * @brief Select Card manager.
 * @details Select Card manager without return value request
 * @return Nothing.
 * @note None.
 */
static void select_card_manger ( void );

/**
 * @brief Create 128 AES symmetrical key.
 * @details Create 128 AES symetrical key and sets its value.
 * @param[in] aes_id : Object ID.
 * @param[in] aes_key : AES key value.
 * @return Nothing.
 * @note AES key value because it's 128 key should be 16 bytes of data.
 */
static void create_128_aes_key ( uint32_t aes_id, uint8_t *aes_key );

/**
 * @brief Encrypt or decrypt data with AES key.
 * @details Encrypt or decrypt data with AES key.
 * @param[in] aes_id : Object ID.
 * @param[in] cipher_type : Encrypt or decrypt macro @b[PLUGNTRUST_P2_ENCRYPT_ONESHOT] || @b[PLUGNTRUST_P2_DECRYPT_ONESHOT].
 * @param[in] data_in : Input buffer.
 * @param[out] data_out : Output buffer.
 * @return @li @c  0 - Success,
 *         @li @c -1 - Error.
 * @note None.
 */
static err_t cipher_data_with_aes_key ( uint32_t aes_id, uint8_t cipher_type, uint8_t *data_in, uint8_t *data_out );

void application_init ( void ) 
{
    log_cfg_t log_cfg;  /**< Logger config object. */
    plugntrust_cfg_t plugntrust_cfg;  /**< Click config object. */
    /** 
     * Logger initialization.
     * Default baud rate: 115200
     * Default log level: LOG_LEVEL_DEBUG
     * @note If USB_UART_RX and USB_UART_TX 
     * are defined as HAL_PIN_NC, you will 
     * need to define them manually for log to work. 
     * See @b LOG_MAP_USB_UART macro definition for detailed explanation.
     */
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, " Application Init " );
    // Click initialization.
    plugntrust_cfg_setup( &plugntrust_cfg );
    PLUGNTRUST_MAP_MIKROBUS( plugntrust_cfg, MIKROBUS_1 );
    err_t init_flag = plugntrust_init( &plugntrust, &plugntrust_cfg );
    if ( init_flag == I2C_MASTER_ERROR ) 
    {
        log_error( &logger, " Application Init Error. " );
        log_info( &logger, " Please, run program again... " );

        for ( ; ; );
    } 
    
    frame_data.apdu = &apdu_data;
    
    plugntrust_default_cfg ( &plugntrust );
    
    if ( PLUGNTRUST_INTERFACE_ISO14443 == plugntrust.interface )
    {
        log_info( &logger, " ISO14443 Interface active..." );
        for ( ; ; );
    }
    
    soft_reset( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    get_data_identify( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    select_card_manger( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    select_applet( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    check_free_memory( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    list_and_delete_objects( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    get_random( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    read_uid_object( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    get_version(  );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    create_check_delete( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    aes_cipher( );
    
    log_info( &logger, " Application Task " );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
}

void application_task ( void ) 
{
    #define DATA_LEN 16
    static uint8_t aes_value[ DATA_LEN ]    = { 0x40, 0x41, 0x42, 0x43,0x44, 0x45, 0x46, 0x47,
                                                0x48, 0x49, 0x4A, 0x4B,0x4C, 0x4D, 0x4E, 0x4F };
    static uint32_t binary_id               = 0xBBBBBBBBul;
    static uint32_t aes_id                  = 0xCCCCCCCCul;
    uint8_t random_data[ DATA_LEN ]         = { 0 };
    uint8_t read_data[ DATA_LEN ]           = { 0 };
    uint8_t encrypted_data[ DATA_LEN ]      = { 0 };
    uint32_t read_len = DATA_LEN;
    
    if ( PLUGNTRUST_OK == plugntrust_get_random_numbers( &plugntrust, random_data, DATA_LEN ) )
    {
        log_printf( &logger, " > Generated random data: 0x" );
        log_buf_hex( random_data, DATA_LEN );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Random" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OBJECT_DOESNT_EXIST == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " Write random data to binary object...\r\n" );
        if ( PLUGNTRUST_OK != plugntrust_write_binary_object( &plugntrust, binary_id, 0, DATA_LEN, random_data ) )
        {
            log_error( &logger, " Write Binary" );
        }
        else
        {
            log_info( &logger, " Status OK" );
        }
    }
    else
    {
        log_error( &logger, " Binary object already exist" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        if ( PLUGNTRUST_OK == plugntrust_read_object( &plugntrust, binary_id, 0, 0, read_data, &read_len ) )
        {
            log_printf( &logger, " > Read data from binary object: 0x" );
            log_buf_hex( read_data, read_len );
            log_printf( &logger, "\r\n" );
        }
        else
        {
            log_error( &logger, " Read binray object" );
        } 
    }
    else
    {
        log_error( &logger, " Binary object doesn't exist" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    log_printf( &logger, " Create AES key...\r\n" );
    create_128_aes_key( aes_id, aes_value );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OK == cipher_data_with_aes_key( aes_id, PLUGNTRUST_P2_ENCRYPT_ONESHOT, read_data, encrypted_data ) )
    {
        log_printf( &logger, " > Encrypted data: 0x" );
        log_buf_hex( encrypted_data, DATA_LEN );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Encrypting data" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OK == cipher_data_with_aes_key( aes_id, PLUGNTRUST_P2_DECRYPT_ONESHOT, encrypted_data, read_data ) )
    {
        log_printf( &logger, " > Decrypted data: 0x" );
        log_buf_hex( read_data, DATA_LEN );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Decrypting data" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    log_printf( &logger, " Delete Binary and AES object...\r\n" );
    if ( ( PLUGNTRUST_OK != plugntrust_delete_object( &plugntrust, binary_id ) ) || ( PLUGNTRUST_OK != plugntrust_delete_object( &plugntrust, aes_id ) ) )
    {
        log_error( &logger, " Deleting objects" );
    }
    log_printf( &logger, "*****************************************************************************\r\n" );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
}

int main ( void ) 
{
    /* Do not remove this line or clock might not be set correctly. */
    #ifdef PREINIT_SUPPORTED
    preinit();
    #endif
    
    application_init( );
    
    for ( ; ; ) 
    {
        application_task( );
    }

    return 0;
}

static void reset_parse ( void )
{
    parse_index = 0;
    parse_len = PARSE_BUF_LEN;
    memset( parse_data, 0, parse_len );
}

static void log_buf_hex ( uint8_t *buf, uint8_t buf_len )
{
    for ( uint8_t i = 0; i < buf_len; i++ )
    {
        log_printf( &logger, "%0.2X", ( uint16_t )buf[ i ] );
    }
}

static void log_status ( void )
{
    if ( ( ( frame_data.pcb & PLUGNTRUST_PCB_BLOCK_R ) != PLUGNTRUST_PCB_BLOCK_R ) && 
         ( ( frame_data.pcb & PLUGNTRUST_PCB_BLOCK_S ) != PLUGNTRUST_PCB_BLOCK_S ) )
    {
        switch ( frame_data.apdu->status )
        {
            case PLUGNTRUST_SW_NOERROR:
            {
                log_info( &logger, " Status OK" );
                break;
            }
            default:
            {
                log_error( &logger, " Status: 0x%.4X", frame_data.apdu->status );
            }
        }
    }
}

static void log_rsp_data_default ( void )
{
    log_printf( &logger, " >NAD: 0x%0.2X \r\n", ( uint16_t )frame_data.nad );
    log_printf( &logger, " >PCB: 0x%0.2X \r\n", ( uint16_t )frame_data.pcb );
    log_printf( &logger, " >LEN: 0x%0.2X \r\n", ( uint16_t )frame_data.len );
    if ( frame_data.len > 0 )
    {
        log_printf( &logger, " >APDU: 0x" );
    }
    log_buf_hex( frame_data.apdu->payload, frame_data.len );
    if ( frame_data.len > 0 )
    {
        log_printf( &logger, " \r\n" );
    }
    log_printf( &logger, " >CRC: 0x%0.4X \r\n", frame_data.crc16 );
    log_printf( &logger, "************************************************************************\r\n" );
}

static void soft_reset( void )
{       
    log_info( &logger, " Resetting device..." );
    plugntrust_atr_t atr_data;
    if ( PLUGNTRUST_OK == plugntrust_sw_reset( &plugntrust, &atr_data ) )
    {
        log_printf( &logger, " > Protocol version: %d\r\n", ( uint16_t )atr_data.protocol_version );
        log_printf( &logger, " > Length of Data Link Layer Parameters value: %d\r\n", 
                    ( uint16_t ) atr_data.data_link_layer_parameters_len );
        log_printf( &logger, " > Data Link Layer Parameters: 0x" );
        log_buf_hex( atr_data.data_link_layer_parameters, atr_data.data_link_layer_parameters_len );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Physical Layer ID: %d\r\n", ( uint16_t )atr_data.physical_layer_id );
        log_printf( &logger, " > Length of Physical Layer Parameters value: %d\r\n", 
                    ( uint16_t ) atr_data.physical_layer_parameters_len );
        log_printf( &logger, " > Physical Layer Parameters: 0x" );
        log_buf_hex( atr_data.physical_layer_parameters, atr_data.physical_layer_parameters_len );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Length of Historical Bytes value: %d\r\n", ( uint16_t ) atr_data.historical_len );
        log_printf( &logger, " > Historical Bytes: 0x" );
        log_buf_hex( atr_data.historical, atr_data.historical_len );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Resetting..." );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void check_free_memory ( void )
{
    log_info( &logger, " Check free memory" );
    uint16_t free_memory = 0;
    if ( PLUGNTRUST_OK == plugntrust_get_free_memory( &plugntrust, PLUGNTRUST_MEM_TRANSIENT_DESELECT, &free_memory ) )
    {
        log_printf( &logger, " > Free Memory: %d\r\n", free_memory );
    }
    else
    {
        log_error( &logger, " Reading Memory" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void get_random ( void )
{
    log_info( &logger, " Get Random" );
    if ( PLUGNTRUST_OK == plugntrust_get_random_numbers( &plugntrust, parse_data, 2 ) )
    {
        log_printf( &logger, " > Random data: 0x" );
        log_buf_hex( parse_data, 2 );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Random" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void read_uid_object ( void )
{
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, PLUGNTRUST_APPLET_RES_ID_UNIQUE_ID ) )
    {
        log_info( &logger, " Read object with Unique ID" );
        
        if ( PLUGNTRUST_OK == plugntrust_read_object( &plugntrust, 
            PLUGNTRUST_APPLET_RES_ID_UNIQUE_ID, 0, 0, parse_data, &parse_len ) )
        {
            log_printf( &logger, " > Object data: 0x" );
            log_buf_hex( parse_data, parse_len );
            log_printf( &logger, "\r\n" );
        }
        else
        {
            log_error( &logger, " Read object with Unique ID" );
        } 
        log_printf( &logger, "************************************************************************\r\n" );
    }
}

static void get_version ( void )
{
    log_info( &logger, " Get Version" );
    plugntrust_version_info_t ver_info;
    if ( PLUGNTRUST_OK == plugntrust_get_applet_info( &plugntrust, &ver_info ) )
    {
        log_printf( &logger, " > Applet Version = %d.%d.%d\r\n", ( uint16_t )ver_info.major_version, 
                                                                 ( uint16_t )ver_info.minor_version, 
                                                                 ( uint16_t )ver_info.patch_version );
        log_printf( &logger, " > AppletConfig = 0x%0.4X\r\n", ver_info.applet_config );
        log_printf( &logger, " > SecureBox = 0x%0.4X\r\n", ver_info.secure_box );
    }
    else
    {
        log_error( &logger, " Version Info" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void get_data_identify ( void )
{
    //select card
    select_card_manger( );
    end_apdu_session( );
    //get data identify
    typedef struct
    {
        uint8_t tag_value_proprietary_data;//0xFE Tag value - proprietary data Only present if class byte is 0x80
        uint8_t length_of_following_data;//0x49 / 0x45 Length of following data Only present if class byte is 0x80
        uint8_t tag_card_identification_data[0x02];//0xDF28 Tag card identification data Only present if class byte is 0x80
        uint8_t length_of_card_identification_data;//0x46 Length of card identification data Only present if class byte is 0x80
        
        uint8_t tag_configuration_id;//0x01 Tag configuration ID Identifies the configuration content
        uint8_t length_configuration_id; //0x0C Length configuration ID
        uint8_t configuration_id[ 0x0C ];  //var Configuration ID
        
        uint8_t tag_patch_id;    //0x02 Tag patch ID Identifies the patch level
        uint8_t length_patch_id; //0x08 Length patch ID
        uint8_t patch_id[ 0x08 ];  //var Patch ID
        
        uint8_t tag_platform_build_id1;//0x03 Tag platform build ID1 Identifies the JCOP platform
        uint8_t length_platform_build_id; //0x18 Length platform build ID
        uint8_t platform_build_id[ 0x18 ];  //var Platform build ID
        
        uint8_t tag_fips_mode;    //0x052 Tag FIPS mode FIPS mode active
        uint8_t length_fips_mode; //0x01 Length FIPS mode
        uint8_t fips_mode;//var FIPS mode 0x00 - FIPS mode not active, 0x01 - FIPS mode active
        
        uint8_t tag_pre_perso_state;//0x07 Tag pre-perso state Lists pre-perso state
        uint8_t length_pre_perso_state;//0x01 Length pre-perso state
        //var Bit mask of pre-perso state bit0 = 1 = config module available,
        //  bit1 = 1 = transport state is active.
        //  Unused bits are set to 0x0.
        uint8_t bit_mask_of_pre_perso_state;

        uint8_t tag_rom_id;    //'08' Tag ROM ID Indentifies the ROM content
        uint8_t length_rom_id; //'08' Length ROM ID Normal ending
        uint8_t rom_id[ 0x08 ];  //var ROM ID
        uint8_t status_word_sw[ 0x02 ]; //9000h Status Word (SW)
    } identify_rsp_t;
    
    identify_rsp_t identify_rsp = {0};
    uint32_t prsp_len = sizeof(identify_rsp_t);
    log_info( &logger, " Get data identify" );
    frame_data.pcb = PLUGNTRUST_PCB_BLOCK_I;
    frame_data.len = 8;
    frame_data.apdu->cla = PLUGNTRUST_CLA_NOT_SECURE;
    frame_data.apdu->ins = 0xCA;
    frame_data.apdu->p1 = 0x00;
    frame_data.apdu->p2 = 0xFE;
    frame_data.apdu->payload_len = 0x02;
    frame_data.apdu->rsp_len = 0x00;
    uint8_t df28[ 2 ] = { 0xDF, 0x28 };
    memcpy( frame_data.apdu->payload, df28, 2 );
    plugntrust_apdu_transfer( &plugntrust, &frame_data );
    if ( frame_data.len == prsp_len )
    {
        memcpy( (uint8_t *)&identify_rsp, frame_data.apdu->payload, prsp_len );
        log_printf( &logger, " > Tag value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_value_proprietary_data );
        log_printf( &logger, " > Length value: %d\r\n", ( uint16_t ) identify_rsp.length_of_following_data );
        log_printf( &logger, " > Tag Card ID value: 0x" );
        log_buf_hex( identify_rsp.tag_card_identification_data, 2 );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Length of Card ID value: %d\r\n", ( uint16_t ) identify_rsp.length_of_card_identification_data );
        log_printf( &logger, " > Tag of Configuration ID value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_configuration_id );
        log_printf( &logger, " > Length of Configuration ID value: %d\r\n", ( uint16_t ) identify_rsp.length_configuration_id );
        log_printf( &logger, " > Configuration ID: 0x" );
        log_buf_hex( identify_rsp.configuration_id, identify_rsp.length_configuration_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of Patch ID value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_patch_id );
        log_printf( &logger, " > Length of Patch ID value: %d\r\n", ( uint16_t ) identify_rsp.length_patch_id );
        log_printf( &logger, " > Patch ID: 0x" );
        log_buf_hex( identify_rsp.patch_id, identify_rsp.length_patch_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of Platform Build ID1 value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_platform_build_id1 );
        log_printf( &logger, " > Length of Platform Build ID1 value: %d\r\n", ( uint16_t ) identify_rsp.length_platform_build_id );
        log_printf( &logger, " > Platform Build ID1: 0x" );
        log_buf_hex( identify_rsp.platform_build_id, identify_rsp.length_platform_build_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of FIPS Mode value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_fips_mode );
        log_printf( &logger, " > Length of FIPS Mode value: %d\r\n", ( uint16_t ) identify_rsp.length_fips_mode );
        log_printf( &logger, " > FIPS Mode: 0x" );
        log_buf_hex( &identify_rsp.fips_mode, identify_rsp.length_fips_mode );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of Pre-Preso State value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_pre_perso_state );
        log_printf( &logger, " > Length of Pre-Preso State value: %d\r\n", ( uint16_t ) identify_rsp.length_pre_perso_state );
        log_printf( &logger, " > Pre-Preso State: 0x" );
        log_buf_hex( &identify_rsp.bit_mask_of_pre_perso_state, identify_rsp.length_pre_perso_state );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of ROM ID value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_rom_id );
        log_printf( &logger, " > Length of ROM ID value: %d\r\n", ( uint16_t ) identify_rsp.length_rom_id );
        log_printf( &logger, " > ROM ID: 0x" );
        log_buf_hex( identify_rsp.rom_id, identify_rsp.length_rom_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Status Word: 0x" );
        log_buf_hex( identify_rsp.status_word_sw, 2 );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Size Error" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
    end_apdu_session( );
}

static void end_apdu_session ( void )
{
    if ( PLUGNTRUST_OK != plugntrust_end_apdu_session( &plugntrust ) )
    {
        log_error( &logger, " End APDU session" );
    }
}

static void create_check_delete ( void )
{    
    //create binary object
    log_info( &logger, " Write Binary" );
    uint8_t data_buf[ 7 ] = "MikroE";
    uint32_t binary_id = 0xAAAAAAAAul;

    if ( PLUGNTRUST_OK != plugntrust_write_binary_object( &plugntrust, 
            binary_id, 0, 6, data_buf ) )
    {
        log_error( &logger, " Write Binary" );
    }
    log_printf( &logger, "************************************************************************\r\n" );

    //check if object exists
    log_info( &logger, " Check object exists" );
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " > Object exist\r\n" );
    }
    else
    {
        log_printf( &logger, " > Object doesn't exist\r\n" );
    } 
    log_printf( &logger, "************************************************************************\r\n" );
    
    //read binary object
    log_info( &logger, " Read object" );
    reset_parse();
    if ( PLUGNTRUST_OK == plugntrust_read_object( &plugntrust, 
            binary_id, 0, 0, parse_data, &parse_len ) )
    {
        log_printf( &logger, " > Object data: %s\r\n", parse_data );
    }
    else
    {
        log_error( &logger, " Read binary object" );
    } 
    log_printf( &logger, "************************************************************************\r\n" );
    //delete object
    log_info( &logger, " Delete Secure Object" );
    if ( PLUGNTRUST_OK == plugntrust_delete_object( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " Object 0x%0.8LX deleted\r\n", binary_id );
    }
    else
    {
        log_error( &logger, " Delete Object"  );
    }
    log_printf( &logger, "************************************************************************\r\n" );
    //check if object exists
    log_info( &logger, " Check object exists" );
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " > Object exist\r\n" );
    }
    else
    {
        log_printf( &logger, " > Object doesn't exist\r\n" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void list_and_delete_objects( void )
{     
    plugntrust_write_binary_object( &plugntrust, 0xAABBCCDDul, 0, 4, "Data" );
    
    log_info( &logger, " Get Object list" );  
    uint32_t ids[ 30 ] = { 0 };
    uint8_t len = 0;
    if ( PLUGNTRUST_OK == plugntrust_object_id_list( &plugntrust, ids, &len ) )
    {
        log_info( &logger, " List len: %d", ( uint16_t )len );
        for ( uint8_t cnt = 0; cnt < len; cnt++ )
        {   //if not NXP defined objectect delete that object
            if ( ( PLUGNTRUST_OBJID_SE05X_APPLET_RES_START != ( PLUGNTRUST_OBJID_APPLET_MASK & ids[ cnt ] ) ) &&
                 ( PLUGNTRUST_SSS_OBJID_DEMO_AUTH_START != ( PLUGNTRUST_OBJID_APPLET_MASK & ids[ cnt ] ) ) &&
                 ( PLUGNTRUST_SSS_OBJID_IOT_HUB_A_START != ( PLUGNTRUST_OBJID_IOT_MASK & ids[ cnt ] ) ) )
            {
                if ( PLUGNTRUST_OK == plugntrust_delete_object( &plugntrust, ids[ cnt ] ) )
                {
                    log_printf( &logger, " > Object Deleted 0x%.8LX\r\n", ids[ cnt ] );
                }
                else
                {
                    log_error( &logger, " Delecte Object  0x%.8LX", ids[ cnt ] );
                }
            }
            else
            {
                log_printf( &logger, " > Object ID: 0x%.8LX\r\n", ids[ cnt ] );
            }
        }
    }
    else
    {
        log_error( &logger, " Object ID List" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void select_applet ( void )
{
    log_info( &logger, " Select SE050 Applet" );
    plugntrust_version_info_t ver_info;
    plugntrust_select_applet( &plugntrust, PLUGNTRUST_PCB_BLOCK_I_NS_ENCODE, &ver_info );
    log_printf( &logger, " > Applet Version = %d.%d.%d\r\n", ( uint16_t )ver_info.major_version, 
                                                             ( uint16_t )ver_info.minor_version, 
                                                             ( uint16_t )ver_info.patch_version );
    log_printf( &logger, " > AppletConfig = 0x%0.4X\r\n", ver_info.applet_config );
    log_printf( &logger, " > SecureBox = 0x%0.4X\r\n", ver_info.secure_box );
    log_printf( &logger, "************************************************************************\r\n" );
}

static void aes_cipher ( void )
{
    //Create AES Key
    log_info( &logger, " Write AES Key" );
    #define AES_DATA_SIZE 16
    uint8_t aes_value[ AES_DATA_SIZE ] = { 0x40, 0x41, 0x42, 0x43,0x44, 0x45, 0x46, 0x47,
                                           0x48, 0x49, 0x4A, 0x4B,0x4C, 0x4D, 0x4E, 0x4F };
    uint32_t symm_id = 0x12345678ul;
    create_128_aes_key( symm_id, aes_value );
    
    //Encrypt Data
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, symm_id ) )
    {
        log_info( &logger, " Encrypt Data" );
        uint8_t data_value[ 16 ] = { ' ', '>', 'P', 'l', 'u', 'g', ' ', '&', ' ', 'T', 'r', 'u', 's', 't', '<', ' ' };
        reset_parse( );
        if ( PLUGNTRUST_OK == cipher_data_with_aes_key( symm_id, PLUGNTRUST_P2_ENCRYPT_ONESHOT, data_value, parse_data ) )
        {
            log_printf( &logger, " > Encrypted data hex: 0x" );
            log_buf_hex( parse_data, AES_DATA_SIZE );
            log_printf( &logger, "\r\n" );
            log_printf( &logger, " > Encrypted data string: %s\r\n", parse_data );
        }
        else
        {
            log_error( &logger, " Parse error" );
        }
    }
    else
    {
        log_printf( &logger, " > Object doesn't exist\r\n" );
    } 
    log_printf( &logger, "************************************************************************\r\n" );

    //Decrypt Data
    log_info( &logger, " Decrypt Data" );
    if ( PLUGNTRUST_OK == cipher_data_with_aes_key( symm_id, PLUGNTRUST_P2_DECRYPT_ONESHOT, parse_data, parse_data ) )
    {
        log_printf( &logger, " > Decrypted data hex: 0x" );
        log_buf_hex( parse_data, parse_len );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Decrypted data string: %s\r\n", parse_data );
    }
    else
    {
        log_error( &logger, " Parse error" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
    
    //Delete Object
    log_info( &logger, " Delete Secure Object" );
    if ( PLUGNTRUST_OK == plugntrust_delete_object( &plugntrust, symm_id ) )
    {
        log_printf( &logger, " Object 0x%0.8LX deleted\r\n", symm_id );
    }
    else
    {
        log_error( &logger, " Delete Object"  );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void select_card_manger ( void )
{
    log_info( &logger, " Select the card manager " );
    if ( PLUGNTRUST_OK != plugntrust_select_card_manager( &plugntrust, PLUGNTRUST_CARD_MANAGER_WITHOUT_RSP, 0, 0 ) )
    {
        log_error( &logger, " Card manager"  );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void create_128_aes_key ( uint32_t aes_id, uint8_t *aes_key )
{
    #define AES_KEY_SIZE 16
    frame_data.pcb = PLUGNTRUST_PCB_BLOCK_I;
    frame_data.apdu->cla = PLUGNTRUST_CLA_NOT_SECURE;
    frame_data.apdu->ins = PLUGNTRUST_INS_WRITE | PLUGNTRUST_INS_TRANSIENT;
    frame_data.apdu->p1 = PLUGNTRUST_P1_AES;
    frame_data.apdu->p2 = PLUGNTRUST_P2_DEFAULT;
    frame_data.apdu->payload_len = 0;//reset apdu payload_len
    frame_data.apdu->rsp_len = 0;//reset apdu le value
    plugntrust_set_tlv_u32( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                            PLUGNTRUST_TLV_TAG_1, aes_id ); //AES key ID
    plugntrust_set_tlv_u8buf( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                            PLUGNTRUST_TLV_TAG_3, aes_key, AES_KEY_SIZE ); //AES key value
    frame_data.len = plugntrust_calculate_apdu_size( frame_data.apdu ); //calculate apdu size
    plugntrust_apdu_transfer( &plugntrust, &frame_data );
    log_status();
    end_apdu_session( );
}

static err_t cipher_data_with_aes_key ( uint32_t aes_id, uint8_t cipher_type, uint8_t *data_in, uint8_t *data_out )
{
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, aes_id ) )//check if object with aes_id exists
    {
        frame_data.pcb = PLUGNTRUST_PCB_BLOCK_I;
        frame_data.apdu->cla = PLUGNTRUST_CLA_NOT_SECURE;
        frame_data.apdu->ins = PLUGNTRUST_INS_CRYPTO;
        frame_data.apdu->p1 = PLUGNTRUST_P1_CIPHER;
        frame_data.apdu->p2 = cipher_type;//PLUGNTRUST_P2_ENCRYPT_ONESHOT || PLUGNTRUST_P2_DECRYPT_ONESHOT
        frame_data.apdu->payload_len = 0;
        frame_data.apdu->rsp_len = 0;
        frame_data.len = 0;
        plugntrust_set_tlv_u32( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                                PLUGNTRUST_TLV_TAG_1, aes_id );//set aes key to be used
        plugntrust_set_tlv_u8( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                                PLUGNTRUST_TLV_TAG_2, PLUGNTRUST_CIPHER_AES_CTR );//set ae cipher type to be used
        plugntrust_set_tlv_u8buf( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                                PLUGNTRUST_TLV_TAG_3, data_in, 16 );//set data to encrypt/decrypt
        frame_data.len = plugntrust_calculate_apdu_size( frame_data.apdu );//calculate apdu data
        frame_data.len++;//increment data
        plugntrust_apdu_transfer( &plugntrust, &frame_data );
        reset_parse( );//reset prase data
        if ( PLUGNTRUST_OK == plugntrust_get_tlv_u8buf( frame_data.apdu->payload, &parse_index, frame_data.len, 
                                                        PLUGNTRUST_TLV_TAG_1, data_out, &parse_len ) )//get encryted/decrypted data
        {
            end_apdu_session( );
            return PLUGNTRUST_OK;
        }
        else
        {
            end_apdu_session( );
            return PLUGNTRUST_ERROR;
        }
    }
    else
    {
        return PLUGNTRUST_ERROR;
    }
}

// ------------------------------------------------------------------------ END
/*!
 * @file main.c
 * @brief PlugnTrust Click example
 *
 * # Description
 * This application is showcasing basic functionality of Plug&Trust
 * click board. It gets identify data from device, selects card 
 * manager and applet. Then checks free memory, reads all objects and 
 * deletes not reserved ones. After that showcases a few of functionality: 
 *      - Generating random data, 
 *      - Creating, reading and deleteing binary objects, 
 *      - Creating AES symmetrical key and cipher with it;
 * In the end it is showcasing funcionality in the endless loop.
 * 
 *
 * The demo application is composed of two sections :
 *
 * ## Application Init
 * At the start it sets comunication interface from default
 * configuration[I2C]. Reads indetifing data from device, 
 * and then selects Card manager and applet. After that it 
 * reads free presistant memory, reads all objects and deletes
 * objects that are not reserved by the Applet. Then it generates
 * 2 byte of random data, and gets the version information 
 * from the Applet. Thtas followed up with creating binary
 * object and 'MikroE' data is wrriten in it. Then its checked
 * it object is created, and reads data back, in the end its 
 * deleted and checked if it still exists. Finally it creates
 * 128AES key (16bytes), and then it encrypts and then decrypts
 * data with that key, and in the end it deletes that key object.
 *
 * ## Application Task
 * It generates 16bytes of data, writes it in binary object and
 * then reads it and logs it. Then creates AES key and encrypts
 * that random data with it, and then decrypts it. In the end it
 * deletes both AES key object and binary object thats created 
 * at the start of task.
 *
 * @note
 * For more informations and explanations refer to documents 
 * from NXP->AN12413 and UM11225.
 *
 * @author Luka Filipovic
 *
 */

#include "board.h"
#include "log.h"
#include "plugntrust.h"

//Library and log objects
static plugntrust_t plugntrust;
static log_t logger;

//Communication objects
static plugntrust_apdu_t apdu_data;
static plugntrust_frame_data_t frame_data;

//Parsing parameters
#define PARSE_BUF_LEN 0xFF
static uint32_t parse_index = 0;
static uint32_t parse_len = PARSE_BUF_LEN;
static uint8_t parse_data[ PARSE_BUF_LEN ] = { 0 };

/**
 * @brief Reset parse data.
 * @details Clears parse index, buffer and resets @b parse_len.
 * @return Nothing.
 * @note None.
 */
static void reset_parse ( void );

/**
 * @brief Log buffer data to .
 * @details Logs buffer data to UART Terminal
 * @param[in] buf : Buffer to log.
 * @param[in] buf_len : Length of buffer to log.
 * @return Nothing.
 * @note None.
 */
static void log_buf_hex ( uint8_t *buf, uint8_t buf_len );

/**
 * @brief Log status data.
 * @details Log status data from @b apdu_data.
 * @return Nothing.
 * @note None.
 */
static void log_status ( void );

/**
 * @brief Log frame data.
 * @details Logs data from @b frame_data.
 * @return Nothing.
 * @note None.
 */
static void log_rsp_data_default ( void );

/**
 * @brief End APDU session.
 * @details Sends request to end APDU session.
 * @return Nothing.
 * @note None.
 */
static void end_apdu_session ( void );

/**
 * @brief Send request to reset device.
 * @details Sends request to reset device and logs ATR data.
 * @return Nothing.
 * @note None.
 */
static void soft_reset( void );

/**
 * @brief Check presistant free memory.
 * @details Sends request to check presistant free
 * memory from Applet, and logs it.
 * @return Nothing.
 * @note None.
 */
static void check_free_memory ( void );

/**
 * @brief Reads 2 bytes of random data from Applet.
 * @details Sends request to Applet to get 2 bytes of 
 * random data, and logs it.
 * @return Nothing.
 * @note None.
 */
static void get_random ( void );

/**
 * @brief Read Object with UID.
 * @details Checks if Object with UID exists and then
 * reads its data, and logs it.
 * @return Nothing.
 * @note None.
 */
static void read_uid_object ( void );

/**
 * @brief Checks the current version of the Applet.
 * @details Send request to check the current version 
 * of Applet and logs return data.
 * @return Nothing.
 * @note None.
 */
static void get_version ( void );

/**
 * @brief Get identify data from device.
 * @details Sends request to get identification data 
 * from device, and logs data.
 * @return Nothing.
 * @note None.
 */
static void get_data_identify ( void );

/**
 * @brief Create, write, read, and delete binary object.
 * @details Creates and writes data to binary object. 
 * Checks if that object exists. Reads that binary object,
 * and then delets it, and checks if its deleted. 
 * Every step and status will be logged.
 * @return Nothing.
 * @note None.
 */
static void create_check_delete ( void );

/**
 * @brief List of all Applet objects and delete if not reserved.
 * @details Create one random object and then lists all objects
 * and delete ones that are not reserved.
 * @return Nothing.
 * @note None.
 */
static void list_and_delete_objects ( void );

/**
 * @brief Select Applet.
 * @details Select applet and log version info.
 * @return Nothing.
 * @note None.
 */
static void select_applet ( void );

/**
 * @brief Create AES key, Encrypt and Decrypt data, and delete AES key.
 * @details Creates 128AES Symmetrical key. 
 * Encrypts data with it. Decrypt data with that key. 
 * and in the end delete that AES key. Logs every status in the process.
 * @return Nothing.
 * @note None.
 */
static void aes_cipher ( void );

/**
 * @brief Select Card manager.
 * @details Select Card manager without return value request
 * @return Nothing.
 * @note None.
 */
static void select_card_manger ( void );

/**
 * @brief Create 128 AES symmetrical key.
 * @details Create 128 AES symetrical key and sets its value.
 * @param[in] aes_id : Object ID.
 * @param[in] aes_key : AES key value.
 * @return Nothing.
 * @note AES key value because it's 128 key should be 16 bytes of data.
 */
static void create_128_aes_key ( uint32_t aes_id, uint8_t *aes_key );

/**
 * @brief Encrypt or decrypt data with AES key.
 * @details Encrypt or decrypt data with AES key.
 * @param[in] aes_id : Object ID.
 * @param[in] cipher_type : Encrypt or decrypt macro @b[PLUGNTRUST_P2_ENCRYPT_ONESHOT] || @b[PLUGNTRUST_P2_DECRYPT_ONESHOT].
 * @param[in] data_in : Input buffer.
 * @param[out] data_out : Output buffer.
 * @return @li @c  0 - Success,
 *         @li @c -1 - Error.
 * @note None.
 */
static err_t cipher_data_with_aes_key ( uint32_t aes_id, uint8_t cipher_type, uint8_t *data_in, uint8_t *data_out );

void application_init ( void ) 
{
    log_cfg_t log_cfg;  /**< Logger config object. */
    plugntrust_cfg_t plugntrust_cfg;  /**< Click config object. */
    /** 
     * Logger initialization.
     * Default baud rate: 115200
     * Default log level: LOG_LEVEL_DEBUG
     * @note If USB_UART_RX and USB_UART_TX 
     * are defined as HAL_PIN_NC, you will 
     * need to define them manually for log to work. 
     * See @b LOG_MAP_USB_UART macro definition for detailed explanation.
     */
    LOG_MAP_USB_UART( log_cfg );
    log_init( &logger, &log_cfg );
    log_info( &logger, " Application Init " );
    // Click initialization.
    plugntrust_cfg_setup( &plugntrust_cfg );
    PLUGNTRUST_MAP_MIKROBUS( plugntrust_cfg, MIKROBUS_1 );
    err_t init_flag = plugntrust_init( &plugntrust, &plugntrust_cfg );
    if ( init_flag == I2C_MASTER_ERROR ) 
    {
        log_error( &logger, " Application Init Error. " );
        log_info( &logger, " Please, run program again... " );

        for ( ; ; );
    } 
    
    frame_data.apdu = &apdu_data;
    
    plugntrust_default_cfg ( &plugntrust );
    
    if ( PLUGNTRUST_INTERFACE_ISO14443 == plugntrust.interface )
    {
        log_info( &logger, " ISO14443 Interface active..." );
        for ( ; ; );
    }
    
    soft_reset( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    get_data_identify( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    select_card_manger( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    select_applet( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    check_free_memory( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    list_and_delete_objects( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    get_random( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    read_uid_object( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    get_version(  );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    create_check_delete( );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    aes_cipher( );
    
    log_info( &logger, " Application Task " );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
}

void application_task ( void ) 
{
    #define DATA_LEN 16
    static uint8_t aes_value[ DATA_LEN ]    = { 0x40, 0x41, 0x42, 0x43,0x44, 0x45, 0x46, 0x47,
                                                0x48, 0x49, 0x4A, 0x4B,0x4C, 0x4D, 0x4E, 0x4F };
    static uint32_t binary_id               = 0xBBBBBBBBul;
    static uint32_t aes_id                  = 0xCCCCCCCCul;
    uint8_t random_data[ DATA_LEN ]         = { 0 };
    uint8_t read_data[ DATA_LEN ]           = { 0 };
    uint8_t encrypted_data[ DATA_LEN ]      = { 0 };
    uint32_t read_len = DATA_LEN;
    
    if ( PLUGNTRUST_OK == plugntrust_get_random_numbers( &plugntrust, random_data, DATA_LEN ) )
    {
        log_printf( &logger, " > Generated random data: 0x" );
        log_buf_hex( random_data, DATA_LEN );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Random" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OBJECT_DOESNT_EXIST == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " Write random data to binary object...\r\n" );
        if ( PLUGNTRUST_OK != plugntrust_write_binary_object( &plugntrust, binary_id, 0, DATA_LEN, random_data ) )
        {
            log_error( &logger, " Write Binary" );
        }
        else
        {
            log_info( &logger, " Status OK" );
        }
    }
    else
    {
        log_error( &logger, " Binary object already exist" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        if ( PLUGNTRUST_OK == plugntrust_read_object( &plugntrust, binary_id, 0, 0, read_data, &read_len ) )
        {
            log_printf( &logger, " > Read data from binary object: 0x" );
            log_buf_hex( read_data, read_len );
            log_printf( &logger, "\r\n" );
        }
        else
        {
            log_error( &logger, " Read binray object" );
        } 
    }
    else
    {
        log_error( &logger, " Binary object doesn't exist" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    log_printf( &logger, " Create AES key...\r\n" );
    create_128_aes_key( aes_id, aes_value );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OK == cipher_data_with_aes_key( aes_id, PLUGNTRUST_P2_ENCRYPT_ONESHOT, read_data, encrypted_data ) )
    {
        log_printf( &logger, " > Encrypted data: 0x" );
        log_buf_hex( encrypted_data, DATA_LEN );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Encrypting data" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    if ( PLUGNTRUST_OK == cipher_data_with_aes_key( aes_id, PLUGNTRUST_P2_DECRYPT_ONESHOT, encrypted_data, read_data ) )
    {
        log_printf( &logger, " > Decrypted data: 0x" );
        log_buf_hex( read_data, DATA_LEN );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Decrypting data" );
    }
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    log_printf( &logger, " Delete Binary and AES object...\r\n" );
    if ( ( PLUGNTRUST_OK != plugntrust_delete_object( &plugntrust, binary_id ) ) || ( PLUGNTRUST_OK != plugntrust_delete_object( &plugntrust, aes_id ) ) )
    {
        log_error( &logger, " Deleting objects" );
    }
    log_printf( &logger, "*****************************************************************************\r\n" );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
    Delay_ms ( 1000 );
}

int main ( void ) 
{
    /* Do not remove this line or clock might not be set correctly. */
    #ifdef PREINIT_SUPPORTED
    preinit();
    #endif
    
    application_init( );
    
    for ( ; ; ) 
    {
        application_task( );
    }

    return 0;
}

static void reset_parse ( void )
{
    parse_index = 0;
    parse_len = PARSE_BUF_LEN;
    memset( parse_data, 0, parse_len );
}

static void log_buf_hex ( uint8_t *buf, uint8_t buf_len )
{
    for ( uint8_t i = 0; i < buf_len; i++ )
    {
        log_printf( &logger, "%0.2X", ( uint16_t )buf[ i ] );
    }
}

static void log_status ( void )
{
    if ( ( ( frame_data.pcb & PLUGNTRUST_PCB_BLOCK_R ) != PLUGNTRUST_PCB_BLOCK_R ) && 
         ( ( frame_data.pcb & PLUGNTRUST_PCB_BLOCK_S ) != PLUGNTRUST_PCB_BLOCK_S ) )
    {
        switch ( frame_data.apdu->status )
        {
            case PLUGNTRUST_SW_NOERROR:
            {
                log_info( &logger, " Status OK" );
                break;
            }
            default:
            {
                log_error( &logger, " Status: 0x%.4X", frame_data.apdu->status );
            }
        }
    }
}

static void log_rsp_data_default ( void )
{
    log_printf( &logger, " >NAD: 0x%0.2X \r\n", ( uint16_t )frame_data.nad );
    log_printf( &logger, " >PCB: 0x%0.2X \r\n", ( uint16_t )frame_data.pcb );
    log_printf( &logger, " >LEN: 0x%0.2X \r\n", ( uint16_t )frame_data.len );
    if ( frame_data.len > 0 )
    {
        log_printf( &logger, " >APDU: 0x" );
    }
    log_buf_hex( frame_data.apdu->payload, frame_data.len );
    if ( frame_data.len > 0 )
    {
        log_printf( &logger, " \r\n" );
    }
    log_printf( &logger, " >CRC: 0x%0.4X \r\n", frame_data.crc16 );
    log_printf( &logger, "************************************************************************\r\n" );
}

static void soft_reset( void )
{       
    log_info( &logger, " Resetting device..." );
    plugntrust_atr_t atr_data;
    if ( PLUGNTRUST_OK == plugntrust_sw_reset( &plugntrust, &atr_data ) )
    {
        log_printf( &logger, " > Protocol version: %d\r\n", ( uint16_t )atr_data.protocol_version );
        log_printf( &logger, " > Length of Data Link Layer Parameters value: %d\r\n", 
                    ( uint16_t ) atr_data.data_link_layer_parameters_len );
        log_printf( &logger, " > Data Link Layer Parameters: 0x" );
        log_buf_hex( atr_data.data_link_layer_parameters, atr_data.data_link_layer_parameters_len );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Physical Layer ID: %d\r\n", ( uint16_t )atr_data.physical_layer_id );
        log_printf( &logger, " > Length of Physical Layer Parameters value: %d\r\n", 
                    ( uint16_t ) atr_data.physical_layer_parameters_len );
        log_printf( &logger, " > Physical Layer Parameters: 0x" );
        log_buf_hex( atr_data.physical_layer_parameters, atr_data.physical_layer_parameters_len );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Length of Historical Bytes value: %d\r\n", ( uint16_t ) atr_data.historical_len );
        log_printf( &logger, " > Historical Bytes: 0x" );
        log_buf_hex( atr_data.historical, atr_data.historical_len );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Resetting..." );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void check_free_memory ( void )
{
    log_info( &logger, " Check free memory" );
    uint16_t free_memory = 0;
    if ( PLUGNTRUST_OK == plugntrust_get_free_memory( &plugntrust, PLUGNTRUST_MEM_TRANSIENT_DESELECT, &free_memory ) )
    {
        log_printf( &logger, " > Free Memory: %d\r\n", free_memory );
    }
    else
    {
        log_error( &logger, " Reading Memory" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void get_random ( void )
{
    log_info( &logger, " Get Random" );
    if ( PLUGNTRUST_OK == plugntrust_get_random_numbers( &plugntrust, parse_data, 2 ) )
    {
        log_printf( &logger, " > Random data: 0x" );
        log_buf_hex( parse_data, 2 );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Random" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void read_uid_object ( void )
{
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, PLUGNTRUST_APPLET_RES_ID_UNIQUE_ID ) )
    {
        log_info( &logger, " Read object with Unique ID" );
        
        if ( PLUGNTRUST_OK == plugntrust_read_object( &plugntrust, 
            PLUGNTRUST_APPLET_RES_ID_UNIQUE_ID, 0, 0, parse_data, &parse_len ) )
        {
            log_printf( &logger, " > Object data: 0x" );
            log_buf_hex( parse_data, parse_len );
            log_printf( &logger, "\r\n" );
        }
        else
        {
            log_error( &logger, " Read object with Unique ID" );
        } 
        log_printf( &logger, "************************************************************************\r\n" );
    }
}

static void get_version ( void )
{
    log_info( &logger, " Get Version" );
    plugntrust_version_info_t ver_info;
    if ( PLUGNTRUST_OK == plugntrust_get_applet_info( &plugntrust, &ver_info ) )
    {
        log_printf( &logger, " > Applet Version = %d.%d.%d\r\n", ( uint16_t )ver_info.major_version, 
                                                                 ( uint16_t )ver_info.minor_version, 
                                                                 ( uint16_t )ver_info.patch_version );
        log_printf( &logger, " > AppletConfig = 0x%0.4X\r\n", ver_info.applet_config );
        log_printf( &logger, " > SecureBox = 0x%0.4X\r\n", ver_info.secure_box );
    }
    else
    {
        log_error( &logger, " Version Info" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void get_data_identify ( void )
{
    //select card
    select_card_manger( );
    end_apdu_session( );
    //get data identify
    typedef struct
    {
        uint8_t tag_value_proprietary_data;//0xFE Tag value - proprietary data Only present if class byte is 0x80
        uint8_t length_of_following_data;//0x49 / 0x45 Length of following data Only present if class byte is 0x80
        uint8_t tag_card_identification_data[0x02];//0xDF28 Tag card identification data Only present if class byte is 0x80
        uint8_t length_of_card_identification_data;//0x46 Length of card identification data Only present if class byte is 0x80
        
        uint8_t tag_configuration_id;//0x01 Tag configuration ID Identifies the configuration content
        uint8_t length_configuration_id; //0x0C Length configuration ID
        uint8_t configuration_id[ 0x0C ];  //var Configuration ID
        
        uint8_t tag_patch_id;    //0x02 Tag patch ID Identifies the patch level
        uint8_t length_patch_id; //0x08 Length patch ID
        uint8_t patch_id[ 0x08 ];  //var Patch ID
        
        uint8_t tag_platform_build_id1;//0x03 Tag platform build ID1 Identifies the JCOP platform
        uint8_t length_platform_build_id; //0x18 Length platform build ID
        uint8_t platform_build_id[ 0x18 ];  //var Platform build ID
        
        uint8_t tag_fips_mode;    //0x052 Tag FIPS mode FIPS mode active
        uint8_t length_fips_mode; //0x01 Length FIPS mode
        uint8_t fips_mode;//var FIPS mode 0x00 - FIPS mode not active, 0x01 - FIPS mode active
        
        uint8_t tag_pre_perso_state;//0x07 Tag pre-perso state Lists pre-perso state
        uint8_t length_pre_perso_state;//0x01 Length pre-perso state
        //var Bit mask of pre-perso state bit0 = 1 = config module available,
        //  bit1 = 1 = transport state is active.
        //  Unused bits are set to 0x0.
        uint8_t bit_mask_of_pre_perso_state;

        uint8_t tag_rom_id;    //'08' Tag ROM ID Indentifies the ROM content
        uint8_t length_rom_id; //'08' Length ROM ID Normal ending
        uint8_t rom_id[ 0x08 ];  //var ROM ID
        uint8_t status_word_sw[ 0x02 ]; //9000h Status Word (SW)
    } identify_rsp_t;
    
    identify_rsp_t identify_rsp = {0};
    uint32_t prsp_len = sizeof(identify_rsp_t);
    log_info( &logger, " Get data identify" );
    frame_data.pcb = PLUGNTRUST_PCB_BLOCK_I;
    frame_data.len = 8;
    frame_data.apdu->cla = PLUGNTRUST_CLA_NOT_SECURE;
    frame_data.apdu->ins = 0xCA;
    frame_data.apdu->p1 = 0x00;
    frame_data.apdu->p2 = 0xFE;
    frame_data.apdu->payload_len = 0x02;
    frame_data.apdu->rsp_len = 0x00;
    uint8_t df28[ 2 ] = { 0xDF, 0x28 };
    memcpy( frame_data.apdu->payload, df28, 2 );
    plugntrust_apdu_transfer( &plugntrust, &frame_data );
    if ( frame_data.len == prsp_len )
    {
        memcpy( (uint8_t *)&identify_rsp, frame_data.apdu->payload, prsp_len );
        log_printf( &logger, " > Tag value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_value_proprietary_data );
        log_printf( &logger, " > Length value: %d\r\n", ( uint16_t ) identify_rsp.length_of_following_data );
        log_printf( &logger, " > Tag Card ID value: 0x" );
        log_buf_hex( identify_rsp.tag_card_identification_data, 2 );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Length of Card ID value: %d\r\n", ( uint16_t ) identify_rsp.length_of_card_identification_data );
        log_printf( &logger, " > Tag of Configuration ID value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_configuration_id );
        log_printf( &logger, " > Length of Configuration ID value: %d\r\n", ( uint16_t ) identify_rsp.length_configuration_id );
        log_printf( &logger, " > Configuration ID: 0x" );
        log_buf_hex( identify_rsp.configuration_id, identify_rsp.length_configuration_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of Patch ID value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_patch_id );
        log_printf( &logger, " > Length of Patch ID value: %d\r\n", ( uint16_t ) identify_rsp.length_patch_id );
        log_printf( &logger, " > Patch ID: 0x" );
        log_buf_hex( identify_rsp.patch_id, identify_rsp.length_patch_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of Platform Build ID1 value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_platform_build_id1 );
        log_printf( &logger, " > Length of Platform Build ID1 value: %d\r\n", ( uint16_t ) identify_rsp.length_platform_build_id );
        log_printf( &logger, " > Platform Build ID1: 0x" );
        log_buf_hex( identify_rsp.platform_build_id, identify_rsp.length_platform_build_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of FIPS Mode value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_fips_mode );
        log_printf( &logger, " > Length of FIPS Mode value: %d\r\n", ( uint16_t ) identify_rsp.length_fips_mode );
        log_printf( &logger, " > FIPS Mode: 0x" );
        log_buf_hex( &identify_rsp.fips_mode, identify_rsp.length_fips_mode );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of Pre-Preso State value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_pre_perso_state );
        log_printf( &logger, " > Length of Pre-Preso State value: %d\r\n", ( uint16_t ) identify_rsp.length_pre_perso_state );
        log_printf( &logger, " > Pre-Preso State: 0x" );
        log_buf_hex( &identify_rsp.bit_mask_of_pre_perso_state, identify_rsp.length_pre_perso_state );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Tag of ROM ID value: 0x%0.2X\r\n", ( uint16_t ) identify_rsp.tag_rom_id );
        log_printf( &logger, " > Length of ROM ID value: %d\r\n", ( uint16_t ) identify_rsp.length_rom_id );
        log_printf( &logger, " > ROM ID: 0x" );
        log_buf_hex( identify_rsp.rom_id, identify_rsp.length_rom_id );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Status Word: 0x" );
        log_buf_hex( identify_rsp.status_word_sw, 2 );
        log_printf( &logger, "\r\n" );
    }
    else
    {
        log_error( &logger, " Size Error" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
    end_apdu_session( );
}

static void end_apdu_session ( void )
{
    if ( PLUGNTRUST_OK != plugntrust_end_apdu_session( &plugntrust ) )
    {
        log_error( &logger, " End APDU session" );
    }
}

static void create_check_delete ( void )
{    
    //create binary object
    log_info( &logger, " Write Binary" );
    uint8_t data_buf[ 7 ] = "MikroE";
    uint32_t binary_id = 0xAAAAAAAAul;

    if ( PLUGNTRUST_OK != plugntrust_write_binary_object( &plugntrust, 
            binary_id, 0, 6, data_buf ) )
    {
        log_error( &logger, " Write Binary" );
    }
    log_printf( &logger, "************************************************************************\r\n" );

    //check if object exists
    log_info( &logger, " Check object exists" );
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " > Object exist\r\n" );
    }
    else
    {
        log_printf( &logger, " > Object doesn't exist\r\n" );
    } 
    log_printf( &logger, "************************************************************************\r\n" );
    
    //read binary object
    log_info( &logger, " Read object" );
    reset_parse();
    if ( PLUGNTRUST_OK == plugntrust_read_object( &plugntrust, 
            binary_id, 0, 0, parse_data, &parse_len ) )
    {
        log_printf( &logger, " > Object data: %s\r\n", parse_data );
    }
    else
    {
        log_error( &logger, " Read binary object" );
    } 
    log_printf( &logger, "************************************************************************\r\n" );
    //delete object
    log_info( &logger, " Delete Secure Object" );
    if ( PLUGNTRUST_OK == plugntrust_delete_object( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " Object 0x%0.8LX deleted\r\n", binary_id );
    }
    else
    {
        log_error( &logger, " Delete Object"  );
    }
    log_printf( &logger, "************************************************************************\r\n" );
    //check if object exists
    log_info( &logger, " Check object exists" );
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, binary_id ) )
    {
        log_printf( &logger, " > Object exist\r\n" );
    }
    else
    {
        log_printf( &logger, " > Object doesn't exist\r\n" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void list_and_delete_objects( void )
{     
    plugntrust_write_binary_object( &plugntrust, 0xAABBCCDDul, 0, 4, "Data" );
    
    log_info( &logger, " Get Object list" );  
    uint32_t ids[ 30 ] = { 0 };
    uint8_t len = 0;
    if ( PLUGNTRUST_OK == plugntrust_object_id_list( &plugntrust, ids, &len ) )
    {
        log_info( &logger, " List len: %d", ( uint16_t )len );
        for ( uint8_t cnt = 0; cnt < len; cnt++ )
        {   //if not NXP defined objectect delete that object
            if ( ( PLUGNTRUST_OBJID_SE05X_APPLET_RES_START != ( PLUGNTRUST_OBJID_APPLET_MASK & ids[ cnt ] ) ) &&
                 ( PLUGNTRUST_SSS_OBJID_DEMO_AUTH_START != ( PLUGNTRUST_OBJID_APPLET_MASK & ids[ cnt ] ) ) &&
                 ( PLUGNTRUST_SSS_OBJID_IOT_HUB_A_START != ( PLUGNTRUST_OBJID_IOT_MASK & ids[ cnt ] ) ) )
            {
                if ( PLUGNTRUST_OK == plugntrust_delete_object( &plugntrust, ids[ cnt ] ) )
                {
                    log_printf( &logger, " > Object Deleted 0x%.8LX\r\n", ids[ cnt ] );
                }
                else
                {
                    log_error( &logger, " Delecte Object  0x%.8LX", ids[ cnt ] );
                }
            }
            else
            {
                log_printf( &logger, " > Object ID: 0x%.8LX\r\n", ids[ cnt ] );
            }
        }
    }
    else
    {
        log_error( &logger, " Object ID List" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void select_applet ( void )
{
    log_info( &logger, " Select SE050 Applet" );
    plugntrust_version_info_t ver_info;
    plugntrust_select_applet( &plugntrust, PLUGNTRUST_PCB_BLOCK_I_NS_ENCODE, &ver_info );
    log_printf( &logger, " > Applet Version = %d.%d.%d\r\n", ( uint16_t )ver_info.major_version, 
                                                             ( uint16_t )ver_info.minor_version, 
                                                             ( uint16_t )ver_info.patch_version );
    log_printf( &logger, " > AppletConfig = 0x%0.4X\r\n", ver_info.applet_config );
    log_printf( &logger, " > SecureBox = 0x%0.4X\r\n", ver_info.secure_box );
    log_printf( &logger, "************************************************************************\r\n" );
}

static void aes_cipher ( void )
{
    //Create AES Key
    log_info( &logger, " Write AES Key" );
    #define AES_DATA_SIZE 16
    uint8_t aes_value[ AES_DATA_SIZE ] = { 0x40, 0x41, 0x42, 0x43,0x44, 0x45, 0x46, 0x47,
                                           0x48, 0x49, 0x4A, 0x4B,0x4C, 0x4D, 0x4E, 0x4F };
    uint32_t symm_id = 0x12345678ul;
    create_128_aes_key( symm_id, aes_value );
    
    //Encrypt Data
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, symm_id ) )
    {
        log_info( &logger, " Encrypt Data" );
        uint8_t data_value[ 16 ] = { ' ', '>', 'P', 'l', 'u', 'g', ' ', '&', ' ', 'T', 'r', 'u', 's', 't', '<', ' ' };
        reset_parse( );
        if ( PLUGNTRUST_OK == cipher_data_with_aes_key( symm_id, PLUGNTRUST_P2_ENCRYPT_ONESHOT, data_value, parse_data ) )
        {
            log_printf( &logger, " > Encrypted data hex: 0x" );
            log_buf_hex( parse_data, AES_DATA_SIZE );
            log_printf( &logger, "\r\n" );
            log_printf( &logger, " > Encrypted data string: %s\r\n", parse_data );
        }
        else
        {
            log_error( &logger, " Parse error" );
        }
    }
    else
    {
        log_printf( &logger, " > Object doesn't exist\r\n" );
    } 
    log_printf( &logger, "************************************************************************\r\n" );

    //Decrypt Data
    log_info( &logger, " Decrypt Data" );
    if ( PLUGNTRUST_OK == cipher_data_with_aes_key( symm_id, PLUGNTRUST_P2_DECRYPT_ONESHOT, parse_data, parse_data ) )
    {
        log_printf( &logger, " > Decrypted data hex: 0x" );
        log_buf_hex( parse_data, parse_len );
        log_printf( &logger, "\r\n" );
        log_printf( &logger, " > Decrypted data string: %s\r\n", parse_data );
    }
    else
    {
        log_error( &logger, " Parse error" );
    }
    log_printf( &logger, "************************************************************************\r\n" );
    
    //Delete Object
    log_info( &logger, " Delete Secure Object" );
    if ( PLUGNTRUST_OK == plugntrust_delete_object( &plugntrust, symm_id ) )
    {
        log_printf( &logger, " Object 0x%0.8LX deleted\r\n", symm_id );
    }
    else
    {
        log_error( &logger, " Delete Object"  );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void select_card_manger ( void )
{
    log_info( &logger, " Select the card manager " );
    if ( PLUGNTRUST_OK != plugntrust_select_card_manager( &plugntrust, PLUGNTRUST_CARD_MANAGER_WITHOUT_RSP, 0, 0 ) )
    {
        log_error( &logger, " Card manager"  );
    }
    log_printf( &logger, "************************************************************************\r\n" );
}

static void create_128_aes_key ( uint32_t aes_id, uint8_t *aes_key )
{
    #define AES_KEY_SIZE 16
    frame_data.pcb = PLUGNTRUST_PCB_BLOCK_I;
    frame_data.apdu->cla = PLUGNTRUST_CLA_NOT_SECURE;
    frame_data.apdu->ins = PLUGNTRUST_INS_WRITE | PLUGNTRUST_INS_TRANSIENT;
    frame_data.apdu->p1 = PLUGNTRUST_P1_AES;
    frame_data.apdu->p2 = PLUGNTRUST_P2_DEFAULT;
    frame_data.apdu->payload_len = 0;//reset apdu payload_len
    frame_data.apdu->rsp_len = 0;//reset apdu le value
    plugntrust_set_tlv_u32( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                            PLUGNTRUST_TLV_TAG_1, aes_id ); //AES key ID
    plugntrust_set_tlv_u8buf( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                            PLUGNTRUST_TLV_TAG_3, aes_key, AES_KEY_SIZE ); //AES key value
    frame_data.len = plugntrust_calculate_apdu_size( frame_data.apdu ); //calculate apdu size
    plugntrust_apdu_transfer( &plugntrust, &frame_data );
    log_status();
    end_apdu_session( );
}

static err_t cipher_data_with_aes_key ( uint32_t aes_id, uint8_t cipher_type, uint8_t *data_in, uint8_t *data_out )
{
    if ( PLUGNTRUST_OBJECT_DOES_EXISTS == plugntrust_check_object_exist( &plugntrust, aes_id ) )//check if object with aes_id exists
    {
        frame_data.pcb = PLUGNTRUST_PCB_BLOCK_I;
        frame_data.apdu->cla = PLUGNTRUST_CLA_NOT_SECURE;
        frame_data.apdu->ins = PLUGNTRUST_INS_CRYPTO;
        frame_data.apdu->p1 = PLUGNTRUST_P1_CIPHER;
        frame_data.apdu->p2 = cipher_type;//PLUGNTRUST_P2_ENCRYPT_ONESHOT || PLUGNTRUST_P2_DECRYPT_ONESHOT
        frame_data.apdu->payload_len = 0;
        frame_data.apdu->rsp_len = 0;
        frame_data.len = 0;
        plugntrust_set_tlv_u32( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                                PLUGNTRUST_TLV_TAG_1, aes_id );//set aes key to be used
        plugntrust_set_tlv_u8( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                                PLUGNTRUST_TLV_TAG_2, PLUGNTRUST_CIPHER_AES_CTR );//set ae cipher type to be used
        plugntrust_set_tlv_u8buf( frame_data.apdu->payload, &frame_data.apdu->payload_len, 
                                PLUGNTRUST_TLV_TAG_3, data_in, 16 );//set data to encrypt/decrypt
        frame_data.len = plugntrust_calculate_apdu_size( frame_data.apdu );//calculate apdu data
        frame_data.len++;//increment data
        plugntrust_apdu_transfer( &plugntrust, &frame_data );
        reset_parse( );//reset prase data
        if ( PLUGNTRUST_OK == plugntrust_get_tlv_u8buf( frame_data.apdu->payload, &parse_index, frame_data.len, 
                                                        PLUGNTRUST_TLV_TAG_1, data_out, &parse_len ) )//get encryted/decrypted data
        {
            end_apdu_session( );
            return PLUGNTRUST_OK;
        }
        else
        {
            end_apdu_session( );
            return PLUGNTRUST_ERROR;
        }
    }
    else
    {
        return PLUGNTRUST_ERROR;
    }
}

// ------------------------------------------------------------------------ END

额外支持

资源

喜欢这个项目吗?

'购买此套件' 按钮会直接带您进入购物车,您可以在购物车中轻松添加或移除产品。