BLE Application to open a Garage door
Dependencies: BLE_API Crypto RNG mbed nRF51822
Fork of BLE_LED by
Diff: SecurityService.h
- Revision:
- 11:3de9b542eeac
- Child:
- 12:eaee29bfa1c7
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/SecurityService.h Wed Aug 26 00:13:10 2015 +0000 @@ -0,0 +1,67 @@ +#ifndef __BLE_SECURITY_SERVICE_H__ +#define __BLE_SECURITY_SERVICE_H__ + +#include "Crypto.h" +class SecurityService { +public: + const static uint16_t SECURITY_SERVICE_UUID = 0x3000; + const static uint16_t SECURITY_IV_CHARACTERISTIC_UUID = 0x3001; + const static uint16_t SECURITY_KEY_CHARACTERISTIC_UUID = 0x3002; + + SecurityService(BLE &_ble, char *shared_key) : + ble(_ble), + SecurityIV(SECURITY_IV_CHARACTERISTIC_UUID, (uint8_t *) 0), + SecurityKey(SECURITY_KEY_CHARACTERISTIC_UUID, (uint8_t *) 0) + { + boot = true; + GattCharacteristic *charTable[] = {&SecurityIV, &SecurityKey}; + + GattService SecurityService(SECURITY_SERVICE_UUID, charTable, sizeof(charTable) / sizeof(GattCharacteristic *)); + ble.gattServer().addService(SecurityService); + + //Initialize AES + setKey(shared_key); + genIV(); + } + + void decode(uint8_t *out, uint8_t *in, uint32_t len) { + AES myAES(AES_128, myKey, iv); + myAES.decrypt(out,in,len); + genIV(); + } + + void setKey(char *shared_key) { + if(boot) { + DBG("Set shared_key = %s\r\n", shared_key); + MD5::computeHash(myKey, (uint8_t*) shared_key, strlen(shared_key)); + } + } + + void bootComplete() { + boot = false; + } + + void genIV() { + //TODO RANDOM THIS: + uint8_t new_iv[16] = { 0xA2, 0x68, 0x56, 0x36, 0x52, 0x18, 0x71, 0xD0, 0x23, 0x06, 0xE2, 0xEB, 0x8F, 0x70, 0x27, 0xB3 }; + memcpy(iv, new_iv,16); + ble.gattServer().write(SecurityIV.getValueHandle(), (uint8_t *)iv, 16*sizeof(uint8_t)); + } + + GattAttribute::Handle_t getKeyHandle() const { + return SecurityKey.getValueHandle(); + } + +private: + BLE &ble; + ReadOnlyArrayGattCharacteristic<uint8_t, 16> SecurityIV; + WriteOnlyArrayGattCharacteristic<uint8_t, 16> SecurityKey; + bool boot; + + uint8_t iv[16]; + //openssl enc -aes-128-cbc -pass pass:********** -nosalt -P + uint8_t myKey[16]; + +}; + +#endif /* #ifndef __BLE_SECURITY_SERVICE_H__ */