file/file_encrypt/main.c

/*******************************************************************************
* # License
* Copyright 2019 Silicon Laboratories Inc. www.silabs.com
*******************************************************************************
*
* The licensor of this software is Silicon Laboratories Inc. Your use of this
* software is governed by the terms of Silicon Labs Master Software License
* Agreement (MSLA) available at
* www.silabs.com/about-us/legal/master-software-license-agreement. This
* software is distributed to you in Source Code format and is governed by the
* sections of the MSLA applicable to Source Code.
*
******************************************************************************/
#include "gos.h"
#include "crypto.h"
// A random 128 bit hex string used as the encryption key.
// This is typically generated at manufacturing time and stored in a database.
// Ideally the encryption key is unique per device.
#define SECURITY_KEY "f12ca2a9dae8bdb48d959e65ec54f6da"
// Size of dummy file to generate
#define FILE_SIZE 1500
#define OUTPUT_FILENAME "encrypted_file_example.bin"
#define APPLICATION_START_LINE "\r\n\r\nStarting File Encryption Example"
uint8_t dummy_buffer[FILE_SIZE];
/*************************************************************************************************/
void gos_app_init(void)
{
gos_result_t result;
uint8_t key[33];
GOS_LOG(APPLICATION_START_LINE);
// First set the user encryption key
// Gecko OS will use this to decrypt user encrypted files
// NOTE: This setting does NOT reset after a factory reset
gos_settings_set_str("system.security_key", SECURITY_KEY);
GOS_LOG("Generating buffer with %d bytes of dummy data", FILE_SIZE);
// Populate dummy file with decimal characters
{
char c = '0';
char *ptr = (char*)dummy_buffer;
for(int i = FILE_SIZE; i > 0; --i)
{
*ptr++ = c++;
if(c == '9'+1)
c = '0';
}
}
// Convert hex key string to binary
strcpy((char*)key, SECURITY_KEY);
str_hex_to_binary((char*)key);
GOS_LOG("Encrypting file ...");
// Encrypt the buffer
result = encrypt_buffer_to_file(key, dummy_buffer, FILE_SIZE, OUTPUT_FILENAME);
if (result == GOS_SUCCESS)
{
GOS_LOG("Encrypted file created: %s", OUTPUT_FILENAME);
// Erase the contents of the buffer
memset(dummy_buffer, 0, FILE_SIZE);
GOS_LOG("Decrypting file ...");
// Decrypt the buffer
result = decrypt_file_to_buffer(key, OUTPUT_FILENAME, dummy_buffer, FILE_SIZE);
if (result == GOS_SUCCESS)
{
GOS_LOG("File successfully decrypted into buffer");
}
else
{
GOS_LOG("Failed to decrypt file: %d", result);
}
}
else
{
GOS_LOG("Failed to encrypt file: %d", result);
}
GOS_LOG("Done");
}