Sunday, January 21, 2024

ESP32-C3 Exploring Embedded Security with ESP32 inbuilt modules


Random Number Generator: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html


Random Numbers are very important in Secuirty and a true random number generator is essential for generating a high entroy randomly generated Security Key.

So, ESP32-C3 has a random number generator module in built we will be using that to generate Random key.
Sample code to generate random key with Random number generator 



#include <stdio.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "driver/gpio.h"
#include "esp_log.h"
#include "led_strip.h"
#include "sdkconfig.h"

//random gen
#include <stdint.h>
#include "esp_random.h"


static const char *TAG = "randomGen";

void generate_random_key(uint8_t *key, size_t key_length) {
size_t i;
for (i = 0; i < key_length / sizeof(uint32_t); ++i) {
((uint32_t *)key)[i] = esp_random();
}
}



void app_main(void)
{
while (1) {
// Example: Generate a 128-bit random key
uint8_t random_key[16];
generate_random_key(random_key, sizeof(random_key));

// Print the generated key
ESP_LOGI(TAG,"Random Key: ");
for (size_t i = 0; i < sizeof(random_key); ++i) {
printf("%02X", random_key[i]);
}
vTaskDelay(5000 / portTICK_PERIOD_MS);
printf("\n");

}
}

Output:




SHA: Generating Hash for given data on ESP32

SHA, or Secure Hash Algorithm, is a family of cryptographic hash functions designed by the National Security Agency (NSA) and published by the National Institute of Standards and Technology (NIST) in the United States. The SHA family consists of several hash functions with different bit lengths, such as SHA-1, SHA-256, SHA-384, SHA-512, and more. Each variant produces a fixed-size hash value, which is typically expressed as a hexadecimal number.

Key Characteristics of SHA:

Collision Resistance: One of the primary objectives of a cryptographic hash function is collision resistance. A collision occurs when two different inputs produce the same hash output. A secure hash function should make it computationally infeasible to find collisions.


Deterministic: For the same input, a SHA function will always produce the same output (hash). This property is essential for verifying data integrity and authenticity.


Fixed Output Size: Each SHA variant produces a fixed-size hash value, regardless of the size of the input data. For example, SHA-256 always produces a 256-bit (32-byte) hash.


Pre-image Resistance: It should be computationally infeasible to reverse the hash function, meaning it should be challenging to find an input that corresponds to a given hash output.

Common Use Cases:

Data Integrity: SHA functions are commonly used to ensure the integrity of data. By comparing the hash of the original data with the hash of received or stored data, one can verify whether the data has been tampered with or corrupted.


Digital Signatures: In digital signatures, a hash of a message is signed to prove the authenticity of the sender and the integrity of the message. The recipient can verify the signature using the sender's public key.


Password Hashing: In password security, storing actual passwords is a security risk. Instead, systems store the hash of passwords. During login, the system hashes the entered password and compares it with the stored hash.


Blockchain and Cryptocurrencies: Cryptocurrencies like Bitcoin use SHA-256 for hashing blocks and creating digital signatures. The immutability of the blockchain relies on the cryptographic properties of the SHA function.


Certificate Authorities: In SSL/TLS and other secure communication protocols, SHA functions are used in digital certificates to verify the authenticity of public keys.

SHA is a fundamental building block of modern cryptography and information security. Its properties make it suitable for a wide range of applications where data integrity, authenticity, and security are paramount.

Below is an Example of how to do it with IDF in ESP32-C3
#include <stdio.h>
#include <string.h>
#include <esp_log.h>
#include <mbedtls/sha256.h>

static const char *TAG = "Hello-SHA";

void sha_example(const char *input, size_t input_len) {
mbedtls_sha256_context sha_ctx;
unsigned char output[32]; // SHA-256 produces a 32-byte hash

mbedtls_sha256_init(&sha_ctx);
mbedtls_sha256_starts(&sha_ctx, 0);

// Update hash with input data
mbedtls_sha256_update(&sha_ctx, (const unsigned char *)input, input_len);

// Finish the hash calculation
mbedtls_sha256_finish(&sha_ctx, output);

// Print the result
ESP_LOGI(TAG, "SHA-256 Hash:");
for (int i = 0; i < 32; i++) {
printf("%02x", output[i]);
}
printf("\n");

mbedtls_sha256_free(&sha_ctx);
}

void app_main() {
// Your input data
const char *input_data = "A quick brown fox jump over the lazy dog!";

// Calculate SHA-256 hash
sha_example(input_data, strlen(input_data));
}

Output:





Check if the generated Hash is correct:


Saturday, January 13, 2024

Security on Embedded Systems: focusing on ESP32-C3



Learning about security features in microcontrollers is a great initiative. Here's a sequence to approach these topics:


Basics of Cryptography:Start with understanding the basics of cryptography.
Learn about symmetric and asymmetric key cryptography.
Understand concepts like encryption, decryption, hashing, and digital signatures.


SHA Accelerator:Begin with Secure Hash Algorithm (SHA) functions (e.g., SHA-256).
Learn how the SHA Accelerator works on the ESP32-C3.
Explore use cases for hashing, such as ensuring data integrity.


AES Accelerator:Move on to Advanced Encryption Standard (AES).
Understand the principles of symmetric-key encryption.
Learn about block ciphers, key expansion, encryption modes, and practical uses.


RSA Accelerator:Study the RSA algorithm for asymmetric key cryptography.
Understand key generation, encryption, and decryption processes.
Explore how the RSA Accelerator on the ESP32-C3 can be used for secure communication.


HMAC Accelerator:Dive into Hash-based Message Authentication Code (HMAC).
Learn how HMAC combines cryptographic hash functions with a secret key.
Explore how HMAC can be used for data integrity and authenticity.


Digital Signature Modules:Understand the concept of digital signatures.
Learn about algorithms like ECDSA (Elliptic Curve Digital Signature Algorithm).
Explore how digital signatures are generated and verified.


Implementing Security in Embedded Systems:Combine your knowledge of cryptographic algorithms with the specific features of the ESP32-C3.
Learn how to use the security accelerators on the microcontroller.
Implement secure communication protocols and data storage mechanisms.


Secure Boot and Firmware Update:Explore advanced topics like secure boot mechanisms.
Learn about securely updating firmware on microcontrollers.
Understand how to maintain the integrity and authenticity of firmware.


Practical Projects:Apply your knowledge in practical projects.
Build projects that involve secure communication, data storage, and firmware updates.


Security Best Practices:Learn about general security best practices for embedded systems.
Understand common vulnerabilities and how to mitigate them.
Keep up-to-date with security developments in the field.

Remember to use the ESP32-C3 datasheet and technical reference manual as primary resources, as they will provide detailed information about the security features and how to utilize them effectively.





Tuesday, January 2, 2024

Privacy and Consent Policy


Last Updated: 3 January 2024

Introduction


Welcome to the Embedded System Interviewer blog ("we," "us," or "our"). Protecting your privacy is important to us. This Privacy and Consent Policy explains how we collect, use, and safeguard your personal information when you visit our blog. By using our blog, you agree to the terms outlined in this policy.

Information We Collect

1. Personal Information:

   - When you subscribe to our newsletter or contact us, we may collect your name and email address.

   - We may collect personal information you choose to share when commenting on blog posts.

2. Non-personal Information:

   - We use cookies to collect non-personal information, including your IP address, browser type, and browsing patterns. This information helps us improve user experience and analyze website traffic.

How We Use Your Information

1. Communication:

   - We may use your personal information to send you newsletters, and updates, and respond to your inquiries.

2. Analytics:

   - Non-personal information is used for analytics purposes to understand user behavior and enhance our content.

Cookies

We use cookies to enhance your experience on our blog. You can manage cookie preferences through your browser settings.

Third-Party Links

Our blog may contain links to third-party websites. We are not responsible for the privacy practices of these websites. Please review their privacy policies.


Your Consent

By using our blog, you consent to the terms outlined in this Privacy and Consent Policy.


Your Rights

You have the right to:
- Access, correct, or delete your personal information.
- Object to the processing of your personal information.
- Withdraw your consent for receiving communications.


To exercise these rights or for questions regarding your privacy, contact us at shirish.jadav47@gmail.com.


Updates to this Policy

We may update this policy periodically. Check the "Last Updated" date for the latest version.


Contact Information

If you have questions or concerns about this Privacy and Consent Policy, please contact us at shirish.jadav47@gmail.com.


Monday, January 1, 2024

Bitwise Brilliance: Bitwise operations and Common interview Questions

Unleashing the Power of Bits: A Dive into Bitwise Operations in C



In the realm of programming, every bit matters. Bitwise operations, often regarded as the unsung heroes of low-level manipulation, allow programmers to perform intricate tasks at the fundamental level of binary representation. This blog embarks on a journey into the world of bitwise brilliance, focusing on the art of bit manipulation in the C programming language.

Bits and Bytes: The Currency of Computers

At the core of every data manipulation lies a binary dance of 0s and 1s. Understanding how to sway these bits with precision opens doors to elegant solutions and efficient algorithms. Bitwise operations provide the tools to navigate this binary landscape, allowing programmers to perform tasks that might seem magical to the uninitiated.

Reversing Binary Integers: A Practical Exploration

Our journey commences with a practical example — the reversal of a binary integer. Through the magic of bitwise XOR, AND, and left-shifting, we'll unravel the steps to flip the binary representation of a number. The intricacies of these operations might seem cryptic at first, but as we dissect each bitwise maneuver, you'll discover the elegance and efficiency they bring to the table.

The Bitwise Toolbox: Shifting Perspectives

Bitwise operations extend far beyond reversing binaries. They are the tools behind setting and clearing specific bits, checking for parity, and even performing arithmetic operations at the level of individual bits. As we delve deeper into this bitwise toolbox, you'll find yourself equipped with the knowledge to tackle a myriad of programming challenges with finesse.

Why Care About Bits?

In a world dominated by high-level abstractions, one might wonder why we should care about bits and bitwise operations. The answer lies in efficiency, optimization, and the sheer joy of mastering the fundamental building blocks of computation. Whether you're working on embedded systems, algorithm design, or simply honing your programming prowess, a solid understanding of bitwise operations will undoubtedly set you apart.

Join us on this journey into the heart of binary manipulation. Bitwise brilliance awaits as we uncover the secrets of C's bitwise operations and witness the transformation of 0s and 1s into a symphony of efficient and elegant code. Let's unravel the magic together!


Write a program to Reverse a Bit integer


#include <stdio.h>
// Function to reverse the bits of an integer
unsigned int reverseBinary(unsigned int num) {
    unsigned int numOfBits = sizeof(num) * 8; // Get the number of bits in an integer
    unsigned int reverseNum = 0;
    for (int i = 0; i < numOfBits; i++) {
        if ((num & (1 << i)) != 0) {
            reverseNum |= 1 << ((numOfBits - 1) - i);
        }
    }
    return reverseNum;
}
int main() {
    unsigned int num;
    // Input binary number
    printf("Enter a binary number: ");
    scanf("%u", &num);
    // Reverse the binary number
    unsigned int reversedNum = reverseBinary(num);
    // Display the result
    printf("Original binary: %u\n", num);
    printf("Reversed binary: %u\n", reversedNum);
    return 0;
}


There are 2 numbers A and B, How many bits you need to flip to equate both the numbers?

#include <stdio.h>
// Function to count the number of bits to be flipped
int countBitsToFlip(int a, int b) {
    int xorResult = a ^ b; // XOR of the two numbers
    int count = 0;
    // Count the set bits in the XOR result
    while (xorResult) {
        count += xorResult & 1;
        xorResult >>= 1;
    }
    return count;
}
int main() {
    int numA, numB;
    // Input numbers
    printf("Enter number A: ");
    scanf("%d", &numA);
    printf("Enter number B: ");
    scanf("%d", &numB);
    // Calculate and display the result
    int flips = countBitsToFlip(numA, numB);
    printf("To make %d and %d equal, you need to flip %d bits.\n", numA, numB, flips);
    return 0;
}

swap the LSB bit to MSB bit of 32 bit integer

#include <stdio.h>

// Function to swap LSB with MSB
unsigned int swapLSBwithMSB(unsigned int num) {
    // Extract LSB and MSB
    unsigned int lsb = num & 1;
    unsigned int msb = (num >> 31) & 1;

    // Clear LSB and MSB in the original number
    num &= 0xFFFFFFFE; // Clear LSB
    num &= 0x7FFFFFFF; // Clear MSB

    // Swap and set the new LSB and MSB
    num |= (lsb << 31); // Set new MSB
    num |= (msb);       // Set new LSB

    return num;
}

int main() {
    unsigned int num;

    // Input number
    printf("Enter a 32-bit number: ");
    scanf("%u", &num);

    // Swap LSB with MSB and display the result
    unsigned int result = swapLSBwithMSB(num);
    printf("Original number: %u\n", num);
    printf("Number after swapping LSB with MSB: %u\n", result);

    return 0;
}

write a program to find endiness?

#include <stdio.h>

// Function to check endianness
int isLittleEndian() {
    int num = 1;
    // Casting the address of the integer to a char pointer
    // allows us to check the value of the first byte (LSB).
    return (*(char*)&num == 1);
}

int main() {
    if (isLittleEndian()) {
        printf("The system is Little Endian.\n");
    } else {
        printf("The system is Big Endian.\n");
    }

    return 0;
}


Navigating the Layers: Visualizing BLE and Wi-Fi Protocol Stacks



In the intricate world of wireless communication, understanding the layers that constitute a protocol stack is paramount. Let's embark on a visual journey to explore the layers of the Bluetooth Low Energy (BLE) and Wi-Fi protocol stacks, unraveling the complexities that enable seamless connectivity.

Bluetooth Low Energy (BLE) Stack:

At the topmost layer, we find the Application Layer, where BLE Profiles, such as Generic Attribute Profile (GATT) and Generic Access Profile (GAP), define the behavior of devices and services. Descending through the stack, we encounter the Attribute Protocol (ATT), GATT, L2CAP (Logical Link Control and Adaptation Protocol), the Security Manager, Link Layer, and finally, the Physical Layer. Each layer plays a crucial role, from managing device attributes to handling security and transmission over the airwaves.

BLE Stack:

Visual Representation:
+---------------------+ | Application | | Layer | +---------------------+ | BLE Profiles | +---------------------+ | ATT | | GATT | | L2CAP | | Security Manager | | Link Layer | | Physical Layer | +---------------------+


  1. Application Layer:

    • BLE Profiles (e.g., GATT, GAP) define the behavior of devices and services.
  2. BLE Stack Layers:

    • ATT (Attribute Protocol): Manages the attributes of the device.
    • GATT (Generic Attribute Profile): Describes how to use attributes.
    • L2CAP (Logical Link Control and Adaptation Protocol): Provides multiplexing of data between different higher-layer protocols.
    • Security Manager: Handles security-related aspects of BLE communication.
    • Link Layer: Manages connections and handles physical layer details.
    • Physical Layer: Deals with the actual transmission of bits over the air.
  3. Physical Layer:

    • Radio signals, modulation, and transmission.

Wi-Fi Stack:

Similarly, the Wi-Fi stack unfolds with the Application Layer housing application-specific protocols like HTTP and MQTT. Descending, we encounter the TCP (Transmission Control Protocol), IP (Internet Protocol), ARP (Address Resolution Protocol), Link Layer, and the Physical Layer. These layers collectively ensure reliable packet delivery, manage routing and addressing, and handle the intricate dance of radio signals and modulation

Wi-Fi Stack:

Visual Representation:
+---------------------+ | Application | | Layer | +---------------------+ | HTTP, MQTT, etc. | +---------------------+ | TCP | | IP | | ARP | | Link Layer | | Physical Layer | +---------------------+

  1. Application Layer:

    • TCP/IP stack, sockets, and higher-level application protocols.
  2. Wi-Fi Stack Layers:

    • HTTP, MQTT, etc.: Application-specific protocols.
    • TCP (Transmission Control Protocol): Ensures reliable, ordered, and error-checked delivery of packets.
    • IP (Internet Protocol): Handles routing and addressing.
    • ARP (Address Resolution Protocol): Maps IP addresses to MAC addresses.
    • Link Layer: Manages logical link control and physical layer details.
    • Physical Layer: Deals with actual transmission over the air.
  3. Physical Layer:

    • Radio signals, modulation, and transmission.

Interview questions to prepare for

Bluetooth Low Energy (BLE):

  1. What is Bluetooth Low Energy (BLE), and how does it differ from classic Bluetooth?

    • Answer: BLE is a wireless communication technology designed for short-range communication with low power consumption. It differs from classic Bluetooth in terms of energy efficiency, making it suitable for battery-powered devices.
  2. Explain the roles of GATT and GAP in BLE.

    • Answer: GATT (Generic Attribute Profile) defines how to use attributes for communication, while GAP (Generic Access Profile) manages the connection and discovery of devices.
  3. What is the significance of the advertising process in BLE?

    • Answer: Advertising is the process by which BLE devices broadcast their presence. It allows devices to discover each other and establish connections.
  4. How does BLE handle security, and what is the role of the Security Manager?

    • Answer: BLE uses the Security Manager to handle security aspects, including pairing and encryption to ensure secure communication between devices.
  5. Explain the concept of characteristic and service in the GATT profile.

    • Answer: In GATT, a service is a collection of characteristics, and a characteristic is a data value or structure that represents a specific piece of data.

Wi-Fi:

  1. Differentiate between TCP and UDP.

    • Answer: TCP (Transmission Control Protocol) provides reliable, connection-oriented communication, while UDP (User Datagram Protocol) is connectionless and provides faster, but unreliable, communication.
  2. What is the purpose of ARP in a Wi-Fi network?

    • Answer: ARP (Address Resolution Protocol) maps IP addresses to MAC addresses, enabling devices to communicate on the same local network.
  3. Explain the concept of DHCP in Wi-Fi networks.

    • Answer: DHCP (Dynamic Host Configuration Protocol) dynamically assigns IP addresses to devices on a network, simplifying network configuration.
  4. How does Wi-Fi handle multiple devices accessing the network simultaneously?

    • Answer: Wi-Fi uses contention-based protocols, like CSMA/CA (Carrier Sense Multiple Access with Collision Avoidance), to manage access in a shared environment.
  5. What is the significance of the TCP/IP stack in Wi-Fi communication?

    • Answer: The TCP/IP stack is a set of protocols that govern communication over the internet, providing a standardized way for devices to communicate in a network.

These questions cover a range of topics, from fundamental concepts to protocol-specific details, and are commonly used to assess a candidate's understanding of BLE and Wi-Fi technologies.

Conclusion: Navigating the Layers for Seamless Connectivity

In the realm of wireless communication, these protocol stacks serve as architectural blueprints, orchestrating the harmonious exchange of data between devices. As developers and engineers, understanding the intricacies of each layer empowers us to build robust and efficient systems.

Whether it's BLE facilitating energy-efficient communication in the Internet of Things (IoT) or Wi-Fi enabling high-speed data transfer in our homes and offices, the layers of these stacks work in concert to make the magic of wireless connectivity possible.

So, the next time you send a file over Wi-Fi or connect your BLE-enabled wearable device, visualize the journey through these layers—each one a crucial player in the symphony of wireless communication. Happy coding!

ESP32-C3 Exploring Embedded Security with ESP32 inbuilt modules

Random Number Generator: https://docs.espressif.com/projects/esp-idf/en/latest/esp32/api-reference/system/random.html Random Numbers are ver...