軟體加密包(STM32 密碼學)

前言

客戶在部分設備中需要加密保護,ST這邊提供2種方式

  • 硬體加密:選擇帶有硬體加密MCU(在ST列表中深藍色代表帶有硬體加密)
  • 軟體加密包X-CUBE-CRYPTOLIB可以使用在ST全系列MCU(需要留意Flash size)

V4的目錄結構 vs. V3的目錄結構

V3軟件包的目錄結構是每一個STM32系列對應一個單獨的目錄

  • 每個芯片系列都有對應的Middleware目錄, 裡麵包含加解密庫
  • 加解密庫有多個庫文件,分別針對不同編譯器以及不同的優化選項
  • 參考例程工程同樣也在每個STM32系列子目錄的Projects目錄中。

V4的目錄結構則完全兼容Cube/X-Cube軟件包(STM32Cubexx / X-Cube-xxx)架構,方便與Cube/X-Cube包進行集成。

  • V4中包含加解密庫的Middleware文件夾直接在頂層目錄
  • lib目錄下的庫文件不針對每個STM32系列,也不再區分不同的編譯器和優化方式
  • 加解密庫文件按照Cortex內核版本,每個內核提供一個統一的庫文件
  • 同一個庫文件可以適用於各種編譯器(AEABI兼容)
  • 對於不同優化選項的選擇可以在鏈接階段進行配置

AES加密

這邊因客戶AES使用較多,會以AES做舉例說明。

AES介紹

AES 是一個 對稱的 加密類型。
“對稱”意味著它使用 加密和解密的密鑰相同 信息此外, 都 發送方和接收方 的數據需要它的副本來解密密碼。
另一方面, 非對稱 關鍵系統使用 每個不同的鍵 兩個過程:加密和解密。
一個對稱系統的優勢 就像 AES 他們是 比非對稱快得多 那些。 這是因為對稱密鑰算法需要 更少的計算能力。 
這就是為什麼非對稱密鑰最適合用於 外部文件傳輸。 對稱鍵更適合 內部加密.

AES 流程

AES流程可以參考下面影片與圖,可以更加明白其操作

ST AES硬體加密

首先可以看到硬體加密的結構如圖
ST也有提供4種模式

  • Mode 1: Encryption using the encryption key stored in the AES Key registers.
  • Mode 2: Key derivation which derives a new key based on the value stored in the AES Key registers before enabling the AES accelerator. This mode is independent from the AES chaining mode selection.
  • Mode 3: Decryption using a given (pre-computed) decryption key stored in the AES Key registers.
  • Mode 4: Key derivation + decryption using an encryption key stored in the AES Key registers (not used 4 when the AES is configured in Counter mode for perform a chaining algorithm).

ST AES LIB軟體實現

這邊下載軟體包後需要把Lib加入專案中下面為Lib路徑

Middlewares\ST\STM32_Cryptographic

這邊使用以變相當便捷主要是呼叫cmox_cipher_encrypt此函數引用ST Lib即可使用

 /* Initialize cryptographic library */
  if (cmox_initialize(NULL) != CMOX_INIT_SUCCESS)
  {
    Error_Handler();
  }

  /* --------------------------------------------------------------------------
   * SINGLE CALL USAGE
   * --------------------------------------------------------------------------
   */

  /* Compute directly the ciphertext passing all the needed parameters */
  /* Note: CMOX_AES_CBC_ENC_ALGO refer to the default AES implementation
   * selected in cmox_default_config.h. To use a specific implementation, user can
   * directly choose:
   * - CMOX_AESFAST_CBC_ENC_ALGO to select the AES fast implementation
   * - CMOX_AESSMALL_CBC_ENC_ALGO to select the AES small implementation
   */
  retval = cmox_cipher_encrypt(CMOX_AES_CBC_ENC_ALGO,                  /* Use AES CBC algorithm */
                               Plaintext, sizeof(Plaintext),           /* Plaintext to encrypt */
                               Key, sizeof(Key),                       /* AES key to use */
                               IV, sizeof(IV),                         /* Initialization vector */
                               Computed_Ciphertext, &computed_size);   /* Data buffer to receive generated ciphertext */

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart