├── .gitignore ├── doc └── resources │ └── SesameSDK_20231201.png ├── main ├── CMakeLists.txt ├── blecent.h ├── sesame │ ├── ssm_cmd.h │ ├── ssm.h │ ├── ssm_cmd.c │ └── ssm.c ├── main.c ├── Kconfig.projbuild ├── utils │ ├── aes-cbc-cmac.h │ ├── TI_aes_128.h │ ├── utils.c │ ├── types.h │ ├── c_ccm.h │ ├── utils.h │ ├── aes-cbc-cmac.c │ ├── c_ccm.c │ ├── TI_aes_128.c │ ├── uECC.h │ ├── curve-specific.inc │ └── uECC.c ├── candy.h └── blecent.c ├── sdkconfig.defaults ├── CMakeLists.txt ├── LICENSE ├── README.md ├── README_JP.md ├── README_EN.md └── .clang-format /.gitignore: -------------------------------------------------------------------------------- 1 | /build/ 2 | /sdkconfig.old 3 | /.vscode 4 | /ze_build.sh 5 | -------------------------------------------------------------------------------- /doc/resources/SesameSDK_20231201.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/CANDY-HOUSE/SesameSDK_ESP32_with_DemoApp/HEAD/doc/resources/SesameSDK_20231201.png -------------------------------------------------------------------------------- /main/CMakeLists.txt: -------------------------------------------------------------------------------- 1 | set(srcs "") 2 | file(GLOB_RECURSE all_c_files "./*.c") 3 | list(APPEND srcs "${all_c_files}") 4 | 5 | idf_component_register(SRCS "${srcs}" 6 | INCLUDE_DIRS "." "sesame" "utils") 7 | -------------------------------------------------------------------------------- /sdkconfig.defaults: -------------------------------------------------------------------------------- 1 | # Override some defaults so BT stack is enabled 2 | # in this example 3 | 4 | # 5 | # BT config 6 | # 7 | CONFIG_BT_ENABLED=y 8 | CONFIG_BTDM_CTRL_MODE_BLE_ONLY=y 9 | CONFIG_BTDM_CTRL_MODE_BR_EDR_ONLY=n 10 | CONFIG_BTDM_CTRL_MODE_BTDM=n 11 | CONFIG_BT_BLUEDROID_ENABLED=n 12 | CONFIG_BT_NIMBLE_ENABLED=y 13 | -------------------------------------------------------------------------------- /CMakeLists.txt: -------------------------------------------------------------------------------- 1 | # The following lines of boilerplate have to be in your project's 2 | # CMakeLists in this exact order for cmake to work correctly 3 | cmake_minimum_required(VERSION 3.16) 4 | 5 | set(EXTRA_COMPONENT_DIRS $ENV{IDF_PATH}/examples/bluetooth/nimble/common/nimble_central_utils) 6 | 7 | include($ENV{IDF_PATH}/tools/cmake/project.cmake) 8 | project(SesameSDK_ESP32) 9 | -------------------------------------------------------------------------------- /main/blecent.h: -------------------------------------------------------------------------------- 1 | #ifndef __BLECENT_H__ 2 | #define __BLECENT_H__ 3 | 4 | #include 5 | #include 6 | 7 | #ifdef __cplusplus 8 | extern "C" { 9 | #endif 10 | 11 | #include "ssm.h" 12 | 13 | void esp_ble_gatt_write(sesame * ssm, uint8_t * value, uint16_t length); 14 | 15 | void esp_ble_init(void); 16 | 17 | #ifdef __cplusplus 18 | } 19 | #endif 20 | 21 | #endif // __BLECENT_H__ 22 | -------------------------------------------------------------------------------- /main/sesame/ssm_cmd.h: -------------------------------------------------------------------------------- 1 | #ifndef __SSM_CMD_H__ 2 | #define __SSM_CMD_H__ 3 | 4 | #include "ssm.h" 5 | 6 | #ifdef __cplusplus 7 | extern "C" { 8 | #endif 9 | 10 | void send_reg_cmd_to_ssm(sesame * ssm); 11 | 12 | void handle_reg_data_from_ssm(sesame * ssm); 13 | 14 | void send_login_cmd_to_ssm(sesame * ssm); 15 | 16 | void send_read_history_cmd_to_ssm(sesame * ssm); 17 | 18 | void ssm_lock(uint8_t * tag, uint8_t tag_length); 19 | 20 | #ifdef __cplusplus 21 | } 22 | #endif 23 | 24 | #endif // __SSM_CMD_H__ 25 | -------------------------------------------------------------------------------- /main/main.c: -------------------------------------------------------------------------------- 1 | #include "blecent.h" 2 | #include "nvs_flash.h" 3 | #include "ssm_cmd.h" 4 | 5 | static const char * TAG = "main.c"; 6 | 7 | static void ssm_action_handle(sesame * ssm) { 8 | ESP_LOGI(TAG, "[ssm_action_handle][ssm status: %s]", SSM_STATUS_STR(ssm->device_status)); 9 | if (ssm->device_status == SSM_UNLOCKED) { 10 | ssm_lock(NULL, 0); 11 | } 12 | } 13 | 14 | void app_main(void) { 15 | ESP_LOGI(TAG, "SesameSDK_ESP32 [11/24][087]"); 16 | nvs_flash_init(); 17 | ssm_init(ssm_action_handle); 18 | esp_ble_init(); 19 | } 20 | -------------------------------------------------------------------------------- /main/Kconfig.projbuild: -------------------------------------------------------------------------------- 1 | menu "Example Configuration" 2 | 3 | config EXAMPLE_PEER_ADDR 4 | string "Peer Address" 5 | default "ADDR_ANY" 6 | help 7 | Enter the peer address in aa:bb:cc:dd:ee:ff form to connect to a specific peripheral 8 | 9 | config EXAMPLE_EXTENDED_ADV 10 | bool 11 | depends on SOC_BLE_50_SUPPORTED 12 | default y if SOC_ESP_NIMBLE_CONTROLLER 13 | select BT_NIMBLE_EXT_ADV 14 | prompt "Enable Extended Adv" 15 | help 16 | Use this option to enable extended advertising in the example 17 | 18 | config EXAMPLE_INIT_DEINIT_LOOP 19 | bool 20 | prompt "Perform init deinit of nimble stack in a loop" 21 | help 22 | Enable this flag, to perform only stack Init and Deinit in a loop. 23 | 24 | config EXAMPLE_ENCRYPTION 25 | bool 26 | prompt "Enable Link Encryption" 27 | help 28 | This enables bonding and encryption after connection has been established. 29 | endmenu 30 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 CANDY HOUSE 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | ![SesameSDK](https://github.com/CANDY-HOUSE/.github/blob/main/profile/images/SesameSDK.png?raw=true) 2 | # ESP32-C3-DevKitM-1 Sesame5 開關控制範例 3 | 4 | 這個專案展示了如何使用 ESP32-C3-DevKitM-1 微控制器來註冊和控制 Sesame5 智能鎖。本範例使用 ESP-IDF 開發框架,透過 BLE 技術自動尋找、連接並註冊附近的 Sesame5 設備。當 ESP32-C3-DevKitM-1 偵測到 Sesame5 達到開鎖位置時,會發出指令自動上鎖。 5 | 6 | ## 多語言版本 7 | - [English version](README_EN.md) 8 | - [日本語版](README_JP.md) 9 | 10 | ## 前提條件 11 | 您需要先安裝 ESP-IDF,可以透過 ESP-IDF 的 `install.sh` 腳本來安裝必要的工具鏈和依賴。 12 | 13 | ## 安裝與環境設定 14 | 1. 請確保您已經通過 ESP-IDF 的 `install.sh` 安裝了工具鏈。 15 | 2. 開啟終端機,導航到 ESP-IDF 的路徑,並執行 `export.sh` 加入環境變數。 16 | 3. 將ESP32-C3-DevKitM-1透過USB連接到您的電腦。 17 | 4. 回到專案資料夾,運行 `idf.py flash` 進行編譯和燒錄。 18 | 19 | ## 使用方法 20 | 燒錄並重啟 ESP32-C3-DevKitM-1 後,它會自動搜尋附近的未註冊的Sesame設備。在連接並註冊後,ESP32-C3-DevKitM-1 會監聽 Sesame5 的狀態,並在適當的時機發送上鎖指令。 21 | 22 | ## 特色與功能 23 | - **自動設備探索**:自動搜尋和連接附近的 Sesame5 智能鎖。 24 | - **自動上鎖**:當 Sesame5 達到預設開鎖位置時,ESP32-C3-DevKitM-1 會發出上鎖指令。 25 | 26 | ## 原始碼參考 27 | 這個範例改自 ESP-IDF 內的 nimble BLE Central Example。 28 | 29 | ## 額外資源 30 | - 請訪問 [CANDY HOUSE 官方網站](https://jp.candyhouse.co/) 了解更多關於 Sesame5 智能鎖的信息。 31 | 32 | ## 許可證 33 | 本專案採用 MIT 許可證。詳情請參見 `LICENSE` 文件。 34 | 35 | ## 致謝 36 | 感謝您對此專案的興趣,以及 CANDY HOUSE 公司對於開放資源的支持。 37 | -------------------------------------------------------------------------------- /README_JP.md: -------------------------------------------------------------------------------- 1 | ![img](./doc/resources/SesameSDK_20231201.png) 2 | # ESP32-C3-DevKitM-1によるセサミ5の操作例 3 | 4 | このプロジェクトでは、ESP32-C3-DevKitM-1マイクロコントローラを使用してセサミ5スマートロックを登録および操作する方法を示します。この例では、ESP-IDF開発フレームワークとBLE技術を利用して、近くのセサミ5デバイスを自動的に探索し、接続して登録します。ESP32-C3-DevKitM-1がセサミ5が解錠位置に達したことを検出すると、自動的にロックするコマンドを発行します。 5 | 6 | ## 多言語バージョン 7 | - [繁體中文版](README.md) 8 | - [English version](README_EN.md) 9 | 10 | ## 前提条件 11 | ESP-IDFをインストールする必要があります。これは、ESP-IDFの`install.sh`スクリプトを使用して必要なツールチェーンと依存関係をインストールすることで行えます。 12 | 13 | ## インストールと環境設定 14 | 1. ESP-IDFの`install.sh`を通じてツールチェーンがインストールされていることを確認してください。 15 | 2. ターミナルを開いて、ESP-IDFのパスに移動し、`export.sh`を実行して環境変数に追加します。 16 | 3. ESP32-C3-DevKitM-1をUSBでコンピュータに接続します。 17 | 4. プロジェクトフォルダに戻り、`idf.py flash`を実行してコンパイルとフラッシュを行います。 18 | 19 | ## 使用方法 20 | ESP32-C3-DevKitM-1にファームウェアを焼いて再起動した後、近くの未登録のSesameデバイスを自動的に検索します。接続して登録した後、ESP32-C3-DevKitM-1はSesame5の状態を監視し、適切なタイミングでロックコマンドを発行します。 21 | 22 | ## 特徴と機能 23 | 24 | - **自動デバイス探索**: 近くのセサミ5スマートロックを自動的に探索して接続します。 25 | - **自動ロック**: セサミ5が予定の解錠位置に達したときに、ESP32-C3-DevKitM-1が自動的にロック指令を発行します。 26 | 27 | ## ソースコードの参照 28 | 29 | この例は、ESP-IDF内のnimble BLE Central Exampleを基に改良されました。 30 | 31 | ## 追加リソース 32 | 33 | - セサミ5スマートロックに関する詳細は、[CANDY HOUSE公式ウェブサイト](https://jp.candyhouse.co/)をご覧ください。 34 | 35 | ## ライセンス 36 | 37 | このプロジェクトはMITライセンスのもとで公開されています。詳細は`LICENSE`ファイルをご覧ください。 38 | 39 | ## 謝辞 40 | 41 | このプロジェクトにご興味を持っていただき、オープンソースリソースに対するCANDY HOUSE社のサポートに感謝します。 42 | -------------------------------------------------------------------------------- /main/utils/aes-cbc-cmac.h: -------------------------------------------------------------------------------- 1 | /** 2 | * File: cmac.h 3 | * Created on: 21 авг. 2015 г. 4 | * Description: 5 | * 6 | * 7 | * Author: Roman Savrulin 8 | * Copyright: 2015 Roman Savrulin 9 | * Copying permission statement: 10 | * 11 | * This file is part of AES-CMAC. 12 | * 13 | * AES-CMAC is free software: you can redistribute it and/or modify 14 | * it under the terms of the GNU General Public License as published by 15 | * the Free Software Foundation, either version 3 of the License, or 16 | * (at your option) any later version. 17 | * 18 | * This program is distributed in the hope that it will be useful, 19 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 21 | * GNU General Public License for more details. 22 | * 23 | * You should have received a copy of the GNU General Public License 24 | * along with this program. If not, see . 25 | * 26 | * 27 | */ 28 | #ifndef AES_CBC_CMAC_H__ 29 | #define AES_CBC_CMAC_H__ 30 | 31 | #ifdef __cplusplus 32 | extern "C" { 33 | #endif 34 | 35 | #define BLOCK_SIZE 16 36 | #define LAST_INDEX (BLOCK_SIZE - 1) 37 | 38 | 39 | 40 | void AES_CMAC(const unsigned char *key, const unsigned char *input, int length, 41 | unsigned char *mac); 42 | 43 | int AES_CMAC_CHECK(const unsigned char *key, const unsigned char *input, 44 | int length, const unsigned char *mac); 45 | 46 | void xor_128(const unsigned char *a, const unsigned char *b, unsigned char *out); 47 | void AES_128_DEC(unsigned const char *key, unsigned const char* msg, unsigned char *cipher); 48 | void AES_128_ENC(unsigned const char *key, unsigned const char* msg, unsigned char *cipher); 49 | #ifdef DEBUG_CMAC 50 | void print_hex(const char *str, const unsigned char *buf, int len); 51 | void print128(const unsigned char *bytes); 52 | void print96(const unsigned char *bytes); 53 | #endif 54 | 55 | #ifdef __cplusplus 56 | } 57 | #endif 58 | 59 | #endif /* AES_CBC_CMAC_H__ */ 60 | -------------------------------------------------------------------------------- /main/sesame/ssm.h: -------------------------------------------------------------------------------- 1 | #ifndef __SSM_H__ 2 | #define __SSM_H__ 3 | 4 | #include "candy.h" 5 | #include 6 | #include 7 | #include 8 | 9 | #ifdef __cplusplus 10 | extern "C" { 11 | #endif 12 | 13 | #define SSM_MAX_NUM (1u) 14 | 15 | #pragma pack(1) 16 | 17 | typedef struct { 18 | int64_t count; 19 | uint8_t nouse; 20 | uint8_t random_code[4]; 21 | } SSM_CCM_NONCE; 22 | 23 | typedef struct { 24 | uint8_t token[16]; 25 | SSM_CCM_NONCE encrypt; 26 | SSM_CCM_NONCE decrypt; 27 | } SesameBleCipher; 28 | 29 | typedef struct mech_status_s { 30 | uint16_t battery; 31 | int16_t target; // 馬達想到的地方 32 | int16_t position; // 感測器同步到的最新角度 33 | uint8_t is_clutch_failed : 1; // 電磁鐵作棟是否成功(沒用到) 34 | uint8_t is_lock_range : 1; // 在關鎖位置 35 | uint8_t is_unlock_range : 1; // 在開鎖位置 36 | uint8_t is_critical : 1; // 開關鎖時間超時,馬達停轉 37 | uint8_t is_stop : 1; // 把手角度沒有變化 38 | uint8_t is_low_battery : 1; // 低電量(<5V) 39 | uint8_t is_clockwise : 1; // 馬達轉動方向 40 | } mech_status_t; // total 7 bytes 41 | 42 | typedef struct { 43 | uint8_t device_uuid[16]; 44 | uint8_t public_key[64]; 45 | uint8_t device_secret[16]; 46 | uint8_t addr[6]; 47 | volatile uint8_t device_status; 48 | SesameBleCipher cipher; 49 | mech_status_t mech_status; 50 | uint16_t c_offset; 51 | uint8_t b_buf[80]; /// max command size is register(80 Bytes). 52 | uint8_t conn_id; 53 | } sesame; 54 | 55 | typedef void (*ssm_action)(sesame * ssm); 56 | 57 | struct ssm_env_tag { 58 | sesame ssm; 59 | ssm_action ssm_cb__; 60 | }; 61 | 62 | #pragma pack() 63 | 64 | extern struct ssm_env_tag * p_ssms_env; 65 | 66 | void ssm_ble_receiver(sesame * ssm, const uint8_t * p_data, uint16_t len); 67 | 68 | void talk_to_ssm(sesame * ssm, uint8_t parsing_type); 69 | 70 | void ssm_mem_deinit(void); 71 | 72 | void ssm_init(ssm_action ssm_action_cb); 73 | 74 | #ifdef __cplusplus 75 | } 76 | #endif 77 | 78 | #endif // __SSM_H__ 79 | -------------------------------------------------------------------------------- /README_EN.md: -------------------------------------------------------------------------------- 1 | ![img](./doc/resources/SesameSDK_20231201.png) 2 | # ESP32-C3-DevKitM-1 Sesame5 Switch Control Example 3 | 4 | This project demonstrates how to use the ESP32-C3-DevKitM-1 microcontroller to register and control a Sesame5 smart lock. Utilizing the ESP-IDF development framework and BLE technology, this example automatically searches for, connects to, and registers nearby Sesame5 devices. When the ESP32-C3-DevKitM-1 detects that the Sesame5 is in the unlock position, it issues a command to automatically lock it. 5 | 6 | ## Other Languages 7 | - [返回中文版](README.md) 8 | - [日本語版](README_JP.md) 9 | 10 | ## Prerequisites 11 | You will need to install ESP-IDF, which can be done using the `install.sh` script from the ESP-IDF to install necessary toolchains and dependencies. 12 | 13 | ## Installation and Environment Setup 14 | 1. Ensure that you have installed the toolchain through ESP-IDF's `install.sh`. 15 | 2. Open a terminal, navigate to the ESP-IDF path, and run `export.sh` to add it to your environment variables. 16 | 3. Connect your ESP32-C3-DevKitM-1 to your computer via USB. 17 | 4. Return to the project folder and run `idf.py flash` to compile and flash. 18 | 19 | ## Usage 20 | After flashing and rebooting the ESP32-C3-DevKitM-1, it will automatically search for unregistered Sesame devices nearby. Once connected and registered, the ESP32-C3-DevKitM-1 will monitor the status of the Sesame5 and issue a lock command at the appropriate time. 21 | 22 | ## Features and Functionality 23 | - **Automatic Device Discovery**: Automatically searches for and connects to nearby Sesame5 smart locks. 24 | - **Automatic Locking**: Issues a lock command when the Sesame5 reaches the preset unlock position. 25 | 26 | ## Source Reference 27 | This example is modified from the nimble BLE Central Example within ESP-IDF. 28 | 29 | ## Additional Resources 30 | - Visit the [CANDY HOUSE Official Website](https://jp.candyhouse.co/) for more information about the Sesame5 smart lock. 31 | 32 | ## License 33 | This project is licensed under the MIT License. See the `LICENSE` file for details. 34 | 35 | ## Acknowledgments 36 | Thank you for your interest in this project and the support of open resources by CANDY HOUSE. 37 | -------------------------------------------------------------------------------- /main/utils/TI_aes_128.h: -------------------------------------------------------------------------------- 1 | /* --COPYRIGHT--,BSD 2 | * Copyright (c) 2011, Texas Instruments Incorporated 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions 7 | * are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 12 | * * Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * * Neither the name of Texas Instruments Incorporated nor the names of 17 | * its contributors may be used to endorse or promote products derived 18 | * from this software without specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 22 | * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 23 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 24 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 25 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 26 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 27 | * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 28 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 29 | * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 30 | * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | * --/COPYRIGHT--*/ 32 | /* 33 | * TI_aes_128.h 34 | * 35 | * Created on: Nov 3, 2011 36 | * Author: Eric Peeters 37 | */ 38 | 39 | #ifndef TI_OPT_AES_H_ 40 | #define TI_OPT_AES_H_ 41 | 42 | #ifdef __cplusplus 43 | extern "C" { 44 | #endif 45 | 46 | void aes_enc_dec(unsigned char * state, unsigned char * key, unsigned char dir); 47 | 48 | #ifdef __cplusplus 49 | } 50 | #endif 51 | 52 | #endif /* TI_OPT_AES_H_ */ 53 | -------------------------------------------------------------------------------- /main/utils/utils.c: -------------------------------------------------------------------------------- 1 | /* utils.c - TinyCrypt platform-dependent run-time operations */ 2 | 3 | /* 4 | * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * - Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * 12 | * - Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * - Neither the name of Intel Corporation nor the names of its contributors 17 | * may be used to endorse or promote products derived from this software 18 | * without specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 24 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 | * POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | #include 34 | 35 | #include 36 | 37 | #define MASK_TWENTY_SEVEN 0x1b 38 | 39 | unsigned int _copy(uint8_t * to, unsigned int to_len, const uint8_t * from, unsigned int from_len) { 40 | if (from_len <= to_len) { 41 | (void) memcpy(to, from, from_len); 42 | return from_len; 43 | } else { 44 | return 0; 45 | } 46 | } 47 | 48 | void _set(void * to, uint8_t val, unsigned int len) { 49 | (void) memset(to, val, len); 50 | } 51 | 52 | /* 53 | * Doubles the value of a byte for values up to 127. 54 | */ 55 | uint8_t _double_byte(uint8_t a) { 56 | return ((a << 1) ^ ((a >> 7) * MASK_TWENTY_SEVEN)); 57 | } 58 | 59 | int _compare(const uint8_t * a, const uint8_t * b, size_t size) { 60 | const uint8_t * tempa = a; 61 | const uint8_t * tempb = b; 62 | uint8_t result = 0; 63 | 64 | for (unsigned int i = 0; i < size; i++) { 65 | result |= tempa[i] ^ tempb[i]; 66 | } 67 | return result; 68 | } 69 | -------------------------------------------------------------------------------- /main/sesame/ssm_cmd.c: -------------------------------------------------------------------------------- 1 | #include "ssm_cmd.h" 2 | #include "aes-cbc-cmac.h" 3 | #include "esp_log.h" 4 | #include "esp_random.h" 5 | #include "uECC.h" 6 | #include 7 | 8 | static const char * TAG = "ssm_cmd.c"; 9 | static uint8_t tag_esp32[] = { 'S', 'E', 'S', 'A', 'M', 'E', ' ', 'E', 'S', 'P', '3', '2' }; 10 | static uint8_t ecc_private_esp32[32]; 11 | 12 | static int crypto_backend_micro_ecc_rng_callback(uint8_t * dest, unsigned size) { 13 | esp_fill_random(dest, (size_t) size); 14 | return 1; 15 | } 16 | 17 | void send_reg_cmd_to_ssm(sesame * ssm) { 18 | ESP_LOGW(TAG, "[esp32->ssm][register]"); 19 | uECC_set_rng(crypto_backend_micro_ecc_rng_callback); 20 | uint8_t ecc_public_esp32[64]; 21 | uECC_make_key_lit(ecc_public_esp32, ecc_private_esp32, uECC_secp256r1()); 22 | ssm->c_offset = sizeof(ecc_public_esp32) + 1; 23 | ssm->b_buf[0] = SSM_ITEM_CODE_REGISTRATION; 24 | memcpy(ssm->b_buf + 1, ecc_public_esp32, sizeof(ecc_public_esp32)); 25 | talk_to_ssm(ssm, SSM_SEG_PARSING_TYPE_PLAINTEXT); 26 | } 27 | 28 | void handle_reg_data_from_ssm(sesame * ssm) { 29 | ESP_LOGW(TAG, "[esp32<-ssm][register]"); 30 | memcpy(ssm->public_key, &ssm->b_buf[13], 64); 31 | uint8_t ecdh_secret_ssm[32]; 32 | uECC_shared_secret_lit(ssm->public_key, ecc_private_esp32, ecdh_secret_ssm, uECC_secp256r1()); 33 | memcpy(ssm->device_secret, ecdh_secret_ssm, 16); 34 | // ESP_LOG_BUFFER_HEX("deviceSecret", ssm->device_secret, 16); 35 | AES_CMAC(ssm->device_secret, (const unsigned char *) ssm->cipher.decrypt.random_code, 4, ssm->cipher.token); 36 | ssm->device_status = SSM_LOGGIN; 37 | p_ssms_env->ssm_cb__(ssm); // callback: ssm_action_handle() in main.c 38 | } 39 | 40 | void send_login_cmd_to_ssm(sesame * ssm) { 41 | ESP_LOGW(TAG, "[esp32->ssm][login]"); 42 | ssm->b_buf[0] = SSM_ITEM_CODE_LOGIN; 43 | AES_CMAC(ssm->device_secret, (const unsigned char *) ssm->cipher.decrypt.random_code, 4, ssm->cipher.token); 44 | memcpy(&ssm->b_buf[1], ssm->cipher.token, 4); 45 | ssm->c_offset = 5; 46 | talk_to_ssm(ssm, SSM_SEG_PARSING_TYPE_PLAINTEXT); 47 | } 48 | 49 | void send_read_history_cmd_to_ssm(sesame * ssm) { 50 | ESP_LOGI(TAG, "[send_read_history_cmd_to_ssm]"); 51 | ssm->c_offset = 2; 52 | ssm->b_buf[0] = SSM_ITEM_CODE_HISTORY; 53 | ssm->b_buf[1] = 1; 54 | talk_to_ssm(ssm, SSM_SEG_PARSING_TYPE_CIPHERTEXT); 55 | } 56 | 57 | void ssm_lock(uint8_t * tag, uint8_t tag_length) { 58 | // ESP_LOGI(TAG, "[ssm][ssm_lock][%s]", SSM_STATUS_STR(p_ssms_env->ssm.device_status)); 59 | sesame * ssm = &p_ssms_env->ssm; 60 | if (ssm->device_status >= SSM_LOGGIN) { 61 | if (tag_length == 0) { 62 | tag = tag_esp32; 63 | tag_length = sizeof(tag_esp32); 64 | } 65 | ssm->b_buf[0] = SSM_ITEM_CODE_LOCK; 66 | ssm->b_buf[1] = tag_length; 67 | ssm->c_offset = tag_length + 2; 68 | memcpy(ssm->b_buf + 2, tag, tag_length); 69 | talk_to_ssm(ssm, SSM_SEG_PARSING_TYPE_CIPHERTEXT); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /main/utils/types.h: -------------------------------------------------------------------------------- 1 | /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */ 2 | 3 | #ifndef _UECC_TYPES_H_ 4 | #define _UECC_TYPES_H_ 5 | 6 | #ifdef __cplusplus 7 | extern "C" { 8 | #endif 9 | 10 | #define uECC_PLATFORM uECC_arch_other 11 | 12 | #ifndef uECC_PLATFORM 13 | #if __AVR__ 14 | #define uECC_PLATFORM uECC_avr 15 | #elif defined(__thumb2__) || defined(_M_ARMT) /* I think MSVC only supports Thumb-2 targets */ 16 | #define uECC_PLATFORM uECC_arm_thumb2 17 | #elif defined(__thumb__) 18 | #define uECC_PLATFORM uECC_arm_thumb 19 | #elif defined(__arm__) || defined(_M_ARM) 20 | #define uECC_PLATFORM uECC_arm 21 | #elif defined(__aarch64__) 22 | #define uECC_PLATFORM uECC_arm64 23 | #elif defined(__i386__) || defined(_M_IX86) || defined(_X86_) || defined(__I86__) 24 | #define uECC_PLATFORM uECC_x86 25 | #elif defined(__amd64__) || defined(_M_X64) 26 | #define uECC_PLATFORM uECC_x86_64 27 | #else 28 | #define uECC_PLATFORM uECC_arch_other 29 | #endif 30 | #endif 31 | 32 | #ifndef uECC_ARM_USE_UMAAL 33 | #if (uECC_PLATFORM == uECC_arm) && (__ARM_ARCH >= 6) 34 | #define uECC_ARM_USE_UMAAL 1 35 | #elif (uECC_PLATFORM == uECC_arm_thumb2) && (__ARM_ARCH >= 6) && !__ARM_ARCH_7M__ 36 | #define uECC_ARM_USE_UMAAL 1 37 | #else 38 | #define uECC_ARM_USE_UMAAL 0 39 | #endif 40 | #endif 41 | 42 | #ifndef uECC_WORD_SIZE 43 | #if uECC_PLATFORM == uECC_avr 44 | #define uECC_WORD_SIZE 1 45 | #elif (uECC_PLATFORM == uECC_x86_64 || uECC_PLATFORM == uECC_arm64) 46 | #define uECC_WORD_SIZE 8 47 | #else 48 | #define uECC_WORD_SIZE 4 49 | #endif 50 | #endif 51 | 52 | #if (uECC_WORD_SIZE != 1) && (uECC_WORD_SIZE != 4) && (uECC_WORD_SIZE != 8) 53 | #error "Unsupported value for uECC_WORD_SIZE" 54 | #endif 55 | 56 | #if ((uECC_PLATFORM == uECC_avr) && (uECC_WORD_SIZE != 1)) 57 | #pragma message("uECC_WORD_SIZE must be 1 for AVR") 58 | #undef uECC_WORD_SIZE 59 | #define uECC_WORD_SIZE 1 60 | #endif 61 | 62 | #if ((uECC_PLATFORM == uECC_arm || uECC_PLATFORM == uECC_arm_thumb || uECC_PLATFORM == uECC_arm_thumb2) && (uECC_WORD_SIZE != 4)) 63 | #pragma message("uECC_WORD_SIZE must be 4 for ARM") 64 | #undef uECC_WORD_SIZE 65 | #define uECC_WORD_SIZE 4 66 | #endif 67 | 68 | #if defined(__SIZEOF_INT128__) || ((__clang_major__ * 100 + __clang_minor__) >= 302) 69 | #define SUPPORTS_INT128 1 70 | #else 71 | #define SUPPORTS_INT128 0 72 | #endif 73 | 74 | typedef int8_t wordcount_t; 75 | typedef int16_t bitcount_t; 76 | typedef int8_t cmpresult_t; 77 | 78 | #if (uECC_WORD_SIZE == 1) 79 | 80 | typedef uint8_t uECC_word_t; 81 | typedef uint16_t uECC_dword_t; 82 | 83 | #define HIGH_BIT_SET 0x80 84 | #define uECC_WORD_BITS 8 85 | #define uECC_WORD_BITS_SHIFT 3 86 | #define uECC_WORD_BITS_MASK 0x07 87 | 88 | #elif (uECC_WORD_SIZE == 4) 89 | 90 | typedef uint32_t uECC_word_t; 91 | typedef uint64_t uECC_dword_t; 92 | 93 | #define HIGH_BIT_SET 0x80000000 94 | #define uECC_WORD_BITS 32 95 | #define uECC_WORD_BITS_SHIFT 5 96 | #define uECC_WORD_BITS_MASK 0x01F 97 | 98 | #elif (uECC_WORD_SIZE == 8) 99 | 100 | typedef uint64_t uECC_word_t; 101 | #if SUPPORTS_INT128 102 | typedef unsigned __int128 uECC_dword_t; 103 | #endif 104 | 105 | #define HIGH_BIT_SET 0x8000000000000000ull 106 | #define uECC_WORD_BITS 64 107 | #define uECC_WORD_BITS_SHIFT 6 108 | #define uECC_WORD_BITS_MASK 0x03F 109 | 110 | #endif /* uECC_WORD_SIZE */ 111 | 112 | #ifdef __cplusplus 113 | } 114 | #endif 115 | 116 | #endif /* _UECC_TYPES_H_ */ 117 | -------------------------------------------------------------------------------- /main/utils/c_ccm.h: -------------------------------------------------------------------------------- 1 | /** 2 | * \file ccm.h 3 | * 4 | * \brief Counter with CBC-MAC (CCM) for 128-bit block ciphers 5 | * 6 | * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved 7 | * SPDX-License-Identifier: Apache-2.0 8 | * 9 | * Licensed under the Apache License, Version 2.0 (the "License"); you may 10 | * not use this file except in compliance with the License. 11 | * You may obtain a copy of the License at 12 | * 13 | * http://www.apache.org/licenses/LICENSE-2.0 14 | * 15 | * Unless required by applicable law or agreed to in writing, software 16 | * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT 17 | * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 18 | * See the License for the specific language governing permissions and 19 | * limitations under the License. 20 | * 21 | * This file is part of mbed TLS (https://tls.mbed.org) 22 | */ 23 | #include 24 | #define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D /**< Bad input parameters to function. */ 25 | #define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F /**< Authenticated decryption failed. */ 26 | 27 | #ifdef __cplusplus 28 | extern "C" { 29 | #endif 30 | 31 | /** 32 | * \brief CCM buffer encryption 33 | * 34 | * \param key key must be 16 bytes 35 | * \param length length of the input data in bytes 36 | * \param iv nonce (initialization vector) 37 | * \param iv_len length of IV in bytes 38 | * must be 2, 3, 4, 5, 6, 7 or 8 39 | * \param add additional data 40 | * \param add_len length of additional data in bytes 41 | * must be less than 2^16 - 2^8 42 | * \param input buffer holding the input data 43 | * \param output buffer for holding the output data 44 | * must be at least 'length' bytes wide 45 | * \param tag buffer for holding the tag 46 | * \param tag_len length of the tag to generate in bytes 47 | * must be 4, 6, 8, 10, 14 or 16 48 | * 49 | * \note The tag is written to a separate buffer. To get the tag 50 | * concatenated with the output as in the CCM spec, use 51 | * tag = output + length and make sure the output buffer is 52 | * at least length + tag_len wide. 53 | * 54 | * \return 0 if successful 55 | */ 56 | int aes_ccm_encrypt_and_tag(const unsigned char * key, const unsigned char * iv, size_t iv_len, const unsigned char * add, size_t add_len, const unsigned char * input, size_t length, unsigned char * output, unsigned char * tag, size_t tag_len); 57 | 58 | /** 59 | * \brief CCM buffer authenticated decryption 60 | * 61 | * \param key key must be 16 bytes 62 | * \param length length of the input data 63 | * \param iv initialization vector 64 | * \param iv_len length of IV 65 | * \param add additional data 66 | * \param add_len length of additional data 67 | * \param input buffer holding the input data 68 | * \param output buffer for holding the output data 69 | * \param tag buffer holding the tag 70 | * \param tag_len length of the tag 71 | * 72 | * \return 0 if successful and authenticated, 73 | * MBEDTLS_ERR_CCM_AUTH_FAILED if tag does not match 74 | */ 75 | int aes_ccm_auth_decrypt(const unsigned char * key, const unsigned char * iv, size_t iv_len, const unsigned char * add, size_t add_len, const unsigned char * input, size_t length, unsigned char * output, const unsigned char * tag, size_t tag_len); 76 | 77 | #ifdef __cplusplus 78 | } 79 | #endif 80 | -------------------------------------------------------------------------------- /main/utils/utils.h: -------------------------------------------------------------------------------- 1 | /* utils.h - TinyCrypt interface to platform-dependent run-time operations */ 2 | 3 | /* 4 | * Copyright (C) 2017 by Intel Corporation, All Rights Reserved. 5 | * 6 | * Redistribution and use in source and binary forms, with or without 7 | * modification, are permitted provided that the following conditions are met: 8 | * 9 | * - Redistributions of source code must retain the above copyright notice, 10 | * this list of conditions and the following disclaimer. 11 | * 12 | * - Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * - Neither the name of Intel Corporation nor the names of its contributors 17 | * may be used to endorse or promote products derived from this software 18 | * without specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 22 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE 23 | * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE 24 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 25 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 26 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 27 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 28 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 29 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 30 | * POSSIBILITY OF SUCH DAMAGE. 31 | */ 32 | 33 | /** 34 | * @file 35 | * @brief Interface to platform-dependent run-time operations. 36 | * 37 | */ 38 | 39 | #ifndef __TC_UTILS_H__ 40 | #define __TC_UTILS_H__ 41 | 42 | #include 43 | #include 44 | 45 | 46 | #ifdef __cplusplus 47 | extern "C" { 48 | #endif 49 | 50 | /** 51 | * @brief Copy the the buffer 'from' to the buffer 'to'. 52 | * @return returns TC_CRYPTO_SUCCESS (1) 53 | * returns TC_CRYPTO_FAIL (0) if: 54 | * from_len > to_len. 55 | * 56 | * @param to OUT -- destination buffer 57 | * @param to_len IN -- length of destination buffer 58 | * @param from IN -- origin buffer 59 | * @param from_len IN -- length of origin buffer 60 | */ 61 | unsigned int _copy(uint8_t * to, unsigned int to_len, const uint8_t * from, unsigned int from_len); 62 | 63 | /** 64 | * @brief Set the value 'val' into the buffer 'to', 'len' times. 65 | * 66 | * @param to OUT -- destination buffer 67 | * @param val IN -- value to be set in 'to' 68 | * @param len IN -- number of times the value will be copied 69 | */ 70 | void _set(void * to, uint8_t val, unsigned int len); 71 | 72 | /* 73 | * @brief AES specific doubling function, which utilizes 74 | * the finite field used by AES. 75 | * @return Returns a^2 76 | * 77 | * @param a IN/OUT -- value to be doubled 78 | */ 79 | uint8_t _double_byte(uint8_t a); 80 | 81 | /* 82 | * @brief Constant-time algorithm to compare if two sequences of bytes are equal 83 | * @return Returns 0 if equal, and non-zero otherwise 84 | * 85 | * @param a IN -- sequence of bytes a 86 | * @param b IN -- sequence of bytes b 87 | * @param size IN -- size of sequences a and b 88 | */ 89 | int _compare(const uint8_t * a, const uint8_t * b, size_t size); 90 | 91 | #ifdef __cplusplus 92 | } 93 | #endif 94 | 95 | #endif /* __TC_UTILS_H__ */ 96 | -------------------------------------------------------------------------------- /.clang-format: -------------------------------------------------------------------------------- 1 | --- 2 | Language: Cpp 3 | # BasedOnStyle: WebKit 4 | AccessModifierOffset: -4 5 | AlignAfterOpenBracket: Align 6 | AlignConsecutiveAssignments: false 7 | AlignConsecutiveDeclarations: false 8 | AlignEscapedNewlines: Right 9 | AlignOperands: false 10 | AlignTrailingComments: true 11 | AllowAllParametersOfDeclarationOnNextLine: true 12 | AllowShortBlocksOnASingleLine: false 13 | AllowShortCaseLabelsOnASingleLine: false 14 | AllowShortFunctionsOnASingleLine: Inline 15 | AllowShortIfStatementsOnASingleLine: false 16 | AllowShortLoopsOnASingleLine: false 17 | AlwaysBreakAfterDefinitionReturnType: None 18 | AlwaysBreakAfterReturnType: None 19 | AlwaysBreakBeforeMultilineStrings: false 20 | AlwaysBreakTemplateDeclarations: true 21 | BinPackArguments: true 22 | BinPackParameters: true 23 | BraceWrapping: 24 | AfterClass: false 25 | AfterControlStatement: false 26 | AfterEnum: false 27 | AfterFunction: false 28 | AfterNamespace: false 29 | AfterObjCDeclaration: false 30 | AfterStruct: false 31 | AfterUnion: false 32 | BeforeCatch: false 33 | BeforeElse: false 34 | IndentBraces: false 35 | SplitEmptyFunction: false 36 | SplitEmptyRecord: false 37 | SplitEmptyNamespace: false 38 | BreakBeforeBinaryOperators: None 39 | BreakBeforeBraces: Custom 40 | BreakBeforeInheritanceComma: false 41 | BreakBeforeTernaryOperators: true 42 | BreakConstructorInitializersBeforeComma: false 43 | BreakConstructorInitializers: AfterColon 44 | BreakAfterJavaFieldAnnotations: false 45 | BreakStringLiterals: true 46 | ColumnLimit: 255 47 | CommentPragmas: '^ IWYU pragma:' 48 | CompactNamespaces: false 49 | ConstructorInitializerAllOnOneLineOrOnePerLine: false 50 | ConstructorInitializerIndentWidth: 4 51 | ContinuationIndentWidth: 4 52 | Cpp11BracedListStyle: false 53 | DerivePointerAlignment: false 54 | DisableFormat: false 55 | ExperimentalAutoDetectBinPacking: false 56 | FixNamespaceComments: true 57 | ForEachMacros: 58 | - foreach 59 | - Q_FOREACH 60 | - BOOST_FOREACH 61 | IncludeCategories: 62 | - Regex: '^cipher.encrypt.nouse = 0; // reset cipher 14 | ssm->cipher.decrypt.nouse = 0; 15 | memcpy(ssm->cipher.encrypt.random_code, ssm->b_buf, 4); 16 | memcpy(ssm->cipher.decrypt.random_code, ssm->b_buf, 4); 17 | ssm->cipher.encrypt.count = 0; 18 | ssm->cipher.decrypt.count = 0; 19 | 20 | if (p_ssms_env->ssm.device_secret[0] == 0) { 21 | ESP_LOGI(TAG, "[ssm][no device_secret]"); 22 | send_reg_cmd_to_ssm(ssm); 23 | return; 24 | } 25 | send_login_cmd_to_ssm(ssm); 26 | } 27 | 28 | static void ssm_parse_publish(sesame * ssm, uint8_t cmd_it_code) { 29 | switch (cmd_it_code) { 30 | case SSM_ITEM_CODE_INITIAL: // get 4 bytes random_code 31 | ssm_initial_handle(ssm, cmd_it_code); 32 | break; 33 | case SSM_ITEM_CODE_MECH_STATUS: 34 | memcpy((void *) &(ssm->mech_status), ssm->b_buf, 7); 35 | device_status_t lockStatus = ssm->mech_status.is_lock_range ? SSM_LOCKED : (ssm->mech_status.is_unlock_range ? SSM_UNLOCKED : SSM_MOVED); 36 | if (ssm->device_status != lockStatus) { 37 | ssm->device_status = lockStatus; 38 | p_ssms_env->ssm_cb__(ssm); // callback: ssm_action_handle 39 | } 40 | break; 41 | default: 42 | break; 43 | } 44 | } 45 | 46 | static void ssm_parse_response(sesame * ssm, uint8_t cmd_it_code) { 47 | ssm->c_offset = ssm->c_offset - 1; 48 | memcpy(ssm->b_buf, ssm->b_buf + 1, ssm->c_offset); 49 | switch (cmd_it_code) { 50 | case SSM_ITEM_CODE_REGISTRATION: 51 | handle_reg_data_from_ssm(ssm); 52 | break; 53 | case SSM_ITEM_CODE_LOGIN: 54 | ESP_LOGI(TAG, "[%d][ssm][login][ok]", ssm->conn_id); 55 | ssm->device_status = SSM_LOGGIN; 56 | p_ssms_env->ssm_cb__(ssm); // callback: ssm_action_handle 57 | break; 58 | case SSM_ITEM_CODE_HISTORY: 59 | ESP_LOGI(TAG, "[%d][ssm][hisdataLength: %d]", ssm->conn_id, ssm->c_offset); 60 | if (ssm->c_offset == 0) { //循環讀取 避免沒取完歷史 61 | return; 62 | } 63 | send_read_history_cmd_to_ssm(ssm); 64 | break; 65 | default: 66 | break; 67 | } 68 | } 69 | 70 | void ssm_ble_receiver(sesame * ssm, const uint8_t * p_data, uint16_t len) { 71 | if (p_data[0] & 1u) { 72 | ssm->c_offset = 0; 73 | } 74 | memcpy(&ssm->b_buf[ssm->c_offset], p_data + 1, len - 1); 75 | ssm->c_offset += len - 1; 76 | if (p_data[0] >> 1u == SSM_SEG_PARSING_TYPE_APPEND_ONLY) { 77 | return; 78 | } 79 | if (p_data[0] >> 1u == SSM_SEG_PARSING_TYPE_CIPHERTEXT) { 80 | ssm->c_offset = ssm->c_offset - CCM_TAG_LENGTH; 81 | aes_ccm_auth_decrypt(ssm->cipher.token, (const unsigned char *) &ssm->cipher.decrypt, 13, additional_data, 1, ssm->b_buf, ssm->c_offset, ssm->b_buf, ssm->b_buf + ssm->c_offset, CCM_TAG_LENGTH); 82 | ssm->cipher.decrypt.count++; 83 | } 84 | 85 | uint8_t cmd_op_code = ssm->b_buf[0]; 86 | uint8_t cmd_it_code = ssm->b_buf[1]; 87 | ssm->c_offset = ssm->c_offset - 2; 88 | memcpy(ssm->b_buf, ssm->b_buf + 2, ssm->c_offset); 89 | ESP_LOGI(TAG, "[ssm][say][%d][%s][%s]", ssm->conn_id, SSM_OP_CODE_STR(cmd_op_code), SSM_ITEM_CODE_STR(cmd_it_code)); 90 | if (cmd_op_code == SSM_OP_CODE_PUBLISH) { 91 | ssm_parse_publish(ssm, cmd_it_code); 92 | } else if (cmd_op_code == SSM_OP_CODE_RESPONSE) { 93 | ssm_parse_response(ssm, cmd_it_code); 94 | } 95 | ssm->c_offset = 0; 96 | } 97 | 98 | void talk_to_ssm(sesame * ssm, uint8_t parsing_type) { 99 | ESP_LOGI(TAG, "[esp32][say][%d][%s]", ssm->conn_id, SSM_ITEM_CODE_STR(ssm->b_buf[0])); 100 | if (parsing_type == SSM_SEG_PARSING_TYPE_CIPHERTEXT) { 101 | aes_ccm_encrypt_and_tag(ssm->cipher.token, (const unsigned char *) &ssm->cipher.encrypt, 13, additional_data, 1, ssm->b_buf, ssm->c_offset, ssm->b_buf, ssm->b_buf + ssm->c_offset, CCM_TAG_LENGTH); 102 | ssm->cipher.encrypt.count++; 103 | ssm->c_offset = ssm->c_offset + CCM_TAG_LENGTH; 104 | } 105 | 106 | uint8_t * data = ssm->b_buf; 107 | uint16_t remain = ssm->c_offset; 108 | uint16_t len = remain; 109 | uint8_t tmp_v[20] = { 0 }; 110 | uint16_t len_l; 111 | 112 | while (remain) { 113 | if (remain <= 19) { 114 | tmp_v[0] = parsing_type << 1u; 115 | len_l = 1 + remain; 116 | } else { 117 | tmp_v[0] = 0; 118 | len_l = 20; 119 | } 120 | if (remain == len) { 121 | tmp_v[0] |= 1u; 122 | } 123 | memcpy(&tmp_v[1], data, len_l - 1); 124 | esp_ble_gatt_write(ssm, tmp_v, len_l); 125 | remain -= (len_l - 1); 126 | data += (len_l - 1); 127 | } 128 | } 129 | 130 | void ssm_mem_deinit(void) { 131 | free(p_ssms_env); 132 | } 133 | 134 | void ssm_init(ssm_action ssm_action_cb) { 135 | p_ssms_env = (struct ssm_env_tag *) calloc(1, sizeof(struct ssm_env_tag)); 136 | if (p_ssms_env == NULL) { 137 | ESP_LOGE(TAG, "[ssm_init][FAIL]"); 138 | } 139 | p_ssms_env->ssm_cb__ = ssm_action_cb; // callback: ssm_action_handle 140 | p_ssms_env->ssm.conn_id = 0xFF; // 0xFF: not connected 141 | p_ssms_env->ssm.device_status = SSM_NOUSE; 142 | ESP_LOGI(TAG, "[ssm_init][SUCCESS]"); 143 | } 144 | -------------------------------------------------------------------------------- /main/utils/aes-cbc-cmac.c: -------------------------------------------------------------------------------- 1 | /** 2 | * File: cmac.c 3 | * Created on: 21 авг. 2015 г. 4 | * Description: 5 | * 6 | * 7 | * Author: Roman Savrulin 8 | * Copyright: 2015 Roman Savrulin 9 | * Copying permission statement: 10 | * 11 | * This file is part of AES-CMAC. 12 | * 13 | * AES-CMAC is free software: you can redistribute it and/or modify 14 | * it under the terms of the GNU General Public License as published by 15 | * the Free Software Foundation, either version 3 of the License, or 16 | * (at your option) any later version. 17 | * 18 | * This program is distributed in the hope that it will be useful, 19 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 20 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 21 | * GNU General Public License for more details. 22 | * 23 | * You should have received a copy of the GNU General Public License 24 | * along with this program. If not, see . 25 | * 26 | * 27 | */ 28 | 29 | /****************************************************************/ 30 | /* AES-CMAC with AES-128 bit */ 31 | /* CMAC Algorithm described in SP800-38B */ 32 | /* Author: Junhyuk Song (junhyuk.song@samsung.com) */ 33 | /* Jicheol Lee (jicheol.lee@samsung.com) */ 34 | /****************************************************************/ 35 | 36 | #include "TI_aes_128.h" 37 | #include "aes-cbc-cmac.h" 38 | #include 39 | #include "aes-cbc-cmac.h" 40 | 41 | #ifdef DEBUG_CMAC 42 | #include 43 | void print_hex(const char *str, const unsigned char *buf, int len) { 44 | int i; 45 | 46 | for (i = 0; i < len; i++) { 47 | if ((i % BLOCK_SIZE) == 0 && i != 0) 48 | printf("%s", str); 49 | printf("%02x", buf[i]); 50 | if ((i % 4) == 3) 51 | printf(" "); 52 | if ((i % BLOCK_SIZE) == LAST_INDEX) 53 | printf("\n"); 54 | } 55 | if ((i % BLOCK_SIZE) != 0) 56 | printf("\n"); 57 | } 58 | void print128(const unsigned char *bytes) { 59 | int j; 60 | for (j = 0; j < BLOCK_SIZE; j++) { 61 | printf("%02x", bytes[j]); 62 | if ((j % 4) == 3) 63 | printf(" "); 64 | } 65 | } 66 | 67 | void print96(const unsigned char *bytes) { 68 | int j; 69 | for (j = 0; j < 12; j++) { 70 | printf("%02x", bytes[j]); 71 | if ((j % 4) == 3) 72 | printf(" "); 73 | } 74 | } 75 | #endif 76 | 77 | /* For CMAC Calculation */ 78 | static unsigned const char const_Rb[BLOCK_SIZE] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 79 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x87 }; 80 | static unsigned const char const_Zero[BLOCK_SIZE] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 81 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 }; 82 | 83 | int AES_CMAC_CHECK(const unsigned char *key, const unsigned char *input, int length, 84 | const unsigned char *mac){ 85 | unsigned char T[BLOCK_SIZE]; 86 | AES_CMAC(key, input, length, T); 87 | /*print128(T); 88 | printf("\n"); 89 | print128(mac);*/ 90 | return memcmp(mac, T, BLOCK_SIZE); 91 | } 92 | 93 | void AES_128_ENC(unsigned const char *key, unsigned const char* msg, unsigned char *cipher){ 94 | unsigned char key_copy[BLOCK_SIZE]; 95 | memcpy(cipher, msg, BLOCK_SIZE); 96 | memcpy(key_copy, key, BLOCK_SIZE); 97 | aes_enc_dec(cipher, key_copy, 0); 98 | } 99 | 100 | void AES_128_DEC(unsigned const char *key, unsigned const char* msg, unsigned char *cipher){ 101 | unsigned char key_copy[BLOCK_SIZE]; 102 | memcpy(cipher, msg, BLOCK_SIZE); 103 | memcpy(key_copy, key, BLOCK_SIZE); 104 | aes_enc_dec(cipher, key_copy, 1); 105 | } 106 | 107 | void xor_128(const unsigned char *a, const unsigned char *b, unsigned char *out) { 108 | int i; 109 | for (i = 0; i < BLOCK_SIZE; i++) { 110 | out[i] = a[i] ^ b[i]; 111 | } 112 | } 113 | 114 | //static void padding_AES(const unsigned char *lastb, unsigned char *pad, int length) { 115 | // int j; 116 | // length = length % BLOCK_SIZE; 117 | // 118 | // if(length == 0){ 119 | // memcpy(pad, lastb, BLOCK_SIZE); 120 | // return; 121 | // } 122 | // 123 | // /* original last block */ 124 | // for (j = 0; j < BLOCK_SIZE; j++) { 125 | // if (j < length) { 126 | // pad[j] = lastb[j]; 127 | // } else { 128 | // pad[j] = 0x00; 129 | // } 130 | // } 131 | //} 132 | 133 | 134 | 135 | static void leftshift_onebit(const unsigned char *input, unsigned char *output) { 136 | int i; 137 | unsigned char overflow = 0; 138 | 139 | for (i = LAST_INDEX; i >= 0; i--) { 140 | output[i] = input[i] << 1; 141 | output[i] |= overflow; 142 | overflow = (input[i] & 0x80) ? 1 : 0; 143 | } 144 | return; 145 | } 146 | 147 | static void generate_subkey(const unsigned char *key, unsigned char *K1, unsigned 148 | char *K2) { 149 | unsigned char L[BLOCK_SIZE]; 150 | unsigned char tmp[BLOCK_SIZE]; 151 | 152 | AES_128_ENC(key, const_Zero, L); 153 | 154 | if ((L[0] & 0x80) == 0) { /* If MSB(L) = 0, then K1 = L << 1 */ 155 | leftshift_onebit(L, K1); 156 | } else { /* Else K1 = ( L << 1 ) (+) Rb */ 157 | 158 | leftshift_onebit(L, tmp); 159 | xor_128(tmp, const_Rb, K1); 160 | } 161 | 162 | if ((K1[0] & 0x80) == 0) { 163 | leftshift_onebit(K1, K2); 164 | } else { 165 | leftshift_onebit(K1, tmp); 166 | xor_128(tmp, const_Rb, K2); 167 | } 168 | return; 169 | } 170 | 171 | static void padding(const unsigned char *lastb, unsigned char *pad, int length) { 172 | int j; 173 | 174 | /* original last block */ 175 | for (j = 0; j < BLOCK_SIZE; j++) { 176 | if (j < length) { 177 | pad[j] = lastb[j]; 178 | } else if (j == length) { 179 | pad[j] = 0x80; 180 | } else { 181 | pad[j] = 0x00; 182 | } 183 | } 184 | } 185 | 186 | void AES_CMAC(const unsigned char *key, const unsigned char *input, int length, 187 | unsigned char *mac) { 188 | unsigned char X[BLOCK_SIZE], Y[BLOCK_SIZE], M_last[BLOCK_SIZE], padded[BLOCK_SIZE]; 189 | unsigned char K1[BLOCK_SIZE], K2[BLOCK_SIZE]; 190 | int n, i, flag; 191 | generate_subkey(key, K1, K2); 192 | 193 | n = (length + LAST_INDEX) / BLOCK_SIZE; /* n is number of rounds */ 194 | 195 | if (n == 0) { 196 | n = 1; 197 | flag = 0; 198 | } else { 199 | if ((length % BLOCK_SIZE) == 0) { /* last block is a complete block */ 200 | flag = 1; 201 | } else { /* last block is not complete block */ 202 | flag = 0; 203 | } 204 | } 205 | 206 | if (flag) { /* last block is complete block */ 207 | xor_128(&input[BLOCK_SIZE * (n - 1)], K1, M_last); 208 | } else { 209 | padding(&input[BLOCK_SIZE * (n - 1)], padded, length % BLOCK_SIZE); 210 | xor_128(padded, K2, M_last); 211 | } 212 | 213 | memset(X, 0, BLOCK_SIZE); 214 | for (i = 0; i < n - 1; i++) { 215 | xor_128(X, &input[BLOCK_SIZE * i], Y); /* Y := Mi (+) X */ 216 | AES_128_ENC(key, Y, X); /* X := AES-128(KEY, Y); */ 217 | } 218 | 219 | xor_128(X, M_last, Y); 220 | AES_128_ENC(key, Y, X); 221 | 222 | memcpy(mac, X, BLOCK_SIZE); 223 | } 224 | -------------------------------------------------------------------------------- /main/candy.h: -------------------------------------------------------------------------------- 1 | #ifndef __CANDY_H__ 2 | #define __CANDY_H__ 3 | 4 | #include 5 | 6 | #ifdef __cplusplus 7 | extern "C" { 8 | #endif 9 | 10 | #define SSM_OP_CODE_STR(op_code) ((op_code) == 7 ? "response" : (op_code) == 8 ? "publish" : "unknown") 11 | #define SSM_ITEM_CODE_STR(code) \ 12 | ((code) == SSM_ITEM_CODE_NONE ? "SSM_ITEM_CODE_NONE" \ 13 | : (code) == SSM_ITEM_CODE_REGISTRATION ? "SSM_ITEM_CODE_REGISTRATION" \ 14 | : (code) == SSM_ITEM_CODE_LOGIN ? "SSM_ITEM_CODE_LOGIN" \ 15 | : (code) == SSM_ITEM_CODE_USER ? "SSM_ITEM_CODE_USER" \ 16 | : (code) == SSM_ITEM_CODE_HISTORY ? "SSM_ITEM_CODE_HISTORY" \ 17 | : (code) == SSM_ITEM_CODE_VERSION_DETAIL ? "SSM_ITEM_CODE_VERSION_DETAIL" \ 18 | : (code) == SSM_ITEM_CODE_DISCONNECT_REBOOT_NOW ? "SSM_ITEM_CODE_DISCONNECT_REBOOT_NOW" \ 19 | : (code) == SSM_ITEM_CODE_ENABLE_DFU ? "SSM_ITEM_CODE_ENABLE_DFU" \ 20 | : (code) == SSM_ITEM_CODE_TIME ? "SSM_ITEM_CODE_TIME" \ 21 | : (code) == SSM_ITEM_CODE_INITIAL ? "SSM_ITEM_CODE_INITIAL" \ 22 | : (code) == SSM_ITEM_CODE_MAGNET ? "SSM_ITEM_CODE_MAGNET" \ 23 | : (code) == SSM_ITEM_CODE_MECH_SETTING ? "SSM_ITEM_CODE_MECH_SETTING" \ 24 | : (code) == SSM_ITEM_CODE_MECH_STATUS ? "SSM_ITEM_CODE_MECH_STATUS" \ 25 | : (code) == SSM_ITEM_CODE_LOCK ? "SSM_ITEM_CODE_LOCK" \ 26 | : (code) == SSM_ITEM_CODE_UNLOCK ? "SSM_ITEM_CODE_UNLOCK" \ 27 | : (code) == SSM2_ITEM_OPS_TIMER_SETTING ? "SSM2_ITEM_OPS_TIMER_SETTING" \ 28 | : "UNKNOWN_ITEM_CODE") 29 | #define SSM_STATUS_STR(status) \ 30 | ((status) == SSM_NOUSE ? "NOUSE" \ 31 | : (status) == SSM_DISCONNECTED ? "DISCONNECTED" \ 32 | : (status) == SSM_SCANNING ? "SCANNING" \ 33 | : (status) == SSM_CONNECTING ? "CONNECTING" \ 34 | : (status) == SSM_CONNECTED ? "CONNECTED" \ 35 | : (status) == SSM_LOGGIN ? "LOGGIN" \ 36 | : (status) == SSM_LOCKED ? "LOCKED" \ 37 | : (status) == SSM_UNLOCKED ? "UNLOCKED" \ 38 | : (status) == SSM_MOVED ? "MOVED" \ 39 | : "status_error") 40 | 41 | #define SSM_MAX_CHAC_LEN (BLE_MAX_OCTETS - 4 - 3) 42 | #define CCM_TAG_LENGTH (4) 43 | 44 | #define SSM_SEG_PARSING_TYPE_APPEND_ONLY (0) 45 | #define SSM_SEG_PARSING_TYPE_PLAINTEXT (1) 46 | #define SSM_SEG_PARSING_TYPE_CIPHERTEXT (2) 47 | 48 | typedef enum { 49 | SESAME_5 = 5, 50 | SESAME_BIKE_2 = 6, 51 | SESAME_5_PRO = 7, 52 | } candy_product_type; 53 | 54 | typedef enum { 55 | SSM_NOUSE = 0, 56 | SSM_DISCONNECTED = 1, 57 | SSM_SCANNING = 2, 58 | SSM_CONNECTING = 3, 59 | SSM_CONNECTED = 4, 60 | SSM_LOGGIN = 5, 61 | SSM_LOCKED = 6, 62 | SSM_UNLOCKED = 7, 63 | SSM_MOVED = 8, 64 | } device_status_t; 65 | 66 | typedef enum { 67 | SSM_OP_CODE_RESPONSE = 0x07, 68 | SSM_OP_CODE_PUBLISH = 0x08, 69 | } ssm_op_code_e; 70 | 71 | typedef enum { 72 | SSM_ITEM_CODE_NONE = 0, 73 | SSM_ITEM_CODE_REGISTRATION = 1, 74 | SSM_ITEM_CODE_LOGIN = 2, 75 | SSM_ITEM_CODE_USER = 3, 76 | SSM_ITEM_CODE_HISTORY = 4, 77 | SSM_ITEM_CODE_VERSION_DETAIL = 5, 78 | SSM_ITEM_CODE_DISCONNECT_REBOOT_NOW = 6, 79 | SSM_ITEM_CODE_ENABLE_DFU = 7, 80 | SSM_ITEM_CODE_TIME = 8, 81 | SSM_ITEM_CODE_INITIAL = 14, 82 | SSM_ITEM_CODE_MAGNET = 17, 83 | SSM_ITEM_CODE_MECH_SETTING = 80, 84 | SSM_ITEM_CODE_MECH_STATUS = 81, 85 | SSM_ITEM_CODE_LOCK = 82, 86 | SSM_ITEM_CODE_UNLOCK = 83, 87 | SSM2_ITEM_OPS_TIMER_SETTING = 92, 88 | } ssm_item_code_e; 89 | 90 | #ifdef __cplusplus 91 | } 92 | #endif 93 | 94 | #endif /* __CANDY_H__ */ 95 | -------------------------------------------------------------------------------- /main/blecent.c: -------------------------------------------------------------------------------- 1 | #include "blecent.h" 2 | #include "candy.h" 3 | #include "esp_central.h" 4 | #include "esp_log.h" 5 | #include "host/ble_gap.h" 6 | #include "host/ble_hs.h" 7 | #include "nimble/nimble_port.h" 8 | #include "nimble/nimble_port_freertos.h" 9 | #include "services/gap/ble_svc_gap.h" 10 | 11 | static const char * TAG = "blecent.c"; 12 | 13 | static const ble_uuid_t * ssm_svc_uuid = BLE_UUID16_DECLARE(0xFD81); // https://github.com/CANDY-HOUSE/API_document/blob/master/SesameOS3/bluetooth.md 14 | static const ble_uuid_t * ssm_chr_uuid = BLE_UUID128_DECLARE(0x3e, 0x99, 0x76, 0xc6, 0xb4, 0xdb, 0xd3, 0xb6, 0x56, 0x98, 0xae, 0xa5, 0x02, 0x00, 0x86, 0x16); 15 | static const ble_uuid_t * ssm_ntf_uuid = BLE_UUID128_DECLARE(0x3e, 0x99, 0x76, 0xc6, 0xb4, 0xdb, 0xd3, 0xb6, 0x56, 0x98, 0xae, 0xa5, 0x03, 0x00, 0x86, 0x16); 16 | 17 | static int ble_gap_connect_event(struct ble_gap_event * event, void * arg); 18 | 19 | static int ssm_enable_notify(uint16_t conn_handle) { 20 | const struct peer_dsc * dsc; 21 | const struct peer * peer = peer_find(conn_handle); 22 | dsc = peer_dsc_find_uuid(peer, ssm_svc_uuid, ssm_ntf_uuid, BLE_UUID16_DECLARE(BLE_GATT_DSC_CLT_CFG_UUID16)); 23 | if (dsc == NULL) { 24 | ESP_LOGE(TAG, "Error: Peer lacks a CCCD for the Unread Alert Status characteristic\n"); 25 | goto err; 26 | } 27 | uint8_t value[2] = { 0x01, 0x00 }; 28 | int rc = ble_gattc_write_flat(conn_handle, dsc->dsc.handle, value, sizeof(value), NULL, NULL); 29 | if (rc != 0) { 30 | ESP_LOGE(TAG, "Error: Failed to subscribe to characteristic; rc=%d\n", rc); 31 | goto err; 32 | } 33 | ESP_LOGW(TAG, "Enable notify success!!"); 34 | return ESP_OK; 35 | err: 36 | return ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM); /* Terminate the connection. */ 37 | } 38 | 39 | static void service_disc_complete(const struct peer * peer, int status, void * arg) { 40 | if (status != 0) { 41 | ESP_LOGE(TAG, "Error: Service discovery failed; status=%d conn_handle=%d\n", status, peer->conn_handle); 42 | ble_gap_terminate(peer->conn_handle, BLE_ERR_REM_USER_CONN_TERM); 43 | return; 44 | } 45 | ESP_LOGI(TAG, "Service discovery complete conn_handle=%d\n", peer->conn_handle); 46 | ssm_enable_notify(peer->conn_handle); 47 | } 48 | 49 | static int ble_gap_event_connect_handle(struct ble_gap_event * event) { 50 | if (event->connect.status != 0) { 51 | ESP_LOGE(TAG, "Error: Connection failed; status=%d\n", event->connect.status); 52 | return ESP_FAIL; 53 | } 54 | static struct ble_gap_conn_desc desc; 55 | int rc = ble_gap_conn_find(event->connect.conn_handle, &desc); 56 | assert(rc == 0); 57 | print_conn_desc(&desc); 58 | rc = peer_add(event->connect.conn_handle); 59 | if (rc != 0) { 60 | ESP_LOGE(TAG, "Failed to add peer; rc=%d\n", rc); 61 | return ESP_FAIL; 62 | } 63 | 64 | // if the sesame device is Sesame Touch / Touch Pro, we need to set the MTU to 251 65 | #ifdef CONFIG_SESAME_TOUCH 66 | rc = ble_att_set_preferred_mtu(251); 67 | if (rc != ESP_OK) { 68 | return ESP_FAIL; 69 | } 70 | rc = ble_gattc_exchange_mtu(event->connect.conn_handle, NULL, NULL); 71 | if (rc != ESP_OK) { 72 | return ESP_FAIL; 73 | } 74 | #endif 75 | 76 | p_ssms_env->ssm.device_status = SSM_CONNECTED; // set the device status 77 | p_ssms_env->ssm.conn_id = event->connect.conn_handle; // save the connection handle 78 | ESP_LOGW(TAG, "Connect SSM success handle=%d", p_ssms_env->ssm.conn_id); 79 | rc = peer_disc_all(event->connect.conn_handle, service_disc_complete, NULL); 80 | if (rc != 0) { 81 | ESP_LOGE(TAG, "Failed to discover services; rc=%d\n", rc); 82 | return ESP_FAIL; 83 | } 84 | return ESP_OK; 85 | } 86 | 87 | static void reconnect_ssm(void) { 88 | ble_addr_t addr; 89 | addr.type = BLE_ADDR_RANDOM; 90 | memcpy(addr.val, p_ssms_env->ssm.addr, 6); 91 | int rc = ble_gap_connect(BLE_OWN_ADDR_PUBLIC, &addr, 30000, NULL, ble_gap_connect_event, NULL); 92 | if (rc != 0) { 93 | ESP_LOGE(TAG, "Error: Failed to connect to device; rc=%d\n", rc); 94 | return; 95 | } 96 | } 97 | 98 | static int ble_gap_connect_event(struct ble_gap_event * event, void * arg) { 99 | // ESP_LOGI(TAG, "[ble_gap_connect_event: %d]", event->type); 100 | switch (event->type) { 101 | case BLE_GAP_EVENT_CONNECT: 102 | return ble_gap_event_connect_handle(event); 103 | 104 | case BLE_GAP_EVENT_DISCONNECT: 105 | ESP_LOGW(TAG, "disconnect; reason=%d ", event->disconnect.reason); 106 | print_conn_desc(&event->disconnect.conn); 107 | peer_delete(event->disconnect.conn.conn_handle); 108 | reconnect_ssm(); 109 | return ESP_OK; 110 | 111 | case BLE_GAP_EVENT_CONN_UPDATE_REQ: 112 | ESP_LOGI(TAG, "connection update request event; conn_handle=%d itvl_min=%d itvl_max=%d latency=%d supervision_timoeut=%d min_ce_len=%d max_ce_len=%d\n", event->conn_update_req.conn_handle, event->conn_update_req.peer_params->itvl_min, 113 | event->conn_update_req.peer_params->itvl_max, event->conn_update_req.peer_params->latency, event->conn_update_req.peer_params->supervision_timeout, event->conn_update_req.peer_params->min_ce_len, 114 | event->conn_update_req.peer_params->max_ce_len); 115 | *event->conn_update_req.self_params = *event->conn_update_req.peer_params; 116 | return ESP_OK; 117 | 118 | case BLE_GAP_EVENT_NOTIFY_RX: 119 | ssm_ble_receiver(&p_ssms_env->ssm, event->notify_rx.om->om_data, event->notify_rx.om->om_len); 120 | return ESP_OK; 121 | 122 | default: 123 | return ESP_OK; 124 | } 125 | } 126 | 127 | static void ssm_scan_connect(const struct ble_hs_adv_fields * fields, void * disc) { 128 | ble_addr_t * addr = &((struct ble_gap_disc_desc *) disc)->addr; 129 | if (((struct ble_gap_disc_desc *) disc)->rssi < -60) { // RSSI threshold 130 | return; 131 | } 132 | if (fields->mfg_data_len >= 5 && fields->mfg_data[0] == 0x5A && fields->mfg_data[1] == 0x05) { // is SSM 133 | if (fields->mfg_data[4] == 0x00) { // unregistered SSM 134 | ESP_LOGW(TAG, "find unregistered SSM[%d]", fields->mfg_data[2]); 135 | if (p_ssms_env->ssm.device_status == SSM_NOUSE) { 136 | memcpy(p_ssms_env->ssm.addr, addr->val, 6); 137 | p_ssms_env->ssm.device_status = SSM_DISCONNECTED; 138 | p_ssms_env->ssm.conn_id = 0xFF; 139 | } 140 | } else { // registered SSM 141 | ESP_LOGI(TAG, "find registered SSM[%d]", fields->mfg_data[2]); 142 | return; 143 | } 144 | } else { 145 | return; // not SSM 146 | } 147 | ble_gap_disc_cancel(); // stop scan 148 | ESP_LOGW(TAG, "Connect SSM addr=%s addrType=%d", addr_str(addr->val), addr->type); 149 | int rc = ble_gap_connect(BLE_OWN_ADDR_PUBLIC, addr, 30000, NULL, ble_gap_connect_event, NULL); 150 | if (rc != 0) { 151 | ESP_LOGE(TAG, "Error: Failed to connect to device; rc=%d\n", rc); 152 | return; 153 | } 154 | } 155 | 156 | static int ble_gap_disc_event(struct ble_gap_event * event, void * arg) { 157 | // ESP_LOG_BUFFER_HEX_LEVEL("[find_device_mac]", event->disc.addr.val, 6, ESP_LOG_WARN); 158 | struct ble_hs_adv_fields fields; 159 | int rc = ble_hs_adv_parse_fields(&fields, event->disc.data, event->disc.length_data); 160 | if (rc != 0) { 161 | return ESP_FAIL; 162 | } 163 | ssm_scan_connect(&fields, &event->disc); 164 | return ESP_OK; 165 | } 166 | 167 | static void blecent_scan(void) { 168 | ESP_LOGI(TAG, "[blecent_scan][START]"); 169 | struct ble_gap_disc_params disc_params; 170 | disc_params.filter_duplicates = 1; 171 | disc_params.passive = 1; 172 | disc_params.itvl = 0; 173 | disc_params.window = 0; 174 | disc_params.filter_policy = 0; 175 | disc_params.limited = 0; 176 | int rc = ble_gap_disc(BLE_OWN_ADDR_PUBLIC, BLE_HS_FOREVER, &disc_params, ble_gap_disc_event, NULL); 177 | if (rc != 0) { 178 | ESP_LOGE(TAG, "Error initiating GAP discovery procedure; rc=0x%x\n", rc); 179 | } 180 | } 181 | 182 | static void blecent_host_task(void * param) { 183 | ESP_LOGI(TAG, "BLE Host Task Started"); 184 | nimble_port_run(); 185 | nimble_port_freertos_deinit(); 186 | } 187 | 188 | void esp_ble_gatt_write(sesame * ssm, uint8_t * value, uint16_t length) { 189 | const struct peer * peer = peer_find(ssm->conn_id); 190 | const struct peer_chr * chr = peer_chr_find_uuid(peer, ssm_svc_uuid, ssm_chr_uuid); 191 | if (chr == NULL) { 192 | ESP_LOGE(TAG, "Error: Peer doesn't have the subscribable characteristic\n"); 193 | return; 194 | } 195 | int rc = ble_gattc_write_flat(ssm->conn_id, chr->chr.val_handle, value, length, NULL, NULL); 196 | if (rc != 0) { 197 | ESP_LOGE(TAG, "Error: Failed to write to the subscribable characteristic; rc=%d\n", rc); 198 | } 199 | } 200 | 201 | void esp_ble_init(void) { 202 | esp_err_t ret = nimble_port_init(); 203 | if (ret != ESP_OK) { 204 | ESP_LOGE(TAG, "Failed to init nimble %d ", ret); 205 | return; 206 | } 207 | ble_hs_cfg.sync_cb = blecent_scan; 208 | int rc = peer_init(SSM_MAX_NUM, 64, 64, 64); 209 | assert(rc == 0); 210 | nimble_port_freertos_init(blecent_host_task); 211 | ESP_LOGI(TAG, "[esp_ble_init][SUCCESS]"); 212 | } 213 | -------------------------------------------------------------------------------- /main/utils/c_ccm.c: -------------------------------------------------------------------------------- 1 | 2 | 3 | #include 4 | #include "aes-cbc-cmac.h" 5 | #include "c_ccm.h" 6 | 7 | #define CCM_ENCRYPT 0 8 | #define CCM_DECRYPT 1 9 | 10 | static int aes_ecb_encrypt(const uint8_t * pKey, uint8_t * input, uint8_t * output) 11 | { 12 | AES_128_ENC(pKey, input, output); 13 | 14 | return 0; 15 | } 16 | 17 | /* Implementation that should never be optimized out by the compiler */ 18 | static void mbedtls_zeroize(void * v, size_t n) 19 | { 20 | volatile unsigned char * p = v; 21 | while (n--) 22 | *p++ = 0; 23 | } 24 | 25 | /* 26 | * Macros for common operations. 27 | * Results in smaller compiled code than static inline functions. 28 | */ 29 | 30 | /* 31 | * Update the CBC-MAC state in y using a block in b 32 | * (Always using b as the source helps the compiler optimise a bit better.) 33 | */ 34 | #define UPDATE_CBC_MAC_1 \ 35 | for (i = 0; i < 16; i++) \ 36 | y[i] ^= b[i]; \ 37 | \ 38 | if ((ret = aes_ecb_encrypt(key, y, y)) != 0) \ 39 | return (ret); 40 | 41 | /* 42 | * Encrypt or decrypt a partial block with CTR 43 | * Warning: using b for temporary storage! src and dst must not be b! 44 | * This avoids allocating one more 16 bytes buffer while allowing src == dst. 45 | */ 46 | #define CTR_CRYPT_1(dst, src, len) \ 47 | if ((ret = aes_ecb_encrypt(key, ctr, b)) != 0) \ 48 | return (ret); \ 49 | \ 50 | for (i = 0; i < len; i++) \ 51 | dst[i] = src[i] ^ b[i]; 52 | 53 | /* 54 | * Authenticated encryption or decryption 55 | */ 56 | static int ccm_auth_crypt(int mode, const unsigned char * key, const unsigned char * iv, size_t iv_len, const unsigned char * add, size_t add_len, const unsigned char * input, size_t length, unsigned char * output, unsigned char * tag, size_t tag_len) 57 | { 58 | int ret; 59 | unsigned char i; 60 | unsigned char q; 61 | size_t len_left; 62 | unsigned char b[16]; 63 | unsigned char y[16]; 64 | unsigned char ctr[16]; 65 | const unsigned char * src; 66 | unsigned char * dst; 67 | 68 | /* 69 | * Check length requirements: SP800-38C A.1 70 | * Additional requirement: a < 2^16 - 2^8 to simplify the code. 71 | * 'length' checked later (when writing it to the first block) 72 | */ 73 | if (tag_len < 4 || tag_len > 16 || tag_len % 2 != 0) 74 | return (MBEDTLS_ERR_CCM_BAD_INPUT); 75 | 76 | /* Also implies q is within bounds */ 77 | if (iv_len < 7 || iv_len > 13) 78 | return (MBEDTLS_ERR_CCM_BAD_INPUT); 79 | 80 | if (add_len > 0xFF00) 81 | return (MBEDTLS_ERR_CCM_BAD_INPUT); 82 | 83 | q = 16 - 1 - (unsigned char) iv_len; 84 | 85 | /* 86 | * First block B_0: 87 | * 0 .. 0 flags 88 | * 1 .. iv_len nonce (aka iv) 89 | * iv_len+1 .. 15 length 90 | * 91 | * With flags as (bits): 92 | * 7 0 93 | * 6 add present? 94 | * 5 .. 3 (t - 2) / 2 95 | * 2 .. 0 q - 1 96 | */ 97 | b[0] = 0; 98 | b[0] |= (add_len > 0) << 6; 99 | b[0] |= ((tag_len - 2) / 2) << 3; 100 | b[0] |= q - 1; 101 | 102 | memcpy(b + 1, iv, iv_len); 103 | 104 | for (i = 0, len_left = length; i < q; i++, len_left >>= 8) 105 | b[15 - i] = (unsigned char) (len_left & 0xFF); 106 | 107 | if (len_left > 0) 108 | return (MBEDTLS_ERR_CCM_BAD_INPUT); 109 | 110 | /* Start CBC-MAC with first block */ 111 | memset(y, 0, 16); 112 | UPDATE_CBC_MAC_1; 113 | 114 | /* 115 | * If there is additional data, update CBC-MAC with 116 | * add_len, add, 0 (padding to a block boundary) 117 | */ 118 | if (add_len > 0) 119 | { 120 | size_t use_len; 121 | len_left = add_len; 122 | src = add; 123 | 124 | memset(b, 0, 16); 125 | b[0] = (unsigned char) ((add_len >> 8) & 0xFF); 126 | b[1] = (unsigned char) ((add_len) &0xFF); 127 | 128 | use_len = len_left < 16 - 2 ? len_left : 16 - 2; 129 | memcpy(b + 2, src, use_len); 130 | len_left -= use_len; 131 | src += use_len; 132 | 133 | UPDATE_CBC_MAC_1; 134 | 135 | while (len_left > 0) 136 | { 137 | use_len = len_left > 16 ? 16 : len_left; 138 | 139 | memset(b, 0, 16); 140 | memcpy(b, src, use_len); 141 | UPDATE_CBC_MAC_1; 142 | 143 | len_left -= use_len; 144 | src += use_len; 145 | } 146 | } 147 | 148 | /* 149 | * Prepare counter block for encryption: 150 | * 0 .. 0 flags 151 | * 1 .. iv_len nonce (aka iv) 152 | * iv_len+1 .. 15 counter (initially 1) 153 | * 154 | * With flags as (bits): 155 | * 7 .. 3 0 156 | * 2 .. 0 q - 1 157 | */ 158 | ctr[0] = q - 1; 159 | memcpy(ctr + 1, iv, iv_len); 160 | memset(ctr + 1 + iv_len, 0, q); 161 | ctr[15] = 1; 162 | 163 | /* 164 | * Authenticate and {en,de}crypt the message. 165 | * 166 | * The only difference between encryption and decryption is 167 | * the respective order of authentication and {en,de}cryption. 168 | */ 169 | len_left = length; 170 | src = input; 171 | dst = output; 172 | 173 | while (len_left > 0) 174 | { 175 | size_t use_len = len_left > 16 ? 16 : len_left; 176 | 177 | if (mode == CCM_ENCRYPT) 178 | { 179 | memset(b, 0, 16); 180 | memcpy(b, src, use_len); 181 | UPDATE_CBC_MAC_1; 182 | } 183 | 184 | CTR_CRYPT_1(dst, src, use_len); 185 | 186 | if (mode == CCM_DECRYPT) 187 | { 188 | memset(b, 0, 16); 189 | memcpy(b, dst, use_len); 190 | UPDATE_CBC_MAC_1; 191 | } 192 | 193 | dst += use_len; 194 | src += use_len; 195 | len_left -= use_len; 196 | 197 | /* 198 | * Increment counter. 199 | * No need to check for overflow thanks to the length check above. 200 | */ 201 | for (i = 0; i < q; i++) 202 | if (++ctr[15 - i] != 0) 203 | break; 204 | } 205 | 206 | /* 207 | * Authentication: reset counter and crypt/mask internal tag 208 | */ 209 | for (i = 0; i < q; i++) 210 | ctr[15 - i] = 0; 211 | 212 | CTR_CRYPT_1(y, y, 16); 213 | memcpy(tag, y, tag_len); 214 | 215 | return (0); 216 | } 217 | 218 | /* 219 | * Authenticated encryption 220 | */ 221 | int aes_ccm_encrypt_and_tag(const unsigned char * key, const unsigned char * iv, size_t iv_len, const unsigned char * add, size_t add_len, const unsigned char * input, size_t length, unsigned char * output, unsigned char * tag, size_t tag_len) 222 | { 223 | return (ccm_auth_crypt(CCM_ENCRYPT, key, iv, iv_len, add, add_len, input, length, output, tag, tag_len)); 224 | } 225 | 226 | /* 227 | * Authenticated decryption 228 | */ 229 | int aes_ccm_auth_decrypt(const unsigned char * key, const unsigned char * iv, size_t iv_len, const unsigned char * add, size_t add_len, const unsigned char * input, size_t length, unsigned char * output, const unsigned char * tag, size_t tag_len) 230 | { 231 | int ret; 232 | unsigned char check_tag[16]; 233 | unsigned char i; 234 | int diff; 235 | 236 | if ((ret = ccm_auth_crypt(CCM_DECRYPT, key, iv, iv_len, add, add_len, input, length, output, check_tag, tag_len)) != 0) 237 | { 238 | return (ret); 239 | } 240 | 241 | /* Check tag in "constant-time" */ 242 | for (diff = 0, i = 0; i < tag_len; i++) 243 | diff |= tag[i] ^ check_tag[i]; 244 | 245 | if (diff != 0) 246 | { 247 | mbedtls_zeroize(output, length); 248 | return (MBEDTLS_ERR_CCM_AUTH_FAILED); 249 | } 250 | 251 | return (0); 252 | } 253 | -------------------------------------------------------------------------------- /main/utils/TI_aes_128.c: -------------------------------------------------------------------------------- 1 | /* --COPYRIGHT--,BSD 2 | * Copyright (c) 2011, Texas Instruments Incorporated 3 | * All rights reserved. 4 | * 5 | * Redistribution and use in source and binary forms, with or without 6 | * modification, are permitted provided that the following conditions 7 | * are met: 8 | * 9 | * * Redistributions of source code must retain the above copyright 10 | * notice, this list of conditions and the following disclaimer. 11 | * 12 | * * Redistributions in binary form must reproduce the above copyright 13 | * notice, this list of conditions and the following disclaimer in the 14 | * documentation and/or other materials provided with the distribution. 15 | * 16 | * * Neither the name of Texas Instruments Incorporated nor the names of 17 | * its contributors may be used to endorse or promote products derived 18 | * from this software without specific prior written permission. 19 | * 20 | * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 21 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, 22 | * THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 23 | * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR 24 | * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, 25 | * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, 26 | * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; 27 | * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, 28 | * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR 29 | * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, 30 | * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 31 | * --/COPYRIGHT--*/ 32 | /* 33 | * TI_aes_128.c 34 | * 35 | * Created on: Nov 3, 2011 36 | * Author: Eric Peeters 37 | * 38 | * Description: Implementation of the AES-128 as defined by the FIPS PUB 197: 39 | * the official AES standard 40 | */ 41 | 42 | 43 | // foreward sbox 44 | const unsigned char sbox[256] = { 45 | //0 1 2 3 4 5 6 7 8 9 A B C D E F 46 | 0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67, 0x2b, 0xfe, 0xd7, 0xab, 0x76, //0 47 | 0xca, 0x82, 0xc9, 0x7d, 0xfa, 0x59, 0x47, 0xf0, 0xad, 0xd4, 0xa2, 0xaf, 0x9c, 0xa4, 0x72, 0xc0, //1 48 | 0xb7, 0xfd, 0x93, 0x26, 0x36, 0x3f, 0xf7, 0xcc, 0x34, 0xa5, 0xe5, 0xf1, 0x71, 0xd8, 0x31, 0x15, //2 49 | 0x04, 0xc7, 0x23, 0xc3, 0x18, 0x96, 0x05, 0x9a, 0x07, 0x12, 0x80, 0xe2, 0xeb, 0x27, 0xb2, 0x75, //3 50 | 0x09, 0x83, 0x2c, 0x1a, 0x1b, 0x6e, 0x5a, 0xa0, 0x52, 0x3b, 0xd6, 0xb3, 0x29, 0xe3, 0x2f, 0x84, //4 51 | 0x53, 0xd1, 0x00, 0xed, 0x20, 0xfc, 0xb1, 0x5b, 0x6a, 0xcb, 0xbe, 0x39, 0x4a, 0x4c, 0x58, 0xcf, //5 52 | 0xd0, 0xef, 0xaa, 0xfb, 0x43, 0x4d, 0x33, 0x85, 0x45, 0xf9, 0x02, 0x7f, 0x50, 0x3c, 0x9f, 0xa8, //6 53 | 0x51, 0xa3, 0x40, 0x8f, 0x92, 0x9d, 0x38, 0xf5, 0xbc, 0xb6, 0xda, 0x21, 0x10, 0xff, 0xf3, 0xd2, //7 54 | 0xcd, 0x0c, 0x13, 0xec, 0x5f, 0x97, 0x44, 0x17, 0xc4, 0xa7, 0x7e, 0x3d, 0x64, 0x5d, 0x19, 0x73, //8 55 | 0x60, 0x81, 0x4f, 0xdc, 0x22, 0x2a, 0x90, 0x88, 0x46, 0xee, 0xb8, 0x14, 0xde, 0x5e, 0x0b, 0xdb, //9 56 | 0xe0, 0x32, 0x3a, 0x0a, 0x49, 0x06, 0x24, 0x5c, 0xc2, 0xd3, 0xac, 0x62, 0x91, 0x95, 0xe4, 0x79, //A 57 | 0xe7, 0xc8, 0x37, 0x6d, 0x8d, 0xd5, 0x4e, 0xa9, 0x6c, 0x56, 0xf4, 0xea, 0x65, 0x7a, 0xae, 0x08, //B 58 | 0xba, 0x78, 0x25, 0x2e, 0x1c, 0xa6, 0xb4, 0xc6, 0xe8, 0xdd, 0x74, 0x1f, 0x4b, 0xbd, 0x8b, 0x8a, //C 59 | 0x70, 0x3e, 0xb5, 0x66, 0x48, 0x03, 0xf6, 0x0e, 0x61, 0x35, 0x57, 0xb9, 0x86, 0xc1, 0x1d, 0x9e, //D 60 | 0xe1, 0xf8, 0x98, 0x11, 0x69, 0xd9, 0x8e, 0x94, 0x9b, 0x1e, 0x87, 0xe9, 0xce, 0x55, 0x28, 0xdf, //E 61 | 0x8c, 0xa1, 0x89, 0x0d, 0xbf, 0xe6, 0x42, 0x68, 0x41, 0x99, 0x2d, 0x0f, 0xb0, 0x54, 0xbb, 0x16 }; //F 62 | 63 | // inverse sbox 64 | const unsigned char rsbox[256] = 65 | { 0x52, 0x09, 0x6a, 0xd5, 0x30, 0x36, 0xa5, 0x38, 0xbf, 0x40, 0xa3, 0x9e, 0x81, 0xf3, 0xd7, 0xfb 66 | , 0x7c, 0xe3, 0x39, 0x82, 0x9b, 0x2f, 0xff, 0x87, 0x34, 0x8e, 0x43, 0x44, 0xc4, 0xde, 0xe9, 0xcb 67 | , 0x54, 0x7b, 0x94, 0x32, 0xa6, 0xc2, 0x23, 0x3d, 0xee, 0x4c, 0x95, 0x0b, 0x42, 0xfa, 0xc3, 0x4e 68 | , 0x08, 0x2e, 0xa1, 0x66, 0x28, 0xd9, 0x24, 0xb2, 0x76, 0x5b, 0xa2, 0x49, 0x6d, 0x8b, 0xd1, 0x25 69 | , 0x72, 0xf8, 0xf6, 0x64, 0x86, 0x68, 0x98, 0x16, 0xd4, 0xa4, 0x5c, 0xcc, 0x5d, 0x65, 0xb6, 0x92 70 | , 0x6c, 0x70, 0x48, 0x50, 0xfd, 0xed, 0xb9, 0xda, 0x5e, 0x15, 0x46, 0x57, 0xa7, 0x8d, 0x9d, 0x84 71 | , 0x90, 0xd8, 0xab, 0x00, 0x8c, 0xbc, 0xd3, 0x0a, 0xf7, 0xe4, 0x58, 0x05, 0xb8, 0xb3, 0x45, 0x06 72 | , 0xd0, 0x2c, 0x1e, 0x8f, 0xca, 0x3f, 0x0f, 0x02, 0xc1, 0xaf, 0xbd, 0x03, 0x01, 0x13, 0x8a, 0x6b 73 | , 0x3a, 0x91, 0x11, 0x41, 0x4f, 0x67, 0xdc, 0xea, 0x97, 0xf2, 0xcf, 0xce, 0xf0, 0xb4, 0xe6, 0x73 74 | , 0x96, 0xac, 0x74, 0x22, 0xe7, 0xad, 0x35, 0x85, 0xe2, 0xf9, 0x37, 0xe8, 0x1c, 0x75, 0xdf, 0x6e 75 | , 0x47, 0xf1, 0x1a, 0x71, 0x1d, 0x29, 0xc5, 0x89, 0x6f, 0xb7, 0x62, 0x0e, 0xaa, 0x18, 0xbe, 0x1b 76 | , 0xfc, 0x56, 0x3e, 0x4b, 0xc6, 0xd2, 0x79, 0x20, 0x9a, 0xdb, 0xc0, 0xfe, 0x78, 0xcd, 0x5a, 0xf4 77 | , 0x1f, 0xdd, 0xa8, 0x33, 0x88, 0x07, 0xc7, 0x31, 0xb1, 0x12, 0x10, 0x59, 0x27, 0x80, 0xec, 0x5f 78 | , 0x60, 0x51, 0x7f, 0xa9, 0x19, 0xb5, 0x4a, 0x0d, 0x2d, 0xe5, 0x7a, 0x9f, 0x93, 0xc9, 0x9c, 0xef 79 | , 0xa0, 0xe0, 0x3b, 0x4d, 0xae, 0x2a, 0xf5, 0xb0, 0xc8, 0xeb, 0xbb, 0x3c, 0x83, 0x53, 0x99, 0x61 80 | , 0x17, 0x2b, 0x04, 0x7e, 0xba, 0x77, 0xd6, 0x26, 0xe1, 0x69, 0x14, 0x63, 0x55, 0x21, 0x0c, 0x7d }; 81 | 82 | // round constant 83 | const unsigned char Rcon[10] = { 84 | 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36}; 85 | 86 | 87 | // multiply by 2 in the galois field 88 | unsigned char galois_mul2(unsigned char value) 89 | { 90 | if (value>>7) 91 | { 92 | return ((value << 1)^0x1b); 93 | } else 94 | return (value << 1); 95 | } 96 | 97 | // AES encryption and decryption function 98 | // The code was optimized for memory (flash and ram) 99 | // Combining both encryption and decryption resulted in a slower implementation 100 | // but much smaller than the 2 functions separated 101 | // This function only implements AES-128 encryption and decryption (AES-192 and 102 | // AES-256 are not supported by this code) 103 | void aes_enc_dec(unsigned char *state, unsigned char *key, unsigned char dir) 104 | { 105 | unsigned char buf1, buf2, buf3, buf4, round, i; 106 | 107 | // In case of decryption 108 | if (dir) { 109 | // compute the last key of encryption before starting the decryption 110 | for (round = 0 ; round < 10; round++) { 111 | //key schedule 112 | key[0] = sbox[key[13]]^key[0]^Rcon[round]; 113 | key[1] = sbox[key[14]]^key[1]; 114 | key[2] = sbox[key[15]]^key[2]; 115 | key[3] = sbox[key[12]]^key[3]; 116 | for (i=4; i<16; i++) { 117 | key[i] = key[i] ^ key[i-4]; 118 | } 119 | } 120 | 121 | //first Addroundkey 122 | for (i = 0; i <16; i++){ 123 | state[i]=state[i] ^ key[i]; 124 | } 125 | } 126 | 127 | // main loop 128 | for (round = 0; round < 10; round++){ 129 | if (dir){ 130 | //Inverse key schedule 131 | for (i=15; i>3; --i) { 132 | key[i] = key[i] ^ key[i-4]; 133 | } 134 | key[0] = sbox[key[13]]^key[0]^Rcon[9-round]; 135 | key[1] = sbox[key[14]]^key[1]; 136 | key[2] = sbox[key[15]]^key[2]; 137 | key[3] = sbox[key[12]]^key[3]; 138 | } else { 139 | for (i = 0; i <16; i++){ 140 | // with shiftrow i+5 mod 16 141 | state[i]=sbox[state[i] ^ key[i]]; 142 | } 143 | //shift rows 144 | buf1 = state[1]; 145 | state[1] = state[5]; 146 | state[5] = state[9]; 147 | state[9] = state[13]; 148 | state[13] = buf1; 149 | 150 | buf1 = state[2]; 151 | buf2 = state[6]; 152 | state[2] = state[10]; 153 | state[6] = state[14]; 154 | state[10] = buf1; 155 | state[14] = buf2; 156 | 157 | buf1 = state[15]; 158 | state[15] = state[11]; 159 | state[11] = state[7]; 160 | state[7] = state[3]; 161 | state[3] = buf1; 162 | } 163 | //mixcol - inv mix 164 | if ((round > 0 && dir) || (round < 9 && !dir)) { 165 | for (i=0; i <4; i++){ 166 | buf4 = (i << 2); 167 | if (dir){ 168 | // precompute for decryption 169 | buf1 = galois_mul2(galois_mul2(state[buf4]^state[buf4+2])); 170 | buf2 = galois_mul2(galois_mul2(state[buf4+1]^state[buf4+3])); 171 | state[buf4] ^= buf1; state[buf4+1] ^= buf2; state[buf4+2] ^= buf1; state[buf4+3] ^= buf2; 172 | } 173 | // in all cases 174 | buf1 = state[buf4] ^ state[buf4+1] ^ state[buf4+2] ^ state[buf4+3]; 175 | buf2 = state[buf4]; 176 | buf3 = state[buf4]^state[buf4+1]; buf3=galois_mul2(buf3); state[buf4] = state[buf4] ^ buf3 ^ buf1; 177 | buf3 = state[buf4+1]^state[buf4+2]; buf3=galois_mul2(buf3); state[buf4+1] = state[buf4+1] ^ buf3 ^ buf1; 178 | buf3 = state[buf4+2]^state[buf4+3]; buf3=galois_mul2(buf3); state[buf4+2] = state[buf4+2] ^ buf3 ^ buf1; 179 | buf3 = state[buf4+3]^buf2; buf3=galois_mul2(buf3); state[buf4+3] = state[buf4+3] ^ buf3 ^ buf1; 180 | } 181 | } 182 | 183 | if (dir) { 184 | //Inv shift rows 185 | // Row 1 186 | buf1 = state[13]; 187 | state[13] = state[9]; 188 | state[9] = state[5]; 189 | state[5] = state[1]; 190 | state[1] = buf1; 191 | //Row 2 192 | buf1 = state[10]; 193 | buf2 = state[14]; 194 | state[10] = state[2]; 195 | state[14] = state[6]; 196 | state[2] = buf1; 197 | state[6] = buf2; 198 | //Row 3 199 | buf1 = state[3]; 200 | state[3] = state[7]; 201 | state[7] = state[11]; 202 | state[11] = state[15]; 203 | state[15] = buf1; 204 | 205 | for (i = 0; i <16; i++){ 206 | // with shiftrow i+5 mod 16 207 | state[i]=rsbox[state[i]] ^ key[i]; 208 | } 209 | } else { 210 | //key schedule 211 | key[0] = sbox[key[13]]^key[0]^Rcon[round]; 212 | key[1] = sbox[key[14]]^key[1]; 213 | key[2] = sbox[key[15]]^key[2]; 214 | key[3] = sbox[key[12]]^key[3]; 215 | for (i=4; i<16; i++) { 216 | key[i] = key[i] ^ key[i-4]; 217 | } 218 | } 219 | } 220 | if (!dir) { 221 | //last Addroundkey 222 | for (i = 0; i <16; i++){ 223 | // with shiftrow i+5 mod 16 224 | state[i]=state[i] ^ key[i]; 225 | } // enf for 226 | } // end if (!dir) 227 | } // end function 228 | -------------------------------------------------------------------------------- /main/utils/uECC.h: -------------------------------------------------------------------------------- 1 | /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */ 2 | 3 | #ifndef _UECC_H_ 4 | #define _UECC_H_ 5 | 6 | #include 7 | 8 | /* Platform selection options. 9 | If uECC_PLATFORM is not defined, the code will try to guess it based on compiler macros. 10 | Possible values for uECC_PLATFORM are defined below: */ 11 | #define uECC_arch_other 0 12 | #define uECC_x86 1 13 | #define uECC_x86_64 2 14 | #define uECC_arm 3 15 | #define uECC_arm_thumb 4 16 | #define uECC_arm_thumb2 5 17 | #define uECC_arm64 6 18 | #define uECC_avr 7 19 | 20 | /* If desired, you can define uECC_WORD_SIZE as appropriate for your platform (1, 4, or 8 bytes). 21 | If uECC_WORD_SIZE is not explicitly defined then it will be automatically set based on your 22 | platform. */ 23 | 24 | /* Optimization level; trade speed for code size. 25 | Larger values produce code that is faster but larger. 26 | Currently supported values are 0 - 4; 0 is unusably slow for most applications. 27 | Optimization level 4 currently only has an effect ARM platforms where more than one 28 | curve is enabled. */ 29 | #ifndef uECC_OPTIMIZATION_LEVEL 30 | #define uECC_OPTIMIZATION_LEVEL 2 31 | #endif 32 | 33 | /* uECC_SQUARE_FUNC - If enabled (defined as nonzero), this will cause a specific function to be 34 | used for (scalar) squaring instead of the generic multiplication function. This can make things 35 | faster somewhat faster, but increases the code size. */ 36 | #ifndef uECC_SQUARE_FUNC 37 | #define uECC_SQUARE_FUNC 0 38 | #endif 39 | 40 | /* uECC_VLI_NATIVE_LITTLE_ENDIAN - If enabled (defined as nonzero), this will switch to native 41 | little-endian format for *all* arrays passed in and out of the public API. This includes public 42 | and private keys, shared secrets, signatures and message hashes. 43 | Using this switch reduces the amount of call stack memory used by uECC, since less intermediate 44 | translations are required. 45 | Note that this will *only* work on native little-endian processors and it will treat the uint8_t 46 | arrays passed into the public API as word arrays, therefore requiring the provided byte arrays 47 | to be word aligned on architectures that do not support unaligned accesses. 48 | IMPORTANT: Keys and signatures generated with uECC_VLI_NATIVE_LITTLE_ENDIAN=1 are incompatible 49 | with keys and signatures generated with uECC_VLI_NATIVE_LITTLE_ENDIAN=0; all parties must use 50 | the same endianness. */ 51 | #ifndef uECC_VLI_NATIVE_LITTLE_ENDIAN 52 | #define uECC_VLI_NATIVE_LITTLE_ENDIAN 1 53 | #endif 54 | 55 | /* Curve support selection. Set to 0 to remove that curve. */ 56 | #ifndef uECC_SUPPORTS_secp160r1 57 | #define uECC_SUPPORTS_secp160r1 0 58 | #endif 59 | #ifndef uECC_SUPPORTS_secp192r1 60 | #define uECC_SUPPORTS_secp192r1 1 61 | #endif 62 | #ifndef uECC_SUPPORTS_secp224r1 63 | #define uECC_SUPPORTS_secp224r1 0 64 | #endif 65 | #ifndef uECC_SUPPORTS_secp256r1 66 | #define uECC_SUPPORTS_secp256r1 1 67 | #endif 68 | #ifndef uECC_SUPPORTS_secp256k1 69 | #define uECC_SUPPORTS_secp256k1 0 70 | #endif 71 | 72 | /* Specifies whether compressed point format is supported. 73 | Set to 0 to disable point compression/decompression functions. */ 74 | #ifndef uECC_SUPPORT_COMPRESSED_POINT 75 | #define uECC_SUPPORT_COMPRESSED_POINT 0 76 | #endif 77 | 78 | struct uECC_Curve_t; 79 | typedef const struct uECC_Curve_t * uECC_Curve; 80 | 81 | #ifdef __cplusplus 82 | extern "C" { 83 | #endif 84 | 85 | #if uECC_SUPPORTS_secp160r1 86 | uECC_Curve uECC_secp160r1(void); 87 | #endif 88 | #if uECC_SUPPORTS_secp192r1 89 | uECC_Curve uECC_secp192r1(void); 90 | #endif 91 | #if uECC_SUPPORTS_secp224r1 92 | uECC_Curve uECC_secp224r1(void); 93 | #endif 94 | #if uECC_SUPPORTS_secp256r1 95 | uECC_Curve uECC_secp256r1(void); 96 | #endif 97 | #if uECC_SUPPORTS_secp256k1 98 | uECC_Curve uECC_secp256k1(void); 99 | #endif 100 | 101 | /* uECC_RNG_Function type 102 | The RNG function should fill 'size' random bytes into 'dest'. It should return 1 if 103 | 'dest' was filled with random data, or 0 if the random data could not be generated. 104 | The filled-in values should be either truly random, or from a cryptographically-secure PRNG. 105 | 106 | A correctly functioning RNG function must be set (using uECC_set_rng()) before calling 107 | uECC_make_key() or uECC_sign(). 108 | 109 | Setting a correctly functioning RNG function improves the resistance to side-channel attacks 110 | for uECC_shared_secret() and uECC_sign_deterministic(). 111 | 112 | A correct RNG function is set by default when building for Windows, Linux, or OS X. 113 | If you are building on another POSIX-compliant system that supports /dev/random or /dev/urandom, 114 | you can define uECC_POSIX to use the predefined RNG. For embedded platforms there is no predefined 115 | RNG function; you must provide your own. 116 | */ 117 | typedef int (*uECC_RNG_Function)(uint8_t * dest, unsigned size); 118 | 119 | /* uECC_set_rng() function. 120 | Set the function that will be used to generate random bytes. The RNG function should 121 | return 1 if the random data was generated, or 0 if the random data could not be generated. 122 | 123 | On platforms where there is no predefined RNG function (eg embedded platforms), this must 124 | be called before uECC_make_key() or uECC_sign() are used. 125 | 126 | Inputs: 127 | rng_function - The function that will be used to generate random bytes. 128 | */ 129 | void uECC_set_rng(uECC_RNG_Function rng_function); 130 | 131 | /* uECC_get_rng() function. 132 | 133 | Returns the function that will be used to generate random bytes. 134 | */ 135 | uECC_RNG_Function uECC_get_rng(void); 136 | 137 | /* uECC_curve_private_key_size() function. 138 | 139 | Returns the size of a private key for the curve in bytes. 140 | */ 141 | int uECC_curve_private_key_size(uECC_Curve curve); 142 | 143 | /* uECC_curve_public_key_size() function. 144 | 145 | Returns the size of a public key for the curve in bytes. 146 | */ 147 | int uECC_curve_public_key_size(uECC_Curve curve); 148 | 149 | /* uECC_make_key() function. 150 | Create a public/private key pair. 151 | 152 | Outputs: 153 | public_key - Will be filled in with the public key. Must be at least 2 * the curve size 154 | (in bytes) long. For example, if the curve is secp256r1, public_key must be 64 155 | bytes long. 156 | private_key - Will be filled in with the private key. Must be as long as the curve order; this 157 | is typically the same as the curve size, except for secp160r1. For example, if the 158 | curve is secp256r1, private_key must be 32 bytes long. 159 | 160 | For secp160r1, private_key must be 21 bytes long! Note that the first byte will 161 | almost always be 0 (there is about a 1 in 2^80 chance of it being non-zero). 162 | 163 | Returns 1 if the key pair was generated successfully, 0 if an error occurred. 164 | */ 165 | int uECC_make_key(uint8_t * public_key, uint8_t * private_key, uECC_Curve curve); 166 | int uECC_make_key_lit(uint8_t * public_key, uint8_t * private_key, uECC_Curve curve); 167 | 168 | /* uECC_shared_secret() function. 169 | Compute a shared secret given your secret key and someone else's public key. 170 | Note: It is recommended that you hash the result of uECC_shared_secret() before using it for 171 | symmetric encryption or HMAC. 172 | 173 | Inputs: 174 | public_key - The public key of the remote party. 175 | private_key - Your private key. 176 | 177 | Outputs: 178 | secret - Will be filled in with the shared secret value. Must be the same size as the 179 | curve size; for example, if the curve is secp256r1, secret must be 32 bytes long. 180 | 181 | Returns 1 if the shared secret was generated successfully, 0 if an error occurred. 182 | */ 183 | int uECC_shared_secret(const uint8_t * public_key, const uint8_t * private_key, uint8_t * secret, uECC_Curve curve); 184 | int uECC_shared_secret_lit(const uint8_t * public_key, const uint8_t * private_key, uint8_t * secret, uECC_Curve curve); 185 | 186 | #if uECC_SUPPORT_COMPRESSED_POINT 187 | /* uECC_compress() function. 188 | Compress a public key. 189 | 190 | Inputs: 191 | public_key - The public key to compress. 192 | 193 | Outputs: 194 | compressed - Will be filled in with the compressed public key. Must be at least 195 | (curve size + 1) bytes long; for example, if the curve is secp256r1, 196 | compressed must be 33 bytes long. 197 | */ 198 | void uECC_compress(const uint8_t * public_key, uint8_t * compressed, uECC_Curve curve); 199 | 200 | /* uECC_decompress() function. 201 | Decompress a compressed public key. 202 | 203 | Inputs: 204 | compressed - The compressed public key. 205 | 206 | Outputs: 207 | public_key - Will be filled in with the decompressed public key. 208 | */ 209 | void uECC_decompress(const uint8_t * compressed, uint8_t * public_key, uECC_Curve curve); 210 | #endif /* uECC_SUPPORT_COMPRESSED_POINT */ 211 | 212 | /* uECC_valid_public_key() function. 213 | Check to see if a public key is valid. 214 | 215 | Note that you are not required to check for a valid public key before using any other uECC 216 | functions. However, you may wish to avoid spending CPU time computing a shared secret or 217 | verifying a signature using an invalid public key. 218 | 219 | Inputs: 220 | public_key - The public key to check. 221 | 222 | Returns 1 if the public key is valid, 0 if it is invalid. 223 | */ 224 | int uECC_valid_public_key(const uint8_t * public_key, uECC_Curve curve); 225 | 226 | /* uECC_compute_public_key() function. 227 | Compute the corresponding public key for a private key. 228 | 229 | Inputs: 230 | private_key - The private key to compute the public key for 231 | 232 | Outputs: 233 | public_key - Will be filled in with the corresponding public key 234 | 235 | Returns 1 if the key was computed successfully, 0 if an error occurred. 236 | */ 237 | int uECC_compute_public_key(const uint8_t * private_key, uint8_t * public_key, uECC_Curve curve); 238 | 239 | /* uECC_sign() function. 240 | Generate an ECDSA signature for a given hash value. 241 | 242 | Usage: Compute a hash of the data you wish to sign (SHA-2 is recommended) and pass it in to 243 | this function along with your private key. 244 | 245 | Inputs: 246 | private_key - Your private key. 247 | message_hash - The hash of the message to sign. 248 | hash_size - The size of message_hash in bytes. 249 | 250 | Outputs: 251 | signature - Will be filled in with the signature value. Must be at least 2 * curve size long. 252 | For example, if the curve is secp256r1, signature must be 64 bytes long. 253 | 254 | Returns 1 if the signature generated successfully, 0 if an error occurred. 255 | */ 256 | int uECC_sign(const uint8_t * private_key, const uint8_t * message_hash, unsigned hash_size, uint8_t * signature, uECC_Curve curve); 257 | 258 | /* uECC_HashContext structure. 259 | This is used to pass in an arbitrary hash function to uECC_sign_deterministic(). 260 | The structure will be used for multiple hash computations; each time a new hash 261 | is computed, init_hash() will be called, followed by one or more calls to 262 | update_hash(), and finally a call to finish_hash() to produce the resulting hash. 263 | 264 | The intention is that you will create a structure that includes uECC_HashContext 265 | followed by any hash-specific data. For example: 266 | 267 | typedef struct SHA256_HashContext { 268 | uECC_HashContext uECC; 269 | SHA256_CTX ctx; 270 | } SHA256_HashContext; 271 | 272 | void init_SHA256(uECC_HashContext *base) { 273 | SHA256_HashContext *context = (SHA256_HashContext *)base; 274 | SHA256_Init(&context->ctx); 275 | } 276 | 277 | void update_SHA256(uECC_HashContext *base, 278 | const uint8_t *message, 279 | unsigned message_size) { 280 | SHA256_HashContext *context = (SHA256_HashContext *)base; 281 | SHA256_Update(&context->ctx, message, message_size); 282 | } 283 | 284 | void finish_SHA256(uECC_HashContext *base, uint8_t *hash_result) { 285 | SHA256_HashContext *context = (SHA256_HashContext *)base; 286 | SHA256_Final(hash_result, &context->ctx); 287 | } 288 | 289 | ... when signing ... 290 | { 291 | uint8_t tmp[32 + 32 + 64]; 292 | SHA256_HashContext ctx = {{&init_SHA256, &update_SHA256, &finish_SHA256, 64, 32, tmp}}; 293 | uECC_sign_deterministic(key, message_hash, &ctx.uECC, signature); 294 | } 295 | */ 296 | typedef struct uECC_HashContext 297 | { 298 | void (*init_hash)(const struct uECC_HashContext * context); 299 | void (*update_hash)(const struct uECC_HashContext * context, const uint8_t * message, unsigned message_size); 300 | void (*finish_hash)(const struct uECC_HashContext * context, uint8_t * hash_result); 301 | unsigned block_size; /* Hash function block size in bytes, eg 64 for SHA-256. */ 302 | unsigned result_size; /* Hash function result size in bytes, eg 32 for SHA-256. */ 303 | uint8_t * tmp; /* Must point to a buffer of at least (2 * result_size + block_size) bytes. */ 304 | } uECC_HashContext; 305 | 306 | /* uECC_sign_deterministic() function. 307 | Generate an ECDSA signature for a given hash value, using a deterministic algorithm 308 | (see RFC 6979). You do not need to set the RNG using uECC_set_rng() before calling 309 | this function; however, if the RNG is defined it will improve resistance to side-channel 310 | attacks. 311 | 312 | Usage: Compute a hash of the data you wish to sign (SHA-2 is recommended) and pass it to 313 | this function along with your private key and a hash context. Note that the message_hash 314 | does not need to be computed with the same hash function used by hash_context. 315 | 316 | Inputs: 317 | private_key - Your private key. 318 | message_hash - The hash of the message to sign. 319 | hash_size - The size of message_hash in bytes. 320 | hash_context - A hash context to use. 321 | 322 | Outputs: 323 | signature - Will be filled in with the signature value. 324 | 325 | Returns 1 if the signature generated successfully, 0 if an error occurred. 326 | */ 327 | int uECC_sign_deterministic(const uint8_t * private_key, const uint8_t * message_hash, unsigned hash_size, const uECC_HashContext * hash_context, uint8_t * signature, uECC_Curve curve); 328 | 329 | /* uECC_verify() function. 330 | Verify an ECDSA signature. 331 | 332 | Usage: Compute the hash of the signed data using the same hash as the signer and 333 | pass it to this function along with the signer's public key and the signature values (r and s). 334 | 335 | Inputs: 336 | public_key - The signer's public key. 337 | message_hash - The hash of the signed data. 338 | hash_size - The size of message_hash in bytes. 339 | signature - The signature value. 340 | 341 | Returns 1 if the signature is valid, 0 if it is invalid. 342 | */ 343 | int uECC_verify(const uint8_t * public_key, const uint8_t * message_hash, unsigned hash_size, const uint8_t * signature, uECC_Curve curve); 344 | 345 | #ifdef __cplusplus 346 | } /* end of extern "C" */ 347 | #endif 348 | 349 | #endif /* _UECC_H_ */ 350 | -------------------------------------------------------------------------------- /main/utils/curve-specific.inc: -------------------------------------------------------------------------------- 1 | /* Copyright 2015, Kenneth MacKay. Licensed under the BSD 2-clause license. */ 2 | 3 | #ifndef _UECC_CURVE_SPECIFIC_H_ 4 | #define _UECC_CURVE_SPECIFIC_H_ 5 | 6 | #define num_bytes_secp160r1 20 7 | #define num_bytes_secp192r1 24 8 | #define num_bytes_secp224r1 28 9 | #define num_bytes_secp256r1 32 10 | #define num_bytes_secp256k1 32 11 | 12 | #if (uECC_WORD_SIZE == 1) 13 | 14 | #define num_words_secp160r1 20 15 | #define num_words_secp192r1 24 16 | #define num_words_secp224r1 28 17 | #define num_words_secp256r1 32 18 | #define num_words_secp256k1 32 19 | 20 | #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) \ 21 | 0x##a, 0x##b, 0x##c, 0x##d, 0x##e, 0x##f, 0x##g, 0x##h 22 | #define BYTES_TO_WORDS_4(a, b, c, d) 0x##a, 0x##b, 0x##c, 0x##d 23 | 24 | #elif (uECC_WORD_SIZE == 4) 25 | 26 | #define num_words_secp160r1 5 27 | #define num_words_secp192r1 6 28 | #define num_words_secp224r1 7 29 | #define num_words_secp256r1 8 30 | #define num_words_secp256k1 8 31 | 32 | #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##d##c##b##a, 0x##h##g##f##e 33 | #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a 34 | 35 | #elif (uECC_WORD_SIZE == 8) 36 | 37 | #define num_words_secp160r1 3 38 | #define num_words_secp192r1 3 39 | #define num_words_secp224r1 4 40 | #define num_words_secp256r1 4 41 | #define num_words_secp256k1 4 42 | 43 | #define BYTES_TO_WORDS_8(a, b, c, d, e, f, g, h) 0x##h##g##f##e##d##c##b##a##ull 44 | #define BYTES_TO_WORDS_4(a, b, c, d) 0x##d##c##b##a##ull 45 | 46 | #endif /* uECC_WORD_SIZE */ 47 | 48 | #if uECC_SUPPORTS_secp160r1 || uECC_SUPPORTS_secp192r1 || \ 49 | uECC_SUPPORTS_secp224r1 || uECC_SUPPORTS_secp256r1 50 | static void double_jacobian_default(uECC_word_t * X1, 51 | uECC_word_t * Y1, 52 | uECC_word_t * Z1, 53 | uECC_Curve curve) { 54 | /* t1 = X, t2 = Y, t3 = Z */ 55 | uECC_word_t t4[uECC_MAX_WORDS]; 56 | uECC_word_t t5[uECC_MAX_WORDS]; 57 | wordcount_t num_words = curve->num_words; 58 | 59 | if (uECC_vli_isZero(Z1, num_words)) { 60 | return; 61 | } 62 | 63 | uECC_vli_modSquare_fast(t4, Y1, curve); /* t4 = y1^2 */ 64 | uECC_vli_modMult_fast(t5, X1, t4, curve); /* t5 = x1*y1^2 = A */ 65 | uECC_vli_modSquare_fast(t4, t4, curve); /* t4 = y1^4 */ 66 | uECC_vli_modMult_fast(Y1, Y1, Z1, curve); /* t2 = y1*z1 = z3 */ 67 | uECC_vli_modSquare_fast(Z1, Z1, curve); /* t3 = z1^2 */ 68 | 69 | uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = x1 + z1^2 */ 70 | uECC_vli_modAdd(Z1, Z1, Z1, curve->p, num_words); /* t3 = 2*z1^2 */ 71 | uECC_vli_modSub(Z1, X1, Z1, curve->p, num_words); /* t3 = x1 - z1^2 */ 72 | uECC_vli_modMult_fast(X1, X1, Z1, curve); /* t1 = x1^2 - z1^4 */ 73 | 74 | uECC_vli_modAdd(Z1, X1, X1, curve->p, num_words); /* t3 = 2*(x1^2 - z1^4) */ 75 | uECC_vli_modAdd(X1, X1, Z1, curve->p, num_words); /* t1 = 3*(x1^2 - z1^4) */ 76 | if (uECC_vli_testBit(X1, 0)) { 77 | uECC_word_t l_carry = uECC_vli_add(X1, X1, curve->p, num_words); 78 | uECC_vli_rshift1(X1, num_words); 79 | X1[num_words - 1] |= l_carry << (uECC_WORD_BITS - 1); 80 | } else { 81 | uECC_vli_rshift1(X1, num_words); 82 | } 83 | /* t1 = 3/2*(x1^2 - z1^4) = B */ 84 | 85 | uECC_vli_modSquare_fast(Z1, X1, curve); /* t3 = B^2 */ 86 | uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - A */ 87 | uECC_vli_modSub(Z1, Z1, t5, curve->p, num_words); /* t3 = B^2 - 2A = x3 */ 88 | uECC_vli_modSub(t5, t5, Z1, curve->p, num_words); /* t5 = A - x3 */ 89 | uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = B * (A - x3) */ 90 | uECC_vli_modSub(t4, X1, t4, curve->p, num_words); /* t4 = B * (A - x3) - y1^4 = y3 */ 91 | 92 | uECC_vli_set(X1, Z1, num_words); 93 | uECC_vli_set(Z1, Y1, num_words); 94 | uECC_vli_set(Y1, t4, num_words); 95 | } 96 | 97 | /* Computes result = x^3 + ax + b. result must not overlap x. */ 98 | static void x_side_default(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve) { 99 | uECC_word_t _3[uECC_MAX_WORDS] = {3}; /* -a = 3 */ 100 | wordcount_t num_words = curve->num_words; 101 | 102 | uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */ 103 | uECC_vli_modSub(result, result, _3, curve->p, num_words); /* r = x^2 - 3 */ 104 | uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 - 3x */ 105 | uECC_vli_modAdd(result, result, curve->b, curve->p, num_words); /* r = x^3 - 3x + b */ 106 | } 107 | #endif /* uECC_SUPPORTS_secp... */ 108 | 109 | #if uECC_SUPPORT_COMPRESSED_POINT 110 | #if uECC_SUPPORTS_secp160r1 || uECC_SUPPORTS_secp192r1 || \ 111 | uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1 112 | /* Compute a = sqrt(a) (mod curve_p). */ 113 | static void mod_sqrt_default(uECC_word_t *a, uECC_Curve curve) { 114 | bitcount_t i; 115 | uECC_word_t p1[uECC_MAX_WORDS] = {1}; 116 | uECC_word_t l_result[uECC_MAX_WORDS] = {1}; 117 | wordcount_t num_words = curve->num_words; 118 | 119 | /* When curve->p == 3 (mod 4), we can compute 120 | sqrt(a) = a^((curve->p + 1) / 4) (mod curve->p). */ 121 | uECC_vli_add(p1, curve->p, p1, num_words); /* p1 = curve_p + 1 */ 122 | for (i = uECC_vli_numBits(p1, num_words) - 1; i > 1; --i) { 123 | uECC_vli_modSquare_fast(l_result, l_result, curve); 124 | if (uECC_vli_testBit(p1, i)) { 125 | uECC_vli_modMult_fast(l_result, l_result, a, curve); 126 | } 127 | } 128 | uECC_vli_set(a, l_result, num_words); 129 | } 130 | #endif /* uECC_SUPPORTS_secp... */ 131 | #endif /* uECC_SUPPORT_COMPRESSED_POINT */ 132 | 133 | #if uECC_SUPPORTS_secp160r1 134 | 135 | #if (uECC_OPTIMIZATION_LEVEL > 0) 136 | static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product); 137 | #endif 138 | 139 | static const struct uECC_Curve_t curve_secp160r1 = { 140 | num_words_secp160r1, 141 | num_bytes_secp160r1, 142 | 161, /* num_n_bits */ 143 | { BYTES_TO_WORDS_8(FF, FF, FF, 7F, FF, FF, FF, FF), 144 | BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), 145 | BYTES_TO_WORDS_4(FF, FF, FF, FF) }, 146 | { BYTES_TO_WORDS_8(57, 22, 75, CA, D3, AE, 27, F9), 147 | BYTES_TO_WORDS_8(C8, F4, 01, 00, 00, 00, 00, 00), 148 | BYTES_TO_WORDS_8(00, 00, 00, 00, 01, 00, 00, 00) }, 149 | { BYTES_TO_WORDS_8(82, FC, CB, 13, B9, 8B, C3, 68), 150 | BYTES_TO_WORDS_8(89, 69, 64, 46, 28, 73, F5, 8E), 151 | BYTES_TO_WORDS_4(68, B5, 96, 4A), 152 | 153 | BYTES_TO_WORDS_8(32, FB, C5, 7A, 37, 51, 23, 04), 154 | BYTES_TO_WORDS_8(12, C9, DC, 59, 7D, 94, 68, 31), 155 | BYTES_TO_WORDS_4(55, 28, A6, 23) }, 156 | { BYTES_TO_WORDS_8(45, FA, 65, C5, AD, D4, D4, 81), 157 | BYTES_TO_WORDS_8(9F, F8, AC, 65, 8B, 7A, BD, 54), 158 | BYTES_TO_WORDS_4(FC, BE, 97, 1C) }, 159 | &double_jacobian_default, 160 | #if uECC_SUPPORT_COMPRESSED_POINT 161 | &mod_sqrt_default, 162 | #endif 163 | &x_side_default, 164 | #if (uECC_OPTIMIZATION_LEVEL > 0) 165 | &vli_mmod_fast_secp160r1 166 | #endif 167 | }; 168 | 169 | uECC_Curve uECC_secp160r1(void) { return &curve_secp160r1; } 170 | 171 | #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1) 172 | /* Computes result = product % curve_p 173 | see http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf page 354 174 | 175 | Note that this only works if log2(omega) < log2(p) / 2 */ 176 | static void omega_mult_secp160r1(uECC_word_t *result, const uECC_word_t *right); 177 | #if uECC_WORD_SIZE == 8 178 | static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product) { 179 | uECC_word_t tmp[2 * num_words_secp160r1]; 180 | uECC_word_t copy; 181 | 182 | uECC_vli_clear(tmp, num_words_secp160r1); 183 | uECC_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1); 184 | 185 | omega_mult_secp160r1(tmp, product + num_words_secp160r1 - 1); /* (Rq, q) = q * c */ 186 | 187 | product[num_words_secp160r1 - 1] &= 0xffffffff; 188 | copy = tmp[num_words_secp160r1 - 1]; 189 | tmp[num_words_secp160r1 - 1] &= 0xffffffff; 190 | uECC_vli_add(result, product, tmp, num_words_secp160r1); /* (C, r) = r + q */ 191 | uECC_vli_clear(product, num_words_secp160r1); 192 | tmp[num_words_secp160r1 - 1] = copy; 193 | omega_mult_secp160r1(product, tmp + num_words_secp160r1 - 1); /* Rq*c */ 194 | uECC_vli_add(result, result, product, num_words_secp160r1); /* (C1, r) = r + Rq*c */ 195 | 196 | while (uECC_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) > 0) { 197 | uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1); 198 | } 199 | } 200 | 201 | static void omega_mult_secp160r1(uint64_t *result, const uint64_t *right) { 202 | uint32_t carry; 203 | unsigned i; 204 | 205 | /* Multiply by (2^31 + 1). */ 206 | carry = 0; 207 | for (i = 0; i < num_words_secp160r1; ++i) { 208 | uint64_t tmp = (right[i] >> 32) | (right[i + 1] << 32); 209 | result[i] = (tmp << 31) + tmp + carry; 210 | carry = (tmp >> 33) + (result[i] < tmp || (carry && result[i] == tmp)); 211 | } 212 | result[i] = carry; 213 | } 214 | #else 215 | static void vli_mmod_fast_secp160r1(uECC_word_t *result, uECC_word_t *product) { 216 | uECC_word_t tmp[2 * num_words_secp160r1]; 217 | uECC_word_t carry; 218 | 219 | uECC_vli_clear(tmp, num_words_secp160r1); 220 | uECC_vli_clear(tmp + num_words_secp160r1, num_words_secp160r1); 221 | 222 | omega_mult_secp160r1(tmp, product + num_words_secp160r1); /* (Rq, q) = q * c */ 223 | 224 | carry = uECC_vli_add(result, product, tmp, num_words_secp160r1); /* (C, r) = r + q */ 225 | uECC_vli_clear(product, num_words_secp160r1); 226 | omega_mult_secp160r1(product, tmp + num_words_secp160r1); /* Rq*c */ 227 | carry += uECC_vli_add(result, result, product, num_words_secp160r1); /* (C1, r) = r + Rq*c */ 228 | 229 | while (carry > 0) { 230 | --carry; 231 | uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1); 232 | } 233 | if (uECC_vli_cmp_unsafe(result, curve_secp160r1.p, num_words_secp160r1) > 0) { 234 | uECC_vli_sub(result, result, curve_secp160r1.p, num_words_secp160r1); 235 | } 236 | } 237 | #endif 238 | 239 | #if uECC_WORD_SIZE == 1 240 | static void omega_mult_secp160r1(uint8_t *result, const uint8_t *right) { 241 | uint8_t carry; 242 | uint8_t i; 243 | 244 | /* Multiply by (2^31 + 1). */ 245 | uECC_vli_set(result + 4, right, num_words_secp160r1); /* 2^32 */ 246 | uECC_vli_rshift1(result + 4, num_words_secp160r1); /* 2^31 */ 247 | result[3] = right[0] << 7; /* get end bit from shift */ 248 | 249 | carry = uECC_vli_add(result, result, right, num_words_secp160r1); /* 2^31 + 1 */ 250 | for (i = num_words_secp160r1; carry; ++i) { 251 | uint16_t sum = (uint16_t)result[i] + carry; 252 | result[i] = (uint8_t)sum; 253 | carry = sum >> 8; 254 | } 255 | } 256 | #elif uECC_WORD_SIZE == 4 257 | static void omega_mult_secp160r1(uint32_t *result, const uint32_t *right) { 258 | uint32_t carry; 259 | unsigned i; 260 | 261 | /* Multiply by (2^31 + 1). */ 262 | uECC_vli_set(result + 1, right, num_words_secp160r1); /* 2^32 */ 263 | uECC_vli_rshift1(result + 1, num_words_secp160r1); /* 2^31 */ 264 | result[0] = right[0] << 31; /* get end bit from shift */ 265 | 266 | carry = uECC_vli_add(result, result, right, num_words_secp160r1); /* 2^31 + 1 */ 267 | for (i = num_words_secp160r1; carry; ++i) { 268 | uint64_t sum = (uint64_t)result[i] + carry; 269 | result[i] = (uint32_t)sum; 270 | carry = sum >> 32; 271 | } 272 | } 273 | #endif /* uECC_WORD_SIZE */ 274 | #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp160r1) */ 275 | 276 | #endif /* uECC_SUPPORTS_secp160r1 */ 277 | 278 | #if uECC_SUPPORTS_secp192r1 279 | 280 | #if (uECC_OPTIMIZATION_LEVEL > 0) 281 | static void vli_mmod_fast_secp192r1(uECC_word_t *result, uECC_word_t *product); 282 | #endif 283 | 284 | static const struct uECC_Curve_t curve_secp192r1 = { 285 | num_words_secp192r1, 286 | num_bytes_secp192r1, 287 | 192, /* num_n_bits */ 288 | { BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), 289 | BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF), 290 | BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF) }, 291 | { BYTES_TO_WORDS_8(31, 28, D2, B4, B1, C9, 6B, 14), 292 | BYTES_TO_WORDS_8(36, F8, DE, 99, FF, FF, FF, FF), 293 | BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF) }, 294 | { BYTES_TO_WORDS_8(12, 10, FF, 82, FD, 0A, FF, F4), 295 | BYTES_TO_WORDS_8(00, 88, A1, 43, EB, 20, BF, 7C), 296 | BYTES_TO_WORDS_8(F6, 90, 30, B0, 0E, A8, 8D, 18), 297 | 298 | BYTES_TO_WORDS_8(11, 48, 79, 1E, A1, 77, F9, 73), 299 | BYTES_TO_WORDS_8(D5, CD, 24, 6B, ED, 11, 10, 63), 300 | BYTES_TO_WORDS_8(78, DA, C8, FF, 95, 2B, 19, 07) }, 301 | { BYTES_TO_WORDS_8(B1, B9, 46, C1, EC, DE, B8, FE), 302 | BYTES_TO_WORDS_8(49, 30, 24, 72, AB, E9, A7, 0F), 303 | BYTES_TO_WORDS_8(E7, 80, 9C, E5, 19, 05, 21, 64) }, 304 | &double_jacobian_default, 305 | #if uECC_SUPPORT_COMPRESSED_POINT 306 | &mod_sqrt_default, 307 | #endif 308 | &x_side_default, 309 | #if (uECC_OPTIMIZATION_LEVEL > 0) 310 | &vli_mmod_fast_secp192r1 311 | #endif 312 | }; 313 | 314 | uECC_Curve uECC_secp192r1(void) { return &curve_secp192r1; } 315 | 316 | #if (uECC_OPTIMIZATION_LEVEL > 0) 317 | /* Computes result = product % curve_p. 318 | See algorithm 5 and 6 from http://www.isys.uni-klu.ac.at/PDF/2001-0126-MT.pdf */ 319 | #if uECC_WORD_SIZE == 1 320 | static void vli_mmod_fast_secp192r1(uint8_t *result, uint8_t *product) { 321 | uint8_t tmp[num_words_secp192r1]; 322 | uint8_t carry; 323 | 324 | uECC_vli_set(result, product, num_words_secp192r1); 325 | 326 | uECC_vli_set(tmp, &product[24], num_words_secp192r1); 327 | carry = uECC_vli_add(result, result, tmp, num_words_secp192r1); 328 | 329 | tmp[0] = tmp[1] = tmp[2] = tmp[3] = tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0; 330 | tmp[8] = product[24]; tmp[9] = product[25]; tmp[10] = product[26]; tmp[11] = product[27]; 331 | tmp[12] = product[28]; tmp[13] = product[29]; tmp[14] = product[30]; tmp[15] = product[31]; 332 | tmp[16] = product[32]; tmp[17] = product[33]; tmp[18] = product[34]; tmp[19] = product[35]; 333 | tmp[20] = product[36]; tmp[21] = product[37]; tmp[22] = product[38]; tmp[23] = product[39]; 334 | carry += uECC_vli_add(result, result, tmp, num_words_secp192r1); 335 | 336 | tmp[0] = tmp[8] = product[40]; 337 | tmp[1] = tmp[9] = product[41]; 338 | tmp[2] = tmp[10] = product[42]; 339 | tmp[3] = tmp[11] = product[43]; 340 | tmp[4] = tmp[12] = product[44]; 341 | tmp[5] = tmp[13] = product[45]; 342 | tmp[6] = tmp[14] = product[46]; 343 | tmp[7] = tmp[15] = product[47]; 344 | tmp[16] = tmp[17] = tmp[18] = tmp[19] = tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0; 345 | carry += uECC_vli_add(result, result, tmp, num_words_secp192r1); 346 | 347 | while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result, num_words_secp192r1) != 1) { 348 | carry -= uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1); 349 | } 350 | } 351 | #elif uECC_WORD_SIZE == 4 352 | static void vli_mmod_fast_secp192r1(uint32_t *result, uint32_t *product) { 353 | uint32_t tmp[num_words_secp192r1]; 354 | int carry; 355 | 356 | uECC_vli_set(result, product, num_words_secp192r1); 357 | 358 | uECC_vli_set(tmp, &product[6], num_words_secp192r1); 359 | carry = uECC_vli_add(result, result, tmp, num_words_secp192r1); 360 | 361 | tmp[0] = tmp[1] = 0; 362 | tmp[2] = product[6]; 363 | tmp[3] = product[7]; 364 | tmp[4] = product[8]; 365 | tmp[5] = product[9]; 366 | carry += uECC_vli_add(result, result, tmp, num_words_secp192r1); 367 | 368 | tmp[0] = tmp[2] = product[10]; 369 | tmp[1] = tmp[3] = product[11]; 370 | tmp[4] = tmp[5] = 0; 371 | carry += uECC_vli_add(result, result, tmp, num_words_secp192r1); 372 | 373 | while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result, num_words_secp192r1) != 1) { 374 | carry -= uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1); 375 | } 376 | } 377 | #else 378 | static void vli_mmod_fast_secp192r1(uint64_t *result, uint64_t *product) { 379 | uint64_t tmp[num_words_secp192r1]; 380 | int carry; 381 | 382 | uECC_vli_set(result, product, num_words_secp192r1); 383 | 384 | uECC_vli_set(tmp, &product[3], num_words_secp192r1); 385 | carry = (int)uECC_vli_add(result, result, tmp, num_words_secp192r1); 386 | 387 | tmp[0] = 0; 388 | tmp[1] = product[3]; 389 | tmp[2] = product[4]; 390 | carry += uECC_vli_add(result, result, tmp, num_words_secp192r1); 391 | 392 | tmp[0] = tmp[1] = product[5]; 393 | tmp[2] = 0; 394 | carry += uECC_vli_add(result, result, tmp, num_words_secp192r1); 395 | 396 | while (carry || uECC_vli_cmp_unsafe(curve_secp192r1.p, result, num_words_secp192r1) != 1) { 397 | carry -= uECC_vli_sub(result, result, curve_secp192r1.p, num_words_secp192r1); 398 | } 399 | } 400 | #endif /* uECC_WORD_SIZE */ 401 | #endif /* (uECC_OPTIMIZATION_LEVEL > 0) */ 402 | 403 | #endif /* uECC_SUPPORTS_secp192r1 */ 404 | 405 | #if uECC_SUPPORTS_secp224r1 406 | 407 | #if uECC_SUPPORT_COMPRESSED_POINT 408 | static void mod_sqrt_secp224r1(uECC_word_t *a, uECC_Curve curve); 409 | #endif 410 | #if (uECC_OPTIMIZATION_LEVEL > 0) 411 | static void vli_mmod_fast_secp224r1(uECC_word_t *result, uECC_word_t *product); 412 | #endif 413 | 414 | static const struct uECC_Curve_t curve_secp224r1 = { 415 | num_words_secp224r1, 416 | num_bytes_secp224r1, 417 | 224, /* num_n_bits */ 418 | { BYTES_TO_WORDS_8(01, 00, 00, 00, 00, 00, 00, 00), 419 | BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF), 420 | BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), 421 | BYTES_TO_WORDS_4(FF, FF, FF, FF) }, 422 | { BYTES_TO_WORDS_8(3D, 2A, 5C, 5C, 45, 29, DD, 13), 423 | BYTES_TO_WORDS_8(3E, F0, B8, E0, A2, 16, FF, FF), 424 | BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), 425 | BYTES_TO_WORDS_4(FF, FF, FF, FF) }, 426 | { BYTES_TO_WORDS_8(21, 1D, 5C, 11, D6, 80, 32, 34), 427 | BYTES_TO_WORDS_8(22, 11, C2, 56, D3, C1, 03, 4A), 428 | BYTES_TO_WORDS_8(B9, 90, 13, 32, 7F, BF, B4, 6B), 429 | BYTES_TO_WORDS_4(BD, 0C, 0E, B7), 430 | 431 | BYTES_TO_WORDS_8(34, 7E, 00, 85, 99, 81, D5, 44), 432 | BYTES_TO_WORDS_8(64, 47, 07, 5A, A0, 75, 43, CD), 433 | BYTES_TO_WORDS_8(E6, DF, 22, 4C, FB, 23, F7, B5), 434 | BYTES_TO_WORDS_4(88, 63, 37, BD) }, 435 | { BYTES_TO_WORDS_8(B4, FF, 55, 23, 43, 39, 0B, 27), 436 | BYTES_TO_WORDS_8(BA, D8, BF, D7, B7, B0, 44, 50), 437 | BYTES_TO_WORDS_8(56, 32, 41, F5, AB, B3, 04, 0C), 438 | BYTES_TO_WORDS_4(85, 0A, 05, B4) }, 439 | &double_jacobian_default, 440 | #if uECC_SUPPORT_COMPRESSED_POINT 441 | &mod_sqrt_secp224r1, 442 | #endif 443 | &x_side_default, 444 | #if (uECC_OPTIMIZATION_LEVEL > 0) 445 | &vli_mmod_fast_secp224r1 446 | #endif 447 | }; 448 | 449 | uECC_Curve uECC_secp224r1(void) { return &curve_secp224r1; } 450 | 451 | 452 | #if uECC_SUPPORT_COMPRESSED_POINT 453 | /* Routine 3.2.4 RS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */ 454 | static void mod_sqrt_secp224r1_rs(uECC_word_t *d1, 455 | uECC_word_t *e1, 456 | uECC_word_t *f1, 457 | const uECC_word_t *d0, 458 | const uECC_word_t *e0, 459 | const uECC_word_t *f0) { 460 | uECC_word_t t[num_words_secp224r1]; 461 | 462 | uECC_vli_modSquare_fast(t, d0, &curve_secp224r1); /* t <-- d0 ^ 2 */ 463 | uECC_vli_modMult_fast(e1, d0, e0, &curve_secp224r1); /* e1 <-- d0 * e0 */ 464 | uECC_vli_modAdd(d1, t, f0, curve_secp224r1.p, num_words_secp224r1); /* d1 <-- t + f0 */ 465 | uECC_vli_modAdd(e1, e1, e1, curve_secp224r1.p, num_words_secp224r1); /* e1 <-- e1 + e1 */ 466 | uECC_vli_modMult_fast(f1, t, f0, &curve_secp224r1); /* f1 <-- t * f0 */ 467 | uECC_vli_modAdd(f1, f1, f1, curve_secp224r1.p, num_words_secp224r1); /* f1 <-- f1 + f1 */ 468 | uECC_vli_modAdd(f1, f1, f1, curve_secp224r1.p, num_words_secp224r1); /* f1 <-- f1 + f1 */ 469 | } 470 | 471 | /* Routine 3.2.5 RSS; from http://www.nsa.gov/ia/_files/nist-routines.pdf */ 472 | static void mod_sqrt_secp224r1_rss(uECC_word_t *d1, 473 | uECC_word_t *e1, 474 | uECC_word_t *f1, 475 | const uECC_word_t *d0, 476 | const uECC_word_t *e0, 477 | const uECC_word_t *f0, 478 | const bitcount_t j) { 479 | bitcount_t i; 480 | 481 | uECC_vli_set(d1, d0, num_words_secp224r1); /* d1 <-- d0 */ 482 | uECC_vli_set(e1, e0, num_words_secp224r1); /* e1 <-- e0 */ 483 | uECC_vli_set(f1, f0, num_words_secp224r1); /* f1 <-- f0 */ 484 | for (i = 1; i <= j; i++) { 485 | mod_sqrt_secp224r1_rs(d1, e1, f1, d1, e1, f1); /* RS (d1,e1,f1,d1,e1,f1) */ 486 | } 487 | } 488 | 489 | /* Routine 3.2.6 RM; from http://www.nsa.gov/ia/_files/nist-routines.pdf */ 490 | static void mod_sqrt_secp224r1_rm(uECC_word_t *d2, 491 | uECC_word_t *e2, 492 | uECC_word_t *f2, 493 | const uECC_word_t *c, 494 | const uECC_word_t *d0, 495 | const uECC_word_t *e0, 496 | const uECC_word_t *d1, 497 | const uECC_word_t *e1) { 498 | uECC_word_t t1[num_words_secp224r1]; 499 | uECC_word_t t2[num_words_secp224r1]; 500 | 501 | uECC_vli_modMult_fast(t1, e0, e1, &curve_secp224r1); /* t1 <-- e0 * e1 */ 502 | uECC_vli_modMult_fast(t1, t1, c, &curve_secp224r1); /* t1 <-- t1 * c */ 503 | /* t1 <-- p - t1 */ 504 | uECC_vli_modSub(t1, curve_secp224r1.p, t1, curve_secp224r1.p, num_words_secp224r1); 505 | uECC_vli_modMult_fast(t2, d0, d1, &curve_secp224r1); /* t2 <-- d0 * d1 */ 506 | uECC_vli_modAdd(t2, t2, t1, curve_secp224r1.p, num_words_secp224r1); /* t2 <-- t2 + t1 */ 507 | uECC_vli_modMult_fast(t1, d0, e1, &curve_secp224r1); /* t1 <-- d0 * e1 */ 508 | uECC_vli_modMult_fast(e2, d1, e0, &curve_secp224r1); /* e2 <-- d1 * e0 */ 509 | uECC_vli_modAdd(e2, e2, t1, curve_secp224r1.p, num_words_secp224r1); /* e2 <-- e2 + t1 */ 510 | uECC_vli_modSquare_fast(f2, e2, &curve_secp224r1); /* f2 <-- e2^2 */ 511 | uECC_vli_modMult_fast(f2, f2, c, &curve_secp224r1); /* f2 <-- f2 * c */ 512 | /* f2 <-- p - f2 */ 513 | uECC_vli_modSub(f2, curve_secp224r1.p, f2, curve_secp224r1.p, num_words_secp224r1); 514 | uECC_vli_set(d2, t2, num_words_secp224r1); /* d2 <-- t2 */ 515 | } 516 | 517 | /* Routine 3.2.7 RP; from http://www.nsa.gov/ia/_files/nist-routines.pdf */ 518 | static void mod_sqrt_secp224r1_rp(uECC_word_t *d1, 519 | uECC_word_t *e1, 520 | uECC_word_t *f1, 521 | const uECC_word_t *c, 522 | const uECC_word_t *r) { 523 | wordcount_t i; 524 | wordcount_t pow2i = 1; 525 | uECC_word_t d0[num_words_secp224r1]; 526 | uECC_word_t e0[num_words_secp224r1] = {1}; /* e0 <-- 1 */ 527 | uECC_word_t f0[num_words_secp224r1]; 528 | 529 | uECC_vli_set(d0, r, num_words_secp224r1); /* d0 <-- r */ 530 | /* f0 <-- p - c */ 531 | uECC_vli_modSub(f0, curve_secp224r1.p, c, curve_secp224r1.p, num_words_secp224r1); 532 | for (i = 0; i <= 6; i++) { 533 | mod_sqrt_secp224r1_rss(d1, e1, f1, d0, e0, f0, pow2i); /* RSS (d1,e1,f1,d0,e0,f0,2^i) */ 534 | mod_sqrt_secp224r1_rm(d1, e1, f1, c, d1, e1, d0, e0); /* RM (d1,e1,f1,c,d1,e1,d0,e0) */ 535 | uECC_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */ 536 | uECC_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */ 537 | uECC_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */ 538 | pow2i *= 2; 539 | } 540 | } 541 | 542 | /* Compute a = sqrt(a) (mod curve_p). */ 543 | /* Routine 3.2.8 mp_mod_sqrt_224; from http://www.nsa.gov/ia/_files/nist-routines.pdf */ 544 | static void mod_sqrt_secp224r1(uECC_word_t *a, uECC_Curve curve) { 545 | bitcount_t i; 546 | uECC_word_t e1[num_words_secp224r1]; 547 | uECC_word_t f1[num_words_secp224r1]; 548 | uECC_word_t d0[num_words_secp224r1]; 549 | uECC_word_t e0[num_words_secp224r1]; 550 | uECC_word_t f0[num_words_secp224r1]; 551 | uECC_word_t d1[num_words_secp224r1]; 552 | 553 | /* s = a; using constant instead of random value */ 554 | mod_sqrt_secp224r1_rp(d0, e0, f0, a, a); /* RP (d0, e0, f0, c, s) */ 555 | mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0, f0); /* RS (d1, e1, f1, d0, e0, f0) */ 556 | for (i = 1; i <= 95; i++) { 557 | uECC_vli_set(d0, d1, num_words_secp224r1); /* d0 <-- d1 */ 558 | uECC_vli_set(e0, e1, num_words_secp224r1); /* e0 <-- e1 */ 559 | uECC_vli_set(f0, f1, num_words_secp224r1); /* f0 <-- f1 */ 560 | mod_sqrt_secp224r1_rs(d1, e1, f1, d0, e0, f0); /* RS (d1, e1, f1, d0, e0, f0) */ 561 | if (uECC_vli_isZero(d1, num_words_secp224r1)) { /* if d1 == 0 */ 562 | break; 563 | } 564 | } 565 | uECC_vli_modInv(f1, e0, curve_secp224r1.p, num_words_secp224r1); /* f1 <-- 1 / e0 */ 566 | uECC_vli_modMult_fast(a, d0, f1, &curve_secp224r1); /* a <-- d0 / e0 */ 567 | } 568 | #endif /* uECC_SUPPORT_COMPRESSED_POINT */ 569 | 570 | #if (uECC_OPTIMIZATION_LEVEL > 0) 571 | /* Computes result = product % curve_p 572 | from http://www.nsa.gov/ia/_files/nist-routines.pdf */ 573 | #if uECC_WORD_SIZE == 1 574 | static void vli_mmod_fast_secp224r1(uint8_t *result, uint8_t *product) { 575 | uint8_t tmp[num_words_secp224r1]; 576 | int8_t carry; 577 | 578 | /* t */ 579 | uECC_vli_set(result, product, num_words_secp224r1); 580 | 581 | /* s1 */ 582 | tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0; 583 | tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0; 584 | tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0; 585 | tmp[12] = product[28]; tmp[13] = product[29]; tmp[14] = product[30]; tmp[15] = product[31]; 586 | tmp[16] = product[32]; tmp[17] = product[33]; tmp[18] = product[34]; tmp[19] = product[35]; 587 | tmp[20] = product[36]; tmp[21] = product[37]; tmp[22] = product[38]; tmp[23] = product[39]; 588 | tmp[24] = product[40]; tmp[25] = product[41]; tmp[26] = product[42]; tmp[27] = product[43]; 589 | carry = uECC_vli_add(result, result, tmp, num_words_secp224r1); 590 | 591 | /* s2 */ 592 | tmp[12] = product[44]; tmp[13] = product[45]; tmp[14] = product[46]; tmp[15] = product[47]; 593 | tmp[16] = product[48]; tmp[17] = product[49]; tmp[18] = product[50]; tmp[19] = product[51]; 594 | tmp[20] = product[52]; tmp[21] = product[53]; tmp[22] = product[54]; tmp[23] = product[55]; 595 | tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0; 596 | carry += uECC_vli_add(result, result, tmp, num_words_secp224r1); 597 | 598 | /* d1 */ 599 | tmp[0] = product[28]; tmp[1] = product[29]; tmp[2] = product[30]; tmp[3] = product[31]; 600 | tmp[4] = product[32]; tmp[5] = product[33]; tmp[6] = product[34]; tmp[7] = product[35]; 601 | tmp[8] = product[36]; tmp[9] = product[37]; tmp[10] = product[38]; tmp[11] = product[39]; 602 | tmp[12] = product[40]; tmp[13] = product[41]; tmp[14] = product[42]; tmp[15] = product[43]; 603 | tmp[16] = product[44]; tmp[17] = product[45]; tmp[18] = product[46]; tmp[19] = product[47]; 604 | tmp[20] = product[48]; tmp[21] = product[49]; tmp[22] = product[50]; tmp[23] = product[51]; 605 | tmp[24] = product[52]; tmp[25] = product[53]; tmp[26] = product[54]; tmp[27] = product[55]; 606 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1); 607 | 608 | /* d2 */ 609 | tmp[0] = product[44]; tmp[1] = product[45]; tmp[2] = product[46]; tmp[3] = product[47]; 610 | tmp[4] = product[48]; tmp[5] = product[49]; tmp[6] = product[50]; tmp[7] = product[51]; 611 | tmp[8] = product[52]; tmp[9] = product[53]; tmp[10] = product[54]; tmp[11] = product[55]; 612 | tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0; 613 | tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0; 614 | tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0; 615 | tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0; 616 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1); 617 | 618 | if (carry < 0) { 619 | do { 620 | carry += uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1); 621 | } while (carry < 0); 622 | } else { 623 | while (carry || uECC_vli_cmp_unsafe(curve_secp224r1.p, result, num_words_secp224r1) != 1) { 624 | carry -= uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1); 625 | } 626 | } 627 | } 628 | #elif uECC_WORD_SIZE == 4 629 | static void vli_mmod_fast_secp224r1(uint32_t *result, uint32_t *product) 630 | { 631 | uint32_t tmp[num_words_secp224r1]; 632 | int carry; 633 | 634 | /* t */ 635 | uECC_vli_set(result, product, num_words_secp224r1); 636 | 637 | /* s1 */ 638 | tmp[0] = tmp[1] = tmp[2] = 0; 639 | tmp[3] = product[7]; 640 | tmp[4] = product[8]; 641 | tmp[5] = product[9]; 642 | tmp[6] = product[10]; 643 | carry = uECC_vli_add(result, result, tmp, num_words_secp224r1); 644 | 645 | /* s2 */ 646 | tmp[3] = product[11]; 647 | tmp[4] = product[12]; 648 | tmp[5] = product[13]; 649 | tmp[6] = 0; 650 | carry += uECC_vli_add(result, result, tmp, num_words_secp224r1); 651 | 652 | /* d1 */ 653 | tmp[0] = product[7]; 654 | tmp[1] = product[8]; 655 | tmp[2] = product[9]; 656 | tmp[3] = product[10]; 657 | tmp[4] = product[11]; 658 | tmp[5] = product[12]; 659 | tmp[6] = product[13]; 660 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1); 661 | 662 | /* d2 */ 663 | tmp[0] = product[11]; 664 | tmp[1] = product[12]; 665 | tmp[2] = product[13]; 666 | tmp[3] = tmp[4] = tmp[5] = tmp[6] = 0; 667 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1); 668 | 669 | if (carry < 0) { 670 | do { 671 | carry += uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1); 672 | } while (carry < 0); 673 | } else { 674 | while (carry || uECC_vli_cmp_unsafe(curve_secp224r1.p, result, num_words_secp224r1) != 1) { 675 | carry -= uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1); 676 | } 677 | } 678 | } 679 | #else 680 | static void vli_mmod_fast_secp224r1(uint64_t *result, uint64_t *product) 681 | { 682 | uint64_t tmp[num_words_secp224r1]; 683 | int carry = 0; 684 | 685 | /* t */ 686 | uECC_vli_set(result, product, num_words_secp224r1); 687 | result[num_words_secp224r1 - 1] &= 0xffffffff; 688 | 689 | /* s1 */ 690 | tmp[0] = 0; 691 | tmp[1] = product[3] & 0xffffffff00000000ull; 692 | tmp[2] = product[4]; 693 | tmp[3] = product[5] & 0xffffffff; 694 | uECC_vli_add(result, result, tmp, num_words_secp224r1); 695 | 696 | /* s2 */ 697 | tmp[1] = product[5] & 0xffffffff00000000ull; 698 | tmp[2] = product[6]; 699 | tmp[3] = 0; 700 | uECC_vli_add(result, result, tmp, num_words_secp224r1); 701 | 702 | /* d1 */ 703 | tmp[0] = (product[3] >> 32) | (product[4] << 32); 704 | tmp[1] = (product[4] >> 32) | (product[5] << 32); 705 | tmp[2] = (product[5] >> 32) | (product[6] << 32); 706 | tmp[3] = product[6] >> 32; 707 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1); 708 | 709 | /* d2 */ 710 | tmp[0] = (product[5] >> 32) | (product[6] << 32); 711 | tmp[1] = product[6] >> 32; 712 | tmp[2] = tmp[3] = 0; 713 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp224r1); 714 | 715 | if (carry < 0) { 716 | do { 717 | carry += uECC_vli_add(result, result, curve_secp224r1.p, num_words_secp224r1); 718 | } while (carry < 0); 719 | } else { 720 | while (uECC_vli_cmp_unsafe(curve_secp224r1.p, result, num_words_secp224r1) != 1) { 721 | uECC_vli_sub(result, result, curve_secp224r1.p, num_words_secp224r1); 722 | } 723 | } 724 | } 725 | #endif /* uECC_WORD_SIZE */ 726 | #endif /* (uECC_OPTIMIZATION_LEVEL > 0) */ 727 | 728 | #endif /* uECC_SUPPORTS_secp224r1 */ 729 | 730 | #if uECC_SUPPORTS_secp256r1 731 | 732 | #if (uECC_OPTIMIZATION_LEVEL > 0) 733 | static void vli_mmod_fast_secp256r1(uECC_word_t *result, uECC_word_t *product); 734 | #endif 735 | 736 | static const struct uECC_Curve_t curve_secp256r1 = { 737 | num_words_secp256r1, 738 | num_bytes_secp256r1, 739 | 256, /* num_n_bits */ 740 | { BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), 741 | BYTES_TO_WORDS_8(FF, FF, FF, FF, 00, 00, 00, 00), 742 | BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00), 743 | BYTES_TO_WORDS_8(01, 00, 00, 00, FF, FF, FF, FF) }, 744 | { BYTES_TO_WORDS_8(51, 25, 63, FC, C2, CA, B9, F3), 745 | BYTES_TO_WORDS_8(84, 9E, 17, A7, AD, FA, E6, BC), 746 | BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), 747 | BYTES_TO_WORDS_8(00, 00, 00, 00, FF, FF, FF, FF) }, 748 | { BYTES_TO_WORDS_8(96, C2, 98, D8, 45, 39, A1, F4), 749 | BYTES_TO_WORDS_8(A0, 33, EB, 2D, 81, 7D, 03, 77), 750 | BYTES_TO_WORDS_8(F2, 40, A4, 63, E5, E6, BC, F8), 751 | BYTES_TO_WORDS_8(47, 42, 2C, E1, F2, D1, 17, 6B), 752 | 753 | BYTES_TO_WORDS_8(F5, 51, BF, 37, 68, 40, B6, CB), 754 | BYTES_TO_WORDS_8(CE, 5E, 31, 6B, 57, 33, CE, 2B), 755 | BYTES_TO_WORDS_8(16, 9E, 0F, 7C, 4A, EB, E7, 8E), 756 | BYTES_TO_WORDS_8(9B, 7F, 1A, FE, E2, 42, E3, 4F) }, 757 | { BYTES_TO_WORDS_8(4B, 60, D2, 27, 3E, 3C, CE, 3B), 758 | BYTES_TO_WORDS_8(F6, B0, 53, CC, B0, 06, 1D, 65), 759 | BYTES_TO_WORDS_8(BC, 86, 98, 76, 55, BD, EB, B3), 760 | BYTES_TO_WORDS_8(E7, 93, 3A, AA, D8, 35, C6, 5A) }, 761 | &double_jacobian_default, 762 | #if uECC_SUPPORT_COMPRESSED_POINT 763 | &mod_sqrt_default, 764 | #endif 765 | &x_side_default, 766 | #if (uECC_OPTIMIZATION_LEVEL > 0) 767 | &vli_mmod_fast_secp256r1 768 | #endif 769 | }; 770 | 771 | uECC_Curve uECC_secp256r1(void) { return &curve_secp256r1; } 772 | 773 | 774 | #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1) 775 | /* Computes result = product % curve_p 776 | from http://www.nsa.gov/ia/_files/nist-routines.pdf */ 777 | #if uECC_WORD_SIZE == 1 778 | static void vli_mmod_fast_secp256r1(uint8_t *result, uint8_t *product) { 779 | uint8_t tmp[num_words_secp256r1]; 780 | int8_t carry; 781 | 782 | /* t */ 783 | uECC_vli_set(result, product, num_words_secp256r1); 784 | 785 | /* s1 */ 786 | tmp[0] = tmp[1] = tmp[2] = tmp[3] = 0; 787 | tmp[4] = tmp[5] = tmp[6] = tmp[7] = 0; 788 | tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0; 789 | tmp[12] = product[44]; tmp[13] = product[45]; tmp[14] = product[46]; tmp[15] = product[47]; 790 | tmp[16] = product[48]; tmp[17] = product[49]; tmp[18] = product[50]; tmp[19] = product[51]; 791 | tmp[20] = product[52]; tmp[21] = product[53]; tmp[22] = product[54]; tmp[23] = product[55]; 792 | tmp[24] = product[56]; tmp[25] = product[57]; tmp[26] = product[58]; tmp[27] = product[59]; 793 | tmp[28] = product[60]; tmp[29] = product[61]; tmp[30] = product[62]; tmp[31] = product[63]; 794 | carry = uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1); 795 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 796 | 797 | /* s2 */ 798 | tmp[12] = product[48]; tmp[13] = product[49]; tmp[14] = product[50]; tmp[15] = product[51]; 799 | tmp[16] = product[52]; tmp[17] = product[53]; tmp[18] = product[54]; tmp[19] = product[55]; 800 | tmp[20] = product[56]; tmp[21] = product[57]; tmp[22] = product[58]; tmp[23] = product[59]; 801 | tmp[24] = product[60]; tmp[25] = product[61]; tmp[26] = product[62]; tmp[27] = product[63]; 802 | tmp[28] = tmp[29] = tmp[30] = tmp[31] = 0; 803 | carry += uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1); 804 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 805 | 806 | /* s3 */ 807 | tmp[0] = product[32]; tmp[1] = product[33]; tmp[2] = product[34]; tmp[3] = product[35]; 808 | tmp[4] = product[36]; tmp[5] = product[37]; tmp[6] = product[38]; tmp[7] = product[39]; 809 | tmp[8] = product[40]; tmp[9] = product[41]; tmp[10] = product[42]; tmp[11] = product[43]; 810 | tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0; 811 | tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0; 812 | tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0; 813 | tmp[24] = product[56]; tmp[25] = product[57]; tmp[26] = product[58]; tmp[27] = product[59]; 814 | tmp[28] = product[60]; tmp[29] = product[61]; tmp[30] = product[62]; tmp[31] = product[63]; 815 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 816 | 817 | /* s4 */ 818 | tmp[0] = product[36]; tmp[1] = product[37]; tmp[2] = product[38]; tmp[3] = product[39]; 819 | tmp[4] = product[40]; tmp[5] = product[41]; tmp[6] = product[42]; tmp[7] = product[43]; 820 | tmp[8] = product[44]; tmp[9] = product[45]; tmp[10] = product[46]; tmp[11] = product[47]; 821 | tmp[12] = product[52]; tmp[13] = product[53]; tmp[14] = product[54]; tmp[15] = product[55]; 822 | tmp[16] = product[56]; tmp[17] = product[57]; tmp[18] = product[58]; tmp[19] = product[59]; 823 | tmp[20] = product[60]; tmp[21] = product[61]; tmp[22] = product[62]; tmp[23] = product[63]; 824 | tmp[24] = product[52]; tmp[25] = product[53]; tmp[26] = product[54]; tmp[27] = product[55]; 825 | tmp[28] = product[32]; tmp[29] = product[33]; tmp[30] = product[34]; tmp[31] = product[35]; 826 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 827 | 828 | /* d1 */ 829 | tmp[0] = product[44]; tmp[1] = product[45]; tmp[2] = product[46]; tmp[3] = product[47]; 830 | tmp[4] = product[48]; tmp[5] = product[49]; tmp[6] = product[50]; tmp[7] = product[51]; 831 | tmp[8] = product[52]; tmp[9] = product[53]; tmp[10] = product[54]; tmp[11] = product[55]; 832 | tmp[12] = tmp[13] = tmp[14] = tmp[15] = 0; 833 | tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0; 834 | tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0; 835 | tmp[24] = product[32]; tmp[25] = product[33]; tmp[26] = product[34]; tmp[27] = product[35]; 836 | tmp[28] = product[40]; tmp[29] = product[41]; tmp[30] = product[42]; tmp[31] = product[43]; 837 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 838 | 839 | /* d2 */ 840 | tmp[0] = product[48]; tmp[1] = product[49]; tmp[2] = product[50]; tmp[3] = product[51]; 841 | tmp[4] = product[52]; tmp[5] = product[53]; tmp[6] = product[54]; tmp[7] = product[55]; 842 | tmp[8] = product[56]; tmp[9] = product[57]; tmp[10] = product[58]; tmp[11] = product[59]; 843 | tmp[12] = product[60]; tmp[13] = product[61]; tmp[14] = product[62]; tmp[15] = product[63]; 844 | tmp[16] = tmp[17] = tmp[18] = tmp[19] = 0; 845 | tmp[20] = tmp[21] = tmp[22] = tmp[23] = 0; 846 | tmp[24] = product[36]; tmp[25] = product[37]; tmp[26] = product[38]; tmp[27] = product[39]; 847 | tmp[28] = product[44]; tmp[29] = product[45]; tmp[30] = product[46]; tmp[31] = product[47]; 848 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 849 | 850 | /* d3 */ 851 | tmp[0] = product[52]; tmp[1] = product[53]; tmp[2] = product[54]; tmp[3] = product[55]; 852 | tmp[4] = product[56]; tmp[5] = product[57]; tmp[6] = product[58]; tmp[7] = product[59]; 853 | tmp[8] = product[60]; tmp[9] = product[61]; tmp[10] = product[62]; tmp[11] = product[63]; 854 | tmp[12] = product[32]; tmp[13] = product[33]; tmp[14] = product[34]; tmp[15] = product[35]; 855 | tmp[16] = product[36]; tmp[17] = product[37]; tmp[18] = product[38]; tmp[19] = product[39]; 856 | tmp[20] = product[40]; tmp[21] = product[41]; tmp[22] = product[42]; tmp[23] = product[43]; 857 | tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0; 858 | tmp[28] = product[48]; tmp[29] = product[49]; tmp[30] = product[50]; tmp[31] = product[51]; 859 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 860 | 861 | /* d4 */ 862 | tmp[0] = product[56]; tmp[1] = product[57]; tmp[2] = product[58]; tmp[3] = product[59]; 863 | tmp[4] = product[60]; tmp[5] = product[61]; tmp[6] = product[62]; tmp[7] = product[63]; 864 | tmp[8] = tmp[9] = tmp[10] = tmp[11] = 0; 865 | tmp[12] = product[36]; tmp[13] = product[37]; tmp[14] = product[38]; tmp[15] = product[39]; 866 | tmp[16] = product[40]; tmp[17] = product[41]; tmp[18] = product[42]; tmp[19] = product[43]; 867 | tmp[20] = product[44]; tmp[21] = product[45]; tmp[22] = product[46]; tmp[23] = product[47]; 868 | tmp[24] = tmp[25] = tmp[26] = tmp[27] = 0; 869 | tmp[28] = product[52]; tmp[29] = product[53]; tmp[30] = product[54]; tmp[31] = product[55]; 870 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 871 | 872 | if (carry < 0) { 873 | do { 874 | carry += uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1); 875 | } while (carry < 0); 876 | } else { 877 | while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result, num_words_secp256r1) != 1) { 878 | carry -= uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1); 879 | } 880 | } 881 | } 882 | #elif uECC_WORD_SIZE == 4 883 | static void vli_mmod_fast_secp256r1(uint32_t *result, uint32_t *product) { 884 | uint32_t tmp[num_words_secp256r1]; 885 | int carry; 886 | 887 | /* t */ 888 | uECC_vli_set(result, product, num_words_secp256r1); 889 | 890 | /* s1 */ 891 | tmp[0] = tmp[1] = tmp[2] = 0; 892 | tmp[3] = product[11]; 893 | tmp[4] = product[12]; 894 | tmp[5] = product[13]; 895 | tmp[6] = product[14]; 896 | tmp[7] = product[15]; 897 | carry = uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1); 898 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 899 | 900 | /* s2 */ 901 | tmp[3] = product[12]; 902 | tmp[4] = product[13]; 903 | tmp[5] = product[14]; 904 | tmp[6] = product[15]; 905 | tmp[7] = 0; 906 | carry += uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1); 907 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 908 | 909 | /* s3 */ 910 | tmp[0] = product[8]; 911 | tmp[1] = product[9]; 912 | tmp[2] = product[10]; 913 | tmp[3] = tmp[4] = tmp[5] = 0; 914 | tmp[6] = product[14]; 915 | tmp[7] = product[15]; 916 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 917 | 918 | /* s4 */ 919 | tmp[0] = product[9]; 920 | tmp[1] = product[10]; 921 | tmp[2] = product[11]; 922 | tmp[3] = product[13]; 923 | tmp[4] = product[14]; 924 | tmp[5] = product[15]; 925 | tmp[6] = product[13]; 926 | tmp[7] = product[8]; 927 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 928 | 929 | /* d1 */ 930 | tmp[0] = product[11]; 931 | tmp[1] = product[12]; 932 | tmp[2] = product[13]; 933 | tmp[3] = tmp[4] = tmp[5] = 0; 934 | tmp[6] = product[8]; 935 | tmp[7] = product[10]; 936 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 937 | 938 | /* d2 */ 939 | tmp[0] = product[12]; 940 | tmp[1] = product[13]; 941 | tmp[2] = product[14]; 942 | tmp[3] = product[15]; 943 | tmp[4] = tmp[5] = 0; 944 | tmp[6] = product[9]; 945 | tmp[7] = product[11]; 946 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 947 | 948 | /* d3 */ 949 | tmp[0] = product[13]; 950 | tmp[1] = product[14]; 951 | tmp[2] = product[15]; 952 | tmp[3] = product[8]; 953 | tmp[4] = product[9]; 954 | tmp[5] = product[10]; 955 | tmp[6] = 0; 956 | tmp[7] = product[12]; 957 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 958 | 959 | /* d4 */ 960 | tmp[0] = product[14]; 961 | tmp[1] = product[15]; 962 | tmp[2] = 0; 963 | tmp[3] = product[9]; 964 | tmp[4] = product[10]; 965 | tmp[5] = product[11]; 966 | tmp[6] = 0; 967 | tmp[7] = product[13]; 968 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 969 | 970 | if (carry < 0) { 971 | do { 972 | carry += uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1); 973 | } while (carry < 0); 974 | } else { 975 | while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result, num_words_secp256r1) != 1) { 976 | carry -= uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1); 977 | } 978 | } 979 | } 980 | #else 981 | static void vli_mmod_fast_secp256r1(uint64_t *result, uint64_t *product) { 982 | uint64_t tmp[num_words_secp256r1]; 983 | int carry; 984 | 985 | /* t */ 986 | uECC_vli_set(result, product, num_words_secp256r1); 987 | 988 | /* s1 */ 989 | tmp[0] = 0; 990 | tmp[1] = product[5] & 0xffffffff00000000ull; 991 | tmp[2] = product[6]; 992 | tmp[3] = product[7]; 993 | carry = (int)uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1); 994 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 995 | 996 | /* s2 */ 997 | tmp[1] = product[6] << 32; 998 | tmp[2] = (product[6] >> 32) | (product[7] << 32); 999 | tmp[3] = product[7] >> 32; 1000 | carry += uECC_vli_add(tmp, tmp, tmp, num_words_secp256r1); 1001 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 1002 | 1003 | /* s3 */ 1004 | tmp[0] = product[4]; 1005 | tmp[1] = product[5] & 0xffffffff; 1006 | tmp[2] = 0; 1007 | tmp[3] = product[7]; 1008 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 1009 | 1010 | /* s4 */ 1011 | tmp[0] = (product[4] >> 32) | (product[5] << 32); 1012 | tmp[1] = (product[5] >> 32) | (product[6] & 0xffffffff00000000ull); 1013 | tmp[2] = product[7]; 1014 | tmp[3] = (product[6] >> 32) | (product[4] << 32); 1015 | carry += uECC_vli_add(result, result, tmp, num_words_secp256r1); 1016 | 1017 | /* d1 */ 1018 | tmp[0] = (product[5] >> 32) | (product[6] << 32); 1019 | tmp[1] = (product[6] >> 32); 1020 | tmp[2] = 0; 1021 | tmp[3] = (product[4] & 0xffffffff) | (product[5] << 32); 1022 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 1023 | 1024 | /* d2 */ 1025 | tmp[0] = product[6]; 1026 | tmp[1] = product[7]; 1027 | tmp[2] = 0; 1028 | tmp[3] = (product[4] >> 32) | (product[5] & 0xffffffff00000000ull); 1029 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 1030 | 1031 | /* d3 */ 1032 | tmp[0] = (product[6] >> 32) | (product[7] << 32); 1033 | tmp[1] = (product[7] >> 32) | (product[4] << 32); 1034 | tmp[2] = (product[4] >> 32) | (product[5] << 32); 1035 | tmp[3] = (product[6] << 32); 1036 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 1037 | 1038 | /* d4 */ 1039 | tmp[0] = product[7]; 1040 | tmp[1] = product[4] & 0xffffffff00000000ull; 1041 | tmp[2] = product[5]; 1042 | tmp[3] = product[6] & 0xffffffff00000000ull; 1043 | carry -= uECC_vli_sub(result, result, tmp, num_words_secp256r1); 1044 | 1045 | if (carry < 0) { 1046 | do { 1047 | carry += uECC_vli_add(result, result, curve_secp256r1.p, num_words_secp256r1); 1048 | } while (carry < 0); 1049 | } else { 1050 | while (carry || uECC_vli_cmp_unsafe(curve_secp256r1.p, result, num_words_secp256r1) != 1) { 1051 | carry -= uECC_vli_sub(result, result, curve_secp256r1.p, num_words_secp256r1); 1052 | } 1053 | } 1054 | } 1055 | #endif /* uECC_WORD_SIZE */ 1056 | #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256r1) */ 1057 | 1058 | #endif /* uECC_SUPPORTS_secp256r1 */ 1059 | 1060 | #if uECC_SUPPORTS_secp256k1 1061 | 1062 | static void double_jacobian_secp256k1(uECC_word_t * X1, 1063 | uECC_word_t * Y1, 1064 | uECC_word_t * Z1, 1065 | uECC_Curve curve); 1066 | static void x_side_secp256k1(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve); 1067 | #if (uECC_OPTIMIZATION_LEVEL > 0) 1068 | static void vli_mmod_fast_secp256k1(uECC_word_t *result, uECC_word_t *product); 1069 | #endif 1070 | 1071 | static const struct uECC_Curve_t curve_secp256k1 = { 1072 | num_words_secp256k1, 1073 | num_bytes_secp256k1, 1074 | 256, /* num_n_bits */ 1075 | { BYTES_TO_WORDS_8(2F, FC, FF, FF, FE, FF, FF, FF), 1076 | BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), 1077 | BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF), 1078 | BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF) }, 1079 | { BYTES_TO_WORDS_8(41, 41, 36, D0, 8C, 5E, D2, BF), 1080 | BYTES_TO_WORDS_8(3B, A0, 48, AF, E6, DC, AE, BA), 1081 | BYTES_TO_WORDS_8(FE, FF, FF, FF, FF, FF, FF, FF), 1082 | BYTES_TO_WORDS_8(FF, FF, FF, FF, FF, FF, FF, FF) }, 1083 | { BYTES_TO_WORDS_8(98, 17, F8, 16, 5B, 81, F2, 59), 1084 | BYTES_TO_WORDS_8(D9, 28, CE, 2D, DB, FC, 9B, 02), 1085 | BYTES_TO_WORDS_8(07, 0B, 87, CE, 95, 62, A0, 55), 1086 | BYTES_TO_WORDS_8(AC, BB, DC, F9, 7E, 66, BE, 79), 1087 | 1088 | BYTES_TO_WORDS_8(B8, D4, 10, FB, 8F, D0, 47, 9C), 1089 | BYTES_TO_WORDS_8(19, 54, 85, A6, 48, B4, 17, FD), 1090 | BYTES_TO_WORDS_8(A8, 08, 11, 0E, FC, FB, A4, 5D), 1091 | BYTES_TO_WORDS_8(65, C4, A3, 26, 77, DA, 3A, 48) }, 1092 | { BYTES_TO_WORDS_8(07, 00, 00, 00, 00, 00, 00, 00), 1093 | BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00), 1094 | BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00), 1095 | BYTES_TO_WORDS_8(00, 00, 00, 00, 00, 00, 00, 00) }, 1096 | &double_jacobian_secp256k1, 1097 | #if uECC_SUPPORT_COMPRESSED_POINT 1098 | &mod_sqrt_default, 1099 | #endif 1100 | &x_side_secp256k1, 1101 | #if (uECC_OPTIMIZATION_LEVEL > 0) 1102 | &vli_mmod_fast_secp256k1 1103 | #endif 1104 | }; 1105 | 1106 | uECC_Curve uECC_secp256k1(void) { return &curve_secp256k1; } 1107 | 1108 | 1109 | /* Double in place */ 1110 | static void double_jacobian_secp256k1(uECC_word_t * X1, 1111 | uECC_word_t * Y1, 1112 | uECC_word_t * Z1, 1113 | uECC_Curve curve) { 1114 | /* t1 = X, t2 = Y, t3 = Z */ 1115 | uECC_word_t t4[num_words_secp256k1]; 1116 | uECC_word_t t5[num_words_secp256k1]; 1117 | 1118 | if (uECC_vli_isZero(Z1, num_words_secp256k1)) { 1119 | return; 1120 | } 1121 | 1122 | uECC_vli_modSquare_fast(t5, Y1, curve); /* t5 = y1^2 */ 1123 | uECC_vli_modMult_fast(t4, X1, t5, curve); /* t4 = x1*y1^2 = A */ 1124 | uECC_vli_modSquare_fast(X1, X1, curve); /* t1 = x1^2 */ 1125 | uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = y1^4 */ 1126 | uECC_vli_modMult_fast(Z1, Y1, Z1, curve); /* t3 = y1*z1 = z3 */ 1127 | 1128 | uECC_vli_modAdd(Y1, X1, X1, curve->p, num_words_secp256k1); /* t2 = 2*x1^2 */ 1129 | uECC_vli_modAdd(Y1, Y1, X1, curve->p, num_words_secp256k1); /* t2 = 3*x1^2 */ 1130 | if (uECC_vli_testBit(Y1, 0)) { 1131 | uECC_word_t carry = uECC_vli_add(Y1, Y1, curve->p, num_words_secp256k1); 1132 | uECC_vli_rshift1(Y1, num_words_secp256k1); 1133 | Y1[num_words_secp256k1 - 1] |= carry << (uECC_WORD_BITS - 1); 1134 | } else { 1135 | uECC_vli_rshift1(Y1, num_words_secp256k1); 1136 | } 1137 | /* t2 = 3/2*(x1^2) = B */ 1138 | 1139 | uECC_vli_modSquare_fast(X1, Y1, curve); /* t1 = B^2 */ 1140 | uECC_vli_modSub(X1, X1, t4, curve->p, num_words_secp256k1); /* t1 = B^2 - A */ 1141 | uECC_vli_modSub(X1, X1, t4, curve->p, num_words_secp256k1); /* t1 = B^2 - 2A = x3 */ 1142 | 1143 | uECC_vli_modSub(t4, t4, X1, curve->p, num_words_secp256k1); /* t4 = A - x3 */ 1144 | uECC_vli_modMult_fast(Y1, Y1, t4, curve); /* t2 = B * (A - x3) */ 1145 | uECC_vli_modSub(Y1, Y1, t5, curve->p, num_words_secp256k1); /* t2 = B * (A - x3) - y1^4 = y3 */ 1146 | } 1147 | 1148 | /* Computes result = x^3 + b. result must not overlap x. */ 1149 | static void x_side_secp256k1(uECC_word_t *result, const uECC_word_t *x, uECC_Curve curve) { 1150 | uECC_vli_modSquare_fast(result, x, curve); /* r = x^2 */ 1151 | uECC_vli_modMult_fast(result, result, x, curve); /* r = x^3 */ 1152 | uECC_vli_modAdd(result, result, curve->b, curve->p, num_words_secp256k1); /* r = x^3 + b */ 1153 | } 1154 | 1155 | #if (uECC_OPTIMIZATION_LEVEL > 0 && !asm_mmod_fast_secp256k1) 1156 | static void omega_mult_secp256k1(uECC_word_t *result, const uECC_word_t *right); 1157 | static void vli_mmod_fast_secp256k1(uECC_word_t *result, uECC_word_t *product) { 1158 | uECC_word_t tmp[2 * num_words_secp256k1]; 1159 | uECC_word_t carry; 1160 | 1161 | uECC_vli_clear(tmp, num_words_secp256k1); 1162 | uECC_vli_clear(tmp + num_words_secp256k1, num_words_secp256k1); 1163 | 1164 | omega_mult_secp256k1(tmp, product + num_words_secp256k1); /* (Rq, q) = q * c */ 1165 | 1166 | carry = uECC_vli_add(result, product, tmp, num_words_secp256k1); /* (C, r) = r + q */ 1167 | uECC_vli_clear(product, num_words_secp256k1); 1168 | omega_mult_secp256k1(product, tmp + num_words_secp256k1); /* Rq*c */ 1169 | carry += uECC_vli_add(result, result, product, num_words_secp256k1); /* (C1, r) = r + Rq*c */ 1170 | 1171 | while (carry > 0) { 1172 | --carry; 1173 | uECC_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1); 1174 | } 1175 | if (uECC_vli_cmp_unsafe(result, curve_secp256k1.p, num_words_secp256k1) > 0) { 1176 | uECC_vli_sub(result, result, curve_secp256k1.p, num_words_secp256k1); 1177 | } 1178 | } 1179 | 1180 | #if uECC_WORD_SIZE == 1 1181 | static void omega_mult_secp256k1(uint8_t * result, const uint8_t * right) { 1182 | /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */ 1183 | uECC_word_t r0 = 0; 1184 | uECC_word_t r1 = 0; 1185 | uECC_word_t r2 = 0; 1186 | wordcount_t k; 1187 | 1188 | /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */ 1189 | muladd(0xD1, right[0], &r0, &r1, &r2); 1190 | result[0] = r0; 1191 | r0 = r1; 1192 | r1 = r2; 1193 | /* r2 is still 0 */ 1194 | 1195 | for (k = 1; k < num_words_secp256k1; ++k) { 1196 | muladd(0x03, right[k - 1], &r0, &r1, &r2); 1197 | muladd(0xD1, right[k], &r0, &r1, &r2); 1198 | result[k] = r0; 1199 | r0 = r1; 1200 | r1 = r2; 1201 | r2 = 0; 1202 | } 1203 | muladd(0x03, right[num_words_secp256k1 - 1], &r0, &r1, &r2); 1204 | result[num_words_secp256k1] = r0; 1205 | result[num_words_secp256k1 + 1] = r1; 1206 | /* add the 2^32 multiple */ 1207 | result[4 + num_words_secp256k1] = 1208 | uECC_vli_add(result + 4, result + 4, right, num_words_secp256k1); 1209 | } 1210 | #elif uECC_WORD_SIZE == 4 1211 | static void omega_mult_secp256k1(uint32_t * result, const uint32_t * right) { 1212 | /* Multiply by (2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */ 1213 | uint32_t carry = 0; 1214 | wordcount_t k; 1215 | 1216 | for (k = 0; k < num_words_secp256k1; ++k) { 1217 | uint64_t p = (uint64_t)0x3D1 * right[k] + carry; 1218 | result[k] = (uint32_t) p; 1219 | carry = p >> 32; 1220 | } 1221 | result[num_words_secp256k1] = carry; 1222 | /* add the 2^32 multiple */ 1223 | result[1 + num_words_secp256k1] = 1224 | uECC_vli_add(result + 1, result + 1, right, num_words_secp256k1); 1225 | } 1226 | #else 1227 | static void omega_mult_secp256k1(uint64_t * result, const uint64_t * right) { 1228 | uECC_word_t r0 = 0; 1229 | uECC_word_t r1 = 0; 1230 | uECC_word_t r2 = 0; 1231 | wordcount_t k; 1232 | 1233 | /* Multiply by (2^32 + 2^9 + 2^8 + 2^7 + 2^6 + 2^4 + 1). */ 1234 | for (k = 0; k < num_words_secp256k1; ++k) { 1235 | muladd(0x1000003D1ull, right[k], &r0, &r1, &r2); 1236 | result[k] = r0; 1237 | r0 = r1; 1238 | r1 = r2; 1239 | r2 = 0; 1240 | } 1241 | result[num_words_secp256k1] = r0; 1242 | } 1243 | #endif /* uECC_WORD_SIZE */ 1244 | #endif /* (uECC_OPTIMIZATION_LEVEL > 0 && && !asm_mmod_fast_secp256k1) */ 1245 | 1246 | #endif /* uECC_SUPPORTS_secp256k1 */ 1247 | 1248 | #endif /* _UECC_CURVE_SPECIFIC_H_ */ 1249 | -------------------------------------------------------------------------------- /main/utils/uECC.c: -------------------------------------------------------------------------------- 1 | /* Copyright 2014, Kenneth MacKay. Licensed under the BSD 2-clause license. */ 2 | 3 | #include "uECC.h" 4 | 5 | #ifndef uECC_RNG_MAX_TRIES 6 | #define uECC_RNG_MAX_TRIES 64 7 | #endif 8 | 9 | #if uECC_ENABLE_VLI_API 10 | #define uECC_VLI_API 11 | #else 12 | #define uECC_VLI_API static 13 | #endif 14 | 15 | #define CONCATX(a, ...) a##__VA_ARGS__ 16 | #define CONCAT(a, ...) CONCATX(a, __VA_ARGS__) 17 | 18 | #define STRX(a) #a 19 | #define STR(a) STRX(a) 20 | 21 | #define EVAL(...) EVAL1(EVAL1(EVAL1(EVAL1(__VA_ARGS__)))) 22 | #define EVAL1(...) EVAL2(EVAL2(EVAL2(EVAL2(__VA_ARGS__)))) 23 | #define EVAL2(...) EVAL3(EVAL3(EVAL3(EVAL3(__VA_ARGS__)))) 24 | #define EVAL3(...) EVAL4(EVAL4(EVAL4(EVAL4(__VA_ARGS__)))) 25 | #define EVAL4(...) __VA_ARGS__ 26 | 27 | #define DEC_1 0 28 | #define DEC_2 1 29 | #define DEC_3 2 30 | #define DEC_4 3 31 | #define DEC_5 4 32 | #define DEC_6 5 33 | #define DEC_7 6 34 | #define DEC_8 7 35 | #define DEC_9 8 36 | #define DEC_10 9 37 | #define DEC_11 10 38 | #define DEC_12 11 39 | #define DEC_13 12 40 | #define DEC_14 13 41 | #define DEC_15 14 42 | #define DEC_16 15 43 | #define DEC_17 16 44 | #define DEC_18 17 45 | #define DEC_19 18 46 | #define DEC_20 19 47 | #define DEC_21 20 48 | #define DEC_22 21 49 | #define DEC_23 22 50 | #define DEC_24 23 51 | #define DEC_25 24 52 | #define DEC_26 25 53 | #define DEC_27 26 54 | #define DEC_28 27 55 | #define DEC_29 28 56 | #define DEC_30 29 57 | #define DEC_31 30 58 | #define DEC_32 31 59 | 60 | #define DEC(N) CONCAT(DEC_, N) 61 | 62 | #define SECOND_ARG(_, val, ...) val 63 | #define SOME_CHECK_0 ~, 0 64 | #define GET_SECOND_ARG(...) SECOND_ARG(__VA_ARGS__, SOME, ) 65 | #define SOME_OR_0(N) GET_SECOND_ARG(CONCAT(SOME_CHECK_, N)) 66 | 67 | #define EMPTY(...) 68 | #define DEFER(...) __VA_ARGS__ EMPTY() 69 | 70 | #define REPEAT_NAME_0() REPEAT_0 71 | #define REPEAT_NAME_SOME() REPEAT_SOME 72 | #define REPEAT_0(...) 73 | #define REPEAT_SOME(N, stuff) DEFER(CONCAT(REPEAT_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), stuff) stuff 74 | #define REPEAT(N, stuff) EVAL(REPEAT_SOME(N, stuff)) 75 | 76 | #define REPEATM_NAME_0() REPEATM_0 77 | #define REPEATM_NAME_SOME() REPEATM_SOME 78 | #define REPEATM_0(...) 79 | #define REPEATM_SOME(N, macro) macro(N) DEFER(CONCAT(REPEATM_NAME_, SOME_OR_0(DEC(N))))()(DEC(N), macro) 80 | #define REPEATM(N, macro) EVAL(REPEATM_SOME(N, macro)) 81 | 82 | #include "types.h" 83 | 84 | #if (uECC_WORD_SIZE == 1) 85 | #if uECC_SUPPORTS_secp160r1 86 | #define uECC_MAX_WORDS 21 /* Due to the size of curve_n. */ 87 | #endif 88 | #if uECC_SUPPORTS_secp192r1 89 | #undef uECC_MAX_WORDS 90 | #define uECC_MAX_WORDS 24 91 | #endif 92 | #if uECC_SUPPORTS_secp224r1 93 | #undef uECC_MAX_WORDS 94 | #define uECC_MAX_WORDS 28 95 | #endif 96 | #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1) 97 | #undef uECC_MAX_WORDS 98 | #define uECC_MAX_WORDS 32 99 | #endif 100 | #elif (uECC_WORD_SIZE == 4) 101 | #if uECC_SUPPORTS_secp160r1 102 | #define uECC_MAX_WORDS 6 /* Due to the size of curve_n. */ 103 | #endif 104 | #if uECC_SUPPORTS_secp192r1 105 | #undef uECC_MAX_WORDS 106 | #define uECC_MAX_WORDS 6 107 | #endif 108 | #if uECC_SUPPORTS_secp224r1 109 | #undef uECC_MAX_WORDS 110 | #define uECC_MAX_WORDS 7 111 | #endif 112 | #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1) 113 | #undef uECC_MAX_WORDS 114 | #define uECC_MAX_WORDS 8 115 | #endif 116 | #elif (uECC_WORD_SIZE == 8) 117 | #if uECC_SUPPORTS_secp160r1 118 | #define uECC_MAX_WORDS 3 119 | #endif 120 | #if uECC_SUPPORTS_secp192r1 121 | #undef uECC_MAX_WORDS 122 | #define uECC_MAX_WORDS 3 123 | #endif 124 | #if uECC_SUPPORTS_secp224r1 125 | #undef uECC_MAX_WORDS 126 | #define uECC_MAX_WORDS 4 127 | #endif 128 | #if (uECC_SUPPORTS_secp256r1 || uECC_SUPPORTS_secp256k1) 129 | #undef uECC_MAX_WORDS 130 | #define uECC_MAX_WORDS 4 131 | #endif 132 | #endif /* uECC_WORD_SIZE */ 133 | 134 | #define BITS_TO_WORDS(num_bits) ((num_bits + ((uECC_WORD_SIZE * 8) - 1)) / (uECC_WORD_SIZE * 8)) 135 | #define BITS_TO_BYTES(num_bits) ((num_bits + 7) / 8) 136 | 137 | struct uECC_Curve_t 138 | { 139 | wordcount_t num_words; 140 | wordcount_t num_bytes; 141 | bitcount_t num_n_bits; 142 | uECC_word_t p[uECC_MAX_WORDS]; 143 | uECC_word_t n[uECC_MAX_WORDS]; 144 | uECC_word_t G[uECC_MAX_WORDS * 2]; 145 | uECC_word_t b[uECC_MAX_WORDS]; 146 | 147 | void (*double_jacobian)(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * Z1, uECC_Curve curve); 148 | 149 | #if uECC_SUPPORT_COMPRESSED_POINT 150 | void (*mod_sqrt)(uECC_word_t * a, uECC_Curve curve); 151 | #endif 152 | 153 | void (*x_side)(uECC_word_t * result, const uECC_word_t * x, uECC_Curve curve); 154 | 155 | #if (uECC_OPTIMIZATION_LEVEL > 0) 156 | 157 | void (*mmod_fast)(uECC_word_t * result, uECC_word_t * product); 158 | 159 | #endif 160 | }; 161 | 162 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 163 | 164 | static void __bocpy(uint8_t * dst, const uint8_t * src, unsigned num_bytes) 165 | { 166 | while (0 != num_bytes) 167 | { 168 | num_bytes--; 169 | dst[num_bytes] = src[num_bytes]; 170 | } 171 | } 172 | 173 | #endif 174 | 175 | static cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t * left, const uECC_word_t * right, wordcount_t num_words); 176 | 177 | #if (uECC_PLATFORM == uECC_arm || uECC_PLATFORM == uECC_arm_thumb || uECC_PLATFORM == uECC_arm_thumb2) 178 | #include "asm_arm.inc" 179 | #endif 180 | 181 | #if (uECC_PLATFORM == uECC_avr) 182 | #include "asm_avr.inc" 183 | #endif 184 | 185 | #if default_RNG_defined 186 | static uECC_RNG_Function g_rng_function = &default_RNG; 187 | #else 188 | static uECC_RNG_Function g_rng_function = 0; 189 | #endif 190 | 191 | void uECC_set_rng(uECC_RNG_Function rng_function) 192 | { 193 | g_rng_function = rng_function; 194 | } 195 | 196 | int uECC_curve_private_key_size(uECC_Curve curve) 197 | { 198 | return BITS_TO_BYTES(curve->num_n_bits); 199 | } 200 | 201 | int uECC_curve_public_key_size(uECC_Curve curve) 202 | { 203 | return 2 * curve->num_bytes; 204 | } 205 | 206 | #if !asm_clear 207 | 208 | uECC_VLI_API void uECC_vli_clear(uECC_word_t * vli, wordcount_t num_words) 209 | { 210 | wordcount_t i; 211 | for (i = 0; i < num_words; ++i) 212 | { 213 | vli[i] = 0; 214 | } 215 | } 216 | 217 | #endif /* !asm_clear */ 218 | 219 | /* Constant-time comparison to zero - secure way to compare long integers */ 220 | /* Returns 1 if vli == 0, 0 otherwise. */ 221 | uECC_VLI_API uECC_word_t uECC_vli_isZero(const uECC_word_t * vli, wordcount_t num_words) 222 | { 223 | uECC_word_t bits = 0; 224 | wordcount_t i; 225 | for (i = 0; i < num_words; ++i) 226 | { 227 | bits |= vli[i]; 228 | } 229 | return (bits == 0); 230 | } 231 | 232 | /* Returns nonzero if bit 'bit' of vli is set. */ 233 | uECC_VLI_API uECC_word_t uECC_vli_testBit(const uECC_word_t * vli, bitcount_t bit) 234 | { 235 | return (vli[bit >> uECC_WORD_BITS_SHIFT] & ((uECC_word_t) 1 << (bit & uECC_WORD_BITS_MASK))); 236 | } 237 | 238 | /* Counts the number of words in vli. */ 239 | static wordcount_t vli_numDigits(const uECC_word_t * vli, const wordcount_t max_words) 240 | { 241 | wordcount_t i; 242 | /* Search from the end until we find a non-zero digit. 243 | We do it in reverse because we expect that most digits will be nonzero. */ 244 | for (i = max_words - 1; i >= 0 && vli[i] == 0; --i) 245 | {} 246 | 247 | return (i + 1); 248 | } 249 | 250 | /* Counts the number of bits required to represent vli. */ 251 | uECC_VLI_API bitcount_t uECC_vli_numBits(const uECC_word_t * vli, const wordcount_t max_words) 252 | { 253 | uECC_word_t i; 254 | uECC_word_t digit; 255 | 256 | wordcount_t num_digits = vli_numDigits(vli, max_words); 257 | if (num_digits == 0) 258 | { 259 | return 0; 260 | } 261 | 262 | digit = vli[num_digits - 1]; 263 | for (i = 0; digit; ++i) 264 | { 265 | digit >>= 1; 266 | } 267 | 268 | return (((bitcount_t) (num_digits - 1) << uECC_WORD_BITS_SHIFT) + i); 269 | } 270 | 271 | /* Sets dest = src. */ 272 | #if !asm_set 273 | 274 | uECC_VLI_API void uECC_vli_set(uECC_word_t * dest, const uECC_word_t * src, wordcount_t num_words) 275 | { 276 | wordcount_t i; 277 | for (i = 0; i < num_words; ++i) 278 | { 279 | dest[i] = src[i]; 280 | } 281 | } 282 | 283 | #endif /* !asm_set */ 284 | 285 | /* Returns sign of left - right. */ 286 | static cmpresult_t uECC_vli_cmp_unsafe(const uECC_word_t * left, const uECC_word_t * right, wordcount_t num_words) 287 | { 288 | wordcount_t i; 289 | for (i = num_words - 1; i >= 0; --i) 290 | { 291 | if (left[i] > right[i]) 292 | { 293 | return 1; 294 | } 295 | else if (left[i] < right[i]) 296 | { 297 | return -1; 298 | } 299 | } 300 | return 0; 301 | } 302 | 303 | /* Constant-time comparison function - secure way to compare long integers */ 304 | /* Returns one if left == right, zero otherwise. */ 305 | uECC_VLI_API uECC_word_t uECC_vli_equal(const uECC_word_t * left, const uECC_word_t * right, wordcount_t num_words) 306 | { 307 | uECC_word_t diff = 0; 308 | wordcount_t i; 309 | for (i = num_words - 1; i >= 0; --i) 310 | { 311 | diff |= (left[i] ^ right[i]); 312 | } 313 | return (diff == 0); 314 | } 315 | 316 | uECC_VLI_API uECC_word_t uECC_vli_sub(uECC_word_t * result, const uECC_word_t * left, const uECC_word_t * right, wordcount_t num_words); 317 | 318 | /* Returns sign of left - right, in constant time. */ 319 | uECC_VLI_API cmpresult_t uECC_vli_cmp(const uECC_word_t * left, const uECC_word_t * right, wordcount_t num_words) 320 | { 321 | uECC_word_t tmp[uECC_MAX_WORDS]; 322 | uECC_word_t neg = !!uECC_vli_sub(tmp, left, right, num_words); 323 | uECC_word_t equal = uECC_vli_isZero(tmp, num_words); 324 | return (!equal - 2 * neg); 325 | } 326 | 327 | /* Computes vli = vli >> 1. */ 328 | #if !asm_rshift1 329 | 330 | uECC_VLI_API void uECC_vli_rshift1(uECC_word_t * vli, wordcount_t num_words) 331 | { 332 | uECC_word_t * end = vli; 333 | uECC_word_t carry = 0; 334 | 335 | vli += num_words; 336 | while (vli-- > end) 337 | { 338 | uECC_word_t temp = *vli; 339 | *vli = (temp >> 1) | carry; 340 | carry = temp << (uECC_WORD_BITS - 1); 341 | } 342 | } 343 | 344 | #endif /* !asm_rshift1 */ 345 | 346 | /* Computes result = left + right, returning carry. Can modify in place. */ 347 | #if !asm_add 348 | 349 | uECC_VLI_API uECC_word_t uECC_vli_add(uECC_word_t * result, const uECC_word_t * left, const uECC_word_t * right, wordcount_t num_words) 350 | { 351 | uECC_word_t carry = 0; 352 | wordcount_t i; 353 | for (i = 0; i < num_words; ++i) 354 | { 355 | uECC_word_t sum = left[i] + right[i] + carry; 356 | if (sum != left[i]) 357 | { 358 | carry = (sum < left[i]); 359 | } 360 | result[i] = sum; 361 | } 362 | return carry; 363 | } 364 | 365 | #endif /* !asm_add */ 366 | 367 | /* Computes result = left - right, returning borrow. Can modify in place. */ 368 | #if !asm_sub 369 | 370 | uECC_VLI_API uECC_word_t uECC_vli_sub(uECC_word_t * result, const uECC_word_t * left, const uECC_word_t * right, wordcount_t num_words) 371 | { 372 | uECC_word_t borrow = 0; 373 | wordcount_t i; 374 | for (i = 0; i < num_words; ++i) 375 | { 376 | uECC_word_t diff = left[i] - right[i] - borrow; 377 | if (diff != left[i]) 378 | { 379 | borrow = (diff > left[i]); 380 | } 381 | result[i] = diff; 382 | } 383 | return borrow; 384 | } 385 | 386 | #endif /* !asm_sub */ 387 | 388 | #if !asm_mult || (uECC_SQUARE_FUNC && !asm_square) || (uECC_SUPPORTS_secp256k1 && (uECC_OPTIMIZATION_LEVEL > 0) && ((uECC_WORD_SIZE == 1) || (uECC_WORD_SIZE == 8))) 389 | 390 | static void muladd(uECC_word_t a, uECC_word_t b, uECC_word_t * r0, uECC_word_t * r1, uECC_word_t * r2) 391 | { 392 | #if uECC_WORD_SIZE == 8 && !SUPPORTS_INT128 393 | uint64_t a0 = a & 0xffffffffull; 394 | uint64_t a1 = a >> 32; 395 | uint64_t b0 = b & 0xffffffffull; 396 | uint64_t b1 = b >> 32; 397 | 398 | uint64_t i0 = a0 * b0; 399 | uint64_t i1 = a0 * b1; 400 | uint64_t i2 = a1 * b0; 401 | uint64_t i3 = a1 * b1; 402 | 403 | uint64_t p0, p1; 404 | 405 | i2 += (i0 >> 32); 406 | i2 += i1; 407 | if (i2 < i1) 408 | { /* overflow */ 409 | i3 += 0x100000000ull; 410 | } 411 | 412 | p0 = (i0 & 0xffffffffull) | (i2 << 32); 413 | p1 = i3 + (i2 >> 32); 414 | 415 | *r0 += p0; 416 | *r1 += (p1 + (*r0 < p0)); 417 | *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0)); 418 | #else 419 | uECC_dword_t p = (uECC_dword_t) a * b; 420 | uECC_dword_t r01 = ((uECC_dword_t) (*r1) << uECC_WORD_BITS) | *r0; 421 | r01 += p; 422 | *r2 += (r01 < p); 423 | *r1 = r01 >> uECC_WORD_BITS; 424 | *r0 = (uECC_word_t) r01; 425 | #endif 426 | } 427 | 428 | #endif /* muladd needed */ 429 | 430 | #if !asm_mult 431 | 432 | uECC_VLI_API void uECC_vli_mult(uECC_word_t * result, const uECC_word_t * left, const uECC_word_t * right, wordcount_t num_words) 433 | { 434 | uECC_word_t r0 = 0; 435 | uECC_word_t r1 = 0; 436 | uECC_word_t r2 = 0; 437 | wordcount_t i, k; 438 | 439 | /* Compute each digit of result in sequence, maintaining the carries. */ 440 | for (k = 0; k < num_words; ++k) 441 | { 442 | for (i = 0; i <= k; ++i) 443 | { 444 | muladd(left[i], right[k - i], &r0, &r1, &r2); 445 | } 446 | result[k] = r0; 447 | r0 = r1; 448 | r1 = r2; 449 | r2 = 0; 450 | } 451 | for (k = num_words; k < num_words * 2 - 1; ++k) 452 | { 453 | for (i = (k + 1) - num_words; i < num_words; ++i) 454 | { 455 | muladd(left[i], right[k - i], &r0, &r1, &r2); 456 | } 457 | result[k] = r0; 458 | r0 = r1; 459 | r1 = r2; 460 | r2 = 0; 461 | } 462 | result[num_words * 2 - 1] = r0; 463 | } 464 | 465 | #endif /* !asm_mult */ 466 | 467 | #if uECC_SQUARE_FUNC 468 | 469 | #if !asm_square 470 | static void mul2add(uECC_word_t a, uECC_word_t b, uECC_word_t * r0, uECC_word_t * r1, uECC_word_t * r2) 471 | { 472 | #if uECC_WORD_SIZE == 8 && !SUPPORTS_INT128 473 | uint64_t a0 = a & 0xffffffffull; 474 | uint64_t a1 = a >> 32; 475 | uint64_t b0 = b & 0xffffffffull; 476 | uint64_t b1 = b >> 32; 477 | 478 | uint64_t i0 = a0 * b0; 479 | uint64_t i1 = a0 * b1; 480 | uint64_t i2 = a1 * b0; 481 | uint64_t i3 = a1 * b1; 482 | 483 | uint64_t p0, p1; 484 | 485 | i2 += (i0 >> 32); 486 | i2 += i1; 487 | if (i2 < i1) 488 | { /* overflow */ 489 | i3 += 0x100000000ull; 490 | } 491 | 492 | p0 = (i0 & 0xffffffffull) | (i2 << 32); 493 | p1 = i3 + (i2 >> 32); 494 | 495 | *r2 += (p1 >> 63); 496 | p1 = (p1 << 1) | (p0 >> 63); 497 | p0 <<= 1; 498 | 499 | *r0 += p0; 500 | *r1 += (p1 + (*r0 < p0)); 501 | *r2 += ((*r1 < p1) || (*r1 == p1 && *r0 < p0)); 502 | #else 503 | uECC_dword_t p = (uECC_dword_t) a * b; 504 | uECC_dword_t r01 = ((uECC_dword_t) (*r1) << uECC_WORD_BITS) | *r0; 505 | *r2 += (p >> (uECC_WORD_BITS * 2 - 1)); 506 | p *= 2; 507 | r01 += p; 508 | *r2 += (r01 < p); 509 | *r1 = r01 >> uECC_WORD_BITS; 510 | *r0 = (uECC_word_t) r01; 511 | #endif 512 | } 513 | 514 | uECC_VLI_API void uECC_vli_square(uECC_word_t * result, const uECC_word_t * left, wordcount_t num_words) 515 | { 516 | uECC_word_t r0 = 0; 517 | uECC_word_t r1 = 0; 518 | uECC_word_t r2 = 0; 519 | 520 | wordcount_t i, k; 521 | 522 | for (k = 0; k < num_words * 2 - 1; ++k) 523 | { 524 | uECC_word_t min = (k < num_words ? 0 : (k + 1) - num_words); 525 | for (i = min; i <= k && i <= k - i; ++i) 526 | { 527 | if (i < k - i) 528 | { 529 | mul2add(left[i], left[k - i], &r0, &r1, &r2); 530 | } 531 | else 532 | { 533 | muladd(left[i], left[k - i], &r0, &r1, &r2); 534 | } 535 | } 536 | result[k] = r0; 537 | r0 = r1; 538 | r1 = r2; 539 | r2 = 0; 540 | } 541 | 542 | result[num_words * 2 - 1] = r0; 543 | } 544 | #endif /* !asm_square */ 545 | 546 | #else /* uECC_SQUARE_FUNC */ 547 | 548 | #if uECC_ENABLE_VLI_API 549 | uECC_VLI_API void uECC_vli_square(uECC_word_t * result, const uECC_word_t * left, wordcount_t num_words) 550 | { 551 | uECC_vli_mult(result, left, left, num_words); 552 | } 553 | #endif /* uECC_ENABLE_VLI_API */ 554 | 555 | #endif /* uECC_SQUARE_FUNC */ 556 | 557 | /* Computes result = (left + right) % mod. 558 | Assumes that left < mod and right < mod, and that result does not overlap mod. */ 559 | uECC_VLI_API void uECC_vli_modAdd(uECC_word_t * result, const uECC_word_t * left, const uECC_word_t * right, const uECC_word_t * mod, wordcount_t num_words) 560 | { 561 | uECC_word_t carry = uECC_vli_add(result, left, right, num_words); 562 | if (carry || uECC_vli_cmp_unsafe(mod, result, num_words) != 1) 563 | { 564 | /* result > mod (result = mod + remainder), so subtract mod to get remainder. */ 565 | uECC_vli_sub(result, result, mod, num_words); 566 | } 567 | } 568 | 569 | /* Computes result = (left - right) % mod. 570 | Assumes that left < mod and right < mod, and that result does not overlap mod. */ 571 | uECC_VLI_API void uECC_vli_modSub(uECC_word_t * result, const uECC_word_t * left, const uECC_word_t * right, const uECC_word_t * mod, wordcount_t num_words) 572 | { 573 | uECC_word_t l_borrow = uECC_vli_sub(result, left, right, num_words); 574 | if (l_borrow) 575 | { 576 | /* In this case, result == -diff == (max int) - diff. Since -x % d == d - x, 577 | we can get the correct result from result + mod (with overflow). */ 578 | uECC_vli_add(result, result, mod, num_words); 579 | } 580 | } 581 | 582 | /* Computes result = product % mod, where product is 2N words long. */ 583 | /* Currently only designed to work for curve_p or curve_n. */ 584 | uECC_VLI_API void uECC_vli_mmod(uECC_word_t * result, uECC_word_t * product, const uECC_word_t * mod, wordcount_t num_words) 585 | { 586 | uECC_word_t mod_multiple[2 * uECC_MAX_WORDS]; 587 | uECC_word_t tmp[2 * uECC_MAX_WORDS]; 588 | uECC_word_t * v[2] = { tmp, product }; 589 | uECC_word_t index; 590 | 591 | /* Shift mod so its highest set bit is at the maximum position. */ 592 | bitcount_t shift = (num_words * 2 * uECC_WORD_BITS) - uECC_vli_numBits(mod, num_words); 593 | wordcount_t word_shift = shift / uECC_WORD_BITS; 594 | wordcount_t bit_shift = shift % uECC_WORD_BITS; 595 | uECC_word_t carry = 0; 596 | uECC_vli_clear(mod_multiple, word_shift); 597 | if (bit_shift > 0) 598 | { 599 | for (index = 0; index < (uECC_word_t) num_words; ++index) 600 | { 601 | mod_multiple[word_shift + index] = (mod[index] << bit_shift) | carry; 602 | carry = mod[index] >> (uECC_WORD_BITS - bit_shift); 603 | } 604 | } 605 | else 606 | { 607 | uECC_vli_set(mod_multiple + word_shift, mod, num_words); 608 | } 609 | 610 | for (index = 1; shift >= 0; --shift) 611 | { 612 | uECC_word_t borrow = 0; 613 | wordcount_t i; 614 | for (i = 0; i < num_words * 2; ++i) 615 | { 616 | uECC_word_t diff = v[index][i] - mod_multiple[i] - borrow; 617 | if (diff != v[index][i]) 618 | { 619 | borrow = (diff > v[index][i]); 620 | } 621 | v[1 - index][i] = diff; 622 | } 623 | index = !(index ^ borrow); /* Swap the index if there was no borrow */ 624 | uECC_vli_rshift1(mod_multiple, num_words); 625 | mod_multiple[num_words - 1] |= mod_multiple[num_words] << (uECC_WORD_BITS - 1); 626 | uECC_vli_rshift1(mod_multiple + num_words, num_words); 627 | } 628 | uECC_vli_set(result, v[index], num_words); 629 | } 630 | 631 | /* Computes result = (left * right) % mod. */ 632 | uECC_VLI_API void uECC_vli_modMult(uECC_word_t * result, const uECC_word_t * left, const uECC_word_t * right, const uECC_word_t * mod, wordcount_t num_words) 633 | { 634 | uECC_word_t product[2 * uECC_MAX_WORDS]; 635 | uECC_vli_mult(product, left, right, num_words); 636 | uECC_vli_mmod(result, product, mod, num_words); 637 | } 638 | 639 | uECC_VLI_API void uECC_vli_modMult_fast(uECC_word_t * result, const uECC_word_t * left, const uECC_word_t * right, uECC_Curve curve) 640 | { 641 | uECC_word_t product[2 * uECC_MAX_WORDS]; 642 | uECC_vli_mult(product, left, right, curve->num_words); 643 | #if (uECC_OPTIMIZATION_LEVEL > 0) 644 | curve->mmod_fast(result, product); 645 | #else 646 | uECC_vli_mmod(result, product, curve->p, curve->num_words); 647 | #endif 648 | } 649 | 650 | #if uECC_SQUARE_FUNC 651 | 652 | #if uECC_ENABLE_VLI_API 653 | /* Computes result = left^2 % mod. */ 654 | uECC_VLI_API void uECC_vli_modSquare(uECC_word_t * result, const uECC_word_t * left, const uECC_word_t * mod, wordcount_t num_words) 655 | { 656 | uECC_word_t product[2 * uECC_MAX_WORDS]; 657 | uECC_vli_square(product, left, num_words); 658 | uECC_vli_mmod(result, product, mod, num_words); 659 | } 660 | #endif /* uECC_ENABLE_VLI_API */ 661 | 662 | uECC_VLI_API void uECC_vli_modSquare_fast(uECC_word_t * result, const uECC_word_t * left, uECC_Curve curve) 663 | { 664 | uECC_word_t product[2 * uECC_MAX_WORDS]; 665 | uECC_vli_square(product, left, curve->num_words); 666 | #if (uECC_OPTIMIZATION_LEVEL > 0) 667 | curve->mmod_fast(result, product); 668 | #else 669 | uECC_vli_mmod(result, product, curve->p, curve->num_words); 670 | #endif 671 | } 672 | 673 | #else /* uECC_SQUARE_FUNC */ 674 | 675 | #if uECC_ENABLE_VLI_API 676 | uECC_VLI_API void uECC_vli_modSquare(uECC_word_t * result, const uECC_word_t * left, const uECC_word_t * mod, wordcount_t num_words) 677 | { 678 | uECC_vli_modMult(result, left, left, mod, num_words); 679 | } 680 | #endif /* uECC_ENABLE_VLI_API */ 681 | 682 | uECC_VLI_API void uECC_vli_modSquare_fast(uECC_word_t * result, const uECC_word_t * left, uECC_Curve curve) 683 | { 684 | uECC_vli_modMult_fast(result, left, left, curve); 685 | } 686 | 687 | #endif /* uECC_SQUARE_FUNC */ 688 | 689 | #define EVEN(vli) (!(vli[0] & 1)) 690 | 691 | static void vli_modInv_update(uECC_word_t * uv, const uECC_word_t * mod, wordcount_t num_words) 692 | { 693 | uECC_word_t carry = 0; 694 | if (!EVEN(uv)) 695 | { 696 | carry = uECC_vli_add(uv, uv, mod, num_words); 697 | } 698 | uECC_vli_rshift1(uv, num_words); 699 | if (carry) 700 | { 701 | uv[num_words - 1] |= HIGH_BIT_SET; 702 | } 703 | } 704 | 705 | /* Computes result = (1 / input) % mod. All VLIs are the same size. 706 | See "From Euclid's GCD to Montgomery Multiplication to the Great Divide" */ 707 | uECC_VLI_API void uECC_vli_modInv(uECC_word_t * result, const uECC_word_t * input, const uECC_word_t * mod, wordcount_t num_words) 708 | { 709 | uECC_word_t a[uECC_MAX_WORDS], b[uECC_MAX_WORDS], u[uECC_MAX_WORDS], v[uECC_MAX_WORDS]; 710 | cmpresult_t cmpResult; 711 | 712 | if (uECC_vli_isZero(input, num_words)) 713 | { 714 | uECC_vli_clear(result, num_words); 715 | return; 716 | } 717 | 718 | uECC_vli_set(a, input, num_words); 719 | uECC_vli_set(b, mod, num_words); 720 | uECC_vli_clear(u, num_words); 721 | u[0] = 1; 722 | uECC_vli_clear(v, num_words); 723 | while ((cmpResult = uECC_vli_cmp_unsafe(a, b, num_words)) != 0) 724 | { 725 | if (EVEN(a)) 726 | { 727 | uECC_vli_rshift1(a, num_words); 728 | vli_modInv_update(u, mod, num_words); 729 | } 730 | else if (EVEN(b)) 731 | { 732 | uECC_vli_rshift1(b, num_words); 733 | vli_modInv_update(v, mod, num_words); 734 | } 735 | else if (cmpResult > 0) 736 | { 737 | uECC_vli_sub(a, a, b, num_words); 738 | uECC_vli_rshift1(a, num_words); 739 | if (uECC_vli_cmp_unsafe(u, v, num_words) < 0) 740 | { 741 | uECC_vli_add(u, u, mod, num_words); 742 | } 743 | uECC_vli_sub(u, u, v, num_words); 744 | vli_modInv_update(u, mod, num_words); 745 | } 746 | else 747 | { 748 | uECC_vli_sub(b, b, a, num_words); 749 | uECC_vli_rshift1(b, num_words); 750 | if (uECC_vli_cmp_unsafe(v, u, num_words) < 0) 751 | { 752 | uECC_vli_add(v, v, mod, num_words); 753 | } 754 | uECC_vli_sub(v, v, u, num_words); 755 | vli_modInv_update(v, mod, num_words); 756 | } 757 | } 758 | uECC_vli_set(result, u, num_words); 759 | } 760 | 761 | /* ------ Point operations ------ */ 762 | 763 | #include "curve-specific.inc" 764 | 765 | /* Returns 1 if 'point' is the point at infinity, 0 otherwise. */ 766 | #define EccPoint_isZero(point, curve) uECC_vli_isZero((point), (curve)->num_words * 2) 767 | 768 | /* Point multiplication algorithm using Montgomery's ladder with co-Z coordinates. 769 | From http://eprint.iacr.org/2011/338.pdf 770 | */ 771 | 772 | /* Modify (x1, y1) => (x1 * z^2, y1 * z^3) */ 773 | static void apply_z(uECC_word_t * X1, uECC_word_t * Y1, const uECC_word_t * const Z, uECC_Curve curve) 774 | { 775 | uECC_word_t t1[uECC_MAX_WORDS]; 776 | 777 | uECC_vli_modSquare_fast(t1, Z, curve); /* z^2 */ 778 | uECC_vli_modMult_fast(X1, X1, t1, curve); /* x1 * z^2 */ 779 | uECC_vli_modMult_fast(t1, t1, Z, curve); /* z^3 */ 780 | uECC_vli_modMult_fast(Y1, Y1, t1, curve); /* y1 * z^3 */ 781 | } 782 | 783 | /* P = (x1, y1) => 2P, (x2, y2) => P' */ 784 | static void XYcZ_initial_double(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2, uECC_word_t * Y2, const uECC_word_t * const initial_Z, uECC_Curve curve) 785 | { 786 | uECC_word_t z[uECC_MAX_WORDS]; 787 | wordcount_t num_words = curve->num_words; 788 | if (initial_Z) 789 | { 790 | uECC_vli_set(z, initial_Z, num_words); 791 | } 792 | else 793 | { 794 | uECC_vli_clear(z, num_words); 795 | z[0] = 1; 796 | } 797 | 798 | uECC_vli_set(X2, X1, num_words); 799 | uECC_vli_set(Y2, Y1, num_words); 800 | 801 | apply_z(X1, Y1, z, curve); 802 | curve->double_jacobian(X1, Y1, z, curve); 803 | apply_z(X2, Y2, z, curve); 804 | } 805 | 806 | /* Input P = (x1, y1, Z), Q = (x2, y2, Z) 807 | Output P' = (x1', y1', Z3), P + Q = (x3, y3, Z3) 808 | or P => P', Q => P + Q 809 | */ 810 | static void XYcZ_add(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2, uECC_word_t * Y2, uECC_Curve curve) 811 | { 812 | /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */ 813 | uECC_word_t t5[uECC_MAX_WORDS]; 814 | wordcount_t num_words = curve->num_words; 815 | 816 | uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */ 817 | uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */ 818 | uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */ 819 | uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */ 820 | uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */ 821 | uECC_vli_modSquare_fast(t5, Y2, curve); /* t5 = (y2 - y1)^2 = D */ 822 | 823 | uECC_vli_modSub(t5, t5, X1, curve->p, num_words); /* t5 = D - B */ 824 | uECC_vli_modSub(t5, t5, X2, curve->p, num_words); /* t5 = D - B - C = x3 */ 825 | uECC_vli_modSub(X2, X2, X1, curve->p, num_words); /* t3 = C - B */ 826 | uECC_vli_modMult_fast(Y1, Y1, X2, curve); /* t2 = y1*(C - B) */ 827 | uECC_vli_modSub(X2, X1, t5, curve->p, num_words); /* t3 = B - x3 */ 828 | uECC_vli_modMult_fast(Y2, Y2, X2, curve); /* t4 = (y2 - y1)*(B - x3) */ 829 | uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y3 */ 830 | 831 | uECC_vli_set(X2, t5, num_words); 832 | } 833 | 834 | /* Input P = (x1, y1, Z), Q = (x2, y2, Z) 835 | Output P + Q = (x3, y3, Z3), P - Q = (x3', y3', Z3) 836 | or P => P - Q, Q => P + Q 837 | */ 838 | static void XYcZ_addC(uECC_word_t * X1, uECC_word_t * Y1, uECC_word_t * X2, uECC_word_t * Y2, uECC_Curve curve) 839 | { 840 | /* t1 = X1, t2 = Y1, t3 = X2, t4 = Y2 */ 841 | uECC_word_t t5[uECC_MAX_WORDS]; 842 | uECC_word_t t6[uECC_MAX_WORDS]; 843 | uECC_word_t t7[uECC_MAX_WORDS]; 844 | wordcount_t num_words = curve->num_words; 845 | 846 | uECC_vli_modSub(t5, X2, X1, curve->p, num_words); /* t5 = x2 - x1 */ 847 | uECC_vli_modSquare_fast(t5, t5, curve); /* t5 = (x2 - x1)^2 = A */ 848 | uECC_vli_modMult_fast(X1, X1, t5, curve); /* t1 = x1*A = B */ 849 | uECC_vli_modMult_fast(X2, X2, t5, curve); /* t3 = x2*A = C */ 850 | uECC_vli_modAdd(t5, Y2, Y1, curve->p, num_words); /* t5 = y2 + y1 */ 851 | uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = y2 - y1 */ 852 | 853 | uECC_vli_modSub(t6, X2, X1, curve->p, num_words); /* t6 = C - B */ 854 | uECC_vli_modMult_fast(Y1, Y1, t6, curve); /* t2 = y1 * (C - B) = E */ 855 | uECC_vli_modAdd(t6, X1, X2, curve->p, num_words); /* t6 = B + C */ 856 | uECC_vli_modSquare_fast(X2, Y2, curve); /* t3 = (y2 - y1)^2 = D */ 857 | uECC_vli_modSub(X2, X2, t6, curve->p, num_words); /* t3 = D - (B + C) = x3 */ 858 | 859 | uECC_vli_modSub(t7, X1, X2, curve->p, num_words); /* t7 = B - x3 */ 860 | uECC_vli_modMult_fast(Y2, Y2, t7, curve); /* t4 = (y2 - y1)*(B - x3) */ 861 | uECC_vli_modSub(Y2, Y2, Y1, curve->p, num_words); /* t4 = (y2 - y1)*(B - x3) - E = y3 */ 862 | 863 | uECC_vli_modSquare_fast(t7, t5, curve); /* t7 = (y2 + y1)^2 = F */ 864 | uECC_vli_modSub(t7, t7, t6, curve->p, num_words); /* t7 = F - (B + C) = x3' */ 865 | uECC_vli_modSub(t6, t7, X1, curve->p, num_words); /* t6 = x3' - B */ 866 | uECC_vli_modMult_fast(t6, t6, t5, curve); /* t6 = (y2+y1)*(x3' - B) */ 867 | uECC_vli_modSub(Y1, t6, Y1, curve->p, num_words); /* t2 = (y2+y1)*(x3' - B) - E = y3' */ 868 | 869 | uECC_vli_set(X1, t7, num_words); 870 | } 871 | 872 | /* result may overlap point. */ 873 | static void EccPoint_mult(uECC_word_t * result, const uECC_word_t * point, const uECC_word_t * scalar, const uECC_word_t * initial_Z, bitcount_t num_bits, uECC_Curve curve) 874 | { 875 | /* R0 and R1 */ 876 | uECC_word_t Rx[2][uECC_MAX_WORDS]; 877 | uECC_word_t Ry[2][uECC_MAX_WORDS]; 878 | uECC_word_t z[uECC_MAX_WORDS]; 879 | bitcount_t i; 880 | uECC_word_t nb; 881 | wordcount_t num_words = curve->num_words; 882 | 883 | uECC_vli_set(Rx[1], point, num_words); 884 | uECC_vli_set(Ry[1], point + num_words, num_words); 885 | 886 | XYcZ_initial_double(Rx[1], Ry[1], Rx[0], Ry[0], initial_Z, curve); 887 | 888 | for (i = num_bits - 2; i > 0; --i) 889 | { 890 | nb = !uECC_vli_testBit(scalar, i); 891 | XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve); 892 | XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve); 893 | } 894 | 895 | nb = !uECC_vli_testBit(scalar, 0); 896 | XYcZ_addC(Rx[1 - nb], Ry[1 - nb], Rx[nb], Ry[nb], curve); 897 | 898 | /* Find final 1/Z value. */ 899 | uECC_vli_modSub(z, Rx[1], Rx[0], curve->p, num_words); /* X1 - X0 */ 900 | uECC_vli_modMult_fast(z, z, Ry[1 - nb], curve); /* Yb * (X1 - X0) */ 901 | uECC_vli_modMult_fast(z, z, point, curve); /* xP * Yb * (X1 - X0) */ 902 | uECC_vli_modInv(z, z, curve->p, num_words); /* 1 / (xP * Yb * (X1 - X0)) */ 903 | /* yP / (xP * Yb * (X1 - X0)) */ 904 | uECC_vli_modMult_fast(z, z, point + num_words, curve); 905 | uECC_vli_modMult_fast(z, z, Rx[1 - nb], curve); /* Xb * yP / (xP * Yb * (X1 - X0)) */ 906 | /* End 1/Z calculation */ 907 | 908 | XYcZ_add(Rx[nb], Ry[nb], Rx[1 - nb], Ry[1 - nb], curve); 909 | apply_z(Rx[0], Ry[0], z, curve); 910 | 911 | uECC_vli_set(result, Rx[0], num_words); 912 | uECC_vli_set(result + num_words, Ry[0], num_words); 913 | } 914 | 915 | static uECC_word_t regularize_k(const uECC_word_t * const k, uECC_word_t * k0, uECC_word_t * k1, uECC_Curve curve) 916 | { 917 | wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); 918 | bitcount_t num_n_bits = curve->num_n_bits; 919 | uECC_word_t carry = uECC_vli_add(k0, k, curve->n, num_n_words) || (num_n_bits < ((bitcount_t) num_n_words * uECC_WORD_SIZE * 8) && uECC_vli_testBit(k0, num_n_bits)); 920 | uECC_vli_add(k1, k0, curve->n, num_n_words); 921 | return carry; 922 | } 923 | 924 | static uECC_word_t EccPoint_compute_public_key(uECC_word_t * result, uECC_word_t * private_key, uECC_Curve curve) 925 | { 926 | uECC_word_t tmp1[uECC_MAX_WORDS]; 927 | uECC_word_t tmp2[uECC_MAX_WORDS]; 928 | uECC_word_t * p2[2] = { tmp1, tmp2 }; 929 | uECC_word_t carry; 930 | 931 | /* Regularize the bitcount for the private key so that attackers cannot use a side channel 932 | attack to learn the number of leading zeros. */ 933 | carry = regularize_k(private_key, tmp1, tmp2, curve); 934 | 935 | EccPoint_mult(result, curve->G, p2[!carry], 0, curve->num_n_bits + 1, curve); 936 | 937 | if (EccPoint_isZero(result, curve)) 938 | { 939 | return 0; 940 | } 941 | return 1; 942 | } 943 | 944 | #if uECC_WORD_SIZE == 1 945 | 946 | uECC_VLI_API void uECC_vli_nativeToBytes(uint8_t * bytes, int num_bytes, const uint8_t * native) 947 | { 948 | wordcount_t i; 949 | for (i = 0; i < num_bytes; ++i) 950 | { 951 | bytes[i] = native[(num_bytes - 1) - i]; 952 | } 953 | } 954 | 955 | uECC_VLI_API void uECC_vli_bytesToNative(uint8_t * native, const uint8_t * bytes, int num_bytes) 956 | { 957 | uECC_vli_nativeToBytes(native, num_bytes, bytes); 958 | } 959 | 960 | #else 961 | 962 | uECC_VLI_API void uECC_vli_nativeToBytes(uint8_t * bytes, int num_bytes, const uECC_word_t * native) 963 | { 964 | wordcount_t i; 965 | for (i = 0; i < num_bytes; ++i) 966 | { 967 | unsigned b = num_bytes - 1 - i; 968 | bytes[i] = native[b / uECC_WORD_SIZE] >> (8 * (b % uECC_WORD_SIZE)); 969 | } 970 | } 971 | 972 | uECC_VLI_API void uECC_vli_bytesToNative(uECC_word_t * native, const uint8_t * bytes, int num_bytes) 973 | { 974 | wordcount_t i; 975 | uECC_vli_clear(native, (num_bytes + (uECC_WORD_SIZE - 1)) / uECC_WORD_SIZE); 976 | for (i = 0; i < num_bytes; ++i) 977 | { 978 | unsigned b = num_bytes - 1 - i; 979 | native[b / uECC_WORD_SIZE] |= (uECC_word_t) bytes[i] << (8 * (b % uECC_WORD_SIZE)); 980 | } 981 | } 982 | 983 | #endif /* uECC_WORD_SIZE */ 984 | 985 | /* Generates a random integer in the range 0 < random < top. 986 | Both random and top have num_words words. */ 987 | uECC_VLI_API int uECC_generate_random_int(uECC_word_t * random, const uECC_word_t * top, wordcount_t num_words) 988 | { 989 | uECC_word_t mask = (uECC_word_t) -1; 990 | uECC_word_t tries; 991 | bitcount_t num_bits = uECC_vli_numBits(top, num_words); 992 | 993 | if (!g_rng_function) 994 | { 995 | return 0; 996 | } 997 | 998 | for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) 999 | { 1000 | if (!g_rng_function((uint8_t *) random, num_words * uECC_WORD_SIZE)) 1001 | { 1002 | return 0; 1003 | } 1004 | random[num_words - 1] &= mask >> ((bitcount_t) (num_words * uECC_WORD_SIZE * 8 - num_bits)); 1005 | if (!uECC_vli_isZero(random, num_words) && uECC_vli_cmp(top, random, num_words) == 1) 1006 | { 1007 | return 1; 1008 | } 1009 | } 1010 | return 0; 1011 | } 1012 | 1013 | int uECC_make_key(uint8_t * public_key, uint8_t * private_key, uECC_Curve curve) 1014 | { 1015 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1016 | uECC_word_t * _private = (uECC_word_t *) private_key; 1017 | uECC_word_t * _public = (uECC_word_t *) public_key; 1018 | #else 1019 | uECC_word_t _private[uECC_MAX_WORDS]; 1020 | uECC_word_t _public[uECC_MAX_WORDS * 2]; 1021 | #endif 1022 | uECC_word_t tries; 1023 | 1024 | for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) 1025 | { 1026 | if (!uECC_generate_random_int(_private, curve->n, BITS_TO_WORDS(curve->num_n_bits))) 1027 | { 1028 | return 0; 1029 | } 1030 | 1031 | if (EccPoint_compute_public_key(_public, _private, curve)) 1032 | { 1033 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0 1034 | uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits), _private); 1035 | uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public); 1036 | uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words); 1037 | #endif 1038 | return 1; 1039 | } 1040 | } 1041 | return 0; 1042 | } 1043 | 1044 | int uECC_make_key_lit(uint8_t * public_key, uint8_t * private_key, uECC_Curve curve) 1045 | { 1046 | 1047 | uECC_word_t _private[uECC_MAX_WORDS]; 1048 | uECC_word_t _public[uECC_MAX_WORDS * 2]; 1049 | uECC_word_t tries; 1050 | 1051 | for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) 1052 | { 1053 | if (!uECC_generate_random_int(_private, curve->n, BITS_TO_WORDS(curve->num_n_bits))) 1054 | { 1055 | return 0; 1056 | } 1057 | 1058 | if (EccPoint_compute_public_key(_public, _private, curve)) 1059 | { 1060 | uECC_vli_nativeToBytes(private_key, BITS_TO_BYTES(curve->num_n_bits), _private); 1061 | uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public); 1062 | uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words); 1063 | return 1; 1064 | } 1065 | } 1066 | return 0; 1067 | } 1068 | 1069 | int uECC_shared_secret_lit(const uint8_t * public_key, const uint8_t * private_key, uint8_t * secret, uECC_Curve curve) 1070 | { 1071 | uECC_word_t _public[uECC_MAX_WORDS * 2]; 1072 | uECC_word_t _private[uECC_MAX_WORDS]; 1073 | 1074 | uECC_word_t tmp[uECC_MAX_WORDS]; 1075 | uECC_word_t * p2[2] = { _private, tmp }; 1076 | uECC_word_t * initial_Z = 0; 1077 | uECC_word_t carry; 1078 | wordcount_t num_words = curve->num_words; 1079 | wordcount_t num_bytes = curve->num_bytes; 1080 | 1081 | uECC_vli_bytesToNative(_private, private_key, BITS_TO_BYTES(curve->num_n_bits)); 1082 | uECC_vli_bytesToNative(_public, public_key, num_bytes); 1083 | uECC_vli_bytesToNative(_public + num_words, public_key + num_bytes, num_bytes); 1084 | 1085 | /* Regularize the bitcount for the private key so that attackers cannot use a side channel 1086 | attack to learn the number of leading zeros. */ 1087 | carry = regularize_k(_private, _private, tmp, curve); 1088 | 1089 | /* If an RNG function was specified, try to get a random initial Z value to improve 1090 | protection against side-channel attacks. */ 1091 | if (g_rng_function) 1092 | { 1093 | if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) 1094 | { 1095 | return 0; 1096 | } 1097 | initial_Z = p2[carry]; 1098 | } 1099 | 1100 | EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1, curve); 1101 | 1102 | uECC_vli_nativeToBytes(secret, num_bytes, _public); 1103 | return !EccPoint_isZero(_public, curve); 1104 | } 1105 | 1106 | int uECC_shared_secret(const uint8_t * public_key, const uint8_t * private_key, uint8_t * secret, uECC_Curve curve) 1107 | { 1108 | uECC_word_t _public[uECC_MAX_WORDS * 2]; 1109 | uECC_word_t _private[uECC_MAX_WORDS]; 1110 | 1111 | uECC_word_t tmp[uECC_MAX_WORDS]; 1112 | uECC_word_t * p2[2] = { _private, tmp }; 1113 | uECC_word_t * initial_Z = 0; 1114 | uECC_word_t carry; 1115 | wordcount_t num_words = curve->num_words; 1116 | wordcount_t num_bytes = curve->num_bytes; 1117 | 1118 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1119 | __bocpy((uint8_t *) _private, private_key, num_bytes); 1120 | __bocpy((uint8_t *) _public, public_key, num_bytes * 2); 1121 | #else 1122 | uECC_vli_bytesToNative(_private, private_key, BITS_TO_BYTES(curve->num_n_bits)); 1123 | uECC_vli_bytesToNative(_public, public_key, num_bytes); 1124 | uECC_vli_bytesToNative(_public + num_words, public_key + num_bytes, num_bytes); 1125 | #endif 1126 | 1127 | /* Regularize the bitcount for the private key so that attackers cannot use a side channel 1128 | attack to learn the number of leading zeros. */ 1129 | carry = regularize_k(_private, _private, tmp, curve); 1130 | 1131 | /* If an RNG function was specified, try to get a random initial Z value to improve 1132 | protection against side-channel attacks. */ 1133 | if (g_rng_function) 1134 | { 1135 | if (!uECC_generate_random_int(p2[carry], curve->p, num_words)) 1136 | { 1137 | return 0; 1138 | } 1139 | initial_Z = p2[carry]; 1140 | } 1141 | 1142 | EccPoint_mult(_public, _public, p2[!carry], initial_Z, curve->num_n_bits + 1, curve); 1143 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1144 | __bocpy((uint8_t *) secret, (uint8_t *) _public, num_bytes); 1145 | #else 1146 | uECC_vli_nativeToBytes(secret, num_bytes, _public); 1147 | #endif 1148 | return !EccPoint_isZero(_public, curve); 1149 | } 1150 | 1151 | #if uECC_SUPPORT_COMPRESSED_POINT 1152 | void uECC_compress(const uint8_t * public_key, uint8_t * compressed, uECC_Curve curve) 1153 | { 1154 | wordcount_t i; 1155 | for (i = 0; i < curve->num_bytes; ++i) 1156 | { 1157 | compressed[i + 1] = public_key[i]; 1158 | } 1159 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1160 | compressed[0] = 2 + (public_key[curve->num_bytes] & 0x01); 1161 | #else 1162 | compressed[0] = 2 + (public_key[curve->num_bytes * 2 - 1] & 0x01); 1163 | #endif 1164 | } 1165 | 1166 | void uECC_decompress(const uint8_t * compressed, uint8_t * public_key, uECC_Curve curve) 1167 | { 1168 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1169 | uECC_word_t * point = (uECC_word_t *) public_key; 1170 | #else 1171 | uECC_word_t point[uECC_MAX_WORDS * 2]; 1172 | #endif 1173 | uECC_word_t * y = point + curve->num_words; 1174 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1175 | __bocpy(public_key, compressed + 1, curve->num_bytes); 1176 | #else 1177 | uECC_vli_bytesToNative(point, compressed + 1, curve->num_bytes); 1178 | #endif 1179 | curve->x_side(y, point, curve); 1180 | curve->mod_sqrt(y, curve); 1181 | 1182 | if ((y[0] & 0x01) != (compressed[0] & 0x01)) 1183 | { 1184 | uECC_vli_sub(y, curve->p, y, curve->num_words); 1185 | } 1186 | 1187 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0 1188 | uECC_vli_nativeToBytes(public_key, curve->num_bytes, point); 1189 | uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, y); 1190 | #endif 1191 | } 1192 | #endif /* uECC_SUPPORT_COMPRESSED_POINT */ 1193 | 1194 | int uECC_valid_point(const uECC_word_t * point, uECC_Curve curve) 1195 | { 1196 | uECC_word_t tmp1[uECC_MAX_WORDS]; 1197 | uECC_word_t tmp2[uECC_MAX_WORDS]; 1198 | wordcount_t num_words = curve->num_words; 1199 | 1200 | /* The point at infinity is invalid. */ 1201 | if (EccPoint_isZero(point, curve)) 1202 | { 1203 | return 0; 1204 | } 1205 | 1206 | /* x and y must be smaller than p. */ 1207 | if (uECC_vli_cmp_unsafe(curve->p, point, num_words) != 1 || uECC_vli_cmp_unsafe(curve->p, point + num_words, num_words) != 1) 1208 | { 1209 | return 0; 1210 | } 1211 | 1212 | uECC_vli_modSquare_fast(tmp1, point + num_words, curve); 1213 | curve->x_side(tmp2, point, curve); /* tmp2 = x^3 + ax + b */ 1214 | 1215 | /* Make sure that y^2 == x^3 + ax + b */ 1216 | return (int) (uECC_vli_equal(tmp1, tmp2, num_words)); 1217 | } 1218 | 1219 | int uECC_valid_public_key(const uint8_t * public_key, uECC_Curve curve) 1220 | { 1221 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1222 | uECC_word_t * _public = (uECC_word_t *) public_key; 1223 | #else 1224 | uECC_word_t _public[uECC_MAX_WORDS * 2]; 1225 | #endif 1226 | 1227 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0 1228 | uECC_vli_bytesToNative(_public, public_key, curve->num_bytes); 1229 | uECC_vli_bytesToNative(_public + curve->num_words, public_key + curve->num_bytes, curve->num_bytes); 1230 | #endif 1231 | return uECC_valid_point(_public, curve); 1232 | } 1233 | 1234 | int uECC_compute_public_key(const uint8_t * private_key, uint8_t * public_key, uECC_Curve curve) 1235 | { 1236 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1237 | uECC_word_t * _private = (uECC_word_t *) private_key; 1238 | uECC_word_t * _public = (uECC_word_t *) public_key; 1239 | #else 1240 | uECC_word_t _private[uECC_MAX_WORDS]; 1241 | uECC_word_t _public[uECC_MAX_WORDS * 2]; 1242 | #endif 1243 | 1244 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0 1245 | uECC_vli_bytesToNative(_private, private_key, BITS_TO_BYTES(curve->num_n_bits)); 1246 | #endif 1247 | 1248 | /* Make sure the private key is in the range [1, n-1]. */ 1249 | if (uECC_vli_isZero(_private, BITS_TO_WORDS(curve->num_n_bits))) 1250 | { 1251 | return 0; 1252 | } 1253 | 1254 | if (uECC_vli_cmp(curve->n, _private, BITS_TO_WORDS(curve->num_n_bits)) != 1) 1255 | { 1256 | return 0; 1257 | } 1258 | 1259 | /* Compute public key. */ 1260 | if (!EccPoint_compute_public_key(_public, _private, curve)) 1261 | { 1262 | return 0; 1263 | } 1264 | 1265 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0 1266 | uECC_vli_nativeToBytes(public_key, curve->num_bytes, _public); 1267 | uECC_vli_nativeToBytes(public_key + curve->num_bytes, curve->num_bytes, _public + curve->num_words); 1268 | #endif 1269 | return 1; 1270 | } 1271 | 1272 | /* -------- ECDSA code -------- */ 1273 | 1274 | static void bits2int(uECC_word_t * native, const uint8_t * bits, unsigned bits_size, uECC_Curve curve) 1275 | { 1276 | unsigned num_n_bytes = BITS_TO_BYTES(curve->num_n_bits); 1277 | unsigned num_n_words = BITS_TO_WORDS(curve->num_n_bits); 1278 | int shift; 1279 | uECC_word_t carry; 1280 | uECC_word_t * ptr; 1281 | 1282 | if (bits_size > num_n_bytes) 1283 | { 1284 | bits_size = num_n_bytes; 1285 | } 1286 | 1287 | uECC_vli_clear(native, num_n_words); 1288 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1289 | __bocpy((uint8_t *) native, bits, bits_size); 1290 | #else 1291 | uECC_vli_bytesToNative(native, bits, bits_size); 1292 | #endif 1293 | if (bits_size * 8 <= (unsigned) curve->num_n_bits) 1294 | { 1295 | return; 1296 | } 1297 | shift = bits_size * 8 - curve->num_n_bits; 1298 | carry = 0; 1299 | ptr = native + num_n_words; 1300 | while (ptr-- > native) 1301 | { 1302 | uECC_word_t temp = *ptr; 1303 | *ptr = (temp >> shift) | carry; 1304 | carry = temp << (uECC_WORD_BITS - shift); 1305 | } 1306 | 1307 | /* Reduce mod curve_n */ 1308 | if (uECC_vli_cmp_unsafe(curve->n, native, num_n_words) != 1) 1309 | { 1310 | uECC_vli_sub(native, native, curve->n, num_n_words); 1311 | } 1312 | } 1313 | 1314 | static int uECC_sign_with_k(const uint8_t * private_key, const uint8_t * message_hash, unsigned hash_size, uECC_word_t * k, uint8_t * signature, uECC_Curve curve) 1315 | { 1316 | 1317 | uECC_word_t tmp[uECC_MAX_WORDS]; 1318 | uECC_word_t s[uECC_MAX_WORDS]; 1319 | uECC_word_t * k2[2] = { tmp, s }; 1320 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1321 | uECC_word_t * p = (uECC_word_t *) signature; 1322 | #else 1323 | uECC_word_t p[uECC_MAX_WORDS * 2]; 1324 | #endif 1325 | uECC_word_t carry; 1326 | wordcount_t num_words = curve->num_words; 1327 | wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); 1328 | bitcount_t num_n_bits = curve->num_n_bits; 1329 | 1330 | /* Make sure 0 < k < curve_n */ 1331 | if (uECC_vli_isZero(k, num_words) || uECC_vli_cmp(curve->n, k, num_n_words) != 1) 1332 | { 1333 | return 0; 1334 | } 1335 | 1336 | carry = regularize_k(k, tmp, s, curve); 1337 | EccPoint_mult(p, curve->G, k2[!carry], 0, num_n_bits + 1, curve); 1338 | if (uECC_vli_isZero(p, num_words)) 1339 | { 1340 | return 0; 1341 | } 1342 | 1343 | /* If an RNG function was specified, get a random number 1344 | to prevent side channel analysis of k. */ 1345 | if (!g_rng_function) 1346 | { 1347 | uECC_vli_clear(tmp, num_n_words); 1348 | tmp[0] = 1; 1349 | } 1350 | else if (!uECC_generate_random_int(tmp, curve->n, num_n_words)) 1351 | { 1352 | return 0; 1353 | } 1354 | 1355 | /* Prevent side channel analysis of uECC_vli_modInv() to determine 1356 | bits of k / the private key by premultiplying by a random number */ 1357 | uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k' = rand * k */ 1358 | uECC_vli_modInv(k, k, curve->n, num_n_words); /* k = 1 / k' */ 1359 | uECC_vli_modMult(k, k, tmp, curve->n, num_n_words); /* k = 1 / k */ 1360 | 1361 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN == 0 1362 | uECC_vli_nativeToBytes(signature, curve->num_bytes, p); /* store r */ 1363 | #endif 1364 | 1365 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1366 | __bocpy((uint8_t *) tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); 1367 | #else 1368 | uECC_vli_bytesToNative(tmp, private_key, BITS_TO_BYTES(curve->num_n_bits)); /* tmp = d */ 1369 | #endif 1370 | 1371 | s[num_n_words - 1] = 0; 1372 | uECC_vli_set(s, p, num_words); 1373 | uECC_vli_modMult(s, tmp, s, curve->n, num_n_words); /* s = r*d */ 1374 | 1375 | bits2int(tmp, message_hash, hash_size, curve); 1376 | uECC_vli_modAdd(s, tmp, s, curve->n, num_n_words); /* s = e + r*d */ 1377 | uECC_vli_modMult(s, s, k, curve->n, num_n_words); /* s = (e + r*d) / k */ 1378 | if (uECC_vli_numBits(s, num_n_words) > (bitcount_t) curve->num_bytes * 8) 1379 | { 1380 | return 0; 1381 | } 1382 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1383 | __bocpy((uint8_t *) signature + curve->num_bytes, (uint8_t *) s, curve->num_bytes); 1384 | #else 1385 | uECC_vli_nativeToBytes(signature + curve->num_bytes, curve->num_bytes, s); 1386 | #endif 1387 | return 1; 1388 | } 1389 | 1390 | int uECC_sign(const uint8_t * private_key, const uint8_t * message_hash, unsigned hash_size, uint8_t * signature, uECC_Curve curve) 1391 | { 1392 | uECC_word_t k[uECC_MAX_WORDS]; 1393 | uECC_word_t tries; 1394 | 1395 | for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) 1396 | { 1397 | if (!uECC_generate_random_int(k, curve->n, BITS_TO_WORDS(curve->num_n_bits))) 1398 | { 1399 | return 0; 1400 | } 1401 | 1402 | if (uECC_sign_with_k(private_key, message_hash, hash_size, k, signature, curve)) 1403 | { 1404 | return 1; 1405 | } 1406 | } 1407 | return 0; 1408 | } 1409 | 1410 | /* Compute an HMAC using K as a key (as in RFC 6979). Note that K is always 1411 | the same size as the hash result size. */ 1412 | static void HMAC_init(const uECC_HashContext * hash_context, const uint8_t * K) 1413 | { 1414 | uint8_t * pad = hash_context->tmp + 2 * hash_context->result_size; 1415 | unsigned i; 1416 | for (i = 0; i < hash_context->result_size; ++i) 1417 | pad[i] = K[i] ^ 0x36; 1418 | for (; i < hash_context->block_size; ++i) 1419 | pad[i] = 0x36; 1420 | 1421 | hash_context->init_hash(hash_context); 1422 | hash_context->update_hash(hash_context, pad, hash_context->block_size); 1423 | } 1424 | 1425 | static void HMAC_update(const uECC_HashContext * hash_context, const uint8_t * message, unsigned message_size) 1426 | { 1427 | hash_context->update_hash(hash_context, message, message_size); 1428 | } 1429 | 1430 | static void HMAC_finish(const uECC_HashContext * hash_context, const uint8_t * K, uint8_t * result) 1431 | { 1432 | uint8_t * pad = hash_context->tmp + 2 * hash_context->result_size; 1433 | unsigned i; 1434 | for (i = 0; i < hash_context->result_size; ++i) 1435 | pad[i] = K[i] ^ 0x5c; 1436 | for (; i < hash_context->block_size; ++i) 1437 | pad[i] = 0x5c; 1438 | 1439 | hash_context->finish_hash(hash_context, result); 1440 | 1441 | hash_context->init_hash(hash_context); 1442 | hash_context->update_hash(hash_context, pad, hash_context->block_size); 1443 | hash_context->update_hash(hash_context, result, hash_context->result_size); 1444 | hash_context->finish_hash(hash_context, result); 1445 | } 1446 | 1447 | /* V = HMAC_K(V) */ 1448 | static void update_V(const uECC_HashContext * hash_context, uint8_t * K, uint8_t * V) 1449 | { 1450 | HMAC_init(hash_context, K); 1451 | HMAC_update(hash_context, V, hash_context->result_size); 1452 | HMAC_finish(hash_context, K, V); 1453 | } 1454 | 1455 | /* Deterministic signing, similar to RFC 6979. Differences are: 1456 | * We just use H(m) directly rather than bits2octets(H(m)) 1457 | (it is not reduced modulo curve_n). 1458 | * We generate a value for k (aka T) directly rather than converting endianness. 1459 | 1460 | Layout of hash_context->tmp: | | (1 byte overlapped 0x00 or 0x01) / */ 1461 | int uECC_sign_deterministic(const uint8_t * private_key, const uint8_t * message_hash, unsigned hash_size, const uECC_HashContext * hash_context, uint8_t * signature, uECC_Curve curve) 1462 | { 1463 | uint8_t * K = hash_context->tmp; 1464 | uint8_t * V = K + hash_context->result_size; 1465 | wordcount_t num_bytes = curve->num_bytes; 1466 | wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); 1467 | bitcount_t num_n_bits = curve->num_n_bits; 1468 | uECC_word_t tries; 1469 | unsigned i; 1470 | for (i = 0; i < hash_context->result_size; ++i) 1471 | { 1472 | V[i] = 0x01; 1473 | K[i] = 0; 1474 | } 1475 | 1476 | /* K = HMAC_K(V || 0x00 || int2octets(x) || h(m)) */ 1477 | HMAC_init(hash_context, K); 1478 | V[hash_context->result_size] = 0x00; 1479 | HMAC_update(hash_context, V, hash_context->result_size + 1); 1480 | HMAC_update(hash_context, private_key, num_bytes); 1481 | HMAC_update(hash_context, message_hash, hash_size); 1482 | HMAC_finish(hash_context, K, K); 1483 | 1484 | update_V(hash_context, K, V); 1485 | 1486 | /* K = HMAC_K(V || 0x01 || int2octets(x) || h(m)) */ 1487 | HMAC_init(hash_context, K); 1488 | V[hash_context->result_size] = 0x01; 1489 | HMAC_update(hash_context, V, hash_context->result_size + 1); 1490 | HMAC_update(hash_context, private_key, num_bytes); 1491 | HMAC_update(hash_context, message_hash, hash_size); 1492 | HMAC_finish(hash_context, K, K); 1493 | 1494 | update_V(hash_context, K, V); 1495 | 1496 | for (tries = 0; tries < uECC_RNG_MAX_TRIES; ++tries) 1497 | { 1498 | uECC_word_t T[uECC_MAX_WORDS]; 1499 | uint8_t * T_ptr = (uint8_t *) T; 1500 | wordcount_t T_bytes = 0; 1501 | for (;;) 1502 | { 1503 | update_V(hash_context, K, V); 1504 | for (i = 0; i < hash_context->result_size; ++i) 1505 | { 1506 | T_ptr[T_bytes++] = V[i]; 1507 | if (T_bytes >= num_n_words * uECC_WORD_SIZE) 1508 | { 1509 | goto filled; 1510 | } 1511 | } 1512 | } 1513 | filled: 1514 | if ((bitcount_t) num_n_words * uECC_WORD_SIZE * 8 > num_n_bits) 1515 | { 1516 | uECC_word_t mask = (uECC_word_t) -1; 1517 | T[num_n_words - 1] &= mask >> ((bitcount_t) (num_n_words * uECC_WORD_SIZE * 8 - num_n_bits)); 1518 | } 1519 | 1520 | if (uECC_sign_with_k(private_key, message_hash, hash_size, T, signature, curve)) 1521 | { 1522 | return 1; 1523 | } 1524 | 1525 | /* K = HMAC_K(V || 0x00) */ 1526 | HMAC_init(hash_context, K); 1527 | V[hash_context->result_size] = 0x00; 1528 | HMAC_update(hash_context, V, hash_context->result_size + 1); 1529 | HMAC_finish(hash_context, K, K); 1530 | 1531 | update_V(hash_context, K, V); 1532 | } 1533 | return 0; 1534 | } 1535 | 1536 | static bitcount_t smax(bitcount_t a, bitcount_t b) 1537 | { 1538 | return (a > b ? a : b); 1539 | } 1540 | 1541 | int uECC_verify(const uint8_t * public_key, const uint8_t * message_hash, unsigned hash_size, const uint8_t * signature, uECC_Curve curve) 1542 | { 1543 | uECC_word_t u1[uECC_MAX_WORDS], u2[uECC_MAX_WORDS]; 1544 | uECC_word_t z[uECC_MAX_WORDS]; 1545 | uECC_word_t sum[uECC_MAX_WORDS * 2]; 1546 | uECC_word_t rx[uECC_MAX_WORDS]; 1547 | uECC_word_t ry[uECC_MAX_WORDS]; 1548 | uECC_word_t tx[uECC_MAX_WORDS]; 1549 | uECC_word_t ty[uECC_MAX_WORDS]; 1550 | uECC_word_t tz[uECC_MAX_WORDS]; 1551 | const uECC_word_t * points[4]; 1552 | const uECC_word_t * point; 1553 | bitcount_t num_bits; 1554 | bitcount_t i; 1555 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1556 | uECC_word_t * _public = (uECC_word_t *) public_key; 1557 | #else 1558 | uECC_word_t _public[uECC_MAX_WORDS * 2]; 1559 | #endif 1560 | uECC_word_t r[uECC_MAX_WORDS], s[uECC_MAX_WORDS]; 1561 | wordcount_t num_words = curve->num_words; 1562 | wordcount_t num_n_words = BITS_TO_WORDS(curve->num_n_bits); 1563 | 1564 | rx[num_n_words - 1] = 0; 1565 | r[num_n_words - 1] = 0; 1566 | s[num_n_words - 1] = 0; 1567 | 1568 | #if uECC_VLI_NATIVE_LITTLE_ENDIAN 1569 | __bocpy((uint8_t *) r, signature, curve->num_bytes); 1570 | __bocpy((uint8_t *) s, signature + curve->num_bytes, curve->num_bytes); 1571 | #else 1572 | uECC_vli_bytesToNative(_public, public_key, curve->num_bytes); 1573 | uECC_vli_bytesToNative(_public + num_words, public_key + curve->num_bytes, curve->num_bytes); 1574 | uECC_vli_bytesToNative(r, signature, curve->num_bytes); 1575 | uECC_vli_bytesToNative(s, signature + curve->num_bytes, curve->num_bytes); 1576 | #endif 1577 | 1578 | /* r, s must not be 0. */ 1579 | if (uECC_vli_isZero(r, num_words) || uECC_vli_isZero(s, num_words)) 1580 | { 1581 | return 0; 1582 | } 1583 | 1584 | /* r, s must be < n. */ 1585 | if (uECC_vli_cmp_unsafe(curve->n, r, num_n_words) != 1 || uECC_vli_cmp_unsafe(curve->n, s, num_n_words) != 1) 1586 | { 1587 | return 0; 1588 | } 1589 | 1590 | /* Calculate u1 and u2. */ 1591 | uECC_vli_modInv(z, s, curve->n, num_n_words); /* z = 1/s */ 1592 | u1[num_n_words - 1] = 0; 1593 | bits2int(u1, message_hash, hash_size, curve); 1594 | uECC_vli_modMult(u1, u1, z, curve->n, num_n_words); /* u1 = e/s */ 1595 | uECC_vli_modMult(u2, r, z, curve->n, num_n_words); /* u2 = r/s */ 1596 | 1597 | /* Calculate sum = G + Q. */ 1598 | uECC_vli_set(sum, _public, num_words); 1599 | uECC_vli_set(sum + num_words, _public + num_words, num_words); 1600 | uECC_vli_set(tx, curve->G, num_words); 1601 | uECC_vli_set(ty, curve->G + num_words, num_words); 1602 | uECC_vli_modSub(z, sum, tx, curve->p, num_words); /* z = x2 - x1 */ 1603 | XYcZ_add(tx, ty, sum, sum + num_words, curve); 1604 | uECC_vli_modInv(z, z, curve->p, num_words); /* z = 1/z */ 1605 | apply_z(sum, sum + num_words, z, curve); 1606 | 1607 | /* Use Shamir's trick to calculate u1*G + u2*Q */ 1608 | points[0] = 0; 1609 | points[1] = curve->G; 1610 | points[2] = _public; 1611 | points[3] = sum; 1612 | num_bits = smax(uECC_vli_numBits(u1, num_n_words), uECC_vli_numBits(u2, num_n_words)); 1613 | 1614 | point = points[(!!uECC_vli_testBit(u1, num_bits - 1)) | ((!!uECC_vli_testBit(u2, num_bits - 1)) << 1)]; 1615 | uECC_vli_set(rx, point, num_words); 1616 | uECC_vli_set(ry, point + num_words, num_words); 1617 | uECC_vli_clear(z, num_words); 1618 | z[0] = 1; 1619 | 1620 | for (i = num_bits - 2; i >= 0; --i) 1621 | { 1622 | uECC_word_t index; 1623 | curve->double_jacobian(rx, ry, z, curve); 1624 | 1625 | index = (!!uECC_vli_testBit(u1, i)) | ((!!uECC_vli_testBit(u2, i)) << 1); 1626 | point = points[index]; 1627 | if (point) 1628 | { 1629 | uECC_vli_set(tx, point, num_words); 1630 | uECC_vli_set(ty, point + num_words, num_words); 1631 | apply_z(tx, ty, z, curve); 1632 | uECC_vli_modSub(tz, rx, tx, curve->p, num_words); /* Z = x2 - x1 */ 1633 | XYcZ_add(tx, ty, rx, ry, curve); 1634 | uECC_vli_modMult_fast(z, z, tz, curve); 1635 | } 1636 | } 1637 | 1638 | uECC_vli_modInv(z, z, curve->p, num_words); /* Z = 1/Z */ 1639 | apply_z(rx, ry, z, curve); 1640 | 1641 | /* v = x1 (mod n) */ 1642 | if (uECC_vli_cmp_unsafe(curve->n, rx, num_n_words) != 1) 1643 | { 1644 | uECC_vli_sub(rx, rx, curve->n, num_n_words); 1645 | } 1646 | 1647 | /* Accept only if v == r. */ 1648 | return (int) (uECC_vli_equal(rx, r, num_words)); 1649 | } 1650 | 1651 | #if uECC_ENABLE_VLI_API 1652 | 1653 | unsigned uECC_curve_num_words(uECC_Curve curve) 1654 | { 1655 | return curve->num_words; 1656 | } 1657 | 1658 | unsigned uECC_curve_num_bytes(uECC_Curve curve) 1659 | { 1660 | return curve->num_bytes; 1661 | } 1662 | 1663 | unsigned uECC_curve_num_bits(uECC_Curve curve) 1664 | { 1665 | return curve->num_bytes * 8; 1666 | } 1667 | 1668 | unsigned uECC_curve_num_n_words(uECC_Curve curve) 1669 | { 1670 | return BITS_TO_WORDS(curve->num_n_bits); 1671 | } 1672 | 1673 | unsigned uECC_curve_num_n_bytes(uECC_Curve curve) 1674 | { 1675 | return BITS_TO_BYTES(curve->num_n_bits); 1676 | } 1677 | 1678 | unsigned uECC_curve_num_n_bits(uECC_Curve curve) 1679 | { 1680 | return curve->num_n_bits; 1681 | } 1682 | 1683 | const uECC_word_t * uECC_curve_p(uECC_Curve curve) 1684 | { 1685 | return curve->p; 1686 | } 1687 | 1688 | const uECC_word_t * uECC_curve_n(uECC_Curve curve) 1689 | { 1690 | return curve->n; 1691 | } 1692 | 1693 | const uECC_word_t * uECC_curve_G(uECC_Curve curve) 1694 | { 1695 | return curve->G; 1696 | } 1697 | 1698 | const uECC_word_t * uECC_curve_b(uECC_Curve curve) 1699 | { 1700 | return curve->b; 1701 | } 1702 | 1703 | #if uECC_SUPPORT_COMPRESSED_POINT 1704 | void uECC_vli_mod_sqrt(uECC_word_t * a, uECC_Curve curve) 1705 | { 1706 | curve->mod_sqrt(a, curve); 1707 | } 1708 | #endif 1709 | 1710 | void uECC_vli_mmod_fast(uECC_word_t * result, uECC_word_t * product, uECC_Curve curve) 1711 | { 1712 | #if (uECC_OPTIMIZATION_LEVEL > 0) 1713 | curve->mmod_fast(result, product); 1714 | #else 1715 | uECC_vli_mmod(result, product, curve->p, curve->num_words); 1716 | #endif 1717 | } 1718 | 1719 | void uECC_point_mult(uECC_word_t * result, const uECC_word_t * point, const uECC_word_t * scalar, uECC_Curve curve) 1720 | { 1721 | uECC_word_t tmp1[uECC_MAX_WORDS]; 1722 | uECC_word_t tmp2[uECC_MAX_WORDS]; 1723 | uECC_word_t * p2[2] = { tmp1, tmp2 }; 1724 | uECC_word_t carry = regularize_k(scalar, tmp1, tmp2, curve); 1725 | 1726 | EccPoint_mult(result, point, p2[!carry], 0, curve->num_n_bits + 1, curve); 1727 | } 1728 | 1729 | #endif /* uECC_ENABLE_VLI_API */ 1730 | --------------------------------------------------------------------------------