aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorLibravatar vnugent <public@vaughnnugent.com>2024-01-28 19:23:18 -0500
committerLibravatar vnugent <public@vaughnnugent.com>2024-01-28 19:23:18 -0500
commit626a8d8d3df8880991684d6d1a06b82f6685b51a (patch)
tree183c981ac44886445240ad1e1945f325ceaa9298
initial commit
-rw-r--r--.gitattributes63
-rw-r--r--.gitignore369
-rw-r--r--CMakeLists.txt143
-rw-r--r--CMakePresets.json61
-rw-r--r--LICENSE293
-rw-r--r--Module.Taskfile.yaml45
-rw-r--r--README.md96
-rw-r--r--Taskfile.yaml78
-rw-r--r--include/mbedtls/aes.h627
-rw-r--r--include/mbedtls/aria.h341
-rw-r--r--include/mbedtls/asn1.h641
-rw-r--r--include/mbedtls/asn1write.h389
-rw-r--r--include/mbedtls/base64.h82
-rw-r--r--include/mbedtls/bignum.h1084
-rw-r--r--include/mbedtls/build_info.h146
-rw-r--r--include/mbedtls/camellia.h303
-rw-r--r--include/mbedtls/ccm.h518
-rw-r--r--include/mbedtls/chacha20.h202
-rw-r--r--include/mbedtls/chachapoly.h342
-rw-r--r--include/mbedtls/check_config.h1206
-rw-r--r--include/mbedtls/cipher.h1183
-rw-r--r--include/mbedtls/cmac.h246
-rw-r--r--include/mbedtls/compat-2.x.h46
-rw-r--r--include/mbedtls/config_adjust_legacy_crypto.h183
-rw-r--r--include/mbedtls/config_adjust_legacy_from_psa.h877
-rw-r--r--include/mbedtls/config_adjust_psa_from_legacy.h334
-rw-r--r--include/mbedtls/config_adjust_psa_superset_legacy.h142
-rw-r--r--include/mbedtls/config_adjust_ssl.h76
-rw-r--r--include/mbedtls/config_adjust_x509.h25
-rw-r--r--include/mbedtls/config_psa.h55
-rw-r--r--include/mbedtls/constant_time.h36
-rw-r--r--include/mbedtls/ctr_drbg.h564
-rw-r--r--include/mbedtls/debug.h308
-rw-r--r--include/mbedtls/des.h385
-rw-r--r--include/mbedtls/dhm.h972
-rw-r--r--include/mbedtls/ecdh.h441
-rw-r--r--include/mbedtls/ecdsa.h671
-rw-r--r--include/mbedtls/ecjpake.h298
-rw-r--r--include/mbedtls/ecp.h1362
-rw-r--r--include/mbedtls/entropy.h273
-rw-r--r--include/mbedtls/error.h201
-rw-r--r--include/mbedtls/gcm.h370
-rw-r--r--include/mbedtls/hkdf.h124
-rw-r--r--include/mbedtls/hmac_drbg.h434
-rw-r--r--include/mbedtls/lms.h440
-rw-r--r--include/mbedtls/mbedtls_config.h4116
-rw-r--r--include/mbedtls/md.h640
-rw-r--r--include/mbedtls/md5.h190
-rw-r--r--include/mbedtls/memory_buffer_alloc.h142
-rw-r--r--include/mbedtls/net_sockets.h299
-rw-r--r--include/mbedtls/nist_kw.h166
-rw-r--r--include/mbedtls/oid.h722
-rw-r--r--include/mbedtls/pem.h160
-rw-r--r--include/mbedtls/pk.h1091
-rw-r--r--include/mbedtls/pkcs12.h186
-rw-r--r--include/mbedtls/pkcs5.h197
-rw-r--r--include/mbedtls/pkcs7.h241
-rw-r--r--include/mbedtls/platform.h485
-rw-r--r--include/mbedtls/platform_time.h79
-rw-r--r--include/mbedtls/platform_util.h201
-rw-r--r--include/mbedtls/poly1305.h168
-rw-r--r--include/mbedtls/private_access.h20
-rw-r--r--include/mbedtls/psa_util.h104
-rw-r--r--include/mbedtls/ripemd160.h136
-rw-r--r--include/mbedtls/rsa.h1152
-rw-r--r--include/mbedtls/sha1.h219
-rw-r--r--include/mbedtls/sha256.h198
-rw-r--r--include/mbedtls/sha3.h172
-rw-r--r--include/mbedtls/sha512.h208
-rw-r--r--include/mbedtls/ssl.h5369
-rw-r--r--include/mbedtls/ssl_cache.h187
-rw-r--r--include/mbedtls/ssl_ciphersuites.h616
-rw-r--r--include/mbedtls/ssl_cookie.h106
-rw-r--r--include/mbedtls/ssl_ticket.h181
-rw-r--r--include/mbedtls/threading.h105
-rw-r--r--include/mbedtls/timing.h94
-rw-r--r--include/mbedtls/version.h78
-rw-r--r--include/mbedtls/x509.h550
-rw-r--r--include/mbedtls/x509_crl.h184
-rw-r--r--include/mbedtls/x509_crt.h1196
-rw-r--r--include/mbedtls/x509_csr.h319
-rw-r--r--include/psa/build_info.h20
-rw-r--r--include/psa/crypto.h4685
-rw-r--r--include/psa/crypto_adjust_auto_enabled.h21
-rw-r--r--include/psa/crypto_adjust_config_key_pair_types.h91
-rw-r--r--include/psa/crypto_adjust_config_synonyms.h45
-rw-r--r--include/psa/crypto_builtin_composites.h210
-rw-r--r--include/psa/crypto_builtin_key_derivation.h118
-rw-r--r--include/psa/crypto_builtin_primitives.h114
-rw-r--r--include/psa/crypto_compat.h153
-rw-r--r--include/psa/crypto_config.h153
-rw-r--r--include/psa/crypto_driver_common.h44
-rw-r--r--include/psa/crypto_driver_contexts_composites.h151
-rw-r--r--include/psa/crypto_driver_contexts_key_derivation.h52
-rw-r--r--include/psa/crypto_driver_contexts_primitives.h105
-rw-r--r--include/psa/crypto_extra.h2064
-rw-r--r--include/psa/crypto_legacy.h88
-rw-r--r--include/psa/crypto_platform.h92
-rw-r--r--include/psa/crypto_se_driver.h1383
-rw-r--r--include/psa/crypto_sizes.h1282
-rw-r--r--include/psa/crypto_struct.h460
-rw-r--r--include/psa/crypto_types.h453
-rw-r--r--include/psa/crypto_values.h2763
-rw-r--r--include/secp256k1.h909
-rw-r--r--include/secp256k1_ecdh.h63
-rw-r--r--include/secp256k1_extrakeys.h247
-rw-r--r--include/secp256k1_schnorrsig.h190
-rw-r--r--noscrypt.build.sln14
-rw-r--r--package.json10
-rw-r--r--src/noscrypt.c865
-rw-r--r--src/noscrypt.h514
-rw-r--r--tests/test.c170
112 files changed, 54881 insertions, 0 deletions
diff --git a/.gitattributes b/.gitattributes
new file mode 100644
index 0000000..1ff0c42
--- /dev/null
+++ b/.gitattributes
@@ -0,0 +1,63 @@
+###############################################################################
+# Set default behavior to automatically normalize line endings.
+###############################################################################
+* text=auto
+
+###############################################################################
+# Set default behavior for command prompt diff.
+#
+# This is need for earlier builds of msysgit that does not have it on by
+# default for csharp files.
+# Note: This is only used by command line
+###############################################################################
+#*.cs diff=csharp
+
+###############################################################################
+# Set the merge driver for project and solution files
+#
+# Merging from the command prompt will add diff markers to the files if there
+# are conflicts (Merging from VS is not affected by the settings below, in VS
+# the diff markers are never inserted). Diff markers may cause the following
+# file extensions to fail to load in VS. An alternative would be to treat
+# these files as binary and thus will always conflict and require user
+# intervention with every merge. To do so, just uncomment the entries below
+###############################################################################
+#*.sln merge=binary
+#*.csproj merge=binary
+#*.vbproj merge=binary
+#*.vcxproj merge=binary
+#*.vcproj merge=binary
+#*.dbproj merge=binary
+#*.fsproj merge=binary
+#*.lsproj merge=binary
+#*.wixproj merge=binary
+#*.modelproj merge=binary
+#*.sqlproj merge=binary
+#*.wwaproj merge=binary
+
+###############################################################################
+# behavior for image files
+#
+# image files are treated as binary by default.
+###############################################################################
+#*.jpg binary
+#*.png binary
+#*.gif binary
+
+###############################################################################
+# diff behavior for common document formats
+#
+# Convert binary document formats to text before diffing them. This feature
+# is only available from the command line. Turn it on by uncommenting the
+# entries below.
+###############################################################################
+#*.doc diff=astextplain
+#*.DOC diff=astextplain
+#*.docx diff=astextplain
+#*.DOCX diff=astextplain
+#*.dot diff=astextplain
+#*.DOT diff=astextplain
+#*.pdf diff=astextplain
+#*.PDF diff=astextplain
+#*.rtf diff=astextplain
+#*.RTF diff=astextplain
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..91eafca
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,369 @@
+## Ignore Visual Studio temporary files, build results, and
+## files generated by popular Visual Studio add-ons.
+##
+## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore
+
+# User-specific files
+*.rsuser
+*.suo
+*.user
+*.userosscache
+*.sln.docstates
+
+# User-specific files (MonoDevelop/Xamarin Studio)
+*.userprefs
+
+# Mono auto generated files
+mono_crash.*
+
+# Build results
+[Dd]ebug/
+[Dd]ebugPublic/
+[Rr]elease/
+[Rr]eleases/
+x64/
+x86/
+[Aa][Rr][Mm]/
+[Aa][Rr][Mm]64/
+bld/
+[Bb]in/
+[Oo]bj/
+[Ll]og/
+[Ll]ogs/
+
+# Visual Studio 2015/2017 cache/options directory
+.vs/
+# Uncomment if you have tasks that create the project's static files in wwwroot
+#wwwroot/
+
+# Visual Studio 2017 auto generated files
+Generated\ Files/
+
+# MSTest test Results
+[Tt]est[Rr]esult*/
+[Bb]uild[Ll]og.*
+
+# NUnit
+*.VisualState.xml
+TestResult.xml
+nunit-*.xml
+
+# Build Results of an ATL Project
+[Dd]ebugPS/
+[Rr]eleasePS/
+dlldata.c
+
+# Benchmark Results
+BenchmarkDotNet.Artifacts/
+
+# .NET Core
+project.lock.json
+project.fragment.lock.json
+artifacts/
+
+# StyleCop
+StyleCopReport.xml
+
+# Files built by Visual Studio
+*_i.c
+*_p.c
+*_h.h
+*.ilk
+*.meta
+*.obj
+*.iobj
+*.pch
+*.pdb
+*.ipdb
+*.pgc
+*.pgd
+*.rsp
+*.sbr
+*.tlb
+*.tli
+*.tlh
+*.tmp
+*.tmp_proj
+*_wpftmp.csproj
+*.log
+*.vspscc
+*.vssscc
+.builds
+*.pidb
+*.svclog
+*.scc
+
+# Chutzpah Test files
+_Chutzpah*
+
+# Visual C++ cache files
+ipch/
+*.aps
+*.ncb
+*.opendb
+*.opensdf
+*.sdf
+*.cachefile
+*.VC.db
+*.VC.VC.opendb
+
+# Visual Studio profiler
+*.psess
+*.vsp
+*.vspx
+*.sap
+
+# Visual Studio Trace Files
+*.e2e
+
+# TFS 2012 Local Workspace
+$tf/
+
+# Guidance Automation Toolkit
+*.gpState
+
+# ReSharper is a .NET coding add-in
+_ReSharper*/
+*.[Rr]e[Ss]harper
+*.DotSettings.user
+
+# TeamCity is a build add-in
+_TeamCity*
+
+# DotCover is a Code Coverage Tool
+*.dotCover
+
+# AxoCover is a Code Coverage Tool
+.axoCover/*
+!.axoCover/settings.json
+
+# Visual Studio code coverage results
+*.coverage
+*.coveragexml
+
+# NCrunch
+_NCrunch_*
+.*crunch*.local.xml
+nCrunchTemp_*
+
+# MightyMoose
+*.mm.*
+AutoTest.Net/
+
+# Web workbench (sass)
+.sass-cache/
+
+# Installshield output folder
+[Ee]xpress/
+
+# DocProject is a documentation generator add-in
+DocProject/buildhelp/
+DocProject/Help/*.HxT
+DocProject/Help/*.HxC
+DocProject/Help/*.hhc
+DocProject/Help/*.hhk
+DocProject/Help/*.hhp
+DocProject/Help/Html2
+DocProject/Help/html
+
+# Click-Once directory
+publish/
+
+# Publish Web Output
+*.[Pp]ublish.xml
+*.azurePubxml
+# Note: Comment the next line if you want to checkin your web deploy settings,
+# but database connection strings (with potential passwords) will be unencrypted
+*.pubxml
+*.publishproj
+
+# Microsoft Azure Web App publish settings. Comment the next line if you want to
+# checkin your Azure Web App publish settings, but sensitive information contained
+# in these scripts will be unencrypted
+PublishScripts/
+
+# NuGet Packages
+*.nupkg
+# NuGet Symbol Packages
+*.snupkg
+# The packages folder can be ignored because of Package Restore
+**/[Pp]ackages/*
+# except build/, which is used as an MSBuild target.
+!**/[Pp]ackages/build/
+# Uncomment if necessary however generally it will be regenerated when needed
+#!**/[Pp]ackages/repositories.config
+# NuGet v3's project.json files produces more ignorable files
+*.nuget.props
+*.nuget.targets
+
+# Microsoft Azure Build Output
+csx/
+*.build.csdef
+
+# Microsoft Azure Emulator
+ecf/
+rcf/
+
+# Windows Store app package directories and files
+AppPackages/
+BundleArtifacts/
+Package.StoreAssociation.xml
+_pkginfo.txt
+*.appx
+*.appxbundle
+*.appxupload
+
+# Visual Studio cache files
+# files ending in .cache can be ignored
+*.[Cc]ache
+# but keep track of directories ending in .cache
+!?*.[Cc]ache/
+
+# Others
+ClientBin/
+~$*
+*~
+*.dbmdl
+*.dbproj.schemaview
+*.jfm
+*.pfx
+*.publishsettings
+orleans.codegen.cs
+
+# Including strong name files can present a security risk
+# (https://github.com/github/gitignore/pull/2483#issue-259490424)
+#*.snk
+
+# Since there are multiple workflows, uncomment next line to ignore bower_components
+# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622)
+#bower_components/
+
+# RIA/Silverlight projects
+Generated_Code/
+
+# Backup & report files from converting an old project file
+# to a newer Visual Studio version. Backup files are not needed,
+# because we have git ;-)
+_UpgradeReport_Files/
+Backup*/
+UpgradeLog*.XML
+UpgradeLog*.htm
+ServiceFabricBackup/
+*.rptproj.bak
+
+# SQL Server files
+*.mdf
+*.ldf
+*.ndf
+
+# Business Intelligence projects
+*.rdl.data
+*.bim.layout
+*.bim_*.settings
+*.rptproj.rsuser
+*- [Bb]ackup.rdl
+*- [Bb]ackup ([0-9]).rdl
+*- [Bb]ackup ([0-9][0-9]).rdl
+
+# Microsoft Fakes
+FakesAssemblies/
+
+# GhostDoc plugin setting file
+*.GhostDoc.xml
+
+# Node.js Tools for Visual Studio
+.ntvs_analysis.dat
+node_modules/
+
+# Visual Studio 6 build log
+*.plg
+
+# Visual Studio 6 workspace options file
+*.opt
+
+# Visual Studio 6 auto-generated workspace file (contains which files were open etc.)
+*.vbw
+
+# Visual Studio LightSwitch build output
+**/*.HTMLClient/GeneratedArtifacts
+**/*.DesktopClient/GeneratedArtifacts
+**/*.DesktopClient/ModelManifest.xml
+**/*.Server/GeneratedArtifacts
+**/*.Server/ModelManifest.xml
+_Pvt_Extensions
+
+# Paket dependency manager
+.paket/paket.exe
+paket-files/
+
+# FAKE - F# Make
+.fake/
+
+# CodeRush personal settings
+.cr/personal
+
+# Python Tools for Visual Studio (PTVS)
+__pycache__/
+*.pyc
+
+# Cake - Uncomment if you are using it
+# tools/**
+# !tools/packages.config
+
+# Tabs Studio
+*.tss
+
+# Telerik's JustMock configuration file
+*.jmconfig
+
+# BizTalk build output
+*.btp.cs
+*.btm.cs
+*.odx.cs
+*.xsd.cs
+
+# OpenCover UI analysis results
+OpenCover/
+
+# Azure Stream Analytics local run output
+ASALocalRun/
+
+# MSBuild Binary and Structured Log
+*.binlog
+
+# NVidia Nsight GPU debugger configuration file
+*.nvuser
+
+# MFractors (Xamarin productivity tool) working folder
+.mfractor/
+
+# Local History for Visual Studio
+.localhistory/
+
+# BeatPulse healthcheck temp database
+healthchecksdb
+
+# Backup folder for Package Reference Convert tool in Visual Studio 2017
+MigrationBackup/
+
+# Ionide (cross platform F# VS Code tools) working folder
+.ionide/
+
+
+#no build dlls in source
+*.dll
+
+**[Ll]aunchSettings*
+
+#licenseheader vs extension files
+*.licenseheader
+
+#package config files
+**[Pp]ackages*
+
+
+*.filters
+**/build/*
+/.editorconfig
+
+**/out/* \ No newline at end of file
diff --git a/CMakeLists.txt b/CMakeLists.txt
new file mode 100644
index 0000000..3872f13
--- /dev/null
+++ b/CMakeLists.txt
@@ -0,0 +1,143 @@
+# CMakeList.txt : CMake project for noscrypt, include source and define
+# project specific logic here.
+#
+
+cmake_minimum_required (VERSION 3.10)
+
+project(noscrypt C)
+
+option(BUILD_TESTS "Build tests" TRUE)
+
+set(NOSCRYPT_SRCS
+ "src/noscrypt.c"
+)
+
+set(NOSCRYPT_HEADERS
+ "src/noscrypt.h"
+)
+
+include_directories(include)
+
+#static/shared library
+add_library(${CMAKE_PROJECT_NAME} SHARED ${NOSCRYPT_SRCS} ${NOSCRYPT_HEADERS})
+add_library(${CMAKE_PROJECT_NAME}_static STATIC ${NOSCRYPT_SRCS} ${NOSCRYPT_HEADERS})
+
+#Setup the compiler options for c90 shared library
+set(CMAKE_C_STANDARD 90)
+set(CMAKE_C_STANDARD_REQUIRED ON)
+set(CMAKE_POSITION_INDEPENDENT_CODE ON)
+
+#if debug
+add_compile_definitions($<$<CONFIG:Debug>:DEBUG>)
+
+#when building we are in libary mode, we need to export our symbols
+add_compile_definitions(NOSCRYPT_EXPORTING)
+
+#setup flags for windows compilation
+if(MSVC)
+
+ #global windows cl flags
+ add_compile_options(
+ /sdl #enable additional security checks
+ /TC #compile as c
+ /GS #buffer security check
+
+ $<$<CONFIG:Debug>:/FC> #show full path in diagnostics
+ $<$<CONFIG:Debug>:/showIncludes> #show a list of all included header files during build
+ )
+
+ #only target our project
+ target_compile_options(
+ ${CMAKE_PROJECT_NAME}
+ PRIVATE
+
+ $<$<CONFIG:Debug>:/wd4820> #disable warnings for struct padding and spectre mitigation wuen WX is enabled
+
+ #for debug configs
+ $<$<CONFIG:Debug>:/options:strict>
+ $<$<CONFIG:Debug>:/Wall> #enable all warnings
+ $<$<CONFIG:Debug>:/WX> #warnings as errors (only for our project)
+ $<$<CONFIG:Debug>:/Zi> #enable rich debug info
+ $<$<CONFIG:Debug>:/Zo>
+ )
+
+ #set build macros
+ add_compile_definitions(
+ $<$<CONFIG:DEBUG>:DEBUG>
+ $<$<CONFIG:RELEASE>:RELEASE>
+ )
+
+#configure gcc flags
+elseif(CMAKE_COMPILER_IS_GNUCC)
+
+ add_compile_options(
+ -Wextra
+ -fstack-protector
+
+ $<$<CONFIG:Debug>:-g>
+ $<$<CONFIG:Debug>:-Og>
+ $<$<CONFIG:Debug>:-Wall>
+ $<$<CONFIG:Debug>:-Werror>
+ )
+
+ #only target our project if building other 3rd party libs in current build
+ target_compile_options(
+ ${CMAKE_PROJECT_NAME}
+ PRIVATE
+ $<$<CONFIG:Debug>:-Wall>
+ $<$<CONFIG:Debug>:-pedantic>
+ )
+
+endif()
+
+# Setup secp256k1 shared libary
+unset(SECP256K1_LIB CACHE)
+
+find_library(SECP256K1_LIB
+ NAMES secp256k1 libsecp256k1 lib_secp256k1 ${}
+)
+
+if(NOT SECP256K1_LIB)
+ message(FATAL_ERROR "secp256k1 library not found on local system")
+endif()
+
+target_link_libraries(${CMAKE_PROJECT_NAME} ${SECP256K1_LIB})
+
+
+#link mbedtls and mbedcrypto shared libraries
+unset(MBEDCRYPTO_LIB CACHE)
+unset(MBEDTLS_LIB CACHE)
+
+find_library(MBEDTLS_LIB NAMES mbedtls libmbedtls)
+find_library(MBEDCRYPTO_LIB NAMES mbedcrypto libmbedcrypto)
+
+if(NOT MBEDCRYPTO_LIB)
+ message(FATAL_ERROR "mbedcrypto library not found on local system")
+endif()
+if(NOT MBEDTLS_LIB)
+ message(FATAL_ERROR "mbedtls library not found on local system")
+endif()
+
+message(STATUS "mbedtls library found at ${MBEDTLS_LIB}")
+message(STATUS "mbedcrypto library found at ${MBEDCRYPTO_LIB}")
+
+target_link_libraries(${CMAKE_PROJECT_NAME} ${MBEDCRYPTO_LIB} ${MBEDTLS_LIB})
+
+
+#TESTS
+if(BUILD_TESTS)
+
+#add test executable and link to library
+add_executable(nctest tests/test.c)
+target_link_libraries(nctest ${CMAKE_PROJECT_NAME})
+#link mbedtls crypto sahred library
+target_link_libraries(nctest ${MBEDCRYPTO_LIB} ${MBEDTLS_LIB})
+
+endif()
+
+
+# Enable Hot Reload for MSVC compilers if supported.
+if (POLICY CMP0141)
+ cmake_policy(SET CMP0141 NEW)
+ set(CMAKE_MSVC_DEBUG_INFORMATION_FORMAT "$<IF:$<AND:$<C_COMPILER_ID:MSVC>,$<CXX_COMPILER_ID:MSVC>>,$<$<CONFIG:Debug,RelWithDebInfo>:EditAndContinue>,$<$<CONFIG:Debug,RelWithDebInfo>:ProgramDatabase>>")
+endif() \ No newline at end of file
diff --git a/CMakePresets.json b/CMakePresets.json
new file mode 100644
index 0000000..8fdd10a
--- /dev/null
+++ b/CMakePresets.json
@@ -0,0 +1,61 @@
+{
+ "version": 3,
+ "configurePresets": [
+ {
+ "name": "windows-base",
+ "hidden": true,
+ "generator": "Visual Studio 17 2022",
+ "binaryDir": "${sourceDir}/out/build/${presetName}",
+ "installDir": "${sourceDir}/out/install/${presetName}",
+ "cacheVariables": {
+ "CMAKE_C_COMPILER": "cl.exe",
+ "CMAKE_CXX_COMPILER": "cl.exe"
+ },
+ "condition": {
+ "type": "equals",
+ "lhs": "${hostSystemName}",
+ "rhs": "Windows"
+ }
+ },
+ {
+ "name": "x64-debug",
+ "displayName": "x64 Debug",
+ "inherits": "windows-base",
+ "architecture": {
+ "value": "x64",
+ "strategy": "external"
+ },
+ "cacheVariables": {
+ "CMAKE_BUILD_TYPE": "Debug"
+ }
+ },
+ {
+ "name": "x64-release",
+ "displayName": "x64 Release",
+ "inherits": "x64-debug",
+ "cacheVariables": {
+ "CMAKE_BUILD_TYPE": "Release"
+ }
+ },
+ {
+ "name": "x86-debug",
+ "displayName": "x86 Debug",
+ "inherits": "windows-base",
+ "architecture": {
+ "value": "x86",
+ "strategy": "external"
+ },
+ "cacheVariables": {
+ "CMAKE_BUILD_TYPE": "Debug"
+ }
+ },
+ {
+ "name": "x86-release",
+ "displayName": "x86 Release",
+ "inherits": "x86-debug",
+ "cacheVariables": {
+ "CMAKE_BUILD_TYPE": "Release"
+ }
+ }
+ ]
+}
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..c8e62be
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,293 @@
+Copyright (c) 2024 Vaughn Nugent
+
+Contact information
+ Name: Vaughn Nugent
+ Email: vnpublic[at]proton.me
+ Website: https://www.vaughnnugent.com
+
+The software in this repository is licensed under the GNU GPL version 2.0 (or any later version).
+
+SPDX-License-Identifier: GPL-2.0-or-later
+
+License-Text:
+
+GNU GENERAL PUBLIC LICENSE
+ Version 2, June 1991
+
+ Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
+ 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+License is intended to guarantee your freedom to share and change free
+software--to make sure the software is free for all its users. This
+General Public License applies to most of the Free Software
+Foundation's software and to any other program whose authors commit to
+using it. (Some other Free Software Foundation software is covered by
+the GNU Lesser General Public License instead.) You can apply it to
+your programs, too.
+
+ When we speak of free software, we are referring to freedom, not
+price. Our General Public Licenses are designed to make sure that you
+have the freedom to distribute copies of free software (and charge for
+this service if you wish), that you receive source code or can get it
+if you want it, that you can change the software or use pieces of it
+in new free programs; and that you know you can do these things.
+
+ To protect your rights, we need to make restrictions that forbid
+anyone to deny you these rights or to ask you to surrender the rights.
+These restrictions translate to certain responsibilities for you if you
+distribute copies of the software, or if you modify it.
+
+ For example, if you distribute copies of such a program, whether
+gratis or for a fee, you must give the recipients all the rights that
+you have. You must make sure that they, too, receive or can get the
+source code. And you must show them these terms so they know their
+rights.
+
+ We protect your rights with two steps: (1) copyright the software, and
+(2) offer you this license which gives you legal permission to copy,
+distribute and/or modify the software.
+
+ Also, for each author's protection and ours, we want to make certain
+that everyone understands that there is no warranty for this free
+software. If the software is modified by someone else and passed on, we
+want its recipients to know that what they have is not the original, so
+that any problems introduced by others will not reflect on the original
+authors' reputations.
+
+ Finally, any free program is threatened constantly by software
+patents. We wish to avoid the danger that redistributors of a free
+program will individually obtain patent licenses, in effect making the
+program proprietary. To prevent this, we have made it clear that any
+patent must be licensed for everyone's free use or not licensed at all.
+
+ The precise terms and conditions for copying, distribution and
+modification follow.
+
+ GNU GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License applies to any program or other work which contains
+a notice placed by the copyright holder saying it may be distributed
+under the terms of this General Public License. The "Program", below,
+refers to any such program or work, and a "work based on the Program"
+means either the Program or any derivative work under copyright law:
+that is to say, a work containing the Program or a portion of it,
+either verbatim or with modifications and/or translated into another
+language. (Hereinafter, translation is included without limitation in
+the term "modification".) Each licensee is addressed as "you".
+
+Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running the Program is not restricted, and the output from the Program
+is covered only if its contents constitute a work based on the
+Program (independent of having been made by running the Program).
+Whether that is true depends on what the Program does.
+
+ 1. You may copy and distribute verbatim copies of the Program's
+source code as you receive it, in any medium, provided that you
+conspicuously and appropriately publish on each copy an appropriate
+copyright notice and disclaimer of warranty; keep intact all the
+notices that refer to this License and to the absence of any warranty;
+and give any other recipients of the Program a copy of this License
+along with the Program.
+
+You may charge a fee for the physical act of transferring a copy, and
+you may at your option offer warranty protection in exchange for a fee.
+
+ 2. You may modify your copy or copies of the Program or any portion
+of it, thus forming a work based on the Program, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) You must cause the modified files to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ b) You must cause any work that you distribute or publish, that in
+ whole or in part contains or is derived from the Program or any
+ part thereof, to be licensed as a whole at no charge to all third
+ parties under the terms of this License.
+
+ c) If the modified program normally reads commands interactively
+ when run, you must cause it, when started running for such
+ interactive use in the most ordinary way, to print or display an
+ announcement including an appropriate copyright notice and a
+ notice that there is no warranty (or else, saying that you provide
+ a warranty) and that users may redistribute the program under
+ these conditions, and telling the user how to view a copy of this
+ License. (Exception: if the Program itself is interactive but
+ does not normally print such an announcement, your work based on
+ the Program is not required to print an announcement.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Program,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Program, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Program.
+
+In addition, mere aggregation of another work not based on the Program
+with the Program (or with a work based on the Program) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may copy and distribute the Program (or a work based on it,
+under Section 2) in object code or executable form under the terms of
+Sections 1 and 2 above provided that you also do one of the following:
+
+ a) Accompany it with the complete corresponding machine-readable
+ source code, which must be distributed under the terms of Sections
+ 1 and 2 above on a medium customarily used for software interchange; or,
+
+ b) Accompany it with a written offer, valid for at least three
+ years, to give any third party, for a charge no more than your
+ cost of physically performing source distribution, a complete
+ machine-readable copy of the corresponding source code, to be
+ distributed under the terms of Sections 1 and 2 above on a medium
+ customarily used for software interchange; or,
+
+ c) Accompany it with the information you received as to the offer
+ to distribute corresponding source code. (This alternative is
+ allowed only for noncommercial distribution and only if you
+ received the program in object code or executable form with such
+ an offer, in accord with Subsection b above.)
+
+The source code for a work means the preferred form of the work for
+making modifications to it. For an executable work, complete source
+code means all the source code for all modules it contains, plus any
+associated interface definition files, plus the scripts used to
+control compilation and installation of the executable. However, as a
+special exception, the source code distributed need not include
+anything that is normally distributed (in either source or binary
+form) with the major components (compiler, kernel, and so on) of the
+operating system on which the executable runs, unless that component
+itself accompanies the executable.
+
+If distribution of executable or object code is made by offering
+access to copy from a designated place, then offering equivalent
+access to copy the source code from the same place counts as
+distribution of the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 4. You may not copy, modify, sublicense, or distribute the Program
+except as expressly provided under this License. Any attempt
+otherwise to copy, modify, sublicense or distribute the Program is
+void, and will automatically terminate your rights under this License.
+However, parties who have received copies, or rights, from you under
+this License will not have their licenses terminated so long as such
+parties remain in full compliance.
+
+ 5. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Program or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Program (or any work based on the
+Program), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Program or works based on it.
+
+ 6. Each time you redistribute the Program (or any work based on the
+Program), the recipient automatically receives a license from the
+original licensor to copy, distribute or modify the Program subject to
+these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties to
+this License.
+
+ 7. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Program at all. For example, if a patent
+license would not permit royalty-free redistribution of the Program by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Program.
+
+If any portion of this section is held invalid or unenforceable under
+any particular circumstance, the balance of the section is intended to
+apply and the section as a whole is intended to apply in other
+circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system, which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 8. If the distribution and/or use of the Program is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Program under this License
+may add an explicit geographical distribution limitation excluding
+those countries, so that distribution is permitted only in or among
+countries not thus excluded. In such case, this License incorporates
+the limitation as if written in the body of this License.
+
+ 9. The Free Software Foundation may publish revised and/or new versions
+of the General Public License from time to time. Such new versions will
+be similar in spirit to the present version, but may differ in detail to
+address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Program
+specifies a version number of this License which applies to it and "any
+later version", you have the option of following the terms and conditions
+either of that version or of any later version published by the Free
+Software Foundation. If the Program does not specify a version number of
+this License, you may choose any version ever published by the Free Software
+Foundation.
+
+ 10. If you wish to incorporate parts of the Program into other free
+programs whose distribution conditions are different, write to the author
+to ask for permission. For software which is copyrighted by the Free
+Software Foundation, write to the Free Software Foundation; we sometimes
+make exceptions for this. Our decision will be guided by the two goals
+of preserving the free status of all derivatives of our free software and
+of promoting the sharing and reuse of software generally.
+
+ NO WARRANTY
+
+ 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
+FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
+OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
+PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
+OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
+MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
+TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
+PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
+REPAIR OR CORRECTION.
+
+ 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
+WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
+REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
+INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
+OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
+TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
+YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
+PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
+POSSIBILITY OF SUCH DAMAGES.
+
+ END OF TERMS AND CONDITIONS \ No newline at end of file
diff --git a/Module.Taskfile.yaml b/Module.Taskfile.yaml
new file mode 100644
index 0000000..5da29ee
--- /dev/null
+++ b/Module.Taskfile.yaml
@@ -0,0 +1,45 @@
+# https://taskfile.dev
+
+#Called by the vnbuild system to produce builds for my website
+#https://www.vaughnnugent.com/resources/software
+
+#This taskfile performs the build operations for a module, it handles
+#git code updates, msbuild on solutions, and sleet NuGet feed pushes.
+
+#this file must be in the same directory as the solution file
+
+version: '3'
+
+tasks:
+
+#called by build pipeline to sync repo
+ update:
+ cmds:
+ - git remote update
+ - git reset --hard
+ - git pull origin {{.BRANCH_NAME}} --verify-signatures
+
+
+#called by build pipeline to build module
+ build:
+ cmds:
+ - echo "building module {{.MODULE_NAME}}"
+
+ postbuild_success:
+ cmds:
+
+ #git archive in the module binry output directory
+ - git archive --format {{.ARCHIVE_FILE_FORMAT}} --output {{.ARCHIVE_FILE_NAME}} HEAD
+
+ postbuild_failed:
+ cmds:
+ - echo "postbuild failed {{.MODULE_NAME}}"
+
+ #called by build pipeline to clean module
+ clean:
+ cmds:
+ #clean solution
+ - cmd: powershell -Command "rm out/ -Recurse "
+ ignore_error: true
+
+
diff --git a/README.md b/README.md
new file mode 100644
index 0000000..c572778
--- /dev/null
+++ b/README.md
@@ -0,0 +1,96 @@
+# noscrypt
+*A compact, C90 cross-platform, cryptography library built specifically for nostr*
+
+At the moment this library is a work in progress, and will be more extensively tested using the suggested nip-44 vector files in [NVault](https://github.com/VnUgE/NVault)
+
+## What is noscrypt?
+A high-level C utility library built specifically for nostr cryptography operations such as those defined in NIP-01 and the new NIP-44. It was designed to simplify the operations that the secp256k1 library was used for, along with data encryption for the new sepc.
+
+API Example:
+```C
+NCValidateSecretKey()
+NCGetPublicKey()
+NCSignData()
+NCVerifyData()
+NCEncrypt()
+NCDecrypt()
+... extended functions
+```
+
+There are no functions that handle key generation, because secp256k1 simply requires a 32byte random number that needs to only be validated. I assume most applications will prefer and or have better random number generators than I can assume. Use your preferred or platform CSRNG.
+
+## Motivation
+At the time of building this project I have not come across any C-only libraries that exposed functionality for nostr specific cryptography. IMO it is easy to use the secp256k1 library incorrectly. In the process of building [NVault](https://github.com/VnUgE/NVault) NIP-44 came out in December and I realized my libraries were falling short for my needs for proper and safe nostr cryptographic operations, and I needed to start over and start with a good base that has all the basic functionality built with trusted and tested libraries.
+
+I wanted a compact and efficient utility library that was portable across systems and runtimes. I will primarily be using this library in a .NET environment, but would like to make a hardware signer sometime.
+
+### Dependency choices
+I carefully chose [mbedTls](https://github.com/Mbed-TLS/mbedtls) and [libsecp256k1](https://github.com/bitcoin-core/secp256k1) for the following reasons
+- Modern, well tested and well trusted
+- Fully open source and actively maintained
+- Absolutely no runtime memory allocations
+- Built for use in embedded applications
+- Simple installations
+- Great cross-platform build support
+
+Initially I wanted to use [MonoCypher](https://monocypher.org/) for its compatibility and compactness but it did not have support for hdkf which is required for NIP-44.
+
+### Future Goals
+- Good support for embedded platforms that wish to implement nostr specific features (would be fun!)
+- Over all better testing suite
+
+## Packages and Docs
+GitHub is simply a mirror for my projects. Extended documentation, pre-compiled binaries and source code bundles are always available on my website, along with PGP signatures and checksums.
+
+[Docs and Articles](https://www.vaughnnugent.com/resources/software/articles?tags=docs,_noscrypt)
+[Builds and Source](https://www.vaughnnugent.com/resources/software/modules/noscrypt)
+
+## Getting the package
+There are 3 ways to get the source code to build this project.
+1. Clone the GitHub repo `git clone https://github.com/VnUgE/noscrypt.git`
+2. Download an archive from my website above
+3. Download a github archive or release when they are available
+
+## Compilation
+This project was built from the start using cmake as the build platform so it is easily cross platform. Builds produce a shared library and a static library so you can choose how to link it with your project.
+
+### Prerequisites
+Before building this library you must install the following dependencies
+- [secp256k1](https://github.com/bitcoin-core/secp256k1)
+- [mbedtls](https://github.com/Mbed-TLS/mbedtls)
+
+These libraries must be installed where cmake can find them, the easiest way is to just install them globally. So for Windows, this means the .lib files need to be available on the system PATH or safe search directories. The build process will fail if those libraries are not available. Follow the instructions for building and installing the libraries using `cmake` before continuing. For Linux libraries must be available in one of the the `lib/` base directories.
+
+*It is recommended to download the release archives of mbedtls and secp256k1 instead of cloning the repositories.*
+
+### Windows users
+Windows users can download pre-compiled x64 binaries from my website above when a build is run. You will still need to manually install dependencies
+
+### Instructions
+Use the following cmake commands to generate and compile the library on your system. This assumes you are in the directory containing the `CMakeLists.txt` file
+```shell
+cmake -B./build/
+cmake --build build/ --config Release
+```
+
+By default building of the test executables are disabled. At the moment testing is very basic, but will grow as time goes on. To enable testing set the `-DENABLE_TESTS=ON` flag during the first stage generation process
+```shell
+cmake -B./build/ -DENABLE_TESTS=ON
+```
+
+This will produce the `nctests` executable file in the build directory. This will likely change a bit in the future.
+
+## Notes
+**Builds** build packages on my website are "manual" I use an internal tool called *vnbuild* that just does the work of preparing a package, but I have to run it myself.
+
+### Branches
+There are currently 2 branches I use because of my build process. `develop` and `master`. All changes happen in develop, then are merged to master when I feel like they are stable enough. After some testing and time, a tag and release will become available.
+
+## License
+The software in this repository is licensed to you under the GNU GPL v2.0 or later. `SPDX-License-Identifier: GPL-2.0-or-later` see the [LICENSE](LICENSE) file for more details. I prefer GNU/FSF licenses and it allows compatibility with with mbedTls.
+
+## Donations
+If you feel so inclined to support me an this project, donations are welcome and much appreciated.
+
+BTC On-Chain: ``bc1qgj4fk6gdu8lnhd4zqzgxgcts0vlwcv3rqznxn9``
+
diff --git a/Taskfile.yaml b/Taskfile.yaml
new file mode 100644
index 0000000..a1e5b6d
--- /dev/null
+++ b/Taskfile.yaml
@@ -0,0 +1,78 @@
+# https://taskfile.dev
+
+#Called by the vnbuild system to produce builds for my website
+#https://www.vaughnnugent.com/resources/software
+
+#This taskfile performs the build operations for a module, it handles
+#git code updates, msbuild on solutions, and sleet NuGet feed pushes.
+
+#this file must be in the same directory as the solution file
+
+#NOTES: Since CI project is pulled from the module root, MODULE_DIR is used instead of PROJECT_DIR
+
+version: '3'
+
+tasks:
+
+ default:
+ desc: "Build the library for your system"
+ cmds:
+ - cmake -S . -B./build/ -DCMAKE_BUILD_TYPE=Release
+ - cmake --build build/ --config Release
+ - cmd: echo "Build complete your files can be found in the build/ directory"
+ silent: true
+
+ #called by build pipeline to build module
+ build:
+ cmds:
+ - echo "building project {{.PROJECT_NAME}}"
+ - cmd: powershell -Command "mkdir bin/ -Force"
+ ignore_error: true
+
+ #build windows x64
+ - task: build_win_x64
+
+ #pack source
+ - task: pack_source
+
+ clean:
+ desc: "Cleans the artifact directory"
+ cmds:
+ - cmd: powershell -Command "rm -r bin/ -Force"
+ ignore_error:
+
+ build_win_x64:
+ internal: true
+ vars:
+ TARGET_DLL: '{{.PROJECT_DIR}}/{{.BINARY_DIR}}/{{.PROJECT_NAME}}-win64.tgz'
+ DLL_FILES: '{{.PROJECT_NAME}}.dll {{.PROJECT_NAME}}.lib license.txt'
+ TARGET_STATIC: '{{.PROJECT_DIR}}/{{.BINARY_DIR}}/{{.PROJECT_NAME}}-win64-static.tgz'
+ STATIC_FILES: '{{.PROJECT_NAME}}_static.lib license.txt'
+ BUILD_DIR: 'out/build/win-x64'
+
+ cmds:
+ #invoke cmake build
+ - cmake -S . -B {{.BUILD_DIR}} -G "Visual Studio 17 2022" -A x64 -DCMAKE_BUILD_TYPE=Release
+ - cmake --build {{.BUILD_DIR}} --config Release
+
+ #copy license to build dir
+ - powershell -Command "cp license {{.BUILD_DIR}}/Release/license.txt"
+
+ #tar up the binaries
+ - cd {{.BUILD_DIR}}/Release && tar -czf "{{.TARGET_DLL}}" {{.DLL_FILES}}
+
+ #tar up static libs
+ - cd {{.BUILD_DIR}}/Release && tar -czf "{{.TARGET_STATIC}}" {{.STATIC_FILES}}
+
+
+ pack_source:
+ internal: true
+ desc: "Packs up the project source code and creates a tarball in the builds binary directory"
+ vars:
+ TARGET_SOURCE: '{{.PROJECT_DIR}}/{{.BINARY_DIR}}/{{.PROJECT_NAME}}-source.tgz'
+ SOURCE_FILES: 'CMakeLists.txt src include license tests Taskfile.yaml'
+
+ cmds:
+ #tar up the source
+ - tar -czf "{{.TARGET_SOURCE}}" {{.SOURCE_FILES}}
+
diff --git a/include/mbedtls/aes.h b/include/mbedtls/aes.h
new file mode 100644
index 0000000..77ecffd
--- /dev/null
+++ b/include/mbedtls/aes.h
@@ -0,0 +1,627 @@
+/**
+ * \file aes.h
+ *
+ * \brief This file contains AES definitions and functions.
+ *
+ * The Advanced Encryption Standard (AES) specifies a FIPS-approved
+ * cryptographic algorithm that can be used to protect electronic
+ * data.
+ *
+ * The AES algorithm is a symmetric block cipher that can
+ * encrypt and decrypt information. For more information, see
+ * <em>FIPS Publication 197: Advanced Encryption Standard</em> and
+ * <em>ISO/IEC 18033-2:2006: Information technology -- Security
+ * techniques -- Encryption algorithms -- Part 2: Asymmetric
+ * ciphers</em>.
+ *
+ * The AES-XTS block mode is standardized by NIST SP 800-38E
+ * <https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38e.pdf>
+ * and described in detail by IEEE P1619
+ * <https://ieeexplore.ieee.org/servlet/opac?punumber=4375278>.
+ */
+
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_AES_H
+#define MBEDTLS_AES_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+#include "mbedtls/platform_util.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+/* padlock.c and aesni.c rely on these values! */
+#define MBEDTLS_AES_ENCRYPT 1 /**< AES encryption. */
+#define MBEDTLS_AES_DECRYPT 0 /**< AES decryption. */
+
+/* Error codes in range 0x0020-0x0022 */
+/** Invalid key length. */
+#define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020
+/** Invalid data input length. */
+#define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022
+
+/* Error codes in range 0x0021-0x0025 */
+/** Invalid input data. */
+#define MBEDTLS_ERR_AES_BAD_INPUT_DATA -0x0021
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_AES_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief The AES context-type definition.
+ */
+typedef struct mbedtls_aes_context {
+ int MBEDTLS_PRIVATE(nr); /*!< The number of rounds. */
+ size_t MBEDTLS_PRIVATE(rk_offset); /*!< The offset in array elements to AES
+ round keys in the buffer. */
+#if defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) && !defined(MBEDTLS_PADLOCK_C)
+ uint32_t MBEDTLS_PRIVATE(buf)[44]; /*!< Aligned data buffer to hold
+ 10 round keys for 128-bit case. */
+#else
+ uint32_t MBEDTLS_PRIVATE(buf)[68]; /*!< Unaligned data buffer. This buffer can
+ hold 32 extra Bytes, which can be used for
+ one of the following purposes:
+ <ul><li>Alignment if VIA padlock is
+ used.</li>
+ <li>Simplifying key expansion in the 256-bit
+ case by generating an extra round key.
+ </li></ul> */
+#endif /* MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH && !MBEDTLS_PADLOCK_C */
+}
+mbedtls_aes_context;
+
+#if defined(MBEDTLS_CIPHER_MODE_XTS)
+/**
+ * \brief The AES XTS context-type definition.
+ */
+typedef struct mbedtls_aes_xts_context {
+ mbedtls_aes_context MBEDTLS_PRIVATE(crypt); /*!< The AES context to use for AES block
+ encryption or decryption. */
+ mbedtls_aes_context MBEDTLS_PRIVATE(tweak); /*!< The AES context used for tweak
+ computation. */
+} mbedtls_aes_xts_context;
+#endif /* MBEDTLS_CIPHER_MODE_XTS */
+
+#else /* MBEDTLS_AES_ALT */
+#include "aes_alt.h"
+#endif /* MBEDTLS_AES_ALT */
+
+/**
+ * \brief This function initializes the specified AES context.
+ *
+ * It must be the first API called before using
+ * the context.
+ *
+ * \param ctx The AES context to initialize. This must not be \c NULL.
+ */
+void mbedtls_aes_init(mbedtls_aes_context *ctx);
+
+/**
+ * \brief This function releases and clears the specified AES context.
+ *
+ * \param ctx The AES context to clear.
+ * If this is \c NULL, this function does nothing.
+ * Otherwise, the context must have been at least initialized.
+ */
+void mbedtls_aes_free(mbedtls_aes_context *ctx);
+
+#if defined(MBEDTLS_CIPHER_MODE_XTS)
+/**
+ * \brief This function initializes the specified AES XTS context.
+ *
+ * It must be the first API called before using
+ * the context.
+ *
+ * \param ctx The AES XTS context to initialize. This must not be \c NULL.
+ */
+void mbedtls_aes_xts_init(mbedtls_aes_xts_context *ctx);
+
+/**
+ * \brief This function releases and clears the specified AES XTS context.
+ *
+ * \param ctx The AES XTS context to clear.
+ * If this is \c NULL, this function does nothing.
+ * Otherwise, the context must have been at least initialized.
+ */
+void mbedtls_aes_xts_free(mbedtls_aes_xts_context *ctx);
+#endif /* MBEDTLS_CIPHER_MODE_XTS */
+
+/**
+ * \brief This function sets the encryption key.
+ *
+ * \param ctx The AES context to which the key should be bound.
+ * It must be initialized.
+ * \param key The encryption key.
+ * This must be a readable buffer of size \p keybits bits.
+ * \param keybits The size of data passed in bits. Valid options are:
+ * <ul><li>128 bits</li>
+ * <li>192 bits</li>
+ * <li>256 bits</li></ul>
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_setkey_enc(mbedtls_aes_context *ctx, const unsigned char *key,
+ unsigned int keybits);
+
+/**
+ * \brief This function sets the decryption key.
+ *
+ * \param ctx The AES context to which the key should be bound.
+ * It must be initialized.
+ * \param key The decryption key.
+ * This must be a readable buffer of size \p keybits bits.
+ * \param keybits The size of data passed. Valid options are:
+ * <ul><li>128 bits</li>
+ * <li>192 bits</li>
+ * <li>256 bits</li></ul>
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_setkey_dec(mbedtls_aes_context *ctx, const unsigned char *key,
+ unsigned int keybits);
+
+#if defined(MBEDTLS_CIPHER_MODE_XTS)
+/**
+ * \brief This function prepares an XTS context for encryption and
+ * sets the encryption key.
+ *
+ * \param ctx The AES XTS context to which the key should be bound.
+ * It must be initialized.
+ * \param key The encryption key. This is comprised of the XTS key1
+ * concatenated with the XTS key2.
+ * This must be a readable buffer of size \p keybits bits.
+ * \param keybits The size of \p key passed in bits. Valid options are:
+ * <ul><li>256 bits (each of key1 and key2 is a 128-bit key)</li>
+ * <li>512 bits (each of key1 and key2 is a 256-bit key)</li></ul>
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_xts_setkey_enc(mbedtls_aes_xts_context *ctx,
+ const unsigned char *key,
+ unsigned int keybits);
+
+/**
+ * \brief This function prepares an XTS context for decryption and
+ * sets the decryption key.
+ *
+ * \param ctx The AES XTS context to which the key should be bound.
+ * It must be initialized.
+ * \param key The decryption key. This is comprised of the XTS key1
+ * concatenated with the XTS key2.
+ * This must be a readable buffer of size \p keybits bits.
+ * \param keybits The size of \p key passed in bits. Valid options are:
+ * <ul><li>256 bits (each of key1 and key2 is a 128-bit key)</li>
+ * <li>512 bits (each of key1 and key2 is a 256-bit key)</li></ul>
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_xts_setkey_dec(mbedtls_aes_xts_context *ctx,
+ const unsigned char *key,
+ unsigned int keybits);
+#endif /* MBEDTLS_CIPHER_MODE_XTS */
+
+/**
+ * \brief This function performs an AES single-block encryption or
+ * decryption operation.
+ *
+ * It performs the operation defined in the \p mode parameter
+ * (encrypt or decrypt), on the input data buffer defined in
+ * the \p input parameter.
+ *
+ * mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or
+ * mbedtls_aes_setkey_dec() must be called before the first
+ * call to this API with the same context.
+ *
+ * \param ctx The AES context to use for encryption or decryption.
+ * It must be initialized and bound to a key.
+ * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
+ * #MBEDTLS_AES_DECRYPT.
+ * \param input The buffer holding the input data.
+ * It must be readable and at least \c 16 Bytes long.
+ * \param output The buffer where the output data will be written.
+ * It must be writeable and at least \c 16 Bytes long.
+
+ * \return \c 0 on success.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_crypt_ecb(mbedtls_aes_context *ctx,
+ int mode,
+ const unsigned char input[16],
+ unsigned char output[16]);
+
+#if defined(MBEDTLS_CIPHER_MODE_CBC)
+/**
+ * \brief This function performs an AES-CBC encryption or decryption operation
+ * on full blocks.
+ *
+ * It performs the operation defined in the \p mode
+ * parameter (encrypt/decrypt), on the input data buffer defined in
+ * the \p input parameter.
+ *
+ * It can be called as many times as needed, until all the input
+ * data is processed. mbedtls_aes_init(), and either
+ * mbedtls_aes_setkey_enc() or mbedtls_aes_setkey_dec() must be called
+ * before the first call to this API with the same context.
+ *
+ * \note This function operates on full blocks, that is, the input size
+ * must be a multiple of the AES block size of \c 16 Bytes.
+ *
+ * \note Upon exit, the content of the IV is updated so that you can
+ * call the same function again on the next
+ * block(s) of data and get the same result as if it was
+ * encrypted in one call. This allows a "streaming" usage.
+ * If you need to retain the contents of the IV, you should
+ * either save it manually or use the cipher module instead.
+ *
+ *
+ * \param ctx The AES context to use for encryption or decryption.
+ * It must be initialized and bound to a key.
+ * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
+ * #MBEDTLS_AES_DECRYPT.
+ * \param length The length of the input data in Bytes. This must be a
+ * multiple of the block size (\c 16 Bytes).
+ * \param iv Initialization vector (updated after use).
+ * It must be a readable and writeable buffer of \c 16 Bytes.
+ * \param input The buffer holding the input data.
+ * It must be readable and of size \p length Bytes.
+ * \param output The buffer holding the output data.
+ * It must be writeable and of size \p length Bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH
+ * on failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_crypt_cbc(mbedtls_aes_context *ctx,
+ int mode,
+ size_t length,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_CBC */
+
+#if defined(MBEDTLS_CIPHER_MODE_XTS)
+/**
+ * \brief This function performs an AES-XTS encryption or decryption
+ * operation for an entire XTS data unit.
+ *
+ * AES-XTS encrypts or decrypts blocks based on their location as
+ * defined by a data unit number. The data unit number must be
+ * provided by \p data_unit.
+ *
+ * NIST SP 800-38E limits the maximum size of a data unit to 2^20
+ * AES blocks. If the data unit is larger than this, this function
+ * returns #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH.
+ *
+ * \param ctx The AES XTS context to use for AES XTS operations.
+ * It must be initialized and bound to a key.
+ * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
+ * #MBEDTLS_AES_DECRYPT.
+ * \param length The length of a data unit in Bytes. This can be any
+ * length between 16 bytes and 2^24 bytes inclusive
+ * (between 1 and 2^20 block cipher blocks).
+ * \param data_unit The address of the data unit encoded as an array of 16
+ * bytes in little-endian format. For disk encryption, this
+ * is typically the index of the block device sector that
+ * contains the data.
+ * \param input The buffer holding the input data (which is an entire
+ * data unit). This function reads \p length Bytes from \p
+ * input.
+ * \param output The buffer holding the output data (which is an entire
+ * data unit). This function writes \p length Bytes to \p
+ * output.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH if \p length is
+ * smaller than an AES block in size (16 Bytes) or if \p
+ * length is larger than 2^20 blocks (16 MiB).
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_crypt_xts(mbedtls_aes_xts_context *ctx,
+ int mode,
+ size_t length,
+ const unsigned char data_unit[16],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_XTS */
+
+#if defined(MBEDTLS_CIPHER_MODE_CFB)
+/**
+ * \brief This function performs an AES-CFB128 encryption or decryption
+ * operation.
+ *
+ * It performs the operation defined in the \p mode
+ * parameter (encrypt or decrypt), on the input data buffer
+ * defined in the \p input parameter.
+ *
+ * For CFB, you must set up the context with mbedtls_aes_setkey_enc(),
+ * regardless of whether you are performing an encryption or decryption
+ * operation, that is, regardless of the \p mode parameter. This is
+ * because CFB mode uses the same key schedule for encryption and
+ * decryption.
+ *
+ * \note Upon exit, the content of the IV is updated so that you can
+ * call the same function again on the next
+ * block(s) of data and get the same result as if it was
+ * encrypted in one call. This allows a "streaming" usage.
+ * If you need to retain the contents of the
+ * IV, you must either save it manually or use the cipher
+ * module instead.
+ *
+ *
+ * \param ctx The AES context to use for encryption or decryption.
+ * It must be initialized and bound to a key.
+ * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
+ * #MBEDTLS_AES_DECRYPT.
+ * \param length The length of the input data in Bytes.
+ * \param iv_off The offset in IV (updated after use).
+ * It must point to a valid \c size_t.
+ * \param iv The initialization vector (updated after use).
+ * It must be a readable and writeable buffer of \c 16 Bytes.
+ * \param input The buffer holding the input data.
+ * It must be readable and of size \p length Bytes.
+ * \param output The buffer holding the output data.
+ * It must be writeable and of size \p length Bytes.
+ *
+ * \return \c 0 on success.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_crypt_cfb128(mbedtls_aes_context *ctx,
+ int mode,
+ size_t length,
+ size_t *iv_off,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output);
+
+/**
+ * \brief This function performs an AES-CFB8 encryption or decryption
+ * operation.
+ *
+ * It performs the operation defined in the \p mode
+ * parameter (encrypt/decrypt), on the input data buffer defined
+ * in the \p input parameter.
+ *
+ * Due to the nature of CFB, you must use the same key schedule for
+ * both encryption and decryption operations. Therefore, you must
+ * use the context initialized with mbedtls_aes_setkey_enc() for
+ * both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.
+ *
+ * \note Upon exit, the content of the IV is updated so that you can
+ * call the same function again on the next
+ * block(s) of data and get the same result as if it was
+ * encrypted in one call. This allows a "streaming" usage.
+ * If you need to retain the contents of the
+ * IV, you should either save it manually or use the cipher
+ * module instead.
+ *
+ *
+ * \param ctx The AES context to use for encryption or decryption.
+ * It must be initialized and bound to a key.
+ * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or
+ * #MBEDTLS_AES_DECRYPT
+ * \param length The length of the input data.
+ * \param iv The initialization vector (updated after use).
+ * It must be a readable and writeable buffer of \c 16 Bytes.
+ * \param input The buffer holding the input data.
+ * It must be readable and of size \p length Bytes.
+ * \param output The buffer holding the output data.
+ * It must be writeable and of size \p length Bytes.
+ *
+ * \return \c 0 on success.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_crypt_cfb8(mbedtls_aes_context *ctx,
+ int mode,
+ size_t length,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /*MBEDTLS_CIPHER_MODE_CFB */
+
+#if defined(MBEDTLS_CIPHER_MODE_OFB)
+/**
+ * \brief This function performs an AES-OFB (Output Feedback Mode)
+ * encryption or decryption operation.
+ *
+ * For OFB, you must set up the context with
+ * mbedtls_aes_setkey_enc(), regardless of whether you are
+ * performing an encryption or decryption operation. This is
+ * because OFB mode uses the same key schedule for encryption and
+ * decryption.
+ *
+ * The OFB operation is identical for encryption or decryption,
+ * therefore no operation mode needs to be specified.
+ *
+ * \note Upon exit, the content of iv, the Initialisation Vector, is
+ * updated so that you can call the same function again on the next
+ * block(s) of data and get the same result as if it was encrypted
+ * in one call. This allows a "streaming" usage, by initialising
+ * iv_off to 0 before the first call, and preserving its value
+ * between calls.
+ *
+ * For non-streaming use, the iv should be initialised on each call
+ * to a unique value, and iv_off set to 0 on each call.
+ *
+ * If you need to retain the contents of the initialisation vector,
+ * you must either save it manually or use the cipher module
+ * instead.
+ *
+ * \warning For the OFB mode, the initialisation vector must be unique
+ * every encryption operation. Reuse of an initialisation vector
+ * will compromise security.
+ *
+ * \param ctx The AES context to use for encryption or decryption.
+ * It must be initialized and bound to a key.
+ * \param length The length of the input data.
+ * \param iv_off The offset in IV (updated after use).
+ * It must point to a valid \c size_t.
+ * \param iv The initialization vector (updated after use).
+ * It must be a readable and writeable buffer of \c 16 Bytes.
+ * \param input The buffer holding the input data.
+ * It must be readable and of size \p length Bytes.
+ * \param output The buffer holding the output data.
+ * It must be writeable and of size \p length Bytes.
+ *
+ * \return \c 0 on success.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_crypt_ofb(mbedtls_aes_context *ctx,
+ size_t length,
+ size_t *iv_off,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output);
+
+#endif /* MBEDTLS_CIPHER_MODE_OFB */
+
+#if defined(MBEDTLS_CIPHER_MODE_CTR)
+/**
+ * \brief This function performs an AES-CTR encryption or decryption
+ * operation.
+ *
+ * Due to the nature of CTR, you must use the same key schedule
+ * for both encryption and decryption operations. Therefore, you
+ * must use the context initialized with mbedtls_aes_setkey_enc()
+ * for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT.
+ *
+ * \warning You must never reuse a nonce value with the same key. Doing so
+ * would void the encryption for the two messages encrypted with
+ * the same nonce and key.
+ *
+ * There are two common strategies for managing nonces with CTR:
+ *
+ * 1. You can handle everything as a single message processed over
+ * successive calls to this function. In that case, you want to
+ * set \p nonce_counter and \p nc_off to 0 for the first call, and
+ * then preserve the values of \p nonce_counter, \p nc_off and \p
+ * stream_block across calls to this function as they will be
+ * updated by this function.
+ *
+ * With this strategy, you must not encrypt more than 2**128
+ * blocks of data with the same key.
+ *
+ * 2. You can encrypt separate messages by dividing the \p
+ * nonce_counter buffer in two areas: the first one used for a
+ * per-message nonce, handled by yourself, and the second one
+ * updated by this function internally.
+ *
+ * For example, you might reserve the first 12 bytes for the
+ * per-message nonce, and the last 4 bytes for internal use. In that
+ * case, before calling this function on a new message you need to
+ * set the first 12 bytes of \p nonce_counter to your chosen nonce
+ * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p
+ * stream_block to be ignored). That way, you can encrypt at most
+ * 2**96 messages of up to 2**32 blocks each with the same key.
+ *
+ * The per-message nonce (or information sufficient to reconstruct
+ * it) needs to be communicated with the ciphertext and must be unique.
+ * The recommended way to ensure uniqueness is to use a message
+ * counter. An alternative is to generate random nonces, but this
+ * limits the number of messages that can be securely encrypted:
+ * for example, with 96-bit random nonces, you should not encrypt
+ * more than 2**32 messages with the same key.
+ *
+ * Note that for both strategies, sizes are measured in blocks and
+ * that an AES block is 16 bytes.
+ *
+ * \warning Upon return, \p stream_block contains sensitive data. Its
+ * content must not be written to insecure storage and should be
+ * securely discarded as soon as it's no longer needed.
+ *
+ * \param ctx The AES context to use for encryption or decryption.
+ * It must be initialized and bound to a key.
+ * \param length The length of the input data.
+ * \param nc_off The offset in the current \p stream_block, for
+ * resuming within the current cipher stream. The
+ * offset pointer should be 0 at the start of a stream.
+ * It must point to a valid \c size_t.
+ * \param nonce_counter The 128-bit nonce and counter.
+ * It must be a readable-writeable buffer of \c 16 Bytes.
+ * \param stream_block The saved stream block for resuming. This is
+ * overwritten by the function.
+ * It must be a readable-writeable buffer of \c 16 Bytes.
+ * \param input The buffer holding the input data.
+ * It must be readable and of size \p length Bytes.
+ * \param output The buffer holding the output data.
+ * It must be writeable and of size \p length Bytes.
+ *
+ * \return \c 0 on success.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_aes_crypt_ctr(mbedtls_aes_context *ctx,
+ size_t length,
+ size_t *nc_off,
+ unsigned char nonce_counter[16],
+ unsigned char stream_block[16],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_CTR */
+
+/**
+ * \brief Internal AES block encryption function. This is only
+ * exposed to allow overriding it using
+ * \c MBEDTLS_AES_ENCRYPT_ALT.
+ *
+ * \param ctx The AES context to use for encryption.
+ * \param input The plaintext block.
+ * \param output The output (ciphertext) block.
+ *
+ * \return \c 0 on success.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_internal_aes_encrypt(mbedtls_aes_context *ctx,
+ const unsigned char input[16],
+ unsigned char output[16]);
+
+/**
+ * \brief Internal AES block decryption function. This is only
+ * exposed to allow overriding it using see
+ * \c MBEDTLS_AES_DECRYPT_ALT.
+ *
+ * \param ctx The AES context to use for decryption.
+ * \param input The ciphertext block.
+ * \param output The output (plaintext) block.
+ *
+ * \return \c 0 on success.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_internal_aes_decrypt(mbedtls_aes_context *ctx,
+ const unsigned char input[16],
+ unsigned char output[16]);
+
+#if defined(MBEDTLS_SELF_TEST)
+/**
+ * \brief Checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+MBEDTLS_CHECK_RETURN_CRITICAL
+int mbedtls_aes_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* aes.h */
diff --git a/include/mbedtls/aria.h b/include/mbedtls/aria.h
new file mode 100644
index 0000000..abb8a3d
--- /dev/null
+++ b/include/mbedtls/aria.h
@@ -0,0 +1,341 @@
+/**
+ * \file aria.h
+ *
+ * \brief ARIA block cipher
+ *
+ * The ARIA algorithm is a symmetric block cipher that can encrypt and
+ * decrypt information. It is defined by the Korean Agency for
+ * Technology and Standards (KATS) in <em>KS X 1213:2004</em> (in
+ * Korean, but see http://210.104.33.10/ARIA/index-e.html in English)
+ * and also described by the IETF in <em>RFC 5794</em>.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_ARIA_H
+#define MBEDTLS_ARIA_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "mbedtls/platform_util.h"
+
+#define MBEDTLS_ARIA_ENCRYPT 1 /**< ARIA encryption. */
+#define MBEDTLS_ARIA_DECRYPT 0 /**< ARIA decryption. */
+
+#define MBEDTLS_ARIA_BLOCKSIZE 16 /**< ARIA block size in bytes. */
+#define MBEDTLS_ARIA_MAX_ROUNDS 16 /**< Maximum number of rounds in ARIA. */
+#define MBEDTLS_ARIA_MAX_KEYSIZE 32 /**< Maximum size of an ARIA key in bytes. */
+
+/** Bad input data. */
+#define MBEDTLS_ERR_ARIA_BAD_INPUT_DATA -0x005C
+
+/** Invalid data input length. */
+#define MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH -0x005E
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_ARIA_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief The ARIA context-type definition.
+ */
+typedef struct mbedtls_aria_context {
+ unsigned char MBEDTLS_PRIVATE(nr); /*!< The number of rounds (12, 14 or 16) */
+ /*! The ARIA round keys. */
+ uint32_t MBEDTLS_PRIVATE(rk)[MBEDTLS_ARIA_MAX_ROUNDS + 1][MBEDTLS_ARIA_BLOCKSIZE / 4];
+}
+mbedtls_aria_context;
+
+#else /* MBEDTLS_ARIA_ALT */
+#include "aria_alt.h"
+#endif /* MBEDTLS_ARIA_ALT */
+
+/**
+ * \brief This function initializes the specified ARIA context.
+ *
+ * It must be the first API called before using
+ * the context.
+ *
+ * \param ctx The ARIA context to initialize. This must not be \c NULL.
+ */
+void mbedtls_aria_init(mbedtls_aria_context *ctx);
+
+/**
+ * \brief This function releases and clears the specified ARIA context.
+ *
+ * \param ctx The ARIA context to clear. This may be \c NULL, in which
+ * case this function returns immediately. If it is not \c NULL,
+ * it must point to an initialized ARIA context.
+ */
+void mbedtls_aria_free(mbedtls_aria_context *ctx);
+
+/**
+ * \brief This function sets the encryption key.
+ *
+ * \param ctx The ARIA context to which the key should be bound.
+ * This must be initialized.
+ * \param key The encryption key. This must be a readable buffer
+ * of size \p keybits Bits.
+ * \param keybits The size of \p key in Bits. Valid options are:
+ * <ul><li>128 bits</li>
+ * <li>192 bits</li>
+ * <li>256 bits</li></ul>
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_aria_setkey_enc(mbedtls_aria_context *ctx,
+ const unsigned char *key,
+ unsigned int keybits);
+
+/**
+ * \brief This function sets the decryption key.
+ *
+ * \param ctx The ARIA context to which the key should be bound.
+ * This must be initialized.
+ * \param key The decryption key. This must be a readable buffer
+ * of size \p keybits Bits.
+ * \param keybits The size of data passed. Valid options are:
+ * <ul><li>128 bits</li>
+ * <li>192 bits</li>
+ * <li>256 bits</li></ul>
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_aria_setkey_dec(mbedtls_aria_context *ctx,
+ const unsigned char *key,
+ unsigned int keybits);
+
+/**
+ * \brief This function performs an ARIA single-block encryption or
+ * decryption operation.
+ *
+ * It performs encryption or decryption (depending on whether
+ * the key was set for encryption on decryption) on the input
+ * data buffer defined in the \p input parameter.
+ *
+ * mbedtls_aria_init(), and either mbedtls_aria_setkey_enc() or
+ * mbedtls_aria_setkey_dec() must be called before the first
+ * call to this API with the same context.
+ *
+ * \param ctx The ARIA context to use for encryption or decryption.
+ * This must be initialized and bound to a key.
+ * \param input The 16-Byte buffer holding the input data.
+ * \param output The 16-Byte buffer holding the output data.
+
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_aria_crypt_ecb(mbedtls_aria_context *ctx,
+ const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE],
+ unsigned char output[MBEDTLS_ARIA_BLOCKSIZE]);
+
+#if defined(MBEDTLS_CIPHER_MODE_CBC)
+/**
+ * \brief This function performs an ARIA-CBC encryption or decryption operation
+ * on full blocks.
+ *
+ * It performs the operation defined in the \p mode
+ * parameter (encrypt/decrypt), on the input data buffer defined in
+ * the \p input parameter.
+ *
+ * It can be called as many times as needed, until all the input
+ * data is processed. mbedtls_aria_init(), and either
+ * mbedtls_aria_setkey_enc() or mbedtls_aria_setkey_dec() must be called
+ * before the first call to this API with the same context.
+ *
+ * \note This function operates on aligned blocks, that is, the input size
+ * must be a multiple of the ARIA block size of 16 Bytes.
+ *
+ * \note Upon exit, the content of the IV is updated so that you can
+ * call the same function again on the next
+ * block(s) of data and get the same result as if it was
+ * encrypted in one call. This allows a "streaming" usage.
+ * If you need to retain the contents of the IV, you should
+ * either save it manually or use the cipher module instead.
+ *
+ *
+ * \param ctx The ARIA context to use for encryption or decryption.
+ * This must be initialized and bound to a key.
+ * \param mode The mode of operation. This must be either
+ * #MBEDTLS_ARIA_ENCRYPT for encryption, or
+ * #MBEDTLS_ARIA_DECRYPT for decryption.
+ * \param length The length of the input data in Bytes. This must be a
+ * multiple of the block size (16 Bytes).
+ * \param iv Initialization vector (updated after use).
+ * This must be a readable buffer of size 16 Bytes.
+ * \param input The buffer holding the input data. This must
+ * be a readable buffer of length \p length Bytes.
+ * \param output The buffer holding the output data. This must
+ * be a writable buffer of length \p length Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_aria_crypt_cbc(mbedtls_aria_context *ctx,
+ int mode,
+ size_t length,
+ unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_CBC */
+
+#if defined(MBEDTLS_CIPHER_MODE_CFB)
+/**
+ * \brief This function performs an ARIA-CFB128 encryption or decryption
+ * operation.
+ *
+ * It performs the operation defined in the \p mode
+ * parameter (encrypt or decrypt), on the input data buffer
+ * defined in the \p input parameter.
+ *
+ * For CFB, you must set up the context with mbedtls_aria_setkey_enc(),
+ * regardless of whether you are performing an encryption or decryption
+ * operation, that is, regardless of the \p mode parameter. This is
+ * because CFB mode uses the same key schedule for encryption and
+ * decryption.
+ *
+ * \note Upon exit, the content of the IV is updated so that you can
+ * call the same function again on the next
+ * block(s) of data and get the same result as if it was
+ * encrypted in one call. This allows a "streaming" usage.
+ * If you need to retain the contents of the
+ * IV, you must either save it manually or use the cipher
+ * module instead.
+ *
+ *
+ * \param ctx The ARIA context to use for encryption or decryption.
+ * This must be initialized and bound to a key.
+ * \param mode The mode of operation. This must be either
+ * #MBEDTLS_ARIA_ENCRYPT for encryption, or
+ * #MBEDTLS_ARIA_DECRYPT for decryption.
+ * \param length The length of the input data \p input in Bytes.
+ * \param iv_off The offset in IV (updated after use).
+ * This must not be larger than 15.
+ * \param iv The initialization vector (updated after use).
+ * This must be a readable buffer of size 16 Bytes.
+ * \param input The buffer holding the input data. This must
+ * be a readable buffer of length \p length Bytes.
+ * \param output The buffer holding the output data. This must
+ * be a writable buffer of length \p length Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_aria_crypt_cfb128(mbedtls_aria_context *ctx,
+ int mode,
+ size_t length,
+ size_t *iv_off,
+ unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_CFB */
+
+#if defined(MBEDTLS_CIPHER_MODE_CTR)
+/**
+ * \brief This function performs an ARIA-CTR encryption or decryption
+ * operation.
+ *
+ * Due to the nature of CTR, you must use the same key schedule
+ * for both encryption and decryption operations. Therefore, you
+ * must use the context initialized with mbedtls_aria_setkey_enc()
+ * for both #MBEDTLS_ARIA_ENCRYPT and #MBEDTLS_ARIA_DECRYPT.
+ *
+ * \warning You must never reuse a nonce value with the same key. Doing so
+ * would void the encryption for the two messages encrypted with
+ * the same nonce and key.
+ *
+ * There are two common strategies for managing nonces with CTR:
+ *
+ * 1. You can handle everything as a single message processed over
+ * successive calls to this function. In that case, you want to
+ * set \p nonce_counter and \p nc_off to 0 for the first call, and
+ * then preserve the values of \p nonce_counter, \p nc_off and \p
+ * stream_block across calls to this function as they will be
+ * updated by this function.
+ *
+ * With this strategy, you must not encrypt more than 2**128
+ * blocks of data with the same key.
+ *
+ * 2. You can encrypt separate messages by dividing the \p
+ * nonce_counter buffer in two areas: the first one used for a
+ * per-message nonce, handled by yourself, and the second one
+ * updated by this function internally.
+ *
+ * For example, you might reserve the first 12 bytes for the
+ * per-message nonce, and the last 4 bytes for internal use. In that
+ * case, before calling this function on a new message you need to
+ * set the first 12 bytes of \p nonce_counter to your chosen nonce
+ * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p
+ * stream_block to be ignored). That way, you can encrypt at most
+ * 2**96 messages of up to 2**32 blocks each with the same key.
+ *
+ * The per-message nonce (or information sufficient to reconstruct
+ * it) needs to be communicated with the ciphertext and must be unique.
+ * The recommended way to ensure uniqueness is to use a message
+ * counter. An alternative is to generate random nonces, but this
+ * limits the number of messages that can be securely encrypted:
+ * for example, with 96-bit random nonces, you should not encrypt
+ * more than 2**32 messages with the same key.
+ *
+ * Note that for both strategies, sizes are measured in blocks and
+ * that an ARIA block is 16 bytes.
+ *
+ * \warning Upon return, \p stream_block contains sensitive data. Its
+ * content must not be written to insecure storage and should be
+ * securely discarded as soon as it's no longer needed.
+ *
+ * \param ctx The ARIA context to use for encryption or decryption.
+ * This must be initialized and bound to a key.
+ * \param length The length of the input data \p input in Bytes.
+ * \param nc_off The offset in Bytes in the current \p stream_block,
+ * for resuming within the current cipher stream. The
+ * offset pointer should be \c 0 at the start of a
+ * stream. This must not be larger than \c 15 Bytes.
+ * \param nonce_counter The 128-bit nonce and counter. This must point to
+ * a read/write buffer of length \c 16 bytes.
+ * \param stream_block The saved stream block for resuming. This must
+ * point to a read/write buffer of length \c 16 bytes.
+ * This is overwritten by the function.
+ * \param input The buffer holding the input data. This must
+ * be a readable buffer of length \p length Bytes.
+ * \param output The buffer holding the output data. This must
+ * be a writable buffer of length \p length Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_aria_crypt_ctr(mbedtls_aria_context *ctx,
+ size_t length,
+ size_t *nc_off,
+ unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE],
+ unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_CTR */
+
+#if defined(MBEDTLS_SELF_TEST)
+/**
+ * \brief Checkup routine.
+ *
+ * \return \c 0 on success, or \c 1 on failure.
+ */
+int mbedtls_aria_self_test(int verbose);
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* aria.h */
diff --git a/include/mbedtls/asn1.h b/include/mbedtls/asn1.h
new file mode 100644
index 0000000..830458b
--- /dev/null
+++ b/include/mbedtls/asn1.h
@@ -0,0 +1,641 @@
+/**
+ * \file asn1.h
+ *
+ * \brief Generic ASN.1 parsing
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_ASN1_H
+#define MBEDTLS_ASN1_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+#include "mbedtls/platform_util.h"
+
+#include <stddef.h>
+
+#if defined(MBEDTLS_BIGNUM_C)
+#include "mbedtls/bignum.h"
+#endif
+
+/**
+ * \addtogroup asn1_module
+ * \{
+ */
+
+/**
+ * \name ASN1 Error codes
+ * These error codes are combined with other error codes for
+ * higher error granularity.
+ * e.g. X.509 and PKCS #7 error codes
+ * ASN1 is a standard to specify data structures.
+ * \{
+ */
+/** Out of data when parsing an ASN1 data structure. */
+#define MBEDTLS_ERR_ASN1_OUT_OF_DATA -0x0060
+/** ASN1 tag was of an unexpected value. */
+#define MBEDTLS_ERR_ASN1_UNEXPECTED_TAG -0x0062
+/** Error when trying to determine the length or invalid length. */
+#define MBEDTLS_ERR_ASN1_INVALID_LENGTH -0x0064
+/** Actual length differs from expected length. */
+#define MBEDTLS_ERR_ASN1_LENGTH_MISMATCH -0x0066
+/** Data is invalid. */
+#define MBEDTLS_ERR_ASN1_INVALID_DATA -0x0068
+/** Memory allocation failed */
+#define MBEDTLS_ERR_ASN1_ALLOC_FAILED -0x006A
+/** Buffer too small when writing ASN.1 data structure. */
+#define MBEDTLS_ERR_ASN1_BUF_TOO_SMALL -0x006C
+
+/** \} name ASN1 Error codes */
+
+/**
+ * \name DER constants
+ * These constants comply with the DER encoded ASN.1 type tags.
+ * DER encoding uses hexadecimal representation.
+ * An example DER sequence is:\n
+ * - 0x02 -- tag indicating INTEGER
+ * - 0x01 -- length in octets
+ * - 0x05 -- value
+ * Such sequences are typically read into \c ::mbedtls_x509_buf.
+ * \{
+ */
+#define MBEDTLS_ASN1_BOOLEAN 0x01
+#define MBEDTLS_ASN1_INTEGER 0x02
+#define MBEDTLS_ASN1_BIT_STRING 0x03
+#define MBEDTLS_ASN1_OCTET_STRING 0x04
+#define MBEDTLS_ASN1_NULL 0x05
+#define MBEDTLS_ASN1_OID 0x06
+#define MBEDTLS_ASN1_ENUMERATED 0x0A
+#define MBEDTLS_ASN1_UTF8_STRING 0x0C
+#define MBEDTLS_ASN1_SEQUENCE 0x10
+#define MBEDTLS_ASN1_SET 0x11
+#define MBEDTLS_ASN1_PRINTABLE_STRING 0x13
+#define MBEDTLS_ASN1_T61_STRING 0x14
+#define MBEDTLS_ASN1_IA5_STRING 0x16
+#define MBEDTLS_ASN1_UTC_TIME 0x17
+#define MBEDTLS_ASN1_GENERALIZED_TIME 0x18
+#define MBEDTLS_ASN1_UNIVERSAL_STRING 0x1C
+#define MBEDTLS_ASN1_BMP_STRING 0x1E
+#define MBEDTLS_ASN1_PRIMITIVE 0x00
+#define MBEDTLS_ASN1_CONSTRUCTED 0x20
+#define MBEDTLS_ASN1_CONTEXT_SPECIFIC 0x80
+
+/* Slightly smaller way to check if tag is a string tag
+ * compared to canonical implementation. */
+#define MBEDTLS_ASN1_IS_STRING_TAG(tag) \
+ ((unsigned int) (tag) < 32u && ( \
+ ((1u << (tag)) & ((1u << MBEDTLS_ASN1_BMP_STRING) | \
+ (1u << MBEDTLS_ASN1_UTF8_STRING) | \
+ (1u << MBEDTLS_ASN1_T61_STRING) | \
+ (1u << MBEDTLS_ASN1_IA5_STRING) | \
+ (1u << MBEDTLS_ASN1_UNIVERSAL_STRING) | \
+ (1u << MBEDTLS_ASN1_PRINTABLE_STRING))) != 0))
+
+/*
+ * Bit masks for each of the components of an ASN.1 tag as specified in
+ * ITU X.690 (08/2015), section 8.1 "General rules for encoding",
+ * paragraph 8.1.2.2:
+ *
+ * Bit 8 7 6 5 1
+ * +-------+-----+------------+
+ * | Class | P/C | Tag number |
+ * +-------+-----+------------+
+ */
+#define MBEDTLS_ASN1_TAG_CLASS_MASK 0xC0
+#define MBEDTLS_ASN1_TAG_PC_MASK 0x20
+#define MBEDTLS_ASN1_TAG_VALUE_MASK 0x1F
+
+/** \} name DER constants */
+
+/** Returns the size of the binary string, without the trailing \\0 */
+#define MBEDTLS_OID_SIZE(x) (sizeof(x) - 1)
+
+/**
+ * Compares an mbedtls_asn1_buf structure to a reference OID.
+ *
+ * Only works for 'defined' oid_str values (MBEDTLS_OID_HMAC_SHA1), you cannot use a
+ * 'unsigned char *oid' here!
+ */
+#define MBEDTLS_OID_CMP(oid_str, oid_buf) \
+ ((MBEDTLS_OID_SIZE(oid_str) != (oid_buf)->len) || \
+ memcmp((oid_str), (oid_buf)->p, (oid_buf)->len) != 0)
+
+#define MBEDTLS_OID_CMP_RAW(oid_str, oid_buf, oid_buf_len) \
+ ((MBEDTLS_OID_SIZE(oid_str) != (oid_buf_len)) || \
+ memcmp((oid_str), (oid_buf), (oid_buf_len)) != 0)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \name Functions to parse ASN.1 data structures
+ * \{
+ */
+
+/**
+ * Type-length-value structure that allows for ASN1 using DER.
+ */
+typedef struct mbedtls_asn1_buf {
+ int tag; /**< ASN1 type, e.g. MBEDTLS_ASN1_UTF8_STRING. */
+ size_t len; /**< ASN1 length, in octets. */
+ unsigned char *p; /**< ASN1 data, e.g. in ASCII. */
+}
+mbedtls_asn1_buf;
+
+/**
+ * Container for ASN1 bit strings.
+ */
+typedef struct mbedtls_asn1_bitstring {
+ size_t len; /**< ASN1 length, in octets. */
+ unsigned char unused_bits; /**< Number of unused bits at the end of the string */
+ unsigned char *p; /**< Raw ASN1 data for the bit string */
+}
+mbedtls_asn1_bitstring;
+
+/**
+ * Container for a sequence of ASN.1 items
+ */
+typedef struct mbedtls_asn1_sequence {
+ mbedtls_asn1_buf buf; /**< Buffer containing the given ASN.1 item. */
+
+ /** The next entry in the sequence.
+ *
+ * The details of memory management for sequences are not documented and
+ * may change in future versions. Set this field to \p NULL when
+ * initializing a structure, and do not modify it except via Mbed TLS
+ * library functions.
+ */
+ struct mbedtls_asn1_sequence *next;
+}
+mbedtls_asn1_sequence;
+
+/**
+ * Container for a sequence or list of 'named' ASN.1 data items
+ */
+typedef struct mbedtls_asn1_named_data {
+ mbedtls_asn1_buf oid; /**< The object identifier. */
+ mbedtls_asn1_buf val; /**< The named value. */
+
+ /** The next entry in the sequence.
+ *
+ * The details of memory management for named data sequences are not
+ * documented and may change in future versions. Set this field to \p NULL
+ * when initializing a structure, and do not modify it except via Mbed TLS
+ * library functions.
+ */
+ struct mbedtls_asn1_named_data *next;
+
+ /** Merge next item into the current one?
+ *
+ * This field exists for the sake of Mbed TLS's X.509 certificate parsing
+ * code and may change in future versions of the library.
+ */
+ unsigned char MBEDTLS_PRIVATE(next_merged);
+}
+mbedtls_asn1_named_data;
+
+#if defined(MBEDTLS_ASN1_PARSE_C) || defined(MBEDTLS_X509_CREATE_C)
+/**
+ * \brief Get the length of an ASN.1 element.
+ * Updates the pointer to immediately behind the length.
+ *
+ * \param p On entry, \c *p points to the first byte of the length,
+ * i.e. immediately after the tag.
+ * On successful completion, \c *p points to the first byte
+ * after the length, i.e. the first byte of the content.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param len On successful completion, \c *len contains the length
+ * read from the ASN.1 input.
+ *
+ * \return 0 if successful.
+ * \return #MBEDTLS_ERR_ASN1_OUT_OF_DATA if the ASN.1 element
+ * would end beyond \p end.
+ * \return #MBEDTLS_ERR_ASN1_INVALID_LENGTH if the length is unparsable.
+ */
+int mbedtls_asn1_get_len(unsigned char **p,
+ const unsigned char *end,
+ size_t *len);
+
+/**
+ * \brief Get the tag and length of the element.
+ * Check for the requested tag.
+ * Updates the pointer to immediately behind the tag and length.
+ *
+ * \param p On entry, \c *p points to the start of the ASN.1 element.
+ * On successful completion, \c *p points to the first byte
+ * after the length, i.e. the first byte of the content.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param len On successful completion, \c *len contains the length
+ * read from the ASN.1 input.
+ * \param tag The expected tag.
+ *
+ * \return 0 if successful.
+ * \return #MBEDTLS_ERR_ASN1_UNEXPECTED_TAG if the data does not start
+ * with the requested tag.
+ * \return #MBEDTLS_ERR_ASN1_OUT_OF_DATA if the ASN.1 element
+ * would end beyond \p end.
+ * \return #MBEDTLS_ERR_ASN1_INVALID_LENGTH if the length is unparsable.
+ */
+int mbedtls_asn1_get_tag(unsigned char **p,
+ const unsigned char *end,
+ size_t *len, int tag);
+#endif /* MBEDTLS_ASN1_PARSE_C || MBEDTLS_X509_CREATE_C */
+
+#if defined(MBEDTLS_ASN1_PARSE_C)
+/**
+ * \brief Retrieve a boolean ASN.1 tag and its value.
+ * Updates the pointer to immediately behind the full tag.
+ *
+ * \param p On entry, \c *p points to the start of the ASN.1 element.
+ * On successful completion, \c *p points to the first byte
+ * beyond the ASN.1 element.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param val On success, the parsed value (\c 0 or \c 1).
+ *
+ * \return 0 if successful.
+ * \return An ASN.1 error code if the input does not start with
+ * a valid ASN.1 BOOLEAN.
+ */
+int mbedtls_asn1_get_bool(unsigned char **p,
+ const unsigned char *end,
+ int *val);
+
+/**
+ * \brief Retrieve an integer ASN.1 tag and its value.
+ * Updates the pointer to immediately behind the full tag.
+ *
+ * \param p On entry, \c *p points to the start of the ASN.1 element.
+ * On successful completion, \c *p points to the first byte
+ * beyond the ASN.1 element.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param val On success, the parsed value.
+ *
+ * \return 0 if successful.
+ * \return An ASN.1 error code if the input does not start with
+ * a valid ASN.1 INTEGER.
+ * \return #MBEDTLS_ERR_ASN1_INVALID_LENGTH if the parsed value does
+ * not fit in an \c int.
+ */
+int mbedtls_asn1_get_int(unsigned char **p,
+ const unsigned char *end,
+ int *val);
+
+/**
+ * \brief Retrieve an enumerated ASN.1 tag and its value.
+ * Updates the pointer to immediately behind the full tag.
+ *
+ * \param p On entry, \c *p points to the start of the ASN.1 element.
+ * On successful completion, \c *p points to the first byte
+ * beyond the ASN.1 element.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param val On success, the parsed value.
+ *
+ * \return 0 if successful.
+ * \return An ASN.1 error code if the input does not start with
+ * a valid ASN.1 ENUMERATED.
+ * \return #MBEDTLS_ERR_ASN1_INVALID_LENGTH if the parsed value does
+ * not fit in an \c int.
+ */
+int mbedtls_asn1_get_enum(unsigned char **p,
+ const unsigned char *end,
+ int *val);
+
+/**
+ * \brief Retrieve a bitstring ASN.1 tag and its value.
+ * Updates the pointer to immediately behind the full tag.
+ *
+ * \param p On entry, \c *p points to the start of the ASN.1 element.
+ * On successful completion, \c *p is equal to \p end.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param bs On success, ::mbedtls_asn1_bitstring information about
+ * the parsed value.
+ *
+ * \return 0 if successful.
+ * \return #MBEDTLS_ERR_ASN1_LENGTH_MISMATCH if the input contains
+ * extra data after a valid BIT STRING.
+ * \return An ASN.1 error code if the input does not start with
+ * a valid ASN.1 BIT STRING.
+ */
+int mbedtls_asn1_get_bitstring(unsigned char **p, const unsigned char *end,
+ mbedtls_asn1_bitstring *bs);
+
+/**
+ * \brief Retrieve a bitstring ASN.1 tag without unused bits and its
+ * value.
+ * Updates the pointer to the beginning of the bit/octet string.
+ *
+ * \param p On entry, \c *p points to the start of the ASN.1 element.
+ * On successful completion, \c *p points to the first byte
+ * of the content of the BIT STRING.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param len On success, \c *len is the length of the content in bytes.
+ *
+ * \return 0 if successful.
+ * \return #MBEDTLS_ERR_ASN1_INVALID_DATA if the input starts with
+ * a valid BIT STRING with a nonzero number of unused bits.
+ * \return An ASN.1 error code if the input does not start with
+ * a valid ASN.1 BIT STRING.
+ */
+int mbedtls_asn1_get_bitstring_null(unsigned char **p,
+ const unsigned char *end,
+ size_t *len);
+
+/**
+ * \brief Parses and splits an ASN.1 "SEQUENCE OF <tag>".
+ * Updates the pointer to immediately behind the full sequence tag.
+ *
+ * This function allocates memory for the sequence elements. You can free
+ * the allocated memory with mbedtls_asn1_sequence_free().
+ *
+ * \note On error, this function may return a partial list in \p cur.
+ * You must set `cur->next = NULL` before calling this function!
+ * Otherwise it is impossible to distinguish a previously non-null
+ * pointer from a pointer to an object allocated by this function.
+ *
+ * \note If the sequence is empty, this function does not modify
+ * \c *cur. If the sequence is valid and non-empty, this
+ * function sets `cur->buf.tag` to \p tag. This allows
+ * callers to distinguish between an empty sequence and
+ * a one-element sequence.
+ *
+ * \param p On entry, \c *p points to the start of the ASN.1 element.
+ * On successful completion, \c *p is equal to \p end.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param cur A ::mbedtls_asn1_sequence which this function fills.
+ * When this function returns, \c *cur is the head of a linked
+ * list. Each node in this list is allocated with
+ * mbedtls_calloc() apart from \p cur itself, and should
+ * therefore be freed with mbedtls_free().
+ * The list describes the content of the sequence.
+ * The head of the list (i.e. \c *cur itself) describes the
+ * first element, `*cur->next` describes the second element, etc.
+ * For each element, `buf.tag == tag`, `buf.len` is the length
+ * of the content of the content of the element, and `buf.p`
+ * points to the first byte of the content (i.e. immediately
+ * past the length of the element).
+ * Note that list elements may be allocated even on error.
+ * \param tag Each element of the sequence must have this tag.
+ *
+ * \return 0 if successful.
+ * \return #MBEDTLS_ERR_ASN1_LENGTH_MISMATCH if the input contains
+ * extra data after a valid SEQUENCE OF \p tag.
+ * \return #MBEDTLS_ERR_ASN1_UNEXPECTED_TAG if the input starts with
+ * an ASN.1 SEQUENCE in which an element has a tag that
+ * is different from \p tag.
+ * \return #MBEDTLS_ERR_ASN1_ALLOC_FAILED if a memory allocation failed.
+ * \return An ASN.1 error code if the input does not start with
+ * a valid ASN.1 SEQUENCE.
+ */
+int mbedtls_asn1_get_sequence_of(unsigned char **p,
+ const unsigned char *end,
+ mbedtls_asn1_sequence *cur,
+ int tag);
+/**
+ * \brief Free a heap-allocated linked list presentation of
+ * an ASN.1 sequence, including the first element.
+ *
+ * There are two common ways to manage the memory used for the representation
+ * of a parsed ASN.1 sequence:
+ * - Allocate a head node `mbedtls_asn1_sequence *head` with mbedtls_calloc().
+ * Pass this node as the `cur` argument to mbedtls_asn1_get_sequence_of().
+ * When you have finished processing the sequence,
+ * call mbedtls_asn1_sequence_free() on `head`.
+ * - Allocate a head node `mbedtls_asn1_sequence *head` in any manner,
+ * for example on the stack. Make sure that `head->next == NULL`.
+ * Pass `head` as the `cur` argument to mbedtls_asn1_get_sequence_of().
+ * When you have finished processing the sequence,
+ * call mbedtls_asn1_sequence_free() on `head->cur`,
+ * then free `head` itself in the appropriate manner.
+ *
+ * \param seq The address of the first sequence component. This may
+ * be \c NULL, in which case this functions returns
+ * immediately.
+ */
+void mbedtls_asn1_sequence_free(mbedtls_asn1_sequence *seq);
+
+/**
+ * \brief Traverse an ASN.1 SEQUENCE container and
+ * call a callback for each entry.
+ *
+ * This function checks that the input is a SEQUENCE of elements that
+ * each have a "must" tag, and calls a callback function on the elements
+ * that have a "may" tag.
+ *
+ * For example, to validate that the input is a SEQUENCE of `tag1` and call
+ * `cb` on each element, use
+ * ```
+ * mbedtls_asn1_traverse_sequence_of(&p, end, 0xff, tag1, 0, 0, cb, ctx);
+ * ```
+ *
+ * To validate that the input is a SEQUENCE of ANY and call `cb` on
+ * each element, use
+ * ```
+ * mbedtls_asn1_traverse_sequence_of(&p, end, 0, 0, 0, 0, cb, ctx);
+ * ```
+ *
+ * To validate that the input is a SEQUENCE of CHOICE {NULL, OCTET STRING}
+ * and call `cb` on each element that is an OCTET STRING, use
+ * ```
+ * mbedtls_asn1_traverse_sequence_of(&p, end, 0xfe, 0x04, 0xff, 0x04, cb, ctx);
+ * ```
+ *
+ * The callback is called on the elements with a "may" tag from left to
+ * right. If the input is not a valid SEQUENCE of elements with a "must" tag,
+ * the callback is called on the elements up to the leftmost point where
+ * the input is invalid.
+ *
+ * \warning This function is still experimental and may change
+ * at any time.
+ *
+ * \param p The address of the pointer to the beginning of
+ * the ASN.1 SEQUENCE header. This is updated to
+ * point to the end of the ASN.1 SEQUENCE container
+ * on a successful invocation.
+ * \param end The end of the ASN.1 SEQUENCE container.
+ * \param tag_must_mask A mask to be applied to the ASN.1 tags found within
+ * the SEQUENCE before comparing to \p tag_must_val.
+ * \param tag_must_val The required value of each ASN.1 tag found in the
+ * SEQUENCE, after masking with \p tag_must_mask.
+ * Mismatching tags lead to an error.
+ * For example, a value of \c 0 for both \p tag_must_mask
+ * and \p tag_must_val means that every tag is allowed,
+ * while a value of \c 0xFF for \p tag_must_mask means
+ * that \p tag_must_val is the only allowed tag.
+ * \param tag_may_mask A mask to be applied to the ASN.1 tags found within
+ * the SEQUENCE before comparing to \p tag_may_val.
+ * \param tag_may_val The desired value of each ASN.1 tag found in the
+ * SEQUENCE, after masking with \p tag_may_mask.
+ * Mismatching tags will be silently ignored.
+ * For example, a value of \c 0 for \p tag_may_mask and
+ * \p tag_may_val means that any tag will be considered,
+ * while a value of \c 0xFF for \p tag_may_mask means
+ * that all tags with value different from \p tag_may_val
+ * will be ignored.
+ * \param cb The callback to trigger for each component
+ * in the ASN.1 SEQUENCE that matches \p tag_may_val.
+ * The callback function is called with the following
+ * parameters:
+ * - \p ctx.
+ * - The tag of the current element.
+ * - A pointer to the start of the current element's
+ * content inside the input.
+ * - The length of the content of the current element.
+ * If the callback returns a non-zero value,
+ * the function stops immediately,
+ * forwarding the callback's return value.
+ * \param ctx The context to be passed to the callback \p cb.
+ *
+ * \return \c 0 if successful the entire ASN.1 SEQUENCE
+ * was traversed without parsing or callback errors.
+ * \return #MBEDTLS_ERR_ASN1_LENGTH_MISMATCH if the input
+ * contains extra data after a valid SEQUENCE
+ * of elements with an accepted tag.
+ * \return #MBEDTLS_ERR_ASN1_UNEXPECTED_TAG if the input starts
+ * with an ASN.1 SEQUENCE in which an element has a tag
+ * that is not accepted.
+ * \return An ASN.1 error code if the input does not start with
+ * a valid ASN.1 SEQUENCE.
+ * \return A non-zero error code forwarded from the callback
+ * \p cb in case the latter returns a non-zero value.
+ */
+int mbedtls_asn1_traverse_sequence_of(
+ unsigned char **p,
+ const unsigned char *end,
+ unsigned char tag_must_mask, unsigned char tag_must_val,
+ unsigned char tag_may_mask, unsigned char tag_may_val,
+ int (*cb)(void *ctx, int tag,
+ unsigned char *start, size_t len),
+ void *ctx);
+
+#if defined(MBEDTLS_BIGNUM_C)
+/**
+ * \brief Retrieve an integer ASN.1 tag and its value.
+ * Updates the pointer to immediately behind the full tag.
+ *
+ * \param p On entry, \c *p points to the start of the ASN.1 element.
+ * On successful completion, \c *p points to the first byte
+ * beyond the ASN.1 element.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param X On success, the parsed value.
+ *
+ * \return 0 if successful.
+ * \return An ASN.1 error code if the input does not start with
+ * a valid ASN.1 INTEGER.
+ * \return #MBEDTLS_ERR_ASN1_INVALID_LENGTH if the parsed value does
+ * not fit in an \c int.
+ * \return An MPI error code if the parsed value is too large.
+ */
+int mbedtls_asn1_get_mpi(unsigned char **p,
+ const unsigned char *end,
+ mbedtls_mpi *X);
+#endif /* MBEDTLS_BIGNUM_C */
+
+/**
+ * \brief Retrieve an AlgorithmIdentifier ASN.1 sequence.
+ * Updates the pointer to immediately behind the full
+ * AlgorithmIdentifier.
+ *
+ * \param p On entry, \c *p points to the start of the ASN.1 element.
+ * On successful completion, \c *p points to the first byte
+ * beyond the AlgorithmIdentifier element.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param alg The buffer to receive the OID.
+ * \param params The buffer to receive the parameters.
+ * This is zeroized if there are no parameters.
+ *
+ * \return 0 if successful or a specific ASN.1 or MPI error code.
+ */
+int mbedtls_asn1_get_alg(unsigned char **p,
+ const unsigned char *end,
+ mbedtls_asn1_buf *alg, mbedtls_asn1_buf *params);
+
+/**
+ * \brief Retrieve an AlgorithmIdentifier ASN.1 sequence with NULL or no
+ * params.
+ * Updates the pointer to immediately behind the full
+ * AlgorithmIdentifier.
+ *
+ * \param p On entry, \c *p points to the start of the ASN.1 element.
+ * On successful completion, \c *p points to the first byte
+ * beyond the AlgorithmIdentifier element.
+ * On error, the value of \c *p is undefined.
+ * \param end End of data.
+ * \param alg The buffer to receive the OID.
+ *
+ * \return 0 if successful or a specific ASN.1 or MPI error code.
+ */
+int mbedtls_asn1_get_alg_null(unsigned char **p,
+ const unsigned char *end,
+ mbedtls_asn1_buf *alg);
+
+/**
+ * \brief Find a specific named_data entry in a sequence or list based on
+ * the OID.
+ *
+ * \param list The list to seek through
+ * \param oid The OID to look for
+ * \param len Size of the OID
+ *
+ * \return NULL if not found, or a pointer to the existing entry.
+ */
+const mbedtls_asn1_named_data *mbedtls_asn1_find_named_data(const mbedtls_asn1_named_data *list,
+ const char *oid, size_t len);
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+/**
+ * \brief Free a mbedtls_asn1_named_data entry
+ *
+ * \deprecated This function is deprecated and will be removed in a
+ * future version of the library.
+ * Please use mbedtls_asn1_free_named_data_list()
+ * or mbedtls_asn1_free_named_data_list_shallow().
+ *
+ * \param entry The named data entry to free.
+ * This function calls mbedtls_free() on
+ * `entry->oid.p` and `entry->val.p`.
+ */
+void MBEDTLS_DEPRECATED mbedtls_asn1_free_named_data(mbedtls_asn1_named_data *entry);
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+/**
+ * \brief Free all entries in a mbedtls_asn1_named_data list.
+ *
+ * \param head Pointer to the head of the list of named data entries to free.
+ * This function calls mbedtls_free() on
+ * `entry->oid.p` and `entry->val.p` and then on `entry`
+ * for each list entry, and sets \c *head to \c NULL.
+ */
+void mbedtls_asn1_free_named_data_list(mbedtls_asn1_named_data **head);
+
+/**
+ * \brief Free all shallow entries in a mbedtls_asn1_named_data list,
+ * but do not free internal pointer targets.
+ *
+ * \param name Head of the list of named data entries to free.
+ * This function calls mbedtls_free() on each list element.
+ */
+void mbedtls_asn1_free_named_data_list_shallow(mbedtls_asn1_named_data *name);
+
+/** \} name Functions to parse ASN.1 data structures */
+/** \} addtogroup asn1_module */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_ASN1_PARSE_C */
+
+#endif /* asn1.h */
diff --git a/include/mbedtls/asn1write.h b/include/mbedtls/asn1write.h
new file mode 100644
index 0000000..7af4aba
--- /dev/null
+++ b/include/mbedtls/asn1write.h
@@ -0,0 +1,389 @@
+/**
+ * \file asn1write.h
+ *
+ * \brief ASN.1 buffer writing functionality
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_ASN1_WRITE_H
+#define MBEDTLS_ASN1_WRITE_H
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/asn1.h"
+
+#define MBEDTLS_ASN1_CHK_ADD(g, f) \
+ do \
+ { \
+ if ((ret = (f)) < 0) \
+ return ret; \
+ else \
+ (g) += ret; \
+ } while (0)
+
+#define MBEDTLS_ASN1_CHK_CLEANUP_ADD(g, f) \
+ do \
+ { \
+ if ((ret = (f)) < 0) \
+ goto cleanup; \
+ else \
+ (g) += ret; \
+ } while (0)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(MBEDTLS_ASN1_WRITE_C) || defined(MBEDTLS_X509_USE_C)
+/**
+ * \brief Write a length field in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param len The length value to write.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_len(unsigned char **p, const unsigned char *start,
+ size_t len);
+/**
+ * \brief Write an ASN.1 tag in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param tag The tag to write.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_tag(unsigned char **p, const unsigned char *start,
+ unsigned char tag);
+#endif /* MBEDTLS_ASN1_WRITE_C || MBEDTLS_X509_USE_C */
+
+#if defined(MBEDTLS_ASN1_WRITE_C)
+/**
+ * \brief Write raw buffer data.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param buf The data buffer to write.
+ * \param size The length of the data buffer.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_raw_buffer(unsigned char **p, const unsigned char *start,
+ const unsigned char *buf, size_t size);
+
+#if defined(MBEDTLS_BIGNUM_C)
+/**
+ * \brief Write an arbitrary-precision number (#MBEDTLS_ASN1_INTEGER)
+ * in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param X The MPI to write.
+ * It must be non-negative.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_mpi(unsigned char **p, const unsigned char *start,
+ const mbedtls_mpi *X);
+#endif /* MBEDTLS_BIGNUM_C */
+
+/**
+ * \brief Write a NULL tag (#MBEDTLS_ASN1_NULL) with zero data
+ * in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_null(unsigned char **p, const unsigned char *start);
+
+/**
+ * \brief Write an OID tag (#MBEDTLS_ASN1_OID) and data
+ * in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param oid The OID to write.
+ * \param oid_len The length of the OID.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_oid(unsigned char **p, const unsigned char *start,
+ const char *oid, size_t oid_len);
+
+/**
+ * \brief Write an AlgorithmIdentifier sequence in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param oid The OID of the algorithm to write.
+ * \param oid_len The length of the algorithm's OID.
+ * \param par_len The length of the parameters, which must be already written.
+ * If 0, NULL parameters are added
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_algorithm_identifier(unsigned char **p,
+ const unsigned char *start,
+ const char *oid, size_t oid_len,
+ size_t par_len);
+
+/**
+ * \brief Write an AlgorithmIdentifier sequence in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param oid The OID of the algorithm to write.
+ * \param oid_len The length of the algorithm's OID.
+ * \param par_len The length of the parameters, which must be already written.
+ * \param has_par If there are any parameters. If 0, par_len must be 0. If 1
+ * and \p par_len is 0, NULL parameters are added.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_algorithm_identifier_ext(unsigned char **p,
+ const unsigned char *start,
+ const char *oid, size_t oid_len,
+ size_t par_len, int has_par);
+
+/**
+ * \brief Write a boolean tag (#MBEDTLS_ASN1_BOOLEAN) and value
+ * in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param boolean The boolean value to write, either \c 0 or \c 1.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_bool(unsigned char **p, const unsigned char *start,
+ int boolean);
+
+/**
+ * \brief Write an int tag (#MBEDTLS_ASN1_INTEGER) and value
+ * in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param val The integer value to write.
+ * It must be non-negative.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_int(unsigned char **p, const unsigned char *start, int val);
+
+/**
+ * \brief Write an enum tag (#MBEDTLS_ASN1_ENUMERATED) and value
+ * in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param val The integer value to write.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_asn1_write_enum(unsigned char **p, const unsigned char *start, int val);
+
+/**
+ * \brief Write a string in ASN.1 format using a specific
+ * string encoding tag.
+
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param tag The string encoding tag to write, e.g.
+ * #MBEDTLS_ASN1_UTF8_STRING.
+ * \param text The string to write.
+ * \param text_len The length of \p text in bytes (which might
+ * be strictly larger than the number of characters).
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_asn1_write_tagged_string(unsigned char **p, const unsigned char *start,
+ int tag, const char *text,
+ size_t text_len);
+
+/**
+ * \brief Write a string in ASN.1 format using the PrintableString
+ * string encoding tag (#MBEDTLS_ASN1_PRINTABLE_STRING).
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param text The string to write.
+ * \param text_len The length of \p text in bytes (which might
+ * be strictly larger than the number of characters).
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_asn1_write_printable_string(unsigned char **p,
+ const unsigned char *start,
+ const char *text, size_t text_len);
+
+/**
+ * \brief Write a UTF8 string in ASN.1 format using the UTF8String
+ * string encoding tag (#MBEDTLS_ASN1_UTF8_STRING).
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param text The string to write.
+ * \param text_len The length of \p text in bytes (which might
+ * be strictly larger than the number of characters).
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_asn1_write_utf8_string(unsigned char **p, const unsigned char *start,
+ const char *text, size_t text_len);
+
+/**
+ * \brief Write a string in ASN.1 format using the IA5String
+ * string encoding tag (#MBEDTLS_ASN1_IA5_STRING).
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param text The string to write.
+ * \param text_len The length of \p text in bytes (which might
+ * be strictly larger than the number of characters).
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_asn1_write_ia5_string(unsigned char **p, const unsigned char *start,
+ const char *text, size_t text_len);
+
+/**
+ * \brief Write a bitstring tag (#MBEDTLS_ASN1_BIT_STRING) and
+ * value in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param buf The bitstring to write.
+ * \param bits The total number of bits in the bitstring.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_asn1_write_bitstring(unsigned char **p, const unsigned char *start,
+ const unsigned char *buf, size_t bits);
+
+/**
+ * \brief This function writes a named bitstring tag
+ * (#MBEDTLS_ASN1_BIT_STRING) and value in ASN.1 format.
+ *
+ * As stated in RFC 5280 Appendix B, trailing zeroes are
+ * omitted when encoding named bitstrings in DER.
+ *
+ * \note This function works backwards within the data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer which is used for bounds-checking.
+ * \param buf The bitstring to write.
+ * \param bits The total number of bits in the bitstring.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_asn1_write_named_bitstring(unsigned char **p,
+ const unsigned char *start,
+ const unsigned char *buf,
+ size_t bits);
+
+/**
+ * \brief Write an octet string tag (#MBEDTLS_ASN1_OCTET_STRING)
+ * and value in ASN.1 format.
+ *
+ * \note This function works backwards in data buffer.
+ *
+ * \param p The reference to the current position pointer.
+ * \param start The start of the buffer, for bounds-checking.
+ * \param buf The buffer holding the data to write.
+ * \param size The length of the data buffer \p buf.
+ *
+ * \return The number of bytes written to \p p on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_asn1_write_octet_string(unsigned char **p, const unsigned char *start,
+ const unsigned char *buf, size_t size);
+
+/**
+ * \brief Create or find a specific named_data entry for writing in a
+ * sequence or list based on the OID. If not already in there,
+ * a new entry is added to the head of the list.
+ * Warning: Destructive behaviour for the val data!
+ *
+ * \param list The pointer to the location of the head of the list to seek
+ * through (will be updated in case of a new entry).
+ * \param oid The OID to look for.
+ * \param oid_len The size of the OID.
+ * \param val The associated data to store. If this is \c NULL,
+ * no data is copied to the new or existing buffer.
+ * \param val_len The minimum length of the data buffer needed.
+ * If this is 0, do not allocate a buffer for the associated
+ * data.
+ * If the OID was already present, enlarge, shrink or free
+ * the existing buffer to fit \p val_len.
+ *
+ * \return A pointer to the new / existing entry on success.
+ * \return \c NULL if there was a memory allocation error.
+ */
+mbedtls_asn1_named_data *mbedtls_asn1_store_named_data(mbedtls_asn1_named_data **list,
+ const char *oid, size_t oid_len,
+ const unsigned char *val,
+ size_t val_len);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_ASN1_WRITE_C */
+
+#endif /* MBEDTLS_ASN1_WRITE_H */
diff --git a/include/mbedtls/base64.h b/include/mbedtls/base64.h
new file mode 100644
index 0000000..8f459b7
--- /dev/null
+++ b/include/mbedtls/base64.h
@@ -0,0 +1,82 @@
+/**
+ * \file base64.h
+ *
+ * \brief RFC 1521 base64 encoding/decoding
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_BASE64_H
+#define MBEDTLS_BASE64_H
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+
+/** Output buffer too small. */
+#define MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL -0x002A
+/** Invalid character in input. */
+#define MBEDTLS_ERR_BASE64_INVALID_CHARACTER -0x002C
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Encode a buffer into base64 format
+ *
+ * \param dst destination buffer
+ * \param dlen size of the destination buffer
+ * \param olen number of bytes written
+ * \param src source buffer
+ * \param slen amount of data to be encoded
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL.
+ * *olen is always updated to reflect the amount
+ * of data that has (or would have) been written.
+ * If that length cannot be represented, then no data is
+ * written to the buffer and *olen is set to the maximum
+ * length representable as a size_t.
+ *
+ * \note Call this function with dlen = 0 to obtain the
+ * required buffer size in *olen
+ */
+int mbedtls_base64_encode(unsigned char *dst, size_t dlen, size_t *olen,
+ const unsigned char *src, size_t slen);
+
+/**
+ * \brief Decode a base64-formatted buffer
+ *
+ * \param dst destination buffer (can be NULL for checking size)
+ * \param dlen size of the destination buffer
+ * \param olen number of bytes written
+ * \param src source buffer
+ * \param slen amount of data to be decoded
+ *
+ * \return 0 if successful, MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL, or
+ * MBEDTLS_ERR_BASE64_INVALID_CHARACTER if the input data is
+ * not correct. *olen is always updated to reflect the amount
+ * of data that has (or would have) been written.
+ *
+ * \note Call this function with *dst = NULL or dlen = 0 to obtain
+ * the required buffer size in *olen
+ */
+int mbedtls_base64_decode(unsigned char *dst, size_t dlen, size_t *olen,
+ const unsigned char *src, size_t slen);
+
+#if defined(MBEDTLS_SELF_TEST)
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if the test failed
+ */
+int mbedtls_base64_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* base64.h */
diff --git a/include/mbedtls/bignum.h b/include/mbedtls/bignum.h
new file mode 100644
index 0000000..931e06d
--- /dev/null
+++ b/include/mbedtls/bignum.h
@@ -0,0 +1,1084 @@
+/**
+ * \file bignum.h
+ *
+ * \brief Multi-precision integer library
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_BIGNUM_H
+#define MBEDTLS_BIGNUM_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#if defined(MBEDTLS_FS_IO)
+#include <stdio.h>
+#endif
+
+/** An error occurred while reading from or writing to a file. */
+#define MBEDTLS_ERR_MPI_FILE_IO_ERROR -0x0002
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_MPI_BAD_INPUT_DATA -0x0004
+/** There is an invalid character in the digit string. */
+#define MBEDTLS_ERR_MPI_INVALID_CHARACTER -0x0006
+/** The buffer is too small to write to. */
+#define MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL -0x0008
+/** The input arguments are negative or result in illegal output. */
+#define MBEDTLS_ERR_MPI_NEGATIVE_VALUE -0x000A
+/** The input argument for division is zero, which is not allowed. */
+#define MBEDTLS_ERR_MPI_DIVISION_BY_ZERO -0x000C
+/** The input arguments are not acceptable. */
+#define MBEDTLS_ERR_MPI_NOT_ACCEPTABLE -0x000E
+/** Memory allocation failed. */
+#define MBEDTLS_ERR_MPI_ALLOC_FAILED -0x0010
+
+#define MBEDTLS_MPI_CHK(f) \
+ do \
+ { \
+ if ((ret = (f)) != 0) \
+ goto cleanup; \
+ } while (0)
+
+/*
+ * Maximum size MPIs are allowed to grow to in number of limbs.
+ */
+#define MBEDTLS_MPI_MAX_LIMBS 10000
+
+#if !defined(MBEDTLS_MPI_WINDOW_SIZE)
+/*
+ * Maximum window size used for modular exponentiation. Default: 2
+ * Minimum value: 1. Maximum value: 6.
+ *
+ * Result is an array of ( 2 ** MBEDTLS_MPI_WINDOW_SIZE ) MPIs used
+ * for the sliding window calculation. (So 64 by default)
+ *
+ * Reduction in size, reduces speed.
+ */
+#define MBEDTLS_MPI_WINDOW_SIZE 2 /**< Maximum window size used. */
+#endif /* !MBEDTLS_MPI_WINDOW_SIZE */
+
+#if !defined(MBEDTLS_MPI_MAX_SIZE)
+/*
+ * Maximum size of MPIs allowed in bits and bytes for user-MPIs.
+ * ( Default: 512 bytes => 4096 bits, Maximum tested: 2048 bytes => 16384 bits )
+ *
+ * Note: Calculations can temporarily result in larger MPIs. So the number
+ * of limbs required (MBEDTLS_MPI_MAX_LIMBS) is higher.
+ */
+#define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */
+#endif /* !MBEDTLS_MPI_MAX_SIZE */
+
+#define MBEDTLS_MPI_MAX_BITS (8 * MBEDTLS_MPI_MAX_SIZE) /**< Maximum number of bits for usable MPIs. */
+
+/*
+ * When reading from files with mbedtls_mpi_read_file() and writing to files with
+ * mbedtls_mpi_write_file() the buffer should have space
+ * for a (short) label, the MPI (in the provided radix), the newline
+ * characters and the '\0'.
+ *
+ * By default we assume at least a 10 char label, a minimum radix of 10
+ * (decimal) and a maximum of 4096 bit numbers (1234 decimal chars).
+ * Autosized at compile time for at least a 10 char label, a minimum radix
+ * of 10 (decimal) for a number of MBEDTLS_MPI_MAX_BITS size.
+ *
+ * This used to be statically sized to 1250 for a maximum of 4096 bit
+ * numbers (1234 decimal chars).
+ *
+ * Calculate using the formula:
+ * MBEDTLS_MPI_RW_BUFFER_SIZE = ceil(MBEDTLS_MPI_MAX_BITS / ln(10) * ln(2)) +
+ * LabelSize + 6
+ */
+#define MBEDTLS_MPI_MAX_BITS_SCALE100 (100 * MBEDTLS_MPI_MAX_BITS)
+#define MBEDTLS_LN_2_DIV_LN_10_SCALE100 332
+#define MBEDTLS_MPI_RW_BUFFER_SIZE (((MBEDTLS_MPI_MAX_BITS_SCALE100 + \
+ MBEDTLS_LN_2_DIV_LN_10_SCALE100 - 1) / \
+ MBEDTLS_LN_2_DIV_LN_10_SCALE100) + 10 + 6)
+
+/*
+ * Define the base integer type, architecture-wise.
+ *
+ * 32 or 64-bit integer types can be forced regardless of the underlying
+ * architecture by defining MBEDTLS_HAVE_INT32 or MBEDTLS_HAVE_INT64
+ * respectively and undefining MBEDTLS_HAVE_ASM.
+ *
+ * Double-width integers (e.g. 128-bit in 64-bit architectures) can be
+ * disabled by defining MBEDTLS_NO_UDBL_DIVISION.
+ */
+#if !defined(MBEDTLS_HAVE_INT32)
+ #if defined(_MSC_VER) && defined(_M_AMD64)
+/* Always choose 64-bit when using MSC */
+ #if !defined(MBEDTLS_HAVE_INT64)
+ #define MBEDTLS_HAVE_INT64
+ #endif /* !MBEDTLS_HAVE_INT64 */
+typedef int64_t mbedtls_mpi_sint;
+typedef uint64_t mbedtls_mpi_uint;
+#define MBEDTLS_MPI_UINT_MAX UINT64_MAX
+ #elif defined(__GNUC__) && ( \
+ defined(__amd64__) || defined(__x86_64__) || \
+ defined(__ppc64__) || defined(__powerpc64__) || \
+ defined(__ia64__) || defined(__alpha__) || \
+ (defined(__sparc__) && defined(__arch64__)) || \
+ defined(__s390x__) || defined(__mips64) || \
+ defined(__aarch64__))
+ #if !defined(MBEDTLS_HAVE_INT64)
+ #define MBEDTLS_HAVE_INT64
+ #endif /* MBEDTLS_HAVE_INT64 */
+typedef int64_t mbedtls_mpi_sint;
+typedef uint64_t mbedtls_mpi_uint;
+#define MBEDTLS_MPI_UINT_MAX UINT64_MAX
+ #if !defined(MBEDTLS_NO_UDBL_DIVISION)
+/* mbedtls_t_udbl defined as 128-bit unsigned int */
+typedef unsigned int mbedtls_t_udbl __attribute__((mode(TI)));
+ #define MBEDTLS_HAVE_UDBL
+ #endif /* !MBEDTLS_NO_UDBL_DIVISION */
+ #elif defined(__ARMCC_VERSION) && defined(__aarch64__)
+/*
+ * __ARMCC_VERSION is defined for both armcc and armclang and
+ * __aarch64__ is only defined by armclang when compiling 64-bit code
+ */
+ #if !defined(MBEDTLS_HAVE_INT64)
+ #define MBEDTLS_HAVE_INT64
+ #endif /* !MBEDTLS_HAVE_INT64 */
+typedef int64_t mbedtls_mpi_sint;
+typedef uint64_t mbedtls_mpi_uint;
+#define MBEDTLS_MPI_UINT_MAX UINT64_MAX
+ #if !defined(MBEDTLS_NO_UDBL_DIVISION)
+/* mbedtls_t_udbl defined as 128-bit unsigned int */
+typedef __uint128_t mbedtls_t_udbl;
+ #define MBEDTLS_HAVE_UDBL
+ #endif /* !MBEDTLS_NO_UDBL_DIVISION */
+ #elif defined(MBEDTLS_HAVE_INT64)
+/* Force 64-bit integers with unknown compiler */
+typedef int64_t mbedtls_mpi_sint;
+typedef uint64_t mbedtls_mpi_uint;
+#define MBEDTLS_MPI_UINT_MAX UINT64_MAX
+ #endif
+#endif /* !MBEDTLS_HAVE_INT32 */
+
+#if !defined(MBEDTLS_HAVE_INT64)
+/* Default to 32-bit compilation */
+ #if !defined(MBEDTLS_HAVE_INT32)
+ #define MBEDTLS_HAVE_INT32
+ #endif /* !MBEDTLS_HAVE_INT32 */
+typedef int32_t mbedtls_mpi_sint;
+typedef uint32_t mbedtls_mpi_uint;
+#define MBEDTLS_MPI_UINT_MAX UINT32_MAX
+ #if !defined(MBEDTLS_NO_UDBL_DIVISION)
+typedef uint64_t mbedtls_t_udbl;
+ #define MBEDTLS_HAVE_UDBL
+ #endif /* !MBEDTLS_NO_UDBL_DIVISION */
+#endif /* !MBEDTLS_HAVE_INT64 */
+
+/*
+ * Sanity check that exactly one of MBEDTLS_HAVE_INT32 or MBEDTLS_HAVE_INT64 is defined,
+ * so that code elsewhere doesn't have to check.
+ */
+#if (!(defined(MBEDTLS_HAVE_INT32) || defined(MBEDTLS_HAVE_INT64))) || \
+ (defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64))
+#error "Only 32-bit or 64-bit limbs are supported in bignum"
+#endif
+
+/** \typedef mbedtls_mpi_uint
+ * \brief The type of machine digits in a bignum, called _limbs_.
+ *
+ * This is always an unsigned integer type with no padding bits. The size
+ * is platform-dependent.
+ */
+
+/** \typedef mbedtls_mpi_sint
+ * \brief The signed type corresponding to #mbedtls_mpi_uint.
+ *
+ * This is always an signed integer type with no padding bits. The size
+ * is platform-dependent.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief MPI structure
+ */
+typedef struct mbedtls_mpi {
+ /** Pointer to limbs.
+ *
+ * This may be \c NULL if \c n is 0.
+ */
+ mbedtls_mpi_uint *MBEDTLS_PRIVATE(p);
+
+ /** Sign: -1 if the mpi is negative, 1 otherwise.
+ *
+ * The number 0 must be represented with `s = +1`. Although many library
+ * functions treat all-limbs-zero as equivalent to a valid representation
+ * of 0 regardless of the sign bit, there are exceptions, so bignum
+ * functions and external callers must always set \c s to +1 for the
+ * number zero.
+ *
+ * Note that this implies that calloc() or `... = {0}` does not create
+ * a valid MPI representation. You must call mbedtls_mpi_init().
+ */
+ signed short MBEDTLS_PRIVATE(s);
+
+ /** Total number of limbs in \c p. */
+ unsigned short MBEDTLS_PRIVATE(n);
+ /* Make sure that MBEDTLS_MPI_MAX_LIMBS fits in n.
+ * Use the same limit value on all platforms so that we don't have to
+ * think about different behavior on the rare platforms where
+ * unsigned short can store values larger than the minimum required by
+ * the C language, which is 65535.
+ */
+#if MBEDTLS_MPI_MAX_LIMBS > 65535
+#error "MBEDTLS_MPI_MAX_LIMBS > 65535 is not supported"
+#endif
+}
+mbedtls_mpi;
+
+/**
+ * \brief Initialize an MPI context.
+ *
+ * This makes the MPI ready to be set or freed,
+ * but does not define a value for the MPI.
+ *
+ * \param X The MPI context to initialize. This must not be \c NULL.
+ */
+void mbedtls_mpi_init(mbedtls_mpi *X);
+
+/**
+ * \brief This function frees the components of an MPI context.
+ *
+ * \param X The MPI context to be cleared. This may be \c NULL,
+ * in which case this function is a no-op. If it is
+ * not \c NULL, it must point to an initialized MPI.
+ */
+void mbedtls_mpi_free(mbedtls_mpi *X);
+
+/**
+ * \brief Enlarge an MPI to the specified number of limbs.
+ *
+ * \note This function does nothing if the MPI is
+ * already large enough.
+ *
+ * \param X The MPI to grow. It must be initialized.
+ * \param nblimbs The target number of limbs.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_mpi_grow(mbedtls_mpi *X, size_t nblimbs);
+
+/**
+ * \brief This function resizes an MPI downwards, keeping at least the
+ * specified number of limbs.
+ *
+ * If \c X is smaller than \c nblimbs, it is resized up
+ * instead.
+ *
+ * \param X The MPI to shrink. This must point to an initialized MPI.
+ * \param nblimbs The minimum number of limbs to keep.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed
+ * (this can only happen when resizing up).
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_mpi_shrink(mbedtls_mpi *X, size_t nblimbs);
+
+/**
+ * \brief Make a copy of an MPI.
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param Y The source MPI. This must point to an initialized MPI.
+ *
+ * \note The limb-buffer in the destination MPI is enlarged
+ * if necessary to hold the value in the source MPI.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_mpi_copy(mbedtls_mpi *X, const mbedtls_mpi *Y);
+
+/**
+ * \brief Swap the contents of two MPIs.
+ *
+ * \param X The first MPI. It must be initialized.
+ * \param Y The second MPI. It must be initialized.
+ */
+void mbedtls_mpi_swap(mbedtls_mpi *X, mbedtls_mpi *Y);
+
+/**
+ * \brief Perform a safe conditional copy of MPI which doesn't
+ * reveal whether the condition was true or not.
+ *
+ * \param X The MPI to conditionally assign to. This must point
+ * to an initialized MPI.
+ * \param Y The MPI to be assigned from. This must point to an
+ * initialized MPI.
+ * \param assign The condition deciding whether to perform the
+ * assignment or not. Must be either 0 or 1:
+ * * \c 1: Perform the assignment `X = Y`.
+ * * \c 0: Keep the original value of \p X.
+ *
+ * \note This function is equivalent to
+ * `if( assign ) mbedtls_mpi_copy( X, Y );`
+ * except that it avoids leaking any information about whether
+ * the assignment was done or not (the above code may leak
+ * information through branch prediction and/or memory access
+ * patterns analysis).
+ *
+ * \warning If \p assign is neither 0 nor 1, the result of this function
+ * is indeterminate, and the resulting value in \p X might be
+ * neither its original value nor the value in \p Y.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_mpi_safe_cond_assign(mbedtls_mpi *X, const mbedtls_mpi *Y, unsigned char assign);
+
+/**
+ * \brief Perform a safe conditional swap which doesn't
+ * reveal whether the condition was true or not.
+ *
+ * \param X The first MPI. This must be initialized.
+ * \param Y The second MPI. This must be initialized.
+ * \param swap The condition deciding whether to perform
+ * the swap or not. Must be either 0 or 1:
+ * * \c 1: Swap the values of \p X and \p Y.
+ * * \c 0: Keep the original values of \p X and \p Y.
+ *
+ * \note This function is equivalent to
+ * if( swap ) mbedtls_mpi_swap( X, Y );
+ * except that it avoids leaking any information about whether
+ * the swap was done or not (the above code may leak
+ * information through branch prediction and/or memory access
+ * patterns analysis).
+ *
+ * \warning If \p swap is neither 0 nor 1, the result of this function
+ * is indeterminate, and both \p X and \p Y might end up with
+ * values different to either of the original ones.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return Another negative error code on other kinds of failure.
+ *
+ */
+int mbedtls_mpi_safe_cond_swap(mbedtls_mpi *X, mbedtls_mpi *Y, unsigned char swap);
+
+/**
+ * \brief Store integer value in MPI.
+ *
+ * \param X The MPI to set. This must be initialized.
+ * \param z The value to use.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_mpi_lset(mbedtls_mpi *X, mbedtls_mpi_sint z);
+
+/**
+ * \brief Get a specific bit from an MPI.
+ *
+ * \param X The MPI to query. This must be initialized.
+ * \param pos Zero-based index of the bit to query.
+ *
+ * \return \c 0 or \c 1 on success, depending on whether bit \c pos
+ * of \c X is unset or set.
+ * \return A negative error code on failure.
+ */
+int mbedtls_mpi_get_bit(const mbedtls_mpi *X, size_t pos);
+
+/**
+ * \brief Modify a specific bit in an MPI.
+ *
+ * \note This function will grow the target MPI if necessary to set a
+ * bit to \c 1 in a not yet existing limb. It will not grow if
+ * the bit should be set to \c 0.
+ *
+ * \param X The MPI to modify. This must be initialized.
+ * \param pos Zero-based index of the bit to modify.
+ * \param val The desired value of bit \c pos: \c 0 or \c 1.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_mpi_set_bit(mbedtls_mpi *X, size_t pos, unsigned char val);
+
+/**
+ * \brief Return the number of bits of value \c 0 before the
+ * least significant bit of value \c 1.
+ *
+ * \note This is the same as the zero-based index of
+ * the least significant bit of value \c 1.
+ *
+ * \param X The MPI to query.
+ *
+ * \return The number of bits of value \c 0 before the least significant
+ * bit of value \c 1 in \p X.
+ */
+size_t mbedtls_mpi_lsb(const mbedtls_mpi *X);
+
+/**
+ * \brief Return the number of bits up to and including the most
+ * significant bit of value \c 1.
+ *
+ * * \note This is same as the one-based index of the most
+ * significant bit of value \c 1.
+ *
+ * \param X The MPI to query. This must point to an initialized MPI.
+ *
+ * \return The number of bits up to and including the most
+ * significant bit of value \c 1.
+ */
+size_t mbedtls_mpi_bitlen(const mbedtls_mpi *X);
+
+/**
+ * \brief Return the total size of an MPI value in bytes.
+ *
+ * \param X The MPI to use. This must point to an initialized MPI.
+ *
+ * \note The value returned by this function may be less than
+ * the number of bytes used to store \p X internally.
+ * This happens if and only if there are trailing bytes
+ * of value zero.
+ *
+ * \return The least number of bytes capable of storing
+ * the absolute value of \p X.
+ */
+size_t mbedtls_mpi_size(const mbedtls_mpi *X);
+
+/**
+ * \brief Import an MPI from an ASCII string.
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param radix The numeric base of the input string.
+ * \param s Null-terminated string buffer.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_mpi_read_string(mbedtls_mpi *X, int radix, const char *s);
+
+/**
+ * \brief Export an MPI to an ASCII string.
+ *
+ * \param X The source MPI. This must point to an initialized MPI.
+ * \param radix The numeric base of the output string.
+ * \param buf The buffer to write the string to. This must be writable
+ * buffer of length \p buflen Bytes.
+ * \param buflen The available size in Bytes of \p buf.
+ * \param olen The address at which to store the length of the string
+ * written, including the final \c NULL byte. This must
+ * not be \c NULL.
+ *
+ * \note You can call this function with `buflen == 0` to obtain the
+ * minimum required buffer size in `*olen`.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if the target buffer \p buf
+ * is too small to hold the value of \p X in the desired base.
+ * In this case, `*olen` is nonetheless updated to contain the
+ * size of \p buf required for a successful call.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_write_string(const mbedtls_mpi *X, int radix,
+ char *buf, size_t buflen, size_t *olen);
+
+#if defined(MBEDTLS_FS_IO)
+/**
+ * \brief Read an MPI from a line in an opened file.
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param radix The numeric base of the string representation used
+ * in the source line.
+ * \param fin The input file handle to use. This must not be \c NULL.
+ *
+ * \note On success, this function advances the file stream
+ * to the end of the current line or to EOF.
+ *
+ * The function returns \c 0 on an empty line.
+ *
+ * Leading whitespaces are ignored, as is a
+ * '0x' prefix for radix \c 16.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if the file read buffer
+ * is too small.
+ * \return Another negative error code on failure.
+ */
+int mbedtls_mpi_read_file(mbedtls_mpi *X, int radix, FILE *fin);
+
+/**
+ * \brief Export an MPI into an opened file.
+ *
+ * \param p A string prefix to emit prior to the MPI data.
+ * For example, this might be a label, or "0x" when
+ * printing in base \c 16. This may be \c NULL if no prefix
+ * is needed.
+ * \param X The source MPI. This must point to an initialized MPI.
+ * \param radix The numeric base to be used in the emitted string.
+ * \param fout The output file handle. This may be \c NULL, in which case
+ * the output is written to \c stdout.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_mpi_write_file(const char *p, const mbedtls_mpi *X,
+ int radix, FILE *fout);
+#endif /* MBEDTLS_FS_IO */
+
+/**
+ * \brief Import an MPI from unsigned big endian binary data.
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param buf The input buffer. This must be a readable buffer of length
+ * \p buflen Bytes.
+ * \param buflen The length of the input buffer \p buf in Bytes.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_read_binary(mbedtls_mpi *X, const unsigned char *buf,
+ size_t buflen);
+
+/**
+ * \brief Import X from unsigned binary data, little endian
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param buf The input buffer. This must be a readable buffer of length
+ * \p buflen Bytes.
+ * \param buflen The length of the input buffer \p buf in Bytes.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_read_binary_le(mbedtls_mpi *X,
+ const unsigned char *buf, size_t buflen);
+
+/**
+ * \brief Export X into unsigned binary data, big endian.
+ * Always fills the whole buffer, which will start with zeros
+ * if the number is smaller.
+ *
+ * \param X The source MPI. This must point to an initialized MPI.
+ * \param buf The output buffer. This must be a writable buffer of length
+ * \p buflen Bytes.
+ * \param buflen The size of the output buffer \p buf in Bytes.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p buf isn't
+ * large enough to hold the value of \p X.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_write_binary(const mbedtls_mpi *X, unsigned char *buf,
+ size_t buflen);
+
+/**
+ * \brief Export X into unsigned binary data, little endian.
+ * Always fills the whole buffer, which will end with zeros
+ * if the number is smaller.
+ *
+ * \param X The source MPI. This must point to an initialized MPI.
+ * \param buf The output buffer. This must be a writable buffer of length
+ * \p buflen Bytes.
+ * \param buflen The size of the output buffer \p buf in Bytes.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_BUFFER_TOO_SMALL if \p buf isn't
+ * large enough to hold the value of \p X.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_write_binary_le(const mbedtls_mpi *X,
+ unsigned char *buf, size_t buflen);
+
+/**
+ * \brief Perform a left-shift on an MPI: X <<= count
+ *
+ * \param X The MPI to shift. This must point to an initialized MPI.
+ * The MPI pointed by \p X may be resized to fit
+ * the resulting number.
+ * \param count The number of bits to shift by.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_shift_l(mbedtls_mpi *X, size_t count);
+
+/**
+ * \brief Perform a right-shift on an MPI: X >>= count
+ *
+ * \param X The MPI to shift. This must point to an initialized MPI.
+ * \param count The number of bits to shift by.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_shift_r(mbedtls_mpi *X, size_t count);
+
+/**
+ * \brief Compare the absolute values of two MPIs.
+ *
+ * \param X The left-hand MPI. This must point to an initialized MPI.
+ * \param Y The right-hand MPI. This must point to an initialized MPI.
+ *
+ * \return \c 1 if `|X|` is greater than `|Y|`.
+ * \return \c -1 if `|X|` is lesser than `|Y|`.
+ * \return \c 0 if `|X|` is equal to `|Y|`.
+ */
+int mbedtls_mpi_cmp_abs(const mbedtls_mpi *X, const mbedtls_mpi *Y);
+
+/**
+ * \brief Compare two MPIs.
+ *
+ * \param X The left-hand MPI. This must point to an initialized MPI.
+ * \param Y The right-hand MPI. This must point to an initialized MPI.
+ *
+ * \return \c 1 if \p X is greater than \p Y.
+ * \return \c -1 if \p X is lesser than \p Y.
+ * \return \c 0 if \p X is equal to \p Y.
+ */
+int mbedtls_mpi_cmp_mpi(const mbedtls_mpi *X, const mbedtls_mpi *Y);
+
+/**
+ * \brief Check if an MPI is less than the other in constant time.
+ *
+ * \param X The left-hand MPI. This must point to an initialized MPI
+ * with the same allocated length as Y.
+ * \param Y The right-hand MPI. This must point to an initialized MPI
+ * with the same allocated length as X.
+ * \param ret The result of the comparison:
+ * \c 1 if \p X is less than \p Y.
+ * \c 0 if \p X is greater than or equal to \p Y.
+ *
+ * \return 0 on success.
+ * \return MBEDTLS_ERR_MPI_BAD_INPUT_DATA if the allocated length of
+ * the two input MPIs is not the same.
+ */
+int mbedtls_mpi_lt_mpi_ct(const mbedtls_mpi *X, const mbedtls_mpi *Y,
+ unsigned *ret);
+
+/**
+ * \brief Compare an MPI with an integer.
+ *
+ * \param X The left-hand MPI. This must point to an initialized MPI.
+ * \param z The integer value to compare \p X to.
+ *
+ * \return \c 1 if \p X is greater than \p z.
+ * \return \c -1 if \p X is lesser than \p z.
+ * \return \c 0 if \p X is equal to \p z.
+ */
+int mbedtls_mpi_cmp_int(const mbedtls_mpi *X, mbedtls_mpi_sint z);
+
+/**
+ * \brief Perform an unsigned addition of MPIs: X = |A| + |B|
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param A The first summand. This must point to an initialized MPI.
+ * \param B The second summand. This must point to an initialized MPI.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_add_abs(mbedtls_mpi *X, const mbedtls_mpi *A,
+ const mbedtls_mpi *B);
+
+/**
+ * \brief Perform an unsigned subtraction of MPIs: X = |A| - |B|
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param A The minuend. This must point to an initialized MPI.
+ * \param B The subtrahend. This must point to an initialized MPI.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p B is greater than \p A.
+ * \return Another negative error code on different kinds of failure.
+ *
+ */
+int mbedtls_mpi_sub_abs(mbedtls_mpi *X, const mbedtls_mpi *A,
+ const mbedtls_mpi *B);
+
+/**
+ * \brief Perform a signed addition of MPIs: X = A + B
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param A The first summand. This must point to an initialized MPI.
+ * \param B The second summand. This must point to an initialized MPI.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_add_mpi(mbedtls_mpi *X, const mbedtls_mpi *A,
+ const mbedtls_mpi *B);
+
+/**
+ * \brief Perform a signed subtraction of MPIs: X = A - B
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param A The minuend. This must point to an initialized MPI.
+ * \param B The subtrahend. This must point to an initialized MPI.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_sub_mpi(mbedtls_mpi *X, const mbedtls_mpi *A,
+ const mbedtls_mpi *B);
+
+/**
+ * \brief Perform a signed addition of an MPI and an integer: X = A + b
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param A The first summand. This must point to an initialized MPI.
+ * \param b The second summand.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_add_int(mbedtls_mpi *X, const mbedtls_mpi *A,
+ mbedtls_mpi_sint b);
+
+/**
+ * \brief Perform a signed subtraction of an MPI and an integer:
+ * X = A - b
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param A The minuend. This must point to an initialized MPI.
+ * \param b The subtrahend.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_sub_int(mbedtls_mpi *X, const mbedtls_mpi *A,
+ mbedtls_mpi_sint b);
+
+/**
+ * \brief Perform a multiplication of two MPIs: X = A * B
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param A The first factor. This must point to an initialized MPI.
+ * \param B The second factor. This must point to an initialized MPI.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ *
+ */
+int mbedtls_mpi_mul_mpi(mbedtls_mpi *X, const mbedtls_mpi *A,
+ const mbedtls_mpi *B);
+
+/**
+ * \brief Perform a multiplication of an MPI with an unsigned integer:
+ * X = A * b
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param A The first factor. This must point to an initialized MPI.
+ * \param b The second factor.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ *
+ */
+int mbedtls_mpi_mul_int(mbedtls_mpi *X, const mbedtls_mpi *A,
+ mbedtls_mpi_uint b);
+
+/**
+ * \brief Perform a division with remainder of two MPIs:
+ * A = Q * B + R
+ *
+ * \param Q The destination MPI for the quotient.
+ * This may be \c NULL if the value of the
+ * quotient is not needed. This must not alias A or B.
+ * \param R The destination MPI for the remainder value.
+ * This may be \c NULL if the value of the
+ * remainder is not needed. This must not alias A or B.
+ * \param A The dividend. This must point to an initialized MPI.
+ * \param B The divisor. This must point to an initialized MPI.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p B equals zero.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_div_mpi(mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
+ const mbedtls_mpi *B);
+
+/**
+ * \brief Perform a division with remainder of an MPI by an integer:
+ * A = Q * b + R
+ *
+ * \param Q The destination MPI for the quotient.
+ * This may be \c NULL if the value of the
+ * quotient is not needed. This must not alias A.
+ * \param R The destination MPI for the remainder value.
+ * This may be \c NULL if the value of the
+ * remainder is not needed. This must not alias A.
+ * \param A The dividend. This must point to an initialized MPi.
+ * \param b The divisor.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p b equals zero.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_div_int(mbedtls_mpi *Q, mbedtls_mpi *R, const mbedtls_mpi *A,
+ mbedtls_mpi_sint b);
+
+/**
+ * \brief Perform a modular reduction. R = A mod B
+ *
+ * \param R The destination MPI for the residue value.
+ * This must point to an initialized MPI.
+ * \param A The MPI to compute the residue of.
+ * This must point to an initialized MPI.
+ * \param B The base of the modular reduction.
+ * This must point to an initialized MPI.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p B equals zero.
+ * \return #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p B is negative.
+ * \return Another negative error code on different kinds of failure.
+ *
+ */
+int mbedtls_mpi_mod_mpi(mbedtls_mpi *R, const mbedtls_mpi *A,
+ const mbedtls_mpi *B);
+
+/**
+ * \brief Perform a modular reduction with respect to an integer.
+ * r = A mod b
+ *
+ * \param r The address at which to store the residue.
+ * This must not be \c NULL.
+ * \param A The MPI to compute the residue of.
+ * This must point to an initialized MPi.
+ * \param b The integer base of the modular reduction.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return #MBEDTLS_ERR_MPI_DIVISION_BY_ZERO if \p b equals zero.
+ * \return #MBEDTLS_ERR_MPI_NEGATIVE_VALUE if \p b is negative.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_mod_int(mbedtls_mpi_uint *r, const mbedtls_mpi *A,
+ mbedtls_mpi_sint b);
+
+/**
+ * \brief Perform a sliding-window exponentiation: X = A^E mod N
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * This must not alias E or N.
+ * \param A The base of the exponentiation.
+ * This must point to an initialized MPI.
+ * \param E The exponent MPI. This must point to an initialized MPI.
+ * \param N The base for the modular reduction. This must point to an
+ * initialized MPI.
+ * \param prec_RR A helper MPI depending solely on \p N which can be used to
+ * speed-up multiple modular exponentiations for the same value
+ * of \p N. This may be \c NULL. If it is not \c NULL, it must
+ * point to an initialized MPI. If it hasn't been used after
+ * the call to mbedtls_mpi_init(), this function will compute
+ * the helper value and store it in \p prec_RR for reuse on
+ * subsequent calls to this function. Otherwise, the function
+ * will assume that \p prec_RR holds the helper value set by a
+ * previous call to mbedtls_mpi_exp_mod(), and reuse it.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \c N is negative or
+ * even, or if \c E is negative.
+ * \return Another negative error code on different kinds of failures.
+ *
+ */
+int mbedtls_mpi_exp_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
+ const mbedtls_mpi *E, const mbedtls_mpi *N,
+ mbedtls_mpi *prec_RR);
+
+/**
+ * \brief Fill an MPI with a number of random bytes.
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param size The number of random bytes to generate.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG parameter to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context argument.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on failure.
+ *
+ * \note The bytes obtained from the RNG are interpreted
+ * as a big-endian representation of an MPI; this can
+ * be relevant in applications like deterministic ECDSA.
+ */
+int mbedtls_mpi_fill_random(mbedtls_mpi *X, size_t size,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/** Generate a random number uniformly in a range.
+ *
+ * This function generates a random number between \p min inclusive and
+ * \p N exclusive.
+ *
+ * The procedure complies with RFC 6979 §3.3 (deterministic ECDSA)
+ * when the RNG is a suitably parametrized instance of HMAC_DRBG
+ * and \p min is \c 1.
+ *
+ * \note There are `N - min` possible outputs. The lower bound
+ * \p min can be reached, but the upper bound \p N cannot.
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param min The minimum value to return.
+ * It must be nonnegative.
+ * \param N The upper bound of the range, exclusive.
+ * In other words, this is one plus the maximum value to return.
+ * \p N must be strictly larger than \p min.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG parameter to be passed to \p f_rng.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p min or \p N is invalid
+ * or if they are incompatible.
+ * \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if the implementation was
+ * unable to find a suitable value within a limited number
+ * of attempts. This has a negligible probability if \p N
+ * is significantly larger than \p min, which is the case
+ * for all usual cryptographic applications.
+ * \return Another negative error code on failure.
+ */
+int mbedtls_mpi_random(mbedtls_mpi *X,
+ mbedtls_mpi_sint min,
+ const mbedtls_mpi *N,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief Compute the greatest common divisor: G = gcd(A, B)
+ *
+ * \param G The destination MPI. This must point to an initialized MPI.
+ * \param A The first operand. This must point to an initialized MPI.
+ * \param B The second operand. This must point to an initialized MPI.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_mpi_gcd(mbedtls_mpi *G, const mbedtls_mpi *A,
+ const mbedtls_mpi *B);
+
+/**
+ * \brief Compute the modular inverse: X = A^-1 mod N
+ *
+ * \param X The destination MPI. This must point to an initialized MPI.
+ * \param A The MPI to calculate the modular inverse of. This must point
+ * to an initialized MPI.
+ * \param N The base of the modular inversion. This must point to an
+ * initialized MPI.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if \p N is less than
+ * or equal to one.
+ * \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if \p A has no modular
+ * inverse with respect to \p N.
+ */
+int mbedtls_mpi_inv_mod(mbedtls_mpi *X, const mbedtls_mpi *A,
+ const mbedtls_mpi *N);
+
+/**
+ * \brief Miller-Rabin primality test.
+ *
+ * \warning If \p X is potentially generated by an adversary, for example
+ * when validating cryptographic parameters that you didn't
+ * generate yourself and that are supposed to be prime, then
+ * \p rounds should be at least the half of the security
+ * strength of the cryptographic algorithm. On the other hand,
+ * if \p X is chosen uniformly or non-adversarially (as is the
+ * case when mbedtls_mpi_gen_prime calls this function), then
+ * \p rounds can be much lower.
+ *
+ * \param X The MPI to check for primality.
+ * This must point to an initialized MPI.
+ * \param rounds The number of bases to perform the Miller-Rabin primality
+ * test for. The probability of returning 0 on a composite is
+ * at most 2<sup>-2*\p rounds </sup>.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG parameter to be passed to \p f_rng.
+ * This may be \c NULL if \p f_rng doesn't use
+ * a context parameter.
+ *
+ * \return \c 0 if successful, i.e. \p X is probably prime.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return #MBEDTLS_ERR_MPI_NOT_ACCEPTABLE if \p X is not prime.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_mpi_is_prime_ext(const mbedtls_mpi *X, int rounds,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+/**
+ * \brief Flags for mbedtls_mpi_gen_prime()
+ *
+ * Each of these flags is a constraint on the result X returned by
+ * mbedtls_mpi_gen_prime().
+ */
+typedef enum {
+ MBEDTLS_MPI_GEN_PRIME_FLAG_DH = 0x0001, /**< (X-1)/2 is prime too */
+ MBEDTLS_MPI_GEN_PRIME_FLAG_LOW_ERR = 0x0002, /**< lower error rate from 2<sup>-80</sup> to 2<sup>-128</sup> */
+} mbedtls_mpi_gen_prime_flag_t;
+
+/**
+ * \brief Generate a prime number.
+ *
+ * \param X The destination MPI to store the generated prime in.
+ * This must point to an initialized MPi.
+ * \param nbits The required size of the destination MPI in bits.
+ * This must be between \c 3 and #MBEDTLS_MPI_MAX_BITS.
+ * \param flags A mask of flags of type #mbedtls_mpi_gen_prime_flag_t.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG parameter to be passed to \p f_rng.
+ * This may be \c NULL if \p f_rng doesn't use
+ * a context parameter.
+ *
+ * \return \c 0 if successful, in which case \p X holds a
+ * probably prime number.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if a memory allocation failed.
+ * \return #MBEDTLS_ERR_MPI_BAD_INPUT_DATA if `nbits` is not between
+ * \c 3 and #MBEDTLS_MPI_MAX_BITS.
+ */
+int mbedtls_mpi_gen_prime(mbedtls_mpi *X, size_t nbits, int flags,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if the test failed
+ */
+int mbedtls_mpi_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* bignum.h */
diff --git a/include/mbedtls/build_info.h b/include/mbedtls/build_info.h
new file mode 100644
index 0000000..87e3c2e
--- /dev/null
+++ b/include/mbedtls/build_info.h
@@ -0,0 +1,146 @@
+/**
+ * \file mbedtls/build_info.h
+ *
+ * \brief Build-time configuration info
+ *
+ * Include this file if you need to depend on the
+ * configuration options defined in mbedtls_config.h or MBEDTLS_CONFIG_FILE
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_BUILD_INFO_H
+#define MBEDTLS_BUILD_INFO_H
+
+/*
+ * This set of compile-time defines can be used to determine the version number
+ * of the Mbed TLS library used. Run-time variables for the same can be found in
+ * version.h
+ */
+
+/**
+ * The version number x.y.z is split into three parts.
+ * Major, Minor, Patchlevel
+ */
+#define MBEDTLS_VERSION_MAJOR 3
+#define MBEDTLS_VERSION_MINOR 5
+#define MBEDTLS_VERSION_PATCH 2
+
+/**
+ * The single version number has the following structure:
+ * MMNNPP00
+ * Major version | Minor version | Patch version
+ */
+#define MBEDTLS_VERSION_NUMBER 0x03050200
+#define MBEDTLS_VERSION_STRING "3.5.2"
+#define MBEDTLS_VERSION_STRING_FULL "Mbed TLS 3.5.2"
+
+/* Macros for build-time platform detection */
+
+#if !defined(MBEDTLS_ARCH_IS_ARM64) && \
+ (defined(__aarch64__) || defined(_M_ARM64) || defined(_M_ARM64EC))
+#define MBEDTLS_ARCH_IS_ARM64
+#endif
+
+#if !defined(MBEDTLS_ARCH_IS_ARM32) && \
+ (defined(__arm__) || defined(_M_ARM) || \
+ defined(_M_ARMT) || defined(__thumb__) || defined(__thumb2__))
+#define MBEDTLS_ARCH_IS_ARM32
+#endif
+
+#if !defined(MBEDTLS_ARCH_IS_X64) && \
+ (defined(__amd64__) || defined(__x86_64__) || \
+ ((defined(_M_X64) || defined(_M_AMD64)) && !defined(_M_ARM64EC)))
+#define MBEDTLS_ARCH_IS_X64
+#endif
+
+#if !defined(MBEDTLS_ARCH_IS_X86) && \
+ (defined(__i386__) || defined(_X86_) || \
+ (defined(_M_IX86) && !defined(_M_I86)))
+#define MBEDTLS_ARCH_IS_X86
+#endif
+
+#if defined(_MSC_VER) && !defined(_CRT_SECURE_NO_DEPRECATE)
+#define _CRT_SECURE_NO_DEPRECATE 1
+#endif
+
+/* Define `inline` on some non-C99-compliant compilers. */
+#if (defined(__ARMCC_VERSION) || defined(_MSC_VER)) && \
+ !defined(inline) && !defined(__cplusplus)
+#define inline __inline
+#endif
+
+/* X.509, TLS and non-PSA crypto configuration */
+#if !defined(MBEDTLS_CONFIG_FILE)
+#include "mbedtls/mbedtls_config.h"
+#else
+#include MBEDTLS_CONFIG_FILE
+#endif
+
+#if defined(MBEDTLS_CONFIG_VERSION) && ( \
+ MBEDTLS_CONFIG_VERSION < 0x03000000 || \
+ MBEDTLS_CONFIG_VERSION > MBEDTLS_VERSION_NUMBER)
+#error "Invalid config version, defined value of MBEDTLS_CONFIG_VERSION is unsupported"
+#endif
+
+/* Target and application specific configurations
+ *
+ * Allow user to override any previous default.
+ *
+ */
+#if defined(MBEDTLS_USER_CONFIG_FILE)
+#include MBEDTLS_USER_CONFIG_FILE
+#endif
+
+/* PSA crypto configuration */
+#if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
+#if defined(MBEDTLS_PSA_CRYPTO_CONFIG_FILE)
+#include MBEDTLS_PSA_CRYPTO_CONFIG_FILE
+#else
+#include "psa/crypto_config.h"
+#endif
+#if defined(MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE)
+#include MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE
+#endif
+#endif /* defined(MBEDTLS_PSA_CRYPTO_CONFIG) */
+
+/* Auto-enable MBEDTLS_CTR_DRBG_USE_128_BIT_KEY if
+ * MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH and MBEDTLS_CTR_DRBG_C defined
+ * to ensure a 128-bit key size in CTR_DRBG.
+ */
+#if defined(MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH) && defined(MBEDTLS_CTR_DRBG_C)
+#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
+#endif
+
+/* Auto-enable MBEDTLS_MD_C if needed by a module that didn't require it
+ * in a previous release, to ensure backwards compatibility.
+ */
+#if defined(MBEDTLS_PKCS5_C)
+#define MBEDTLS_MD_C
+#endif
+
+/* PSA crypto specific configuration options
+ * - If config_psa.h reads a configuration option in preprocessor directive,
+ * this symbol should be set before its inclusion. (e.g. MBEDTLS_MD_C)
+ * - If config_psa.h writes a configuration option in conditional directive,
+ * this symbol should be consulted after its inclusion.
+ * (e.g. MBEDTLS_MD_LIGHT)
+ */
+#if defined(MBEDTLS_PSA_CRYPTO_CONFIG) /* PSA_WANT_xxx influences MBEDTLS_xxx */ || \
+ defined(MBEDTLS_PSA_CRYPTO_C) /* MBEDTLS_xxx influences PSA_WANT_xxx */
+#include "mbedtls/config_psa.h"
+#endif
+
+#include "mbedtls/config_adjust_legacy_crypto.h"
+
+#include "mbedtls/config_adjust_x509.h"
+
+#include "mbedtls/config_adjust_ssl.h"
+
+/* Make sure all configuration symbols are set before including check_config.h,
+ * even the ones that are calculated programmatically. */
+#include "mbedtls/check_config.h"
+
+#endif /* MBEDTLS_BUILD_INFO_H */
diff --git a/include/mbedtls/camellia.h b/include/mbedtls/camellia.h
new file mode 100644
index 0000000..6c674fe
--- /dev/null
+++ b/include/mbedtls/camellia.h
@@ -0,0 +1,303 @@
+/**
+ * \file camellia.h
+ *
+ * \brief Camellia block cipher
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_CAMELLIA_H
+#define MBEDTLS_CAMELLIA_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#include "mbedtls/platform_util.h"
+
+#define MBEDTLS_CAMELLIA_ENCRYPT 1
+#define MBEDTLS_CAMELLIA_DECRYPT 0
+
+/** Bad input data. */
+#define MBEDTLS_ERR_CAMELLIA_BAD_INPUT_DATA -0x0024
+
+/** Invalid data input length. */
+#define MBEDTLS_ERR_CAMELLIA_INVALID_INPUT_LENGTH -0x0026
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_CAMELLIA_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief CAMELLIA context structure
+ */
+typedef struct mbedtls_camellia_context {
+ int MBEDTLS_PRIVATE(nr); /*!< number of rounds */
+ uint32_t MBEDTLS_PRIVATE(rk)[68]; /*!< CAMELLIA round keys */
+}
+mbedtls_camellia_context;
+
+#else /* MBEDTLS_CAMELLIA_ALT */
+#include "camellia_alt.h"
+#endif /* MBEDTLS_CAMELLIA_ALT */
+
+/**
+ * \brief Initialize a CAMELLIA context.
+ *
+ * \param ctx The CAMELLIA context to be initialized.
+ * This must not be \c NULL.
+ */
+void mbedtls_camellia_init(mbedtls_camellia_context *ctx);
+
+/**
+ * \brief Clear a CAMELLIA context.
+ *
+ * \param ctx The CAMELLIA context to be cleared. This may be \c NULL,
+ * in which case this function returns immediately. If it is not
+ * \c NULL, it must be initialized.
+ */
+void mbedtls_camellia_free(mbedtls_camellia_context *ctx);
+
+/**
+ * \brief Perform a CAMELLIA key schedule operation for encryption.
+ *
+ * \param ctx The CAMELLIA context to use. This must be initialized.
+ * \param key The encryption key to use. This must be a readable buffer
+ * of size \p keybits Bits.
+ * \param keybits The length of \p key in Bits. This must be either \c 128,
+ * \c 192 or \c 256.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_camellia_setkey_enc(mbedtls_camellia_context *ctx,
+ const unsigned char *key,
+ unsigned int keybits);
+
+/**
+ * \brief Perform a CAMELLIA key schedule operation for decryption.
+ *
+ * \param ctx The CAMELLIA context to use. This must be initialized.
+ * \param key The decryption key. This must be a readable buffer
+ * of size \p keybits Bits.
+ * \param keybits The length of \p key in Bits. This must be either \c 128,
+ * \c 192 or \c 256.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_camellia_setkey_dec(mbedtls_camellia_context *ctx,
+ const unsigned char *key,
+ unsigned int keybits);
+
+/**
+ * \brief Perform a CAMELLIA-ECB block encryption/decryption operation.
+ *
+ * \param ctx The CAMELLIA context to use. This must be initialized
+ * and bound to a key.
+ * \param mode The mode of operation. This must be either
+ * #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT.
+ * \param input The input block. This must be a readable buffer
+ * of size \c 16 Bytes.
+ * \param output The output block. This must be a writable buffer
+ * of size \c 16 Bytes.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_camellia_crypt_ecb(mbedtls_camellia_context *ctx,
+ int mode,
+ const unsigned char input[16],
+ unsigned char output[16]);
+
+#if defined(MBEDTLS_CIPHER_MODE_CBC)
+/**
+ * \brief Perform a CAMELLIA-CBC buffer encryption/decryption operation.
+ *
+ * \note Upon exit, the content of the IV is updated so that you can
+ * call the function same function again on the following
+ * block(s) of data and get the same result as if it was
+ * encrypted in one call. This allows a "streaming" usage.
+ * If on the other hand you need to retain the contents of the
+ * IV, you should either save it manually or use the cipher
+ * module instead.
+ *
+ * \param ctx The CAMELLIA context to use. This must be initialized
+ * and bound to a key.
+ * \param mode The mode of operation. This must be either
+ * #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT.
+ * \param length The length in Bytes of the input data \p input.
+ * This must be a multiple of \c 16 Bytes.
+ * \param iv The initialization vector. This must be a read/write buffer
+ * of length \c 16 Bytes. It is updated to allow streaming
+ * use as explained above.
+ * \param input The buffer holding the input data. This must point to a
+ * readable buffer of length \p length Bytes.
+ * \param output The buffer holding the output data. This must point to a
+ * writable buffer of length \p length Bytes.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_camellia_crypt_cbc(mbedtls_camellia_context *ctx,
+ int mode,
+ size_t length,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_CBC */
+
+#if defined(MBEDTLS_CIPHER_MODE_CFB)
+/**
+ * \brief Perform a CAMELLIA-CFB128 buffer encryption/decryption
+ * operation.
+ *
+ * \note Due to the nature of CFB mode, you should use the same
+ * key for both encryption and decryption. In particular, calls
+ * to this function should be preceded by a key-schedule via
+ * mbedtls_camellia_setkey_enc() regardless of whether \p mode
+ * is #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT.
+ *
+ * \note Upon exit, the content of the IV is updated so that you can
+ * call the function same function again on the following
+ * block(s) of data and get the same result as if it was
+ * encrypted in one call. This allows a "streaming" usage.
+ * If on the other hand you need to retain the contents of the
+ * IV, you should either save it manually or use the cipher
+ * module instead.
+ *
+ * \param ctx The CAMELLIA context to use. This must be initialized
+ * and bound to a key.
+ * \param mode The mode of operation. This must be either
+ * #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT.
+ * \param length The length of the input data \p input. Any value is allowed.
+ * \param iv_off The current offset in the IV. This must be smaller
+ * than \c 16 Bytes. It is updated after this call to allow
+ * the aforementioned streaming usage.
+ * \param iv The initialization vector. This must be a read/write buffer
+ * of length \c 16 Bytes. It is updated after this call to
+ * allow the aforementioned streaming usage.
+ * \param input The buffer holding the input data. This must be a readable
+ * buffer of size \p length Bytes.
+ * \param output The buffer to hold the output data. This must be a writable
+ * buffer of length \p length Bytes.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_camellia_crypt_cfb128(mbedtls_camellia_context *ctx,
+ int mode,
+ size_t length,
+ size_t *iv_off,
+ unsigned char iv[16],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_CFB */
+
+#if defined(MBEDTLS_CIPHER_MODE_CTR)
+/**
+ * \brief Perform a CAMELLIA-CTR buffer encryption/decryption operation.
+ *
+ * *note Due to the nature of CTR mode, you should use the same
+ * key for both encryption and decryption. In particular, calls
+ * to this function should be preceded by a key-schedule via
+ * mbedtls_camellia_setkey_enc() regardless of whether the mode
+ * is #MBEDTLS_CAMELLIA_ENCRYPT or #MBEDTLS_CAMELLIA_DECRYPT.
+ *
+ * \warning You must never reuse a nonce value with the same key. Doing so
+ * would void the encryption for the two messages encrypted with
+ * the same nonce and key.
+ *
+ * There are two common strategies for managing nonces with CTR:
+ *
+ * 1. You can handle everything as a single message processed over
+ * successive calls to this function. In that case, you want to
+ * set \p nonce_counter and \p nc_off to 0 for the first call, and
+ * then preserve the values of \p nonce_counter, \p nc_off and \p
+ * stream_block across calls to this function as they will be
+ * updated by this function.
+ *
+ * With this strategy, you must not encrypt more than 2**128
+ * blocks of data with the same key.
+ *
+ * 2. You can encrypt separate messages by dividing the \p
+ * nonce_counter buffer in two areas: the first one used for a
+ * per-message nonce, handled by yourself, and the second one
+ * updated by this function internally.
+ *
+ * For example, you might reserve the first \c 12 Bytes for the
+ * per-message nonce, and the last \c 4 Bytes for internal use.
+ * In that case, before calling this function on a new message you
+ * need to set the first \c 12 Bytes of \p nonce_counter to your
+ * chosen nonce value, the last four to \c 0, and \p nc_off to \c 0
+ * (which will cause \p stream_block to be ignored). That way, you
+ * can encrypt at most \c 2**96 messages of up to \c 2**32 blocks
+ * each with the same key.
+ *
+ * The per-message nonce (or information sufficient to reconstruct
+ * it) needs to be communicated with the ciphertext and must be
+ * unique. The recommended way to ensure uniqueness is to use a
+ * message counter. An alternative is to generate random nonces,
+ * but this limits the number of messages that can be securely
+ * encrypted: for example, with 96-bit random nonces, you should
+ * not encrypt more than 2**32 messages with the same key.
+ *
+ * Note that for both strategies, sizes are measured in blocks and
+ * that a CAMELLIA block is \c 16 Bytes.
+ *
+ * \warning Upon return, \p stream_block contains sensitive data. Its
+ * content must not be written to insecure storage and should be
+ * securely discarded as soon as it's no longer needed.
+ *
+ * \param ctx The CAMELLIA context to use. This must be initialized
+ * and bound to a key.
+ * \param length The length of the input data \p input in Bytes.
+ * Any value is allowed.
+ * \param nc_off The offset in the current \p stream_block (for resuming
+ * within current cipher stream). The offset pointer to
+ * should be \c 0 at the start of a stream. It is updated
+ * at the end of this call.
+ * \param nonce_counter The 128-bit nonce and counter. This must be a read/write
+ * buffer of length \c 16 Bytes.
+ * \param stream_block The saved stream-block for resuming. This must be a
+ * read/write buffer of length \c 16 Bytes.
+ * \param input The input data stream. This must be a readable buffer of
+ * size \p length Bytes.
+ * \param output The output data stream. This must be a writable buffer
+ * of size \p length Bytes.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_camellia_crypt_ctr(mbedtls_camellia_context *ctx,
+ size_t length,
+ size_t *nc_off,
+ unsigned char nonce_counter[16],
+ unsigned char stream_block[16],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_CTR */
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if the test failed
+ */
+int mbedtls_camellia_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* camellia.h */
diff --git a/include/mbedtls/ccm.h b/include/mbedtls/ccm.h
new file mode 100644
index 0000000..a98111b
--- /dev/null
+++ b/include/mbedtls/ccm.h
@@ -0,0 +1,518 @@
+/**
+ * \file ccm.h
+ *
+ * \brief This file provides an API for the CCM authenticated encryption
+ * mode for block ciphers.
+ *
+ * CCM combines Counter mode encryption with CBC-MAC authentication
+ * for 128-bit block ciphers.
+ *
+ * Input to CCM includes the following elements:
+ * <ul><li>Payload - data that is both authenticated and encrypted.</li>
+ * <li>Associated data (Adata) - data that is authenticated but not
+ * encrypted, For example, a header.</li>
+ * <li>Nonce - A unique value that is assigned to the payload and the
+ * associated data.</li></ul>
+ *
+ * Definition of CCM:
+ * http://csrc.nist.gov/publications/nistpubs/800-38C/SP800-38C_updated-July20_2007.pdf
+ * RFC 3610 "Counter with CBC-MAC (CCM)"
+ *
+ * Related:
+ * RFC 5116 "An Interface and Algorithms for Authenticated Encryption"
+ *
+ * Definition of CCM*:
+ * IEEE 802.15.4 - IEEE Standard for Local and metropolitan area networks
+ * Integer representation is fixed most-significant-octet-first order and
+ * the representation of octets is most-significant-bit-first order. This is
+ * consistent with RFC 3610.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CCM_H
+#define MBEDTLS_CCM_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/cipher.h"
+
+#define MBEDTLS_CCM_DECRYPT 0
+#define MBEDTLS_CCM_ENCRYPT 1
+#define MBEDTLS_CCM_STAR_DECRYPT 2
+#define MBEDTLS_CCM_STAR_ENCRYPT 3
+
+/** Bad input parameters to the function. */
+#define MBEDTLS_ERR_CCM_BAD_INPUT -0x000D
+/** Authenticated decryption failed. */
+#define MBEDTLS_ERR_CCM_AUTH_FAILED -0x000F
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_CCM_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief The CCM context-type definition. The CCM context is passed
+ * to the APIs called.
+ */
+typedef struct mbedtls_ccm_context {
+ unsigned char MBEDTLS_PRIVATE(y)[16]; /*!< The Y working buffer */
+ unsigned char MBEDTLS_PRIVATE(ctr)[16]; /*!< The counter buffer */
+ size_t MBEDTLS_PRIVATE(plaintext_len); /*!< Total plaintext length */
+ size_t MBEDTLS_PRIVATE(add_len); /*!< Total authentication data length */
+ size_t MBEDTLS_PRIVATE(tag_len); /*!< Total tag length */
+ size_t MBEDTLS_PRIVATE(processed); /*!< Track how many bytes of input data
+ were processed (chunked input).
+ Used independently for both auth data
+ and plaintext/ciphertext.
+ This variable is set to zero after
+ auth data input is finished. */
+ unsigned int MBEDTLS_PRIVATE(q); /*!< The Q working value */
+ unsigned int MBEDTLS_PRIVATE(mode); /*!< The operation to perform:
+ #MBEDTLS_CCM_ENCRYPT or
+ #MBEDTLS_CCM_DECRYPT or
+ #MBEDTLS_CCM_STAR_ENCRYPT or
+ #MBEDTLS_CCM_STAR_DECRYPT. */
+ mbedtls_cipher_context_t MBEDTLS_PRIVATE(cipher_ctx); /*!< The cipher context used. */
+ int MBEDTLS_PRIVATE(state); /*!< Working value holding context's
+ state. Used for chunked data input */
+}
+mbedtls_ccm_context;
+
+#else /* MBEDTLS_CCM_ALT */
+#include "ccm_alt.h"
+#endif /* MBEDTLS_CCM_ALT */
+
+/**
+ * \brief This function initializes the specified CCM context,
+ * to make references valid, and prepare the context
+ * for mbedtls_ccm_setkey() or mbedtls_ccm_free().
+ *
+ * \param ctx The CCM context to initialize. This must not be \c NULL.
+ */
+void mbedtls_ccm_init(mbedtls_ccm_context *ctx);
+
+/**
+ * \brief This function initializes the CCM context set in the
+ * \p ctx parameter and sets the encryption key.
+ *
+ * \param ctx The CCM context to initialize. This must be an initialized
+ * context.
+ * \param cipher The 128-bit block cipher to use.
+ * \param key The encryption key. This must not be \c NULL.
+ * \param keybits The key size in bits. This must be acceptable by the cipher.
+ *
+ * \return \c 0 on success.
+ * \return A CCM or cipher-specific error code on failure.
+ */
+int mbedtls_ccm_setkey(mbedtls_ccm_context *ctx,
+ mbedtls_cipher_id_t cipher,
+ const unsigned char *key,
+ unsigned int keybits);
+
+/**
+ * \brief This function releases and clears the specified CCM context
+ * and underlying cipher sub-context.
+ *
+ * \param ctx The CCM context to clear. If this is \c NULL, the function
+ * has no effect. Otherwise, this must be initialized.
+ */
+void mbedtls_ccm_free(mbedtls_ccm_context *ctx);
+
+/**
+ * \brief This function encrypts a buffer using CCM.
+ *
+ * \note The tag is written to a separate buffer. To concatenate
+ * the \p tag with the \p output, as done in <em>RFC-3610:
+ * Counter with CBC-MAC (CCM)</em>, use
+ * \p tag = \p output + \p length, and make sure that the
+ * output buffer is at least \p length + \p tag_len wide.
+ *
+ * \param ctx The CCM context to use for encryption. This must be
+ * initialized and bound to a key.
+ * \param length The length of the input data in Bytes.
+ * \param iv The initialization vector (nonce). This must be a readable
+ * buffer of at least \p iv_len Bytes.
+ * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
+ * or 13. The length L of the message length field is
+ * 15 - \p iv_len.
+ * \param ad The additional data field. If \p ad_len is greater than
+ * zero, \p ad must be a readable buffer of at least that
+ * length.
+ * \param ad_len The length of additional data in Bytes.
+ * This must be less than `2^16 - 2^8`.
+ * \param input The buffer holding the input data. If \p length is greater
+ * than zero, \p input must be a readable buffer of at least
+ * that length.
+ * \param output The buffer holding the output data. If \p length is greater
+ * than zero, \p output must be a writable buffer of at least
+ * that length.
+ * \param tag The buffer holding the authentication field. This must be a
+ * writable buffer of at least \p tag_len Bytes.
+ * \param tag_len The length of the authentication field to generate in Bytes:
+ * 4, 6, 8, 10, 12, 14 or 16.
+ *
+ * \return \c 0 on success.
+ * \return A CCM or cipher-specific error code on failure.
+ */
+int mbedtls_ccm_encrypt_and_tag(mbedtls_ccm_context *ctx, size_t length,
+ const unsigned char *iv, size_t iv_len,
+ const unsigned char *ad, size_t ad_len,
+ const unsigned char *input, unsigned char *output,
+ unsigned char *tag, size_t tag_len);
+
+/**
+ * \brief This function encrypts a buffer using CCM*.
+ *
+ * \note The tag is written to a separate buffer. To concatenate
+ * the \p tag with the \p output, as done in <em>RFC-3610:
+ * Counter with CBC-MAC (CCM)</em>, use
+ * \p tag = \p output + \p length, and make sure that the
+ * output buffer is at least \p length + \p tag_len wide.
+ *
+ * \note When using this function in a variable tag length context,
+ * the tag length has to be encoded into the \p iv passed to
+ * this function.
+ *
+ * \param ctx The CCM context to use for encryption. This must be
+ * initialized and bound to a key.
+ * \param length The length of the input data in Bytes.
+ * For tag length = 0, input length is ignored.
+ * \param iv The initialization vector (nonce). This must be a readable
+ * buffer of at least \p iv_len Bytes.
+ * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
+ * or 13. The length L of the message length field is
+ * 15 - \p iv_len.
+ * \param ad The additional data field. This must be a readable buffer of
+ * at least \p ad_len Bytes.
+ * \param ad_len The length of additional data in Bytes.
+ * This must be less than 2^16 - 2^8.
+ * \param input The buffer holding the input data. If \p length is greater
+ * than zero, \p input must be a readable buffer of at least
+ * that length.
+ * \param output The buffer holding the output data. If \p length is greater
+ * than zero, \p output must be a writable buffer of at least
+ * that length.
+ * \param tag The buffer holding the authentication field. This must be a
+ * writable buffer of at least \p tag_len Bytes.
+ * \param tag_len The length of the authentication field to generate in Bytes:
+ * 0, 4, 6, 8, 10, 12, 14 or 16.
+ *
+ * \warning Passing \c 0 as \p tag_len means that the message is no
+ * longer authenticated.
+ *
+ * \return \c 0 on success.
+ * \return A CCM or cipher-specific error code on failure.
+ */
+int mbedtls_ccm_star_encrypt_and_tag(mbedtls_ccm_context *ctx, size_t length,
+ const unsigned char *iv, size_t iv_len,
+ const unsigned char *ad, size_t ad_len,
+ const unsigned char *input, unsigned char *output,
+ unsigned char *tag, size_t tag_len);
+
+/**
+ * \brief This function performs a CCM authenticated decryption of a
+ * buffer.
+ *
+ * \param ctx The CCM context to use for decryption. This must be
+ * initialized and bound to a key.
+ * \param length The length of the input data in Bytes.
+ * \param iv The initialization vector (nonce). This must be a readable
+ * buffer of at least \p iv_len Bytes.
+ * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
+ * or 13. The length L of the message length field is
+ * 15 - \p iv_len.
+ * \param ad The additional data field. This must be a readable buffer
+ * of at least that \p ad_len Bytes..
+ * \param ad_len The length of additional data in Bytes.
+ * This must be less than 2^16 - 2^8.
+ * \param input The buffer holding the input data. If \p length is greater
+ * than zero, \p input must be a readable buffer of at least
+ * that length.
+ * \param output The buffer holding the output data. If \p length is greater
+ * than zero, \p output must be a writable buffer of at least
+ * that length.
+ * \param tag The buffer holding the authentication field. This must be a
+ * readable buffer of at least \p tag_len Bytes.
+ * \param tag_len The length of the authentication field to generate in Bytes:
+ * 4, 6, 8, 10, 12, 14 or 16.
+ *
+ * \return \c 0 on success. This indicates that the message is authentic.
+ * \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match.
+ * \return A cipher-specific error code on calculation failure.
+ */
+int mbedtls_ccm_auth_decrypt(mbedtls_ccm_context *ctx, size_t length,
+ const unsigned char *iv, size_t iv_len,
+ const unsigned char *ad, size_t ad_len,
+ const unsigned char *input, unsigned char *output,
+ const unsigned char *tag, size_t tag_len);
+
+/**
+ * \brief This function performs a CCM* authenticated decryption of a
+ * buffer.
+ *
+ * \note When using this function in a variable tag length context,
+ * the tag length has to be decoded from \p iv and passed to
+ * this function as \p tag_len. (\p tag needs to be adjusted
+ * accordingly.)
+ *
+ * \param ctx The CCM context to use for decryption. This must be
+ * initialized and bound to a key.
+ * \param length The length of the input data in Bytes.
+ * For tag length = 0, input length is ignored.
+ * \param iv The initialization vector (nonce). This must be a readable
+ * buffer of at least \p iv_len Bytes.
+ * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
+ * or 13. The length L of the message length field is
+ * 15 - \p iv_len.
+ * \param ad The additional data field. This must be a readable buffer of
+ * at least that \p ad_len Bytes.
+ * \param ad_len The length of additional data in Bytes.
+ * This must be less than 2^16 - 2^8.
+ * \param input The buffer holding the input data. If \p length is greater
+ * than zero, \p input must be a readable buffer of at least
+ * that length.
+ * \param output The buffer holding the output data. If \p length is greater
+ * than zero, \p output must be a writable buffer of at least
+ * that length.
+ * \param tag The buffer holding the authentication field. This must be a
+ * readable buffer of at least \p tag_len Bytes.
+ * \param tag_len The length of the authentication field in Bytes.
+ * 0, 4, 6, 8, 10, 12, 14 or 16.
+ *
+ * \warning Passing \c 0 as \p tag_len means that the message is nos
+ * longer authenticated.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CCM_AUTH_FAILED if the tag does not match.
+ * \return A cipher-specific error code on calculation failure.
+ */
+int mbedtls_ccm_star_auth_decrypt(mbedtls_ccm_context *ctx, size_t length,
+ const unsigned char *iv, size_t iv_len,
+ const unsigned char *ad, size_t ad_len,
+ const unsigned char *input, unsigned char *output,
+ const unsigned char *tag, size_t tag_len);
+
+/**
+ * \brief This function starts a CCM encryption or decryption
+ * operation.
+ *
+ * This function and mbedtls_ccm_set_lengths() must be called
+ * before calling mbedtls_ccm_update_ad() or
+ * mbedtls_ccm_update(). This function can be called before
+ * or after mbedtls_ccm_set_lengths().
+ *
+ * \note This function is not implemented in Mbed TLS yet.
+ *
+ * \param ctx The CCM context. This must be initialized.
+ * \param mode The operation to perform: #MBEDTLS_CCM_ENCRYPT or
+ * #MBEDTLS_CCM_DECRYPT or #MBEDTLS_CCM_STAR_ENCRYPT or
+ * #MBEDTLS_CCM_STAR_DECRYPT.
+ * \param iv The initialization vector. This must be a readable buffer
+ * of at least \p iv_len Bytes.
+ * \param iv_len The length of the nonce in Bytes: 7, 8, 9, 10, 11, 12,
+ * or 13. The length L of the message length field is
+ * 15 - \p iv_len.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CCM_BAD_INPUT on failure:
+ * \p ctx is in an invalid state,
+ * \p mode is invalid,
+ * \p iv_len is invalid (lower than \c 7 or greater than
+ * \c 13).
+ */
+int mbedtls_ccm_starts(mbedtls_ccm_context *ctx,
+ int mode,
+ const unsigned char *iv,
+ size_t iv_len);
+
+/**
+ * \brief This function declares the lengths of the message
+ * and additional data for a CCM encryption or decryption
+ * operation.
+ *
+ * This function and mbedtls_ccm_starts() must be called
+ * before calling mbedtls_ccm_update_ad() or
+ * mbedtls_ccm_update(). This function can be called before
+ * or after mbedtls_ccm_starts().
+ *
+ * \note This function is not implemented in Mbed TLS yet.
+ *
+ * \param ctx The CCM context. This must be initialized.
+ * \param total_ad_len The total length of additional data in bytes.
+ * This must be less than `2^16 - 2^8`.
+ * \param plaintext_len The length in bytes of the plaintext to encrypt or
+ * result of the decryption (thus not encompassing the
+ * additional data that are not encrypted).
+ * \param tag_len The length of the tag to generate in Bytes:
+ * 4, 6, 8, 10, 12, 14 or 16.
+ * For CCM*, zero is also valid.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CCM_BAD_INPUT on failure:
+ * \p ctx is in an invalid state,
+ * \p total_ad_len is greater than \c 0xFF00.
+ */
+int mbedtls_ccm_set_lengths(mbedtls_ccm_context *ctx,
+ size_t total_ad_len,
+ size_t plaintext_len,
+ size_t tag_len);
+
+/**
+ * \brief This function feeds an input buffer as associated data
+ * (authenticated but not encrypted data) in a CCM
+ * encryption or decryption operation.
+ *
+ * You may call this function zero, one or more times
+ * to pass successive parts of the additional data. The
+ * lengths \p ad_len of the data parts should eventually add
+ * up exactly to the total length of additional data
+ * \c total_ad_len passed to mbedtls_ccm_set_lengths(). You
+ * may not call this function after calling
+ * mbedtls_ccm_update().
+ *
+ * \note This function is not implemented in Mbed TLS yet.
+ *
+ * \param ctx The CCM context. This must have been started with
+ * mbedtls_ccm_starts(), the lengths of the message and
+ * additional data must have been declared with
+ * mbedtls_ccm_set_lengths() and this must not have yet
+ * received any input with mbedtls_ccm_update().
+ * \param ad The buffer holding the additional data, or \c NULL
+ * if \p ad_len is \c 0.
+ * \param ad_len The length of the additional data. If \c 0,
+ * \p ad may be \c NULL.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CCM_BAD_INPUT on failure:
+ * \p ctx is in an invalid state,
+ * total input length too long.
+ */
+int mbedtls_ccm_update_ad(mbedtls_ccm_context *ctx,
+ const unsigned char *ad,
+ size_t ad_len);
+
+/**
+ * \brief This function feeds an input buffer into an ongoing CCM
+ * encryption or decryption operation.
+ *
+ * You may call this function zero, one or more times
+ * to pass successive parts of the input: the plaintext to
+ * encrypt, or the ciphertext (not including the tag) to
+ * decrypt. After the last part of the input, call
+ * mbedtls_ccm_finish(). The lengths \p input_len of the
+ * data parts should eventually add up exactly to the
+ * plaintext length \c plaintext_len passed to
+ * mbedtls_ccm_set_lengths().
+ *
+ * This function may produce output in one of the following
+ * ways:
+ * - Immediate output: the output length is always equal
+ * to the input length.
+ * - Buffered output: except for the last part of input data,
+ * the output consists of a whole number of 16-byte blocks.
+ * If the total input length so far (not including
+ * associated data) is 16 \* *B* + *A* with *A* < 16 then
+ * the total output length is 16 \* *B*.
+ * For the last part of input data, the output length is
+ * equal to the input length plus the number of bytes (*A*)
+ * buffered in the previous call to the function (if any).
+ * The function uses the plaintext length
+ * \c plaintext_len passed to mbedtls_ccm_set_lengths()
+ * to detect the last part of input data.
+ *
+ * In particular:
+ * - It is always correct to call this function with
+ * \p output_size >= \p input_len + 15.
+ * - If \p input_len is a multiple of 16 for all the calls
+ * to this function during an operation (not necessary for
+ * the last one) then it is correct to use \p output_size
+ * =\p input_len.
+ *
+ * \note This function is not implemented in Mbed TLS yet.
+ *
+ * \param ctx The CCM context. This must have been started with
+ * mbedtls_ccm_starts() and the lengths of the message and
+ * additional data must have been declared with
+ * mbedtls_ccm_set_lengths().
+ * \param input The buffer holding the input data. If \p input_len
+ * is greater than zero, this must be a readable buffer
+ * of at least \p input_len bytes.
+ * \param input_len The length of the input data in bytes.
+ * \param output The buffer for the output data. If \p output_size
+ * is greater than zero, this must be a writable buffer of
+ * at least \p output_size bytes.
+ * \param output_size The size of the output buffer in bytes.
+ * See the function description regarding the output size.
+ * \param output_len On success, \p *output_len contains the actual
+ * length of the output written in \p output.
+ * On failure, the content of \p *output_len is
+ * unspecified.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CCM_BAD_INPUT on failure:
+ * \p ctx is in an invalid state,
+ * total input length too long,
+ * or \p output_size too small.
+ */
+int mbedtls_ccm_update(mbedtls_ccm_context *ctx,
+ const unsigned char *input, size_t input_len,
+ unsigned char *output, size_t output_size,
+ size_t *output_len);
+
+/**
+ * \brief This function finishes the CCM operation and generates
+ * the authentication tag.
+ *
+ * It wraps up the CCM stream, and generates the
+ * tag. The tag can have a maximum length of 16 Bytes.
+ *
+ * \note This function is not implemented in Mbed TLS yet.
+ *
+ * \param ctx The CCM context. This must have been started with
+ * mbedtls_ccm_starts() and the lengths of the message and
+ * additional data must have been declared with
+ * mbedtls_ccm_set_lengths().
+ * \param tag The buffer for holding the tag. If \p tag_len is greater
+ * than zero, this must be a writable buffer of at least \p
+ * tag_len Bytes.
+ * \param tag_len The length of the tag. Must match the tag length passed to
+ * mbedtls_ccm_set_lengths() function.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CCM_BAD_INPUT on failure:
+ * \p ctx is in an invalid state,
+ * invalid value of \p tag_len,
+ * the total amount of additional data passed to
+ * mbedtls_ccm_update_ad() was lower than the total length of
+ * additional data \c total_ad_len passed to
+ * mbedtls_ccm_set_lengths(),
+ * the total amount of input data passed to
+ * mbedtls_ccm_update() was lower than the plaintext length
+ * \c plaintext_len passed to mbedtls_ccm_set_lengths().
+ */
+int mbedtls_ccm_finish(mbedtls_ccm_context *ctx,
+ unsigned char *tag, size_t tag_len);
+
+#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
+/**
+ * \brief The CCM checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_ccm_self_test(int verbose);
+#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_CCM_H */
diff --git a/include/mbedtls/chacha20.h b/include/mbedtls/chacha20.h
new file mode 100644
index 0000000..680fe36
--- /dev/null
+++ b/include/mbedtls/chacha20.h
@@ -0,0 +1,202 @@
+/**
+ * \file chacha20.h
+ *
+ * \brief This file contains ChaCha20 definitions and functions.
+ *
+ * ChaCha20 is a stream cipher that can encrypt and decrypt
+ * information. ChaCha was created by Daniel Bernstein as a variant of
+ * its Salsa cipher https://cr.yp.to/chacha/chacha-20080128.pdf
+ * ChaCha20 is the variant with 20 rounds, that was also standardized
+ * in RFC 7539.
+ *
+ * \author Daniel King <damaki.gh@gmail.com>
+ */
+
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CHACHA20_H
+#define MBEDTLS_CHACHA20_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stdint.h>
+#include <stddef.h>
+
+/** Invalid input parameter(s). */
+#define MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA -0x0051
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_CHACHA20_ALT)
+
+typedef struct mbedtls_chacha20_context {
+ uint32_t MBEDTLS_PRIVATE(state)[16]; /*! The state (before round operations). */
+ uint8_t MBEDTLS_PRIVATE(keystream8)[64]; /*! Leftover keystream bytes. */
+ size_t MBEDTLS_PRIVATE(keystream_bytes_used); /*! Number of keystream bytes already used. */
+}
+mbedtls_chacha20_context;
+
+#else /* MBEDTLS_CHACHA20_ALT */
+#include "chacha20_alt.h"
+#endif /* MBEDTLS_CHACHA20_ALT */
+
+/**
+ * \brief This function initializes the specified ChaCha20 context.
+ *
+ * It must be the first API called before using
+ * the context.
+ *
+ * It is usually followed by calls to
+ * \c mbedtls_chacha20_setkey() and
+ * \c mbedtls_chacha20_starts(), then one or more calls to
+ * to \c mbedtls_chacha20_update(), and finally to
+ * \c mbedtls_chacha20_free().
+ *
+ * \param ctx The ChaCha20 context to initialize.
+ * This must not be \c NULL.
+ */
+void mbedtls_chacha20_init(mbedtls_chacha20_context *ctx);
+
+/**
+ * \brief This function releases and clears the specified
+ * ChaCha20 context.
+ *
+ * \param ctx The ChaCha20 context to clear. This may be \c NULL,
+ * in which case this function is a no-op. If it is not
+ * \c NULL, it must point to an initialized context.
+ *
+ */
+void mbedtls_chacha20_free(mbedtls_chacha20_context *ctx);
+
+/**
+ * \brief This function sets the encryption/decryption key.
+ *
+ * \note After using this function, you must also call
+ * \c mbedtls_chacha20_starts() to set a nonce before you
+ * start encrypting/decrypting data with
+ * \c mbedtls_chacha_update().
+ *
+ * \param ctx The ChaCha20 context to which the key should be bound.
+ * It must be initialized.
+ * \param key The encryption/decryption key. This must be \c 32 Bytes
+ * in length.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or key is NULL.
+ */
+int mbedtls_chacha20_setkey(mbedtls_chacha20_context *ctx,
+ const unsigned char key[32]);
+
+/**
+ * \brief This function sets the nonce and initial counter value.
+ *
+ * \note A ChaCha20 context can be re-used with the same key by
+ * calling this function to change the nonce.
+ *
+ * \warning You must never use the same nonce twice with the same key.
+ * This would void any confidentiality guarantees for the
+ * messages encrypted with the same nonce and key.
+ *
+ * \param ctx The ChaCha20 context to which the nonce should be bound.
+ * It must be initialized and bound to a key.
+ * \param nonce The nonce. This must be \c 12 Bytes in size.
+ * \param counter The initial counter value. This is usually \c 0.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CHACHA20_BAD_INPUT_DATA if ctx or nonce is
+ * NULL.
+ */
+int mbedtls_chacha20_starts(mbedtls_chacha20_context *ctx,
+ const unsigned char nonce[12],
+ uint32_t counter);
+
+/**
+ * \brief This function encrypts or decrypts data.
+ *
+ * Since ChaCha20 is a stream cipher, the same operation is
+ * used for encrypting and decrypting data.
+ *
+ * \note The \p input and \p output pointers must either be equal or
+ * point to non-overlapping buffers.
+ *
+ * \note \c mbedtls_chacha20_setkey() and
+ * \c mbedtls_chacha20_starts() must be called at least once
+ * to setup the context before this function can be called.
+ *
+ * \note This function can be called multiple times in a row in
+ * order to encrypt of decrypt data piecewise with the same
+ * key and nonce.
+ *
+ * \param ctx The ChaCha20 context to use for encryption or decryption.
+ * It must be initialized and bound to a key and nonce.
+ * \param size The length of the input data in Bytes.
+ * \param input The buffer holding the input data.
+ * This pointer can be \c NULL if `size == 0`.
+ * \param output The buffer holding the output data.
+ * This must be able to hold \p size Bytes.
+ * This pointer can be \c NULL if `size == 0`.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_chacha20_update(mbedtls_chacha20_context *ctx,
+ size_t size,
+ const unsigned char *input,
+ unsigned char *output);
+
+/**
+ * \brief This function encrypts or decrypts data with ChaCha20 and
+ * the given key and nonce.
+ *
+ * Since ChaCha20 is a stream cipher, the same operation is
+ * used for encrypting and decrypting data.
+ *
+ * \warning You must never use the same (key, nonce) pair more than
+ * once. This would void any confidentiality guarantees for
+ * the messages encrypted with the same nonce and key.
+ *
+ * \note The \p input and \p output pointers must either be equal or
+ * point to non-overlapping buffers.
+ *
+ * \param key The encryption/decryption key.
+ * This must be \c 32 Bytes in length.
+ * \param nonce The nonce. This must be \c 12 Bytes in size.
+ * \param counter The initial counter value. This is usually \c 0.
+ * \param size The length of the input data in Bytes.
+ * \param input The buffer holding the input data.
+ * This pointer can be \c NULL if `size == 0`.
+ * \param output The buffer holding the output data.
+ * This must be able to hold \p size Bytes.
+ * This pointer can be \c NULL if `size == 0`.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_chacha20_crypt(const unsigned char key[32],
+ const unsigned char nonce[12],
+ uint32_t counter,
+ size_t size,
+ const unsigned char *input,
+ unsigned char *output);
+
+#if defined(MBEDTLS_SELF_TEST)
+/**
+ * \brief The ChaCha20 checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_chacha20_self_test(int verbose);
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_CHACHA20_H */
diff --git a/include/mbedtls/chachapoly.h b/include/mbedtls/chachapoly.h
new file mode 100644
index 0000000..3dc21e3
--- /dev/null
+++ b/include/mbedtls/chachapoly.h
@@ -0,0 +1,342 @@
+/**
+ * \file chachapoly.h
+ *
+ * \brief This file contains the AEAD-ChaCha20-Poly1305 definitions and
+ * functions.
+ *
+ * ChaCha20-Poly1305 is an algorithm for Authenticated Encryption
+ * with Associated Data (AEAD) that can be used to encrypt and
+ * authenticate data. It is based on ChaCha20 and Poly1305 by Daniel
+ * Bernstein and was standardized in RFC 7539.
+ *
+ * \author Daniel King <damaki.gh@gmail.com>
+ */
+
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CHACHAPOLY_H
+#define MBEDTLS_CHACHAPOLY_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+/* for shared error codes */
+#include "mbedtls/poly1305.h"
+
+/** The requested operation is not permitted in the current state. */
+#define MBEDTLS_ERR_CHACHAPOLY_BAD_STATE -0x0054
+/** Authenticated decryption failed: data was not authentic. */
+#define MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED -0x0056
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+ MBEDTLS_CHACHAPOLY_ENCRYPT, /**< The mode value for performing encryption. */
+ MBEDTLS_CHACHAPOLY_DECRYPT /**< The mode value for performing decryption. */
+}
+mbedtls_chachapoly_mode_t;
+
+#if !defined(MBEDTLS_CHACHAPOLY_ALT)
+
+#include "mbedtls/chacha20.h"
+
+typedef struct mbedtls_chachapoly_context {
+ mbedtls_chacha20_context MBEDTLS_PRIVATE(chacha20_ctx); /**< The ChaCha20 context. */
+ mbedtls_poly1305_context MBEDTLS_PRIVATE(poly1305_ctx); /**< The Poly1305 context. */
+ uint64_t MBEDTLS_PRIVATE(aad_len); /**< The length (bytes) of the Additional Authenticated Data. */
+ uint64_t MBEDTLS_PRIVATE(ciphertext_len); /**< The length (bytes) of the ciphertext. */
+ int MBEDTLS_PRIVATE(state); /**< The current state of the context. */
+ mbedtls_chachapoly_mode_t MBEDTLS_PRIVATE(mode); /**< Cipher mode (encrypt or decrypt). */
+}
+mbedtls_chachapoly_context;
+
+#else /* !MBEDTLS_CHACHAPOLY_ALT */
+#include "chachapoly_alt.h"
+#endif /* !MBEDTLS_CHACHAPOLY_ALT */
+
+/**
+ * \brief This function initializes the specified ChaCha20-Poly1305 context.
+ *
+ * It must be the first API called before using
+ * the context. It must be followed by a call to
+ * \c mbedtls_chachapoly_setkey() before any operation can be
+ * done, and to \c mbedtls_chachapoly_free() once all
+ * operations with that context have been finished.
+ *
+ * In order to encrypt or decrypt full messages at once, for
+ * each message you should make a single call to
+ * \c mbedtls_chachapoly_crypt_and_tag() or
+ * \c mbedtls_chachapoly_auth_decrypt().
+ *
+ * In order to encrypt messages piecewise, for each
+ * message you should make a call to
+ * \c mbedtls_chachapoly_starts(), then 0 or more calls to
+ * \c mbedtls_chachapoly_update_aad(), then 0 or more calls to
+ * \c mbedtls_chachapoly_update(), then one call to
+ * \c mbedtls_chachapoly_finish().
+ *
+ * \warning Decryption with the piecewise API is discouraged! Always
+ * use \c mbedtls_chachapoly_auth_decrypt() when possible!
+ *
+ * If however this is not possible because the data is too
+ * large to fit in memory, you need to:
+ *
+ * - call \c mbedtls_chachapoly_starts() and (if needed)
+ * \c mbedtls_chachapoly_update_aad() as above,
+ * - call \c mbedtls_chachapoly_update() multiple times and
+ * ensure its output (the plaintext) is NOT used in any other
+ * way than placing it in temporary storage at this point,
+ * - call \c mbedtls_chachapoly_finish() to compute the
+ * authentication tag and compared it in constant time to the
+ * tag received with the ciphertext.
+ *
+ * If the tags are not equal, you must immediately discard
+ * all previous outputs of \c mbedtls_chachapoly_update(),
+ * otherwise you can now safely use the plaintext.
+ *
+ * \param ctx The ChachaPoly context to initialize. Must not be \c NULL.
+ */
+void mbedtls_chachapoly_init(mbedtls_chachapoly_context *ctx);
+
+/**
+ * \brief This function releases and clears the specified
+ * ChaCha20-Poly1305 context.
+ *
+ * \param ctx The ChachaPoly context to clear. This may be \c NULL, in which
+ * case this function is a no-op.
+ */
+void mbedtls_chachapoly_free(mbedtls_chachapoly_context *ctx);
+
+/**
+ * \brief This function sets the ChaCha20-Poly1305
+ * symmetric encryption key.
+ *
+ * \param ctx The ChaCha20-Poly1305 context to which the key should be
+ * bound. This must be initialized.
+ * \param key The \c 256 Bit (\c 32 Bytes) key.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_chachapoly_setkey(mbedtls_chachapoly_context *ctx,
+ const unsigned char key[32]);
+
+/**
+ * \brief This function starts a ChaCha20-Poly1305 encryption or
+ * decryption operation.
+ *
+ * \warning You must never use the same nonce twice with the same key.
+ * This would void any confidentiality and authenticity
+ * guarantees for the messages encrypted with the same nonce
+ * and key.
+ *
+ * \note If the context is being used for AAD only (no data to
+ * encrypt or decrypt) then \p mode can be set to any value.
+ *
+ * \warning Decryption with the piecewise API is discouraged, see the
+ * warning on \c mbedtls_chachapoly_init().
+ *
+ * \param ctx The ChaCha20-Poly1305 context. This must be initialized
+ * and bound to a key.
+ * \param nonce The nonce/IV to use for the message.
+ * This must be a readable buffer of length \c 12 Bytes.
+ * \param mode The operation to perform: #MBEDTLS_CHACHAPOLY_ENCRYPT or
+ * #MBEDTLS_CHACHAPOLY_DECRYPT (discouraged, see warning).
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_chachapoly_starts(mbedtls_chachapoly_context *ctx,
+ const unsigned char nonce[12],
+ mbedtls_chachapoly_mode_t mode);
+
+/**
+ * \brief This function feeds additional data to be authenticated
+ * into an ongoing ChaCha20-Poly1305 operation.
+ *
+ * The Additional Authenticated Data (AAD), also called
+ * Associated Data (AD) is only authenticated but not
+ * encrypted nor included in the encrypted output. It is
+ * usually transmitted separately from the ciphertext or
+ * computed locally by each party.
+ *
+ * \note This function is called before data is encrypted/decrypted.
+ * I.e. call this function to process the AAD before calling
+ * \c mbedtls_chachapoly_update().
+ *
+ * You may call this function multiple times to process
+ * an arbitrary amount of AAD. It is permitted to call
+ * this function 0 times, if no AAD is used.
+ *
+ * This function cannot be called any more if data has
+ * been processed by \c mbedtls_chachapoly_update(),
+ * or if the context has been finished.
+ *
+ * \warning Decryption with the piecewise API is discouraged, see the
+ * warning on \c mbedtls_chachapoly_init().
+ *
+ * \param ctx The ChaCha20-Poly1305 context. This must be initialized
+ * and bound to a key.
+ * \param aad_len The length in Bytes of the AAD. The length has no
+ * restrictions.
+ * \param aad Buffer containing the AAD.
+ * This pointer can be \c NULL if `aad_len == 0`.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA
+ * if \p ctx or \p aad are NULL.
+ * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE
+ * if the operations has not been started or has been
+ * finished, or if the AAD has been finished.
+ */
+int mbedtls_chachapoly_update_aad(mbedtls_chachapoly_context *ctx,
+ const unsigned char *aad,
+ size_t aad_len);
+
+/**
+ * \brief Thus function feeds data to be encrypted or decrypted
+ * into an on-going ChaCha20-Poly1305
+ * operation.
+ *
+ * The direction (encryption or decryption) depends on the
+ * mode that was given when calling
+ * \c mbedtls_chachapoly_starts().
+ *
+ * You may call this function multiple times to process
+ * an arbitrary amount of data. It is permitted to call
+ * this function 0 times, if no data is to be encrypted
+ * or decrypted.
+ *
+ * \warning Decryption with the piecewise API is discouraged, see the
+ * warning on \c mbedtls_chachapoly_init().
+ *
+ * \param ctx The ChaCha20-Poly1305 context to use. This must be initialized.
+ * \param len The length (in bytes) of the data to encrypt or decrypt.
+ * \param input The buffer containing the data to encrypt or decrypt.
+ * This pointer can be \c NULL if `len == 0`.
+ * \param output The buffer to where the encrypted or decrypted data is
+ * written. This must be able to hold \p len bytes.
+ * This pointer can be \c NULL if `len == 0`.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE
+ * if the operation has not been started or has been
+ * finished.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_chachapoly_update(mbedtls_chachapoly_context *ctx,
+ size_t len,
+ const unsigned char *input,
+ unsigned char *output);
+
+/**
+ * \brief This function finished the ChaCha20-Poly1305 operation and
+ * generates the MAC (authentication tag).
+ *
+ * \param ctx The ChaCha20-Poly1305 context to use. This must be initialized.
+ * \param mac The buffer to where the 128-bit (16 bytes) MAC is written.
+ *
+ * \warning Decryption with the piecewise API is discouraged, see the
+ * warning on \c mbedtls_chachapoly_init().
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CHACHAPOLY_BAD_STATE
+ * if the operation has not been started or has been
+ * finished.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_chachapoly_finish(mbedtls_chachapoly_context *ctx,
+ unsigned char mac[16]);
+
+/**
+ * \brief This function performs a complete ChaCha20-Poly1305
+ * authenticated encryption with the previously-set key.
+ *
+ * \note Before using this function, you must set the key with
+ * \c mbedtls_chachapoly_setkey().
+ *
+ * \warning You must never use the same nonce twice with the same key.
+ * This would void any confidentiality and authenticity
+ * guarantees for the messages encrypted with the same nonce
+ * and key.
+ *
+ * \param ctx The ChaCha20-Poly1305 context to use (holds the key).
+ * This must be initialized.
+ * \param length The length (in bytes) of the data to encrypt or decrypt.
+ * \param nonce The 96-bit (12 bytes) nonce/IV to use.
+ * \param aad The buffer containing the additional authenticated
+ * data (AAD). This pointer can be \c NULL if `aad_len == 0`.
+ * \param aad_len The length (in bytes) of the AAD data to process.
+ * \param input The buffer containing the data to encrypt or decrypt.
+ * This pointer can be \c NULL if `ilen == 0`.
+ * \param output The buffer to where the encrypted or decrypted data
+ * is written. This pointer can be \c NULL if `ilen == 0`.
+ * \param tag The buffer to where the computed 128-bit (16 bytes) MAC
+ * is written. This must not be \c NULL.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_chachapoly_encrypt_and_tag(mbedtls_chachapoly_context *ctx,
+ size_t length,
+ const unsigned char nonce[12],
+ const unsigned char *aad,
+ size_t aad_len,
+ const unsigned char *input,
+ unsigned char *output,
+ unsigned char tag[16]);
+
+/**
+ * \brief This function performs a complete ChaCha20-Poly1305
+ * authenticated decryption with the previously-set key.
+ *
+ * \note Before using this function, you must set the key with
+ * \c mbedtls_chachapoly_setkey().
+ *
+ * \param ctx The ChaCha20-Poly1305 context to use (holds the key).
+ * \param length The length (in Bytes) of the data to decrypt.
+ * \param nonce The \c 96 Bit (\c 12 bytes) nonce/IV to use.
+ * \param aad The buffer containing the additional authenticated data (AAD).
+ * This pointer can be \c NULL if `aad_len == 0`.
+ * \param aad_len The length (in bytes) of the AAD data to process.
+ * \param tag The buffer holding the authentication tag.
+ * This must be a readable buffer of length \c 16 Bytes.
+ * \param input The buffer containing the data to decrypt.
+ * This pointer can be \c NULL if `ilen == 0`.
+ * \param output The buffer to where the decrypted data is written.
+ * This pointer can be \c NULL if `ilen == 0`.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CHACHAPOLY_AUTH_FAILED
+ * if the data was not authentic.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_chachapoly_auth_decrypt(mbedtls_chachapoly_context *ctx,
+ size_t length,
+ const unsigned char nonce[12],
+ const unsigned char *aad,
+ size_t aad_len,
+ const unsigned char tag[16],
+ const unsigned char *input,
+ unsigned char *output);
+
+#if defined(MBEDTLS_SELF_TEST)
+/**
+ * \brief The ChaCha20-Poly1305 checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_chachapoly_self_test(int verbose);
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_CHACHAPOLY_H */
diff --git a/include/mbedtls/check_config.h b/include/mbedtls/check_config.h
new file mode 100644
index 0000000..e479ef3
--- /dev/null
+++ b/include/mbedtls/check_config.h
@@ -0,0 +1,1206 @@
+/**
+ * \file check_config.h
+ *
+ * \brief Consistency checks for configuration options
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CHECK_CONFIG_H
+#define MBEDTLS_CHECK_CONFIG_H
+
+/* *INDENT-OFF* */
+/*
+ * We assume CHAR_BIT is 8 in many places. In practice, this is true on our
+ * target platforms, so not an issue, but let's just be extra sure.
+ */
+#include <limits.h>
+#if CHAR_BIT != 8
+#error "Mbed TLS requires a platform with 8-bit chars"
+#endif
+
+#include <stdint.h>
+
+#if defined(__MINGW32__) || (defined(_MSC_VER) && _MSC_VER <= 1900)
+#if !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_C is required on Windows"
+#endif
+
+/* Fix the config here. Not convenient to put an #ifdef _WIN32 in mbedtls_config.h as
+ * it would confuse config.py. */
+#if !defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) && \
+ !defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO)
+#define MBEDTLS_PLATFORM_SNPRINTF_ALT
+#endif
+
+#if !defined(MBEDTLS_PLATFORM_VSNPRINTF_ALT) && \
+ !defined(MBEDTLS_PLATFORM_VSNPRINTF_MACRO)
+#define MBEDTLS_PLATFORM_VSNPRINTF_ALT
+#endif
+#endif /* _MINGW32__ || (_MSC_VER && (_MSC_VER <= 1900)) */
+
+#if defined(TARGET_LIKE_MBED) && defined(MBEDTLS_NET_C)
+#error "The NET module is not available for mbed OS - please use the network functions provided by Mbed OS"
+#endif
+
+#if defined(MBEDTLS_DEPRECATED_WARNING) && \
+ !defined(__GNUC__) && !defined(__clang__)
+#error "MBEDTLS_DEPRECATED_WARNING only works with GCC and Clang"
+#endif
+
+#if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_HAVE_TIME)
+#error "MBEDTLS_HAVE_TIME_DATE without MBEDTLS_HAVE_TIME does not make sense"
+#endif
+
+/* Check that each MBEDTLS_ECP_DP_xxx symbol has its PSA_WANT_ECC_xxx counterpart
+ * when PSA crypto is enabled. */
+#if defined(MBEDTLS_PSA_CRYPTO_CONFIG) || defined(MBEDTLS_PSA_CRYPTO_C)
+
+#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) && !defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
+#error "MBEDTLS_ECP_DP_BP256R1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) && !defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
+#error "MBEDTLS_ECP_DP_BP384R1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) && !defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
+#error "MBEDTLS_ECP_DP_BP512R1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) && !defined(PSA_WANT_ECC_MONTGOMERY_255)
+#error "MBEDTLS_ECP_DP_CURVE25519_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) && !defined(PSA_WANT_ECC_MONTGOMERY_448)
+#error "MBEDTLS_ECP_DP_CURVE448_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) && !defined(PSA_WANT_ECC_SECP_R1_192)
+#error "MBEDTLS_ECP_DP_SECP192R1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) && !defined(PSA_WANT_ECC_SECP_R1_224)
+#error "MBEDTLS_ECP_DP_SECP224R1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) && !defined(PSA_WANT_ECC_SECP_R1_256)
+#error "MBEDTLS_ECP_DP_SECP256R1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) && !defined(PSA_WANT_ECC_SECP_R1_384)
+#error "MBEDTLS_ECP_DP_SECP384R1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) && !defined(PSA_WANT_ECC_SECP_R1_521)
+#error "MBEDTLS_ECP_DP_SECP521R1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) && !defined(PSA_WANT_ECC_SECP_K1_192)
+#error "MBEDTLS_ECP_DP_SECP192K1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+/* SECP224K1 is buggy in PSA API so we skip this check */
+#if 0 && defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) && !defined(PSA_WANT_ECC_SECP_K1_224)
+#error "MBEDTLS_ECP_DP_SECP224K1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) && !defined(PSA_WANT_ECC_SECP_K1_256)
+#error "MBEDTLS_ECP_DP_SECP256K1_ENABLED defined, but not its PSA counterpart"
+#endif
+
+#endif /* MBEDTLS_PSA_CRYPTO_CONFIG || MBEDTLS_PSA_CRYPTO_C */
+
+/* Limitations on ECC key types acceleration: if we have any of `PUBLIC_KEY`,
+ * `KEY_PAIR_BASIC`, `KEY_PAIR_IMPORT`, `KEY_PAIR_EXPORT` then we must have
+ * all 4 of them.
+ */
+#if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) || \
+ defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC) || \
+ defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT) || \
+ defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) || \
+ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC) || \
+ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT) || \
+ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT)
+#error "Unsupported partial support for ECC key type acceleration, see docs/driver-only-builds.md"
+#endif /* not all of public, basic, import, export */
+#endif /* one of public, basic, import, export */
+
+/* Limitations on ECC curves acceleration: partial curve acceleration is only
+ * supported with crypto excluding PK, X.509 or TLS.
+ * Note: no need to check X.509 as it depends on PK. */
+#if defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_256) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_384) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_512) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_MONTGOMERY_255) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_MONTGOMERY_448) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_192) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_224) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_256) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_192) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_224) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_256) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_384) || \
+ defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_521)
+#if defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES)
+#if defined(MBEDTLS_PK_C) || \
+ defined(MBEDTLS_SSL_TLS_C)
+#error "Unsupported partial support for ECC curves acceleration, see docs/driver-only-builds.md"
+#endif /* modules beyond what's supported */
+#endif /* not all curves accelerated */
+#endif /* some curve accelerated */
+
+#if defined(MBEDTLS_CTR_DRBG_C) && !defined(MBEDTLS_AES_C)
+#error "MBEDTLS_CTR_DRBG_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_DHM_C) && !defined(MBEDTLS_BIGNUM_C)
+#error "MBEDTLS_DHM_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_CMAC_C) && \
+ ( !defined(MBEDTLS_CIPHER_C ) || ( !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_DES_C) ) )
+#error "MBEDTLS_CMAC_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_NIST_KW_C) && \
+ ( !defined(MBEDTLS_AES_C) || !defined(MBEDTLS_CIPHER_C) )
+#error "MBEDTLS_NIST_KW_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECDH_C) && !defined(MBEDTLS_ECP_C)
+#error "MBEDTLS_ECDH_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECDSA_C) && \
+ ( !defined(MBEDTLS_ECP_C) || \
+ !( defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) ) || \
+ !defined(MBEDTLS_ASN1_PARSE_C) || \
+ !defined(MBEDTLS_ASN1_WRITE_C) )
+#error "MBEDTLS_ECDSA_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECJPAKE_C) && \
+ ( !defined(MBEDTLS_ECP_C) || \
+ !( defined(MBEDTLS_MD_C) || defined(MBEDTLS_PSA_CRYPTO_C) ) )
+#error "MBEDTLS_ECJPAKE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_RESTARTABLE) && \
+ ( defined(MBEDTLS_ECDH_COMPUTE_SHARED_ALT) || \
+ defined(MBEDTLS_ECDH_GEN_PUBLIC_ALT) || \
+ defined(MBEDTLS_ECDSA_SIGN_ALT) || \
+ defined(MBEDTLS_ECDSA_VERIFY_ALT) || \
+ defined(MBEDTLS_ECDSA_GENKEY_ALT) || \
+ defined(MBEDTLS_ECP_INTERNAL_ALT) || \
+ defined(MBEDTLS_ECP_ALT) )
+#error "MBEDTLS_ECP_RESTARTABLE defined, but it cannot coexist with an alternative ECP implementation"
+#endif
+
+#if defined(MBEDTLS_ECP_RESTARTABLE) && \
+ !defined(MBEDTLS_ECP_C)
+#error "MBEDTLS_ECP_RESTARTABLE defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECDSA_DETERMINISTIC) && !defined(MBEDTLS_HMAC_DRBG_C)
+#error "MBEDTLS_ECDSA_DETERMINISTIC defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_C) && ( !defined(MBEDTLS_BIGNUM_C) || ( \
+ !defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) && \
+ !defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) ) )
+#error "MBEDTLS_ECP_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_ASN1_PARSE_C)
+#error "MBEDTLS_PK_PARSE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PKCS12_C) && !defined(MBEDTLS_CIPHER_C)
+#error "MBEDTLS_PKCS12_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PKCS5_C) && \
+ !defined(MBEDTLS_CIPHER_C)
+#error "MBEDTLS_PKCS5_C defined, but not all prerequisites"
+#endif
+
+/* Helpers for hash dependencies, will be undefined at the end of the file */
+/* Do SHA-256, 384, 512 to cover Entropy and TLS. */
+#if defined(MBEDTLS_SHA256_C) || \
+ (defined(MBEDTLS_PSA_CRYPTO_C) && defined(PSA_WANT_ALG_SHA_256))
+#define MBEDTLS_MD_HAVE_SHA256
+#endif
+#if defined(MBEDTLS_SHA384_C) || \
+ (defined(MBEDTLS_PSA_CRYPTO_C) && defined(PSA_WANT_ALG_SHA_384))
+#define MBEDTLS_MD_HAVE_SHA384
+#endif
+#if defined(MBEDTLS_SHA512_C) || \
+ (defined(MBEDTLS_PSA_CRYPTO_C) && defined(PSA_WANT_ALG_SHA_512))
+#define MBEDTLS_MD_HAVE_SHA512
+#endif
+
+#if defined(MBEDTLS_ENTROPY_C) && \
+ !(defined(MBEDTLS_MD_HAVE_SHA512) || defined(MBEDTLS_MD_HAVE_SHA256))
+#error "MBEDTLS_ENTROPY_C defined, but not all prerequisites"
+#endif
+#if defined(MBEDTLS_ENTROPY_C) && \
+ defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 64)
+#error "MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high"
+#endif
+#if defined(MBEDTLS_ENTROPY_C) && \
+ (defined(MBEDTLS_ENTROPY_FORCE_SHA256) || !defined(MBEDTLS_MD_HAVE_SHA512)) \
+ && defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) && (MBEDTLS_CTR_DRBG_ENTROPY_LEN > 32)
+#error "MBEDTLS_CTR_DRBG_ENTROPY_LEN value too high"
+#endif
+#if defined(MBEDTLS_ENTROPY_C) && \
+ defined(MBEDTLS_ENTROPY_FORCE_SHA256) && !defined(MBEDTLS_MD_HAVE_SHA256)
+#error "MBEDTLS_ENTROPY_FORCE_SHA256 defined, but not all prerequisites"
+#endif
+
+#if defined(__has_feature)
+#if __has_feature(memory_sanitizer)
+#define MBEDTLS_HAS_MEMSAN
+#endif
+#endif
+#if defined(MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN) && !defined(MBEDTLS_HAS_MEMSAN)
+#error "MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN requires building with MemorySanitizer"
+#endif
+#undef MBEDTLS_HAS_MEMSAN
+
+#if defined(MBEDTLS_CCM_C) && ( \
+ !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_CAMELLIA_C) && !defined(MBEDTLS_ARIA_C) )
+#error "MBEDTLS_CCM_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_CCM_C) && !defined(MBEDTLS_CIPHER_C)
+#error "MBEDTLS_CCM_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_GCM_C) && ( \
+ !defined(MBEDTLS_AES_C) && !defined(MBEDTLS_CAMELLIA_C) && !defined(MBEDTLS_ARIA_C) )
+#error "MBEDTLS_GCM_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_GCM_C) && !defined(MBEDTLS_CIPHER_C)
+#error "MBEDTLS_GCM_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_CHACHAPOLY_C) && !defined(MBEDTLS_CHACHA20_C)
+#error "MBEDTLS_CHACHAPOLY_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_CHACHAPOLY_C) && !defined(MBEDTLS_POLY1305_C)
+#error "MBEDTLS_CHACHAPOLY_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_RANDOMIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_RANDOMIZE_JAC_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_ADD_MIXED_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_ADD_MIXED_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_DOUBLE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_DOUBLE_JAC_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_NORMALIZE_JAC_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_NORMALIZE_JAC_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_RANDOMIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_RANDOMIZE_MXZ_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_NORMALIZE_MXZ_ALT) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_NORMALIZE_MXZ_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ECP_NO_FALLBACK) && !defined(MBEDTLS_ECP_INTERNAL_ALT)
+#error "MBEDTLS_ECP_NO_FALLBACK defined, but no alternative implementation enabled"
+#endif
+
+#if defined(MBEDTLS_HKDF_C) && !defined(MBEDTLS_MD_C)
+#error "MBEDTLS_HKDF_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_HMAC_DRBG_C) && !defined(MBEDTLS_MD_C)
+#error "MBEDTLS_HMAC_DRBG_C defined, but not all prerequisites"
+#endif
+
+/* Helper for JPAKE dependencies, will be undefined at the end of the file */
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#if defined(PSA_WANT_ALG_JPAKE) && defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
+#define MBEDTLS_PK_HAVE_JPAKE
+#endif
+#else /* MBEDTLS_USE_PSA_CRYPTO */
+#if defined(MBEDTLS_ECJPAKE_C)
+#define MBEDTLS_PK_HAVE_JPAKE
+#endif
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
+/* Helper for curve SECP256R1 */
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#if defined(PSA_WANT_ECC_SECP_R1_256)
+#define MBEDTLS_PK_HAVE_CURVE_SECP256R1
+#endif
+#else /* MBEDTLS_USE_PSA_CRYPTO */
+#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
+#define MBEDTLS_PK_HAVE_CURVE_SECP256R1
+#endif
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) && \
+ ( !defined(MBEDTLS_CAN_ECDH) || \
+ !defined(MBEDTLS_PK_CAN_ECDSA_SIGN) || \
+ !defined(MBEDTLS_X509_CRT_PARSE_C) )
+#error "MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) && \
+ ( !defined(MBEDTLS_CAN_ECDH) || !defined(MBEDTLS_RSA_C) || \
+ !defined(MBEDTLS_X509_CRT_PARSE_C) )
+#error "MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) && !defined(MBEDTLS_DHM_C)
+#error "MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) && \
+ !defined(MBEDTLS_CAN_ECDH)
+#error "MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) && \
+ ( !defined(MBEDTLS_DHM_C) || !defined(MBEDTLS_RSA_C) || \
+ !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) )
+#error "MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) && \
+ ( !defined(MBEDTLS_CAN_ECDH) || !defined(MBEDTLS_RSA_C) || \
+ !defined(MBEDTLS_X509_CRT_PARSE_C) || !defined(MBEDTLS_PKCS1_V15) )
+#error "MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) && \
+ ( !defined(MBEDTLS_CAN_ECDH) || \
+ !defined(MBEDTLS_PK_CAN_ECDSA_SIGN) || \
+ !defined(MBEDTLS_X509_CRT_PARSE_C) )
+#error "MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) && \
+ ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \
+ !defined(MBEDTLS_PKCS1_V15) )
+#error "MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) && \
+ ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_X509_CRT_PARSE_C) || \
+ !defined(MBEDTLS_PKCS1_V15) )
+#error "MBEDTLS_KEY_EXCHANGE_RSA_ENABLED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \
+ ( !defined(MBEDTLS_PK_HAVE_JPAKE) || \
+ !defined(MBEDTLS_PK_HAVE_CURVE_SECP256R1) )
+#error "MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED defined, but not all prerequisites"
+#endif
+
+/* Use of EC J-PAKE in TLS requires SHA-256. */
+#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) && \
+ !defined(MBEDTLS_MD_HAVE_SHA256)
+#error "MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) && \
+ !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) && \
+ ( !defined(MBEDTLS_SHA256_C) && \
+ !defined(MBEDTLS_SHA512_C) && \
+ !defined(MBEDTLS_SHA1_C) )
+#error "!MBEDTLS_SSL_KEEP_PEER_CERTIFICATE requires MBEDTLS_SHA512_C, MBEDTLS_SHA256_C or MBEDTLS_SHA1_C"
+#endif
+
+#if defined(MBEDTLS_MD_C) && !( \
+ defined(MBEDTLS_MD5_C) || \
+ defined(MBEDTLS_RIPEMD160_C) || \
+ defined(MBEDTLS_SHA1_C) || \
+ defined(MBEDTLS_SHA224_C) || \
+ defined(MBEDTLS_SHA256_C) || \
+ defined(MBEDTLS_SHA384_C) || \
+ defined(MBEDTLS_SHA512_C) || \
+ (defined(MBEDTLS_PSA_CRYPTO_C) && \
+ (defined(PSA_WANT_ALG_MD5) || \
+ defined(PSA_WANT_ALG_RIPEMD160) || \
+ defined(PSA_WANT_ALG_SHA_1) || \
+ defined(PSA_WANT_ALG_SHA_224) || \
+ defined(PSA_WANT_ALG_SHA_256) || \
+ defined(PSA_WANT_ALG_SHA_384) || \
+ defined(PSA_WANT_ALG_SHA_512))))
+#error "MBEDTLS_MD_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_LMS_C) && \
+ ! ( defined(MBEDTLS_PSA_CRYPTO_C) && defined(PSA_WANT_ALG_SHA_256) )
+#error "MBEDTLS_LMS_C requires MBEDTLS_PSA_CRYPTO_C and PSA_WANT_ALG_SHA_256"
+#endif
+
+#if defined(MBEDTLS_LMS_PRIVATE) && \
+ ( !defined(MBEDTLS_LMS_C) )
+#error "MBEDTLS_LMS_PRIVATE requires MBEDTLS_LMS_C"
+#endif
+
+#if defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C) && \
+ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) )
+#error "MBEDTLS_MEMORY_BUFFER_ALLOC_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_MEMORY_BACKTRACE) && !defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
+#error "MBEDTLS_MEMORY_BACKTRACE defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_MEMORY_DEBUG) && !defined(MBEDTLS_MEMORY_BUFFER_ALLOC_C)
+#error "MBEDTLS_MEMORY_DEBUG defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PEM_PARSE_C) && !defined(MBEDTLS_BASE64_C)
+#error "MBEDTLS_PEM_PARSE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PEM_WRITE_C) && !defined(MBEDTLS_BASE64_C)
+#error "MBEDTLS_PEM_WRITE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PK_C) && \
+ !defined(MBEDTLS_RSA_C) && !defined(MBEDTLS_PK_HAVE_ECC_KEYS)
+#error "MBEDTLS_PK_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PK_PARSE_C) && !defined(MBEDTLS_PK_C)
+#error "MBEDTLS_PK_PARSE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PK_WRITE_C) && !defined(MBEDTLS_PK_C)
+#error "MBEDTLS_PK_WRITE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_EXIT_ALT) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_EXIT_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_EXIT_MACRO) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_EXIT_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_EXIT_MACRO) &&\
+ ( defined(MBEDTLS_PLATFORM_STD_EXIT) ||\
+ defined(MBEDTLS_PLATFORM_EXIT_ALT) )
+#error "MBEDTLS_PLATFORM_EXIT_MACRO and MBEDTLS_PLATFORM_STD_EXIT/MBEDTLS_PLATFORM_EXIT_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_SETBUF_ALT) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_SETBUF_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_SETBUF_MACRO) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_SETBUF_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_SETBUF_MACRO) &&\
+ ( defined(MBEDTLS_PLATFORM_STD_SETBUF) ||\
+ defined(MBEDTLS_PLATFORM_SETBUF_ALT) )
+#error "MBEDTLS_PLATFORM_SETBUF_MACRO and MBEDTLS_PLATFORM_STD_SETBUF/MBEDTLS_PLATFORM_SETBUF_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_TIME_ALT) &&\
+ ( !defined(MBEDTLS_PLATFORM_C) ||\
+ !defined(MBEDTLS_HAVE_TIME) )
+#error "MBEDTLS_PLATFORM_TIME_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_TIME_MACRO) &&\
+ ( !defined(MBEDTLS_PLATFORM_C) ||\
+ !defined(MBEDTLS_HAVE_TIME) )
+#error "MBEDTLS_PLATFORM_TIME_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO) &&\
+ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_HAVE_TIME) )
+#error "MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_MS_TIME_ALT) && \
+ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_HAVE_TIME) )
+#error "MBEDTLS_PLATFORM_MS_TIME_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) &&\
+ ( !defined(MBEDTLS_PLATFORM_C) ||\
+ !defined(MBEDTLS_HAVE_TIME) )
+#error "MBEDTLS_PLATFORM_TIME_TYPE_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_TIME_MACRO) &&\
+ ( defined(MBEDTLS_PLATFORM_STD_TIME) ||\
+ defined(MBEDTLS_PLATFORM_TIME_ALT) )
+#error "MBEDTLS_PLATFORM_TIME_MACRO and MBEDTLS_PLATFORM_STD_TIME/MBEDTLS_PLATFORM_TIME_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO) &&\
+ ( defined(MBEDTLS_PLATFORM_STD_TIME) ||\
+ defined(MBEDTLS_PLATFORM_TIME_ALT) )
+#error "MBEDTLS_PLATFORM_TIME_TYPE_MACRO and MBEDTLS_PLATFORM_STD_TIME/MBEDTLS_PLATFORM_TIME_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_FPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_FPRINTF_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_FPRINTF_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO) &&\
+ ( defined(MBEDTLS_PLATFORM_STD_FPRINTF) ||\
+ defined(MBEDTLS_PLATFORM_FPRINTF_ALT) )
+#error "MBEDTLS_PLATFORM_FPRINTF_MACRO and MBEDTLS_PLATFORM_STD_FPRINTF/MBEDTLS_PLATFORM_FPRINTF_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_FREE_MACRO) &&\
+ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) )
+#error "MBEDTLS_PLATFORM_FREE_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_FREE_MACRO) &&\
+ defined(MBEDTLS_PLATFORM_STD_FREE)
+#error "MBEDTLS_PLATFORM_FREE_MACRO and MBEDTLS_PLATFORM_STD_FREE cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_FREE_MACRO) && !defined(MBEDTLS_PLATFORM_CALLOC_MACRO)
+#error "MBEDTLS_PLATFORM_CALLOC_MACRO must be defined if MBEDTLS_PLATFORM_FREE_MACRO is"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&\
+ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_PLATFORM_MEMORY) )
+#error "MBEDTLS_PLATFORM_CALLOC_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) &&\
+ defined(MBEDTLS_PLATFORM_STD_CALLOC)
+#error "MBEDTLS_PLATFORM_CALLOC_MACRO and MBEDTLS_PLATFORM_STD_CALLOC cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_CALLOC_MACRO) && !defined(MBEDTLS_PLATFORM_FREE_MACRO)
+#error "MBEDTLS_PLATFORM_FREE_MACRO must be defined if MBEDTLS_PLATFORM_CALLOC_MACRO is"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_MEMORY) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_MEMORY defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_PRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_PRINTF_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_PRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_PRINTF_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_PRINTF_MACRO) &&\
+ ( defined(MBEDTLS_PLATFORM_STD_PRINTF) ||\
+ defined(MBEDTLS_PLATFORM_PRINTF_ALT) )
+#error "MBEDTLS_PLATFORM_PRINTF_MACRO and MBEDTLS_PLATFORM_STD_PRINTF/MBEDTLS_PLATFORM_PRINTF_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_SNPRINTF_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_SNPRINTF_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO) &&\
+ ( defined(MBEDTLS_PLATFORM_STD_SNPRINTF) ||\
+ defined(MBEDTLS_PLATFORM_SNPRINTF_ALT) )
+#error "MBEDTLS_PLATFORM_SNPRINTF_MACRO and MBEDTLS_PLATFORM_STD_SNPRINTF/MBEDTLS_PLATFORM_SNPRINTF_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_VSNPRINTF_ALT) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_VSNPRINTF_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_VSNPRINTF_MACRO) && !defined(MBEDTLS_PLATFORM_C)
+#error "MBEDTLS_PLATFORM_VSNPRINTF_MACRO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_VSNPRINTF_MACRO) &&\
+ ( defined(MBEDTLS_PLATFORM_STD_VSNPRINTF) ||\
+ defined(MBEDTLS_PLATFORM_VSNPRINTF_ALT) )
+#error "MBEDTLS_PLATFORM_VSNPRINTF_MACRO and MBEDTLS_PLATFORM_STD_VSNPRINTF/MBEDTLS_PLATFORM_VSNPRINTF_ALT cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_MEM_HDR) &&\
+ !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS)
+#error "MBEDTLS_PLATFORM_STD_MEM_HDR defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_CALLOC) && !defined(MBEDTLS_PLATFORM_MEMORY)
+#error "MBEDTLS_PLATFORM_STD_CALLOC defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_FREE) && !defined(MBEDTLS_PLATFORM_MEMORY)
+#error "MBEDTLS_PLATFORM_STD_FREE defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_EXIT) &&\
+ !defined(MBEDTLS_PLATFORM_EXIT_ALT)
+#error "MBEDTLS_PLATFORM_STD_EXIT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_TIME) &&\
+ ( !defined(MBEDTLS_PLATFORM_TIME_ALT) ||\
+ !defined(MBEDTLS_HAVE_TIME) )
+#error "MBEDTLS_PLATFORM_STD_TIME defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_FPRINTF) &&\
+ !defined(MBEDTLS_PLATFORM_FPRINTF_ALT)
+#error "MBEDTLS_PLATFORM_STD_FPRINTF defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_PRINTF) &&\
+ !defined(MBEDTLS_PLATFORM_PRINTF_ALT)
+#error "MBEDTLS_PLATFORM_STD_PRINTF defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_SNPRINTF) &&\
+ !defined(MBEDTLS_PLATFORM_SNPRINTF_ALT)
+#error "MBEDTLS_PLATFORM_STD_SNPRINTF defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_ENTROPY_NV_SEED) &&\
+ ( !defined(MBEDTLS_PLATFORM_C) || !defined(MBEDTLS_ENTROPY_C) )
+#error "MBEDTLS_ENTROPY_NV_SEED defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT) &&\
+ !defined(MBEDTLS_ENTROPY_NV_SEED)
+#error "MBEDTLS_PLATFORM_NV_SEED_ALT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) &&\
+ !defined(MBEDTLS_PLATFORM_NV_SEED_ALT)
+#error "MBEDTLS_PLATFORM_STD_NV_SEED_READ defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) &&\
+ !defined(MBEDTLS_PLATFORM_NV_SEED_ALT)
+#error "MBEDTLS_PLATFORM_STD_NV_SEED_WRITE defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) &&\
+ ( defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ) ||\
+ defined(MBEDTLS_PLATFORM_NV_SEED_ALT) )
+#error "MBEDTLS_PLATFORM_NV_SEED_READ_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_READ cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO) &&\
+ ( defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE) ||\
+ defined(MBEDTLS_PLATFORM_NV_SEED_ALT) )
+#error "MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO and MBEDTLS_PLATFORM_STD_NV_SEED_WRITE cannot be defined simultaneously"
+#endif
+
+#if defined(MBEDTLS_PSA_CRYPTO_C) && \
+ !( ( ( defined(MBEDTLS_CTR_DRBG_C) || defined(MBEDTLS_HMAC_DRBG_C) ) && \
+ defined(MBEDTLS_ENTROPY_C) ) || \
+ defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) )
+#error "MBEDTLS_PSA_CRYPTO_C defined, but not all prerequisites (missing RNG)"
+#endif
+
+#if defined(MBEDTLS_PSA_CRYPTO_C) && !defined(MBEDTLS_CIPHER_C )
+#error "MBEDTLS_PSA_CRYPTO_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PSA_CRYPTO_SPM) && !defined(MBEDTLS_PSA_CRYPTO_C)
+#error "MBEDTLS_PSA_CRYPTO_SPM defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PSA_CRYPTO_SE_C) && \
+ ! ( defined(MBEDTLS_PSA_CRYPTO_C) && \
+ defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) )
+#error "MBEDTLS_PSA_CRYPTO_SE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
+#if defined(MBEDTLS_DEPRECATED_REMOVED)
+#error "MBEDTLS_PSA_CRYPTO_SE_C is deprecated and will be removed in a future version of Mbed TLS"
+#elif defined(MBEDTLS_DEPRECATED_WARNING)
+#warning "MBEDTLS_PSA_CRYPTO_SE_C is deprecated and will be removed in a future version of Mbed TLS"
+#endif
+#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
+
+#if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) && \
+ ! defined(MBEDTLS_PSA_CRYPTO_C)
+#error "MBEDTLS_PSA_CRYPTO_STORAGE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
+ !( defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) && \
+ defined(MBEDTLS_ENTROPY_NV_SEED) )
+#error "MBEDTLS_PSA_INJECT_ENTROPY defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
+ !defined(MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES)
+#error "MBEDTLS_PSA_INJECT_ENTROPY is not compatible with actual entropy sources"
+#endif
+
+#if defined(MBEDTLS_PSA_INJECT_ENTROPY) && \
+ defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
+#error "MBEDTLS_PSA_INJECT_ENTROPY is not compatible with MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG"
+#endif
+
+#if defined(MBEDTLS_PSA_ITS_FILE_C) && \
+ !defined(MBEDTLS_FS_IO)
+#error "MBEDTLS_PSA_ITS_FILE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_BIGNUM_C) || \
+ !defined(MBEDTLS_OID_C) )
+#error "MBEDTLS_RSA_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_RSA_C) && ( !defined(MBEDTLS_PKCS1_V21) && \
+ !defined(MBEDTLS_PKCS1_V15) )
+#error "MBEDTLS_RSA_C defined, but none of the PKCS1 versions enabled"
+#endif
+
+#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) && \
+ ( !defined(MBEDTLS_RSA_C) || !defined(MBEDTLS_PKCS1_V21) )
+#error "MBEDTLS_X509_RSASSA_PSS_SUPPORT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT) && \
+ defined(MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY)
+#error "Must only define one of MBEDTLS_SHA512_USE_A64_CRYPTO_*"
+#endif
+
+#if defined(MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT) || \
+ defined(MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY)
+#if !defined(MBEDTLS_SHA512_C)
+#error "MBEDTLS_SHA512_USE_A64_CRYPTO_* defined without MBEDTLS_SHA512_C"
+#endif
+#if defined(MBEDTLS_SHA512_ALT) || defined(MBEDTLS_SHA512_PROCESS_ALT)
+#error "MBEDTLS_SHA512_*ALT can't be used with MBEDTLS_SHA512_USE_A64_CRYPTO_*"
+#endif
+
+#endif /* MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT || MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY */
+
+#if defined(MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY) && !defined(__aarch64__)
+#error "MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY defined on non-Aarch64 system"
+#endif
+
+#if defined(MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT) && \
+ defined(MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY)
+#error "Must only define one of MBEDTLS_SHA256_USE_A64_CRYPTO_*"
+#endif
+
+#if defined(MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT) || \
+ defined(MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY)
+#if !defined(MBEDTLS_SHA256_C)
+#error "MBEDTLS_SHA256_USE_A64_CRYPTO_* defined without MBEDTLS_SHA256_C"
+#endif
+#if defined(MBEDTLS_SHA256_ALT) || defined(MBEDTLS_SHA256_PROCESS_ALT)
+#error "MBEDTLS_SHA256_*ALT can't be used with MBEDTLS_SHA256_USE_A64_CRYPTO_*"
+#endif
+
+#endif
+
+#if defined(MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY) && \
+ !defined(__aarch64__) && !defined(_M_ARM64)
+#error "MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY defined on non-Aarch64 system"
+#endif
+
+/* TLS 1.3 requires separate HKDF parts from PSA,
+ * and at least one ciphersuite, so at least SHA-256 or SHA-384
+ * from PSA to use with HKDF.
+ *
+ * Note: for dependencies common with TLS 1.2 (running handshake hash),
+ * see MBEDTLS_SSL_TLS_C. */
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
+ !(defined(MBEDTLS_PSA_CRYPTO_C) && \
+ defined(PSA_WANT_ALG_HKDF_EXTRACT) && \
+ defined(PSA_WANT_ALG_HKDF_EXPAND) && \
+ (defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA_384)))
+#error "MBEDTLS_SSL_PROTO_TLS1_3 defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
+#if !( (defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH)) && \
+ defined(MBEDTLS_X509_CRT_PARSE_C) && \
+ ( defined(MBEDTLS_PK_CAN_ECDSA_SIGN) || defined(MBEDTLS_PKCS1_V21) ) )
+#error "MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED defined, but not all prerequisites"
+#endif
+#endif
+
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
+#if !( defined(PSA_WANT_ALG_ECDH) || defined(PSA_WANT_ALG_FFDH) )
+#error "MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED defined, but not all prerequisites"
+#endif
+#endif
+
+/*
+ * The current implementation of TLS 1.3 requires MBEDTLS_SSL_KEEP_PEER_CERTIFICATE.
+ */
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
+#error "MBEDTLS_SSL_PROTO_TLS1_3 defined without MBEDTLS_SSL_KEEP_PEER_CERTIFICATE"
+#endif
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
+ !(defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) )
+#error "One or more versions of the TLS protocol are enabled " \
+ "but no key exchange methods defined with MBEDTLS_KEY_EXCHANGE_xxxx"
+#endif
+
+#if defined(MBEDTLS_SSL_EARLY_DATA) && \
+ ( !defined(MBEDTLS_SSL_SESSION_TICKETS) || \
+ ( !defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED) && \
+ !defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED) ) )
+#error "MBEDTLS_SSL_EARLY_DATA defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_SRV_C) && \
+ defined(MBEDTLS_SSL_MAX_EARLY_DATA_SIZE) && \
+ ((MBEDTLS_SSL_MAX_EARLY_DATA_SIZE < 0) || \
+ (MBEDTLS_SSL_MAX_EARLY_DATA_SIZE > UINT32_MAX))
+#error "MBEDTLS_SSL_MAX_EARLY_DATA_SIZE must be in the range(0..UINT32_MAX)"
+#endif
+
+#if defined(MBEDTLS_SSL_PROTO_DTLS) && \
+ !defined(MBEDTLS_SSL_PROTO_TLS1_2)
+#error "MBEDTLS_SSL_PROTO_DTLS defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_CLI_C) && !defined(MBEDTLS_SSL_TLS_C)
+#error "MBEDTLS_SSL_CLI_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && !defined(MBEDTLS_X509_CRT_PARSE_C)
+#error "MBEDTLS_SSL_ASYNC_PRIVATE defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_TLS_C) && !defined(MBEDTLS_CIPHER_C)
+#error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites"
+#endif
+
+/* TLS 1.2 and 1.3 require SHA-256 or SHA-384 (running handshake hash) */
+#if defined(MBEDTLS_SSL_TLS_C)
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#if !(defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA_384))
+#error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites"
+#endif
+#else /* MBEDTLS_USE_PSA_CRYPTO */
+#if !defined(MBEDTLS_MD_C) || \
+ !(defined(MBEDTLS_MD_HAVE_SHA256) || defined(MBEDTLS_MD_HAVE_SHA384))
+#error "MBEDTLS_SSL_TLS_C defined, but not all prerequisites"
+#endif
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+#endif /* MBEDTLS_SSL_TLS_C */
+
+#if defined(MBEDTLS_SSL_SRV_C) && !defined(MBEDTLS_SSL_TLS_C)
+#error "MBEDTLS_SSL_SRV_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_TLS_C) && \
+ !( defined(MBEDTLS_SSL_PROTO_TLS1_2) || defined(MBEDTLS_SSL_PROTO_TLS1_3) )
+#error "MBEDTLS_SSL_TLS_C defined, but no protocols are active"
+#endif
+
+#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && !defined(MBEDTLS_SSL_PROTO_DTLS)
+#error "MBEDTLS_SSL_DTLS_HELLO_VERIFY defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE) && \
+ !defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY)
+#error "MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) && \
+ ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) )
+#error "MBEDTLS_SSL_DTLS_ANTI_REPLAY defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
+ ( !defined(MBEDTLS_SSL_TLS_C) || !defined(MBEDTLS_SSL_PROTO_DTLS) )
+#error "MBEDTLS_SSL_DTLS_CONNECTION_ID defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
+ defined(MBEDTLS_SSL_CID_IN_LEN_MAX) && \
+ MBEDTLS_SSL_CID_IN_LEN_MAX > 255
+#error "MBEDTLS_SSL_CID_IN_LEN_MAX too large (max 255)"
+#endif
+
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
+ defined(MBEDTLS_SSL_CID_OUT_LEN_MAX) && \
+ MBEDTLS_SSL_CID_OUT_LEN_MAX > 255
+#error "MBEDTLS_SSL_CID_OUT_LEN_MAX too large (max 255)"
+#endif
+
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT) && \
+ !defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
+#error "MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT) && MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT != 0
+#if defined(MBEDTLS_DEPRECATED_REMOVED)
+#error "MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT is deprecated and will be removed in a future version of Mbed TLS"
+#elif defined(MBEDTLS_DEPRECATED_WARNING)
+#warning "MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT is deprecated and will be removed in a future version of Mbed TLS"
+#endif
+#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT && MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT != 0 */
+
+#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) && \
+ !defined(MBEDTLS_SSL_PROTO_TLS1_2)
+#error "MBEDTLS_SSL_ENCRYPT_THEN_MAC defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) && \
+ !defined(MBEDTLS_SSL_PROTO_TLS1_2)
+#error "MBEDTLS_SSL_EXTENDED_MASTER_SECRET defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_RENEGOTIATION) && \
+ !defined(MBEDTLS_SSL_PROTO_TLS1_2)
+#error "MBEDTLS_SSL_RENEGOTIATION defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_TICKET_C) && ( !defined(MBEDTLS_CIPHER_C) && \
+ !defined(MBEDTLS_USE_PSA_CRYPTO) )
+#error "MBEDTLS_SSL_TICKET_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_TICKET_C) && \
+ !( defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) || defined(MBEDTLS_CHACHAPOLY_C) )
+#error "MBEDTLS_SSL_TICKET_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH) && \
+ MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH >= 256
+#error "MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH must be less than 256"
+#endif
+
+#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && \
+ !defined(MBEDTLS_X509_CRT_PARSE_C)
+#error "MBEDTLS_SSL_SERVER_NAME_INDICATION defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_THREADING_PTHREAD)
+#if !defined(MBEDTLS_THREADING_C) || defined(MBEDTLS_THREADING_IMPL)
+#error "MBEDTLS_THREADING_PTHREAD defined, but not all prerequisites"
+#endif
+#define MBEDTLS_THREADING_IMPL
+#endif
+
+#if defined(MBEDTLS_THREADING_ALT)
+#if !defined(MBEDTLS_THREADING_C) || defined(MBEDTLS_THREADING_IMPL)
+#error "MBEDTLS_THREADING_ALT defined, but not all prerequisites"
+#endif
+#define MBEDTLS_THREADING_IMPL
+#endif
+
+#if defined(MBEDTLS_THREADING_C) && !defined(MBEDTLS_THREADING_IMPL)
+#error "MBEDTLS_THREADING_C defined, single threading implementation required"
+#endif
+#undef MBEDTLS_THREADING_IMPL
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_PSA_CRYPTO_C)
+#error "MBEDTLS_USE_PSA_CRYPTO defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_VERSION_FEATURES) && !defined(MBEDTLS_VERSION_C)
+#error "MBEDTLS_VERSION_FEATURES defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_X509_USE_C) && \
+ (!defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_PARSE_C) || \
+ !defined(MBEDTLS_PK_PARSE_C) || \
+ ( !defined(MBEDTLS_MD_C) && !defined(MBEDTLS_USE_PSA_CRYPTO) ) )
+#error "MBEDTLS_X509_USE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_X509_CREATE_C) && \
+ (!defined(MBEDTLS_OID_C) || !defined(MBEDTLS_ASN1_WRITE_C) || \
+ !defined(MBEDTLS_PK_PARSE_C) || \
+ ( !defined(MBEDTLS_MD_C) && !defined(MBEDTLS_USE_PSA_CRYPTO) ) )
+#error "MBEDTLS_X509_CREATE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) )
+#error "MBEDTLS_X509_CRT_PARSE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_X509_CRL_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) )
+#error "MBEDTLS_X509_CRL_PARSE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_X509_CSR_PARSE_C) && ( !defined(MBEDTLS_X509_USE_C) )
+#error "MBEDTLS_X509_CSR_PARSE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_X509_CRT_WRITE_C) && ( !defined(MBEDTLS_X509_CREATE_C) )
+#error "MBEDTLS_X509_CRT_WRITE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_X509_CSR_WRITE_C) && ( !defined(MBEDTLS_X509_CREATE_C) )
+#error "MBEDTLS_X509_CSR_WRITE_C defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK) && \
+ ( !defined(MBEDTLS_X509_CRT_PARSE_C) )
+#error "MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_HAVE_INT32) && defined(MBEDTLS_HAVE_INT64)
+#error "MBEDTLS_HAVE_INT32 and MBEDTLS_HAVE_INT64 cannot be defined simultaneously"
+#endif /* MBEDTLS_HAVE_INT32 && MBEDTLS_HAVE_INT64 */
+
+#if ( defined(MBEDTLS_HAVE_INT32) || defined(MBEDTLS_HAVE_INT64) ) && \
+ defined(MBEDTLS_HAVE_ASM)
+#error "MBEDTLS_HAVE_INT32/MBEDTLS_HAVE_INT64 and MBEDTLS_HAVE_ASM cannot be defined simultaneously"
+#endif /* (MBEDTLS_HAVE_INT32 || MBEDTLS_HAVE_INT64) && MBEDTLS_HAVE_ASM */
+
+#if defined(MBEDTLS_SSL_DTLS_SRTP) && ( !defined(MBEDTLS_SSL_PROTO_DTLS) )
+#error "MBEDTLS_SSL_DTLS_SRTP defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH) && ( !defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) )
+#error "MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_RECORD_SIZE_LIMIT) && ( !defined(MBEDTLS_SSL_PROTO_TLS1_3) )
+#error "MBEDTLS_SSL_RECORD_SIZE_LIMIT defined, but not all prerequisites"
+#endif
+
+#if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION) && !( defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) || defined(MBEDTLS_CHACHAPOLY_C) )
+#error "MBEDTLS_SSL_CONTEXT_SERIALIZATION defined, but not all prerequisites"
+#endif
+
+/* Reject attempts to enable options that have been removed and that could
+ * cause a build to succeed but with features removed. */
+
+#if defined(MBEDTLS_HAVEGE_C) //no-check-names
+#error "MBEDTLS_HAVEGE_C was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/2599"
+#endif
+
+#if defined(MBEDTLS_SSL_HW_RECORD_ACCEL) //no-check-names
+#error "MBEDTLS_SSL_HW_RECORD_ACCEL was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4031"
+#endif
+
+#if defined(MBEDTLS_SSL_PROTO_SSL3) //no-check-names
+#error "MBEDTLS_SSL_PROTO_SSL3 (SSL v3.0 support) was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4031"
+#endif
+
+#if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) //no-check-names
+#error "MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO (SSL v2 ClientHello support) was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4031"
+#endif
+
+#if defined(MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT) //no-check-names
+#error "MBEDTLS_SSL_TRUNCATED_HMAC_COMPAT (compatibility with the buggy implementation of truncated HMAC in Mbed TLS up to 2.7) was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4031"
+#endif
+
+#if defined(MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES) //no-check-names
+#error "MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES was removed in Mbed TLS 3.0. See the ChangeLog entry if you really need SHA-1-signed certificates."
+#endif
+
+#if defined(MBEDTLS_ZLIB_SUPPORT) //no-check-names
+#error "MBEDTLS_ZLIB_SUPPORT was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4031"
+#endif
+
+#if defined(MBEDTLS_CHECK_PARAMS) //no-check-names
+#error "MBEDTLS_CHECK_PARAMS was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4313"
+#endif
+
+#if defined(MBEDTLS_SSL_CID_PADDING_GRANULARITY) //no-check-names
+#error "MBEDTLS_SSL_CID_PADDING_GRANULARITY was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4335"
+#endif
+
+#if defined(MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY) //no-check-names
+#error "MBEDTLS_SSL_TLS1_3_PADDING_GRANULARITY was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4335"
+#endif
+
+#if defined(MBEDTLS_SSL_TRUNCATED_HMAC) //no-check-names
+#error "MBEDTLS_SSL_TRUNCATED_HMAC was removed in Mbed TLS 3.0. See https://github.com/Mbed-TLS/mbedtls/issues/4341"
+#endif
+
+#if defined(MBEDTLS_PKCS7_C) && ( ( !defined(MBEDTLS_ASN1_PARSE_C) ) || \
+ ( !defined(MBEDTLS_OID_C) ) || ( !defined(MBEDTLS_PK_PARSE_C) ) || \
+ ( !defined(MBEDTLS_X509_CRT_PARSE_C) ) || \
+ ( !defined(MBEDTLS_X509_CRL_PARSE_C) ) || \
+ ( !defined(MBEDTLS_MD_C) ) )
+#error "MBEDTLS_PKCS7_C is defined, but not all prerequisites"
+#endif
+
+/* Undefine helper symbols */
+#undef MBEDTLS_PK_HAVE_JPAKE
+#undef MBEDTLS_MD_HAVE_SHA256
+#undef MBEDTLS_MD_HAVE_SHA384
+#undef MBEDTLS_MD_HAVE_SHA512
+#undef MBEDTLS_PK_HAVE_CURVE_SECP256R1
+
+/*
+ * Avoid warning from -pedantic. This is a convenient place for this
+ * workaround since this is included by every single file before the
+ * #if defined(MBEDTLS_xxx_C) that results in empty translation units.
+ */
+typedef int mbedtls_iso_c_forbids_empty_translation_units;
+
+/* *INDENT-ON* */
+#endif /* MBEDTLS_CHECK_CONFIG_H */
diff --git a/include/mbedtls/cipher.h b/include/mbedtls/cipher.h
new file mode 100644
index 0000000..2596baa
--- /dev/null
+++ b/include/mbedtls/cipher.h
@@ -0,0 +1,1183 @@
+/**
+ * \file cipher.h
+ *
+ * \brief This file contains an abstraction interface for use with the cipher
+ * primitives provided by the library. It provides a common interface to all of
+ * the available cipher operations.
+ *
+ * \author Adriaan de Jong <dejong@fox-it.com>
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CIPHER_H
+#define MBEDTLS_CIPHER_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#include "mbedtls/platform_util.h"
+
+#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
+#define MBEDTLS_CIPHER_MODE_AEAD
+#endif
+
+#if defined(MBEDTLS_CIPHER_MODE_CBC)
+#define MBEDTLS_CIPHER_MODE_WITH_PADDING
+#endif
+
+#if defined(MBEDTLS_CIPHER_NULL_CIPHER) || \
+ defined(MBEDTLS_CHACHA20_C)
+#define MBEDTLS_CIPHER_MODE_STREAM
+#endif
+
+/** The selected feature is not available. */
+#define MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE -0x6080
+/** Bad input parameters. */
+#define MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA -0x6100
+/** Failed to allocate memory. */
+#define MBEDTLS_ERR_CIPHER_ALLOC_FAILED -0x6180
+/** Input data contains invalid padding and is rejected. */
+#define MBEDTLS_ERR_CIPHER_INVALID_PADDING -0x6200
+/** Decryption of block requires a full block. */
+#define MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED -0x6280
+/** Authentication failed (for AEAD modes). */
+#define MBEDTLS_ERR_CIPHER_AUTH_FAILED -0x6300
+/** The context is invalid. For example, because it was freed. */
+#define MBEDTLS_ERR_CIPHER_INVALID_CONTEXT -0x6380
+
+#define MBEDTLS_CIPHER_VARIABLE_IV_LEN 0x01 /**< Cipher accepts IVs of variable length. */
+#define MBEDTLS_CIPHER_VARIABLE_KEY_LEN 0x02 /**< Cipher accepts keys of variable length. */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Supported cipher types.
+ *
+ * \warning DES/3DES are considered weak ciphers and their use
+ * constitutes a security risk. We recommend considering stronger
+ * ciphers instead.
+ */
+typedef enum {
+ MBEDTLS_CIPHER_ID_NONE = 0, /**< Placeholder to mark the end of cipher ID lists. */
+ MBEDTLS_CIPHER_ID_NULL, /**< The identity cipher, treated as a stream cipher. */
+ MBEDTLS_CIPHER_ID_AES, /**< The AES cipher. */
+ MBEDTLS_CIPHER_ID_DES, /**< The DES cipher. \warning DES is considered weak. */
+ MBEDTLS_CIPHER_ID_3DES, /**< The Triple DES cipher. \warning 3DES is considered weak. */
+ MBEDTLS_CIPHER_ID_CAMELLIA, /**< The Camellia cipher. */
+ MBEDTLS_CIPHER_ID_ARIA, /**< The Aria cipher. */
+ MBEDTLS_CIPHER_ID_CHACHA20, /**< The ChaCha20 cipher. */
+} mbedtls_cipher_id_t;
+
+/**
+ * \brief Supported {cipher type, cipher mode} pairs.
+ *
+ * \warning DES/3DES are considered weak ciphers and their use
+ * constitutes a security risk. We recommend considering stronger
+ * ciphers instead.
+ */
+typedef enum {
+ MBEDTLS_CIPHER_NONE = 0, /**< Placeholder to mark the end of cipher-pair lists. */
+ MBEDTLS_CIPHER_NULL, /**< The identity stream cipher. */
+ MBEDTLS_CIPHER_AES_128_ECB, /**< AES cipher with 128-bit ECB mode. */
+ MBEDTLS_CIPHER_AES_192_ECB, /**< AES cipher with 192-bit ECB mode. */
+ MBEDTLS_CIPHER_AES_256_ECB, /**< AES cipher with 256-bit ECB mode. */
+ MBEDTLS_CIPHER_AES_128_CBC, /**< AES cipher with 128-bit CBC mode. */
+ MBEDTLS_CIPHER_AES_192_CBC, /**< AES cipher with 192-bit CBC mode. */
+ MBEDTLS_CIPHER_AES_256_CBC, /**< AES cipher with 256-bit CBC mode. */
+ MBEDTLS_CIPHER_AES_128_CFB128, /**< AES cipher with 128-bit CFB128 mode. */
+ MBEDTLS_CIPHER_AES_192_CFB128, /**< AES cipher with 192-bit CFB128 mode. */
+ MBEDTLS_CIPHER_AES_256_CFB128, /**< AES cipher with 256-bit CFB128 mode. */
+ MBEDTLS_CIPHER_AES_128_CTR, /**< AES cipher with 128-bit CTR mode. */
+ MBEDTLS_CIPHER_AES_192_CTR, /**< AES cipher with 192-bit CTR mode. */
+ MBEDTLS_CIPHER_AES_256_CTR, /**< AES cipher with 256-bit CTR mode. */
+ MBEDTLS_CIPHER_AES_128_GCM, /**< AES cipher with 128-bit GCM mode. */
+ MBEDTLS_CIPHER_AES_192_GCM, /**< AES cipher with 192-bit GCM mode. */
+ MBEDTLS_CIPHER_AES_256_GCM, /**< AES cipher with 256-bit GCM mode. */
+ MBEDTLS_CIPHER_CAMELLIA_128_ECB, /**< Camellia cipher with 128-bit ECB mode. */
+ MBEDTLS_CIPHER_CAMELLIA_192_ECB, /**< Camellia cipher with 192-bit ECB mode. */
+ MBEDTLS_CIPHER_CAMELLIA_256_ECB, /**< Camellia cipher with 256-bit ECB mode. */
+ MBEDTLS_CIPHER_CAMELLIA_128_CBC, /**< Camellia cipher with 128-bit CBC mode. */
+ MBEDTLS_CIPHER_CAMELLIA_192_CBC, /**< Camellia cipher with 192-bit CBC mode. */
+ MBEDTLS_CIPHER_CAMELLIA_256_CBC, /**< Camellia cipher with 256-bit CBC mode. */
+ MBEDTLS_CIPHER_CAMELLIA_128_CFB128, /**< Camellia cipher with 128-bit CFB128 mode. */
+ MBEDTLS_CIPHER_CAMELLIA_192_CFB128, /**< Camellia cipher with 192-bit CFB128 mode. */
+ MBEDTLS_CIPHER_CAMELLIA_256_CFB128, /**< Camellia cipher with 256-bit CFB128 mode. */
+ MBEDTLS_CIPHER_CAMELLIA_128_CTR, /**< Camellia cipher with 128-bit CTR mode. */
+ MBEDTLS_CIPHER_CAMELLIA_192_CTR, /**< Camellia cipher with 192-bit CTR mode. */
+ MBEDTLS_CIPHER_CAMELLIA_256_CTR, /**< Camellia cipher with 256-bit CTR mode. */
+ MBEDTLS_CIPHER_CAMELLIA_128_GCM, /**< Camellia cipher with 128-bit GCM mode. */
+ MBEDTLS_CIPHER_CAMELLIA_192_GCM, /**< Camellia cipher with 192-bit GCM mode. */
+ MBEDTLS_CIPHER_CAMELLIA_256_GCM, /**< Camellia cipher with 256-bit GCM mode. */
+ MBEDTLS_CIPHER_DES_ECB, /**< DES cipher with ECB mode. \warning DES is considered weak. */
+ MBEDTLS_CIPHER_DES_CBC, /**< DES cipher with CBC mode. \warning DES is considered weak. */
+ MBEDTLS_CIPHER_DES_EDE_ECB, /**< DES cipher with EDE ECB mode. \warning 3DES is considered weak. */
+ MBEDTLS_CIPHER_DES_EDE_CBC, /**< DES cipher with EDE CBC mode. \warning 3DES is considered weak. */
+ MBEDTLS_CIPHER_DES_EDE3_ECB, /**< DES cipher with EDE3 ECB mode. \warning 3DES is considered weak. */
+ MBEDTLS_CIPHER_DES_EDE3_CBC, /**< DES cipher with EDE3 CBC mode. \warning 3DES is considered weak. */
+ MBEDTLS_CIPHER_AES_128_CCM, /**< AES cipher with 128-bit CCM mode. */
+ MBEDTLS_CIPHER_AES_192_CCM, /**< AES cipher with 192-bit CCM mode. */
+ MBEDTLS_CIPHER_AES_256_CCM, /**< AES cipher with 256-bit CCM mode. */
+ MBEDTLS_CIPHER_AES_128_CCM_STAR_NO_TAG, /**< AES cipher with 128-bit CCM_STAR_NO_TAG mode. */
+ MBEDTLS_CIPHER_AES_192_CCM_STAR_NO_TAG, /**< AES cipher with 192-bit CCM_STAR_NO_TAG mode. */
+ MBEDTLS_CIPHER_AES_256_CCM_STAR_NO_TAG, /**< AES cipher with 256-bit CCM_STAR_NO_TAG mode. */
+ MBEDTLS_CIPHER_CAMELLIA_128_CCM, /**< Camellia cipher with 128-bit CCM mode. */
+ MBEDTLS_CIPHER_CAMELLIA_192_CCM, /**< Camellia cipher with 192-bit CCM mode. */
+ MBEDTLS_CIPHER_CAMELLIA_256_CCM, /**< Camellia cipher with 256-bit CCM mode. */
+ MBEDTLS_CIPHER_CAMELLIA_128_CCM_STAR_NO_TAG, /**< Camellia cipher with 128-bit CCM_STAR_NO_TAG mode. */
+ MBEDTLS_CIPHER_CAMELLIA_192_CCM_STAR_NO_TAG, /**< Camellia cipher with 192-bit CCM_STAR_NO_TAG mode. */
+ MBEDTLS_CIPHER_CAMELLIA_256_CCM_STAR_NO_TAG, /**< Camellia cipher with 256-bit CCM_STAR_NO_TAG mode. */
+ MBEDTLS_CIPHER_ARIA_128_ECB, /**< Aria cipher with 128-bit key and ECB mode. */
+ MBEDTLS_CIPHER_ARIA_192_ECB, /**< Aria cipher with 192-bit key and ECB mode. */
+ MBEDTLS_CIPHER_ARIA_256_ECB, /**< Aria cipher with 256-bit key and ECB mode. */
+ MBEDTLS_CIPHER_ARIA_128_CBC, /**< Aria cipher with 128-bit key and CBC mode. */
+ MBEDTLS_CIPHER_ARIA_192_CBC, /**< Aria cipher with 192-bit key and CBC mode. */
+ MBEDTLS_CIPHER_ARIA_256_CBC, /**< Aria cipher with 256-bit key and CBC mode. */
+ MBEDTLS_CIPHER_ARIA_128_CFB128, /**< Aria cipher with 128-bit key and CFB-128 mode. */
+ MBEDTLS_CIPHER_ARIA_192_CFB128, /**< Aria cipher with 192-bit key and CFB-128 mode. */
+ MBEDTLS_CIPHER_ARIA_256_CFB128, /**< Aria cipher with 256-bit key and CFB-128 mode. */
+ MBEDTLS_CIPHER_ARIA_128_CTR, /**< Aria cipher with 128-bit key and CTR mode. */
+ MBEDTLS_CIPHER_ARIA_192_CTR, /**< Aria cipher with 192-bit key and CTR mode. */
+ MBEDTLS_CIPHER_ARIA_256_CTR, /**< Aria cipher with 256-bit key and CTR mode. */
+ MBEDTLS_CIPHER_ARIA_128_GCM, /**< Aria cipher with 128-bit key and GCM mode. */
+ MBEDTLS_CIPHER_ARIA_192_GCM, /**< Aria cipher with 192-bit key and GCM mode. */
+ MBEDTLS_CIPHER_ARIA_256_GCM, /**< Aria cipher with 256-bit key and GCM mode. */
+ MBEDTLS_CIPHER_ARIA_128_CCM, /**< Aria cipher with 128-bit key and CCM mode. */
+ MBEDTLS_CIPHER_ARIA_192_CCM, /**< Aria cipher with 192-bit key and CCM mode. */
+ MBEDTLS_CIPHER_ARIA_256_CCM, /**< Aria cipher with 256-bit key and CCM mode. */
+ MBEDTLS_CIPHER_ARIA_128_CCM_STAR_NO_TAG, /**< Aria cipher with 128-bit key and CCM_STAR_NO_TAG mode. */
+ MBEDTLS_CIPHER_ARIA_192_CCM_STAR_NO_TAG, /**< Aria cipher with 192-bit key and CCM_STAR_NO_TAG mode. */
+ MBEDTLS_CIPHER_ARIA_256_CCM_STAR_NO_TAG, /**< Aria cipher with 256-bit key and CCM_STAR_NO_TAG mode. */
+ MBEDTLS_CIPHER_AES_128_OFB, /**< AES 128-bit cipher in OFB mode. */
+ MBEDTLS_CIPHER_AES_192_OFB, /**< AES 192-bit cipher in OFB mode. */
+ MBEDTLS_CIPHER_AES_256_OFB, /**< AES 256-bit cipher in OFB mode. */
+ MBEDTLS_CIPHER_AES_128_XTS, /**< AES 128-bit cipher in XTS block mode. */
+ MBEDTLS_CIPHER_AES_256_XTS, /**< AES 256-bit cipher in XTS block mode. */
+ MBEDTLS_CIPHER_CHACHA20, /**< ChaCha20 stream cipher. */
+ MBEDTLS_CIPHER_CHACHA20_POLY1305, /**< ChaCha20-Poly1305 AEAD cipher. */
+ MBEDTLS_CIPHER_AES_128_KW, /**< AES cipher with 128-bit NIST KW mode. */
+ MBEDTLS_CIPHER_AES_192_KW, /**< AES cipher with 192-bit NIST KW mode. */
+ MBEDTLS_CIPHER_AES_256_KW, /**< AES cipher with 256-bit NIST KW mode. */
+ MBEDTLS_CIPHER_AES_128_KWP, /**< AES cipher with 128-bit NIST KWP mode. */
+ MBEDTLS_CIPHER_AES_192_KWP, /**< AES cipher with 192-bit NIST KWP mode. */
+ MBEDTLS_CIPHER_AES_256_KWP, /**< AES cipher with 256-bit NIST KWP mode. */
+} mbedtls_cipher_type_t;
+
+/** Supported cipher modes. */
+typedef enum {
+ MBEDTLS_MODE_NONE = 0, /**< None. */
+ MBEDTLS_MODE_ECB, /**< The ECB cipher mode. */
+ MBEDTLS_MODE_CBC, /**< The CBC cipher mode. */
+ MBEDTLS_MODE_CFB, /**< The CFB cipher mode. */
+ MBEDTLS_MODE_OFB, /**< The OFB cipher mode. */
+ MBEDTLS_MODE_CTR, /**< The CTR cipher mode. */
+ MBEDTLS_MODE_GCM, /**< The GCM cipher mode. */
+ MBEDTLS_MODE_STREAM, /**< The stream cipher mode. */
+ MBEDTLS_MODE_CCM, /**< The CCM cipher mode. */
+ MBEDTLS_MODE_CCM_STAR_NO_TAG, /**< The CCM*-no-tag cipher mode. */
+ MBEDTLS_MODE_XTS, /**< The XTS cipher mode. */
+ MBEDTLS_MODE_CHACHAPOLY, /**< The ChaCha-Poly cipher mode. */
+ MBEDTLS_MODE_KW, /**< The SP800-38F KW mode */
+ MBEDTLS_MODE_KWP, /**< The SP800-38F KWP mode */
+} mbedtls_cipher_mode_t;
+
+/** Supported cipher padding types. */
+typedef enum {
+ MBEDTLS_PADDING_PKCS7 = 0, /**< PKCS7 padding (default). */
+ MBEDTLS_PADDING_ONE_AND_ZEROS, /**< ISO/IEC 7816-4 padding. */
+ MBEDTLS_PADDING_ZEROS_AND_LEN, /**< ANSI X.923 padding. */
+ MBEDTLS_PADDING_ZEROS, /**< Zero padding (not reversible). */
+ MBEDTLS_PADDING_NONE, /**< Never pad (full blocks only). */
+} mbedtls_cipher_padding_t;
+
+/** Type of operation. */
+typedef enum {
+ MBEDTLS_OPERATION_NONE = -1,
+ MBEDTLS_DECRYPT = 0,
+ MBEDTLS_ENCRYPT,
+} mbedtls_operation_t;
+
+enum {
+ /** Undefined key length. */
+ MBEDTLS_KEY_LENGTH_NONE = 0,
+ /** Key length, in bits (including parity), for DES keys. \warning DES is considered weak. */
+ MBEDTLS_KEY_LENGTH_DES = 64,
+ /** Key length in bits, including parity, for DES in two-key EDE. \warning 3DES is considered weak. */
+ MBEDTLS_KEY_LENGTH_DES_EDE = 128,
+ /** Key length in bits, including parity, for DES in three-key EDE. \warning 3DES is considered weak. */
+ MBEDTLS_KEY_LENGTH_DES_EDE3 = 192,
+};
+
+/** Maximum length of any IV, in Bytes. */
+/* This should ideally be derived automatically from list of ciphers.
+ * This should be kept in sync with MBEDTLS_SSL_MAX_IV_LENGTH defined
+ * in library/ssl_misc.h. */
+#define MBEDTLS_MAX_IV_LENGTH 16
+
+/** Maximum block size of any cipher, in Bytes. */
+/* This should ideally be derived automatically from list of ciphers.
+ * This should be kept in sync with MBEDTLS_SSL_MAX_BLOCK_LENGTH defined
+ * in library/ssl_misc.h. */
+#define MBEDTLS_MAX_BLOCK_LENGTH 16
+
+/** Maximum key length, in Bytes. */
+/* This should ideally be derived automatically from list of ciphers.
+ * For now, only check whether XTS is enabled which uses 64 Byte keys,
+ * and use 32 Bytes as an upper bound for the maximum key length otherwise.
+ * This should be kept in sync with MBEDTLS_SSL_MAX_BLOCK_LENGTH defined
+ * in library/ssl_misc.h, which however deliberately ignores the case of XTS
+ * since the latter isn't used in SSL/TLS. */
+#if defined(MBEDTLS_CIPHER_MODE_XTS)
+#define MBEDTLS_MAX_KEY_LENGTH 64
+#else
+#define MBEDTLS_MAX_KEY_LENGTH 32
+#endif /* MBEDTLS_CIPHER_MODE_XTS */
+
+/**
+ * Base cipher information (opaque struct).
+ */
+typedef struct mbedtls_cipher_base_t mbedtls_cipher_base_t;
+
+/**
+ * CMAC context (opaque struct).
+ */
+typedef struct mbedtls_cmac_context_t mbedtls_cmac_context_t;
+
+/**
+ * Cipher information. Allows calling cipher functions
+ * in a generic way.
+ *
+ * \note The library does not support custom cipher info structures,
+ * only built-in structures returned by the functions
+ * mbedtls_cipher_info_from_string(),
+ * mbedtls_cipher_info_from_type(),
+ * mbedtls_cipher_info_from_values(),
+ * mbedtls_cipher_info_from_psa().
+ *
+ * \note Some fields store a value that has been right-shifted to save
+ * code-size, so should not be used directly. The accessor
+ * functions adjust for this and return the "natural" value.
+ */
+typedef struct mbedtls_cipher_info_t {
+ /** Name of the cipher. */
+ const char *MBEDTLS_PRIVATE(name);
+
+ /** The block size, in bytes. */
+ unsigned int MBEDTLS_PRIVATE(block_size) : 5;
+
+ /** IV or nonce size, in bytes (right shifted by #MBEDTLS_IV_SIZE_SHIFT).
+ * For ciphers that accept variable IV sizes,
+ * this is the recommended size.
+ */
+ unsigned int MBEDTLS_PRIVATE(iv_size) : 3;
+
+ /** The cipher key length, in bits (right shifted by #MBEDTLS_KEY_BITLEN_SHIFT).
+ * This is the default length for variable sized ciphers.
+ * Includes parity bits for ciphers like DES.
+ */
+ unsigned int MBEDTLS_PRIVATE(key_bitlen) : 4;
+
+ /** The cipher mode (as per mbedtls_cipher_mode_t).
+ * For example, MBEDTLS_MODE_CBC.
+ */
+ unsigned int MBEDTLS_PRIVATE(mode) : 4;
+
+ /** Full cipher identifier (as per mbedtls_cipher_type_t).
+ * For example, MBEDTLS_CIPHER_AES_256_CBC.
+ *
+ * This could be 7 bits, but 8 bits retains byte alignment for the
+ * next field, which reduces code size to access that field.
+ */
+ unsigned int MBEDTLS_PRIVATE(type) : 8;
+
+ /** Bitflag comprised of MBEDTLS_CIPHER_VARIABLE_IV_LEN and
+ * MBEDTLS_CIPHER_VARIABLE_KEY_LEN indicating whether the
+ * cipher supports variable IV or variable key sizes, respectively.
+ */
+ unsigned int MBEDTLS_PRIVATE(flags) : 2;
+
+ /** Index to LUT for base cipher information and functions. */
+ unsigned int MBEDTLS_PRIVATE(base_idx) : 5;
+
+} mbedtls_cipher_info_t;
+
+/* For internal use only.
+ * These are used to more compactly represent the fields above. */
+#define MBEDTLS_KEY_BITLEN_SHIFT 6
+#define MBEDTLS_IV_SIZE_SHIFT 2
+/**
+ * Generic cipher context.
+ */
+typedef struct mbedtls_cipher_context_t {
+ /** Information about the associated cipher. */
+ const mbedtls_cipher_info_t *MBEDTLS_PRIVATE(cipher_info);
+
+ /** Key length to use. */
+ int MBEDTLS_PRIVATE(key_bitlen);
+
+ /** Operation that the key of the context has been
+ * initialized for.
+ */
+ mbedtls_operation_t MBEDTLS_PRIVATE(operation);
+
+#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
+ /** Padding functions to use, if relevant for
+ * the specific cipher mode.
+ */
+ void(*MBEDTLS_PRIVATE(add_padding))(unsigned char *output, size_t olen, size_t data_len);
+ int(*MBEDTLS_PRIVATE(get_padding))(unsigned char *input, size_t ilen, size_t *data_len);
+#endif
+
+ /** Buffer for input that has not been processed yet. */
+ unsigned char MBEDTLS_PRIVATE(unprocessed_data)[MBEDTLS_MAX_BLOCK_LENGTH];
+
+ /** Number of Bytes that have not been processed yet. */
+ size_t MBEDTLS_PRIVATE(unprocessed_len);
+
+ /** Current IV or NONCE_COUNTER for CTR-mode, data unit (or sector) number
+ * for XTS-mode. */
+ unsigned char MBEDTLS_PRIVATE(iv)[MBEDTLS_MAX_IV_LENGTH];
+
+ /** IV size in Bytes, for ciphers with variable-length IVs. */
+ size_t MBEDTLS_PRIVATE(iv_size);
+
+ /** The cipher-specific context. */
+ void *MBEDTLS_PRIVATE(cipher_ctx);
+
+#if defined(MBEDTLS_CMAC_C)
+ /** CMAC-specific context. */
+ mbedtls_cmac_context_t *MBEDTLS_PRIVATE(cmac_ctx);
+#endif
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO) && !defined(MBEDTLS_DEPRECATED_REMOVED)
+ /** Indicates whether the cipher operations should be performed
+ * by Mbed TLS' own crypto library or an external implementation
+ * of the PSA Crypto API.
+ * This is unset if the cipher context was established through
+ * mbedtls_cipher_setup(), and set if it was established through
+ * mbedtls_cipher_setup_psa().
+ */
+ unsigned char MBEDTLS_PRIVATE(psa_enabled);
+#endif /* MBEDTLS_USE_PSA_CRYPTO && !MBEDTLS_DEPRECATED_REMOVED */
+
+} mbedtls_cipher_context_t;
+
+/**
+ * \brief This function retrieves the list of ciphers supported
+ * by the generic cipher module.
+ *
+ * For any cipher identifier in the returned list, you can
+ * obtain the corresponding generic cipher information structure
+ * via mbedtls_cipher_info_from_type(), which can then be used
+ * to prepare a cipher context via mbedtls_cipher_setup().
+ *
+ *
+ * \return A statically-allocated array of cipher identifiers
+ * of type cipher_type_t. The last entry is zero.
+ */
+const int *mbedtls_cipher_list(void);
+
+/**
+ * \brief This function retrieves the cipher-information
+ * structure associated with the given cipher name.
+ *
+ * \param cipher_name Name of the cipher to search for. This must not be
+ * \c NULL.
+ *
+ * \return The cipher information structure associated with the
+ * given \p cipher_name.
+ * \return \c NULL if the associated cipher information is not found.
+ */
+const mbedtls_cipher_info_t *mbedtls_cipher_info_from_string(const char *cipher_name);
+
+/**
+ * \brief This function retrieves the cipher-information
+ * structure associated with the given cipher type.
+ *
+ * \param cipher_type Type of the cipher to search for.
+ *
+ * \return The cipher information structure associated with the
+ * given \p cipher_type.
+ * \return \c NULL if the associated cipher information is not found.
+ */
+const mbedtls_cipher_info_t *mbedtls_cipher_info_from_type(const mbedtls_cipher_type_t cipher_type);
+
+/**
+ * \brief This function retrieves the cipher-information
+ * structure associated with the given cipher ID,
+ * key size and mode.
+ *
+ * \param cipher_id The ID of the cipher to search for. For example,
+ * #MBEDTLS_CIPHER_ID_AES.
+ * \param key_bitlen The length of the key in bits.
+ * \param mode The cipher mode. For example, #MBEDTLS_MODE_CBC.
+ *
+ * \return The cipher information structure associated with the
+ * given \p cipher_id.
+ * \return \c NULL if the associated cipher information is not found.
+ */
+const mbedtls_cipher_info_t *mbedtls_cipher_info_from_values(const mbedtls_cipher_id_t cipher_id,
+ int key_bitlen,
+ const mbedtls_cipher_mode_t mode);
+
+/**
+ * \brief Retrieve the identifier for a cipher info structure.
+ *
+ * \param[in] info The cipher info structure to query.
+ * This may be \c NULL.
+ *
+ * \return The full cipher identifier (\c MBEDTLS_CIPHER_xxx).
+ * \return #MBEDTLS_CIPHER_NONE if \p info is \c NULL.
+ */
+static inline mbedtls_cipher_type_t mbedtls_cipher_info_get_type(
+ const mbedtls_cipher_info_t *info)
+{
+ if (info == NULL) {
+ return MBEDTLS_CIPHER_NONE;
+ } else {
+ return (mbedtls_cipher_type_t) info->MBEDTLS_PRIVATE(type);
+ }
+}
+
+/**
+ * \brief Retrieve the operation mode for a cipher info structure.
+ *
+ * \param[in] info The cipher info structure to query.
+ * This may be \c NULL.
+ *
+ * \return The cipher mode (\c MBEDTLS_MODE_xxx).
+ * \return #MBEDTLS_MODE_NONE if \p info is \c NULL.
+ */
+static inline mbedtls_cipher_mode_t mbedtls_cipher_info_get_mode(
+ const mbedtls_cipher_info_t *info)
+{
+ if (info == NULL) {
+ return MBEDTLS_MODE_NONE;
+ } else {
+ return (mbedtls_cipher_mode_t) info->MBEDTLS_PRIVATE(mode);
+ }
+}
+
+/**
+ * \brief Retrieve the key size for a cipher info structure.
+ *
+ * \param[in] info The cipher info structure to query.
+ * This may be \c NULL.
+ *
+ * \return The key length in bits.
+ * For variable-sized ciphers, this is the default length.
+ * For DES, this includes the parity bits.
+ * \return \c 0 if \p info is \c NULL.
+ */
+static inline size_t mbedtls_cipher_info_get_key_bitlen(
+ const mbedtls_cipher_info_t *info)
+{
+ if (info == NULL) {
+ return 0;
+ } else {
+ return info->MBEDTLS_PRIVATE(key_bitlen) << MBEDTLS_KEY_BITLEN_SHIFT;
+ }
+}
+
+/**
+ * \brief Retrieve the human-readable name for a
+ * cipher info structure.
+ *
+ * \param[in] info The cipher info structure to query.
+ * This may be \c NULL.
+ *
+ * \return The cipher name, which is a human readable string,
+ * with static storage duration.
+ * \return \c NULL if \p info is \c NULL.
+ */
+static inline const char *mbedtls_cipher_info_get_name(
+ const mbedtls_cipher_info_t *info)
+{
+ if (info == NULL) {
+ return NULL;
+ } else {
+ return info->MBEDTLS_PRIVATE(name);
+ }
+}
+
+/**
+ * \brief This function returns the size of the IV or nonce
+ * for the cipher info structure, in bytes.
+ *
+ * \param info The cipher info structure. This may be \c NULL.
+ *
+ * \return The recommended IV size.
+ * \return \c 0 for ciphers not using an IV or a nonce.
+ * \return \c 0 if \p info is \c NULL.
+ */
+static inline size_t mbedtls_cipher_info_get_iv_size(
+ const mbedtls_cipher_info_t *info)
+{
+ if (info == NULL) {
+ return 0;
+ }
+
+ return ((size_t) info->MBEDTLS_PRIVATE(iv_size)) << MBEDTLS_IV_SIZE_SHIFT;
+}
+
+/**
+ * \brief This function returns the block size of the given
+ * cipher info structure in bytes.
+ *
+ * \param info The cipher info structure. This may be \c NULL.
+ *
+ * \return The block size of the cipher.
+ * \return \c 1 if the cipher is a stream cipher.
+ * \return \c 0 if \p info is \c NULL.
+ */
+static inline size_t mbedtls_cipher_info_get_block_size(
+ const mbedtls_cipher_info_t *info)
+{
+ if (info == NULL) {
+ return 0;
+ }
+
+ return (size_t) (info->MBEDTLS_PRIVATE(block_size));
+}
+
+/**
+ * \brief This function returns a non-zero value if the key length for
+ * the given cipher is variable.
+ *
+ * \param info The cipher info structure. This may be \c NULL.
+ *
+ * \return Non-zero if the key length is variable, \c 0 otherwise.
+ * \return \c 0 if the given pointer is \c NULL.
+ */
+static inline int mbedtls_cipher_info_has_variable_key_bitlen(
+ const mbedtls_cipher_info_t *info)
+{
+ if (info == NULL) {
+ return 0;
+ }
+
+ return info->MBEDTLS_PRIVATE(flags) & MBEDTLS_CIPHER_VARIABLE_KEY_LEN;
+}
+
+/**
+ * \brief This function returns a non-zero value if the IV size for
+ * the given cipher is variable.
+ *
+ * \param info The cipher info structure. This may be \c NULL.
+ *
+ * \return Non-zero if the IV size is variable, \c 0 otherwise.
+ * \return \c 0 if the given pointer is \c NULL.
+ */
+static inline int mbedtls_cipher_info_has_variable_iv_size(
+ const mbedtls_cipher_info_t *info)
+{
+ if (info == NULL) {
+ return 0;
+ }
+
+ return info->MBEDTLS_PRIVATE(flags) & MBEDTLS_CIPHER_VARIABLE_IV_LEN;
+}
+
+/**
+ * \brief This function initializes a \p ctx as NONE.
+ *
+ * \param ctx The context to be initialized. This must not be \c NULL.
+ */
+void mbedtls_cipher_init(mbedtls_cipher_context_t *ctx);
+
+/**
+ * \brief This function frees and clears the cipher-specific
+ * context of \p ctx. Freeing \p ctx itself remains the
+ * responsibility of the caller.
+ *
+ * \param ctx The context to be freed. If this is \c NULL, the
+ * function has no effect, otherwise this must point to an
+ * initialized context.
+ */
+void mbedtls_cipher_free(mbedtls_cipher_context_t *ctx);
+
+
+/**
+ * \brief This function prepares a cipher context for
+ * use with the given cipher primitive.
+ *
+ * \note After calling this function, you should call
+ * mbedtls_cipher_setkey() and, if the mode uses padding,
+ * mbedtls_cipher_set_padding_mode(), then for each
+ * message to encrypt or decrypt with this key, either:
+ * - mbedtls_cipher_crypt() for one-shot processing with
+ * non-AEAD modes;
+ * - mbedtls_cipher_auth_encrypt_ext() or
+ * mbedtls_cipher_auth_decrypt_ext() for one-shot
+ * processing with AEAD modes or NIST_KW;
+ * - for multi-part processing, see the documentation of
+ * mbedtls_cipher_reset().
+ *
+ * \param ctx The context to prepare. This must be initialized by
+ * a call to mbedtls_cipher_init() first.
+ * \param cipher_info The cipher to use.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
+ * parameter-verification failure.
+ * \return #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the
+ * cipher-specific context fails.
+ */
+int mbedtls_cipher_setup(mbedtls_cipher_context_t *ctx,
+ const mbedtls_cipher_info_t *cipher_info);
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+/**
+ * \brief This function initializes a cipher context for
+ * PSA-based use with the given cipher primitive.
+ *
+ * \deprecated This function is deprecated and will be removed in a
+ * future version of the library.
+ * Please use psa_aead_xxx() / psa_cipher_xxx() directly
+ * instead.
+ *
+ * \note See #MBEDTLS_USE_PSA_CRYPTO for information on PSA.
+ *
+ * \param ctx The context to initialize. May not be \c NULL.
+ * \param cipher_info The cipher to use.
+ * \param taglen For AEAD ciphers, the length in bytes of the
+ * authentication tag to use. Subsequent uses of
+ * mbedtls_cipher_auth_encrypt_ext() or
+ * mbedtls_cipher_auth_decrypt_ext() must provide
+ * the same tag length.
+ * For non-AEAD ciphers, the value must be \c 0.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
+ * parameter-verification failure.
+ * \return #MBEDTLS_ERR_CIPHER_ALLOC_FAILED if allocation of the
+ * cipher-specific context fails.
+ */
+int MBEDTLS_DEPRECATED mbedtls_cipher_setup_psa(mbedtls_cipher_context_t *ctx,
+ const mbedtls_cipher_info_t *cipher_info,
+ size_t taglen);
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
+/**
+ * \brief This function returns the block size of the given cipher
+ * in bytes.
+ *
+ * \param ctx The context of the cipher.
+ *
+ * \return The block size of the underlying cipher.
+ * \return \c 1 if the cipher is a stream cipher.
+ * \return \c 0 if \p ctx has not been initialized.
+ */
+static inline unsigned int mbedtls_cipher_get_block_size(
+ const mbedtls_cipher_context_t *ctx)
+{
+ MBEDTLS_INTERNAL_VALIDATE_RET(ctx != NULL, 0);
+ if (ctx->MBEDTLS_PRIVATE(cipher_info) == NULL) {
+ return 0;
+ }
+
+ return (unsigned int) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(block_size);
+}
+
+/**
+ * \brief This function returns the mode of operation for
+ * the cipher. For example, MBEDTLS_MODE_CBC.
+ *
+ * \param ctx The context of the cipher. This must be initialized.
+ *
+ * \return The mode of operation.
+ * \return #MBEDTLS_MODE_NONE if \p ctx has not been initialized.
+ */
+static inline mbedtls_cipher_mode_t mbedtls_cipher_get_cipher_mode(
+ const mbedtls_cipher_context_t *ctx)
+{
+ MBEDTLS_INTERNAL_VALIDATE_RET(ctx != NULL, MBEDTLS_MODE_NONE);
+ if (ctx->MBEDTLS_PRIVATE(cipher_info) == NULL) {
+ return MBEDTLS_MODE_NONE;
+ }
+
+ return (mbedtls_cipher_mode_t) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(mode);
+}
+
+/**
+ * \brief This function returns the size of the IV or nonce
+ * of the cipher, in Bytes.
+ *
+ * \param ctx The context of the cipher. This must be initialized.
+ *
+ * \return The recommended IV size if no IV has been set.
+ * \return \c 0 for ciphers not using an IV or a nonce.
+ * \return The actual size if an IV has been set.
+ */
+static inline int mbedtls_cipher_get_iv_size(
+ const mbedtls_cipher_context_t *ctx)
+{
+ MBEDTLS_INTERNAL_VALIDATE_RET(ctx != NULL, 0);
+ if (ctx->MBEDTLS_PRIVATE(cipher_info) == NULL) {
+ return 0;
+ }
+
+ if (ctx->MBEDTLS_PRIVATE(iv_size) != 0) {
+ return (int) ctx->MBEDTLS_PRIVATE(iv_size);
+ }
+
+ return (int) (((int) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(iv_size)) <<
+ MBEDTLS_IV_SIZE_SHIFT);
+}
+
+/**
+ * \brief This function returns the type of the given cipher.
+ *
+ * \param ctx The context of the cipher. This must be initialized.
+ *
+ * \return The type of the cipher.
+ * \return #MBEDTLS_CIPHER_NONE if \p ctx has not been initialized.
+ */
+static inline mbedtls_cipher_type_t mbedtls_cipher_get_type(
+ const mbedtls_cipher_context_t *ctx)
+{
+ MBEDTLS_INTERNAL_VALIDATE_RET(
+ ctx != NULL, MBEDTLS_CIPHER_NONE);
+ if (ctx->MBEDTLS_PRIVATE(cipher_info) == NULL) {
+ return MBEDTLS_CIPHER_NONE;
+ }
+
+ return (mbedtls_cipher_type_t) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(type);
+}
+
+/**
+ * \brief This function returns the name of the given cipher
+ * as a string.
+ *
+ * \param ctx The context of the cipher. This must be initialized.
+ *
+ * \return The name of the cipher.
+ * \return NULL if \p ctx has not been not initialized.
+ */
+static inline const char *mbedtls_cipher_get_name(
+ const mbedtls_cipher_context_t *ctx)
+{
+ MBEDTLS_INTERNAL_VALIDATE_RET(ctx != NULL, 0);
+ if (ctx->MBEDTLS_PRIVATE(cipher_info) == NULL) {
+ return 0;
+ }
+
+ return ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(name);
+}
+
+/**
+ * \brief This function returns the key length of the cipher.
+ *
+ * \param ctx The context of the cipher. This must be initialized.
+ *
+ * \return The key length of the cipher in bits.
+ * \return #MBEDTLS_KEY_LENGTH_NONE if \p ctx has not been
+ * initialized.
+ */
+static inline int mbedtls_cipher_get_key_bitlen(
+ const mbedtls_cipher_context_t *ctx)
+{
+ MBEDTLS_INTERNAL_VALIDATE_RET(
+ ctx != NULL, MBEDTLS_KEY_LENGTH_NONE);
+ if (ctx->MBEDTLS_PRIVATE(cipher_info) == NULL) {
+ return MBEDTLS_KEY_LENGTH_NONE;
+ }
+
+ return (int) ctx->MBEDTLS_PRIVATE(cipher_info)->MBEDTLS_PRIVATE(key_bitlen) <<
+ MBEDTLS_KEY_BITLEN_SHIFT;
+}
+
+/**
+ * \brief This function returns the operation of the given cipher.
+ *
+ * \param ctx The context of the cipher. This must be initialized.
+ *
+ * \return The type of operation: #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT.
+ * \return #MBEDTLS_OPERATION_NONE if \p ctx has not been initialized.
+ */
+static inline mbedtls_operation_t mbedtls_cipher_get_operation(
+ const mbedtls_cipher_context_t *ctx)
+{
+ MBEDTLS_INTERNAL_VALIDATE_RET(
+ ctx != NULL, MBEDTLS_OPERATION_NONE);
+ if (ctx->MBEDTLS_PRIVATE(cipher_info) == NULL) {
+ return MBEDTLS_OPERATION_NONE;
+ }
+
+ return ctx->MBEDTLS_PRIVATE(operation);
+}
+
+/**
+ * \brief This function sets the key to use with the given context.
+ *
+ * \param ctx The generic cipher context. This must be initialized and
+ * bound to a cipher information structure.
+ * \param key The key to use. This must be a readable buffer of at
+ * least \p key_bitlen Bits.
+ * \param key_bitlen The key length to use, in Bits.
+ * \param operation The operation that the key will be used for:
+ * #MBEDTLS_ENCRYPT or #MBEDTLS_DECRYPT.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
+ * parameter-verification failure.
+ * \return A cipher-specific error code on failure.
+ */
+int mbedtls_cipher_setkey(mbedtls_cipher_context_t *ctx,
+ const unsigned char *key,
+ int key_bitlen,
+ const mbedtls_operation_t operation);
+
+#if defined(MBEDTLS_CIPHER_MODE_WITH_PADDING)
+/**
+ * \brief This function sets the padding mode, for cipher modes
+ * that use padding.
+ *
+ *
+ * \param ctx The generic cipher context. This must be initialized and
+ * bound to a cipher information structure.
+ * \param mode The padding mode.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE
+ * if the selected padding mode is not supported.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA if the cipher mode
+ * does not support padding.
+ */
+int mbedtls_cipher_set_padding_mode(mbedtls_cipher_context_t *ctx,
+ mbedtls_cipher_padding_t mode);
+#endif /* MBEDTLS_CIPHER_MODE_WITH_PADDING */
+
+/**
+ * \brief This function sets the initialization vector (IV)
+ * or nonce.
+ *
+ * \note Some ciphers do not use IVs nor nonce. For these
+ * ciphers, this function has no effect.
+ *
+ * \note For #MBEDTLS_CIPHER_CHACHA20, the nonce length must
+ * be 12, and the initial counter value is 0.
+ *
+ * \note For #MBEDTLS_CIPHER_CHACHA20_POLY1305, the nonce length
+ * must be 12.
+ *
+ * \param ctx The generic cipher context. This must be initialized and
+ * bound to a cipher information structure.
+ * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers. This
+ * must be a readable buffer of at least \p iv_len Bytes.
+ * \param iv_len The IV length for ciphers with variable-size IV.
+ * This parameter is discarded by ciphers with fixed-size IV.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
+ * parameter-verification failure.
+ */
+int mbedtls_cipher_set_iv(mbedtls_cipher_context_t *ctx,
+ const unsigned char *iv,
+ size_t iv_len);
+
+/**
+ * \brief This function resets the cipher state.
+ *
+ * \note With non-AEAD ciphers, the order of calls for each message
+ * is as follows:
+ * 1. mbedtls_cipher_set_iv() if the mode uses an IV/nonce.
+ * 2. mbedtls_cipher_reset()
+ * 3. mbedtls_cipher_update() one or more times
+ * 4. mbedtls_cipher_finish()
+ * .
+ * This sequence can be repeated to encrypt or decrypt multiple
+ * messages with the same key.
+ *
+ * \note With AEAD ciphers, the order of calls for each message
+ * is as follows:
+ * 1. mbedtls_cipher_set_iv() if the mode uses an IV/nonce.
+ * 2. mbedtls_cipher_reset()
+ * 3. mbedtls_cipher_update_ad()
+ * 4. mbedtls_cipher_update() one or more times
+ * 5. mbedtls_cipher_finish()
+ * 6. mbedtls_cipher_check_tag() (for decryption) or
+ * mbedtls_cipher_write_tag() (for encryption).
+ * .
+ * This sequence can be repeated to encrypt or decrypt multiple
+ * messages with the same key.
+ *
+ * \param ctx The generic cipher context. This must be bound to a key.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
+ * parameter-verification failure.
+ */
+int mbedtls_cipher_reset(mbedtls_cipher_context_t *ctx);
+
+#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
+/**
+ * \brief This function adds additional data for AEAD ciphers.
+ * Currently supported with GCM and ChaCha20+Poly1305.
+ *
+ * \param ctx The generic cipher context. This must be initialized.
+ * \param ad The additional data to use. This must be a readable
+ * buffer of at least \p ad_len Bytes.
+ * \param ad_len The length of \p ad in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A specific error code on failure.
+ */
+int mbedtls_cipher_update_ad(mbedtls_cipher_context_t *ctx,
+ const unsigned char *ad, size_t ad_len);
+#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
+
+/**
+ * \brief The generic cipher update function. It encrypts or
+ * decrypts using the given cipher context. Writes as
+ * many block-sized blocks of data as possible to output.
+ * Any data that cannot be written immediately is either
+ * added to the next block, or flushed when
+ * mbedtls_cipher_finish() is called.
+ * Exception: For MBEDTLS_MODE_ECB, expects a single block
+ * in size. For example, 16 Bytes for AES.
+ *
+ * \param ctx The generic cipher context. This must be initialized and
+ * bound to a key.
+ * \param input The buffer holding the input data. This must be a
+ * readable buffer of at least \p ilen Bytes.
+ * \param ilen The length of the input data.
+ * \param output The buffer for the output data. This must be able to
+ * hold at least `ilen + block_size`. This must not be the
+ * same buffer as \p input.
+ * \param olen The length of the output data, to be updated with the
+ * actual number of Bytes written. This must not be
+ * \c NULL.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
+ * parameter-verification failure.
+ * \return #MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE on an
+ * unsupported mode for a cipher.
+ * \return A cipher-specific error code on failure.
+ */
+int mbedtls_cipher_update(mbedtls_cipher_context_t *ctx,
+ const unsigned char *input,
+ size_t ilen, unsigned char *output,
+ size_t *olen);
+
+/**
+ * \brief The generic cipher finalization function. If data still
+ * needs to be flushed from an incomplete block, the data
+ * contained in it is padded to the size of
+ * the last block, and written to the \p output buffer.
+ *
+ * \param ctx The generic cipher context. This must be initialized and
+ * bound to a key.
+ * \param output The buffer to write data to. This needs to be a writable
+ * buffer of at least block_size Bytes.
+ * \param olen The length of the data written to the \p output buffer.
+ * This may not be \c NULL.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
+ * parameter-verification failure.
+ * \return #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption
+ * expecting a full block but not receiving one.
+ * \return #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
+ * while decrypting.
+ * \return A cipher-specific error code on failure.
+ */
+int mbedtls_cipher_finish(mbedtls_cipher_context_t *ctx,
+ unsigned char *output, size_t *olen);
+
+#if defined(MBEDTLS_GCM_C) || defined(MBEDTLS_CHACHAPOLY_C)
+/**
+ * \brief This function writes a tag for AEAD ciphers.
+ * Currently supported with GCM and ChaCha20+Poly1305.
+ * This must be called after mbedtls_cipher_finish().
+ *
+ * \param ctx The generic cipher context. This must be initialized,
+ * bound to a key, and have just completed a cipher
+ * operation through mbedtls_cipher_finish() the tag for
+ * which should be written.
+ * \param tag The buffer to write the tag to. This must be a writable
+ * buffer of at least \p tag_len Bytes.
+ * \param tag_len The length of the tag to write.
+ *
+ * \return \c 0 on success.
+ * \return A specific error code on failure.
+ */
+int mbedtls_cipher_write_tag(mbedtls_cipher_context_t *ctx,
+ unsigned char *tag, size_t tag_len);
+
+/**
+ * \brief This function checks the tag for AEAD ciphers.
+ * Currently supported with GCM and ChaCha20+Poly1305.
+ * This must be called after mbedtls_cipher_finish().
+ *
+ * \param ctx The generic cipher context. This must be initialized.
+ * \param tag The buffer holding the tag. This must be a readable
+ * buffer of at least \p tag_len Bytes.
+ * \param tag_len The length of the tag to check.
+ *
+ * \return \c 0 on success.
+ * \return A specific error code on failure.
+ */
+int mbedtls_cipher_check_tag(mbedtls_cipher_context_t *ctx,
+ const unsigned char *tag, size_t tag_len);
+#endif /* MBEDTLS_GCM_C || MBEDTLS_CHACHAPOLY_C */
+
+/**
+ * \brief The generic all-in-one encryption/decryption function,
+ * for all ciphers except AEAD constructs.
+ *
+ * \param ctx The generic cipher context. This must be initialized.
+ * \param iv The IV to use, or NONCE_COUNTER for CTR-mode ciphers.
+ * This must be a readable buffer of at least \p iv_len
+ * Bytes.
+ * \param iv_len The IV length for ciphers with variable-size IV.
+ * This parameter is discarded by ciphers with fixed-size
+ * IV.
+ * \param input The buffer holding the input data. This must be a
+ * readable buffer of at least \p ilen Bytes.
+ * \param ilen The length of the input data in Bytes.
+ * \param output The buffer for the output data. This must be able to
+ * hold at least `ilen + block_size`. This must not be the
+ * same buffer as \p input.
+ * \param olen The length of the output data, to be updated with the
+ * actual number of Bytes written. This must not be
+ * \c NULL.
+ *
+ * \note Some ciphers do not use IVs nor nonce. For these
+ * ciphers, use \p iv = NULL and \p iv_len = 0.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
+ * parameter-verification failure.
+ * \return #MBEDTLS_ERR_CIPHER_FULL_BLOCK_EXPECTED on decryption
+ * expecting a full block but not receiving one.
+ * \return #MBEDTLS_ERR_CIPHER_INVALID_PADDING on invalid padding
+ * while decrypting.
+ * \return A cipher-specific error code on failure.
+ */
+int mbedtls_cipher_crypt(mbedtls_cipher_context_t *ctx,
+ const unsigned char *iv, size_t iv_len,
+ const unsigned char *input, size_t ilen,
+ unsigned char *output, size_t *olen);
+
+#if defined(MBEDTLS_CIPHER_MODE_AEAD) || defined(MBEDTLS_NIST_KW_C)
+/**
+ * \brief The authenticated encryption (AEAD/NIST_KW) function.
+ *
+ * \note For AEAD modes, the tag will be appended to the
+ * ciphertext, as recommended by RFC 5116.
+ * (NIST_KW doesn't have a separate tag.)
+ *
+ * \param ctx The generic cipher context. This must be initialized and
+ * bound to a key, with an AEAD algorithm or NIST_KW.
+ * \param iv The nonce to use. This must be a readable buffer of
+ * at least \p iv_len Bytes and may be \c NULL if \p
+ * iv_len is \c 0.
+ * \param iv_len The length of the nonce. For AEAD ciphers, this must
+ * satisfy the constraints imposed by the cipher used.
+ * For NIST_KW, this must be \c 0.
+ * \param ad The additional data to authenticate. This must be a
+ * readable buffer of at least \p ad_len Bytes, and may
+ * be \c NULL is \p ad_len is \c 0.
+ * \param ad_len The length of \p ad. For NIST_KW, this must be \c 0.
+ * \param input The buffer holding the input data. This must be a
+ * readable buffer of at least \p ilen Bytes, and may be
+ * \c NULL if \p ilen is \c 0.
+ * \param ilen The length of the input data.
+ * \param output The buffer for the output data. This must be a
+ * writable buffer of at least \p output_len Bytes, and
+ * must not be \c NULL.
+ * \param output_len The length of the \p output buffer in Bytes. For AEAD
+ * ciphers, this must be at least \p ilen + \p tag_len.
+ * For NIST_KW, this must be at least \p ilen + 8
+ * (rounded up to a multiple of 8 if KWP is used);
+ * \p ilen + 15 is always a safe value.
+ * \param olen This will be filled with the actual number of Bytes
+ * written to the \p output buffer. This must point to a
+ * writable object of type \c size_t.
+ * \param tag_len The desired length of the authentication tag. For AEAD
+ * ciphers, this must match the constraints imposed by
+ * the cipher used, and in particular must not be \c 0.
+ * For NIST_KW, this must be \c 0.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
+ * parameter-verification failure.
+ * \return A cipher-specific error code on failure.
+ */
+int mbedtls_cipher_auth_encrypt_ext(mbedtls_cipher_context_t *ctx,
+ const unsigned char *iv, size_t iv_len,
+ const unsigned char *ad, size_t ad_len,
+ const unsigned char *input, size_t ilen,
+ unsigned char *output, size_t output_len,
+ size_t *olen, size_t tag_len);
+
+/**
+ * \brief The authenticated encryption (AEAD/NIST_KW) function.
+ *
+ * \note If the data is not authentic, then the output buffer
+ * is zeroed out to prevent the unauthentic plaintext being
+ * used, making this interface safer.
+ *
+ * \note For AEAD modes, the tag must be appended to the
+ * ciphertext, as recommended by RFC 5116.
+ * (NIST_KW doesn't have a separate tag.)
+ *
+ * \param ctx The generic cipher context. This must be initialized and
+ * bound to a key, with an AEAD algorithm or NIST_KW.
+ * \param iv The nonce to use. This must be a readable buffer of
+ * at least \p iv_len Bytes and may be \c NULL if \p
+ * iv_len is \c 0.
+ * \param iv_len The length of the nonce. For AEAD ciphers, this must
+ * satisfy the constraints imposed by the cipher used.
+ * For NIST_KW, this must be \c 0.
+ * \param ad The additional data to authenticate. This must be a
+ * readable buffer of at least \p ad_len Bytes, and may
+ * be \c NULL is \p ad_len is \c 0.
+ * \param ad_len The length of \p ad. For NIST_KW, this must be \c 0.
+ * \param input The buffer holding the input data. This must be a
+ * readable buffer of at least \p ilen Bytes, and may be
+ * \c NULL if \p ilen is \c 0.
+ * \param ilen The length of the input data. For AEAD ciphers this
+ * must be at least \p tag_len. For NIST_KW this must be
+ * at least \c 8.
+ * \param output The buffer for the output data. This must be a
+ * writable buffer of at least \p output_len Bytes, and
+ * may be \c NULL if \p output_len is \c 0.
+ * \param output_len The length of the \p output buffer in Bytes. For AEAD
+ * ciphers, this must be at least \p ilen - \p tag_len.
+ * For NIST_KW, this must be at least \p ilen - 8.
+ * \param olen This will be filled with the actual number of Bytes
+ * written to the \p output buffer. This must point to a
+ * writable object of type \c size_t.
+ * \param tag_len The actual length of the authentication tag. For AEAD
+ * ciphers, this must match the constraints imposed by
+ * the cipher used, and in particular must not be \c 0.
+ * For NIST_KW, this must be \c 0.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA on
+ * parameter-verification failure.
+ * \return #MBEDTLS_ERR_CIPHER_AUTH_FAILED if data is not authentic.
+ * \return A cipher-specific error code on failure.
+ */
+int mbedtls_cipher_auth_decrypt_ext(mbedtls_cipher_context_t *ctx,
+ const unsigned char *iv, size_t iv_len,
+ const unsigned char *ad, size_t ad_len,
+ const unsigned char *input, size_t ilen,
+ unsigned char *output, size_t output_len,
+ size_t *olen, size_t tag_len);
+#endif /* MBEDTLS_CIPHER_MODE_AEAD || MBEDTLS_NIST_KW_C */
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_CIPHER_H */
diff --git a/include/mbedtls/cmac.h b/include/mbedtls/cmac.h
new file mode 100644
index 0000000..97b86fc
--- /dev/null
+++ b/include/mbedtls/cmac.h
@@ -0,0 +1,246 @@
+/**
+ * \file cmac.h
+ *
+ * \brief This file contains CMAC definitions and functions.
+ *
+ * The Cipher-based Message Authentication Code (CMAC) Mode for
+ * Authentication is defined in <em>RFC-4493: The AES-CMAC Algorithm</em>.
+ * It is supported with AES and DES.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CMAC_H
+#define MBEDTLS_CMAC_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/cipher.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define MBEDTLS_AES_BLOCK_SIZE 16
+#define MBEDTLS_DES3_BLOCK_SIZE 8
+
+/* We don't support Camellia or ARIA in this module */
+#if defined(MBEDTLS_AES_C)
+#define MBEDTLS_CMAC_MAX_BLOCK_SIZE 16 /**< The longest block used by CMAC is that of AES. */
+#else
+#define MBEDTLS_CMAC_MAX_BLOCK_SIZE 8 /**< The longest block used by CMAC is that of 3DES. */
+#endif
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+/** The longest block supported by the cipher module.
+ *
+ * \deprecated
+ * For the maximum block size of a cipher supported by the CMAC module,
+ * use #MBEDTLS_CMAC_MAX_BLOCK_SIZE.
+ * For the maximum block size of a cipher supported by the cipher module,
+ * use #MBEDTLS_MAX_BLOCK_LENGTH.
+ */
+/* Before Mbed TLS 3.5, this was the maximum block size supported by the CMAC
+ * module, so it didn't take Camellia or ARIA into account. Since the name
+ * of the macro doesn't even convey "CMAC", this was misleading. Now the size
+ * is sufficient for any cipher, but the name is defined in cmac.h for
+ * backward compatibility. */
+#define MBEDTLS_CIPHER_BLKSIZE_MAX MBEDTLS_MAX_BLOCK_LENGTH
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+#if !defined(MBEDTLS_CMAC_ALT)
+
+/**
+ * The CMAC context structure.
+ */
+struct mbedtls_cmac_context_t {
+ /** The internal state of the CMAC algorithm. */
+ unsigned char MBEDTLS_PRIVATE(state)[MBEDTLS_CMAC_MAX_BLOCK_SIZE];
+
+ /** Unprocessed data - either data that was not block aligned and is still
+ * pending processing, or the final block. */
+ unsigned char MBEDTLS_PRIVATE(unprocessed_block)[MBEDTLS_CMAC_MAX_BLOCK_SIZE];
+
+ /** The length of data pending processing. */
+ size_t MBEDTLS_PRIVATE(unprocessed_len);
+};
+
+#else /* !MBEDTLS_CMAC_ALT */
+#include "cmac_alt.h"
+#endif /* !MBEDTLS_CMAC_ALT */
+
+/**
+ * \brief This function starts a new CMAC computation
+ * by setting the CMAC key, and preparing to authenticate
+ * the input data.
+ * It must be called with an initialized cipher context.
+ *
+ * Once this function has completed, data can be supplied
+ * to the CMAC computation by calling
+ * mbedtls_cipher_cmac_update().
+ *
+ * To start a CMAC computation using the same key as a previous
+ * CMAC computation, use mbedtls_cipher_cmac_finish().
+ *
+ * \note When the CMAC implementation is supplied by an alternate
+ * implementation (through #MBEDTLS_CMAC_ALT), some ciphers
+ * may not be supported by that implementation, and thus
+ * return an error. Alternate implementations must support
+ * AES-128 and AES-256, and may support AES-192 and 3DES.
+ *
+ * \param ctx The cipher context used for the CMAC operation, initialized
+ * as one of the following types: MBEDTLS_CIPHER_AES_128_ECB,
+ * MBEDTLS_CIPHER_AES_192_ECB, MBEDTLS_CIPHER_AES_256_ECB,
+ * or MBEDTLS_CIPHER_DES_EDE3_ECB.
+ * \param key The CMAC key.
+ * \param keybits The length of the CMAC key in bits.
+ * Must be supported by the cipher.
+ *
+ * \return \c 0 on success.
+ * \return A cipher-specific error code on failure.
+ */
+int mbedtls_cipher_cmac_starts(mbedtls_cipher_context_t *ctx,
+ const unsigned char *key, size_t keybits);
+
+/**
+ * \brief This function feeds an input buffer into an ongoing CMAC
+ * computation.
+ *
+ * The CMAC computation must have previously been started
+ * by calling mbedtls_cipher_cmac_starts() or
+ * mbedtls_cipher_cmac_reset().
+ *
+ * Call this function as many times as needed to input the
+ * data to be authenticated.
+ * Once all of the required data has been input,
+ * call mbedtls_cipher_cmac_finish() to obtain the result
+ * of the CMAC operation.
+ *
+ * \param ctx The cipher context used for the CMAC operation.
+ * \param input The buffer holding the input data.
+ * \param ilen The length of the input data.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ * if parameter verification fails.
+ */
+int mbedtls_cipher_cmac_update(mbedtls_cipher_context_t *ctx,
+ const unsigned char *input, size_t ilen);
+
+/**
+ * \brief This function finishes an ongoing CMAC operation, and
+ * writes the result to the output buffer.
+ *
+ * It should be followed either by
+ * mbedtls_cipher_cmac_reset(), which starts another CMAC
+ * operation with the same key, or mbedtls_cipher_free(),
+ * which clears the cipher context.
+ *
+ * \param ctx The cipher context used for the CMAC operation.
+ * \param output The output buffer for the CMAC checksum result.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ * if parameter verification fails.
+ */
+int mbedtls_cipher_cmac_finish(mbedtls_cipher_context_t *ctx,
+ unsigned char *output);
+
+/**
+ * \brief This function starts a new CMAC operation with the same
+ * key as the previous one.
+ *
+ * It should be called after finishing the previous CMAC
+ * operation with mbedtls_cipher_cmac_finish().
+ * After calling this function,
+ * call mbedtls_cipher_cmac_update() to supply the new
+ * CMAC operation with data.
+ *
+ * \param ctx The cipher context used for the CMAC operation.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ * if parameter verification fails.
+ */
+int mbedtls_cipher_cmac_reset(mbedtls_cipher_context_t *ctx);
+
+/**
+ * \brief This function calculates the full generic CMAC
+ * on the input buffer with the provided key.
+ *
+ * The function allocates the context, performs the
+ * calculation, and frees the context.
+ *
+ * The CMAC result is calculated as
+ * output = generic CMAC(cmac key, input buffer).
+ *
+ * \note When the CMAC implementation is supplied by an alternate
+ * implementation (through #MBEDTLS_CMAC_ALT), some ciphers
+ * may not be supported by that implementation, and thus
+ * return an error. Alternate implementations must support
+ * AES-128 and AES-256, and may support AES-192 and 3DES.
+ *
+ * \param cipher_info The cipher information.
+ * \param key The CMAC key.
+ * \param keylen The length of the CMAC key in bits.
+ * \param input The buffer holding the input data.
+ * \param ilen The length of the input data.
+ * \param output The buffer for the generic CMAC result.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA
+ * if parameter verification fails.
+ */
+int mbedtls_cipher_cmac(const mbedtls_cipher_info_t *cipher_info,
+ const unsigned char *key, size_t keylen,
+ const unsigned char *input, size_t ilen,
+ unsigned char *output);
+
+#if defined(MBEDTLS_AES_C)
+/**
+ * \brief This function implements the AES-CMAC-PRF-128 pseudorandom
+ * function, as defined in
+ * <em>RFC-4615: The Advanced Encryption Standard-Cipher-based
+ * Message Authentication Code-Pseudo-Random Function-128
+ * (AES-CMAC-PRF-128) Algorithm for the Internet Key
+ * Exchange Protocol (IKE).</em>
+ *
+ * \param key The key to use.
+ * \param key_len The key length in Bytes.
+ * \param input The buffer holding the input data.
+ * \param in_len The length of the input data in Bytes.
+ * \param output The buffer holding the generated 16 Bytes of
+ * pseudorandom output.
+ *
+ * \return \c 0 on success.
+ */
+int mbedtls_aes_cmac_prf_128(const unsigned char *key, size_t key_len,
+ const unsigned char *input, size_t in_len,
+ unsigned char output[16]);
+#endif /* MBEDTLS_AES_C */
+
+#if defined(MBEDTLS_SELF_TEST) && (defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C))
+/**
+ * \brief The CMAC checkup routine.
+ *
+ * \note In case the CMAC routines are provided by an alternative
+ * implementation (i.e. #MBEDTLS_CMAC_ALT is defined), the
+ * checkup routine will succeed even if the implementation does
+ * not support the less widely used AES-192 or 3DES primitives.
+ * The self-test requires at least AES-128 and AES-256 to be
+ * supported by the underlying implementation.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_cmac_self_test(int verbose);
+#endif /* MBEDTLS_SELF_TEST && ( MBEDTLS_AES_C || MBEDTLS_DES_C ) */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_CMAC_H */
diff --git a/include/mbedtls/compat-2.x.h b/include/mbedtls/compat-2.x.h
new file mode 100644
index 0000000..096341b
--- /dev/null
+++ b/include/mbedtls/compat-2.x.h
@@ -0,0 +1,46 @@
+/**
+ * \file compat-2.x.h
+ *
+ * \brief Compatibility definitions
+ *
+ * \deprecated Use the new names directly instead
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#warning "Including compat-2.x.h is deprecated"
+#endif
+
+#ifndef MBEDTLS_COMPAT2X_H
+#define MBEDTLS_COMPAT2X_H
+
+/*
+ * Macros for renamed functions
+ */
+#define mbedtls_ctr_drbg_update_ret mbedtls_ctr_drbg_update
+#define mbedtls_hmac_drbg_update_ret mbedtls_hmac_drbg_update
+#define mbedtls_md5_starts_ret mbedtls_md5_starts
+#define mbedtls_md5_update_ret mbedtls_md5_update
+#define mbedtls_md5_finish_ret mbedtls_md5_finish
+#define mbedtls_md5_ret mbedtls_md5
+#define mbedtls_ripemd160_starts_ret mbedtls_ripemd160_starts
+#define mbedtls_ripemd160_update_ret mbedtls_ripemd160_update
+#define mbedtls_ripemd160_finish_ret mbedtls_ripemd160_finish
+#define mbedtls_ripemd160_ret mbedtls_ripemd160
+#define mbedtls_sha1_starts_ret mbedtls_sha1_starts
+#define mbedtls_sha1_update_ret mbedtls_sha1_update
+#define mbedtls_sha1_finish_ret mbedtls_sha1_finish
+#define mbedtls_sha1_ret mbedtls_sha1
+#define mbedtls_sha256_starts_ret mbedtls_sha256_starts
+#define mbedtls_sha256_update_ret mbedtls_sha256_update
+#define mbedtls_sha256_finish_ret mbedtls_sha256_finish
+#define mbedtls_sha256_ret mbedtls_sha256
+#define mbedtls_sha512_starts_ret mbedtls_sha512_starts
+#define mbedtls_sha512_update_ret mbedtls_sha512_update
+#define mbedtls_sha512_finish_ret mbedtls_sha512_finish
+#define mbedtls_sha512_ret mbedtls_sha512
+
+#endif /* MBEDTLS_COMPAT2X_H */
diff --git a/include/mbedtls/config_adjust_legacy_crypto.h b/include/mbedtls/config_adjust_legacy_crypto.h
new file mode 100644
index 0000000..f769765
--- /dev/null
+++ b/include/mbedtls/config_adjust_legacy_crypto.h
@@ -0,0 +1,183 @@
+/**
+ * \file mbedtls/config_adjust_legacy_crypto.h
+ * \brief Adjust legacy configuration configuration
+ *
+ * Automatically enable certain dependencies. Generally, MBEDLTS_xxx
+ * configurations need to be explicitly enabled by the user: enabling
+ * MBEDTLS_xxx_A but not MBEDTLS_xxx_B when A requires B results in a
+ * compilation error. However, we do automatically enable certain options
+ * in some circumstances. One case is if MBEDTLS_xxx_B is an internal option
+ * used to identify parts of a module that are used by other module, and we
+ * don't want to make the symbol MBEDTLS_xxx_B part of the public API.
+ * Another case is if A didn't depend on B in earlier versions, and we
+ * want to use B in A but we need to preserve backward compatibility with
+ * configurations that explicitly activate MBEDTLS_xxx_A but not
+ * MBEDTLS_xxx_B.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CONFIG_ADJUST_LEGACY_CRYPTO_H
+#define MBEDTLS_CONFIG_ADJUST_LEGACY_CRYPTO_H
+
+/* Auto-enable MBEDTLS_MD_LIGHT based on MBEDTLS_MD_C.
+ * This allows checking for MD_LIGHT rather than MD_LIGHT || MD_C.
+ */
+#if defined(MBEDTLS_MD_C)
+#define MBEDTLS_MD_LIGHT
+#endif
+
+/* Auto-enable MBEDTLS_MD_LIGHT if needed by a module that didn't require it
+ * in a previous release, to ensure backwards compatibility.
+ */
+#if defined(MBEDTLS_ECJPAKE_C) || \
+ defined(MBEDTLS_PEM_PARSE_C) || \
+ defined(MBEDTLS_ENTROPY_C) || \
+ defined(MBEDTLS_PK_C) || \
+ defined(MBEDTLS_PKCS12_C) || \
+ defined(MBEDTLS_RSA_C) || \
+ defined(MBEDTLS_SSL_TLS_C) || \
+ defined(MBEDTLS_X509_USE_C) || \
+ defined(MBEDTLS_X509_CREATE_C)
+#define MBEDTLS_MD_LIGHT
+#endif
+
+/* MBEDTLS_ECP_LIGHT is auto-enabled by the following symbols:
+ * - MBEDTLS_ECP_C because now it consists of MBEDTLS_ECP_LIGHT plus functions
+ * for curve arithmetic. As a consequence if MBEDTLS_ECP_C is required for
+ * some reason, then MBEDTLS_ECP_LIGHT should be enabled as well.
+ * - MBEDTLS_PK_PARSE_EC_EXTENDED and MBEDTLS_PK_PARSE_EC_COMPRESSED because
+ * these features are not supported in PSA so the only way to have them is
+ * to enable the built-in solution.
+ * Both of them are temporary dependencies:
+ * - PK_PARSE_EC_EXTENDED will be removed after #7779 and #7789
+ * - support for compressed points should also be added to PSA, but in this
+ * case there is no associated issue to track it yet.
+ * - PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE because Weierstrass key derivation
+ * still depends on ECP_LIGHT.
+ * - PK_C + USE_PSA + PSA_WANT_ALG_ECDSA is a temporary dependency which will
+ * be fixed by #7453.
+ */
+#if defined(MBEDTLS_ECP_C) || \
+ defined(MBEDTLS_PK_PARSE_EC_EXTENDED) || \
+ defined(MBEDTLS_PK_PARSE_EC_COMPRESSED) || \
+ defined(MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
+#define MBEDTLS_ECP_LIGHT
+#endif
+
+/* MBEDTLS_PK_PARSE_EC_COMPRESSED is introduced in MbedTLS version 3.5, while
+ * in previous version compressed points were automatically supported as long
+ * as PK_PARSE_C and ECP_C were enabled. As a consequence, for backward
+ * compatibility, we auto-enable PK_PARSE_EC_COMPRESSED when these conditions
+ * are met. */
+#if defined(MBEDTLS_PK_PARSE_C) && defined(MBEDTLS_ECP_C)
+#define MBEDTLS_PK_PARSE_EC_COMPRESSED
+#endif
+
+/* Helper symbol to state that there is support for ECDH, either through
+ * library implementation (ECDH_C) or through PSA. */
+#if (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_ALG_ECDH)) || \
+ (!defined(MBEDTLS_USE_PSA_CRYPTO) && defined(MBEDTLS_ECDH_C))
+#define MBEDTLS_CAN_ECDH
+#endif
+
+/* PK module can achieve ECDSA functionalities by means of either software
+ * implementations (ECDSA_C) or through a PSA driver. The following defines
+ * are meant to list these capabilities in a general way which abstracts how
+ * they are implemented under the hood. */
+#if !defined(MBEDTLS_USE_PSA_CRYPTO)
+#if defined(MBEDTLS_ECDSA_C)
+#define MBEDTLS_PK_CAN_ECDSA_SIGN
+#define MBEDTLS_PK_CAN_ECDSA_VERIFY
+#endif /* MBEDTLS_ECDSA_C */
+#else /* MBEDTLS_USE_PSA_CRYPTO */
+#if defined(PSA_WANT_ALG_ECDSA)
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
+#define MBEDTLS_PK_CAN_ECDSA_SIGN
+#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC */
+#if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)
+#define MBEDTLS_PK_CAN_ECDSA_VERIFY
+#endif /* PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY */
+#endif /* PSA_WANT_ALG_ECDSA */
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
+#if defined(MBEDTLS_PK_CAN_ECDSA_VERIFY) || defined(MBEDTLS_PK_CAN_ECDSA_SIGN)
+#define MBEDTLS_PK_CAN_ECDSA_SOME
+#endif
+
+/* If MBEDTLS_PSA_CRYPTO_C is defined, make sure MBEDTLS_PSA_CRYPTO_CLIENT
+ * is defined as well to include all PSA code.
+ */
+#if defined(MBEDTLS_PSA_CRYPTO_C)
+#define MBEDTLS_PSA_CRYPTO_CLIENT
+#endif /* MBEDTLS_PSA_CRYPTO_C */
+
+/* The PK wrappers need pk_write functions to format RSA key objects
+ * when they are dispatching to the PSA API. This happens under USE_PSA_CRYPTO,
+ * and also even without USE_PSA_CRYPTO for mbedtls_pk_sign_ext(). */
+#if defined(MBEDTLS_PSA_CRYPTO_C) && defined(MBEDTLS_RSA_C)
+#define MBEDTLS_PK_C
+#define MBEDTLS_PK_WRITE_C
+#define MBEDTLS_PK_PARSE_C
+#endif
+
+/* Helpers to state that each key is supported either on the builtin or PSA side. */
+#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_521)
+#define MBEDTLS_ECP_HAVE_SECP521R1
+#endif
+#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
+#define MBEDTLS_ECP_HAVE_BP512R1
+#endif
+#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) || defined(PSA_WANT_ECC_MONTGOMERY_448)
+#define MBEDTLS_ECP_HAVE_CURVE448
+#endif
+#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
+#define MBEDTLS_ECP_HAVE_BP384R1
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_384)
+#define MBEDTLS_ECP_HAVE_SECP384R1
+#endif
+#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
+#define MBEDTLS_ECP_HAVE_BP256R1
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) || defined(PSA_WANT_ECC_SECP_K1_256)
+#define MBEDTLS_ECP_HAVE_SECP256K1
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_256)
+#define MBEDTLS_ECP_HAVE_SECP256R1
+#endif
+#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) || defined(PSA_WANT_ECC_MONTGOMERY_255)
+#define MBEDTLS_ECP_HAVE_CURVE25519
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || defined(PSA_WANT_ECC_SECP_K1_224)
+#define MBEDTLS_ECP_HAVE_SECP224K1
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_224)
+#define MBEDTLS_ECP_HAVE_SECP224R1
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || defined(PSA_WANT_ECC_SECP_K1_192)
+#define MBEDTLS_ECP_HAVE_SECP192K1
+#endif
+#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || defined(PSA_WANT_ECC_SECP_R1_192)
+#define MBEDTLS_ECP_HAVE_SECP192R1
+#endif
+
+/* Helper symbol to state that the PK module has support for EC keys. This
+ * can either be provided through the legacy ECP solution or through the
+ * PSA friendly MBEDTLS_PK_USE_PSA_EC_DATA (see pk.h for its description). */
+#if defined(MBEDTLS_ECP_C) || \
+ (defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY))
+#define MBEDTLS_PK_HAVE_ECC_KEYS
+#endif /* MBEDTLS_PK_USE_PSA_EC_DATA || MBEDTLS_ECP_C */
+
+/* Historically pkparse did not check the CBC padding when decrypting
+ * a key. This was a bug, which is now fixed. As a consequence, pkparse
+ * now needs PKCS7 padding support, but existing configurations might not
+ * enable it, so we enable it here. */
+#if defined(MBEDTLS_PK_PARSE_C) && defined(MBEDTLS_PKCS5_C) && defined(MBEDTLS_CIPHER_MODE_CBC)
+#define MBEDTLS_CIPHER_PADDING_PKCS7
+#endif
+
+#endif /* MBEDTLS_CONFIG_ADJUST_LEGACY_CRYPTO_H */
diff --git a/include/mbedtls/config_adjust_legacy_from_psa.h b/include/mbedtls/config_adjust_legacy_from_psa.h
new file mode 100644
index 0000000..ab18d98
--- /dev/null
+++ b/include/mbedtls/config_adjust_legacy_from_psa.h
@@ -0,0 +1,877 @@
+/**
+ * \file mbedtls/config_adjust_legacy_from_psa.h
+ * \brief Adjust PSA configuration: activate legacy implementations
+ *
+ * When MBEDTLS_PSA_CRYPTO_CONFIG is enabled, activate legacy implementations
+ * of cryptographic mechanisms as needed to fulfill the needs of the PSA
+ * configuration. Generally speaking, we activate a legacy mechanism if
+ * it's needed for a requested PSA mechanism and there is no PSA driver
+ * for it.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CONFIG_ADJUST_LEGACY_FROM_PSA_H
+#define MBEDTLS_CONFIG_ADJUST_LEGACY_FROM_PSA_H
+
+/* Define appropriate ACCEL macros for the p256-m driver.
+ * In the future, those should be generated from the drivers JSON description.
+ */
+#if defined(MBEDTLS_PSA_P256M_DRIVER_ENABLED)
+#define MBEDTLS_PSA_ACCEL_ECC_SECP_R1_256
+#define MBEDTLS_PSA_ACCEL_ALG_ECDSA
+#define MBEDTLS_PSA_ACCEL_ALG_ECDH
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE
+#endif
+
+/*
+ * ECC: support for a feature is controlled by a triplet or a pair:
+ * (curve, key_type public/basic, alg) or (curve, key_type_<action>).
+ *
+ * A triplet/pair is accelerated if all of is components are accelerated;
+ * otherwise each component needs to be built in.
+ *
+ * We proceed in two passes:
+ * 1. Check if acceleration is complete for curves, key types, algs.
+ * 2. Then enable built-ins for each thing that's either not accelerated of
+ * doesn't have complete acceleration of the other triplet/pair components.
+ *
+ * Note: this needs psa/crypto_adjust_keypair_types.h to have been included
+ * already, so that we know the full set of key types that are requested.
+ */
+
+/* ECC: curves: is acceleration complete? */
+#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_256)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_384)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_512)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_MONTGOMERY_255) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_MONTGOMERY_255)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_MONTGOMERY_448) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_MONTGOMERY_448)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_SECP_R1_192) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_192)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_SECP_R1_224) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_224)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_SECP_R1_256) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_256)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_SECP_R1_384) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_384)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_SECP_R1_521) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_521)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_SECP_K1_192) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_192)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_SECP_K1_224) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_224)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+#if defined(PSA_WANT_ECC_SECP_K1_256) && \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_256)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES
+#endif
+
+/* ECC: algs: is acceleration complete? */
+#if defined(PSA_WANT_ALG_DETERMINISTIC_ECDSA) && \
+ !defined(MBEDTLS_PSA_ACCEL_ALG_DETERMINISTIC_ECDSA)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS
+#endif
+
+#if defined(PSA_WANT_ALG_ECDH) && \
+ !defined(MBEDTLS_PSA_ACCEL_ALG_ECDH)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS
+#endif
+
+#if defined(PSA_WANT_ALG_ECDSA) && \
+ !defined(MBEDTLS_PSA_ACCEL_ALG_ECDSA)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS
+#endif
+
+#if defined(PSA_WANT_ALG_JPAKE) && \
+ !defined(MBEDTLS_PSA_ACCEL_ALG_JPAKE)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS
+#endif
+
+/* ECC: key types: is acceleration complete? */
+#if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) && \
+ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES_BASIC
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) && \
+ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES_BASIC
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT) && \
+ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT) && \
+ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE) && \
+ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES
+#endif
+
+/* Special case: we don't support cooked key derivation in drivers yet */
+#if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
+#undef MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE
+#endif
+
+/* Note: the condition is always true as DERIVE can't be accelerated yet */
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE) && \
+ !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
+#define MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES
+#endif
+
+/* ECC: curves: enable built-ins as needed.
+ *
+ * We need the curve built-in:
+ * - if it's not accelerated, or
+ * - if there's a key type with missing acceleration, or
+ * - if there's a alg with missing acceleration.
+ */
+#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_256) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_BRAINPOOL_P_R1_256 1
+#define MBEDTLS_ECP_DP_BP256R1_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_BRAINPOOL_P_R1_256 */
+
+#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_384) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_BRAINPOOL_P_R1_384 1
+#define MBEDTLS_ECP_DP_BP384R1_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_BRAINPOOL_P_R1_384 */
+
+#if defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_BRAINPOOL_P_R1_512) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_BRAINPOOL_P_R1_512 1
+#define MBEDTLS_ECP_DP_BP512R1_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_BRAINPOOL_P_R1_512 */
+
+#if defined(PSA_WANT_ECC_MONTGOMERY_255)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_MONTGOMERY_255) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_MONTGOMERY_255 1
+#define MBEDTLS_ECP_DP_CURVE25519_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_MONTGOMERY_255 */
+
+#if defined(PSA_WANT_ECC_MONTGOMERY_448)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_MONTGOMERY_448) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_MONTGOMERY_448 1
+#define MBEDTLS_ECP_DP_CURVE448_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_MONTGOMERY_448 */
+
+#if defined(PSA_WANT_ECC_SECP_R1_192)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_192) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_192 1
+#define MBEDTLS_ECP_DP_SECP192R1_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_SECP_R1_192 */
+
+#if defined(PSA_WANT_ECC_SECP_R1_224)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_224) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_224 1
+#define MBEDTLS_ECP_DP_SECP224R1_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_SECP_R1_224 */
+
+#if defined(PSA_WANT_ECC_SECP_R1_256)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_256) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_256 1
+#define MBEDTLS_ECP_DP_SECP256R1_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_SECP_R1_256 */
+
+#if defined(PSA_WANT_ECC_SECP_R1_384)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_384) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_384 1
+#define MBEDTLS_ECP_DP_SECP384R1_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_SECP_R1_384 */
+
+#if defined(PSA_WANT_ECC_SECP_R1_521)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_521) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_521 1
+#define MBEDTLS_ECP_DP_SECP521R1_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_SECP_R1_521 */
+
+#if defined(PSA_WANT_ECC_SECP_K1_192)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_192) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_K1_192 1
+#define MBEDTLS_ECP_DP_SECP192K1_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_SECP_K1_192 */
+
+#if defined(PSA_WANT_ECC_SECP_K1_224)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_224) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_K1_224 1
+#define MBEDTLS_ECP_DP_SECP224K1_ENABLED
+/* https://github.com/Mbed-TLS/mbedtls/issues/3541 */
+#error "SECP224K1 is buggy via the PSA API in Mbed TLS."
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_SECP_K1_224 */
+
+#if defined(PSA_WANT_ECC_SECP_K1_256)
+#if !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_K1_256) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_K1_256 1
+#define MBEDTLS_ECP_DP_SECP256K1_ENABLED
+#endif /* missing accel */
+#endif /* PSA_WANT_ECC_SECP_K1_256 */
+
+/* ECC: algs: enable built-ins as needed.
+ *
+ * We need the alg built-in:
+ * - if it's not accelerated, or
+ * - if there's a relevant curve (see below) with missing acceleration, or
+ * - if there's a key type among (public, basic) with missing acceleration.
+ *
+ * Relevant curves are:
+ * - all curves for ECDH
+ * - Weierstrass curves for (deterministic) ECDSA
+ * - secp256r1 for EC J-PAKE
+ */
+#if defined(PSA_WANT_ALG_DETERMINISTIC_ECDSA)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_DETERMINISTIC_ECDSA) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES_BASIC)
+#define MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA 1
+#define MBEDTLS_ECDSA_DETERMINISTIC
+#define MBEDTLS_HMAC_DRBG_C
+#define MBEDTLS_MD_C
+#define MBEDTLS_ECDSA_C
+#define MBEDTLS_ECP_C
+#define MBEDTLS_BIGNUM_C
+#define MBEDTLS_ASN1_PARSE_C
+#define MBEDTLS_ASN1_WRITE_C
+#endif /* missing accel */
+#endif /* PSA_WANT_ALG_DETERMINISTIC_ECDSA */
+
+#if defined(PSA_WANT_ALG_ECDH)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_ECDH) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES_BASIC)
+#define MBEDTLS_PSA_BUILTIN_ALG_ECDH 1
+#define MBEDTLS_ECDH_C
+#define MBEDTLS_ECP_C
+#define MBEDTLS_BIGNUM_C
+#endif /* missing accel */
+#endif /* PSA_WANT_ALG_ECDH */
+
+#if defined(PSA_WANT_ALG_ECDSA)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_ECDSA) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_WEIERSTRASS_CURVES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES_BASIC)
+#define MBEDTLS_PSA_BUILTIN_ALG_ECDSA 1
+#define MBEDTLS_ECDSA_C
+#define MBEDTLS_ECP_C
+#define MBEDTLS_BIGNUM_C
+#define MBEDTLS_ASN1_PARSE_C
+#define MBEDTLS_ASN1_WRITE_C
+#endif /* missing accel */
+#endif /* PSA_WANT_ALG_ECDSA */
+
+#if defined(PSA_WANT_ALG_JPAKE)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_JPAKE) || \
+ !defined(MBEDTLS_PSA_ACCEL_ECC_SECP_R1_256) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_KEY_TYPES_BASIC)
+#define MBEDTLS_PSA_BUILTIN_PAKE 1
+#define MBEDTLS_PSA_BUILTIN_ALG_JPAKE 1
+#define MBEDTLS_ECP_DP_SECP256R1_ENABLED
+#define MBEDTLS_BIGNUM_C
+#define MBEDTLS_ECP_C
+#define MBEDTLS_ECJPAKE_C
+#endif /* missing accel */
+#endif /* PSA_WANT_ALG_JPAKE */
+
+/* ECC: key types: enable built-ins as needed.
+ *
+ * We need the key type built-in:
+ * - if it's not accelerated, or
+ * - if there's a curve with missing acceleration, or
+ * - only for public/basic: if there's an alg with missing acceleration.
+ */
+#if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY 1
+#define MBEDTLS_ECP_LIGHT
+#define MBEDTLS_BIGNUM_C
+#endif /* missing accel */
+#endif /* PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY */
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_ALGS)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
+#define MBEDTLS_ECP_LIGHT
+#define MBEDTLS_BIGNUM_C
+#endif /* missing accel */
+#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC */
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
+#define MBEDTLS_ECP_LIGHT
+#define MBEDTLS_BIGNUM_C
+#endif /* missing accel */
+#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT */
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
+#define MBEDTLS_ECP_C
+#define MBEDTLS_BIGNUM_C
+#endif /* missing accel */
+#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT */
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
+#define MBEDTLS_ECP_C
+#define MBEDTLS_BIGNUM_C
+#endif /* missing accel */
+#endif /* PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE */
+
+/* Note: the condition is always true as DERIVE can't be accelerated yet */
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE) || \
+ defined(MBEDTLS_PSA_ECC_ACCEL_INCOMPLETE_CURVES)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
+#define MBEDTLS_ECP_LIGHT
+#define MBEDTLS_BIGNUM_C
+#endif /* missing accel */
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE */
+
+/* End of ECC section */
+
+#if defined(PSA_WANT_ALG_FFDH)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_FFDH)
+#define MBEDTLS_PSA_BUILTIN_ALG_FFDH 1
+#define MBEDTLS_BIGNUM_C
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_FFDH */
+#endif /* PSA_WANT_ALG_FFDH */
+
+#if defined(PSA_WANT_ALG_HKDF)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_HKDF)
+/*
+ * The PSA implementation has its own implementation of HKDF, separate from
+ * hkdf.c. No need to enable MBEDTLS_HKDF_C here.
+ */
+#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
+#define MBEDTLS_PSA_BUILTIN_ALG_HKDF 1
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_HKDF */
+#endif /* PSA_WANT_ALG_HKDF */
+
+#if defined(PSA_WANT_ALG_HKDF_EXTRACT)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_HKDF_EXTRACT)
+/*
+ * The PSA implementation has its own implementation of HKDF, separate from
+ * hkdf.c. No need to enable MBEDTLS_HKDF_C here.
+ */
+#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
+#define MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT 1
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_HKDF_EXTRACT */
+#endif /* PSA_WANT_ALG_HKDF_EXTRACT */
+
+#if defined(PSA_WANT_ALG_HKDF_EXPAND)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_HKDF_EXPAND)
+/*
+ * The PSA implementation has its own implementation of HKDF, separate from
+ * hkdf.c. No need to enable MBEDTLS_HKDF_C here.
+ */
+#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
+#define MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND 1
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_HKDF_EXPAND */
+#endif /* PSA_WANT_ALG_HKDF_EXPAND */
+
+#if defined(PSA_WANT_ALG_HMAC)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_HMAC)
+#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_HMAC */
+#endif /* PSA_WANT_ALG_HMAC */
+
+#if defined(PSA_WANT_ALG_MD5) && !defined(MBEDTLS_PSA_ACCEL_ALG_MD5)
+#define MBEDTLS_PSA_BUILTIN_ALG_MD5 1
+#define MBEDTLS_MD5_C
+#endif
+
+#if defined(PSA_WANT_ALG_RIPEMD160) && !defined(MBEDTLS_PSA_ACCEL_ALG_RIPEMD160)
+#define MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160 1
+#define MBEDTLS_RIPEMD160_C
+#endif
+
+#if defined(PSA_WANT_ALG_RSA_OAEP)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_RSA_OAEP)
+#define MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP 1
+#define MBEDTLS_RSA_C
+#define MBEDTLS_BIGNUM_C
+#define MBEDTLS_OID_C
+#define MBEDTLS_PKCS1_V21
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_RSA_OAEP */
+#endif /* PSA_WANT_ALG_RSA_OAEP */
+
+#if defined(PSA_WANT_ALG_RSA_PKCS1V15_CRYPT)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_CRYPT)
+#define MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT 1
+#define MBEDTLS_RSA_C
+#define MBEDTLS_BIGNUM_C
+#define MBEDTLS_OID_C
+#define MBEDTLS_PKCS1_V15
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_CRYPT */
+#endif /* PSA_WANT_ALG_RSA_PKCS1V15_CRYPT */
+
+#if defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_SIGN)
+#define MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN 1
+#define MBEDTLS_RSA_C
+#define MBEDTLS_BIGNUM_C
+#define MBEDTLS_OID_C
+#define MBEDTLS_PKCS1_V15
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_SIGN */
+#endif /* PSA_WANT_ALG_RSA_PKCS1V15_SIGN */
+
+#if defined(PSA_WANT_ALG_RSA_PSS)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PSS)
+#define MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS 1
+#define MBEDTLS_RSA_C
+#define MBEDTLS_BIGNUM_C
+#define MBEDTLS_OID_C
+#define MBEDTLS_PKCS1_V21
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_RSA_PSS */
+#endif /* PSA_WANT_ALG_RSA_PSS */
+
+#if defined(PSA_WANT_ALG_SHA_1) && !defined(MBEDTLS_PSA_ACCEL_ALG_SHA_1)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA_1 1
+#define MBEDTLS_SHA1_C
+#endif
+
+#if defined(PSA_WANT_ALG_SHA_224) && !defined(MBEDTLS_PSA_ACCEL_ALG_SHA_224)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA_224 1
+#define MBEDTLS_SHA224_C
+#endif
+
+#if defined(PSA_WANT_ALG_SHA_256) && !defined(MBEDTLS_PSA_ACCEL_ALG_SHA_256)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA_256 1
+#define MBEDTLS_SHA256_C
+#endif
+
+#if defined(PSA_WANT_ALG_SHA_384) && !defined(MBEDTLS_PSA_ACCEL_ALG_SHA_384)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA_384 1
+#define MBEDTLS_SHA384_C
+#endif
+
+#if defined(PSA_WANT_ALG_SHA_512) && !defined(MBEDTLS_PSA_ACCEL_ALG_SHA_512)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA_512 1
+#define MBEDTLS_SHA512_C
+#endif
+
+#if defined(PSA_WANT_ALG_SHA3_224) && !defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_224)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA3_224 1
+#define MBEDTLS_SHA3_C
+#endif
+
+#if defined(PSA_WANT_ALG_SHA3_256) && !defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_256)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA3_256 1
+#define MBEDTLS_SHA3_C
+#endif
+
+#if defined(PSA_WANT_ALG_SHA3_384) && !defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_384)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA3_384 1
+#define MBEDTLS_SHA3_C
+#endif
+
+#if defined(PSA_WANT_ALG_SHA3_512) && !defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_512)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA3_512 1
+#define MBEDTLS_SHA3_C
+#endif
+
+#if defined(PSA_WANT_ALG_PBKDF2_HMAC)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_PBKDF2_HMAC)
+#define MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC 1
+#define PSA_HAVE_SOFT_PBKDF2_HMAC 1
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_HMAC)
+#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_HMAC */
+#endif /* !MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_HMAC */
+#endif /* PSA_WANT_ALG_PBKDF2_HMAC */
+
+#if defined(PSA_WANT_ALG_TLS12_PRF)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_TLS12_PRF)
+#define MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF 1
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_TLS12_PRF */
+#endif /* PSA_WANT_ALG_TLS12_PRF */
+
+#if defined(PSA_WANT_ALG_TLS12_PSK_TO_MS)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_TLS12_PSK_TO_MS)
+#define MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS 1
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_TLS12_PSK_TO_MS */
+#endif /* PSA_WANT_ALG_TLS12_PSK_TO_MS */
+
+#if defined(PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_TLS12_ECJPAKE_TO_PMS)
+#define MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS 1
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_TLS12_ECJPAKE_TO_PMS */
+#endif /* PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS */
+
+#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_IMPORT)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_IMPORT */
+#endif /* PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT */
+
+#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_EXPORT)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_EXPORT */
+#endif /* PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT */
+
+#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1
+#define MBEDTLS_GENPRIME
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_GENERATE */
+#endif /* PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE */
+
+#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_BASIC)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_BASIC */
+#endif /* PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC */
+
+#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_IMPORT)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_IMPORT 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_IMPORT */
+#endif /* PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT */
+
+#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_EXPORT)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_EXPORT 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_EXPORT */
+#endif /* PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT */
+
+#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_GENERATE)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_GENERATE */
+#endif /* PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE */
+
+#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_BASIC)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_BASIC 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_KEY_PAIR_BASIC */
+#endif /* PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC */
+
+#if defined(PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_PUBLIC_KEY)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY 1
+#define MBEDTLS_BIGNUM_C
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DH_PUBLIC_KEY */
+#endif /* PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY */
+
+#if defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_PUBLIC_KEY)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY 1
+#define MBEDTLS_RSA_C
+#define MBEDTLS_BIGNUM_C
+#define MBEDTLS_OID_C
+#define MBEDTLS_PK_PARSE_C
+#define MBEDTLS_PK_WRITE_C
+#define MBEDTLS_PK_C
+#define MBEDTLS_ASN1_PARSE_C
+#define MBEDTLS_ASN1_WRITE_C
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_PUBLIC_KEY */
+#endif /* PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY */
+
+/* If any of the block modes are requested that don't have an
+ * associated HW assist, define PSA_HAVE_SOFT_BLOCK_MODE for checking
+ * in the block cipher key types. */
+#if (defined(PSA_WANT_ALG_CTR) && !defined(MBEDTLS_PSA_ACCEL_ALG_CTR)) || \
+ (defined(PSA_WANT_ALG_CFB) && !defined(MBEDTLS_PSA_ACCEL_ALG_CFB)) || \
+ (defined(PSA_WANT_ALG_OFB) && !defined(MBEDTLS_PSA_ACCEL_ALG_OFB)) || \
+ defined(PSA_WANT_ALG_ECB_NO_PADDING) || \
+ (defined(PSA_WANT_ALG_CBC_NO_PADDING) && \
+ !defined(MBEDTLS_PSA_ACCEL_ALG_CBC_NO_PADDING)) || \
+ (defined(PSA_WANT_ALG_CBC_PKCS7) && \
+ !defined(MBEDTLS_PSA_ACCEL_ALG_CBC_PKCS7)) || \
+ (defined(PSA_WANT_ALG_CMAC) && !defined(MBEDTLS_PSA_ACCEL_ALG_CMAC))
+#define PSA_HAVE_SOFT_BLOCK_MODE 1
+#endif
+
+#if (defined(PSA_WANT_ALG_GCM) && !defined(MBEDTLS_PSA_ACCEL_ALG_GCM)) || \
+ (defined(PSA_WANT_ALG_CCM) && !defined(MBEDTLS_PSA_ACCEL_ALG_CCM))
+#define PSA_HAVE_SOFT_BLOCK_AEAD 1
+#endif
+
+#if defined(PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_PBKDF2_AES_CMAC_PRF_128)
+#define MBEDTLS_PSA_BUILTIN_ALG_PBKDF2_AES_CMAC_PRF_128 1
+#define PSA_HAVE_SOFT_PBKDF2_CMAC 1
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_PBKDF2_AES_CMAC_PRF_128 */
+#endif /* PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128 */
+
+#if defined(PSA_WANT_KEY_TYPE_AES)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_AES)
+#define PSA_HAVE_SOFT_KEY_TYPE_AES 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_AES */
+#if defined(PSA_HAVE_SOFT_KEY_TYPE_AES) || \
+ defined(PSA_HAVE_SOFT_BLOCK_MODE) || \
+ defined(PSA_HAVE_SOFT_BLOCK_AEAD) || \
+ defined(PSA_HAVE_SOFT_PBKDF2_CMAC)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_AES 1
+#define MBEDTLS_AES_C
+#endif /* PSA_HAVE_SOFT_KEY_TYPE_AES || PSA_HAVE_SOFT_BLOCK_MODE */
+#endif /* PSA_WANT_KEY_TYPE_AES */
+
+#if defined(PSA_WANT_KEY_TYPE_ARIA)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ARIA)
+#define PSA_HAVE_SOFT_KEY_TYPE_ARIA 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_ARIA */
+#if defined(PSA_HAVE_SOFT_KEY_TYPE_ARIA) || \
+ defined(PSA_HAVE_SOFT_BLOCK_MODE) || \
+ defined(PSA_HAVE_SOFT_BLOCK_AEAD)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ARIA 1
+#define MBEDTLS_ARIA_C
+#endif /* PSA_HAVE_SOFT_KEY_TYPE_ARIA || PSA_HAVE_SOFT_BLOCK_MODE */
+#endif /* PSA_WANT_KEY_TYPE_ARIA */
+
+#if defined(PSA_WANT_KEY_TYPE_CAMELLIA)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_CAMELLIA)
+#define PSA_HAVE_SOFT_KEY_TYPE_CAMELLIA 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_CAMELLIA */
+#if defined(PSA_HAVE_SOFT_KEY_TYPE_CAMELLIA) || \
+ defined(PSA_HAVE_SOFT_BLOCK_MODE) || \
+ defined(PSA_HAVE_SOFT_BLOCK_AEAD)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_CAMELLIA 1
+#define MBEDTLS_CAMELLIA_C
+#endif /* PSA_HAVE_SOFT_KEY_TYPE_CAMELLIA || PSA_HAVE_SOFT_BLOCK_MODE */
+#endif /* PSA_WANT_KEY_TYPE_CAMELLIA */
+
+#if defined(PSA_WANT_KEY_TYPE_DES)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_DES)
+#define PSA_HAVE_SOFT_KEY_TYPE_DES 1
+#endif /* !MBEDTLS_PSA_ACCEL_KEY_TYPE_DES */
+#if defined(PSA_HAVE_SOFT_KEY_TYPE_DES) || \
+ defined(PSA_HAVE_SOFT_BLOCK_MODE)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES 1
+#define MBEDTLS_DES_C
+#endif /*PSA_HAVE_SOFT_KEY_TYPE_DES || PSA_HAVE_SOFT_BLOCK_MODE */
+#endif /* PSA_WANT_KEY_TYPE_DES */
+
+#if defined(PSA_WANT_KEY_TYPE_CHACHA20)
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_CHACHA20)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_CHACHA20 1
+#define MBEDTLS_CHACHA20_C
+#endif /*!MBEDTLS_PSA_ACCEL_KEY_TYPE_CHACHA20 */
+#endif /* PSA_WANT_KEY_TYPE_CHACHA20 */
+
+/* If any of the software block ciphers are selected, define
+ * PSA_HAVE_SOFT_BLOCK_CIPHER, which can be used in any of these
+ * situations. */
+#if defined(PSA_HAVE_SOFT_KEY_TYPE_AES) || \
+ defined(PSA_HAVE_SOFT_KEY_TYPE_ARIA) || \
+ defined(PSA_HAVE_SOFT_KEY_TYPE_DES) || \
+ defined(PSA_HAVE_SOFT_KEY_TYPE_CAMELLIA)
+#define PSA_HAVE_SOFT_BLOCK_CIPHER 1
+#endif
+
+#if defined(PSA_WANT_ALG_STREAM_CIPHER)
+#define MBEDTLS_PSA_BUILTIN_ALG_STREAM_CIPHER 1
+#endif /* PSA_WANT_ALG_STREAM_CIPHER */
+
+#if defined(PSA_WANT_ALG_CBC_MAC)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_CBC_MAC)
+#error "CBC-MAC is not yet supported via the PSA API in Mbed TLS."
+#define MBEDTLS_PSA_BUILTIN_ALG_CBC_MAC 1
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_CBC_MAC */
+#endif /* PSA_WANT_ALG_CBC_MAC */
+
+#if defined(PSA_WANT_ALG_CMAC)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_CMAC) || \
+ defined(PSA_HAVE_SOFT_BLOCK_CIPHER) || \
+ defined(PSA_HAVE_SOFT_PBKDF2_CMAC)
+#define MBEDTLS_PSA_BUILTIN_ALG_CMAC 1
+#define MBEDTLS_CMAC_C
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_CMAC */
+#endif /* PSA_WANT_ALG_CMAC */
+
+#if defined(PSA_HAVE_SOFT_PBKDF2_HMAC) || \
+ defined(PSA_HAVE_SOFT_PBKDF2_CMAC)
+#define PSA_HAVE_SOFT_PBKDF2 1
+#endif /* PSA_HAVE_SOFT_PBKDF2_HMAC || PSA_HAVE_SOFT_PBKDF2_CMAC */
+
+#if defined(PSA_WANT_ALG_CTR)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_CTR) || \
+ defined(PSA_HAVE_SOFT_BLOCK_CIPHER)
+#define MBEDTLS_PSA_BUILTIN_ALG_CTR 1
+#define MBEDTLS_CIPHER_MODE_CTR
+#endif
+#endif /* PSA_WANT_ALG_CTR */
+
+#if defined(PSA_WANT_ALG_CFB)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_CFB) || \
+ defined(PSA_HAVE_SOFT_BLOCK_CIPHER)
+#define MBEDTLS_PSA_BUILTIN_ALG_CFB 1
+#define MBEDTLS_CIPHER_MODE_CFB
+#endif
+#endif /* PSA_WANT_ALG_CFB */
+
+#if defined(PSA_WANT_ALG_OFB)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_OFB) || \
+ defined(PSA_HAVE_SOFT_BLOCK_CIPHER)
+#define MBEDTLS_PSA_BUILTIN_ALG_OFB 1
+#define MBEDTLS_CIPHER_MODE_OFB
+#endif
+#endif /* PSA_WANT_ALG_OFB */
+
+#if defined(PSA_WANT_ALG_ECB_NO_PADDING) && \
+ !defined(MBEDTLS_PSA_ACCEL_ALG_ECB_NO_PADDING)
+#define MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING 1
+#endif
+
+#if defined(PSA_WANT_ALG_CBC_NO_PADDING)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_CBC_NO_PADDING) || \
+ defined(PSA_HAVE_SOFT_BLOCK_CIPHER)
+#define MBEDTLS_CIPHER_MODE_CBC
+#define MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING 1
+#endif
+#endif /* PSA_WANT_ALG_CBC_NO_PADDING */
+
+#if defined(PSA_WANT_ALG_CBC_PKCS7)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_CBC_PKCS7) || \
+ defined(PSA_HAVE_SOFT_BLOCK_CIPHER)
+#define MBEDTLS_CIPHER_MODE_CBC
+#define MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7 1
+#define MBEDTLS_CIPHER_PADDING_PKCS7
+#endif
+#endif /* PSA_WANT_ALG_CBC_PKCS7 */
+
+#if defined(PSA_WANT_ALG_CCM)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_CCM) || \
+ defined(PSA_HAVE_SOFT_KEY_TYPE_AES) || \
+ defined(PSA_HAVE_SOFT_KEY_TYPE_ARIA) || \
+ defined(PSA_HAVE_SOFT_KEY_TYPE_CAMELLIA)
+#define MBEDTLS_PSA_BUILTIN_ALG_CCM 1
+#define MBEDTLS_PSA_BUILTIN_ALG_CCM_STAR_NO_TAG 1
+#define MBEDTLS_CCM_C
+#endif
+#endif /* PSA_WANT_ALG_CCM */
+
+#if defined(PSA_WANT_ALG_GCM)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_GCM) || \
+ defined(PSA_HAVE_SOFT_KEY_TYPE_AES) || \
+ defined(PSA_HAVE_SOFT_KEY_TYPE_ARIA) || \
+ defined(PSA_HAVE_SOFT_KEY_TYPE_CAMELLIA)
+#define MBEDTLS_PSA_BUILTIN_ALG_GCM 1
+#define MBEDTLS_GCM_C
+#endif
+#endif /* PSA_WANT_ALG_GCM */
+
+#if defined(PSA_WANT_ALG_CHACHA20_POLY1305)
+#if !defined(MBEDTLS_PSA_ACCEL_ALG_CHACHA20_POLY1305)
+#if defined(PSA_WANT_KEY_TYPE_CHACHA20)
+#define MBEDTLS_CHACHAPOLY_C
+#define MBEDTLS_CHACHA20_C
+#define MBEDTLS_POLY1305_C
+#define MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 1
+#endif /* PSA_WANT_KEY_TYPE_CHACHA20 */
+#endif /* !MBEDTLS_PSA_ACCEL_ALG_CHACHA20_POLY1305 */
+#endif /* PSA_WANT_ALG_CHACHA20_POLY1305 */
+
+#endif /* MBEDTLS_CONFIG_ADJUST_LEGACY_FROM_PSA_H */
diff --git a/include/mbedtls/config_adjust_psa_from_legacy.h b/include/mbedtls/config_adjust_psa_from_legacy.h
new file mode 100644
index 0000000..c31a462
--- /dev/null
+++ b/include/mbedtls/config_adjust_psa_from_legacy.h
@@ -0,0 +1,334 @@
+/**
+ * \file mbedtls/config_adjust_psa_from_legacy.h
+ * \brief Adjust PSA configuration: construct PSA configuration from legacy
+ *
+ * When MBEDTLS_PSA_CRYPTO_CONFIG is disabled, we automatically enable
+ * cryptographic mechanisms through the PSA interface when the corresponding
+ * legacy mechanism is enabled. In many cases, this just enables the PSA
+ * wrapper code around the legacy implementation, but we also do this for
+ * some mechanisms where PSA has its own independent implementation so
+ * that high-level modules that can use either cryptographic API have the
+ * same feature set in both cases.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CONFIG_ADJUST_PSA_FROM_LEGACY_H
+#define MBEDTLS_CONFIG_ADJUST_PSA_FROM_LEGACY_H
+
+/*
+ * Ensure PSA_WANT_* defines are setup properly if MBEDTLS_PSA_CRYPTO_CONFIG
+ * is not defined
+ */
+
+#if defined(MBEDTLS_CCM_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_CCM 1
+#define MBEDTLS_PSA_BUILTIN_ALG_CCM_STAR_NO_TAG 1
+#define PSA_WANT_ALG_CCM 1
+#define PSA_WANT_ALG_CCM_STAR_NO_TAG 1
+#endif /* MBEDTLS_CCM_C */
+
+#if defined(MBEDTLS_CMAC_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_CMAC 1
+#define PSA_WANT_ALG_CMAC 1
+#endif /* MBEDTLS_CMAC_C */
+
+#if defined(MBEDTLS_ECDH_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_ECDH 1
+#define PSA_WANT_ALG_ECDH 1
+#endif /* MBEDTLS_ECDH_C */
+
+#if defined(MBEDTLS_ECDSA_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_ECDSA 1
+#define PSA_WANT_ALG_ECDSA 1
+#define PSA_WANT_ALG_ECDSA_ANY 1
+
+// Only add in DETERMINISTIC support if ECDSA is also enabled
+#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
+#define MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA 1
+#define PSA_WANT_ALG_DETERMINISTIC_ECDSA 1
+#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
+
+#endif /* MBEDTLS_ECDSA_C */
+
+#if defined(MBEDTLS_ECP_C)
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
+/* Normally we wouldn't enable this because it's not implemented in ecp.c,
+ * but since it used to be available any time ECP_C was enabled, let's enable
+ * it anyway for the sake of backwards compatibility */
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
+/* See comment for PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE above. */
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ECC_PUBLIC_KEY 1
+#define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1
+#endif /* MBEDTLS_ECP_C */
+
+#if defined(MBEDTLS_DHM_C)
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC 1
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT 1
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT 1
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE 1
+#define PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY 1
+#define PSA_WANT_ALG_FFDH 1
+#define PSA_WANT_DH_FAMILY_RFC7919 1
+#define MBEDTLS_PSA_BUILTIN_ALG_FFDH 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_BASIC 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_IMPORT 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_EXPORT 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_KEY_PAIR_GENERATE 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DH_PUBLIC_KEY 1
+#endif /* MBEDTLS_DHM_C */
+
+#if defined(MBEDTLS_GCM_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_GCM 1
+#define PSA_WANT_ALG_GCM 1
+#endif /* MBEDTLS_GCM_C */
+
+/* Enable PSA HKDF algorithm if mbedtls HKDF is supported.
+ * PSA HKDF EXTRACT and PSA HKDF EXPAND have minimal cost when
+ * PSA HKDF is enabled, so enable both algorithms together
+ * with PSA HKDF. */
+#if defined(MBEDTLS_HKDF_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
+#define PSA_WANT_ALG_HMAC 1
+#define MBEDTLS_PSA_BUILTIN_ALG_HKDF 1
+#define PSA_WANT_ALG_HKDF 1
+#define MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT 1
+#define PSA_WANT_ALG_HKDF_EXTRACT 1
+#define MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND 1
+#define PSA_WANT_ALG_HKDF_EXPAND 1
+#endif /* MBEDTLS_HKDF_C */
+
+#define MBEDTLS_PSA_BUILTIN_ALG_HMAC 1
+#define PSA_WANT_ALG_HMAC 1
+#define PSA_WANT_KEY_TYPE_HMAC 1
+
+#if defined(MBEDTLS_MD_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF 1
+#define PSA_WANT_ALG_TLS12_PRF 1
+#define MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS 1
+#define PSA_WANT_ALG_TLS12_PSK_TO_MS 1
+#endif /* MBEDTLS_MD_C */
+
+#if defined(MBEDTLS_MD5_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_MD5 1
+#define PSA_WANT_ALG_MD5 1
+#endif
+
+#if defined(MBEDTLS_ECJPAKE_C)
+#define MBEDTLS_PSA_BUILTIN_PAKE 1
+#define MBEDTLS_PSA_BUILTIN_ALG_JPAKE 1
+#define PSA_WANT_ALG_JPAKE 1
+#endif
+
+#if defined(MBEDTLS_RIPEMD160_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160 1
+#define PSA_WANT_ALG_RIPEMD160 1
+#endif
+
+#if defined(MBEDTLS_RSA_C)
+#if defined(MBEDTLS_PKCS1_V15)
+#define MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_CRYPT 1
+#define PSA_WANT_ALG_RSA_PKCS1V15_CRYPT 1
+#define MBEDTLS_PSA_BUILTIN_ALG_RSA_PKCS1V15_SIGN 1
+#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN 1
+#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW 1
+#endif /* MBEDTLS_PKCS1_V15 */
+#if defined(MBEDTLS_PKCS1_V21)
+#define MBEDTLS_PSA_BUILTIN_ALG_RSA_OAEP 1
+#define PSA_WANT_ALG_RSA_OAEP 1
+#define MBEDTLS_PSA_BUILTIN_ALG_RSA_PSS 1
+#define PSA_WANT_ALG_RSA_PSS 1
+#endif /* MBEDTLS_PKCS1_V21 */
+#if defined(MBEDTLS_GENPRIME)
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1
+#endif /* MBEDTLS_GENPRIME */
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_RSA_PUBLIC_KEY 1
+#define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1
+#endif /* MBEDTLS_RSA_C */
+
+#if defined(MBEDTLS_SHA1_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA_1 1
+#define PSA_WANT_ALG_SHA_1 1
+#endif
+
+#if defined(MBEDTLS_SHA224_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA_224 1
+#define PSA_WANT_ALG_SHA_224 1
+#endif
+
+#if defined(MBEDTLS_SHA256_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA_256 1
+#define PSA_WANT_ALG_SHA_256 1
+#endif
+
+#if defined(MBEDTLS_SHA384_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA_384 1
+#define PSA_WANT_ALG_SHA_384 1
+#endif
+
+#if defined(MBEDTLS_SHA512_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA_512 1
+#define PSA_WANT_ALG_SHA_512 1
+#endif
+
+#if defined(MBEDTLS_SHA3_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA3_224 1
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA3_256 1
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA3_384 1
+#define MBEDTLS_PSA_BUILTIN_ALG_SHA3_512 1
+#define PSA_WANT_ALG_SHA3_224 1
+#define PSA_WANT_ALG_SHA3_256 1
+#define PSA_WANT_ALG_SHA3_384 1
+#define PSA_WANT_ALG_SHA3_512 1
+#endif
+
+#if defined(MBEDTLS_AES_C)
+#define PSA_WANT_KEY_TYPE_AES 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_AES 1
+#endif
+
+#if defined(MBEDTLS_ARIA_C)
+#define PSA_WANT_KEY_TYPE_ARIA 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_ARIA 1
+#endif
+
+#if defined(MBEDTLS_CAMELLIA_C)
+#define PSA_WANT_KEY_TYPE_CAMELLIA 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_CAMELLIA 1
+#endif
+
+#if defined(MBEDTLS_DES_C)
+#define PSA_WANT_KEY_TYPE_DES 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES 1
+#endif
+
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256)
+#define MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS 1
+#define PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS 1
+#endif
+
+#if defined(MBEDTLS_CHACHA20_C)
+#define PSA_WANT_KEY_TYPE_CHACHA20 1
+#define PSA_WANT_ALG_STREAM_CIPHER 1
+#define MBEDTLS_PSA_BUILTIN_KEY_TYPE_CHACHA20 1
+#define MBEDTLS_PSA_BUILTIN_ALG_STREAM_CIPHER 1
+#if defined(MBEDTLS_CHACHAPOLY_C)
+#define PSA_WANT_ALG_CHACHA20_POLY1305 1
+#define MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 1
+#endif
+#endif
+
+#if defined(MBEDTLS_CIPHER_MODE_CBC)
+#define MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING 1
+#define PSA_WANT_ALG_CBC_NO_PADDING 1
+#if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
+#define MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7 1
+#define PSA_WANT_ALG_CBC_PKCS7 1
+#endif
+#endif
+
+#if defined(MBEDTLS_AES_C) || defined(MBEDTLS_DES_C) || \
+ defined(MBEDTLS_ARIA_C) || defined(MBEDTLS_CAMELLIA_C)
+#define MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING 1
+#define PSA_WANT_ALG_ECB_NO_PADDING 1
+#endif
+
+#if defined(MBEDTLS_CIPHER_MODE_CFB)
+#define MBEDTLS_PSA_BUILTIN_ALG_CFB 1
+#define PSA_WANT_ALG_CFB 1
+#endif
+
+#if defined(MBEDTLS_CIPHER_MODE_CTR)
+#define MBEDTLS_PSA_BUILTIN_ALG_CTR 1
+#define PSA_WANT_ALG_CTR 1
+#endif
+
+#if defined(MBEDTLS_CIPHER_MODE_OFB)
+#define MBEDTLS_PSA_BUILTIN_ALG_OFB 1
+#define PSA_WANT_ALG_OFB 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_BRAINPOOL_P_R1_256 1
+#define PSA_WANT_ECC_BRAINPOOL_P_R1_256 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_BRAINPOOL_P_R1_384 1
+#define PSA_WANT_ECC_BRAINPOOL_P_R1_384 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_BRAINPOOL_P_R1_512 1
+#define PSA_WANT_ECC_BRAINPOOL_P_R1_512 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_MONTGOMERY_255 1
+#define PSA_WANT_ECC_MONTGOMERY_255 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_MONTGOMERY_448 1
+#define PSA_WANT_ECC_MONTGOMERY_448 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_192 1
+#define PSA_WANT_ECC_SECP_R1_192 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_224 1
+#define PSA_WANT_ECC_SECP_R1_224 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_256 1
+#define PSA_WANT_ECC_SECP_R1_256 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_384 1
+#define PSA_WANT_ECC_SECP_R1_384 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_R1_521 1
+#define PSA_WANT_ECC_SECP_R1_521 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_K1_192 1
+#define PSA_WANT_ECC_SECP_K1_192 1
+#endif
+
+/* SECP224K1 is buggy via the PSA API (https://github.com/Mbed-TLS/mbedtls/issues/3541) */
+#if 0 && defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_K1_224 1
+#define PSA_WANT_ECC_SECP_K1_224 1
+#endif
+
+#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
+#define MBEDTLS_PSA_BUILTIN_ECC_SECP_K1_256 1
+#define PSA_WANT_ECC_SECP_K1_256 1
+#endif
+
+#endif /* MBEDTLS_CONFIG_ADJUST_PSA_FROM_LEGACY_H */
diff --git a/include/mbedtls/config_adjust_psa_superset_legacy.h b/include/mbedtls/config_adjust_psa_superset_legacy.h
new file mode 100644
index 0000000..3a55c3f
--- /dev/null
+++ b/include/mbedtls/config_adjust_psa_superset_legacy.h
@@ -0,0 +1,142 @@
+/**
+ * \file mbedtls/config_adjust_psa_superset_legacy.h
+ * \brief Adjust PSA configuration: automatic enablement from legacy
+ *
+ * To simplify some edge cases, we automatically enable certain cryptographic
+ * mechanisms in the PSA API if they are enabled in the legacy API. The general
+ * idea is that if legacy module M uses mechanism A internally, and A has
+ * both a legacy and a PSA implementation, we enable A through PSA whenever
+ * it's enabled through legacy. This facilitates the transition to PSA
+ * implementations of A for users of M.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CONFIG_ADJUST_PSA_SUPERSET_LEGACY_H
+#define MBEDTLS_CONFIG_ADJUST_PSA_SUPERSET_LEGACY_H
+
+/****************************************************************/
+/* Hashes that are built in are also enabled in PSA.
+ * This simplifies dependency declarations especially
+ * for modules that obey MBEDTLS_USE_PSA_CRYPTO. */
+/****************************************************************/
+
+#if defined(MBEDTLS_MD5_C)
+#define PSA_WANT_ALG_MD5 1
+#endif
+
+#if defined(MBEDTLS_RIPEMD160_C)
+#define PSA_WANT_ALG_RIPEMD160 1
+#endif
+
+#if defined(MBEDTLS_SHA1_C)
+#define PSA_WANT_ALG_SHA_1 1
+#endif
+
+#if defined(MBEDTLS_SHA224_C)
+#define PSA_WANT_ALG_SHA_224 1
+#endif
+
+#if defined(MBEDTLS_SHA256_C)
+#define PSA_WANT_ALG_SHA_256 1
+#endif
+
+#if defined(MBEDTLS_SHA384_C)
+#define PSA_WANT_ALG_SHA_384 1
+#endif
+
+#if defined(MBEDTLS_SHA512_C)
+#define PSA_WANT_ALG_SHA_512 1
+#endif
+
+#if defined(MBEDTLS_SHA3_C)
+#define PSA_WANT_ALG_SHA3_224 1
+#define PSA_WANT_ALG_SHA3_256 1
+#define PSA_WANT_ALG_SHA3_384 1
+#define PSA_WANT_ALG_SHA3_512 1
+#endif
+
+/* Ensure that the PSA's supported curves (PSA_WANT_ECC_xxx) are always a
+ * superset of the builtin ones (MBEDTLS_ECP_DP_xxx). */
+#if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
+#if !defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
+#define PSA_WANT_ECC_BRAINPOOL_P_R1_256 1
+#endif /* PSA_WANT_ECC_BRAINPOOL_P_R1_256 */
+#endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
+#if !defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
+#define PSA_WANT_ECC_BRAINPOOL_P_R1_384 1
+#endif /* PSA_WANT_ECC_BRAINPOOL_P_R1_384 */
+#endif /*MBEDTLS_ECP_DP_BP384R1_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
+#if !defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
+#define PSA_WANT_ECC_BRAINPOOL_P_R1_512 1
+#endif /* PSA_WANT_ECC_BRAINPOOL_P_R1_512 */
+#endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
+#if !defined(PSA_WANT_ECC_MONTGOMERY_255)
+#define PSA_WANT_ECC_MONTGOMERY_255 1
+#endif /* PSA_WANT_ECC_MONTGOMERY_255 */
+#endif /* MBEDTLS_ECP_DP_CURVE25519_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
+#if !defined(PSA_WANT_ECC_MONTGOMERY_448)
+#define PSA_WANT_ECC_MONTGOMERY_448 1
+#endif /* PSA_WANT_ECC_MONTGOMERY_448 */
+#endif /* MBEDTLS_ECP_DP_CURVE448_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
+#if !defined(PSA_WANT_ECC_SECP_R1_192)
+#define PSA_WANT_ECC_SECP_R1_192 1
+#endif /* PSA_WANT_ECC_SECP_R1_192 */
+#endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
+#if !defined(PSA_WANT_ECC_SECP_R1_224)
+#define PSA_WANT_ECC_SECP_R1_224 1
+#endif /* PSA_WANT_ECC_SECP_R1_224 */
+#endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
+#if !defined(PSA_WANT_ECC_SECP_R1_256)
+#define PSA_WANT_ECC_SECP_R1_256 1
+#endif /* PSA_WANT_ECC_SECP_R1_256 */
+#endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
+#if !defined(PSA_WANT_ECC_SECP_R1_384)
+#define PSA_WANT_ECC_SECP_R1_384 1
+#endif /* PSA_WANT_ECC_SECP_R1_384 */
+#endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
+#if !defined(PSA_WANT_ECC_SECP_R1_521)
+#define PSA_WANT_ECC_SECP_R1_521 1
+#endif /* PSA_WANT_ECC_SECP_R1_521 */
+#endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
+#if !defined(PSA_WANT_ECC_SECP_K1_192)
+#define PSA_WANT_ECC_SECP_K1_192 1
+#endif /* PSA_WANT_ECC_SECP_K1_192 */
+#endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */
+
+/* SECP224K1 is buggy via the PSA API (https://github.com/Mbed-TLS/mbedtls/issues/3541) */
+#if 0 && defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
+#if !defined(PSA_WANT_ECC_SECP_K1_224)
+#define PSA_WANT_ECC_SECP_K1_224 1
+#endif /* PSA_WANT_ECC_SECP_K1_224 */
+#endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */
+
+#if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
+#if !defined(PSA_WANT_ECC_SECP_K1_256)
+#define PSA_WANT_ECC_SECP_K1_256 1
+#endif /* PSA_WANT_ECC_SECP_K1_256 */
+#endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */
+
+#endif /* MBEDTLS_CONFIG_ADJUST_PSA_SUPERSET_LEGACY_H */
diff --git a/include/mbedtls/config_adjust_ssl.h b/include/mbedtls/config_adjust_ssl.h
new file mode 100644
index 0000000..8415f3e
--- /dev/null
+++ b/include/mbedtls/config_adjust_ssl.h
@@ -0,0 +1,76 @@
+/**
+ * \file mbedtls/config_adjust_ssl.h
+ * \brief Adjust TLS configuration
+ *
+ * Automatically enable certain dependencies. Generally, MBEDLTS_xxx
+ * configurations need to be explicitly enabled by the user: enabling
+ * MBEDTLS_xxx_A but not MBEDTLS_xxx_B when A requires B results in a
+ * compilation error. However, we do automatically enable certain options
+ * in some circumstances. One case is if MBEDTLS_xxx_B is an internal option
+ * used to identify parts of a module that are used by other module, and we
+ * don't want to make the symbol MBEDTLS_xxx_B part of the public API.
+ * Another case is if A didn't depend on B in earlier versions, and we
+ * want to use B in A but we need to preserve backward compatibility with
+ * configurations that explicitly activate MBEDTLS_xxx_A but not
+ * MBEDTLS_xxx_B.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CONFIG_ADJUST_SSL_H
+#define MBEDTLS_CONFIG_ADJUST_SSL_H
+
+/* The following blocks make it easier to disable all of TLS,
+ * or of TLS 1.2 or 1.3 or DTLS, without having to manually disable all
+ * key exchanges, options and extensions related to them. */
+
+#if !defined(MBEDTLS_SSL_TLS_C)
+#undef MBEDTLS_SSL_CLI_C
+#undef MBEDTLS_SSL_SRV_C
+#undef MBEDTLS_SSL_PROTO_TLS1_3
+#undef MBEDTLS_SSL_PROTO_TLS1_2
+#undef MBEDTLS_SSL_PROTO_DTLS
+#endif
+
+#if !defined(MBEDTLS_SSL_PROTO_DTLS)
+#undef MBEDTLS_SSL_DTLS_ANTI_REPLAY
+#undef MBEDTLS_SSL_DTLS_CONNECTION_ID
+#undef MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT
+#undef MBEDTLS_SSL_DTLS_HELLO_VERIFY
+#undef MBEDTLS_SSL_DTLS_SRTP
+#undef MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
+#endif
+
+#if !defined(MBEDTLS_SSL_PROTO_TLS1_2)
+#undef MBEDTLS_SSL_ENCRYPT_THEN_MAC
+#undef MBEDTLS_SSL_EXTENDED_MASTER_SECRET
+#undef MBEDTLS_SSL_RENEGOTIATION
+#undef MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
+#undef MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
+#undef MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
+#undef MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
+#undef MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
+#undef MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED
+#undef MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
+#undef MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+#undef MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
+#undef MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED
+#undef MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
+#endif
+
+#if !defined(MBEDTLS_SSL_PROTO_TLS1_3)
+#undef MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
+#undef MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
+#undef MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED
+#undef MBEDTLS_SSL_EARLY_DATA
+#endif
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \
+ (defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED))
+#define MBEDTLS_SSL_TLS1_2_SOME_ECC
+#endif
+
+#endif /* MBEDTLS_CONFIG_ADJUST_SSL_H */
diff --git a/include/mbedtls/config_adjust_x509.h b/include/mbedtls/config_adjust_x509.h
new file mode 100644
index 0000000..346c8ae
--- /dev/null
+++ b/include/mbedtls/config_adjust_x509.h
@@ -0,0 +1,25 @@
+/**
+ * \file mbedtls/config_adjust_x509.h
+ * \brief Adjust X.509 configuration
+ *
+ * Automatically enable certain dependencies. Generally, MBEDLTS_xxx
+ * configurations need to be explicitly enabled by the user: enabling
+ * MBEDTLS_xxx_A but not MBEDTLS_xxx_B when A requires B results in a
+ * compilation error. However, we do automatically enable certain options
+ * in some circumstances. One case is if MBEDTLS_xxx_B is an internal option
+ * used to identify parts of a module that are used by other module, and we
+ * don't want to make the symbol MBEDTLS_xxx_B part of the public API.
+ * Another case is if A didn't depend on B in earlier versions, and we
+ * want to use B in A but we need to preserve backward compatibility with
+ * configurations that explicitly activate MBEDTLS_xxx_A but not
+ * MBEDTLS_xxx_B.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CONFIG_ADJUST_X509_H
+#define MBEDTLS_CONFIG_ADJUST_X509_H
+
+#endif /* MBEDTLS_CONFIG_ADJUST_X509_H */
diff --git a/include/mbedtls/config_psa.h b/include/mbedtls/config_psa.h
new file mode 100644
index 0000000..17da61b
--- /dev/null
+++ b/include/mbedtls/config_psa.h
@@ -0,0 +1,55 @@
+/**
+ * \file mbedtls/config_psa.h
+ * \brief PSA crypto configuration options (set of defines)
+ *
+ * This set of compile-time options takes settings defined in
+ * include/mbedtls/mbedtls_config.h and include/psa/crypto_config.h and uses
+ * those definitions to define symbols used in the library code.
+ *
+ * Users and integrators should not edit this file, please edit
+ * include/mbedtls/mbedtls_config.h for MBEDTLS_XXX settings or
+ * include/psa/crypto_config.h for PSA_WANT_XXX settings.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CONFIG_PSA_H
+#define MBEDTLS_CONFIG_PSA_H
+
+#include "psa/crypto_legacy.h"
+
+#include "psa/crypto_adjust_config_synonyms.h"
+
+#include "mbedtls/config_adjust_psa_superset_legacy.h"
+
+#if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
+
+/* Require built-in implementations based on PSA requirements */
+
+/* We need this to have a complete list of requirements
+ * before we deduce what built-ins are required. */
+#include "psa/crypto_adjust_config_key_pair_types.h"
+
+#include "mbedtls/config_adjust_legacy_from_psa.h"
+
+#else /* MBEDTLS_PSA_CRYPTO_CONFIG */
+
+/* Infer PSA requirements from Mbed TLS capabilities */
+
+#include "mbedtls/config_adjust_psa_from_legacy.h"
+
+/* Hopefully the file above will have enabled keypair symbols in a consistent
+ * way, but including this here fixes them if that wasn't the case. */
+#include "psa/crypto_adjust_config_key_pair_types.h"
+
+#endif /* MBEDTLS_PSA_CRYPTO_CONFIG */
+
+#if defined(PSA_WANT_ALG_JPAKE)
+#define PSA_WANT_ALG_SOME_PAKE 1
+#endif
+
+#include "psa/crypto_adjust_auto_enabled.h"
+
+#endif /* MBEDTLS_CONFIG_PSA_H */
diff --git a/include/mbedtls/constant_time.h b/include/mbedtls/constant_time.h
new file mode 100644
index 0000000..d31bff6
--- /dev/null
+++ b/include/mbedtls/constant_time.h
@@ -0,0 +1,36 @@
+/**
+ * Constant-time functions
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CONSTANT_TIME_H
+#define MBEDTLS_CONSTANT_TIME_H
+
+#include <stddef.h>
+
+/** Constant-time buffer comparison without branches.
+ *
+ * This is equivalent to the standard memcmp function, but is likely to be
+ * compiled to code using bitwise operations rather than a branch, such that
+ * the time taken is constant w.r.t. the data pointed to by \p a and \p b,
+ * and w.r.t. whether \p a and \p b are equal or not. It is not constant-time
+ * w.r.t. \p n .
+ *
+ * This function can be used to write constant-time code by replacing branches
+ * with bit operations using masks.
+ *
+ * \param a Pointer to the first buffer, containing at least \p n bytes. May not be NULL.
+ * \param b Pointer to the second buffer, containing at least \p n bytes. May not be NULL.
+ * \param n The number of bytes to compare.
+ *
+ * \return Zero if the contents of the two buffers are the same,
+ * otherwise non-zero.
+ */
+int mbedtls_ct_memcmp(const void *a,
+ const void *b,
+ size_t n);
+
+#endif /* MBEDTLS_CONSTANT_TIME_H */
diff --git a/include/mbedtls/ctr_drbg.h b/include/mbedtls/ctr_drbg.h
new file mode 100644
index 0000000..d1f19e6
--- /dev/null
+++ b/include/mbedtls/ctr_drbg.h
@@ -0,0 +1,564 @@
+/**
+ * \file ctr_drbg.h
+ *
+ * \brief This file contains definitions and functions for the
+ * CTR_DRBG pseudorandom generator.
+ *
+ * CTR_DRBG is a standardized way of building a PRNG from a block-cipher
+ * in counter mode operation, as defined in <em>NIST SP 800-90A:
+ * Recommendation for Random Number Generation Using Deterministic Random
+ * Bit Generators</em>.
+ *
+ * The Mbed TLS implementation of CTR_DRBG uses AES-256 (default) or AES-128
+ * (if \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is enabled at compile time)
+ * as the underlying block cipher, with a derivation function.
+ *
+ * The security strength as defined in NIST SP 800-90A is
+ * 128 bits when AES-128 is used (\c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY enabled)
+ * and 256 bits otherwise, provided that #MBEDTLS_CTR_DRBG_ENTROPY_LEN is
+ * kept at its default value (and not overridden in mbedtls_config.h) and that the
+ * DRBG instance is set up with default parameters.
+ * See the documentation of mbedtls_ctr_drbg_seed() for more
+ * information.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_CTR_DRBG_H
+#define MBEDTLS_CTR_DRBG_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/aes.h"
+#include "entropy.h"
+
+#if defined(MBEDTLS_THREADING_C)
+#include "mbedtls/threading.h"
+#endif
+
+/** The entropy source failed. */
+#define MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED -0x0034
+/** The requested random buffer length is too big. */
+#define MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG -0x0036
+/** The input (entropy + additional data) is too large. */
+#define MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG -0x0038
+/** Read or write error in file. */
+#define MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR -0x003A
+
+#define MBEDTLS_CTR_DRBG_BLOCKSIZE 16 /**< The block size used by the cipher. */
+
+#if defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY)
+#define MBEDTLS_CTR_DRBG_KEYSIZE 16
+/**< The key size in bytes used by the cipher.
+ *
+ * Compile-time choice: 16 bytes (128 bits)
+ * because #MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is enabled.
+ */
+#else
+#define MBEDTLS_CTR_DRBG_KEYSIZE 32
+/**< The key size in bytes used by the cipher.
+ *
+ * Compile-time choice: 32 bytes (256 bits)
+ * because \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is disabled.
+ */
+#endif
+
+#define MBEDTLS_CTR_DRBG_KEYBITS (MBEDTLS_CTR_DRBG_KEYSIZE * 8) /**< The key size for the DRBG operation, in bits. */
+#define MBEDTLS_CTR_DRBG_SEEDLEN (MBEDTLS_CTR_DRBG_KEYSIZE + MBEDTLS_CTR_DRBG_BLOCKSIZE) /**< The seed length, calculated as (counter + AES key). */
+
+/**
+ * \name SECTION: Module settings
+ *
+ * The configuration options you can set for this module are in this section.
+ * Either change them in mbedtls_config.h or define them using the compiler command
+ * line.
+ * \{
+ */
+
+/** \def MBEDTLS_CTR_DRBG_ENTROPY_LEN
+ *
+ * \brief The amount of entropy used per seed by default, in bytes.
+ */
+#if !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN)
+#if defined(MBEDTLS_ENTROPY_SHA512_ACCUMULATOR)
+/** This is 48 bytes because the entropy module uses SHA-512.
+ */
+#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48
+
+#else /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
+
+/** This is 32 bytes because the entropy module uses SHA-256.
+ */
+#if !defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY)
+/** \warning To achieve a 256-bit security strength, you must pass a nonce
+ * to mbedtls_ctr_drbg_seed().
+ */
+#endif /* !defined(MBEDTLS_CTR_DRBG_USE_128_BIT_KEY) */
+#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 32
+#endif /* MBEDTLS_ENTROPY_SHA512_ACCUMULATOR */
+#endif /* !defined(MBEDTLS_CTR_DRBG_ENTROPY_LEN) */
+
+#if !defined(MBEDTLS_CTR_DRBG_RESEED_INTERVAL)
+#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000
+/**< The interval before reseed is performed by default. */
+#endif
+
+#if !defined(MBEDTLS_CTR_DRBG_MAX_INPUT)
+#define MBEDTLS_CTR_DRBG_MAX_INPUT 256
+/**< The maximum number of additional input Bytes. */
+#endif
+
+#if !defined(MBEDTLS_CTR_DRBG_MAX_REQUEST)
+#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024
+/**< The maximum number of requested Bytes per call. */
+#endif
+
+#if !defined(MBEDTLS_CTR_DRBG_MAX_SEED_INPUT)
+#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384
+/**< The maximum size of seed or reseed buffer in bytes. */
+#endif
+
+/** \} name SECTION: Module settings */
+
+#define MBEDTLS_CTR_DRBG_PR_OFF 0
+/**< Prediction resistance is disabled. */
+#define MBEDTLS_CTR_DRBG_PR_ON 1
+/**< Prediction resistance is enabled. */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if MBEDTLS_CTR_DRBG_ENTROPY_LEN >= MBEDTLS_CTR_DRBG_KEYSIZE * 3 / 2
+/** The default length of the nonce read from the entropy source.
+ *
+ * This is \c 0 because a single read from the entropy source is sufficient
+ * to include a nonce.
+ * See the documentation of mbedtls_ctr_drbg_seed() for more information.
+ */
+#define MBEDTLS_CTR_DRBG_ENTROPY_NONCE_LEN 0
+#else
+/** The default length of the nonce read from the entropy source.
+ *
+ * This is half of the default entropy length because a single read from
+ * the entropy source does not provide enough material to form a nonce.
+ * See the documentation of mbedtls_ctr_drbg_seed() for more information.
+ */
+#define MBEDTLS_CTR_DRBG_ENTROPY_NONCE_LEN (MBEDTLS_CTR_DRBG_ENTROPY_LEN + 1) / 2
+#endif
+
+/**
+ * \brief The CTR_DRBG context structure.
+ */
+typedef struct mbedtls_ctr_drbg_context {
+ unsigned char MBEDTLS_PRIVATE(counter)[16]; /*!< The counter (V). */
+ int MBEDTLS_PRIVATE(reseed_counter); /*!< The reseed counter.
+ * This is the number of requests that have
+ * been made since the last (re)seeding,
+ * minus one.
+ * Before the initial seeding, this field
+ * contains the amount of entropy in bytes
+ * to use as a nonce for the initial seeding,
+ * or -1 if no nonce length has been explicitly
+ * set (see mbedtls_ctr_drbg_set_nonce_len()).
+ */
+ int MBEDTLS_PRIVATE(prediction_resistance); /*!< This determines whether prediction
+ resistance is enabled, that is
+ whether to systematically reseed before
+ each random generation. */
+ size_t MBEDTLS_PRIVATE(entropy_len); /*!< The amount of entropy grabbed on each
+ seed or reseed operation, in bytes. */
+ int MBEDTLS_PRIVATE(reseed_interval); /*!< The reseed interval.
+ * This is the maximum number of requests
+ * that can be made between reseedings. */
+
+ mbedtls_aes_context MBEDTLS_PRIVATE(aes_ctx); /*!< The AES context. */
+
+ /*
+ * Callbacks (Entropy)
+ */
+ int(*MBEDTLS_PRIVATE(f_entropy))(void *, unsigned char *, size_t);
+ /*!< The entropy callback function. */
+
+ void *MBEDTLS_PRIVATE(p_entropy); /*!< The context for the entropy function. */
+
+#if defined(MBEDTLS_THREADING_C)
+ /* Invariant: the mutex is initialized if and only if f_entropy != NULL.
+ * This means that the mutex is initialized during the initial seeding
+ * in mbedtls_ctr_drbg_seed() and freed in mbedtls_ctr_drbg_free().
+ *
+ * Note that this invariant may change without notice. Do not rely on it
+ * and do not access the mutex directly in application code.
+ */
+ mbedtls_threading_mutex_t MBEDTLS_PRIVATE(mutex);
+#endif
+}
+mbedtls_ctr_drbg_context;
+
+/**
+ * \brief This function initializes the CTR_DRBG context,
+ * and prepares it for mbedtls_ctr_drbg_seed()
+ * or mbedtls_ctr_drbg_free().
+ *
+ * \note The reseed interval is
+ * #MBEDTLS_CTR_DRBG_RESEED_INTERVAL by default.
+ * You can override it by calling
+ * mbedtls_ctr_drbg_set_reseed_interval().
+ *
+ * \param ctx The CTR_DRBG context to initialize.
+ */
+void mbedtls_ctr_drbg_init(mbedtls_ctr_drbg_context *ctx);
+
+/**
+ * \brief This function seeds and sets up the CTR_DRBG
+ * entropy source for future reseeds.
+ *
+ * A typical choice for the \p f_entropy and \p p_entropy parameters is
+ * to use the entropy module:
+ * - \p f_entropy is mbedtls_entropy_func();
+ * - \p p_entropy is an instance of ::mbedtls_entropy_context initialized
+ * with mbedtls_entropy_init() (which registers the platform's default
+ * entropy sources).
+ *
+ * The entropy length is #MBEDTLS_CTR_DRBG_ENTROPY_LEN by default.
+ * You can override it by calling mbedtls_ctr_drbg_set_entropy_len().
+ *
+ * The entropy nonce length is:
+ * - \c 0 if the entropy length is at least 3/2 times the entropy length,
+ * which guarantees that the security strength is the maximum permitted
+ * by the key size and entropy length according to NIST SP 800-90A §10.2.1;
+ * - Half the entropy length otherwise.
+ * You can override it by calling mbedtls_ctr_drbg_set_nonce_len().
+ * With the default entropy length, the entropy nonce length is
+ * #MBEDTLS_CTR_DRBG_ENTROPY_NONCE_LEN.
+ *
+ * You can provide a nonce and personalization string in addition to the
+ * entropy source, to make this instantiation as unique as possible.
+ * See SP 800-90A §8.6.7 for more details about nonces.
+ *
+ * The _seed_material_ value passed to the derivation function in
+ * the CTR_DRBG Instantiate Process described in NIST SP 800-90A §10.2.1.3.2
+ * is the concatenation of the following strings:
+ * - A string obtained by calling \p f_entropy function for the entropy
+ * length.
+ */
+#if MBEDTLS_CTR_DRBG_ENTROPY_NONCE_LEN == 0
+/**
+ * - If mbedtls_ctr_drbg_set_nonce_len() has been called, a string
+ * obtained by calling \p f_entropy function for the specified length.
+ */
+#else
+/**
+ * - A string obtained by calling \p f_entropy function for the entropy nonce
+ * length. If the entropy nonce length is \c 0, this function does not
+ * make a second call to \p f_entropy.
+ */
+#endif
+#if defined(MBEDTLS_THREADING_C)
+/**
+ * \note When Mbed TLS is built with threading support,
+ * after this function returns successfully,
+ * it is safe to call mbedtls_ctr_drbg_random()
+ * from multiple threads. Other operations, including
+ * reseeding, are not thread-safe.
+ */
+#endif /* MBEDTLS_THREADING_C */
+/**
+ * - The \p custom string.
+ *
+ * \note To achieve the nominal security strength permitted
+ * by CTR_DRBG, the entropy length must be:
+ * - at least 16 bytes for a 128-bit strength
+ * (maximum achievable strength when using AES-128);
+ * - at least 32 bytes for a 256-bit strength
+ * (maximum achievable strength when using AES-256).
+ *
+ * In addition, if you do not pass a nonce in \p custom,
+ * the sum of the entropy length
+ * and the entropy nonce length must be:
+ * - at least 24 bytes for a 128-bit strength
+ * (maximum achievable strength when using AES-128);
+ * - at least 48 bytes for a 256-bit strength
+ * (maximum achievable strength when using AES-256).
+ *
+ * \param ctx The CTR_DRBG context to seed.
+ * It must have been initialized with
+ * mbedtls_ctr_drbg_init().
+ * After a successful call to mbedtls_ctr_drbg_seed(),
+ * you may not call mbedtls_ctr_drbg_seed() again on
+ * the same context unless you call
+ * mbedtls_ctr_drbg_free() and mbedtls_ctr_drbg_init()
+ * again first.
+ * After a failed call to mbedtls_ctr_drbg_seed(),
+ * you must call mbedtls_ctr_drbg_free().
+ * \param f_entropy The entropy callback, taking as arguments the
+ * \p p_entropy context, the buffer to fill, and the
+ * length of the buffer.
+ * \p f_entropy is always called with a buffer size
+ * less than or equal to the entropy length.
+ * \param p_entropy The entropy context to pass to \p f_entropy.
+ * \param custom The personalization string.
+ * This can be \c NULL, in which case the personalization
+ * string is empty regardless of the value of \p len.
+ * \param len The length of the personalization string.
+ * This must be at most
+ * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT
+ * - #MBEDTLS_CTR_DRBG_ENTROPY_LEN.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
+ */
+int mbedtls_ctr_drbg_seed(mbedtls_ctr_drbg_context *ctx,
+ int (*f_entropy)(void *, unsigned char *, size_t),
+ void *p_entropy,
+ const unsigned char *custom,
+ size_t len);
+
+/**
+ * \brief This function resets CTR_DRBG context to the state immediately
+ * after initial call of mbedtls_ctr_drbg_init().
+ *
+ * \param ctx The CTR_DRBG context to clear.
+ */
+void mbedtls_ctr_drbg_free(mbedtls_ctr_drbg_context *ctx);
+
+/**
+ * \brief This function turns prediction resistance on or off.
+ * The default value is off.
+ *
+ * \note If enabled, entropy is gathered at the beginning of
+ * every call to mbedtls_ctr_drbg_random_with_add()
+ * or mbedtls_ctr_drbg_random().
+ * Only use this if your entropy source has sufficient
+ * throughput.
+ *
+ * \param ctx The CTR_DRBG context.
+ * \param resistance #MBEDTLS_CTR_DRBG_PR_ON or #MBEDTLS_CTR_DRBG_PR_OFF.
+ */
+void mbedtls_ctr_drbg_set_prediction_resistance(mbedtls_ctr_drbg_context *ctx,
+ int resistance);
+
+/**
+ * \brief This function sets the amount of entropy grabbed on each
+ * seed or reseed.
+ *
+ * The default value is #MBEDTLS_CTR_DRBG_ENTROPY_LEN.
+ *
+ * \note The security strength of CTR_DRBG is bounded by the
+ * entropy length. Thus:
+ * - When using AES-256
+ * (\c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is disabled,
+ * which is the default),
+ * \p len must be at least 32 (in bytes)
+ * to achieve a 256-bit strength.
+ * - When using AES-128
+ * (\c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY is enabled)
+ * \p len must be at least 16 (in bytes)
+ * to achieve a 128-bit strength.
+ *
+ * \param ctx The CTR_DRBG context.
+ * \param len The amount of entropy to grab, in bytes.
+ * This must be at most #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT
+ * and at most the maximum length accepted by the
+ * entropy function that is set in the context.
+ */
+void mbedtls_ctr_drbg_set_entropy_len(mbedtls_ctr_drbg_context *ctx,
+ size_t len);
+
+/**
+ * \brief This function sets the amount of entropy grabbed
+ * as a nonce for the initial seeding.
+ *
+ * Call this function before calling mbedtls_ctr_drbg_seed() to read
+ * a nonce from the entropy source during the initial seeding.
+ *
+ * \param ctx The CTR_DRBG context.
+ * \param len The amount of entropy to grab for the nonce, in bytes.
+ * This must be at most #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT
+ * and at most the maximum length accepted by the
+ * entropy function that is set in the context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG if \p len is
+ * more than #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT.
+ * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED
+ * if the initial seeding has already taken place.
+ */
+int mbedtls_ctr_drbg_set_nonce_len(mbedtls_ctr_drbg_context *ctx,
+ size_t len);
+
+/**
+ * \brief This function sets the reseed interval.
+ *
+ * The reseed interval is the number of calls to mbedtls_ctr_drbg_random()
+ * or mbedtls_ctr_drbg_random_with_add() after which the entropy function
+ * is called again.
+ *
+ * The default value is #MBEDTLS_CTR_DRBG_RESEED_INTERVAL.
+ *
+ * \param ctx The CTR_DRBG context.
+ * \param interval The reseed interval.
+ */
+void mbedtls_ctr_drbg_set_reseed_interval(mbedtls_ctr_drbg_context *ctx,
+ int interval);
+
+/**
+ * \brief This function reseeds the CTR_DRBG context, that is
+ * extracts data from the entropy source.
+ *
+ * \note This function is not thread-safe. It is not safe
+ * to call this function if another thread might be
+ * concurrently obtaining random numbers from the same
+ * context or updating or reseeding the same context.
+ *
+ * \param ctx The CTR_DRBG context.
+ * \param additional Additional data to add to the state. Can be \c NULL.
+ * \param len The length of the additional data.
+ * This must be less than
+ * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - \c entropy_len
+ * where \c entropy_len is the entropy length
+ * configured for the context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on failure.
+ */
+int mbedtls_ctr_drbg_reseed(mbedtls_ctr_drbg_context *ctx,
+ const unsigned char *additional, size_t len);
+
+/**
+ * \brief This function updates the state of the CTR_DRBG context.
+ *
+ * \note This function is not thread-safe. It is not safe
+ * to call this function if another thread might be
+ * concurrently obtaining random numbers from the same
+ * context or updating or reseeding the same context.
+ *
+ * \param ctx The CTR_DRBG context.
+ * \param additional The data to update the state with. This must not be
+ * \c NULL unless \p add_len is \c 0.
+ * \param add_len Length of \p additional in bytes. This must be at
+ * most #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG if
+ * \p add_len is more than
+ * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT.
+ * \return An error from the underlying AES cipher on failure.
+ */
+int mbedtls_ctr_drbg_update(mbedtls_ctr_drbg_context *ctx,
+ const unsigned char *additional,
+ size_t add_len);
+
+/**
+ * \brief This function updates a CTR_DRBG instance with additional
+ * data and uses it to generate random data.
+ *
+ * This function automatically reseeds if the reseed counter is exceeded
+ * or prediction resistance is enabled.
+ *
+ * \note This function is not thread-safe. It is not safe
+ * to call this function if another thread might be
+ * concurrently obtaining random numbers from the same
+ * context or updating or reseeding the same context.
+ *
+ * \param p_rng The CTR_DRBG context. This must be a pointer to a
+ * #mbedtls_ctr_drbg_context structure.
+ * \param output The buffer to fill.
+ * \param output_len The length of the buffer in bytes.
+ * \param additional Additional data to update. Can be \c NULL, in which
+ * case the additional data is empty regardless of
+ * the value of \p add_len.
+ * \param add_len The length of the additional data
+ * if \p additional is not \c NULL.
+ * This must be less than #MBEDTLS_CTR_DRBG_MAX_INPUT
+ * and less than
+ * #MBEDTLS_CTR_DRBG_MAX_SEED_INPUT - \c entropy_len
+ * where \c entropy_len is the entropy length
+ * configured for the context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
+ * #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure.
+ */
+int mbedtls_ctr_drbg_random_with_add(void *p_rng,
+ unsigned char *output, size_t output_len,
+ const unsigned char *additional, size_t add_len);
+
+/**
+ * \brief This function uses CTR_DRBG to generate random data.
+ *
+ * This function automatically reseeds if the reseed counter is exceeded
+ * or prediction resistance is enabled.
+ */
+#if defined(MBEDTLS_THREADING_C)
+/**
+ * \note When Mbed TLS is built with threading support,
+ * it is safe to call mbedtls_ctr_drbg_random()
+ * from multiple threads. Other operations, including
+ * reseeding, are not thread-safe.
+ */
+#endif /* MBEDTLS_THREADING_C */
+/**
+ * \param p_rng The CTR_DRBG context. This must be a pointer to a
+ * #mbedtls_ctr_drbg_context structure.
+ * \param output The buffer to fill.
+ * \param output_len The length of the buffer in bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED or
+ * #MBEDTLS_ERR_CTR_DRBG_REQUEST_TOO_BIG on failure.
+ */
+int mbedtls_ctr_drbg_random(void *p_rng,
+ unsigned char *output, size_t output_len);
+
+#if defined(MBEDTLS_FS_IO)
+/**
+ * \brief This function writes a seed file.
+ *
+ * \param ctx The CTR_DRBG context.
+ * \param path The name of the file.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error.
+ * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on reseed
+ * failure.
+ */
+int mbedtls_ctr_drbg_write_seed_file(mbedtls_ctr_drbg_context *ctx, const char *path);
+
+/**
+ * \brief This function reads and updates a seed file. The seed
+ * is added to this instance.
+ *
+ * \param ctx The CTR_DRBG context.
+ * \param path The name of the file.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_CTR_DRBG_FILE_IO_ERROR on file error.
+ * \return #MBEDTLS_ERR_CTR_DRBG_ENTROPY_SOURCE_FAILED on
+ * reseed failure.
+ * \return #MBEDTLS_ERR_CTR_DRBG_INPUT_TOO_BIG if the existing
+ * seed file is too large.
+ */
+int mbedtls_ctr_drbg_update_seed_file(mbedtls_ctr_drbg_context *ctx, const char *path);
+#endif /* MBEDTLS_FS_IO */
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief The CTR_DRBG checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_ctr_drbg_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ctr_drbg.h */
diff --git a/include/mbedtls/debug.h b/include/mbedtls/debug.h
new file mode 100644
index 0000000..0aef2ed
--- /dev/null
+++ b/include/mbedtls/debug.h
@@ -0,0 +1,308 @@
+/**
+ * \file debug.h
+ *
+ * \brief Functions for controlling and providing debug output from the library.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_DEBUG_H
+#define MBEDTLS_DEBUG_H
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/ssl.h"
+
+#if defined(MBEDTLS_ECP_C)
+#include "mbedtls/ecp.h"
+#endif
+
+#if defined(MBEDTLS_DEBUG_C)
+
+#define MBEDTLS_DEBUG_STRIP_PARENS(...) __VA_ARGS__
+
+#define MBEDTLS_SSL_DEBUG_MSG(level, args) \
+ mbedtls_debug_print_msg(ssl, level, __FILE__, __LINE__, \
+ MBEDTLS_DEBUG_STRIP_PARENS args)
+
+#define MBEDTLS_SSL_DEBUG_RET(level, text, ret) \
+ mbedtls_debug_print_ret(ssl, level, __FILE__, __LINE__, text, ret)
+
+#define MBEDTLS_SSL_DEBUG_BUF(level, text, buf, len) \
+ mbedtls_debug_print_buf(ssl, level, __FILE__, __LINE__, text, buf, len)
+
+#if defined(MBEDTLS_BIGNUM_C)
+#define MBEDTLS_SSL_DEBUG_MPI(level, text, X) \
+ mbedtls_debug_print_mpi(ssl, level, __FILE__, __LINE__, text, X)
+#endif
+
+#if defined(MBEDTLS_ECP_C)
+#define MBEDTLS_SSL_DEBUG_ECP(level, text, X) \
+ mbedtls_debug_print_ecp(ssl, level, __FILE__, __LINE__, text, X)
+#endif
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+#if !defined(MBEDTLS_X509_REMOVE_INFO)
+#define MBEDTLS_SSL_DEBUG_CRT(level, text, crt) \
+ mbedtls_debug_print_crt(ssl, level, __FILE__, __LINE__, text, crt)
+#else
+#define MBEDTLS_SSL_DEBUG_CRT(level, text, crt) do { } while (0)
+#endif /* MBEDTLS_X509_REMOVE_INFO */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+#if defined(MBEDTLS_ECDH_C)
+#define MBEDTLS_SSL_DEBUG_ECDH(level, ecdh, attr) \
+ mbedtls_debug_printf_ecdh(ssl, level, __FILE__, __LINE__, ecdh, attr)
+#endif
+
+#else /* MBEDTLS_DEBUG_C */
+
+#define MBEDTLS_SSL_DEBUG_MSG(level, args) do { } while (0)
+#define MBEDTLS_SSL_DEBUG_RET(level, text, ret) do { } while (0)
+#define MBEDTLS_SSL_DEBUG_BUF(level, text, buf, len) do { } while (0)
+#define MBEDTLS_SSL_DEBUG_MPI(level, text, X) do { } while (0)
+#define MBEDTLS_SSL_DEBUG_ECP(level, text, X) do { } while (0)
+#define MBEDTLS_SSL_DEBUG_CRT(level, text, crt) do { } while (0)
+#define MBEDTLS_SSL_DEBUG_ECDH(level, ecdh, attr) do { } while (0)
+
+#endif /* MBEDTLS_DEBUG_C */
+
+/**
+ * \def MBEDTLS_PRINTF_ATTRIBUTE
+ *
+ * Mark a function as having printf attributes, and thus enable checking
+ * via -wFormat and other flags. This does nothing on builds with compilers
+ * that do not support the format attribute
+ *
+ * Module: library/debug.c
+ * Caller:
+ *
+ * This module provides debugging functions.
+ */
+#if defined(__has_attribute)
+#if __has_attribute(format)
+#if defined(__MINGW32__) && __USE_MINGW_ANSI_STDIO == 1
+#define MBEDTLS_PRINTF_ATTRIBUTE(string_index, first_to_check) \
+ __attribute__((__format__(gnu_printf, string_index, first_to_check)))
+#else /* defined(__MINGW32__) && __USE_MINGW_ANSI_STDIO == 1 */
+#define MBEDTLS_PRINTF_ATTRIBUTE(string_index, first_to_check) \
+ __attribute__((format(printf, string_index, first_to_check)))
+#endif
+#else /* __has_attribute(format) */
+#define MBEDTLS_PRINTF_ATTRIBUTE(string_index, first_to_check)
+#endif /* __has_attribute(format) */
+#else /* defined(__has_attribute) */
+#define MBEDTLS_PRINTF_ATTRIBUTE(string_index, first_to_check)
+#endif
+
+/**
+ * \def MBEDTLS_PRINTF_SIZET
+ *
+ * MBEDTLS_PRINTF_xxx: Due to issues with older window compilers
+ * and MinGW we need to define the printf specifier for size_t
+ * and long long per platform.
+ *
+ * Module: library/debug.c
+ * Caller:
+ *
+ * This module provides debugging functions.
+ */
+#if (defined(__MINGW32__) && __USE_MINGW_ANSI_STDIO == 0) || (defined(_MSC_VER) && _MSC_VER < 1800)
+ #include <inttypes.h>
+ #define MBEDTLS_PRINTF_SIZET PRIuPTR
+ #define MBEDTLS_PRINTF_LONGLONG "I64d"
+#else \
+ /* (defined(__MINGW32__) && __USE_MINGW_ANSI_STDIO == 0) || (defined(_MSC_VER) && _MSC_VER < 1800) */
+ #define MBEDTLS_PRINTF_SIZET "zu"
+ #define MBEDTLS_PRINTF_LONGLONG "lld"
+#endif \
+ /* (defined(__MINGW32__) && __USE_MINGW_ANSI_STDIO == 0) || (defined(_MSC_VER) && _MSC_VER < 1800) */
+
+#if !defined(MBEDTLS_PRINTF_MS_TIME)
+#define MBEDTLS_PRINTF_MS_TIME PRId64
+#endif /* MBEDTLS_PRINTF_MS_TIME */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Set the threshold error level to handle globally all debug output.
+ * Debug messages that have a level over the threshold value are
+ * discarded.
+ * (Default value: 0 = No debug )
+ *
+ * \param threshold threshold level of messages to filter on. Messages at a
+ * higher level will be discarded.
+ * - Debug levels
+ * - 0 No debug
+ * - 1 Error
+ * - 2 State change
+ * - 3 Informational
+ * - 4 Verbose
+ */
+void mbedtls_debug_set_threshold(int threshold);
+
+/**
+ * \brief Print a message to the debug output. This function is always used
+ * through the MBEDTLS_SSL_DEBUG_MSG() macro, which supplies the ssl
+ * context, file and line number parameters.
+ *
+ * \param ssl SSL context
+ * \param level error level of the debug message
+ * \param file file the message has occurred in
+ * \param line line number the message has occurred at
+ * \param format format specifier, in printf format
+ * \param ... variables used by the format specifier
+ *
+ * \attention This function is intended for INTERNAL usage within the
+ * library only.
+ */
+void mbedtls_debug_print_msg(const mbedtls_ssl_context *ssl, int level,
+ const char *file, int line,
+ const char *format, ...) MBEDTLS_PRINTF_ATTRIBUTE(5, 6);
+
+/**
+ * \brief Print the return value of a function to the debug output. This
+ * function is always used through the MBEDTLS_SSL_DEBUG_RET() macro,
+ * which supplies the ssl context, file and line number parameters.
+ *
+ * \param ssl SSL context
+ * \param level error level of the debug message
+ * \param file file the error has occurred in
+ * \param line line number the error has occurred in
+ * \param text the name of the function that returned the error
+ * \param ret the return code value
+ *
+ * \attention This function is intended for INTERNAL usage within the
+ * library only.
+ */
+void mbedtls_debug_print_ret(const mbedtls_ssl_context *ssl, int level,
+ const char *file, int line,
+ const char *text, int ret);
+
+/**
+ * \brief Output a buffer of size len bytes to the debug output. This function
+ * is always used through the MBEDTLS_SSL_DEBUG_BUF() macro,
+ * which supplies the ssl context, file and line number parameters.
+ *
+ * \param ssl SSL context
+ * \param level error level of the debug message
+ * \param file file the error has occurred in
+ * \param line line number the error has occurred in
+ * \param text a name or label for the buffer being dumped. Normally the
+ * variable or buffer name
+ * \param buf the buffer to be outputted
+ * \param len length of the buffer
+ *
+ * \attention This function is intended for INTERNAL usage within the
+ * library only.
+ */
+void mbedtls_debug_print_buf(const mbedtls_ssl_context *ssl, int level,
+ const char *file, int line, const char *text,
+ const unsigned char *buf, size_t len);
+
+#if defined(MBEDTLS_BIGNUM_C)
+/**
+ * \brief Print a MPI variable to the debug output. This function is always
+ * used through the MBEDTLS_SSL_DEBUG_MPI() macro, which supplies the
+ * ssl context, file and line number parameters.
+ *
+ * \param ssl SSL context
+ * \param level error level of the debug message
+ * \param file file the error has occurred in
+ * \param line line number the error has occurred in
+ * \param text a name or label for the MPI being output. Normally the
+ * variable name
+ * \param X the MPI variable
+ *
+ * \attention This function is intended for INTERNAL usage within the
+ * library only.
+ */
+void mbedtls_debug_print_mpi(const mbedtls_ssl_context *ssl, int level,
+ const char *file, int line,
+ const char *text, const mbedtls_mpi *X);
+#endif
+
+#if defined(MBEDTLS_ECP_C)
+/**
+ * \brief Print an ECP point to the debug output. This function is always
+ * used through the MBEDTLS_SSL_DEBUG_ECP() macro, which supplies the
+ * ssl context, file and line number parameters.
+ *
+ * \param ssl SSL context
+ * \param level error level of the debug message
+ * \param file file the error has occurred in
+ * \param line line number the error has occurred in
+ * \param text a name or label for the ECP point being output. Normally the
+ * variable name
+ * \param X the ECP point
+ *
+ * \attention This function is intended for INTERNAL usage within the
+ * library only.
+ */
+void mbedtls_debug_print_ecp(const mbedtls_ssl_context *ssl, int level,
+ const char *file, int line,
+ const char *text, const mbedtls_ecp_point *X);
+#endif
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C) && !defined(MBEDTLS_X509_REMOVE_INFO)
+/**
+ * \brief Print a X.509 certificate structure to the debug output. This
+ * function is always used through the MBEDTLS_SSL_DEBUG_CRT() macro,
+ * which supplies the ssl context, file and line number parameters.
+ *
+ * \param ssl SSL context
+ * \param level error level of the debug message
+ * \param file file the error has occurred in
+ * \param line line number the error has occurred in
+ * \param text a name or label for the certificate being output
+ * \param crt X.509 certificate structure
+ *
+ * \attention This function is intended for INTERNAL usage within the
+ * library only.
+ */
+void mbedtls_debug_print_crt(const mbedtls_ssl_context *ssl, int level,
+ const char *file, int line,
+ const char *text, const mbedtls_x509_crt *crt);
+#endif
+
+/* Note: the MBEDTLS_ECDH_C guard here is mandatory because this debug function
+ only works for the built-in implementation. */
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_ANY_ENABLED) && \
+ defined(MBEDTLS_ECDH_C)
+typedef enum {
+ MBEDTLS_DEBUG_ECDH_Q,
+ MBEDTLS_DEBUG_ECDH_QP,
+ MBEDTLS_DEBUG_ECDH_Z,
+} mbedtls_debug_ecdh_attr;
+
+/**
+ * \brief Print a field of the ECDH structure in the SSL context to the debug
+ * output. This function is always used through the
+ * MBEDTLS_SSL_DEBUG_ECDH() macro, which supplies the ssl context, file
+ * and line number parameters.
+ *
+ * \param ssl SSL context
+ * \param level error level of the debug message
+ * \param file file the error has occurred in
+ * \param line line number the error has occurred in
+ * \param ecdh the ECDH context
+ * \param attr the identifier of the attribute being output
+ *
+ * \attention This function is intended for INTERNAL usage within the
+ * library only.
+ */
+void mbedtls_debug_printf_ecdh(const mbedtls_ssl_context *ssl, int level,
+ const char *file, int line,
+ const mbedtls_ecdh_context *ecdh,
+ mbedtls_debug_ecdh_attr attr);
+#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_ANY_ENABLED &&
+ MBEDTLS_ECDH_C */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* debug.h */
diff --git a/include/mbedtls/des.h b/include/mbedtls/des.h
new file mode 100644
index 0000000..2b097a1
--- /dev/null
+++ b/include/mbedtls/des.h
@@ -0,0 +1,385 @@
+/**
+ * \file des.h
+ *
+ * \brief DES block cipher
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ *
+ */
+#ifndef MBEDTLS_DES_H
+#define MBEDTLS_DES_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+#include "mbedtls/platform_util.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#define MBEDTLS_DES_ENCRYPT 1
+#define MBEDTLS_DES_DECRYPT 0
+
+/** The data input has an invalid length. */
+#define MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH -0x0032
+
+#define MBEDTLS_DES_KEY_SIZE 8
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_DES_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief DES context structure
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+typedef struct mbedtls_des_context {
+ uint32_t MBEDTLS_PRIVATE(sk)[32]; /*!< DES subkeys */
+}
+mbedtls_des_context;
+
+/**
+ * \brief Triple-DES context structure
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+typedef struct mbedtls_des3_context {
+ uint32_t MBEDTLS_PRIVATE(sk)[96]; /*!< 3DES subkeys */
+}
+mbedtls_des3_context;
+
+#else /* MBEDTLS_DES_ALT */
+#include "des_alt.h"
+#endif /* MBEDTLS_DES_ALT */
+
+/**
+ * \brief Initialize DES context
+ *
+ * \param ctx DES context to be initialized
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+void mbedtls_des_init(mbedtls_des_context *ctx);
+
+/**
+ * \brief Clear DES context
+ *
+ * \param ctx DES context to be cleared
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+void mbedtls_des_free(mbedtls_des_context *ctx);
+
+/**
+ * \brief Initialize Triple-DES context
+ *
+ * \param ctx DES3 context to be initialized
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+void mbedtls_des3_init(mbedtls_des3_context *ctx);
+
+/**
+ * \brief Clear Triple-DES context
+ *
+ * \param ctx DES3 context to be cleared
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+void mbedtls_des3_free(mbedtls_des3_context *ctx);
+
+/**
+ * \brief Set key parity on the given key to odd.
+ *
+ * DES keys are 56 bits long, but each byte is padded with
+ * a parity bit to allow verification.
+ *
+ * \param key 8-byte secret key
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+void mbedtls_des_key_set_parity(unsigned char key[MBEDTLS_DES_KEY_SIZE]);
+
+/**
+ * \brief Check that key parity on the given key is odd.
+ *
+ * DES keys are 56 bits long, but each byte is padded with
+ * a parity bit to allow verification.
+ *
+ * \param key 8-byte secret key
+ *
+ * \return 0 is parity was ok, 1 if parity was not correct.
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des_key_check_key_parity(const unsigned char key[MBEDTLS_DES_KEY_SIZE]);
+
+/**
+ * \brief Check that key is not a weak or semi-weak DES key
+ *
+ * \param key 8-byte secret key
+ *
+ * \return 0 if no weak key was found, 1 if a weak key was identified.
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des_key_check_weak(const unsigned char key[MBEDTLS_DES_KEY_SIZE]);
+
+/**
+ * \brief DES key schedule (56-bit, encryption)
+ *
+ * \param ctx DES context to be initialized
+ * \param key 8-byte secret key
+ *
+ * \return 0
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des_setkey_enc(mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE]);
+
+/**
+ * \brief DES key schedule (56-bit, decryption)
+ *
+ * \param ctx DES context to be initialized
+ * \param key 8-byte secret key
+ *
+ * \return 0
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des_setkey_dec(mbedtls_des_context *ctx, const unsigned char key[MBEDTLS_DES_KEY_SIZE]);
+
+/**
+ * \brief Triple-DES key schedule (112-bit, encryption)
+ *
+ * \param ctx 3DES context to be initialized
+ * \param key 16-byte secret key
+ *
+ * \return 0
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des3_set2key_enc(mbedtls_des3_context *ctx,
+ const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2]);
+
+/**
+ * \brief Triple-DES key schedule (112-bit, decryption)
+ *
+ * \param ctx 3DES context to be initialized
+ * \param key 16-byte secret key
+ *
+ * \return 0
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des3_set2key_dec(mbedtls_des3_context *ctx,
+ const unsigned char key[MBEDTLS_DES_KEY_SIZE * 2]);
+
+/**
+ * \brief Triple-DES key schedule (168-bit, encryption)
+ *
+ * \param ctx 3DES context to be initialized
+ * \param key 24-byte secret key
+ *
+ * \return 0
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des3_set3key_enc(mbedtls_des3_context *ctx,
+ const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3]);
+
+/**
+ * \brief Triple-DES key schedule (168-bit, decryption)
+ *
+ * \param ctx 3DES context to be initialized
+ * \param key 24-byte secret key
+ *
+ * \return 0
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des3_set3key_dec(mbedtls_des3_context *ctx,
+ const unsigned char key[MBEDTLS_DES_KEY_SIZE * 3]);
+
+/**
+ * \brief DES-ECB block encryption/decryption
+ *
+ * \param ctx DES context
+ * \param input 64-bit input block
+ * \param output 64-bit output block
+ *
+ * \return 0 if successful
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des_crypt_ecb(mbedtls_des_context *ctx,
+ const unsigned char input[8],
+ unsigned char output[8]);
+
+#if defined(MBEDTLS_CIPHER_MODE_CBC)
+/**
+ * \brief DES-CBC buffer encryption/decryption
+ *
+ * \note Upon exit, the content of the IV is updated so that you can
+ * call the function same function again on the following
+ * block(s) of data and get the same result as if it was
+ * encrypted in one call. This allows a "streaming" usage.
+ * If on the other hand you need to retain the contents of the
+ * IV, you should either save it manually or use the cipher
+ * module instead.
+ *
+ * \param ctx DES context
+ * \param mode MBEDTLS_DES_ENCRYPT or MBEDTLS_DES_DECRYPT
+ * \param length length of the input data
+ * \param iv initialization vector (updated after use)
+ * \param input buffer holding the input data
+ * \param output buffer holding the output data
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des_crypt_cbc(mbedtls_des_context *ctx,
+ int mode,
+ size_t length,
+ unsigned char iv[8],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_CBC */
+
+/**
+ * \brief 3DES-ECB block encryption/decryption
+ *
+ * \param ctx 3DES context
+ * \param input 64-bit input block
+ * \param output 64-bit output block
+ *
+ * \return 0 if successful
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des3_crypt_ecb(mbedtls_des3_context *ctx,
+ const unsigned char input[8],
+ unsigned char output[8]);
+
+#if defined(MBEDTLS_CIPHER_MODE_CBC)
+/**
+ * \brief 3DES-CBC buffer encryption/decryption
+ *
+ * \note Upon exit, the content of the IV is updated so that you can
+ * call the function same function again on the following
+ * block(s) of data and get the same result as if it was
+ * encrypted in one call. This allows a "streaming" usage.
+ * If on the other hand you need to retain the contents of the
+ * IV, you should either save it manually or use the cipher
+ * module instead.
+ *
+ * \param ctx 3DES context
+ * \param mode MBEDTLS_DES_ENCRYPT or MBEDTLS_DES_DECRYPT
+ * \param length length of the input data
+ * \param iv initialization vector (updated after use)
+ * \param input buffer holding the input data
+ * \param output buffer holding the output data
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_DES_INVALID_INPUT_LENGTH
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_des3_crypt_cbc(mbedtls_des3_context *ctx,
+ int mode,
+ size_t length,
+ unsigned char iv[8],
+ const unsigned char *input,
+ unsigned char *output);
+#endif /* MBEDTLS_CIPHER_MODE_CBC */
+
+/**
+ * \brief Internal function for key expansion.
+ * (Only exposed to allow overriding it,
+ * see MBEDTLS_DES_SETKEY_ALT)
+ *
+ * \param SK Round keys
+ * \param key Base key
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers
+ * instead.
+ */
+void mbedtls_des_setkey(uint32_t SK[32],
+ const unsigned char key[MBEDTLS_DES_KEY_SIZE]);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if the test failed
+ */
+MBEDTLS_CHECK_RETURN_CRITICAL
+int mbedtls_des_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* des.h */
diff --git a/include/mbedtls/dhm.h b/include/mbedtls/dhm.h
new file mode 100644
index 0000000..fcba3d2
--- /dev/null
+++ b/include/mbedtls/dhm.h
@@ -0,0 +1,972 @@
+/**
+ * \file dhm.h
+ *
+ * \brief This file contains Diffie-Hellman-Merkle (DHM) key exchange
+ * definitions and functions.
+ *
+ * Diffie-Hellman-Merkle (DHM) key exchange is defined in
+ * <em>RFC-2631: Diffie-Hellman Key Agreement Method</em> and
+ * <em>Public-Key Cryptography Standards (PKCS) #3: Diffie
+ * Hellman Key Agreement Standard</em>.
+ *
+ * <em>RFC-3526: More Modular Exponential (MODP) Diffie-Hellman groups for
+ * Internet Key Exchange (IKE)</em> defines a number of standardized
+ * Diffie-Hellman groups for IKE.
+ *
+ * <em>RFC-5114: Additional Diffie-Hellman Groups for Use with IETF
+ * Standards</em> defines a number of standardized Diffie-Hellman
+ * groups that can be used.
+ *
+ * \warning The security of the DHM key exchange relies on the proper choice
+ * of prime modulus - optimally, it should be a safe prime. The usage
+ * of non-safe primes both decreases the difficulty of the underlying
+ * discrete logarithm problem and can lead to small subgroup attacks
+ * leaking private exponent bits when invalid public keys are used
+ * and not detected. This is especially relevant if the same DHM
+ * parameters are reused for multiple key exchanges as in static DHM,
+ * while the criticality of small-subgroup attacks is lower for
+ * ephemeral DHM.
+ *
+ * \warning For performance reasons, the code does neither perform primality
+ * nor safe primality tests, nor the expensive checks for invalid
+ * subgroups. Moreover, even if these were performed, non-standardized
+ * primes cannot be trusted because of the possibility of backdoors
+ * that can't be effectively checked for.
+ *
+ * \warning Diffie-Hellman-Merkle is therefore a security risk when not using
+ * standardized primes generated using a trustworthy ("nothing up
+ * my sleeve") method, such as the RFC 3526 / 7919 primes. In the TLS
+ * protocol, DH parameters need to be negotiated, so using the default
+ * primes systematically is not always an option. If possible, use
+ * Elliptic Curve Diffie-Hellman (ECDH), which has better performance,
+ * and for which the TLS protocol mandates the use of standard
+ * parameters.
+ *
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_DHM_H
+#define MBEDTLS_DHM_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+#include "mbedtls/bignum.h"
+
+/*
+ * DHM Error codes
+ */
+/** Bad input parameters. */
+#define MBEDTLS_ERR_DHM_BAD_INPUT_DATA -0x3080
+/** Reading of the DHM parameters failed. */
+#define MBEDTLS_ERR_DHM_READ_PARAMS_FAILED -0x3100
+/** Making of the DHM parameters failed. */
+#define MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED -0x3180
+/** Reading of the public values failed. */
+#define MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED -0x3200
+/** Making of the public value failed. */
+#define MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED -0x3280
+/** Calculation of the DHM secret failed. */
+#define MBEDTLS_ERR_DHM_CALC_SECRET_FAILED -0x3300
+/** The ASN.1 data is not formatted correctly. */
+#define MBEDTLS_ERR_DHM_INVALID_FORMAT -0x3380
+/** Allocation of memory failed. */
+#define MBEDTLS_ERR_DHM_ALLOC_FAILED -0x3400
+/** Read or write of file failed. */
+#define MBEDTLS_ERR_DHM_FILE_IO_ERROR -0x3480
+/** Setting the modulus and generator failed. */
+#define MBEDTLS_ERR_DHM_SET_GROUP_FAILED -0x3580
+
+/** Which parameter to access in mbedtls_dhm_get_value(). */
+typedef enum {
+ MBEDTLS_DHM_PARAM_P, /*!< The prime modulus. */
+ MBEDTLS_DHM_PARAM_G, /*!< The generator. */
+ MBEDTLS_DHM_PARAM_X, /*!< Our secret value. */
+ MBEDTLS_DHM_PARAM_GX, /*!< Our public key = \c G^X mod \c P. */
+ MBEDTLS_DHM_PARAM_GY, /*!< The public key of the peer = \c G^Y mod \c P. */
+ MBEDTLS_DHM_PARAM_K, /*!< The shared secret = \c G^(XY) mod \c P. */
+} mbedtls_dhm_parameter;
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_DHM_ALT)
+
+/**
+ * \brief The DHM context structure.
+ */
+typedef struct mbedtls_dhm_context {
+ mbedtls_mpi MBEDTLS_PRIVATE(P); /*!< The prime modulus. */
+ mbedtls_mpi MBEDTLS_PRIVATE(G); /*!< The generator. */
+ mbedtls_mpi MBEDTLS_PRIVATE(X); /*!< Our secret value. */
+ mbedtls_mpi MBEDTLS_PRIVATE(GX); /*!< Our public key = \c G^X mod \c P. */
+ mbedtls_mpi MBEDTLS_PRIVATE(GY); /*!< The public key of the peer = \c G^Y mod \c P. */
+ mbedtls_mpi MBEDTLS_PRIVATE(K); /*!< The shared secret = \c G^(XY) mod \c P. */
+ mbedtls_mpi MBEDTLS_PRIVATE(RP); /*!< The cached value = \c R^2 mod \c P. */
+ mbedtls_mpi MBEDTLS_PRIVATE(Vi); /*!< The blinding value. */
+ mbedtls_mpi MBEDTLS_PRIVATE(Vf); /*!< The unblinding value. */
+ mbedtls_mpi MBEDTLS_PRIVATE(pX); /*!< The previous \c X. */
+}
+mbedtls_dhm_context;
+
+#else /* MBEDTLS_DHM_ALT */
+#include "dhm_alt.h"
+#endif /* MBEDTLS_DHM_ALT */
+
+/**
+ * \brief This function initializes the DHM context.
+ *
+ * \param ctx The DHM context to initialize.
+ */
+void mbedtls_dhm_init(mbedtls_dhm_context *ctx);
+
+/**
+ * \brief This function parses the DHM parameters in a
+ * TLS ServerKeyExchange handshake message
+ * (DHM modulus, generator, and public key).
+ *
+ * \note In a TLS handshake, this is the how the client
+ * sets up its DHM context from the server's public
+ * DHM key material.
+ *
+ * \param ctx The DHM context to use. This must be initialized.
+ * \param p On input, *p must be the start of the input buffer.
+ * On output, *p is updated to point to the end of the data
+ * that has been read. On success, this is the first byte
+ * past the end of the ServerKeyExchange parameters.
+ * On error, this is the point at which an error has been
+ * detected, which is usually not useful except to debug
+ * failures.
+ * \param end The end of the input buffer.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure.
+ */
+int mbedtls_dhm_read_params(mbedtls_dhm_context *ctx,
+ unsigned char **p,
+ const unsigned char *end);
+
+/**
+ * \brief This function generates a DHM key pair and exports its
+ * public part together with the DHM parameters in the format
+ * used in a TLS ServerKeyExchange handshake message.
+ *
+ * \note This function assumes that the DHM parameters \c ctx->P
+ * and \c ctx->G have already been properly set. For that, use
+ * mbedtls_dhm_set_group() below in conjunction with
+ * mbedtls_mpi_read_binary() and mbedtls_mpi_read_string().
+ *
+ * \note In a TLS handshake, this is the how the server generates
+ * and exports its DHM key material.
+ *
+ * \param ctx The DHM context to use. This must be initialized
+ * and have the DHM parameters set. It may or may not
+ * already have imported the peer's public key.
+ * \param x_size The private key size in Bytes.
+ * \param olen The address at which to store the number of Bytes
+ * written on success. This must not be \c NULL.
+ * \param output The destination buffer. This must be a writable buffer of
+ * sufficient size to hold the reduced binary presentation of
+ * the modulus, the generator and the public key, each wrapped
+ * with a 2-byte length field. It is the responsibility of the
+ * caller to ensure that enough space is available. Refer to
+ * mbedtls_mpi_size() to computing the byte-size of an MPI.
+ * \param f_rng The RNG function. Must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context parameter.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure.
+ */
+int mbedtls_dhm_make_params(mbedtls_dhm_context *ctx, int x_size,
+ unsigned char *output, size_t *olen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function sets the prime modulus and generator.
+ *
+ * \note This function can be used to set \c ctx->P, \c ctx->G
+ * in preparation for mbedtls_dhm_make_params().
+ *
+ * \param ctx The DHM context to configure. This must be initialized.
+ * \param P The MPI holding the DHM prime modulus. This must be
+ * an initialized MPI.
+ * \param G The MPI holding the DHM generator. This must be an
+ * initialized MPI.
+ *
+ * \return \c 0 if successful.
+ * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure.
+ */
+int mbedtls_dhm_set_group(mbedtls_dhm_context *ctx,
+ const mbedtls_mpi *P,
+ const mbedtls_mpi *G);
+
+/**
+ * \brief This function imports the raw public value of the peer.
+ *
+ * \note In a TLS handshake, this is the how the server imports
+ * the Client's public DHM key.
+ *
+ * \param ctx The DHM context to use. This must be initialized and have
+ * its DHM parameters set, e.g. via mbedtls_dhm_set_group().
+ * It may or may not already have generated its own private key.
+ * \param input The input buffer containing the \c G^Y value of the peer.
+ * This must be a readable buffer of size \p ilen Bytes.
+ * \param ilen The size of the input buffer \p input in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure.
+ */
+int mbedtls_dhm_read_public(mbedtls_dhm_context *ctx,
+ const unsigned char *input, size_t ilen);
+
+/**
+ * \brief This function creates a DHM key pair and exports
+ * the raw public key in big-endian format.
+ *
+ * \note The destination buffer is always fully written
+ * so as to contain a big-endian representation of G^X mod P.
+ * If it is larger than \c ctx->len, it is padded accordingly
+ * with zero-bytes at the beginning.
+ *
+ * \param ctx The DHM context to use. This must be initialized and
+ * have the DHM parameters set. It may or may not already
+ * have imported the peer's public key.
+ * \param x_size The private key size in Bytes.
+ * \param output The destination buffer. This must be a writable buffer of
+ * size \p olen Bytes.
+ * \param olen The length of the destination buffer. This must be at least
+ * equal to `ctx->len` (the size of \c P).
+ * \param f_rng The RNG function. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL
+ * if \p f_rng doesn't need a context argument.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure.
+ */
+int mbedtls_dhm_make_public(mbedtls_dhm_context *ctx, int x_size,
+ unsigned char *output, size_t olen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function derives and exports the shared secret
+ * \c (G^Y)^X mod \c P.
+ *
+ * \note If \p f_rng is not \c NULL, it is used to blind the input as
+ * a countermeasure against timing attacks. Blinding is used
+ * only if our private key \c X is re-used, and not used
+ * otherwise. We recommend always passing a non-NULL
+ * \p f_rng argument.
+ *
+ * \param ctx The DHM context to use. This must be initialized
+ * and have its own private key generated and the peer's
+ * public key imported.
+ * \param output The buffer to write the generated shared key to. This
+ * must be a writable buffer of size \p output_size Bytes.
+ * \param output_size The size of the destination buffer. This must be at
+ * least the size of \c ctx->len (the size of \c P).
+ * \param olen On exit, holds the actual number of Bytes written.
+ * \param f_rng The RNG function. Must not be \c NULL. Used for
+ * blinding.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context parameter.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure.
+ */
+int mbedtls_dhm_calc_secret(mbedtls_dhm_context *ctx,
+ unsigned char *output, size_t output_size, size_t *olen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function returns the size of the prime modulus in bits.
+ *
+ * \param ctx The DHM context to query.
+ *
+ * \return The size of the prime modulus in bits,
+ * i.e. the number n such that 2^(n-1) <= P < 2^n.
+ */
+size_t mbedtls_dhm_get_bitlen(const mbedtls_dhm_context *ctx);
+
+/**
+ * \brief This function returns the size of the prime modulus in bytes.
+ *
+ * \param ctx The DHM context to query.
+ *
+ * \return The size of the prime modulus in bytes,
+ * i.e. the number n such that 2^(8*(n-1)) <= P < 2^(8*n).
+ */
+size_t mbedtls_dhm_get_len(const mbedtls_dhm_context *ctx);
+
+/**
+ * \brief This function copies a parameter of a DHM key.
+ *
+ * \param ctx The DHM context to query.
+ * \param param The parameter to copy.
+ * \param dest The MPI object to copy the value into. It must be
+ * initialized.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_DHM_BAD_INPUT_DATA if \p param is invalid.
+ * \return An \c MBEDTLS_ERR_MPI_XXX error code if the copy fails.
+ */
+int mbedtls_dhm_get_value(const mbedtls_dhm_context *ctx,
+ mbedtls_dhm_parameter param,
+ mbedtls_mpi *dest);
+
+/**
+ * \brief This function frees and clears the components
+ * of a DHM context.
+ *
+ * \param ctx The DHM context to free and clear. This may be \c NULL,
+ * in which case this function is a no-op. If it is not \c NULL,
+ * it must point to an initialized DHM context.
+ */
+void mbedtls_dhm_free(mbedtls_dhm_context *ctx);
+
+#if defined(MBEDTLS_ASN1_PARSE_C)
+/**
+ * \brief This function parses DHM parameters in PEM or DER format.
+ *
+ * \param dhm The DHM context to import the DHM parameters into.
+ * This must be initialized.
+ * \param dhmin The input buffer. This must be a readable buffer of
+ * length \p dhminlen Bytes.
+ * \param dhminlen The size of the input buffer \p dhmin, including the
+ * terminating \c NULL Byte for PEM data.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_DHM_XXX or \c MBEDTLS_ERR_PEM_XXX error
+ * code on failure.
+ */
+int mbedtls_dhm_parse_dhm(mbedtls_dhm_context *dhm, const unsigned char *dhmin,
+ size_t dhminlen);
+
+#if defined(MBEDTLS_FS_IO)
+/**
+ * \brief This function loads and parses DHM parameters from a file.
+ *
+ * \param dhm The DHM context to load the parameters to.
+ * This must be initialized.
+ * \param path The filename to read the DHM parameters from.
+ * This must not be \c NULL.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_DHM_XXX or \c MBEDTLS_ERR_PEM_XXX
+ * error code on failure.
+ */
+int mbedtls_dhm_parse_dhmfile(mbedtls_dhm_context *dhm, const char *path);
+#endif /* MBEDTLS_FS_IO */
+#endif /* MBEDTLS_ASN1_PARSE_C */
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief The DMH checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_dhm_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+#ifdef __cplusplus
+}
+#endif
+
+/**
+ * RFC 3526, RFC 5114 and RFC 7919 standardize a number of
+ * Diffie-Hellman groups, some of which are included here
+ * for use within the SSL/TLS module and the user's convenience
+ * when configuring the Diffie-Hellman parameters by hand
+ * through \c mbedtls_ssl_conf_dh_param.
+ *
+ * The following lists the source of the above groups in the standards:
+ * - RFC 5114 section 2.2: 2048-bit MODP Group with 224-bit Prime Order Subgroup
+ * - RFC 3526 section 3: 2048-bit MODP Group
+ * - RFC 3526 section 4: 3072-bit MODP Group
+ * - RFC 3526 section 5: 4096-bit MODP Group
+ * - RFC 7919 section A.1: ffdhe2048
+ * - RFC 7919 section A.2: ffdhe3072
+ * - RFC 7919 section A.3: ffdhe4096
+ * - RFC 7919 section A.4: ffdhe6144
+ * - RFC 7919 section A.5: ffdhe8192
+ *
+ * The constants with suffix "_p" denote the chosen prime moduli, while
+ * the constants with suffix "_g" denote the chosen generator
+ * of the associated prime field.
+ *
+ * The constants further suffixed with "_bin" are provided in binary format,
+ * while all other constants represent null-terminated strings holding the
+ * hexadecimal presentation of the respective numbers.
+ *
+ * The primes from RFC 3526 and RFC 7919 have been generating by the following
+ * trust-worthy procedure:
+ * - Fix N in { 2048, 3072, 4096, 6144, 8192 } and consider the N-bit number
+ * the first and last 64 bits are all 1, and the remaining N - 128 bits of
+ * which are 0x7ff...ff.
+ * - Add the smallest multiple of the first N - 129 bits of the binary expansion
+ * of pi (for RFC 5236) or e (for RFC 7919) to this intermediate bit-string
+ * such that the resulting integer is a safe-prime.
+ * - The result is the respective RFC 3526 / 7919 prime, and the corresponding
+ * generator is always chosen to be 2 (which is a square for these prime,
+ * hence the corresponding subgroup has order (p-1)/2 and avoids leaking a
+ * bit in the private exponent).
+ *
+ */
+
+/*
+ * Trustworthy DHM parameters in binary form
+ */
+
+#define MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN { \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+ 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \
+ 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \
+ 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \
+ 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \
+ 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \
+ 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \
+ 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \
+ 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \
+ 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \
+ 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \
+ 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \
+ 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \
+ 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \
+ 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \
+ 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \
+ 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \
+ 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \
+ 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \
+ 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \
+ 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \
+ 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \
+ 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \
+ 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \
+ 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \
+ 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \
+ 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \
+ 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \
+ 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \
+ 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \
+ 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC3526_MODP_3072_P_BIN { \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+ 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \
+ 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \
+ 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \
+ 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \
+ 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \
+ 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \
+ 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \
+ 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \
+ 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \
+ 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \
+ 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \
+ 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \
+ 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \
+ 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \
+ 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \
+ 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \
+ 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \
+ 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \
+ 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \
+ 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \
+ 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \
+ 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \
+ 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \
+ 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \
+ 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \
+ 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \
+ 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \
+ 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \
+ 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \
+ 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \
+ 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \
+ 0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \
+ 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \
+ 0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \
+ 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \
+ 0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \
+ 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \
+ 0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \
+ 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \
+ 0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \
+ 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \
+ 0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \
+ 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \
+ 0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \
+ 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \
+ 0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x3A, 0xD2, 0xCA, \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC3526_MODP_3072_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC3526_MODP_4096_P_BIN { \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+ 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \
+ 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \
+ 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \
+ 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \
+ 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \
+ 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \
+ 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \
+ 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \
+ 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \
+ 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \
+ 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \
+ 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \
+ 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \
+ 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \
+ 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \
+ 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \
+ 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \
+ 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \
+ 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \
+ 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \
+ 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \
+ 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \
+ 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \
+ 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \
+ 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \
+ 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \
+ 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \
+ 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \
+ 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \
+ 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \
+ 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \
+ 0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \
+ 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \
+ 0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \
+ 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \
+ 0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \
+ 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \
+ 0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \
+ 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \
+ 0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \
+ 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \
+ 0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \
+ 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \
+ 0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \
+ 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \
+ 0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01, \
+ 0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7, \
+ 0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26, \
+ 0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C, \
+ 0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA, \
+ 0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8, \
+ 0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9, \
+ 0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6, \
+ 0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D, \
+ 0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2, \
+ 0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED, \
+ 0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF, \
+ 0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C, \
+ 0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9, \
+ 0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1, \
+ 0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F, \
+ 0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99, \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC3526_MODP_4096_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE2048_P_BIN { \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE2048_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE3072_P_BIN { \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0xC6, 0x2E, 0x37, \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE3072_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE4096_P_BIN { \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \
+ 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \
+ 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \
+ 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \
+ 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \
+ 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \
+ 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \
+ 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \
+ 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \
+ 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \
+ 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \
+ 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \
+ 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \
+ 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \
+ 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \
+ 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \
+ 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x65, 0x5F, 0x6A, \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE4096_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE6144_P_BIN { \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \
+ 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \
+ 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \
+ 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \
+ 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \
+ 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \
+ 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \
+ 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \
+ 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \
+ 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \
+ 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \
+ 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \
+ 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \
+ 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \
+ 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \
+ 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \
+ 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \
+ 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \
+ 0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \
+ 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \
+ 0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \
+ 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \
+ 0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \
+ 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \
+ 0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \
+ 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \
+ 0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \
+ 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \
+ 0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \
+ 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \
+ 0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \
+ 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \
+ 0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \
+ 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \
+ 0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \
+ 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \
+ 0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \
+ 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \
+ 0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \
+ 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \
+ 0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \
+ 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \
+ 0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \
+ 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \
+ 0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \
+ 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \
+ 0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \
+ 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \
+ 0xA4, 0x0E, 0x32, 0x9C, 0xD0, 0xE4, 0x0E, 0x65, \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE6144_G_BIN { 0x02 }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE8192_P_BIN { \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \
+ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \
+ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \
+ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \
+ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \
+ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \
+ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \
+ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \
+ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \
+ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \
+ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \
+ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \
+ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \
+ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \
+ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \
+ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \
+ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \
+ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \
+ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \
+ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \
+ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \
+ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \
+ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \
+ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \
+ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \
+ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \
+ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \
+ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \
+ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \
+ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \
+ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \
+ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \
+ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \
+ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \
+ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \
+ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \
+ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \
+ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \
+ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \
+ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \
+ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \
+ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \
+ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \
+ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \
+ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \
+ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \
+ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \
+ 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \
+ 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \
+ 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \
+ 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \
+ 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \
+ 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \
+ 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \
+ 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \
+ 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \
+ 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \
+ 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \
+ 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \
+ 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \
+ 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \
+ 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \
+ 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \
+ 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \
+ 0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \
+ 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \
+ 0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \
+ 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \
+ 0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \
+ 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \
+ 0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \
+ 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \
+ 0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \
+ 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \
+ 0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \
+ 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \
+ 0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \
+ 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \
+ 0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \
+ 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \
+ 0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \
+ 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \
+ 0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \
+ 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \
+ 0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \
+ 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \
+ 0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \
+ 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \
+ 0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \
+ 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \
+ 0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \
+ 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \
+ 0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \
+ 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \
+ 0xA4, 0x0E, 0x32, 0x9C, 0xCF, 0xF4, 0x6A, 0xAA, \
+ 0x36, 0xAD, 0x00, 0x4C, 0xF6, 0x00, 0xC8, 0x38, \
+ 0x1E, 0x42, 0x5A, 0x31, 0xD9, 0x51, 0xAE, 0x64, \
+ 0xFD, 0xB2, 0x3F, 0xCE, 0xC9, 0x50, 0x9D, 0x43, \
+ 0x68, 0x7F, 0xEB, 0x69, 0xED, 0xD1, 0xCC, 0x5E, \
+ 0x0B, 0x8C, 0xC3, 0xBD, 0xF6, 0x4B, 0x10, 0xEF, \
+ 0x86, 0xB6, 0x31, 0x42, 0xA3, 0xAB, 0x88, 0x29, \
+ 0x55, 0x5B, 0x2F, 0x74, 0x7C, 0x93, 0x26, 0x65, \
+ 0xCB, 0x2C, 0x0F, 0x1C, 0xC0, 0x1B, 0xD7, 0x02, \
+ 0x29, 0x38, 0x88, 0x39, 0xD2, 0xAF, 0x05, 0xE4, \
+ 0x54, 0x50, 0x4A, 0xC7, 0x8B, 0x75, 0x82, 0x82, \
+ 0x28, 0x46, 0xC0, 0xBA, 0x35, 0xC3, 0x5F, 0x5C, \
+ 0x59, 0x16, 0x0C, 0xC0, 0x46, 0xFD, 0x82, 0x51, \
+ 0x54, 0x1F, 0xC6, 0x8C, 0x9C, 0x86, 0xB0, 0x22, \
+ 0xBB, 0x70, 0x99, 0x87, 0x6A, 0x46, 0x0E, 0x74, \
+ 0x51, 0xA8, 0xA9, 0x31, 0x09, 0x70, 0x3F, 0xEE, \
+ 0x1C, 0x21, 0x7E, 0x6C, 0x38, 0x26, 0xE5, 0x2C, \
+ 0x51, 0xAA, 0x69, 0x1E, 0x0E, 0x42, 0x3C, 0xFC, \
+ 0x99, 0xE9, 0xE3, 0x16, 0x50, 0xC1, 0x21, 0x7B, \
+ 0x62, 0x48, 0x16, 0xCD, 0xAD, 0x9A, 0x95, 0xF9, \
+ 0xD5, 0xB8, 0x01, 0x94, 0x88, 0xD9, 0xC0, 0xA0, \
+ 0xA1, 0xFE, 0x30, 0x75, 0xA5, 0x77, 0xE2, 0x31, \
+ 0x83, 0xF8, 0x1D, 0x4A, 0x3F, 0x2F, 0xA4, 0x57, \
+ 0x1E, 0xFC, 0x8C, 0xE0, 0xBA, 0x8A, 0x4F, 0xE8, \
+ 0xB6, 0x85, 0x5D, 0xFE, 0x72, 0xB0, 0xA6, 0x6E, \
+ 0xDE, 0xD2, 0xFB, 0xAB, 0xFB, 0xE5, 0x8A, 0x30, \
+ 0xFA, 0xFA, 0xBE, 0x1C, 0x5D, 0x71, 0xA8, 0x7E, \
+ 0x2F, 0x74, 0x1E, 0xF8, 0xC1, 0xFE, 0x86, 0xFE, \
+ 0xA6, 0xBB, 0xFD, 0xE5, 0x30, 0x67, 0x7F, 0x0D, \
+ 0x97, 0xD1, 0x1D, 0x49, 0xF7, 0xA8, 0x44, 0x3D, \
+ 0x08, 0x22, 0xE5, 0x06, 0xA9, 0xF4, 0x61, 0x4E, \
+ 0x01, 0x1E, 0x2A, 0x94, 0x83, 0x8F, 0xF8, 0x8C, \
+ 0xD6, 0x8C, 0x8B, 0xB7, 0xC5, 0xC6, 0x42, 0x4C, \
+ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF }
+
+#define MBEDTLS_DHM_RFC7919_FFDHE8192_G_BIN { 0x02 }
+
+#endif /* dhm.h */
diff --git a/include/mbedtls/ecdh.h b/include/mbedtls/ecdh.h
new file mode 100644
index 0000000..792db79
--- /dev/null
+++ b/include/mbedtls/ecdh.h
@@ -0,0 +1,441 @@
+/**
+ * \file ecdh.h
+ *
+ * \brief This file contains ECDH definitions and functions.
+ *
+ * The Elliptic Curve Diffie-Hellman (ECDH) protocol is an anonymous
+ * key agreement protocol allowing two parties to establish a shared
+ * secret over an insecure channel. Each party must have an
+ * elliptic-curve public–private key pair.
+ *
+ * For more information, see <em>NIST SP 800-56A Rev. 2: Recommendation for
+ * Pair-Wise Key Establishment Schemes Using Discrete Logarithm
+ * Cryptography</em>.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_ECDH_H
+#define MBEDTLS_ECDH_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/ecp.h"
+
+/*
+ * Mbed TLS supports two formats for ECDH contexts (#mbedtls_ecdh_context
+ * defined in `ecdh.h`). For most applications, the choice of format makes
+ * no difference, since all library functions can work with either format,
+ * except that the new format is incompatible with MBEDTLS_ECP_RESTARTABLE.
+
+ * The new format used when this option is disabled is smaller
+ * (56 bytes on a 32-bit platform). In future versions of the library, it
+ * will support alternative implementations of ECDH operations.
+ * The new format is incompatible with applications that access
+ * context fields directly and with restartable ECP operations.
+ */
+
+#if defined(MBEDTLS_ECP_RESTARTABLE)
+#define MBEDTLS_ECDH_LEGACY_CONTEXT
+#else
+#undef MBEDTLS_ECDH_LEGACY_CONTEXT
+#endif
+
+#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
+#undef MBEDTLS_ECDH_LEGACY_CONTEXT
+#include "everest/everest.h"
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Defines the source of the imported EC key.
+ */
+typedef enum {
+ MBEDTLS_ECDH_OURS, /**< Our key. */
+ MBEDTLS_ECDH_THEIRS, /**< The key of the peer. */
+} mbedtls_ecdh_side;
+
+#if !defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
+/**
+ * Defines the ECDH implementation used.
+ *
+ * Later versions of the library may add new variants, therefore users should
+ * not make any assumptions about them.
+ */
+typedef enum {
+ MBEDTLS_ECDH_VARIANT_NONE = 0, /*!< Implementation not defined. */
+ MBEDTLS_ECDH_VARIANT_MBEDTLS_2_0,/*!< The default Mbed TLS implementation */
+#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
+ MBEDTLS_ECDH_VARIANT_EVEREST /*!< Everest implementation */
+#endif
+} mbedtls_ecdh_variant;
+
+/**
+ * The context used by the default ECDH implementation.
+ *
+ * Later versions might change the structure of this context, therefore users
+ * should not make any assumptions about the structure of
+ * mbedtls_ecdh_context_mbed.
+ */
+typedef struct mbedtls_ecdh_context_mbed {
+ mbedtls_ecp_group MBEDTLS_PRIVATE(grp); /*!< The elliptic curve used. */
+ mbedtls_mpi MBEDTLS_PRIVATE(d); /*!< The private key. */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Q); /*!< The public key. */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Qp); /*!< The value of the public key of the peer. */
+ mbedtls_mpi MBEDTLS_PRIVATE(z); /*!< The shared secret. */
+#if defined(MBEDTLS_ECP_RESTARTABLE)
+ mbedtls_ecp_restart_ctx MBEDTLS_PRIVATE(rs); /*!< The restart context for EC computations. */
+#endif
+} mbedtls_ecdh_context_mbed;
+#endif
+
+/**
+ *
+ * \warning Performing multiple operations concurrently on the same
+ * ECDSA context is not supported; objects of this type
+ * should not be shared between multiple threads.
+ * \brief The ECDH context structure.
+ */
+typedef struct mbedtls_ecdh_context {
+#if defined(MBEDTLS_ECDH_LEGACY_CONTEXT)
+ mbedtls_ecp_group MBEDTLS_PRIVATE(grp); /*!< The elliptic curve used. */
+ mbedtls_mpi MBEDTLS_PRIVATE(d); /*!< The private key. */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Q); /*!< The public key. */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Qp); /*!< The value of the public key of the peer. */
+ mbedtls_mpi MBEDTLS_PRIVATE(z); /*!< The shared secret. */
+ int MBEDTLS_PRIVATE(point_format); /*!< The format of point export in TLS messages. */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Vi); /*!< The blinding value. */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Vf); /*!< The unblinding value. */
+ mbedtls_mpi MBEDTLS_PRIVATE(_d); /*!< The previous \p d. */
+#if defined(MBEDTLS_ECP_RESTARTABLE)
+ int MBEDTLS_PRIVATE(restart_enabled); /*!< The flag for restartable mode. */
+ mbedtls_ecp_restart_ctx MBEDTLS_PRIVATE(rs); /*!< The restart context for EC computations. */
+#endif /* MBEDTLS_ECP_RESTARTABLE */
+#else
+ uint8_t MBEDTLS_PRIVATE(point_format); /*!< The format of point export in TLS messages
+ as defined in RFC 4492. */
+ mbedtls_ecp_group_id MBEDTLS_PRIVATE(grp_id);/*!< The elliptic curve used. */
+ mbedtls_ecdh_variant MBEDTLS_PRIVATE(var); /*!< The ECDH implementation/structure used. */
+ union {
+ mbedtls_ecdh_context_mbed MBEDTLS_PRIVATE(mbed_ecdh);
+#if defined(MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED)
+ mbedtls_ecdh_context_everest MBEDTLS_PRIVATE(everest_ecdh);
+#endif
+ } MBEDTLS_PRIVATE(ctx); /*!< Implementation-specific context. The
+ context in use is specified by the \c var
+ field. */
+#if defined(MBEDTLS_ECP_RESTARTABLE)
+ uint8_t MBEDTLS_PRIVATE(restart_enabled); /*!< The flag for restartable mode. Functions of
+ an alternative implementation not supporting
+ restartable mode must return
+ MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED error
+ if this flag is set. */
+#endif /* MBEDTLS_ECP_RESTARTABLE */
+#endif /* MBEDTLS_ECDH_LEGACY_CONTEXT */
+}
+mbedtls_ecdh_context;
+
+/**
+ * \brief Check whether a given group can be used for ECDH.
+ *
+ * \param gid The ECP group ID to check.
+ *
+ * \return \c 1 if the group can be used, \c 0 otherwise
+ */
+int mbedtls_ecdh_can_do(mbedtls_ecp_group_id gid);
+
+/**
+ * \brief This function generates an ECDH keypair on an elliptic
+ * curve.
+ *
+ * This function performs the first of two core computations
+ * implemented during the ECDH key exchange. The second core
+ * computation is performed by mbedtls_ecdh_compute_shared().
+ *
+ * \see ecp.h
+ *
+ * \param grp The ECP group to use. This must be initialized and have
+ * domain parameters loaded, for example through
+ * mbedtls_ecp_load() or mbedtls_ecp_tls_read_group().
+ * \param d The destination MPI (private key).
+ * This must be initialized.
+ * \param Q The destination point (public key).
+ * This must be initialized.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL in case \p f_rng doesn't need a context argument.
+ *
+ * \return \c 0 on success.
+ * \return Another \c MBEDTLS_ERR_ECP_XXX or
+ * \c MBEDTLS_MPI_XXX error code on failure.
+ */
+int mbedtls_ecdh_gen_public(mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function computes the shared secret.
+ *
+ * This function performs the second of two core computations
+ * implemented during the ECDH key exchange. The first core
+ * computation is performed by mbedtls_ecdh_gen_public().
+ *
+ * \see ecp.h
+ *
+ * \note If \p f_rng is not NULL, it is used to implement
+ * countermeasures against side-channel attacks.
+ * For more information, see mbedtls_ecp_mul().
+ *
+ * \param grp The ECP group to use. This must be initialized and have
+ * domain parameters loaded, for example through
+ * mbedtls_ecp_load() or mbedtls_ecp_tls_read_group().
+ * \param z The destination MPI (shared secret).
+ * This must be initialized.
+ * \param Q The public key from another party.
+ * This must be initialized.
+ * \param d Our secret exponent (private key).
+ * This must be initialized.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng is \c NULL or doesn't need a
+ * context argument.
+ *
+ * \return \c 0 on success.
+ * \return Another \c MBEDTLS_ERR_ECP_XXX or
+ * \c MBEDTLS_MPI_XXX error code on failure.
+ */
+int mbedtls_ecdh_compute_shared(mbedtls_ecp_group *grp, mbedtls_mpi *z,
+ const mbedtls_ecp_point *Q, const mbedtls_mpi *d,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function initializes an ECDH context.
+ *
+ * \param ctx The ECDH context to initialize. This must not be \c NULL.
+ */
+void mbedtls_ecdh_init(mbedtls_ecdh_context *ctx);
+
+/**
+ * \brief This function sets up the ECDH context with the information
+ * given.
+ *
+ * This function should be called after mbedtls_ecdh_init() but
+ * before mbedtls_ecdh_make_params(). There is no need to call
+ * this function before mbedtls_ecdh_read_params().
+ *
+ * This is the first function used by a TLS server for ECDHE
+ * ciphersuites.
+ *
+ * \param ctx The ECDH context to set up. This must be initialized.
+ * \param grp_id The group id of the group to set up the context for.
+ *
+ * \return \c 0 on success.
+ */
+int mbedtls_ecdh_setup(mbedtls_ecdh_context *ctx,
+ mbedtls_ecp_group_id grp_id);
+
+/**
+ * \brief This function frees a context.
+ *
+ * \param ctx The context to free. This may be \c NULL, in which
+ * case this function does nothing. If it is not \c NULL,
+ * it must point to an initialized ECDH context.
+ */
+void mbedtls_ecdh_free(mbedtls_ecdh_context *ctx);
+
+/**
+ * \brief This function generates an EC key pair and exports its
+ * in the format used in a TLS ServerKeyExchange handshake
+ * message.
+ *
+ * This is the second function used by a TLS server for ECDHE
+ * ciphersuites. (It is called after mbedtls_ecdh_setup().)
+ *
+ * \see ecp.h
+ *
+ * \param ctx The ECDH context to use. This must be initialized
+ * and bound to a group, for example via mbedtls_ecdh_setup().
+ * \param olen The address at which to store the number of Bytes written.
+ * \param buf The destination buffer. This must be a writable buffer of
+ * length \p blen Bytes.
+ * \param blen The length of the destination buffer \p buf in Bytes.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL in case \p f_rng doesn't need a context argument.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
+ */
+int mbedtls_ecdh_make_params(mbedtls_ecdh_context *ctx, size_t *olen,
+ unsigned char *buf, size_t blen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function parses the ECDHE parameters in a
+ * TLS ServerKeyExchange handshake message.
+ *
+ * \note In a TLS handshake, this is the how the client
+ * sets up its ECDHE context from the server's public
+ * ECDHE key material.
+ *
+ * \see ecp.h
+ *
+ * \param ctx The ECDHE context to use. This must be initialized.
+ * \param buf On input, \c *buf must be the start of the input buffer.
+ * On output, \c *buf is updated to point to the end of the
+ * data that has been read. On success, this is the first byte
+ * past the end of the ServerKeyExchange parameters.
+ * On error, this is the point at which an error has been
+ * detected, which is usually not useful except to debug
+ * failures.
+ * \param end The end of the input buffer.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
+ *
+ */
+int mbedtls_ecdh_read_params(mbedtls_ecdh_context *ctx,
+ const unsigned char **buf,
+ const unsigned char *end);
+
+/**
+ * \brief This function sets up an ECDH context from an EC key.
+ *
+ * It is used by clients and servers in place of the
+ * ServerKeyEchange for static ECDH, and imports ECDH
+ * parameters from the EC key information of a certificate.
+ *
+ * \see ecp.h
+ *
+ * \param ctx The ECDH context to set up. This must be initialized.
+ * \param key The EC key to use. This must be initialized.
+ * \param side Defines the source of the key. Possible values are:
+ * - #MBEDTLS_ECDH_OURS: The key is ours.
+ * - #MBEDTLS_ECDH_THEIRS: The key is that of the peer.
+ *
+ * \return \c 0 on success.
+ * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
+ *
+ */
+int mbedtls_ecdh_get_params(mbedtls_ecdh_context *ctx,
+ const mbedtls_ecp_keypair *key,
+ mbedtls_ecdh_side side);
+
+/**
+ * \brief This function generates a public key and exports it
+ * as a TLS ClientKeyExchange payload.
+ *
+ * This is the second function used by a TLS client for ECDH(E)
+ * ciphersuites.
+ *
+ * \see ecp.h
+ *
+ * \param ctx The ECDH context to use. This must be initialized
+ * and bound to a group, the latter usually by
+ * mbedtls_ecdh_read_params().
+ * \param olen The address at which to store the number of Bytes written.
+ * This must not be \c NULL.
+ * \param buf The destination buffer. This must be a writable buffer
+ * of length \p blen Bytes.
+ * \param blen The size of the destination buffer \p buf in Bytes.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL in case \p f_rng doesn't need a context argument.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
+ */
+int mbedtls_ecdh_make_public(mbedtls_ecdh_context *ctx, size_t *olen,
+ unsigned char *buf, size_t blen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function parses and processes the ECDHE payload of a
+ * TLS ClientKeyExchange message.
+ *
+ * This is the third function used by a TLS server for ECDH(E)
+ * ciphersuites. (It is called after mbedtls_ecdh_setup() and
+ * mbedtls_ecdh_make_params().)
+ *
+ * \see ecp.h
+ *
+ * \param ctx The ECDH context to use. This must be initialized
+ * and bound to a group, for example via mbedtls_ecdh_setup().
+ * \param buf The pointer to the ClientKeyExchange payload. This must
+ * be a readable buffer of length \p blen Bytes.
+ * \param blen The length of the input buffer \p buf in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX error code on failure.
+ */
+int mbedtls_ecdh_read_public(mbedtls_ecdh_context *ctx,
+ const unsigned char *buf, size_t blen);
+
+/**
+ * \brief This function derives and exports the shared secret.
+ *
+ * This is the last function used by both TLS client
+ * and servers.
+ *
+ * \note If \p f_rng is not NULL, it is used to implement
+ * countermeasures against side-channel attacks.
+ * For more information, see mbedtls_ecp_mul().
+ *
+ * \see ecp.h
+
+ * \param ctx The ECDH context to use. This must be initialized
+ * and have its own private key generated and the peer's
+ * public key imported.
+ * \param olen The address at which to store the total number of
+ * Bytes written on success. This must not be \c NULL.
+ * \param buf The buffer to write the generated shared key to. This
+ * must be a writable buffer of size \p blen Bytes.
+ * \param blen The length of the destination buffer \p buf in Bytes.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG context. This may be \c NULL if \p f_rng
+ * doesn't need a context argument.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ * \return Another \c MBEDTLS_ERR_ECP_XXX error code on failure.
+ */
+int mbedtls_ecdh_calc_secret(mbedtls_ecdh_context *ctx, size_t *olen,
+ unsigned char *buf, size_t blen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+#if defined(MBEDTLS_ECP_RESTARTABLE)
+/**
+ * \brief This function enables restartable EC computations for this
+ * context. (Default: disabled.)
+ *
+ * \see \c mbedtls_ecp_set_max_ops()
+ *
+ * \note It is not possible to safely disable restartable
+ * computations once enabled, except by free-ing the context,
+ * which cancels possible in-progress operations.
+ *
+ * \param ctx The ECDH context to use. This must be initialized.
+ */
+void mbedtls_ecdh_enable_restart(mbedtls_ecdh_context *ctx);
+#endif /* MBEDTLS_ECP_RESTARTABLE */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ecdh.h */
diff --git a/include/mbedtls/ecdsa.h b/include/mbedtls/ecdsa.h
new file mode 100644
index 0000000..2ecf349
--- /dev/null
+++ b/include/mbedtls/ecdsa.h
@@ -0,0 +1,671 @@
+/**
+ * \file ecdsa.h
+ *
+ * \brief This file contains ECDSA definitions and functions.
+ *
+ * The Elliptic Curve Digital Signature Algorithm (ECDSA) is defined in
+ * <em>Standards for Efficient Cryptography Group (SECG):
+ * SEC1 Elliptic Curve Cryptography</em>.
+ * The use of ECDSA for TLS is defined in <em>RFC-4492: Elliptic Curve
+ * Cryptography (ECC) Cipher Suites for Transport Layer Security (TLS)</em>.
+ *
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_ECDSA_H
+#define MBEDTLS_ECDSA_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/ecp.h"
+#include "mbedtls/md.h"
+
+/**
+ * \brief Maximum ECDSA signature size for a given curve bit size
+ *
+ * \param bits Curve size in bits
+ * \return Maximum signature size in bytes
+ *
+ * \note This macro returns a compile-time constant if its argument
+ * is one. It may evaluate its argument multiple times.
+ */
+/*
+ * Ecdsa-Sig-Value ::= SEQUENCE {
+ * r INTEGER,
+ * s INTEGER
+ * }
+ *
+ * For each of r and s, the value (V) may include an extra initial "0" bit.
+ */
+#define MBEDTLS_ECDSA_MAX_SIG_LEN(bits) \
+ (/*T,L of SEQUENCE*/ ((bits) >= 61 * 8 ? 3 : 2) + \
+ /*T,L of r,s*/ 2 * (((bits) >= 127 * 8 ? 3 : 2) + \
+ /*V of r,s*/ ((bits) + 8) / 8))
+
+/** The maximal size of an ECDSA signature in Bytes. */
+#define MBEDTLS_ECDSA_MAX_LEN MBEDTLS_ECDSA_MAX_SIG_LEN(MBEDTLS_ECP_MAX_BITS)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief The ECDSA context structure.
+ *
+ * \warning Performing multiple operations concurrently on the same
+ * ECDSA context is not supported; objects of this type
+ * should not be shared between multiple threads.
+ *
+ * \note pk_wrap module assumes that "ecdsa_context" is identical
+ * to "ecp_keypair" (see for example structure
+ * "mbedtls_eckey_info" where ECDSA sign/verify functions
+ * are used also for EC key)
+ */
+typedef mbedtls_ecp_keypair mbedtls_ecdsa_context;
+
+#if defined(MBEDTLS_ECP_RESTARTABLE)
+
+/**
+ * \brief Internal restart context for ecdsa_verify()
+ *
+ * \note Opaque struct, defined in ecdsa.c
+ */
+typedef struct mbedtls_ecdsa_restart_ver mbedtls_ecdsa_restart_ver_ctx;
+
+/**
+ * \brief Internal restart context for ecdsa_sign()
+ *
+ * \note Opaque struct, defined in ecdsa.c
+ */
+typedef struct mbedtls_ecdsa_restart_sig mbedtls_ecdsa_restart_sig_ctx;
+
+#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
+/**
+ * \brief Internal restart context for ecdsa_sign_det()
+ *
+ * \note Opaque struct, defined in ecdsa.c
+ */
+typedef struct mbedtls_ecdsa_restart_det mbedtls_ecdsa_restart_det_ctx;
+#endif
+
+/**
+ * \brief General context for resuming ECDSA operations
+ */
+typedef struct {
+ mbedtls_ecp_restart_ctx MBEDTLS_PRIVATE(ecp); /*!< base context for ECP restart and
+ shared administrative info */
+ mbedtls_ecdsa_restart_ver_ctx *MBEDTLS_PRIVATE(ver); /*!< ecdsa_verify() sub-context */
+ mbedtls_ecdsa_restart_sig_ctx *MBEDTLS_PRIVATE(sig); /*!< ecdsa_sign() sub-context */
+#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
+ mbedtls_ecdsa_restart_det_ctx *MBEDTLS_PRIVATE(det); /*!< ecdsa_sign_det() sub-context */
+#endif
+} mbedtls_ecdsa_restart_ctx;
+
+#else /* MBEDTLS_ECP_RESTARTABLE */
+
+/* Now we can declare functions that take a pointer to that */
+typedef void mbedtls_ecdsa_restart_ctx;
+
+#endif /* MBEDTLS_ECP_RESTARTABLE */
+
+/**
+ * \brief This function checks whether a given group can be used
+ * for ECDSA.
+ *
+ * \param gid The ECP group ID to check.
+ *
+ * \return \c 1 if the group can be used, \c 0 otherwise
+ */
+int mbedtls_ecdsa_can_do(mbedtls_ecp_group_id gid);
+
+/**
+ * \brief This function computes the ECDSA signature of a
+ * previously-hashed message.
+ *
+ * \note The deterministic version implemented in
+ * mbedtls_ecdsa_sign_det_ext() is usually preferred.
+ *
+ * \note If the bitlength of the message hash is larger than the
+ * bitlength of the group order, then the hash is truncated
+ * as defined in <em>Standards for Efficient Cryptography Group
+ * (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ * 4.1.3, step 5.
+ *
+ * \see ecp.h
+ *
+ * \param grp The context for the elliptic curve to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param r The MPI context in which to store the first part
+ * the signature. This must be initialized.
+ * \param s The MPI context in which to store the second part
+ * the signature. This must be initialized.
+ * \param d The private signing key. This must be initialized.
+ * \param buf The content to be signed. This is usually the hash of
+ * the original data to be signed. This must be a readable
+ * buffer of length \p blen Bytes. It may be \c NULL if
+ * \p blen is zero.
+ * \param blen The length of \p buf in Bytes.
+ * \param f_rng The RNG function. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context parameter.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX
+ * or \c MBEDTLS_MPI_XXX error code on failure.
+ */
+int mbedtls_ecdsa_sign(mbedtls_ecp_group *grp, mbedtls_mpi *r, mbedtls_mpi *s,
+ const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
+
+#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
+/**
+ * \brief This function computes the ECDSA signature of a
+ * previously-hashed message, deterministic version.
+ *
+ * For more information, see <em>RFC-6979: Deterministic
+ * Usage of the Digital Signature Algorithm (DSA) and Elliptic
+ * Curve Digital Signature Algorithm (ECDSA)</em>.
+ *
+ * \note If the bitlength of the message hash is larger than the
+ * bitlength of the group order, then the hash is truncated as
+ * defined in <em>Standards for Efficient Cryptography Group
+ * (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ * 4.1.3, step 5.
+ *
+ * \see ecp.h
+ *
+ * \param grp The context for the elliptic curve to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param r The MPI context in which to store the first part
+ * the signature. This must be initialized.
+ * \param s The MPI context in which to store the second part
+ * the signature. This must be initialized.
+ * \param d The private signing key. This must be initialized
+ * and setup, for example through mbedtls_ecp_gen_privkey().
+ * \param buf The hashed content to be signed. This must be a readable
+ * buffer of length \p blen Bytes. It may be \c NULL if
+ * \p blen is zero.
+ * \param blen The length of \p buf in Bytes.
+ * \param md_alg The hash algorithm used to hash the original data.
+ * \param f_rng_blind The RNG function used for blinding. This must not be
+ * \c NULL.
+ * \param p_rng_blind The RNG context to be passed to \p f_rng_blind. This
+ * may be \c NULL if \p f_rng_blind doesn't need a context
+ * parameter.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX
+ * error code on failure.
+ */
+int mbedtls_ecdsa_sign_det_ext(mbedtls_ecp_group *grp, mbedtls_mpi *r,
+ mbedtls_mpi *s, const mbedtls_mpi *d,
+ const unsigned char *buf, size_t blen,
+ mbedtls_md_type_t md_alg,
+ int (*f_rng_blind)(void *, unsigned char *, size_t),
+ void *p_rng_blind);
+#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
+
+#if !defined(MBEDTLS_ECDSA_SIGN_ALT)
+/**
+ * \brief This function computes the ECDSA signature of a
+ * previously-hashed message, in a restartable way.
+ *
+ * \note The deterministic version implemented in
+ * mbedtls_ecdsa_sign_det_restartable() is usually
+ * preferred.
+ *
+ * \note This function is like \c mbedtls_ecdsa_sign() but
+ * it can return early and restart according to the
+ * limit set with \c mbedtls_ecp_set_max_ops() to
+ * reduce blocking.
+ *
+ * \note If the bitlength of the message hash is larger
+ * than the bitlength of the group order, then the
+ * hash is truncated as defined in <em>Standards for
+ * Efficient Cryptography Group (SECG): SEC1 Elliptic
+ * Curve Cryptography</em>, section 4.1.3, step 5.
+ *
+ * \see ecp.h
+ *
+ * \param grp The context for the elliptic curve to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param r The MPI context in which to store the first part
+ * the signature. This must be initialized.
+ * \param s The MPI context in which to store the second part
+ * the signature. This must be initialized.
+ * \param d The private signing key. This must be initialized
+ * and setup, for example through
+ * mbedtls_ecp_gen_privkey().
+ * \param buf The hashed content to be signed. This must be a readable
+ * buffer of length \p blen Bytes. It may be \c NULL if
+ * \p blen is zero.
+ * \param blen The length of \p buf in Bytes.
+ * \param f_rng The RNG function. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context parameter.
+ * \param f_rng_blind The RNG function used for blinding. This must not be
+ * \c NULL.
+ * \param p_rng_blind The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context parameter.
+ * \param rs_ctx The restart context to use. This may be \c NULL
+ * to disable restarting. If it is not \c NULL, it
+ * must point to an initialized restart context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c
+ * mbedtls_ecp_set_max_ops().
+ * \return Another \c MBEDTLS_ERR_ECP_XXX, \c
+ * MBEDTLS_ERR_MPI_XXX or \c MBEDTLS_ERR_ASN1_XXX
+ * error code on failure.
+ */
+int mbedtls_ecdsa_sign_restartable(
+ mbedtls_ecp_group *grp,
+ mbedtls_mpi *r, mbedtls_mpi *s,
+ const mbedtls_mpi *d,
+ const unsigned char *buf, size_t blen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ int (*f_rng_blind)(void *, unsigned char *, size_t),
+ void *p_rng_blind,
+ mbedtls_ecdsa_restart_ctx *rs_ctx);
+
+#endif /* !MBEDTLS_ECDSA_SIGN_ALT */
+
+#if defined(MBEDTLS_ECDSA_DETERMINISTIC)
+
+/**
+ * \brief This function computes the ECDSA signature of a
+ * previously-hashed message, in a restartable way.
+ *
+ * \note This function is like \c
+ * mbedtls_ecdsa_sign_det_ext() but it can return
+ * early and restart according to the limit set with
+ * \c mbedtls_ecp_set_max_ops() to reduce blocking.
+ *
+ * \note If the bitlength of the message hash is larger
+ * than the bitlength of the group order, then the
+ * hash is truncated as defined in <em>Standards for
+ * Efficient Cryptography Group (SECG): SEC1 Elliptic
+ * Curve Cryptography</em>, section 4.1.3, step 5.
+ *
+ * \see ecp.h
+ *
+ * \param grp The context for the elliptic curve to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param r The MPI context in which to store the first part
+ * the signature. This must be initialized.
+ * \param s The MPI context in which to store the second part
+ * the signature. This must be initialized.
+ * \param d The private signing key. This must be initialized
+ * and setup, for example through
+ * mbedtls_ecp_gen_privkey().
+ * \param buf The hashed content to be signed. This must be a readable
+ * buffer of length \p blen Bytes. It may be \c NULL if
+ * \p blen is zero.
+ * \param blen The length of \p buf in Bytes.
+ * \param md_alg The hash algorithm used to hash the original data.
+ * \param f_rng_blind The RNG function used for blinding. This must not be
+ * \c NULL.
+ * \param p_rng_blind The RNG context to be passed to \p f_rng_blind. This may be
+ * \c NULL if \p f_rng_blind doesn't need a context parameter.
+ * \param rs_ctx The restart context to use. This may be \c NULL
+ * to disable restarting. If it is not \c NULL, it
+ * must point to an initialized restart context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c
+ * mbedtls_ecp_set_max_ops().
+ * \return Another \c MBEDTLS_ERR_ECP_XXX, \c
+ * MBEDTLS_ERR_MPI_XXX or \c MBEDTLS_ERR_ASN1_XXX
+ * error code on failure.
+ */
+int mbedtls_ecdsa_sign_det_restartable(
+ mbedtls_ecp_group *grp,
+ mbedtls_mpi *r, mbedtls_mpi *s,
+ const mbedtls_mpi *d, const unsigned char *buf, size_t blen,
+ mbedtls_md_type_t md_alg,
+ int (*f_rng_blind)(void *, unsigned char *, size_t),
+ void *p_rng_blind,
+ mbedtls_ecdsa_restart_ctx *rs_ctx);
+
+#endif /* MBEDTLS_ECDSA_DETERMINISTIC */
+
+/**
+ * \brief This function verifies the ECDSA signature of a
+ * previously-hashed message.
+ *
+ * \note If the bitlength of the message hash is larger than the
+ * bitlength of the group order, then the hash is truncated as
+ * defined in <em>Standards for Efficient Cryptography Group
+ * (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ * 4.1.4, step 3.
+ *
+ * \see ecp.h
+ *
+ * \param grp The ECP group to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param buf The hashed content that was signed. This must be a readable
+ * buffer of length \p blen Bytes. It may be \c NULL if
+ * \p blen is zero.
+ * \param blen The length of \p buf in Bytes.
+ * \param Q The public key to use for verification. This must be
+ * initialized and setup.
+ * \param r The first integer of the signature.
+ * This must be initialized.
+ * \param s The second integer of the signature.
+ * This must be initialized.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX
+ * error code on failure.
+ */
+int mbedtls_ecdsa_verify(mbedtls_ecp_group *grp,
+ const unsigned char *buf, size_t blen,
+ const mbedtls_ecp_point *Q, const mbedtls_mpi *r,
+ const mbedtls_mpi *s);
+
+#if !defined(MBEDTLS_ECDSA_VERIFY_ALT)
+/**
+ * \brief This function verifies the ECDSA signature of a
+ * previously-hashed message, in a restartable manner
+ *
+ * \note If the bitlength of the message hash is larger than the
+ * bitlength of the group order, then the hash is truncated as
+ * defined in <em>Standards for Efficient Cryptography Group
+ * (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ * 4.1.4, step 3.
+ *
+ * \see ecp.h
+ *
+ * \param grp The ECP group to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param buf The hashed content that was signed. This must be a readable
+ * buffer of length \p blen Bytes. It may be \c NULL if
+ * \p blen is zero.
+ * \param blen The length of \p buf in Bytes.
+ * \param Q The public key to use for verification. This must be
+ * initialized and setup.
+ * \param r The first integer of the signature.
+ * This must be initialized.
+ * \param s The second integer of the signature.
+ * This must be initialized.
+ * \param rs_ctx The restart context to use. This may be \c NULL to disable
+ * restarting. If it is not \c NULL, it must point to an
+ * initialized restart context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX
+ * error code on failure.
+ */
+int mbedtls_ecdsa_verify_restartable(mbedtls_ecp_group *grp,
+ const unsigned char *buf, size_t blen,
+ const mbedtls_ecp_point *Q,
+ const mbedtls_mpi *r,
+ const mbedtls_mpi *s,
+ mbedtls_ecdsa_restart_ctx *rs_ctx);
+
+#endif /* !MBEDTLS_ECDSA_VERIFY_ALT */
+
+/**
+ * \brief This function computes the ECDSA signature and writes it
+ * to a buffer, serialized as defined in <em>RFC-4492:
+ * Elliptic Curve Cryptography (ECC) Cipher Suites for
+ * Transport Layer Security (TLS)</em>.
+ *
+ * \warning It is not thread-safe to use the same context in
+ * multiple threads.
+ *
+ * \note The deterministic version is used if
+ * #MBEDTLS_ECDSA_DETERMINISTIC is defined. For more
+ * information, see <em>RFC-6979: Deterministic Usage
+ * of the Digital Signature Algorithm (DSA) and Elliptic
+ * Curve Digital Signature Algorithm (ECDSA)</em>.
+ *
+ * \note If the bitlength of the message hash is larger than the
+ * bitlength of the group order, then the hash is truncated as
+ * defined in <em>Standards for Efficient Cryptography Group
+ * (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ * 4.1.3, step 5.
+ *
+ * \see ecp.h
+ *
+ * \param ctx The ECDSA context to use. This must be initialized
+ * and have a group and private key bound to it, for example
+ * via mbedtls_ecdsa_genkey() or mbedtls_ecdsa_from_keypair().
+ * \param md_alg The message digest that was used to hash the message.
+ * \param hash The message hash to be signed. This must be a readable
+ * buffer of length \p hlen Bytes.
+ * \param hlen The length of the hash \p hash in Bytes.
+ * \param sig The buffer to which to write the signature. This must be a
+ * writable buffer of length at least twice as large as the
+ * size of the curve used, plus 9. For example, 73 Bytes if
+ * a 256-bit curve is used. A buffer length of
+ * #MBEDTLS_ECDSA_MAX_LEN is always safe.
+ * \param sig_size The size of the \p sig buffer in bytes.
+ * \param slen The address at which to store the actual length of
+ * the signature written. Must not be \c NULL.
+ * \param f_rng The RNG function. This must not be \c NULL if
+ * #MBEDTLS_ECDSA_DETERMINISTIC is unset. Otherwise,
+ * it is used only for blinding and may be set to \c NULL, but
+ * doing so is DEPRECATED.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng is \c NULL or doesn't use a context.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or
+ * \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_ecdsa_write_signature(mbedtls_ecdsa_context *ctx,
+ mbedtls_md_type_t md_alg,
+ const unsigned char *hash, size_t hlen,
+ unsigned char *sig, size_t sig_size, size_t *slen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function computes the ECDSA signature and writes it
+ * to a buffer, in a restartable way.
+ *
+ * \see \c mbedtls_ecdsa_write_signature()
+ *
+ * \note This function is like \c mbedtls_ecdsa_write_signature()
+ * but it can return early and restart according to the limit
+ * set with \c mbedtls_ecp_set_max_ops() to reduce blocking.
+ *
+ * \param ctx The ECDSA context to use. This must be initialized
+ * and have a group and private key bound to it, for example
+ * via mbedtls_ecdsa_genkey() or mbedtls_ecdsa_from_keypair().
+ * \param md_alg The message digest that was used to hash the message.
+ * \param hash The message hash to be signed. This must be a readable
+ * buffer of length \p hlen Bytes.
+ * \param hlen The length of the hash \p hash in Bytes.
+ * \param sig The buffer to which to write the signature. This must be a
+ * writable buffer of length at least twice as large as the
+ * size of the curve used, plus 9. For example, 73 Bytes if
+ * a 256-bit curve is used. A buffer length of
+ * #MBEDTLS_ECDSA_MAX_LEN is always safe.
+ * \param sig_size The size of the \p sig buffer in bytes.
+ * \param slen The address at which to store the actual length of
+ * the signature written. Must not be \c NULL.
+ * \param f_rng The RNG function. This must not be \c NULL if
+ * #MBEDTLS_ECDSA_DETERMINISTIC is unset. Otherwise,
+ * it is unused and may be set to \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng is \c NULL or doesn't use a context.
+ * \param rs_ctx The restart context to use. This may be \c NULL to disable
+ * restarting. If it is not \c NULL, it must point to an
+ * initialized restart context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ * \return Another \c MBEDTLS_ERR_ECP_XXX, \c MBEDTLS_ERR_MPI_XXX or
+ * \c MBEDTLS_ERR_ASN1_XXX error code on failure.
+ */
+int mbedtls_ecdsa_write_signature_restartable(mbedtls_ecdsa_context *ctx,
+ mbedtls_md_type_t md_alg,
+ const unsigned char *hash, size_t hlen,
+ unsigned char *sig, size_t sig_size, size_t *slen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ mbedtls_ecdsa_restart_ctx *rs_ctx);
+
+/**
+ * \brief This function reads and verifies an ECDSA signature.
+ *
+ * \note If the bitlength of the message hash is larger than the
+ * bitlength of the group order, then the hash is truncated as
+ * defined in <em>Standards for Efficient Cryptography Group
+ * (SECG): SEC1 Elliptic Curve Cryptography</em>, section
+ * 4.1.4, step 3.
+ *
+ * \see ecp.h
+ *
+ * \param ctx The ECDSA context to use. This must be initialized
+ * and have a group and public key bound to it.
+ * \param hash The message hash that was signed. This must be a readable
+ * buffer of length \p hlen Bytes.
+ * \param hlen The size of the hash \p hash.
+ * \param sig The signature to read and verify. This must be a readable
+ * buffer of length \p slen Bytes.
+ * \param slen The size of \p sig in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid.
+ * \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid
+ * signature in \p sig, but its length is less than \p siglen.
+ * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX
+ * error code on failure for any other reason.
+ */
+int mbedtls_ecdsa_read_signature(mbedtls_ecdsa_context *ctx,
+ const unsigned char *hash, size_t hlen,
+ const unsigned char *sig, size_t slen);
+
+/**
+ * \brief This function reads and verifies an ECDSA signature,
+ * in a restartable way.
+ *
+ * \see \c mbedtls_ecdsa_read_signature()
+ *
+ * \note This function is like \c mbedtls_ecdsa_read_signature()
+ * but it can return early and restart according to the limit
+ * set with \c mbedtls_ecp_set_max_ops() to reduce blocking.
+ *
+ * \param ctx The ECDSA context to use. This must be initialized
+ * and have a group and public key bound to it.
+ * \param hash The message hash that was signed. This must be a readable
+ * buffer of length \p hlen Bytes.
+ * \param hlen The size of the hash \p hash.
+ * \param sig The signature to read and verify. This must be a readable
+ * buffer of length \p slen Bytes.
+ * \param slen The size of \p sig in Bytes.
+ * \param rs_ctx The restart context to use. This may be \c NULL to disable
+ * restarting. If it is not \c NULL, it must point to an
+ * initialized restart context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if signature is invalid.
+ * \return #MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH if there is a valid
+ * signature in \p sig, but its length is less than \p siglen.
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ * \return Another \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_ERR_MPI_XXX
+ * error code on failure for any other reason.
+ */
+int mbedtls_ecdsa_read_signature_restartable(mbedtls_ecdsa_context *ctx,
+ const unsigned char *hash, size_t hlen,
+ const unsigned char *sig, size_t slen,
+ mbedtls_ecdsa_restart_ctx *rs_ctx);
+
+/**
+ * \brief This function generates an ECDSA keypair on the given curve.
+ *
+ * \see ecp.h
+ *
+ * \param ctx The ECDSA context to store the keypair in.
+ * This must be initialized.
+ * \param gid The elliptic curve to use. One of the various
+ * \c MBEDTLS_ECP_DP_XXX macros depending on configuration.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context argument.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX code on failure.
+ */
+int mbedtls_ecdsa_genkey(mbedtls_ecdsa_context *ctx, mbedtls_ecp_group_id gid,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
+
+/**
+ * \brief This function sets up an ECDSA context from an EC key pair.
+ *
+ * \see ecp.h
+ *
+ * \param ctx The ECDSA context to setup. This must be initialized.
+ * \param key The EC key to use. This must be initialized and hold
+ * a private-public key pair or a public key. In the former
+ * case, the ECDSA context may be used for signature creation
+ * and verification after this call. In the latter case, it
+ * may be used for signature verification.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX code on failure.
+ */
+int mbedtls_ecdsa_from_keypair(mbedtls_ecdsa_context *ctx,
+ const mbedtls_ecp_keypair *key);
+
+/**
+ * \brief This function initializes an ECDSA context.
+ *
+ * \param ctx The ECDSA context to initialize.
+ * This must not be \c NULL.
+ */
+void mbedtls_ecdsa_init(mbedtls_ecdsa_context *ctx);
+
+/**
+ * \brief This function frees an ECDSA context.
+ *
+ * \param ctx The ECDSA context to free. This may be \c NULL,
+ * in which case this function does nothing. If it
+ * is not \c NULL, it must be initialized.
+ */
+void mbedtls_ecdsa_free(mbedtls_ecdsa_context *ctx);
+
+#if defined(MBEDTLS_ECP_RESTARTABLE)
+/**
+ * \brief Initialize a restart context.
+ *
+ * \param ctx The restart context to initialize.
+ * This must not be \c NULL.
+ */
+void mbedtls_ecdsa_restart_init(mbedtls_ecdsa_restart_ctx *ctx);
+
+/**
+ * \brief Free the components of a restart context.
+ *
+ * \param ctx The restart context to free. This may be \c NULL,
+ * in which case this function does nothing. If it
+ * is not \c NULL, it must be initialized.
+ */
+void mbedtls_ecdsa_restart_free(mbedtls_ecdsa_restart_ctx *ctx);
+#endif /* MBEDTLS_ECP_RESTARTABLE */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ecdsa.h */
diff --git a/include/mbedtls/ecjpake.h b/include/mbedtls/ecjpake.h
new file mode 100644
index 0000000..c2148a2
--- /dev/null
+++ b/include/mbedtls/ecjpake.h
@@ -0,0 +1,298 @@
+/**
+ * \file ecjpake.h
+ *
+ * \brief Elliptic curve J-PAKE
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_ECJPAKE_H
+#define MBEDTLS_ECJPAKE_H
+#include "mbedtls/private_access.h"
+
+/*
+ * J-PAKE is a password-authenticated key exchange that allows deriving a
+ * strong shared secret from a (potentially low entropy) pre-shared
+ * passphrase, with forward secrecy and mutual authentication.
+ * https://en.wikipedia.org/wiki/Password_Authenticated_Key_Exchange_by_Juggling
+ *
+ * This file implements the Elliptic Curve variant of J-PAKE,
+ * as defined in Chapter 7.4 of the Thread v1.0 Specification,
+ * available to members of the Thread Group http://threadgroup.org/
+ *
+ * As the J-PAKE algorithm is inherently symmetric, so is our API.
+ * Each party needs to send its first round message, in any order, to the
+ * other party, then each sends its second round message, in any order.
+ * The payloads are serialized in a way suitable for use in TLS, but could
+ * also be use outside TLS.
+ */
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/ecp.h"
+#include "mbedtls/md.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Roles in the EC J-PAKE exchange
+ */
+typedef enum {
+ MBEDTLS_ECJPAKE_CLIENT = 0, /**< Client */
+ MBEDTLS_ECJPAKE_SERVER, /**< Server */
+ MBEDTLS_ECJPAKE_NONE, /**< Undefined */
+} mbedtls_ecjpake_role;
+
+#if !defined(MBEDTLS_ECJPAKE_ALT)
+/**
+ * EC J-PAKE context structure.
+ *
+ * J-PAKE is a symmetric protocol, except for the identifiers used in
+ * Zero-Knowledge Proofs, and the serialization of the second message
+ * (KeyExchange) as defined by the Thread spec.
+ *
+ * In order to benefit from this symmetry, we choose a different naming
+ * convention from the Thread v1.0 spec. Correspondence is indicated in the
+ * description as a pair C: client name, S: server name
+ */
+typedef struct mbedtls_ecjpake_context {
+ mbedtls_md_type_t MBEDTLS_PRIVATE(md_type); /**< Hash to use */
+ mbedtls_ecp_group MBEDTLS_PRIVATE(grp); /**< Elliptic curve */
+ mbedtls_ecjpake_role MBEDTLS_PRIVATE(role); /**< Are we client or server? */
+ int MBEDTLS_PRIVATE(point_format); /**< Format for point export */
+
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Xm1); /**< My public key 1 C: X1, S: X3 */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Xm2); /**< My public key 2 C: X2, S: X4 */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Xp1); /**< Peer public key 1 C: X3, S: X1 */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Xp2); /**< Peer public key 2 C: X4, S: X2 */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Xp); /**< Peer public key C: Xs, S: Xc */
+
+ mbedtls_mpi MBEDTLS_PRIVATE(xm1); /**< My private key 1 C: x1, S: x3 */
+ mbedtls_mpi MBEDTLS_PRIVATE(xm2); /**< My private key 2 C: x2, S: x4 */
+
+ mbedtls_mpi MBEDTLS_PRIVATE(s); /**< Pre-shared secret (passphrase) */
+} mbedtls_ecjpake_context;
+
+#else /* MBEDTLS_ECJPAKE_ALT */
+#include "ecjpake_alt.h"
+#endif /* MBEDTLS_ECJPAKE_ALT */
+
+/**
+ * \brief Initialize an ECJPAKE context.
+ *
+ * \param ctx The ECJPAKE context to initialize.
+ * This must not be \c NULL.
+ */
+void mbedtls_ecjpake_init(mbedtls_ecjpake_context *ctx);
+
+/**
+ * \brief Set up an ECJPAKE context for use.
+ *
+ * \note Currently the only values for hash/curve allowed by the
+ * standard are #MBEDTLS_MD_SHA256/#MBEDTLS_ECP_DP_SECP256R1.
+ *
+ * \param ctx The ECJPAKE context to set up. This must be initialized.
+ * \param role The role of the caller. This must be either
+ * #MBEDTLS_ECJPAKE_CLIENT or #MBEDTLS_ECJPAKE_SERVER.
+ * \param hash The identifier of the hash function to use,
+ * for example #MBEDTLS_MD_SHA256.
+ * \param curve The identifier of the elliptic curve to use,
+ * for example #MBEDTLS_ECP_DP_SECP256R1.
+ * \param secret The pre-shared secret (passphrase). This must be
+ * a readable not empty buffer of length \p len Bytes. It need
+ * only be valid for the duration of this call.
+ * \param len The length of the pre-shared secret \p secret.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ecjpake_setup(mbedtls_ecjpake_context *ctx,
+ mbedtls_ecjpake_role role,
+ mbedtls_md_type_t hash,
+ mbedtls_ecp_group_id curve,
+ const unsigned char *secret,
+ size_t len);
+
+/**
+ * \brief Set the point format for future reads and writes.
+ *
+ * \param ctx The ECJPAKE context to configure.
+ * \param point_format The point format to use:
+ * #MBEDTLS_ECP_PF_UNCOMPRESSED (default)
+ * or #MBEDTLS_ECP_PF_COMPRESSED.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if \p point_format
+ * is invalid.
+ */
+int mbedtls_ecjpake_set_point_format(mbedtls_ecjpake_context *ctx,
+ int point_format);
+
+/**
+ * \brief Check if an ECJPAKE context is ready for use.
+ *
+ * \param ctx The ECJPAKE context to check. This must be
+ * initialized.
+ *
+ * \return \c 0 if the context is ready for use.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA otherwise.
+ */
+int mbedtls_ecjpake_check(const mbedtls_ecjpake_context *ctx);
+
+/**
+ * \brief Generate and write the first round message
+ * (TLS: contents of the Client/ServerHello extension,
+ * excluding extension type and length bytes).
+ *
+ * \param ctx The ECJPAKE context to use. This must be
+ * initialized and set up.
+ * \param buf The buffer to write the contents to. This must be a
+ * writable buffer of length \p len Bytes.
+ * \param len The length of \p buf in Bytes.
+ * \param olen The address at which to store the total number
+ * of Bytes written to \p buf. This must not be \c NULL.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG parameter to be passed to \p f_rng. This
+ * may be \c NULL if \p f_rng doesn't use a context.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ecjpake_write_round_one(mbedtls_ecjpake_context *ctx,
+ unsigned char *buf, size_t len, size_t *olen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief Read and process the first round message
+ * (TLS: contents of the Client/ServerHello extension,
+ * excluding extension type and length bytes).
+ *
+ * \param ctx The ECJPAKE context to use. This must be initialized
+ * and set up.
+ * \param buf The buffer holding the first round message. This must
+ * be a readable buffer of length \p len Bytes.
+ * \param len The length in Bytes of \p buf.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ecjpake_read_round_one(mbedtls_ecjpake_context *ctx,
+ const unsigned char *buf,
+ size_t len);
+
+/**
+ * \brief Generate and write the second round message
+ * (TLS: contents of the Client/ServerKeyExchange).
+ *
+ * \param ctx The ECJPAKE context to use. This must be initialized,
+ * set up, and already have performed round one.
+ * \param buf The buffer to write the round two contents to.
+ * This must be a writable buffer of length \p len Bytes.
+ * \param len The size of \p buf in Bytes.
+ * \param olen The address at which to store the total number of Bytes
+ * written to \p buf. This must not be \c NULL.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG parameter to be passed to \p f_rng. This
+ * may be \c NULL if \p f_rng doesn't use a context.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ecjpake_write_round_two(mbedtls_ecjpake_context *ctx,
+ unsigned char *buf, size_t len, size_t *olen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief Read and process the second round message
+ * (TLS: contents of the Client/ServerKeyExchange).
+ *
+ * \param ctx The ECJPAKE context to use. This must be initialized
+ * and set up and already have performed round one.
+ * \param buf The buffer holding the second round message. This must
+ * be a readable buffer of length \p len Bytes.
+ * \param len The length in Bytes of \p buf.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ecjpake_read_round_two(mbedtls_ecjpake_context *ctx,
+ const unsigned char *buf,
+ size_t len);
+
+/**
+ * \brief Derive the shared secret
+ * (TLS: Pre-Master Secret).
+ *
+ * \param ctx The ECJPAKE context to use. This must be initialized,
+ * set up and have performed both round one and two.
+ * \param buf The buffer to write the derived secret to. This must
+ * be a writable buffer of length \p len Bytes.
+ * \param len The length of \p buf in Bytes.
+ * \param olen The address at which to store the total number of Bytes
+ * written to \p buf. This must not be \c NULL.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG parameter to be passed to \p f_rng. This
+ * may be \c NULL if \p f_rng doesn't use a context.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ecjpake_derive_secret(mbedtls_ecjpake_context *ctx,
+ unsigned char *buf, size_t len, size_t *olen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief Write the shared key material to be passed to a Key
+ * Derivation Function as described in RFC8236.
+ *
+ * \param ctx The ECJPAKE context to use. This must be initialized,
+ * set up and have performed both round one and two.
+ * \param buf The buffer to write the derived secret to. This must
+ * be a writable buffer of length \p len Bytes.
+ * \param len The length of \p buf in Bytes.
+ * \param olen The address at which to store the total number of bytes
+ * written to \p buf. This must not be \c NULL.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG parameter to be passed to \p f_rng. This
+ * may be \c NULL if \p f_rng doesn't use a context.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ecjpake_write_shared_key(mbedtls_ecjpake_context *ctx,
+ unsigned char *buf, size_t len, size_t *olen,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This clears an ECJPAKE context and frees any
+ * embedded data structure.
+ *
+ * \param ctx The ECJPAKE context to free. This may be \c NULL,
+ * in which case this function does nothing. If it is not
+ * \c NULL, it must point to an initialized ECJPAKE context.
+ */
+void mbedtls_ecjpake_free(mbedtls_ecjpake_context *ctx);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if a test failed
+ */
+int mbedtls_ecjpake_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* ecjpake.h */
diff --git a/include/mbedtls/ecp.h b/include/mbedtls/ecp.h
new file mode 100644
index 0000000..7f5e880
--- /dev/null
+++ b/include/mbedtls/ecp.h
@@ -0,0 +1,1362 @@
+/**
+ * \file ecp.h
+ *
+ * \brief This file provides an API for Elliptic Curves over GF(P) (ECP).
+ *
+ * The use of ECP in cryptography and TLS is defined in
+ * <em>Standards for Efficient Cryptography Group (SECG): SEC1
+ * Elliptic Curve Cryptography</em> and
+ * <em>RFC-4492: Elliptic Curve Cryptography (ECC) Cipher Suites
+ * for Transport Layer Security (TLS)</em>.
+ *
+ * <em>RFC-2409: The Internet Key Exchange (IKE)</em> defines ECP
+ * group types.
+ *
+ */
+
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_ECP_H
+#define MBEDTLS_ECP_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/bignum.h"
+
+/*
+ * ECP error codes
+ */
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_ECP_BAD_INPUT_DATA -0x4F80
+/** The buffer is too small to write to. */
+#define MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL -0x4F00
+/** The requested feature is not available, for example, the requested curve is not supported. */
+#define MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE -0x4E80
+/** The signature is not valid. */
+#define MBEDTLS_ERR_ECP_VERIFY_FAILED -0x4E00
+/** Memory allocation failed. */
+#define MBEDTLS_ERR_ECP_ALLOC_FAILED -0x4D80
+/** Generation of random value, such as ephemeral key, failed. */
+#define MBEDTLS_ERR_ECP_RANDOM_FAILED -0x4D00
+/** Invalid private or public key. */
+#define MBEDTLS_ERR_ECP_INVALID_KEY -0x4C80
+/** The buffer contains a valid signature followed by more data. */
+#define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH -0x4C00
+/** Operation in progress, call again with the same parameters to continue. */
+#define MBEDTLS_ERR_ECP_IN_PROGRESS -0x4B00
+
+/* Flags indicating whether to include code that is specific to certain
+ * types of curves. These flags are for internal library use only. */
+#if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
+#define MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED
+#endif
+#if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) || \
+ defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
+#define MBEDTLS_ECP_MONTGOMERY_ENABLED
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Domain-parameter identifiers: curve, subgroup, and generator.
+ *
+ * \note Only curves over prime fields are supported.
+ *
+ * \warning This library does not support validation of arbitrary domain
+ * parameters. Therefore, only standardized domain parameters from trusted
+ * sources should be used. See mbedtls_ecp_group_load().
+ */
+/* Note: when adding a new curve:
+ * - Add it at the end of this enum, otherwise you'll break the ABI by
+ * changing the numerical value for existing curves.
+ * - Increment MBEDTLS_ECP_DP_MAX below if needed.
+ * - Update the calculation of MBEDTLS_ECP_MAX_BITS below.
+ * - Add the corresponding MBEDTLS_ECP_DP_xxx_ENABLED macro definition to
+ * mbedtls_config.h.
+ * - List the curve as a dependency of MBEDTLS_ECP_C and
+ * MBEDTLS_ECDSA_C if supported in check_config.h.
+ * - Add the curve to the appropriate curve type macro
+ * MBEDTLS_ECP_yyy_ENABLED above.
+ * - Add the necessary definitions to ecp_curves.c.
+ * - Add the curve to the ecp_supported_curves array in ecp.c.
+ * - Add the curve to applicable profiles in x509_crt.c.
+ * - Add the curve to applicable presets in ssl_tls.c.
+ */
+typedef enum {
+ MBEDTLS_ECP_DP_NONE = 0, /*!< Curve not defined. */
+ MBEDTLS_ECP_DP_SECP192R1, /*!< Domain parameters for the 192-bit curve defined by FIPS 186-4 and SEC1. */
+ MBEDTLS_ECP_DP_SECP224R1, /*!< Domain parameters for the 224-bit curve defined by FIPS 186-4 and SEC1. */
+ MBEDTLS_ECP_DP_SECP256R1, /*!< Domain parameters for the 256-bit curve defined by FIPS 186-4 and SEC1. */
+ MBEDTLS_ECP_DP_SECP384R1, /*!< Domain parameters for the 384-bit curve defined by FIPS 186-4 and SEC1. */
+ MBEDTLS_ECP_DP_SECP521R1, /*!< Domain parameters for the 521-bit curve defined by FIPS 186-4 and SEC1. */
+ MBEDTLS_ECP_DP_BP256R1, /*!< Domain parameters for 256-bit Brainpool curve. */
+ MBEDTLS_ECP_DP_BP384R1, /*!< Domain parameters for 384-bit Brainpool curve. */
+ MBEDTLS_ECP_DP_BP512R1, /*!< Domain parameters for 512-bit Brainpool curve. */
+ MBEDTLS_ECP_DP_CURVE25519, /*!< Domain parameters for Curve25519. */
+ MBEDTLS_ECP_DP_SECP192K1, /*!< Domain parameters for 192-bit "Koblitz" curve. */
+ MBEDTLS_ECP_DP_SECP224K1, /*!< Domain parameters for 224-bit "Koblitz" curve. */
+ MBEDTLS_ECP_DP_SECP256K1, /*!< Domain parameters for 256-bit "Koblitz" curve. */
+ MBEDTLS_ECP_DP_CURVE448, /*!< Domain parameters for Curve448. */
+} mbedtls_ecp_group_id;
+
+/**
+ * The number of supported curves, plus one for #MBEDTLS_ECP_DP_NONE.
+ */
+#define MBEDTLS_ECP_DP_MAX 14
+
+/*
+ * Curve types
+ */
+typedef enum {
+ MBEDTLS_ECP_TYPE_NONE = 0,
+ MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS, /* y^2 = x^3 + a x + b */
+ MBEDTLS_ECP_TYPE_MONTGOMERY, /* y^2 = x^3 + a x^2 + x */
+} mbedtls_ecp_curve_type;
+
+/**
+ * Curve information, for use by other modules.
+ *
+ * The fields of this structure are part of the public API and can be
+ * accessed directly by applications. Future versions of the library may
+ * add extra fields or reorder existing fields.
+ */
+typedef struct mbedtls_ecp_curve_info {
+ mbedtls_ecp_group_id grp_id; /*!< An internal identifier. */
+ uint16_t tls_id; /*!< The TLS NamedCurve identifier. */
+ uint16_t bit_size; /*!< The curve size in bits. */
+ const char *name; /*!< A human-friendly name. */
+} mbedtls_ecp_curve_info;
+
+/**
+ * \brief The ECP point structure, in Jacobian coordinates.
+ *
+ * \note All functions expect and return points satisfying
+ * the following condition: <code>Z == 0</code> or
+ * <code>Z == 1</code>. Other values of \p Z are
+ * used only by internal functions.
+ * The point is zero, or "at infinity", if <code>Z == 0</code>.
+ * Otherwise, \p X and \p Y are its standard (affine)
+ * coordinates.
+ */
+typedef struct mbedtls_ecp_point {
+ mbedtls_mpi MBEDTLS_PRIVATE(X); /*!< The X coordinate of the ECP point. */
+ mbedtls_mpi MBEDTLS_PRIVATE(Y); /*!< The Y coordinate of the ECP point. */
+ mbedtls_mpi MBEDTLS_PRIVATE(Z); /*!< The Z coordinate of the ECP point. */
+}
+mbedtls_ecp_point;
+
+#if !defined(MBEDTLS_ECP_ALT)
+/*
+ * default Mbed TLS elliptic curve arithmetic implementation
+ *
+ * (in case MBEDTLS_ECP_ALT is defined then the developer has to provide an
+ * alternative implementation for the whole module and it will replace this
+ * one.)
+ */
+
+/**
+ * \brief The ECP group structure.
+ *
+ * We consider two types of curve equations:
+ * <ul><li>Short Weierstrass: <code>y^2 = x^3 + A x + B mod P</code>
+ * (SEC1 + RFC-4492)</li>
+ * <li>Montgomery: <code>y^2 = x^3 + A x^2 + x mod P</code> (Curve25519,
+ * Curve448)</li></ul>
+ * In both cases, the generator (\p G) for a prime-order subgroup is fixed.
+ *
+ * For Short Weierstrass, this subgroup is the whole curve, and its
+ * cardinality is denoted by \p N. Our code requires that \p N is an
+ * odd prime as mbedtls_ecp_mul() requires an odd number, and
+ * mbedtls_ecdsa_sign() requires that it is prime for blinding purposes.
+ *
+ * The default implementation only initializes \p A without setting it to the
+ * authentic value for curves with <code>A = -3</code>(SECP256R1, etc), in which
+ * case you need to load \p A by yourself when using domain parameters directly,
+ * for example:
+ * \code
+ * mbedtls_mpi_init(&A);
+ * mbedtls_ecp_group_init(&grp);
+ * CHECK_RETURN(mbedtls_ecp_group_load(&grp, grp_id));
+ * if (mbedtls_ecp_group_a_is_minus_3(&grp)) {
+ * CHECK_RETURN(mbedtls_mpi_sub_int(&A, &grp.P, 3));
+ * } else {
+ * CHECK_RETURN(mbedtls_mpi_copy(&A, &grp.A));
+ * }
+ *
+ * do_something_with_a(&A);
+ *
+ * cleanup:
+ * mbedtls_mpi_free(&A);
+ * mbedtls_ecp_group_free(&grp);
+ * \endcode
+ *
+ * For Montgomery curves, we do not store \p A, but <code>(A + 2) / 4</code>,
+ * which is the quantity used in the formulas. Additionally, \p nbits is
+ * not the size of \p N but the required size for private keys.
+ *
+ * If \p modp is NULL, reduction modulo \p P is done using a generic algorithm.
+ * Otherwise, \p modp must point to a function that takes an \p mbedtls_mpi in the
+ * range of <code>0..2^(2*pbits)-1</code>, and transforms it in-place to an integer
+ * which is congruent mod \p P to the given MPI, and is close enough to \p pbits
+ * in size, so that it may be efficiently brought in the 0..P-1 range by a few
+ * additions or subtractions. Therefore, it is only an approximative modular
+ * reduction. It must return 0 on success and non-zero on failure.
+ *
+ * \note Alternative implementations of the ECP module must obey the
+ * following constraints.
+ * * Group IDs must be distinct: if two group structures have
+ * the same ID, then they must be identical.
+ * * The fields \c id, \c P, \c A, \c B, \c G, \c N,
+ * \c pbits and \c nbits must have the same type and semantics
+ * as in the built-in implementation.
+ * They must be available for reading, but direct modification
+ * of these fields does not need to be supported.
+ * They do not need to be at the same offset in the structure.
+ */
+typedef struct mbedtls_ecp_group {
+ mbedtls_ecp_group_id id; /*!< An internal group identifier. */
+ mbedtls_mpi P; /*!< The prime modulus of the base field. */
+ mbedtls_mpi A; /*!< For Short Weierstrass: \p A in the equation. Note that
+ \p A is not set to the authentic value in some cases.
+ Refer to detailed description of ::mbedtls_ecp_group if
+ using domain parameters in the structure.
+ For Montgomery curves: <code>(A + 2) / 4</code>. */
+ mbedtls_mpi B; /*!< For Short Weierstrass: \p B in the equation.
+ For Montgomery curves: unused. */
+ mbedtls_ecp_point G; /*!< The generator of the subgroup used. */
+ mbedtls_mpi N; /*!< The order of \p G. */
+ size_t pbits; /*!< The number of bits in \p P.*/
+ size_t nbits; /*!< For Short Weierstrass: The number of bits in \p P.
+ For Montgomery curves: the number of bits in the
+ private keys. */
+ /* End of public fields */
+
+ unsigned int MBEDTLS_PRIVATE(h); /*!< \internal 1 if the constants are static. */
+ int(*MBEDTLS_PRIVATE(modp))(mbedtls_mpi *); /*!< The function for fast pseudo-reduction
+ mod \p P (see above).*/
+ int(*MBEDTLS_PRIVATE(t_pre))(mbedtls_ecp_point *, void *); /*!< Unused. */
+ int(*MBEDTLS_PRIVATE(t_post))(mbedtls_ecp_point *, void *); /*!< Unused. */
+ void *MBEDTLS_PRIVATE(t_data); /*!< Unused. */
+ mbedtls_ecp_point *MBEDTLS_PRIVATE(T); /*!< Pre-computed points for ecp_mul_comb(). */
+ size_t MBEDTLS_PRIVATE(T_size); /*!< The number of dynamic allocated pre-computed points. */
+}
+mbedtls_ecp_group;
+
+/**
+ * \name SECTION: Module settings
+ *
+ * The configuration options you can set for this module are in this section.
+ * Either change them in mbedtls_config.h, or define them using the compiler command line.
+ * \{
+ */
+
+#if !defined(MBEDTLS_ECP_WINDOW_SIZE)
+/*
+ * Maximum "window" size used for point multiplication.
+ * Default: a point where higher memory usage yields diminishing performance
+ * returns.
+ * Minimum value: 2. Maximum value: 7.
+ *
+ * Result is an array of at most ( 1 << ( MBEDTLS_ECP_WINDOW_SIZE - 1 ) )
+ * points used for point multiplication. This value is directly tied to EC
+ * peak memory usage, so decreasing it by one should roughly cut memory usage
+ * by two (if large curves are in use).
+ *
+ * Reduction in size may reduce speed, but larger curves are impacted first.
+ * Sample performances (in ECDHE handshakes/s, with FIXED_POINT_OPTIM = 1):
+ * w-size: 6 5 4 3 2
+ * 521 145 141 135 120 97
+ * 384 214 209 198 177 146
+ * 256 320 320 303 262 226
+ * 224 475 475 453 398 342
+ * 192 640 640 633 587 476
+ */
+#define MBEDTLS_ECP_WINDOW_SIZE 4 /**< The maximum window size used. */
+#endif /* MBEDTLS_ECP_WINDOW_SIZE */
+
+#if !defined(MBEDTLS_ECP_FIXED_POINT_OPTIM)
+/*
+ * Trade code size for speed on fixed-point multiplication.
+ *
+ * This speeds up repeated multiplication of the generator (that is, the
+ * multiplication in ECDSA signatures, and half of the multiplications in
+ * ECDSA verification and ECDHE) by a factor roughly 3 to 4.
+ *
+ * For each n-bit Short Weierstrass curve that is enabled, this adds 4n bytes
+ * of code size if n < 384 and 8n otherwise.
+ *
+ * Change this value to 0 to reduce code size.
+ */
+#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up. */
+#endif /* MBEDTLS_ECP_FIXED_POINT_OPTIM */
+
+/** \} name SECTION: Module settings */
+
+#else /* MBEDTLS_ECP_ALT */
+#include "ecp_alt.h"
+#endif /* MBEDTLS_ECP_ALT */
+
+/**
+ * The maximum size of the groups, that is, of \c N and \c P.
+ */
+#if !defined(MBEDTLS_ECP_LIGHT)
+/* Dummy definition to help code that has optional ECP support and
+ * defines an MBEDTLS_ECP_MAX_BYTES-sized array unconditionally. */
+#define MBEDTLS_ECP_MAX_BITS 1
+/* Note: the curves must be listed in DECREASING size! */
+#elif defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 521
+#elif defined(MBEDTLS_ECP_DP_BP512R1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 512
+#elif defined(MBEDTLS_ECP_DP_CURVE448_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 448
+#elif defined(MBEDTLS_ECP_DP_BP384R1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 384
+#elif defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 384
+#elif defined(MBEDTLS_ECP_DP_BP256R1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 256
+#elif defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 256
+#elif defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 256
+#elif defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 255
+#elif defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 225 // n is slightly above 2^224
+#elif defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 224
+#elif defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 192
+#elif defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED)
+#define MBEDTLS_ECP_MAX_BITS 192
+#else /* !MBEDTLS_ECP_LIGHT */
+#error "Missing definition of MBEDTLS_ECP_MAX_BITS"
+#endif /* !MBEDTLS_ECP_LIGHT */
+
+#define MBEDTLS_ECP_MAX_BYTES ((MBEDTLS_ECP_MAX_BITS + 7) / 8)
+#define MBEDTLS_ECP_MAX_PT_LEN (2 * MBEDTLS_ECP_MAX_BYTES + 1)
+
+#if defined(MBEDTLS_ECP_RESTARTABLE)
+
+/**
+ * \brief Internal restart context for multiplication
+ *
+ * \note Opaque struct
+ */
+typedef struct mbedtls_ecp_restart_mul mbedtls_ecp_restart_mul_ctx;
+
+/**
+ * \brief Internal restart context for ecp_muladd()
+ *
+ * \note Opaque struct
+ */
+typedef struct mbedtls_ecp_restart_muladd mbedtls_ecp_restart_muladd_ctx;
+
+/**
+ * \brief General context for resuming ECC operations
+ */
+typedef struct {
+ unsigned MBEDTLS_PRIVATE(ops_done); /*!< current ops count */
+ unsigned MBEDTLS_PRIVATE(depth); /*!< call depth (0 = top-level) */
+ mbedtls_ecp_restart_mul_ctx *MBEDTLS_PRIVATE(rsm); /*!< ecp_mul_comb() sub-context */
+ mbedtls_ecp_restart_muladd_ctx *MBEDTLS_PRIVATE(ma); /*!< ecp_muladd() sub-context */
+} mbedtls_ecp_restart_ctx;
+
+/*
+ * Operation counts for restartable functions
+ */
+#define MBEDTLS_ECP_OPS_CHK 3 /*!< basic ops count for ecp_check_pubkey() */
+#define MBEDTLS_ECP_OPS_DBL 8 /*!< basic ops count for ecp_double_jac() */
+#define MBEDTLS_ECP_OPS_ADD 11 /*!< basic ops count for see ecp_add_mixed() */
+#define MBEDTLS_ECP_OPS_INV 120 /*!< empirical equivalent for mpi_mod_inv() */
+
+/**
+ * \brief Internal; for restartable functions in other modules.
+ * Check and update basic ops budget.
+ *
+ * \param grp Group structure
+ * \param rs_ctx Restart context
+ * \param ops Number of basic ops to do
+ *
+ * \return \c 0 if doing \p ops basic ops is still allowed,
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS otherwise.
+ */
+int mbedtls_ecp_check_budget(const mbedtls_ecp_group *grp,
+ mbedtls_ecp_restart_ctx *rs_ctx,
+ unsigned ops);
+
+/* Utility macro for checking and updating ops budget */
+#define MBEDTLS_ECP_BUDGET(ops) \
+ MBEDTLS_MPI_CHK(mbedtls_ecp_check_budget(grp, rs_ctx, \
+ (unsigned) (ops)));
+
+#else /* MBEDTLS_ECP_RESTARTABLE */
+
+#define MBEDTLS_ECP_BUDGET(ops) /* no-op; for compatibility */
+
+/* We want to declare restartable versions of existing functions anyway */
+typedef void mbedtls_ecp_restart_ctx;
+
+#endif /* MBEDTLS_ECP_RESTARTABLE */
+
+/**
+ * \brief The ECP key-pair structure.
+ *
+ * A generic key-pair that may be used for ECDSA and fixed ECDH, for example.
+ *
+ * \note Members are deliberately in the same order as in the
+ * ::mbedtls_ecdsa_context structure.
+ */
+typedef struct mbedtls_ecp_keypair {
+ mbedtls_ecp_group MBEDTLS_PRIVATE(grp); /*!< Elliptic curve and base point */
+ mbedtls_mpi MBEDTLS_PRIVATE(d); /*!< our secret value */
+ mbedtls_ecp_point MBEDTLS_PRIVATE(Q); /*!< our public value */
+}
+mbedtls_ecp_keypair;
+
+/**
+ * The uncompressed point format for Short Weierstrass curves
+ * (MBEDTLS_ECP_DP_SECP_XXX and MBEDTLS_ECP_DP_BP_XXX).
+ */
+#define MBEDTLS_ECP_PF_UNCOMPRESSED 0
+/**
+ * The compressed point format for Short Weierstrass curves
+ * (MBEDTLS_ECP_DP_SECP_XXX and MBEDTLS_ECP_DP_BP_XXX).
+ *
+ * \warning While this format is supported for all concerned curves for
+ * writing, when it comes to parsing, it is not supported for all
+ * curves. Specifically, parsing compressed points on
+ * MBEDTLS_ECP_DP_SECP224R1 and MBEDTLS_ECP_DP_SECP224K1 is not
+ * supported.
+ */
+#define MBEDTLS_ECP_PF_COMPRESSED 1
+
+/*
+ * Some other constants from RFC 4492
+ */
+#define MBEDTLS_ECP_TLS_NAMED_CURVE 3 /**< The named_curve of ECCurveType. */
+
+#if defined(MBEDTLS_ECP_RESTARTABLE)
+/**
+ * \brief Set the maximum number of basic operations done in a row.
+ *
+ * If more operations are needed to complete a computation,
+ * #MBEDTLS_ERR_ECP_IN_PROGRESS will be returned by the
+ * function performing the computation. It is then the
+ * caller's responsibility to either call again with the same
+ * parameters until it returns 0 or an error code; or to free
+ * the restart context if the operation is to be aborted.
+ *
+ * It is strictly required that all input parameters and the
+ * restart context be the same on successive calls for the
+ * same operation, but output parameters need not be the
+ * same; they must not be used until the function finally
+ * returns 0.
+ *
+ * This only applies to functions whose documentation
+ * mentions they may return #MBEDTLS_ERR_ECP_IN_PROGRESS (or
+ * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS for functions in the
+ * SSL module). For functions that accept a "restart context"
+ * argument, passing NULL disables restart and makes the
+ * function equivalent to the function with the same name
+ * with \c _restartable removed. For functions in the ECDH
+ * module, restart is disabled unless the function accepts
+ * an "ECDH context" argument and
+ * mbedtls_ecdh_enable_restart() was previously called on
+ * that context. For function in the SSL module, restart is
+ * only enabled for specific sides and key exchanges
+ * (currently only for clients and ECDHE-ECDSA).
+ *
+ * \warning Using the PSA interruptible interfaces with keys in local
+ * storage and no accelerator driver will also call this
+ * function to set the values specified via those interfaces,
+ * overwriting values previously set. Care should be taken if
+ * mixing these two interfaces.
+ *
+ * \param max_ops Maximum number of basic operations done in a row.
+ * Default: 0 (unlimited).
+ * Lower (non-zero) values mean ECC functions will block for
+ * a lesser maximum amount of time.
+ *
+ * \note A "basic operation" is defined as a rough equivalent of a
+ * multiplication in GF(p) for the NIST P-256 curve.
+ * As an indication, with default settings, a scalar
+ * multiplication (full run of \c mbedtls_ecp_mul()) is:
+ * - about 3300 basic operations for P-256
+ * - about 9400 basic operations for P-384
+ *
+ * \note Very low values are not always respected: sometimes
+ * functions need to block for a minimum number of
+ * operations, and will do so even if max_ops is set to a
+ * lower value. That minimum depends on the curve size, and
+ * can be made lower by decreasing the value of
+ * \c MBEDTLS_ECP_WINDOW_SIZE. As an indication, here is the
+ * lowest effective value for various curves and values of
+ * that parameter (w for short):
+ * w=6 w=5 w=4 w=3 w=2
+ * P-256 208 208 160 136 124
+ * P-384 682 416 320 272 248
+ * P-521 1364 832 640 544 496
+ *
+ * \note This setting is currently ignored by Curve25519.
+ */
+void mbedtls_ecp_set_max_ops(unsigned max_ops);
+
+/**
+ * \brief Check if restart is enabled (max_ops != 0)
+ *
+ * \return \c 0 if \c max_ops == 0 (restart disabled)
+ * \return \c 1 otherwise (restart enabled)
+ */
+int mbedtls_ecp_restart_is_enabled(void);
+#endif /* MBEDTLS_ECP_RESTARTABLE */
+
+/*
+ * Get the type of a curve
+ */
+mbedtls_ecp_curve_type mbedtls_ecp_get_type(const mbedtls_ecp_group *grp);
+
+/**
+ * \brief This function retrieves the information defined in
+ * mbedtls_ecp_curve_info() for all supported curves.
+ *
+ * \note This function returns information about all curves
+ * supported by the library. Some curves may not be
+ * supported for all algorithms. Call mbedtls_ecdh_can_do()
+ * or mbedtls_ecdsa_can_do() to check if a curve is
+ * supported for ECDH or ECDSA.
+ *
+ * \return A statically allocated array. The last entry is 0.
+ */
+const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list(void);
+
+/**
+ * \brief This function retrieves the list of internal group
+ * identifiers of all supported curves in the order of
+ * preference.
+ *
+ * \note This function returns information about all curves
+ * supported by the library. Some curves may not be
+ * supported for all algorithms. Call mbedtls_ecdh_can_do()
+ * or mbedtls_ecdsa_can_do() to check if a curve is
+ * supported for ECDH or ECDSA.
+ *
+ * \return A statically allocated array,
+ * terminated with MBEDTLS_ECP_DP_NONE.
+ */
+const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list(void);
+
+/**
+ * \brief This function retrieves curve information from an internal
+ * group identifier.
+ *
+ * \param grp_id An \c MBEDTLS_ECP_DP_XXX value.
+ *
+ * \return The associated curve information on success.
+ * \return NULL on failure.
+ */
+const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id(mbedtls_ecp_group_id grp_id);
+
+/**
+ * \brief This function retrieves curve information from a TLS
+ * NamedCurve value.
+ *
+ * \param tls_id An \c MBEDTLS_ECP_DP_XXX value.
+ *
+ * \return The associated curve information on success.
+ * \return NULL on failure.
+ */
+const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id(uint16_t tls_id);
+
+/**
+ * \brief This function retrieves curve information from a
+ * human-readable name.
+ *
+ * \param name The human-readable name.
+ *
+ * \return The associated curve information on success.
+ * \return NULL on failure.
+ */
+const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name(const char *name);
+
+/**
+ * \brief This function initializes a point as zero.
+ *
+ * \param pt The point to initialize.
+ */
+void mbedtls_ecp_point_init(mbedtls_ecp_point *pt);
+
+/**
+ * \brief This function initializes an ECP group context
+ * without loading any domain parameters.
+ *
+ * \note After this function is called, domain parameters
+ * for various ECP groups can be loaded through the
+ * mbedtls_ecp_group_load() or mbedtls_ecp_tls_read_group()
+ * functions.
+ */
+void mbedtls_ecp_group_init(mbedtls_ecp_group *grp);
+
+/**
+ * \brief This function initializes a key pair as an invalid one.
+ *
+ * \param key The key pair to initialize.
+ */
+void mbedtls_ecp_keypair_init(mbedtls_ecp_keypair *key);
+
+/**
+ * \brief This function frees the components of a point.
+ *
+ * \param pt The point to free.
+ */
+void mbedtls_ecp_point_free(mbedtls_ecp_point *pt);
+
+/**
+ * \brief This function frees the components of an ECP group.
+ *
+ * \param grp The group to free. This may be \c NULL, in which
+ * case this function returns immediately. If it is not
+ * \c NULL, it must point to an initialized ECP group.
+ */
+void mbedtls_ecp_group_free(mbedtls_ecp_group *grp);
+
+/**
+ * \brief This function frees the components of a key pair.
+ *
+ * \param key The key pair to free. This may be \c NULL, in which
+ * case this function returns immediately. If it is not
+ * \c NULL, it must point to an initialized ECP key pair.
+ */
+void mbedtls_ecp_keypair_free(mbedtls_ecp_keypair *key);
+
+#if defined(MBEDTLS_ECP_RESTARTABLE)
+/**
+ * \brief Initialize a restart context.
+ *
+ * \param ctx The restart context to initialize. This must
+ * not be \c NULL.
+ */
+void mbedtls_ecp_restart_init(mbedtls_ecp_restart_ctx *ctx);
+
+/**
+ * \brief Free the components of a restart context.
+ *
+ * \param ctx The restart context to free. This may be \c NULL, in which
+ * case this function returns immediately. If it is not
+ * \c NULL, it must point to an initialized restart context.
+ */
+void mbedtls_ecp_restart_free(mbedtls_ecp_restart_ctx *ctx);
+#endif /* MBEDTLS_ECP_RESTARTABLE */
+
+/**
+ * \brief This function copies the contents of point \p Q into
+ * point \p P.
+ *
+ * \param P The destination point. This must be initialized.
+ * \param Q The source point. This must be initialized.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
+ * \return Another negative error code for other kinds of failure.
+ */
+int mbedtls_ecp_copy(mbedtls_ecp_point *P, const mbedtls_ecp_point *Q);
+
+/**
+ * \brief This function copies the contents of group \p src into
+ * group \p dst.
+ *
+ * \param dst The destination group. This must be initialized.
+ * \param src The source group. This must be initialized.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_group_copy(mbedtls_ecp_group *dst,
+ const mbedtls_ecp_group *src);
+
+/**
+ * \brief This function sets a point to the point at infinity.
+ *
+ * \param pt The point to set. This must be initialized.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_set_zero(mbedtls_ecp_point *pt);
+
+/**
+ * \brief This function checks if a point is the point at infinity.
+ *
+ * \param pt The point to test. This must be initialized.
+ *
+ * \return \c 1 if the point is zero.
+ * \return \c 0 if the point is non-zero.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ecp_is_zero(mbedtls_ecp_point *pt);
+
+/**
+ * \brief This function compares two points.
+ *
+ * \note This assumes that the points are normalized. Otherwise,
+ * they may compare as "not equal" even if they are.
+ *
+ * \param P The first point to compare. This must be initialized.
+ * \param Q The second point to compare. This must be initialized.
+ *
+ * \return \c 0 if the points are equal.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the points are not equal.
+ */
+int mbedtls_ecp_point_cmp(const mbedtls_ecp_point *P,
+ const mbedtls_ecp_point *Q);
+
+/**
+ * \brief This function imports a non-zero point from two ASCII
+ * strings.
+ *
+ * \param P The destination point. This must be initialized.
+ * \param radix The numeric base of the input.
+ * \param x The first affine coordinate, as a null-terminated string.
+ * \param y The second affine coordinate, as a null-terminated string.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_MPI_XXX error code on failure.
+ */
+int mbedtls_ecp_point_read_string(mbedtls_ecp_point *P, int radix,
+ const char *x, const char *y);
+
+/**
+ * \brief This function exports a point into unsigned binary data.
+ *
+ * \param grp The group to which the point should belong.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param P The point to export. This must be initialized.
+ * \param format The point format. This must be either
+ * #MBEDTLS_ECP_PF_COMPRESSED or #MBEDTLS_ECP_PF_UNCOMPRESSED.
+ * (For groups without these formats, this parameter is
+ * ignored. But it still has to be either of the above
+ * values.)
+ * \param olen The address at which to store the length of
+ * the output in Bytes. This must not be \c NULL.
+ * \param buf The output buffer. This must be a writable buffer
+ * of length \p buflen Bytes.
+ * \param buflen The length of the output buffer \p buf in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the output buffer
+ * is too small to hold the point.
+ * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the point format
+ * or the export for the given group is not implemented.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_point_write_binary(const mbedtls_ecp_group *grp,
+ const mbedtls_ecp_point *P,
+ int format, size_t *olen,
+ unsigned char *buf, size_t buflen);
+
+/**
+ * \brief This function imports a point from unsigned binary data.
+ *
+ * \note This function does not check that the point actually
+ * belongs to the given group, see mbedtls_ecp_check_pubkey()
+ * for that.
+ *
+ * \note For compressed points, see #MBEDTLS_ECP_PF_COMPRESSED for
+ * limitations.
+ *
+ * \param grp The group to which the point should belong.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param P The destination context to import the point to.
+ * This must be initialized.
+ * \param buf The input buffer. This must be a readable buffer
+ * of length \p ilen Bytes.
+ * \param ilen The length of the input buffer \p buf in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the input is invalid.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
+ * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the import for the
+ * given group is not implemented.
+ */
+int mbedtls_ecp_point_read_binary(const mbedtls_ecp_group *grp,
+ mbedtls_ecp_point *P,
+ const unsigned char *buf, size_t ilen);
+
+/**
+ * \brief This function imports a point from a TLS ECPoint record.
+ *
+ * \note On function return, \p *buf is updated to point immediately
+ * after the ECPoint record.
+ *
+ * \param grp The ECP group to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param pt The destination point.
+ * \param buf The address of the pointer to the start of the input buffer.
+ * \param len The length of the buffer.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_MPI_XXX error code on initialization
+ * failure.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid.
+ */
+int mbedtls_ecp_tls_read_point(const mbedtls_ecp_group *grp,
+ mbedtls_ecp_point *pt,
+ const unsigned char **buf, size_t len);
+
+/**
+ * \brief This function exports a point as a TLS ECPoint record
+ * defined in RFC 4492, Section 5.4.
+ *
+ * \param grp The ECP group to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param pt The point to be exported. This must be initialized.
+ * \param format The point format to use. This must be either
+ * #MBEDTLS_ECP_PF_COMPRESSED or #MBEDTLS_ECP_PF_UNCOMPRESSED.
+ * \param olen The address at which to store the length in Bytes
+ * of the data written.
+ * \param buf The target buffer. This must be a writable buffer of
+ * length \p blen Bytes.
+ * \param blen The length of the target buffer \p buf in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the input is invalid.
+ * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the target buffer
+ * is too small to hold the exported point.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_tls_write_point(const mbedtls_ecp_group *grp,
+ const mbedtls_ecp_point *pt,
+ int format, size_t *olen,
+ unsigned char *buf, size_t blen);
+
+/**
+ * \brief This function sets up an ECP group context
+ * from a standardized set of domain parameters.
+ *
+ * \note The index should be a value of the NamedCurve enum,
+ * as defined in <em>RFC-4492: Elliptic Curve Cryptography
+ * (ECC) Cipher Suites for Transport Layer Security (TLS)</em>,
+ * usually in the form of an \c MBEDTLS_ECP_DP_XXX macro.
+ *
+ * \param grp The group context to setup. This must be initialized.
+ * \param id The identifier of the domain parameter set to load.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if \p id doesn't
+ * correspond to a known group.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_group_load(mbedtls_ecp_group *grp, mbedtls_ecp_group_id id);
+
+/**
+ * \brief This function sets up an ECP group context from a TLS
+ * ECParameters record as defined in RFC 4492, Section 5.4.
+ *
+ * \note The read pointer \p buf is updated to point right after
+ * the ECParameters record on exit.
+ *
+ * \param grp The group context to setup. This must be initialized.
+ * \param buf The address of the pointer to the start of the input buffer.
+ * \param len The length of the input buffer \c *buf in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid.
+ * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the group is not
+ * recognized.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_tls_read_group(mbedtls_ecp_group *grp,
+ const unsigned char **buf, size_t len);
+
+/**
+ * \brief This function extracts an elliptic curve group ID from a
+ * TLS ECParameters record as defined in RFC 4492, Section 5.4.
+ *
+ * \note The read pointer \p buf is updated to point right after
+ * the ECParameters record on exit.
+ *
+ * \param grp The address at which to store the group id.
+ * This must not be \c NULL.
+ * \param buf The address of the pointer to the start of the input buffer.
+ * \param len The length of the input buffer \c *buf in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid.
+ * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the group is not
+ * recognized.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_tls_read_group_id(mbedtls_ecp_group_id *grp,
+ const unsigned char **buf,
+ size_t len);
+/**
+ * \brief This function exports an elliptic curve as a TLS
+ * ECParameters record as defined in RFC 4492, Section 5.4.
+ *
+ * \param grp The ECP group to be exported.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param olen The address at which to store the number of Bytes written.
+ * This must not be \c NULL.
+ * \param buf The buffer to write to. This must be a writable buffer
+ * of length \p blen Bytes.
+ * \param blen The length of the output buffer \p buf in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the output
+ * buffer is too small to hold the exported group.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_tls_write_group(const mbedtls_ecp_group *grp,
+ size_t *olen,
+ unsigned char *buf, size_t blen);
+
+/**
+ * \brief This function performs a scalar multiplication of a point
+ * by an integer: \p R = \p m * \p P.
+ *
+ * It is not thread-safe to use same group in multiple threads.
+ *
+ * \note To prevent timing attacks, this function
+ * executes the exact same sequence of base-field
+ * operations for any valid \p m. It avoids any if-branch or
+ * array index depending on the value of \p m. It also uses
+ * \p f_rng to randomize some intermediate results.
+ *
+ * \param grp The ECP group to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param R The point in which to store the result of the calculation.
+ * This must be initialized.
+ * \param m The integer by which to multiply. This must be initialized.
+ * \param P The point to multiply. This must be initialized.
+ * \param f_rng The RNG function. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be \c
+ * NULL if \p f_rng doesn't need a context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private
+ * key, or \p P is not a valid public key.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_mul(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
+ const mbedtls_mpi *m, const mbedtls_ecp_point *P,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
+
+/**
+ * \brief This function performs multiplication of a point by
+ * an integer: \p R = \p m * \p P in a restartable way.
+ *
+ * \see mbedtls_ecp_mul()
+ *
+ * \note This function does the same as \c mbedtls_ecp_mul(), but
+ * it can return early and restart according to the limit set
+ * with \c mbedtls_ecp_set_max_ops() to reduce blocking.
+ *
+ * \param grp The ECP group to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param R The point in which to store the result of the calculation.
+ * This must be initialized.
+ * \param m The integer by which to multiply. This must be initialized.
+ * \param P The point to multiply. This must be initialized.
+ * \param f_rng The RNG function. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be \c
+ * NULL if \p f_rng doesn't need a context.
+ * \param rs_ctx The restart context (NULL disables restart).
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private
+ * key, or \p P is not a valid public key.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_mul_restartable(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
+ const mbedtls_mpi *m, const mbedtls_ecp_point *P,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
+ mbedtls_ecp_restart_ctx *rs_ctx);
+
+#if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED)
+/**
+ * \brief This function checks if domain parameter A of the curve is
+ * \c -3.
+ *
+ * \note This function is only defined for short Weierstrass curves.
+ * It may not be included in builds without any short
+ * Weierstrass curve.
+ *
+ * \param grp The ECP group to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ *
+ * \return \c 1 if <code>A = -3</code>.
+ * \return \c 0 Otherwise.
+ */
+static inline int mbedtls_ecp_group_a_is_minus_3(const mbedtls_ecp_group *grp)
+{
+ return grp->A.MBEDTLS_PRIVATE(p) == NULL;
+}
+
+/**
+ * \brief This function performs multiplication and addition of two
+ * points by integers: \p R = \p m * \p P + \p n * \p Q
+ *
+ * It is not thread-safe to use same group in multiple threads.
+ *
+ * \note In contrast to mbedtls_ecp_mul(), this function does not
+ * guarantee a constant execution flow and timing.
+ *
+ * \note This function is only defined for short Weierstrass curves.
+ * It may not be included in builds without any short
+ * Weierstrass curve.
+ *
+ * \param grp The ECP group to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param R The point in which to store the result of the calculation.
+ * This must be initialized.
+ * \param m The integer by which to multiply \p P.
+ * This must be initialized.
+ * \param P The point to multiply by \p m. This must be initialized.
+ * \param n The integer by which to multiply \p Q.
+ * This must be initialized.
+ * \param Q The point to be multiplied by \p n.
+ * This must be initialized.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not
+ * valid private keys, or \p P or \p Q are not valid public
+ * keys.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
+ * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if \p grp does not
+ * designate a short Weierstrass curve.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_muladd(mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
+ const mbedtls_mpi *m, const mbedtls_ecp_point *P,
+ const mbedtls_mpi *n, const mbedtls_ecp_point *Q);
+
+/**
+ * \brief This function performs multiplication and addition of two
+ * points by integers: \p R = \p m * \p P + \p n * \p Q in a
+ * restartable way.
+ *
+ * \see \c mbedtls_ecp_muladd()
+ *
+ * \note This function works the same as \c mbedtls_ecp_muladd(),
+ * but it can return early and restart according to the limit
+ * set with \c mbedtls_ecp_set_max_ops() to reduce blocking.
+ *
+ * \note This function is only defined for short Weierstrass curves.
+ * It may not be included in builds without any short
+ * Weierstrass curve.
+ *
+ * \param grp The ECP group to use.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param R The point in which to store the result of the calculation.
+ * This must be initialized.
+ * \param m The integer by which to multiply \p P.
+ * This must be initialized.
+ * \param P The point to multiply by \p m. This must be initialized.
+ * \param n The integer by which to multiply \p Q.
+ * This must be initialized.
+ * \param Q The point to be multiplied by \p n.
+ * This must be initialized.
+ * \param rs_ctx The restart context (NULL disables restart).
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not
+ * valid private keys, or \p P or \p Q are not valid public
+ * keys.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
+ * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if \p grp does not
+ * designate a short Weierstrass curve.
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_muladd_restartable(
+ mbedtls_ecp_group *grp, mbedtls_ecp_point *R,
+ const mbedtls_mpi *m, const mbedtls_ecp_point *P,
+ const mbedtls_mpi *n, const mbedtls_ecp_point *Q,
+ mbedtls_ecp_restart_ctx *rs_ctx);
+#endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */
+
+/**
+ * \brief This function checks that a point is a valid public key
+ * on this curve.
+ *
+ * It only checks that the point is non-zero, has
+ * valid coordinates and lies on the curve. It does not verify
+ * that it is indeed a multiple of \c G. This additional
+ * check is computationally more expensive, is not required
+ * by standards, and should not be necessary if the group
+ * used has a small cofactor. In particular, it is useless for
+ * the NIST groups which all have a cofactor of 1.
+ *
+ * \note This function uses bare components rather than an
+ * ::mbedtls_ecp_keypair structure, to ease use with other
+ * structures, such as ::mbedtls_ecdh_context or
+ * ::mbedtls_ecdsa_context.
+ *
+ * \param grp The ECP group the point should belong to.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param pt The point to check. This must be initialized.
+ *
+ * \return \c 0 if the point is a valid public key.
+ * \return #MBEDTLS_ERR_ECP_INVALID_KEY if the point is not
+ * a valid public key for the given curve.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_check_pubkey(const mbedtls_ecp_group *grp,
+ const mbedtls_ecp_point *pt);
+
+/**
+ * \brief This function checks that an \c mbedtls_mpi is a
+ * valid private key for this curve.
+ *
+ * \note This function uses bare components rather than an
+ * ::mbedtls_ecp_keypair structure to ease use with other
+ * structures, such as ::mbedtls_ecdh_context or
+ * ::mbedtls_ecdsa_context.
+ *
+ * \param grp The ECP group the private key should belong to.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param d The integer to check. This must be initialized.
+ *
+ * \return \c 0 if the point is a valid private key.
+ * \return #MBEDTLS_ERR_ECP_INVALID_KEY if the point is not a valid
+ * private key for the given curve.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_check_privkey(const mbedtls_ecp_group *grp,
+ const mbedtls_mpi *d);
+
+/**
+ * \brief This function generates a private key.
+ *
+ * \param grp The ECP group to generate a private key for.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param d The destination MPI (secret part). This must be initialized.
+ * \param f_rng The RNG function. This must not be \c NULL.
+ * \param p_rng The RNG parameter to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context argument.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code
+ * on failure.
+ */
+int mbedtls_ecp_gen_privkey(const mbedtls_ecp_group *grp,
+ mbedtls_mpi *d,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function generates a keypair with a configurable base
+ * point.
+ *
+ * \note This function uses bare components rather than an
+ * ::mbedtls_ecp_keypair structure to ease use with other
+ * structures, such as ::mbedtls_ecdh_context or
+ * ::mbedtls_ecdsa_context.
+ *
+ * \param grp The ECP group to generate a key pair for.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param G The base point to use. This must be initialized
+ * and belong to \p grp. It replaces the default base
+ * point \c grp->G used by mbedtls_ecp_gen_keypair().
+ * \param d The destination MPI (secret part).
+ * This must be initialized.
+ * \param Q The destination point (public part).
+ * This must be initialized.
+ * \param f_rng The RNG function. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may
+ * be \c NULL if \p f_rng doesn't need a context argument.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code
+ * on failure.
+ */
+int mbedtls_ecp_gen_keypair_base(mbedtls_ecp_group *grp,
+ const mbedtls_ecp_point *G,
+ mbedtls_mpi *d, mbedtls_ecp_point *Q,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function generates an ECP keypair.
+ *
+ * \note This function uses bare components rather than an
+ * ::mbedtls_ecp_keypair structure to ease use with other
+ * structures, such as ::mbedtls_ecdh_context or
+ * ::mbedtls_ecdsa_context.
+ *
+ * \param grp The ECP group to generate a key pair for.
+ * This must be initialized and have group parameters
+ * set, for example through mbedtls_ecp_group_load().
+ * \param d The destination MPI (secret part).
+ * This must be initialized.
+ * \param Q The destination point (public part).
+ * This must be initialized.
+ * \param f_rng The RNG function. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may
+ * be \c NULL if \p f_rng doesn't need a context argument.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code
+ * on failure.
+ */
+int mbedtls_ecp_gen_keypair(mbedtls_ecp_group *grp, mbedtls_mpi *d,
+ mbedtls_ecp_point *Q,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function generates an ECP key.
+ *
+ * \param grp_id The ECP group identifier.
+ * \param key The destination key. This must be initialized.
+ * \param f_rng The RNG function to use. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may
+ * be \c NULL if \p f_rng doesn't need a context argument.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code
+ * on failure.
+ */
+int mbedtls_ecp_gen_key(mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief This function reads an elliptic curve private key.
+ *
+ * \param grp_id The ECP group identifier.
+ * \param key The destination key.
+ * \param buf The buffer containing the binary representation of the
+ * key. (Big endian integer for Weierstrass curves, byte
+ * string for Montgomery curves.)
+ * \param buflen The length of the buffer in bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_INVALID_KEY error if the key is
+ * invalid.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed.
+ * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the operation for
+ * the group is not implemented.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_ecp_read_key(mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key,
+ const unsigned char *buf, size_t buflen);
+
+/**
+ * \brief This function exports an elliptic curve private key.
+ *
+ * \param key The private key.
+ * \param buf The output buffer for containing the binary representation
+ * of the key. (Big endian integer for Weierstrass curves, byte
+ * string for Montgomery curves.)
+ * \param buflen The total length of the buffer in bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the \p key
+ representation is larger than the available space in \p buf.
+ * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the operation for
+ * the group is not implemented.
+ * \return Another negative error code on different kinds of failure.
+ */
+int mbedtls_ecp_write_key(mbedtls_ecp_keypair *key,
+ unsigned char *buf, size_t buflen);
+
+/**
+ * \brief This function checks that the keypair objects
+ * \p pub and \p prv have the same group and the
+ * same public point, and that the private key in
+ * \p prv is consistent with the public key.
+ *
+ * \param pub The keypair structure holding the public key. This
+ * must be initialized. If it contains a private key, that
+ * part is ignored.
+ * \param prv The keypair structure holding the full keypair.
+ * This must be initialized.
+ * \param f_rng The RNG function. This must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be \c
+ * NULL if \p f_rng doesn't need a context.
+ *
+ * \return \c 0 on success, meaning that the keys are valid and match.
+ * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the keys are invalid or do not match.
+ * \return An \c MBEDTLS_ERR_ECP_XXX or an \c MBEDTLS_ERR_MPI_XXX
+ * error code on calculation failure.
+ */
+int mbedtls_ecp_check_pub_priv(
+ const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
+
+/**
+ * \brief This function exports generic key-pair parameters.
+ *
+ * \param key The key pair to export from.
+ * \param grp Slot for exported ECP group.
+ * It must point to an initialized ECP group.
+ * \param d Slot for the exported secret value.
+ * It must point to an initialized mpi.
+ * \param Q Slot for the exported public value.
+ * It must point to an initialized ECP point.
+ *
+ * \return \c 0 on success,
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure.
+ * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if key id doesn't
+ * correspond to a known group.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ecp_export(const mbedtls_ecp_keypair *key, mbedtls_ecp_group *grp,
+ mbedtls_mpi *d, mbedtls_ecp_point *Q);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief The ECP checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_ecp_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ecp.h */
diff --git a/include/mbedtls/entropy.h b/include/mbedtls/entropy.h
new file mode 100644
index 0000000..20fd687
--- /dev/null
+++ b/include/mbedtls/entropy.h
@@ -0,0 +1,273 @@
+/**
+ * \file entropy.h
+ *
+ * \brief Entropy accumulator implementation
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_ENTROPY_H
+#define MBEDTLS_ENTROPY_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+
+#include "md.h"
+
+#if defined(MBEDTLS_MD_CAN_SHA512) && !defined(MBEDTLS_ENTROPY_FORCE_SHA256)
+#define MBEDTLS_ENTROPY_SHA512_ACCUMULATOR
+#define MBEDTLS_ENTROPY_MD MBEDTLS_MD_SHA512
+#define MBEDTLS_ENTROPY_BLOCK_SIZE 64 /**< Block size of entropy accumulator (SHA-512) */
+#else
+#if defined(MBEDTLS_MD_CAN_SHA256)
+#define MBEDTLS_ENTROPY_SHA256_ACCUMULATOR
+#define MBEDTLS_ENTROPY_MD MBEDTLS_MD_SHA256
+#define MBEDTLS_ENTROPY_BLOCK_SIZE 32 /**< Block size of entropy accumulator (SHA-256) */
+#endif
+#endif
+
+#if defined(MBEDTLS_THREADING_C)
+#include "mbedtls/threading.h"
+#endif
+
+
+/** Critical entropy source failure. */
+#define MBEDTLS_ERR_ENTROPY_SOURCE_FAILED -0x003C
+/** No more sources can be added. */
+#define MBEDTLS_ERR_ENTROPY_MAX_SOURCES -0x003E
+/** No sources have been added to poll. */
+#define MBEDTLS_ERR_ENTROPY_NO_SOURCES_DEFINED -0x0040
+/** No strong sources have been added to poll. */
+#define MBEDTLS_ERR_ENTROPY_NO_STRONG_SOURCE -0x003D
+/** Read/write error in file. */
+#define MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR -0x003F
+
+/**
+ * \name SECTION: Module settings
+ *
+ * The configuration options you can set for this module are in this section.
+ * Either change them in mbedtls_config.h or define them on the compiler command line.
+ * \{
+ */
+
+#if !defined(MBEDTLS_ENTROPY_MAX_SOURCES)
+#define MBEDTLS_ENTROPY_MAX_SOURCES 20 /**< Maximum number of sources supported */
+#endif
+
+#if !defined(MBEDTLS_ENTROPY_MAX_GATHER)
+#define MBEDTLS_ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */
+#endif
+
+/** \} name SECTION: Module settings */
+
+#define MBEDTLS_ENTROPY_MAX_SEED_SIZE 1024 /**< Maximum size of seed we read from seed file */
+#define MBEDTLS_ENTROPY_SOURCE_MANUAL MBEDTLS_ENTROPY_MAX_SOURCES
+
+#define MBEDTLS_ENTROPY_SOURCE_STRONG 1 /**< Entropy source is strong */
+#define MBEDTLS_ENTROPY_SOURCE_WEAK 0 /**< Entropy source is weak */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Entropy poll callback pointer
+ *
+ * \param data Callback-specific data pointer
+ * \param output Data to fill
+ * \param len Maximum size to provide
+ * \param olen The actual amount of bytes put into the buffer (Can be 0)
+ *
+ * \return 0 if no critical failures occurred,
+ * MBEDTLS_ERR_ENTROPY_SOURCE_FAILED otherwise
+ */
+typedef int (*mbedtls_entropy_f_source_ptr)(void *data, unsigned char *output, size_t len,
+ size_t *olen);
+
+/**
+ * \brief Entropy source state
+ */
+typedef struct mbedtls_entropy_source_state {
+ mbedtls_entropy_f_source_ptr MBEDTLS_PRIVATE(f_source); /**< The entropy source callback */
+ void *MBEDTLS_PRIVATE(p_source); /**< The callback data pointer */
+ size_t MBEDTLS_PRIVATE(size); /**< Amount received in bytes */
+ size_t MBEDTLS_PRIVATE(threshold); /**< Minimum bytes required before release */
+ int MBEDTLS_PRIVATE(strong); /**< Is the source strong? */
+}
+mbedtls_entropy_source_state;
+
+/**
+ * \brief Entropy context structure
+ */
+typedef struct mbedtls_entropy_context {
+ mbedtls_md_context_t MBEDTLS_PRIVATE(accumulator);
+ int MBEDTLS_PRIVATE(accumulator_started); /* 0 after init.
+ * 1 after the first update.
+ * -1 after free. */
+ int MBEDTLS_PRIVATE(source_count); /* Number of entries used in source. */
+ mbedtls_entropy_source_state MBEDTLS_PRIVATE(source)[MBEDTLS_ENTROPY_MAX_SOURCES];
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_threading_mutex_t MBEDTLS_PRIVATE(mutex); /*!< mutex */
+#endif
+#if defined(MBEDTLS_ENTROPY_NV_SEED)
+ int MBEDTLS_PRIVATE(initial_entropy_run);
+#endif
+}
+mbedtls_entropy_context;
+
+#if !defined(MBEDTLS_NO_PLATFORM_ENTROPY)
+/**
+ * \brief Platform-specific entropy poll callback
+ */
+int mbedtls_platform_entropy_poll(void *data,
+ unsigned char *output, size_t len, size_t *olen);
+#endif
+
+/**
+ * \brief Initialize the context
+ *
+ * \param ctx Entropy context to initialize
+ */
+void mbedtls_entropy_init(mbedtls_entropy_context *ctx);
+
+/**
+ * \brief Free the data in the context
+ *
+ * \param ctx Entropy context to free
+ */
+void mbedtls_entropy_free(mbedtls_entropy_context *ctx);
+
+/**
+ * \brief Adds an entropy source to poll
+ * (Thread-safe if MBEDTLS_THREADING_C is enabled)
+ *
+ * \param ctx Entropy context
+ * \param f_source Entropy function
+ * \param p_source Function data
+ * \param threshold Minimum required from source before entropy is released
+ * ( with mbedtls_entropy_func() ) (in bytes)
+ * \param strong MBEDTLS_ENTROPY_SOURCE_STRONG or
+ * MBEDTLS_ENTROPY_SOURCE_WEAK.
+ * At least one strong source needs to be added.
+ * Weaker sources (such as the cycle counter) can be used as
+ * a complement.
+ *
+ * \return 0 if successful or MBEDTLS_ERR_ENTROPY_MAX_SOURCES
+ */
+int mbedtls_entropy_add_source(mbedtls_entropy_context *ctx,
+ mbedtls_entropy_f_source_ptr f_source, void *p_source,
+ size_t threshold, int strong);
+
+/**
+ * \brief Trigger an extra gather poll for the accumulator
+ * (Thread-safe if MBEDTLS_THREADING_C is enabled)
+ *
+ * \param ctx Entropy context
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
+ */
+int mbedtls_entropy_gather(mbedtls_entropy_context *ctx);
+
+/**
+ * \brief Retrieve entropy from the accumulator
+ * (Maximum length: MBEDTLS_ENTROPY_BLOCK_SIZE)
+ * (Thread-safe if MBEDTLS_THREADING_C is enabled)
+ *
+ * \param data Entropy context
+ * \param output Buffer to fill
+ * \param len Number of bytes desired, must be at most MBEDTLS_ENTROPY_BLOCK_SIZE
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
+ */
+int mbedtls_entropy_func(void *data, unsigned char *output, size_t len);
+
+/**
+ * \brief Add data to the accumulator manually
+ * (Thread-safe if MBEDTLS_THREADING_C is enabled)
+ *
+ * \param ctx Entropy context
+ * \param data Data to add
+ * \param len Length of data
+ *
+ * \return 0 if successful
+ */
+int mbedtls_entropy_update_manual(mbedtls_entropy_context *ctx,
+ const unsigned char *data, size_t len);
+
+#if defined(MBEDTLS_ENTROPY_NV_SEED)
+/**
+ * \brief Trigger an update of the seed file in NV by using the
+ * current entropy pool.
+ *
+ * \param ctx Entropy context
+ *
+ * \return 0 if successful
+ */
+int mbedtls_entropy_update_nv_seed(mbedtls_entropy_context *ctx);
+#endif /* MBEDTLS_ENTROPY_NV_SEED */
+
+#if defined(MBEDTLS_FS_IO)
+/**
+ * \brief Write a seed file
+ *
+ * \param ctx Entropy context
+ * \param path Name of the file
+ *
+ * \return 0 if successful,
+ * MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR on file error, or
+ * MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
+ */
+int mbedtls_entropy_write_seed_file(mbedtls_entropy_context *ctx, const char *path);
+
+/**
+ * \brief Read and update a seed file. Seed is added to this
+ * instance. No more than MBEDTLS_ENTROPY_MAX_SEED_SIZE bytes are
+ * read from the seed file. The rest is ignored.
+ *
+ * \param ctx Entropy context
+ * \param path Name of the file
+ *
+ * \return 0 if successful,
+ * MBEDTLS_ERR_ENTROPY_FILE_IO_ERROR on file error,
+ * MBEDTLS_ERR_ENTROPY_SOURCE_FAILED
+ */
+int mbedtls_entropy_update_seed_file(mbedtls_entropy_context *ctx, const char *path);
+#endif /* MBEDTLS_FS_IO */
+
+#if defined(MBEDTLS_SELF_TEST)
+/**
+ * \brief Checkup routine
+ *
+ * This module self-test also calls the entropy self-test,
+ * mbedtls_entropy_source_self_test();
+ *
+ * \return 0 if successful, or 1 if a test failed
+ */
+int mbedtls_entropy_self_test(int verbose);
+
+#if defined(MBEDTLS_ENTROPY_HARDWARE_ALT)
+/**
+ * \brief Checkup routine
+ *
+ * Verifies the integrity of the hardware entropy source
+ * provided by the function 'mbedtls_hardware_poll()'.
+ *
+ * Note this is the only hardware entropy source that is known
+ * at link time, and other entropy sources configured
+ * dynamically at runtime by the function
+ * mbedtls_entropy_add_source() will not be tested.
+ *
+ * \return 0 if successful, or 1 if a test failed
+ */
+int mbedtls_entropy_source_self_test(int verbose);
+#endif /* MBEDTLS_ENTROPY_HARDWARE_ALT */
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* entropy.h */
diff --git a/include/mbedtls/error.h b/include/mbedtls/error.h
new file mode 100644
index 0000000..186589a
--- /dev/null
+++ b/include/mbedtls/error.h
@@ -0,0 +1,201 @@
+/**
+ * \file error.h
+ *
+ * \brief Error to string translation
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_ERROR_H
+#define MBEDTLS_ERROR_H
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+
+/**
+ * Error code layout.
+ *
+ * Currently we try to keep all error codes within the negative space of 16
+ * bits signed integers to support all platforms (-0x0001 - -0x7FFF). In
+ * addition we'd like to give two layers of information on the error if
+ * possible.
+ *
+ * For that purpose the error codes are segmented in the following manner:
+ *
+ * 16 bit error code bit-segmentation
+ *
+ * 1 bit - Unused (sign bit)
+ * 3 bits - High level module ID
+ * 5 bits - Module-dependent error code
+ * 7 bits - Low level module errors
+ *
+ * For historical reasons, low-level error codes are divided in even and odd,
+ * even codes were assigned first, and -1 is reserved for other errors.
+ *
+ * Low-level module errors (0x0002-0x007E, 0x0001-0x007F)
+ *
+ * Module Nr Codes assigned
+ * ERROR 2 0x006E 0x0001
+ * MPI 7 0x0002-0x0010
+ * GCM 3 0x0012-0x0016 0x0013-0x0013
+ * THREADING 3 0x001A-0x001E
+ * AES 5 0x0020-0x0022 0x0021-0x0025
+ * CAMELLIA 3 0x0024-0x0026 0x0027-0x0027
+ * BASE64 2 0x002A-0x002C
+ * OID 1 0x002E-0x002E 0x000B-0x000B
+ * PADLOCK 1 0x0030-0x0030
+ * DES 2 0x0032-0x0032 0x0033-0x0033
+ * CTR_DBRG 4 0x0034-0x003A
+ * ENTROPY 3 0x003C-0x0040 0x003D-0x003F
+ * NET 13 0x0042-0x0052 0x0043-0x0049
+ * ARIA 4 0x0058-0x005E
+ * ASN1 7 0x0060-0x006C
+ * CMAC 1 0x007A-0x007A
+ * PBKDF2 1 0x007C-0x007C
+ * HMAC_DRBG 4 0x0003-0x0009
+ * CCM 3 0x000D-0x0011
+ * MD5 1 0x002F-0x002F
+ * RIPEMD160 1 0x0031-0x0031
+ * SHA1 1 0x0035-0x0035 0x0073-0x0073
+ * SHA256 1 0x0037-0x0037 0x0074-0x0074
+ * SHA512 1 0x0039-0x0039 0x0075-0x0075
+ * SHA-3 1 0x0076-0x0076
+ * CHACHA20 3 0x0051-0x0055
+ * POLY1305 3 0x0057-0x005B
+ * CHACHAPOLY 2 0x0054-0x0056
+ * PLATFORM 2 0x0070-0x0072
+ * LMS 5 0x0011-0x0019
+ *
+ * High-level module nr (3 bits - 0x0...-0x7...)
+ * Name ID Nr of Errors
+ * PEM 1 9
+ * PKCS#12 1 4 (Started from top)
+ * X509 2 20
+ * PKCS5 2 4 (Started from top)
+ * DHM 3 11
+ * PK 3 15 (Started from top)
+ * RSA 4 11
+ * ECP 4 10 (Started from top)
+ * MD 5 5
+ * HKDF 5 1 (Started from top)
+ * PKCS7 5 12 (Started from 0x5300)
+ * SSL 5 2 (Started from 0x5F00)
+ * CIPHER 6 8 (Started from 0x6080)
+ * SSL 6 22 (Started from top, plus 0x6000)
+ * SSL 7 20 (Started from 0x7000, gaps at
+ * 0x7380, 0x7900-0x7980, 0x7A80-0x7E80)
+ *
+ * Module dependent error code (5 bits 0x.00.-0x.F8.)
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Generic error */
+#define MBEDTLS_ERR_ERROR_GENERIC_ERROR -0x0001
+/** This is a bug in the library */
+#define MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED -0x006E
+
+/** Hardware accelerator failed */
+#define MBEDTLS_ERR_PLATFORM_HW_ACCEL_FAILED -0x0070
+/** The requested feature is not supported by the platform */
+#define MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED -0x0072
+
+/**
+ * \brief Combines a high-level and low-level error code together.
+ *
+ * Wrapper macro for mbedtls_error_add(). See that function for
+ * more details.
+ */
+#define MBEDTLS_ERROR_ADD(high, low) \
+ mbedtls_error_add(high, low, __FILE__, __LINE__)
+
+#if defined(MBEDTLS_TEST_HOOKS)
+/**
+ * \brief Testing hook called before adding/combining two error codes together.
+ * Only used when invasive testing is enabled via MBEDTLS_TEST_HOOKS.
+ */
+extern void (*mbedtls_test_hook_error_add)(int, int, const char *, int);
+#endif
+
+/**
+ * \brief Combines a high-level and low-level error code together.
+ *
+ * This function can be called directly however it is usually
+ * called via the #MBEDTLS_ERROR_ADD macro.
+ *
+ * While a value of zero is not a negative error code, it is still an
+ * error code (that denotes success) and can be combined with both a
+ * negative error code or another value of zero.
+ *
+ * \note When invasive testing is enabled via #MBEDTLS_TEST_HOOKS, also try to
+ * call \link mbedtls_test_hook_error_add \endlink.
+ *
+ * \param high high-level error code. See error.h for more details.
+ * \param low low-level error code. See error.h for more details.
+ * \param file file where this error code addition occurred.
+ * \param line line where this error code addition occurred.
+ */
+static inline int mbedtls_error_add(int high, int low,
+ const char *file, int line)
+{
+#if defined(MBEDTLS_TEST_HOOKS)
+ if (*mbedtls_test_hook_error_add != NULL) {
+ (*mbedtls_test_hook_error_add)(high, low, file, line);
+ }
+#endif
+ (void) file;
+ (void) line;
+
+ return high + low;
+}
+
+/**
+ * \brief Translate an Mbed TLS error code into a string representation.
+ * The result is truncated if necessary and always includes a
+ * terminating null byte.
+ *
+ * \param errnum error code
+ * \param buffer buffer to place representation in
+ * \param buflen length of the buffer
+ */
+void mbedtls_strerror(int errnum, char *buffer, size_t buflen);
+
+/**
+ * \brief Translate the high-level part of an Mbed TLS error code into a string
+ * representation.
+ *
+ * This function returns a const pointer to an un-modifiable string. The caller
+ * must not try to modify the string. It is intended to be used mostly for
+ * logging purposes.
+ *
+ * \param error_code error code
+ *
+ * \return The string representation of the error code, or \c NULL if the error
+ * code is unknown.
+ */
+const char *mbedtls_high_level_strerr(int error_code);
+
+/**
+ * \brief Translate the low-level part of an Mbed TLS error code into a string
+ * representation.
+ *
+ * This function returns a const pointer to an un-modifiable string. The caller
+ * must not try to modify the string. It is intended to be used mostly for
+ * logging purposes.
+ *
+ * \param error_code error code
+ *
+ * \return The string representation of the error code, or \c NULL if the error
+ * code is unknown.
+ */
+const char *mbedtls_low_level_strerr(int error_code);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* error.h */
diff --git a/include/mbedtls/gcm.h b/include/mbedtls/gcm.h
new file mode 100644
index 0000000..837cecc
--- /dev/null
+++ b/include/mbedtls/gcm.h
@@ -0,0 +1,370 @@
+/**
+ * \file gcm.h
+ *
+ * \brief This file contains GCM definitions and functions.
+ *
+ * The Galois/Counter Mode (GCM) for 128-bit block ciphers is defined
+ * in <em>D. McGrew, J. Viega, The Galois/Counter Mode of Operation
+ * (GCM), Natl. Inst. Stand. Technol.</em>
+ *
+ * For more information on GCM, see <em>NIST SP 800-38D: Recommendation for
+ * Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC</em>.
+ *
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_GCM_H
+#define MBEDTLS_GCM_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/cipher.h"
+
+#include <stdint.h>
+
+#define MBEDTLS_GCM_ENCRYPT 1
+#define MBEDTLS_GCM_DECRYPT 0
+
+/** Authenticated decryption failed. */
+#define MBEDTLS_ERR_GCM_AUTH_FAILED -0x0012
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_GCM_BAD_INPUT -0x0014
+/** An output buffer is too small. */
+#define MBEDTLS_ERR_GCM_BUFFER_TOO_SMALL -0x0016
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_GCM_ALT)
+
+/**
+ * \brief The GCM context structure.
+ */
+typedef struct mbedtls_gcm_context {
+ mbedtls_cipher_context_t MBEDTLS_PRIVATE(cipher_ctx); /*!< The cipher context used. */
+ uint64_t MBEDTLS_PRIVATE(HL)[16]; /*!< Precalculated HTable low. */
+ uint64_t MBEDTLS_PRIVATE(HH)[16]; /*!< Precalculated HTable high. */
+ uint64_t MBEDTLS_PRIVATE(len); /*!< The total length of the encrypted data. */
+ uint64_t MBEDTLS_PRIVATE(add_len); /*!< The total length of the additional data. */
+ unsigned char MBEDTLS_PRIVATE(base_ectr)[16]; /*!< The first ECTR for tag. */
+ unsigned char MBEDTLS_PRIVATE(y)[16]; /*!< The Y working value. */
+ unsigned char MBEDTLS_PRIVATE(buf)[16]; /*!< The buf working value. */
+ int MBEDTLS_PRIVATE(mode); /*!< The operation to perform:
+ #MBEDTLS_GCM_ENCRYPT or
+ #MBEDTLS_GCM_DECRYPT. */
+}
+mbedtls_gcm_context;
+
+#else /* !MBEDTLS_GCM_ALT */
+#include "gcm_alt.h"
+#endif /* !MBEDTLS_GCM_ALT */
+
+/**
+ * \brief This function initializes the specified GCM context,
+ * to make references valid, and prepares the context
+ * for mbedtls_gcm_setkey() or mbedtls_gcm_free().
+ *
+ * The function does not bind the GCM context to a particular
+ * cipher, nor set the key. For this purpose, use
+ * mbedtls_gcm_setkey().
+ *
+ * \param ctx The GCM context to initialize. This must not be \c NULL.
+ */
+void mbedtls_gcm_init(mbedtls_gcm_context *ctx);
+
+/**
+ * \brief This function associates a GCM context with a
+ * cipher algorithm and a key.
+ *
+ * \param ctx The GCM context. This must be initialized.
+ * \param cipher The 128-bit block cipher to use.
+ * \param key The encryption key. This must be a readable buffer of at
+ * least \p keybits bits.
+ * \param keybits The key size in bits. Valid options are:
+ * <ul><li>128 bits</li>
+ * <li>192 bits</li>
+ * <li>256 bits</li></ul>
+ *
+ * \return \c 0 on success.
+ * \return A cipher-specific error code on failure.
+ */
+int mbedtls_gcm_setkey(mbedtls_gcm_context *ctx,
+ mbedtls_cipher_id_t cipher,
+ const unsigned char *key,
+ unsigned int keybits);
+
+/**
+ * \brief This function performs GCM encryption or decryption of a buffer.
+ *
+ * \note For encryption, the output buffer can be the same as the
+ * input buffer. For decryption, the output buffer cannot be
+ * the same as input buffer. If the buffers overlap, the output
+ * buffer must trail at least 8 Bytes behind the input buffer.
+ *
+ * \warning When this function performs a decryption, it outputs the
+ * authentication tag and does not verify that the data is
+ * authentic. You should use this function to perform encryption
+ * only. For decryption, use mbedtls_gcm_auth_decrypt() instead.
+ *
+ * \param ctx The GCM context to use for encryption or decryption. This
+ * must be initialized.
+ * \param mode The operation to perform:
+ * - #MBEDTLS_GCM_ENCRYPT to perform authenticated encryption.
+ * The ciphertext is written to \p output and the
+ * authentication tag is written to \p tag.
+ * - #MBEDTLS_GCM_DECRYPT to perform decryption.
+ * The plaintext is written to \p output and the
+ * authentication tag is written to \p tag.
+ * Note that this mode is not recommended, because it does
+ * not verify the authenticity of the data. For this reason,
+ * you should use mbedtls_gcm_auth_decrypt() instead of
+ * calling this function in decryption mode.
+ * \param length The length of the input data, which is equal to the length
+ * of the output data.
+ * \param iv The initialization vector. This must be a readable buffer of
+ * at least \p iv_len Bytes.
+ * \param iv_len The length of the IV.
+ * \param add The buffer holding the additional data. This must be of at
+ * least that size in Bytes.
+ * \param add_len The length of the additional data.
+ * \param input The buffer holding the input data. If \p length is greater
+ * than zero, this must be a readable buffer of at least that
+ * size in Bytes.
+ * \param output The buffer for holding the output data. If \p length is greater
+ * than zero, this must be a writable buffer of at least that
+ * size in Bytes.
+ * \param tag_len The length of the tag to generate.
+ * \param tag The buffer for holding the tag. This must be a writable
+ * buffer of at least \p tag_len Bytes.
+ *
+ * \return \c 0 if the encryption or decryption was performed
+ * successfully. Note that in #MBEDTLS_GCM_DECRYPT mode,
+ * this does not indicate that the data is authentic.
+ * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths or pointers are
+ * not valid or a cipher-specific error code if the encryption
+ * or decryption failed.
+ */
+int mbedtls_gcm_crypt_and_tag(mbedtls_gcm_context *ctx,
+ int mode,
+ size_t length,
+ const unsigned char *iv,
+ size_t iv_len,
+ const unsigned char *add,
+ size_t add_len,
+ const unsigned char *input,
+ unsigned char *output,
+ size_t tag_len,
+ unsigned char *tag);
+
+/**
+ * \brief This function performs a GCM authenticated decryption of a
+ * buffer.
+ *
+ * \note For decryption, the output buffer cannot be the same as
+ * input buffer. If the buffers overlap, the output buffer
+ * must trail at least 8 Bytes behind the input buffer.
+ *
+ * \param ctx The GCM context. This must be initialized.
+ * \param length The length of the ciphertext to decrypt, which is also
+ * the length of the decrypted plaintext.
+ * \param iv The initialization vector. This must be a readable buffer
+ * of at least \p iv_len Bytes.
+ * \param iv_len The length of the IV.
+ * \param add The buffer holding the additional data. This must be of at
+ * least that size in Bytes.
+ * \param add_len The length of the additional data.
+ * \param tag The buffer holding the tag to verify. This must be a
+ * readable buffer of at least \p tag_len Bytes.
+ * \param tag_len The length of the tag to verify.
+ * \param input The buffer holding the ciphertext. If \p length is greater
+ * than zero, this must be a readable buffer of at least that
+ * size.
+ * \param output The buffer for holding the decrypted plaintext. If \p length
+ * is greater than zero, this must be a writable buffer of at
+ * least that size.
+ *
+ * \return \c 0 if successful and authenticated.
+ * \return #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match.
+ * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths or pointers are
+ * not valid or a cipher-specific error code if the decryption
+ * failed.
+ */
+int mbedtls_gcm_auth_decrypt(mbedtls_gcm_context *ctx,
+ size_t length,
+ const unsigned char *iv,
+ size_t iv_len,
+ const unsigned char *add,
+ size_t add_len,
+ const unsigned char *tag,
+ size_t tag_len,
+ const unsigned char *input,
+ unsigned char *output);
+
+/**
+ * \brief This function starts a GCM encryption or decryption
+ * operation.
+ *
+ * \param ctx The GCM context. This must be initialized.
+ * \param mode The operation to perform: #MBEDTLS_GCM_ENCRYPT or
+ * #MBEDTLS_GCM_DECRYPT.
+ * \param iv The initialization vector. This must be a readable buffer of
+ * at least \p iv_len Bytes.
+ * \param iv_len The length of the IV.
+ *
+ * \return \c 0 on success.
+ */
+int mbedtls_gcm_starts(mbedtls_gcm_context *ctx,
+ int mode,
+ const unsigned char *iv,
+ size_t iv_len);
+
+/**
+ * \brief This function feeds an input buffer as associated data
+ * (authenticated but not encrypted data) in a GCM
+ * encryption or decryption operation.
+ *
+ * Call this function after mbedtls_gcm_starts() to pass
+ * the associated data. If the associated data is empty,
+ * you do not need to call this function. You may not
+ * call this function after calling mbedtls_cipher_update().
+ *
+ * \param ctx The GCM context. This must have been started with
+ * mbedtls_gcm_starts() and must not have yet received
+ * any input with mbedtls_gcm_update().
+ * \param add The buffer holding the additional data, or \c NULL
+ * if \p add_len is \c 0.
+ * \param add_len The length of the additional data. If \c 0,
+ * \p add may be \c NULL.
+ *
+ * \return \c 0 on success.
+ */
+int mbedtls_gcm_update_ad(mbedtls_gcm_context *ctx,
+ const unsigned char *add,
+ size_t add_len);
+
+/**
+ * \brief This function feeds an input buffer into an ongoing GCM
+ * encryption or decryption operation.
+ *
+ * You may call this function zero, one or more times
+ * to pass successive parts of the input: the plaintext to
+ * encrypt, or the ciphertext (not including the tag) to
+ * decrypt. After the last part of the input, call
+ * mbedtls_gcm_finish().
+ *
+ * This function may produce output in one of the following
+ * ways:
+ * - Immediate output: the output length is always equal
+ * to the input length.
+ * - Buffered output: the output consists of a whole number
+ * of 16-byte blocks. If the total input length so far
+ * (not including associated data) is 16 \* *B* + *A*
+ * with *A* < 16 then the total output length is 16 \* *B*.
+ *
+ * In particular:
+ * - It is always correct to call this function with
+ * \p output_size >= \p input_length + 15.
+ * - If \p input_length is a multiple of 16 for all the calls
+ * to this function during an operation, then it is
+ * correct to use \p output_size = \p input_length.
+ *
+ * \note For decryption, the output buffer cannot be the same as
+ * input buffer. If the buffers overlap, the output buffer
+ * must trail at least 8 Bytes behind the input buffer.
+ *
+ * \param ctx The GCM context. This must be initialized.
+ * \param input The buffer holding the input data. If \p input_length
+ * is greater than zero, this must be a readable buffer
+ * of at least \p input_length bytes.
+ * \param input_length The length of the input data in bytes.
+ * \param output The buffer for the output data. If \p output_size
+ * is greater than zero, this must be a writable buffer of
+ * of at least \p output_size bytes.
+ * \param output_size The size of the output buffer in bytes.
+ * See the function description regarding the output size.
+ * \param output_length On success, \p *output_length contains the actual
+ * length of the output written in \p output.
+ * On failure, the content of \p *output_length is
+ * unspecified.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure:
+ * total input length too long,
+ * unsupported input/output buffer overlap detected,
+ * or \p output_size too small.
+ */
+int mbedtls_gcm_update(mbedtls_gcm_context *ctx,
+ const unsigned char *input, size_t input_length,
+ unsigned char *output, size_t output_size,
+ size_t *output_length);
+
+/**
+ * \brief This function finishes the GCM operation and generates
+ * the authentication tag.
+ *
+ * It wraps up the GCM stream, and generates the
+ * tag. The tag can have a maximum length of 16 Bytes.
+ *
+ * \param ctx The GCM context. This must be initialized.
+ * \param tag The buffer for holding the tag. This must be a writable
+ * buffer of at least \p tag_len Bytes.
+ * \param tag_len The length of the tag to generate. This must be at least
+ * four.
+ * \param output The buffer for the final output.
+ * If \p output_size is nonzero, this must be a writable
+ * buffer of at least \p output_size bytes.
+ * \param output_size The size of the \p output buffer in bytes.
+ * This must be large enough for the output that
+ * mbedtls_gcm_update() has not produced. In particular:
+ * - If mbedtls_gcm_update() produces immediate output,
+ * or if the total input size is a multiple of \c 16,
+ * then mbedtls_gcm_finish() never produces any output,
+ * so \p output_size can be \c 0.
+ * - \p output_size never needs to be more than \c 15.
+ * \param output_length On success, \p *output_length contains the actual
+ * length of the output written in \p output.
+ * On failure, the content of \p *output_length is
+ * unspecified.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure:
+ * invalid value of \p tag_len,
+ * or \p output_size too small.
+ */
+int mbedtls_gcm_finish(mbedtls_gcm_context *ctx,
+ unsigned char *output, size_t output_size,
+ size_t *output_length,
+ unsigned char *tag, size_t tag_len);
+
+/**
+ * \brief This function clears a GCM context and the underlying
+ * cipher sub-context.
+ *
+ * \param ctx The GCM context to clear. If this is \c NULL, the call has
+ * no effect. Otherwise, this must be initialized.
+ */
+void mbedtls_gcm_free(mbedtls_gcm_context *ctx);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief The GCM checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_gcm_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+
+#endif /* gcm.h */
diff --git a/include/mbedtls/hkdf.h b/include/mbedtls/hkdf.h
new file mode 100644
index 0000000..930e93f
--- /dev/null
+++ b/include/mbedtls/hkdf.h
@@ -0,0 +1,124 @@
+/**
+ * \file hkdf.h
+ *
+ * \brief This file contains the HKDF interface.
+ *
+ * The HMAC-based Extract-and-Expand Key Derivation Function (HKDF) is
+ * specified by RFC 5869.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_HKDF_H
+#define MBEDTLS_HKDF_H
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/md.h"
+
+/**
+ * \name HKDF Error codes
+ * \{
+ */
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_HKDF_BAD_INPUT_DATA -0x5F80
+/** \} name */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief This is the HMAC-based Extract-and-Expand Key Derivation Function
+ * (HKDF).
+ *
+ * \param md A hash function; md.size denotes the length of the hash
+ * function output in bytes.
+ * \param salt An optional salt value (a non-secret random value);
+ * if the salt is not provided, a string of all zeros of
+ * md.size length is used as the salt.
+ * \param salt_len The length in bytes of the optional \p salt.
+ * \param ikm The input keying material.
+ * \param ikm_len The length in bytes of \p ikm.
+ * \param info An optional context and application specific information
+ * string. This can be a zero-length string.
+ * \param info_len The length of \p info in bytes.
+ * \param okm The output keying material of \p okm_len bytes.
+ * \param okm_len The length of the output keying material in bytes. This
+ * must be less than or equal to 255 * md.size bytes.
+ *
+ * \return 0 on success.
+ * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid.
+ * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying
+ * MD layer.
+ */
+int mbedtls_hkdf(const mbedtls_md_info_t *md, const unsigned char *salt,
+ size_t salt_len, const unsigned char *ikm, size_t ikm_len,
+ const unsigned char *info, size_t info_len,
+ unsigned char *okm, size_t okm_len);
+
+/**
+ * \brief Take the input keying material \p ikm and extract from it a
+ * fixed-length pseudorandom key \p prk.
+ *
+ * \warning This function should only be used if the security of it has been
+ * studied and established in that particular context (eg. TLS 1.3
+ * key schedule). For standard HKDF security guarantees use
+ * \c mbedtls_hkdf instead.
+ *
+ * \param md A hash function; md.size denotes the length of the
+ * hash function output in bytes.
+ * \param salt An optional salt value (a non-secret random value);
+ * if the salt is not provided, a string of all zeros
+ * of md.size length is used as the salt.
+ * \param salt_len The length in bytes of the optional \p salt.
+ * \param ikm The input keying material.
+ * \param ikm_len The length in bytes of \p ikm.
+ * \param[out] prk A pseudorandom key of at least md.size bytes.
+ *
+ * \return 0 on success.
+ * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid.
+ * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying
+ * MD layer.
+ */
+int mbedtls_hkdf_extract(const mbedtls_md_info_t *md,
+ const unsigned char *salt, size_t salt_len,
+ const unsigned char *ikm, size_t ikm_len,
+ unsigned char *prk);
+
+/**
+ * \brief Expand the supplied \p prk into several additional pseudorandom
+ * keys, which is the output of the HKDF.
+ *
+ * \warning This function should only be used if the security of it has been
+ * studied and established in that particular context (eg. TLS 1.3
+ * key schedule). For standard HKDF security guarantees use
+ * \c mbedtls_hkdf instead.
+ *
+ * \param md A hash function; md.size denotes the length of the hash
+ * function output in bytes.
+ * \param prk A pseudorandom key of at least md.size bytes. \p prk is
+ * usually the output from the HKDF extract step.
+ * \param prk_len The length in bytes of \p prk.
+ * \param info An optional context and application specific information
+ * string. This can be a zero-length string.
+ * \param info_len The length of \p info in bytes.
+ * \param okm The output keying material of \p okm_len bytes.
+ * \param okm_len The length of the output keying material in bytes. This
+ * must be less than or equal to 255 * md.size bytes.
+ *
+ * \return 0 on success.
+ * \return #MBEDTLS_ERR_HKDF_BAD_INPUT_DATA when the parameters are invalid.
+ * \return An MBEDTLS_ERR_MD_* error for errors returned from the underlying
+ * MD layer.
+ */
+int mbedtls_hkdf_expand(const mbedtls_md_info_t *md, const unsigned char *prk,
+ size_t prk_len, const unsigned char *info,
+ size_t info_len, unsigned char *okm, size_t okm_len);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* hkdf.h */
diff --git a/include/mbedtls/hmac_drbg.h b/include/mbedtls/hmac_drbg.h
new file mode 100644
index 0000000..18b1b75
--- /dev/null
+++ b/include/mbedtls/hmac_drbg.h
@@ -0,0 +1,434 @@
+/**
+ * \file hmac_drbg.h
+ *
+ * \brief The HMAC_DRBG pseudorandom generator.
+ *
+ * This module implements the HMAC_DRBG pseudorandom generator described
+ * in <em>NIST SP 800-90A: Recommendation for Random Number Generation Using
+ * Deterministic Random Bit Generators</em>.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_HMAC_DRBG_H
+#define MBEDTLS_HMAC_DRBG_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/md.h"
+
+#if defined(MBEDTLS_THREADING_C)
+#include "mbedtls/threading.h"
+#endif
+
+/*
+ * Error codes
+ */
+/** Too many random requested in single call. */
+#define MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG -0x0003
+/** Input too large (Entropy + additional). */
+#define MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG -0x0005
+/** Read/write error in file. */
+#define MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR -0x0007
+/** The entropy source failed. */
+#define MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED -0x0009
+
+/**
+ * \name SECTION: Module settings
+ *
+ * The configuration options you can set for this module are in this section.
+ * Either change them in mbedtls_config.h or define them on the compiler command line.
+ * \{
+ */
+
+#if !defined(MBEDTLS_HMAC_DRBG_RESEED_INTERVAL)
+#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */
+#endif
+
+#if !defined(MBEDTLS_HMAC_DRBG_MAX_INPUT)
+#define MBEDTLS_HMAC_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */
+#endif
+
+#if !defined(MBEDTLS_HMAC_DRBG_MAX_REQUEST)
+#define MBEDTLS_HMAC_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */
+#endif
+
+#if !defined(MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT)
+#define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */
+#endif
+
+/** \} name SECTION: Module settings */
+
+#define MBEDTLS_HMAC_DRBG_PR_OFF 0 /**< No prediction resistance */
+#define MBEDTLS_HMAC_DRBG_PR_ON 1 /**< Prediction resistance enabled */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * HMAC_DRBG context.
+ */
+typedef struct mbedtls_hmac_drbg_context {
+ /* Working state: the key K is not stored explicitly,
+ * but is implied by the HMAC context */
+ mbedtls_md_context_t MBEDTLS_PRIVATE(md_ctx); /*!< HMAC context (inc. K) */
+ unsigned char MBEDTLS_PRIVATE(V)[MBEDTLS_MD_MAX_SIZE]; /*!< V in the spec */
+ int MBEDTLS_PRIVATE(reseed_counter); /*!< reseed counter */
+
+ /* Administrative state */
+ size_t MBEDTLS_PRIVATE(entropy_len); /*!< entropy bytes grabbed on each (re)seed */
+ int MBEDTLS_PRIVATE(prediction_resistance); /*!< enable prediction resistance (Automatic
+ reseed before every random generation) */
+ int MBEDTLS_PRIVATE(reseed_interval); /*!< reseed interval */
+
+ /* Callbacks */
+ int(*MBEDTLS_PRIVATE(f_entropy))(void *, unsigned char *, size_t); /*!< entropy function */
+ void *MBEDTLS_PRIVATE(p_entropy); /*!< context for the entropy function */
+
+#if defined(MBEDTLS_THREADING_C)
+ /* Invariant: the mutex is initialized if and only if
+ * md_ctx->md_info != NULL. This means that the mutex is initialized
+ * during the initial seeding in mbedtls_hmac_drbg_seed() or
+ * mbedtls_hmac_drbg_seed_buf() and freed in mbedtls_ctr_drbg_free().
+ *
+ * Note that this invariant may change without notice. Do not rely on it
+ * and do not access the mutex directly in application code.
+ */
+ mbedtls_threading_mutex_t MBEDTLS_PRIVATE(mutex);
+#endif
+} mbedtls_hmac_drbg_context;
+
+/**
+ * \brief HMAC_DRBG context initialization.
+ *
+ * This function makes the context ready for mbedtls_hmac_drbg_seed(),
+ * mbedtls_hmac_drbg_seed_buf() or mbedtls_hmac_drbg_free().
+ *
+ * \note The reseed interval is #MBEDTLS_HMAC_DRBG_RESEED_INTERVAL
+ * by default. Override this value by calling
+ * mbedtls_hmac_drbg_set_reseed_interval().
+ *
+ * \param ctx HMAC_DRBG context to be initialized.
+ */
+void mbedtls_hmac_drbg_init(mbedtls_hmac_drbg_context *ctx);
+
+/**
+ * \brief HMAC_DRBG initial seeding.
+ *
+ * Set the initial seed and set up the entropy source for future reseeds.
+ *
+ * A typical choice for the \p f_entropy and \p p_entropy parameters is
+ * to use the entropy module:
+ * - \p f_entropy is mbedtls_entropy_func();
+ * - \p p_entropy is an instance of ::mbedtls_entropy_context initialized
+ * with mbedtls_entropy_init() (which registers the platform's default
+ * entropy sources).
+ *
+ * You can provide a personalization string in addition to the
+ * entropy source, to make this instantiation as unique as possible.
+ *
+ * \note By default, the security strength as defined by NIST is:
+ * - 128 bits if \p md_info is SHA-1;
+ * - 192 bits if \p md_info is SHA-224;
+ * - 256 bits if \p md_info is SHA-256, SHA-384 or SHA-512.
+ * Note that SHA-256 is just as efficient as SHA-224.
+ * The security strength can be reduced if a smaller
+ * entropy length is set with
+ * mbedtls_hmac_drbg_set_entropy_len().
+ *
+ * \note The default entropy length is the security strength
+ * (converted from bits to bytes). You can override
+ * it by calling mbedtls_hmac_drbg_set_entropy_len().
+ *
+ * \note During the initial seeding, this function calls
+ * the entropy source to obtain a nonce
+ * whose length is half the entropy length.
+ */
+#if defined(MBEDTLS_THREADING_C)
+/**
+ * \note When Mbed TLS is built with threading support,
+ * after this function returns successfully,
+ * it is safe to call mbedtls_hmac_drbg_random()
+ * from multiple threads. Other operations, including
+ * reseeding, are not thread-safe.
+ */
+#endif /* MBEDTLS_THREADING_C */
+/**
+ * \param ctx HMAC_DRBG context to be seeded.
+ * \param md_info MD algorithm to use for HMAC_DRBG.
+ * \param f_entropy The entropy callback, taking as arguments the
+ * \p p_entropy context, the buffer to fill, and the
+ * length of the buffer.
+ * \p f_entropy is always called with a length that is
+ * less than or equal to the entropy length.
+ * \param p_entropy The entropy context to pass to \p f_entropy.
+ * \param custom The personalization string.
+ * This can be \c NULL, in which case the personalization
+ * string is empty regardless of the value of \p len.
+ * \param len The length of the personalization string.
+ * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT
+ * and also at most
+ * #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \c entropy_len * 3 / 2
+ * where \c entropy_len is the entropy length
+ * described above.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is
+ * invalid.
+ * \return #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough
+ * memory to allocate context data.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
+ * if the call to \p f_entropy failed.
+ */
+int mbedtls_hmac_drbg_seed(mbedtls_hmac_drbg_context *ctx,
+ const mbedtls_md_info_t *md_info,
+ int (*f_entropy)(void *, unsigned char *, size_t),
+ void *p_entropy,
+ const unsigned char *custom,
+ size_t len);
+
+/**
+ * \brief Initialisation of simplified HMAC_DRBG (never reseeds).
+ *
+ * This function is meant for use in algorithms that need a pseudorandom
+ * input such as deterministic ECDSA.
+ */
+#if defined(MBEDTLS_THREADING_C)
+/**
+ * \note When Mbed TLS is built with threading support,
+ * after this function returns successfully,
+ * it is safe to call mbedtls_hmac_drbg_random()
+ * from multiple threads. Other operations, including
+ * reseeding, are not thread-safe.
+ */
+#endif /* MBEDTLS_THREADING_C */
+/**
+ * \param ctx HMAC_DRBG context to be initialised.
+ * \param md_info MD algorithm to use for HMAC_DRBG.
+ * \param data Concatenation of the initial entropy string and
+ * the additional data.
+ * \param data_len Length of \p data in bytes.
+ *
+ * \return \c 0 if successful. or
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is
+ * invalid.
+ * \return #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough
+ * memory to allocate context data.
+ */
+int mbedtls_hmac_drbg_seed_buf(mbedtls_hmac_drbg_context *ctx,
+ const mbedtls_md_info_t *md_info,
+ const unsigned char *data, size_t data_len);
+
+/**
+ * \brief This function turns prediction resistance on or off.
+ * The default value is off.
+ *
+ * \note If enabled, entropy is gathered at the beginning of
+ * every call to mbedtls_hmac_drbg_random_with_add()
+ * or mbedtls_hmac_drbg_random().
+ * Only use this if your entropy source has sufficient
+ * throughput.
+ *
+ * \param ctx The HMAC_DRBG context.
+ * \param resistance #MBEDTLS_HMAC_DRBG_PR_ON or #MBEDTLS_HMAC_DRBG_PR_OFF.
+ */
+void mbedtls_hmac_drbg_set_prediction_resistance(mbedtls_hmac_drbg_context *ctx,
+ int resistance);
+
+/**
+ * \brief This function sets the amount of entropy grabbed on each
+ * seed or reseed.
+ *
+ * See the documentation of mbedtls_hmac_drbg_seed() for the default value.
+ *
+ * \param ctx The HMAC_DRBG context.
+ * \param len The amount of entropy to grab, in bytes.
+ */
+void mbedtls_hmac_drbg_set_entropy_len(mbedtls_hmac_drbg_context *ctx,
+ size_t len);
+
+/**
+ * \brief Set the reseed interval.
+ *
+ * The reseed interval is the number of calls to mbedtls_hmac_drbg_random()
+ * or mbedtls_hmac_drbg_random_with_add() after which the entropy function
+ * is called again.
+ *
+ * The default value is #MBEDTLS_HMAC_DRBG_RESEED_INTERVAL.
+ *
+ * \param ctx The HMAC_DRBG context.
+ * \param interval The reseed interval.
+ */
+void mbedtls_hmac_drbg_set_reseed_interval(mbedtls_hmac_drbg_context *ctx,
+ int interval);
+
+/**
+ * \brief This function updates the state of the HMAC_DRBG context.
+ *
+ * \note This function is not thread-safe. It is not safe
+ * to call this function if another thread might be
+ * concurrently obtaining random numbers from the same
+ * context or updating or reseeding the same context.
+ *
+ * \param ctx The HMAC_DRBG context.
+ * \param additional The data to update the state with.
+ * If this is \c NULL, there is no additional data.
+ * \param add_len Length of \p additional in bytes.
+ * Unused if \p additional is \c NULL.
+ *
+ * \return \c 0 on success, or an error from the underlying
+ * hash calculation.
+ */
+int mbedtls_hmac_drbg_update(mbedtls_hmac_drbg_context *ctx,
+ const unsigned char *additional, size_t add_len);
+
+/**
+ * \brief This function reseeds the HMAC_DRBG context, that is
+ * extracts data from the entropy source.
+ *
+ * \note This function is not thread-safe. It is not safe
+ * to call this function if another thread might be
+ * concurrently obtaining random numbers from the same
+ * context or updating or reseeding the same context.
+ *
+ * \param ctx The HMAC_DRBG context.
+ * \param additional Additional data to add to the state.
+ * If this is \c NULL, there is no additional data
+ * and \p len should be \c 0.
+ * \param len The length of the additional data.
+ * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT
+ * and also at most
+ * #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \c entropy_len
+ * where \c entropy_len is the entropy length
+ * (see mbedtls_hmac_drbg_set_entropy_len()).
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
+ * if a call to the entropy function failed.
+ */
+int mbedtls_hmac_drbg_reseed(mbedtls_hmac_drbg_context *ctx,
+ const unsigned char *additional, size_t len);
+
+/**
+ * \brief This function updates an HMAC_DRBG instance with additional
+ * data and uses it to generate random data.
+ *
+ * This function automatically reseeds if the reseed counter is exceeded
+ * or prediction resistance is enabled.
+ *
+ * \note This function is not thread-safe. It is not safe
+ * to call this function if another thread might be
+ * concurrently obtaining random numbers from the same
+ * context or updating or reseeding the same context.
+ *
+ * \param p_rng The HMAC_DRBG context. This must be a pointer to a
+ * #mbedtls_hmac_drbg_context structure.
+ * \param output The buffer to fill.
+ * \param output_len The length of the buffer in bytes.
+ * This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
+ * \param additional Additional data to update with.
+ * If this is \c NULL, there is no additional data
+ * and \p add_len should be \c 0.
+ * \param add_len The length of the additional data.
+ * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
+ * if a call to the entropy source failed.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if
+ * \p output_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if
+ * \p add_len > #MBEDTLS_HMAC_DRBG_MAX_INPUT.
+ */
+int mbedtls_hmac_drbg_random_with_add(void *p_rng,
+ unsigned char *output, size_t output_len,
+ const unsigned char *additional,
+ size_t add_len);
+
+/**
+ * \brief This function uses HMAC_DRBG to generate random data.
+ *
+ * This function automatically reseeds if the reseed counter is exceeded
+ * or prediction resistance is enabled.
+ */
+#if defined(MBEDTLS_THREADING_C)
+/**
+ * \note When Mbed TLS is built with threading support,
+ * it is safe to call mbedtls_ctr_drbg_random()
+ * from multiple threads. Other operations, including
+ * reseeding, are not thread-safe.
+ */
+#endif /* MBEDTLS_THREADING_C */
+/**
+ * \param p_rng The HMAC_DRBG context. This must be a pointer to a
+ * #mbedtls_hmac_drbg_context structure.
+ * \param output The buffer to fill.
+ * \param out_len The length of the buffer in bytes.
+ * This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED
+ * if a call to the entropy source failed.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if
+ * \p out_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST.
+ */
+int mbedtls_hmac_drbg_random(void *p_rng, unsigned char *output, size_t out_len);
+
+/**
+ * \brief This function resets HMAC_DRBG context to the state immediately
+ * after initial call of mbedtls_hmac_drbg_init().
+ *
+ * \param ctx The HMAC_DRBG context to free.
+ */
+void mbedtls_hmac_drbg_free(mbedtls_hmac_drbg_context *ctx);
+
+#if defined(MBEDTLS_FS_IO)
+/**
+ * \brief This function writes a seed file.
+ *
+ * \param ctx The HMAC_DRBG context.
+ * \param path The name of the file.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on reseed
+ * failure.
+ */
+int mbedtls_hmac_drbg_write_seed_file(mbedtls_hmac_drbg_context *ctx, const char *path);
+
+/**
+ * \brief This function reads and updates a seed file. The seed
+ * is added to this instance.
+ *
+ * \param ctx The HMAC_DRBG context.
+ * \param path The name of the file.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on
+ * reseed failure.
+ * \return #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if the existing
+ * seed file is too large.
+ */
+int mbedtls_hmac_drbg_update_seed_file(mbedtls_hmac_drbg_context *ctx, const char *path);
+#endif /* MBEDTLS_FS_IO */
+
+
+#if defined(MBEDTLS_SELF_TEST)
+/**
+ * \brief The HMAC_DRBG Checkup routine.
+ *
+ * \return \c 0 if successful.
+ * \return \c 1 if the test failed.
+ */
+int mbedtls_hmac_drbg_self_test(int verbose);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* hmac_drbg.h */
diff --git a/include/mbedtls/lms.h b/include/mbedtls/lms.h
new file mode 100644
index 0000000..95fce21
--- /dev/null
+++ b/include/mbedtls/lms.h
@@ -0,0 +1,440 @@
+/**
+ * \file lms.h
+ *
+ * \brief This file provides an API for the LMS post-quantum-safe stateful-hash
+ public-key signature scheme as defined in RFC8554 and NIST.SP.200-208.
+ * This implementation currently only supports a single parameter set
+ * MBEDTLS_LMS_SHA256_M32_H10 in order to reduce complexity. This is one
+ * of the signature schemes recommended by the IETF draft SUIT standard
+ * for IOT firmware upgrades (RFC9019).
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_LMS_H
+#define MBEDTLS_LMS_H
+
+#include <stdint.h>
+#include <stddef.h>
+
+#include "mbedtls/private_access.h"
+#include "mbedtls/build_info.h"
+
+#define MBEDTLS_ERR_LMS_BAD_INPUT_DATA -0x0011 /**< Bad data has been input to an LMS function */
+#define MBEDTLS_ERR_LMS_OUT_OF_PRIVATE_KEYS -0x0013 /**< Specified LMS key has utilised all of its private keys */
+#define MBEDTLS_ERR_LMS_VERIFY_FAILED -0x0015 /**< LMS signature verification failed */
+#define MBEDTLS_ERR_LMS_ALLOC_FAILED -0x0017 /**< LMS failed to allocate space for a private key */
+#define MBEDTLS_ERR_LMS_BUFFER_TOO_SMALL -0x0019 /**< Input/output buffer is too small to contain requited data */
+
+/* Currently only defined for SHA256, 32 is the max hash output size */
+#define MBEDTLS_LMOTS_N_HASH_LEN_MAX (32u)
+#define MBEDTLS_LMOTS_P_SIG_DIGIT_COUNT_MAX (34u)
+#define MBEDTLS_LMOTS_N_HASH_LEN(type) ((type) == MBEDTLS_LMOTS_SHA256_N32_W8 ? 32u : 0)
+#define MBEDTLS_LMOTS_I_KEY_ID_LEN (16u)
+#define MBEDTLS_LMOTS_Q_LEAF_ID_LEN (4u)
+#define MBEDTLS_LMOTS_TYPE_LEN (4u)
+#define MBEDTLS_LMOTS_P_SIG_DIGIT_COUNT(type) ((type) == MBEDTLS_LMOTS_SHA256_N32_W8 ? 34u : 0)
+#define MBEDTLS_LMOTS_C_RANDOM_VALUE_LEN(type) (MBEDTLS_LMOTS_N_HASH_LEN(type))
+
+#define MBEDTLS_LMOTS_SIG_LEN(type) (MBEDTLS_LMOTS_TYPE_LEN + \
+ MBEDTLS_LMOTS_C_RANDOM_VALUE_LEN(type) + \
+ (MBEDTLS_LMOTS_P_SIG_DIGIT_COUNT(type) * \
+ MBEDTLS_LMOTS_N_HASH_LEN(type)))
+
+
+#define MBEDTLS_LMS_TYPE_LEN (4)
+#define MBEDTLS_LMS_H_TREE_HEIGHT(type) ((type) == MBEDTLS_LMS_SHA256_M32_H10 ? 10u : 0)
+
+/* The length of a hash output, Currently only implemented for SHA256.
+ * Max is 32 bytes.
+ */
+#define MBEDTLS_LMS_M_NODE_BYTES(type) ((type) == MBEDTLS_LMS_SHA256_M32_H10 ? 32 : 0)
+#define MBEDTLS_LMS_M_NODE_BYTES_MAX 32
+
+#define MBEDTLS_LMS_SIG_LEN(type, otstype) (MBEDTLS_LMOTS_Q_LEAF_ID_LEN + \
+ MBEDTLS_LMOTS_SIG_LEN(otstype) + \
+ MBEDTLS_LMS_TYPE_LEN + \
+ (MBEDTLS_LMS_H_TREE_HEIGHT(type) * \
+ MBEDTLS_LMS_M_NODE_BYTES(type)))
+
+#define MBEDTLS_LMS_PUBLIC_KEY_LEN(type) (MBEDTLS_LMS_TYPE_LEN + \
+ MBEDTLS_LMOTS_TYPE_LEN + \
+ MBEDTLS_LMOTS_I_KEY_ID_LEN + \
+ MBEDTLS_LMS_M_NODE_BYTES(type))
+
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** The Identifier of the LMS parameter set, as per
+ * https://www.iana.org/assignments/leighton-micali-signatures/leighton-micali-signatures.xhtml
+ * We are only implementing a subset of the types, particularly H10, for the sake of simplicity.
+ */
+typedef enum {
+ MBEDTLS_LMS_SHA256_M32_H10 = 0x6,
+} mbedtls_lms_algorithm_type_t;
+
+/** The Identifier of the LMOTS parameter set, as per
+ * https://www.iana.org/assignments/leighton-micali-signatures/leighton-micali-signatures.xhtml.
+ * We are only implementing a subset of the types, particularly N32_W8, for the sake of simplicity.
+ */
+typedef enum {
+ MBEDTLS_LMOTS_SHA256_N32_W8 = 4
+} mbedtls_lmots_algorithm_type_t;
+
+/** LMOTS parameters structure.
+ *
+ * This contains the metadata associated with an LMOTS key, detailing the
+ * algorithm type, the key ID, and the leaf identifier should be key be part of
+ * a LMS key.
+ */
+typedef struct {
+ unsigned char MBEDTLS_PRIVATE(I_key_identifier[MBEDTLS_LMOTS_I_KEY_ID_LEN]); /*!< The key
+ identifier. */
+ unsigned char MBEDTLS_PRIVATE(q_leaf_identifier[MBEDTLS_LMOTS_Q_LEAF_ID_LEN]); /*!< Which
+ leaf of the LMS key this is.
+ 0 if the key is not part of an LMS key. */
+ mbedtls_lmots_algorithm_type_t MBEDTLS_PRIVATE(type); /*!< The LM-OTS key type identifier as
+ per IANA. Only SHA256_N32_W8 is
+ currently supported. */
+} mbedtls_lmots_parameters_t;
+
+/** LMOTS public context structure.
+ *
+ * A LMOTS public key is a hash output, and the applicable parameter set.
+ *
+ * The context must be initialized before it is used. A public key must either
+ * be imported or generated from a private context.
+ *
+ * \dot
+ * digraph lmots_public_t {
+ * UNINITIALIZED -> INIT [label="init"];
+ * HAVE_PUBLIC_KEY -> INIT [label="free"];
+ * INIT -> HAVE_PUBLIC_KEY [label="import_public_key"];
+ * INIT -> HAVE_PUBLIC_KEY [label="calculate_public_key from private key"];
+ * HAVE_PUBLIC_KEY -> HAVE_PUBLIC_KEY [label="export_public_key"];
+ * }
+ * \enddot
+ */
+typedef struct {
+ mbedtls_lmots_parameters_t MBEDTLS_PRIVATE(params);
+ unsigned char MBEDTLS_PRIVATE(public_key)[MBEDTLS_LMOTS_N_HASH_LEN_MAX];
+ unsigned char MBEDTLS_PRIVATE(have_public_key); /*!< Whether the context contains a public key.
+ Boolean values only. */
+} mbedtls_lmots_public_t;
+
+#if defined(MBEDTLS_LMS_PRIVATE)
+/** LMOTS private context structure.
+ *
+ * A LMOTS private key is one hash output for each of digit of the digest +
+ * checksum, and the applicable parameter set.
+ *
+ * The context must be initialized before it is used. A public key must either
+ * be imported or generated from a private context.
+ *
+ * \dot
+ * digraph lmots_public_t {
+ * UNINITIALIZED -> INIT [label="init"];
+ * HAVE_PRIVATE_KEY -> INIT [label="free"];
+ * INIT -> HAVE_PRIVATE_KEY [label="generate_private_key"];
+ * HAVE_PRIVATE_KEY -> INIT [label="sign"];
+ * }
+ * \enddot
+ */
+typedef struct {
+ mbedtls_lmots_parameters_t MBEDTLS_PRIVATE(params);
+ unsigned char MBEDTLS_PRIVATE(private_key)[MBEDTLS_LMOTS_P_SIG_DIGIT_COUNT_MAX][
+ MBEDTLS_LMOTS_N_HASH_LEN_MAX];
+ unsigned char MBEDTLS_PRIVATE(have_private_key); /*!< Whether the context contains a private key.
+ Boolean values only. */
+} mbedtls_lmots_private_t;
+#endif /* defined(MBEDTLS_LMS_PRIVATE) */
+
+
+/** LMS parameters structure.
+ *
+ * This contains the metadata associated with an LMS key, detailing the
+ * algorithm type, the type of the underlying OTS algorithm, and the key ID.
+ */
+typedef struct {
+ unsigned char MBEDTLS_PRIVATE(I_key_identifier[MBEDTLS_LMOTS_I_KEY_ID_LEN]); /*!< The key
+ identifier. */
+ mbedtls_lmots_algorithm_type_t MBEDTLS_PRIVATE(otstype); /*!< The LM-OTS key type identifier as
+ per IANA. Only SHA256_N32_W8 is
+ currently supported. */
+ mbedtls_lms_algorithm_type_t MBEDTLS_PRIVATE(type); /*!< The LMS key type identifier as per
+ IANA. Only SHA256_M32_H10 is currently
+ supported. */
+} mbedtls_lms_parameters_t;
+
+/** LMS public context structure.
+ *
+ * A LMS public key is the hash output that is the root of the Merkle tree, and
+ * the applicable parameter set
+ *
+ * The context must be initialized before it is used. A public key must either
+ * be imported or generated from a private context.
+ *
+ * \dot
+ * digraph lms_public_t {
+ * UNINITIALIZED -> INIT [label="init"];
+ * HAVE_PUBLIC_KEY -> INIT [label="free"];
+ * INIT -> HAVE_PUBLIC_KEY [label="import_public_key"];
+ * INIT -> HAVE_PUBLIC_KEY [label="calculate_public_key from private key"];
+ * HAVE_PUBLIC_KEY -> HAVE_PUBLIC_KEY [label="export_public_key"];
+ * }
+ * \enddot
+ */
+typedef struct {
+ mbedtls_lms_parameters_t MBEDTLS_PRIVATE(params);
+ unsigned char MBEDTLS_PRIVATE(T_1_pub_key)[MBEDTLS_LMS_M_NODE_BYTES_MAX]; /*!< The public key, in
+ the form of the Merkle tree root node. */
+ unsigned char MBEDTLS_PRIVATE(have_public_key); /*!< Whether the context contains a public key.
+ Boolean values only. */
+} mbedtls_lms_public_t;
+
+
+#if defined(MBEDTLS_LMS_PRIVATE)
+/** LMS private context structure.
+ *
+ * A LMS private key is a set of LMOTS private keys, an index to the next usable
+ * key, and the applicable parameter set.
+ *
+ * The context must be initialized before it is used. A public key must either
+ * be imported or generated from a private context.
+ *
+ * \dot
+ * digraph lms_public_t {
+ * UNINITIALIZED -> INIT [label="init"];
+ * HAVE_PRIVATE_KEY -> INIT [label="free"];
+ * INIT -> HAVE_PRIVATE_KEY [label="generate_private_key"];
+ * }
+ * \enddot
+ */
+typedef struct {
+ mbedtls_lms_parameters_t MBEDTLS_PRIVATE(params);
+ uint32_t MBEDTLS_PRIVATE(q_next_usable_key); /*!< The index of the next OTS key that has not
+ been used. */
+ mbedtls_lmots_private_t *MBEDTLS_PRIVATE(ots_private_keys); /*!< The private key material. One OTS key
+ for each leaf node in the Merkle tree. NULL
+ when have_private_key is 0 and non-NULL otherwise.
+ is 2^MBEDTLS_LMS_H_TREE_HEIGHT(type) in length. */
+ mbedtls_lmots_public_t *MBEDTLS_PRIVATE(ots_public_keys); /*!< The OTS key public keys, used to
+ build the Merkle tree. NULL
+ when have_private_key is 0 and
+ non-NULL otherwise.
+ Is 2^MBEDTLS_LMS_H_TREE_HEIGHT(type)
+ in length. */
+ unsigned char MBEDTLS_PRIVATE(have_private_key); /*!< Whether the context contains a private key.
+ Boolean values only. */
+} mbedtls_lms_private_t;
+#endif /* defined(MBEDTLS_LMS_PRIVATE) */
+
+/**
+ * \brief This function initializes an LMS public context
+ *
+ * \param ctx The uninitialized LMS context that will then be
+ * initialized.
+ */
+void mbedtls_lms_public_init(mbedtls_lms_public_t *ctx);
+
+/**
+ * \brief This function uninitializes an LMS public context
+ *
+ * \param ctx The initialized LMS context that will then be
+ * uninitialized.
+ */
+void mbedtls_lms_public_free(mbedtls_lms_public_t *ctx);
+
+/**
+ * \brief This function imports an LMS public key into a
+ * public LMS context.
+ *
+ * \note Before this function is called, the context must
+ * have been initialized.
+ *
+ * \note See IETF RFC8554 for details of the encoding of
+ * this public key.
+ *
+ * \param ctx The initialized LMS context store the key in.
+ * \param key The buffer from which the key will be read.
+ * #MBEDTLS_LMS_PUBLIC_KEY_LEN bytes will be read from
+ * this.
+ * \param key_size The size of the key being imported.
+ *
+ * \return \c 0 on success.
+ * \return A non-zero error code on failure.
+ */
+int mbedtls_lms_import_public_key(mbedtls_lms_public_t *ctx,
+ const unsigned char *key, size_t key_size);
+
+/**
+ * \brief This function exports an LMS public key from a
+ * LMS public context that already contains a public
+ * key.
+ *
+ * \note Before this function is called, the context must
+ * have been initialized and the context must contain
+ * a public key.
+ *
+ * \note See IETF RFC8554 for details of the encoding of
+ * this public key.
+ *
+ * \param ctx The initialized LMS public context that contains
+ * the public key.
+ * \param key The buffer into which the key will be output. Must
+ * be at least #MBEDTLS_LMS_PUBLIC_KEY_LEN in size.
+ * \param key_size The size of the key buffer.
+ * \param key_len If not NULL, will be written with the size of the
+ * key.
+ *
+ * \return \c 0 on success.
+ * \return A non-zero error code on failure.
+ */
+int mbedtls_lms_export_public_key(const mbedtls_lms_public_t *ctx,
+ unsigned char *key, size_t key_size,
+ size_t *key_len);
+
+/**
+ * \brief This function verifies a LMS signature, using a
+ * LMS context that contains a public key.
+ *
+ * \note Before this function is called, the context must
+ * have been initialized and must contain a public key
+ * (either by import or generation).
+ *
+ * \param ctx The initialized LMS public context from which the
+ * public key will be read.
+ * \param msg The buffer from which the message will be read.
+ * \param msg_size The size of the message that will be read.
+ * \param sig The buf from which the signature will be read.
+ * #MBEDTLS_LMS_SIG_LEN bytes will be read from
+ * this.
+ * \param sig_size The size of the signature to be verified.
+ *
+ * \return \c 0 on successful verification.
+ * \return A non-zero error code on failure.
+ */
+int mbedtls_lms_verify(const mbedtls_lms_public_t *ctx,
+ const unsigned char *msg, size_t msg_size,
+ const unsigned char *sig, size_t sig_size);
+
+#if defined(MBEDTLS_LMS_PRIVATE)
+/**
+ * \brief This function initializes an LMS private context
+ *
+ * \param ctx The uninitialized LMS private context that will
+ * then be initialized. */
+void mbedtls_lms_private_init(mbedtls_lms_private_t *ctx);
+
+/**
+ * \brief This function uninitializes an LMS private context
+ *
+ * \param ctx The initialized LMS private context that will then
+ * be uninitialized.
+ */
+void mbedtls_lms_private_free(mbedtls_lms_private_t *ctx);
+
+/**
+ * \brief This function generates an LMS private key, and
+ * stores in into an LMS private context.
+ *
+ * \warning This function is **not intended for use in
+ * production**, due to as-yet unsolved problems with
+ * handling stateful keys. The API for this function
+ * may change considerably in future versions.
+ *
+ * \note The seed must have at least 256 bits of entropy.
+ *
+ * \param ctx The initialized LMOTS context to generate the key
+ * into.
+ * \param type The LMS parameter set identifier.
+ * \param otstype The LMOTS parameter set identifier.
+ * \param f_rng The RNG function to be used to generate the key ID.
+ * \param p_rng The RNG context to be passed to f_rng
+ * \param seed The seed used to deterministically generate the
+ * key.
+ * \param seed_size The length of the seed.
+ *
+ * \return \c 0 on success.
+ * \return A non-zero error code on failure.
+ */
+int mbedtls_lms_generate_private_key(mbedtls_lms_private_t *ctx,
+ mbedtls_lms_algorithm_type_t type,
+ mbedtls_lmots_algorithm_type_t otstype,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng, const unsigned char *seed,
+ size_t seed_size);
+
+/**
+ * \brief This function calculates an LMS public key from a
+ * LMS context that already contains a private key.
+ *
+ * \note Before this function is called, the context must
+ * have been initialized and the context must contain
+ * a private key.
+ *
+ * \param ctx The initialized LMS public context to calculate the key
+ * from and store it into.
+ *
+ * \param priv_ctx The LMS private context to read the private key
+ * from. This must have been initialized and contain a
+ * private key.
+ *
+ * \return \c 0 on success.
+ * \return A non-zero error code on failure.
+ */
+int mbedtls_lms_calculate_public_key(mbedtls_lms_public_t *ctx,
+ const mbedtls_lms_private_t *priv_ctx);
+
+/**
+ * \brief This function creates a LMS signature, using a
+ * LMS context that contains unused private keys.
+ *
+ * \warning This function is **not intended for use in
+ * production**, due to as-yet unsolved problems with
+ * handling stateful keys. The API for this function
+ * may change considerably in future versions.
+ *
+ * \note Before this function is called, the context must
+ * have been initialized and must contain a private
+ * key.
+ *
+ * \note Each of the LMOTS private keys inside a LMS private
+ * key can only be used once. If they are reused, then
+ * attackers may be able to forge signatures with that
+ * key. This is all handled transparently, but it is
+ * important to not perform copy operations on LMS
+ * contexts that contain private key material.
+ *
+ * \param ctx The initialized LMS private context from which the
+ * private key will be read.
+ * \param f_rng The RNG function to be used for signature
+ * generation.
+ * \param p_rng The RNG context to be passed to f_rng
+ * \param msg The buffer from which the message will be read.
+ * \param msg_size The size of the message that will be read.
+ * \param sig The buf into which the signature will be stored.
+ * Must be at least #MBEDTLS_LMS_SIG_LEN in size.
+ * \param sig_size The size of the buffer the signature will be
+ * written into.
+ * \param sig_len If not NULL, will be written with the size of the
+ * signature.
+ *
+ * \return \c 0 on success.
+ * \return A non-zero error code on failure.
+ */
+int mbedtls_lms_sign(mbedtls_lms_private_t *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng, const unsigned char *msg,
+ unsigned int msg_size, unsigned char *sig, size_t sig_size,
+ size_t *sig_len);
+#endif /* defined(MBEDTLS_LMS_PRIVATE) */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_LMS_H */
diff --git a/include/mbedtls/mbedtls_config.h b/include/mbedtls/mbedtls_config.h
new file mode 100644
index 0000000..e1456b9
--- /dev/null
+++ b/include/mbedtls/mbedtls_config.h
@@ -0,0 +1,4116 @@
+/**
+ * \file mbedtls_config.h
+ *
+ * \brief Configuration options (set of defines)
+ *
+ * This set of compile-time options may be used to enable
+ * or disable features selectively, and reduce the global
+ * memory footprint.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+/**
+ * This is an optional version symbol that enables compatibility handling of
+ * config files.
+ *
+ * It is equal to the #MBEDTLS_VERSION_NUMBER of the Mbed TLS version that
+ * introduced the config format we want to be compatible with.
+ */
+//#define MBEDTLS_CONFIG_VERSION 0x03000000
+
+/**
+ * \name SECTION: System support
+ *
+ * This section sets system specific settings.
+ * \{
+ */
+
+/**
+ * \def MBEDTLS_HAVE_ASM
+ *
+ * The compiler has support for asm().
+ *
+ * Requires support for asm() in compiler.
+ *
+ * Used in:
+ * library/aesni.h
+ * library/aria.c
+ * library/bn_mul.h
+ * library/constant_time.c
+ * library/padlock.h
+ *
+ * Required by:
+ * MBEDTLS_AESCE_C
+ * MBEDTLS_AESNI_C (on some platforms)
+ * MBEDTLS_PADLOCK_C
+ *
+ * Comment to disable the use of assembly code.
+ */
+#define MBEDTLS_HAVE_ASM
+
+/**
+ * \def MBEDTLS_NO_UDBL_DIVISION
+ *
+ * The platform lacks support for double-width integer division (64-bit
+ * division on a 32-bit platform, 128-bit division on a 64-bit platform).
+ *
+ * Used in:
+ * include/mbedtls/bignum.h
+ * library/bignum.c
+ *
+ * The bignum code uses double-width division to speed up some operations.
+ * Double-width division is often implemented in software that needs to
+ * be linked with the program. The presence of a double-width integer
+ * type is usually detected automatically through preprocessor macros,
+ * but the automatic detection cannot know whether the code needs to
+ * and can be linked with an implementation of division for that type.
+ * By default division is assumed to be usable if the type is present.
+ * Uncomment this option to prevent the use of double-width division.
+ *
+ * Note that division for the native integer type is always required.
+ * Furthermore, a 64-bit type is always required even on a 32-bit
+ * platform, but it need not support multiplication or division. In some
+ * cases it is also desirable to disable some double-width operations. For
+ * example, if double-width division is implemented in software, disabling
+ * it can reduce code size in some embedded targets.
+ */
+//#define MBEDTLS_NO_UDBL_DIVISION
+
+/**
+ * \def MBEDTLS_NO_64BIT_MULTIPLICATION
+ *
+ * The platform lacks support for 32x32 -> 64-bit multiplication.
+ *
+ * Used in:
+ * library/poly1305.c
+ *
+ * Some parts of the library may use multiplication of two unsigned 32-bit
+ * operands with a 64-bit result in order to speed up computations. On some
+ * platforms, this is not available in hardware and has to be implemented in
+ * software, usually in a library provided by the toolchain.
+ *
+ * Sometimes it is not desirable to have to link to that library. This option
+ * removes the dependency of that library on platforms that lack a hardware
+ * 64-bit multiplier by embedding a software implementation in Mbed TLS.
+ *
+ * Note that depending on the compiler, this may decrease performance compared
+ * to using the library function provided by the toolchain.
+ */
+//#define MBEDTLS_NO_64BIT_MULTIPLICATION
+
+/**
+ * \def MBEDTLS_HAVE_SSE2
+ *
+ * CPU supports SSE2 instruction set.
+ *
+ * Uncomment if the CPU supports SSE2 (IA-32 specific).
+ */
+//#define MBEDTLS_HAVE_SSE2
+
+/**
+ * \def MBEDTLS_HAVE_TIME
+ *
+ * System has time.h and time().
+ * The time does not need to be correct, only time differences are used,
+ * by contrast with MBEDTLS_HAVE_TIME_DATE
+ *
+ * Defining MBEDTLS_HAVE_TIME allows you to specify MBEDTLS_PLATFORM_TIME_ALT,
+ * MBEDTLS_PLATFORM_TIME_MACRO, MBEDTLS_PLATFORM_TIME_TYPE_MACRO and
+ * MBEDTLS_PLATFORM_STD_TIME.
+ *
+ * Comment if your system does not support time functions.
+ *
+ * \note If MBEDTLS_TIMING_C is set - to enable the semi-portable timing
+ * interface - timing.c will include time.h on suitable platforms
+ * regardless of the setting of MBEDTLS_HAVE_TIME, unless
+ * MBEDTLS_TIMING_ALT is used. See timing.c for more information.
+ */
+#define MBEDTLS_HAVE_TIME
+
+/**
+ * \def MBEDTLS_HAVE_TIME_DATE
+ *
+ * System has time.h, time(), and an implementation for
+ * mbedtls_platform_gmtime_r() (see below).
+ * The time needs to be correct (not necessarily very accurate, but at least
+ * the date should be correct). This is used to verify the validity period of
+ * X.509 certificates.
+ *
+ * Comment if your system does not have a correct clock.
+ *
+ * \note mbedtls_platform_gmtime_r() is an abstraction in platform_util.h that
+ * behaves similarly to the gmtime_r() function from the C standard. Refer to
+ * the documentation for mbedtls_platform_gmtime_r() for more information.
+ *
+ * \note It is possible to configure an implementation for
+ * mbedtls_platform_gmtime_r() at compile-time by using the macro
+ * MBEDTLS_PLATFORM_GMTIME_R_ALT.
+ */
+#define MBEDTLS_HAVE_TIME_DATE
+
+/**
+ * \def MBEDTLS_PLATFORM_MEMORY
+ *
+ * Enable the memory allocation layer.
+ *
+ * By default Mbed TLS uses the system-provided calloc() and free().
+ * This allows different allocators (self-implemented or provided) to be
+ * provided to the platform abstraction layer.
+ *
+ * Enabling #MBEDTLS_PLATFORM_MEMORY without the
+ * MBEDTLS_PLATFORM_{FREE,CALLOC}_MACROs will provide
+ * "mbedtls_platform_set_calloc_free()" allowing you to set an alternative calloc() and
+ * free() function pointer at runtime.
+ *
+ * Enabling #MBEDTLS_PLATFORM_MEMORY and specifying
+ * MBEDTLS_PLATFORM_{CALLOC,FREE}_MACROs will allow you to specify the
+ * alternate function at compile time.
+ *
+ * An overview of how the value of mbedtls_calloc is determined:
+ *
+ * - if !MBEDTLS_PLATFORM_MEMORY
+ * - mbedtls_calloc = calloc
+ * - if MBEDTLS_PLATFORM_MEMORY
+ * - if (MBEDTLS_PLATFORM_CALLOC_MACRO && MBEDTLS_PLATFORM_FREE_MACRO):
+ * - mbedtls_calloc = MBEDTLS_PLATFORM_CALLOC_MACRO
+ * - if !(MBEDTLS_PLATFORM_CALLOC_MACRO && MBEDTLS_PLATFORM_FREE_MACRO):
+ * - Dynamic setup via mbedtls_platform_set_calloc_free is now possible with a default value MBEDTLS_PLATFORM_STD_CALLOC.
+ * - How is MBEDTLS_PLATFORM_STD_CALLOC handled?
+ * - if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS:
+ * - MBEDTLS_PLATFORM_STD_CALLOC is not set to anything;
+ * - MBEDTLS_PLATFORM_STD_MEM_HDR can be included if present;
+ * - if !MBEDTLS_PLATFORM_NO_STD_FUNCTIONS:
+ * - if MBEDTLS_PLATFORM_STD_CALLOC is present:
+ * - User-defined MBEDTLS_PLATFORM_STD_CALLOC is respected;
+ * - if !MBEDTLS_PLATFORM_STD_CALLOC:
+ * - MBEDTLS_PLATFORM_STD_CALLOC = calloc
+ *
+ * - At this point the presence of MBEDTLS_PLATFORM_STD_CALLOC is checked.
+ * - if !MBEDTLS_PLATFORM_STD_CALLOC
+ * - MBEDTLS_PLATFORM_STD_CALLOC = uninitialized_calloc
+ *
+ * - mbedtls_calloc = MBEDTLS_PLATFORM_STD_CALLOC.
+ *
+ * Defining MBEDTLS_PLATFORM_CALLOC_MACRO and #MBEDTLS_PLATFORM_STD_CALLOC at the same time is not possible.
+ * MBEDTLS_PLATFORM_CALLOC_MACRO and MBEDTLS_PLATFORM_FREE_MACRO must both be defined or undefined at the same time.
+ * #MBEDTLS_PLATFORM_STD_CALLOC and #MBEDTLS_PLATFORM_STD_FREE do not have to be defined at the same time, as, if they are used,
+ * dynamic setup of these functions is possible. See the tree above to see how are they handled in all cases.
+ * An uninitialized #MBEDTLS_PLATFORM_STD_CALLOC always fails, returning a null pointer.
+ * An uninitialized #MBEDTLS_PLATFORM_STD_FREE does not do anything.
+ *
+ * Requires: MBEDTLS_PLATFORM_C
+ *
+ * Enable this layer to allow use of alternative memory allocators.
+ */
+//#define MBEDTLS_PLATFORM_MEMORY
+
+/**
+ * \def MBEDTLS_PLATFORM_NO_STD_FUNCTIONS
+ *
+ * Do not assign standard functions in the platform layer (e.g. calloc() to
+ * MBEDTLS_PLATFORM_STD_CALLOC and printf() to MBEDTLS_PLATFORM_STD_PRINTF)
+ *
+ * This makes sure there are no linking errors on platforms that do not support
+ * these functions. You will HAVE to provide alternatives, either at runtime
+ * via the platform_set_xxx() functions or at compile time by setting
+ * the MBEDTLS_PLATFORM_STD_XXX defines, or enabling a
+ * MBEDTLS_PLATFORM_XXX_MACRO.
+ *
+ * Requires: MBEDTLS_PLATFORM_C
+ *
+ * Uncomment to prevent default assignment of standard functions in the
+ * platform layer.
+ */
+//#define MBEDTLS_PLATFORM_NO_STD_FUNCTIONS
+
+/**
+ * \def MBEDTLS_PLATFORM_EXIT_ALT
+ *
+ * MBEDTLS_PLATFORM_XXX_ALT: Uncomment a macro to let Mbed TLS support the
+ * function in the platform abstraction layer.
+ *
+ * Example: In case you uncomment MBEDTLS_PLATFORM_PRINTF_ALT, Mbed TLS will
+ * provide a function "mbedtls_platform_set_printf()" that allows you to set an
+ * alternative printf function pointer.
+ *
+ * All these define require MBEDTLS_PLATFORM_C to be defined!
+ *
+ * \note MBEDTLS_PLATFORM_SNPRINTF_ALT is required on Windows;
+ * it will be enabled automatically by check_config.h
+ *
+ * \warning MBEDTLS_PLATFORM_XXX_ALT cannot be defined at the same time as
+ * MBEDTLS_PLATFORM_XXX_MACRO!
+ *
+ * Requires: MBEDTLS_PLATFORM_TIME_ALT requires MBEDTLS_HAVE_TIME
+ *
+ * Uncomment a macro to enable alternate implementation of specific base
+ * platform function
+ */
+//#define MBEDTLS_PLATFORM_SETBUF_ALT
+//#define MBEDTLS_PLATFORM_EXIT_ALT
+//#define MBEDTLS_PLATFORM_TIME_ALT
+//#define MBEDTLS_PLATFORM_FPRINTF_ALT
+//#define MBEDTLS_PLATFORM_PRINTF_ALT
+//#define MBEDTLS_PLATFORM_SNPRINTF_ALT
+//#define MBEDTLS_PLATFORM_VSNPRINTF_ALT
+//#define MBEDTLS_PLATFORM_NV_SEED_ALT
+//#define MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT
+//#define MBEDTLS_PLATFORM_MS_TIME_ALT
+
+/**
+ * Uncomment the macro to let Mbed TLS use your alternate implementation of
+ * mbedtls_platform_gmtime_r(). This replaces the default implementation in
+ * platform_util.c.
+ *
+ * gmtime() is not a thread-safe function as defined in the C standard. The
+ * library will try to use safer implementations of this function, such as
+ * gmtime_r() when available. However, if Mbed TLS cannot identify the target
+ * system, the implementation of mbedtls_platform_gmtime_r() will default to
+ * using the standard gmtime(). In this case, calls from the library to
+ * gmtime() will be guarded by the global mutex mbedtls_threading_gmtime_mutex
+ * if MBEDTLS_THREADING_C is enabled. We recommend that calls from outside the
+ * library are also guarded with this mutex to avoid race conditions. However,
+ * if the macro MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, Mbed TLS will
+ * unconditionally use the implementation for mbedtls_platform_gmtime_r()
+ * supplied at compile time.
+ */
+//#define MBEDTLS_PLATFORM_GMTIME_R_ALT
+
+/**
+ * Uncomment the macro to let Mbed TLS use your alternate implementation of
+ * mbedtls_platform_zeroize(), to wipe sensitive data in memory. This replaces
+ * the default implementation in platform_util.c.
+ *
+ * By default, the library uses a system function such as memset_s()
+ * (optional feature of C11), explicit_bzero() (BSD and compatible), or
+ * SecureZeroMemory (Windows). If no such function is detected, the library
+ * falls back to a plain C implementation. Compilers are technically
+ * permitted to optimize this implementation out, meaning that the memory is
+ * not actually wiped. The library tries to prevent that, but the C language
+ * makes it impossible to guarantee that the memory will always be wiped.
+ *
+ * If your platform provides a guaranteed method to wipe memory which
+ * `platform_util.c` does not detect, define this macro to the name of
+ * a function that takes two arguments, a `void *` pointer and a length,
+ * and wipes that many bytes starting at the specified address. For example,
+ * if your platform has explicit_bzero() but `platform_util.c` does not
+ * detect its presence, define `MBEDTLS_PLATFORM_ZEROIZE_ALT` to be
+ * `explicit_bzero` to use that function as mbedtls_platform_zeroize().
+ */
+//#define MBEDTLS_PLATFORM_ZEROIZE_ALT
+
+/**
+ * \def MBEDTLS_DEPRECATED_WARNING
+ *
+ * Mark deprecated functions and features so that they generate a warning if
+ * used. Functionality deprecated in one version will usually be removed in the
+ * next version. You can enable this to help you prepare the transition to a
+ * new major version by making sure your code is not using this functionality.
+ *
+ * This only works with GCC and Clang. With other compilers, you may want to
+ * use MBEDTLS_DEPRECATED_REMOVED
+ *
+ * Uncomment to get warnings on using deprecated functions and features.
+ */
+//#define MBEDTLS_DEPRECATED_WARNING
+
+/**
+ * \def MBEDTLS_DEPRECATED_REMOVED
+ *
+ * Remove deprecated functions and features so that they generate an error if
+ * used. Functionality deprecated in one version will usually be removed in the
+ * next version. You can enable this to help you prepare the transition to a
+ * new major version by making sure your code is not using this functionality.
+ *
+ * Uncomment to get errors on using deprecated functions and features.
+ */
+//#define MBEDTLS_DEPRECATED_REMOVED
+
+/** \} name SECTION: System support */
+
+/**
+ * \name SECTION: Mbed TLS feature support
+ *
+ * This section sets support for features that are or are not needed
+ * within the modules that are enabled.
+ * \{
+ */
+
+/**
+ * \def MBEDTLS_TIMING_ALT
+ *
+ * Uncomment to provide your own alternate implementation for
+ * mbedtls_timing_get_timer(), mbedtls_set_alarm(), mbedtls_set/get_delay()
+ *
+ * Only works if you have MBEDTLS_TIMING_C enabled.
+ *
+ * You will need to provide a header "timing_alt.h" and an implementation at
+ * compile time.
+ */
+//#define MBEDTLS_TIMING_ALT
+
+/**
+ * \def MBEDTLS_AES_ALT
+ *
+ * MBEDTLS__MODULE_NAME__ALT: Uncomment a macro to let Mbed TLS use your
+ * alternate core implementation of a symmetric crypto, an arithmetic or hash
+ * module (e.g. platform specific assembly optimized implementations). Keep
+ * in mind that the function prototypes should remain the same.
+ *
+ * This replaces the whole module. If you only want to replace one of the
+ * functions, use one of the MBEDTLS__FUNCTION_NAME__ALT flags.
+ *
+ * Example: In case you uncomment MBEDTLS_AES_ALT, Mbed TLS will no longer
+ * provide the "struct mbedtls_aes_context" definition and omit the base
+ * function declarations and implementations. "aes_alt.h" will be included from
+ * "aes.h" to include the new function definitions.
+ *
+ * Uncomment a macro to enable alternate implementation of the corresponding
+ * module.
+ *
+ * \warning MD5, DES and SHA-1 are considered weak and their
+ * use constitutes a security risk. If possible, we recommend
+ * avoiding dependencies on them, and considering stronger message
+ * digests and ciphers instead.
+ *
+ */
+//#define MBEDTLS_AES_ALT
+//#define MBEDTLS_ARIA_ALT
+//#define MBEDTLS_CAMELLIA_ALT
+//#define MBEDTLS_CCM_ALT
+//#define MBEDTLS_CHACHA20_ALT
+//#define MBEDTLS_CHACHAPOLY_ALT
+//#define MBEDTLS_CMAC_ALT
+//#define MBEDTLS_DES_ALT
+//#define MBEDTLS_DHM_ALT
+//#define MBEDTLS_ECJPAKE_ALT
+//#define MBEDTLS_GCM_ALT
+//#define MBEDTLS_NIST_KW_ALT
+//#define MBEDTLS_MD5_ALT
+//#define MBEDTLS_POLY1305_ALT
+//#define MBEDTLS_RIPEMD160_ALT
+//#define MBEDTLS_RSA_ALT
+//#define MBEDTLS_SHA1_ALT
+//#define MBEDTLS_SHA256_ALT
+//#define MBEDTLS_SHA512_ALT
+
+/*
+ * When replacing the elliptic curve module, please consider, that it is
+ * implemented with two .c files:
+ * - ecp.c
+ * - ecp_curves.c
+ * You can replace them very much like all the other MBEDTLS__MODULE_NAME__ALT
+ * macros as described above. The only difference is that you have to make sure
+ * that you provide functionality for both .c files.
+ */
+//#define MBEDTLS_ECP_ALT
+
+/**
+ * \def MBEDTLS_SHA256_PROCESS_ALT
+ *
+ * MBEDTLS__FUNCTION_NAME__ALT: Uncomment a macro to let Mbed TLS use you
+ * alternate core implementation of symmetric crypto or hash function. Keep in
+ * mind that function prototypes should remain the same.
+ *
+ * This replaces only one function. The header file from Mbed TLS is still
+ * used, in contrast to the MBEDTLS__MODULE_NAME__ALT flags.
+ *
+ * Example: In case you uncomment MBEDTLS_SHA256_PROCESS_ALT, Mbed TLS will
+ * no longer provide the mbedtls_sha1_process() function, but it will still provide
+ * the other function (using your mbedtls_sha1_process() function) and the definition
+ * of mbedtls_sha1_context, so your implementation of mbedtls_sha1_process must be compatible
+ * with this definition.
+ *
+ * \note If you use the AES_xxx_ALT macros, then it is recommended to also set
+ * MBEDTLS_AES_ROM_TABLES in order to help the linker garbage-collect the AES
+ * tables.
+ *
+ * Uncomment a macro to enable alternate implementation of the corresponding
+ * function.
+ *
+ * \warning MD5, DES and SHA-1 are considered weak and their use
+ * constitutes a security risk. If possible, we recommend avoiding
+ * dependencies on them, and considering stronger message digests
+ * and ciphers instead.
+ *
+ * \warning If both MBEDTLS_ECDSA_SIGN_ALT and MBEDTLS_ECDSA_DETERMINISTIC are
+ * enabled, then the deterministic ECDH signature functions pass the
+ * the static HMAC-DRBG as RNG to mbedtls_ecdsa_sign(). Therefore
+ * alternative implementations should use the RNG only for generating
+ * the ephemeral key and nothing else. If this is not possible, then
+ * MBEDTLS_ECDSA_DETERMINISTIC should be disabled and an alternative
+ * implementation should be provided for mbedtls_ecdsa_sign_det_ext().
+ *
+ */
+//#define MBEDTLS_MD5_PROCESS_ALT
+//#define MBEDTLS_RIPEMD160_PROCESS_ALT
+//#define MBEDTLS_SHA1_PROCESS_ALT
+//#define MBEDTLS_SHA256_PROCESS_ALT
+//#define MBEDTLS_SHA512_PROCESS_ALT
+//#define MBEDTLS_DES_SETKEY_ALT
+//#define MBEDTLS_DES_CRYPT_ECB_ALT
+//#define MBEDTLS_DES3_CRYPT_ECB_ALT
+//#define MBEDTLS_AES_SETKEY_ENC_ALT
+//#define MBEDTLS_AES_SETKEY_DEC_ALT
+//#define MBEDTLS_AES_ENCRYPT_ALT
+//#define MBEDTLS_AES_DECRYPT_ALT
+//#define MBEDTLS_ECDH_GEN_PUBLIC_ALT
+//#define MBEDTLS_ECDH_COMPUTE_SHARED_ALT
+//#define MBEDTLS_ECDSA_VERIFY_ALT
+//#define MBEDTLS_ECDSA_SIGN_ALT
+//#define MBEDTLS_ECDSA_GENKEY_ALT
+
+/**
+ * \def MBEDTLS_ECP_INTERNAL_ALT
+ *
+ * Expose a part of the internal interface of the Elliptic Curve Point module.
+ *
+ * MBEDTLS_ECP__FUNCTION_NAME__ALT: Uncomment a macro to let Mbed TLS use your
+ * alternative core implementation of elliptic curve arithmetic. Keep in mind
+ * that function prototypes should remain the same.
+ *
+ * This partially replaces one function. The header file from Mbed TLS is still
+ * used, in contrast to the MBEDTLS_ECP_ALT flag. The original implementation
+ * is still present and it is used for group structures not supported by the
+ * alternative.
+ *
+ * The original implementation can in addition be removed by setting the
+ * MBEDTLS_ECP_NO_FALLBACK option, in which case any function for which the
+ * corresponding MBEDTLS_ECP__FUNCTION_NAME__ALT macro is defined will not be
+ * able to fallback to curves not supported by the alternative implementation.
+ *
+ * Any of these options become available by defining MBEDTLS_ECP_INTERNAL_ALT
+ * and implementing the following functions:
+ * unsigned char mbedtls_internal_ecp_grp_capable(
+ * const mbedtls_ecp_group *grp )
+ * int mbedtls_internal_ecp_init( const mbedtls_ecp_group *grp )
+ * void mbedtls_internal_ecp_free( const mbedtls_ecp_group *grp )
+ * The mbedtls_internal_ecp_grp_capable function should return 1 if the
+ * replacement functions implement arithmetic for the given group and 0
+ * otherwise.
+ * The functions mbedtls_internal_ecp_init and mbedtls_internal_ecp_free are
+ * called before and after each point operation and provide an opportunity to
+ * implement optimized set up and tear down instructions.
+ *
+ * Example: In case you set MBEDTLS_ECP_INTERNAL_ALT and
+ * MBEDTLS_ECP_DOUBLE_JAC_ALT, Mbed TLS will still provide the ecp_double_jac()
+ * function, but will use your mbedtls_internal_ecp_double_jac() if the group
+ * for the operation is supported by your implementation (i.e. your
+ * mbedtls_internal_ecp_grp_capable() function returns 1 for this group). If the
+ * group is not supported by your implementation, then the original Mbed TLS
+ * implementation of ecp_double_jac() is used instead, unless this fallback
+ * behaviour is disabled by setting MBEDTLS_ECP_NO_FALLBACK (in which case
+ * ecp_double_jac() will return MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE).
+ *
+ * The function prototypes and the definition of mbedtls_ecp_group and
+ * mbedtls_ecp_point will not change based on MBEDTLS_ECP_INTERNAL_ALT, so your
+ * implementation of mbedtls_internal_ecp__function_name__ must be compatible
+ * with their definitions.
+ *
+ * Uncomment a macro to enable alternate implementation of the corresponding
+ * function.
+ */
+/* Required for all the functions in this section */
+//#define MBEDTLS_ECP_INTERNAL_ALT
+/* Turn off software fallback for curves not supported in hardware */
+//#define MBEDTLS_ECP_NO_FALLBACK
+/* Support for Weierstrass curves with Jacobi representation */
+//#define MBEDTLS_ECP_RANDOMIZE_JAC_ALT
+//#define MBEDTLS_ECP_ADD_MIXED_ALT
+//#define MBEDTLS_ECP_DOUBLE_JAC_ALT
+//#define MBEDTLS_ECP_NORMALIZE_JAC_MANY_ALT
+//#define MBEDTLS_ECP_NORMALIZE_JAC_ALT
+/* Support for curves with Montgomery arithmetic */
+//#define MBEDTLS_ECP_DOUBLE_ADD_MXZ_ALT
+//#define MBEDTLS_ECP_RANDOMIZE_MXZ_ALT
+//#define MBEDTLS_ECP_NORMALIZE_MXZ_ALT
+
+/**
+ * \def MBEDTLS_ENTROPY_HARDWARE_ALT
+ *
+ * Uncomment this macro to let Mbed TLS use your own implementation of a
+ * hardware entropy collector.
+ *
+ * Your function must be called \c mbedtls_hardware_poll(), have the same
+ * prototype as declared in library/entropy_poll.h, and accept NULL as first
+ * argument.
+ *
+ * Uncomment to use your own hardware entropy collector.
+ */
+//#define MBEDTLS_ENTROPY_HARDWARE_ALT
+
+/**
+ * \def MBEDTLS_AES_ROM_TABLES
+ *
+ * Use precomputed AES tables stored in ROM.
+ *
+ * Uncomment this macro to use precomputed AES tables stored in ROM.
+ * Comment this macro to generate AES tables in RAM at runtime.
+ *
+ * Tradeoff: Using precomputed ROM tables reduces RAM usage by ~8kb
+ * (or ~2kb if \c MBEDTLS_AES_FEWER_TABLES is used) and reduces the
+ * initialization time before the first AES operation can be performed.
+ * It comes at the cost of additional ~8kb ROM use (resp. ~2kb if \c
+ * MBEDTLS_AES_FEWER_TABLES below is used), and potentially degraded
+ * performance if ROM access is slower than RAM access.
+ *
+ * This option is independent of \c MBEDTLS_AES_FEWER_TABLES.
+ */
+//#define MBEDTLS_AES_ROM_TABLES
+
+/**
+ * \def MBEDTLS_AES_FEWER_TABLES
+ *
+ * Use less ROM/RAM for AES tables.
+ *
+ * Uncommenting this macro omits 75% of the AES tables from
+ * ROM / RAM (depending on the value of \c MBEDTLS_AES_ROM_TABLES)
+ * by computing their values on the fly during operations
+ * (the tables are entry-wise rotations of one another).
+ *
+ * Tradeoff: Uncommenting this reduces the RAM / ROM footprint
+ * by ~6kb but at the cost of more arithmetic operations during
+ * runtime. Specifically, one has to compare 4 accesses within
+ * different tables to 4 accesses with additional arithmetic
+ * operations within the same table. The performance gain/loss
+ * depends on the system and memory details.
+ *
+ * This option is independent of \c MBEDTLS_AES_ROM_TABLES.
+ */
+//#define MBEDTLS_AES_FEWER_TABLES
+
+/**
+ * \def MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH
+ *
+ * Use only 128-bit keys in AES operations to save ROM.
+ *
+ * Uncomment this macro to remove support for AES operations that use 192-
+ * or 256-bit keys.
+ *
+ * Uncommenting this macro reduces the size of AES code by ~300 bytes
+ * on v8-M/Thumb2.
+ *
+ * Module: library/aes.c
+ *
+ * Requires: MBEDTLS_AES_C
+ */
+//#define MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH
+
+/*
+ * Disable plain C implementation for AES.
+ *
+ * When the plain C implementation is enabled, and an implementation using a
+ * special CPU feature (such as MBEDTLS_AESCE_C) is also enabled, runtime
+ * detection will be used to select between them.
+ *
+ * If only one implementation is present, runtime detection will not be used.
+ * This configuration will crash at runtime if running on a CPU without the
+ * necessary features. It will not build unless at least one of MBEDTLS_AESCE_C
+ * and/or MBEDTLS_AESNI_C is enabled & present in the build.
+ */
+//#define MBEDTLS_AES_USE_HARDWARE_ONLY
+
+/**
+ * \def MBEDTLS_CAMELLIA_SMALL_MEMORY
+ *
+ * Use less ROM for the Camellia implementation (saves about 768 bytes).
+ *
+ * Uncomment this macro to use less memory for Camellia.
+ */
+//#define MBEDTLS_CAMELLIA_SMALL_MEMORY
+
+/**
+ * \def MBEDTLS_CHECK_RETURN_WARNING
+ *
+ * If this macro is defined, emit a compile-time warning if application code
+ * calls a function without checking its return value, but the return value
+ * should generally be checked in portable applications.
+ *
+ * This is only supported on platforms where #MBEDTLS_CHECK_RETURN is
+ * implemented. Otherwise this option has no effect.
+ *
+ * Uncomment to get warnings on using fallible functions without checking
+ * their return value.
+ *
+ * \note This feature is a work in progress.
+ * Warnings will be added to more functions in the future.
+ *
+ * \note A few functions are considered critical, and ignoring the return
+ * value of these functions will trigger a warning even if this
+ * macro is not defined. To completely disable return value check
+ * warnings, define #MBEDTLS_CHECK_RETURN with an empty expansion.
+ */
+//#define MBEDTLS_CHECK_RETURN_WARNING
+
+/**
+ * \def MBEDTLS_CIPHER_MODE_CBC
+ *
+ * Enable Cipher Block Chaining mode (CBC) for symmetric ciphers.
+ */
+#define MBEDTLS_CIPHER_MODE_CBC
+
+/**
+ * \def MBEDTLS_CIPHER_MODE_CFB
+ *
+ * Enable Cipher Feedback mode (CFB) for symmetric ciphers.
+ */
+#define MBEDTLS_CIPHER_MODE_CFB
+
+/**
+ * \def MBEDTLS_CIPHER_MODE_CTR
+ *
+ * Enable Counter Block Cipher mode (CTR) for symmetric ciphers.
+ */
+#define MBEDTLS_CIPHER_MODE_CTR
+
+/**
+ * \def MBEDTLS_CIPHER_MODE_OFB
+ *
+ * Enable Output Feedback mode (OFB) for symmetric ciphers.
+ */
+#define MBEDTLS_CIPHER_MODE_OFB
+
+/**
+ * \def MBEDTLS_CIPHER_MODE_XTS
+ *
+ * Enable Xor-encrypt-xor with ciphertext stealing mode (XTS) for AES.
+ */
+#define MBEDTLS_CIPHER_MODE_XTS
+
+/**
+ * \def MBEDTLS_CIPHER_NULL_CIPHER
+ *
+ * Enable NULL cipher.
+ * Warning: Only do so when you know what you are doing. This allows for
+ * encryption or channels without any security!
+ *
+ * To enable the following ciphersuites:
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA
+ * MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA
+ * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384
+ * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256
+ * MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA
+ * MBEDTLS_TLS_RSA_WITH_NULL_SHA256
+ * MBEDTLS_TLS_RSA_WITH_NULL_SHA
+ * MBEDTLS_TLS_RSA_WITH_NULL_MD5
+ * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256
+ * MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA
+ * MBEDTLS_TLS_PSK_WITH_NULL_SHA384
+ * MBEDTLS_TLS_PSK_WITH_NULL_SHA256
+ * MBEDTLS_TLS_PSK_WITH_NULL_SHA
+ *
+ * Uncomment this macro to enable the NULL cipher and ciphersuites
+ */
+//#define MBEDTLS_CIPHER_NULL_CIPHER
+
+/**
+ * \def MBEDTLS_CIPHER_PADDING_PKCS7
+ *
+ * MBEDTLS_CIPHER_PADDING_XXX: Uncomment or comment macros to add support for
+ * specific padding modes in the cipher layer with cipher modes that support
+ * padding (e.g. CBC)
+ *
+ * If you disable all padding modes, only full blocks can be used with CBC.
+ *
+ * Enable padding modes in the cipher layer.
+ */
+#define MBEDTLS_CIPHER_PADDING_PKCS7
+#define MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS
+#define MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN
+#define MBEDTLS_CIPHER_PADDING_ZEROS
+
+/** \def MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
+ *
+ * Uncomment this macro to use a 128-bit key in the CTR_DRBG module.
+ * Without this, CTR_DRBG uses a 256-bit key
+ * unless \c MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH is set.
+ */
+//#define MBEDTLS_CTR_DRBG_USE_128_BIT_KEY
+
+/**
+ * Enable the verified implementations of ECDH primitives from Project Everest
+ * (currently only Curve25519). This feature changes the layout of ECDH
+ * contexts and therefore is a compatibility break for applications that access
+ * fields of a mbedtls_ecdh_context structure directly. See also
+ * MBEDTLS_ECDH_LEGACY_CONTEXT in include/mbedtls/ecdh.h.
+ *
+ * The Everest code is provided under the Apache 2.0 license only; therefore enabling this
+ * option is not compatible with taking the library under the GPL v2.0-or-later license.
+ */
+//#define MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED
+
+/**
+ * \def MBEDTLS_ECP_DP_SECP192R1_ENABLED
+ *
+ * MBEDTLS_ECP_XXXX_ENABLED: Enables specific curves within the Elliptic Curve
+ * module. By default all supported curves are enabled.
+ *
+ * Comment macros to disable the curve and functions for it
+ */
+/* Short Weierstrass curves (supporting ECP, ECDH, ECDSA) */
+#define MBEDTLS_ECP_DP_SECP192R1_ENABLED
+#define MBEDTLS_ECP_DP_SECP224R1_ENABLED
+#define MBEDTLS_ECP_DP_SECP256R1_ENABLED
+#define MBEDTLS_ECP_DP_SECP384R1_ENABLED
+#define MBEDTLS_ECP_DP_SECP521R1_ENABLED
+#define MBEDTLS_ECP_DP_SECP192K1_ENABLED
+#define MBEDTLS_ECP_DP_SECP224K1_ENABLED
+#define MBEDTLS_ECP_DP_SECP256K1_ENABLED
+#define MBEDTLS_ECP_DP_BP256R1_ENABLED
+#define MBEDTLS_ECP_DP_BP384R1_ENABLED
+#define MBEDTLS_ECP_DP_BP512R1_ENABLED
+/* Montgomery curves (supporting ECP) */
+#define MBEDTLS_ECP_DP_CURVE25519_ENABLED
+#define MBEDTLS_ECP_DP_CURVE448_ENABLED
+
+/**
+ * \def MBEDTLS_ECP_NIST_OPTIM
+ *
+ * Enable specific 'modulo p' routines for each NIST prime.
+ * Depending on the prime and architecture, makes operations 4 to 8 times
+ * faster on the corresponding curve.
+ *
+ * Comment this macro to disable NIST curves optimisation.
+ */
+#define MBEDTLS_ECP_NIST_OPTIM
+
+/**
+ * \def MBEDTLS_ECP_RESTARTABLE
+ *
+ * Enable "non-blocking" ECC operations that can return early and be resumed.
+ *
+ * This allows various functions to pause by returning
+ * #MBEDTLS_ERR_ECP_IN_PROGRESS (or, for functions in the SSL module,
+ * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS) and then be called later again in
+ * order to further progress and eventually complete their operation. This is
+ * controlled through mbedtls_ecp_set_max_ops() which limits the maximum
+ * number of ECC operations a function may perform before pausing; see
+ * mbedtls_ecp_set_max_ops() for more information.
+ *
+ * This is useful in non-threaded environments if you want to avoid blocking
+ * for too long on ECC (and, hence, X.509 or SSL/TLS) operations.
+ *
+ * This option:
+ * - Adds xxx_restartable() variants of existing operations in the
+ * following modules, with corresponding restart context types:
+ * - ECP (for Short Weierstrass curves only): scalar multiplication (mul),
+ * linear combination (muladd);
+ * - ECDSA: signature generation & verification;
+ * - PK: signature generation & verification;
+ * - X509: certificate chain verification.
+ * - Adds mbedtls_ecdh_enable_restart() in the ECDH module.
+ * - Changes the behaviour of TLS 1.2 clients (not servers) when using the
+ * ECDHE-ECDSA key exchange (not other key exchanges) to make all ECC
+ * computations restartable:
+ * - ECDH operations from the key exchange, only for Short Weierstrass
+ * curves, only when MBEDTLS_USE_PSA_CRYPTO is not enabled.
+ * - verification of the server's key exchange signature;
+ * - verification of the server's certificate chain;
+ * - generation of the client's signature if client authentication is used,
+ * with an ECC key/certificate.
+ *
+ * \note In the cases above, the usual SSL/TLS functions, such as
+ * mbedtls_ssl_handshake(), can now return
+ * MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS.
+ *
+ * \note When this option and MBEDTLS_USE_PSA_CRYPTO are both enabled,
+ * restartable operations in PK, X.509 and TLS (see above) are not
+ * using PSA. On the other hand, ECDH computations in TLS are using
+ * PSA, and are not restartable. These are temporary limitations that
+ * should be lifted in the future.
+ *
+ * \note This option only works with the default software implementation of
+ * elliptic curve functionality. It is incompatible with
+ * MBEDTLS_ECP_ALT, MBEDTLS_ECDH_XXX_ALT, MBEDTLS_ECDSA_XXX_ALT.
+ *
+ * Requires: MBEDTLS_ECP_C
+ *
+ * Uncomment this macro to enable restartable ECC computations.
+ */
+//#define MBEDTLS_ECP_RESTARTABLE
+
+/**
+ * Uncomment to enable using new bignum code in the ECC modules.
+ *
+ * \warning This is currently experimental, incomplete and therefore should not
+ * be used in production.
+ */
+//#define MBEDTLS_ECP_WITH_MPI_UINT
+
+/**
+ * \def MBEDTLS_ECDSA_DETERMINISTIC
+ *
+ * Enable deterministic ECDSA (RFC 6979).
+ * Standard ECDSA is "fragile" in the sense that lack of entropy when signing
+ * may result in a compromise of the long-term signing key. This is avoided by
+ * the deterministic variant.
+ *
+ * Requires: MBEDTLS_HMAC_DRBG_C, MBEDTLS_ECDSA_C
+ *
+ * Comment this macro to disable deterministic ECDSA.
+ */
+#define MBEDTLS_ECDSA_DETERMINISTIC
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
+ *
+ * Enable the PSK based ciphersuite modes in SSL / TLS.
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256
+ */
+#define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED
+ *
+ * Enable the DHE-PSK based ciphersuite modes in SSL / TLS.
+ *
+ * Requires: MBEDTLS_DHM_C
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
+ *
+ * \warning Using DHE constitutes a security risk as it
+ * is not possible to validate custom DH parameters.
+ * If possible, it is recommended users should consider
+ * preferring other methods of key exchange.
+ * See dhm.h for more details.
+ *
+ */
+#define MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+ *
+ * Enable the ECDHE-PSK based ciphersuite modes in SSL / TLS.
+ *
+ * Requires: MBEDTLS_ECDH_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDH)
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
+ */
+#define MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
+ *
+ * Enable the RSA-PSK based ciphersuite modes in SSL / TLS.
+ *
+ * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15,
+ * MBEDTLS_X509_CRT_PARSE_C
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256
+ */
+#define MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
+ *
+ * Enable the RSA-only based ciphersuite modes in SSL / TLS.
+ *
+ * Requires: MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15,
+ * MBEDTLS_X509_CRT_PARSE_C
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256
+ * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
+ * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
+ */
+#define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
+ *
+ * Enable the DHE-RSA based ciphersuite modes in SSL / TLS.
+ *
+ * Requires: MBEDTLS_DHM_C, MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15,
+ * MBEDTLS_X509_CRT_PARSE_C
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
+ *
+ * \warning Using DHE constitutes a security risk as it
+ * is not possible to validate custom DH parameters.
+ * If possible, it is recommended users should consider
+ * preferring other methods of key exchange.
+ * See dhm.h for more details.
+ *
+ */
+#define MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
+ *
+ * Enable the ECDHE-RSA based ciphersuite modes in SSL / TLS.
+ *
+ * Requires: MBEDTLS_ECDH_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDH)
+ * MBEDTLS_RSA_C
+ * MBEDTLS_PKCS1_V15
+ * MBEDTLS_X509_CRT_PARSE_C
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
+ */
+#define MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
+ *
+ * Enable the ECDHE-ECDSA based ciphersuite modes in SSL / TLS.
+ *
+ * Requires: MBEDTLS_ECDH_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDH)
+ * MBEDTLS_ECDSA_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDSA)
+ * MBEDTLS_X509_CRT_PARSE_C
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256
+ */
+#define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED
+ *
+ * Enable the ECDH-ECDSA based ciphersuite modes in SSL / TLS.
+ *
+ * Requires: MBEDTLS_ECDH_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDH)
+ * MBEDTLS_ECDSA_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDSA)
+ * MBEDTLS_X509_CRT_PARSE_C
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384
+ */
+#define MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
+ *
+ * Enable the ECDH-RSA based ciphersuite modes in SSL / TLS.
+ *
+ * Requires: MBEDTLS_ECDH_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDH)
+ * MBEDTLS_RSA_C
+ * MBEDTLS_X509_CRT_PARSE_C
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384
+ */
+#define MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED
+
+/**
+ * \def MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
+ *
+ * Enable the ECJPAKE based ciphersuite modes in SSL / TLS.
+ *
+ * \warning This is currently experimental. EC J-PAKE support is based on the
+ * Thread v1.0.0 specification; incompatible changes to the specification
+ * might still happen. For this reason, this is disabled by default.
+ *
+ * Requires: MBEDTLS_ECJPAKE_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_JPAKE)
+ * SHA-256 (via MBEDTLS_SHA256_C or a PSA driver)
+ * MBEDTLS_ECP_DP_SECP256R1_ENABLED
+ *
+ * \warning If SHA-256 is provided only by a PSA driver, you must call
+ * psa_crypto_init() before the first hanshake (even if
+ * MBEDTLS_USE_PSA_CRYPTO is disabled).
+ *
+ * This enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8
+ */
+//#define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED
+
+/**
+ * \def MBEDTLS_PK_PARSE_EC_EXTENDED
+ *
+ * Enhance support for reading EC keys using variants of SEC1 not allowed by
+ * RFC 5915 and RFC 5480.
+ *
+ * Currently this means parsing the SpecifiedECDomain choice of EC
+ * parameters (only known groups are supported, not arbitrary domains, to
+ * avoid validation issues).
+ *
+ * Disable if you only need to support RFC 5915 + 5480 key formats.
+ */
+#define MBEDTLS_PK_PARSE_EC_EXTENDED
+
+/**
+ * \def MBEDTLS_PK_PARSE_EC_COMPRESSED
+ *
+ * Enable the support for parsing public keys of type Short Weierstrass
+ * (MBEDTLS_ECP_DP_SECP_XXX and MBEDTLS_ECP_DP_BP_XXX) which are using the
+ * compressed point format. This parsing is done through ECP module's functions.
+ *
+ * \note As explained in the description of MBEDTLS_ECP_PF_COMPRESSED (in ecp.h)
+ * the only unsupported curves are MBEDTLS_ECP_DP_SECP224R1 and
+ * MBEDTLS_ECP_DP_SECP224K1.
+ */
+#define MBEDTLS_PK_PARSE_EC_COMPRESSED
+
+/**
+ * \def MBEDTLS_ERROR_STRERROR_DUMMY
+ *
+ * Enable a dummy error function to make use of mbedtls_strerror() in
+ * third party libraries easier when MBEDTLS_ERROR_C is disabled
+ * (no effect when MBEDTLS_ERROR_C is enabled).
+ *
+ * You can safely disable this if MBEDTLS_ERROR_C is enabled, or if you're
+ * not using mbedtls_strerror() or error_strerror() in your application.
+ *
+ * Disable if you run into name conflicts and want to really remove the
+ * mbedtls_strerror()
+ */
+#define MBEDTLS_ERROR_STRERROR_DUMMY
+
+/**
+ * \def MBEDTLS_GENPRIME
+ *
+ * Enable the prime-number generation code.
+ *
+ * Requires: MBEDTLS_BIGNUM_C
+ */
+#define MBEDTLS_GENPRIME
+
+/**
+ * \def MBEDTLS_FS_IO
+ *
+ * Enable functions that use the filesystem.
+ */
+#define MBEDTLS_FS_IO
+
+/**
+ * \def MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES
+ *
+ * Do not add default entropy sources in mbedtls_entropy_init().
+ *
+ * This is useful to have more control over the added entropy sources in an
+ * application.
+ *
+ * Uncomment this macro to prevent loading of default entropy functions.
+ */
+//#define MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES
+
+/**
+ * \def MBEDTLS_NO_PLATFORM_ENTROPY
+ *
+ * Do not use built-in platform entropy functions.
+ * This is useful if your platform does not support
+ * standards like the /dev/urandom or Windows CryptoAPI.
+ *
+ * Uncomment this macro to disable the built-in platform entropy functions.
+ */
+//#define MBEDTLS_NO_PLATFORM_ENTROPY
+
+/**
+ * \def MBEDTLS_ENTROPY_FORCE_SHA256
+ *
+ * Force the entropy accumulator to use a SHA-256 accumulator instead of the
+ * default SHA-512 based one (if both are available).
+ *
+ * Requires: MBEDTLS_SHA256_C
+ *
+ * On 32-bit systems SHA-256 can be much faster than SHA-512. Use this option
+ * if you have performance concerns.
+ *
+ * This option is only useful if both MBEDTLS_SHA256_C and
+ * MBEDTLS_SHA512_C are defined. Otherwise the available hash module is used.
+ */
+//#define MBEDTLS_ENTROPY_FORCE_SHA256
+
+/**
+ * \def MBEDTLS_ENTROPY_NV_SEED
+ *
+ * Enable the non-volatile (NV) seed file-based entropy source.
+ * (Also enables the NV seed read/write functions in the platform layer)
+ *
+ * This is crucial (if not required) on systems that do not have a
+ * cryptographic entropy source (in hardware or kernel) available.
+ *
+ * Requires: MBEDTLS_ENTROPY_C, MBEDTLS_PLATFORM_C
+ *
+ * \note The read/write functions that are used by the entropy source are
+ * determined in the platform layer, and can be modified at runtime and/or
+ * compile-time depending on the flags (MBEDTLS_PLATFORM_NV_SEED_*) used.
+ *
+ * \note If you use the default implementation functions that read a seedfile
+ * with regular fopen(), please make sure you make a seedfile with the
+ * proper name (defined in MBEDTLS_PLATFORM_STD_NV_SEED_FILE) and at
+ * least MBEDTLS_ENTROPY_BLOCK_SIZE bytes in size that can be read from
+ * and written to or you will get an entropy source error! The default
+ * implementation will only use the first MBEDTLS_ENTROPY_BLOCK_SIZE
+ * bytes from the file.
+ *
+ * \note The entropy collector will write to the seed file before entropy is
+ * given to an external source, to update it.
+ */
+//#define MBEDTLS_ENTROPY_NV_SEED
+
+/* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER
+ *
+ * Enable key identifiers that encode a key owner identifier.
+ *
+ * The owner of a key is identified by a value of type ::mbedtls_key_owner_id_t
+ * which is currently hard-coded to be int32_t.
+ *
+ * Note that this option is meant for internal use only and may be removed
+ * without notice.
+ */
+//#define MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER
+
+/**
+ * \def MBEDTLS_MEMORY_DEBUG
+ *
+ * Enable debugging of buffer allocator memory issues. Automatically prints
+ * (to stderr) all (fatal) messages on memory allocation issues. Enables
+ * function for 'debug output' of allocated memory.
+ *
+ * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C
+ *
+ * Uncomment this macro to let the buffer allocator print out error messages.
+ */
+//#define MBEDTLS_MEMORY_DEBUG
+
+/**
+ * \def MBEDTLS_MEMORY_BACKTRACE
+ *
+ * Include backtrace information with each allocated block.
+ *
+ * Requires: MBEDTLS_MEMORY_BUFFER_ALLOC_C
+ * GLIBC-compatible backtrace() and backtrace_symbols() support
+ *
+ * Uncomment this macro to include backtrace information
+ */
+//#define MBEDTLS_MEMORY_BACKTRACE
+
+/**
+ * \def MBEDTLS_PK_RSA_ALT_SUPPORT
+ *
+ * Support external private RSA keys (eg from a HSM) in the PK layer.
+ *
+ * Comment this macro to disable support for external private RSA keys.
+ */
+#define MBEDTLS_PK_RSA_ALT_SUPPORT
+
+/**
+ * \def MBEDTLS_PKCS1_V15
+ *
+ * Enable support for PKCS#1 v1.5 encoding.
+ *
+ * Requires: MBEDTLS_RSA_C
+ *
+ * This enables support for PKCS#1 v1.5 operations.
+ */
+#define MBEDTLS_PKCS1_V15
+
+/**
+ * \def MBEDTLS_PKCS1_V21
+ *
+ * Enable support for PKCS#1 v2.1 encoding.
+ *
+ * Requires: MBEDTLS_RSA_C
+ *
+ * \warning If using a hash that is only provided by PSA drivers, you must
+ * call psa_crypto_init() before doing any PKCS#1 v2.1 operation.
+ *
+ * This enables support for RSAES-OAEP and RSASSA-PSS operations.
+ */
+#define MBEDTLS_PKCS1_V21
+
+/** \def MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS
+ *
+ * Enable support for platform built-in keys. If you enable this feature,
+ * you must implement the function mbedtls_psa_platform_get_builtin_key().
+ * See the documentation of that function for more information.
+ *
+ * Built-in keys are typically derived from a hardware unique key or
+ * stored in a secure element.
+ *
+ * Requires: MBEDTLS_PSA_CRYPTO_C.
+ *
+ * \warning This interface is experimental and may change or be removed
+ * without notice.
+ */
+//#define MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS
+
+/** \def MBEDTLS_PSA_CRYPTO_CLIENT
+ *
+ * Enable support for PSA crypto client.
+ *
+ * \note This option allows to include the code necessary for a PSA
+ * crypto client when the PSA crypto implementation is not included in
+ * the library (MBEDTLS_PSA_CRYPTO_C disabled). The code included is the
+ * code to set and get PSA key attributes.
+ * The development of PSA drivers partially relying on the library to
+ * fulfill the hardware gaps is another possible usage of this option.
+ *
+ * \warning This interface is experimental and may change or be removed
+ * without notice.
+ */
+//#define MBEDTLS_PSA_CRYPTO_CLIENT
+
+/** \def MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG
+ *
+ * Make the PSA Crypto module use an external random generator provided
+ * by a driver, instead of Mbed TLS's entropy and DRBG modules.
+ *
+ * \note This random generator must deliver random numbers with cryptographic
+ * quality and high performance. It must supply unpredictable numbers
+ * with a uniform distribution. The implementation of this function
+ * is responsible for ensuring that the random generator is seeded
+ * with sufficient entropy. If you have a hardware TRNG which is slow
+ * or delivers non-uniform output, declare it as an entropy source
+ * with mbedtls_entropy_add_source() instead of enabling this option.
+ *
+ * If you enable this option, you must configure the type
+ * ::mbedtls_psa_external_random_context_t in psa/crypto_platform.h
+ * and define a function called mbedtls_psa_external_get_random()
+ * with the following prototype:
+ * ```
+ * psa_status_t mbedtls_psa_external_get_random(
+ * mbedtls_psa_external_random_context_t *context,
+ * uint8_t *output, size_t output_size, size_t *output_length);
+ * );
+ * ```
+ * The \c context value is initialized to 0 before the first call.
+ * The function must fill the \c output buffer with \c output_size bytes
+ * of random data and set \c *output_length to \c output_size.
+ *
+ * Requires: MBEDTLS_PSA_CRYPTO_C
+ *
+ * \warning If you enable this option, code that uses the PSA cryptography
+ * interface will not use any of the entropy sources set up for
+ * the entropy module, nor the NV seed that MBEDTLS_ENTROPY_NV_SEED
+ * enables.
+ *
+ * \note This option is experimental and may be removed without notice.
+ */
+//#define MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG
+
+/**
+ * \def MBEDTLS_PSA_CRYPTO_SPM
+ *
+ * When MBEDTLS_PSA_CRYPTO_SPM is defined, the code is built for SPM (Secure
+ * Partition Manager) integration which separates the code into two parts: a
+ * NSPE (Non-Secure Process Environment) and an SPE (Secure Process
+ * Environment).
+ *
+ * If you enable this option, your build environment must include a header
+ * file `"crypto_spe.h"` (either in the `psa` subdirectory of the Mbed TLS
+ * header files, or in another directory on the compiler's include search
+ * path). Alternatively, your platform may customize the header
+ * `psa/crypto_platform.h`, in which case it can skip or replace the
+ * inclusion of `"crypto_spe.h"`.
+ *
+ * Module: library/psa_crypto.c
+ * Requires: MBEDTLS_PSA_CRYPTO_C
+ *
+ */
+//#define MBEDTLS_PSA_CRYPTO_SPM
+
+/**
+ * Uncomment to enable p256-m. This is an alternative implementation of
+ * key generation, ECDH and (randomized) ECDSA on the curve SECP256R1.
+ * Compared to the default implementation:
+ *
+ * - p256-m has a much smaller code size and RAM footprint.
+ * - p256-m is only available via the PSA API. This includes the pk module
+ * when #MBEDTLS_USE_PSA_CRYPTO is enabled.
+ * - p256-m does not support deterministic ECDSA, EC-JPAKE, custom protocols
+ * over the core arithmetic, or deterministic derivation of keys.
+ *
+ * We recommend enabling this option if your application uses the PSA API
+ * and the only elliptic curve support it needs is ECDH and ECDSA over
+ * SECP256R1.
+ *
+ * If you enable this option, you do not need to enable any ECC-related
+ * MBEDTLS_xxx option. You do need to separately request support for the
+ * cryptographic mechanisms through the PSA API:
+ * - #MBEDTLS_PSA_CRYPTO_C and #MBEDTLS_PSA_CRYPTO_CONFIG for PSA-based
+ * configuration;
+ * - #MBEDTLS_USE_PSA_CRYPTO if you want to use p256-m from PK, X.509 or TLS;
+ * - #PSA_WANT_ECC_SECP_R1_256;
+ * - #PSA_WANT_ALG_ECDH and/or #PSA_WANT_ALG_ECDSA as needed;
+ * - #PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY, #PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC,
+ * #PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT,
+ * #PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT and/or
+ * #PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE as needed.
+ *
+ * \note To benefit from the smaller code size of p256-m, make sure that you
+ * do not enable any ECC-related option not supported by p256-m: this
+ * would cause the built-in ECC implementation to be built as well, in
+ * order to provide the required option.
+ * Make sure #PSA_WANT_ALG_DETERMINISTIC_ECDSA, #PSA_WANT_ALG_JPAKE and
+ * #PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE, and curves other than
+ * SECP256R1 are disabled as they are not supported by this driver.
+ * Also, avoid defining #MBEDTLS_PK_PARSE_EC_COMPRESSED or
+ * #MBEDTLS_PK_PARSE_EC_EXTENDED as those currently require a subset of
+ * the built-in ECC implementation, see docs/driver-only-builds.md.
+ */
+//#define MBEDTLS_PSA_P256M_DRIVER_ENABLED
+
+/**
+ * \def MBEDTLS_PSA_INJECT_ENTROPY
+ *
+ * Enable support for entropy injection at first boot. This feature is
+ * required on systems that do not have a built-in entropy source (TRNG).
+ * This feature is currently not supported on systems that have a built-in
+ * entropy source.
+ *
+ * Requires: MBEDTLS_PSA_CRYPTO_STORAGE_C, MBEDTLS_ENTROPY_NV_SEED
+ *
+ */
+//#define MBEDTLS_PSA_INJECT_ENTROPY
+
+/**
+ * \def MBEDTLS_RSA_NO_CRT
+ *
+ * Do not use the Chinese Remainder Theorem
+ * for the RSA private operation.
+ *
+ * Uncomment this macro to disable the use of CRT in RSA.
+ *
+ */
+//#define MBEDTLS_RSA_NO_CRT
+
+/**
+ * \def MBEDTLS_SELF_TEST
+ *
+ * Enable the checkup functions (*_self_test).
+ */
+#define MBEDTLS_SELF_TEST
+
+/**
+ * \def MBEDTLS_SHA256_SMALLER
+ *
+ * Enable an implementation of SHA-256 that has lower ROM footprint but also
+ * lower performance.
+ *
+ * The default implementation is meant to be a reasonable compromise between
+ * performance and size. This version optimizes more aggressively for size at
+ * the expense of performance. Eg on Cortex-M4 it reduces the size of
+ * mbedtls_sha256_process() from ~2KB to ~0.5KB for a performance hit of about
+ * 30%.
+ *
+ * Uncomment to enable the smaller implementation of SHA256.
+ */
+//#define MBEDTLS_SHA256_SMALLER
+
+/**
+ * \def MBEDTLS_SHA512_SMALLER
+ *
+ * Enable an implementation of SHA-512 that has lower ROM footprint but also
+ * lower performance.
+ *
+ * Uncomment to enable the smaller implementation of SHA512.
+ */
+//#define MBEDTLS_SHA512_SMALLER
+
+/**
+ * \def MBEDTLS_SSL_ALL_ALERT_MESSAGES
+ *
+ * Enable sending of alert messages in case of encountered errors as per RFC.
+ * If you choose not to send the alert messages, Mbed TLS can still communicate
+ * with other servers, only debugging of failures is harder.
+ *
+ * The advantage of not sending alert messages, is that no information is given
+ * about reasons for failures thus preventing adversaries of gaining intel.
+ *
+ * Enable sending of all alert messages
+ */
+#define MBEDTLS_SSL_ALL_ALERT_MESSAGES
+
+/**
+ * \def MBEDTLS_SSL_DTLS_CONNECTION_ID
+ *
+ * Enable support for the DTLS Connection ID (CID) extension,
+ * which allows to identify DTLS connections across changes
+ * in the underlying transport. The CID functionality is described
+ * in RFC 9146.
+ *
+ * Setting this option enables the SSL APIs `mbedtls_ssl_set_cid()`,
+ * mbedtls_ssl_get_own_cid()`, `mbedtls_ssl_get_peer_cid()` and
+ * `mbedtls_ssl_conf_cid()`. See the corresponding documentation for
+ * more information.
+ *
+ * The maximum lengths of outgoing and incoming CIDs can be configured
+ * through the options
+ * - MBEDTLS_SSL_CID_OUT_LEN_MAX
+ * - MBEDTLS_SSL_CID_IN_LEN_MAX.
+ *
+ * Requires: MBEDTLS_SSL_PROTO_DTLS
+ *
+ * Uncomment to enable the Connection ID extension.
+ */
+#define MBEDTLS_SSL_DTLS_CONNECTION_ID
+
+
+/**
+ * \def MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT
+ *
+ * Defines whether RFC 9146 (default) or the legacy version
+ * (version draft-ietf-tls-dtls-connection-id-05,
+ * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05)
+ * is used.
+ *
+ * Set the value to 0 for the standard version, and
+ * 1 for the legacy draft version.
+ *
+ * \deprecated Support for the legacy version of the DTLS
+ * Connection ID feature is deprecated. Please
+ * switch to the standardized version defined
+ * in RFC 9146 enabled by utilizing
+ * MBEDTLS_SSL_DTLS_CONNECTION_ID without use
+ * of MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT.
+ *
+ * Requires: MBEDTLS_SSL_DTLS_CONNECTION_ID
+ */
+#define MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT 0
+
+/**
+ * \def MBEDTLS_SSL_ASYNC_PRIVATE
+ *
+ * Enable asynchronous external private key operations in SSL. This allows
+ * you to configure an SSL connection to call an external cryptographic
+ * module to perform private key operations instead of performing the
+ * operation inside the library.
+ *
+ * Requires: MBEDTLS_X509_CRT_PARSE_C
+ */
+//#define MBEDTLS_SSL_ASYNC_PRIVATE
+
+/**
+ * \def MBEDTLS_SSL_CONTEXT_SERIALIZATION
+ *
+ * Enable serialization of the TLS context structures, through use of the
+ * functions mbedtls_ssl_context_save() and mbedtls_ssl_context_load().
+ *
+ * This pair of functions allows one side of a connection to serialize the
+ * context associated with the connection, then free or re-use that context
+ * while the serialized state is persisted elsewhere, and finally deserialize
+ * that state to a live context for resuming read/write operations on the
+ * connection. From a protocol perspective, the state of the connection is
+ * unaffected, in particular this is entirely transparent to the peer.
+ *
+ * Note: this is distinct from TLS session resumption, which is part of the
+ * protocol and fully visible by the peer. TLS session resumption enables
+ * establishing new connections associated to a saved session with shorter,
+ * lighter handshakes, while context serialization is a local optimization in
+ * handling a single, potentially long-lived connection.
+ *
+ * Enabling these APIs makes some SSL structures larger, as 64 extra bytes are
+ * saved after the handshake to allow for more efficient serialization, so if
+ * you don't need this feature you'll save RAM by disabling it.
+ *
+ * Requires: MBEDTLS_GCM_C or MBEDTLS_CCM_C or MBEDTLS_CHACHAPOLY_C
+ *
+ * Comment to disable the context serialization APIs.
+ */
+#define MBEDTLS_SSL_CONTEXT_SERIALIZATION
+
+/**
+ * \def MBEDTLS_SSL_DEBUG_ALL
+ *
+ * Enable the debug messages in SSL module for all issues.
+ * Debug messages have been disabled in some places to prevent timing
+ * attacks due to (unbalanced) debugging function calls.
+ *
+ * If you need all error reporting you should enable this during debugging,
+ * but remove this for production servers that should log as well.
+ *
+ * Uncomment this macro to report all debug messages on errors introducing
+ * a timing side-channel.
+ *
+ */
+//#define MBEDTLS_SSL_DEBUG_ALL
+
+/** \def MBEDTLS_SSL_ENCRYPT_THEN_MAC
+ *
+ * Enable support for Encrypt-then-MAC, RFC 7366.
+ *
+ * This allows peers that both support it to use a more robust protection for
+ * ciphersuites using CBC, providing deep resistance against timing attacks
+ * on the padding or underlying cipher.
+ *
+ * This only affects CBC ciphersuites, and is useless if none is defined.
+ *
+ * Requires: MBEDTLS_SSL_PROTO_TLS1_2
+ *
+ * Comment this macro to disable support for Encrypt-then-MAC
+ */
+#define MBEDTLS_SSL_ENCRYPT_THEN_MAC
+
+/** \def MBEDTLS_SSL_EXTENDED_MASTER_SECRET
+ *
+ * Enable support for RFC 7627: Session Hash and Extended Master Secret
+ * Extension.
+ *
+ * This was introduced as "the proper fix" to the Triple Handshake family of
+ * attacks, but it is recommended to always use it (even if you disable
+ * renegotiation), since it actually fixes a more fundamental issue in the
+ * original SSL/TLS design, and has implications beyond Triple Handshake.
+ *
+ * Requires: MBEDTLS_SSL_PROTO_TLS1_2
+ *
+ * Comment this macro to disable support for Extended Master Secret.
+ */
+#define MBEDTLS_SSL_EXTENDED_MASTER_SECRET
+
+/**
+ * \def MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
+ *
+ * This option controls the availability of the API mbedtls_ssl_get_peer_cert()
+ * giving access to the peer's certificate after completion of the handshake.
+ *
+ * Unless you need mbedtls_ssl_peer_cert() in your application, it is
+ * recommended to disable this option for reduced RAM usage.
+ *
+ * \note If this option is disabled, mbedtls_ssl_get_peer_cert() is still
+ * defined, but always returns \c NULL.
+ *
+ * \note This option has no influence on the protection against the
+ * triple handshake attack. Even if it is disabled, Mbed TLS will
+ * still ensure that certificates do not change during renegotiation,
+ * for example by keeping a hash of the peer's certificate.
+ *
+ * \note This option is required if MBEDTLS_SSL_PROTO_TLS1_3 is set.
+ *
+ * Comment this macro to disable storing the peer's certificate
+ * after the handshake.
+ */
+#define MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
+
+/**
+ * \def MBEDTLS_SSL_RENEGOTIATION
+ *
+ * Enable support for TLS renegotiation.
+ *
+ * The two main uses of renegotiation are (1) refresh keys on long-lived
+ * connections and (2) client authentication after the initial handshake.
+ * If you don't need renegotiation, it's probably better to disable it, since
+ * it has been associated with security issues in the past and is easy to
+ * misuse/misunderstand.
+ *
+ * Requires: MBEDTLS_SSL_PROTO_TLS1_2
+ *
+ * Comment this to disable support for renegotiation.
+ *
+ * \note Even if this option is disabled, both client and server are aware
+ * of the Renegotiation Indication Extension (RFC 5746) used to
+ * prevent the SSL renegotiation attack (see RFC 5746 Sect. 1).
+ * (See \c mbedtls_ssl_conf_legacy_renegotiation for the
+ * configuration of this extension).
+ *
+ */
+#define MBEDTLS_SSL_RENEGOTIATION
+
+/**
+ * \def MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
+ *
+ * Enable support for RFC 6066 max_fragment_length extension in SSL.
+ *
+ * Comment this macro to disable support for the max_fragment_length extension
+ */
+#define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
+
+/**
+ * \def MBEDTLS_SSL_RECORD_SIZE_LIMIT
+ *
+ * Enable support for RFC 8449 record_size_limit extension in SSL (TLS 1.3 only).
+ *
+ * \warning This extension is currently in development and must NOT be used except
+ * for testing purposes.
+ *
+ * Requires: MBEDTLS_SSL_PROTO_TLS1_3
+ *
+ * Uncomment this macro to enable support for the record_size_limit extension
+ */
+//#define MBEDTLS_SSL_RECORD_SIZE_LIMIT
+
+/**
+ * \def MBEDTLS_SSL_PROTO_TLS1_2
+ *
+ * Enable support for TLS 1.2 (and DTLS 1.2 if DTLS is enabled).
+ *
+ * Requires: Without MBEDTLS_USE_PSA_CRYPTO: MBEDTLS_MD_C and
+ * (MBEDTLS_SHA256_C or MBEDTLS_SHA384_C or
+ * SHA-256 or SHA-512 provided by a PSA driver)
+ * With MBEDTLS_USE_PSA_CRYPTO:
+ * PSA_WANT_ALG_SHA_256 or PSA_WANT_ALG_SHA_384
+ *
+ * \warning If building with MBEDTLS_USE_PSA_CRYPTO, or if the hash(es) used
+ * are only provided by PSA drivers, you must call psa_crypto_init() before
+ * doing any TLS operations.
+ *
+ * Comment this macro to disable support for TLS 1.2 / DTLS 1.2
+ */
+#define MBEDTLS_SSL_PROTO_TLS1_2
+
+/**
+ * \def MBEDTLS_SSL_PROTO_TLS1_3
+ *
+ * Enable support for TLS 1.3.
+ *
+ * \note See docs/architecture/tls13-support.md for a description of the TLS
+ * 1.3 support that this option enables.
+ *
+ * Requires: MBEDTLS_SSL_KEEP_PEER_CERTIFICATE
+ * Requires: MBEDTLS_PSA_CRYPTO_C
+ *
+ * \note TLS 1.3 uses PSA crypto for cryptographic operations that are
+ * directly performed by TLS 1.3 code. As a consequence, you must
+ * call psa_crypto_init() before the first TLS 1.3 handshake.
+ *
+ * \note Cryptographic operations performed indirectly via another module
+ * (X.509, PK) or by code shared with TLS 1.2 (record protection,
+ * running handshake hash) only use PSA crypto if
+ * #MBEDTLS_USE_PSA_CRYPTO is enabled.
+ *
+ * Uncomment this macro to enable the support for TLS 1.3.
+ */
+//#define MBEDTLS_SSL_PROTO_TLS1_3
+
+/**
+ * \def MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE
+ *
+ * Enable TLS 1.3 middlebox compatibility mode.
+ *
+ * As specified in Section D.4 of RFC 8446, TLS 1.3 offers a compatibility
+ * mode to make a TLS 1.3 connection more likely to pass through middle boxes
+ * expecting TLS 1.2 traffic.
+ *
+ * Turning on the compatibility mode comes at the cost of a few added bytes
+ * on the wire, but it doesn't affect compatibility with TLS 1.3 implementations
+ * that don't use it. Therefore, unless transmission bandwidth is critical and
+ * you know that middlebox compatibility issues won't occur, it is therefore
+ * recommended to set this option.
+ *
+ * Comment to disable compatibility mode for TLS 1.3. If
+ * MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not have any
+ * effect on the build.
+ *
+ */
+//#define MBEDTLS_SSL_TLS1_3_COMPATIBILITY_MODE
+
+/**
+ * \def MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
+ *
+ * Enable TLS 1.3 PSK key exchange mode.
+ *
+ * Comment to disable support for the PSK key exchange mode in TLS 1.3. If
+ * MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not have any
+ * effect on the build.
+ *
+ */
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED
+
+/**
+ * \def MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
+ *
+ * Enable TLS 1.3 ephemeral key exchange mode.
+ *
+ * Requires: PSA_WANT_ALG_ECDH or PSA_WANT_ALG_FFDH
+ * MBEDTLS_X509_CRT_PARSE_C
+ * and at least one of:
+ * MBEDTLS_ECDSA_C or (MBEDTLS_USE_PSA_CRYPTO and PSA_WANT_ALG_ECDSA)
+ * MBEDTLS_PKCS1_V21
+ *
+ * Comment to disable support for the ephemeral key exchange mode in TLS 1.3.
+ * If MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not have any
+ * effect on the build.
+ *
+ */
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED
+
+/**
+ * \def MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED
+ *
+ * Enable TLS 1.3 PSK ephemeral key exchange mode.
+ *
+ * Requires: PSA_WANT_ALG_ECDH or PSA_WANT_ALG_FFDH
+ *
+ * Comment to disable support for the PSK ephemeral key exchange mode in
+ * TLS 1.3. If MBEDTLS_SSL_PROTO_TLS1_3 is not enabled, this option does not
+ * have any effect on the build.
+ *
+ */
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED
+
+/**
+ * \def MBEDTLS_SSL_EARLY_DATA
+ *
+ * Enable support for RFC 8446 TLS 1.3 early data.
+ *
+ * Requires: MBEDTLS_SSL_SESSION_TICKETS and either
+ * MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED or
+ * MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED
+ *
+ * Comment this to disable support for early data. If MBEDTLS_SSL_PROTO_TLS1_3
+ * is not enabled, this option does not have any effect on the build.
+ *
+ * This feature is experimental, not completed and thus not ready for
+ * production.
+ *
+ * \note The maximum amount of early data can be set with
+ * MBEDTLS_SSL_MAX_EARLY_DATA_SIZE.
+ *
+ */
+//#define MBEDTLS_SSL_EARLY_DATA
+
+/**
+ * \def MBEDTLS_SSL_PROTO_DTLS
+ *
+ * Enable support for DTLS (all available versions).
+ *
+ * Enable this and MBEDTLS_SSL_PROTO_TLS1_2 to enable DTLS 1.2.
+ *
+ * Requires: MBEDTLS_SSL_PROTO_TLS1_2
+ *
+ * Comment this macro to disable support for DTLS
+ */
+#define MBEDTLS_SSL_PROTO_DTLS
+
+/**
+ * \def MBEDTLS_SSL_ALPN
+ *
+ * Enable support for RFC 7301 Application Layer Protocol Negotiation.
+ *
+ * Comment this macro to disable support for ALPN.
+ */
+#define MBEDTLS_SSL_ALPN
+
+/**
+ * \def MBEDTLS_SSL_DTLS_ANTI_REPLAY
+ *
+ * Enable support for the anti-replay mechanism in DTLS.
+ *
+ * Requires: MBEDTLS_SSL_TLS_C
+ * MBEDTLS_SSL_PROTO_DTLS
+ *
+ * \warning Disabling this is often a security risk!
+ * See mbedtls_ssl_conf_dtls_anti_replay() for details.
+ *
+ * Comment this to disable anti-replay in DTLS.
+ */
+#define MBEDTLS_SSL_DTLS_ANTI_REPLAY
+
+/**
+ * \def MBEDTLS_SSL_DTLS_HELLO_VERIFY
+ *
+ * Enable support for HelloVerifyRequest on DTLS servers.
+ *
+ * This feature is highly recommended to prevent DTLS servers being used as
+ * amplifiers in DoS attacks against other hosts. It should always be enabled
+ * unless you know for sure amplification cannot be a problem in the
+ * environment in which your server operates.
+ *
+ * \warning Disabling this can be a security risk! (see above)
+ *
+ * Requires: MBEDTLS_SSL_PROTO_DTLS
+ *
+ * Comment this to disable support for HelloVerifyRequest.
+ */
+#define MBEDTLS_SSL_DTLS_HELLO_VERIFY
+
+/**
+ * \def MBEDTLS_SSL_DTLS_SRTP
+ *
+ * Enable support for negotiation of DTLS-SRTP (RFC 5764)
+ * through the use_srtp extension.
+ *
+ * \note This feature provides the minimum functionality required
+ * to negotiate the use of DTLS-SRTP and to allow the derivation of
+ * the associated SRTP packet protection key material.
+ * In particular, the SRTP packet protection itself, as well as the
+ * demultiplexing of RTP and DTLS packets at the datagram layer
+ * (see Section 5 of RFC 5764), are not handled by this feature.
+ * Instead, after successful completion of a handshake negotiating
+ * the use of DTLS-SRTP, the extended key exporter API
+ * mbedtls_ssl_conf_export_keys_cb() should be used to implement
+ * the key exporter described in Section 4.2 of RFC 5764 and RFC 5705
+ * (this is implemented in the SSL example programs).
+ * The resulting key should then be passed to an SRTP stack.
+ *
+ * Setting this option enables the runtime API
+ * mbedtls_ssl_conf_dtls_srtp_protection_profiles()
+ * through which the supported DTLS-SRTP protection
+ * profiles can be configured. You must call this API at
+ * runtime if you wish to negotiate the use of DTLS-SRTP.
+ *
+ * Requires: MBEDTLS_SSL_PROTO_DTLS
+ *
+ * Uncomment this to enable support for use_srtp extension.
+ */
+//#define MBEDTLS_SSL_DTLS_SRTP
+
+/**
+ * \def MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
+ *
+ * Enable server-side support for clients that reconnect from the same port.
+ *
+ * Some clients unexpectedly close the connection and try to reconnect using the
+ * same source port. This needs special support from the server to handle the
+ * new connection securely, as described in section 4.2.8 of RFC 6347. This
+ * flag enables that support.
+ *
+ * Requires: MBEDTLS_SSL_DTLS_HELLO_VERIFY
+ *
+ * Comment this to disable support for clients reusing the source port.
+ */
+#define MBEDTLS_SSL_DTLS_CLIENT_PORT_REUSE
+
+/**
+ * \def MBEDTLS_SSL_SESSION_TICKETS
+ *
+ * Enable support for RFC 5077 session tickets in SSL.
+ * Client-side, provides full support for session tickets (maintenance of a
+ * session store remains the responsibility of the application, though).
+ * Server-side, you also need to provide callbacks for writing and parsing
+ * tickets, including authenticated encryption and key management. Example
+ * callbacks are provided by MBEDTLS_SSL_TICKET_C.
+ *
+ * Comment this macro to disable support for SSL session tickets
+ */
+#define MBEDTLS_SSL_SESSION_TICKETS
+
+/**
+ * \def MBEDTLS_SSL_SERVER_NAME_INDICATION
+ *
+ * Enable support for RFC 6066 server name indication (SNI) in SSL.
+ *
+ * Requires: MBEDTLS_X509_CRT_PARSE_C
+ *
+ * Comment this macro to disable support for server name indication in SSL
+ */
+#define MBEDTLS_SSL_SERVER_NAME_INDICATION
+
+/**
+ * \def MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH
+ *
+ * When this option is enabled, the SSL buffer will be resized automatically
+ * based on the negotiated maximum fragment length in each direction.
+ *
+ * Requires: MBEDTLS_SSL_MAX_FRAGMENT_LENGTH
+ */
+//#define MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH
+
+/**
+ * \def MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN
+ *
+ * Enable testing of the constant-flow nature of some sensitive functions with
+ * clang's MemorySanitizer. This causes some existing tests to also test
+ * this non-functional property of the code under test.
+ *
+ * This setting requires compiling with clang -fsanitize=memory. The test
+ * suites can then be run normally.
+ *
+ * \warning This macro is only used for extended testing; it is not considered
+ * part of the library's API, so it may change or disappear at any time.
+ *
+ * Uncomment to enable testing of the constant-flow nature of selected code.
+ */
+//#define MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN
+
+/**
+ * \def MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND
+ *
+ * Enable testing of the constant-flow nature of some sensitive functions with
+ * valgrind's memcheck tool. This causes some existing tests to also test
+ * this non-functional property of the code under test.
+ *
+ * This setting requires valgrind headers for building, and is only useful for
+ * testing if the tests suites are run with valgrind's memcheck. This can be
+ * done for an individual test suite with 'valgrind ./test_suite_xxx', or when
+ * using CMake, this can be done for all test suites with 'make memcheck'.
+ *
+ * \warning This macro is only used for extended testing; it is not considered
+ * part of the library's API, so it may change or disappear at any time.
+ *
+ * Uncomment to enable testing of the constant-flow nature of selected code.
+ */
+//#define MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND
+
+/**
+ * \def MBEDTLS_TEST_HOOKS
+ *
+ * Enable features for invasive testing such as introspection functions and
+ * hooks for fault injection. This enables additional unit tests.
+ *
+ * Merely enabling this feature should not change the behavior of the product.
+ * It only adds new code, and new branching points where the default behavior
+ * is the same as when this feature is disabled.
+ * However, this feature increases the attack surface: there is an added
+ * risk of vulnerabilities, and more gadgets that can make exploits easier.
+ * Therefore this feature must never be enabled in production.
+ *
+ * See `docs/architecture/testing/mbed-crypto-invasive-testing.md` for more
+ * information.
+ *
+ * Uncomment to enable invasive tests.
+ */
+//#define MBEDTLS_TEST_HOOKS
+
+/**
+ * \def MBEDTLS_THREADING_ALT
+ *
+ * Provide your own alternate threading implementation.
+ *
+ * Requires: MBEDTLS_THREADING_C
+ *
+ * Uncomment this to allow your own alternate threading implementation.
+ */
+//#define MBEDTLS_THREADING_ALT
+
+/**
+ * \def MBEDTLS_THREADING_PTHREAD
+ *
+ * Enable the pthread wrapper layer for the threading layer.
+ *
+ * Requires: MBEDTLS_THREADING_C
+ *
+ * Uncomment this to enable pthread mutexes.
+ */
+//#define MBEDTLS_THREADING_PTHREAD
+
+/**
+ * \def MBEDTLS_USE_PSA_CRYPTO
+ *
+ * Make the X.509 and TLS libraries use PSA for cryptographic operations as
+ * much as possible, and enable new APIs for using keys handled by PSA Crypto.
+ *
+ * \note Development of this option is currently in progress, and parts of Mbed
+ * TLS's X.509 and TLS modules are not ported to PSA yet. However, these parts
+ * will still continue to work as usual, so enabling this option should not
+ * break backwards compatibility.
+ *
+ * \warning If you enable this option, you need to call `psa_crypto_init()`
+ * before calling any function from the SSL/TLS, X.509 or PK modules, except
+ * for the various mbedtls_xxx_init() functions which can be called at any time.
+ *
+ * \note An important and desirable effect of this option is that it allows
+ * PK, X.509 and TLS to take advantage of PSA drivers. For example, enabling
+ * this option is what allows use of drivers for ECDSA, ECDH and EC J-PAKE in
+ * those modules. However, note that even with this option disabled, some code
+ * in PK, X.509, TLS or the crypto library might still use PSA drivers, if it
+ * can determine it's safe to do so; currently that's the case for hashes.
+ *
+ * \note See docs/use-psa-crypto.md for a complete description this option.
+ *
+ * Requires: MBEDTLS_PSA_CRYPTO_C.
+ *
+ * Uncomment this to enable internal use of PSA Crypto and new associated APIs.
+ */
+//#define MBEDTLS_USE_PSA_CRYPTO
+
+/**
+ * \def MBEDTLS_PSA_CRYPTO_CONFIG
+ *
+ * This setting allows support for cryptographic mechanisms through the PSA
+ * API to be configured separately from support through the mbedtls API.
+ *
+ * When this option is disabled, the PSA API exposes the cryptographic
+ * mechanisms that can be implemented on top of the `mbedtls_xxx` API
+ * configured with `MBEDTLS_XXX` symbols.
+ *
+ * When this option is enabled, the PSA API exposes the cryptographic
+ * mechanisms requested by the `PSA_WANT_XXX` symbols defined in
+ * include/psa/crypto_config.h. The corresponding `MBEDTLS_XXX` settings are
+ * automatically enabled if required (i.e. if no PSA driver provides the
+ * mechanism). You may still freely enable additional `MBEDTLS_XXX` symbols
+ * in mbedtls_config.h.
+ *
+ * If the symbol #MBEDTLS_PSA_CRYPTO_CONFIG_FILE is defined, it specifies
+ * an alternative header to include instead of include/psa/crypto_config.h.
+ *
+ * \warning This option is experimental, in that the set of `PSA_WANT_XXX`
+ * symbols is not completely finalized yet, and the configuration
+ * tooling is not ideally adapted to having two separate configuration
+ * files.
+ * Future minor releases of Mbed TLS may make minor changes to those
+ * symbols, but we will endeavor to provide a transition path.
+ * Nonetheless, this option is considered mature enough to use in
+ * production, as long as you accept that you may need to make
+ * minor changes to psa/crypto_config.h when upgrading Mbed TLS.
+ */
+//#define MBEDTLS_PSA_CRYPTO_CONFIG
+
+/**
+ * \def MBEDTLS_VERSION_FEATURES
+ *
+ * Allow run-time checking of compile-time enabled features. Thus allowing users
+ * to check at run-time if the library is for instance compiled with threading
+ * support via mbedtls_version_check_feature().
+ *
+ * Requires: MBEDTLS_VERSION_C
+ *
+ * Comment this to disable run-time checking and save ROM space
+ */
+#define MBEDTLS_VERSION_FEATURES
+
+/**
+ * \def MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK
+ *
+ * If set, this enables the X.509 API `mbedtls_x509_crt_verify_with_ca_cb()`
+ * and the SSL API `mbedtls_ssl_conf_ca_cb()` which allow users to configure
+ * the set of trusted certificates through a callback instead of a linked
+ * list.
+ *
+ * This is useful for example in environments where a large number of trusted
+ * certificates is present and storing them in a linked list isn't efficient
+ * enough, or when the set of trusted certificates changes frequently.
+ *
+ * See the documentation of `mbedtls_x509_crt_verify_with_ca_cb()` and
+ * `mbedtls_ssl_conf_ca_cb()` for more information.
+ *
+ * Requires: MBEDTLS_X509_CRT_PARSE_C
+ *
+ * Uncomment to enable trusted certificate callbacks.
+ */
+//#define MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK
+
+/**
+ * \def MBEDTLS_X509_REMOVE_INFO
+ *
+ * Disable mbedtls_x509_*_info() and related APIs.
+ *
+ * Uncomment to omit mbedtls_x509_*_info(), as well as mbedtls_debug_print_crt()
+ * and other functions/constants only used by these functions, thus reducing
+ * the code footprint by several KB.
+ */
+//#define MBEDTLS_X509_REMOVE_INFO
+
+/**
+ * \def MBEDTLS_X509_RSASSA_PSS_SUPPORT
+ *
+ * Enable parsing and verification of X.509 certificates, CRLs and CSRS
+ * signed with RSASSA-PSS (aka PKCS#1 v2.1).
+ *
+ * Comment this macro to disallow using RSASSA-PSS in certificates.
+ */
+#define MBEDTLS_X509_RSASSA_PSS_SUPPORT
+/** \} name SECTION: Mbed TLS feature support */
+
+/**
+ * \name SECTION: Mbed TLS modules
+ *
+ * This section enables or disables entire modules in Mbed TLS
+ * \{
+ */
+
+/**
+ * \def MBEDTLS_AESNI_C
+ *
+ * Enable AES-NI support on x86-64 or x86-32.
+ *
+ * \note AESNI is only supported with certain compilers and target options:
+ * - Visual Studio 2013: supported.
+ * - GCC, x86-64, target not explicitly supporting AESNI:
+ * requires MBEDTLS_HAVE_ASM.
+ * - GCC, x86-32, target not explicitly supporting AESNI:
+ * not supported.
+ * - GCC, x86-64 or x86-32, target supporting AESNI: supported.
+ * For this assembly-less implementation, you must currently compile
+ * `library/aesni.c` and `library/aes.c` with machine options to enable
+ * SSE2 and AESNI instructions: `gcc -msse2 -maes -mpclmul` or
+ * `clang -maes -mpclmul`.
+ * - Non-x86 targets: this option is silently ignored.
+ * - Other compilers: this option is silently ignored.
+ *
+ * \note
+ * Above, "GCC" includes compatible compilers such as Clang.
+ * The limitations on target support are likely to be relaxed in the future.
+ *
+ * Module: library/aesni.c
+ * Caller: library/aes.c
+ *
+ * Requires: MBEDTLS_HAVE_ASM (on some platforms, see note)
+ *
+ * This modules adds support for the AES-NI instructions on x86.
+ */
+#define MBEDTLS_AESNI_C
+
+/**
+ * \def MBEDTLS_AESCE_C
+ *
+ * Enable AES cryptographic extension support on 64-bit Arm.
+ *
+ * Module: library/aesce.c
+ * Caller: library/aes.c
+ *
+ * Requires: MBEDTLS_AES_C
+ *
+ * \warning Runtime detection only works on Linux. For non-Linux operating
+ * system, Armv8-A Cryptographic Extensions must be supported by
+ * the CPU when this option is enabled.
+ *
+ * \note Minimum compiler versions for this feature are Clang 4.0,
+ * armclang 6.6, GCC 6.0 or MSVC 2019 version 16.11.2.
+ *
+ * \note \c CFLAGS must be set to a minimum of \c -march=armv8-a+crypto for
+ * armclang <= 6.9
+ *
+ * This module adds support for the AES Armv8-A Cryptographic Extensions on Aarch64 systems.
+ */
+#define MBEDTLS_AESCE_C
+
+/**
+ * \def MBEDTLS_AES_C
+ *
+ * Enable the AES block cipher.
+ *
+ * Module: library/aes.c
+ * Caller: library/cipher.c
+ * library/pem.c
+ * library/ctr_drbg.c
+ *
+ * This module enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256
+ * MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA
+ * MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384
+ * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384
+ * MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA
+ * MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256
+ * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256
+ * MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA
+ *
+ * PEM_PARSE uses AES for decrypting encrypted keys.
+ */
+#define MBEDTLS_AES_C
+
+/**
+ * \def MBEDTLS_ASN1_PARSE_C
+ *
+ * Enable the generic ASN1 parser.
+ *
+ * Module: library/asn1.c
+ * Caller: library/x509.c
+ * library/dhm.c
+ * library/pkcs12.c
+ * library/pkcs5.c
+ * library/pkparse.c
+ */
+#define MBEDTLS_ASN1_PARSE_C
+
+/**
+ * \def MBEDTLS_ASN1_WRITE_C
+ *
+ * Enable the generic ASN1 writer.
+ *
+ * Module: library/asn1write.c
+ * Caller: library/ecdsa.c
+ * library/pkwrite.c
+ * library/x509_create.c
+ * library/x509write_crt.c
+ * library/x509write_csr.c
+ */
+#define MBEDTLS_ASN1_WRITE_C
+
+/**
+ * \def MBEDTLS_BASE64_C
+ *
+ * Enable the Base64 module.
+ *
+ * Module: library/base64.c
+ * Caller: library/pem.c
+ *
+ * This module is required for PEM support (required by X.509).
+ */
+#define MBEDTLS_BASE64_C
+
+/**
+ * \def MBEDTLS_BIGNUM_C
+ *
+ * Enable the multi-precision integer library.
+ *
+ * Module: library/bignum.c
+ * library/bignum_core.c
+ * library/bignum_mod.c
+ * library/bignum_mod_raw.c
+ * Caller: library/dhm.c
+ * library/ecp.c
+ * library/ecdsa.c
+ * library/rsa.c
+ * library/rsa_alt_helpers.c
+ * library/ssl_tls.c
+ *
+ * This module is required for RSA, DHM and ECC (ECDH, ECDSA) support.
+ */
+#define MBEDTLS_BIGNUM_C
+
+/**
+ * \def MBEDTLS_CAMELLIA_C
+ *
+ * Enable the Camellia block cipher.
+ *
+ * Module: library/camellia.c
+ * Caller: library/cipher.c
+ *
+ * This module enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA
+ * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA
+ * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256
+ * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384
+ * MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384
+ * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256
+ * MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256
+ */
+#define MBEDTLS_CAMELLIA_C
+
+/**
+ * \def MBEDTLS_ARIA_C
+ *
+ * Enable the ARIA block cipher.
+ *
+ * Module: library/aria.c
+ * Caller: library/cipher.c
+ *
+ * This module enables the following ciphersuites (if other requisites are
+ * enabled as well):
+ *
+ * MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256
+ * MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384
+ * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384
+ * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384
+ * MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256
+ * MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384
+ * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256
+ * MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256
+ * MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384
+ * MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256
+ * MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384
+ * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256
+ * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256
+ * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384
+ * MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256
+ * MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384
+ * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256
+ * MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384
+ * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256
+ * MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256
+ * MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384
+ */
+#define MBEDTLS_ARIA_C
+
+/**
+ * \def MBEDTLS_CCM_C
+ *
+ * Enable the Counter with CBC-MAC (CCM) mode for 128-bit block cipher.
+ *
+ * Module: library/ccm.c
+ *
+ * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C or
+ * MBEDTLS_ARIA_C
+ *
+ * This module enables the AES-CCM ciphersuites, if other requisites are
+ * enabled as well.
+ */
+#define MBEDTLS_CCM_C
+
+/**
+ * \def MBEDTLS_CHACHA20_C
+ *
+ * Enable the ChaCha20 stream cipher.
+ *
+ * Module: library/chacha20.c
+ */
+#define MBEDTLS_CHACHA20_C
+
+/**
+ * \def MBEDTLS_CHACHAPOLY_C
+ *
+ * Enable the ChaCha20-Poly1305 AEAD algorithm.
+ *
+ * Module: library/chachapoly.c
+ *
+ * This module requires: MBEDTLS_CHACHA20_C, MBEDTLS_POLY1305_C
+ */
+#define MBEDTLS_CHACHAPOLY_C
+
+/**
+ * \def MBEDTLS_CIPHER_C
+ *
+ * Enable the generic cipher layer.
+ *
+ * Module: library/cipher.c
+ * Caller: library/ccm.c
+ * library/cmac.c
+ * library/gcm.c
+ * library/nist_kw.c
+ * library/pkcs12.c
+ * library/pkcs5.c
+ * library/psa_crypto_aead.c
+ * library/psa_crypto_mac.c
+ * library/ssl_ciphersuites.c
+ * library/ssl_msg.c
+ * library/ssl_ticket.c (unless MBEDTLS_USE_PSA_CRYPTO is enabled)
+ *
+ * Uncomment to enable generic cipher wrappers.
+ */
+#define MBEDTLS_CIPHER_C
+
+/**
+ * \def MBEDTLS_CMAC_C
+ *
+ * Enable the CMAC (Cipher-based Message Authentication Code) mode for block
+ * ciphers.
+ *
+ * \note When #MBEDTLS_CMAC_ALT is active, meaning that the underlying
+ * implementation of the CMAC algorithm is provided by an alternate
+ * implementation, that alternate implementation may opt to not support
+ * AES-192 or 3DES as underlying block ciphers for the CMAC operation.
+ *
+ * Module: library/cmac.c
+ *
+ * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_DES_C
+ *
+ */
+#define MBEDTLS_CMAC_C
+
+/**
+ * \def MBEDTLS_CTR_DRBG_C
+ *
+ * Enable the CTR_DRBG AES-based random generator.
+ * The CTR_DRBG generator uses AES-256 by default.
+ * To use AES-128 instead, enable \c MBEDTLS_CTR_DRBG_USE_128_BIT_KEY above.
+ *
+ * \note AES-128 will be used if \c MBEDTLS_AES_ONLY_128_BIT_KEY_LENGTH is set.
+ *
+ * \note To achieve a 256-bit security strength with CTR_DRBG,
+ * you must use AES-256 *and* use sufficient entropy.
+ * See ctr_drbg.h for more details.
+ *
+ * Module: library/ctr_drbg.c
+ * Caller:
+ *
+ * Requires: MBEDTLS_AES_C
+ *
+ * This module provides the CTR_DRBG AES random number generator.
+ */
+#define MBEDTLS_CTR_DRBG_C
+
+/**
+ * \def MBEDTLS_DEBUG_C
+ *
+ * Enable the debug functions.
+ *
+ * Module: library/debug.c
+ * Caller: library/ssl_msg.c
+ * library/ssl_tls.c
+ * library/ssl_tls12_*.c
+ * library/ssl_tls13_*.c
+ *
+ * This module provides debugging functions.
+ */
+#define MBEDTLS_DEBUG_C
+
+/**
+ * \def MBEDTLS_DES_C
+ *
+ * Enable the DES block cipher.
+ *
+ * Module: library/des.c
+ * Caller: library/pem.c
+ * library/cipher.c
+ *
+ * PEM_PARSE uses DES/3DES for decrypting encrypted keys.
+ *
+ * \warning DES/3DES are considered weak ciphers and their use constitutes a
+ * security risk. We recommend considering stronger ciphers instead.
+ */
+#define MBEDTLS_DES_C
+
+/**
+ * \def MBEDTLS_DHM_C
+ *
+ * Enable the Diffie-Hellman-Merkle module.
+ *
+ * Module: library/dhm.c
+ * Caller: library/ssl_tls.c
+ * library/ssl*_client.c
+ * library/ssl*_server.c
+ *
+ * This module is used by the following key exchanges:
+ * DHE-RSA, DHE-PSK
+ *
+ * \warning Using DHE constitutes a security risk as it
+ * is not possible to validate custom DH parameters.
+ * If possible, it is recommended users should consider
+ * preferring other methods of key exchange.
+ * See dhm.h for more details.
+ *
+ */
+#define MBEDTLS_DHM_C
+
+/**
+ * \def MBEDTLS_ECDH_C
+ *
+ * Enable the elliptic curve Diffie-Hellman library.
+ *
+ * Module: library/ecdh.c
+ * Caller: library/psa_crypto.c
+ * library/ssl_tls.c
+ * library/ssl*_client.c
+ * library/ssl*_server.c
+ *
+ * This module is used by the following key exchanges:
+ * ECDHE-ECDSA, ECDHE-RSA, DHE-PSK
+ *
+ * Requires: MBEDTLS_ECP_C
+ */
+#define MBEDTLS_ECDH_C
+
+/**
+ * \def MBEDTLS_ECDSA_C
+ *
+ * Enable the elliptic curve DSA library.
+ *
+ * Module: library/ecdsa.c
+ * Caller:
+ *
+ * This module is used by the following key exchanges:
+ * ECDHE-ECDSA
+ *
+ * Requires: MBEDTLS_ECP_C, MBEDTLS_ASN1_WRITE_C, MBEDTLS_ASN1_PARSE_C,
+ * and at least one MBEDTLS_ECP_DP_XXX_ENABLED for a
+ * short Weierstrass curve.
+ */
+#define MBEDTLS_ECDSA_C
+
+/**
+ * \def MBEDTLS_ECJPAKE_C
+ *
+ * Enable the elliptic curve J-PAKE library.
+ *
+ * \note EC J-PAKE support is based on the Thread v1.0.0 specification.
+ * It has not been reviewed for compliance with newer standards such as
+ * Thread v1.1 or RFC 8236.
+ *
+ * Module: library/ecjpake.c
+ * Caller:
+ *
+ * This module is used by the following key exchanges:
+ * ECJPAKE
+ *
+ * Requires: MBEDTLS_ECP_C and either MBEDTLS_MD_C or MBEDTLS_PSA_CRYPTO_C
+ *
+ * \warning If using a hash that is only provided by PSA drivers, you must
+ * call psa_crypto_init() before doing any EC J-PAKE operations.
+ */
+#define MBEDTLS_ECJPAKE_C
+
+/**
+ * \def MBEDTLS_ECP_C
+ *
+ * Enable the elliptic curve over GF(p) library.
+ *
+ * Module: library/ecp.c
+ * Caller: library/ecdh.c
+ * library/ecdsa.c
+ * library/ecjpake.c
+ *
+ * Requires: MBEDTLS_BIGNUM_C and at least one MBEDTLS_ECP_DP_XXX_ENABLED
+ */
+#define MBEDTLS_ECP_C
+
+/**
+ * \def MBEDTLS_ENTROPY_C
+ *
+ * Enable the platform-specific entropy code.
+ *
+ * Module: library/entropy.c
+ * Caller:
+ *
+ * Requires: MBEDTLS_SHA512_C or MBEDTLS_SHA256_C
+ *
+ * This module provides a generic entropy pool
+ */
+#define MBEDTLS_ENTROPY_C
+
+/**
+ * \def MBEDTLS_ERROR_C
+ *
+ * Enable error code to error string conversion.
+ *
+ * Module: library/error.c
+ * Caller:
+ *
+ * This module enables mbedtls_strerror().
+ */
+#define MBEDTLS_ERROR_C
+
+/**
+ * \def MBEDTLS_GCM_C
+ *
+ * Enable the Galois/Counter Mode (GCM).
+ *
+ * Module: library/gcm.c
+ *
+ * Requires: MBEDTLS_CIPHER_C, MBEDTLS_AES_C or MBEDTLS_CAMELLIA_C or
+ * MBEDTLS_ARIA_C
+ *
+ * This module enables the AES-GCM and CAMELLIA-GCM ciphersuites, if other
+ * requisites are enabled as well.
+ */
+#define MBEDTLS_GCM_C
+
+/**
+ * \def MBEDTLS_HKDF_C
+ *
+ * Enable the HKDF algorithm (RFC 5869).
+ *
+ * Module: library/hkdf.c
+ * Caller:
+ *
+ * Requires: MBEDTLS_MD_C
+ *
+ * This module adds support for the Hashed Message Authentication Code
+ * (HMAC)-based key derivation function (HKDF).
+ */
+#define MBEDTLS_HKDF_C
+
+/**
+ * \def MBEDTLS_HMAC_DRBG_C
+ *
+ * Enable the HMAC_DRBG random generator.
+ *
+ * Module: library/hmac_drbg.c
+ * Caller:
+ *
+ * Requires: MBEDTLS_MD_C
+ *
+ * Uncomment to enable the HMAC_DRBG random number generator.
+ */
+#define MBEDTLS_HMAC_DRBG_C
+
+/**
+ * \def MBEDTLS_LMS_C
+ *
+ * Enable the LMS stateful-hash asymmetric signature algorithm.
+ *
+ * Module: library/lms.c
+ * Caller:
+ *
+ * Requires: MBEDTLS_PSA_CRYPTO_C
+ *
+ * Uncomment to enable the LMS verification algorithm and public key operations.
+ */
+#define MBEDTLS_LMS_C
+
+/**
+ * \def MBEDTLS_LMS_PRIVATE
+ *
+ * Enable LMS private-key operations and signing code. Functions enabled by this
+ * option are experimental, and should not be used in production.
+ *
+ * Requires: MBEDTLS_LMS_C
+ *
+ * Uncomment to enable the LMS signature algorithm and private key operations.
+ */
+//#define MBEDTLS_LMS_PRIVATE
+
+/**
+ * \def MBEDTLS_NIST_KW_C
+ *
+ * Enable the Key Wrapping mode for 128-bit block ciphers,
+ * as defined in NIST SP 800-38F. Only KW and KWP modes
+ * are supported. At the moment, only AES is approved by NIST.
+ *
+ * Module: library/nist_kw.c
+ *
+ * Requires: MBEDTLS_AES_C and MBEDTLS_CIPHER_C
+ */
+#define MBEDTLS_NIST_KW_C
+
+/**
+ * \def MBEDTLS_MD_C
+ *
+ * Enable the generic layer for message digest (hashing) and HMAC.
+ *
+ * Requires: one of: MBEDTLS_MD5_C, MBEDTLS_RIPEMD160_C, MBEDTLS_SHA1_C,
+ * MBEDTLS_SHA224_C, MBEDTLS_SHA256_C, MBEDTLS_SHA384_C,
+ * MBEDTLS_SHA512_C, or MBEDTLS_PSA_CRYPTO_C with at least
+ * one hash.
+ * Module: library/md.c
+ * Caller: library/constant_time.c
+ * library/ecdsa.c
+ * library/ecjpake.c
+ * library/hkdf.c
+ * library/hmac_drbg.c
+ * library/pk.c
+ * library/pkcs5.c
+ * library/pkcs12.c
+ * library/psa_crypto_ecp.c
+ * library/psa_crypto_rsa.c
+ * library/rsa.c
+ * library/ssl_cookie.c
+ * library/ssl_msg.c
+ * library/ssl_tls.c
+ * library/x509.c
+ * library/x509_crt.c
+ * library/x509write_crt.c
+ * library/x509write_csr.c
+ *
+ * Uncomment to enable generic message digest wrappers.
+ */
+#define MBEDTLS_MD_C
+
+/**
+ * \def MBEDTLS_MD5_C
+ *
+ * Enable the MD5 hash algorithm.
+ *
+ * Module: library/md5.c
+ * Caller: library/md.c
+ * library/pem.c
+ * library/ssl_tls.c
+ *
+ * This module is required for TLS 1.2 depending on the handshake parameters.
+ * Further, it is used for checking MD5-signed certificates, and for PBKDF1
+ * when decrypting PEM-encoded encrypted keys.
+ *
+ * \warning MD5 is considered a weak message digest and its use constitutes a
+ * security risk. If possible, we recommend avoiding dependencies on
+ * it, and considering stronger message digests instead.
+ *
+ */
+#define MBEDTLS_MD5_C
+
+/**
+ * \def MBEDTLS_MEMORY_BUFFER_ALLOC_C
+ *
+ * Enable the buffer allocator implementation that makes use of a (stack)
+ * based buffer to 'allocate' dynamic memory. (replaces calloc() and free()
+ * calls)
+ *
+ * Module: library/memory_buffer_alloc.c
+ *
+ * Requires: MBEDTLS_PLATFORM_C
+ * MBEDTLS_PLATFORM_MEMORY (to use it within Mbed TLS)
+ *
+ * Enable this module to enable the buffer memory allocator.
+ */
+//#define MBEDTLS_MEMORY_BUFFER_ALLOC_C
+
+/**
+ * \def MBEDTLS_NET_C
+ *
+ * Enable the TCP and UDP over IPv6/IPv4 networking routines.
+ *
+ * \note This module only works on POSIX/Unix (including Linux, BSD and OS X)
+ * and Windows. For other platforms, you'll want to disable it, and write your
+ * own networking callbacks to be passed to \c mbedtls_ssl_set_bio().
+ *
+ * \note See also our Knowledge Base article about porting to a new
+ * environment:
+ * https://mbed-tls.readthedocs.io/en/latest/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS
+ *
+ * Module: library/net_sockets.c
+ *
+ * This module provides networking routines.
+ */
+#define MBEDTLS_NET_C
+
+/**
+ * \def MBEDTLS_OID_C
+ *
+ * Enable the OID database.
+ *
+ * Module: library/oid.c
+ * Caller: library/asn1write.c
+ * library/pkcs5.c
+ * library/pkparse.c
+ * library/pkwrite.c
+ * library/rsa.c
+ * library/x509.c
+ * library/x509_create.c
+ * library/x509_crl.c
+ * library/x509_crt.c
+ * library/x509_csr.c
+ * library/x509write_crt.c
+ * library/x509write_csr.c
+ *
+ * This modules translates between OIDs and internal values.
+ */
+#define MBEDTLS_OID_C
+
+/**
+ * \def MBEDTLS_PADLOCK_C
+ *
+ * Enable VIA Padlock support on x86.
+ *
+ * Module: library/padlock.c
+ * Caller: library/aes.c
+ *
+ * Requires: MBEDTLS_HAVE_ASM
+ *
+ * This modules adds support for the VIA PadLock on x86.
+ */
+#define MBEDTLS_PADLOCK_C
+
+/**
+ * \def MBEDTLS_PEM_PARSE_C
+ *
+ * Enable PEM decoding / parsing.
+ *
+ * Module: library/pem.c
+ * Caller: library/dhm.c
+ * library/pkparse.c
+ * library/x509_crl.c
+ * library/x509_crt.c
+ * library/x509_csr.c
+ *
+ * Requires: MBEDTLS_BASE64_C
+ * optionally MBEDTLS_MD5_C, or PSA Crypto with MD5 (see below)
+ *
+ * \warning When parsing password-protected files, if MD5 is provided only by
+ * a PSA driver, you must call psa_crypto_init() before the first file.
+ *
+ * This modules adds support for decoding / parsing PEM files.
+ */
+#define MBEDTLS_PEM_PARSE_C
+
+/**
+ * \def MBEDTLS_PEM_WRITE_C
+ *
+ * Enable PEM encoding / writing.
+ *
+ * Module: library/pem.c
+ * Caller: library/pkwrite.c
+ * library/x509write_crt.c
+ * library/x509write_csr.c
+ *
+ * Requires: MBEDTLS_BASE64_C
+ *
+ * This modules adds support for encoding / writing PEM files.
+ */
+#define MBEDTLS_PEM_WRITE_C
+
+/**
+ * \def MBEDTLS_PK_C
+ *
+ * Enable the generic public (asymmetric) key layer.
+ *
+ * Module: library/pk.c
+ * Caller: library/psa_crypto_rsa.c
+ * library/ssl_tls.c
+ * library/ssl*_client.c
+ * library/ssl*_server.c
+ * library/x509.c
+ *
+ * Requires: MBEDTLS_MD_C, MBEDTLS_RSA_C or MBEDTLS_ECP_C
+ *
+ * Uncomment to enable generic public key wrappers.
+ */
+#define MBEDTLS_PK_C
+
+/**
+ * \def MBEDTLS_PK_PARSE_C
+ *
+ * Enable the generic public (asymmetric) key parser.
+ *
+ * Module: library/pkparse.c
+ * Caller: library/x509_crt.c
+ * library/x509_csr.c
+ *
+ * Requires: MBEDTLS_PK_C
+ *
+ * Uncomment to enable generic public key parse functions.
+ */
+#define MBEDTLS_PK_PARSE_C
+
+/**
+ * \def MBEDTLS_PK_WRITE_C
+ *
+ * Enable the generic public (asymmetric) key writer.
+ *
+ * Module: library/pkwrite.c
+ * Caller: library/x509write.c
+ *
+ * Requires: MBEDTLS_PK_C
+ *
+ * Uncomment to enable generic public key write functions.
+ */
+#define MBEDTLS_PK_WRITE_C
+
+/**
+ * \def MBEDTLS_PKCS5_C
+ *
+ * Enable PKCS#5 functions.
+ *
+ * Module: library/pkcs5.c
+ *
+ * Requires: MBEDTLS_CIPHER_C
+ * Auto-enables: MBEDTLS_MD_C
+ *
+ * \warning If using a hash that is only provided by PSA drivers, you must
+ * call psa_crypto_init() before doing any PKCS5 operations.
+ *
+ * This module adds support for the PKCS#5 functions.
+ */
+#define MBEDTLS_PKCS5_C
+
+/**
+ * \def MBEDTLS_PKCS7_C
+ *
+ * Enable PKCS #7 core for using PKCS #7-formatted signatures.
+ * RFC Link - https://tools.ietf.org/html/rfc2315
+ *
+ * Module: library/pkcs7.c
+ *
+ * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_OID_C, MBEDTLS_PK_PARSE_C,
+ * MBEDTLS_X509_CRT_PARSE_C MBEDTLS_X509_CRL_PARSE_C,
+ * MBEDTLS_BIGNUM_C, MBEDTLS_MD_C
+ *
+ * This module is required for the PKCS #7 parsing modules.
+ */
+#define MBEDTLS_PKCS7_C
+
+/**
+ * \def MBEDTLS_PKCS12_C
+ *
+ * Enable PKCS#12 PBE functions.
+ * Adds algorithms for parsing PKCS#8 encrypted private keys
+ *
+ * Module: library/pkcs12.c
+ * Caller: library/pkparse.c
+ *
+ * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_CIPHER_C and either
+ * MBEDTLS_MD_C or MBEDTLS_PSA_CRYPTO_C.
+ *
+ * \warning If using a hash that is only provided by PSA drivers, you must
+ * call psa_crypto_init() before doing any PKCS12 operations.
+ *
+ * This module enables PKCS#12 functions.
+ */
+#define MBEDTLS_PKCS12_C
+
+/**
+ * \def MBEDTLS_PLATFORM_C
+ *
+ * Enable the platform abstraction layer that allows you to re-assign
+ * functions like calloc(), free(), snprintf(), printf(), fprintf(), exit().
+ *
+ * Enabling MBEDTLS_PLATFORM_C enables to use of MBEDTLS_PLATFORM_XXX_ALT
+ * or MBEDTLS_PLATFORM_XXX_MACRO directives, allowing the functions mentioned
+ * above to be specified at runtime or compile time respectively.
+ *
+ * \note This abstraction layer must be enabled on Windows (including MSYS2)
+ * as other modules rely on it for a fixed snprintf implementation.
+ *
+ * Module: library/platform.c
+ * Caller: Most other .c files
+ *
+ * This module enables abstraction of common (libc) functions.
+ */
+#define MBEDTLS_PLATFORM_C
+
+/**
+ * \def MBEDTLS_POLY1305_C
+ *
+ * Enable the Poly1305 MAC algorithm.
+ *
+ * Module: library/poly1305.c
+ * Caller: library/chachapoly.c
+ */
+#define MBEDTLS_POLY1305_C
+
+/**
+ * \def MBEDTLS_PSA_CRYPTO_C
+ *
+ * Enable the Platform Security Architecture cryptography API.
+ *
+ * Module: library/psa_crypto.c
+ *
+ * Requires: MBEDTLS_CIPHER_C,
+ * either MBEDTLS_CTR_DRBG_C and MBEDTLS_ENTROPY_C,
+ * or MBEDTLS_HMAC_DRBG_C and MBEDTLS_ENTROPY_C,
+ * or MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG.
+ *
+ */
+#define MBEDTLS_PSA_CRYPTO_C
+
+/**
+ * \def MBEDTLS_PSA_CRYPTO_SE_C
+ *
+ * Enable dynamic secure element support in the Platform Security Architecture
+ * cryptography API.
+ *
+ * \deprecated This feature is deprecated. Please switch to the PSA driver
+ * interface.
+ *
+ * Module: library/psa_crypto_se.c
+ *
+ * Requires: MBEDTLS_PSA_CRYPTO_C, MBEDTLS_PSA_CRYPTO_STORAGE_C
+ *
+ */
+//#define MBEDTLS_PSA_CRYPTO_SE_C
+
+/**
+ * \def MBEDTLS_PSA_CRYPTO_STORAGE_C
+ *
+ * Enable the Platform Security Architecture persistent key storage.
+ *
+ * Module: library/psa_crypto_storage.c
+ *
+ * Requires: MBEDTLS_PSA_CRYPTO_C,
+ * either MBEDTLS_PSA_ITS_FILE_C or a native implementation of
+ * the PSA ITS interface
+ */
+#define MBEDTLS_PSA_CRYPTO_STORAGE_C
+
+/**
+ * \def MBEDTLS_PSA_ITS_FILE_C
+ *
+ * Enable the emulation of the Platform Security Architecture
+ * Internal Trusted Storage (PSA ITS) over files.
+ *
+ * Module: library/psa_its_file.c
+ *
+ * Requires: MBEDTLS_FS_IO
+ */
+#define MBEDTLS_PSA_ITS_FILE_C
+
+/**
+ * \def MBEDTLS_RIPEMD160_C
+ *
+ * Enable the RIPEMD-160 hash algorithm.
+ *
+ * Module: library/ripemd160.c
+ * Caller: library/md.c
+ *
+ */
+#define MBEDTLS_RIPEMD160_C
+
+/**
+ * \def MBEDTLS_RSA_C
+ *
+ * Enable the RSA public-key cryptosystem.
+ *
+ * Module: library/rsa.c
+ * library/rsa_alt_helpers.c
+ * Caller: library/pk.c
+ * library/psa_crypto.c
+ * library/ssl_tls.c
+ * library/ssl*_client.c
+ * library/ssl*_server.c
+ *
+ * This module is used by the following key exchanges:
+ * RSA, DHE-RSA, ECDHE-RSA, RSA-PSK
+ *
+ * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C
+ */
+#define MBEDTLS_RSA_C
+
+/**
+ * \def MBEDTLS_SHA1_C
+ *
+ * Enable the SHA1 cryptographic hash algorithm.
+ *
+ * Module: library/sha1.c
+ * Caller: library/md.c
+ * library/psa_crypto_hash.c
+ *
+ * This module is required for TLS 1.2 depending on the handshake parameters,
+ * and for SHA1-signed certificates.
+ *
+ * \warning SHA-1 is considered a weak message digest and its use constitutes
+ * a security risk. If possible, we recommend avoiding dependencies
+ * on it, and considering stronger message digests instead.
+ *
+ */
+#define MBEDTLS_SHA1_C
+
+/**
+ * \def MBEDTLS_SHA224_C
+ *
+ * Enable the SHA-224 cryptographic hash algorithm.
+ *
+ * Module: library/sha256.c
+ * Caller: library/md.c
+ * library/ssl_cookie.c
+ *
+ * This module adds support for SHA-224.
+ */
+#define MBEDTLS_SHA224_C
+
+/**
+ * \def MBEDTLS_SHA256_C
+ *
+ * Enable the SHA-256 cryptographic hash algorithm.
+ *
+ * Module: library/sha256.c
+ * Caller: library/entropy.c
+ * library/md.c
+ * library/ssl_tls.c
+ * library/ssl*_client.c
+ * library/ssl*_server.c
+ *
+ * This module adds support for SHA-256.
+ * This module is required for the SSL/TLS 1.2 PRF function.
+ */
+#define MBEDTLS_SHA256_C
+
+/**
+ * \def MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT
+ *
+ * Enable acceleration of the SHA-256 and SHA-224 cryptographic hash algorithms
+ * with the ARMv8 cryptographic extensions if they are available at runtime.
+ * If not, the library will fall back to the C implementation.
+ *
+ * \note If MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT is defined when building
+ * for a non-Aarch64 build it will be silently ignored.
+ *
+ * \note Minimum compiler versions for this feature are Clang 4.0,
+ * armclang 6.6 or GCC 6.0.
+ *
+ * \note \c CFLAGS must be set to a minimum of \c -march=armv8-a+crypto for
+ * armclang <= 6.9
+ *
+ * \warning MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT cannot be defined at the
+ * same time as MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY.
+ *
+ * Requires: MBEDTLS_SHA256_C.
+ *
+ * Module: library/sha256.c
+ *
+ * Uncomment to have the library check for the A64 SHA-256 crypto extensions
+ * and use them if available.
+ */
+//#define MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT
+
+/**
+ * \def MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY
+ *
+ * Enable acceleration of the SHA-256 and SHA-224 cryptographic hash algorithms
+ * with the ARMv8 cryptographic extensions, which must be available at runtime
+ * or else an illegal instruction fault will occur.
+ *
+ * \note This allows builds with a smaller code size than with
+ * MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT
+ *
+ * \note Minimum compiler versions for this feature are Clang 4.0,
+ * armclang 6.6 or GCC 6.0.
+ *
+ * \note \c CFLAGS must be set to a minimum of \c -march=armv8-a+crypto for
+ * armclang <= 6.9
+ *
+ * \warning MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY cannot be defined at the same
+ * time as MBEDTLS_SHA256_USE_A64_CRYPTO_IF_PRESENT.
+ *
+ * Requires: MBEDTLS_SHA256_C.
+ *
+ * Module: library/sha256.c
+ *
+ * Uncomment to have the library use the A64 SHA-256 crypto extensions
+ * unconditionally.
+ */
+//#define MBEDTLS_SHA256_USE_A64_CRYPTO_ONLY
+
+/**
+ * \def MBEDTLS_SHA384_C
+ *
+ * Enable the SHA-384 cryptographic hash algorithm.
+ *
+ * Module: library/sha512.c
+ * Caller: library/md.c
+ * library/psa_crypto_hash.c
+ * library/ssl_tls.c
+ * library/ssl*_client.c
+ * library/ssl*_server.c
+ *
+ * Comment to disable SHA-384
+ */
+#define MBEDTLS_SHA384_C
+
+/**
+ * \def MBEDTLS_SHA512_C
+ *
+ * Enable SHA-512 cryptographic hash algorithms.
+ *
+ * Module: library/sha512.c
+ * Caller: library/entropy.c
+ * library/md.c
+ * library/ssl_tls.c
+ * library/ssl_cookie.c
+ *
+ * This module adds support for SHA-512.
+ */
+#define MBEDTLS_SHA512_C
+
+/**
+ * \def MBEDTLS_SHA3_C
+ *
+ * Enable the SHA3 cryptographic hash algorithm.
+ *
+ * Module: library/sha3.c
+ *
+ * This module adds support for SHA3.
+ */
+#define MBEDTLS_SHA3_C
+
+/**
+ * \def MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT
+ *
+ * Enable acceleration of the SHA-512 and SHA-384 cryptographic hash algorithms
+ * with the ARMv8 cryptographic extensions if they are available at runtime.
+ * If not, the library will fall back to the C implementation.
+ *
+ * \note If MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT is defined when building
+ * for a non-Aarch64 build it will be silently ignored.
+ *
+ * \note Minimum compiler versions for this feature are Clang 7.0,
+ * armclang 6.9 or GCC 8.0.
+ *
+ * \note \c CFLAGS must be set to a minimum of \c -march=armv8.2-a+sha3 for
+ * armclang 6.9
+ *
+ * \warning MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT cannot be defined at the
+ * same time as MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY.
+ *
+ * Requires: MBEDTLS_SHA512_C.
+ *
+ * Module: library/sha512.c
+ *
+ * Uncomment to have the library check for the A64 SHA-512 crypto extensions
+ * and use them if available.
+ */
+//#define MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT
+
+/**
+ * \def MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY
+ *
+ * Enable acceleration of the SHA-512 and SHA-384 cryptographic hash algorithms
+ * with the ARMv8 cryptographic extensions, which must be available at runtime
+ * or else an illegal instruction fault will occur.
+ *
+ * \note This allows builds with a smaller code size than with
+ * MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT
+ *
+ * \note Minimum compiler versions for this feature are Clang 7.0,
+ * armclang 6.9 or GCC 8.0.
+ *
+ * \note \c CFLAGS must be set to a minimum of \c -march=armv8.2-a+sha3 for
+ * armclang 6.9
+ *
+ * \warning MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY cannot be defined at the same
+ * time as MBEDTLS_SHA512_USE_A64_CRYPTO_IF_PRESENT.
+ *
+ * Requires: MBEDTLS_SHA512_C.
+ *
+ * Module: library/sha512.c
+ *
+ * Uncomment to have the library use the A64 SHA-512 crypto extensions
+ * unconditionally.
+ */
+//#define MBEDTLS_SHA512_USE_A64_CRYPTO_ONLY
+
+/**
+ * \def MBEDTLS_SSL_CACHE_C
+ *
+ * Enable simple SSL cache implementation.
+ *
+ * Module: library/ssl_cache.c
+ * Caller:
+ *
+ * Requires: MBEDTLS_SSL_CACHE_C
+ */
+#define MBEDTLS_SSL_CACHE_C
+
+/**
+ * \def MBEDTLS_SSL_COOKIE_C
+ *
+ * Enable basic implementation of DTLS cookies for hello verification.
+ *
+ * Module: library/ssl_cookie.c
+ * Caller:
+ */
+#define MBEDTLS_SSL_COOKIE_C
+
+/**
+ * \def MBEDTLS_SSL_TICKET_C
+ *
+ * Enable an implementation of TLS server-side callbacks for session tickets.
+ *
+ * Module: library/ssl_ticket.c
+ * Caller:
+ *
+ * Requires: (MBEDTLS_CIPHER_C || MBEDTLS_USE_PSA_CRYPTO) &&
+ * (MBEDTLS_GCM_C || MBEDTLS_CCM_C || MBEDTLS_CHACHAPOLY_C)
+ */
+#define MBEDTLS_SSL_TICKET_C
+
+/**
+ * \def MBEDTLS_SSL_CLI_C
+ *
+ * Enable the SSL/TLS client code.
+ *
+ * Module: library/ssl*_client.c
+ * Caller:
+ *
+ * Requires: MBEDTLS_SSL_TLS_C
+ *
+ * This module is required for SSL/TLS client support.
+ */
+#define MBEDTLS_SSL_CLI_C
+
+/**
+ * \def MBEDTLS_SSL_SRV_C
+ *
+ * Enable the SSL/TLS server code.
+ *
+ * Module: library/ssl*_server.c
+ * Caller:
+ *
+ * Requires: MBEDTLS_SSL_TLS_C
+ *
+ * This module is required for SSL/TLS server support.
+ */
+#define MBEDTLS_SSL_SRV_C
+
+/**
+ * \def MBEDTLS_SSL_TLS_C
+ *
+ * Enable the generic SSL/TLS code.
+ *
+ * Module: library/ssl_tls.c
+ * Caller: library/ssl*_client.c
+ * library/ssl*_server.c
+ *
+ * Requires: MBEDTLS_CIPHER_C, MBEDTLS_MD_C
+ * and at least one of the MBEDTLS_SSL_PROTO_XXX defines
+ *
+ * This module is required for SSL/TLS.
+ */
+#define MBEDTLS_SSL_TLS_C
+
+/**
+ * \def MBEDTLS_THREADING_C
+ *
+ * Enable the threading abstraction layer.
+ * By default Mbed TLS assumes it is used in a non-threaded environment or that
+ * contexts are not shared between threads. If you do intend to use contexts
+ * between threads, you will need to enable this layer to prevent race
+ * conditions. See also our Knowledge Base article about threading:
+ * https://mbed-tls.readthedocs.io/en/latest/kb/development/thread-safety-and-multi-threading
+ *
+ * Module: library/threading.c
+ *
+ * This allows different threading implementations (self-implemented or
+ * provided).
+ *
+ * You will have to enable either MBEDTLS_THREADING_ALT or
+ * MBEDTLS_THREADING_PTHREAD.
+ *
+ * Enable this layer to allow use of mutexes within Mbed TLS
+ */
+//#define MBEDTLS_THREADING_C
+
+/**
+ * \def MBEDTLS_TIMING_C
+ *
+ * Enable the semi-portable timing interface.
+ *
+ * \note The provided implementation only works on POSIX/Unix (including Linux,
+ * BSD and OS X) and Windows. On other platforms, you can either disable that
+ * module and provide your own implementations of the callbacks needed by
+ * \c mbedtls_ssl_set_timer_cb() for DTLS, or leave it enabled and provide
+ * your own implementation of the whole module by setting
+ * \c MBEDTLS_TIMING_ALT in the current file.
+ *
+ * \note The timing module will include time.h on suitable platforms
+ * regardless of the setting of MBEDTLS_HAVE_TIME, unless
+ * MBEDTLS_TIMING_ALT is used. See timing.c for more information.
+ *
+ * \note See also our Knowledge Base article about porting to a new
+ * environment:
+ * https://mbed-tls.readthedocs.io/en/latest/kb/how-to/how-do-i-port-mbed-tls-to-a-new-environment-OS
+ *
+ * Module: library/timing.c
+ */
+#define MBEDTLS_TIMING_C
+
+/**
+ * \def MBEDTLS_VERSION_C
+ *
+ * Enable run-time version information.
+ *
+ * Module: library/version.c
+ *
+ * This module provides run-time version information.
+ */
+#define MBEDTLS_VERSION_C
+
+/**
+ * \def MBEDTLS_X509_USE_C
+ *
+ * Enable X.509 core for using certificates.
+ *
+ * Module: library/x509.c
+ * Caller: library/x509_crl.c
+ * library/x509_crt.c
+ * library/x509_csr.c
+ *
+ * Requires: MBEDTLS_ASN1_PARSE_C, MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, MBEDTLS_PK_PARSE_C,
+ * (MBEDTLS_MD_C or MBEDTLS_USE_PSA_CRYPTO)
+ *
+ * \warning If building with MBEDTLS_USE_PSA_CRYPTO, you must call
+ * psa_crypto_init() before doing any X.509 operation.
+ *
+ * This module is required for the X.509 parsing modules.
+ */
+#define MBEDTLS_X509_USE_C
+
+/**
+ * \def MBEDTLS_X509_CRT_PARSE_C
+ *
+ * Enable X.509 certificate parsing.
+ *
+ * Module: library/x509_crt.c
+ * Caller: library/ssl_tls.c
+ * library/ssl*_client.c
+ * library/ssl*_server.c
+ *
+ * Requires: MBEDTLS_X509_USE_C
+ *
+ * This module is required for X.509 certificate parsing.
+ */
+#define MBEDTLS_X509_CRT_PARSE_C
+
+/**
+ * \def MBEDTLS_X509_CRL_PARSE_C
+ *
+ * Enable X.509 CRL parsing.
+ *
+ * Module: library/x509_crl.c
+ * Caller: library/x509_crt.c
+ *
+ * Requires: MBEDTLS_X509_USE_C
+ *
+ * This module is required for X.509 CRL parsing.
+ */
+#define MBEDTLS_X509_CRL_PARSE_C
+
+/**
+ * \def MBEDTLS_X509_CSR_PARSE_C
+ *
+ * Enable X.509 Certificate Signing Request (CSR) parsing.
+ *
+ * Module: library/x509_csr.c
+ * Caller: library/x509_crt_write.c
+ *
+ * Requires: MBEDTLS_X509_USE_C
+ *
+ * This module is used for reading X.509 certificate request.
+ */
+#define MBEDTLS_X509_CSR_PARSE_C
+
+/**
+ * \def MBEDTLS_X509_CREATE_C
+ *
+ * Enable X.509 core for creating certificates.
+ *
+ * Module: library/x509_create.c
+ *
+ * Requires: MBEDTLS_BIGNUM_C, MBEDTLS_OID_C, MBEDTLS_PK_PARSE_C,
+ * (MBEDTLS_MD_C or MBEDTLS_USE_PSA_CRYPTO)
+ *
+ * \warning If building with MBEDTLS_USE_PSA_CRYPTO, you must call
+ * psa_crypto_init() before doing any X.509 create operation.
+ *
+ * This module is the basis for creating X.509 certificates and CSRs.
+ */
+#define MBEDTLS_X509_CREATE_C
+
+/**
+ * \def MBEDTLS_X509_CRT_WRITE_C
+ *
+ * Enable creating X.509 certificates.
+ *
+ * Module: library/x509_crt_write.c
+ *
+ * Requires: MBEDTLS_X509_CREATE_C
+ *
+ * This module is required for X.509 certificate creation.
+ */
+#define MBEDTLS_X509_CRT_WRITE_C
+
+/**
+ * \def MBEDTLS_X509_CSR_WRITE_C
+ *
+ * Enable creating X.509 Certificate Signing Requests (CSR).
+ *
+ * Module: library/x509_csr_write.c
+ *
+ * Requires: MBEDTLS_X509_CREATE_C
+ *
+ * This module is required for X.509 certificate request writing.
+ */
+#define MBEDTLS_X509_CSR_WRITE_C
+
+/** \} name SECTION: Mbed TLS modules */
+
+/**
+ * \name SECTION: General configuration options
+ *
+ * This section contains Mbed TLS build settings that are not associated
+ * with a particular module.
+ *
+ * \{
+ */
+
+/**
+ * \def MBEDTLS_CONFIG_FILE
+ *
+ * If defined, this is a header which will be included instead of
+ * `"mbedtls/mbedtls_config.h"`.
+ * This header file specifies the compile-time configuration of Mbed TLS.
+ * Unlike other configuration options, this one must be defined on the
+ * compiler command line: a definition in `mbedtls_config.h` would have
+ * no effect.
+ *
+ * This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
+ * non-standard feature of the C language, so this feature is only available
+ * with compilers that perform macro expansion on an <tt>\#include</tt> line.
+ *
+ * The value of this symbol is typically a path in double quotes, either
+ * absolute or relative to a directory on the include search path.
+ */
+//#define MBEDTLS_CONFIG_FILE "mbedtls/mbedtls_config.h"
+
+/**
+ * \def MBEDTLS_USER_CONFIG_FILE
+ *
+ * If defined, this is a header which will be included after
+ * `"mbedtls/mbedtls_config.h"` or #MBEDTLS_CONFIG_FILE.
+ * This allows you to modify the default configuration, including the ability
+ * to undefine options that are enabled by default.
+ *
+ * This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
+ * non-standard feature of the C language, so this feature is only available
+ * with compilers that perform macro expansion on an <tt>\#include</tt> line.
+ *
+ * The value of this symbol is typically a path in double quotes, either
+ * absolute or relative to a directory on the include search path.
+ */
+//#define MBEDTLS_USER_CONFIG_FILE "/dev/null"
+
+/**
+ * \def MBEDTLS_PSA_CRYPTO_CONFIG_FILE
+ *
+ * If defined, this is a header which will be included instead of
+ * `"psa/crypto_config.h"`.
+ * This header file specifies which cryptographic mechanisms are available
+ * through the PSA API when #MBEDTLS_PSA_CRYPTO_CONFIG is enabled, and
+ * is not used when #MBEDTLS_PSA_CRYPTO_CONFIG is disabled.
+ *
+ * This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
+ * non-standard feature of the C language, so this feature is only available
+ * with compilers that perform macro expansion on an <tt>\#include</tt> line.
+ *
+ * The value of this symbol is typically a path in double quotes, either
+ * absolute or relative to a directory on the include search path.
+ */
+//#define MBEDTLS_PSA_CRYPTO_CONFIG_FILE "psa/crypto_config.h"
+
+/**
+ * \def MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE
+ *
+ * If defined, this is a header which will be included after
+ * `"psa/crypto_config.h"` or #MBEDTLS_PSA_CRYPTO_CONFIG_FILE.
+ * This allows you to modify the default configuration, including the ability
+ * to undefine options that are enabled by default.
+ *
+ * This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
+ * non-standard feature of the C language, so this feature is only available
+ * with compilers that perform macro expansion on an <tt>\#include</tt> line.
+ *
+ * The value of this symbol is typically a path in double quotes, either
+ * absolute or relative to a directory on the include search path.
+ */
+//#define MBEDTLS_PSA_CRYPTO_USER_CONFIG_FILE "/dev/null"
+
+/**
+ * \def MBEDTLS_PSA_CRYPTO_PLATFORM_FILE
+ *
+ * If defined, this is a header which will be included instead of
+ * `"psa/crypto_platform.h"`. This file should declare the same identifiers
+ * as the one in Mbed TLS, but with definitions adapted to the platform on
+ * which the library code will run.
+ *
+ * \note The required content of this header can vary from one version of
+ * Mbed TLS to the next. Integrators who provide an alternative file
+ * should review the changes in the original file whenever they
+ * upgrade Mbed TLS.
+ *
+ * This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
+ * non-standard feature of the C language, so this feature is only available
+ * with compilers that perform macro expansion on an <tt>\#include</tt> line.
+ *
+ * The value of this symbol is typically a path in double quotes, either
+ * absolute or relative to a directory on the include search path.
+ */
+//#define MBEDTLS_PSA_CRYPTO_PLATFORM_FILE "psa/crypto_platform_alt.h"
+
+/**
+ * \def MBEDTLS_PSA_CRYPTO_STRUCT_FILE
+ *
+ * If defined, this is a header which will be included instead of
+ * `"psa/crypto_struct.h"`. This file should declare the same identifiers
+ * as the one in Mbed TLS, but with definitions adapted to the environment
+ * in which the library code will run. The typical use for this feature
+ * is to provide alternative type definitions on the client side in
+ * client-server integrations of PSA crypto, where operation structures
+ * contain handles instead of cryptographic data.
+ *
+ * \note The required content of this header can vary from one version of
+ * Mbed TLS to the next. Integrators who provide an alternative file
+ * should review the changes in the original file whenever they
+ * upgrade Mbed TLS.
+ *
+ * This macro is expanded after an <tt>\#include</tt> directive. This is a popular but
+ * non-standard feature of the C language, so this feature is only available
+ * with compilers that perform macro expansion on an <tt>\#include</tt> line.
+ *
+ * The value of this symbol is typically a path in double quotes, either
+ * absolute or relative to a directory on the include search path.
+ */
+//#define MBEDTLS_PSA_CRYPTO_STRUCT_FILE "psa/crypto_struct_alt.h"
+
+/** \} name SECTION: General configuration options */
+
+/**
+ * \name SECTION: Module configuration options
+ *
+ * This section allows for the setting of module specific sizes and
+ * configuration options. The default values are already present in the
+ * relevant header files and should suffice for the regular use cases.
+ *
+ * Our advice is to enable options and change their values here
+ * only if you have a good reason and know the consequences.
+ * \{
+ */
+/* The Doxygen documentation here is used when a user comments out a
+ * setting and runs doxygen themselves. On the other hand, when we typeset
+ * the full documentation including disabled settings, the documentation
+ * in specific modules' header files is used if present. When editing this
+ * file, make sure that each option is documented in exactly one place,
+ * plus optionally a same-line Doxygen comment here if there is a Doxygen
+ * comment in the specific module. */
+
+/* MPI / BIGNUM options */
+//#define MBEDTLS_MPI_WINDOW_SIZE 2 /**< Maximum window size used. */
+//#define MBEDTLS_MPI_MAX_SIZE 1024 /**< Maximum number of bytes for usable MPIs. */
+
+/* CTR_DRBG options */
+//#define MBEDTLS_CTR_DRBG_ENTROPY_LEN 48 /**< Amount of entropy used per seed by default (48 with SHA-512, 32 with SHA-256) */
+//#define MBEDTLS_CTR_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */
+//#define MBEDTLS_CTR_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */
+//#define MBEDTLS_CTR_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */
+//#define MBEDTLS_CTR_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */
+
+/* HMAC_DRBG options */
+//#define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */
+//#define MBEDTLS_HMAC_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */
+//#define MBEDTLS_HMAC_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */
+//#define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */
+
+/* ECP options */
+//#define MBEDTLS_ECP_WINDOW_SIZE 4 /**< Maximum window size used */
+//#define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up */
+
+/* Entropy options */
+//#define MBEDTLS_ENTROPY_MAX_SOURCES 20 /**< Maximum number of sources supported */
+//#define MBEDTLS_ENTROPY_MAX_GATHER 128 /**< Maximum amount requested from entropy sources */
+//#define MBEDTLS_ENTROPY_MIN_HARDWARE 32 /**< Default minimum number of bytes required for the hardware entropy source mbedtls_hardware_poll() before entropy is released */
+
+/* Memory buffer allocator options */
+//#define MBEDTLS_MEMORY_ALIGN_MULTIPLE 4 /**< Align on multiples of this value */
+
+/* Platform options */
+//#define MBEDTLS_PLATFORM_STD_MEM_HDR <stdlib.h> /**< Header to include if MBEDTLS_PLATFORM_NO_STD_FUNCTIONS is defined. Don't define if no header is needed. */
+
+/** \def MBEDTLS_PLATFORM_STD_CALLOC
+ *
+ * Default allocator to use, can be undefined.
+ * It must initialize the allocated buffer memory to zeroes.
+ * The size of the buffer is the product of the two parameters.
+ * The calloc function returns either a null pointer or a pointer to the allocated space.
+ * If the product is 0, the function may either return NULL or a valid pointer to an array of size 0 which is a valid input to the deallocation function.
+ * An uninitialized #MBEDTLS_PLATFORM_STD_CALLOC always fails, returning a null pointer.
+ * See the description of #MBEDTLS_PLATFORM_MEMORY for more details.
+ * The corresponding deallocation function is #MBEDTLS_PLATFORM_STD_FREE.
+ */
+//#define MBEDTLS_PLATFORM_STD_CALLOC calloc
+
+/** \def MBEDTLS_PLATFORM_STD_FREE
+ *
+ * Default free to use, can be undefined.
+ * NULL is a valid parameter, and the function must do nothing.
+ * A non-null parameter will always be a pointer previously returned by #MBEDTLS_PLATFORM_STD_CALLOC and not yet freed.
+ * An uninitialized #MBEDTLS_PLATFORM_STD_FREE does not do anything.
+ * See the description of #MBEDTLS_PLATFORM_MEMORY for more details (same principles as for MBEDTLS_PLATFORM_STD_CALLOC apply).
+ */
+//#define MBEDTLS_PLATFORM_STD_FREE free
+//#define MBEDTLS_PLATFORM_STD_SETBUF setbuf /**< Default setbuf to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_EXIT exit /**< Default exit to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_TIME time /**< Default time to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
+//#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< Default fprintf to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< Default printf to use, can be undefined */
+/* Note: your snprintf must correctly zero-terminate the buffer! */
+//#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< Default snprintf to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS 0 /**< Default exit value to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE 1 /**< Default exit value to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_NV_SEED_READ mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */
+//#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE "seedfile" /**< Seed file to read/write with default implementation */
+
+/* To use the following function macros, MBEDTLS_PLATFORM_C must be enabled. */
+/* MBEDTLS_PLATFORM_XXX_MACRO and MBEDTLS_PLATFORM_XXX_ALT cannot both be defined */
+//#define MBEDTLS_PLATFORM_CALLOC_MACRO calloc /**< Default allocator macro to use, can be undefined. See MBEDTLS_PLATFORM_STD_CALLOC for requirements. */
+//#define MBEDTLS_PLATFORM_FREE_MACRO free /**< Default free macro to use, can be undefined. See MBEDTLS_PLATFORM_STD_FREE for requirements. */
+//#define MBEDTLS_PLATFORM_EXIT_MACRO exit /**< Default exit macro to use, can be undefined */
+//#define MBEDTLS_PLATFORM_SETBUF_MACRO setbuf /**< Default setbuf macro to use, can be undefined */
+//#define MBEDTLS_PLATFORM_TIME_MACRO time /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
+//#define MBEDTLS_PLATFORM_TIME_TYPE_MACRO time_t /**< Default time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled */
+//#define MBEDTLS_PLATFORM_FPRINTF_MACRO fprintf /**< Default fprintf macro to use, can be undefined */
+//#define MBEDTLS_PLATFORM_PRINTF_MACRO printf /**< Default printf macro to use, can be undefined */
+/* Note: your snprintf must correctly zero-terminate the buffer! */
+//#define MBEDTLS_PLATFORM_SNPRINTF_MACRO snprintf /**< Default snprintf macro to use, can be undefined */
+//#define MBEDTLS_PLATFORM_VSNPRINTF_MACRO vsnprintf /**< Default vsnprintf macro to use, can be undefined */
+//#define MBEDTLS_PLATFORM_NV_SEED_READ_MACRO mbedtls_platform_std_nv_seed_read /**< Default nv_seed_read function to use, can be undefined */
+//#define MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO mbedtls_platform_std_nv_seed_write /**< Default nv_seed_write function to use, can be undefined */
+//#define MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO int64_t //#define MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO int64_t /**< Default milliseconds time macro to use, can be undefined. MBEDTLS_HAVE_TIME must be enabled. It must be signed, and at least 64 bits. If it is changed from the default, MBEDTLS_PRINTF_MS_TIME must be updated to match.*/
+//#define MBEDTLS_PRINTF_MS_TIME PRId64 /**< Default fmt for printf. That's avoid compiler warning if mbedtls_ms_time_t is redefined */
+
+/** \def MBEDTLS_CHECK_RETURN
+ *
+ * This macro is used at the beginning of the declaration of a function
+ * to indicate that its return value should be checked. It should
+ * instruct the compiler to emit a warning or an error if the function
+ * is called without checking its return value.
+ *
+ * There is a default implementation for popular compilers in platform_util.h.
+ * You can override the default implementation by defining your own here.
+ *
+ * If the implementation here is empty, this will effectively disable the
+ * checking of functions' return values.
+ */
+//#define MBEDTLS_CHECK_RETURN __attribute__((__warn_unused_result__))
+
+/** \def MBEDTLS_IGNORE_RETURN
+ *
+ * This macro requires one argument, which should be a C function call.
+ * If that function call would cause a #MBEDTLS_CHECK_RETURN warning, this
+ * warning is suppressed.
+ */
+//#define MBEDTLS_IGNORE_RETURN( result ) ((void) !(result))
+
+/* PSA options */
+/**
+ * Use HMAC_DRBG with the specified hash algorithm for HMAC_DRBG for the
+ * PSA crypto subsystem.
+ *
+ * If this option is unset:
+ * - If CTR_DRBG is available, the PSA subsystem uses it rather than HMAC_DRBG.
+ * - Otherwise, the PSA subsystem uses HMAC_DRBG with either
+ * #MBEDTLS_MD_SHA512 or #MBEDTLS_MD_SHA256 based on availability and
+ * on unspecified heuristics.
+ */
+//#define MBEDTLS_PSA_HMAC_DRBG_MD_TYPE MBEDTLS_MD_SHA256
+
+/** \def MBEDTLS_PSA_KEY_SLOT_COUNT
+ * Restrict the PSA library to supporting a maximum amount of simultaneously
+ * loaded keys. A loaded key is a key stored by the PSA Crypto core as a
+ * volatile key, or a persistent key which is loaded temporarily by the
+ * library as part of a crypto operation in flight.
+ *
+ * If this option is unset, the library will fall back to a default value of
+ * 32 keys.
+ */
+//#define MBEDTLS_PSA_KEY_SLOT_COUNT 32
+
+/* RSA OPTIONS */
+//#define MBEDTLS_RSA_GEN_KEY_MIN_BITS 1024 /**< Minimum RSA key size that can be generated in bits (Minimum possible value is 128 bits) */
+
+/* SSL Cache options */
+//#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT 86400 /**< 1 day */
+//#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /**< Maximum entries in cache */
+
+/* SSL options */
+
+/** \def MBEDTLS_SSL_IN_CONTENT_LEN
+ *
+ * Maximum length (in bytes) of incoming plaintext fragments.
+ *
+ * This determines the size of the incoming TLS I/O buffer in such a way
+ * that it is capable of holding the specified amount of plaintext data,
+ * regardless of the protection mechanism used.
+ *
+ * \note When using a value less than the default of 16KB on the client, it is
+ * recommended to use the Maximum Fragment Length (MFL) extension to
+ * inform the server about this limitation. On the server, there
+ * is no supported, standardized way of informing the client about
+ * restriction on the maximum size of incoming messages, and unless
+ * the limitation has been communicated by other means, it is recommended
+ * to only change the outgoing buffer size #MBEDTLS_SSL_OUT_CONTENT_LEN
+ * while keeping the default value of 16KB for the incoming buffer.
+ *
+ * Uncomment to set the maximum plaintext size of the incoming I/O buffer.
+ */
+//#define MBEDTLS_SSL_IN_CONTENT_LEN 16384
+
+/** \def MBEDTLS_SSL_CID_IN_LEN_MAX
+ *
+ * The maximum length of CIDs used for incoming DTLS messages.
+ *
+ */
+//#define MBEDTLS_SSL_CID_IN_LEN_MAX 32
+
+/** \def MBEDTLS_SSL_CID_OUT_LEN_MAX
+ *
+ * The maximum length of CIDs used for outgoing DTLS messages.
+ *
+ */
+//#define MBEDTLS_SSL_CID_OUT_LEN_MAX 32
+
+/** \def MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY
+ *
+ * This option controls the use of record plaintext padding
+ * in TLS 1.3 and when using the Connection ID extension in DTLS 1.2.
+ *
+ * The padding will always be chosen so that the length of the
+ * padded plaintext is a multiple of the value of this option.
+ *
+ * Note: A value of \c 1 means that no padding will be used
+ * for outgoing records.
+ *
+ * Note: On systems lacking division instructions,
+ * a power of two should be preferred.
+ */
+//#define MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY 16
+
+/** \def MBEDTLS_SSL_OUT_CONTENT_LEN
+ *
+ * Maximum length (in bytes) of outgoing plaintext fragments.
+ *
+ * This determines the size of the outgoing TLS I/O buffer in such a way
+ * that it is capable of holding the specified amount of plaintext data,
+ * regardless of the protection mechanism used.
+ *
+ * It is possible to save RAM by setting a smaller outward buffer, while keeping
+ * the default inward 16384 byte buffer to conform to the TLS specification.
+ *
+ * The minimum required outward buffer size is determined by the handshake
+ * protocol's usage. Handshaking will fail if the outward buffer is too small.
+ * The specific size requirement depends on the configured ciphers and any
+ * certificate data which is sent during the handshake.
+ *
+ * Uncomment to set the maximum plaintext size of the outgoing I/O buffer.
+ */
+//#define MBEDTLS_SSL_OUT_CONTENT_LEN 16384
+
+/** \def MBEDTLS_SSL_DTLS_MAX_BUFFERING
+ *
+ * Maximum number of heap-allocated bytes for the purpose of
+ * DTLS handshake message reassembly and future message buffering.
+ *
+ * This should be at least 9/8 * MBEDTLS_SSL_IN_CONTENT_LEN
+ * to account for a reassembled handshake message of maximum size,
+ * together with its reassembly bitmap.
+ *
+ * A value of 2 * MBEDTLS_SSL_IN_CONTENT_LEN (32768 by default)
+ * should be sufficient for all practical situations as it allows
+ * to reassembly a large handshake message (such as a certificate)
+ * while buffering multiple smaller handshake messages.
+ *
+ */
+//#define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768
+
+//#define MBEDTLS_PSK_MAX_LEN 32 /**< Max size of TLS pre-shared keys, in bytes (default 256 or 384 bits) */
+//#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */
+
+/**
+ * Complete list of ciphersuites to use, in order of preference.
+ *
+ * \warning No dependency checking is done on that field! This option can only
+ * be used to restrict the set of available ciphersuites. It is your
+ * responsibility to make sure the needed modules are active.
+ *
+ * Use this to save a few hundred bytes of ROM (default ordering of all
+ * available ciphersuites) and a few to a few hundred bytes of RAM.
+ *
+ * The value below is only an example, not the default.
+ */
+//#define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384,MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256
+
+/**
+ * \def MBEDTLS_SSL_MAX_EARLY_DATA_SIZE
+ *
+ * The default maximum amount of 0-RTT data. See the documentation of
+ * \c mbedtls_ssl_tls13_conf_max_early_data_size() for more information.
+ *
+ * It must be positive and smaller than UINT32_MAX.
+ *
+ * If MBEDTLS_SSL_EARLY_DATA is not defined, this default value does not
+ * have any impact on the build.
+ *
+ * This feature is experimental, not completed and thus not ready for
+ * production.
+ *
+ */
+//#define MBEDTLS_SSL_MAX_EARLY_DATA_SIZE 1024
+
+/**
+ * \def MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE
+ *
+ * Maximum time difference in milliseconds tolerated between the age of a
+ * ticket from the server and client point of view.
+ * From the client point of view, the age of a ticket is the time difference
+ * between the time when the client proposes to the server to use the ticket
+ * (time of writing of the Pre-Shared Key Extension including the ticket) and
+ * the time the client received the ticket from the server.
+ * From the server point of view, the age of a ticket is the time difference
+ * between the time when the server receives a proposition from the client
+ * to use the ticket and the time when the ticket was created by the server.
+ * The server age is expected to be always greater than the client one and
+ * MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE defines the
+ * maximum difference tolerated for the server to accept the ticket.
+ * This is not used in TLS 1.2.
+ *
+ */
+//#define MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE 6000
+
+/**
+ * \def MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH
+ *
+ * Size in bytes of a ticket nonce. This is not used in TLS 1.2.
+ *
+ * This must be less than 256.
+ */
+//#define MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH 32
+
+/**
+ * \def MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS
+ *
+ * Default number of NewSessionTicket messages to be sent by a TLS 1.3 server
+ * after handshake completion. This is not used in TLS 1.2 and relevant only if
+ * the MBEDTLS_SSL_SESSION_TICKETS option is enabled.
+ *
+ */
+//#define MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS 1
+
+/* X509 options */
+//#define MBEDTLS_X509_MAX_INTERMEDIATE_CA 8 /**< Maximum number of intermediate CAs in a verification chain. */
+//#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512 /**< Maximum length of a path/filename string in bytes including the null terminator character ('\0'). */
+
+/** \} name SECTION: Module configuration options */
diff --git a/include/mbedtls/md.h b/include/mbedtls/md.h
new file mode 100644
index 0000000..ff7b133
--- /dev/null
+++ b/include/mbedtls/md.h
@@ -0,0 +1,640 @@
+/**
+ * \file md.h
+ *
+ * \brief This file contains the generic functions for message-digest
+ * (hashing) and HMAC.
+ *
+ * \author Adriaan de Jong <dejong@fox-it.com>
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_MD_H
+#define MBEDTLS_MD_H
+#include "mbedtls/private_access.h"
+
+#include <stddef.h>
+
+#include "mbedtls/build_info.h"
+#include "mbedtls/platform_util.h"
+
+#if defined(MBEDTLS_MD_LIGHT)
+
+/*
+ * - MBEDTLS_MD_CAN_xxx is defined if the md module can perform xxx.
+ * - MBEDTLS_MD_xxx_VIA_PSA is defined if the md module may perform xxx via PSA
+ * (see below).
+ * - MBEDTLS_MD_SOME_PSA is defined if at least one algorithm may be performed
+ * via PSA (see below).
+ * - MBEDTLS_MD_SOME_LEGACY is defined if at least one algorithm may be performed
+ * via a direct legacy call (see below).
+ *
+ * The md module performs an algorithm via PSA if there is a PSA hash
+ * accelerator and the PSA driver subsytem is initialized at the time the
+ * operation is started, and makes a direct legacy call otherwise.
+ */
+
+/* PSA accelerated implementations */
+#if defined(MBEDTLS_PSA_CRYPTO_C)
+#if defined(MBEDTLS_PSA_ACCEL_ALG_MD5)
+#define MBEDTLS_MD_CAN_MD5
+#define MBEDTLS_MD_MD5_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#if defined(MBEDTLS_PSA_ACCEL_ALG_SHA_1)
+#define MBEDTLS_MD_CAN_SHA1
+#define MBEDTLS_MD_SHA1_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#if defined(MBEDTLS_PSA_ACCEL_ALG_SHA_224)
+#define MBEDTLS_MD_CAN_SHA224
+#define MBEDTLS_MD_SHA224_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#if defined(MBEDTLS_PSA_ACCEL_ALG_SHA_256)
+#define MBEDTLS_MD_CAN_SHA256
+#define MBEDTLS_MD_SHA256_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#if defined(MBEDTLS_PSA_ACCEL_ALG_SHA_384)
+#define MBEDTLS_MD_CAN_SHA384
+#define MBEDTLS_MD_SHA384_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#if defined(MBEDTLS_PSA_ACCEL_ALG_SHA_512)
+#define MBEDTLS_MD_CAN_SHA512
+#define MBEDTLS_MD_SHA512_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#if defined(MBEDTLS_PSA_ACCEL_ALG_RIPEMD160)
+#define MBEDTLS_MD_CAN_RIPEMD160
+#define MBEDTLS_MD_RIPEMD160_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#if defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_224)
+#define MBEDTLS_MD_CAN_SHA3_224
+#define MBEDTLS_MD_SHA3_224_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#if defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_256)
+#define MBEDTLS_MD_CAN_SHA3_256
+#define MBEDTLS_MD_SHA3_256_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#if defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_384)
+#define MBEDTLS_MD_CAN_SHA3_384
+#define MBEDTLS_MD_SHA3_384_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#if defined(MBEDTLS_PSA_ACCEL_ALG_SHA3_512)
+#define MBEDTLS_MD_CAN_SHA3_512
+#define MBEDTLS_MD_SHA3_512_VIA_PSA
+#define MBEDTLS_MD_SOME_PSA
+#endif
+#endif /* MBEDTLS_PSA_CRYPTO_C */
+
+/* Built-in implementations */
+#if defined(MBEDTLS_MD5_C)
+#define MBEDTLS_MD_CAN_MD5
+#define MBEDTLS_MD_SOME_LEGACY
+#endif
+#if defined(MBEDTLS_SHA1_C)
+#define MBEDTLS_MD_CAN_SHA1
+#define MBEDTLS_MD_SOME_LEGACY
+#endif
+#if defined(MBEDTLS_SHA224_C)
+#define MBEDTLS_MD_CAN_SHA224
+#define MBEDTLS_MD_SOME_LEGACY
+#endif
+#if defined(MBEDTLS_SHA256_C)
+#define MBEDTLS_MD_CAN_SHA256
+#define MBEDTLS_MD_SOME_LEGACY
+#endif
+#if defined(MBEDTLS_SHA384_C)
+#define MBEDTLS_MD_CAN_SHA384
+#define MBEDTLS_MD_SOME_LEGACY
+#endif
+#if defined(MBEDTLS_SHA512_C)
+#define MBEDTLS_MD_CAN_SHA512
+#define MBEDTLS_MD_SOME_LEGACY
+#endif
+#if defined(MBEDTLS_SHA3_C)
+#define MBEDTLS_MD_CAN_SHA3_224
+#define MBEDTLS_MD_CAN_SHA3_256
+#define MBEDTLS_MD_CAN_SHA3_384
+#define MBEDTLS_MD_CAN_SHA3_512
+#define MBEDTLS_MD_SOME_LEGACY
+#endif
+#if defined(MBEDTLS_RIPEMD160_C)
+#define MBEDTLS_MD_CAN_RIPEMD160
+#define MBEDTLS_MD_SOME_LEGACY
+#endif
+
+#endif /* MBEDTLS_MD_LIGHT */
+
+/** The selected feature is not available. */
+#define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE -0x5080
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_MD_BAD_INPUT_DATA -0x5100
+/** Failed to allocate memory. */
+#define MBEDTLS_ERR_MD_ALLOC_FAILED -0x5180
+/** Opening or reading of file failed. */
+#define MBEDTLS_ERR_MD_FILE_IO_ERROR -0x5200
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Supported message digests.
+ *
+ * \warning MD5 and SHA-1 are considered weak message digests and
+ * their use constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+/* Note: these are aligned with the definitions of PSA_ALG_ macros for hashes,
+ * in order to enable an efficient implementation of conversion functions.
+ * This is tested by md_to_from_psa() in test_suite_md. */
+typedef enum {
+ MBEDTLS_MD_NONE=0, /**< None. */
+ MBEDTLS_MD_MD5=0x03, /**< The MD5 message digest. */
+ MBEDTLS_MD_RIPEMD160=0x04, /**< The RIPEMD-160 message digest. */
+ MBEDTLS_MD_SHA1=0x05, /**< The SHA-1 message digest. */
+ MBEDTLS_MD_SHA224=0x08, /**< The SHA-224 message digest. */
+ MBEDTLS_MD_SHA256=0x09, /**< The SHA-256 message digest. */
+ MBEDTLS_MD_SHA384=0x0a, /**< The SHA-384 message digest. */
+ MBEDTLS_MD_SHA512=0x0b, /**< The SHA-512 message digest. */
+ MBEDTLS_MD_SHA3_224=0x10, /**< The SHA3-224 message digest. */
+ MBEDTLS_MD_SHA3_256=0x11, /**< The SHA3-256 message digest. */
+ MBEDTLS_MD_SHA3_384=0x12, /**< The SHA3-384 message digest. */
+ MBEDTLS_MD_SHA3_512=0x13, /**< The SHA3-512 message digest. */
+} mbedtls_md_type_t;
+
+/* Note: this should always be >= PSA_HASH_MAX_SIZE
+ * in all builds with both CRYPTO_C and MD_LIGHT.
+ *
+ * This is to make things easier for modules such as TLS that may define a
+ * buffer size using MD_MAX_SIZE in a part of the code that's common to PSA
+ * and legacy, then assume the buffer's size is PSA_HASH_MAX_SIZE in another
+ * part of the code based on PSA.
+ */
+#if defined(MBEDTLS_MD_CAN_SHA512) || defined(MBEDTLS_MD_CAN_SHA3_512)
+#define MBEDTLS_MD_MAX_SIZE 64 /* longest known is SHA512 */
+#elif defined(MBEDTLS_MD_CAN_SHA384) || defined(MBEDTLS_MD_CAN_SHA3_384)
+#define MBEDTLS_MD_MAX_SIZE 48 /* longest known is SHA384 */
+#elif defined(MBEDTLS_MD_CAN_SHA256) || defined(MBEDTLS_MD_CAN_SHA3_256)
+#define MBEDTLS_MD_MAX_SIZE 32 /* longest known is SHA256 */
+#elif defined(MBEDTLS_MD_CAN_SHA224) || defined(MBEDTLS_MD_CAN_SHA3_224)
+#define MBEDTLS_MD_MAX_SIZE 28 /* longest known is SHA224 */
+#else
+#define MBEDTLS_MD_MAX_SIZE 20 /* longest known is SHA1 or RIPE MD-160
+ or smaller (MD5 and earlier) */
+#endif
+
+#if defined(MBEDTLS_MD_CAN_SHA3_224)
+#define MBEDTLS_MD_MAX_BLOCK_SIZE 144 /* the longest known is SHA3-224 */
+#elif defined(MBEDTLS_MD_CAN_SHA3_256)
+#define MBEDTLS_MD_MAX_BLOCK_SIZE 136
+#elif defined(MBEDTLS_MD_CAN_SHA512) || defined(MBEDTLS_MD_CAN_SHA384)
+#define MBEDTLS_MD_MAX_BLOCK_SIZE 128
+#elif defined(MBEDTLS_MD_CAN_SHA3_384)
+#define MBEDTLS_MD_MAX_BLOCK_SIZE 104
+#elif defined(MBEDTLS_MD_CAN_SHA3_512)
+#define MBEDTLS_MD_MAX_BLOCK_SIZE 72
+#else
+#define MBEDTLS_MD_MAX_BLOCK_SIZE 64
+#endif
+
+/**
+ * Opaque struct.
+ *
+ * Constructed using either #mbedtls_md_info_from_string or
+ * #mbedtls_md_info_from_type.
+ *
+ * Fields can be accessed with #mbedtls_md_get_size,
+ * #mbedtls_md_get_type and #mbedtls_md_get_name.
+ */
+/* Defined internally in library/md_wrap.h. */
+typedef struct mbedtls_md_info_t mbedtls_md_info_t;
+
+/**
+ * Used internally to indicate whether a context uses legacy or PSA.
+ *
+ * Internal use only.
+ */
+typedef enum {
+ MBEDTLS_MD_ENGINE_LEGACY = 0,
+ MBEDTLS_MD_ENGINE_PSA,
+} mbedtls_md_engine_t;
+
+/**
+ * The generic message-digest context.
+ */
+typedef struct mbedtls_md_context_t {
+ /** Information about the associated message digest. */
+ const mbedtls_md_info_t *MBEDTLS_PRIVATE(md_info);
+
+#if defined(MBEDTLS_MD_SOME_PSA)
+ /** Are hash operations dispatched to PSA or legacy? */
+ mbedtls_md_engine_t MBEDTLS_PRIVATE(engine);
+#endif
+
+ /** The digest-specific context (legacy) or the PSA operation. */
+ void *MBEDTLS_PRIVATE(md_ctx);
+
+#if defined(MBEDTLS_MD_C)
+ /** The HMAC part of the context. */
+ void *MBEDTLS_PRIVATE(hmac_ctx);
+#endif
+} mbedtls_md_context_t;
+
+/**
+ * \brief This function returns the message-digest information
+ * associated with the given digest type.
+ *
+ * \param md_type The type of digest to search for.
+ *
+ * \return The message-digest information associated with \p md_type.
+ * \return NULL if the associated message-digest information is not found.
+ */
+const mbedtls_md_info_t *mbedtls_md_info_from_type(mbedtls_md_type_t md_type);
+
+/**
+ * \brief This function initializes a message-digest context without
+ * binding it to a particular message-digest algorithm.
+ *
+ * This function should always be called first. It prepares the
+ * context for mbedtls_md_setup() for binding it to a
+ * message-digest algorithm.
+ */
+void mbedtls_md_init(mbedtls_md_context_t *ctx);
+
+/**
+ * \brief This function clears the internal structure of \p ctx and
+ * frees any embedded internal structure, but does not free
+ * \p ctx itself.
+ *
+ * If you have called mbedtls_md_setup() on \p ctx, you must
+ * call mbedtls_md_free() when you are no longer using the
+ * context.
+ * Calling this function if you have previously
+ * called mbedtls_md_init() and nothing else is optional.
+ * You must not call this function if you have not called
+ * mbedtls_md_init().
+ */
+void mbedtls_md_free(mbedtls_md_context_t *ctx);
+
+
+/**
+ * \brief This function selects the message digest algorithm to use,
+ * and allocates internal structures.
+ *
+ * It should be called after mbedtls_md_init() or
+ * mbedtls_md_free(). Makes it necessary to call
+ * mbedtls_md_free() later.
+ *
+ * \param ctx The context to set up.
+ * \param md_info The information structure of the message-digest algorithm
+ * to use.
+ * \param hmac Defines if HMAC is used. 0: HMAC is not used (saves some memory),
+ * or non-zero: HMAC is used with this context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
+ * failure.
+ * \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_setup(mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac);
+
+/**
+ * \brief This function clones the state of a message-digest
+ * context.
+ *
+ * \note You must call mbedtls_md_setup() on \c dst before calling
+ * this function.
+ *
+ * \note The two contexts must have the same type,
+ * for example, both are SHA-256.
+ *
+ * \warning This function clones the message-digest state, not the
+ * HMAC state.
+ *
+ * \param dst The destination context.
+ * \param src The context to be cloned.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification failure.
+ * \return #MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE if both contexts are
+ * not using the same engine. This can be avoided by moving
+ * the call to psa_crypto_init() before the first call to
+ * mbedtls_md_setup().
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_clone(mbedtls_md_context_t *dst,
+ const mbedtls_md_context_t *src);
+
+/**
+ * \brief This function extracts the message-digest size from the
+ * message-digest information structure.
+ *
+ * \param md_info The information structure of the message-digest algorithm
+ * to use.
+ *
+ * \return The size of the message-digest output in Bytes.
+ */
+unsigned char mbedtls_md_get_size(const mbedtls_md_info_t *md_info);
+
+/**
+ * \brief This function gives the message-digest size associated to
+ * message-digest type.
+ *
+ * \param md_type The message-digest type.
+ *
+ * \return The size of the message-digest output in Bytes,
+ * or 0 if the message-digest type is not known.
+ */
+static inline unsigned char mbedtls_md_get_size_from_type(mbedtls_md_type_t md_type)
+{
+ return mbedtls_md_get_size(mbedtls_md_info_from_type(md_type));
+}
+
+/**
+ * \brief This function extracts the message-digest type from the
+ * message-digest information structure.
+ *
+ * \param md_info The information structure of the message-digest algorithm
+ * to use.
+ *
+ * \return The type of the message digest.
+ */
+mbedtls_md_type_t mbedtls_md_get_type(const mbedtls_md_info_t *md_info);
+
+/**
+ * \brief This function starts a message-digest computation.
+ *
+ * You must call this function after setting up the context
+ * with mbedtls_md_setup(), and before passing data with
+ * mbedtls_md_update().
+ *
+ * \param ctx The generic message-digest context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
+ * failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_starts(mbedtls_md_context_t *ctx);
+
+/**
+ * \brief This function feeds an input buffer into an ongoing
+ * message-digest computation.
+ *
+ * You must call mbedtls_md_starts() before calling this
+ * function. You may call this function multiple times.
+ * Afterwards, call mbedtls_md_finish().
+ *
+ * \param ctx The generic message-digest context.
+ * \param input The buffer holding the input data.
+ * \param ilen The length of the input data.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
+ * failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_update(mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen);
+
+/**
+ * \brief This function finishes the digest operation,
+ * and writes the result to the output buffer.
+ *
+ * Call this function after a call to mbedtls_md_starts(),
+ * followed by any number of calls to mbedtls_md_update().
+ * Afterwards, you may either clear the context with
+ * mbedtls_md_free(), or call mbedtls_md_starts() to reuse
+ * the context for another digest operation with the same
+ * algorithm.
+ *
+ * \param ctx The generic message-digest context.
+ * \param output The buffer for the generic message-digest checksum result.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
+ * failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_finish(mbedtls_md_context_t *ctx, unsigned char *output);
+
+/**
+ * \brief This function calculates the message-digest of a buffer,
+ * with respect to a configurable message-digest algorithm
+ * in a single call.
+ *
+ * The result is calculated as
+ * Output = message_digest(input buffer).
+ *
+ * \param md_info The information structure of the message-digest algorithm
+ * to use.
+ * \param input The buffer holding the data.
+ * \param ilen The length of the input data.
+ * \param output The generic message-digest checksum result.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
+ * failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md(const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen,
+ unsigned char *output);
+
+/**
+ * \brief This function returns the list of digests supported by the
+ * generic digest module.
+ *
+ * \note The list starts with the strongest available hashes.
+ *
+ * \return A statically allocated array of digests. Each element
+ * in the returned list is an integer belonging to the
+ * message-digest enumeration #mbedtls_md_type_t.
+ * The last entry is 0.
+ */
+const int *mbedtls_md_list(void);
+
+/**
+ * \brief This function returns the message-digest information
+ * associated with the given digest name.
+ *
+ * \param md_name The name of the digest to search for.
+ *
+ * \return The message-digest information associated with \p md_name.
+ * \return NULL if the associated message-digest information is not found.
+ */
+const mbedtls_md_info_t *mbedtls_md_info_from_string(const char *md_name);
+
+/**
+ * \brief This function returns the name of the message digest for
+ * the message-digest information structure given.
+ *
+ * \param md_info The information structure of the message-digest algorithm
+ * to use.
+ *
+ * \return The name of the message digest.
+ */
+const char *mbedtls_md_get_name(const mbedtls_md_info_t *md_info);
+
+/**
+ * \brief This function returns the message-digest information
+ * from the given context.
+ *
+ * \param ctx The context from which to extract the information.
+ * This must be initialized (or \c NULL).
+ *
+ * \return The message-digest information associated with \p ctx.
+ * \return \c NULL if \p ctx is \c NULL.
+ */
+const mbedtls_md_info_t *mbedtls_md_info_from_ctx(
+ const mbedtls_md_context_t *ctx);
+
+#if defined(MBEDTLS_FS_IO)
+/**
+ * \brief This function calculates the message-digest checksum
+ * result of the contents of the provided file.
+ *
+ * The result is calculated as
+ * Output = message_digest(file contents).
+ *
+ * \param md_info The information structure of the message-digest algorithm
+ * to use.
+ * \param path The input file name.
+ * \param output The generic message-digest checksum result.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_FILE_IO_ERROR on an I/O error accessing
+ * the file pointed by \p path.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info was NULL.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_file(const mbedtls_md_info_t *md_info, const char *path,
+ unsigned char *output);
+#endif /* MBEDTLS_FS_IO */
+
+/**
+ * \brief This function sets the HMAC key and prepares to
+ * authenticate a new message.
+ *
+ * Call this function after mbedtls_md_setup(), to use
+ * the MD context for an HMAC calculation, then call
+ * mbedtls_md_hmac_update() to provide the input data, and
+ * mbedtls_md_hmac_finish() to get the HMAC value.
+ *
+ * \param ctx The message digest context containing an embedded HMAC
+ * context.
+ * \param key The HMAC secret key.
+ * \param keylen The length of the HMAC key in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
+ * failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_hmac_starts(mbedtls_md_context_t *ctx, const unsigned char *key,
+ size_t keylen);
+
+/**
+ * \brief This function feeds an input buffer into an ongoing HMAC
+ * computation.
+ *
+ * Call mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset()
+ * before calling this function.
+ * You may call this function multiple times to pass the
+ * input piecewise.
+ * Afterwards, call mbedtls_md_hmac_finish().
+ *
+ * \param ctx The message digest context containing an embedded HMAC
+ * context.
+ * \param input The buffer holding the input data.
+ * \param ilen The length of the input data.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
+ * failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_hmac_update(mbedtls_md_context_t *ctx, const unsigned char *input,
+ size_t ilen);
+
+/**
+ * \brief This function finishes the HMAC operation, and writes
+ * the result to the output buffer.
+ *
+ * Call this function after mbedtls_md_hmac_starts() and
+ * mbedtls_md_hmac_update() to get the HMAC value. Afterwards
+ * you may either call mbedtls_md_free() to clear the context,
+ * or call mbedtls_md_hmac_reset() to reuse the context with
+ * the same HMAC key.
+ *
+ * \param ctx The message digest context containing an embedded HMAC
+ * context.
+ * \param output The generic HMAC checksum result.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
+ * failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_hmac_finish(mbedtls_md_context_t *ctx, unsigned char *output);
+
+/**
+ * \brief This function prepares to authenticate a new message with
+ * the same key as the previous HMAC operation.
+ *
+ * You may call this function after mbedtls_md_hmac_finish().
+ * Afterwards call mbedtls_md_hmac_update() to pass the new
+ * input.
+ *
+ * \param ctx The message digest context containing an embedded HMAC
+ * context.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
+ * failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_hmac_reset(mbedtls_md_context_t *ctx);
+
+/**
+ * \brief This function calculates the full generic HMAC
+ * on the input buffer with the provided key.
+ *
+ * The function allocates the context, performs the
+ * calculation, and frees the context.
+ *
+ * The HMAC result is calculated as
+ * output = generic HMAC(hmac key, input buffer).
+ *
+ * \param md_info The information structure of the message-digest algorithm
+ * to use.
+ * \param key The HMAC secret key.
+ * \param keylen The length of the HMAC secret key in Bytes.
+ * \param input The buffer holding the input data.
+ * \param ilen The length of the input data.
+ * \param output The generic HMAC result.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification
+ * failure.
+ */
+MBEDTLS_CHECK_RETURN_TYPICAL
+int mbedtls_md_hmac(const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen,
+ const unsigned char *input, size_t ilen,
+ unsigned char *output);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_MD_H */
diff --git a/include/mbedtls/md5.h b/include/mbedtls/md5.h
new file mode 100644
index 0000000..6bf0754
--- /dev/null
+++ b/include/mbedtls/md5.h
@@ -0,0 +1,190 @@
+/**
+ * \file md5.h
+ *
+ * \brief MD5 message digest algorithm (hash function)
+ *
+ * \warning MD5 is considered a weak message digest and its use constitutes a
+ * security risk. We recommend considering stronger message
+ * digests instead.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_MD5_H
+#define MBEDTLS_MD5_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_MD5_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief MD5 context structure
+ *
+ * \warning MD5 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+typedef struct mbedtls_md5_context {
+ uint32_t MBEDTLS_PRIVATE(total)[2]; /*!< number of bytes processed */
+ uint32_t MBEDTLS_PRIVATE(state)[4]; /*!< intermediate digest state */
+ unsigned char MBEDTLS_PRIVATE(buffer)[64]; /*!< data block being processed */
+}
+mbedtls_md5_context;
+
+#else /* MBEDTLS_MD5_ALT */
+#include "md5_alt.h"
+#endif /* MBEDTLS_MD5_ALT */
+
+/**
+ * \brief Initialize MD5 context
+ *
+ * \param ctx MD5 context to be initialized
+ *
+ * \warning MD5 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+void mbedtls_md5_init(mbedtls_md5_context *ctx);
+
+/**
+ * \brief Clear MD5 context
+ *
+ * \param ctx MD5 context to be cleared
+ *
+ * \warning MD5 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+void mbedtls_md5_free(mbedtls_md5_context *ctx);
+
+/**
+ * \brief Clone (the state of) an MD5 context
+ *
+ * \param dst The destination context
+ * \param src The context to be cloned
+ *
+ * \warning MD5 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+void mbedtls_md5_clone(mbedtls_md5_context *dst,
+ const mbedtls_md5_context *src);
+
+/**
+ * \brief MD5 context setup
+ *
+ * \param ctx context to be initialized
+ *
+ * \return 0 if successful
+ *
+ * \warning MD5 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+int mbedtls_md5_starts(mbedtls_md5_context *ctx);
+
+/**
+ * \brief MD5 process buffer
+ *
+ * \param ctx MD5 context
+ * \param input buffer holding the data
+ * \param ilen length of the input data
+ *
+ * \return 0 if successful
+ *
+ * \warning MD5 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+int mbedtls_md5_update(mbedtls_md5_context *ctx,
+ const unsigned char *input,
+ size_t ilen);
+
+/**
+ * \brief MD5 final digest
+ *
+ * \param ctx MD5 context
+ * \param output MD5 checksum result
+ *
+ * \return 0 if successful
+ *
+ * \warning MD5 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+int mbedtls_md5_finish(mbedtls_md5_context *ctx,
+ unsigned char output[16]);
+
+/**
+ * \brief MD5 process data block (internal use only)
+ *
+ * \param ctx MD5 context
+ * \param data buffer holding one block of data
+ *
+ * \return 0 if successful
+ *
+ * \warning MD5 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+int mbedtls_internal_md5_process(mbedtls_md5_context *ctx,
+ const unsigned char data[64]);
+
+/**
+ * \brief Output = MD5( input buffer )
+ *
+ * \param input buffer holding the data
+ * \param ilen length of the input data
+ * \param output MD5 checksum result
+ *
+ * \return 0 if successful
+ *
+ * \warning MD5 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+int mbedtls_md5(const unsigned char *input,
+ size_t ilen,
+ unsigned char output[16]);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if the test failed
+ *
+ * \warning MD5 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+int mbedtls_md5_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* mbedtls_md5.h */
diff --git a/include/mbedtls/memory_buffer_alloc.h b/include/mbedtls/memory_buffer_alloc.h
new file mode 100644
index 0000000..b527d9b
--- /dev/null
+++ b/include/mbedtls/memory_buffer_alloc.h
@@ -0,0 +1,142 @@
+/**
+ * \file memory_buffer_alloc.h
+ *
+ * \brief Buffer-based memory allocator
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_MEMORY_BUFFER_ALLOC_H
+#define MBEDTLS_MEMORY_BUFFER_ALLOC_H
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+
+/**
+ * \name SECTION: Module settings
+ *
+ * The configuration options you can set for this module are in this section.
+ * Either change them in mbedtls_config.h or define them on the compiler command line.
+ * \{
+ */
+
+#if !defined(MBEDTLS_MEMORY_ALIGN_MULTIPLE)
+#define MBEDTLS_MEMORY_ALIGN_MULTIPLE 4 /**< Align on multiples of this value */
+#endif
+
+/** \} name SECTION: Module settings */
+
+#define MBEDTLS_MEMORY_VERIFY_NONE 0
+#define MBEDTLS_MEMORY_VERIFY_ALLOC (1 << 0)
+#define MBEDTLS_MEMORY_VERIFY_FREE (1 << 1)
+#define MBEDTLS_MEMORY_VERIFY_ALWAYS (MBEDTLS_MEMORY_VERIFY_ALLOC | \
+ MBEDTLS_MEMORY_VERIFY_FREE)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Initialize use of stack-based memory allocator.
+ * The stack-based allocator does memory management inside the
+ * presented buffer and does not call calloc() and free().
+ * It sets the global mbedtls_calloc() and mbedtls_free() pointers
+ * to its own functions.
+ * (Provided mbedtls_calloc() and mbedtls_free() are thread-safe if
+ * MBEDTLS_THREADING_C is defined)
+ *
+ * \note This code is not optimized and provides a straight-forward
+ * implementation of a stack-based memory allocator.
+ *
+ * \param buf buffer to use as heap
+ * \param len size of the buffer
+ */
+void mbedtls_memory_buffer_alloc_init(unsigned char *buf, size_t len);
+
+/**
+ * \brief Free the mutex for thread-safety and clear remaining memory
+ */
+void mbedtls_memory_buffer_alloc_free(void);
+
+/**
+ * \brief Determine when the allocator should automatically verify the state
+ * of the entire chain of headers / meta-data.
+ * (Default: MBEDTLS_MEMORY_VERIFY_NONE)
+ *
+ * \param verify One of MBEDTLS_MEMORY_VERIFY_NONE, MBEDTLS_MEMORY_VERIFY_ALLOC,
+ * MBEDTLS_MEMORY_VERIFY_FREE or MBEDTLS_MEMORY_VERIFY_ALWAYS
+ */
+void mbedtls_memory_buffer_set_verify(int verify);
+
+#if defined(MBEDTLS_MEMORY_DEBUG)
+/**
+ * \brief Print out the status of the allocated memory (primarily for use
+ * after a program should have de-allocated all memory)
+ * Prints out a list of 'still allocated' blocks and their stack
+ * trace if MBEDTLS_MEMORY_BACKTRACE is defined.
+ */
+void mbedtls_memory_buffer_alloc_status(void);
+
+/**
+ * \brief Get the number of alloc/free so far.
+ *
+ * \param alloc_count Number of allocations.
+ * \param free_count Number of frees.
+ */
+void mbedtls_memory_buffer_alloc_count_get(size_t *alloc_count, size_t *free_count);
+
+/**
+ * \brief Get the peak heap usage so far
+ *
+ * \param max_used Peak number of bytes in use or committed. This
+ * includes bytes in allocated blocks too small to split
+ * into smaller blocks but larger than the requested size.
+ * \param max_blocks Peak number of blocks in use, including free and used
+ */
+void mbedtls_memory_buffer_alloc_max_get(size_t *max_used, size_t *max_blocks);
+
+/**
+ * \brief Reset peak statistics
+ */
+void mbedtls_memory_buffer_alloc_max_reset(void);
+
+/**
+ * \brief Get the current heap usage
+ *
+ * \param cur_used Current number of bytes in use or committed. This
+ * includes bytes in allocated blocks too small to split
+ * into smaller blocks but larger than the requested size.
+ * \param cur_blocks Current number of blocks in use, including free and used
+ */
+void mbedtls_memory_buffer_alloc_cur_get(size_t *cur_used, size_t *cur_blocks);
+#endif /* MBEDTLS_MEMORY_DEBUG */
+
+/**
+ * \brief Verifies that all headers in the memory buffer are correct
+ * and contain sane values. Helps debug buffer-overflow errors.
+ *
+ * Prints out first failure if MBEDTLS_MEMORY_DEBUG is defined.
+ * Prints out full header information if MBEDTLS_MEMORY_DEBUG
+ * is defined. (Includes stack trace information for each block if
+ * MBEDTLS_MEMORY_BACKTRACE is defined as well).
+ *
+ * \return 0 if verified, 1 otherwise
+ */
+int mbedtls_memory_buffer_alloc_verify(void);
+
+#if defined(MBEDTLS_SELF_TEST)
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if a test failed
+ */
+int mbedtls_memory_buffer_alloc_self_test(int verbose);
+#endif
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* memory_buffer_alloc.h */
diff --git a/include/mbedtls/net_sockets.h b/include/mbedtls/net_sockets.h
new file mode 100644
index 0000000..026f627
--- /dev/null
+++ b/include/mbedtls/net_sockets.h
@@ -0,0 +1,299 @@
+/**
+ * \file net_sockets.h
+ *
+ * \brief Network sockets abstraction layer to integrate Mbed TLS into a
+ * BSD-style sockets API.
+ *
+ * The network sockets module provides an example integration of the
+ * Mbed TLS library into a BSD sockets implementation. The module is
+ * intended to be an example of how Mbed TLS can be integrated into a
+ * networking stack, as well as to be Mbed TLS's network integration
+ * for its supported platforms.
+ *
+ * The module is intended only to be used with the Mbed TLS library and
+ * is not intended to be used by third party application software
+ * directly.
+ *
+ * The supported platforms are as follows:
+ * * Microsoft Windows and Windows CE
+ * * POSIX/Unix platforms including Linux, OS X
+ *
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_NET_SOCKETS_H
+#define MBEDTLS_NET_SOCKETS_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/ssl.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+/** Failed to open a socket. */
+#define MBEDTLS_ERR_NET_SOCKET_FAILED -0x0042
+/** The connection to the given server / port failed. */
+#define MBEDTLS_ERR_NET_CONNECT_FAILED -0x0044
+/** Binding of the socket failed. */
+#define MBEDTLS_ERR_NET_BIND_FAILED -0x0046
+/** Could not listen on the socket. */
+#define MBEDTLS_ERR_NET_LISTEN_FAILED -0x0048
+/** Could not accept the incoming connection. */
+#define MBEDTLS_ERR_NET_ACCEPT_FAILED -0x004A
+/** Reading information from the socket failed. */
+#define MBEDTLS_ERR_NET_RECV_FAILED -0x004C
+/** Sending information through the socket failed. */
+#define MBEDTLS_ERR_NET_SEND_FAILED -0x004E
+/** Connection was reset by peer. */
+#define MBEDTLS_ERR_NET_CONN_RESET -0x0050
+/** Failed to get an IP address for the given hostname. */
+#define MBEDTLS_ERR_NET_UNKNOWN_HOST -0x0052
+/** Buffer is too small to hold the data. */
+#define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL -0x0043
+/** The context is invalid, eg because it was free()ed. */
+#define MBEDTLS_ERR_NET_INVALID_CONTEXT -0x0045
+/** Polling the net context failed. */
+#define MBEDTLS_ERR_NET_POLL_FAILED -0x0047
+/** Input invalid. */
+#define MBEDTLS_ERR_NET_BAD_INPUT_DATA -0x0049
+
+#define MBEDTLS_NET_LISTEN_BACKLOG 10 /**< The backlog that listen() should use. */
+
+#define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */
+#define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */
+
+#define MBEDTLS_NET_POLL_READ 1 /**< Used in \c mbedtls_net_poll to check for pending data */
+#define MBEDTLS_NET_POLL_WRITE 2 /**< Used in \c mbedtls_net_poll to check if write possible */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Wrapper type for sockets.
+ *
+ * Currently backed by just a file descriptor, but might be more in the future
+ * (eg two file descriptors for combined IPv4 + IPv6 support, or additional
+ * structures for hand-made UDP demultiplexing).
+ */
+typedef struct mbedtls_net_context {
+ /** The underlying file descriptor.
+ *
+ * This field is only guaranteed to be present on POSIX/Unix-like platforms.
+ * On other platforms, it may have a different type, have a different
+ * meaning, or be absent altogether.
+ */
+ int fd;
+}
+mbedtls_net_context;
+
+/**
+ * \brief Initialize a context
+ * Just makes the context ready to be used or freed safely.
+ *
+ * \param ctx Context to initialize
+ */
+void mbedtls_net_init(mbedtls_net_context *ctx);
+
+/**
+ * \brief Initiate a connection with host:port in the given protocol
+ *
+ * \param ctx Socket to use
+ * \param host Host to connect to
+ * \param port Port to connect to
+ * \param proto Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP
+ *
+ * \return 0 if successful, or one of:
+ * MBEDTLS_ERR_NET_SOCKET_FAILED,
+ * MBEDTLS_ERR_NET_UNKNOWN_HOST,
+ * MBEDTLS_ERR_NET_CONNECT_FAILED
+ *
+ * \note Sets the socket in connected mode even with UDP.
+ */
+int mbedtls_net_connect(mbedtls_net_context *ctx, const char *host, const char *port, int proto);
+
+/**
+ * \brief Create a receiving socket on bind_ip:port in the chosen
+ * protocol. If bind_ip == NULL, all interfaces are bound.
+ *
+ * \param ctx Socket to use
+ * \param bind_ip IP to bind to, can be NULL
+ * \param port Port number to use
+ * \param proto Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP
+ *
+ * \return 0 if successful, or one of:
+ * MBEDTLS_ERR_NET_SOCKET_FAILED,
+ * MBEDTLS_ERR_NET_UNKNOWN_HOST,
+ * MBEDTLS_ERR_NET_BIND_FAILED,
+ * MBEDTLS_ERR_NET_LISTEN_FAILED
+ *
+ * \note Regardless of the protocol, opens the sockets and binds it.
+ * In addition, make the socket listening if protocol is TCP.
+ */
+int mbedtls_net_bind(mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto);
+
+/**
+ * \brief Accept a connection from a remote client
+ *
+ * \param bind_ctx Relevant socket
+ * \param client_ctx Will contain the connected client socket
+ * \param client_ip Will contain the client IP address, can be NULL
+ * \param buf_size Size of the client_ip buffer
+ * \param ip_len Will receive the size of the client IP written,
+ * can be NULL if client_ip is null
+ *
+ * \return 0 if successful, or
+ * MBEDTLS_ERR_NET_SOCKET_FAILED,
+ * MBEDTLS_ERR_NET_BIND_FAILED,
+ * MBEDTLS_ERR_NET_ACCEPT_FAILED, or
+ * MBEDTLS_ERR_NET_BUFFER_TOO_SMALL if buf_size is too small,
+ * MBEDTLS_ERR_SSL_WANT_READ if bind_fd was set to
+ * non-blocking and accept() would block.
+ */
+int mbedtls_net_accept(mbedtls_net_context *bind_ctx,
+ mbedtls_net_context *client_ctx,
+ void *client_ip, size_t buf_size, size_t *ip_len);
+
+/**
+ * \brief Check and wait for the context to be ready for read/write
+ *
+ * \note The current implementation of this function uses
+ * select() and returns an error if the file descriptor
+ * is \c FD_SETSIZE or greater.
+ *
+ * \param ctx Socket to check
+ * \param rw Bitflag composed of MBEDTLS_NET_POLL_READ and
+ * MBEDTLS_NET_POLL_WRITE specifying the events
+ * to wait for:
+ * - If MBEDTLS_NET_POLL_READ is set, the function
+ * will return as soon as the net context is available
+ * for reading.
+ * - If MBEDTLS_NET_POLL_WRITE is set, the function
+ * will return as soon as the net context is available
+ * for writing.
+ * \param timeout Maximal amount of time to wait before returning,
+ * in milliseconds. If \c timeout is zero, the
+ * function returns immediately. If \c timeout is
+ * -1u, the function blocks potentially indefinitely.
+ *
+ * \return Bitmask composed of MBEDTLS_NET_POLL_READ/WRITE
+ * on success or timeout, or a negative return code otherwise.
+ */
+int mbedtls_net_poll(mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout);
+
+/**
+ * \brief Set the socket blocking
+ *
+ * \param ctx Socket to set
+ *
+ * \return 0 if successful, or a non-zero error code
+ */
+int mbedtls_net_set_block(mbedtls_net_context *ctx);
+
+/**
+ * \brief Set the socket non-blocking
+ *
+ * \param ctx Socket to set
+ *
+ * \return 0 if successful, or a non-zero error code
+ */
+int mbedtls_net_set_nonblock(mbedtls_net_context *ctx);
+
+/**
+ * \brief Portable usleep helper
+ *
+ * \param usec Amount of microseconds to sleep
+ *
+ * \note Real amount of time slept will not be less than
+ * select()'s timeout granularity (typically, 10ms).
+ */
+void mbedtls_net_usleep(unsigned long usec);
+
+/**
+ * \brief Read at most 'len' characters. If no error occurs,
+ * the actual amount read is returned.
+ *
+ * \param ctx Socket
+ * \param buf The buffer to write to
+ * \param len Maximum length of the buffer
+ *
+ * \return the number of bytes received,
+ * or a non-zero error code; with a non-blocking socket,
+ * MBEDTLS_ERR_SSL_WANT_READ indicates read() would block.
+ */
+int mbedtls_net_recv(void *ctx, unsigned char *buf, size_t len);
+
+/**
+ * \brief Write at most 'len' characters. If no error occurs,
+ * the actual amount read is returned.
+ *
+ * \param ctx Socket
+ * \param buf The buffer to read from
+ * \param len The length of the buffer
+ *
+ * \return the number of bytes sent,
+ * or a non-zero error code; with a non-blocking socket,
+ * MBEDTLS_ERR_SSL_WANT_WRITE indicates write() would block.
+ */
+int mbedtls_net_send(void *ctx, const unsigned char *buf, size_t len);
+
+/**
+ * \brief Read at most 'len' characters, blocking for at most
+ * 'timeout' seconds. If no error occurs, the actual amount
+ * read is returned.
+ *
+ * \note The current implementation of this function uses
+ * select() and returns an error if the file descriptor
+ * is \c FD_SETSIZE or greater.
+ *
+ * \param ctx Socket
+ * \param buf The buffer to write to
+ * \param len Maximum length of the buffer
+ * \param timeout Maximum number of milliseconds to wait for data
+ * 0 means no timeout (wait forever)
+ *
+ * \return The number of bytes received if successful.
+ * MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out.
+ * MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal.
+ * Another negative error code (MBEDTLS_ERR_NET_xxx)
+ * for other failures.
+ *
+ * \note This function will block (until data becomes available or
+ * timeout is reached) even if the socket is set to
+ * non-blocking. Handling timeouts with non-blocking reads
+ * requires a different strategy.
+ */
+int mbedtls_net_recv_timeout(void *ctx, unsigned char *buf, size_t len,
+ uint32_t timeout);
+
+/**
+ * \brief Closes down the connection and free associated data
+ *
+ * \param ctx The context to close
+ *
+ * \note This function frees and clears data associated with the
+ * context but does not free the memory pointed to by \p ctx.
+ * This memory is the responsibility of the caller.
+ */
+void mbedtls_net_close(mbedtls_net_context *ctx);
+
+/**
+ * \brief Gracefully shutdown the connection and free associated data
+ *
+ * \param ctx The context to free
+ *
+ * \note This function frees and clears data associated with the
+ * context but does not free the memory pointed to by \p ctx.
+ * This memory is the responsibility of the caller.
+ */
+void mbedtls_net_free(mbedtls_net_context *ctx);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* net_sockets.h */
diff --git a/include/mbedtls/nist_kw.h b/include/mbedtls/nist_kw.h
new file mode 100644
index 0000000..d353f3d
--- /dev/null
+++ b/include/mbedtls/nist_kw.h
@@ -0,0 +1,166 @@
+/**
+ * \file nist_kw.h
+ *
+ * \brief This file provides an API for key wrapping (KW) and key wrapping with
+ * padding (KWP) as defined in NIST SP 800-38F.
+ * https://nvlpubs.nist.gov/nistpubs/SpecialPublications/NIST.SP.800-38F.pdf
+ *
+ * Key wrapping specifies a deterministic authenticated-encryption mode
+ * of operation, according to <em>NIST SP 800-38F: Recommendation for
+ * Block Cipher Modes of Operation: Methods for Key Wrapping</em>. Its
+ * purpose is to protect cryptographic keys.
+ *
+ * Its equivalent is RFC 3394 for KW, and RFC 5649 for KWP.
+ * https://tools.ietf.org/html/rfc3394
+ * https://tools.ietf.org/html/rfc5649
+ *
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_NIST_KW_H
+#define MBEDTLS_NIST_KW_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/cipher.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef enum {
+ MBEDTLS_KW_MODE_KW = 0,
+ MBEDTLS_KW_MODE_KWP = 1
+} mbedtls_nist_kw_mode_t;
+
+#if !defined(MBEDTLS_NIST_KW_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief The key wrapping context-type definition. The key wrapping context is passed
+ * to the APIs called.
+ *
+ * \note The definition of this type may change in future library versions.
+ * Don't make any assumptions on this context!
+ */
+typedef struct {
+ mbedtls_cipher_context_t MBEDTLS_PRIVATE(cipher_ctx); /*!< The cipher context used. */
+} mbedtls_nist_kw_context;
+
+#else /* MBEDTLS_NIST_key wrapping_ALT */
+#include "nist_kw_alt.h"
+#endif /* MBEDTLS_NIST_KW_ALT */
+
+/**
+ * \brief This function initializes the specified key wrapping context
+ * to make references valid and prepare the context
+ * for mbedtls_nist_kw_setkey() or mbedtls_nist_kw_free().
+ *
+ * \param ctx The key wrapping context to initialize.
+ *
+ */
+void mbedtls_nist_kw_init(mbedtls_nist_kw_context *ctx);
+
+/**
+ * \brief This function initializes the key wrapping context set in the
+ * \p ctx parameter and sets the encryption key.
+ *
+ * \param ctx The key wrapping context.
+ * \param cipher The 128-bit block cipher to use. Only AES is supported.
+ * \param key The Key Encryption Key (KEK).
+ * \param keybits The KEK size in bits. This must be acceptable by the cipher.
+ * \param is_wrap Specify whether the operation within the context is wrapping or unwrapping
+ *
+ * \return \c 0 on success.
+ * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for any invalid input.
+ * \return \c MBEDTLS_ERR_CIPHER_FEATURE_UNAVAILABLE for 128-bit block ciphers
+ * which are not supported.
+ * \return cipher-specific error code on failure of the underlying cipher.
+ */
+int mbedtls_nist_kw_setkey(mbedtls_nist_kw_context *ctx,
+ mbedtls_cipher_id_t cipher,
+ const unsigned char *key,
+ unsigned int keybits,
+ const int is_wrap);
+
+/**
+ * \brief This function releases and clears the specified key wrapping context
+ * and underlying cipher sub-context.
+ *
+ * \param ctx The key wrapping context to clear.
+ */
+void mbedtls_nist_kw_free(mbedtls_nist_kw_context *ctx);
+
+/**
+ * \brief This function encrypts a buffer using key wrapping.
+ *
+ * \param ctx The key wrapping context to use for encryption.
+ * \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP)
+ * \param input The buffer holding the input data.
+ * \param in_len The length of the input data in Bytes.
+ * The input uses units of 8 Bytes called semiblocks.
+ * <ul><li>For KW mode: a multiple of 8 bytes between 16 and 2^57-8 inclusive. </li>
+ * <li>For KWP mode: any length between 1 and 2^32-1 inclusive.</li></ul>
+ * \param[out] output The buffer holding the output data.
+ * <ul><li>For KW mode: Must be at least 8 bytes larger than \p in_len.</li>
+ * <li>For KWP mode: Must be at least 8 bytes larger rounded up to a multiple of
+ * 8 bytes for KWP (15 bytes at most).</li></ul>
+ * \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure.
+ * \param[in] out_size The capacity of the output buffer.
+ *
+ * \return \c 0 on success.
+ * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length.
+ * \return cipher-specific error code on failure of the underlying cipher.
+ */
+int mbedtls_nist_kw_wrap(mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode,
+ const unsigned char *input, size_t in_len,
+ unsigned char *output, size_t *out_len, size_t out_size);
+
+/**
+ * \brief This function decrypts a buffer using key wrapping.
+ *
+ * \param ctx The key wrapping context to use for decryption.
+ * \param mode The key wrapping mode to use (MBEDTLS_KW_MODE_KW or MBEDTLS_KW_MODE_KWP)
+ * \param input The buffer holding the input data.
+ * \param in_len The length of the input data in Bytes.
+ * The input uses units of 8 Bytes called semiblocks.
+ * The input must be a multiple of semiblocks.
+ * <ul><li>For KW mode: a multiple of 8 bytes between 24 and 2^57 inclusive. </li>
+ * <li>For KWP mode: a multiple of 8 bytes between 16 and 2^32 inclusive.</li></ul>
+ * \param[out] output The buffer holding the output data.
+ * The output buffer's minimal length is 8 bytes shorter than \p in_len.
+ * \param[out] out_len The number of bytes written to the output buffer. \c 0 on failure.
+ * For KWP mode, the length could be up to 15 bytes shorter than \p in_len,
+ * depending on how much padding was added to the data.
+ * \param[in] out_size The capacity of the output buffer.
+ *
+ * \return \c 0 on success.
+ * \return \c MBEDTLS_ERR_CIPHER_BAD_INPUT_DATA for invalid input length.
+ * \return \c MBEDTLS_ERR_CIPHER_AUTH_FAILED for verification failure of the ciphertext.
+ * \return cipher-specific error code on failure of the underlying cipher.
+ */
+int mbedtls_nist_kw_unwrap(mbedtls_nist_kw_context *ctx, mbedtls_nist_kw_mode_t mode,
+ const unsigned char *input, size_t in_len,
+ unsigned char *output, size_t *out_len, size_t out_size);
+
+
+#if defined(MBEDTLS_SELF_TEST) && defined(MBEDTLS_AES_C)
+/**
+ * \brief The key wrapping checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_nist_kw_self_test(int verbose);
+#endif /* MBEDTLS_SELF_TEST && MBEDTLS_AES_C */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_NIST_KW_H */
diff --git a/include/mbedtls/oid.h b/include/mbedtls/oid.h
new file mode 100644
index 0000000..e48817d
--- /dev/null
+++ b/include/mbedtls/oid.h
@@ -0,0 +1,722 @@
+/**
+ * \file oid.h
+ *
+ * \brief Object Identifier (OID) database
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_OID_H
+#define MBEDTLS_OID_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/asn1.h"
+#include "mbedtls/pk.h"
+
+#include <stddef.h>
+
+#if defined(MBEDTLS_CIPHER_C)
+#include "mbedtls/cipher.h"
+#endif
+
+#include "mbedtls/md.h"
+
+/** OID is not found. */
+#define MBEDTLS_ERR_OID_NOT_FOUND -0x002E
+/** output buffer is too small */
+#define MBEDTLS_ERR_OID_BUF_TOO_SMALL -0x000B
+
+/* This is for the benefit of X.509, but defined here in order to avoid
+ * having a "backwards" include of x.509.h here */
+/*
+ * X.509 extension types (internal, arbitrary values for bitsets)
+ */
+#define MBEDTLS_OID_X509_EXT_AUTHORITY_KEY_IDENTIFIER (1 << 0)
+#define MBEDTLS_OID_X509_EXT_SUBJECT_KEY_IDENTIFIER (1 << 1)
+#define MBEDTLS_OID_X509_EXT_KEY_USAGE (1 << 2)
+#define MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES (1 << 3)
+#define MBEDTLS_OID_X509_EXT_POLICY_MAPPINGS (1 << 4)
+#define MBEDTLS_OID_X509_EXT_SUBJECT_ALT_NAME (1 << 5)
+#define MBEDTLS_OID_X509_EXT_ISSUER_ALT_NAME (1 << 6)
+#define MBEDTLS_OID_X509_EXT_SUBJECT_DIRECTORY_ATTRS (1 << 7)
+#define MBEDTLS_OID_X509_EXT_BASIC_CONSTRAINTS (1 << 8)
+#define MBEDTLS_OID_X509_EXT_NAME_CONSTRAINTS (1 << 9)
+#define MBEDTLS_OID_X509_EXT_POLICY_CONSTRAINTS (1 << 10)
+#define MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE (1 << 11)
+#define MBEDTLS_OID_X509_EXT_CRL_DISTRIBUTION_POINTS (1 << 12)
+#define MBEDTLS_OID_X509_EXT_INIHIBIT_ANYPOLICY (1 << 13)
+#define MBEDTLS_OID_X509_EXT_FRESHEST_CRL (1 << 14)
+#define MBEDTLS_OID_X509_EXT_NS_CERT_TYPE (1 << 16)
+
+/*
+ * Maximum number of OID components allowed
+ */
+#define MBEDTLS_OID_MAX_COMPONENTS 128
+
+/*
+ * Top level OID tuples
+ */
+#define MBEDTLS_OID_ISO_MEMBER_BODIES "\x2a" /* {iso(1) member-body(2)} */
+#define MBEDTLS_OID_ISO_IDENTIFIED_ORG "\x2b" /* {iso(1) identified-organization(3)} */
+#define MBEDTLS_OID_ISO_CCITT_DS "\x55" /* {joint-iso-ccitt(2) ds(5)} */
+#define MBEDTLS_OID_ISO_ITU_COUNTRY "\x60" /* {joint-iso-itu-t(2) country(16)} */
+
+/*
+ * ISO Member bodies OID parts
+ */
+#define MBEDTLS_OID_COUNTRY_US "\x86\x48" /* {us(840)} */
+#define MBEDTLS_OID_ORG_RSA_DATA_SECURITY "\x86\xf7\x0d" /* {rsadsi(113549)} */
+#define MBEDTLS_OID_RSA_COMPANY MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \
+ MBEDTLS_OID_ORG_RSA_DATA_SECURITY /* {iso(1) member-body(2) us(840) rsadsi(113549)} */
+#define MBEDTLS_OID_ORG_ANSI_X9_62 "\xce\x3d" /* ansi-X9-62(10045) */
+#define MBEDTLS_OID_ANSI_X9_62 MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \
+ MBEDTLS_OID_ORG_ANSI_X9_62
+
+/*
+ * ISO Identified organization OID parts
+ */
+#define MBEDTLS_OID_ORG_DOD "\x06" /* {dod(6)} */
+#define MBEDTLS_OID_ORG_OIW "\x0e"
+#define MBEDTLS_OID_OIW_SECSIG MBEDTLS_OID_ORG_OIW "\x03"
+#define MBEDTLS_OID_OIW_SECSIG_ALG MBEDTLS_OID_OIW_SECSIG "\x02"
+#define MBEDTLS_OID_OIW_SECSIG_SHA1 MBEDTLS_OID_OIW_SECSIG_ALG "\x1a"
+#define MBEDTLS_OID_ORG_THAWTE "\x65" /* thawte(101) */
+#define MBEDTLS_OID_THAWTE MBEDTLS_OID_ISO_IDENTIFIED_ORG \
+ MBEDTLS_OID_ORG_THAWTE
+#define MBEDTLS_OID_ORG_CERTICOM "\x81\x04" /* certicom(132) */
+#define MBEDTLS_OID_CERTICOM MBEDTLS_OID_ISO_IDENTIFIED_ORG \
+ MBEDTLS_OID_ORG_CERTICOM
+#define MBEDTLS_OID_ORG_TELETRUST "\x24" /* teletrust(36) */
+#define MBEDTLS_OID_TELETRUST MBEDTLS_OID_ISO_IDENTIFIED_ORG \
+ MBEDTLS_OID_ORG_TELETRUST
+
+/*
+ * ISO ITU OID parts
+ */
+#define MBEDTLS_OID_ORGANIZATION "\x01" /* {organization(1)} */
+#define MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ISO_ITU_COUNTRY MBEDTLS_OID_COUNTRY_US \
+ MBEDTLS_OID_ORGANIZATION /* {joint-iso-itu-t(2) country(16) us(840) organization(1)} */
+
+#define MBEDTLS_OID_ORG_GOV "\x65" /* {gov(101)} */
+#define MBEDTLS_OID_GOV MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_GOV /* {joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101)} */
+
+#define MBEDTLS_OID_ORG_NETSCAPE "\x86\xF8\x42" /* {netscape(113730)} */
+#define MBEDTLS_OID_NETSCAPE MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_NETSCAPE /* Netscape OID {joint-iso-itu-t(2) country(16) us(840) organization(1) netscape(113730)} */
+
+/* ISO arc for standard certificate and CRL extensions */
+#define MBEDTLS_OID_ID_CE MBEDTLS_OID_ISO_CCITT_DS "\x1D" /**< id-ce OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 29} */
+
+#define MBEDTLS_OID_NIST_ALG MBEDTLS_OID_GOV "\x03\x04" /** { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) */
+
+/**
+ * Private Internet Extensions
+ * { iso(1) identified-organization(3) dod(6) internet(1)
+ * security(5) mechanisms(5) pkix(7) }
+ */
+#define MBEDTLS_OID_INTERNET MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_DOD \
+ "\x01"
+#define MBEDTLS_OID_PKIX MBEDTLS_OID_INTERNET "\x05\x05\x07"
+
+/*
+ * Arc for standard naming attributes
+ */
+#define MBEDTLS_OID_AT MBEDTLS_OID_ISO_CCITT_DS "\x04" /**< id-at OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 4} */
+#define MBEDTLS_OID_AT_CN MBEDTLS_OID_AT "\x03" /**< id-at-commonName AttributeType:= {id-at 3} */
+#define MBEDTLS_OID_AT_SUR_NAME MBEDTLS_OID_AT "\x04" /**< id-at-surName AttributeType:= {id-at 4} */
+#define MBEDTLS_OID_AT_SERIAL_NUMBER MBEDTLS_OID_AT "\x05" /**< id-at-serialNumber AttributeType:= {id-at 5} */
+#define MBEDTLS_OID_AT_COUNTRY MBEDTLS_OID_AT "\x06" /**< id-at-countryName AttributeType:= {id-at 6} */
+#define MBEDTLS_OID_AT_LOCALITY MBEDTLS_OID_AT "\x07" /**< id-at-locality AttributeType:= {id-at 7} */
+#define MBEDTLS_OID_AT_STATE MBEDTLS_OID_AT "\x08" /**< id-at-state AttributeType:= {id-at 8} */
+#define MBEDTLS_OID_AT_ORGANIZATION MBEDTLS_OID_AT "\x0A" /**< id-at-organizationName AttributeType:= {id-at 10} */
+#define MBEDTLS_OID_AT_ORG_UNIT MBEDTLS_OID_AT "\x0B" /**< id-at-organizationalUnitName AttributeType:= {id-at 11} */
+#define MBEDTLS_OID_AT_TITLE MBEDTLS_OID_AT "\x0C" /**< id-at-title AttributeType:= {id-at 12} */
+#define MBEDTLS_OID_AT_POSTAL_ADDRESS MBEDTLS_OID_AT "\x10" /**< id-at-postalAddress AttributeType:= {id-at 16} */
+#define MBEDTLS_OID_AT_POSTAL_CODE MBEDTLS_OID_AT "\x11" /**< id-at-postalCode AttributeType:= {id-at 17} */
+#define MBEDTLS_OID_AT_GIVEN_NAME MBEDTLS_OID_AT "\x2A" /**< id-at-givenName AttributeType:= {id-at 42} */
+#define MBEDTLS_OID_AT_INITIALS MBEDTLS_OID_AT "\x2B" /**< id-at-initials AttributeType:= {id-at 43} */
+#define MBEDTLS_OID_AT_GENERATION_QUALIFIER MBEDTLS_OID_AT "\x2C" /**< id-at-generationQualifier AttributeType:= {id-at 44} */
+#define MBEDTLS_OID_AT_UNIQUE_IDENTIFIER MBEDTLS_OID_AT "\x2D" /**< id-at-uniqueIdentifier AttributeType:= {id-at 45} */
+#define MBEDTLS_OID_AT_DN_QUALIFIER MBEDTLS_OID_AT "\x2E" /**< id-at-dnQualifier AttributeType:= {id-at 46} */
+#define MBEDTLS_OID_AT_PSEUDONYM MBEDTLS_OID_AT "\x41" /**< id-at-pseudonym AttributeType:= {id-at 65} */
+
+#define MBEDTLS_OID_UID "\x09\x92\x26\x89\x93\xF2\x2C\x64\x01\x01" /** id-domainComponent AttributeType:= {itu-t(0) data(9) pss(2342) ucl(19200300) pilot(100) pilotAttributeType(1) uid(1)} */
+#define MBEDTLS_OID_DOMAIN_COMPONENT "\x09\x92\x26\x89\x93\xF2\x2C\x64\x01\x19" /** id-domainComponent AttributeType:= {itu-t(0) data(9) pss(2342) ucl(19200300) pilot(100) pilotAttributeType(1) domainComponent(25)} */
+
+/*
+ * OIDs for standard certificate extensions
+ */
+#define MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER MBEDTLS_OID_ID_CE "\x23" /**< id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 } */
+#define MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER MBEDTLS_OID_ID_CE "\x0E" /**< id-ce-subjectKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 14 } */
+#define MBEDTLS_OID_KEY_USAGE MBEDTLS_OID_ID_CE "\x0F" /**< id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } */
+#define MBEDTLS_OID_CERTIFICATE_POLICIES MBEDTLS_OID_ID_CE "\x20" /**< id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 } */
+#define MBEDTLS_OID_POLICY_MAPPINGS MBEDTLS_OID_ID_CE "\x21" /**< id-ce-policyMappings OBJECT IDENTIFIER ::= { id-ce 33 } */
+#define MBEDTLS_OID_SUBJECT_ALT_NAME MBEDTLS_OID_ID_CE "\x11" /**< id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 } */
+#define MBEDTLS_OID_ISSUER_ALT_NAME MBEDTLS_OID_ID_CE "\x12" /**< id-ce-issuerAltName OBJECT IDENTIFIER ::= { id-ce 18 } */
+#define MBEDTLS_OID_SUBJECT_DIRECTORY_ATTRS MBEDTLS_OID_ID_CE "\x09" /**< id-ce-subjectDirectoryAttributes OBJECT IDENTIFIER ::= { id-ce 9 } */
+#define MBEDTLS_OID_BASIC_CONSTRAINTS MBEDTLS_OID_ID_CE "\x13" /**< id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } */
+#define MBEDTLS_OID_NAME_CONSTRAINTS MBEDTLS_OID_ID_CE "\x1E" /**< id-ce-nameConstraints OBJECT IDENTIFIER ::= { id-ce 30 } */
+#define MBEDTLS_OID_POLICY_CONSTRAINTS MBEDTLS_OID_ID_CE "\x24" /**< id-ce-policyConstraints OBJECT IDENTIFIER ::= { id-ce 36 } */
+#define MBEDTLS_OID_EXTENDED_KEY_USAGE MBEDTLS_OID_ID_CE "\x25" /**< id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } */
+#define MBEDTLS_OID_CRL_DISTRIBUTION_POINTS MBEDTLS_OID_ID_CE "\x1F" /**< id-ce-cRLDistributionPoints OBJECT IDENTIFIER ::= { id-ce 31 } */
+#define MBEDTLS_OID_INIHIBIT_ANYPOLICY MBEDTLS_OID_ID_CE "\x36" /**< id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-ce 54 } */
+#define MBEDTLS_OID_FRESHEST_CRL MBEDTLS_OID_ID_CE "\x2E" /**< id-ce-freshestCRL OBJECT IDENTIFIER ::= { id-ce 46 } */
+
+/*
+ * Certificate policies
+ */
+#define MBEDTLS_OID_ANY_POLICY MBEDTLS_OID_CERTIFICATE_POLICIES "\x00" /**< anyPolicy OBJECT IDENTIFIER ::= { id-ce-certificatePolicies 0 } */
+
+/*
+ * Netscape certificate extensions
+ */
+#define MBEDTLS_OID_NS_CERT MBEDTLS_OID_NETSCAPE "\x01"
+#define MBEDTLS_OID_NS_CERT_TYPE MBEDTLS_OID_NS_CERT "\x01"
+#define MBEDTLS_OID_NS_BASE_URL MBEDTLS_OID_NS_CERT "\x02"
+#define MBEDTLS_OID_NS_REVOCATION_URL MBEDTLS_OID_NS_CERT "\x03"
+#define MBEDTLS_OID_NS_CA_REVOCATION_URL MBEDTLS_OID_NS_CERT "\x04"
+#define MBEDTLS_OID_NS_RENEWAL_URL MBEDTLS_OID_NS_CERT "\x07"
+#define MBEDTLS_OID_NS_CA_POLICY_URL MBEDTLS_OID_NS_CERT "\x08"
+#define MBEDTLS_OID_NS_SSL_SERVER_NAME MBEDTLS_OID_NS_CERT "\x0C"
+#define MBEDTLS_OID_NS_COMMENT MBEDTLS_OID_NS_CERT "\x0D"
+#define MBEDTLS_OID_NS_DATA_TYPE MBEDTLS_OID_NETSCAPE "\x02"
+#define MBEDTLS_OID_NS_CERT_SEQUENCE MBEDTLS_OID_NS_DATA_TYPE "\x05"
+
+/*
+ * OIDs for CRL extensions
+ */
+#define MBEDTLS_OID_PRIVATE_KEY_USAGE_PERIOD MBEDTLS_OID_ID_CE "\x10"
+#define MBEDTLS_OID_CRL_NUMBER MBEDTLS_OID_ID_CE "\x14" /**< id-ce-cRLNumber OBJECT IDENTIFIER ::= { id-ce 20 } */
+
+/*
+ * X.509 v3 Extended key usage OIDs
+ */
+#define MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE MBEDTLS_OID_EXTENDED_KEY_USAGE "\x00" /**< anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } */
+
+#define MBEDTLS_OID_KP MBEDTLS_OID_PKIX "\x03" /**< id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } */
+#define MBEDTLS_OID_SERVER_AUTH MBEDTLS_OID_KP "\x01" /**< id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } */
+#define MBEDTLS_OID_CLIENT_AUTH MBEDTLS_OID_KP "\x02" /**< id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } */
+#define MBEDTLS_OID_CODE_SIGNING MBEDTLS_OID_KP "\x03" /**< id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } */
+#define MBEDTLS_OID_EMAIL_PROTECTION MBEDTLS_OID_KP "\x04" /**< id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } */
+#define MBEDTLS_OID_TIME_STAMPING MBEDTLS_OID_KP "\x08" /**< id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } */
+#define MBEDTLS_OID_OCSP_SIGNING MBEDTLS_OID_KP "\x09" /**< id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } */
+
+/**
+ * Wi-SUN Alliance Field Area Network
+ * { iso(1) identified-organization(3) dod(6) internet(1)
+ * private(4) enterprise(1) WiSUN(45605) FieldAreaNetwork(1) }
+ */
+#define MBEDTLS_OID_WISUN_FAN MBEDTLS_OID_INTERNET "\x04\x01\x82\xe4\x25\x01"
+
+#define MBEDTLS_OID_ON MBEDTLS_OID_PKIX "\x08" /**< id-on OBJECT IDENTIFIER ::= { id-pkix 8 } */
+#define MBEDTLS_OID_ON_HW_MODULE_NAME MBEDTLS_OID_ON "\x04" /**< id-on-hardwareModuleName OBJECT IDENTIFIER ::= { id-on 4 } */
+
+/*
+ * PKCS definition OIDs
+ */
+
+#define MBEDTLS_OID_PKCS MBEDTLS_OID_RSA_COMPANY "\x01" /**< pkcs OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) 1 } */
+#define MBEDTLS_OID_PKCS1 MBEDTLS_OID_PKCS "\x01" /**< pkcs-1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } */
+#define MBEDTLS_OID_PKCS5 MBEDTLS_OID_PKCS "\x05" /**< pkcs-5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 } */
+#define MBEDTLS_OID_PKCS7 MBEDTLS_OID_PKCS "\x07" /**< pkcs-7 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 7 } */
+#define MBEDTLS_OID_PKCS9 MBEDTLS_OID_PKCS "\x09" /**< pkcs-9 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 } */
+#define MBEDTLS_OID_PKCS12 MBEDTLS_OID_PKCS "\x0c" /**< pkcs-12 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 } */
+
+/*
+ * PKCS#1 OIDs
+ */
+#define MBEDTLS_OID_PKCS1_RSA MBEDTLS_OID_PKCS1 "\x01" /**< rsaEncryption OBJECT IDENTIFIER ::= { pkcs-1 1 } */
+#define MBEDTLS_OID_PKCS1_MD5 MBEDTLS_OID_PKCS1 "\x04" /**< md5WithRSAEncryption ::= { pkcs-1 4 } */
+#define MBEDTLS_OID_PKCS1_SHA1 MBEDTLS_OID_PKCS1 "\x05" /**< sha1WithRSAEncryption ::= { pkcs-1 5 } */
+#define MBEDTLS_OID_PKCS1_SHA224 MBEDTLS_OID_PKCS1 "\x0e" /**< sha224WithRSAEncryption ::= { pkcs-1 14 } */
+#define MBEDTLS_OID_PKCS1_SHA256 MBEDTLS_OID_PKCS1 "\x0b" /**< sha256WithRSAEncryption ::= { pkcs-1 11 } */
+#define MBEDTLS_OID_PKCS1_SHA384 MBEDTLS_OID_PKCS1 "\x0c" /**< sha384WithRSAEncryption ::= { pkcs-1 12 } */
+#define MBEDTLS_OID_PKCS1_SHA512 MBEDTLS_OID_PKCS1 "\x0d" /**< sha512WithRSAEncryption ::= { pkcs-1 13 } */
+
+#define MBEDTLS_OID_RSA_SHA_OBS "\x2B\x0E\x03\x02\x1D"
+
+#define MBEDTLS_OID_PKCS9_EMAIL MBEDTLS_OID_PKCS9 "\x01" /**< emailAddress AttributeType ::= { pkcs-9 1 } */
+
+/* RFC 4055 */
+#define MBEDTLS_OID_RSASSA_PSS MBEDTLS_OID_PKCS1 "\x0a" /**< id-RSASSA-PSS ::= { pkcs-1 10 } */
+#define MBEDTLS_OID_MGF1 MBEDTLS_OID_PKCS1 "\x08" /**< id-mgf1 ::= { pkcs-1 8 } */
+
+/*
+ * Digest algorithms
+ */
+#define MBEDTLS_OID_DIGEST_ALG_MD5 MBEDTLS_OID_RSA_COMPANY "\x02\x05" /**< id-mbedtls_md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 5 } */
+#define MBEDTLS_OID_DIGEST_ALG_SHA1 MBEDTLS_OID_ISO_IDENTIFIED_ORG \
+ MBEDTLS_OID_OIW_SECSIG_SHA1 /**< id-mbedtls_sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } */
+#define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_NIST_ALG "\x02\x04" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */
+#define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_NIST_ALG "\x02\x01" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */
+
+#define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_NIST_ALG "\x02\x02" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */
+
+#define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_NIST_ALG "\x02\x03" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */
+
+#define MBEDTLS_OID_DIGEST_ALG_RIPEMD160 MBEDTLS_OID_TELETRUST "\x03\x02\x01" /**< id-ripemd160 OBJECT IDENTIFIER :: { iso(1) identified-organization(3) teletrust(36) algorithm(3) hashAlgorithm(2) ripemd160(1) } */
+
+#define MBEDTLS_OID_DIGEST_ALG_SHA3_224 MBEDTLS_OID_NIST_ALG "\x02\x07" /**< id-sha3-224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithms(4) hashalgs(2) sha3-224(7) } */
+
+#define MBEDTLS_OID_DIGEST_ALG_SHA3_256 MBEDTLS_OID_NIST_ALG "\x02\x08" /**< id-sha3-256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithms(4) hashalgs(2) sha3-256(8) } */
+
+#define MBEDTLS_OID_DIGEST_ALG_SHA3_384 MBEDTLS_OID_NIST_ALG "\x02\x09" /**< id-sha3-384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithms(4) hashalgs(2) sha3-384(9) } */
+
+#define MBEDTLS_OID_DIGEST_ALG_SHA3_512 MBEDTLS_OID_NIST_ALG "\x02\x0a" /**< id-sha3-512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithms(4) hashalgs(2) sha3-512(10) } */
+
+
+#define MBEDTLS_OID_HMAC_SHA1 MBEDTLS_OID_RSA_COMPANY "\x02\x07" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */
+
+#define MBEDTLS_OID_HMAC_SHA224 MBEDTLS_OID_RSA_COMPANY "\x02\x08" /**< id-hmacWithSHA224 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 8 } */
+
+#define MBEDTLS_OID_HMAC_SHA256 MBEDTLS_OID_RSA_COMPANY "\x02\x09" /**< id-hmacWithSHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 9 } */
+
+#define MBEDTLS_OID_HMAC_SHA384 MBEDTLS_OID_RSA_COMPANY "\x02\x0A" /**< id-hmacWithSHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 10 } */
+
+#define MBEDTLS_OID_HMAC_SHA512 MBEDTLS_OID_RSA_COMPANY "\x02\x0B" /**< id-hmacWithSHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 11 } */
+
+#define MBEDTLS_OID_HMAC_SHA3_224 MBEDTLS_OID_NIST_ALG "\x02\x0d" /**< id-hmacWithSHA3-512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithms(4) hashalgs(2) hmacWithSHA3-224(13) } */
+
+#define MBEDTLS_OID_HMAC_SHA3_256 MBEDTLS_OID_NIST_ALG "\x02\x0e" /**< id-hmacWithSHA3-512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithms(4) hashalgs(2) hmacWithSHA3-256(14) } */
+
+#define MBEDTLS_OID_HMAC_SHA3_384 MBEDTLS_OID_NIST_ALG "\x02\x0f" /**< id-hmacWithSHA3-512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithms(4) hashalgs(2) hmacWithSHA3-384(15) } */
+
+#define MBEDTLS_OID_HMAC_SHA3_512 MBEDTLS_OID_NIST_ALG "\x02\x10" /**< id-hmacWithSHA3-512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithms(4) hashalgs(2) hmacWithSHA3-512(16) } */
+
+#define MBEDTLS_OID_HMAC_RIPEMD160 MBEDTLS_OID_INTERNET "\x05\x05\x08\x01\x04" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= {iso(1) iso-identified-organization(3) dod(6) internet(1) security(5) mechanisms(5) ipsec(8) isakmpOakley(1) hmacRIPEMD160(4)} */
+
+/*
+ * Encryption algorithms
+ */
+#define MBEDTLS_OID_DES_CBC MBEDTLS_OID_ISO_IDENTIFIED_ORG \
+ MBEDTLS_OID_OIW_SECSIG_ALG "\x07" /**< desCBC OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 7 } */
+#define MBEDTLS_OID_DES_EDE3_CBC MBEDTLS_OID_RSA_COMPANY "\x03\x07" /**< des-ede3-cbc OBJECT IDENTIFIER ::= { iso(1) member-body(2) -- us(840) rsadsi(113549) encryptionAlgorithm(3) 7 } */
+#define MBEDTLS_OID_AES MBEDTLS_OID_NIST_ALG "\x01" /** aes OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) 1 } */
+
+/*
+ * Key Wrapping algorithms
+ */
+/*
+ * RFC 5649
+ */
+#define MBEDTLS_OID_AES128_KW MBEDTLS_OID_AES "\x05" /** id-aes128-wrap OBJECT IDENTIFIER ::= { aes 5 } */
+#define MBEDTLS_OID_AES128_KWP MBEDTLS_OID_AES "\x08" /** id-aes128-wrap-pad OBJECT IDENTIFIER ::= { aes 8 } */
+#define MBEDTLS_OID_AES192_KW MBEDTLS_OID_AES "\x19" /** id-aes192-wrap OBJECT IDENTIFIER ::= { aes 25 } */
+#define MBEDTLS_OID_AES192_KWP MBEDTLS_OID_AES "\x1c" /** id-aes192-wrap-pad OBJECT IDENTIFIER ::= { aes 28 } */
+#define MBEDTLS_OID_AES256_KW MBEDTLS_OID_AES "\x2d" /** id-aes256-wrap OBJECT IDENTIFIER ::= { aes 45 } */
+#define MBEDTLS_OID_AES256_KWP MBEDTLS_OID_AES "\x30" /** id-aes256-wrap-pad OBJECT IDENTIFIER ::= { aes 48 } */
+/*
+ * PKCS#5 OIDs
+ */
+#define MBEDTLS_OID_PKCS5_PBKDF2 MBEDTLS_OID_PKCS5 "\x0c" /**< id-PBKDF2 OBJECT IDENTIFIER ::= {pkcs-5 12} */
+#define MBEDTLS_OID_PKCS5_PBES2 MBEDTLS_OID_PKCS5 "\x0d" /**< id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} */
+#define MBEDTLS_OID_PKCS5_PBMAC1 MBEDTLS_OID_PKCS5 "\x0e" /**< id-PBMAC1 OBJECT IDENTIFIER ::= {pkcs-5 14} */
+
+/*
+ * PKCS#5 PBES1 algorithms
+ */
+#define MBEDTLS_OID_PKCS5_PBE_MD5_DES_CBC MBEDTLS_OID_PKCS5 "\x03" /**< pbeWithMD5AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 3} */
+#define MBEDTLS_OID_PKCS5_PBE_MD5_RC2_CBC MBEDTLS_OID_PKCS5 "\x06" /**< pbeWithMD5AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 6} */
+#define MBEDTLS_OID_PKCS5_PBE_SHA1_DES_CBC MBEDTLS_OID_PKCS5 "\x0a" /**< pbeWithSHA1AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 10} */
+#define MBEDTLS_OID_PKCS5_PBE_SHA1_RC2_CBC MBEDTLS_OID_PKCS5 "\x0b" /**< pbeWithSHA1AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 11} */
+
+/*
+ * PKCS#7 OIDs
+ */
+#define MBEDTLS_OID_PKCS7_DATA MBEDTLS_OID_PKCS7 "\x01" /**< Content type is Data OBJECT IDENTIFIER ::= {pkcs-7 1} */
+#define MBEDTLS_OID_PKCS7_SIGNED_DATA MBEDTLS_OID_PKCS7 "\x02" /**< Content type is Signed Data OBJECT IDENTIFIER ::= {pkcs-7 2} */
+#define MBEDTLS_OID_PKCS7_ENVELOPED_DATA MBEDTLS_OID_PKCS7 "\x03" /**< Content type is Enveloped Data OBJECT IDENTIFIER ::= {pkcs-7 3} */
+#define MBEDTLS_OID_PKCS7_SIGNED_AND_ENVELOPED_DATA MBEDTLS_OID_PKCS7 "\x04" /**< Content type is Signed and Enveloped Data OBJECT IDENTIFIER ::= {pkcs-7 4} */
+#define MBEDTLS_OID_PKCS7_DIGESTED_DATA MBEDTLS_OID_PKCS7 "\x05" /**< Content type is Digested Data OBJECT IDENTIFIER ::= {pkcs-7 5} */
+#define MBEDTLS_OID_PKCS7_ENCRYPTED_DATA MBEDTLS_OID_PKCS7 "\x06" /**< Content type is Encrypted Data OBJECT IDENTIFIER ::= {pkcs-7 6} */
+
+/*
+ * PKCS#8 OIDs
+ */
+#define MBEDTLS_OID_PKCS9_CSR_EXT_REQ MBEDTLS_OID_PKCS9 "\x0e" /**< extensionRequest OBJECT IDENTIFIER ::= {pkcs-9 14} */
+
+/*
+ * PKCS#12 PBE OIDs
+ */
+#define MBEDTLS_OID_PKCS12_PBE MBEDTLS_OID_PKCS12 "\x01" /**< pkcs-12PbeIds OBJECT IDENTIFIER ::= {pkcs-12 1} */
+
+#define MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC MBEDTLS_OID_PKCS12_PBE "\x03" /**< pbeWithSHAAnd3-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 3} */
+#define MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC MBEDTLS_OID_PKCS12_PBE "\x04" /**< pbeWithSHAAnd2-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 4} */
+#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_128_CBC MBEDTLS_OID_PKCS12_PBE "\x05" /**< pbeWithSHAAnd128BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 5} */
+#define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_40_CBC MBEDTLS_OID_PKCS12_PBE "\x06" /**< pbeWithSHAAnd40BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 6} */
+
+/*
+ * EC key algorithms from RFC 5480
+ */
+
+/* id-ecPublicKey OBJECT IDENTIFIER ::= {
+ * iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } */
+#define MBEDTLS_OID_EC_ALG_UNRESTRICTED MBEDTLS_OID_ANSI_X9_62 "\x02\01"
+
+/* id-ecDH OBJECT IDENTIFIER ::= {
+ * iso(1) identified-organization(3) certicom(132)
+ * schemes(1) ecdh(12) } */
+#define MBEDTLS_OID_EC_ALG_ECDH MBEDTLS_OID_CERTICOM "\x01\x0c"
+
+/*
+ * ECParameters namedCurve identifiers, from RFC 5480, RFC 5639, and SEC2
+ */
+
+/* secp192r1 OBJECT IDENTIFIER ::= {
+ * iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 1 } */
+#define MBEDTLS_OID_EC_GRP_SECP192R1 MBEDTLS_OID_ANSI_X9_62 "\x03\x01\x01"
+
+/* secp224r1 OBJECT IDENTIFIER ::= {
+ * iso(1) identified-organization(3) certicom(132) curve(0) 33 } */
+#define MBEDTLS_OID_EC_GRP_SECP224R1 MBEDTLS_OID_CERTICOM "\x00\x21"
+
+/* secp256r1 OBJECT IDENTIFIER ::= {
+ * iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 7 } */
+#define MBEDTLS_OID_EC_GRP_SECP256R1 MBEDTLS_OID_ANSI_X9_62 "\x03\x01\x07"
+
+/* secp384r1 OBJECT IDENTIFIER ::= {
+ * iso(1) identified-organization(3) certicom(132) curve(0) 34 } */
+#define MBEDTLS_OID_EC_GRP_SECP384R1 MBEDTLS_OID_CERTICOM "\x00\x22"
+
+/* secp521r1 OBJECT IDENTIFIER ::= {
+ * iso(1) identified-organization(3) certicom(132) curve(0) 35 } */
+#define MBEDTLS_OID_EC_GRP_SECP521R1 MBEDTLS_OID_CERTICOM "\x00\x23"
+
+/* secp192k1 OBJECT IDENTIFIER ::= {
+ * iso(1) identified-organization(3) certicom(132) curve(0) 31 } */
+#define MBEDTLS_OID_EC_GRP_SECP192K1 MBEDTLS_OID_CERTICOM "\x00\x1f"
+
+/* secp224k1 OBJECT IDENTIFIER ::= {
+ * iso(1) identified-organization(3) certicom(132) curve(0) 32 } */
+#define MBEDTLS_OID_EC_GRP_SECP224K1 MBEDTLS_OID_CERTICOM "\x00\x20"
+
+/* secp256k1 OBJECT IDENTIFIER ::= {
+ * iso(1) identified-organization(3) certicom(132) curve(0) 10 } */
+#define MBEDTLS_OID_EC_GRP_SECP256K1 MBEDTLS_OID_CERTICOM "\x00\x0a"
+
+/* RFC 5639 4.1
+ * ecStdCurvesAndGeneration OBJECT IDENTIFIER::= {iso(1)
+ * identified-organization(3) teletrust(36) algorithm(3) signature-
+ * algorithm(3) ecSign(2) 8}
+ * ellipticCurve OBJECT IDENTIFIER ::= {ecStdCurvesAndGeneration 1}
+ * versionOne OBJECT IDENTIFIER ::= {ellipticCurve 1} */
+#define MBEDTLS_OID_EC_BRAINPOOL_V1 MBEDTLS_OID_TELETRUST "\x03\x03\x02\x08\x01\x01"
+
+/* brainpoolP256r1 OBJECT IDENTIFIER ::= {versionOne 7} */
+#define MBEDTLS_OID_EC_GRP_BP256R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x07"
+
+/* brainpoolP384r1 OBJECT IDENTIFIER ::= {versionOne 11} */
+#define MBEDTLS_OID_EC_GRP_BP384R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x0B"
+
+/* brainpoolP512r1 OBJECT IDENTIFIER ::= {versionOne 13} */
+#define MBEDTLS_OID_EC_GRP_BP512R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x0D"
+
+/*
+ * SEC1 C.1
+ *
+ * prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 }
+ * id-fieldType OBJECT IDENTIFIER ::= { ansi-X9-62 fieldType(1)}
+ */
+#define MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE MBEDTLS_OID_ANSI_X9_62 "\x01"
+#define MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE "\x01"
+
+/*
+ * ECDSA signature identifiers, from RFC 5480
+ */
+#define MBEDTLS_OID_ANSI_X9_62_SIG MBEDTLS_OID_ANSI_X9_62 "\x04" /* signatures(4) */
+#define MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 MBEDTLS_OID_ANSI_X9_62_SIG "\x03" /* ecdsa-with-SHA2(3) */
+
+/* ecdsa-with-SHA1 OBJECT IDENTIFIER ::= {
+ * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) 1 } */
+#define MBEDTLS_OID_ECDSA_SHA1 MBEDTLS_OID_ANSI_X9_62_SIG "\x01"
+
+/* ecdsa-with-SHA224 OBJECT IDENTIFIER ::= {
+ * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
+ * ecdsa-with-SHA2(3) 1 } */
+#define MBEDTLS_OID_ECDSA_SHA224 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x01"
+
+/* ecdsa-with-SHA256 OBJECT IDENTIFIER ::= {
+ * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
+ * ecdsa-with-SHA2(3) 2 } */
+#define MBEDTLS_OID_ECDSA_SHA256 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x02"
+
+/* ecdsa-with-SHA384 OBJECT IDENTIFIER ::= {
+ * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
+ * ecdsa-with-SHA2(3) 3 } */
+#define MBEDTLS_OID_ECDSA_SHA384 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x03"
+
+/* ecdsa-with-SHA512 OBJECT IDENTIFIER ::= {
+ * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4)
+ * ecdsa-with-SHA2(3) 4 } */
+#define MBEDTLS_OID_ECDSA_SHA512 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x04"
+
+/*
+ * EC key algorithms from RFC 8410
+ */
+
+#define MBEDTLS_OID_X25519 MBEDTLS_OID_THAWTE "\x6e" /**< id-X25519 OBJECT IDENTIFIER ::= { 1 3 101 110 } */
+#define MBEDTLS_OID_X448 MBEDTLS_OID_THAWTE "\x6f" /**< id-X448 OBJECT IDENTIFIER ::= { 1 3 101 111 } */
+#define MBEDTLS_OID_ED25519 MBEDTLS_OID_THAWTE "\x70" /**< id-Ed25519 OBJECT IDENTIFIER ::= { 1 3 101 112 } */
+#define MBEDTLS_OID_ED448 MBEDTLS_OID_THAWTE "\x71" /**< id-Ed448 OBJECT IDENTIFIER ::= { 1 3 101 113 } */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Base OID descriptor structure
+ */
+typedef struct mbedtls_oid_descriptor_t {
+ const char *MBEDTLS_PRIVATE(asn1); /*!< OID ASN.1 representation */
+ size_t MBEDTLS_PRIVATE(asn1_len); /*!< length of asn1 */
+#if !defined(MBEDTLS_X509_REMOVE_INFO)
+ const char *MBEDTLS_PRIVATE(name); /*!< official name (e.g. from RFC) */
+ const char *MBEDTLS_PRIVATE(description); /*!< human friendly description */
+#endif
+} mbedtls_oid_descriptor_t;
+
+/**
+ * \brief Translate an ASN.1 OID into its numeric representation
+ * (e.g. "\x2A\x86\x48\x86\xF7\x0D" into "1.2.840.113549")
+ *
+ * \param buf buffer to put representation in
+ * \param size size of the buffer
+ * \param oid OID to translate
+ *
+ * \return Length of the string written (excluding final NULL) or
+ * MBEDTLS_ERR_OID_BUF_TOO_SMALL in case of error
+ */
+int mbedtls_oid_get_numeric_string(char *buf, size_t size, const mbedtls_asn1_buf *oid);
+
+/**
+ * \brief Translate a string containing a dotted-decimal
+ * representation of an ASN.1 OID into its encoded form
+ * (e.g. "1.2.840.113549" into "\x2A\x86\x48\x86\xF7\x0D").
+ * On success, this function allocates oid->buf from the
+ * heap. It must be freed by the caller using mbedtls_free().
+ *
+ * \param oid #mbedtls_asn1_buf to populate with the DER-encoded OID
+ * \param oid_str string representation of the OID to parse
+ * \param size length of the OID string, not including any null terminator
+ *
+ * \return 0 if successful
+ * \return #MBEDTLS_ERR_ASN1_INVALID_DATA if \p oid_str does not
+ * represent a valid OID
+ * \return #MBEDTLS_ERR_ASN1_ALLOC_FAILED if the function fails to
+ * allocate oid->buf
+ */
+int mbedtls_oid_from_numeric_string(mbedtls_asn1_buf *oid, const char *oid_str, size_t size);
+
+/**
+ * \brief Translate an X.509 extension OID into local values
+ *
+ * \param oid OID to use
+ * \param ext_type place to store the extension type
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_x509_ext_type(const mbedtls_asn1_buf *oid, int *ext_type);
+
+/**
+ * \brief Translate an X.509 attribute type OID into the short name
+ * (e.g. the OID for an X520 Common Name into "CN")
+ *
+ * \param oid OID to use
+ * \param short_name place to store the string pointer
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_attr_short_name(const mbedtls_asn1_buf *oid, const char **short_name);
+
+/**
+ * \brief Translate PublicKeyAlgorithm OID into pk_type
+ *
+ * \param oid OID to use
+ * \param pk_alg place to store public key algorithm
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_pk_alg(const mbedtls_asn1_buf *oid, mbedtls_pk_type_t *pk_alg);
+
+/**
+ * \brief Translate pk_type into PublicKeyAlgorithm OID
+ *
+ * \param pk_alg Public key type to look for
+ * \param oid place to store ASN.1 OID string pointer
+ * \param olen length of the OID
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_oid_by_pk_alg(mbedtls_pk_type_t pk_alg,
+ const char **oid, size_t *olen);
+
+#if defined(MBEDTLS_PK_HAVE_ECC_KEYS)
+/**
+ * \brief Translate NamedCurve OID into an EC group identifier
+ *
+ * \param oid OID to use
+ * \param grp_id place to store group id
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_ec_grp(const mbedtls_asn1_buf *oid, mbedtls_ecp_group_id *grp_id);
+
+/**
+ * \brief Translate EC group identifier into NamedCurve OID
+ *
+ * \param grp_id EC group identifier
+ * \param oid place to store ASN.1 OID string pointer
+ * \param olen length of the OID
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_oid_by_ec_grp(mbedtls_ecp_group_id grp_id,
+ const char **oid, size_t *olen);
+
+/**
+ * \brief Translate AlgorithmIdentifier OID into an EC group identifier,
+ * for curves that are directly encoded at this level
+ *
+ * \param oid OID to use
+ * \param grp_id place to store group id
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_ec_grp_algid(const mbedtls_asn1_buf *oid, mbedtls_ecp_group_id *grp_id);
+
+/**
+ * \brief Translate EC group identifier into AlgorithmIdentifier OID,
+ * for curves that are directly encoded at this level
+ *
+ * \param grp_id EC group identifier
+ * \param oid place to store ASN.1 OID string pointer
+ * \param olen length of the OID
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_oid_by_ec_grp_algid(mbedtls_ecp_group_id grp_id,
+ const char **oid, size_t *olen);
+#endif /* MBEDTLS_PK_HAVE_ECC_KEYS */
+
+/**
+ * \brief Translate SignatureAlgorithm OID into md_type and pk_type
+ *
+ * \param oid OID to use
+ * \param md_alg place to store message digest algorithm
+ * \param pk_alg place to store public key algorithm
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_sig_alg(const mbedtls_asn1_buf *oid,
+ mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg);
+
+/**
+ * \brief Translate SignatureAlgorithm OID into description
+ *
+ * \param oid OID to use
+ * \param desc place to store string pointer
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_sig_alg_desc(const mbedtls_asn1_buf *oid, const char **desc);
+
+/**
+ * \brief Translate md_type and pk_type into SignatureAlgorithm OID
+ *
+ * \param md_alg message digest algorithm
+ * \param pk_alg public key algorithm
+ * \param oid place to store ASN.1 OID string pointer
+ * \param olen length of the OID
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_oid_by_sig_alg(mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,
+ const char **oid, size_t *olen);
+
+/**
+ * \brief Translate hmac algorithm OID into md_type
+ *
+ * \param oid OID to use
+ * \param md_hmac place to store message hmac algorithm
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_md_hmac(const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_hmac);
+
+/**
+ * \brief Translate hash algorithm OID into md_type
+ *
+ * \param oid OID to use
+ * \param md_alg place to store message digest algorithm
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_md_alg(const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg);
+
+#if !defined(MBEDTLS_X509_REMOVE_INFO)
+/**
+ * \brief Translate Extended Key Usage OID into description
+ *
+ * \param oid OID to use
+ * \param desc place to store string pointer
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_extended_key_usage(const mbedtls_asn1_buf *oid, const char **desc);
+#endif
+
+/**
+ * \brief Translate certificate policies OID into description
+ *
+ * \param oid OID to use
+ * \param desc place to store string pointer
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_certificate_policies(const mbedtls_asn1_buf *oid, const char **desc);
+
+/**
+ * \brief Translate md_type into hash algorithm OID
+ *
+ * \param md_alg message digest algorithm
+ * \param oid place to store ASN.1 OID string pointer
+ * \param olen length of the OID
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_oid_by_md(mbedtls_md_type_t md_alg, const char **oid, size_t *olen);
+
+#if defined(MBEDTLS_CIPHER_C)
+/**
+ * \brief Translate encryption algorithm OID into cipher_type
+ *
+ * \param oid OID to use
+ * \param cipher_alg place to store cipher algorithm
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_cipher_alg(const mbedtls_asn1_buf *oid, mbedtls_cipher_type_t *cipher_alg);
+#endif /* MBEDTLS_CIPHER_C */
+
+#if defined(MBEDTLS_PKCS12_C)
+/**
+ * \brief Translate PKCS#12 PBE algorithm OID into md_type and
+ * cipher_type
+ *
+ * \param oid OID to use
+ * \param md_alg place to store message digest algorithm
+ * \param cipher_alg place to store cipher algorithm
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND
+ */
+int mbedtls_oid_get_pkcs12_pbe_alg(const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg,
+ mbedtls_cipher_type_t *cipher_alg);
+#endif /* MBEDTLS_PKCS12_C */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* oid.h */
diff --git a/include/mbedtls/pem.h b/include/mbedtls/pem.h
new file mode 100644
index 0000000..cc617a9
--- /dev/null
+++ b/include/mbedtls/pem.h
@@ -0,0 +1,160 @@
+/**
+ * \file pem.h
+ *
+ * \brief Privacy Enhanced Mail (PEM) decoding
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_PEM_H
+#define MBEDTLS_PEM_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+
+/**
+ * \name PEM Error codes
+ * These error codes are returned in case of errors reading the
+ * PEM data.
+ * \{
+ */
+/** No PEM header or footer found. */
+#define MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT -0x1080
+/** PEM string is not as expected. */
+#define MBEDTLS_ERR_PEM_INVALID_DATA -0x1100
+/** Failed to allocate memory. */
+#define MBEDTLS_ERR_PEM_ALLOC_FAILED -0x1180
+/** RSA IV is not in hex-format. */
+#define MBEDTLS_ERR_PEM_INVALID_ENC_IV -0x1200
+/** Unsupported key encryption algorithm. */
+#define MBEDTLS_ERR_PEM_UNKNOWN_ENC_ALG -0x1280
+/** Private key password can't be empty. */
+#define MBEDTLS_ERR_PEM_PASSWORD_REQUIRED -0x1300
+/** Given private key password does not allow for correct decryption. */
+#define MBEDTLS_ERR_PEM_PASSWORD_MISMATCH -0x1380
+/** Unavailable feature, e.g. hashing/encryption combination. */
+#define MBEDTLS_ERR_PEM_FEATURE_UNAVAILABLE -0x1400
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_PEM_BAD_INPUT_DATA -0x1480
+/** \} name PEM Error codes */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(MBEDTLS_PEM_PARSE_C)
+/**
+ * \brief PEM context structure
+ */
+typedef struct mbedtls_pem_context {
+ unsigned char *MBEDTLS_PRIVATE(buf); /*!< buffer for decoded data */
+ size_t MBEDTLS_PRIVATE(buflen); /*!< length of the buffer */
+ unsigned char *MBEDTLS_PRIVATE(info); /*!< buffer for extra header information */
+}
+mbedtls_pem_context;
+
+/**
+ * \brief PEM context setup
+ *
+ * \param ctx context to be initialized
+ */
+void mbedtls_pem_init(mbedtls_pem_context *ctx);
+
+/**
+ * \brief Read a buffer for PEM information and store the resulting
+ * data into the specified context buffers.
+ *
+ * \param ctx context to use
+ * \param header header string to seek and expect
+ * \param footer footer string to seek and expect
+ * \param data source data to look in (must be nul-terminated)
+ * \param pwd password for decryption (can be NULL)
+ * \param pwdlen length of password
+ * \param use_len destination for total length used (set after header is
+ * correctly read, so unless you get
+ * MBEDTLS_ERR_PEM_BAD_INPUT_DATA or
+ * MBEDTLS_ERR_PEM_NO_HEADER_FOOTER_PRESENT, use_len is
+ * the length to skip)
+ *
+ * \note Attempts to check password correctness by verifying if
+ * the decrypted text starts with an ASN.1 sequence of
+ * appropriate length
+ *
+ * \note \c mbedtls_pem_free must be called on PEM context before
+ * the PEM context can be reused in another call to
+ * \c mbedtls_pem_read_buffer
+ *
+ * \return 0 on success, or a specific PEM error code
+ */
+int mbedtls_pem_read_buffer(mbedtls_pem_context *ctx, const char *header, const char *footer,
+ const unsigned char *data,
+ const unsigned char *pwd,
+ size_t pwdlen, size_t *use_len);
+
+/**
+ * \brief Get the pointer to the decoded binary data in a PEM context.
+ *
+ * \param ctx PEM context to access.
+ * \param buflen On success, this will contain the length of the binary data.
+ * This must be a valid (non-null) pointer.
+ *
+ * \return A pointer to the decoded binary data.
+ *
+ * \note The returned pointer remains valid only until \p ctx is
+ modified or freed.
+ */
+static inline const unsigned char *mbedtls_pem_get_buffer(mbedtls_pem_context *ctx, size_t *buflen)
+{
+ *buflen = ctx->MBEDTLS_PRIVATE(buflen);
+ return ctx->MBEDTLS_PRIVATE(buf);
+}
+
+
+/**
+ * \brief PEM context memory freeing
+ *
+ * \param ctx context to be freed
+ */
+void mbedtls_pem_free(mbedtls_pem_context *ctx);
+#endif /* MBEDTLS_PEM_PARSE_C */
+
+#if defined(MBEDTLS_PEM_WRITE_C)
+/**
+ * \brief Write a buffer of PEM information from a DER encoded
+ * buffer.
+ *
+ * \param header The header string to write.
+ * \param footer The footer string to write.
+ * \param der_data The DER data to encode.
+ * \param der_len The length of the DER data \p der_data in Bytes.
+ * \param buf The buffer to write to.
+ * \param buf_len The length of the output buffer \p buf in Bytes.
+ * \param olen The address at which to store the total length written
+ * or required (if \p buf_len is not enough).
+ *
+ * \note You may pass \c NULL for \p buf and \c 0 for \p buf_len
+ * to request the length of the resulting PEM buffer in
+ * `*olen`.
+ *
+ * \note This function may be called with overlapping \p der_data
+ * and \p buf buffers.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_BASE64_BUFFER_TOO_SMALL if \p buf isn't large
+ * enough to hold the PEM buffer. In this case, `*olen` holds
+ * the required minimum size of \p buf.
+ * \return Another PEM or BASE64 error code on other kinds of failure.
+ */
+int mbedtls_pem_write_buffer(const char *header, const char *footer,
+ const unsigned char *der_data, size_t der_len,
+ unsigned char *buf, size_t buf_len, size_t *olen);
+#endif /* MBEDTLS_PEM_WRITE_C */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* pem.h */
diff --git a/include/mbedtls/pk.h b/include/mbedtls/pk.h
new file mode 100644
index 0000000..24b1188
--- /dev/null
+++ b/include/mbedtls/pk.h
@@ -0,0 +1,1091 @@
+/**
+ * \file pk.h
+ *
+ * \brief Public Key abstraction layer
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_PK_H
+#define MBEDTLS_PK_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/md.h"
+
+#if defined(MBEDTLS_RSA_C)
+#include "mbedtls/rsa.h"
+#endif
+
+#if defined(MBEDTLS_ECP_C)
+#include "mbedtls/ecp.h"
+#endif
+
+#if defined(MBEDTLS_ECDSA_C)
+#include "mbedtls/ecdsa.h"
+#endif
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO) || defined(MBEDTLS_PSA_CRYPTO_C)
+#include "psa/crypto.h"
+#endif
+
+/** Memory allocation failed. */
+#define MBEDTLS_ERR_PK_ALLOC_FAILED -0x3F80
+/** Type mismatch, eg attempt to encrypt with an ECDSA key */
+#define MBEDTLS_ERR_PK_TYPE_MISMATCH -0x3F00
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_PK_BAD_INPUT_DATA -0x3E80
+/** Read/write of file failed. */
+#define MBEDTLS_ERR_PK_FILE_IO_ERROR -0x3E00
+/** Unsupported key version */
+#define MBEDTLS_ERR_PK_KEY_INVALID_VERSION -0x3D80
+/** Invalid key tag or value. */
+#define MBEDTLS_ERR_PK_KEY_INVALID_FORMAT -0x3D00
+/** Key algorithm is unsupported (only RSA and EC are supported). */
+#define MBEDTLS_ERR_PK_UNKNOWN_PK_ALG -0x3C80
+/** Private key password can't be empty. */
+#define MBEDTLS_ERR_PK_PASSWORD_REQUIRED -0x3C00
+/** Given private key password does not allow for correct decryption. */
+#define MBEDTLS_ERR_PK_PASSWORD_MISMATCH -0x3B80
+/** The pubkey tag or value is invalid (only RSA and EC are supported). */
+#define MBEDTLS_ERR_PK_INVALID_PUBKEY -0x3B00
+/** The algorithm tag or value is invalid. */
+#define MBEDTLS_ERR_PK_INVALID_ALG -0x3A80
+/** Elliptic curve is unsupported (only NIST curves are supported). */
+#define MBEDTLS_ERR_PK_UNKNOWN_NAMED_CURVE -0x3A00
+/** Unavailable feature, e.g. RSA disabled for RSA key. */
+#define MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE -0x3980
+/** The buffer contains a valid signature followed by more data. */
+#define MBEDTLS_ERR_PK_SIG_LEN_MISMATCH -0x3900
+/** The output buffer is too small. */
+#define MBEDTLS_ERR_PK_BUFFER_TOO_SMALL -0x3880
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Public key types
+ */
+typedef enum {
+ MBEDTLS_PK_NONE=0,
+ MBEDTLS_PK_RSA,
+ MBEDTLS_PK_ECKEY,
+ MBEDTLS_PK_ECKEY_DH,
+ MBEDTLS_PK_ECDSA,
+ MBEDTLS_PK_RSA_ALT,
+ MBEDTLS_PK_RSASSA_PSS,
+ MBEDTLS_PK_OPAQUE,
+} mbedtls_pk_type_t;
+
+/**
+ * \brief Options for RSASSA-PSS signature verification.
+ * See \c mbedtls_rsa_rsassa_pss_verify_ext()
+ */
+typedef struct mbedtls_pk_rsassa_pss_options {
+ /** The digest to use for MGF1 in PSS.
+ *
+ * \note When #MBEDTLS_USE_PSA_CRYPTO is enabled and #MBEDTLS_RSA_C is
+ * disabled, this must be equal to the \c md_alg argument passed
+ * to mbedtls_pk_verify_ext(). In a future version of the library,
+ * this constraint may apply whenever #MBEDTLS_USE_PSA_CRYPTO is
+ * enabled regardless of the status of #MBEDTLS_RSA_C.
+ */
+ mbedtls_md_type_t mgf1_hash_id;
+
+ /** The expected length of the salt, in bytes. This may be
+ * #MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length.
+ *
+ * \note When #MBEDTLS_USE_PSA_CRYPTO is enabled, only
+ * #MBEDTLS_RSA_SALT_LEN_ANY is valid. Any other value may be
+ * ignored (allowing any salt length).
+ */
+ int expected_salt_len;
+
+} mbedtls_pk_rsassa_pss_options;
+
+/**
+ * \brief Maximum size of a signature made by mbedtls_pk_sign().
+ */
+/* We need to set MBEDTLS_PK_SIGNATURE_MAX_SIZE to the maximum signature
+ * size among the supported signature types. Do it by starting at 0,
+ * then incrementally increasing to be large enough for each supported
+ * signature mechanism.
+ *
+ * The resulting value can be 0, for example if MBEDTLS_ECDH_C is enabled
+ * (which allows the pk module to be included) but neither MBEDTLS_ECDSA_C
+ * nor MBEDTLS_RSA_C nor any opaque signature mechanism (PSA or RSA_ALT).
+ */
+#define MBEDTLS_PK_SIGNATURE_MAX_SIZE 0
+
+#if (defined(MBEDTLS_RSA_C) || defined(MBEDTLS_PK_RSA_ALT_SUPPORT)) && \
+ MBEDTLS_MPI_MAX_SIZE > MBEDTLS_PK_SIGNATURE_MAX_SIZE
+/* For RSA, the signature can be as large as the bignum module allows.
+ * For RSA_ALT, the signature size is not necessarily tied to what the
+ * bignum module can do, but in the absence of any specific setting,
+ * we use that (rsa_alt_sign_wrap in library/pk_wrap.h will check). */
+#undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
+#define MBEDTLS_PK_SIGNATURE_MAX_SIZE MBEDTLS_MPI_MAX_SIZE
+#endif
+
+#if defined(MBEDTLS_ECDSA_C) && \
+ MBEDTLS_ECDSA_MAX_LEN > MBEDTLS_PK_SIGNATURE_MAX_SIZE
+/* For ECDSA, the ecdsa module exports a constant for the maximum
+ * signature size. */
+#undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
+#define MBEDTLS_PK_SIGNATURE_MAX_SIZE MBEDTLS_ECDSA_MAX_LEN
+#endif
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#if PSA_SIGNATURE_MAX_SIZE > MBEDTLS_PK_SIGNATURE_MAX_SIZE
+/* PSA_SIGNATURE_MAX_SIZE is the maximum size of a signature made
+ * through the PSA API in the PSA representation. */
+#undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
+#define MBEDTLS_PK_SIGNATURE_MAX_SIZE PSA_SIGNATURE_MAX_SIZE
+#endif
+
+#if PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE + 11 > MBEDTLS_PK_SIGNATURE_MAX_SIZE
+/* The Mbed TLS representation is different for ECDSA signatures:
+ * PSA uses the raw concatenation of r and s,
+ * whereas Mbed TLS uses the ASN.1 representation (SEQUENCE of two INTEGERs).
+ * Add the overhead of ASN.1: up to (1+2) + 2 * (1+2+1) for the
+ * types, lengths (represented by up to 2 bytes), and potential leading
+ * zeros of the INTEGERs and the SEQUENCE. */
+#undef MBEDTLS_PK_SIGNATURE_MAX_SIZE
+#define MBEDTLS_PK_SIGNATURE_MAX_SIZE (PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE + 11)
+#endif
+#endif /* defined(MBEDTLS_USE_PSA_CRYPTO) */
+
+/* Internal helper to define which fields in the pk_context structure below
+ * should be used for EC keys: legacy ecp_keypair or the raw (PSA friendly)
+ * format. It should be noted that this only affects how data is stored, not
+ * which functions are used for various operations. The overall picture looks
+ * like this:
+ * - if USE_PSA is not defined and ECP_C is defined then use ecp_keypair data
+ * structure and legacy functions
+ * - if USE_PSA is defined and
+ * - if ECP_C then use ecp_keypair structure, convert data to a PSA friendly
+ * format and use PSA functions
+ * - if !ECP_C then use new raw data and PSA functions directly.
+ *
+ * The main reason for the "intermediate" (USE_PSA + ECP_C) above is that as long
+ * as ECP_C is defined mbedtls_pk_ec() gives the user a read/write access to the
+ * ecp_keypair structure inside the pk_context so they can modify it using
+ * ECP functions which are not under PK module's control.
+ */
+#if defined(MBEDTLS_USE_PSA_CRYPTO) && defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) && \
+ !defined(MBEDTLS_ECP_C)
+#define MBEDTLS_PK_USE_PSA_EC_DATA
+#endif
+
+/* Helper symbol to state that the PK module has support for EC keys. This
+ * can either be provided through the legacy ECP solution or through the
+ * PSA friendly MBEDTLS_PK_USE_PSA_EC_DATA. */
+#if defined(MBEDTLS_PK_USE_PSA_EC_DATA) || defined(MBEDTLS_ECP_C)
+#define MBEDTLS_PK_HAVE_ECC_KEYS
+#endif /* MBEDTLS_PK_USE_PSA_EC_DATA || MBEDTLS_ECP_C */
+
+/**
+ * \brief Types for interfacing with the debug module
+ */
+typedef enum {
+ MBEDTLS_PK_DEBUG_NONE = 0,
+ MBEDTLS_PK_DEBUG_MPI,
+ MBEDTLS_PK_DEBUG_ECP,
+ MBEDTLS_PK_DEBUG_PSA_EC,
+} mbedtls_pk_debug_type;
+
+/**
+ * \brief Item to send to the debug module
+ */
+typedef struct mbedtls_pk_debug_item {
+ mbedtls_pk_debug_type MBEDTLS_PRIVATE(type);
+ const char *MBEDTLS_PRIVATE(name);
+ void *MBEDTLS_PRIVATE(value);
+} mbedtls_pk_debug_item;
+
+/** Maximum number of item send for debugging, plus 1 */
+#define MBEDTLS_PK_DEBUG_MAX_ITEMS 3
+
+/**
+ * \brief Public key information and operations
+ *
+ * \note The library does not support custom pk info structures,
+ * only built-in structures returned by
+ * mbedtls_cipher_info_from_type().
+ */
+typedef struct mbedtls_pk_info_t mbedtls_pk_info_t;
+
+#define MBEDTLS_PK_MAX_EC_PUBKEY_RAW_LEN \
+ PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)
+/**
+ * \brief Public key container
+ */
+typedef struct mbedtls_pk_context {
+ const mbedtls_pk_info_t *MBEDTLS_PRIVATE(pk_info); /**< Public key information */
+ void *MBEDTLS_PRIVATE(pk_ctx); /**< Underlying public key context */
+ /* The following field is used to store the ID of a private key in the
+ * following cases:
+ * - opaque key when MBEDTLS_PSA_CRYPTO_C is defined
+ * - normal key when MBEDTLS_PK_USE_PSA_EC_DATA is defined. In this case:
+ * - the pk_ctx above is not not used to store the private key anymore.
+ * Actually that field not populated at all in this case because also
+ * the public key will be stored in raw format as explained below
+ * - this ID is used for all private key operations (ex: sign, check
+ * key pair, key write, etc) using PSA functions
+ *
+ * Note: this private key storing solution only affects EC keys, not the
+ * other ones. The latters still use the pk_ctx to store their own
+ * context.
+ *
+ * Note: this priv_id is guarded by MBEDTLS_PSA_CRYPTO_C and not by
+ * MBEDTLS_PK_USE_PSA_EC_DATA (as the public counterpart below) because,
+ * when working with opaque keys, it can be used also in
+ * mbedtls_pk_sign_ext for RSA keys. */
+#if defined(MBEDTLS_PSA_CRYPTO_C)
+ mbedtls_svc_key_id_t MBEDTLS_PRIVATE(priv_id); /**< Key ID for opaque keys */
+#endif /* MBEDTLS_PSA_CRYPTO_C */
+ /* The following fields are meant for storing the public key in raw format
+ * which is handy for:
+ * - easily importing it into the PSA context
+ * - reducing the ECP module dependencies in the PK one.
+ *
+ * When MBEDTLS_PK_USE_PSA_EC_DATA is enabled:
+ * - the pk_ctx above is not used anymore for storing the public key
+ * inside the ecp_keypair structure
+ * - the following fields are used for all public key operations: signature
+ * verify, key pair check and key write.
+ * Of course, when MBEDTLS_PK_USE_PSA_EC_DATA is not enabled, the legacy
+ * ecp_keypair structure is used for storing the public key and performing
+ * all the operations.
+ *
+ * Note: This new public key storing solution only works for EC keys, not
+ * other ones. The latters still use pk_ctx to store their own
+ * context.
+ */
+#if defined(MBEDTLS_PK_USE_PSA_EC_DATA)
+ uint8_t MBEDTLS_PRIVATE(pub_raw)[MBEDTLS_PK_MAX_EC_PUBKEY_RAW_LEN]; /**< Raw public key */
+ size_t MBEDTLS_PRIVATE(pub_raw_len); /**< Valid bytes in "pub_raw" */
+ psa_ecc_family_t MBEDTLS_PRIVATE(ec_family); /**< EC family of pk */
+ size_t MBEDTLS_PRIVATE(ec_bits); /**< Curve's bits of pk */
+#endif /* MBEDTLS_PK_USE_PSA_EC_DATA */
+} mbedtls_pk_context;
+
+#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
+/**
+ * \brief Context for resuming operations
+ */
+typedef struct {
+ const mbedtls_pk_info_t *MBEDTLS_PRIVATE(pk_info); /**< Public key information */
+ void *MBEDTLS_PRIVATE(rs_ctx); /**< Underlying restart context */
+} mbedtls_pk_restart_ctx;
+#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
+/* Now we can declare functions that take a pointer to that */
+typedef void mbedtls_pk_restart_ctx;
+#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
+
+#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
+/**
+ * \brief Types for RSA-alt abstraction
+ */
+typedef int (*mbedtls_pk_rsa_alt_decrypt_func)(void *ctx, size_t *olen,
+ const unsigned char *input, unsigned char *output,
+ size_t output_max_len);
+typedef int (*mbedtls_pk_rsa_alt_sign_func)(void *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ mbedtls_md_type_t md_alg, unsigned int hashlen,
+ const unsigned char *hash, unsigned char *sig);
+typedef size_t (*mbedtls_pk_rsa_alt_key_len_func)(void *ctx);
+#endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
+
+/**
+ * \brief Return information associated with the given PK type
+ *
+ * \param pk_type PK type to search for.
+ *
+ * \return The PK info associated with the type or NULL if not found.
+ */
+const mbedtls_pk_info_t *mbedtls_pk_info_from_type(mbedtls_pk_type_t pk_type);
+
+/**
+ * \brief Initialize a #mbedtls_pk_context (as NONE).
+ *
+ * \param ctx The context to initialize.
+ * This must not be \c NULL.
+ */
+void mbedtls_pk_init(mbedtls_pk_context *ctx);
+
+/**
+ * \brief Free the components of a #mbedtls_pk_context.
+ *
+ * \param ctx The context to clear. It must have been initialized.
+ * If this is \c NULL, this function does nothing.
+ *
+ * \note For contexts that have been set up with
+ * mbedtls_pk_setup_opaque(), this does not free the underlying
+ * PSA key and you still need to call psa_destroy_key()
+ * independently if you want to destroy that key.
+ */
+void mbedtls_pk_free(mbedtls_pk_context *ctx);
+
+#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
+/**
+ * \brief Initialize a restart context
+ *
+ * \param ctx The context to initialize.
+ * This must not be \c NULL.
+ */
+void mbedtls_pk_restart_init(mbedtls_pk_restart_ctx *ctx);
+
+/**
+ * \brief Free the components of a restart context
+ *
+ * \param ctx The context to clear. It must have been initialized.
+ * If this is \c NULL, this function does nothing.
+ */
+void mbedtls_pk_restart_free(mbedtls_pk_restart_ctx *ctx);
+#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
+
+/**
+ * \brief Initialize a PK context with the information given
+ * and allocates the type-specific PK subcontext.
+ *
+ * \param ctx Context to initialize. It must not have been set
+ * up yet (type #MBEDTLS_PK_NONE).
+ * \param info Information to use
+ *
+ * \return 0 on success,
+ * MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input,
+ * MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure.
+ *
+ * \note For contexts holding an RSA-alt key, use
+ * \c mbedtls_pk_setup_rsa_alt() instead.
+ */
+int mbedtls_pk_setup(mbedtls_pk_context *ctx, const mbedtls_pk_info_t *info);
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+/**
+ * \brief Initialize a PK context to wrap a PSA key.
+ *
+ * \note This function replaces mbedtls_pk_setup() for contexts
+ * that wrap a (possibly opaque) PSA key instead of
+ * storing and manipulating the key material directly.
+ *
+ * \param ctx The context to initialize. It must be empty (type NONE).
+ * \param key The PSA key to wrap, which must hold an ECC or RSA key
+ * pair (see notes below).
+ *
+ * \note The wrapped key must remain valid as long as the
+ * wrapping PK context is in use, that is at least between
+ * the point this function is called and the point
+ * mbedtls_pk_free() is called on this context. The wrapped
+ * key might then be independently used or destroyed.
+ *
+ * \note This function is currently only available for ECC or RSA
+ * key pairs (that is, keys containing private key material).
+ * Support for other key types may be added later.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_PK_BAD_INPUT_DATA on invalid input
+ * (context already used, invalid key identifier).
+ * \return #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the key is not an
+ * ECC key pair.
+ * \return #MBEDTLS_ERR_PK_ALLOC_FAILED on allocation failure.
+ */
+int mbedtls_pk_setup_opaque(mbedtls_pk_context *ctx,
+ const mbedtls_svc_key_id_t key);
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
+#if defined(MBEDTLS_PK_RSA_ALT_SUPPORT)
+/**
+ * \brief Initialize an RSA-alt context
+ *
+ * \param ctx Context to initialize. It must not have been set
+ * up yet (type #MBEDTLS_PK_NONE).
+ * \param key RSA key pointer
+ * \param decrypt_func Decryption function
+ * \param sign_func Signing function
+ * \param key_len_func Function returning key length in bytes
+ *
+ * \return 0 on success, or MBEDTLS_ERR_PK_BAD_INPUT_DATA if the
+ * context wasn't already initialized as RSA_ALT.
+ *
+ * \note This function replaces \c mbedtls_pk_setup() for RSA-alt.
+ */
+int mbedtls_pk_setup_rsa_alt(mbedtls_pk_context *ctx, void *key,
+ mbedtls_pk_rsa_alt_decrypt_func decrypt_func,
+ mbedtls_pk_rsa_alt_sign_func sign_func,
+ mbedtls_pk_rsa_alt_key_len_func key_len_func);
+#endif /* MBEDTLS_PK_RSA_ALT_SUPPORT */
+
+/**
+ * \brief Get the size in bits of the underlying key
+ *
+ * \param ctx The context to query. It must have been initialized.
+ *
+ * \return Key size in bits, or 0 on error
+ */
+size_t mbedtls_pk_get_bitlen(const mbedtls_pk_context *ctx);
+
+/**
+ * \brief Get the length in bytes of the underlying key
+ *
+ * \param ctx The context to query. It must have been initialized.
+ *
+ * \return Key length in bytes, or 0 on error
+ */
+static inline size_t mbedtls_pk_get_len(const mbedtls_pk_context *ctx)
+{
+ return (mbedtls_pk_get_bitlen(ctx) + 7) / 8;
+}
+
+/**
+ * \brief Tell if a context can do the operation given by type
+ *
+ * \param ctx The context to query. It must have been initialized.
+ * \param type The desired type.
+ *
+ * \return 1 if the context can do operations on the given type.
+ * \return 0 if the context cannot do the operations on the given
+ * type. This is always the case for a context that has
+ * been initialized but not set up, or that has been
+ * cleared with mbedtls_pk_free().
+ */
+int mbedtls_pk_can_do(const mbedtls_pk_context *ctx, mbedtls_pk_type_t type);
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+/**
+ * \brief Tell if context can do the operation given by PSA algorithm
+ *
+ * \param ctx The context to query. It must have been initialized.
+ * \param alg PSA algorithm to check against, the following are allowed:
+ * PSA_ALG_RSA_PKCS1V15_SIGN(hash),
+ * PSA_ALG_RSA_PSS(hash),
+ * PSA_ALG_RSA_PKCS1V15_CRYPT,
+ * PSA_ALG_ECDSA(hash),
+ * PSA_ALG_ECDH, where hash is a specific hash.
+ * \param usage PSA usage flag to check against, must be composed of:
+ * PSA_KEY_USAGE_SIGN_HASH
+ * PSA_KEY_USAGE_DECRYPT
+ * PSA_KEY_USAGE_DERIVE.
+ * Context key must match all passed usage flags.
+ *
+ * \warning Since the set of allowed algorithms and usage flags may be
+ * expanded in the future, the return value \c 0 should not
+ * be taken in account for non-allowed algorithms and usage
+ * flags.
+ *
+ * \return 1 if the context can do operations on the given type.
+ * \return 0 if the context cannot do the operations on the given
+ * type, for non-allowed algorithms and usage flags, or
+ * for a context that has been initialized but not set up
+ * or that has been cleared with mbedtls_pk_free().
+ */
+int mbedtls_pk_can_do_ext(const mbedtls_pk_context *ctx, psa_algorithm_t alg,
+ psa_key_usage_t usage);
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
+/**
+ * \brief Verify signature (including padding if relevant).
+ *
+ * \param ctx The PK context to use. It must have been set up.
+ * \param md_alg Hash algorithm used.
+ * This can be #MBEDTLS_MD_NONE if the signature algorithm
+ * does not rely on a hash algorithm (non-deterministic
+ * ECDSA, RSA PKCS#1 v1.5).
+ * For PKCS#1 v1.5, if \p md_alg is #MBEDTLS_MD_NONE, then
+ * \p hash is the DigestInfo structure used by RFC 8017
+ * &sect;9.2 steps 3&ndash;6. If \p md_alg is a valid hash
+ * algorithm then \p hash is the digest itself, and this
+ * function calculates the DigestInfo encoding internally.
+ * \param hash Hash of the message to sign
+ * \param hash_len Hash length
+ * \param sig Signature to verify
+ * \param sig_len Signature length
+ *
+ * \return 0 on success (signature is valid),
+ * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
+ * signature in \p sig but its length is less than \p sig_len,
+ * or a specific error code.
+ *
+ * \note For RSA keys, the default padding type is PKCS#1 v1.5.
+ * Use \c mbedtls_pk_verify_ext( MBEDTLS_PK_RSASSA_PSS, ... )
+ * to verify RSASSA_PSS signatures.
+ */
+int mbedtls_pk_verify(mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
+ const unsigned char *hash, size_t hash_len,
+ const unsigned char *sig, size_t sig_len);
+
+/**
+ * \brief Restartable version of \c mbedtls_pk_verify()
+ *
+ * \note Performs the same job as \c mbedtls_pk_verify(), but can
+ * return early and restart according to the limit set with
+ * \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC
+ * operations. For RSA, same as \c mbedtls_pk_verify().
+ *
+ * \param ctx The PK context to use. It must have been set up.
+ * \param md_alg Hash algorithm used (see notes)
+ * \param hash Hash of the message to sign
+ * \param hash_len Hash length or 0 (see notes)
+ * \param sig Signature to verify
+ * \param sig_len Signature length
+ * \param rs_ctx Restart context (NULL to disable restart)
+ *
+ * \return See \c mbedtls_pk_verify(), or
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ */
+int mbedtls_pk_verify_restartable(mbedtls_pk_context *ctx,
+ mbedtls_md_type_t md_alg,
+ const unsigned char *hash, size_t hash_len,
+ const unsigned char *sig, size_t sig_len,
+ mbedtls_pk_restart_ctx *rs_ctx);
+
+/**
+ * \brief Verify signature, with options.
+ * (Includes verification of the padding depending on type.)
+ *
+ * \param type Signature type (inc. possible padding type) to verify
+ * \param options Pointer to type-specific options, or NULL
+ * \param ctx The PK context to use. It must have been set up.
+ * \param md_alg Hash algorithm used (see notes)
+ * \param hash Hash of the message to sign
+ * \param hash_len Hash length or 0 (see notes)
+ * \param sig Signature to verify
+ * \param sig_len Signature length
+ *
+ * \return 0 on success (signature is valid),
+ * #MBEDTLS_ERR_PK_TYPE_MISMATCH if the PK context can't be
+ * used for this type of signatures,
+ * #MBEDTLS_ERR_PK_SIG_LEN_MISMATCH if there is a valid
+ * signature in \p sig but its length is less than \p sig_len,
+ * or a specific error code.
+ *
+ * \note If hash_len is 0, then the length associated with md_alg
+ * is used instead, or an error returned if it is invalid.
+ *
+ * \note md_alg may be MBEDTLS_MD_NONE, only if hash_len != 0
+ *
+ * \note If type is MBEDTLS_PK_RSASSA_PSS, then options must point
+ * to a mbedtls_pk_rsassa_pss_options structure,
+ * otherwise it must be NULL. Note that if
+ * #MBEDTLS_USE_PSA_CRYPTO is defined, the salt length is not
+ * verified as PSA_ALG_RSA_PSS_ANY_SALT is used.
+ */
+int mbedtls_pk_verify_ext(mbedtls_pk_type_t type, const void *options,
+ mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
+ const unsigned char *hash, size_t hash_len,
+ const unsigned char *sig, size_t sig_len);
+
+/**
+ * \brief Make signature, including padding if relevant.
+ *
+ * \param ctx The PK context to use. It must have been set up
+ * with a private key.
+ * \param md_alg Hash algorithm used (see notes)
+ * \param hash Hash of the message to sign
+ * \param hash_len Hash length
+ * \param sig Place to write the signature.
+ * It must have enough room for the signature.
+ * #MBEDTLS_PK_SIGNATURE_MAX_SIZE is always enough.
+ * You may use a smaller buffer if it is large enough
+ * given the key type.
+ * \param sig_size The size of the \p sig buffer in bytes.
+ * \param sig_len On successful return,
+ * the number of bytes written to \p sig.
+ * \param f_rng RNG function, must not be \c NULL.
+ * \param p_rng RNG parameter
+ *
+ * \return 0 on success, or a specific error code.
+ *
+ * \note For RSA keys, the default padding type is PKCS#1 v1.5.
+ * There is no interface in the PK module to make RSASSA-PSS
+ * signatures yet.
+ *
+ * \note For RSA, md_alg may be MBEDTLS_MD_NONE if hash_len != 0.
+ * For ECDSA, md_alg may never be MBEDTLS_MD_NONE.
+ */
+int mbedtls_pk_sign(mbedtls_pk_context *ctx, mbedtls_md_type_t md_alg,
+ const unsigned char *hash, size_t hash_len,
+ unsigned char *sig, size_t sig_size, size_t *sig_len,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
+
+#if defined(MBEDTLS_PSA_CRYPTO_C)
+/**
+ * \brief Make signature given a signature type.
+ *
+ * \param pk_type Signature type.
+ * \param ctx The PK context to use. It must have been set up
+ * with a private key.
+ * \param md_alg Hash algorithm used (see notes)
+ * \param hash Hash of the message to sign
+ * \param hash_len Hash length
+ * \param sig Place to write the signature.
+ * It must have enough room for the signature.
+ * #MBEDTLS_PK_SIGNATURE_MAX_SIZE is always enough.
+ * You may use a smaller buffer if it is large enough
+ * given the key type.
+ * \param sig_size The size of the \p sig buffer in bytes.
+ * \param sig_len On successful return,
+ * the number of bytes written to \p sig.
+ * \param f_rng RNG function, must not be \c NULL.
+ * \param p_rng RNG parameter
+ *
+ * \return 0 on success, or a specific error code.
+ *
+ * \note When \p pk_type is #MBEDTLS_PK_RSASSA_PSS,
+ * see #PSA_ALG_RSA_PSS for a description of PSS options used.
+ *
+ * \note For RSA, md_alg may be MBEDTLS_MD_NONE if hash_len != 0.
+ * For ECDSA, md_alg may never be MBEDTLS_MD_NONE.
+ *
+ */
+int mbedtls_pk_sign_ext(mbedtls_pk_type_t pk_type,
+ mbedtls_pk_context *ctx,
+ mbedtls_md_type_t md_alg,
+ const unsigned char *hash, size_t hash_len,
+ unsigned char *sig, size_t sig_size, size_t *sig_len,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+#endif /* MBEDTLS_PSA_CRYPTO_C */
+
+/**
+ * \brief Restartable version of \c mbedtls_pk_sign()
+ *
+ * \note Performs the same job as \c mbedtls_pk_sign(), but can
+ * return early and restart according to the limit set with
+ * \c mbedtls_ecp_set_max_ops() to reduce blocking for ECC
+ * operations. For RSA, same as \c mbedtls_pk_sign().
+ *
+ * \param ctx The PK context to use. It must have been set up
+ * with a private key.
+ * \param md_alg Hash algorithm used (see notes for mbedtls_pk_sign())
+ * \param hash Hash of the message to sign
+ * \param hash_len Hash length
+ * \param sig Place to write the signature.
+ * It must have enough room for the signature.
+ * #MBEDTLS_PK_SIGNATURE_MAX_SIZE is always enough.
+ * You may use a smaller buffer if it is large enough
+ * given the key type.
+ * \param sig_size The size of the \p sig buffer in bytes.
+ * \param sig_len On successful return,
+ * the number of bytes written to \p sig.
+ * \param f_rng RNG function, must not be \c NULL.
+ * \param p_rng RNG parameter
+ * \param rs_ctx Restart context (NULL to disable restart)
+ *
+ * \return See \c mbedtls_pk_sign().
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ */
+int mbedtls_pk_sign_restartable(mbedtls_pk_context *ctx,
+ mbedtls_md_type_t md_alg,
+ const unsigned char *hash, size_t hash_len,
+ unsigned char *sig, size_t sig_size, size_t *sig_len,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
+ mbedtls_pk_restart_ctx *rs_ctx);
+
+/**
+ * \brief Decrypt message (including padding if relevant).
+ *
+ * \param ctx The PK context to use. It must have been set up
+ * with a private key.
+ * \param input Input to decrypt
+ * \param ilen Input size
+ * \param output Decrypted output
+ * \param olen Decrypted message length
+ * \param osize Size of the output buffer
+ * \param f_rng RNG function, must not be \c NULL.
+ * \param p_rng RNG parameter
+ *
+ * \note For RSA keys, the default padding type is PKCS#1 v1.5.
+ *
+ * \return 0 on success, or a specific error code.
+ */
+int mbedtls_pk_decrypt(mbedtls_pk_context *ctx,
+ const unsigned char *input, size_t ilen,
+ unsigned char *output, size_t *olen, size_t osize,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
+
+/**
+ * \brief Encrypt message (including padding if relevant).
+ *
+ * \param ctx The PK context to use. It must have been set up.
+ * \param input Message to encrypt
+ * \param ilen Message size
+ * \param output Encrypted output
+ * \param olen Encrypted output length
+ * \param osize Size of the output buffer
+ * \param f_rng RNG function, must not be \c NULL.
+ * \param p_rng RNG parameter
+ *
+ * \note \p f_rng is used for padding generation.
+ *
+ * \note For RSA keys, the default padding type is PKCS#1 v1.5.
+ *
+ * \return 0 on success, or a specific error code.
+ */
+int mbedtls_pk_encrypt(mbedtls_pk_context *ctx,
+ const unsigned char *input, size_t ilen,
+ unsigned char *output, size_t *olen, size_t osize,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
+
+/**
+ * \brief Check if a public-private pair of keys matches.
+ *
+ * \param pub Context holding a public key.
+ * \param prv Context holding a private (and public) key.
+ * \param f_rng RNG function, must not be \c NULL.
+ * \param p_rng RNG parameter
+ *
+ * \return \c 0 on success (keys were checked and match each other).
+ * \return #MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE if the keys could not
+ * be checked - in that case they may or may not match.
+ * \return #MBEDTLS_ERR_PK_BAD_INPUT_DATA if a context is invalid.
+ * \return Another non-zero value if the keys do not match.
+ */
+int mbedtls_pk_check_pair(const mbedtls_pk_context *pub,
+ const mbedtls_pk_context *prv,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief Export debug information
+ *
+ * \param ctx The PK context to use. It must have been initialized.
+ * \param items Place to write debug items
+ *
+ * \return 0 on success or MBEDTLS_ERR_PK_BAD_INPUT_DATA
+ */
+int mbedtls_pk_debug(const mbedtls_pk_context *ctx, mbedtls_pk_debug_item *items);
+
+/**
+ * \brief Access the type name
+ *
+ * \param ctx The PK context to use. It must have been initialized.
+ *
+ * \return Type name on success, or "invalid PK"
+ */
+const char *mbedtls_pk_get_name(const mbedtls_pk_context *ctx);
+
+/**
+ * \brief Get the key type
+ *
+ * \param ctx The PK context to use. It must have been initialized.
+ *
+ * \return Type on success.
+ * \return #MBEDTLS_PK_NONE for a context that has not been set up.
+ */
+mbedtls_pk_type_t mbedtls_pk_get_type(const mbedtls_pk_context *ctx);
+
+#if defined(MBEDTLS_RSA_C)
+/**
+ * Quick access to an RSA context inside a PK context.
+ *
+ * \warning This function can only be used when the type of the context, as
+ * returned by mbedtls_pk_get_type(), is #MBEDTLS_PK_RSA.
+ * Ensuring that is the caller's responsibility.
+ * Alternatively, you can check whether this function returns NULL.
+ *
+ * \return The internal RSA context held by the PK context, or NULL.
+ */
+static inline mbedtls_rsa_context *mbedtls_pk_rsa(const mbedtls_pk_context pk)
+{
+ switch (mbedtls_pk_get_type(&pk)) {
+ case MBEDTLS_PK_RSA:
+ return (mbedtls_rsa_context *) (pk).MBEDTLS_PRIVATE(pk_ctx);
+ default:
+ return NULL;
+ }
+}
+#endif /* MBEDTLS_RSA_C */
+
+#if defined(MBEDTLS_ECP_C)
+/**
+ * Quick access to an EC context inside a PK context.
+ *
+ * \warning This function can only be used when the type of the context, as
+ * returned by mbedtls_pk_get_type(), is #MBEDTLS_PK_ECKEY,
+ * #MBEDTLS_PK_ECKEY_DH, or #MBEDTLS_PK_ECDSA.
+ * Ensuring that is the caller's responsibility.
+ * Alternatively, you can check whether this function returns NULL.
+ *
+ * \return The internal EC context held by the PK context, or NULL.
+ */
+static inline mbedtls_ecp_keypair *mbedtls_pk_ec(const mbedtls_pk_context pk)
+{
+ switch (mbedtls_pk_get_type(&pk)) {
+ case MBEDTLS_PK_ECKEY:
+ case MBEDTLS_PK_ECKEY_DH:
+ case MBEDTLS_PK_ECDSA:
+ return (mbedtls_ecp_keypair *) (pk).MBEDTLS_PRIVATE(pk_ctx);
+ default:
+ return NULL;
+ }
+}
+#endif /* MBEDTLS_ECP_C */
+
+#if defined(MBEDTLS_PK_PARSE_C)
+/** \ingroup pk_module */
+/**
+ * \brief Parse a private key in PEM or DER format
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param ctx The PK context to fill. It must have been initialized
+ * but not set up.
+ * \param key Input buffer to parse.
+ * The buffer must contain the input exactly, with no
+ * extra trailing material. For PEM, the buffer must
+ * contain a null-terminated string.
+ * \param keylen Size of \b key in bytes.
+ * For PEM data, this includes the terminating null byte,
+ * so \p keylen must be equal to `strlen(key) + 1`.
+ * \param pwd Optional password for decryption.
+ * Pass \c NULL if expecting a non-encrypted key.
+ * Pass a string of \p pwdlen bytes if expecting an encrypted
+ * key; a non-encrypted key will also be accepted.
+ * The empty password is not supported.
+ * \param pwdlen Size of the password in bytes.
+ * Ignored if \p pwd is \c NULL.
+ * \param f_rng RNG function, must not be \c NULL. Used for blinding.
+ * \param p_rng RNG parameter
+ *
+ * \note On entry, ctx must be empty, either freshly initialised
+ * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
+ * specific key type, check the result with mbedtls_pk_can_do().
+ *
+ * \note The key is also checked for correctness.
+ *
+ * \return 0 if successful, or a specific PK or PEM error code
+ */
+int mbedtls_pk_parse_key(mbedtls_pk_context *ctx,
+ const unsigned char *key, size_t keylen,
+ const unsigned char *pwd, size_t pwdlen,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
+
+/** \ingroup pk_module */
+/**
+ * \brief Parse a public key in PEM or DER format
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param ctx The PK context to fill. It must have been initialized
+ * but not set up.
+ * \param key Input buffer to parse.
+ * The buffer must contain the input exactly, with no
+ * extra trailing material. For PEM, the buffer must
+ * contain a null-terminated string.
+ * \param keylen Size of \b key in bytes.
+ * For PEM data, this includes the terminating null byte,
+ * so \p keylen must be equal to `strlen(key) + 1`.
+ *
+ * \note On entry, ctx must be empty, either freshly initialised
+ * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
+ * specific key type, check the result with mbedtls_pk_can_do().
+ *
+ * \note For compressed points, see #MBEDTLS_ECP_PF_COMPRESSED for
+ * limitations.
+ *
+ * \note The key is also checked for correctness.
+ *
+ * \return 0 if successful, or a specific PK or PEM error code
+ */
+int mbedtls_pk_parse_public_key(mbedtls_pk_context *ctx,
+ const unsigned char *key, size_t keylen);
+
+#if defined(MBEDTLS_FS_IO)
+/** \ingroup pk_module */
+/**
+ * \brief Load and parse a private key
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param ctx The PK context to fill. It must have been initialized
+ * but not set up.
+ * \param path filename to read the private key from
+ * \param password Optional password to decrypt the file.
+ * Pass \c NULL if expecting a non-encrypted key.
+ * Pass a null-terminated string if expecting an encrypted
+ * key; a non-encrypted key will also be accepted.
+ * The empty password is not supported.
+ * \param f_rng RNG function, must not be \c NULL. Used for blinding.
+ * \param p_rng RNG parameter
+ *
+ * \note On entry, ctx must be empty, either freshly initialised
+ * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If you need a
+ * specific key type, check the result with mbedtls_pk_can_do().
+ *
+ * \note The key is also checked for correctness.
+ *
+ * \return 0 if successful, or a specific PK or PEM error code
+ */
+int mbedtls_pk_parse_keyfile(mbedtls_pk_context *ctx,
+ const char *path, const char *password,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng);
+
+/** \ingroup pk_module */
+/**
+ * \brief Load and parse a public key
+ *
+ * \param ctx The PK context to fill. It must have been initialized
+ * but not set up.
+ * \param path filename to read the public key from
+ *
+ * \note On entry, ctx must be empty, either freshly initialised
+ * with mbedtls_pk_init() or reset with mbedtls_pk_free(). If
+ * you need a specific key type, check the result with
+ * mbedtls_pk_can_do().
+ *
+ * \note The key is also checked for correctness.
+ *
+ * \return 0 if successful, or a specific PK or PEM error code
+ */
+int mbedtls_pk_parse_public_keyfile(mbedtls_pk_context *ctx, const char *path);
+#endif /* MBEDTLS_FS_IO */
+#endif /* MBEDTLS_PK_PARSE_C */
+
+#if defined(MBEDTLS_PK_WRITE_C)
+/**
+ * \brief Write a private key to a PKCS#1 or SEC1 DER structure
+ * Note: data is written at the end of the buffer! Use the
+ * return value to determine where you should start
+ * using the buffer
+ *
+ * \param ctx PK context which must contain a valid private key.
+ * \param buf buffer to write to
+ * \param size size of the buffer
+ *
+ * \return length of data written if successful, or a specific
+ * error code
+ */
+int mbedtls_pk_write_key_der(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
+
+/**
+ * \brief Write a public key to a SubjectPublicKeyInfo DER structure
+ * Note: data is written at the end of the buffer! Use the
+ * return value to determine where you should start
+ * using the buffer
+ *
+ * \param ctx PK context which must contain a valid public or private key.
+ * \param buf buffer to write to
+ * \param size size of the buffer
+ *
+ * \return length of data written if successful, or a specific
+ * error code
+ */
+int mbedtls_pk_write_pubkey_der(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
+
+#if defined(MBEDTLS_PEM_WRITE_C)
+/**
+ * \brief Write a public key to a PEM string
+ *
+ * \param ctx PK context which must contain a valid public or private key.
+ * \param buf Buffer to write to. The output includes a
+ * terminating null byte.
+ * \param size Size of the buffer in bytes.
+ *
+ * \return 0 if successful, or a specific error code
+ */
+int mbedtls_pk_write_pubkey_pem(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
+
+/**
+ * \brief Write a private key to a PKCS#1 or SEC1 PEM string
+ *
+ * \param ctx PK context which must contain a valid private key.
+ * \param buf Buffer to write to. The output includes a
+ * terminating null byte.
+ * \param size Size of the buffer in bytes.
+ *
+ * \return 0 if successful, or a specific error code
+ */
+int mbedtls_pk_write_key_pem(const mbedtls_pk_context *ctx, unsigned char *buf, size_t size);
+#endif /* MBEDTLS_PEM_WRITE_C */
+#endif /* MBEDTLS_PK_WRITE_C */
+
+/*
+ * WARNING: Low-level functions. You probably do not want to use these unless
+ * you are certain you do ;)
+ */
+
+#if defined(MBEDTLS_PK_PARSE_C)
+/**
+ * \brief Parse a SubjectPublicKeyInfo DER structure
+ *
+ * \param p the position in the ASN.1 data
+ * \param end end of the buffer
+ * \param pk The PK context to fill. It must have been initialized
+ * but not set up.
+ *
+ * \return 0 if successful, or a specific PK error code
+ */
+int mbedtls_pk_parse_subpubkey(unsigned char **p, const unsigned char *end,
+ mbedtls_pk_context *pk);
+#endif /* MBEDTLS_PK_PARSE_C */
+
+#if defined(MBEDTLS_PK_WRITE_C)
+/**
+ * \brief Write a subjectPublicKey to ASN.1 data
+ * Note: function works backwards in data buffer
+ *
+ * \param p reference to current position pointer
+ * \param start start of the buffer (for bounds-checking)
+ * \param key PK context which must contain a valid public or private key.
+ *
+ * \return the length written or a negative error code
+ */
+int mbedtls_pk_write_pubkey(unsigned char **p, unsigned char *start,
+ const mbedtls_pk_context *key);
+#endif /* MBEDTLS_PK_WRITE_C */
+
+/*
+ * Internal module functions. You probably do not want to use these unless you
+ * know you do.
+ */
+#if defined(MBEDTLS_FS_IO)
+int mbedtls_pk_load_file(const char *path, unsigned char **buf, size_t *n);
+#endif
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+/**
+ * \brief Turn an EC or RSA key into an opaque one.
+ *
+ * \warning This is a temporary utility function for tests. It might
+ * change or be removed at any time without notice.
+ *
+ * \param pk Input: the EC or RSA key to import to a PSA key.
+ * Output: a PK context wrapping that PSA key.
+ * \param key Output: a PSA key identifier.
+ * It's the caller's responsibility to call
+ * psa_destroy_key() on that key identifier after calling
+ * mbedtls_pk_free() on the PK context.
+ * \param alg The algorithm to allow for use with that key.
+ * \param usage The usage to allow for use with that key.
+ * \param alg2 The secondary algorithm to allow for use with that key.
+ *
+ * \return \c 0 if successful.
+ * \return An Mbed TLS error code otherwise.
+ */
+int mbedtls_pk_wrap_as_opaque(mbedtls_pk_context *pk,
+ mbedtls_svc_key_id_t *key,
+ psa_algorithm_t alg,
+ psa_key_usage_t usage,
+ psa_algorithm_t alg2);
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_PK_H */
diff --git a/include/mbedtls/pkcs12.h b/include/mbedtls/pkcs12.h
new file mode 100644
index 0000000..42e8453
--- /dev/null
+++ b/include/mbedtls/pkcs12.h
@@ -0,0 +1,186 @@
+/**
+ * \file pkcs12.h
+ *
+ * \brief PKCS#12 Personal Information Exchange Syntax
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_PKCS12_H
+#define MBEDTLS_PKCS12_H
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/md.h"
+#include "mbedtls/cipher.h"
+#include "mbedtls/asn1.h"
+
+#include <stddef.h>
+
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA -0x1F80
+/** Feature not available, e.g. unsupported encryption scheme. */
+#define MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE -0x1F00
+/** PBE ASN.1 data not as expected. */
+#define MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT -0x1E80
+/** Given private key password does not allow for correct decryption. */
+#define MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH -0x1E00
+
+#define MBEDTLS_PKCS12_DERIVE_KEY 1 /**< encryption/decryption key */
+#define MBEDTLS_PKCS12_DERIVE_IV 2 /**< initialization vector */
+#define MBEDTLS_PKCS12_DERIVE_MAC_KEY 3 /**< integrity / MAC key */
+
+#define MBEDTLS_PKCS12_PBE_DECRYPT 0
+#define MBEDTLS_PKCS12_PBE_ENCRYPT 1
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(MBEDTLS_ASN1_PARSE_C)
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+/**
+ * \brief PKCS12 Password Based function (encryption / decryption)
+ * for cipher-based and mbedtls_md-based PBE's
+ *
+ * \note When encrypting, #MBEDTLS_CIPHER_PADDING_PKCS7 must
+ * be enabled at compile time.
+ *
+ * \deprecated This function is deprecated and will be removed in a
+ * future version of the library.
+ * Please use mbedtls_pkcs12_pbe_ext() instead.
+ *
+ * \warning When decrypting:
+ * - if #MBEDTLS_CIPHER_PADDING_PKCS7 is enabled at compile
+ * time, this function validates the CBC padding and returns
+ * #MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH if the padding is
+ * invalid. Note that this can help active adversaries
+ * attempting to brute-forcing the password. Note also that
+ * there is no guarantee that an invalid password will be
+ * detected (the chances of a valid padding with a random
+ * password are about 1/255).
+ * - if #MBEDTLS_CIPHER_PADDING_PKCS7 is disabled at compile
+ * time, this function does not validate the CBC padding.
+ *
+ * \param pbe_params an ASN1 buffer containing the pkcs-12 PbeParams structure
+ * \param mode either #MBEDTLS_PKCS12_PBE_ENCRYPT or
+ * #MBEDTLS_PKCS12_PBE_DECRYPT
+ * \param cipher_type the cipher used
+ * \param md_type the mbedtls_md used
+ * \param pwd Latin1-encoded password used. This may only be \c NULL when
+ * \p pwdlen is 0. No null terminator should be used.
+ * \param pwdlen length of the password (may be 0)
+ * \param data the input data
+ * \param len data length
+ * \param output Output buffer.
+ * On success, it contains the encrypted or decrypted data,
+ * possibly followed by the CBC padding.
+ * On failure, the content is indeterminate.
+ * For decryption, there must be enough room for \p len
+ * bytes.
+ * For encryption, there must be enough room for
+ * \p len + 1 bytes, rounded up to the block size of
+ * the block cipher identified by \p pbe_params.
+ *
+ * \return 0 if successful, or a MBEDTLS_ERR_XXX code
+ */
+int MBEDTLS_DEPRECATED mbedtls_pkcs12_pbe(mbedtls_asn1_buf *pbe_params, int mode,
+ mbedtls_cipher_type_t cipher_type,
+ mbedtls_md_type_t md_type,
+ const unsigned char *pwd, size_t pwdlen,
+ const unsigned char *data, size_t len,
+ unsigned char *output);
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+#if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
+
+/**
+ * \brief PKCS12 Password Based function (encryption / decryption)
+ * for cipher-based and mbedtls_md-based PBE's
+ *
+ *
+ * \warning When decrypting:
+ * - This function validates the CBC padding and returns
+ * #MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH if the padding is
+ * invalid. Note that this can help active adversaries
+ * attempting to brute-forcing the password. Note also that
+ * there is no guarantee that an invalid password will be
+ * detected (the chances of a valid padding with a random
+ * password are about 1/255).
+ *
+ * \param pbe_params an ASN1 buffer containing the pkcs-12 PbeParams structure
+ * \param mode either #MBEDTLS_PKCS12_PBE_ENCRYPT or
+ * #MBEDTLS_PKCS12_PBE_DECRYPT
+ * \param cipher_type the cipher used
+ * \param md_type the mbedtls_md used
+ * \param pwd Latin1-encoded password used. This may only be \c NULL when
+ * \p pwdlen is 0. No null terminator should be used.
+ * \param pwdlen length of the password (may be 0)
+ * \param data the input data
+ * \param len data length
+ * \param output Output buffer.
+ * On success, it contains the encrypted or decrypted data,
+ * possibly followed by the CBC padding.
+ * On failure, the content is indeterminate.
+ * For decryption, there must be enough room for \p len
+ * bytes.
+ * For encryption, there must be enough room for
+ * \p len + 1 bytes, rounded up to the block size of
+ * the block cipher identified by \p pbe_params.
+ * \param output_size size of output buffer.
+ * This must be big enough to accommodate for output plus
+ * padding data.
+ * \param output_len On success, length of actual data written to the output buffer.
+ *
+ * \return 0 if successful, or a MBEDTLS_ERR_XXX code
+ */
+int mbedtls_pkcs12_pbe_ext(mbedtls_asn1_buf *pbe_params, int mode,
+ mbedtls_cipher_type_t cipher_type, mbedtls_md_type_t md_type,
+ const unsigned char *pwd, size_t pwdlen,
+ const unsigned char *data, size_t len,
+ unsigned char *output, size_t output_size,
+ size_t *output_len);
+
+#endif /* MBEDTLS_CIPHER_PADDING_PKCS7 */
+
+#endif /* MBEDTLS_ASN1_PARSE_C */
+
+/**
+ * \brief The PKCS#12 derivation function uses a password and a salt
+ * to produce pseudo-random bits for a particular "purpose".
+ *
+ * Depending on the given id, this function can produce an
+ * encryption/decryption key, an initialization vector or an
+ * integrity key.
+ *
+ * \param data buffer to store the derived data in
+ * \param datalen length of buffer to fill
+ * \param pwd The password to use. For compliance with PKCS#12 §B.1, this
+ * should be a BMPString, i.e. a Unicode string where each
+ * character is encoded as 2 bytes in big-endian order, with
+ * no byte order mark and with a null terminator (i.e. the
+ * last two bytes should be 0x00 0x00).
+ * \param pwdlen length of the password (may be 0).
+ * \param salt Salt buffer to use. This may only be \c NULL when
+ * \p saltlen is 0.
+ * \param saltlen length of the salt (may be zero)
+ * \param mbedtls_md mbedtls_md type to use during the derivation
+ * \param id id that describes the purpose (can be
+ * #MBEDTLS_PKCS12_DERIVE_KEY, #MBEDTLS_PKCS12_DERIVE_IV or
+ * #MBEDTLS_PKCS12_DERIVE_MAC_KEY)
+ * \param iterations number of iterations
+ *
+ * \return 0 if successful, or a MD, BIGNUM type error.
+ */
+int mbedtls_pkcs12_derivation(unsigned char *data, size_t datalen,
+ const unsigned char *pwd, size_t pwdlen,
+ const unsigned char *salt, size_t saltlen,
+ mbedtls_md_type_t mbedtls_md, int id, int iterations);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* pkcs12.h */
diff --git a/include/mbedtls/pkcs5.h b/include/mbedtls/pkcs5.h
new file mode 100644
index 0000000..e004f45
--- /dev/null
+++ b/include/mbedtls/pkcs5.h
@@ -0,0 +1,197 @@
+/**
+ * \file pkcs5.h
+ *
+ * \brief PKCS#5 functions
+ *
+ * \author Mathias Olsson <mathias@kompetensum.com>
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_PKCS5_H
+#define MBEDTLS_PKCS5_H
+
+#include "mbedtls/build_info.h"
+#include "mbedtls/platform_util.h"
+
+#include "mbedtls/asn1.h"
+#include "mbedtls/md.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_PKCS5_BAD_INPUT_DATA -0x2f80
+/** Unexpected ASN.1 data. */
+#define MBEDTLS_ERR_PKCS5_INVALID_FORMAT -0x2f00
+/** Requested encryption or digest alg not available. */
+#define MBEDTLS_ERR_PKCS5_FEATURE_UNAVAILABLE -0x2e80
+/** Given private key password does not allow for correct decryption. */
+#define MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH -0x2e00
+
+#define MBEDTLS_PKCS5_DECRYPT 0
+#define MBEDTLS_PKCS5_ENCRYPT 1
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if defined(MBEDTLS_ASN1_PARSE_C)
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+/**
+ * \brief PKCS#5 PBES2 function
+ *
+ * \note When encrypting, #MBEDTLS_CIPHER_PADDING_PKCS7 must
+ * be enabled at compile time.
+ *
+ * \deprecated This function is deprecated and will be removed in a
+ * future version of the library.
+ * Please use mbedtls_pkcs5_pbes2_ext() instead.
+ *
+ * \warning When decrypting:
+ * - if #MBEDTLS_CIPHER_PADDING_PKCS7 is enabled at compile
+ * time, this function validates the CBC padding and returns
+ * #MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH if the padding is
+ * invalid. Note that this can help active adversaries
+ * attempting to brute-forcing the password. Note also that
+ * there is no guarantee that an invalid password will be
+ * detected (the chances of a valid padding with a random
+ * password are about 1/255).
+ * - if #MBEDTLS_CIPHER_PADDING_PKCS7 is disabled at compile
+ * time, this function does not validate the CBC padding.
+ *
+ * \param pbe_params the ASN.1 algorithm parameters
+ * \param mode either #MBEDTLS_PKCS5_DECRYPT or #MBEDTLS_PKCS5_ENCRYPT
+ * \param pwd password to use when generating key
+ * \param pwdlen length of password
+ * \param data data to process
+ * \param datalen length of data
+ * \param output Output buffer.
+ * On success, it contains the encrypted or decrypted data,
+ * possibly followed by the CBC padding.
+ * On failure, the content is indeterminate.
+ * For decryption, there must be enough room for \p datalen
+ * bytes.
+ * For encryption, there must be enough room for
+ * \p datalen + 1 bytes, rounded up to the block size of
+ * the block cipher identified by \p pbe_params.
+ *
+ * \returns 0 on success, or a MBEDTLS_ERR_XXX code if verification fails.
+ */
+int MBEDTLS_DEPRECATED mbedtls_pkcs5_pbes2(const mbedtls_asn1_buf *pbe_params, int mode,
+ const unsigned char *pwd, size_t pwdlen,
+ const unsigned char *data, size_t datalen,
+ unsigned char *output);
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+#if defined(MBEDTLS_CIPHER_PADDING_PKCS7)
+
+/**
+ * \brief PKCS#5 PBES2 function
+ *
+ * \warning When decrypting:
+ * - This function validates the CBC padding and returns
+ * #MBEDTLS_ERR_PKCS5_PASSWORD_MISMATCH if the padding is
+ * invalid. Note that this can help active adversaries
+ * attempting to brute-forcing the password. Note also that
+ * there is no guarantee that an invalid password will be
+ * detected (the chances of a valid padding with a random
+ * password are about 1/255).
+ *
+ * \param pbe_params the ASN.1 algorithm parameters
+ * \param mode either #MBEDTLS_PKCS5_DECRYPT or #MBEDTLS_PKCS5_ENCRYPT
+ * \param pwd password to use when generating key
+ * \param pwdlen length of password
+ * \param data data to process
+ * \param datalen length of data
+ * \param output Output buffer.
+ * On success, it contains the decrypted data.
+ * On failure, the content is indetermidate.
+ * For decryption, there must be enough room for \p datalen
+ * bytes.
+ * For encryption, there must be enough room for
+ * \p datalen + 1 bytes, rounded up to the block size of
+ * the block cipher identified by \p pbe_params.
+ * \param output_size size of output buffer.
+ * This must be big enough to accommodate for output plus
+ * padding data.
+ * \param output_len On success, length of actual data written to the output buffer.
+ *
+ * \returns 0 on success, or a MBEDTLS_ERR_XXX code if parsing or decryption fails.
+ */
+int mbedtls_pkcs5_pbes2_ext(const mbedtls_asn1_buf *pbe_params, int mode,
+ const unsigned char *pwd, size_t pwdlen,
+ const unsigned char *data, size_t datalen,
+ unsigned char *output, size_t output_size,
+ size_t *output_len);
+
+#endif /* MBEDTLS_CIPHER_PADDING_PKCS7 */
+
+#endif /* MBEDTLS_ASN1_PARSE_C */
+
+/**
+ * \brief PKCS#5 PBKDF2 using HMAC without using the HMAC context
+ *
+ * \param md_type Hash algorithm used
+ * \param password Password to use when generating key
+ * \param plen Length of password
+ * \param salt Salt to use when generating key
+ * \param slen Length of salt
+ * \param iteration_count Iteration count
+ * \param key_length Length of generated key in bytes
+ * \param output Generated key. Must be at least as big as key_length
+ *
+ * \returns 0 on success, or a MBEDTLS_ERR_XXX code if verification fails.
+ */
+int mbedtls_pkcs5_pbkdf2_hmac_ext(mbedtls_md_type_t md_type,
+ const unsigned char *password,
+ size_t plen, const unsigned char *salt, size_t slen,
+ unsigned int iteration_count,
+ uint32_t key_length, unsigned char *output);
+
+#if defined(MBEDTLS_MD_C)
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+/**
+ * \brief PKCS#5 PBKDF2 using HMAC
+ *
+ * \deprecated Superseded by mbedtls_pkcs5_pbkdf2_hmac_ext().
+ *
+ * \param ctx Generic HMAC context
+ * \param password Password to use when generating key
+ * \param plen Length of password
+ * \param salt Salt to use when generating key
+ * \param slen Length of salt
+ * \param iteration_count Iteration count
+ * \param key_length Length of generated key in bytes
+ * \param output Generated key. Must be at least as big as key_length
+ *
+ * \returns 0 on success, or a MBEDTLS_ERR_XXX code if verification fails.
+ */
+int MBEDTLS_DEPRECATED mbedtls_pkcs5_pbkdf2_hmac(mbedtls_md_context_t *ctx,
+ const unsigned char *password,
+ size_t plen,
+ const unsigned char *salt,
+ size_t slen,
+ unsigned int iteration_count,
+ uint32_t key_length,
+ unsigned char *output);
+#endif /* !MBEDTLS_DEPRECATED_REMOVED */
+#endif /* MBEDTLS_MD_C */
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if the test failed
+ */
+int mbedtls_pkcs5_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* pkcs5.h */
diff --git a/include/mbedtls/pkcs7.h b/include/mbedtls/pkcs7.h
new file mode 100644
index 0000000..70b25a9
--- /dev/null
+++ b/include/mbedtls/pkcs7.h
@@ -0,0 +1,241 @@
+/**
+ * \file pkcs7.h
+ *
+ * \brief PKCS #7 generic defines and structures
+ * https://tools.ietf.org/html/rfc2315
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+/**
+ * Note: For the time being, this implementation of the PKCS #7 cryptographic
+ * message syntax is a partial implementation of RFC 2315.
+ * Differences include:
+ * - The RFC specifies 6 different content types. The only type currently
+ * supported in Mbed TLS is the signed-data content type.
+ * - The only supported PKCS #7 Signed Data syntax version is version 1
+ * - The RFC specifies support for BER. This implementation is limited to
+ * DER only.
+ * - The RFC specifies that multiple digest algorithms can be specified
+ * in the Signed Data type. Only one digest algorithm is supported in Mbed TLS.
+ * - The RFC specifies the Signed Data type can contain multiple X.509 or PKCS #6 extended
+ * certificates. In Mbed TLS, this list can only contain 0 or 1 certificates
+ * and they must be in X.509 format.
+ * - The RFC specifies the Signed Data type can contain
+ * certificate-revocation lists (CRLs). This implementation has no support
+ * for CRLs so it is assumed to be an empty list.
+ * - The RFC allows for SignerInfo structure to optionally contain
+ * unauthenticatedAttributes and authenticatedAttributes. In Mbed TLS it is
+ * assumed these fields are empty.
+ * - The RFC allows for the signed Data type to contain contentInfo. This
+ * implementation assumes the type is DATA and the content is empty.
+ */
+
+#ifndef MBEDTLS_PKCS7_H
+#define MBEDTLS_PKCS7_H
+
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/asn1.h"
+#include "mbedtls/x509.h"
+#include "mbedtls/x509_crt.h"
+
+/**
+ * \name PKCS #7 Module Error codes
+ * \{
+ */
+#define MBEDTLS_ERR_PKCS7_INVALID_FORMAT -0x5300 /**< The format is invalid, e.g. different type expected. */
+#define MBEDTLS_ERR_PKCS7_FEATURE_UNAVAILABLE -0x5380 /**< Unavailable feature, e.g. anything other than signed data. */
+#define MBEDTLS_ERR_PKCS7_INVALID_VERSION -0x5400 /**< The PKCS #7 version element is invalid or cannot be parsed. */
+#define MBEDTLS_ERR_PKCS7_INVALID_CONTENT_INFO -0x5480 /**< The PKCS #7 content info is invalid or cannot be parsed. */
+#define MBEDTLS_ERR_PKCS7_INVALID_ALG -0x5500 /**< The algorithm tag or value is invalid or cannot be parsed. */
+#define MBEDTLS_ERR_PKCS7_INVALID_CERT -0x5580 /**< The certificate tag or value is invalid or cannot be parsed. */
+#define MBEDTLS_ERR_PKCS7_INVALID_SIGNATURE -0x5600 /**< Error parsing the signature */
+#define MBEDTLS_ERR_PKCS7_INVALID_SIGNER_INFO -0x5680 /**< Error parsing the signer's info */
+#define MBEDTLS_ERR_PKCS7_BAD_INPUT_DATA -0x5700 /**< Input invalid. */
+#define MBEDTLS_ERR_PKCS7_ALLOC_FAILED -0x5780 /**< Allocation of memory failed. */
+#define MBEDTLS_ERR_PKCS7_VERIFY_FAIL -0x5800 /**< Verification Failed */
+#define MBEDTLS_ERR_PKCS7_CERT_DATE_INVALID -0x5880 /**< The PKCS #7 date issued/expired dates are invalid */
+/* \} name */
+
+/**
+ * \name PKCS #7 Supported Version
+ * \{
+ */
+#define MBEDTLS_PKCS7_SUPPORTED_VERSION 0x01
+/* \} name */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Type-length-value structure that allows for ASN.1 using DER.
+ */
+typedef mbedtls_asn1_buf mbedtls_pkcs7_buf;
+
+/**
+ * Container for ASN.1 named information objects.
+ * It allows for Relative Distinguished Names (e.g. cn=localhost,ou=code,etc.).
+ */
+typedef mbedtls_asn1_named_data mbedtls_pkcs7_name;
+
+/**
+ * Container for a sequence of ASN.1 items
+ */
+typedef mbedtls_asn1_sequence mbedtls_pkcs7_sequence;
+
+/**
+ * PKCS #7 types
+ */
+typedef enum {
+ MBEDTLS_PKCS7_NONE=0,
+ MBEDTLS_PKCS7_DATA,
+ MBEDTLS_PKCS7_SIGNED_DATA,
+ MBEDTLS_PKCS7_ENVELOPED_DATA,
+ MBEDTLS_PKCS7_SIGNED_AND_ENVELOPED_DATA,
+ MBEDTLS_PKCS7_DIGESTED_DATA,
+ MBEDTLS_PKCS7_ENCRYPTED_DATA,
+}
+mbedtls_pkcs7_type;
+
+/**
+ * Structure holding PKCS #7 signer info
+ */
+typedef struct mbedtls_pkcs7_signer_info {
+ int MBEDTLS_PRIVATE(version);
+ mbedtls_x509_buf MBEDTLS_PRIVATE(serial);
+ mbedtls_x509_name MBEDTLS_PRIVATE(issuer);
+ mbedtls_x509_buf MBEDTLS_PRIVATE(issuer_raw);
+ mbedtls_x509_buf MBEDTLS_PRIVATE(alg_identifier);
+ mbedtls_x509_buf MBEDTLS_PRIVATE(sig_alg_identifier);
+ mbedtls_x509_buf MBEDTLS_PRIVATE(sig);
+ struct mbedtls_pkcs7_signer_info *MBEDTLS_PRIVATE(next);
+}
+mbedtls_pkcs7_signer_info;
+
+/**
+ * Structure holding the signed data section
+ */
+typedef struct mbedtls_pkcs7_signed_data {
+ int MBEDTLS_PRIVATE(version);
+ mbedtls_pkcs7_buf MBEDTLS_PRIVATE(digest_alg_identifiers);
+ int MBEDTLS_PRIVATE(no_of_certs);
+ mbedtls_x509_crt MBEDTLS_PRIVATE(certs);
+ int MBEDTLS_PRIVATE(no_of_crls);
+ mbedtls_x509_crl MBEDTLS_PRIVATE(crl);
+ int MBEDTLS_PRIVATE(no_of_signers);
+ mbedtls_pkcs7_signer_info MBEDTLS_PRIVATE(signers);
+}
+mbedtls_pkcs7_signed_data;
+
+/**
+ * Structure holding PKCS #7 structure, only signed data for now
+ */
+typedef struct mbedtls_pkcs7 {
+ mbedtls_pkcs7_buf MBEDTLS_PRIVATE(raw);
+ mbedtls_pkcs7_signed_data MBEDTLS_PRIVATE(signed_data);
+}
+mbedtls_pkcs7;
+
+/**
+ * \brief Initialize mbedtls_pkcs7 structure.
+ *
+ * \param pkcs7 mbedtls_pkcs7 structure.
+ */
+void mbedtls_pkcs7_init(mbedtls_pkcs7 *pkcs7);
+
+/**
+ * \brief Parse a single DER formatted PKCS #7 detached signature.
+ *
+ * \param pkcs7 The mbedtls_pkcs7 structure to be filled by the parser.
+ * \param buf The buffer holding only the DER encoded PKCS #7 content.
+ * \param buflen The size in bytes of \p buf. The size must be exactly the
+ * length of the DER encoded PKCS #7 content.
+ *
+ * \note This function makes an internal copy of the PKCS #7 buffer
+ * \p buf. In particular, \p buf may be destroyed or reused
+ * after this call returns.
+ * \note Signatures with internal data are not supported.
+ *
+ * \return The \c mbedtls_pkcs7_type of \p buf, if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_pkcs7_parse_der(mbedtls_pkcs7 *pkcs7, const unsigned char *buf,
+ const size_t buflen);
+
+/**
+ * \brief Verification of PKCS #7 signature against a caller-supplied
+ * certificate.
+ *
+ * For each signer in the PKCS structure, this function computes
+ * a signature over the supplied data, using the supplied
+ * certificate and the same digest algorithm as specified by the
+ * signer. It then compares this signature against the
+ * signer's signature; verification succeeds if any comparison
+ * matches.
+ *
+ * This function does not use the certificates held within the
+ * PKCS #7 structure itself, and does not check that the
+ * certificate is signed by a trusted certification authority.
+ *
+ * \param pkcs7 mbedtls_pkcs7 structure containing signature.
+ * \param cert Certificate containing key to verify signature.
+ * \param data Plain data on which signature has to be verified.
+ * \param datalen Length of the data.
+ *
+ * \note This function internally calculates the hash on the supplied
+ * plain data for signature verification.
+ *
+ * \return 0 if the signature verifies, or a negative error code on failure.
+ */
+int mbedtls_pkcs7_signed_data_verify(mbedtls_pkcs7 *pkcs7,
+ const mbedtls_x509_crt *cert,
+ const unsigned char *data,
+ size_t datalen);
+
+/**
+ * \brief Verification of PKCS #7 signature against a caller-supplied
+ * certificate.
+ *
+ * For each signer in the PKCS structure, this function
+ * validates a signature over the supplied hash, using the
+ * supplied certificate and the same digest algorithm as
+ * specified by the signer. Verification succeeds if any
+ * signature is good.
+ *
+ * This function does not use the certificates held within the
+ * PKCS #7 structure itself, and does not check that the
+ * certificate is signed by a trusted certification authority.
+ *
+ * \param pkcs7 PKCS #7 structure containing signature.
+ * \param cert Certificate containing key to verify signature.
+ * \param hash Hash of the plain data on which signature has to be verified.
+ * \param hashlen Length of the hash.
+ *
+ * \note This function is different from mbedtls_pkcs7_signed_data_verify()
+ * in that it is directly passed the hash of the data.
+ *
+ * \return 0 if the signature verifies, or a negative error code on failure.
+ */
+int mbedtls_pkcs7_signed_hash_verify(mbedtls_pkcs7 *pkcs7,
+ const mbedtls_x509_crt *cert,
+ const unsigned char *hash, size_t hashlen);
+
+/**
+ * \brief Unallocate all PKCS #7 data and zeroize the memory.
+ * It doesn't free \p pkcs7 itself. This should be done by the caller.
+ *
+ * \param pkcs7 mbedtls_pkcs7 structure to free.
+ */
+void mbedtls_pkcs7_free(mbedtls_pkcs7 *pkcs7);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* pkcs7.h */
diff --git a/include/mbedtls/platform.h b/include/mbedtls/platform.h
new file mode 100644
index 0000000..de3d71d
--- /dev/null
+++ b/include/mbedtls/platform.h
@@ -0,0 +1,485 @@
+/**
+ * \file platform.h
+ *
+ * \brief This file contains the definitions and functions of the
+ * Mbed TLS platform abstraction layer.
+ *
+ * The platform abstraction layer removes the need for the library
+ * to directly link to standard C library functions or operating
+ * system services, making the library easier to port and embed.
+ * Application developers and users of the library can provide their own
+ * implementations of these functions, or implementations specific to
+ * their platform, which can be statically linked to the library or
+ * dynamically configured at runtime.
+ *
+ * When all compilation options related to platform abstraction are
+ * disabled, this header just defines `mbedtls_xxx` function names
+ * as aliases to the standard `xxx` function.
+ *
+ * Most modules in the library and example programs are expected to
+ * include this header.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_PLATFORM_H
+#define MBEDTLS_PLATFORM_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#if defined(MBEDTLS_HAVE_TIME)
+#include "mbedtls/platform_time.h"
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \name SECTION: Module settings
+ *
+ * The configuration options you can set for this module are in this section.
+ * Either change them in mbedtls_config.h or define them on the compiler command line.
+ * \{
+ */
+
+/* The older Microsoft Windows common runtime provides non-conforming
+ * implementations of some standard library functions, including snprintf
+ * and vsnprintf. This affects MSVC and MinGW builds.
+ */
+#if defined(__MINGW32__) || (defined(_MSC_VER) && _MSC_VER <= 1900)
+#define MBEDTLS_PLATFORM_HAS_NON_CONFORMING_SNPRINTF
+#define MBEDTLS_PLATFORM_HAS_NON_CONFORMING_VSNPRINTF
+#endif
+
+#if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS)
+#include <stdio.h>
+#include <stdlib.h>
+#if defined(MBEDTLS_HAVE_TIME)
+#include <time.h>
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_SNPRINTF)
+#if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_SNPRINTF)
+#define MBEDTLS_PLATFORM_STD_SNPRINTF mbedtls_platform_win32_snprintf /**< The default \c snprintf function to use. */
+#else
+#define MBEDTLS_PLATFORM_STD_SNPRINTF snprintf /**< The default \c snprintf function to use. */
+#endif
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_VSNPRINTF)
+#if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_VSNPRINTF)
+#define MBEDTLS_PLATFORM_STD_VSNPRINTF mbedtls_platform_win32_vsnprintf /**< The default \c vsnprintf function to use. */
+#else
+#define MBEDTLS_PLATFORM_STD_VSNPRINTF vsnprintf /**< The default \c vsnprintf function to use. */
+#endif
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_PRINTF)
+#define MBEDTLS_PLATFORM_STD_PRINTF printf /**< The default \c printf function to use. */
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_FPRINTF)
+#define MBEDTLS_PLATFORM_STD_FPRINTF fprintf /**< The default \c fprintf function to use. */
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_CALLOC)
+#define MBEDTLS_PLATFORM_STD_CALLOC calloc /**< The default \c calloc function to use. */
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_FREE)
+#define MBEDTLS_PLATFORM_STD_FREE free /**< The default \c free function to use. */
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_SETBUF)
+#define MBEDTLS_PLATFORM_STD_SETBUF setbuf /**< The default \c setbuf function to use. */
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_EXIT)
+#define MBEDTLS_PLATFORM_STD_EXIT exit /**< The default \c exit function to use. */
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_TIME)
+#define MBEDTLS_PLATFORM_STD_TIME time /**< The default \c time function to use. */
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS)
+#define MBEDTLS_PLATFORM_STD_EXIT_SUCCESS EXIT_SUCCESS /**< The default exit value to use. */
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE)
+#define MBEDTLS_PLATFORM_STD_EXIT_FAILURE EXIT_FAILURE /**< The default exit value to use. */
+#endif
+#if defined(MBEDTLS_FS_IO)
+#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_READ)
+#define MBEDTLS_PLATFORM_STD_NV_SEED_READ mbedtls_platform_std_nv_seed_read
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_WRITE)
+#define MBEDTLS_PLATFORM_STD_NV_SEED_WRITE mbedtls_platform_std_nv_seed_write
+#endif
+#if !defined(MBEDTLS_PLATFORM_STD_NV_SEED_FILE)
+#define MBEDTLS_PLATFORM_STD_NV_SEED_FILE "seedfile"
+#endif
+#endif /* MBEDTLS_FS_IO */
+#else /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */
+#if defined(MBEDTLS_PLATFORM_STD_MEM_HDR)
+#include MBEDTLS_PLATFORM_STD_MEM_HDR
+#endif
+#endif /* MBEDTLS_PLATFORM_NO_STD_FUNCTIONS */
+
+/* Enable certain documented defines only when generating doxygen to avoid
+ * an "unrecognized define" error. */
+#if defined(__DOXYGEN__) && !defined(MBEDTLS_PLATFORM_STD_CALLOC)
+#define MBEDTLS_PLATFORM_STD_CALLOC
+#endif
+
+#if defined(__DOXYGEN__) && !defined(MBEDTLS_PLATFORM_STD_FREE)
+#define MBEDTLS_PLATFORM_STD_FREE
+#endif
+
+/** \} name SECTION: Module settings */
+
+/*
+ * The function pointers for calloc and free.
+ * Please see MBEDTLS_PLATFORM_STD_CALLOC and MBEDTLS_PLATFORM_STD_FREE
+ * in mbedtls_config.h for more information about behaviour and requirements.
+ */
+#if defined(MBEDTLS_PLATFORM_MEMORY)
+#if defined(MBEDTLS_PLATFORM_FREE_MACRO) && \
+ defined(MBEDTLS_PLATFORM_CALLOC_MACRO)
+#undef mbedtls_free
+#undef mbedtls_calloc
+#define mbedtls_free MBEDTLS_PLATFORM_FREE_MACRO
+#define mbedtls_calloc MBEDTLS_PLATFORM_CALLOC_MACRO
+#else
+/* For size_t */
+#include <stddef.h>
+extern void *mbedtls_calloc(size_t n, size_t size);
+extern void mbedtls_free(void *ptr);
+
+/**
+ * \brief This function dynamically sets the memory-management
+ * functions used by the library, during runtime.
+ *
+ * \param calloc_func The \c calloc function implementation.
+ * \param free_func The \c free function implementation.
+ *
+ * \return \c 0.
+ */
+int mbedtls_platform_set_calloc_free(void *(*calloc_func)(size_t, size_t),
+ void (*free_func)(void *));
+#endif /* MBEDTLS_PLATFORM_FREE_MACRO && MBEDTLS_PLATFORM_CALLOC_MACRO */
+#else /* !MBEDTLS_PLATFORM_MEMORY */
+#undef mbedtls_free
+#undef mbedtls_calloc
+#define mbedtls_free free
+#define mbedtls_calloc calloc
+#endif /* MBEDTLS_PLATFORM_MEMORY && !MBEDTLS_PLATFORM_{FREE,CALLOC}_MACRO */
+
+/*
+ * The function pointers for fprintf
+ */
+#if defined(MBEDTLS_PLATFORM_FPRINTF_ALT)
+/* We need FILE * */
+#include <stdio.h>
+extern int (*mbedtls_fprintf)(FILE *stream, const char *format, ...);
+
+/**
+ * \brief This function dynamically configures the fprintf
+ * function that is called when the
+ * mbedtls_fprintf() function is invoked by the library.
+ *
+ * \param fprintf_func The \c fprintf function implementation.
+ *
+ * \return \c 0.
+ */
+int mbedtls_platform_set_fprintf(int (*fprintf_func)(FILE *stream, const char *,
+ ...));
+#else
+#undef mbedtls_fprintf
+#if defined(MBEDTLS_PLATFORM_FPRINTF_MACRO)
+#define mbedtls_fprintf MBEDTLS_PLATFORM_FPRINTF_MACRO
+#else
+#define mbedtls_fprintf fprintf
+#endif /* MBEDTLS_PLATFORM_FPRINTF_MACRO */
+#endif /* MBEDTLS_PLATFORM_FPRINTF_ALT */
+
+/*
+ * The function pointers for printf
+ */
+#if defined(MBEDTLS_PLATFORM_PRINTF_ALT)
+extern int (*mbedtls_printf)(const char *format, ...);
+
+/**
+ * \brief This function dynamically configures the snprintf
+ * function that is called when the mbedtls_snprintf()
+ * function is invoked by the library.
+ *
+ * \param printf_func The \c printf function implementation.
+ *
+ * \return \c 0 on success.
+ */
+int mbedtls_platform_set_printf(int (*printf_func)(const char *, ...));
+#else /* !MBEDTLS_PLATFORM_PRINTF_ALT */
+#undef mbedtls_printf
+#if defined(MBEDTLS_PLATFORM_PRINTF_MACRO)
+#define mbedtls_printf MBEDTLS_PLATFORM_PRINTF_MACRO
+#else
+#define mbedtls_printf printf
+#endif /* MBEDTLS_PLATFORM_PRINTF_MACRO */
+#endif /* MBEDTLS_PLATFORM_PRINTF_ALT */
+
+/*
+ * The function pointers for snprintf
+ *
+ * The snprintf implementation should conform to C99:
+ * - it *must* always correctly zero-terminate the buffer
+ * (except when n == 0, then it must leave the buffer untouched)
+ * - however it is acceptable to return -1 instead of the required length when
+ * the destination buffer is too short.
+ */
+#if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_SNPRINTF)
+/* For Windows (inc. MSYS2), we provide our own fixed implementation */
+int mbedtls_platform_win32_snprintf(char *s, size_t n, const char *fmt, ...);
+#endif
+
+#if defined(MBEDTLS_PLATFORM_SNPRINTF_ALT)
+extern int (*mbedtls_snprintf)(char *s, size_t n, const char *format, ...);
+
+/**
+ * \brief This function allows configuring a custom
+ * \c snprintf function pointer.
+ *
+ * \param snprintf_func The \c snprintf function implementation.
+ *
+ * \return \c 0 on success.
+ */
+int mbedtls_platform_set_snprintf(int (*snprintf_func)(char *s, size_t n,
+ const char *format, ...));
+#else /* MBEDTLS_PLATFORM_SNPRINTF_ALT */
+#undef mbedtls_snprintf
+#if defined(MBEDTLS_PLATFORM_SNPRINTF_MACRO)
+#define mbedtls_snprintf MBEDTLS_PLATFORM_SNPRINTF_MACRO
+#else
+#define mbedtls_snprintf MBEDTLS_PLATFORM_STD_SNPRINTF
+#endif /* MBEDTLS_PLATFORM_SNPRINTF_MACRO */
+#endif /* MBEDTLS_PLATFORM_SNPRINTF_ALT */
+
+/*
+ * The function pointers for vsnprintf
+ *
+ * The vsnprintf implementation should conform to C99:
+ * - it *must* always correctly zero-terminate the buffer
+ * (except when n == 0, then it must leave the buffer untouched)
+ * - however it is acceptable to return -1 instead of the required length when
+ * the destination buffer is too short.
+ */
+#if defined(MBEDTLS_PLATFORM_HAS_NON_CONFORMING_VSNPRINTF)
+#include <stdarg.h>
+/* For Older Windows (inc. MSYS2), we provide our own fixed implementation */
+int mbedtls_platform_win32_vsnprintf(char *s, size_t n, const char *fmt, va_list arg);
+#endif
+
+#if defined(MBEDTLS_PLATFORM_VSNPRINTF_ALT)
+#include <stdarg.h>
+extern int (*mbedtls_vsnprintf)(char *s, size_t n, const char *format, va_list arg);
+
+/**
+ * \brief Set your own snprintf function pointer
+ *
+ * \param vsnprintf_func The \c vsnprintf function implementation
+ *
+ * \return \c 0
+ */
+int mbedtls_platform_set_vsnprintf(int (*vsnprintf_func)(char *s, size_t n,
+ const char *format, va_list arg));
+#else /* MBEDTLS_PLATFORM_VSNPRINTF_ALT */
+#undef mbedtls_vsnprintf
+#if defined(MBEDTLS_PLATFORM_VSNPRINTF_MACRO)
+#define mbedtls_vsnprintf MBEDTLS_PLATFORM_VSNPRINTF_MACRO
+#else
+#define mbedtls_vsnprintf vsnprintf
+#endif /* MBEDTLS_PLATFORM_VSNPRINTF_MACRO */
+#endif /* MBEDTLS_PLATFORM_VSNPRINTF_ALT */
+
+/*
+ * The function pointers for setbuf
+ */
+#if defined(MBEDTLS_PLATFORM_SETBUF_ALT)
+#include <stdio.h>
+/**
+ * \brief Function pointer to call for `setbuf()` functionality
+ * (changing the internal buffering on stdio calls).
+ *
+ * \note The library calls this function to disable
+ * buffering when reading or writing sensitive data,
+ * to avoid having extra copies of sensitive data
+ * remaining in stdio buffers after the file is
+ * closed. If this is not a concern, for example if
+ * your platform's stdio doesn't have any buffering,
+ * you can set mbedtls_setbuf to a function that
+ * does nothing.
+ *
+ * The library always calls this function with
+ * `buf` equal to `NULL`.
+ */
+extern void (*mbedtls_setbuf)(FILE *stream, char *buf);
+
+/**
+ * \brief Dynamically configure the function that is called
+ * when the mbedtls_setbuf() function is called by the
+ * library.
+ *
+ * \param setbuf_func The \c setbuf function implementation
+ *
+ * \return \c 0
+ */
+int mbedtls_platform_set_setbuf(void (*setbuf_func)(
+ FILE *stream, char *buf));
+#else
+#undef mbedtls_setbuf
+#if defined(MBEDTLS_PLATFORM_SETBUF_MACRO)
+/**
+ * \brief Macro defining the function for the library to
+ * call for `setbuf` functionality (changing the
+ * internal buffering on stdio calls).
+ *
+ * \note See extra comments on the mbedtls_setbuf() function
+ * pointer above.
+ *
+ * \return \c 0 on success, negative on error.
+ */
+#define mbedtls_setbuf MBEDTLS_PLATFORM_SETBUF_MACRO
+#else
+#define mbedtls_setbuf setbuf
+#endif /* MBEDTLS_PLATFORM_SETBUF_MACRO */
+#endif /* MBEDTLS_PLATFORM_SETBUF_ALT */
+
+/*
+ * The function pointers for exit
+ */
+#if defined(MBEDTLS_PLATFORM_EXIT_ALT)
+extern void (*mbedtls_exit)(int status);
+
+/**
+ * \brief This function dynamically configures the exit
+ * function that is called when the mbedtls_exit()
+ * function is invoked by the library.
+ *
+ * \param exit_func The \c exit function implementation.
+ *
+ * \return \c 0 on success.
+ */
+int mbedtls_platform_set_exit(void (*exit_func)(int status));
+#else
+#undef mbedtls_exit
+#if defined(MBEDTLS_PLATFORM_EXIT_MACRO)
+#define mbedtls_exit MBEDTLS_PLATFORM_EXIT_MACRO
+#else
+#define mbedtls_exit exit
+#endif /* MBEDTLS_PLATFORM_EXIT_MACRO */
+#endif /* MBEDTLS_PLATFORM_EXIT_ALT */
+
+/*
+ * The default exit values
+ */
+#if defined(MBEDTLS_PLATFORM_STD_EXIT_SUCCESS)
+#define MBEDTLS_EXIT_SUCCESS MBEDTLS_PLATFORM_STD_EXIT_SUCCESS
+#else
+#define MBEDTLS_EXIT_SUCCESS 0
+#endif
+#if defined(MBEDTLS_PLATFORM_STD_EXIT_FAILURE)
+#define MBEDTLS_EXIT_FAILURE MBEDTLS_PLATFORM_STD_EXIT_FAILURE
+#else
+#define MBEDTLS_EXIT_FAILURE 1
+#endif
+
+/*
+ * The function pointers for reading from and writing a seed file to
+ * Non-Volatile storage (NV) in a platform-independent way
+ *
+ * Only enabled when the NV seed entropy source is enabled
+ */
+#if defined(MBEDTLS_ENTROPY_NV_SEED)
+#if !defined(MBEDTLS_PLATFORM_NO_STD_FUNCTIONS) && defined(MBEDTLS_FS_IO)
+/* Internal standard platform definitions */
+int mbedtls_platform_std_nv_seed_read(unsigned char *buf, size_t buf_len);
+int mbedtls_platform_std_nv_seed_write(unsigned char *buf, size_t buf_len);
+#endif
+
+#if defined(MBEDTLS_PLATFORM_NV_SEED_ALT)
+extern int (*mbedtls_nv_seed_read)(unsigned char *buf, size_t buf_len);
+extern int (*mbedtls_nv_seed_write)(unsigned char *buf, size_t buf_len);
+
+/**
+ * \brief This function allows configuring custom seed file writing and
+ * reading functions.
+ *
+ * \param nv_seed_read_func The seed reading function implementation.
+ * \param nv_seed_write_func The seed writing function implementation.
+ *
+ * \return \c 0 on success.
+ */
+int mbedtls_platform_set_nv_seed(
+ int (*nv_seed_read_func)(unsigned char *buf, size_t buf_len),
+ int (*nv_seed_write_func)(unsigned char *buf, size_t buf_len)
+ );
+#else
+#undef mbedtls_nv_seed_read
+#undef mbedtls_nv_seed_write
+#if defined(MBEDTLS_PLATFORM_NV_SEED_READ_MACRO) && \
+ defined(MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO)
+#define mbedtls_nv_seed_read MBEDTLS_PLATFORM_NV_SEED_READ_MACRO
+#define mbedtls_nv_seed_write MBEDTLS_PLATFORM_NV_SEED_WRITE_MACRO
+#else
+#define mbedtls_nv_seed_read mbedtls_platform_std_nv_seed_read
+#define mbedtls_nv_seed_write mbedtls_platform_std_nv_seed_write
+#endif
+#endif /* MBEDTLS_PLATFORM_NV_SEED_ALT */
+#endif /* MBEDTLS_ENTROPY_NV_SEED */
+
+#if !defined(MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT)
+
+/**
+ * \brief The platform context structure.
+ *
+ * \note This structure may be used to assist platform-specific
+ * setup or teardown operations.
+ */
+typedef struct mbedtls_platform_context {
+ char MBEDTLS_PRIVATE(dummy); /**< A placeholder member, as empty structs are not portable. */
+}
+mbedtls_platform_context;
+
+#else
+#include "platform_alt.h"
+#endif /* !MBEDTLS_PLATFORM_SETUP_TEARDOWN_ALT */
+
+/**
+ * \brief This function performs any platform-specific initialization
+ * operations.
+ *
+ * \note This function should be called before any other library functions.
+ *
+ * Its implementation is platform-specific, and unless
+ * platform-specific code is provided, it does nothing.
+ *
+ * \note The usage and necessity of this function is dependent on the platform.
+ *
+ * \param ctx The platform context.
+ *
+ * \return \c 0 on success.
+ */
+int mbedtls_platform_setup(mbedtls_platform_context *ctx);
+/**
+ * \brief This function performs any platform teardown operations.
+ *
+ * \note This function should be called after every other Mbed TLS module
+ * has been correctly freed using the appropriate free function.
+ *
+ * Its implementation is platform-specific, and unless
+ * platform-specific code is provided, it does nothing.
+ *
+ * \note The usage and necessity of this function is dependent on the platform.
+ *
+ * \param ctx The platform context.
+ *
+ */
+void mbedtls_platform_teardown(mbedtls_platform_context *ctx);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* platform.h */
diff --git a/include/mbedtls/platform_time.h b/include/mbedtls/platform_time.h
new file mode 100644
index 0000000..97f1963
--- /dev/null
+++ b/include/mbedtls/platform_time.h
@@ -0,0 +1,79 @@
+/**
+ * \file platform_time.h
+ *
+ * \brief Mbed TLS Platform time abstraction
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_PLATFORM_TIME_H
+#define MBEDTLS_PLATFORM_TIME_H
+
+#include "mbedtls/build_info.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * The time_t datatype
+ */
+#if defined(MBEDTLS_PLATFORM_TIME_TYPE_MACRO)
+typedef MBEDTLS_PLATFORM_TIME_TYPE_MACRO mbedtls_time_t;
+#else
+/* For time_t */
+#include <time.h>
+typedef time_t mbedtls_time_t;
+#endif /* MBEDTLS_PLATFORM_TIME_TYPE_MACRO */
+
+#if defined(MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO)
+typedef MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO mbedtls_ms_time_t;
+#else
+#include <stdint.h>
+#include <inttypes.h>
+typedef int64_t mbedtls_ms_time_t;
+#endif /* MBEDTLS_PLATFORM_MS_TIME_TYPE_MACRO */
+
+/**
+ * \brief Get time in milliseconds.
+ *
+ * \return Monotonically-increasing current time in milliseconds.
+ *
+ * \note Define MBEDTLS_PLATFORM_MS_TIME_ALT to be able to provide an
+ * alternative implementation
+ *
+ * \warning This function returns a monotonically-increasing time value from a
+ * start time that will differ from platform to platform, and possibly
+ * from run to run of the process.
+ *
+ */
+mbedtls_ms_time_t mbedtls_ms_time(void);
+
+/*
+ * The function pointers for time
+ */
+#if defined(MBEDTLS_PLATFORM_TIME_ALT)
+extern mbedtls_time_t (*mbedtls_time)(mbedtls_time_t *time);
+
+/**
+ * \brief Set your own time function pointer
+ *
+ * \param time_func the time function implementation
+ *
+ * \return 0
+ */
+int mbedtls_platform_set_time(mbedtls_time_t (*time_func)(mbedtls_time_t *time));
+#else
+#if defined(MBEDTLS_PLATFORM_TIME_MACRO)
+#define mbedtls_time MBEDTLS_PLATFORM_TIME_MACRO
+#else
+#define mbedtls_time time
+#endif /* MBEDTLS_PLATFORM_TIME_MACRO */
+#endif /* MBEDTLS_PLATFORM_TIME_ALT */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* platform_time.h */
diff --git a/include/mbedtls/platform_util.h b/include/mbedtls/platform_util.h
new file mode 100644
index 0000000..cba02ab
--- /dev/null
+++ b/include/mbedtls/platform_util.h
@@ -0,0 +1,201 @@
+/**
+ * \file platform_util.h
+ *
+ * \brief Common and shared functions used by multiple modules in the Mbed TLS
+ * library.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_PLATFORM_UTIL_H
+#define MBEDTLS_PLATFORM_UTIL_H
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#if defined(MBEDTLS_HAVE_TIME_DATE)
+#include "mbedtls/platform_time.h"
+#include <time.h>
+#endif /* MBEDTLS_HAVE_TIME_DATE */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Internal macros meant to be called only from within the library. */
+#define MBEDTLS_INTERNAL_VALIDATE_RET(cond, ret) do { } while (0)
+#define MBEDTLS_INTERNAL_VALIDATE(cond) do { } while (0)
+
+/* Internal helper macros for deprecating API constants. */
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+#if defined(MBEDTLS_DEPRECATED_WARNING)
+#define MBEDTLS_DEPRECATED __attribute__((deprecated))
+MBEDTLS_DEPRECATED typedef char const *mbedtls_deprecated_string_constant_t;
+#define MBEDTLS_DEPRECATED_STRING_CONSTANT(VAL) \
+ ((mbedtls_deprecated_string_constant_t) (VAL))
+MBEDTLS_DEPRECATED typedef int mbedtls_deprecated_numeric_constant_t;
+#define MBEDTLS_DEPRECATED_NUMERIC_CONSTANT(VAL) \
+ ((mbedtls_deprecated_numeric_constant_t) (VAL))
+#else /* MBEDTLS_DEPRECATED_WARNING */
+#define MBEDTLS_DEPRECATED
+#define MBEDTLS_DEPRECATED_STRING_CONSTANT(VAL) VAL
+#define MBEDTLS_DEPRECATED_NUMERIC_CONSTANT(VAL) VAL
+#endif /* MBEDTLS_DEPRECATED_WARNING */
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+/* Implementation of the check-return facility.
+ * See the user documentation in mbedtls_config.h.
+ *
+ * Do not use this macro directly to annotate function: instead,
+ * use one of MBEDTLS_CHECK_RETURN_CRITICAL or MBEDTLS_CHECK_RETURN_TYPICAL
+ * depending on how important it is to check the return value.
+ */
+#if !defined(MBEDTLS_CHECK_RETURN)
+#if defined(__GNUC__)
+#define MBEDTLS_CHECK_RETURN __attribute__((__warn_unused_result__))
+#elif defined(_MSC_VER) && _MSC_VER >= 1700
+#include <sal.h>
+#define MBEDTLS_CHECK_RETURN _Check_return_
+#else
+#define MBEDTLS_CHECK_RETURN
+#endif
+#endif
+
+/** Critical-failure function
+ *
+ * This macro appearing at the beginning of the declaration of a function
+ * indicates that its return value should be checked in all applications.
+ * Omitting the check is very likely to indicate a bug in the application
+ * and will result in a compile-time warning if #MBEDTLS_CHECK_RETURN
+ * is implemented for the compiler in use.
+ *
+ * \note The use of this macro is a work in progress.
+ * This macro may be added to more functions in the future.
+ * Such an extension is not considered an API break, provided that
+ * there are near-unavoidable circumstances under which the function
+ * can fail. For example, signature/MAC/AEAD verification functions,
+ * and functions that require a random generator, are considered
+ * return-check-critical.
+ */
+#define MBEDTLS_CHECK_RETURN_CRITICAL MBEDTLS_CHECK_RETURN
+
+/** Ordinary-failure function
+ *
+ * This macro appearing at the beginning of the declaration of a function
+ * indicates that its return value should be generally be checked in portable
+ * applications. Omitting the check will result in a compile-time warning if
+ * #MBEDTLS_CHECK_RETURN is implemented for the compiler in use and
+ * #MBEDTLS_CHECK_RETURN_WARNING is enabled in the compile-time configuration.
+ *
+ * You can use #MBEDTLS_IGNORE_RETURN to explicitly ignore the return value
+ * of a function that is annotated with #MBEDTLS_CHECK_RETURN.
+ *
+ * \note The use of this macro is a work in progress.
+ * This macro will be added to more functions in the future.
+ * Eventually this should appear before most functions returning
+ * an error code (as \c int in the \c mbedtls_xxx API or
+ * as ::psa_status_t in the \c psa_xxx API).
+ */
+#if defined(MBEDTLS_CHECK_RETURN_WARNING)
+#define MBEDTLS_CHECK_RETURN_TYPICAL MBEDTLS_CHECK_RETURN
+#else
+#define MBEDTLS_CHECK_RETURN_TYPICAL
+#endif
+
+/** Benign-failure function
+ *
+ * This macro appearing at the beginning of the declaration of a function
+ * indicates that it is rarely useful to check its return value.
+ *
+ * This macro has an empty expansion. It exists for documentation purposes:
+ * a #MBEDTLS_CHECK_RETURN_OPTIONAL annotation indicates that the function
+ * has been analyzed for return-check usefulness, whereas the lack of
+ * an annotation indicates that the function has not been analyzed and its
+ * return-check usefulness is unknown.
+ */
+#define MBEDTLS_CHECK_RETURN_OPTIONAL
+
+/** \def MBEDTLS_IGNORE_RETURN
+ *
+ * Call this macro with one argument, a function call, to suppress a warning
+ * from #MBEDTLS_CHECK_RETURN due to that function call.
+ */
+#if !defined(MBEDTLS_IGNORE_RETURN)
+/* GCC doesn't silence the warning with just (void)(result).
+ * (void)!(result) is known to work up at least up to GCC 10, as well
+ * as with Clang and MSVC.
+ *
+ * https://gcc.gnu.org/onlinedocs/gcc-3.4.6/gcc/Non_002dbugs.html
+ * https://stackoverflow.com/questions/40576003/ignoring-warning-wunused-result
+ * https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66425#c34
+ */
+#define MBEDTLS_IGNORE_RETURN(result) ((void) !(result))
+#endif
+
+/* If the following macro is defined, the library is being built by the test
+ * framework, and the framework is going to provide a replacement
+ * mbedtls_platform_zeroize() using a preprocessor macro, so the function
+ * declaration should be omitted. */
+#if !defined(MBEDTLS_TEST_DEFINES_ZEROIZE) //no-check-names
+/**
+ * \brief Securely zeroize a buffer
+ *
+ * The function is meant to wipe the data contained in a buffer so
+ * that it can no longer be recovered even if the program memory
+ * is later compromised. Call this function on sensitive data
+ * stored on the stack before returning from a function, and on
+ * sensitive data stored on the heap before freeing the heap
+ * object.
+ *
+ * It is extremely difficult to guarantee that calls to
+ * mbedtls_platform_zeroize() are not removed by aggressive
+ * compiler optimizations in a portable way. For this reason, Mbed
+ * TLS provides the configuration option
+ * MBEDTLS_PLATFORM_ZEROIZE_ALT, which allows users to configure
+ * mbedtls_platform_zeroize() to use a suitable implementation for
+ * their platform and needs
+ *
+ * \param buf Buffer to be zeroized
+ * \param len Length of the buffer in bytes
+ *
+ */
+void mbedtls_platform_zeroize(void *buf, size_t len);
+#endif
+
+#if defined(MBEDTLS_HAVE_TIME_DATE)
+/**
+ * \brief Platform-specific implementation of gmtime_r()
+ *
+ * The function is a thread-safe abstraction that behaves
+ * similarly to the gmtime_r() function from Unix/POSIX.
+ *
+ * Mbed TLS will try to identify the underlying platform and
+ * make use of an appropriate underlying implementation (e.g.
+ * gmtime_r() for POSIX and gmtime_s() for Windows). If this is
+ * not possible, then gmtime() will be used. In this case, calls
+ * from the library to gmtime() will be guarded by the mutex
+ * mbedtls_threading_gmtime_mutex if MBEDTLS_THREADING_C is
+ * enabled. It is recommended that calls from outside the library
+ * are also guarded by this mutex.
+ *
+ * If MBEDTLS_PLATFORM_GMTIME_R_ALT is defined, then Mbed TLS will
+ * unconditionally use the alternative implementation for
+ * mbedtls_platform_gmtime_r() supplied by the user at compile time.
+ *
+ * \param tt Pointer to an object containing time (in seconds) since the
+ * epoch to be converted
+ * \param tm_buf Pointer to an object where the results will be stored
+ *
+ * \return Pointer to an object of type struct tm on success, otherwise
+ * NULL
+ */
+struct tm *mbedtls_platform_gmtime_r(const mbedtls_time_t *tt,
+ struct tm *tm_buf);
+#endif /* MBEDTLS_HAVE_TIME_DATE */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_PLATFORM_UTIL_H */
diff --git a/include/mbedtls/poly1305.h b/include/mbedtls/poly1305.h
new file mode 100644
index 0000000..61bcaa6
--- /dev/null
+++ b/include/mbedtls/poly1305.h
@@ -0,0 +1,168 @@
+/**
+ * \file poly1305.h
+ *
+ * \brief This file contains Poly1305 definitions and functions.
+ *
+ * Poly1305 is a one-time message authenticator that can be used to
+ * authenticate messages. Poly1305-AES was created by Daniel
+ * Bernstein https://cr.yp.to/mac/poly1305-20050329.pdf The generic
+ * Poly1305 algorithm (not tied to AES) was also standardized in RFC
+ * 7539.
+ *
+ * \author Daniel King <damaki.gh@gmail.com>
+ */
+
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_POLY1305_H
+#define MBEDTLS_POLY1305_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stdint.h>
+#include <stddef.h>
+
+/** Invalid input parameter(s). */
+#define MBEDTLS_ERR_POLY1305_BAD_INPUT_DATA -0x0057
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_POLY1305_ALT)
+
+typedef struct mbedtls_poly1305_context {
+ uint32_t MBEDTLS_PRIVATE(r)[4]; /** The value for 'r' (low 128 bits of the key). */
+ uint32_t MBEDTLS_PRIVATE(s)[4]; /** The value for 's' (high 128 bits of the key). */
+ uint32_t MBEDTLS_PRIVATE(acc)[5]; /** The accumulator number. */
+ uint8_t MBEDTLS_PRIVATE(queue)[16]; /** The current partial block of data. */
+ size_t MBEDTLS_PRIVATE(queue_len); /** The number of bytes stored in 'queue'. */
+}
+mbedtls_poly1305_context;
+
+#else /* MBEDTLS_POLY1305_ALT */
+#include "poly1305_alt.h"
+#endif /* MBEDTLS_POLY1305_ALT */
+
+/**
+ * \brief This function initializes the specified Poly1305 context.
+ *
+ * It must be the first API called before using
+ * the context.
+ *
+ * It is usually followed by a call to
+ * \c mbedtls_poly1305_starts(), then one or more calls to
+ * \c mbedtls_poly1305_update(), then one call to
+ * \c mbedtls_poly1305_finish(), then finally
+ * \c mbedtls_poly1305_free().
+ *
+ * \param ctx The Poly1305 context to initialize. This must
+ * not be \c NULL.
+ */
+void mbedtls_poly1305_init(mbedtls_poly1305_context *ctx);
+
+/**
+ * \brief This function releases and clears the specified
+ * Poly1305 context.
+ *
+ * \param ctx The Poly1305 context to clear. This may be \c NULL, in which
+ * case this function is a no-op. If it is not \c NULL, it must
+ * point to an initialized Poly1305 context.
+ */
+void mbedtls_poly1305_free(mbedtls_poly1305_context *ctx);
+
+/**
+ * \brief This function sets the one-time authentication key.
+ *
+ * \warning The key must be unique and unpredictable for each
+ * invocation of Poly1305.
+ *
+ * \param ctx The Poly1305 context to which the key should be bound.
+ * This must be initialized.
+ * \param key The buffer containing the \c 32 Byte (\c 256 Bit) key.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_poly1305_starts(mbedtls_poly1305_context *ctx,
+ const unsigned char key[32]);
+
+/**
+ * \brief This functions feeds an input buffer into an ongoing
+ * Poly1305 computation.
+ *
+ * It is called between \c mbedtls_cipher_poly1305_starts() and
+ * \c mbedtls_cipher_poly1305_finish().
+ * It can be called repeatedly to process a stream of data.
+ *
+ * \param ctx The Poly1305 context to use for the Poly1305 operation.
+ * This must be initialized and bound to a key.
+ * \param ilen The length of the input data in Bytes.
+ * Any value is accepted.
+ * \param input The buffer holding the input data.
+ * This pointer can be \c NULL if `ilen == 0`.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_poly1305_update(mbedtls_poly1305_context *ctx,
+ const unsigned char *input,
+ size_t ilen);
+
+/**
+ * \brief This function generates the Poly1305 Message
+ * Authentication Code (MAC).
+ *
+ * \param ctx The Poly1305 context to use for the Poly1305 operation.
+ * This must be initialized and bound to a key.
+ * \param mac The buffer to where the MAC is written. This must
+ * be a writable buffer of length \c 16 Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_poly1305_finish(mbedtls_poly1305_context *ctx,
+ unsigned char mac[16]);
+
+/**
+ * \brief This function calculates the Poly1305 MAC of the input
+ * buffer with the provided key.
+ *
+ * \warning The key must be unique and unpredictable for each
+ * invocation of Poly1305.
+ *
+ * \param key The buffer containing the \c 32 Byte (\c 256 Bit) key.
+ * \param ilen The length of the input data in Bytes.
+ * Any value is accepted.
+ * \param input The buffer holding the input data.
+ * This pointer can be \c NULL if `ilen == 0`.
+ * \param mac The buffer to where the MAC is written. This must be
+ * a writable buffer of length \c 16 Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_poly1305_mac(const unsigned char key[32],
+ const unsigned char *input,
+ size_t ilen,
+ unsigned char mac[16]);
+
+#if defined(MBEDTLS_SELF_TEST)
+/**
+ * \brief The Poly1305 checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_poly1305_self_test(int verbose);
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_POLY1305_H */
diff --git a/include/mbedtls/private_access.h b/include/mbedtls/private_access.h
new file mode 100644
index 0000000..580f3eb
--- /dev/null
+++ b/include/mbedtls/private_access.h
@@ -0,0 +1,20 @@
+/**
+ * \file private_access.h
+ *
+ * \brief Macro wrapper for struct's members.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_PRIVATE_ACCESS_H
+#define MBEDTLS_PRIVATE_ACCESS_H
+
+#ifndef MBEDTLS_ALLOW_PRIVATE_ACCESS
+#define MBEDTLS_PRIVATE(member) private_##member
+#else
+#define MBEDTLS_PRIVATE(member) member
+#endif
+
+#endif /* MBEDTLS_PRIVATE_ACCESS_H */
diff --git a/include/mbedtls/psa_util.h b/include/mbedtls/psa_util.h
new file mode 100644
index 0000000..643e8aa
--- /dev/null
+++ b/include/mbedtls/psa_util.h
@@ -0,0 +1,104 @@
+/**
+ * \file psa_util.h
+ *
+ * \brief Utility functions for the use of the PSA Crypto library.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_PSA_UTIL_H
+#define MBEDTLS_PSA_UTIL_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#if defined(MBEDTLS_PSA_CRYPTO_C)
+
+/* Expose whatever RNG the PSA subsystem uses to applications using the
+ * mbedtls_xxx API. The declarations and definitions here need to be
+ * consistent with the implementation in library/psa_crypto_random_impl.h.
+ * See that file for implementation documentation. */
+
+
+/* The type of a `f_rng` random generator function that many library functions
+ * take.
+ *
+ * This type name is not part of the Mbed TLS stable API. It may be renamed
+ * or moved without warning.
+ */
+typedef int mbedtls_f_rng_t(void *p_rng, unsigned char *output, size_t output_size);
+
+#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
+
+/** The random generator function for the PSA subsystem.
+ *
+ * This function is suitable as the `f_rng` random generator function
+ * parameter of many `mbedtls_xxx` functions. Use #MBEDTLS_PSA_RANDOM_STATE
+ * to obtain the \p p_rng parameter.
+ *
+ * The implementation of this function depends on the configuration of the
+ * library.
+ *
+ * \note Depending on the configuration, this may be a function or
+ * a pointer to a function.
+ *
+ * \note This function may only be used if the PSA crypto subsystem is active.
+ * This means that you must call psa_crypto_init() before any call to
+ * this function, and you must not call this function after calling
+ * mbedtls_psa_crypto_free().
+ *
+ * \param p_rng The random generator context. This must be
+ * #MBEDTLS_PSA_RANDOM_STATE. No other state is
+ * supported.
+ * \param output The buffer to fill. It must have room for
+ * \c output_size bytes.
+ * \param output_size The number of bytes to write to \p output.
+ * This function may fail if \p output_size is too
+ * large. It is guaranteed to accept any output size
+ * requested by Mbed TLS library functions. The
+ * maximum request size depends on the library
+ * configuration.
+ *
+ * \return \c 0 on success.
+ * \return An `MBEDTLS_ERR_ENTROPY_xxx`,
+ * `MBEDTLS_ERR_PLATFORM_xxx,
+ * `MBEDTLS_ERR_CTR_DRBG_xxx` or
+ * `MBEDTLS_ERR_HMAC_DRBG_xxx` on error.
+ */
+int mbedtls_psa_get_random(void *p_rng,
+ unsigned char *output,
+ size_t output_size);
+
+/** The random generator state for the PSA subsystem.
+ *
+ * This macro expands to an expression which is suitable as the `p_rng`
+ * random generator state parameter of many `mbedtls_xxx` functions.
+ * It must be used in combination with the random generator function
+ * mbedtls_psa_get_random().
+ *
+ * The implementation of this macro depends on the configuration of the
+ * library. Do not make any assumption on its nature.
+ */
+#define MBEDTLS_PSA_RANDOM_STATE NULL
+
+#else /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
+
+#if defined(MBEDTLS_CTR_DRBG_C)
+#include "mbedtls/ctr_drbg.h"
+typedef mbedtls_ctr_drbg_context mbedtls_psa_drbg_context_t;
+static mbedtls_f_rng_t *const mbedtls_psa_get_random = mbedtls_ctr_drbg_random;
+#elif defined(MBEDTLS_HMAC_DRBG_C)
+#include "mbedtls/hmac_drbg.h"
+typedef mbedtls_hmac_drbg_context mbedtls_psa_drbg_context_t;
+static mbedtls_f_rng_t *const mbedtls_psa_get_random = mbedtls_hmac_drbg_random;
+#endif
+extern mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state;
+
+#define MBEDTLS_PSA_RANDOM_STATE mbedtls_psa_random_state
+
+#endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */
+
+#endif /* MBEDTLS_PSA_CRYPTO_C */
+#endif /* MBEDTLS_PSA_UTIL_H */
diff --git a/include/mbedtls/ripemd160.h b/include/mbedtls/ripemd160.h
new file mode 100644
index 0000000..279f92b
--- /dev/null
+++ b/include/mbedtls/ripemd160.h
@@ -0,0 +1,136 @@
+/**
+ * \file ripemd160.h
+ *
+ * \brief RIPE MD-160 message digest
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_RIPEMD160_H
+#define MBEDTLS_RIPEMD160_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_RIPEMD160_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief RIPEMD-160 context structure
+ */
+typedef struct mbedtls_ripemd160_context {
+ uint32_t MBEDTLS_PRIVATE(total)[2]; /*!< number of bytes processed */
+ uint32_t MBEDTLS_PRIVATE(state)[5]; /*!< intermediate digest state */
+ unsigned char MBEDTLS_PRIVATE(buffer)[64]; /*!< data block being processed */
+}
+mbedtls_ripemd160_context;
+
+#else /* MBEDTLS_RIPEMD160_ALT */
+#include "ripemd160_alt.h"
+#endif /* MBEDTLS_RIPEMD160_ALT */
+
+/**
+ * \brief Initialize RIPEMD-160 context
+ *
+ * \param ctx RIPEMD-160 context to be initialized
+ */
+void mbedtls_ripemd160_init(mbedtls_ripemd160_context *ctx);
+
+/**
+ * \brief Clear RIPEMD-160 context
+ *
+ * \param ctx RIPEMD-160 context to be cleared
+ */
+void mbedtls_ripemd160_free(mbedtls_ripemd160_context *ctx);
+
+/**
+ * \brief Clone (the state of) a RIPEMD-160 context
+ *
+ * \param dst The destination context
+ * \param src The context to be cloned
+ */
+void mbedtls_ripemd160_clone(mbedtls_ripemd160_context *dst,
+ const mbedtls_ripemd160_context *src);
+
+/**
+ * \brief RIPEMD-160 context setup
+ *
+ * \param ctx context to be initialized
+ *
+ * \return 0 if successful
+ */
+int mbedtls_ripemd160_starts(mbedtls_ripemd160_context *ctx);
+
+/**
+ * \brief RIPEMD-160 process buffer
+ *
+ * \param ctx RIPEMD-160 context
+ * \param input buffer holding the data
+ * \param ilen length of the input data
+ *
+ * \return 0 if successful
+ */
+int mbedtls_ripemd160_update(mbedtls_ripemd160_context *ctx,
+ const unsigned char *input,
+ size_t ilen);
+
+/**
+ * \brief RIPEMD-160 final digest
+ *
+ * \param ctx RIPEMD-160 context
+ * \param output RIPEMD-160 checksum result
+ *
+ * \return 0 if successful
+ */
+int mbedtls_ripemd160_finish(mbedtls_ripemd160_context *ctx,
+ unsigned char output[20]);
+
+/**
+ * \brief RIPEMD-160 process data block (internal use only)
+ *
+ * \param ctx RIPEMD-160 context
+ * \param data buffer holding one block of data
+ *
+ * \return 0 if successful
+ */
+int mbedtls_internal_ripemd160_process(mbedtls_ripemd160_context *ctx,
+ const unsigned char data[64]);
+
+/**
+ * \brief Output = RIPEMD-160( input buffer )
+ *
+ * \param input buffer holding the data
+ * \param ilen length of the input data
+ * \param output RIPEMD-160 checksum result
+ *
+ * \return 0 if successful
+ */
+int mbedtls_ripemd160(const unsigned char *input,
+ size_t ilen,
+ unsigned char output[20]);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief Checkup routine
+ *
+ * \return 0 if successful, or 1 if the test failed
+ */
+int mbedtls_ripemd160_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* mbedtls_ripemd160.h */
diff --git a/include/mbedtls/rsa.h b/include/mbedtls/rsa.h
new file mode 100644
index 0000000..be831f1
--- /dev/null
+++ b/include/mbedtls/rsa.h
@@ -0,0 +1,1152 @@
+/**
+ * \file rsa.h
+ *
+ * \brief This file provides an API for the RSA public-key cryptosystem.
+ *
+ * The RSA public-key cryptosystem is defined in <em>Public-Key
+ * Cryptography Standards (PKCS) #1 v1.5: RSA Encryption</em>
+ * and <em>Public-Key Cryptography Standards (PKCS) #1 v2.1:
+ * RSA Cryptography Specifications</em>.
+ *
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_RSA_H
+#define MBEDTLS_RSA_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/bignum.h"
+#include "mbedtls/md.h"
+
+#if defined(MBEDTLS_THREADING_C)
+#include "mbedtls/threading.h"
+#endif
+
+/*
+ * RSA Error codes
+ */
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_RSA_BAD_INPUT_DATA -0x4080
+/** Input data contains invalid padding and is rejected. */
+#define MBEDTLS_ERR_RSA_INVALID_PADDING -0x4100
+/** Something failed during generation of a key. */
+#define MBEDTLS_ERR_RSA_KEY_GEN_FAILED -0x4180
+/** Key failed to pass the validity check of the library. */
+#define MBEDTLS_ERR_RSA_KEY_CHECK_FAILED -0x4200
+/** The public key operation failed. */
+#define MBEDTLS_ERR_RSA_PUBLIC_FAILED -0x4280
+/** The private key operation failed. */
+#define MBEDTLS_ERR_RSA_PRIVATE_FAILED -0x4300
+/** The PKCS#1 verification failed. */
+#define MBEDTLS_ERR_RSA_VERIFY_FAILED -0x4380
+/** The output buffer for decryption is not large enough. */
+#define MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE -0x4400
+/** The random generator failed to generate non-zeros. */
+#define MBEDTLS_ERR_RSA_RNG_FAILED -0x4480
+
+/*
+ * RSA constants
+ */
+
+#define MBEDTLS_RSA_PKCS_V15 0 /**< Use PKCS#1 v1.5 encoding. */
+#define MBEDTLS_RSA_PKCS_V21 1 /**< Use PKCS#1 v2.1 encoding. */
+
+#define MBEDTLS_RSA_SIGN 1 /**< Identifier for RSA signature operations. */
+#define MBEDTLS_RSA_CRYPT 2 /**< Identifier for RSA encryption and decryption operations. */
+
+#define MBEDTLS_RSA_SALT_LEN_ANY -1
+
+/*
+ * The above constants may be used even if the RSA module is compile out,
+ * eg for alternative (PKCS#11) RSA implementations in the PK layers.
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_RSA_ALT)
+// Regular implementation
+//
+
+#if !defined(MBEDTLS_RSA_GEN_KEY_MIN_BITS)
+#define MBEDTLS_RSA_GEN_KEY_MIN_BITS 1024
+#elif MBEDTLS_RSA_GEN_KEY_MIN_BITS < 128
+#error "MBEDTLS_RSA_GEN_KEY_MIN_BITS must be at least 128 bits"
+#endif
+
+/**
+ * \brief The RSA context structure.
+ */
+typedef struct mbedtls_rsa_context {
+ int MBEDTLS_PRIVATE(ver); /*!< Reserved for internal purposes.
+ * Do not set this field in application
+ * code. Its meaning might change without
+ * notice. */
+ size_t MBEDTLS_PRIVATE(len); /*!< The size of \p N in Bytes. */
+
+ mbedtls_mpi MBEDTLS_PRIVATE(N); /*!< The public modulus. */
+ mbedtls_mpi MBEDTLS_PRIVATE(E); /*!< The public exponent. */
+
+ mbedtls_mpi MBEDTLS_PRIVATE(D); /*!< The private exponent. */
+ mbedtls_mpi MBEDTLS_PRIVATE(P); /*!< The first prime factor. */
+ mbedtls_mpi MBEDTLS_PRIVATE(Q); /*!< The second prime factor. */
+
+ mbedtls_mpi MBEDTLS_PRIVATE(DP); /*!< <code>D % (P - 1)</code>. */
+ mbedtls_mpi MBEDTLS_PRIVATE(DQ); /*!< <code>D % (Q - 1)</code>. */
+ mbedtls_mpi MBEDTLS_PRIVATE(QP); /*!< <code>1 / (Q % P)</code>. */
+
+ mbedtls_mpi MBEDTLS_PRIVATE(RN); /*!< cached <code>R^2 mod N</code>. */
+
+ mbedtls_mpi MBEDTLS_PRIVATE(RP); /*!< cached <code>R^2 mod P</code>. */
+ mbedtls_mpi MBEDTLS_PRIVATE(RQ); /*!< cached <code>R^2 mod Q</code>. */
+
+ mbedtls_mpi MBEDTLS_PRIVATE(Vi); /*!< The cached blinding value. */
+ mbedtls_mpi MBEDTLS_PRIVATE(Vf); /*!< The cached un-blinding value. */
+
+ int MBEDTLS_PRIVATE(padding); /*!< Selects padding mode:
+ #MBEDTLS_RSA_PKCS_V15 for 1.5 padding and
+ #MBEDTLS_RSA_PKCS_V21 for OAEP or PSS. */
+ int MBEDTLS_PRIVATE(hash_id); /*!< Hash identifier of mbedtls_md_type_t type,
+ as specified in md.h for use in the MGF
+ mask generating function used in the
+ EME-OAEP and EMSA-PSS encodings. */
+#if defined(MBEDTLS_THREADING_C)
+ /* Invariant: the mutex is initialized iff ver != 0. */
+ mbedtls_threading_mutex_t MBEDTLS_PRIVATE(mutex); /*!< Thread-safety mutex. */
+#endif
+}
+mbedtls_rsa_context;
+
+#else /* MBEDTLS_RSA_ALT */
+#include "rsa_alt.h"
+#endif /* MBEDTLS_RSA_ALT */
+
+/**
+ * \brief This function initializes an RSA context.
+ *
+ * \note This function initializes the padding and the hash
+ * identifier to respectively #MBEDTLS_RSA_PKCS_V15 and
+ * #MBEDTLS_MD_NONE. See mbedtls_rsa_set_padding() for more
+ * information about those parameters.
+ *
+ * \param ctx The RSA context to initialize. This must not be \c NULL.
+ */
+void mbedtls_rsa_init(mbedtls_rsa_context *ctx);
+
+/**
+ * \brief This function sets padding for an already initialized RSA
+ * context.
+ *
+ * \note Set padding to #MBEDTLS_RSA_PKCS_V21 for the RSAES-OAEP
+ * encryption scheme and the RSASSA-PSS signature scheme.
+ *
+ * \note The \p hash_id parameter is ignored when using
+ * #MBEDTLS_RSA_PKCS_V15 padding.
+ *
+ * \note The choice of padding mode is strictly enforced for private
+ * key operations, since there might be security concerns in
+ * mixing padding modes. For public key operations it is
+ * a default value, which can be overridden by calling specific
+ * \c mbedtls_rsa_rsaes_xxx or \c mbedtls_rsa_rsassa_xxx
+ * functions.
+ *
+ * \note The hash selected in \p hash_id is always used for OEAP
+ * encryption. For PSS signatures, it is always used for
+ * making signatures, but can be overridden for verifying them.
+ * If set to #MBEDTLS_MD_NONE, it is always overridden.
+ *
+ * \param ctx The initialized RSA context to be configured.
+ * \param padding The padding mode to use. This must be either
+ * #MBEDTLS_RSA_PKCS_V15 or #MBEDTLS_RSA_PKCS_V21.
+ * \param hash_id The hash identifier for PSS or OAEP, if \p padding is
+ * #MBEDTLS_RSA_PKCS_V21. #MBEDTLS_MD_NONE is accepted by this
+ * function but may be not suitable for some operations.
+ * Ignored if \p padding is #MBEDTLS_RSA_PKCS_V15.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_RSA_INVALID_PADDING failure:
+ * \p padding or \p hash_id is invalid.
+ */
+int mbedtls_rsa_set_padding(mbedtls_rsa_context *ctx, int padding,
+ mbedtls_md_type_t hash_id);
+
+/**
+ * \brief This function retrieves padding mode of initialized
+ * RSA context.
+ *
+ * \param ctx The initialized RSA context.
+ *
+ * \return RSA padding mode.
+ *
+ */
+int mbedtls_rsa_get_padding_mode(const mbedtls_rsa_context *ctx);
+
+/**
+ * \brief This function retrieves hash identifier of mbedtls_md_type_t
+ * type.
+ *
+ * \param ctx The initialized RSA context.
+ *
+ * \return Hash identifier of mbedtls_md_type_t type.
+ *
+ */
+int mbedtls_rsa_get_md_alg(const mbedtls_rsa_context *ctx);
+
+/**
+ * \brief This function imports a set of core parameters into an
+ * RSA context.
+ *
+ * \note This function can be called multiple times for successive
+ * imports, if the parameters are not simultaneously present.
+ *
+ * Any sequence of calls to this function should be followed
+ * by a call to mbedtls_rsa_complete(), which checks and
+ * completes the provided information to a ready-for-use
+ * public or private RSA key.
+ *
+ * \note See mbedtls_rsa_complete() for more information on which
+ * parameters are necessary to set up a private or public
+ * RSA key.
+ *
+ * \note The imported parameters are copied and need not be preserved
+ * for the lifetime of the RSA context being set up.
+ *
+ * \param ctx The initialized RSA context to store the parameters in.
+ * \param N The RSA modulus. This may be \c NULL.
+ * \param P The first prime factor of \p N. This may be \c NULL.
+ * \param Q The second prime factor of \p N. This may be \c NULL.
+ * \param D The private exponent. This may be \c NULL.
+ * \param E The public exponent. This may be \c NULL.
+ *
+ * \return \c 0 on success.
+ * \return A non-zero error code on failure.
+ */
+int mbedtls_rsa_import(mbedtls_rsa_context *ctx,
+ const mbedtls_mpi *N,
+ const mbedtls_mpi *P, const mbedtls_mpi *Q,
+ const mbedtls_mpi *D, const mbedtls_mpi *E);
+
+/**
+ * \brief This function imports core RSA parameters, in raw big-endian
+ * binary format, into an RSA context.
+ *
+ * \note This function can be called multiple times for successive
+ * imports, if the parameters are not simultaneously present.
+ *
+ * Any sequence of calls to this function should be followed
+ * by a call to mbedtls_rsa_complete(), which checks and
+ * completes the provided information to a ready-for-use
+ * public or private RSA key.
+ *
+ * \note See mbedtls_rsa_complete() for more information on which
+ * parameters are necessary to set up a private or public
+ * RSA key.
+ *
+ * \note The imported parameters are copied and need not be preserved
+ * for the lifetime of the RSA context being set up.
+ *
+ * \param ctx The initialized RSA context to store the parameters in.
+ * \param N The RSA modulus. This may be \c NULL.
+ * \param N_len The Byte length of \p N; it is ignored if \p N == NULL.
+ * \param P The first prime factor of \p N. This may be \c NULL.
+ * \param P_len The Byte length of \p P; it is ignored if \p P == NULL.
+ * \param Q The second prime factor of \p N. This may be \c NULL.
+ * \param Q_len The Byte length of \p Q; it is ignored if \p Q == NULL.
+ * \param D The private exponent. This may be \c NULL.
+ * \param D_len The Byte length of \p D; it is ignored if \p D == NULL.
+ * \param E The public exponent. This may be \c NULL.
+ * \param E_len The Byte length of \p E; it is ignored if \p E == NULL.
+ *
+ * \return \c 0 on success.
+ * \return A non-zero error code on failure.
+ */
+int mbedtls_rsa_import_raw(mbedtls_rsa_context *ctx,
+ unsigned char const *N, size_t N_len,
+ unsigned char const *P, size_t P_len,
+ unsigned char const *Q, size_t Q_len,
+ unsigned char const *D, size_t D_len,
+ unsigned char const *E, size_t E_len);
+
+/**
+ * \brief This function completes an RSA context from
+ * a set of imported core parameters.
+ *
+ * To setup an RSA public key, precisely \c N and \c E
+ * must have been imported.
+ *
+ * To setup an RSA private key, sufficient information must
+ * be present for the other parameters to be derivable.
+ *
+ * The default implementation supports the following:
+ * <ul><li>Derive \c P, \c Q from \c N, \c D, \c E.</li>
+ * <li>Derive \c N, \c D from \c P, \c Q, \c E.</li></ul>
+ * Alternative implementations need not support these.
+ *
+ * If this function runs successfully, it guarantees that
+ * the RSA context can be used for RSA operations without
+ * the risk of failure or crash.
+ *
+ * \warning This function need not perform consistency checks
+ * for the imported parameters. In particular, parameters that
+ * are not needed by the implementation might be silently
+ * discarded and left unchecked. To check the consistency
+ * of the key material, see mbedtls_rsa_check_privkey().
+ *
+ * \param ctx The initialized RSA context holding imported parameters.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_RSA_BAD_INPUT_DATA if the attempted derivations
+ * failed.
+ *
+ */
+int mbedtls_rsa_complete(mbedtls_rsa_context *ctx);
+
+/**
+ * \brief This function exports the core parameters of an RSA key.
+ *
+ * If this function runs successfully, the non-NULL buffers
+ * pointed to by \p N, \p P, \p Q, \p D, and \p E are fully
+ * written, with additional unused space filled leading by
+ * zero Bytes.
+ *
+ * Possible reasons for returning
+ * #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:<ul>
+ * <li>An alternative RSA implementation is in use, which
+ * stores the key externally, and either cannot or should
+ * not export it into RAM.</li>
+ * <li>A SW or HW implementation might not support a certain
+ * deduction. For example, \p P, \p Q from \p N, \p D,
+ * and \p E if the former are not part of the
+ * implementation.</li></ul>
+ *
+ * If the function fails due to an unsupported operation,
+ * the RSA context stays intact and remains usable.
+ *
+ * \param ctx The initialized RSA context.
+ * \param N The MPI to hold the RSA modulus.
+ * This may be \c NULL if this field need not be exported.
+ * \param P The MPI to hold the first prime factor of \p N.
+ * This may be \c NULL if this field need not be exported.
+ * \param Q The MPI to hold the second prime factor of \p N.
+ * This may be \c NULL if this field need not be exported.
+ * \param D The MPI to hold the private exponent.
+ * This may be \c NULL if this field need not be exported.
+ * \param E The MPI to hold the public exponent.
+ * This may be \c NULL if this field need not be exported.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED if exporting the
+ * requested parameters cannot be done due to missing
+ * functionality or because of security policies.
+ * \return A non-zero return code on any other failure.
+ *
+ */
+int mbedtls_rsa_export(const mbedtls_rsa_context *ctx,
+ mbedtls_mpi *N, mbedtls_mpi *P, mbedtls_mpi *Q,
+ mbedtls_mpi *D, mbedtls_mpi *E);
+
+/**
+ * \brief This function exports core parameters of an RSA key
+ * in raw big-endian binary format.
+ *
+ * If this function runs successfully, the non-NULL buffers
+ * pointed to by \p N, \p P, \p Q, \p D, and \p E are fully
+ * written, with additional unused space filled leading by
+ * zero Bytes.
+ *
+ * Possible reasons for returning
+ * #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED:<ul>
+ * <li>An alternative RSA implementation is in use, which
+ * stores the key externally, and either cannot or should
+ * not export it into RAM.</li>
+ * <li>A SW or HW implementation might not support a certain
+ * deduction. For example, \p P, \p Q from \p N, \p D,
+ * and \p E if the former are not part of the
+ * implementation.</li></ul>
+ * If the function fails due to an unsupported operation,
+ * the RSA context stays intact and remains usable.
+ *
+ * \note The length parameters are ignored if the corresponding
+ * buffer pointers are NULL.
+ *
+ * \param ctx The initialized RSA context.
+ * \param N The Byte array to store the RSA modulus,
+ * or \c NULL if this field need not be exported.
+ * \param N_len The size of the buffer for the modulus.
+ * \param P The Byte array to hold the first prime factor of \p N,
+ * or \c NULL if this field need not be exported.
+ * \param P_len The size of the buffer for the first prime factor.
+ * \param Q The Byte array to hold the second prime factor of \p N,
+ * or \c NULL if this field need not be exported.
+ * \param Q_len The size of the buffer for the second prime factor.
+ * \param D The Byte array to hold the private exponent,
+ * or \c NULL if this field need not be exported.
+ * \param D_len The size of the buffer for the private exponent.
+ * \param E The Byte array to hold the public exponent,
+ * or \c NULL if this field need not be exported.
+ * \param E_len The size of the buffer for the public exponent.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_PLATFORM_FEATURE_UNSUPPORTED if exporting the
+ * requested parameters cannot be done due to missing
+ * functionality or because of security policies.
+ * \return A non-zero return code on any other failure.
+ */
+int mbedtls_rsa_export_raw(const mbedtls_rsa_context *ctx,
+ unsigned char *N, size_t N_len,
+ unsigned char *P, size_t P_len,
+ unsigned char *Q, size_t Q_len,
+ unsigned char *D, size_t D_len,
+ unsigned char *E, size_t E_len);
+
+/**
+ * \brief This function exports CRT parameters of a private RSA key.
+ *
+ * \note Alternative RSA implementations not using CRT-parameters
+ * internally can implement this function based on
+ * mbedtls_rsa_deduce_opt().
+ *
+ * \param ctx The initialized RSA context.
+ * \param DP The MPI to hold \c D modulo `P-1`,
+ * or \c NULL if it need not be exported.
+ * \param DQ The MPI to hold \c D modulo `Q-1`,
+ * or \c NULL if it need not be exported.
+ * \param QP The MPI to hold modular inverse of \c Q modulo \c P,
+ * or \c NULL if it need not be exported.
+ *
+ * \return \c 0 on success.
+ * \return A non-zero error code on failure.
+ *
+ */
+int mbedtls_rsa_export_crt(const mbedtls_rsa_context *ctx,
+ mbedtls_mpi *DP, mbedtls_mpi *DQ, mbedtls_mpi *QP);
+
+/**
+ * \brief This function retrieves the length of RSA modulus in Bytes.
+ *
+ * \param ctx The initialized RSA context.
+ *
+ * \return The length of the RSA modulus in Bytes.
+ *
+ */
+size_t mbedtls_rsa_get_len(const mbedtls_rsa_context *ctx);
+
+/**
+ * \brief This function generates an RSA keypair.
+ *
+ * \note mbedtls_rsa_init() must be called before this function,
+ * to set up the RSA context.
+ *
+ * \param ctx The initialized RSA context used to hold the key.
+ * \param f_rng The RNG function to be used for key generation.
+ * This is mandatory and must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng.
+ * This may be \c NULL if \p f_rng doesn't need a context.
+ * \param nbits The size of the public key in bits.
+ * \param exponent The public exponent to use. For example, \c 65537.
+ * This must be odd and greater than \c 1.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_gen_key(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ unsigned int nbits, int exponent);
+
+/**
+ * \brief This function checks if a context contains at least an RSA
+ * public key.
+ *
+ * If the function runs successfully, it is guaranteed that
+ * enough information is present to perform an RSA public key
+ * operation using mbedtls_rsa_public().
+ *
+ * \param ctx The initialized RSA context to check.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ *
+ */
+int mbedtls_rsa_check_pubkey(const mbedtls_rsa_context *ctx);
+
+/**
+ * \brief This function checks if a context contains an RSA private key
+ * and perform basic consistency checks.
+ *
+ * \note The consistency checks performed by this function not only
+ * ensure that mbedtls_rsa_private() can be called successfully
+ * on the given context, but that the various parameters are
+ * mutually consistent with high probability, in the sense that
+ * mbedtls_rsa_public() and mbedtls_rsa_private() are inverses.
+ *
+ * \warning This function should catch accidental misconfigurations
+ * like swapping of parameters, but it cannot establish full
+ * trust in neither the quality nor the consistency of the key
+ * material that was used to setup the given RSA context:
+ * <ul><li>Consistency: Imported parameters that are irrelevant
+ * for the implementation might be silently dropped. If dropped,
+ * the current function does not have access to them,
+ * and therefore cannot check them. See mbedtls_rsa_complete().
+ * If you want to check the consistency of the entire
+ * content of a PKCS1-encoded RSA private key, for example, you
+ * should use mbedtls_rsa_validate_params() before setting
+ * up the RSA context.
+ * Additionally, if the implementation performs empirical checks,
+ * these checks substantiate but do not guarantee consistency.</li>
+ * <li>Quality: This function is not expected to perform
+ * extended quality assessments like checking that the prime
+ * factors are safe. Additionally, it is the responsibility of the
+ * user to ensure the trustworthiness of the source of his RSA
+ * parameters, which goes beyond what is effectively checkable
+ * by the library.</li></ul>
+ *
+ * \param ctx The initialized RSA context to check.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_check_privkey(const mbedtls_rsa_context *ctx);
+
+/**
+ * \brief This function checks a public-private RSA key pair.
+ *
+ * It checks each of the contexts, and makes sure they match.
+ *
+ * \param pub The initialized RSA context holding the public key.
+ * \param prv The initialized RSA context holding the private key.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_check_pub_priv(const mbedtls_rsa_context *pub,
+ const mbedtls_rsa_context *prv);
+
+/**
+ * \brief This function performs an RSA public key operation.
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param input The input buffer. This must be a readable buffer
+ * of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ * \param output The output buffer. This must be a writable buffer
+ * of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ *
+ * \note This function does not handle message padding.
+ *
+ * \note Make sure to set \p input[0] = 0 or ensure that
+ * input is smaller than \c N.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_public(mbedtls_rsa_context *ctx,
+ const unsigned char *input,
+ unsigned char *output);
+
+/**
+ * \brief This function performs an RSA private key operation.
+ *
+ * \note Blinding is used if and only if a PRNG is provided.
+ *
+ * \note If blinding is used, both the base of exponentiation
+ * and the exponent are blinded, providing protection
+ * against some side-channel attacks.
+ *
+ * \warning It is deprecated and a security risk to not provide
+ * a PRNG here and thereby prevent the use of blinding.
+ * Future versions of the library may enforce the presence
+ * of a PRNG.
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG function, used for blinding. It is mandatory.
+ * \param p_rng The RNG context to pass to \p f_rng. This may be \c NULL
+ * if \p f_rng doesn't need a context.
+ * \param input The input buffer. This must be a readable buffer
+ * of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ * \param output The output buffer. This must be a writable buffer
+ * of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ *
+ */
+int mbedtls_rsa_private(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ const unsigned char *input,
+ unsigned char *output);
+
+/**
+ * \brief This function adds the message padding, then performs an RSA
+ * operation.
+ *
+ * It is the generic wrapper for performing a PKCS#1 encryption
+ * operation.
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG to use. It is used for padding generation
+ * and it is mandatory.
+ * \param p_rng The RNG context to be passed to \p f_rng. May be
+ * \c NULL if \p f_rng doesn't need a context argument.
+ * \param ilen The length of the plaintext in Bytes.
+ * \param input The input data to encrypt. This must be a readable
+ * buffer of size \p ilen Bytes. It may be \c NULL if
+ * `ilen == 0`.
+ * \param output The output buffer. This must be a writable buffer
+ * of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_pkcs1_encrypt(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ size_t ilen,
+ const unsigned char *input,
+ unsigned char *output);
+
+/**
+ * \brief This function performs a PKCS#1 v1.5 encryption operation
+ * (RSAES-PKCS1-v1_5-ENCRYPT).
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG function to use. It is mandatory and used for
+ * padding generation.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may
+ * be \c NULL if \p f_rng doesn't need a context argument.
+ * \param ilen The length of the plaintext in Bytes.
+ * \param input The input data to encrypt. This must be a readable
+ * buffer of size \p ilen Bytes. It may be \c NULL if
+ * `ilen == 0`.
+ * \param output The output buffer. This must be a writable buffer
+ * of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_rsaes_pkcs1_v15_encrypt(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ size_t ilen,
+ const unsigned char *input,
+ unsigned char *output);
+
+/**
+ * \brief This function performs a PKCS#1 v2.1 OAEP encryption
+ * operation (RSAES-OAEP-ENCRYPT).
+ *
+ * \note The output buffer must be as large as the size
+ * of ctx->N. For example, 128 Bytes if RSA-1024 is used.
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG function to use. This is needed for padding
+ * generation and is mandatory.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may
+ * be \c NULL if \p f_rng doesn't need a context argument.
+ * \param label The buffer holding the custom label to use.
+ * This must be a readable buffer of length \p label_len
+ * Bytes. It may be \c NULL if \p label_len is \c 0.
+ * \param label_len The length of the label in Bytes.
+ * \param ilen The length of the plaintext buffer \p input in Bytes.
+ * \param input The input data to encrypt. This must be a readable
+ * buffer of size \p ilen Bytes. It may be \c NULL if
+ * `ilen == 0`.
+ * \param output The output buffer. This must be a writable buffer
+ * of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_rsaes_oaep_encrypt(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ const unsigned char *label, size_t label_len,
+ size_t ilen,
+ const unsigned char *input,
+ unsigned char *output);
+
+/**
+ * \brief This function performs an RSA operation, then removes the
+ * message padding.
+ *
+ * It is the generic wrapper for performing a PKCS#1 decryption
+ * operation.
+ *
+ * \warning When \p ctx->padding is set to #MBEDTLS_RSA_PKCS_V15,
+ * mbedtls_rsa_rsaes_pkcs1_v15_decrypt() is called, which is an
+ * inherently dangerous function (CWE-242).
+ *
+ * \note The output buffer length \c output_max_len should be
+ * as large as the size \p ctx->len of \p ctx->N (for example,
+ * 128 Bytes if RSA-1024 is used) to be able to hold an
+ * arbitrary decrypted message. If it is not large enough to
+ * hold the decryption of the particular ciphertext provided,
+ * the function returns \c MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE.
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG function. This is used for blinding and is
+ * mandatory; see mbedtls_rsa_private() for more.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context.
+ * \param olen The address at which to store the length of
+ * the plaintext. This must not be \c NULL.
+ * \param input The ciphertext buffer. This must be a readable buffer
+ * of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ * \param output The buffer used to hold the plaintext. This must
+ * be a writable buffer of length \p output_max_len Bytes.
+ * \param output_max_len The length in Bytes of the output buffer \p output.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_pkcs1_decrypt(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ size_t *olen,
+ const unsigned char *input,
+ unsigned char *output,
+ size_t output_max_len);
+
+/**
+ * \brief This function performs a PKCS#1 v1.5 decryption
+ * operation (RSAES-PKCS1-v1_5-DECRYPT).
+ *
+ * \warning This is an inherently dangerous function (CWE-242). Unless
+ * it is used in a side channel free and safe way (eg.
+ * implementing the TLS protocol as per 7.4.7.1 of RFC 5246),
+ * the calling code is vulnerable.
+ *
+ * \note The output buffer length \c output_max_len should be
+ * as large as the size \p ctx->len of \p ctx->N, for example,
+ * 128 Bytes if RSA-1024 is used, to be able to hold an
+ * arbitrary decrypted message. If it is not large enough to
+ * hold the decryption of the particular ciphertext provided,
+ * the function returns #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE.
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG function. This is used for blinding and is
+ * mandatory; see mbedtls_rsa_private() for more.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context.
+ * \param olen The address at which to store the length of
+ * the plaintext. This must not be \c NULL.
+ * \param input The ciphertext buffer. This must be a readable buffer
+ * of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ * \param output The buffer used to hold the plaintext. This must
+ * be a writable buffer of length \p output_max_len Bytes.
+ * \param output_max_len The length in Bytes of the output buffer \p output.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ *
+ */
+int mbedtls_rsa_rsaes_pkcs1_v15_decrypt(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ size_t *olen,
+ const unsigned char *input,
+ unsigned char *output,
+ size_t output_max_len);
+
+/**
+ * \brief This function performs a PKCS#1 v2.1 OAEP decryption
+ * operation (RSAES-OAEP-DECRYPT).
+ *
+ * \note The output buffer length \c output_max_len should be
+ * as large as the size \p ctx->len of \p ctx->N, for
+ * example, 128 Bytes if RSA-1024 is used, to be able to
+ * hold an arbitrary decrypted message. If it is not
+ * large enough to hold the decryption of the particular
+ * ciphertext provided, the function returns
+ * #MBEDTLS_ERR_RSA_OUTPUT_TOO_LARGE.
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG function. This is used for blinding and is
+ * mandatory.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be
+ * \c NULL if \p f_rng doesn't need a context.
+ * \param label The buffer holding the custom label to use.
+ * This must be a readable buffer of length \p label_len
+ * Bytes. It may be \c NULL if \p label_len is \c 0.
+ * \param label_len The length of the label in Bytes.
+ * \param olen The address at which to store the length of
+ * the plaintext. This must not be \c NULL.
+ * \param input The ciphertext buffer. This must be a readable buffer
+ * of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ * \param output The buffer used to hold the plaintext. This must
+ * be a writable buffer of length \p output_max_len Bytes.
+ * \param output_max_len The length in Bytes of the output buffer \p output.
+ *
+ * \return \c 0 on success.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_rsaes_oaep_decrypt(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ const unsigned char *label, size_t label_len,
+ size_t *olen,
+ const unsigned char *input,
+ unsigned char *output,
+ size_t output_max_len);
+
+/**
+ * \brief This function performs a private RSA operation to sign
+ * a message digest using PKCS#1.
+ *
+ * It is the generic wrapper for performing a PKCS#1
+ * signature.
+ *
+ * \note The \p sig buffer must be as large as the size
+ * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used.
+ *
+ * \note For PKCS#1 v2.1 encoding, see comments on
+ * mbedtls_rsa_rsassa_pss_sign() for details on
+ * \p md_alg and \p hash_id.
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG function to use. This is mandatory and
+ * must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL
+ * if \p f_rng doesn't need a context argument.
+ * \param md_alg The message-digest algorithm used to hash the original data.
+ * Use #MBEDTLS_MD_NONE for signing raw data.
+ * \param hashlen The length of the message digest or raw data in Bytes.
+ * If \p md_alg is not #MBEDTLS_MD_NONE, this must match the
+ * output length of the corresponding hash algorithm.
+ * \param hash The buffer holding the message digest or raw data.
+ * This must be a readable buffer of at least \p hashlen Bytes.
+ * \param sig The buffer to hold the signature. This must be a writable
+ * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus. A buffer length of
+ * #MBEDTLS_MPI_MAX_SIZE is always safe.
+ *
+ * \return \c 0 if the signing operation was successful.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_pkcs1_sign(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ mbedtls_md_type_t md_alg,
+ unsigned int hashlen,
+ const unsigned char *hash,
+ unsigned char *sig);
+
+/**
+ * \brief This function performs a PKCS#1 v1.5 signature
+ * operation (RSASSA-PKCS1-v1_5-SIGN).
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG function. This is used for blinding and is
+ * mandatory; see mbedtls_rsa_private() for more.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL
+ * if \p f_rng doesn't need a context argument.
+ * \param md_alg The message-digest algorithm used to hash the original data.
+ * Use #MBEDTLS_MD_NONE for signing raw data.
+ * \param hashlen The length of the message digest or raw data in Bytes.
+ * If \p md_alg is not #MBEDTLS_MD_NONE, this must match the
+ * output length of the corresponding hash algorithm.
+ * \param hash The buffer holding the message digest or raw data.
+ * This must be a readable buffer of at least \p hashlen Bytes.
+ * \param sig The buffer to hold the signature. This must be a writable
+ * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus. A buffer length of
+ * #MBEDTLS_MPI_MAX_SIZE is always safe.
+ *
+ * \return \c 0 if the signing operation was successful.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_rsassa_pkcs1_v15_sign(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ mbedtls_md_type_t md_alg,
+ unsigned int hashlen,
+ const unsigned char *hash,
+ unsigned char *sig);
+
+/**
+ * \brief This function performs a PKCS#1 v2.1 PSS signature
+ * operation (RSASSA-PSS-SIGN).
+ *
+ * \note The \c hash_id set in \p ctx by calling
+ * mbedtls_rsa_set_padding() selects the hash used for the
+ * encoding operation and for the mask generation function
+ * (MGF1). For more details on the encoding operation and the
+ * mask generation function, consult <em>RFC-3447: Public-Key
+ * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography
+ * Specifications</em>.
+ *
+ * \note This function enforces that the provided salt length complies
+ * with FIPS 186-4 §5.5 (e) and RFC 8017 (PKCS#1 v2.2) §9.1.1
+ * step 3. The constraint is that the hash length plus the salt
+ * length plus 2 bytes must be at most the key length. If this
+ * constraint is not met, this function returns
+ * #MBEDTLS_ERR_RSA_BAD_INPUT_DATA.
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG function. It is mandatory and must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL
+ * if \p f_rng doesn't need a context argument.
+ * \param md_alg The message-digest algorithm used to hash the original data.
+ * Use #MBEDTLS_MD_NONE for signing raw data.
+ * \param hashlen The length of the message digest or raw data in Bytes.
+ * If \p md_alg is not #MBEDTLS_MD_NONE, this must match the
+ * output length of the corresponding hash algorithm.
+ * \param hash The buffer holding the message digest or raw data.
+ * This must be a readable buffer of at least \p hashlen Bytes.
+ * \param saltlen The length of the salt that should be used.
+ * If passed #MBEDTLS_RSA_SALT_LEN_ANY, the function will use
+ * the largest possible salt length up to the hash length,
+ * which is the largest permitted by some standards including
+ * FIPS 186-4 §5.5.
+ * \param sig The buffer to hold the signature. This must be a writable
+ * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus. A buffer length of
+ * #MBEDTLS_MPI_MAX_SIZE is always safe.
+ *
+ * \return \c 0 if the signing operation was successful.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_rsassa_pss_sign_ext(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ mbedtls_md_type_t md_alg,
+ unsigned int hashlen,
+ const unsigned char *hash,
+ int saltlen,
+ unsigned char *sig);
+
+/**
+ * \brief This function performs a PKCS#1 v2.1 PSS signature
+ * operation (RSASSA-PSS-SIGN).
+ *
+ * \note The \c hash_id set in \p ctx by calling
+ * mbedtls_rsa_set_padding() selects the hash used for the
+ * encoding operation and for the mask generation function
+ * (MGF1). For more details on the encoding operation and the
+ * mask generation function, consult <em>RFC-3447: Public-Key
+ * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography
+ * Specifications</em>.
+ *
+ * \note This function always uses the maximum possible salt size,
+ * up to the length of the payload hash. This choice of salt
+ * size complies with FIPS 186-4 §5.5 (e) and RFC 8017 (PKCS#1
+ * v2.2) §9.1.1 step 3. Furthermore this function enforces a
+ * minimum salt size which is the hash size minus 2 bytes. If
+ * this minimum size is too large given the key size (the salt
+ * size, plus the hash size, plus 2 bytes must be no more than
+ * the key size in bytes), this function returns
+ * #MBEDTLS_ERR_RSA_BAD_INPUT_DATA.
+ *
+ * \param ctx The initialized RSA context to use.
+ * \param f_rng The RNG function. It is mandatory and must not be \c NULL.
+ * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL
+ * if \p f_rng doesn't need a context argument.
+ * \param md_alg The message-digest algorithm used to hash the original data.
+ * Use #MBEDTLS_MD_NONE for signing raw data.
+ * \param hashlen The length of the message digest or raw data in Bytes.
+ * If \p md_alg is not #MBEDTLS_MD_NONE, this must match the
+ * output length of the corresponding hash algorithm.
+ * \param hash The buffer holding the message digest or raw data.
+ * This must be a readable buffer of at least \p hashlen Bytes.
+ * \param sig The buffer to hold the signature. This must be a writable
+ * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus. A buffer length of
+ * #MBEDTLS_MPI_MAX_SIZE is always safe.
+ *
+ * \return \c 0 if the signing operation was successful.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_rsassa_pss_sign(mbedtls_rsa_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng,
+ mbedtls_md_type_t md_alg,
+ unsigned int hashlen,
+ const unsigned char *hash,
+ unsigned char *sig);
+
+/**
+ * \brief This function performs a public RSA operation and checks
+ * the message digest.
+ *
+ * This is the generic wrapper for performing a PKCS#1
+ * verification.
+ *
+ * \note For PKCS#1 v2.1 encoding, see comments on
+ * mbedtls_rsa_rsassa_pss_verify() about \c md_alg and
+ * \c hash_id.
+ *
+ * \param ctx The initialized RSA public key context to use.
+ * \param md_alg The message-digest algorithm used to hash the original data.
+ * Use #MBEDTLS_MD_NONE for signing raw data.
+ * \param hashlen The length of the message digest or raw data in Bytes.
+ * If \p md_alg is not #MBEDTLS_MD_NONE, this must match the
+ * output length of the corresponding hash algorithm.
+ * \param hash The buffer holding the message digest or raw data.
+ * This must be a readable buffer of at least \p hashlen Bytes.
+ * \param sig The buffer holding the signature. This must be a readable
+ * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ *
+ * \return \c 0 if the verify operation was successful.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_pkcs1_verify(mbedtls_rsa_context *ctx,
+ mbedtls_md_type_t md_alg,
+ unsigned int hashlen,
+ const unsigned char *hash,
+ const unsigned char *sig);
+
+/**
+ * \brief This function performs a PKCS#1 v1.5 verification
+ * operation (RSASSA-PKCS1-v1_5-VERIFY).
+ *
+ * \param ctx The initialized RSA public key context to use.
+ * \param md_alg The message-digest algorithm used to hash the original data.
+ * Use #MBEDTLS_MD_NONE for signing raw data.
+ * \param hashlen The length of the message digest or raw data in Bytes.
+ * If \p md_alg is not #MBEDTLS_MD_NONE, this must match the
+ * output length of the corresponding hash algorithm.
+ * \param hash The buffer holding the message digest or raw data.
+ * This must be a readable buffer of at least \p hashlen Bytes.
+ * \param sig The buffer holding the signature. This must be a readable
+ * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ *
+ * \return \c 0 if the verify operation was successful.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_rsassa_pkcs1_v15_verify(mbedtls_rsa_context *ctx,
+ mbedtls_md_type_t md_alg,
+ unsigned int hashlen,
+ const unsigned char *hash,
+ const unsigned char *sig);
+
+/**
+ * \brief This function performs a PKCS#1 v2.1 PSS verification
+ * operation (RSASSA-PSS-VERIFY).
+ *
+ * \note The \c hash_id set in \p ctx by calling
+ * mbedtls_rsa_set_padding() selects the hash used for the
+ * encoding operation and for the mask generation function
+ * (MGF1). For more details on the encoding operation and the
+ * mask generation function, consult <em>RFC-3447: Public-Key
+ * Cryptography Standards (PKCS) #1 v2.1: RSA Cryptography
+ * Specifications</em>. If the \c hash_id set in \p ctx by
+ * mbedtls_rsa_set_padding() is #MBEDTLS_MD_NONE, the \p md_alg
+ * parameter is used.
+ *
+ * \param ctx The initialized RSA public key context to use.
+ * \param md_alg The message-digest algorithm used to hash the original data.
+ * Use #MBEDTLS_MD_NONE for signing raw data.
+ * \param hashlen The length of the message digest or raw data in Bytes.
+ * If \p md_alg is not #MBEDTLS_MD_NONE, this must match the
+ * output length of the corresponding hash algorithm.
+ * \param hash The buffer holding the message digest or raw data.
+ * This must be a readable buffer of at least \p hashlen Bytes.
+ * \param sig The buffer holding the signature. This must be a readable
+ * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ *
+ * \return \c 0 if the verify operation was successful.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_rsassa_pss_verify(mbedtls_rsa_context *ctx,
+ mbedtls_md_type_t md_alg,
+ unsigned int hashlen,
+ const unsigned char *hash,
+ const unsigned char *sig);
+
+/**
+ * \brief This function performs a PKCS#1 v2.1 PSS verification
+ * operation (RSASSA-PSS-VERIFY).
+ *
+ * \note The \p sig buffer must be as large as the size
+ * of \p ctx->N. For example, 128 Bytes if RSA-1024 is used.
+ *
+ * \note The \c hash_id set in \p ctx by mbedtls_rsa_set_padding() is
+ * ignored.
+ *
+ * \param ctx The initialized RSA public key context to use.
+ * \param md_alg The message-digest algorithm used to hash the original data.
+ * Use #MBEDTLS_MD_NONE for signing raw data.
+ * \param hashlen The length of the message digest or raw data in Bytes.
+ * If \p md_alg is not #MBEDTLS_MD_NONE, this must match the
+ * output length of the corresponding hash algorithm.
+ * \param hash The buffer holding the message digest or raw data.
+ * This must be a readable buffer of at least \p hashlen Bytes.
+ * \param mgf1_hash_id The message digest algorithm used for the
+ * verification operation and the mask generation
+ * function (MGF1). For more details on the encoding
+ * operation and the mask generation function, consult
+ * <em>RFC-3447: Public-Key Cryptography Standards
+ * (PKCS) #1 v2.1: RSA Cryptography
+ * Specifications</em>.
+ * \param expected_salt_len The length of the salt used in padding. Use
+ * #MBEDTLS_RSA_SALT_LEN_ANY to accept any salt length.
+ * \param sig The buffer holding the signature. This must be a readable
+ * buffer of length \c ctx->len Bytes. For example, \c 256 Bytes
+ * for an 2048-bit RSA modulus.
+ *
+ * \return \c 0 if the verify operation was successful.
+ * \return An \c MBEDTLS_ERR_RSA_XXX error code on failure.
+ */
+int mbedtls_rsa_rsassa_pss_verify_ext(mbedtls_rsa_context *ctx,
+ mbedtls_md_type_t md_alg,
+ unsigned int hashlen,
+ const unsigned char *hash,
+ mbedtls_md_type_t mgf1_hash_id,
+ int expected_salt_len,
+ const unsigned char *sig);
+
+/**
+ * \brief This function copies the components of an RSA context.
+ *
+ * \param dst The destination context. This must be initialized.
+ * \param src The source context. This must be initialized.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory allocation failure.
+ */
+int mbedtls_rsa_copy(mbedtls_rsa_context *dst, const mbedtls_rsa_context *src);
+
+/**
+ * \brief This function frees the components of an RSA key.
+ *
+ * \param ctx The RSA context to free. May be \c NULL, in which case
+ * this function is a no-op. If it is not \c NULL, it must
+ * point to an initialized RSA context.
+ */
+void mbedtls_rsa_free(mbedtls_rsa_context *ctx);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief The RSA checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_rsa_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* rsa.h */
diff --git a/include/mbedtls/sha1.h b/include/mbedtls/sha1.h
new file mode 100644
index 0000000..592ffd1
--- /dev/null
+++ b/include/mbedtls/sha1.h
@@ -0,0 +1,219 @@
+/**
+ * \file sha1.h
+ *
+ * \brief This file contains SHA-1 definitions and functions.
+ *
+ * The Secure Hash Algorithm 1 (SHA-1) cryptographic hash function is defined in
+ * <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
+ *
+ * \warning SHA-1 is considered a weak message digest and its use constitutes
+ * a security risk. We recommend considering stronger message
+ * digests instead.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_SHA1_H
+#define MBEDTLS_SHA1_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+/** SHA-1 input data was malformed. */
+#define MBEDTLS_ERR_SHA1_BAD_INPUT_DATA -0x0073
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_SHA1_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief The SHA-1 context structure.
+ *
+ * \warning SHA-1 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ */
+typedef struct mbedtls_sha1_context {
+ uint32_t MBEDTLS_PRIVATE(total)[2]; /*!< The number of Bytes processed. */
+ uint32_t MBEDTLS_PRIVATE(state)[5]; /*!< The intermediate digest state. */
+ unsigned char MBEDTLS_PRIVATE(buffer)[64]; /*!< The data block being processed. */
+}
+mbedtls_sha1_context;
+
+#else /* MBEDTLS_SHA1_ALT */
+#include "sha1_alt.h"
+#endif /* MBEDTLS_SHA1_ALT */
+
+/**
+ * \brief This function initializes a SHA-1 context.
+ *
+ * \warning SHA-1 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ * \param ctx The SHA-1 context to initialize.
+ * This must not be \c NULL.
+ *
+ */
+void mbedtls_sha1_init(mbedtls_sha1_context *ctx);
+
+/**
+ * \brief This function clears a SHA-1 context.
+ *
+ * \warning SHA-1 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ * \param ctx The SHA-1 context to clear. This may be \c NULL,
+ * in which case this function does nothing. If it is
+ * not \c NULL, it must point to an initialized
+ * SHA-1 context.
+ *
+ */
+void mbedtls_sha1_free(mbedtls_sha1_context *ctx);
+
+/**
+ * \brief This function clones the state of a SHA-1 context.
+ *
+ * \warning SHA-1 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ * \param dst The SHA-1 context to clone to. This must be initialized.
+ * \param src The SHA-1 context to clone from. This must be initialized.
+ *
+ */
+void mbedtls_sha1_clone(mbedtls_sha1_context *dst,
+ const mbedtls_sha1_context *src);
+
+/**
+ * \brief This function starts a SHA-1 checksum calculation.
+ *
+ * \warning SHA-1 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ * \param ctx The SHA-1 context to initialize. This must be initialized.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ *
+ */
+int mbedtls_sha1_starts(mbedtls_sha1_context *ctx);
+
+/**
+ * \brief This function feeds an input buffer into an ongoing SHA-1
+ * checksum calculation.
+ *
+ * \warning SHA-1 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ * \param ctx The SHA-1 context. This must be initialized
+ * and have a hash operation started.
+ * \param input The buffer holding the input data.
+ * This must be a readable buffer of length \p ilen Bytes.
+ * \param ilen The length of the input data \p input in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha1_update(mbedtls_sha1_context *ctx,
+ const unsigned char *input,
+ size_t ilen);
+
+/**
+ * \brief This function finishes the SHA-1 operation, and writes
+ * the result to the output buffer.
+ *
+ * \warning SHA-1 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ * \param ctx The SHA-1 context to use. This must be initialized and
+ * have a hash operation started.
+ * \param output The SHA-1 checksum result. This must be a writable
+ * buffer of length \c 20 Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha1_finish(mbedtls_sha1_context *ctx,
+ unsigned char output[20]);
+
+/**
+ * \brief SHA-1 process data block (internal use only).
+ *
+ * \warning SHA-1 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ * \param ctx The SHA-1 context to use. This must be initialized.
+ * \param data The data block being processed. This must be a
+ * readable buffer of length \c 64 Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ *
+ */
+int mbedtls_internal_sha1_process(mbedtls_sha1_context *ctx,
+ const unsigned char data[64]);
+
+/**
+ * \brief This function calculates the SHA-1 checksum of a buffer.
+ *
+ * The function allocates the context, performs the
+ * calculation, and frees the context.
+ *
+ * The SHA-1 result is calculated as
+ * output = SHA-1(input buffer).
+ *
+ * \warning SHA-1 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ * \param input The buffer holding the input data.
+ * This must be a readable buffer of length \p ilen Bytes.
+ * \param ilen The length of the input data \p input in Bytes.
+ * \param output The SHA-1 checksum result.
+ * This must be a writable buffer of length \c 20 Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ *
+ */
+int mbedtls_sha1(const unsigned char *input,
+ size_t ilen,
+ unsigned char output[20]);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+/**
+ * \brief The SHA-1 checkup routine.
+ *
+ * \warning SHA-1 is considered a weak message digest and its use
+ * constitutes a security risk. We recommend considering
+ * stronger message digests instead.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ *
+ */
+int mbedtls_sha1_self_test(int verbose);
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* mbedtls_sha1.h */
diff --git a/include/mbedtls/sha256.h b/include/mbedtls/sha256.h
new file mode 100644
index 0000000..4ee780f
--- /dev/null
+++ b/include/mbedtls/sha256.h
@@ -0,0 +1,198 @@
+/**
+ * \file sha256.h
+ *
+ * \brief This file contains SHA-224 and SHA-256 definitions and functions.
+ *
+ * The Secure Hash Algorithms 224 and 256 (SHA-224 and SHA-256) cryptographic
+ * hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_SHA256_H
+#define MBEDTLS_SHA256_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+/** SHA-256 input data was malformed. */
+#define MBEDTLS_ERR_SHA256_BAD_INPUT_DATA -0x0074
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_SHA256_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief The SHA-256 context structure.
+ *
+ * The structure is used both for SHA-256 and for SHA-224
+ * checksum calculations. The choice between these two is
+ * made in the call to mbedtls_sha256_starts().
+ */
+typedef struct mbedtls_sha256_context {
+ unsigned char MBEDTLS_PRIVATE(buffer)[64]; /*!< The data block being processed. */
+ uint32_t MBEDTLS_PRIVATE(total)[2]; /*!< The number of Bytes processed. */
+ uint32_t MBEDTLS_PRIVATE(state)[8]; /*!< The intermediate digest state. */
+ int MBEDTLS_PRIVATE(is224); /*!< Determines which function to use:
+ 0: Use SHA-256, or 1: Use SHA-224. */
+}
+mbedtls_sha256_context;
+
+#else /* MBEDTLS_SHA256_ALT */
+#include "sha256_alt.h"
+#endif /* MBEDTLS_SHA256_ALT */
+
+/**
+ * \brief This function initializes a SHA-256 context.
+ *
+ * \param ctx The SHA-256 context to initialize. This must not be \c NULL.
+ */
+void mbedtls_sha256_init(mbedtls_sha256_context *ctx);
+
+/**
+ * \brief This function clears a SHA-256 context.
+ *
+ * \param ctx The SHA-256 context to clear. This may be \c NULL, in which
+ * case this function returns immediately. If it is not \c NULL,
+ * it must point to an initialized SHA-256 context.
+ */
+void mbedtls_sha256_free(mbedtls_sha256_context *ctx);
+
+/**
+ * \brief This function clones the state of a SHA-256 context.
+ *
+ * \param dst The destination context. This must be initialized.
+ * \param src The context to clone. This must be initialized.
+ */
+void mbedtls_sha256_clone(mbedtls_sha256_context *dst,
+ const mbedtls_sha256_context *src);
+
+/**
+ * \brief This function starts a SHA-224 or SHA-256 checksum
+ * calculation.
+ *
+ * \param ctx The context to use. This must be initialized.
+ * \param is224 This determines which function to use. This must be
+ * either \c 0 for SHA-256, or \c 1 for SHA-224.
+ *
+ * \note is224 must be defined accordingly to the enabled
+ * MBEDTLS_SHA224_C/MBEDTLS_SHA256_C symbols otherwise the
+ * function will return #MBEDTLS_ERR_SHA512_BAD_INPUT_DATA.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha256_starts(mbedtls_sha256_context *ctx, int is224);
+
+/**
+ * \brief This function feeds an input buffer into an ongoing
+ * SHA-256 checksum calculation.
+ *
+ * \param ctx The SHA-256 context. This must be initialized
+ * and have a hash operation started.
+ * \param input The buffer holding the data. This must be a readable
+ * buffer of length \p ilen Bytes.
+ * \param ilen The length of the input data in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha256_update(mbedtls_sha256_context *ctx,
+ const unsigned char *input,
+ size_t ilen);
+
+/**
+ * \brief This function finishes the SHA-256 operation, and writes
+ * the result to the output buffer.
+ *
+ * \param ctx The SHA-256 context. This must be initialized
+ * and have a hash operation started.
+ * \param output The SHA-224 or SHA-256 checksum result.
+ * This must be a writable buffer of length \c 32 bytes
+ * for SHA-256, \c 28 bytes for SHA-224.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha256_finish(mbedtls_sha256_context *ctx,
+ unsigned char *output);
+
+/**
+ * \brief This function processes a single data block within
+ * the ongoing SHA-256 computation. This function is for
+ * internal use only.
+ *
+ * \param ctx The SHA-256 context. This must be initialized.
+ * \param data The buffer holding one block of data. This must
+ * be a readable buffer of length \c 64 Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_internal_sha256_process(mbedtls_sha256_context *ctx,
+ const unsigned char data[64]);
+
+/**
+ * \brief This function calculates the SHA-224 or SHA-256
+ * checksum of a buffer.
+ *
+ * The function allocates the context, performs the
+ * calculation, and frees the context.
+ *
+ * The SHA-256 result is calculated as
+ * output = SHA-256(input buffer).
+ *
+ * \param input The buffer holding the data. This must be a readable
+ * buffer of length \p ilen Bytes.
+ * \param ilen The length of the input data in Bytes.
+ * \param output The SHA-224 or SHA-256 checksum result.
+ * This must be a writable buffer of length \c 32 bytes
+ * for SHA-256, \c 28 bytes for SHA-224.
+ * \param is224 Determines which function to use. This must be
+ * either \c 0 for SHA-256, or \c 1 for SHA-224.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha256(const unsigned char *input,
+ size_t ilen,
+ unsigned char *output,
+ int is224);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+#if defined(MBEDTLS_SHA224_C)
+/**
+ * \brief The SHA-224 checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_sha224_self_test(int verbose);
+#endif /* MBEDTLS_SHA224_C */
+
+#if defined(MBEDTLS_SHA256_C)
+/**
+ * \brief The SHA-256 checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_sha256_self_test(int verbose);
+#endif /* MBEDTLS_SHA256_C */
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* mbedtls_sha256.h */
diff --git a/include/mbedtls/sha3.h b/include/mbedtls/sha3.h
new file mode 100644
index 0000000..3eeee65
--- /dev/null
+++ b/include/mbedtls/sha3.h
@@ -0,0 +1,172 @@
+/**
+ * \file sha3.h
+ *
+ * \brief This file contains SHA-3 definitions and functions.
+ *
+ * The Secure Hash Algorithms cryptographic
+ * hash functions are defined in <em>FIPS 202: SHA-3 Standard:
+ * Permutation-Based Hash and Extendable-Output Functions </em>.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_SHA3_H
+#define MBEDTLS_SHA3_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** SHA-3 input data was malformed. */
+#define MBEDTLS_ERR_SHA3_BAD_INPUT_DATA -0x0076
+
+/**
+ * SHA-3 family id.
+ *
+ * It identifies the family (SHA3-256, SHA3-512, etc.)
+ */
+
+typedef enum {
+ MBEDTLS_SHA3_NONE = 0, /*!< Operation not defined. */
+ MBEDTLS_SHA3_224, /*!< SHA3-224 */
+ MBEDTLS_SHA3_256, /*!< SHA3-256 */
+ MBEDTLS_SHA3_384, /*!< SHA3-384 */
+ MBEDTLS_SHA3_512, /*!< SHA3-512 */
+} mbedtls_sha3_id;
+
+/**
+ * \brief The SHA-3 context structure.
+ *
+ * The structure is used SHA-3 checksum calculations.
+ */
+typedef struct {
+ uint64_t MBEDTLS_PRIVATE(state[25]);
+ uint32_t MBEDTLS_PRIVATE(index);
+ uint16_t MBEDTLS_PRIVATE(olen);
+ uint16_t MBEDTLS_PRIVATE(max_block_size);
+}
+mbedtls_sha3_context;
+
+/**
+ * \brief This function initializes a SHA-3 context.
+ *
+ * \param ctx The SHA-3 context to initialize. This must not be \c NULL.
+ */
+void mbedtls_sha3_init(mbedtls_sha3_context *ctx);
+
+/**
+ * \brief This function clears a SHA-3 context.
+ *
+ * \param ctx The SHA-3 context to clear. This may be \c NULL, in which
+ * case this function returns immediately. If it is not \c NULL,
+ * it must point to an initialized SHA-3 context.
+ */
+void mbedtls_sha3_free(mbedtls_sha3_context *ctx);
+
+/**
+ * \brief This function clones the state of a SHA-3 context.
+ *
+ * \param dst The destination context. This must be initialized.
+ * \param src The context to clone. This must be initialized.
+ */
+void mbedtls_sha3_clone(mbedtls_sha3_context *dst,
+ const mbedtls_sha3_context *src);
+
+/**
+ * \brief This function starts a SHA-3 checksum
+ * calculation.
+ *
+ * \param ctx The context to use. This must be initialized.
+ * \param id The id of the SHA-3 family.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha3_starts(mbedtls_sha3_context *ctx, mbedtls_sha3_id id);
+
+/**
+ * \brief This function feeds an input buffer into an ongoing
+ * SHA-3 checksum calculation.
+ *
+ * \param ctx The SHA-3 context. This must be initialized
+ * and have a hash operation started.
+ * \param input The buffer holding the data. This must be a readable
+ * buffer of length \p ilen Bytes.
+ * \param ilen The length of the input data in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha3_update(mbedtls_sha3_context *ctx,
+ const uint8_t *input,
+ size_t ilen);
+
+/**
+ * \brief This function finishes the SHA-3 operation, and writes
+ * the result to the output buffer.
+ *
+ * \param ctx The SHA-3 context. This must be initialized
+ * and have a hash operation started.
+ * \param output The SHA-3 checksum result.
+ * This must be a writable buffer of length \c olen bytes.
+ * \param olen Defines the length of output buffer (in bytes). For SHA-3 224, SHA-3 256,
+ * SHA-3 384 and SHA-3 512 \c olen must equal to 28, 32, 48 and 64,
+ * respectively.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha3_finish(mbedtls_sha3_context *ctx,
+ uint8_t *output, size_t olen);
+
+/**
+ * \brief This function calculates the SHA-3
+ * checksum of a buffer.
+ *
+ * The function allocates the context, performs the
+ * calculation, and frees the context.
+ *
+ * The SHA-3 result is calculated as
+ * output = SHA-3(id, input buffer, d).
+ *
+ * \param id The id of the SHA-3 family.
+ * \param input The buffer holding the data. This must be a readable
+ * buffer of length \p ilen Bytes.
+ * \param ilen The length of the input data in Bytes.
+ * \param output The SHA-3 checksum result.
+ * This must be a writable buffer of length \c olen bytes.
+ * \param olen Defines the length of output buffer (in bytes). For SHA-3 224, SHA-3 256,
+ * SHA-3 384 and SHA-3 512 \c olen must equal to 28, 32, 48 and 64,
+ * respectively.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha3(mbedtls_sha3_id id, const uint8_t *input,
+ size_t ilen,
+ uint8_t *output,
+ size_t olen);
+
+#if defined(MBEDTLS_SELF_TEST)
+/**
+ * \brief Checkup routine for the algorithms implemented
+ * by this module: SHA3-224, SHA3-256, SHA3-384, SHA3-512.
+ *
+ * \return 0 if successful, or 1 if the test failed.
+ */
+int mbedtls_sha3_self_test(int verbose);
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* mbedtls_sha3.h */
diff --git a/include/mbedtls/sha512.h b/include/mbedtls/sha512.h
new file mode 100644
index 0000000..1c20e4c
--- /dev/null
+++ b/include/mbedtls/sha512.h
@@ -0,0 +1,208 @@
+/**
+ * \file sha512.h
+ * \brief This file contains SHA-384 and SHA-512 definitions and functions.
+ *
+ * The Secure Hash Algorithms 384 and 512 (SHA-384 and SHA-512) cryptographic
+ * hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_SHA512_H
+#define MBEDTLS_SHA512_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stddef.h>
+#include <stdint.h>
+
+/** SHA-512 input data was malformed. */
+#define MBEDTLS_ERR_SHA512_BAD_INPUT_DATA -0x0075
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_SHA512_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief The SHA-512 context structure.
+ *
+ * The structure is used both for SHA-384 and for SHA-512
+ * checksum calculations. The choice between these two is
+ * made in the call to mbedtls_sha512_starts().
+ */
+typedef struct mbedtls_sha512_context {
+ uint64_t MBEDTLS_PRIVATE(total)[2]; /*!< The number of Bytes processed. */
+ uint64_t MBEDTLS_PRIVATE(state)[8]; /*!< The intermediate digest state. */
+ unsigned char MBEDTLS_PRIVATE(buffer)[128]; /*!< The data block being processed. */
+#if defined(MBEDTLS_SHA384_C)
+ int MBEDTLS_PRIVATE(is384); /*!< Determines which function to use:
+ 0: Use SHA-512, or 1: Use SHA-384. */
+#endif
+}
+mbedtls_sha512_context;
+
+#else /* MBEDTLS_SHA512_ALT */
+#include "sha512_alt.h"
+#endif /* MBEDTLS_SHA512_ALT */
+
+/**
+ * \brief This function initializes a SHA-512 context.
+ *
+ * \param ctx The SHA-512 context to initialize. This must
+ * not be \c NULL.
+ */
+void mbedtls_sha512_init(mbedtls_sha512_context *ctx);
+
+/**
+ * \brief This function clears a SHA-512 context.
+ *
+ * \param ctx The SHA-512 context to clear. This may be \c NULL,
+ * in which case this function does nothing. If it
+ * is not \c NULL, it must point to an initialized
+ * SHA-512 context.
+ */
+void mbedtls_sha512_free(mbedtls_sha512_context *ctx);
+
+/**
+ * \brief This function clones the state of a SHA-512 context.
+ *
+ * \param dst The destination context. This must be initialized.
+ * \param src The context to clone. This must be initialized.
+ */
+void mbedtls_sha512_clone(mbedtls_sha512_context *dst,
+ const mbedtls_sha512_context *src);
+
+/**
+ * \brief This function starts a SHA-384 or SHA-512 checksum
+ * calculation.
+ *
+ * \param ctx The SHA-512 context to use. This must be initialized.
+ * \param is384 Determines which function to use. This must be
+ * either \c 0 for SHA-512, or \c 1 for SHA-384.
+ *
+ * \note is384 must be defined accordingly to the enabled
+ * MBEDTLS_SHA384_C/MBEDTLS_SHA512_C symbols otherwise the
+ * function will return #MBEDTLS_ERR_SHA512_BAD_INPUT_DATA.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha512_starts(mbedtls_sha512_context *ctx, int is384);
+
+/**
+ * \brief This function feeds an input buffer into an ongoing
+ * SHA-512 checksum calculation.
+ *
+ * \param ctx The SHA-512 context. This must be initialized
+ * and have a hash operation started.
+ * \param input The buffer holding the input data. This must
+ * be a readable buffer of length \p ilen Bytes.
+ * \param ilen The length of the input data in Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha512_update(mbedtls_sha512_context *ctx,
+ const unsigned char *input,
+ size_t ilen);
+
+/**
+ * \brief This function finishes the SHA-512 operation, and writes
+ * the result to the output buffer.
+ *
+ * \param ctx The SHA-512 context. This must be initialized
+ * and have a hash operation started.
+ * \param output The SHA-384 or SHA-512 checksum result.
+ * This must be a writable buffer of length \c 64 bytes
+ * for SHA-512, \c 48 bytes for SHA-384.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha512_finish(mbedtls_sha512_context *ctx,
+ unsigned char *output);
+
+/**
+ * \brief This function processes a single data block within
+ * the ongoing SHA-512 computation.
+ * This function is for internal use only.
+ *
+ * \param ctx The SHA-512 context. This must be initialized.
+ * \param data The buffer holding one block of data. This
+ * must be a readable buffer of length \c 128 Bytes.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_internal_sha512_process(mbedtls_sha512_context *ctx,
+ const unsigned char data[128]);
+
+/**
+ * \brief This function calculates the SHA-512 or SHA-384
+ * checksum of a buffer.
+ *
+ * The function allocates the context, performs the
+ * calculation, and frees the context.
+ *
+ * The SHA-512 result is calculated as
+ * output = SHA-512(input buffer).
+ *
+ * \param input The buffer holding the input data. This must be
+ * a readable buffer of length \p ilen Bytes.
+ * \param ilen The length of the input data in Bytes.
+ * \param output The SHA-384 or SHA-512 checksum result.
+ * This must be a writable buffer of length \c 64 bytes
+ * for SHA-512, \c 48 bytes for SHA-384.
+ * \param is384 Determines which function to use. This must be either
+ * \c 0 for SHA-512, or \c 1 for SHA-384.
+ *
+ * \note is384 must be defined accordingly with the supported
+ * symbols in the config file. If:
+ * - is384 is 0, but \c MBEDTLS_SHA384_C is not defined, or
+ * - is384 is 1, but \c MBEDTLS_SHA512_C is not defined
+ * then the function will return
+ * #MBEDTLS_ERR_SHA512_BAD_INPUT_DATA.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_sha512(const unsigned char *input,
+ size_t ilen,
+ unsigned char *output,
+ int is384);
+
+#if defined(MBEDTLS_SELF_TEST)
+
+#if defined(MBEDTLS_SHA384_C)
+/**
+ * \brief The SHA-384 checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_sha384_self_test(int verbose);
+#endif /* MBEDTLS_SHA384_C */
+
+#if defined(MBEDTLS_SHA512_C)
+/**
+ * \brief The SHA-512 checkup routine.
+ *
+ * \return \c 0 on success.
+ * \return \c 1 on failure.
+ */
+int mbedtls_sha512_self_test(int verbose);
+#endif /* MBEDTLS_SHA512_C */
+
+#endif /* MBEDTLS_SELF_TEST */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* mbedtls_sha512.h */
diff --git a/include/mbedtls/ssl.h b/include/mbedtls/ssl.h
new file mode 100644
index 0000000..89f7b81
--- /dev/null
+++ b/include/mbedtls/ssl.h
@@ -0,0 +1,5369 @@
+/**
+ * \file ssl.h
+ *
+ * \brief SSL/TLS functions.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_SSL_H
+#define MBEDTLS_SSL_H
+#include "mbedtls/platform_util.h"
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/bignum.h"
+#include "mbedtls/ecp.h"
+
+#include "mbedtls/ssl_ciphersuites.h"
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+#include "mbedtls/x509_crt.h"
+#include "mbedtls/x509_crl.h"
+#endif
+
+#if defined(MBEDTLS_DHM_C)
+#include "mbedtls/dhm.h"
+#endif
+
+#include "mbedtls/md.h"
+
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_ANY_ENABLED)
+#include "mbedtls/ecdh.h"
+#endif
+
+#if defined(MBEDTLS_HAVE_TIME)
+#include "mbedtls/platform_time.h"
+#endif
+
+#include "psa/crypto.h"
+
+/*
+ * SSL Error codes
+ */
+/** A cryptographic operation is in progress. Try again later. */
+#define MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS -0x7000
+/** The requested feature is not available. */
+#define MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE -0x7080
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_SSL_BAD_INPUT_DATA -0x7100
+/** Verification of the message MAC failed. */
+#define MBEDTLS_ERR_SSL_INVALID_MAC -0x7180
+/** An invalid SSL record was received. */
+#define MBEDTLS_ERR_SSL_INVALID_RECORD -0x7200
+/** The connection indicated an EOF. */
+#define MBEDTLS_ERR_SSL_CONN_EOF -0x7280
+/** A message could not be parsed due to a syntactic error. */
+#define MBEDTLS_ERR_SSL_DECODE_ERROR -0x7300
+/* Error space gap */
+/** No RNG was provided to the SSL module. */
+#define MBEDTLS_ERR_SSL_NO_RNG -0x7400
+/** No client certification received from the client, but required by the authentication mode. */
+#define MBEDTLS_ERR_SSL_NO_CLIENT_CERTIFICATE -0x7480
+/** Client received an extended server hello containing an unsupported extension */
+#define MBEDTLS_ERR_SSL_UNSUPPORTED_EXTENSION -0x7500
+/** No ALPN protocols supported that the client advertises */
+#define MBEDTLS_ERR_SSL_NO_APPLICATION_PROTOCOL -0x7580
+/** The own private key or pre-shared key is not set, but needed. */
+#define MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED -0x7600
+/** No CA Chain is set, but required to operate. */
+#define MBEDTLS_ERR_SSL_CA_CHAIN_REQUIRED -0x7680
+/** An unexpected message was received from our peer. */
+#define MBEDTLS_ERR_SSL_UNEXPECTED_MESSAGE -0x7700
+/** A fatal alert message was received from our peer. */
+#define MBEDTLS_ERR_SSL_FATAL_ALERT_MESSAGE -0x7780
+/** No server could be identified matching the client's SNI. */
+#define MBEDTLS_ERR_SSL_UNRECOGNIZED_NAME -0x7800
+/** The peer notified us that the connection is going to be closed. */
+#define MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY -0x7880
+/* Error space gap */
+/* Error space gap */
+/** Processing of the Certificate handshake message failed. */
+#define MBEDTLS_ERR_SSL_BAD_CERTIFICATE -0x7A00
+/* Error space gap */
+/**
+ * Received NewSessionTicket Post Handshake Message.
+ * This error code is experimental and may be changed or removed without notice.
+ */
+#define MBEDTLS_ERR_SSL_RECEIVED_NEW_SESSION_TICKET -0x7B00
+/** Not possible to read early data */
+#define MBEDTLS_ERR_SSL_CANNOT_READ_EARLY_DATA -0x7B80
+/** Not possible to write early data */
+#define MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA -0x7C00
+/* Error space gap */
+/* Error space gap */
+/* Error space gap */
+/* Error space gap */
+/** Cache entry not found */
+#define MBEDTLS_ERR_SSL_CACHE_ENTRY_NOT_FOUND -0x7E80
+/** Memory allocation failed */
+#define MBEDTLS_ERR_SSL_ALLOC_FAILED -0x7F00
+/** Hardware acceleration function returned with error */
+#define MBEDTLS_ERR_SSL_HW_ACCEL_FAILED -0x7F80
+/** Hardware acceleration function skipped / left alone data */
+#define MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH -0x6F80
+/** Handshake protocol not within min/max boundaries */
+#define MBEDTLS_ERR_SSL_BAD_PROTOCOL_VERSION -0x6E80
+/** The handshake negotiation failed. */
+#define MBEDTLS_ERR_SSL_HANDSHAKE_FAILURE -0x6E00
+/** Session ticket has expired. */
+#define MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED -0x6D80
+/** Public key type mismatch (eg, asked for RSA key exchange and presented EC key) */
+#define MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH -0x6D00
+/** Unknown identity received (eg, PSK identity) */
+#define MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY -0x6C80
+/** Internal error (eg, unexpected failure in lower-level module) */
+#define MBEDTLS_ERR_SSL_INTERNAL_ERROR -0x6C00
+/** A counter would wrap (eg, too many messages exchanged). */
+#define MBEDTLS_ERR_SSL_COUNTER_WRAPPING -0x6B80
+/** Unexpected message at ServerHello in renegotiation. */
+#define MBEDTLS_ERR_SSL_WAITING_SERVER_HELLO_RENEGO -0x6B00
+/** DTLS client must retry for hello verification */
+#define MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED -0x6A80
+/** A buffer is too small to receive or write a message */
+#define MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL -0x6A00
+/* Error space gap */
+/** No data of requested type currently available on underlying transport. */
+#define MBEDTLS_ERR_SSL_WANT_READ -0x6900
+/** Connection requires a write call. */
+#define MBEDTLS_ERR_SSL_WANT_WRITE -0x6880
+/** The operation timed out. */
+#define MBEDTLS_ERR_SSL_TIMEOUT -0x6800
+/** The client initiated a reconnect from the same port. */
+#define MBEDTLS_ERR_SSL_CLIENT_RECONNECT -0x6780
+/** Record header looks valid but is not expected. */
+#define MBEDTLS_ERR_SSL_UNEXPECTED_RECORD -0x6700
+/** The alert message received indicates a non-fatal error. */
+#define MBEDTLS_ERR_SSL_NON_FATAL -0x6680
+/** A field in a message was incorrect or inconsistent with other fields. */
+#define MBEDTLS_ERR_SSL_ILLEGAL_PARAMETER -0x6600
+/** Internal-only message signaling that further message-processing should be done */
+#define MBEDTLS_ERR_SSL_CONTINUE_PROCESSING -0x6580
+/** The asynchronous operation is not completed yet. */
+#define MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS -0x6500
+/** Internal-only message signaling that a message arrived early. */
+#define MBEDTLS_ERR_SSL_EARLY_MESSAGE -0x6480
+/* Error space gap */
+/* Error space gap */
+/* Error space gap */
+/* Error space gap */
+/* Error space gap */
+/* Error space gap */
+/* Error space gap */
+/* Error space gap */
+/** An encrypted DTLS-frame with an unexpected CID was received. */
+#define MBEDTLS_ERR_SSL_UNEXPECTED_CID -0x6000
+/** An operation failed due to an unexpected version or configuration. */
+#define MBEDTLS_ERR_SSL_VERSION_MISMATCH -0x5F00
+/** Invalid value in SSL config */
+#define MBEDTLS_ERR_SSL_BAD_CONFIG -0x5E80
+
+/*
+ * Constants from RFC 8446 for TLS 1.3 PSK modes
+ *
+ * Those are used in the Pre-Shared Key Exchange Modes extension.
+ * See Section 4.2.9 in RFC 8446.
+ */
+#define MBEDTLS_SSL_TLS1_3_PSK_MODE_PURE 0 /* Pure PSK-based exchange */
+#define MBEDTLS_SSL_TLS1_3_PSK_MODE_ECDHE 1 /* PSK+ECDHE-based exchange */
+
+/*
+ * TLS 1.3 NamedGroup values
+ *
+ * From RF 8446
+ * enum {
+ * // Elliptic Curve Groups (ECDHE)
+ * secp256r1(0x0017), secp384r1(0x0018), secp521r1(0x0019),
+ * x25519(0x001D), x448(0x001E),
+ * // Finite Field Groups (DHE)
+ * ffdhe2048(0x0100), ffdhe3072(0x0101), ffdhe4096(0x0102),
+ * ffdhe6144(0x0103), ffdhe8192(0x0104),
+ * // Reserved Code Points
+ * ffdhe_private_use(0x01FC..0x01FF),
+ * ecdhe_private_use(0xFE00..0xFEFF),
+ * (0xFFFF)
+ * } NamedGroup;
+ *
+ */
+
+/* Elliptic Curve Groups (ECDHE) */
+#define MBEDTLS_SSL_IANA_TLS_GROUP_NONE 0
+#define MBEDTLS_SSL_IANA_TLS_GROUP_SECP192K1 0x0012
+#define MBEDTLS_SSL_IANA_TLS_GROUP_SECP192R1 0x0013
+#define MBEDTLS_SSL_IANA_TLS_GROUP_SECP224K1 0x0014
+#define MBEDTLS_SSL_IANA_TLS_GROUP_SECP224R1 0x0015
+#define MBEDTLS_SSL_IANA_TLS_GROUP_SECP256K1 0x0016
+#define MBEDTLS_SSL_IANA_TLS_GROUP_SECP256R1 0x0017
+#define MBEDTLS_SSL_IANA_TLS_GROUP_SECP384R1 0x0018
+#define MBEDTLS_SSL_IANA_TLS_GROUP_SECP521R1 0x0019
+#define MBEDTLS_SSL_IANA_TLS_GROUP_BP256R1 0x001A
+#define MBEDTLS_SSL_IANA_TLS_GROUP_BP384R1 0x001B
+#define MBEDTLS_SSL_IANA_TLS_GROUP_BP512R1 0x001C
+#define MBEDTLS_SSL_IANA_TLS_GROUP_X25519 0x001D
+#define MBEDTLS_SSL_IANA_TLS_GROUP_X448 0x001E
+/* Finite Field Groups (DHE) */
+#define MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE2048 0x0100
+#define MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE3072 0x0101
+#define MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE4096 0x0102
+#define MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE6144 0x0103
+#define MBEDTLS_SSL_IANA_TLS_GROUP_FFDHE8192 0x0104
+
+/*
+ * TLS 1.3 Key Exchange Modes
+ *
+ * Mbed TLS internal identifiers for use with the SSL configuration API
+ * mbedtls_ssl_conf_tls13_key_exchange_modes().
+ */
+
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK (1u << 0) /*!< Pure-PSK TLS 1.3 key exchange,
+ * encompassing both externally agreed PSKs
+ * as well as resumption PSKs. */
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL (1u << 1) /*!< Pure-Ephemeral TLS 1.3 key exchanges,
+ * including for example ECDHE and DHE
+ * key exchanges. */
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL (1u << 2) /*!< PSK-Ephemeral TLS 1.3 key exchanges,
+ * using both a PSK and an ephemeral
+ * key exchange. */
+
+/* Convenience macros for sets of key exchanges. */
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_ALL \
+ (MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK | \
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL | \
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL) /*!< All TLS 1.3 key exchanges */
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL \
+ (MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK | \
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL) /*!< All PSK-based TLS 1.3 key exchanges */
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ALL \
+ (MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL | \
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL) /*!< All ephemeral TLS 1.3 key exchanges */
+
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_NONE (0)
+
+/*
+ * Various constants
+ */
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+/* These are the high and low bytes of ProtocolVersion as defined by:
+ * - RFC 5246: ProtocolVersion version = { 3, 3 }; // TLS v1.2
+ * - RFC 8446: see section 4.2.1
+ */
+#define MBEDTLS_SSL_MAJOR_VERSION_3 3
+#define MBEDTLS_SSL_MINOR_VERSION_3 3 /*!< TLS v1.2 */
+#define MBEDTLS_SSL_MINOR_VERSION_4 4 /*!< TLS v1.3 */
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+#define MBEDTLS_SSL_TRANSPORT_STREAM 0 /*!< TLS */
+#define MBEDTLS_SSL_TRANSPORT_DATAGRAM 1 /*!< DTLS */
+
+#define MBEDTLS_SSL_MAX_HOST_NAME_LEN 255 /*!< Maximum host name defined in RFC 1035 */
+#define MBEDTLS_SSL_MAX_ALPN_NAME_LEN 255 /*!< Maximum size in bytes of a protocol name in alpn ext., RFC 7301 */
+
+#define MBEDTLS_SSL_MAX_ALPN_LIST_LEN 65535 /*!< Maximum size in bytes of list in alpn ext., RFC 7301 */
+
+/* RFC 6066 section 4, see also mfl_code_to_length in ssl_tls.c
+ * NONE must be zero so that memset()ing structure to zero works */
+#define MBEDTLS_SSL_MAX_FRAG_LEN_NONE 0 /*!< don't use this extension */
+#define MBEDTLS_SSL_MAX_FRAG_LEN_512 1 /*!< MaxFragmentLength 2^9 */
+#define MBEDTLS_SSL_MAX_FRAG_LEN_1024 2 /*!< MaxFragmentLength 2^10 */
+#define MBEDTLS_SSL_MAX_FRAG_LEN_2048 3 /*!< MaxFragmentLength 2^11 */
+#define MBEDTLS_SSL_MAX_FRAG_LEN_4096 4 /*!< MaxFragmentLength 2^12 */
+#define MBEDTLS_SSL_MAX_FRAG_LEN_INVALID 5 /*!< first invalid value */
+
+#define MBEDTLS_SSL_IS_CLIENT 0
+#define MBEDTLS_SSL_IS_SERVER 1
+
+#define MBEDTLS_SSL_EXTENDED_MS_DISABLED 0
+#define MBEDTLS_SSL_EXTENDED_MS_ENABLED 1
+
+#define MBEDTLS_SSL_CID_DISABLED 0
+#define MBEDTLS_SSL_CID_ENABLED 1
+
+#define MBEDTLS_SSL_ETM_DISABLED 0
+#define MBEDTLS_SSL_ETM_ENABLED 1
+
+#define MBEDTLS_SSL_COMPRESS_NULL 0
+
+#define MBEDTLS_SSL_VERIFY_NONE 0
+#define MBEDTLS_SSL_VERIFY_OPTIONAL 1
+#define MBEDTLS_SSL_VERIFY_REQUIRED 2
+#define MBEDTLS_SSL_VERIFY_UNSET 3 /* Used only for sni_authmode */
+
+#define MBEDTLS_SSL_LEGACY_RENEGOTIATION 0
+#define MBEDTLS_SSL_SECURE_RENEGOTIATION 1
+
+#define MBEDTLS_SSL_RENEGOTIATION_DISABLED 0
+#define MBEDTLS_SSL_RENEGOTIATION_ENABLED 1
+
+#define MBEDTLS_SSL_ANTI_REPLAY_DISABLED 0
+#define MBEDTLS_SSL_ANTI_REPLAY_ENABLED 1
+
+#define MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED -1
+#define MBEDTLS_SSL_RENEGO_MAX_RECORDS_DEFAULT 16
+
+#define MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION 0
+#define MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION 1
+#define MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE 2
+
+#define MBEDTLS_SSL_TRUNC_HMAC_DISABLED 0
+#define MBEDTLS_SSL_TRUNC_HMAC_ENABLED 1
+#define MBEDTLS_SSL_TRUNCATED_HMAC_LEN 10 /* 80 bits, rfc 6066 section 7 */
+
+#define MBEDTLS_SSL_SESSION_TICKETS_DISABLED 0
+#define MBEDTLS_SSL_SESSION_TICKETS_ENABLED 1
+
+#define MBEDTLS_SSL_PRESET_DEFAULT 0
+#define MBEDTLS_SSL_PRESET_SUITEB 2
+
+#define MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED 1
+#define MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED 0
+
+#define MBEDTLS_SSL_EARLY_DATA_DISABLED 0
+#define MBEDTLS_SSL_EARLY_DATA_ENABLED 1
+
+#define MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED 0
+#define MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED 1
+
+#define MBEDTLS_SSL_SRV_CIPHERSUITE_ORDER_CLIENT 1
+#define MBEDTLS_SSL_SRV_CIPHERSUITE_ORDER_SERVER 0
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_SESSION_TICKETS)
+#if defined(PSA_WANT_ALG_SHA_384)
+#define MBEDTLS_SSL_TLS1_3_TICKET_RESUMPTION_KEY_LEN 48
+#elif defined(PSA_WANT_ALG_SHA_256)
+#define MBEDTLS_SSL_TLS1_3_TICKET_RESUMPTION_KEY_LEN 32
+#endif
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 && MBEDTLS_SSL_SESSION_TICKETS */
+/*
+ * Default range for DTLS retransmission timer value, in milliseconds.
+ * RFC 6347 4.2.4.1 says from 1 second to 60 seconds.
+ */
+#define MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MIN 1000
+#define MBEDTLS_SSL_DTLS_TIMEOUT_DFL_MAX 60000
+
+/**
+ * \name SECTION: Module settings
+ *
+ * The configuration options you can set for this module are in this section.
+ * Either change them in mbedtls_config.h or define them on the compiler command line.
+ * \{
+ */
+
+/*
+ * Maximum fragment length in bytes,
+ * determines the size of each of the two internal I/O buffers.
+ *
+ * Note: the RFC defines the default size of SSL / TLS messages. If you
+ * change the value here, other clients / servers may not be able to
+ * communicate with you anymore. Only change this value if you control
+ * both sides of the connection and have it reduced at both sides, or
+ * if you're using the Max Fragment Length extension and you know all your
+ * peers are using it too!
+ */
+#if !defined(MBEDTLS_SSL_IN_CONTENT_LEN)
+#define MBEDTLS_SSL_IN_CONTENT_LEN 16384
+#endif
+
+#if !defined(MBEDTLS_SSL_OUT_CONTENT_LEN)
+#define MBEDTLS_SSL_OUT_CONTENT_LEN 16384
+#endif
+
+/*
+ * Maximum number of heap-allocated bytes for the purpose of
+ * DTLS handshake message reassembly and future message buffering.
+ */
+#if !defined(MBEDTLS_SSL_DTLS_MAX_BUFFERING)
+#define MBEDTLS_SSL_DTLS_MAX_BUFFERING 32768
+#endif
+
+/*
+ * Maximum length of CIDs for incoming and outgoing messages.
+ */
+#if !defined(MBEDTLS_SSL_CID_IN_LEN_MAX)
+#define MBEDTLS_SSL_CID_IN_LEN_MAX 32
+#endif
+
+#if !defined(MBEDTLS_SSL_CID_OUT_LEN_MAX)
+#define MBEDTLS_SSL_CID_OUT_LEN_MAX 32
+#endif
+
+#if !defined(MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY)
+#define MBEDTLS_SSL_CID_TLS1_3_PADDING_GRANULARITY 16
+#endif
+
+#if !defined(MBEDTLS_SSL_MAX_EARLY_DATA_SIZE)
+#define MBEDTLS_SSL_MAX_EARLY_DATA_SIZE 1024
+#endif
+
+#if !defined(MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE)
+#define MBEDTLS_SSL_TLS1_3_TICKET_AGE_TOLERANCE 6000
+#endif
+
+#if !defined(MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH)
+#define MBEDTLS_SSL_TLS1_3_TICKET_NONCE_LENGTH 32
+#endif
+
+#if !defined(MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS)
+#define MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS 1
+#endif
+
+/** \} name SECTION: Module settings */
+
+/*
+ * Default to standard CID mode
+ */
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) && \
+ !defined(MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT)
+#define MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT 0
+#endif
+
+/*
+ * Length of the verify data for secure renegotiation
+ */
+#define MBEDTLS_SSL_VERIFY_DATA_MAX_LEN 12
+
+/*
+ * Signaling ciphersuite values (SCSV)
+ */
+#define MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO 0xFF /**< renegotiation info ext */
+
+/*
+ * Supported Signature and Hash algorithms (For TLS 1.2)
+ * RFC 5246 section 7.4.1.4.1
+ */
+#define MBEDTLS_SSL_HASH_NONE 0
+#define MBEDTLS_SSL_HASH_MD5 1
+#define MBEDTLS_SSL_HASH_SHA1 2
+#define MBEDTLS_SSL_HASH_SHA224 3
+#define MBEDTLS_SSL_HASH_SHA256 4
+#define MBEDTLS_SSL_HASH_SHA384 5
+#define MBEDTLS_SSL_HASH_SHA512 6
+
+#define MBEDTLS_SSL_SIG_ANON 0
+#define MBEDTLS_SSL_SIG_RSA 1
+#define MBEDTLS_SSL_SIG_ECDSA 3
+
+/*
+ * TLS 1.3 signature algorithms
+ * RFC 8446, Section 4.2.2
+ */
+
+/* RSASSA-PKCS1-v1_5 algorithms */
+#define MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA256 0x0401
+#define MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA384 0x0501
+#define MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA512 0x0601
+
+/* ECDSA algorithms */
+#define MBEDTLS_TLS1_3_SIG_ECDSA_SECP256R1_SHA256 0x0403
+#define MBEDTLS_TLS1_3_SIG_ECDSA_SECP384R1_SHA384 0x0503
+#define MBEDTLS_TLS1_3_SIG_ECDSA_SECP521R1_SHA512 0x0603
+
+/* RSASSA-PSS algorithms with public key OID rsaEncryption */
+#define MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA256 0x0804
+#define MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA384 0x0805
+#define MBEDTLS_TLS1_3_SIG_RSA_PSS_RSAE_SHA512 0x0806
+
+/* EdDSA algorithms */
+#define MBEDTLS_TLS1_3_SIG_ED25519 0x0807
+#define MBEDTLS_TLS1_3_SIG_ED448 0x0808
+
+/* RSASSA-PSS algorithms with public key OID RSASSA-PSS */
+#define MBEDTLS_TLS1_3_SIG_RSA_PSS_PSS_SHA256 0x0809
+#define MBEDTLS_TLS1_3_SIG_RSA_PSS_PSS_SHA384 0x080A
+#define MBEDTLS_TLS1_3_SIG_RSA_PSS_PSS_SHA512 0x080B
+
+/* LEGACY ALGORITHMS */
+#define MBEDTLS_TLS1_3_SIG_RSA_PKCS1_SHA1 0x0201
+#define MBEDTLS_TLS1_3_SIG_ECDSA_SHA1 0x0203
+
+#define MBEDTLS_TLS1_3_SIG_NONE 0x0
+
+/*
+ * Client Certificate Types
+ * RFC 5246 section 7.4.4 plus RFC 4492 section 5.5
+ */
+#define MBEDTLS_SSL_CERT_TYPE_RSA_SIGN 1
+#define MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN 64
+
+/*
+ * Message, alert and handshake types
+ */
+#define MBEDTLS_SSL_MSG_CHANGE_CIPHER_SPEC 20
+#define MBEDTLS_SSL_MSG_ALERT 21
+#define MBEDTLS_SSL_MSG_HANDSHAKE 22
+#define MBEDTLS_SSL_MSG_APPLICATION_DATA 23
+#define MBEDTLS_SSL_MSG_CID 25
+
+#define MBEDTLS_SSL_ALERT_LEVEL_WARNING 1
+#define MBEDTLS_SSL_ALERT_LEVEL_FATAL 2
+
+#define MBEDTLS_SSL_ALERT_MSG_CLOSE_NOTIFY 0 /* 0x00 */
+#define MBEDTLS_SSL_ALERT_MSG_UNEXPECTED_MESSAGE 10 /* 0x0A */
+#define MBEDTLS_SSL_ALERT_MSG_BAD_RECORD_MAC 20 /* 0x14 */
+#define MBEDTLS_SSL_ALERT_MSG_DECRYPTION_FAILED 21 /* 0x15 */
+#define MBEDTLS_SSL_ALERT_MSG_RECORD_OVERFLOW 22 /* 0x16 */
+#define MBEDTLS_SSL_ALERT_MSG_DECOMPRESSION_FAILURE 30 /* 0x1E */
+#define MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE 40 /* 0x28 */
+#define MBEDTLS_SSL_ALERT_MSG_NO_CERT 41 /* 0x29 */
+#define MBEDTLS_SSL_ALERT_MSG_BAD_CERT 42 /* 0x2A */
+#define MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_CERT 43 /* 0x2B */
+#define MBEDTLS_SSL_ALERT_MSG_CERT_REVOKED 44 /* 0x2C */
+#define MBEDTLS_SSL_ALERT_MSG_CERT_EXPIRED 45 /* 0x2D */
+#define MBEDTLS_SSL_ALERT_MSG_CERT_UNKNOWN 46 /* 0x2E */
+#define MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER 47 /* 0x2F */
+#define MBEDTLS_SSL_ALERT_MSG_UNKNOWN_CA 48 /* 0x30 */
+#define MBEDTLS_SSL_ALERT_MSG_ACCESS_DENIED 49 /* 0x31 */
+#define MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR 50 /* 0x32 */
+#define MBEDTLS_SSL_ALERT_MSG_DECRYPT_ERROR 51 /* 0x33 */
+#define MBEDTLS_SSL_ALERT_MSG_EXPORT_RESTRICTION 60 /* 0x3C */
+#define MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION 70 /* 0x46 */
+#define MBEDTLS_SSL_ALERT_MSG_INSUFFICIENT_SECURITY 71 /* 0x47 */
+#define MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR 80 /* 0x50 */
+#define MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK 86 /* 0x56 */
+#define MBEDTLS_SSL_ALERT_MSG_USER_CANCELED 90 /* 0x5A */
+#define MBEDTLS_SSL_ALERT_MSG_NO_RENEGOTIATION 100 /* 0x64 */
+#define MBEDTLS_SSL_ALERT_MSG_MISSING_EXTENSION 109 /* 0x6d -- new in TLS 1.3 */
+#define MBEDTLS_SSL_ALERT_MSG_UNSUPPORTED_EXT 110 /* 0x6E */
+#define MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME 112 /* 0x70 */
+#define MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY 115 /* 0x73 */
+#define MBEDTLS_SSL_ALERT_MSG_CERT_REQUIRED 116 /* 0x74 */
+#define MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL 120 /* 0x78 */
+
+#define MBEDTLS_SSL_HS_HELLO_REQUEST 0
+#define MBEDTLS_SSL_HS_CLIENT_HELLO 1
+#define MBEDTLS_SSL_HS_SERVER_HELLO 2
+#define MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST 3
+#define MBEDTLS_SSL_HS_NEW_SESSION_TICKET 4
+#define MBEDTLS_SSL_HS_END_OF_EARLY_DATA 5
+#define MBEDTLS_SSL_HS_ENCRYPTED_EXTENSIONS 8
+#define MBEDTLS_SSL_HS_CERTIFICATE 11
+#define MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE 12
+#define MBEDTLS_SSL_HS_CERTIFICATE_REQUEST 13
+#define MBEDTLS_SSL_HS_SERVER_HELLO_DONE 14
+#define MBEDTLS_SSL_HS_CERTIFICATE_VERIFY 15
+#define MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE 16
+#define MBEDTLS_SSL_HS_FINISHED 20
+#define MBEDTLS_SSL_HS_MESSAGE_HASH 254
+
+/*
+ * TLS extensions
+ */
+#define MBEDTLS_TLS_EXT_SERVERNAME 0
+#define MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME 0
+
+#define MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH 1
+
+#define MBEDTLS_TLS_EXT_TRUNCATED_HMAC 4
+#define MBEDTLS_TLS_EXT_STATUS_REQUEST 5 /* RFC 6066 TLS 1.2 and 1.3 */
+
+#define MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES 10
+#define MBEDTLS_TLS_EXT_SUPPORTED_GROUPS 10 /* RFC 8422,7919 TLS 1.2 and 1.3 */
+#define MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS 11
+
+#define MBEDTLS_TLS_EXT_SIG_ALG 13 /* RFC 8446 TLS 1.3 */
+#define MBEDTLS_TLS_EXT_USE_SRTP 14
+#define MBEDTLS_TLS_EXT_HEARTBEAT 15 /* RFC 6520 TLS 1.2 and 1.3 */
+#define MBEDTLS_TLS_EXT_ALPN 16
+
+#define MBEDTLS_TLS_EXT_SCT 18 /* RFC 6962 TLS 1.2 and 1.3 */
+#define MBEDTLS_TLS_EXT_CLI_CERT_TYPE 19 /* RFC 7250 TLS 1.2 and 1.3 */
+#define MBEDTLS_TLS_EXT_SERV_CERT_TYPE 20 /* RFC 7250 TLS 1.2 and 1.3 */
+#define MBEDTLS_TLS_EXT_PADDING 21 /* RFC 7685 TLS 1.2 and 1.3 */
+#define MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC 22 /* 0x16 */
+#define MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET 0x0017 /* 23 */
+
+#define MBEDTLS_TLS_EXT_RECORD_SIZE_LIMIT 28 /* RFC 8449 (implemented for TLS 1.3 only) */
+
+#define MBEDTLS_TLS_EXT_SESSION_TICKET 35
+
+#define MBEDTLS_TLS_EXT_PRE_SHARED_KEY 41 /* RFC 8446 TLS 1.3 */
+#define MBEDTLS_TLS_EXT_EARLY_DATA 42 /* RFC 8446 TLS 1.3 */
+#define MBEDTLS_TLS_EXT_SUPPORTED_VERSIONS 43 /* RFC 8446 TLS 1.3 */
+#define MBEDTLS_TLS_EXT_COOKIE 44 /* RFC 8446 TLS 1.3 */
+#define MBEDTLS_TLS_EXT_PSK_KEY_EXCHANGE_MODES 45 /* RFC 8446 TLS 1.3 */
+
+#define MBEDTLS_TLS_EXT_CERT_AUTH 47 /* RFC 8446 TLS 1.3 */
+#define MBEDTLS_TLS_EXT_OID_FILTERS 48 /* RFC 8446 TLS 1.3 */
+#define MBEDTLS_TLS_EXT_POST_HANDSHAKE_AUTH 49 /* RFC 8446 TLS 1.3 */
+#define MBEDTLS_TLS_EXT_SIG_ALG_CERT 50 /* RFC 8446 TLS 1.3 */
+#define MBEDTLS_TLS_EXT_KEY_SHARE 51 /* RFC 8446 TLS 1.3 */
+
+#if MBEDTLS_SSL_DTLS_CONNECTION_ID_COMPAT == 0
+#define MBEDTLS_TLS_EXT_CID 54 /* RFC 9146 DTLS 1.2 CID */
+#else
+#define MBEDTLS_TLS_EXT_CID 254 /* Pre-RFC 9146 DTLS 1.2 CID */
+#endif
+
+#define MBEDTLS_TLS_EXT_ECJPAKE_KKPP 256 /* experimental */
+
+#define MBEDTLS_TLS_EXT_RENEGOTIATION_INFO 0xFF01
+
+/*
+ * Size defines
+ */
+#if !defined(MBEDTLS_PSK_MAX_LEN)
+/*
+ * If the library supports TLS 1.3 tickets and the cipher suite
+ * TLS1-3-AES-256-GCM-SHA384, set the PSK maximum length to 48 instead of 32.
+ * That way, the TLS 1.3 client and server are able to resume sessions where
+ * the cipher suite is TLS1-3-AES-256-GCM-SHA384 (pre-shared keys are 48
+ * bytes long in that case).
+ */
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && \
+ defined(MBEDTLS_SSL_SESSION_TICKETS) && \
+ defined(MBEDTLS_AES_C) && defined(MBEDTLS_GCM_C) && \
+ defined(MBEDTLS_MD_CAN_SHA384)
+#define MBEDTLS_PSK_MAX_LEN 48 /* 384 bits */
+#else
+#define MBEDTLS_PSK_MAX_LEN 32 /* 256 bits */
+#endif
+#endif /* !MBEDTLS_PSK_MAX_LEN */
+
+/* Dummy type used only for its size */
+union mbedtls_ssl_premaster_secret {
+ unsigned char dummy; /* Make the union non-empty even with SSL disabled */
+#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED)
+ unsigned char _pms_rsa[48]; /* RFC 5246 8.1.1 */
+#endif
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED)
+ unsigned char _pms_dhm[MBEDTLS_MPI_MAX_SIZE]; /* RFC 5246 8.1.2 */
+#endif
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
+ unsigned char _pms_ecdh[MBEDTLS_ECP_MAX_BYTES]; /* RFC 4492 5.10 */
+#endif
+#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED)
+ unsigned char _pms_psk[4 + 2 * MBEDTLS_PSK_MAX_LEN]; /* RFC 4279 2 */
+#endif
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
+ unsigned char _pms_dhe_psk[4 + MBEDTLS_MPI_MAX_SIZE
+ + MBEDTLS_PSK_MAX_LEN]; /* RFC 4279 3 */
+#endif
+#if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED)
+ unsigned char _pms_rsa_psk[52 + MBEDTLS_PSK_MAX_LEN]; /* RFC 4279 4 */
+#endif
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
+ unsigned char _pms_ecdhe_psk[4 + MBEDTLS_ECP_MAX_BYTES
+ + MBEDTLS_PSK_MAX_LEN]; /* RFC 5489 2 */
+#endif
+#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
+ unsigned char _pms_ecjpake[32]; /* Thread spec: SHA-256 output */
+#endif
+};
+
+#define MBEDTLS_PREMASTER_SIZE sizeof(union mbedtls_ssl_premaster_secret)
+
+#define MBEDTLS_TLS1_3_MD_MAX_SIZE PSA_HASH_MAX_SIZE
+
+
+/* Length in number of bytes of the TLS sequence number */
+#define MBEDTLS_SSL_SEQUENCE_NUMBER_LEN 8
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * SSL state machine
+ */
+typedef enum {
+ MBEDTLS_SSL_HELLO_REQUEST,
+ MBEDTLS_SSL_CLIENT_HELLO,
+ MBEDTLS_SSL_SERVER_HELLO,
+ MBEDTLS_SSL_SERVER_CERTIFICATE,
+ MBEDTLS_SSL_SERVER_KEY_EXCHANGE,
+ MBEDTLS_SSL_CERTIFICATE_REQUEST,
+ MBEDTLS_SSL_SERVER_HELLO_DONE,
+ MBEDTLS_SSL_CLIENT_CERTIFICATE,
+ MBEDTLS_SSL_CLIENT_KEY_EXCHANGE,
+ MBEDTLS_SSL_CERTIFICATE_VERIFY,
+ MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC,
+ MBEDTLS_SSL_CLIENT_FINISHED,
+ MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC,
+ MBEDTLS_SSL_SERVER_FINISHED,
+ MBEDTLS_SSL_FLUSH_BUFFERS,
+ MBEDTLS_SSL_HANDSHAKE_WRAPUP,
+
+ MBEDTLS_SSL_NEW_SESSION_TICKET,
+ MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT,
+ MBEDTLS_SSL_HELLO_RETRY_REQUEST,
+ MBEDTLS_SSL_ENCRYPTED_EXTENSIONS,
+ MBEDTLS_SSL_END_OF_EARLY_DATA,
+ MBEDTLS_SSL_CLIENT_CERTIFICATE_VERIFY,
+ MBEDTLS_SSL_CLIENT_CCS_AFTER_SERVER_FINISHED,
+ MBEDTLS_SSL_CLIENT_CCS_BEFORE_2ND_CLIENT_HELLO,
+ MBEDTLS_SSL_SERVER_CCS_AFTER_SERVER_HELLO,
+ MBEDTLS_SSL_CLIENT_CCS_AFTER_CLIENT_HELLO,
+ MBEDTLS_SSL_SERVER_CCS_AFTER_HELLO_RETRY_REQUEST,
+ MBEDTLS_SSL_HANDSHAKE_OVER,
+ MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET,
+ MBEDTLS_SSL_TLS1_3_NEW_SESSION_TICKET_FLUSH,
+}
+mbedtls_ssl_states;
+
+/**
+ * \brief Callback type: send data on the network.
+ *
+ * \note That callback may be either blocking or non-blocking.
+ *
+ * \param ctx Context for the send callback (typically a file descriptor)
+ * \param buf Buffer holding the data to send
+ * \param len Length of the data to send
+ *
+ * \return The callback must return the number of bytes sent if any,
+ * or a non-zero error code.
+ * If performing non-blocking I/O, \c MBEDTLS_ERR_SSL_WANT_WRITE
+ * must be returned when the operation would block.
+ *
+ * \note The callback is allowed to send fewer bytes than requested.
+ * It must always return the number of bytes actually sent.
+ */
+typedef int mbedtls_ssl_send_t(void *ctx,
+ const unsigned char *buf,
+ size_t len);
+
+/**
+ * \brief Callback type: receive data from the network.
+ *
+ * \note That callback may be either blocking or non-blocking.
+ *
+ * \param ctx Context for the receive callback (typically a file
+ * descriptor)
+ * \param buf Buffer to write the received data to
+ * \param len Length of the receive buffer
+ *
+ * \returns If data has been received, the positive number of bytes received.
+ * \returns \c 0 if the connection has been closed.
+ * \returns If performing non-blocking I/O, \c MBEDTLS_ERR_SSL_WANT_READ
+ * must be returned when the operation would block.
+ * \returns Another negative error code on other kinds of failures.
+ *
+ * \note The callback may receive fewer bytes than the length of the
+ * buffer. It must always return the number of bytes actually
+ * received and written to the buffer.
+ */
+typedef int mbedtls_ssl_recv_t(void *ctx,
+ unsigned char *buf,
+ size_t len);
+
+/**
+ * \brief Callback type: receive data from the network, with timeout
+ *
+ * \note That callback must block until data is received, or the
+ * timeout delay expires, or the operation is interrupted by a
+ * signal.
+ *
+ * \param ctx Context for the receive callback (typically a file descriptor)
+ * \param buf Buffer to write the received data to
+ * \param len Length of the receive buffer
+ * \param timeout Maximum number of milliseconds to wait for data
+ * 0 means no timeout (potentially waiting forever)
+ *
+ * \return The callback must return the number of bytes received,
+ * or a non-zero error code:
+ * \c MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out,
+ * \c MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal.
+ *
+ * \note The callback may receive fewer bytes than the length of the
+ * buffer. It must always return the number of bytes actually
+ * received and written to the buffer.
+ */
+typedef int mbedtls_ssl_recv_timeout_t(void *ctx,
+ unsigned char *buf,
+ size_t len,
+ uint32_t timeout);
+/**
+ * \brief Callback type: set a pair of timers/delays to watch
+ *
+ * \param ctx Context pointer
+ * \param int_ms Intermediate delay in milliseconds
+ * \param fin_ms Final delay in milliseconds
+ * 0 cancels the current timer.
+ *
+ * \note This callback must at least store the necessary information
+ * for the associated \c mbedtls_ssl_get_timer_t callback to
+ * return correct information.
+ *
+ * \note If using an event-driven style of programming, an event must
+ * be generated when the final delay is passed. The event must
+ * cause a call to \c mbedtls_ssl_handshake() with the proper
+ * SSL context to be scheduled. Care must be taken to ensure
+ * that at most one such call happens at a time.
+ *
+ * \note Only one timer at a time must be running. Calling this
+ * function while a timer is running must cancel it. Cancelled
+ * timers must not generate any event.
+ */
+typedef void mbedtls_ssl_set_timer_t(void *ctx,
+ uint32_t int_ms,
+ uint32_t fin_ms);
+
+/**
+ * \brief Callback type: get status of timers/delays
+ *
+ * \param ctx Context pointer
+ *
+ * \return This callback must return:
+ * -1 if cancelled (fin_ms == 0),
+ * 0 if none of the delays have passed,
+ * 1 if only the intermediate delay has passed,
+ * 2 if the final delay has passed.
+ */
+typedef int mbedtls_ssl_get_timer_t(void *ctx);
+
+/* Defined below */
+typedef struct mbedtls_ssl_session mbedtls_ssl_session;
+typedef struct mbedtls_ssl_context mbedtls_ssl_context;
+typedef struct mbedtls_ssl_config mbedtls_ssl_config;
+
+/* Defined in library/ssl_misc.h */
+typedef struct mbedtls_ssl_transform mbedtls_ssl_transform;
+typedef struct mbedtls_ssl_handshake_params mbedtls_ssl_handshake_params;
+typedef struct mbedtls_ssl_sig_hash_set_t mbedtls_ssl_sig_hash_set_t;
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+typedef struct mbedtls_ssl_key_cert mbedtls_ssl_key_cert;
+#endif
+#if defined(MBEDTLS_SSL_PROTO_DTLS)
+typedef struct mbedtls_ssl_flight_item mbedtls_ssl_flight_item;
+#endif
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_SESSION_TICKETS)
+#define MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_PSK_RESUMPTION \
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK /* 1U << 0 */
+#define MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_PSK_EPHEMERAL_RESUMPTION \
+ MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL /* 1U << 2 */
+#define MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_EARLY_DATA (1U << 3)
+
+#define MBEDTLS_SSL_TLS1_3_TICKET_FLAGS_MASK \
+ (MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_PSK_RESUMPTION | \
+ MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_PSK_EPHEMERAL_RESUMPTION | \
+ MBEDTLS_SSL_TLS1_3_TICKET_ALLOW_EARLY_DATA)
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 && MBEDTLS_SSL_SESSION_TICKETS */
+
+/**
+ * \brief Callback type: server-side session cache getter
+ *
+ * The session cache is logically a key value store, with
+ * keys being session IDs and values being instances of
+ * mbedtls_ssl_session.
+ *
+ * This callback retrieves an entry in this key-value store.
+ *
+ * \param data The address of the session cache structure to query.
+ * \param session_id The buffer holding the session ID to query.
+ * \param session_id_len The length of \p session_id in Bytes.
+ * \param session The address of the session structure to populate.
+ * It is initialized with mbdtls_ssl_session_init(),
+ * and the callback must always leave it in a state
+ * where it can safely be freed via
+ * mbedtls_ssl_session_free() independent of the
+ * return code of this function.
+ *
+ * \return \c 0 on success
+ * \return A non-zero return value on failure.
+ *
+ */
+typedef int mbedtls_ssl_cache_get_t(void *data,
+ unsigned char const *session_id,
+ size_t session_id_len,
+ mbedtls_ssl_session *session);
+/**
+ * \brief Callback type: server-side session cache setter
+ *
+ * The session cache is logically a key value store, with
+ * keys being session IDs and values being instances of
+ * mbedtls_ssl_session.
+ *
+ * This callback sets an entry in this key-value store.
+ *
+ * \param data The address of the session cache structure to modify.
+ * \param session_id The buffer holding the session ID to query.
+ * \param session_id_len The length of \p session_id in Bytes.
+ * \param session The address of the session to be stored in the
+ * session cache.
+ *
+ * \return \c 0 on success
+ * \return A non-zero return value on failure.
+ */
+typedef int mbedtls_ssl_cache_set_t(void *data,
+ unsigned char const *session_id,
+ size_t session_id_len,
+ const mbedtls_ssl_session *session);
+
+#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+/**
+ * \brief Callback type: start external signature operation.
+ *
+ * This callback is called during an SSL handshake to start
+ * a signature decryption operation using an
+ * external processor. The parameter \p cert contains
+ * the public key; it is up to the callback function to
+ * determine how to access the associated private key.
+ *
+ * This function typically sends or enqueues a request, and
+ * does not wait for the operation to complete. This allows
+ * the handshake step to be non-blocking.
+ *
+ * The parameters \p ssl and \p cert are guaranteed to remain
+ * valid throughout the handshake. On the other hand, this
+ * function must save the contents of \p hash if the value
+ * is needed for later processing, because the \p hash buffer
+ * is no longer valid after this function returns.
+ *
+ * This function may call mbedtls_ssl_set_async_operation_data()
+ * to store an operation context for later retrieval
+ * by the resume or cancel callback.
+ *
+ * \note For RSA signatures, this function must produce output
+ * that is consistent with PKCS#1 v1.5 in the same way as
+ * mbedtls_rsa_pkcs1_sign(). Before the private key operation,
+ * apply the padding steps described in RFC 8017, section 9.2
+ * "EMSA-PKCS1-v1_5" as follows.
+ * - If \p md_alg is #MBEDTLS_MD_NONE, apply the PKCS#1 v1.5
+ * encoding, treating \p hash as the DigestInfo to be
+ * padded. In other words, apply EMSA-PKCS1-v1_5 starting
+ * from step 3, with `T = hash` and `tLen = hash_len`.
+ * - If `md_alg != MBEDTLS_MD_NONE`, apply the PKCS#1 v1.5
+ * encoding, treating \p hash as the hash to be encoded and
+ * padded. In other words, apply EMSA-PKCS1-v1_5 starting
+ * from step 2, with `digestAlgorithm` obtained by calling
+ * mbedtls_oid_get_oid_by_md() on \p md_alg.
+ *
+ * \note For ECDSA signatures, the output format is the DER encoding
+ * `Ecdsa-Sig-Value` defined in
+ * [RFC 4492 section 5.4](https://tools.ietf.org/html/rfc4492#section-5.4).
+ *
+ * \param ssl The SSL connection instance. It should not be
+ * modified other than via
+ * mbedtls_ssl_set_async_operation_data().
+ * \param cert Certificate containing the public key.
+ * In simple cases, this is one of the pointers passed to
+ * mbedtls_ssl_conf_own_cert() when configuring the SSL
+ * connection. However, if other callbacks are used, this
+ * property may not hold. For example, if an SNI callback
+ * is registered with mbedtls_ssl_conf_sni(), then
+ * this callback determines what certificate is used.
+ * \param md_alg Hash algorithm.
+ * \param hash Buffer containing the hash. This buffer is
+ * no longer valid when the function returns.
+ * \param hash_len Size of the \c hash buffer in bytes.
+ *
+ * \return 0 if the operation was started successfully and the SSL
+ * stack should call the resume callback immediately.
+ * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation
+ * was started successfully and the SSL stack should return
+ * immediately without calling the resume callback yet.
+ * \return #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external
+ * processor does not support this key. The SSL stack will
+ * use the private key object instead.
+ * \return Any other error indicates a fatal failure and is
+ * propagated up the call chain. The callback should
+ * use \c MBEDTLS_ERR_PK_xxx error codes, and <b>must not</b>
+ * use \c MBEDTLS_ERR_SSL_xxx error codes except as
+ * directed in the documentation of this callback.
+ */
+typedef int mbedtls_ssl_async_sign_t(mbedtls_ssl_context *ssl,
+ mbedtls_x509_crt *cert,
+ mbedtls_md_type_t md_alg,
+ const unsigned char *hash,
+ size_t hash_len);
+
+/**
+ * \brief Callback type: start external decryption operation.
+ *
+ * This callback is called during an SSL handshake to start
+ * an RSA decryption operation using an
+ * external processor. The parameter \p cert contains
+ * the public key; it is up to the callback function to
+ * determine how to access the associated private key.
+ *
+ * This function typically sends or enqueues a request, and
+ * does not wait for the operation to complete. This allows
+ * the handshake step to be non-blocking.
+ *
+ * The parameters \p ssl and \p cert are guaranteed to remain
+ * valid throughout the handshake. On the other hand, this
+ * function must save the contents of \p input if the value
+ * is needed for later processing, because the \p input buffer
+ * is no longer valid after this function returns.
+ *
+ * This function may call mbedtls_ssl_set_async_operation_data()
+ * to store an operation context for later retrieval
+ * by the resume or cancel callback.
+ *
+ * \warning RSA decryption as used in TLS is subject to a potential
+ * timing side channel attack first discovered by Bleichenbacher
+ * in 1998. This attack can be remotely exploitable
+ * in practice. To avoid this attack, you must ensure that
+ * if the callback performs an RSA decryption, the time it
+ * takes to execute and return the result does not depend
+ * on whether the RSA decryption succeeded or reported
+ * invalid padding.
+ *
+ * \param ssl The SSL connection instance. It should not be
+ * modified other than via
+ * mbedtls_ssl_set_async_operation_data().
+ * \param cert Certificate containing the public key.
+ * In simple cases, this is one of the pointers passed to
+ * mbedtls_ssl_conf_own_cert() when configuring the SSL
+ * connection. However, if other callbacks are used, this
+ * property may not hold. For example, if an SNI callback
+ * is registered with mbedtls_ssl_conf_sni(), then
+ * this callback determines what certificate is used.
+ * \param input Buffer containing the input ciphertext. This buffer
+ * is no longer valid when the function returns.
+ * \param input_len Size of the \p input buffer in bytes.
+ *
+ * \return 0 if the operation was started successfully and the SSL
+ * stack should call the resume callback immediately.
+ * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation
+ * was started successfully and the SSL stack should return
+ * immediately without calling the resume callback yet.
+ * \return #MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH if the external
+ * processor does not support this key. The SSL stack will
+ * use the private key object instead.
+ * \return Any other error indicates a fatal failure and is
+ * propagated up the call chain. The callback should
+ * use \c MBEDTLS_ERR_PK_xxx error codes, and <b>must not</b>
+ * use \c MBEDTLS_ERR_SSL_xxx error codes except as
+ * directed in the documentation of this callback.
+ */
+typedef int mbedtls_ssl_async_decrypt_t(mbedtls_ssl_context *ssl,
+ mbedtls_x509_crt *cert,
+ const unsigned char *input,
+ size_t input_len);
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+/**
+ * \brief Callback type: resume external operation.
+ *
+ * This callback is called during an SSL handshake to resume
+ * an external operation started by the
+ * ::mbedtls_ssl_async_sign_t or
+ * ::mbedtls_ssl_async_decrypt_t callback.
+ *
+ * This function typically checks the status of a pending
+ * request or causes the request queue to make progress, and
+ * does not wait for the operation to complete. This allows
+ * the handshake step to be non-blocking.
+ *
+ * This function may call mbedtls_ssl_get_async_operation_data()
+ * to retrieve an operation context set by the start callback.
+ * It may call mbedtls_ssl_set_async_operation_data() to modify
+ * this context.
+ *
+ * Note that when this function returns a status other than
+ * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, it must free any
+ * resources associated with the operation.
+ *
+ * \param ssl The SSL connection instance. It should not be
+ * modified other than via
+ * mbedtls_ssl_set_async_operation_data().
+ * \param output Buffer containing the output (signature or decrypted
+ * data) on success.
+ * \param output_len On success, number of bytes written to \p output.
+ * \param output_size Size of the \p output buffer in bytes.
+ *
+ * \return 0 if output of the operation is available in the
+ * \p output buffer.
+ * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if the operation
+ * is still in progress. Subsequent requests for progress
+ * on the SSL connection will call the resume callback
+ * again.
+ * \return Any other error means that the operation is aborted.
+ * The SSL handshake is aborted. The callback should
+ * use \c MBEDTLS_ERR_PK_xxx error codes, and <b>must not</b>
+ * use \c MBEDTLS_ERR_SSL_xxx error codes except as
+ * directed in the documentation of this callback.
+ */
+typedef int mbedtls_ssl_async_resume_t(mbedtls_ssl_context *ssl,
+ unsigned char *output,
+ size_t *output_len,
+ size_t output_size);
+
+/**
+ * \brief Callback type: cancel external operation.
+ *
+ * This callback is called if an SSL connection is closed
+ * while an asynchronous operation is in progress. Note that
+ * this callback is not called if the
+ * ::mbedtls_ssl_async_resume_t callback has run and has
+ * returned a value other than
+ * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS, since in that case
+ * the asynchronous operation has already completed.
+ *
+ * This function may call mbedtls_ssl_get_async_operation_data()
+ * to retrieve an operation context set by the start callback.
+ *
+ * \param ssl The SSL connection instance. It should not be
+ * modified.
+ */
+typedef void mbedtls_ssl_async_cancel_t(mbedtls_ssl_context *ssl);
+#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
+
+#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) && \
+ !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
+#define MBEDTLS_SSL_PEER_CERT_DIGEST_MAX_LEN 48
+#if defined(MBEDTLS_MD_CAN_SHA256)
+#define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE MBEDTLS_MD_SHA256
+#define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN 32
+#elif defined(MBEDTLS_MD_CAN_SHA384)
+#define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE MBEDTLS_MD_SHA384
+#define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN 48
+#elif defined(MBEDTLS_MD_CAN_SHA1)
+#define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_TYPE MBEDTLS_MD_SHA1
+#define MBEDTLS_SSL_PEER_CERT_DIGEST_DFL_LEN 20
+#else
+/* This is already checked in check_config.h, but be sure. */
+#error "Bad configuration - need SHA-1, SHA-256 or SHA-512 enabled to compute digest of peer CRT."
+#endif
+#endif /* MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED &&
+ !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
+
+typedef struct {
+ unsigned char client_application_traffic_secret_N[MBEDTLS_TLS1_3_MD_MAX_SIZE];
+ unsigned char server_application_traffic_secret_N[MBEDTLS_TLS1_3_MD_MAX_SIZE];
+ unsigned char exporter_master_secret[MBEDTLS_TLS1_3_MD_MAX_SIZE];
+ unsigned char resumption_master_secret[MBEDTLS_TLS1_3_MD_MAX_SIZE];
+} mbedtls_ssl_tls13_application_secrets;
+
+#if defined(MBEDTLS_SSL_DTLS_SRTP)
+
+#define MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH 255
+#define MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH 4
+/*
+ * For code readability use a typedef for DTLS-SRTP profiles
+ *
+ * Use_srtp extension protection profiles values as defined in
+ * http://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml
+ *
+ * Reminder: if this list is expanded mbedtls_ssl_check_srtp_profile_value
+ * must be updated too.
+ */
+#define MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80 ((uint16_t) 0x0001)
+#define MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32 ((uint16_t) 0x0002)
+#define MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80 ((uint16_t) 0x0005)
+#define MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32 ((uint16_t) 0x0006)
+/* This one is not iana defined, but for code readability. */
+#define MBEDTLS_TLS_SRTP_UNSET ((uint16_t) 0x0000)
+
+typedef uint16_t mbedtls_ssl_srtp_profile;
+
+typedef struct mbedtls_dtls_srtp_info_t {
+ /*! The SRTP profile that was negotiated. */
+ mbedtls_ssl_srtp_profile MBEDTLS_PRIVATE(chosen_dtls_srtp_profile);
+ /*! The length of mki_value. */
+ uint16_t MBEDTLS_PRIVATE(mki_len);
+ /*! The mki_value used, with max size of 256 bytes. */
+ unsigned char MBEDTLS_PRIVATE(mki_value)[MBEDTLS_TLS_SRTP_MAX_MKI_LENGTH];
+}
+mbedtls_dtls_srtp_info;
+
+#endif /* MBEDTLS_SSL_DTLS_SRTP */
+
+/** Human-friendly representation of the (D)TLS protocol version. */
+typedef enum {
+ MBEDTLS_SSL_VERSION_UNKNOWN, /*!< Context not in use or version not yet negotiated. */
+ MBEDTLS_SSL_VERSION_TLS1_2 = 0x0303, /*!< (D)TLS 1.2 */
+ MBEDTLS_SSL_VERSION_TLS1_3 = 0x0304, /*!< (D)TLS 1.3 */
+} mbedtls_ssl_protocol_version;
+
+/*
+ * This structure is used for storing current session data.
+ *
+ * Note: when changing this definition, we need to check and update:
+ * - in tests/suites/test_suite_ssl.function:
+ * ssl_populate_session() and ssl_serialize_session_save_load()
+ * - in library/ssl_tls.c:
+ * mbedtls_ssl_session_init() and mbedtls_ssl_session_free()
+ * mbedtls_ssl_session_save() and ssl_session_load()
+ * ssl_session_copy()
+ */
+struct mbedtls_ssl_session {
+#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
+ unsigned char MBEDTLS_PRIVATE(mfl_code); /*!< MaxFragmentLength negotiated by peer */
+#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
+
+ unsigned char MBEDTLS_PRIVATE(exported);
+
+ /** TLS version negotiated in the session. Used if and when renegotiating
+ * or resuming a session instead of the configured minor TLS version.
+ */
+ mbedtls_ssl_protocol_version MBEDTLS_PRIVATE(tls_version);
+
+#if defined(MBEDTLS_HAVE_TIME)
+ mbedtls_time_t MBEDTLS_PRIVATE(start); /*!< starting time */
+#endif
+ int MBEDTLS_PRIVATE(ciphersuite); /*!< chosen ciphersuite */
+ size_t MBEDTLS_PRIVATE(id_len); /*!< session id length */
+ unsigned char MBEDTLS_PRIVATE(id)[32]; /*!< session identifier */
+ unsigned char MBEDTLS_PRIVATE(master)[48]; /*!< the master secret */
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+#if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE)
+ mbedtls_x509_crt *MBEDTLS_PRIVATE(peer_cert); /*!< peer X.509 cert chain */
+#else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
+ /*! The digest of the peer's end-CRT. This must be kept to detect CRT
+ * changes during renegotiation, mitigating the triple handshake attack. */
+ unsigned char *MBEDTLS_PRIVATE(peer_cert_digest);
+ size_t MBEDTLS_PRIVATE(peer_cert_digest_len);
+ mbedtls_md_type_t MBEDTLS_PRIVATE(peer_cert_digest_type);
+#endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+ uint32_t MBEDTLS_PRIVATE(verify_result); /*!< verification result */
+
+#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_CLI_C)
+ unsigned char *MBEDTLS_PRIVATE(ticket); /*!< RFC 5077 session ticket */
+ size_t MBEDTLS_PRIVATE(ticket_len); /*!< session ticket length */
+ uint32_t MBEDTLS_PRIVATE(ticket_lifetime); /*!< ticket lifetime hint */
+#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_CLI_C */
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_SESSION_TICKETS)
+ uint8_t MBEDTLS_PRIVATE(endpoint); /*!< 0: client, 1: server */
+ uint8_t MBEDTLS_PRIVATE(ticket_flags); /*!< Ticket flags */
+ uint32_t MBEDTLS_PRIVATE(ticket_age_add); /*!< Randomly generated value used to obscure the age of the ticket */
+ uint8_t MBEDTLS_PRIVATE(resumption_key_len); /*!< resumption_key length */
+ unsigned char MBEDTLS_PRIVATE(resumption_key)[MBEDTLS_SSL_TLS1_3_TICKET_RESUMPTION_KEY_LEN];
+
+#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) && defined(MBEDTLS_SSL_CLI_C)
+ char *MBEDTLS_PRIVATE(hostname); /*!< host name binded with tickets */
+#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION && MBEDTLS_SSL_CLI_C */
+
+#if defined(MBEDTLS_HAVE_TIME) && defined(MBEDTLS_SSL_CLI_C)
+ mbedtls_time_t MBEDTLS_PRIVATE(ticket_received); /*!< time ticket was received */
+#endif /* MBEDTLS_HAVE_TIME && MBEDTLS_SSL_CLI_C */
+
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 && MBEDTLS_SSL_SESSION_TICKETS */
+
+#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
+ int MBEDTLS_PRIVATE(encrypt_then_mac); /*!< flag for EtM activation */
+#endif
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+ mbedtls_ssl_tls13_application_secrets MBEDTLS_PRIVATE(app_secrets);
+#endif
+};
+
+/*
+ * Identifiers for PRFs used in various versions of TLS.
+ */
+typedef enum {
+ MBEDTLS_SSL_TLS_PRF_NONE,
+ MBEDTLS_SSL_TLS_PRF_SHA384,
+ MBEDTLS_SSL_TLS_PRF_SHA256,
+ MBEDTLS_SSL_HKDF_EXPAND_SHA384,
+ MBEDTLS_SSL_HKDF_EXPAND_SHA256
+}
+mbedtls_tls_prf_types;
+
+typedef enum {
+ MBEDTLS_SSL_KEY_EXPORT_TLS12_MASTER_SECRET = 0,
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+ MBEDTLS_SSL_KEY_EXPORT_TLS1_3_CLIENT_EARLY_SECRET,
+ MBEDTLS_SSL_KEY_EXPORT_TLS1_3_EARLY_EXPORTER_SECRET,
+ MBEDTLS_SSL_KEY_EXPORT_TLS1_3_CLIENT_HANDSHAKE_TRAFFIC_SECRET,
+ MBEDTLS_SSL_KEY_EXPORT_TLS1_3_SERVER_HANDSHAKE_TRAFFIC_SECRET,
+ MBEDTLS_SSL_KEY_EXPORT_TLS1_3_CLIENT_APPLICATION_TRAFFIC_SECRET,
+ MBEDTLS_SSL_KEY_EXPORT_TLS1_3_SERVER_APPLICATION_TRAFFIC_SECRET,
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
+} mbedtls_ssl_key_export_type;
+
+/**
+ * \brief Callback type: Export key alongside random values for
+ * session identification, and PRF for
+ * implementation of TLS key exporters.
+ *
+ * \param p_expkey Context for the callback.
+ * \param type The type of the key that is being exported.
+ * \param secret The address of the buffer holding the secret
+ * that's being exporterd.
+ * \param secret_len The length of \p secret in bytes.
+ * \param client_random The client random bytes.
+ * \param server_random The server random bytes.
+ * \param tls_prf_type The identifier for the PRF used in the handshake
+ * to which the key belongs.
+ */
+typedef void mbedtls_ssl_export_keys_t(void *p_expkey,
+ mbedtls_ssl_key_export_type type,
+ const unsigned char *secret,
+ size_t secret_len,
+ const unsigned char client_random[32],
+ const unsigned char server_random[32],
+ mbedtls_tls_prf_types tls_prf_type);
+
+#if defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Callback type: generic handshake callback
+ *
+ * \note Callbacks may use user_data funcs to set/get app user data.
+ * See \c mbedtls_ssl_get_user_data_p()
+ * \c mbedtls_ssl_get_user_data_n()
+ * \c mbedtls_ssl_conf_get_user_data_p()
+ * \c mbedtls_ssl_conf_get_user_data_n()
+ *
+ * \param ssl \c mbedtls_ssl_context on which the callback is run
+ *
+ * \return The return value of the callback is 0 if successful,
+ * or a specific MBEDTLS_ERR_XXX code, which will cause
+ * the handshake to be aborted.
+ */
+typedef int (*mbedtls_ssl_hs_cb_t)(mbedtls_ssl_context *ssl);
+#endif
+
+/* A type for storing user data in a library structure.
+ *
+ * The representation of type may change in future versions of the library.
+ * Only the behaviors guaranteed by documented accessor functions are
+ * guaranteed to remain stable.
+ */
+typedef union {
+ uintptr_t n; /* typically a handle to an associated object */
+ void *p; /* typically a pointer to extra data */
+} mbedtls_ssl_user_data_t;
+
+/**
+ * SSL/TLS configuration to be shared between mbedtls_ssl_context structures.
+ */
+struct mbedtls_ssl_config {
+ /* Group items mostly by size. This helps to reduce memory wasted to
+ * padding. It also helps to keep smaller fields early in the structure,
+ * so that elements tend to be in the 128-element direct access window
+ * on Arm Thumb, which reduces the code size. */
+
+ mbedtls_ssl_protocol_version MBEDTLS_PRIVATE(max_tls_version); /*!< max. TLS version used */
+ mbedtls_ssl_protocol_version MBEDTLS_PRIVATE(min_tls_version); /*!< min. TLS version used */
+
+ /*
+ * Flags (could be bit-fields to save RAM, but separate bytes make
+ * the code smaller on architectures with an instruction for direct
+ * byte access).
+ */
+
+ uint8_t MBEDTLS_PRIVATE(endpoint); /*!< 0: client, 1: server */
+ uint8_t MBEDTLS_PRIVATE(transport); /*!< 0: stream (TLS), 1: datagram (DTLS) */
+ uint8_t MBEDTLS_PRIVATE(authmode); /*!< MBEDTLS_SSL_VERIFY_XXX */
+ /* needed even with renego disabled for LEGACY_BREAK_HANDSHAKE */
+ uint8_t MBEDTLS_PRIVATE(allow_legacy_renegotiation); /*!< MBEDTLS_LEGACY_XXX */
+#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
+ uint8_t MBEDTLS_PRIVATE(mfl_code); /*!< desired fragment length indicator
+ (MBEDTLS_SSL_MAX_FRAG_LEN_XXX) */
+#endif
+#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
+ uint8_t MBEDTLS_PRIVATE(encrypt_then_mac); /*!< negotiate encrypt-then-mac? */
+#endif
+#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
+ uint8_t MBEDTLS_PRIVATE(extended_ms); /*!< negotiate extended master secret? */
+#endif
+#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
+ uint8_t MBEDTLS_PRIVATE(anti_replay); /*!< detect and prevent replay? */
+#endif
+#if defined(MBEDTLS_SSL_RENEGOTIATION)
+ uint8_t MBEDTLS_PRIVATE(disable_renegotiation); /*!< disable renegotiation? */
+#endif
+#if defined(MBEDTLS_SSL_SESSION_TICKETS) && \
+ defined(MBEDTLS_SSL_CLI_C)
+ uint8_t MBEDTLS_PRIVATE(session_tickets); /*!< use session tickets? */
+#endif
+
+#if defined(MBEDTLS_SSL_SESSION_TICKETS) && \
+ defined(MBEDTLS_SSL_SRV_C) && \
+ defined(MBEDTLS_SSL_PROTO_TLS1_3)
+ uint16_t MBEDTLS_PRIVATE(new_session_tickets_count); /*!< number of NewSessionTicket */
+#endif
+
+#if defined(MBEDTLS_SSL_SRV_C)
+ uint8_t MBEDTLS_PRIVATE(cert_req_ca_list); /*!< enable sending CA list in
+ Certificate Request messages? */
+ uint8_t MBEDTLS_PRIVATE(respect_cli_pref); /*!< pick the ciphersuite according to
+ the client's preferences rather
+ than ours? */
+#endif
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
+ uint8_t MBEDTLS_PRIVATE(ignore_unexpected_cid); /*!< Should DTLS record with
+ * unexpected CID
+ * lead to failure? */
+#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
+#if defined(MBEDTLS_SSL_DTLS_SRTP)
+ uint8_t MBEDTLS_PRIVATE(dtls_srtp_mki_support); /* support having mki_value
+ in the use_srtp extension? */
+#endif
+
+ /*
+ * Pointers
+ */
+
+ /** Allowed ciphersuites for (D)TLS 1.2 (0-terminated) */
+ const int *MBEDTLS_PRIVATE(ciphersuite_list);
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+ /** Allowed TLS 1.3 key exchange modes. */
+ int MBEDTLS_PRIVATE(tls13_kex_modes);
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
+
+ /** Callback for printing debug output */
+ void(*MBEDTLS_PRIVATE(f_dbg))(void *, int, const char *, int, const char *);
+ void *MBEDTLS_PRIVATE(p_dbg); /*!< context for the debug function */
+
+ /** Callback for getting (pseudo-)random numbers */
+ int(*MBEDTLS_PRIVATE(f_rng))(void *, unsigned char *, size_t);
+ void *MBEDTLS_PRIVATE(p_rng); /*!< context for the RNG function */
+
+ /** Callback to retrieve a session from the cache */
+ mbedtls_ssl_cache_get_t *MBEDTLS_PRIVATE(f_get_cache);
+ /** Callback to store a session into the cache */
+ mbedtls_ssl_cache_set_t *MBEDTLS_PRIVATE(f_set_cache);
+ void *MBEDTLS_PRIVATE(p_cache); /*!< context for cache callbacks */
+
+#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
+ /** Callback for setting cert according to SNI extension */
+ int(*MBEDTLS_PRIVATE(f_sni))(void *, mbedtls_ssl_context *, const unsigned char *, size_t);
+ void *MBEDTLS_PRIVATE(p_sni); /*!< context for SNI callback */
+#endif
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+ /** Callback to customize X.509 certificate chain verification */
+ int(*MBEDTLS_PRIVATE(f_vrfy))(void *, mbedtls_x509_crt *, int, uint32_t *);
+ void *MBEDTLS_PRIVATE(p_vrfy); /*!< context for X.509 verify calllback */
+#endif
+
+#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
+#if defined(MBEDTLS_SSL_SRV_C)
+ /** Callback to retrieve PSK key from identity */
+ int(*MBEDTLS_PRIVATE(f_psk))(void *, mbedtls_ssl_context *, const unsigned char *, size_t);
+ void *MBEDTLS_PRIVATE(p_psk); /*!< context for PSK callback */
+#endif
+#endif
+
+#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
+ /** Callback to create & write a cookie for ClientHello verification */
+ int(*MBEDTLS_PRIVATE(f_cookie_write))(void *, unsigned char **, unsigned char *,
+ const unsigned char *, size_t);
+ /** Callback to verify validity of a ClientHello cookie */
+ int(*MBEDTLS_PRIVATE(f_cookie_check))(void *, const unsigned char *, size_t,
+ const unsigned char *, size_t);
+ void *MBEDTLS_PRIVATE(p_cookie); /*!< context for the cookie callbacks */
+#endif
+
+#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_SRV_C)
+ /** Callback to create & write a session ticket */
+ int(*MBEDTLS_PRIVATE(f_ticket_write))(void *, const mbedtls_ssl_session *,
+ unsigned char *, const unsigned char *, size_t *,
+ uint32_t *);
+ /** Callback to parse a session ticket into a session structure */
+ int(*MBEDTLS_PRIVATE(f_ticket_parse))(void *, mbedtls_ssl_session *, unsigned char *, size_t);
+ void *MBEDTLS_PRIVATE(p_ticket); /*!< context for the ticket callbacks */
+#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_SRV_C */
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
+ size_t MBEDTLS_PRIVATE(cid_len); /*!< The length of CIDs for incoming DTLS records. */
+#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+ const mbedtls_x509_crt_profile *MBEDTLS_PRIVATE(cert_profile); /*!< verification profile */
+ mbedtls_ssl_key_cert *MBEDTLS_PRIVATE(key_cert); /*!< own certificate/key pair(s) */
+ mbedtls_x509_crt *MBEDTLS_PRIVATE(ca_chain); /*!< trusted CAs */
+ mbedtls_x509_crl *MBEDTLS_PRIVATE(ca_crl); /*!< trusted CAs CRLs */
+#if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
+ mbedtls_x509_crt_ca_cb_t MBEDTLS_PRIVATE(f_ca_cb);
+ void *MBEDTLS_PRIVATE(p_ca_cb);
+#endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+ mbedtls_ssl_async_sign_t *MBEDTLS_PRIVATE(f_async_sign_start); /*!< start asynchronous signature operation */
+ mbedtls_ssl_async_decrypt_t *MBEDTLS_PRIVATE(f_async_decrypt_start); /*!< start asynchronous decryption operation */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+ mbedtls_ssl_async_resume_t *MBEDTLS_PRIVATE(f_async_resume); /*!< resume asynchronous operation */
+ mbedtls_ssl_async_cancel_t *MBEDTLS_PRIVATE(f_async_cancel); /*!< cancel asynchronous operation */
+ void *MBEDTLS_PRIVATE(p_async_config_data); /*!< Configuration data set by mbedtls_ssl_conf_async_private_cb(). */
+#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
+
+#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+ const int *MBEDTLS_PRIVATE(sig_hashes); /*!< allowed signature hashes */
+#endif
+ const uint16_t *MBEDTLS_PRIVATE(sig_algs); /*!< allowed signature algorithms */
+#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
+
+#if defined(MBEDTLS_ECP_C) && !defined(MBEDTLS_DEPRECATED_REMOVED)
+ const mbedtls_ecp_group_id *MBEDTLS_PRIVATE(curve_list); /*!< allowed curves */
+#endif
+
+ const uint16_t *MBEDTLS_PRIVATE(group_list); /*!< allowed IANA NamedGroups */
+
+#if defined(MBEDTLS_DHM_C)
+ mbedtls_mpi MBEDTLS_PRIVATE(dhm_P); /*!< prime modulus for DHM */
+ mbedtls_mpi MBEDTLS_PRIVATE(dhm_G); /*!< generator for DHM */
+#endif
+
+#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+ mbedtls_svc_key_id_t MBEDTLS_PRIVATE(psk_opaque); /*!< PSA key slot holding opaque PSK. This field
+ * should only be set via
+ * mbedtls_ssl_conf_psk_opaque().
+ * If either no PSK or a raw PSK have been
+ * configured, this has value \c 0.
+ */
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+ unsigned char *MBEDTLS_PRIVATE(psk); /*!< The raw pre-shared key. This field should
+ * only be set via mbedtls_ssl_conf_psk().
+ * If either no PSK or an opaque PSK
+ * have been configured, this has value NULL. */
+ size_t MBEDTLS_PRIVATE(psk_len); /*!< The length of the raw pre-shared key.
+ * This field should only be set via
+ * mbedtls_ssl_conf_psk().
+ * Its value is non-zero if and only if
+ * \c psk is not \c NULL. */
+
+ unsigned char *MBEDTLS_PRIVATE(psk_identity); /*!< The PSK identity for PSK negotiation.
+ * This field should only be set via
+ * mbedtls_ssl_conf_psk().
+ * This is set if and only if either
+ * \c psk or \c psk_opaque are set. */
+ size_t MBEDTLS_PRIVATE(psk_identity_len);/*!< The length of PSK identity.
+ * This field should only be set via
+ * mbedtls_ssl_conf_psk().
+ * Its value is non-zero if and only if
+ * \c psk is not \c NULL or \c psk_opaque
+ * is not \c 0. */
+#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
+
+#if defined(MBEDTLS_SSL_EARLY_DATA)
+ int MBEDTLS_PRIVATE(early_data_enabled); /*!< Early data enablement:
+ * - MBEDTLS_SSL_EARLY_DATA_DISABLED,
+ * - MBEDTLS_SSL_EARLY_DATA_ENABLED */
+
+#if defined(MBEDTLS_SSL_SRV_C)
+ /* The maximum amount of 0-RTT data. RFC 8446 section 4.6.1 */
+ uint32_t MBEDTLS_PRIVATE(max_early_data_size);
+#endif /* MBEDTLS_SSL_SRV_C */
+
+#endif /* MBEDTLS_SSL_EARLY_DATA */
+
+#if defined(MBEDTLS_SSL_ALPN)
+ const char **MBEDTLS_PRIVATE(alpn_list); /*!< ordered list of protocols */
+#endif
+
+#if defined(MBEDTLS_SSL_DTLS_SRTP)
+ /*! ordered list of supported srtp profile */
+ const mbedtls_ssl_srtp_profile *MBEDTLS_PRIVATE(dtls_srtp_profile_list);
+ /*! number of supported profiles */
+ size_t MBEDTLS_PRIVATE(dtls_srtp_profile_list_len);
+#endif /* MBEDTLS_SSL_DTLS_SRTP */
+
+ /*
+ * Numerical settings (int)
+ */
+
+ uint32_t MBEDTLS_PRIVATE(read_timeout); /*!< timeout for mbedtls_ssl_read (ms) */
+
+#if defined(MBEDTLS_SSL_PROTO_DTLS)
+ uint32_t MBEDTLS_PRIVATE(hs_timeout_min); /*!< initial value of the handshake
+ retransmission timeout (ms) */
+ uint32_t MBEDTLS_PRIVATE(hs_timeout_max); /*!< maximum value of the handshake
+ retransmission timeout (ms) */
+#endif
+
+#if defined(MBEDTLS_SSL_RENEGOTIATION)
+ int MBEDTLS_PRIVATE(renego_max_records); /*!< grace period for renegotiation */
+ unsigned char MBEDTLS_PRIVATE(renego_period)[8]; /*!< value of the record counters
+ that triggers renegotiation */
+#endif
+
+ unsigned int MBEDTLS_PRIVATE(badmac_limit); /*!< limit of records with a bad MAC */
+
+#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
+ unsigned int MBEDTLS_PRIVATE(dhm_min_bitlen); /*!< min. bit length of the DHM prime */
+#endif
+
+ /** User data pointer or handle.
+ *
+ * The library sets this to \p 0 when creating a context and does not
+ * access it afterwards.
+ */
+ mbedtls_ssl_user_data_t MBEDTLS_PRIVATE(user_data);
+
+#if defined(MBEDTLS_SSL_SRV_C)
+ mbedtls_ssl_hs_cb_t MBEDTLS_PRIVATE(f_cert_cb); /*!< certificate selection callback */
+#endif /* MBEDTLS_SSL_SRV_C */
+
+#if defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
+ const mbedtls_x509_crt *MBEDTLS_PRIVATE(dn_hints);/*!< acceptable client cert issuers */
+#endif
+};
+
+struct mbedtls_ssl_context {
+ const mbedtls_ssl_config *MBEDTLS_PRIVATE(conf); /*!< configuration information */
+
+ /*
+ * Miscellaneous
+ */
+ int MBEDTLS_PRIVATE(state); /*!< SSL handshake: current state */
+#if defined(MBEDTLS_SSL_RENEGOTIATION)
+ int MBEDTLS_PRIVATE(renego_status); /*!< Initial, in progress, pending? */
+ int MBEDTLS_PRIVATE(renego_records_seen); /*!< Records since renego request, or with DTLS,
+ number of retransmissions of request if
+ renego_max_records is < 0 */
+#endif /* MBEDTLS_SSL_RENEGOTIATION */
+
+ /**
+ * Maximum TLS version to be negotiated, then negotiated TLS version.
+ *
+ * It is initialized as the configured maximum TLS version to be
+ * negotiated by mbedtls_ssl_setup().
+ *
+ * When renegotiating or resuming a session, it is overwritten in the
+ * ClientHello writing preparation stage with the previously negotiated
+ * TLS version.
+ *
+ * On client side, it is updated to the TLS version selected by the server
+ * for the handshake when the ServerHello is received.
+ *
+ * On server side, it is updated to the TLS version the server selects for
+ * the handshake when the ClientHello is received.
+ */
+ mbedtls_ssl_protocol_version MBEDTLS_PRIVATE(tls_version);
+
+ unsigned MBEDTLS_PRIVATE(badmac_seen); /*!< records with a bad MAC received */
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+ /** Callback to customize X.509 certificate chain verification */
+ int(*MBEDTLS_PRIVATE(f_vrfy))(void *, mbedtls_x509_crt *, int, uint32_t *);
+ void *MBEDTLS_PRIVATE(p_vrfy); /*!< context for X.509 verify callback */
+#endif
+
+ mbedtls_ssl_send_t *MBEDTLS_PRIVATE(f_send); /*!< Callback for network send */
+ mbedtls_ssl_recv_t *MBEDTLS_PRIVATE(f_recv); /*!< Callback for network receive */
+ mbedtls_ssl_recv_timeout_t *MBEDTLS_PRIVATE(f_recv_timeout);
+ /*!< Callback for network receive with timeout */
+
+ void *MBEDTLS_PRIVATE(p_bio); /*!< context for I/O operations */
+
+ /*
+ * Session layer
+ */
+ mbedtls_ssl_session *MBEDTLS_PRIVATE(session_in); /*!< current session data (in) */
+ mbedtls_ssl_session *MBEDTLS_PRIVATE(session_out); /*!< current session data (out) */
+ mbedtls_ssl_session *MBEDTLS_PRIVATE(session); /*!< negotiated session data */
+ mbedtls_ssl_session *MBEDTLS_PRIVATE(session_negotiate); /*!< session data in negotiation */
+
+ mbedtls_ssl_handshake_params *MBEDTLS_PRIVATE(handshake); /*!< params required only during
+ the handshake process */
+
+ /*
+ * Record layer transformations
+ */
+ mbedtls_ssl_transform *MBEDTLS_PRIVATE(transform_in); /*!< current transform params (in)
+ * This is always a reference,
+ * never an owning pointer. */
+ mbedtls_ssl_transform *MBEDTLS_PRIVATE(transform_out); /*!< current transform params (out)
+ * This is always a reference,
+ * never an owning pointer. */
+ mbedtls_ssl_transform *MBEDTLS_PRIVATE(transform); /*!< negotiated transform params
+ * This pointer owns the transform
+ * it references. */
+#if defined(MBEDTLS_SSL_PROTO_TLS1_2)
+ mbedtls_ssl_transform *MBEDTLS_PRIVATE(transform_negotiate); /*!< transform params in negotiation
+ * This pointer owns the transform
+ * it references. */
+#endif /* MBEDTLS_SSL_PROTO_TLS1_2 */
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+ /*! The application data transform in TLS 1.3.
+ * This pointer owns the transform it references. */
+ mbedtls_ssl_transform *MBEDTLS_PRIVATE(transform_application);
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
+
+ /*
+ * Timers
+ */
+ void *MBEDTLS_PRIVATE(p_timer); /*!< context for the timer callbacks */
+
+ mbedtls_ssl_set_timer_t *MBEDTLS_PRIVATE(f_set_timer); /*!< set timer callback */
+ mbedtls_ssl_get_timer_t *MBEDTLS_PRIVATE(f_get_timer); /*!< get timer callback */
+
+ /*
+ * Record layer (incoming data)
+ */
+ unsigned char *MBEDTLS_PRIVATE(in_buf); /*!< input buffer */
+ unsigned char *MBEDTLS_PRIVATE(in_ctr); /*!< 64-bit incoming message counter
+ TLS: maintained by us
+ DTLS: read from peer */
+ unsigned char *MBEDTLS_PRIVATE(in_hdr); /*!< start of record header */
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
+ unsigned char *MBEDTLS_PRIVATE(in_cid); /*!< The start of the CID;
+ * (the end is marked by in_len). */
+#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
+ unsigned char *MBEDTLS_PRIVATE(in_len); /*!< two-bytes message length field */
+ unsigned char *MBEDTLS_PRIVATE(in_iv); /*!< ivlen-byte IV */
+ unsigned char *MBEDTLS_PRIVATE(in_msg); /*!< message contents (in_iv+ivlen) */
+ unsigned char *MBEDTLS_PRIVATE(in_offt); /*!< read offset in application data */
+
+ int MBEDTLS_PRIVATE(in_msgtype); /*!< record header: message type */
+ size_t MBEDTLS_PRIVATE(in_msglen); /*!< record header: message length */
+ size_t MBEDTLS_PRIVATE(in_left); /*!< amount of data read so far */
+#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
+ size_t MBEDTLS_PRIVATE(in_buf_len); /*!< length of input buffer */
+#endif
+#if defined(MBEDTLS_SSL_PROTO_DTLS)
+ uint16_t MBEDTLS_PRIVATE(in_epoch); /*!< DTLS epoch for incoming records */
+ size_t MBEDTLS_PRIVATE(next_record_offset); /*!< offset of the next record in datagram
+ (equal to in_left if none) */
+#endif /* MBEDTLS_SSL_PROTO_DTLS */
+#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
+ uint64_t MBEDTLS_PRIVATE(in_window_top); /*!< last validated record seq_num */
+ uint64_t MBEDTLS_PRIVATE(in_window); /*!< bitmask for replay detection */
+#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
+
+ size_t MBEDTLS_PRIVATE(in_hslen); /*!< current handshake message length,
+ including the handshake header */
+ int MBEDTLS_PRIVATE(nb_zero); /*!< # of 0-length encrypted messages */
+
+ int MBEDTLS_PRIVATE(keep_current_message); /*!< drop or reuse current message
+ on next call to record layer? */
+
+ /* The following three variables indicate if and, if yes,
+ * what kind of alert is pending to be sent.
+ */
+ unsigned char MBEDTLS_PRIVATE(send_alert); /*!< Determines if a fatal alert
+ should be sent. Values:
+ - \c 0 , no alert is to be sent.
+ - \c 1 , alert is to be sent. */
+ unsigned char MBEDTLS_PRIVATE(alert_type); /*!< Type of alert if send_alert
+ != 0 */
+ int MBEDTLS_PRIVATE(alert_reason); /*!< The error code to be returned
+ to the user once the fatal alert
+ has been sent. */
+
+#if defined(MBEDTLS_SSL_PROTO_DTLS)
+ uint8_t MBEDTLS_PRIVATE(disable_datagram_packing); /*!< Disable packing multiple records
+ * within a single datagram. */
+#endif /* MBEDTLS_SSL_PROTO_DTLS */
+
+ /*
+ * Record layer (outgoing data)
+ */
+ unsigned char *MBEDTLS_PRIVATE(out_buf); /*!< output buffer */
+ unsigned char *MBEDTLS_PRIVATE(out_ctr); /*!< 64-bit outgoing message counter */
+ unsigned char *MBEDTLS_PRIVATE(out_hdr); /*!< start of record header */
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
+ unsigned char *MBEDTLS_PRIVATE(out_cid); /*!< The start of the CID;
+ * (the end is marked by in_len). */
+#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
+ unsigned char *MBEDTLS_PRIVATE(out_len); /*!< two-bytes message length field */
+ unsigned char *MBEDTLS_PRIVATE(out_iv); /*!< ivlen-byte IV */
+ unsigned char *MBEDTLS_PRIVATE(out_msg); /*!< message contents (out_iv+ivlen) */
+
+ int MBEDTLS_PRIVATE(out_msgtype); /*!< record header: message type */
+ size_t MBEDTLS_PRIVATE(out_msglen); /*!< record header: message length */
+ size_t MBEDTLS_PRIVATE(out_left); /*!< amount of data not yet written */
+#if defined(MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH)
+ size_t MBEDTLS_PRIVATE(out_buf_len); /*!< length of output buffer */
+#endif
+
+ unsigned char MBEDTLS_PRIVATE(cur_out_ctr)[MBEDTLS_SSL_SEQUENCE_NUMBER_LEN]; /*!< Outgoing record sequence number. */
+
+#if defined(MBEDTLS_SSL_PROTO_DTLS)
+ uint16_t MBEDTLS_PRIVATE(mtu); /*!< path mtu, used to fragment outgoing messages */
+#endif /* MBEDTLS_SSL_PROTO_DTLS */
+
+ /*
+ * User settings
+ */
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+ char *MBEDTLS_PRIVATE(hostname); /*!< expected peer CN for verification
+ (and SNI if available) */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+#if defined(MBEDTLS_SSL_ALPN)
+ const char *MBEDTLS_PRIVATE(alpn_chosen); /*!< negotiated protocol */
+#endif /* MBEDTLS_SSL_ALPN */
+
+#if defined(MBEDTLS_SSL_DTLS_SRTP)
+ /*
+ * use_srtp extension
+ */
+ mbedtls_dtls_srtp_info MBEDTLS_PRIVATE(dtls_srtp_info);
+#endif /* MBEDTLS_SSL_DTLS_SRTP */
+
+ /*
+ * Information for DTLS hello verify
+ */
+#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
+ unsigned char *MBEDTLS_PRIVATE(cli_id); /*!< transport-level ID of the client */
+ size_t MBEDTLS_PRIVATE(cli_id_len); /*!< length of cli_id */
+#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
+
+ /*
+ * Secure renegotiation
+ */
+ /* needed to know when to send extension on server */
+ int MBEDTLS_PRIVATE(secure_renegotiation); /*!< does peer support legacy or
+ secure renegotiation */
+#if defined(MBEDTLS_SSL_RENEGOTIATION)
+ size_t MBEDTLS_PRIVATE(verify_data_len); /*!< length of verify data stored */
+ char MBEDTLS_PRIVATE(own_verify_data)[MBEDTLS_SSL_VERIFY_DATA_MAX_LEN]; /*!< previous handshake verify data */
+ char MBEDTLS_PRIVATE(peer_verify_data)[MBEDTLS_SSL_VERIFY_DATA_MAX_LEN]; /*!< previous handshake verify data */
+#endif /* MBEDTLS_SSL_RENEGOTIATION */
+
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
+ /* CID configuration to use in subsequent handshakes. */
+
+ /*! The next incoming CID, chosen by the user and applying to
+ * all subsequent handshakes. This may be different from the
+ * CID currently used in case the user has re-configured the CID
+ * after an initial handshake. */
+ unsigned char MBEDTLS_PRIVATE(own_cid)[MBEDTLS_SSL_CID_IN_LEN_MAX];
+ uint8_t MBEDTLS_PRIVATE(own_cid_len); /*!< The length of \c own_cid. */
+ uint8_t MBEDTLS_PRIVATE(negotiate_cid); /*!< This indicates whether the CID extension should
+ * be negotiated in the next handshake or not.
+ * Possible values are #MBEDTLS_SSL_CID_ENABLED
+ * and #MBEDTLS_SSL_CID_DISABLED. */
+#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
+
+#if defined(MBEDTLS_SSL_EARLY_DATA) && defined(MBEDTLS_SSL_CLI_C)
+ int MBEDTLS_PRIVATE(early_data_status);
+#endif /* MBEDTLS_SSL_EARLY_DATA && MBEDTLS_SSL_CLI_C */
+
+ /** Callback to export key block and master secret */
+ mbedtls_ssl_export_keys_t *MBEDTLS_PRIVATE(f_export_keys);
+ void *MBEDTLS_PRIVATE(p_export_keys); /*!< context for key export callback */
+
+ /** User data pointer or handle.
+ *
+ * The library sets this to \p 0 when creating a context and does not
+ * access it afterwards.
+ *
+ * \warning Serializing and restoring an SSL context with
+ * mbedtls_ssl_context_save() and mbedtls_ssl_context_load()
+ * does not currently restore the user data.
+ */
+ mbedtls_ssl_user_data_t MBEDTLS_PRIVATE(user_data);
+};
+
+/**
+ * \brief Return the name of the ciphersuite associated with the
+ * given ID
+ *
+ * \param ciphersuite_id SSL ciphersuite ID
+ *
+ * \return a string containing the ciphersuite name
+ */
+const char *mbedtls_ssl_get_ciphersuite_name(const int ciphersuite_id);
+
+/**
+ * \brief Return the ID of the ciphersuite associated with the
+ * given name
+ *
+ * \param ciphersuite_name SSL ciphersuite name
+ *
+ * \return the ID with the ciphersuite or 0 if not found
+ */
+int mbedtls_ssl_get_ciphersuite_id(const char *ciphersuite_name);
+
+/**
+ * \brief Initialize an SSL context
+ * Just makes the context ready for mbedtls_ssl_setup() or
+ * mbedtls_ssl_free()
+ *
+ * \param ssl SSL context
+ */
+void mbedtls_ssl_init(mbedtls_ssl_context *ssl);
+
+/**
+ * \brief Set up an SSL context for use
+ *
+ * \note No copy of the configuration context is made, it can be
+ * shared by many mbedtls_ssl_context structures.
+ *
+ * \warning The conf structure will be accessed during the session.
+ * It must not be modified or freed as long as the session
+ * is active.
+ *
+ * \warning This function must be called exactly once per context.
+ * Calling mbedtls_ssl_setup again is not supported, even
+ * if no session is active.
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param ssl SSL context
+ * \param conf SSL configuration to use
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED if
+ * memory allocation failed
+ */
+int mbedtls_ssl_setup(mbedtls_ssl_context *ssl,
+ const mbedtls_ssl_config *conf);
+
+/**
+ * \brief Reset an already initialized SSL context for re-use
+ * while retaining application-set variables, function
+ * pointers and data.
+ *
+ * \param ssl SSL context
+ * \return 0 if successful, or MBEDTLS_ERR_SSL_ALLOC_FAILED or
+ MBEDTLS_ERR_SSL_HW_ACCEL_FAILED
+ */
+int mbedtls_ssl_session_reset(mbedtls_ssl_context *ssl);
+
+/**
+ * \brief Set the current endpoint type
+ *
+ * \param conf SSL configuration
+ * \param endpoint must be MBEDTLS_SSL_IS_CLIENT or MBEDTLS_SSL_IS_SERVER
+ */
+void mbedtls_ssl_conf_endpoint(mbedtls_ssl_config *conf, int endpoint);
+
+/**
+ * \brief Get the current endpoint type
+ *
+ * \param conf SSL configuration
+ *
+ * \return Endpoint type, either MBEDTLS_SSL_IS_CLIENT
+ * or MBEDTLS_SSL_IS_SERVER
+ */
+static inline int mbedtls_ssl_conf_get_endpoint(const mbedtls_ssl_config *conf)
+{
+ return conf->MBEDTLS_PRIVATE(endpoint);
+}
+
+/**
+ * \brief Set the transport type (TLS or DTLS).
+ * Default: TLS
+ *
+ * \note For DTLS, you must either provide a recv callback that
+ * doesn't block, or one that handles timeouts, see
+ * \c mbedtls_ssl_set_bio(). You also need to provide timer
+ * callbacks with \c mbedtls_ssl_set_timer_cb().
+ *
+ * \param conf SSL configuration
+ * \param transport transport type:
+ * MBEDTLS_SSL_TRANSPORT_STREAM for TLS,
+ * MBEDTLS_SSL_TRANSPORT_DATAGRAM for DTLS.
+ */
+void mbedtls_ssl_conf_transport(mbedtls_ssl_config *conf, int transport);
+
+/**
+ * \brief Set the certificate verification mode
+ * Default: NONE on server, REQUIRED on client
+ *
+ * \param conf SSL configuration
+ * \param authmode can be:
+ *
+ * MBEDTLS_SSL_VERIFY_NONE: peer certificate is not checked
+ * (default on server)
+ * (insecure on client)
+ *
+ * MBEDTLS_SSL_VERIFY_OPTIONAL: peer certificate is checked, however the
+ * handshake continues even if verification failed;
+ * mbedtls_ssl_get_verify_result() can be called after the
+ * handshake is complete.
+ *
+ * MBEDTLS_SSL_VERIFY_REQUIRED: peer *must* present a valid certificate,
+ * handshake is aborted if verification failed.
+ * (default on client)
+ *
+ * \note On client, MBEDTLS_SSL_VERIFY_REQUIRED is the recommended mode.
+ * With MBEDTLS_SSL_VERIFY_OPTIONAL, the user needs to call mbedtls_ssl_get_verify_result() at
+ * the right time(s), which may not be obvious, while REQUIRED always perform
+ * the verification as soon as possible. For example, REQUIRED was protecting
+ * against the "triple handshake" attack even before it was found.
+ */
+void mbedtls_ssl_conf_authmode(mbedtls_ssl_config *conf, int authmode);
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3) && defined(MBEDTLS_SSL_EARLY_DATA)
+/**
+ * \brief Set the early data mode
+ * Default: disabled on server and client
+ *
+ * \param conf The SSL configuration to use.
+ * \param early_data_enabled can be:
+ *
+ * MBEDTLS_SSL_EARLY_DATA_DISABLED: early data functionality is disabled
+ * This is the default on client and server.
+ *
+ * MBEDTLS_SSL_EARLY_DATA_ENABLED: early data functionality is enabled and
+ * may be negotiated in the handshake. Application using
+ * early data functionality needs to be aware of the
+ * lack of replay protection of the early data application
+ * payloads.
+ *
+ * \warning This interface is experimental and may change without notice.
+ *
+ */
+void mbedtls_ssl_tls13_conf_early_data(mbedtls_ssl_config *conf,
+ int early_data_enabled);
+
+#if defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Set the maximum amount of 0-RTT data in bytes
+ * Default: #MBEDTLS_SSL_MAX_EARLY_DATA_SIZE
+ *
+ * This function sets the value of the max_early_data_size
+ * field of the early data indication extension included in
+ * the NewSessionTicket messages that the server may send.
+ *
+ * The value defines the maximum amount of 0-RTT data
+ * in bytes that a client will be allowed to send when using
+ * one of the tickets defined by the NewSessionTicket messages.
+ *
+ * \note When resuming a session using a ticket, if the server receives more
+ * early data than allowed for the ticket, it terminates the connection.
+ * The maximum amount of 0-RTT data should thus be large enough
+ * to allow a minimum of early data to be exchanged.
+ *
+ * \param[in] conf The SSL configuration to use.
+ * \param[in] max_early_data_size The maximum amount of 0-RTT data.
+ *
+ * \warning This interface is experimental and may change without notice.
+ *
+ */
+void mbedtls_ssl_tls13_conf_max_early_data_size(
+ mbedtls_ssl_config *conf, uint32_t max_early_data_size);
+#endif /* MBEDTLS_SSL_SRV_C */
+
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 && MBEDTLS_SSL_EARLY_DATA */
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+/**
+ * \brief Set the verification callback (Optional).
+ *
+ * If set, the provided verify callback is called for each
+ * certificate in the peer's CRT chain, including the trusted
+ * root. For more information, please see the documentation of
+ * \c mbedtls_x509_crt_verify().
+ *
+ * \note For per context callbacks and contexts, please use
+ * mbedtls_ssl_set_verify() instead.
+ *
+ * \param conf The SSL configuration to use.
+ * \param f_vrfy The verification callback to use during CRT verification.
+ * \param p_vrfy The opaque context to be passed to the callback.
+ */
+void mbedtls_ssl_conf_verify(mbedtls_ssl_config *conf,
+ int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
+ void *p_vrfy);
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+/**
+ * \brief Set the random number generator callback
+ *
+ * \param conf SSL configuration
+ * \param f_rng RNG function (mandatory)
+ * \param p_rng RNG parameter
+ */
+void mbedtls_ssl_conf_rng(mbedtls_ssl_config *conf,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief Set the debug callback
+ *
+ * The callback has the following argument:
+ * void * opaque context for the callback
+ * int debug level
+ * const char * file name
+ * int line number
+ * const char * message
+ *
+ * \param conf SSL configuration
+ * \param f_dbg debug function
+ * \param p_dbg debug parameter
+ */
+void mbedtls_ssl_conf_dbg(mbedtls_ssl_config *conf,
+ void (*f_dbg)(void *, int, const char *, int, const char *),
+ void *p_dbg);
+
+/**
+ * \brief Return the SSL configuration structure associated
+ * with the given SSL context.
+ *
+ * \note The pointer returned by this function is guaranteed to
+ * remain valid until the context is freed.
+ *
+ * \param ssl The SSL context to query.
+ * \return Pointer to the SSL configuration associated with \p ssl.
+ */
+static inline const mbedtls_ssl_config *mbedtls_ssl_context_get_config(
+ const mbedtls_ssl_context *ssl)
+{
+ return ssl->MBEDTLS_PRIVATE(conf);
+}
+
+/**
+ * \brief Set the underlying BIO callbacks for write, read and
+ * read-with-timeout.
+ *
+ * \param ssl SSL context
+ * \param p_bio parameter (context) shared by BIO callbacks
+ * \param f_send write callback
+ * \param f_recv read callback
+ * \param f_recv_timeout blocking read callback with timeout.
+ *
+ * \note One of f_recv or f_recv_timeout can be NULL, in which case
+ * the other is used. If both are non-NULL, f_recv_timeout is
+ * used and f_recv is ignored (as if it were NULL).
+ *
+ * \note The two most common use cases are:
+ * - non-blocking I/O, f_recv != NULL, f_recv_timeout == NULL
+ * - blocking I/O, f_recv == NULL, f_recv_timeout != NULL
+ *
+ * \note For DTLS, you need to provide either a non-NULL
+ * f_recv_timeout callback, or a f_recv that doesn't block.
+ *
+ * \note See the documentations of \c mbedtls_ssl_send_t,
+ * \c mbedtls_ssl_recv_t and \c mbedtls_ssl_recv_timeout_t for
+ * the conventions those callbacks must follow.
+ *
+ * \note On some platforms, net_sockets.c provides
+ * \c mbedtls_net_send(), \c mbedtls_net_recv() and
+ * \c mbedtls_net_recv_timeout() that are suitable to be used
+ * here.
+ */
+void mbedtls_ssl_set_bio(mbedtls_ssl_context *ssl,
+ void *p_bio,
+ mbedtls_ssl_send_t *f_send,
+ mbedtls_ssl_recv_t *f_recv,
+ mbedtls_ssl_recv_timeout_t *f_recv_timeout);
+
+#if defined(MBEDTLS_SSL_PROTO_DTLS)
+
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
+
+
+/**
+ * \brief Configure the use of the Connection ID (CID)
+ * extension in the next handshake.
+ *
+ * Reference: RFC 9146 (or draft-ietf-tls-dtls-connection-id-05
+ * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05
+ * for legacy version)
+ *
+ * The DTLS CID extension allows the reliable association of
+ * DTLS records to DTLS connections across changes in the
+ * underlying transport (changed IP and Port metadata) by
+ * adding explicit connection identifiers (CIDs) to the
+ * headers of encrypted DTLS records. The desired CIDs are
+ * configured by the application layer and are exchanged in
+ * new `ClientHello` / `ServerHello` extensions during the
+ * handshake, where each side indicates the CID it wants the
+ * peer to use when writing encrypted messages. The CIDs are
+ * put to use once records get encrypted: the stack discards
+ * any incoming records that don't include the configured CID
+ * in their header, and adds the peer's requested CID to the
+ * headers of outgoing messages.
+ *
+ * This API enables or disables the use of the CID extension
+ * in the next handshake and sets the value of the CID to
+ * be used for incoming messages.
+ *
+ * \param ssl The SSL context to configure. This must be initialized.
+ * \param enable This value determines whether the CID extension should
+ * be used or not. Possible values are:
+ * - MBEDTLS_SSL_CID_ENABLED to enable the use of the CID.
+ * - MBEDTLS_SSL_CID_DISABLED (default) to disable the use
+ * of the CID.
+ * \param own_cid The address of the readable buffer holding the CID we want
+ * the peer to use when sending encrypted messages to us.
+ * This may be \c NULL if \p own_cid_len is \c 0.
+ * This parameter is unused if \p enable is set to
+ * MBEDTLS_SSL_CID_DISABLED.
+ * \param own_cid_len The length of \p own_cid.
+ * This parameter is unused if \p enable is set to
+ * MBEDTLS_SSL_CID_DISABLED.
+ *
+ * \note The value of \p own_cid_len must match the value of the
+ * \c len parameter passed to mbedtls_ssl_conf_cid()
+ * when configuring the ::mbedtls_ssl_config that \p ssl
+ * is bound to.
+ *
+ * \note This CID configuration applies to subsequent handshakes
+ * performed on the SSL context \p ssl, but does not trigger
+ * one. You still have to call `mbedtls_ssl_handshake()`
+ * (for the initial handshake) or `mbedtls_ssl_renegotiate()`
+ * (for a renegotiation handshake) explicitly after a
+ * successful call to this function to run the handshake.
+ *
+ * \note This call cannot guarantee that the use of the CID
+ * will be successfully negotiated in the next handshake,
+ * because the peer might not support it. Specifically:
+ * - On the Client, enabling the use of the CID through
+ * this call implies that the `ClientHello` in the next
+ * handshake will include the CID extension, thereby
+ * offering the use of the CID to the server. Only if
+ * the `ServerHello` contains the CID extension, too,
+ * the CID extension will actually be put to use.
+ * - On the Server, enabling the use of the CID through
+ * this call implies that the server will look for
+ * the CID extension in a `ClientHello` from the client,
+ * and, if present, reply with a CID extension in its
+ * `ServerHello`.
+ *
+ * \note To check whether the use of the CID was negotiated
+ * after the subsequent handshake has completed, please
+ * use the API mbedtls_ssl_get_peer_cid().
+ *
+ * \warning If the use of the CID extension is enabled in this call
+ * and the subsequent handshake negotiates its use, Mbed TLS
+ * will silently drop every packet whose CID does not match
+ * the CID configured in \p own_cid. It is the responsibility
+ * of the user to adapt the underlying transport to take care
+ * of CID-based demultiplexing before handing datagrams to
+ * Mbed TLS.
+ *
+ * \return \c 0 on success. In this case, the CID configuration
+ * applies to the next handshake.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ssl_set_cid(mbedtls_ssl_context *ssl,
+ int enable,
+ unsigned char const *own_cid,
+ size_t own_cid_len);
+
+/**
+ * \brief Get information about our request for usage of the CID
+ * extension in the current connection.
+ *
+ * \param ssl The SSL context to query.
+ * \param enabled The address at which to store whether the CID extension
+ * is requested to be used or not. If the CID is
+ * requested, `*enabled` is set to
+ * MBEDTLS_SSL_CID_ENABLED; otherwise, it is set to
+ * MBEDTLS_SSL_CID_DISABLED.
+ * \param own_cid The address of the buffer in which to store our own
+ * CID (if the CID extension is requested). This may be
+ * \c NULL in case the value of our CID isn't needed. If
+ * it is not \c NULL, \p own_cid_len must not be \c NULL.
+ * \param own_cid_len The address at which to store the size of our own CID
+ * (if the CID extension is requested). This is also the
+ * number of Bytes in \p own_cid that have been written.
+ * This may be \c NULL in case the length of our own CID
+ * isn't needed. If it is \c NULL, \p own_cid must be
+ * \c NULL, too.
+ *
+ *\note If we are requesting an empty CID this function sets
+ * `*enabled` to #MBEDTLS_SSL_CID_DISABLED (the rationale
+ * for this is that the resulting outcome is the
+ * same as if the CID extensions wasn't requested).
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ssl_get_own_cid(mbedtls_ssl_context *ssl,
+ int *enabled,
+ unsigned char own_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX],
+ size_t *own_cid_len);
+
+/**
+ * \brief Get information about the use of the CID extension
+ * in the current connection.
+ *
+ * \param ssl The SSL context to query.
+ * \param enabled The address at which to store whether the CID extension
+ * is currently in use or not. If the CID is in use,
+ * `*enabled` is set to MBEDTLS_SSL_CID_ENABLED;
+ * otherwise, it is set to MBEDTLS_SSL_CID_DISABLED.
+ * \param peer_cid The address of the buffer in which to store the CID
+ * chosen by the peer (if the CID extension is used).
+ * This may be \c NULL in case the value of peer CID
+ * isn't needed. If it is not \c NULL, \p peer_cid_len
+ * must not be \c NULL.
+ * \param peer_cid_len The address at which to store the size of the CID
+ * chosen by the peer (if the CID extension is used).
+ * This is also the number of Bytes in \p peer_cid that
+ * have been written.
+ * This may be \c NULL in case the length of the peer CID
+ * isn't needed. If it is \c NULL, \p peer_cid must be
+ * \c NULL, too.
+ *
+ * \note This applies to the state of the CID negotiated in
+ * the last complete handshake. If a handshake is in
+ * progress, this function will attempt to complete
+ * the handshake first.
+ *
+ * \note If CID extensions have been exchanged but both client
+ * and server chose to use an empty CID, this function
+ * sets `*enabled` to #MBEDTLS_SSL_CID_DISABLED
+ * (the rationale for this is that the resulting
+ * communication is the same as if the CID extensions
+ * hadn't been used).
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ssl_get_peer_cid(mbedtls_ssl_context *ssl,
+ int *enabled,
+ unsigned char peer_cid[MBEDTLS_SSL_CID_OUT_LEN_MAX],
+ size_t *peer_cid_len);
+
+#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
+
+/**
+ * \brief Set the Maximum Transport Unit (MTU).
+ * Special value: 0 means unset (no limit).
+ * This represents the maximum size of a datagram payload
+ * handled by the transport layer (usually UDP) as determined
+ * by the network link and stack. In practice, this controls
+ * the maximum size datagram the DTLS layer will pass to the
+ * \c f_send() callback set using \c mbedtls_ssl_set_bio().
+ *
+ * \note The limit on datagram size is converted to a limit on
+ * record payload by subtracting the current overhead of
+ * encapsulation and encryption/authentication if any.
+ *
+ * \note This can be called at any point during the connection, for
+ * example when a Path Maximum Transfer Unit (PMTU)
+ * estimate becomes available from other sources,
+ * such as lower (or higher) protocol layers.
+ *
+ * \note This setting only controls the size of the packets we send,
+ * and does not restrict the size of the datagrams we're
+ * willing to receive. Client-side, you can request the
+ * server to use smaller records with \c
+ * mbedtls_ssl_conf_max_frag_len().
+ *
+ * \note If both a MTU and a maximum fragment length have been
+ * configured (or negotiated with the peer), the resulting
+ * lower limit on record payload (see first note) is used.
+ *
+ * \note This can only be used to decrease the maximum size
+ * of datagrams (hence records, see first note) sent. It
+ * cannot be used to increase the maximum size of records over
+ * the limit set by #MBEDTLS_SSL_OUT_CONTENT_LEN.
+ *
+ * \note Values lower than the current record layer expansion will
+ * result in an error when trying to send data.
+ *
+ * \param ssl SSL context
+ * \param mtu Value of the path MTU in bytes
+ */
+void mbedtls_ssl_set_mtu(mbedtls_ssl_context *ssl, uint16_t mtu);
+#endif /* MBEDTLS_SSL_PROTO_DTLS */
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+/**
+ * \brief Set a connection-specific verification callback (optional).
+ *
+ * If set, the provided verify callback is called for each
+ * certificate in the peer's CRT chain, including the trusted
+ * root. For more information, please see the documentation of
+ * \c mbedtls_x509_crt_verify().
+ *
+ * \note This call is analogous to mbedtls_ssl_conf_verify() but
+ * binds the verification callback and context to an SSL context
+ * as opposed to an SSL configuration.
+ * If mbedtls_ssl_conf_verify() and mbedtls_ssl_set_verify()
+ * are both used, mbedtls_ssl_set_verify() takes precedence.
+ *
+ * \param ssl The SSL context to use.
+ * \param f_vrfy The verification callback to use during CRT verification.
+ * \param p_vrfy The opaque context to be passed to the callback.
+ */
+void mbedtls_ssl_set_verify(mbedtls_ssl_context *ssl,
+ int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
+ void *p_vrfy);
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+/**
+ * \brief Set the timeout period for mbedtls_ssl_read()
+ * (Default: no timeout.)
+ *
+ * \param conf SSL configuration context
+ * \param timeout Timeout value in milliseconds.
+ * Use 0 for no timeout (default).
+ *
+ * \note With blocking I/O, this will only work if a non-NULL
+ * \c f_recv_timeout was set with \c mbedtls_ssl_set_bio().
+ * With non-blocking I/O, this will only work if timer
+ * callbacks were set with \c mbedtls_ssl_set_timer_cb().
+ *
+ * \note With non-blocking I/O, you may also skip this function
+ * altogether and handle timeouts at the application layer.
+ */
+void mbedtls_ssl_conf_read_timeout(mbedtls_ssl_config *conf, uint32_t timeout);
+
+/**
+ * \brief Check whether a buffer contains a valid and authentic record
+ * that has not been seen before. (DTLS only).
+ *
+ * This function does not change the user-visible state
+ * of the SSL context. Its sole purpose is to provide
+ * an indication of the legitimacy of an incoming record.
+ *
+ * This can be useful e.g. in distributed server environments
+ * using the DTLS Connection ID feature, in which connections
+ * might need to be passed between service instances on a change
+ * of peer address, but where such disruptive operations should
+ * only happen after the validity of incoming records has been
+ * confirmed.
+ *
+ * \param ssl The SSL context to use.
+ * \param buf The address of the buffer holding the record to be checked.
+ * This must be a read/write buffer of length \p buflen Bytes.
+ * \param buflen The length of \p buf in Bytes.
+ *
+ * \note This routine only checks whether the provided buffer begins
+ * with a valid and authentic record that has not been seen
+ * before, but does not check potential data following the
+ * initial record. In particular, it is possible to pass DTLS
+ * datagrams containing multiple records, in which case only
+ * the first record is checked.
+ *
+ * \note This function modifies the input buffer \p buf. If you need
+ * to preserve the original record, you have to maintain a copy.
+ *
+ * \return \c 0 if the record is valid and authentic and has not been
+ * seen before.
+ * \return MBEDTLS_ERR_SSL_INVALID_MAC if the check completed
+ * successfully but the record was found to be not authentic.
+ * \return MBEDTLS_ERR_SSL_INVALID_RECORD if the check completed
+ * successfully but the record was found to be invalid for
+ * a reason different from authenticity checking.
+ * \return MBEDTLS_ERR_SSL_UNEXPECTED_RECORD if the check completed
+ * successfully but the record was found to be unexpected
+ * in the state of the SSL context, including replayed records.
+ * \return Another negative error code on different kinds of failure.
+ * In this case, the SSL context becomes unusable and needs
+ * to be freed or reset before reuse.
+ */
+int mbedtls_ssl_check_record(mbedtls_ssl_context const *ssl,
+ unsigned char *buf,
+ size_t buflen);
+
+/**
+ * \brief Set the timer callbacks (Mandatory for DTLS.)
+ *
+ * \param ssl SSL context
+ * \param p_timer parameter (context) shared by timer callbacks
+ * \param f_set_timer set timer callback
+ * \param f_get_timer get timer callback. Must return:
+ *
+ * \note See the documentation of \c mbedtls_ssl_set_timer_t and
+ * \c mbedtls_ssl_get_timer_t for the conventions this pair of
+ * callbacks must follow.
+ *
+ * \note On some platforms, timing.c provides
+ * \c mbedtls_timing_set_delay() and
+ * \c mbedtls_timing_get_delay() that are suitable for using
+ * here, except if using an event-driven style.
+ *
+ * \note See also the "DTLS tutorial" article in our knowledge base.
+ * https://mbed-tls.readthedocs.io/en/latest/kb/how-to/dtls-tutorial
+ */
+void mbedtls_ssl_set_timer_cb(mbedtls_ssl_context *ssl,
+ void *p_timer,
+ mbedtls_ssl_set_timer_t *f_set_timer,
+ mbedtls_ssl_get_timer_t *f_get_timer);
+
+#if defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Set the certificate selection callback (server-side only).
+ *
+ * If set, the callback is always called for each handshake,
+ * after `ClientHello` processing has finished.
+ *
+ * \param conf The SSL configuration to register the callback with.
+ * \param f_cert_cb The callback for selecting server certificate after
+ * `ClientHello` processing has finished.
+ */
+static inline void mbedtls_ssl_conf_cert_cb(mbedtls_ssl_config *conf,
+ mbedtls_ssl_hs_cb_t f_cert_cb)
+{
+ conf->MBEDTLS_PRIVATE(f_cert_cb) = f_cert_cb;
+}
+#endif /* MBEDTLS_SSL_SRV_C */
+
+/**
+ * \brief Callback type: generate and write session ticket
+ *
+ * \note This describes what a callback implementation should do.
+ * This callback should generate an encrypted and
+ * authenticated ticket for the session and write it to the
+ * output buffer. Here, ticket means the opaque ticket part
+ * of the NewSessionTicket structure of RFC 5077.
+ *
+ * \param p_ticket Context for the callback
+ * \param session SSL session to be written in the ticket
+ * \param start Start of the output buffer
+ * \param end End of the output buffer
+ * \param tlen On exit, holds the length written
+ * \param lifetime On exit, holds the lifetime of the ticket in seconds
+ *
+ * \return 0 if successful, or
+ * a specific MBEDTLS_ERR_XXX code.
+ */
+typedef int mbedtls_ssl_ticket_write_t(void *p_ticket,
+ const mbedtls_ssl_session *session,
+ unsigned char *start,
+ const unsigned char *end,
+ size_t *tlen,
+ uint32_t *lifetime);
+
+/**
+ * \brief Callback type: parse and load session ticket
+ *
+ * \note This describes what a callback implementation should do.
+ * This callback should parse a session ticket as generated
+ * by the corresponding mbedtls_ssl_ticket_write_t function,
+ * and, if the ticket is authentic and valid, load the
+ * session.
+ *
+ * \note The implementation is allowed to modify the first len
+ * bytes of the input buffer, eg to use it as a temporary
+ * area for the decrypted ticket contents.
+ *
+ * \param p_ticket Context for the callback
+ * \param session SSL session to be loaded
+ * \param buf Start of the buffer containing the ticket
+ * \param len Length of the ticket.
+ *
+ * \return 0 if successful, or
+ * MBEDTLS_ERR_SSL_INVALID_MAC if not authentic, or
+ * MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED if expired, or
+ * any other non-zero code for other failures.
+ */
+typedef int mbedtls_ssl_ticket_parse_t(void *p_ticket,
+ mbedtls_ssl_session *session,
+ unsigned char *buf,
+ size_t len);
+
+#if defined(MBEDTLS_SSL_SESSION_TICKETS) && defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Configure SSL session ticket callbacks (server only).
+ * (Default: none.)
+ *
+ * \note On server, session tickets are enabled by providing
+ * non-NULL callbacks.
+ *
+ * \note On client, use \c mbedtls_ssl_conf_session_tickets().
+ *
+ * \param conf SSL configuration context
+ * \param f_ticket_write Callback for writing a ticket
+ * \param f_ticket_parse Callback for parsing a ticket
+ * \param p_ticket Context shared by the two callbacks
+ */
+void mbedtls_ssl_conf_session_tickets_cb(mbedtls_ssl_config *conf,
+ mbedtls_ssl_ticket_write_t *f_ticket_write,
+ mbedtls_ssl_ticket_parse_t *f_ticket_parse,
+ void *p_ticket);
+#endif /* MBEDTLS_SSL_SESSION_TICKETS && MBEDTLS_SSL_SRV_C */
+
+/**
+ * \brief Configure a key export callback.
+ * (Default: none.)
+ *
+ * This API can be used for two purposes:
+ * - Debugging: Use this API to e.g. generate an NSSKeylog
+ * file and use it to inspect encrypted traffic in tools
+ * such as Wireshark.
+ * - Application-specific export: Use this API to implement
+ * key exporters, e.g. for EAP-TLS or DTLS-SRTP.
+ *
+ *
+ * \param ssl The SSL context to which the export
+ * callback should be attached.
+ * \param f_export_keys The callback for the key export.
+ * \param p_export_keys The opaque context pointer to be passed to the
+ * callback \p f_export_keys.
+ */
+void mbedtls_ssl_set_export_keys_cb(mbedtls_ssl_context *ssl,
+ mbedtls_ssl_export_keys_t *f_export_keys,
+ void *p_export_keys);
+
+/** \brief Set the user data in an SSL configuration to a pointer.
+ *
+ * You can retrieve this value later with mbedtls_ssl_conf_get_user_data_p().
+ *
+ * \note The library stores \c p without accessing it. It is the responsibility
+ * of the caller to ensure that the pointer remains valid.
+ *
+ * \param conf The SSL configuration context to modify.
+ * \param p The new value of the user data.
+ */
+static inline void mbedtls_ssl_conf_set_user_data_p(
+ mbedtls_ssl_config *conf,
+ void *p)
+{
+ conf->MBEDTLS_PRIVATE(user_data).p = p;
+}
+
+/** \brief Set the user data in an SSL configuration to an integer.
+ *
+ * You can retrieve this value later with mbedtls_ssl_conf_get_user_data_n().
+ *
+ * \param conf The SSL configuration context to modify.
+ * \param n The new value of the user data.
+ */
+static inline void mbedtls_ssl_conf_set_user_data_n(
+ mbedtls_ssl_config *conf,
+ uintptr_t n)
+{
+ conf->MBEDTLS_PRIVATE(user_data).n = n;
+}
+
+/** \brief Retrieve the user data in an SSL configuration as a pointer.
+ *
+ * This is the value last set with mbedtls_ssl_conf_set_user_data_p(), or
+ * \c NULL if mbedtls_ssl_conf_set_user_data_p() has not previously been
+ * called. The value is undefined if mbedtls_ssl_conf_set_user_data_n() has
+ * been called without a subsequent call to mbedtls_ssl_conf_set_user_data_p().
+ *
+ * \param conf The SSL configuration context to modify.
+ * \return The current value of the user data.
+ */
+static inline void *mbedtls_ssl_conf_get_user_data_p(
+ mbedtls_ssl_config *conf)
+{
+ return conf->MBEDTLS_PRIVATE(user_data).p;
+}
+
+/** \brief Retrieve the user data in an SSL configuration as an integer.
+ *
+ * This is the value last set with mbedtls_ssl_conf_set_user_data_n(), or
+ * \c 0 if mbedtls_ssl_conf_set_user_data_n() has not previously been
+ * called. The value is undefined if mbedtls_ssl_conf_set_user_data_p() has
+ * been called without a subsequent call to mbedtls_ssl_conf_set_user_data_n().
+ *
+ * \param conf The SSL configuration context to modify.
+ * \return The current value of the user data.
+ */
+static inline uintptr_t mbedtls_ssl_conf_get_user_data_n(
+ mbedtls_ssl_config *conf)
+{
+ return conf->MBEDTLS_PRIVATE(user_data).n;
+}
+
+/** \brief Set the user data in an SSL context to a pointer.
+ *
+ * You can retrieve this value later with mbedtls_ssl_get_user_data_p().
+ *
+ * \note The library stores \c p without accessing it. It is the responsibility
+ * of the caller to ensure that the pointer remains valid.
+ *
+ * \param ssl The SSL context to modify.
+ * \param p The new value of the user data.
+ */
+static inline void mbedtls_ssl_set_user_data_p(
+ mbedtls_ssl_context *ssl,
+ void *p)
+{
+ ssl->MBEDTLS_PRIVATE(user_data).p = p;
+}
+
+/** \brief Set the user data in an SSL context to an integer.
+ *
+ * You can retrieve this value later with mbedtls_ssl_get_user_data_n().
+ *
+ * \param ssl The SSL context to modify.
+ * \param n The new value of the user data.
+ */
+static inline void mbedtls_ssl_set_user_data_n(
+ mbedtls_ssl_context *ssl,
+ uintptr_t n)
+{
+ ssl->MBEDTLS_PRIVATE(user_data).n = n;
+}
+
+/** \brief Retrieve the user data in an SSL context as a pointer.
+ *
+ * This is the value last set with mbedtls_ssl_set_user_data_p(), or
+ * \c NULL if mbedtls_ssl_set_user_data_p() has not previously been
+ * called. The value is undefined if mbedtls_ssl_set_user_data_n() has
+ * been called without a subsequent call to mbedtls_ssl_set_user_data_p().
+ *
+ * \param ssl The SSL context to modify.
+ * \return The current value of the user data.
+ */
+static inline void *mbedtls_ssl_get_user_data_p(
+ mbedtls_ssl_context *ssl)
+{
+ return ssl->MBEDTLS_PRIVATE(user_data).p;
+}
+
+/** \brief Retrieve the user data in an SSL context as an integer.
+ *
+ * This is the value last set with mbedtls_ssl_set_user_data_n(), or
+ * \c 0 if mbedtls_ssl_set_user_data_n() has not previously been
+ * called. The value is undefined if mbedtls_ssl_set_user_data_p() has
+ * been called without a subsequent call to mbedtls_ssl_set_user_data_n().
+ *
+ * \param ssl The SSL context to modify.
+ * \return The current value of the user data.
+ */
+static inline uintptr_t mbedtls_ssl_get_user_data_n(
+ mbedtls_ssl_context *ssl)
+{
+ return ssl->MBEDTLS_PRIVATE(user_data).n;
+}
+
+#if defined(MBEDTLS_SSL_ASYNC_PRIVATE)
+/**
+ * \brief Configure asynchronous private key operation callbacks.
+ *
+ * \param conf SSL configuration context
+ * \param f_async_sign Callback to start a signature operation. See
+ * the description of ::mbedtls_ssl_async_sign_t
+ * for more information. This may be \c NULL if the
+ * external processor does not support any signature
+ * operation; in this case the private key object
+ * associated with the certificate will be used.
+ * \param f_async_decrypt Callback to start a decryption operation. See
+ * the description of ::mbedtls_ssl_async_decrypt_t
+ * for more information. This may be \c NULL if the
+ * external processor does not support any decryption
+ * operation; in this case the private key object
+ * associated with the certificate will be used.
+ * \param f_async_resume Callback to resume an asynchronous operation. See
+ * the description of ::mbedtls_ssl_async_resume_t
+ * for more information. This may not be \c NULL unless
+ * \p f_async_sign and \p f_async_decrypt are both
+ * \c NULL.
+ * \param f_async_cancel Callback to cancel an asynchronous operation. See
+ * the description of ::mbedtls_ssl_async_cancel_t
+ * for more information. This may be \c NULL if
+ * no cleanup is needed.
+ * \param config_data A pointer to configuration data which can be
+ * retrieved with
+ * mbedtls_ssl_conf_get_async_config_data(). The
+ * library stores this value without dereferencing it.
+ */
+void mbedtls_ssl_conf_async_private_cb(mbedtls_ssl_config *conf,
+ mbedtls_ssl_async_sign_t *f_async_sign,
+ mbedtls_ssl_async_decrypt_t *f_async_decrypt,
+ mbedtls_ssl_async_resume_t *f_async_resume,
+ mbedtls_ssl_async_cancel_t *f_async_cancel,
+ void *config_data);
+
+/**
+ * \brief Retrieve the configuration data set by
+ * mbedtls_ssl_conf_async_private_cb().
+ *
+ * \param conf SSL configuration context
+ * \return The configuration data set by
+ * mbedtls_ssl_conf_async_private_cb().
+ */
+void *mbedtls_ssl_conf_get_async_config_data(const mbedtls_ssl_config *conf);
+
+/**
+ * \brief Retrieve the asynchronous operation user context.
+ *
+ * \note This function may only be called while a handshake
+ * is in progress.
+ *
+ * \param ssl The SSL context to access.
+ *
+ * \return The asynchronous operation user context that was last
+ * set during the current handshake. If
+ * mbedtls_ssl_set_async_operation_data() has not yet been
+ * called during the current handshake, this function returns
+ * \c NULL.
+ */
+void *mbedtls_ssl_get_async_operation_data(const mbedtls_ssl_context *ssl);
+
+/**
+ * \brief Retrieve the asynchronous operation user context.
+ *
+ * \note This function may only be called while a handshake
+ * is in progress.
+ *
+ * \param ssl The SSL context to access.
+ * \param ctx The new value of the asynchronous operation user context.
+ * Call mbedtls_ssl_get_async_operation_data() later during the
+ * same handshake to retrieve this value.
+ */
+void mbedtls_ssl_set_async_operation_data(mbedtls_ssl_context *ssl,
+ void *ctx);
+#endif /* MBEDTLS_SSL_ASYNC_PRIVATE */
+
+/**
+ * \brief Callback type: generate a cookie
+ *
+ * \param ctx Context for the callback
+ * \param p Buffer to write to,
+ * must be updated to point right after the cookie
+ * \param end Pointer to one past the end of the output buffer
+ * \param info Client ID info that was passed to
+ * \c mbedtls_ssl_set_client_transport_id()
+ * \param ilen Length of info in bytes
+ *
+ * \return The callback must return 0 on success,
+ * or a negative error code.
+ */
+typedef int mbedtls_ssl_cookie_write_t(void *ctx,
+ unsigned char **p, unsigned char *end,
+ const unsigned char *info, size_t ilen);
+
+/**
+ * \brief Callback type: verify a cookie
+ *
+ * \param ctx Context for the callback
+ * \param cookie Cookie to verify
+ * \param clen Length of cookie
+ * \param info Client ID info that was passed to
+ * \c mbedtls_ssl_set_client_transport_id()
+ * \param ilen Length of info in bytes
+ *
+ * \return The callback must return 0 if cookie is valid,
+ * or a negative error code.
+ */
+typedef int mbedtls_ssl_cookie_check_t(void *ctx,
+ const unsigned char *cookie, size_t clen,
+ const unsigned char *info, size_t ilen);
+
+#if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) && defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Register callbacks for DTLS cookies
+ * (Server only. DTLS only.)
+ *
+ * Default: dummy callbacks that fail, in order to force you to
+ * register working callbacks (and initialize their context).
+ *
+ * To disable HelloVerifyRequest, register NULL callbacks.
+ *
+ * \warning Disabling hello verification allows your server to be used
+ * for amplification in DoS attacks against other hosts.
+ * Only disable if you known this can't happen in your
+ * particular environment.
+ *
+ * \note See comments on \c mbedtls_ssl_handshake() about handling
+ * the MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED that is expected
+ * on the first handshake attempt when this is enabled.
+ *
+ * \note This is also necessary to handle client reconnection from
+ * the same port as described in RFC 6347 section 4.2.8 (only
+ * the variant with cookies is supported currently). See
+ * comments on \c mbedtls_ssl_read() for details.
+ *
+ * \param conf SSL configuration
+ * \param f_cookie_write Cookie write callback
+ * \param f_cookie_check Cookie check callback
+ * \param p_cookie Context for both callbacks
+ */
+void mbedtls_ssl_conf_dtls_cookies(mbedtls_ssl_config *conf,
+ mbedtls_ssl_cookie_write_t *f_cookie_write,
+ mbedtls_ssl_cookie_check_t *f_cookie_check,
+ void *p_cookie);
+
+/**
+ * \brief Set client's transport-level identification info.
+ * (Server only. DTLS only.)
+ *
+ * This is usually the IP address (and port), but could be
+ * anything identify the client depending on the underlying
+ * network stack. Used for HelloVerifyRequest with DTLS.
+ * This is *not* used to route the actual packets.
+ *
+ * \param ssl SSL context
+ * \param info Transport-level info identifying the client (eg IP + port)
+ * \param ilen Length of info in bytes
+ *
+ * \note An internal copy is made, so the info buffer can be reused.
+ *
+ * \return 0 on success,
+ * MBEDTLS_ERR_SSL_BAD_INPUT_DATA if used on client,
+ * MBEDTLS_ERR_SSL_ALLOC_FAILED if out of memory.
+ */
+int mbedtls_ssl_set_client_transport_id(mbedtls_ssl_context *ssl,
+ const unsigned char *info,
+ size_t ilen);
+
+#endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY && MBEDTLS_SSL_SRV_C */
+
+#if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY)
+/**
+ * \brief Enable or disable anti-replay protection for DTLS.
+ * (DTLS only, no effect on TLS.)
+ * Default: enabled.
+ *
+ * \param conf SSL configuration
+ * \param mode MBEDTLS_SSL_ANTI_REPLAY_ENABLED or MBEDTLS_SSL_ANTI_REPLAY_DISABLED.
+ *
+ * \warning Disabling this is a security risk unless the application
+ * protocol handles duplicated packets in a safe way. You
+ * should not disable this without careful consideration.
+ * However, if your application already detects duplicated
+ * packets and needs information about them to adjust its
+ * transmission strategy, then you'll want to disable this.
+ */
+void mbedtls_ssl_conf_dtls_anti_replay(mbedtls_ssl_config *conf, char mode);
+#endif /* MBEDTLS_SSL_DTLS_ANTI_REPLAY */
+
+/**
+ * \brief Set a limit on the number of records with a bad MAC
+ * before terminating the connection.
+ * (DTLS only, no effect on TLS.)
+ * Default: 0 (disabled).
+ *
+ * \param conf SSL configuration
+ * \param limit Limit, or 0 to disable.
+ *
+ * \note If the limit is N, then the connection is terminated when
+ * the Nth non-authentic record is seen.
+ *
+ * \note Records with an invalid header are not counted, only the
+ * ones going through the authentication-decryption phase.
+ *
+ * \note This is a security trade-off related to the fact that it's
+ * often relatively easy for an active attacker to inject UDP
+ * datagrams. On one hand, setting a low limit here makes it
+ * easier for such an attacker to forcibly terminated a
+ * connection. On the other hand, a high limit or no limit
+ * might make us waste resources checking authentication on
+ * many bogus packets.
+ */
+void mbedtls_ssl_conf_dtls_badmac_limit(mbedtls_ssl_config *conf, unsigned limit);
+
+#if defined(MBEDTLS_SSL_PROTO_DTLS)
+
+/**
+ * \brief Allow or disallow packing of multiple handshake records
+ * within a single datagram.
+ *
+ * \param ssl The SSL context to configure.
+ * \param allow_packing This determines whether datagram packing may
+ * be used or not. A value of \c 0 means that every
+ * record will be sent in a separate datagram; a
+ * value of \c 1 means that, if space permits,
+ * multiple handshake messages (including CCS) belonging to
+ * a single flight may be packed within a single datagram.
+ *
+ * \note This is enabled by default and should only be disabled
+ * for test purposes, or if datagram packing causes
+ * interoperability issues with peers that don't support it.
+ *
+ * \note Allowing datagram packing reduces the network load since
+ * there's less overhead if multiple messages share the same
+ * datagram. Also, it increases the handshake efficiency
+ * since messages belonging to a single datagram will not
+ * be reordered in transit, and so future message buffering
+ * or flight retransmission (if no buffering is used) as
+ * means to deal with reordering are needed less frequently.
+ *
+ * \note Application records are not affected by this option and
+ * are currently always sent in separate datagrams.
+ *
+ */
+void mbedtls_ssl_set_datagram_packing(mbedtls_ssl_context *ssl,
+ unsigned allow_packing);
+
+/**
+ * \brief Set retransmit timeout values for the DTLS handshake.
+ * (DTLS only, no effect on TLS.)
+ *
+ * \param conf SSL configuration
+ * \param min Initial timeout value in milliseconds.
+ * Default: 1000 (1 second).
+ * \param max Maximum timeout value in milliseconds.
+ * Default: 60000 (60 seconds).
+ *
+ * \note Default values are from RFC 6347 section 4.2.4.1.
+ *
+ * \note The 'min' value should typically be slightly above the
+ * expected round-trip time to your peer, plus whatever time
+ * it takes for the peer to process the message. For example,
+ * if your RTT is about 600ms and you peer needs up to 1s to
+ * do the cryptographic operations in the handshake, then you
+ * should set 'min' slightly above 1600. Lower values of 'min'
+ * might cause spurious resends which waste network resources,
+ * while larger value of 'min' will increase overall latency
+ * on unreliable network links.
+ *
+ * \note The more unreliable your network connection is, the larger
+ * your max / min ratio needs to be in order to achieve
+ * reliable handshakes.
+ *
+ * \note Messages are retransmitted up to log2(ceil(max/min)) times.
+ * For example, if min = 1s and max = 5s, the retransmit plan
+ * goes: send ... 1s -> resend ... 2s -> resend ... 4s ->
+ * resend ... 5s -> give up and return a timeout error.
+ */
+void mbedtls_ssl_conf_handshake_timeout(mbedtls_ssl_config *conf, uint32_t min, uint32_t max);
+#endif /* MBEDTLS_SSL_PROTO_DTLS */
+
+#if defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Set the session cache callbacks (server-side only)
+ * If not set, no session resuming is done (except if session
+ * tickets are enabled too).
+ *
+ * The session cache has the responsibility to check for stale
+ * entries based on timeout. See RFC 5246 for recommendations.
+ *
+ * Warning: session.peer_cert is cleared by the SSL/TLS layer on
+ * connection shutdown, so do not cache the pointer! Either set
+ * it to NULL or make a full copy of the certificate.
+ *
+ * The get callback is called once during the initial handshake
+ * to enable session resuming. The get function has the
+ * following parameters: (void *parameter, mbedtls_ssl_session *session)
+ * If a valid entry is found, it should fill the master of
+ * the session object with the cached values and return 0,
+ * return 1 otherwise. Optionally peer_cert can be set as well
+ * if it is properly present in cache entry.
+ *
+ * The set callback is called once during the initial handshake
+ * to enable session resuming after the entire handshake has
+ * been finished. The set function has the following parameters:
+ * (void *parameter, const mbedtls_ssl_session *session). The function
+ * should create a cache entry for future retrieval based on
+ * the data in the session structure and should keep in mind
+ * that the mbedtls_ssl_session object presented (and all its referenced
+ * data) is cleared by the SSL/TLS layer when the connection is
+ * terminated. It is recommended to add metadata to determine if
+ * an entry is still valid in the future. Return 0 if
+ * successfully cached, return 1 otherwise.
+ *
+ * \param conf SSL configuration
+ * \param p_cache parameter (context) for both callbacks
+ * \param f_get_cache session get callback
+ * \param f_set_cache session set callback
+ */
+void mbedtls_ssl_conf_session_cache(mbedtls_ssl_config *conf,
+ void *p_cache,
+ mbedtls_ssl_cache_get_t *f_get_cache,
+ mbedtls_ssl_cache_set_t *f_set_cache);
+#endif /* MBEDTLS_SSL_SRV_C */
+
+#if defined(MBEDTLS_SSL_CLI_C)
+/**
+ * \brief Load a session for session resumption.
+ *
+ * Sessions loaded through this call will be considered
+ * for session resumption in the next handshake.
+ *
+ * \note Even if this call succeeds, it is not guaranteed that
+ * the next handshake will indeed be shortened through the
+ * use of session resumption: The server is always free
+ * to reject any attempt for resumption and fall back to
+ * a full handshake.
+ *
+ * \note This function can handle a variety of mechanisms for session
+ * resumption: For TLS 1.2, both session ID-based resumption and
+ * ticket-based resumption will be considered. For TLS 1.3,
+ * once implemented, sessions equate to tickets, and loading
+ * one or more sessions via this call will lead to their
+ * corresponding tickets being advertised as resumption PSKs
+ * by the client.
+ *
+ * \note Calling this function multiple times will only be useful
+ * once TLS 1.3 is supported. For TLS 1.2 connections, this
+ * function should be called at most once.
+ *
+ * \param ssl The SSL context representing the connection which should
+ * be attempted to be setup using session resumption. This
+ * must be initialized via mbedtls_ssl_init() and bound to
+ * an SSL configuration via mbedtls_ssl_setup(), but
+ * the handshake must not yet have been started.
+ * \param session The session to be considered for session resumption.
+ * This must be a session previously exported via
+ * mbedtls_ssl_get_session(), and potentially serialized and
+ * deserialized through mbedtls_ssl_session_save() and
+ * mbedtls_ssl_session_load() in the meantime.
+ *
+ * \return \c 0 if successful.
+ * \return \c MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE if the session
+ * could not be loaded because of an implementation limitation.
+ * This error is non-fatal, and has no observable effect on
+ * the SSL context or the session that was attempted to be loaded.
+ * \return Another negative error code on other kinds of failure.
+ *
+ * \sa mbedtls_ssl_get_session()
+ * \sa mbedtls_ssl_session_load()
+ */
+int mbedtls_ssl_set_session(mbedtls_ssl_context *ssl, const mbedtls_ssl_session *session);
+#endif /* MBEDTLS_SSL_CLI_C */
+
+/**
+ * \brief Load serialized session data into a session structure.
+ * On client, this can be used for loading saved sessions
+ * before resuming them with mbedtls_ssl_set_session().
+ * On server, this can be used for alternative implementations
+ * of session cache or session tickets.
+ *
+ * \warning If a peer certificate chain is associated with the session,
+ * the serialized state will only contain the peer's
+ * end-entity certificate and the result of the chain
+ * verification (unless verification was disabled), but not
+ * the rest of the chain.
+ *
+ * \see mbedtls_ssl_session_save()
+ * \see mbedtls_ssl_set_session()
+ *
+ * \param session The session structure to be populated. It must have been
+ * initialised with mbedtls_ssl_session_init() but not
+ * populated yet.
+ * \param buf The buffer holding the serialized session data. It must be a
+ * readable buffer of at least \p len bytes.
+ * \param len The size of the serialized data in bytes.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed.
+ * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA if input data is invalid.
+ * \return #MBEDTLS_ERR_SSL_VERSION_MISMATCH if the serialized data
+ * was generated in a different version or configuration of
+ * Mbed TLS.
+ * \return Another negative value for other kinds of errors (for
+ * example, unsupported features in the embedded certificate).
+ */
+int mbedtls_ssl_session_load(mbedtls_ssl_session *session,
+ const unsigned char *buf,
+ size_t len);
+
+/**
+ * \brief Save session structure as serialized data in a buffer.
+ * On client, this can be used for saving session data,
+ * potentially in non-volatile storage, for resuming later.
+ * On server, this can be used for alternative implementations
+ * of session cache or session tickets.
+ *
+ * \see mbedtls_ssl_session_load()
+ *
+ * \param session The session structure to be saved.
+ * \param buf The buffer to write the serialized data to. It must be a
+ * writeable buffer of at least \p buf_len bytes, or may be \c
+ * NULL if \p buf_len is \c 0.
+ * \param buf_len The number of bytes available for writing in \p buf.
+ * \param olen The size in bytes of the data that has been or would have
+ * been written. It must point to a valid \c size_t.
+ *
+ * \note \p olen is updated to the correct value regardless of
+ * whether \p buf_len was large enough. This makes it possible
+ * to determine the necessary size by calling this function
+ * with \p buf set to \c NULL and \p buf_len to \c 0.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL if \p buf is too small.
+ */
+int mbedtls_ssl_session_save(const mbedtls_ssl_session *session,
+ unsigned char *buf,
+ size_t buf_len,
+ size_t *olen);
+
+/**
+ * \brief Set the list of allowed ciphersuites and the preference
+ * order. First in the list has the highest preference.
+ *
+ * For TLS 1.2, the notion of ciphersuite determines both
+ * the key exchange mechanism and the suite of symmetric
+ * algorithms to be used during and after the handshake.
+ *
+ * For TLS 1.3 (in development), the notion of ciphersuite
+ * only determines the suite of symmetric algorithms to be
+ * used during and after the handshake, while key exchange
+ * mechanisms are configured separately.
+ *
+ * In Mbed TLS, ciphersuites for both TLS 1.2 and TLS 1.3
+ * are configured via this function. For users of TLS 1.3,
+ * there will be separate API for the configuration of key
+ * exchange mechanisms.
+ *
+ * The list of ciphersuites passed to this function may
+ * contain a mixture of TLS 1.2 and TLS 1.3 ciphersuite
+ * identifiers. This is useful if negotiation of TLS 1.3
+ * should be attempted, but a fallback to TLS 1.2 would
+ * be tolerated.
+ *
+ * \note By default, the server chooses its preferred
+ * ciphersuite among those that the client supports. If
+ * mbedtls_ssl_conf_preference_order() is called to prefer
+ * the client's preferences, the server instead chooses
+ * the client's preferred ciphersuite among those that
+ * the server supports.
+ *
+ * \warning The ciphersuites array \p ciphersuites is not copied.
+ * It must remain valid for the lifetime of the SSL
+ * configuration \p conf.
+ *
+ * \param conf The SSL configuration to modify.
+ * \param ciphersuites A 0-terminated list of IANA identifiers of supported
+ * ciphersuites, accessible through \c MBEDTLS_TLS_XXX
+ * and \c MBEDTLS_TLS1_3_XXX macros defined in
+ * ssl_ciphersuites.h.
+ */
+void mbedtls_ssl_conf_ciphersuites(mbedtls_ssl_config *conf,
+ const int *ciphersuites);
+
+#if defined(MBEDTLS_SSL_PROTO_TLS1_3)
+/**
+ * \brief Set the supported key exchange modes for TLS 1.3 connections.
+ *
+ * In contrast to TLS 1.2, the ciphersuite concept in TLS 1.3 does not
+ * include the choice of key exchange mechanism. It is therefore not
+ * covered by the API mbedtls_ssl_conf_ciphersuites(). See the
+ * documentation of mbedtls_ssl_conf_ciphersuites() for more
+ * information on the ciphersuite concept in TLS 1.2 and TLS 1.3.
+ *
+ * The present function is specific to TLS 1.3 and allows users to
+ * configure the set of supported key exchange mechanisms in TLS 1.3.
+ *
+ * \param conf The SSL configuration the change should apply to.
+ * \param kex_modes A bitwise combination of one or more of the following:
+ * - MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK
+ * This flag enables pure-PSK key exchanges.
+ * - MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL
+ * This flag enables combined PSK-ephemeral key exchanges.
+ * - MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL
+ * This flag enables pure-ephemeral key exchanges.
+ * For convenience, the following pre-defined macros are
+ * available for combinations of the above:
+ * - MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_ALL
+ * Includes all of pure-PSK, PSK-ephemeral and pure-ephemeral.
+ * - MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ALL
+ * Includes both pure-PSK and combined PSK-ephemeral
+ * key exchanges, but excludes pure-ephemeral key exchanges.
+ * - MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ALL
+ * Includes both pure-ephemeral and combined PSK-ephemeral
+ * key exchanges.
+ *
+ * \note If a PSK-based key exchange mode shall be supported, applications
+ * must also use the APIs mbedtls_ssl_conf_psk() or
+ * mbedtls_ssl_conf_psk_cb() or mbedtls_ssl_conf_psk_opaque()
+ * to configure the PSKs to be used.
+ *
+ * \note If a pure-ephemeral key exchange mode shall be supported,
+ * server-side applications must also provide a certificate via
+ * mbedtls_ssl_conf_own_cert().
+ *
+ */
+
+void mbedtls_ssl_conf_tls13_key_exchange_modes(mbedtls_ssl_config *conf,
+ const int kex_modes);
+#endif /* MBEDTLS_SSL_PROTO_TLS1_3 */
+
+#if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID)
+#define MBEDTLS_SSL_UNEXPECTED_CID_IGNORE 0
+#define MBEDTLS_SSL_UNEXPECTED_CID_FAIL 1
+/**
+ * \brief Specify the length of Connection IDs for incoming
+ * encrypted DTLS records, as well as the behaviour
+ * on unexpected CIDs.
+ *
+ * By default, the CID length is set to \c 0,
+ * and unexpected CIDs are silently ignored.
+ *
+ * \param conf The SSL configuration to modify.
+ * \param len The length in Bytes of the CID fields in encrypted
+ * DTLS records using the CID mechanism. This must
+ * not be larger than #MBEDTLS_SSL_CID_OUT_LEN_MAX.
+ * \param ignore_other_cids This determines the stack's behaviour when
+ * receiving a record with an unexpected CID.
+ * Possible values are:
+ * - #MBEDTLS_SSL_UNEXPECTED_CID_IGNORE
+ * In this case, the record is silently ignored.
+ * - #MBEDTLS_SSL_UNEXPECTED_CID_FAIL
+ * In this case, the stack fails with the specific
+ * error code #MBEDTLS_ERR_SSL_UNEXPECTED_CID.
+ *
+ * \note The CID specification allows implementations to either
+ * use a common length for all incoming connection IDs or
+ * allow variable-length incoming IDs. Mbed TLS currently
+ * requires a common length for all connections sharing the
+ * same SSL configuration; this allows simpler parsing of
+ * record headers.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA if \p len
+ * is too large.
+ */
+int mbedtls_ssl_conf_cid(mbedtls_ssl_config *conf, size_t len,
+ int ignore_other_cids);
+#endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+/**
+ * \brief Set the X.509 security profile used for verification
+ *
+ * \note The restrictions are enforced for all certificates in the
+ * chain. However, signatures in the handshake are not covered
+ * by this setting but by \b mbedtls_ssl_conf_sig_hashes().
+ *
+ * \param conf SSL configuration
+ * \param profile Profile to use
+ */
+void mbedtls_ssl_conf_cert_profile(mbedtls_ssl_config *conf,
+ const mbedtls_x509_crt_profile *profile);
+
+/**
+ * \brief Set the data required to verify peer certificate
+ *
+ * \note See \c mbedtls_x509_crt_verify() for notes regarding the
+ * parameters ca_chain (maps to trust_ca for that function)
+ * and ca_crl.
+ *
+ * \param conf SSL configuration
+ * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs)
+ * \param ca_crl trusted CA CRLs
+ */
+void mbedtls_ssl_conf_ca_chain(mbedtls_ssl_config *conf,
+ mbedtls_x509_crt *ca_chain,
+ mbedtls_x509_crl *ca_crl);
+
+#if defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
+/**
+ * \brief Set DN hints sent to client in CertificateRequest message
+ *
+ * \note If not set, subject distinguished names (DNs) are taken
+ * from \c mbedtls_ssl_conf_ca_chain()
+ * or \c mbedtls_ssl_set_hs_ca_chain())
+ *
+ * \param conf SSL configuration
+ * \param crt crt chain whose subject DNs are issuer DNs of client certs
+ * from which the client should select client peer certificate.
+ */
+static inline
+void mbedtls_ssl_conf_dn_hints(mbedtls_ssl_config *conf,
+ const mbedtls_x509_crt *crt)
+{
+ conf->MBEDTLS_PRIVATE(dn_hints) = crt;
+}
+#endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
+
+#if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
+/**
+ * \brief Set the trusted certificate callback.
+ *
+ * This API allows to register the set of trusted certificates
+ * through a callback, instead of a linked list as configured
+ * by mbedtls_ssl_conf_ca_chain().
+ *
+ * This is useful for example in contexts where a large number
+ * of CAs are used, and the inefficiency of maintaining them
+ * in a linked list cannot be tolerated. It is also useful when
+ * the set of trusted CAs needs to be modified frequently.
+ *
+ * See the documentation of `mbedtls_x509_crt_ca_cb_t` for
+ * more information.
+ *
+ * \param conf The SSL configuration to register the callback with.
+ * \param f_ca_cb The trusted certificate callback to use when verifying
+ * certificate chains.
+ * \param p_ca_cb The context to be passed to \p f_ca_cb (for example,
+ * a reference to a trusted CA database).
+ *
+ * \note This API is incompatible with mbedtls_ssl_conf_ca_chain():
+ * Any call to this function overwrites the values set through
+ * earlier calls to mbedtls_ssl_conf_ca_chain() or
+ * mbedtls_ssl_conf_ca_cb().
+ *
+ * \note This API is incompatible with CA indication in
+ * CertificateRequest messages: A server-side SSL context which
+ * is bound to an SSL configuration that uses a CA callback
+ * configured via mbedtls_ssl_conf_ca_cb(), and which requires
+ * client authentication, will send an empty CA list in the
+ * corresponding CertificateRequest message.
+ *
+ * \note This API is incompatible with mbedtls_ssl_set_hs_ca_chain():
+ * If an SSL context is bound to an SSL configuration which uses
+ * CA callbacks configured via mbedtls_ssl_conf_ca_cb(), then
+ * calls to mbedtls_ssl_set_hs_ca_chain() have no effect.
+ *
+ * \note The use of this API disables the use of restartable ECC
+ * during X.509 CRT signature verification (but doesn't affect
+ * other uses).
+ *
+ * \warning This API is incompatible with the use of CRLs. Any call to
+ * mbedtls_ssl_conf_ca_cb() unsets CRLs configured through
+ * earlier calls to mbedtls_ssl_conf_ca_chain().
+ *
+ * \warning In multi-threaded environments, the callback \p f_ca_cb
+ * must be thread-safe, and it is the user's responsibility
+ * to guarantee this (for example through a mutex
+ * contained in the callback context pointed to by \p p_ca_cb).
+ */
+void mbedtls_ssl_conf_ca_cb(mbedtls_ssl_config *conf,
+ mbedtls_x509_crt_ca_cb_t f_ca_cb,
+ void *p_ca_cb);
+#endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
+
+/**
+ * \brief Set own certificate chain and private key
+ *
+ * \note own_cert should contain in order from the bottom up your
+ * certificate chain. The top certificate (self-signed)
+ * can be omitted.
+ *
+ * \note On server, this function can be called multiple times to
+ * provision more than one cert/key pair (eg one ECDSA, one
+ * RSA with SHA-256, one RSA with SHA-1). An adequate
+ * certificate will be selected according to the client's
+ * advertised capabilities. In case multiple certificates are
+ * adequate, preference is given to the one set by the first
+ * call to this function, then second, etc.
+ *
+ * \note On client, only the first call has any effect. That is,
+ * only one client certificate can be provisioned. The
+ * server's preferences in its CertificateRequest message will
+ * be ignored and our only cert will be sent regardless of
+ * whether it matches those preferences - the server can then
+ * decide what it wants to do with it.
+ *
+ * \note The provided \p pk_key needs to match the public key in the
+ * first certificate in \p own_cert, or all handshakes using
+ * that certificate will fail. It is your responsibility
+ * to ensure that; this function will not perform any check.
+ * You may use mbedtls_pk_check_pair() in order to perform
+ * this check yourself, but be aware that this function can
+ * be computationally expensive on some key types.
+ *
+ * \param conf SSL configuration
+ * \param own_cert own public certificate chain
+ * \param pk_key own private key
+ *
+ * \return 0 on success or MBEDTLS_ERR_SSL_ALLOC_FAILED
+ */
+int mbedtls_ssl_conf_own_cert(mbedtls_ssl_config *conf,
+ mbedtls_x509_crt *own_cert,
+ mbedtls_pk_context *pk_key);
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED)
+/**
+ * \brief Configure pre-shared keys (PSKs) and their
+ * identities to be used in PSK-based ciphersuites.
+ *
+ * Only one PSK can be registered, through either
+ * mbedtls_ssl_conf_psk() or mbedtls_ssl_conf_psk_opaque().
+ * If you attempt to register more than one PSK, this function
+ * fails, though this may change in future versions, which
+ * may add support for multiple PSKs.
+ *
+ * \note This is mainly useful for clients. Servers will usually
+ * want to use \c mbedtls_ssl_conf_psk_cb() instead.
+ *
+ * \note A PSK set by \c mbedtls_ssl_set_hs_psk() in the PSK callback
+ * takes precedence over a PSK configured by this function.
+ *
+ * \param conf The SSL configuration to register the PSK with.
+ * \param psk The pointer to the pre-shared key to use.
+ * \param psk_len The length of the pre-shared key in bytes.
+ * \param psk_identity The pointer to the pre-shared key identity.
+ * \param psk_identity_len The length of the pre-shared key identity
+ * in bytes.
+ *
+ * \note The PSK and its identity are copied internally and
+ * hence need not be preserved by the caller for the lifetime
+ * of the SSL configuration.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE if no more PSKs
+ * can be configured. In this case, the old PSK(s) remain intact.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ssl_conf_psk(mbedtls_ssl_config *conf,
+ const unsigned char *psk, size_t psk_len,
+ const unsigned char *psk_identity, size_t psk_identity_len);
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+/**
+ * \brief Configure one or more opaque pre-shared keys (PSKs) and
+ * their identities to be used in PSK-based ciphersuites.
+ *
+ * Only one PSK can be registered, through either
+ * mbedtls_ssl_conf_psk() or mbedtls_ssl_conf_psk_opaque().
+ * If you attempt to register more than one PSK, this function
+ * fails, though this may change in future versions, which
+ * may add support for multiple PSKs.
+ *
+ * \note This is mainly useful for clients. Servers will usually
+ * want to use \c mbedtls_ssl_conf_psk_cb() instead.
+ *
+ * \note An opaque PSK set by \c mbedtls_ssl_set_hs_psk_opaque() in
+ * the PSK callback takes precedence over an opaque PSK
+ * configured by this function.
+ *
+ * \param conf The SSL configuration to register the PSK with.
+ * \param psk The identifier of the key slot holding the PSK.
+ * Until \p conf is destroyed or this function is successfully
+ * called again, the key slot \p psk must be populated with a
+ * key of type PSA_ALG_CATEGORY_KEY_DERIVATION whose policy
+ * allows its use for the key derivation algorithm applied
+ * in the handshake.
+ * \param psk_identity The pointer to the pre-shared key identity.
+ * \param psk_identity_len The length of the pre-shared key identity
+ * in bytes.
+ *
+ * \note The PSK identity hint is copied internally and hence need
+ * not be preserved by the caller for the lifetime of the
+ * SSL configuration.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE if no more PSKs
+ * can be configured. In this case, the old PSK(s) remain intact.
+ * \return Another negative error code on other kinds of failure.
+ */
+int mbedtls_ssl_conf_psk_opaque(mbedtls_ssl_config *conf,
+ mbedtls_svc_key_id_t psk,
+ const unsigned char *psk_identity,
+ size_t psk_identity_len);
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
+/**
+ * \brief Set the pre-shared Key (PSK) for the current handshake.
+ *
+ * \note This should only be called inside the PSK callback,
+ * i.e. the function passed to \c mbedtls_ssl_conf_psk_cb().
+ *
+ * \note A PSK set by this function takes precedence over a PSK
+ * configured by \c mbedtls_ssl_conf_psk().
+ *
+ * \param ssl The SSL context to configure a PSK for.
+ * \param psk The pointer to the pre-shared key.
+ * \param psk_len The length of the pre-shared key in bytes.
+ *
+ * \return \c 0 if successful.
+ * \return An \c MBEDTLS_ERR_SSL_XXX error code on failure.
+ */
+int mbedtls_ssl_set_hs_psk(mbedtls_ssl_context *ssl,
+ const unsigned char *psk, size_t psk_len);
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+/**
+ * \brief Set an opaque pre-shared Key (PSK) for the current handshake.
+ *
+ * \note This should only be called inside the PSK callback,
+ * i.e. the function passed to \c mbedtls_ssl_conf_psk_cb().
+ *
+ * \note An opaque PSK set by this function takes precedence over an
+ * opaque PSK configured by \c mbedtls_ssl_conf_psk_opaque().
+ *
+ * \param ssl The SSL context to configure a PSK for.
+ * \param psk The identifier of the key slot holding the PSK.
+ * For the duration of the current handshake, the key slot
+ * must be populated with a key of type
+ * PSA_ALG_CATEGORY_KEY_DERIVATION whose policy allows its
+ * use for the key derivation algorithm
+ * applied in the handshake.
+ *
+ * \return \c 0 if successful.
+ * \return An \c MBEDTLS_ERR_SSL_XXX error code on failure.
+ */
+int mbedtls_ssl_set_hs_psk_opaque(mbedtls_ssl_context *ssl,
+ mbedtls_svc_key_id_t psk);
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+
+#if defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Set the PSK callback (server-side only).
+ *
+ * If set, the PSK callback is called for each
+ * handshake where a PSK-based ciphersuite was negotiated.
+ * The caller provides the identity received and wants to
+ * receive the actual PSK data and length.
+ *
+ * The callback has the following parameters:
+ * - \c void*: The opaque pointer \p p_psk.
+ * - \c mbedtls_ssl_context*: The SSL context to which
+ * the operation applies.
+ * - \c const unsigned char*: The PSK identity
+ * selected by the client.
+ * - \c size_t: The length of the PSK identity
+ * selected by the client.
+ *
+ * If a valid PSK identity is found, the callback should use
+ * \c mbedtls_ssl_set_hs_psk() or
+ * \c mbedtls_ssl_set_hs_psk_opaque()
+ * on the SSL context to set the correct PSK and return \c 0.
+ * Any other return value will result in a denied PSK identity.
+ *
+ * \note A dynamic PSK (i.e. set by the PSK callback) takes
+ * precedence over a static PSK (i.e. set by
+ * \c mbedtls_ssl_conf_psk() or
+ * \c mbedtls_ssl_conf_psk_opaque()).
+ * This means that if you set a PSK callback using this
+ * function, you don't need to set a PSK using
+ * \c mbedtls_ssl_conf_psk() or
+ * \c mbedtls_ssl_conf_psk_opaque()).
+ *
+ * \param conf The SSL configuration to register the callback with.
+ * \param f_psk The callback for selecting and setting the PSK based
+ * in the PSK identity chosen by the client.
+ * \param p_psk A pointer to an opaque structure to be passed to
+ * the callback, for example a PSK store.
+ */
+void mbedtls_ssl_conf_psk_cb(mbedtls_ssl_config *conf,
+ int (*f_psk)(void *, mbedtls_ssl_context *, const unsigned char *,
+ size_t),
+ void *p_psk);
+#endif /* MBEDTLS_SSL_SRV_C */
+#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED */
+
+#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Set the Diffie-Hellman public P and G values
+ * from big-endian binary presentations.
+ * (Default values: MBEDTLS_DHM_RFC3526_MODP_2048_[PG]_BIN)
+ *
+ * \param conf SSL configuration
+ * \param dhm_P Diffie-Hellman-Merkle modulus in big-endian binary form
+ * \param P_len Length of DHM modulus
+ * \param dhm_G Diffie-Hellman-Merkle generator in big-endian binary form
+ * \param G_len Length of DHM generator
+ *
+ * \return 0 if successful
+ */
+int mbedtls_ssl_conf_dh_param_bin(mbedtls_ssl_config *conf,
+ const unsigned char *dhm_P, size_t P_len,
+ const unsigned char *dhm_G, size_t G_len);
+
+/**
+ * \brief Set the Diffie-Hellman public P and G values,
+ * read from existing context (server-side only)
+ *
+ * \param conf SSL configuration
+ * \param dhm_ctx Diffie-Hellman-Merkle context
+ *
+ * \return 0 if successful
+ */
+int mbedtls_ssl_conf_dh_param_ctx(mbedtls_ssl_config *conf, mbedtls_dhm_context *dhm_ctx);
+#endif /* MBEDTLS_DHM_C && defined(MBEDTLS_SSL_SRV_C) */
+
+#if defined(MBEDTLS_DHM_C) && defined(MBEDTLS_SSL_CLI_C)
+/**
+ * \brief Set the minimum length for Diffie-Hellman parameters.
+ * (Client-side only.)
+ * (Default: 1024 bits.)
+ *
+ * \param conf SSL configuration
+ * \param bitlen Minimum bit length of the DHM prime
+ */
+void mbedtls_ssl_conf_dhm_min_bitlen(mbedtls_ssl_config *conf,
+ unsigned int bitlen);
+#endif /* MBEDTLS_DHM_C && MBEDTLS_SSL_CLI_C */
+
+#if defined(MBEDTLS_ECP_C)
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+/**
+ * \brief Set the allowed curves in order of preference.
+ *
+ * On server: this only affects selection of the ECDHE curve;
+ * the curves used for ECDH and ECDSA are determined by the
+ * list of available certificates instead.
+ *
+ * On client: this affects the list of curves offered for any
+ * use. The server can override our preference order.
+ *
+ * Both sides: limits the set of curves accepted for use in
+ * ECDHE and in the peer's end-entity certificate.
+ *
+ * \deprecated Superseded by mbedtls_ssl_conf_groups().
+ *
+ * \note This has no influence on which curves are allowed inside the
+ * certificate chains, see \c mbedtls_ssl_conf_cert_profile()
+ * for that. For the end-entity certificate however, the key
+ * will be accepted only if it is allowed both by this list
+ * and by the cert profile.
+ *
+ * \note This list should be ordered by decreasing preference
+ * (preferred curve first).
+ *
+ * \note The default list is the same set of curves that
+ * #mbedtls_x509_crt_profile_default allows, plus
+ * ECDHE-only curves selected according to the same criteria.
+ * The order favors curves with the lowest resource usage.
+ *
+ * \note New minor versions of Mbed TLS may extend this list,
+ * for example if new curves are added to the library.
+ * New minor versions of Mbed TLS will not remove items
+ * from this list unless serious security concerns require it.
+ * New minor versions of Mbed TLS may change the order in
+ * keeping with the general principle of favoring the lowest
+ * resource usage.
+ *
+ * \param conf SSL configuration
+ * \param curves Ordered list of allowed curves,
+ * terminated by MBEDTLS_ECP_DP_NONE.
+ */
+void MBEDTLS_DEPRECATED mbedtls_ssl_conf_curves(mbedtls_ssl_config *conf,
+ const mbedtls_ecp_group_id *curves);
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+#endif /* MBEDTLS_ECP_C */
+
+/**
+ * \brief Set the allowed groups in order of preference.
+ *
+ * On server: This only affects the choice of key agreement mechanism
+ *
+ * On client: this affects the list of groups offered for any
+ * use. The server can override our preference order.
+ *
+ * Both sides: limits the set of groups accepted for use in
+ * key sharing.
+ *
+ * \note This function replaces the deprecated mbedtls_ssl_conf_curves(),
+ * which only allows ECP curves to be configured.
+ *
+ * \note The most recent invocation of either mbedtls_ssl_conf_curves()
+ * or mbedtls_ssl_conf_groups() nullifies all previous invocations
+ * of both.
+ *
+ * \note This list should be ordered by decreasing preference
+ * (preferred group first).
+ *
+ * \note When this function is not called, a default list is used,
+ * consisting of all supported curves at 255 bits and above,
+ * and all supported finite fields at 2048 bits and above.
+ * The order favors groups with the lowest resource usage.
+ *
+ * \note New minor versions of Mbed TLS will not remove items
+ * from the default list unless serious security concerns require it.
+ * New minor versions of Mbed TLS may change the order in
+ * keeping with the general principle of favoring the lowest
+ * resource usage.
+ *
+ * \param conf SSL configuration
+ * \param groups List of allowed groups ordered by preference, terminated by 0.
+ * Must contain valid IANA NamedGroup IDs (provided via either an integer
+ * or using MBEDTLS_TLS1_3_NAMED_GROUP_XXX macros).
+ */
+void mbedtls_ssl_conf_groups(mbedtls_ssl_config *conf,
+ const uint16_t *groups);
+
+#if defined(MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED)
+#if !defined(MBEDTLS_DEPRECATED_REMOVED) && defined(MBEDTLS_SSL_PROTO_TLS1_2)
+/**
+ * \brief Set the allowed hashes for signatures during the handshake.
+ *
+ * \note This only affects which hashes are offered and can be used
+ * for signatures during the handshake. Hashes for message
+ * authentication and the TLS PRF are controlled by the
+ * ciphersuite, see \c mbedtls_ssl_conf_ciphersuites(). Hashes
+ * used for certificate signature are controlled by the
+ * verification profile, see \c mbedtls_ssl_conf_cert_profile().
+ *
+ * \note This list should be ordered by decreasing preference
+ * (preferred hash first).
+ *
+ * \note By default, all supported hashes whose length is at least
+ * 256 bits are allowed. This is the same set as the default
+ * for certificate verification
+ * (#mbedtls_x509_crt_profile_default).
+ * The preference order is currently unspecified and may
+ * change in future versions.
+ *
+ * \note New minor versions of Mbed TLS may extend this list,
+ * for example if new curves are added to the library.
+ * New minor versions of Mbed TLS will not remove items
+ * from this list unless serious security concerns require it.
+ *
+ * \param conf SSL configuration
+ * \param hashes Ordered list of allowed signature hashes,
+ * terminated by \c MBEDTLS_MD_NONE.
+ */
+void MBEDTLS_DEPRECATED mbedtls_ssl_conf_sig_hashes(mbedtls_ssl_config *conf,
+ const int *hashes);
+#endif /* !MBEDTLS_DEPRECATED_REMOVED && MBEDTLS_SSL_PROTO_TLS1_2 */
+
+/**
+ * \brief Configure allowed signature algorithms for use in TLS 1.3
+ *
+ * \param conf The SSL configuration to use.
+ * \param sig_algs List of allowed IANA values for TLS 1.3 signature algorithms,
+ * terminated by \c MBEDTLS_TLS1_3_SIG_NONE. The list must remain
+ * available throughout the lifetime of the conf object. Supported
+ * values are available as \c MBEDTLS_TLS1_3_SIG_XXXX
+ */
+void mbedtls_ssl_conf_sig_algs(mbedtls_ssl_config *conf,
+ const uint16_t *sig_algs);
+#endif /* MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED */
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+/**
+ * \brief Set or reset the hostname to check against the received
+ * server certificate. It sets the ServerName TLS extension,
+ * too, if that extension is enabled. (client-side only)
+ *
+ * \param ssl SSL context
+ * \param hostname the server hostname, may be NULL to clear hostname
+
+ * \note Maximum hostname length MBEDTLS_SSL_MAX_HOST_NAME_LEN.
+ *
+ * \return 0 if successful, MBEDTLS_ERR_SSL_ALLOC_FAILED on
+ * allocation failure, MBEDTLS_ERR_SSL_BAD_INPUT_DATA on
+ * too long input hostname.
+ *
+ * Hostname set to the one provided on success (cleared
+ * when NULL). On allocation failure hostname is cleared.
+ * On too long input failure, old hostname is unchanged.
+ */
+int mbedtls_ssl_set_hostname(mbedtls_ssl_context *ssl, const char *hostname);
+
+/**
+ * \brief Get the hostname that checked against the received
+ * server certificate. It is used to set the ServerName
+ * TLS extension, too, if that extension is enabled.
+ * (client-side only)
+ *
+ * \param ssl SSL context
+ *
+ * \return const pointer to the hostname value
+ */
+static inline const char *mbedtls_ssl_get_hostname(mbedtls_ssl_context *ssl)
+{
+ return ssl->MBEDTLS_PRIVATE(hostname);
+}
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+#if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION)
+/**
+ * \brief Retrieve SNI extension value for the current handshake.
+ * Available in \c f_cert_cb of \c mbedtls_ssl_conf_cert_cb(),
+ * this is the same value passed to \c f_sni callback of
+ * \c mbedtls_ssl_conf_sni() and may be used instead of
+ * \c mbedtls_ssl_conf_sni().
+ *
+ * \param ssl SSL context
+ * \param name_len pointer into which to store length of returned value.
+ * 0 if SNI extension is not present or not yet processed.
+ *
+ * \return const pointer to SNI extension value.
+ * - value is valid only when called in \c f_cert_cb
+ * registered with \c mbedtls_ssl_conf_cert_cb().
+ * - value is NULL if SNI extension is not present.
+ * - value is not '\0'-terminated. Use \c name_len for len.
+ * - value must not be freed.
+ */
+const unsigned char *mbedtls_ssl_get_hs_sni(mbedtls_ssl_context *ssl,
+ size_t *name_len);
+
+/**
+ * \brief Set own certificate and key for the current handshake
+ *
+ * \note Same as \c mbedtls_ssl_conf_own_cert() but for use within
+ * the SNI callback or the certificate selection callback.
+ *
+ * \note Passing null \c own_cert clears the certificate list for
+ * the current handshake.
+ *
+ * \param ssl SSL context
+ * \param own_cert own public certificate chain
+ * \param pk_key own private key
+ *
+ * \return 0 on success or MBEDTLS_ERR_SSL_ALLOC_FAILED
+ */
+int mbedtls_ssl_set_hs_own_cert(mbedtls_ssl_context *ssl,
+ mbedtls_x509_crt *own_cert,
+ mbedtls_pk_context *pk_key);
+
+/**
+ * \brief Set the data required to verify peer certificate for the
+ * current handshake
+ *
+ * \note Same as \c mbedtls_ssl_conf_ca_chain() but for use within
+ * the SNI callback or the certificate selection callback.
+ *
+ * \param ssl SSL context
+ * \param ca_chain trusted CA chain (meaning all fully trusted top-level CAs)
+ * \param ca_crl trusted CA CRLs
+ */
+void mbedtls_ssl_set_hs_ca_chain(mbedtls_ssl_context *ssl,
+ mbedtls_x509_crt *ca_chain,
+ mbedtls_x509_crl *ca_crl);
+
+#if defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED)
+/**
+ * \brief Set DN hints sent to client in CertificateRequest message
+ *
+ * \note Same as \c mbedtls_ssl_conf_dn_hints() but for use within
+ * the SNI callback or the certificate selection callback.
+ *
+ * \param ssl SSL context
+ * \param crt crt chain whose subject DNs are issuer DNs of client certs
+ * from which the client should select client peer certificate.
+ */
+void mbedtls_ssl_set_hs_dn_hints(mbedtls_ssl_context *ssl,
+ const mbedtls_x509_crt *crt);
+#endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */
+
+/**
+ * \brief Set authmode for the current handshake.
+ *
+ * \note Same as \c mbedtls_ssl_conf_authmode() but for use within
+ * the SNI callback or the certificate selection callback.
+ *
+ * \param ssl SSL context
+ * \param authmode MBEDTLS_SSL_VERIFY_NONE, MBEDTLS_SSL_VERIFY_OPTIONAL or
+ * MBEDTLS_SSL_VERIFY_REQUIRED
+ */
+void mbedtls_ssl_set_hs_authmode(mbedtls_ssl_context *ssl,
+ int authmode);
+
+/**
+ * \brief Set server side ServerName TLS extension callback
+ * (optional, server-side only).
+ *
+ * If set, the ServerName callback is called whenever the
+ * server receives a ServerName TLS extension from the client
+ * during a handshake. The ServerName callback has the
+ * following parameters: (void *parameter, mbedtls_ssl_context *ssl,
+ * const unsigned char *hostname, size_t len). If a suitable
+ * certificate is found, the callback must set the
+ * certificate(s) and key(s) to use with \c
+ * mbedtls_ssl_set_hs_own_cert() (can be called repeatedly),
+ * and may optionally adjust the CA and associated CRL with \c
+ * mbedtls_ssl_set_hs_ca_chain() as well as the client
+ * authentication mode with \c mbedtls_ssl_set_hs_authmode(),
+ * then must return 0. If no matching name is found, the
+ * callback may return non-zero to abort the handshake.
+ *
+ * \param conf SSL configuration
+ * \param f_sni verification function
+ * \param p_sni verification parameter
+ */
+void mbedtls_ssl_conf_sni(mbedtls_ssl_config *conf,
+ int (*f_sni)(void *, mbedtls_ssl_context *, const unsigned char *,
+ size_t),
+ void *p_sni);
+#endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */
+
+#if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
+/**
+ * \brief Set the EC J-PAKE password for current handshake.
+ *
+ * \note An internal copy is made, and destroyed as soon as the
+ * handshake is completed, or when the SSL context is reset or
+ * freed.
+ *
+ * \note The SSL context needs to be already set up. The right place
+ * to call this function is between \c mbedtls_ssl_setup() or
+ * \c mbedtls_ssl_reset() and \c mbedtls_ssl_handshake().
+ * Password cannot be empty (see RFC 8236).
+ *
+ * \param ssl SSL context
+ * \param pw EC J-PAKE password (pre-shared secret). It cannot be empty
+ * \param pw_len length of pw in bytes
+ *
+ * \return 0 on success, or a negative error code.
+ */
+int mbedtls_ssl_set_hs_ecjpake_password(mbedtls_ssl_context *ssl,
+ const unsigned char *pw,
+ size_t pw_len);
+
+/**
+ * \brief Set the EC J-PAKE opaque password for current handshake.
+ *
+ * \note The key must remain valid until the handshake is over.
+ *
+ * \note The SSL context needs to be already set up. The right place
+ * to call this function is between \c mbedtls_ssl_setup() or
+ * \c mbedtls_ssl_reset() and \c mbedtls_ssl_handshake().
+ *
+ * \param ssl SSL context
+ * \param pwd EC J-PAKE opaque password
+ *
+ * \return 0 on success, or a negative error code.
+ */
+int mbedtls_ssl_set_hs_ecjpake_password_opaque(mbedtls_ssl_context *ssl,
+ mbedtls_svc_key_id_t pwd);
+#endif /*MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */
+
+#if defined(MBEDTLS_SSL_ALPN)
+/**
+ * \brief Set the supported Application Layer Protocols.
+ *
+ * \param conf SSL configuration
+ * \param protos Pointer to a NULL-terminated list of supported protocols,
+ * in decreasing preference order. The pointer to the list is
+ * recorded by the library for later reference as required, so
+ * the lifetime of the table must be at least as long as the
+ * lifetime of the SSL configuration structure.
+ *
+ * \return 0 on success, or MBEDTLS_ERR_SSL_BAD_INPUT_DATA.
+ */
+int mbedtls_ssl_conf_alpn_protocols(mbedtls_ssl_config *conf, const char **protos);
+
+/**
+ * \brief Get the name of the negotiated Application Layer Protocol.
+ * This function should be called after the handshake is
+ * completed.
+ *
+ * \param ssl SSL context
+ *
+ * \return Protocol name, or NULL if no protocol was negotiated.
+ */
+const char *mbedtls_ssl_get_alpn_protocol(const mbedtls_ssl_context *ssl);
+#endif /* MBEDTLS_SSL_ALPN */
+
+#if defined(MBEDTLS_SSL_DTLS_SRTP)
+#if defined(MBEDTLS_DEBUG_C)
+static inline const char *mbedtls_ssl_get_srtp_profile_as_string(mbedtls_ssl_srtp_profile profile)
+{
+ switch (profile) {
+ case MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80:
+ return "MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_80";
+ case MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32:
+ return "MBEDTLS_TLS_SRTP_AES128_CM_HMAC_SHA1_32";
+ case MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80:
+ return "MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_80";
+ case MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32:
+ return "MBEDTLS_TLS_SRTP_NULL_HMAC_SHA1_32";
+ default: break;
+ }
+ return "";
+}
+#endif /* MBEDTLS_DEBUG_C */
+/**
+ * \brief Manage support for mki(master key id) value
+ * in use_srtp extension.
+ * MKI is an optional part of SRTP used for key management
+ * and re-keying. See RFC3711 section 3.1 for details.
+ * The default value is
+ * #MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED.
+ *
+ * \param conf The SSL configuration to manage mki support.
+ * \param support_mki_value Enable or disable mki usage. Values are
+ * #MBEDTLS_SSL_DTLS_SRTP_MKI_UNSUPPORTED
+ * or #MBEDTLS_SSL_DTLS_SRTP_MKI_SUPPORTED.
+ */
+void mbedtls_ssl_conf_srtp_mki_value_supported(mbedtls_ssl_config *conf,
+ int support_mki_value);
+
+/**
+ * \brief Set the supported DTLS-SRTP protection profiles.
+ *
+ * \param conf SSL configuration
+ * \param profiles Pointer to a List of MBEDTLS_TLS_SRTP_UNSET terminated
+ * supported protection profiles
+ * in decreasing preference order.
+ * The pointer to the list is recorded by the library
+ * for later reference as required, so the lifetime
+ * of the table must be at least as long as the lifetime
+ * of the SSL configuration structure.
+ * The list must not hold more than
+ * MBEDTLS_TLS_SRTP_MAX_PROFILE_LIST_LENGTH elements
+ * (excluding the terminating MBEDTLS_TLS_SRTP_UNSET).
+ *
+ * \return 0 on success
+ * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA when the list of
+ * protection profiles is incorrect.
+ */
+int mbedtls_ssl_conf_dtls_srtp_protection_profiles
+ (mbedtls_ssl_config *conf,
+ const mbedtls_ssl_srtp_profile *profiles);
+
+/**
+ * \brief Set the mki_value for the current DTLS-SRTP session.
+ *
+ * \param ssl SSL context to use.
+ * \param mki_value The MKI value to set.
+ * \param mki_len The length of the MKI value.
+ *
+ * \note This function is relevant on client side only.
+ * The server discovers the mki value during handshake.
+ * A mki value set on server side using this function
+ * is ignored.
+ *
+ * \return 0 on success
+ * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA
+ * \return #MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE
+ */
+int mbedtls_ssl_dtls_srtp_set_mki_value(mbedtls_ssl_context *ssl,
+ unsigned char *mki_value,
+ uint16_t mki_len);
+/**
+ * \brief Get the negotiated DTLS-SRTP information:
+ * Protection profile and MKI value.
+ *
+ * \warning This function must be called after the handshake is
+ * completed. The value returned by this function must
+ * not be trusted or acted upon before the handshake completes.
+ *
+ * \param ssl The SSL context to query.
+ * \param dtls_srtp_info The negotiated DTLS-SRTP information:
+ * - Protection profile in use.
+ * A direct mapping of the iana defined value for protection
+ * profile on an uint16_t.
+ http://www.iana.org/assignments/srtp-protection/srtp-protection.xhtml
+ * #MBEDTLS_TLS_SRTP_UNSET if the use of SRTP was not negotiated
+ * or peer's Hello packet was not parsed yet.
+ * - mki size and value( if size is > 0 ).
+ */
+void mbedtls_ssl_get_dtls_srtp_negotiation_result(const mbedtls_ssl_context *ssl,
+ mbedtls_dtls_srtp_info *dtls_srtp_info);
+#endif /* MBEDTLS_SSL_DTLS_SRTP */
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+/**
+ * \brief Set the maximum supported version sent from the client side
+ * and/or accepted at the server side.
+ *
+ * See also the documentation of mbedtls_ssl_conf_min_version().
+ *
+ * \note This ignores ciphersuites from higher versions.
+ *
+ * \note This function is deprecated and has been replaced by
+ * \c mbedtls_ssl_conf_max_tls_version().
+ *
+ * \param conf SSL configuration
+ * \param major Major version number (#MBEDTLS_SSL_MAJOR_VERSION_3)
+ * \param minor Minor version number
+ * (#MBEDTLS_SSL_MINOR_VERSION_3 for (D)TLS 1.2,
+ * #MBEDTLS_SSL_MINOR_VERSION_4 for TLS 1.3)
+ */
+void MBEDTLS_DEPRECATED mbedtls_ssl_conf_max_version(mbedtls_ssl_config *conf, int major,
+ int minor);
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+/**
+ * \brief Set the maximum supported version sent from the client side
+ * and/or accepted at the server side.
+ *
+ * \note After the handshake, you can call
+ * mbedtls_ssl_get_version_number() to see what version was
+ * negotiated.
+ *
+ * \param conf SSL configuration
+ * \param tls_version TLS protocol version number (\c mbedtls_ssl_protocol_version)
+ * (#MBEDTLS_SSL_VERSION_UNKNOWN is not valid)
+ */
+static inline void mbedtls_ssl_conf_max_tls_version(mbedtls_ssl_config *conf,
+ mbedtls_ssl_protocol_version tls_version)
+{
+ conf->MBEDTLS_PRIVATE(max_tls_version) = tls_version;
+}
+
+#if !defined(MBEDTLS_DEPRECATED_REMOVED)
+/**
+ * \brief Set the minimum accepted SSL/TLS protocol version
+ *
+ * \note By default, all supported versions are accepted.
+ * Future versions of the library may disable older
+ * protocol versions by default if they become deprecated.
+ *
+ * \note The following versions are supported (if enabled at
+ * compile time):
+ * - (D)TLS 1.2: \p major = #MBEDTLS_SSL_MAJOR_VERSION_3,
+ * \p minor = #MBEDTLS_SSL_MINOR_VERSION_3
+ * - TLS 1.3: \p major = #MBEDTLS_SSL_MAJOR_VERSION_3,
+ * \p minor = #MBEDTLS_SSL_MINOR_VERSION_4
+ *
+ * Note that the numbers in the constant names are the
+ * TLS internal protocol numbers, and the minor versions
+ * differ by one from the human-readable versions!
+ *
+ * \note Input outside of the SSL_MAX_XXXXX_VERSION and
+ * SSL_MIN_XXXXX_VERSION range is ignored.
+ *
+ * \note After the handshake, you can call
+ * mbedtls_ssl_get_version_number() to see what version was
+ * negotiated.
+ *
+ * \note This function is deprecated and has been replaced by
+ * \c mbedtls_ssl_conf_min_tls_version().
+ *
+ * \param conf SSL configuration
+ * \param major Major version number (#MBEDTLS_SSL_MAJOR_VERSION_3)
+ * \param minor Minor version number
+ * (#MBEDTLS_SSL_MINOR_VERSION_3 for (D)TLS 1.2,
+ * #MBEDTLS_SSL_MINOR_VERSION_4 for TLS 1.3)
+ */
+void MBEDTLS_DEPRECATED mbedtls_ssl_conf_min_version(mbedtls_ssl_config *conf, int major,
+ int minor);
+#endif /* MBEDTLS_DEPRECATED_REMOVED */
+
+/**
+ * \brief Set the minimum supported version sent from the client side
+ * and/or accepted at the server side.
+ *
+ * \note After the handshake, you can call
+ * mbedtls_ssl_get_version_number() to see what version was
+ * negotiated.
+ *
+ * \param conf SSL configuration
+ * \param tls_version TLS protocol version number (\c mbedtls_ssl_protocol_version)
+ * (#MBEDTLS_SSL_VERSION_UNKNOWN is not valid)
+ */
+static inline void mbedtls_ssl_conf_min_tls_version(mbedtls_ssl_config *conf,
+ mbedtls_ssl_protocol_version tls_version)
+{
+ conf->MBEDTLS_PRIVATE(min_tls_version) = tls_version;
+}
+
+#if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC)
+/**
+ * \brief Enable or disable Encrypt-then-MAC
+ * (Default: MBEDTLS_SSL_ETM_ENABLED)
+ *
+ * \note This should always be enabled, it is a security
+ * improvement, and should not cause any interoperability
+ * issue (used only if the peer supports it too).
+ *
+ * \param conf SSL configuration
+ * \param etm MBEDTLS_SSL_ETM_ENABLED or MBEDTLS_SSL_ETM_DISABLED
+ */
+void mbedtls_ssl_conf_encrypt_then_mac(mbedtls_ssl_config *conf, char etm);
+#endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */
+
+#if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET)
+/**
+ * \brief Enable or disable Extended Master Secret negotiation.
+ * (Default: MBEDTLS_SSL_EXTENDED_MS_ENABLED)
+ *
+ * \note This should always be enabled, it is a security fix to the
+ * protocol, and should not cause any interoperability issue
+ * (used only if the peer supports it too).
+ *
+ * \param conf SSL configuration
+ * \param ems MBEDTLS_SSL_EXTENDED_MS_ENABLED or MBEDTLS_SSL_EXTENDED_MS_DISABLED
+ */
+void mbedtls_ssl_conf_extended_master_secret(mbedtls_ssl_config *conf, char ems);
+#endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */
+
+#if defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Whether to send a list of acceptable CAs in
+ * CertificateRequest messages.
+ * (Default: do send)
+ *
+ * \param conf SSL configuration
+ * \param cert_req_ca_list MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED or
+ * MBEDTLS_SSL_CERT_REQ_CA_LIST_DISABLED
+ */
+void mbedtls_ssl_conf_cert_req_ca_list(mbedtls_ssl_config *conf,
+ char cert_req_ca_list);
+#endif /* MBEDTLS_SSL_SRV_C */
+
+#if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH)
+/**
+ * \brief Set the maximum fragment length to emit and/or negotiate.
+ * (Typical: the smaller of #MBEDTLS_SSL_IN_CONTENT_LEN and
+ * #MBEDTLS_SSL_OUT_CONTENT_LEN, usually `2^14` bytes)
+ * (Server: set maximum fragment length to emit,
+ * usually negotiated by the client during handshake)
+ * (Client: set maximum fragment length to emit *and*
+ * negotiate with the server during handshake)
+ * (Default: #MBEDTLS_SSL_MAX_FRAG_LEN_NONE)
+ *
+ * \note On the client side, the maximum fragment length extension
+ * *will not* be used, unless the maximum fragment length has
+ * been set via this function to a value different than
+ * #MBEDTLS_SSL_MAX_FRAG_LEN_NONE.
+ *
+ * \note With TLS, this currently only affects ApplicationData (sent
+ * with \c mbedtls_ssl_read()), not handshake messages.
+ * With DTLS, this affects both ApplicationData and handshake.
+ *
+ * \note This sets the maximum length for a record's payload,
+ * excluding record overhead that will be added to it, see
+ * \c mbedtls_ssl_get_record_expansion().
+ *
+ * \note For DTLS, it is also possible to set a limit for the total
+ * size of datagrams passed to the transport layer, including
+ * record overhead, see \c mbedtls_ssl_set_mtu().
+ *
+ * \param conf SSL configuration
+ * \param mfl_code Code for maximum fragment length (allowed values:
+ * MBEDTLS_SSL_MAX_FRAG_LEN_512, MBEDTLS_SSL_MAX_FRAG_LEN_1024,
+ * MBEDTLS_SSL_MAX_FRAG_LEN_2048, MBEDTLS_SSL_MAX_FRAG_LEN_4096)
+ *
+ * \return 0 if successful or MBEDTLS_ERR_SSL_BAD_INPUT_DATA
+ */
+int mbedtls_ssl_conf_max_frag_len(mbedtls_ssl_config *conf, unsigned char mfl_code);
+#endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */
+
+#if defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Pick the ciphersuites order according to the second parameter
+ * in the SSL Server module (MBEDTLS_SSL_SRV_C).
+ * (Default, if never called: MBEDTLS_SSL_SRV_CIPHERSUITE_ORDER_SERVER)
+ *
+ * \param conf SSL configuration
+ * \param order Server or client (MBEDTLS_SSL_SRV_CIPHERSUITE_ORDER_SERVER
+ * or MBEDTLS_SSL_SRV_CIPHERSUITE_ORDER_CLIENT)
+ */
+void mbedtls_ssl_conf_preference_order(mbedtls_ssl_config *conf, int order);
+#endif /* MBEDTLS_SSL_SRV_C */
+
+#if defined(MBEDTLS_SSL_SESSION_TICKETS) && \
+ defined(MBEDTLS_SSL_CLI_C)
+/**
+ * \brief Enable / Disable session tickets (client only).
+ * (Default: MBEDTLS_SSL_SESSION_TICKETS_ENABLED.)
+ *
+ * \note On server, use \c mbedtls_ssl_conf_session_tickets_cb().
+ *
+ * \param conf SSL configuration
+ * \param use_tickets Enable or disable (MBEDTLS_SSL_SESSION_TICKETS_ENABLED or
+ * MBEDTLS_SSL_SESSION_TICKETS_DISABLED)
+ */
+void mbedtls_ssl_conf_session_tickets(mbedtls_ssl_config *conf, int use_tickets);
+#endif /* MBEDTLS_SSL_SESSION_TICKETS &&
+ MBEDTLS_SSL_CLI_C */
+
+#if defined(MBEDTLS_SSL_SESSION_TICKETS) && \
+ defined(MBEDTLS_SSL_SRV_C) && \
+ defined(MBEDTLS_SSL_PROTO_TLS1_3)
+/**
+ * \brief Number of NewSessionTicket messages for the server to send
+ * after handshake completion.
+ *
+ * \note The default value is
+ * \c MBEDTLS_SSL_TLS1_3_DEFAULT_NEW_SESSION_TICKETS.
+ *
+ * \note In case of a session resumption, this setting only partially apply.
+ * At most one ticket is sent in that case to just renew the pool of
+ * tickets of the client. The rationale is to avoid the number of
+ * tickets on the server to become rapidly out of control when the
+ * server has the same configuration for all its connection instances.
+ *
+ * \param conf SSL configuration
+ * \param num_tickets Number of NewSessionTicket.
+ *
+ */
+void mbedtls_ssl_conf_new_session_tickets(mbedtls_ssl_config *conf,
+ uint16_t num_tickets);
+#endif /* MBEDTLS_SSL_SESSION_TICKETS &&
+ MBEDTLS_SSL_SRV_C &&
+ MBEDTLS_SSL_PROTO_TLS1_3*/
+
+#if defined(MBEDTLS_SSL_RENEGOTIATION)
+/**
+ * \brief Enable / Disable renegotiation support for connection when
+ * initiated by peer
+ * (Default: MBEDTLS_SSL_RENEGOTIATION_DISABLED)
+ *
+ * \warning It is recommended to always disable renegotiation unless you
+ * know you need it and you know what you're doing. In the
+ * past, there have been several issues associated with
+ * renegotiation or a poor understanding of its properties.
+ *
+ * \note Server-side, enabling renegotiation also makes the server
+ * susceptible to a resource DoS by a malicious client.
+ *
+ * \param conf SSL configuration
+ * \param renegotiation Enable or disable (MBEDTLS_SSL_RENEGOTIATION_ENABLED or
+ * MBEDTLS_SSL_RENEGOTIATION_DISABLED)
+ */
+void mbedtls_ssl_conf_renegotiation(mbedtls_ssl_config *conf, int renegotiation);
+#endif /* MBEDTLS_SSL_RENEGOTIATION */
+
+/**
+ * \brief Prevent or allow legacy renegotiation.
+ * (Default: MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION)
+ *
+ * MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION allows connections to
+ * be established even if the peer does not support
+ * secure renegotiation, but does not allow renegotiation
+ * to take place if not secure.
+ * (Interoperable and secure option)
+ *
+ * MBEDTLS_SSL_LEGACY_ALLOW_RENEGOTIATION allows renegotiations
+ * with non-upgraded peers. Allowing legacy renegotiation
+ * makes the connection vulnerable to specific man in the
+ * middle attacks. (See RFC 5746)
+ * (Most interoperable and least secure option)
+ *
+ * MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE breaks off connections
+ * if peer does not support secure renegotiation. Results
+ * in interoperability issues with non-upgraded peers
+ * that do not support renegotiation altogether.
+ * (Most secure option, interoperability issues)
+ *
+ * \param conf SSL configuration
+ * \param allow_legacy Prevent or allow (SSL_NO_LEGACY_RENEGOTIATION,
+ * SSL_ALLOW_LEGACY_RENEGOTIATION or
+ * MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE)
+ */
+void mbedtls_ssl_conf_legacy_renegotiation(mbedtls_ssl_config *conf, int allow_legacy);
+
+#if defined(MBEDTLS_SSL_RENEGOTIATION)
+/**
+ * \brief Enforce renegotiation requests.
+ * (Default: enforced, max_records = 16)
+ *
+ * When we request a renegotiation, the peer can comply or
+ * ignore the request. This function allows us to decide
+ * whether to enforce our renegotiation requests by closing
+ * the connection if the peer doesn't comply.
+ *
+ * However, records could already be in transit from the peer
+ * when the request is emitted. In order to increase
+ * reliability, we can accept a number of records before the
+ * expected handshake records.
+ *
+ * The optimal value is highly dependent on the specific usage
+ * scenario.
+ *
+ * \note With DTLS and server-initiated renegotiation, the
+ * HelloRequest is retransmitted every time mbedtls_ssl_read() times
+ * out or receives Application Data, until:
+ * - max_records records have beens seen, if it is >= 0, or
+ * - the number of retransmits that would happen during an
+ * actual handshake has been reached.
+ * Please remember the request might be lost a few times
+ * if you consider setting max_records to a really low value.
+ *
+ * \warning On client, the grace period can only happen during
+ * mbedtls_ssl_read(), as opposed to mbedtls_ssl_write() and mbedtls_ssl_renegotiate()
+ * which always behave as if max_record was 0. The reason is,
+ * if we receive application data from the server, we need a
+ * place to write it, which only happens during mbedtls_ssl_read().
+ *
+ * \param conf SSL configuration
+ * \param max_records Use MBEDTLS_SSL_RENEGOTIATION_NOT_ENFORCED if you don't want to
+ * enforce renegotiation, or a non-negative value to enforce
+ * it but allow for a grace period of max_records records.
+ */
+void mbedtls_ssl_conf_renegotiation_enforced(mbedtls_ssl_config *conf, int max_records);
+
+/**
+ * \brief Set record counter threshold for periodic renegotiation.
+ * (Default: 2^48 - 1)
+ *
+ * Renegotiation is automatically triggered when a record
+ * counter (outgoing or incoming) crosses the defined
+ * threshold. The default value is meant to prevent the
+ * connection from being closed when the counter is about to
+ * reached its maximal value (it is not allowed to wrap).
+ *
+ * Lower values can be used to enforce policies such as "keys
+ * must be refreshed every N packets with cipher X".
+ *
+ * The renegotiation period can be disabled by setting
+ * conf->disable_renegotiation to
+ * MBEDTLS_SSL_RENEGOTIATION_DISABLED.
+ *
+ * \note When the configured transport is
+ * MBEDTLS_SSL_TRANSPORT_DATAGRAM the maximum renegotiation
+ * period is 2^48 - 1, and for MBEDTLS_SSL_TRANSPORT_STREAM,
+ * the maximum renegotiation period is 2^64 - 1.
+ *
+ * \param conf SSL configuration
+ * \param period The threshold value: a big-endian 64-bit number.
+ */
+void mbedtls_ssl_conf_renegotiation_period(mbedtls_ssl_config *conf,
+ const unsigned char period[8]);
+#endif /* MBEDTLS_SSL_RENEGOTIATION */
+
+/**
+ * \brief Check if there is data already read from the
+ * underlying transport but not yet processed.
+ *
+ * \param ssl SSL context
+ *
+ * \return 0 if nothing's pending, 1 otherwise.
+ *
+ * \note This is different in purpose and behaviour from
+ * \c mbedtls_ssl_get_bytes_avail in that it considers
+ * any kind of unprocessed data, not only unread
+ * application data. If \c mbedtls_ssl_get_bytes
+ * returns a non-zero value, this function will
+ * also signal pending data, but the converse does
+ * not hold. For example, in DTLS there might be
+ * further records waiting to be processed from
+ * the current underlying transport's datagram.
+ *
+ * \note If this function returns 1 (data pending), this
+ * does not imply that a subsequent call to
+ * \c mbedtls_ssl_read will provide any data;
+ * e.g., the unprocessed data might turn out
+ * to be an alert or a handshake message.
+ *
+ * \note This function is useful in the following situation:
+ * If the SSL/TLS module successfully returns from an
+ * operation - e.g. a handshake or an application record
+ * read - and you're awaiting incoming data next, you
+ * must not immediately idle on the underlying transport
+ * to have data ready, but you need to check the value
+ * of this function first. The reason is that the desired
+ * data might already be read but not yet processed.
+ * If, in contrast, a previous call to the SSL/TLS module
+ * returned MBEDTLS_ERR_SSL_WANT_READ, it is not necessary
+ * to call this function, as the latter error code entails
+ * that all internal data has been processed.
+ *
+ */
+int mbedtls_ssl_check_pending(const mbedtls_ssl_context *ssl);
+
+/**
+ * \brief Return the number of application data bytes
+ * remaining to be read from the current record.
+ *
+ * \param ssl SSL context
+ *
+ * \return How many bytes are available in the application
+ * data record read buffer.
+ *
+ * \note When working over a datagram transport, this is
+ * useful to detect the current datagram's boundary
+ * in case \c mbedtls_ssl_read has written the maximal
+ * amount of data fitting into the input buffer.
+ *
+ */
+size_t mbedtls_ssl_get_bytes_avail(const mbedtls_ssl_context *ssl);
+
+/**
+ * \brief Return the result of the certificate verification
+ *
+ * \param ssl The SSL context to use.
+ *
+ * \return \c 0 if the certificate verification was successful.
+ * \return \c -1u if the result is not available. This may happen
+ * e.g. if the handshake aborts early, or a verification
+ * callback returned a fatal error.
+ * \return A bitwise combination of \c MBEDTLS_X509_BADCERT_XXX
+ * and \c MBEDTLS_X509_BADCRL_XXX failure flags; see x509.h.
+ */
+uint32_t mbedtls_ssl_get_verify_result(const mbedtls_ssl_context *ssl);
+
+/**
+ * \brief Return the id of the current ciphersuite
+ *
+ * \param ssl SSL context
+ *
+ * \return a ciphersuite id
+ */
+int mbedtls_ssl_get_ciphersuite_id_from_ssl(const mbedtls_ssl_context *ssl);
+
+/**
+ * \brief Return the name of the current ciphersuite
+ *
+ * \param ssl SSL context
+ *
+ * \return a string containing the ciphersuite name
+ */
+const char *mbedtls_ssl_get_ciphersuite(const mbedtls_ssl_context *ssl);
+
+
+/**
+ * \brief Return the (D)TLS protocol version negotiated in the
+ * given connection.
+ *
+ * \note If you call this function too early during the initial
+ * handshake, before the two sides have agreed on a version,
+ * this function returns #MBEDTLS_SSL_VERSION_UNKNOWN.
+ *
+ * \param ssl The SSL context to query.
+ * \return The negotiated protocol version.
+ */
+static inline mbedtls_ssl_protocol_version mbedtls_ssl_get_version_number(
+ const mbedtls_ssl_context *ssl)
+{
+ return ssl->MBEDTLS_PRIVATE(tls_version);
+}
+
+/**
+ * \brief Return the current TLS version
+ *
+ * \param ssl SSL context
+ *
+ * \return a string containing the TLS version
+ */
+const char *mbedtls_ssl_get_version(const mbedtls_ssl_context *ssl);
+
+/**
+ * \brief Return the (maximum) number of bytes added by the record
+ * layer: header + encryption/MAC overhead (inc. padding)
+ *
+ * \param ssl SSL context
+ *
+ * \return Current maximum record expansion in bytes
+ */
+int mbedtls_ssl_get_record_expansion(const mbedtls_ssl_context *ssl);
+
+/**
+ * \brief Return the current maximum outgoing record payload in bytes.
+ *
+ * \note The logic to determine the maximum outgoing record payload is
+ * version-specific. It takes into account various factors, such as
+ * the mbedtls_config.h setting \c MBEDTLS_SSL_OUT_CONTENT_LEN, extensions
+ * such as the max fragment length or record size limit extension if
+ * used, and for DTLS the path MTU as configured and current
+ * record expansion.
+ *
+ * \note With DTLS, \c mbedtls_ssl_write() will return an error if
+ * called with a larger length value.
+ * With TLS, \c mbedtls_ssl_write() will fragment the input if
+ * necessary and return the number of bytes written; it is up
+ * to the caller to call \c mbedtls_ssl_write() again in
+ * order to send the remaining bytes if any.
+ *
+ * \sa mbedtls_ssl_get_max_out_record_payload()
+ * \sa mbedtls_ssl_get_record_expansion()
+ *
+ * \param ssl SSL context
+ *
+ * \return Current maximum payload for an outgoing record,
+ * or a negative error code.
+ */
+int mbedtls_ssl_get_max_out_record_payload(const mbedtls_ssl_context *ssl);
+
+/**
+ * \brief Return the current maximum incoming record payload in bytes.
+ *
+ * \note The logic to determine the maximum incoming record payload is
+ * version-specific. It takes into account various factors, such as
+ * the mbedtls_config.h setting \c MBEDTLS_SSL_IN_CONTENT_LEN, extensions
+ * such as the max fragment length extension or record size limit
+ * extension if used, and the current record expansion.
+ *
+ * \sa mbedtls_ssl_set_mtu()
+ * \sa mbedtls_ssl_get_max_in_record_payload()
+ * \sa mbedtls_ssl_get_record_expansion()
+ *
+ * \param ssl SSL context
+ *
+ * \return Current maximum payload for an incoming record,
+ * or a negative error code.
+ */
+int mbedtls_ssl_get_max_in_record_payload(const mbedtls_ssl_context *ssl);
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+/**
+ * \brief Return the peer certificate from the current connection.
+ *
+ * \param ssl The SSL context to use. This must be initialized and setup.
+ *
+ * \return The current peer certificate, if available.
+ * The returned certificate is owned by the SSL context and
+ * is valid only until the next call to the SSL API.
+ * \return \c NULL if no peer certificate is available. This might
+ * be because the chosen ciphersuite doesn't use CRTs
+ * (PSK-based ciphersuites, for example), or because
+ * #MBEDTLS_SSL_KEEP_PEER_CERTIFICATE has been disabled,
+ * allowing the stack to free the peer's CRT to save memory.
+ *
+ * \note For one-time inspection of the peer's certificate during
+ * the handshake, consider registering an X.509 CRT verification
+ * callback through mbedtls_ssl_conf_verify() instead of calling
+ * this function. Using mbedtls_ssl_conf_verify() also comes at
+ * the benefit of allowing you to influence the verification
+ * process, for example by masking expected and tolerated
+ * verification failures.
+ *
+ * \warning You must not use the pointer returned by this function
+ * after any further call to the SSL API, including
+ * mbedtls_ssl_read() and mbedtls_ssl_write(); this is
+ * because the pointer might change during renegotiation,
+ * which happens transparently to the user.
+ * If you want to use the certificate across API calls,
+ * you must make a copy.
+ */
+const mbedtls_x509_crt *mbedtls_ssl_get_peer_cert(const mbedtls_ssl_context *ssl);
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+#if defined(MBEDTLS_SSL_CLI_C)
+/**
+ * \brief Export a session in order to resume it later.
+ *
+ * \param ssl The SSL context representing the connection for which to
+ * to export a session structure for later resumption.
+ * \param session The target structure in which to store the exported session.
+ * This must have been initialized with mbedtls_ssl_init_session()
+ * but otherwise be unused.
+ *
+ * \note This function can handle a variety of mechanisms for session
+ * resumption: For TLS 1.2, both session ID-based resumption and
+ * ticket-based resumption will be considered. For TLS 1.3,
+ * once implemented, sessions equate to tickets, and calling
+ * this function multiple times will export the available
+ * tickets one a time until no further tickets are available,
+ * in which case MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE will
+ * be returned.
+ *
+ * \note Calling this function multiple times will only be useful
+ * once TLS 1.3 is supported. For TLS 1.2 connections, this
+ * function should be called at most once.
+ *
+ * \return \c 0 if successful. In this case, \p session can be used for
+ * session resumption by passing it to mbedtls_ssl_set_session(),
+ * and serialized for storage via mbedtls_ssl_session_save().
+ * \return #MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE if no further session
+ * is available for export.
+ * This error is a non-fatal, and has no observable effect on
+ * the SSL context or the destination session.
+ * \return Another negative error code on other kinds of failure.
+ *
+ * \sa mbedtls_ssl_set_session()
+ * \sa mbedtls_ssl_session_save()
+ */
+int mbedtls_ssl_get_session(const mbedtls_ssl_context *ssl,
+ mbedtls_ssl_session *session);
+#endif /* MBEDTLS_SSL_CLI_C */
+
+/**
+ * \brief Perform the SSL handshake
+ *
+ * \param ssl SSL context
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE
+ * if the handshake is incomplete and waiting for data to
+ * be available for reading from or writing to the underlying
+ * transport - in this case you must call this function again
+ * when the underlying transport is ready for the operation.
+ * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous
+ * operation is in progress (see
+ * mbedtls_ssl_conf_async_private_cb()) - in this case you
+ * must call this function again when the operation is ready.
+ * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic
+ * operation is in progress (see mbedtls_ecp_set_max_ops()) -
+ * in this case you must call this function again to complete
+ * the handshake when you're done attending other tasks.
+ * \return #MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED if DTLS is in use
+ * and the client did not demonstrate reachability yet - in
+ * this case you must stop using the context (see below).
+ * \return Another SSL error code - in this case you must stop using
+ * the context (see below).
+ *
+ * \warning If this function returns something other than
+ * \c 0,
+ * #MBEDTLS_ERR_SSL_WANT_READ,
+ * #MBEDTLS_ERR_SSL_WANT_WRITE,
+ * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or
+ * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS,
+ * you must stop using the SSL context for reading or writing,
+ * and either free it or call \c mbedtls_ssl_session_reset()
+ * on it before re-using it for a new connection; the current
+ * connection must be closed.
+ *
+ * \note If DTLS is in use, then you may choose to handle
+ * #MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED specially for logging
+ * purposes, as it is an expected return value rather than an
+ * actual error, but you still need to reset/free the context.
+ *
+ * \note Remarks regarding event-driven DTLS:
+ * If the function returns #MBEDTLS_ERR_SSL_WANT_READ, no datagram
+ * from the underlying transport layer is currently being processed,
+ * and it is safe to idle until the timer or the underlying transport
+ * signal a new event. This is not true for a successful handshake,
+ * in which case the datagram of the underlying transport that is
+ * currently being processed might or might not contain further
+ * DTLS records.
+ *
+ * \note If the context is configured to allow TLS 1.3, or if
+ * #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ */
+int mbedtls_ssl_handshake(mbedtls_ssl_context *ssl);
+
+/**
+ * \brief After calling mbedtls_ssl_handshake() to start the SSL
+ * handshake you can call this function to check whether the
+ * handshake is over for a given SSL context. This function
+ * should be also used to determine when to stop calling
+ * mbedtls_handshake_step() for that context.
+ *
+ * \param ssl SSL context
+ *
+ * \return \c 1 if handshake is over, \c 0 if it is still ongoing.
+ */
+static inline int mbedtls_ssl_is_handshake_over(mbedtls_ssl_context *ssl)
+{
+ return ssl->MBEDTLS_PRIVATE(state) >= MBEDTLS_SSL_HANDSHAKE_OVER;
+}
+
+/**
+ * \brief Perform a single step of the SSL handshake
+ *
+ * \note The state of the context (ssl->state) will be at
+ * the next state after this function returns \c 0. Do not
+ * call this function if mbedtls_ssl_is_handshake_over()
+ * returns \c 1.
+ *
+ * \warning Whilst in the past you may have used direct access to the
+ * context state (ssl->state) in order to ascertain when to
+ * stop calling this function and although you can still do
+ * so with something like ssl->MBEDTLS_PRIVATE(state) or by
+ * defining MBEDTLS_ALLOW_PRIVATE_ACCESS, this is now
+ * considered deprecated and could be broken in any future
+ * release. If you still find you have good reason for such
+ * direct access, then please do contact the team to explain
+ * this (raise an issue or post to the mailing list), so that
+ * we can add a solution to your problem that will be
+ * guaranteed to work in the future.
+ *
+ * \param ssl SSL context
+ *
+ * \return See mbedtls_ssl_handshake().
+ *
+ * \warning If this function returns something other than \c 0,
+ * #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE,
+ * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or
+ * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using
+ * the SSL context for reading or writing, and either free it
+ * or call \c mbedtls_ssl_session_reset() on it before
+ * re-using it for a new connection; the current connection
+ * must be closed.
+ */
+int mbedtls_ssl_handshake_step(mbedtls_ssl_context *ssl);
+
+#if defined(MBEDTLS_SSL_RENEGOTIATION)
+/**
+ * \brief Initiate an SSL renegotiation on the running connection.
+ * Client: perform the renegotiation right now.
+ * Server: request renegotiation, which will be performed
+ * during the next call to mbedtls_ssl_read() if honored by
+ * client.
+ *
+ * \param ssl SSL context
+ *
+ * \return 0 if successful, or any mbedtls_ssl_handshake() return
+ * value except #MBEDTLS_ERR_SSL_CLIENT_RECONNECT that can't
+ * happen during a renegotiation.
+ *
+ * \warning If this function returns something other than \c 0,
+ * #MBEDTLS_ERR_SSL_WANT_READ, #MBEDTLS_ERR_SSL_WANT_WRITE,
+ * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or
+ * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS, you must stop using
+ * the SSL context for reading or writing, and either free it
+ * or call \c mbedtls_ssl_session_reset() on it before
+ * re-using it for a new connection; the current connection
+ * must be closed.
+ *
+ */
+int mbedtls_ssl_renegotiate(mbedtls_ssl_context *ssl);
+#endif /* MBEDTLS_SSL_RENEGOTIATION */
+
+/**
+ * \brief Read at most 'len' application data bytes
+ *
+ * \param ssl SSL context
+ * \param buf buffer that will hold the data
+ * \param len maximum number of bytes to read
+ *
+ * \return The (positive) number of bytes read if successful.
+ * \return \c 0 if the read end of the underlying transport was closed
+ * without sending a CloseNotify beforehand, which might happen
+ * because of various reasons (internal error of an underlying
+ * stack, non-conformant peer not sending a CloseNotify and
+ * such) - in this case you must stop using the context
+ * (see below).
+ * \return #MBEDTLS_ERR_SSL_PEER_CLOSE_NOTIFY if the underlying
+ * transport is still functional, but the peer has
+ * acknowledged to not send anything anymore.
+ * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE
+ * if the handshake is incomplete and waiting for data to
+ * be available for reading from or writing to the underlying
+ * transport - in this case you must call this function again
+ * when the underlying transport is ready for the operation.
+ * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous
+ * operation is in progress (see
+ * mbedtls_ssl_conf_async_private_cb()) - in this case you
+ * must call this function again when the operation is ready.
+ * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic
+ * operation is in progress (see mbedtls_ecp_set_max_ops()) -
+ * in this case you must call this function again to complete
+ * the handshake when you're done attending other tasks.
+ * \return #MBEDTLS_ERR_SSL_CLIENT_RECONNECT if we're at the server
+ * side of a DTLS connection and the client is initiating a
+ * new connection using the same source port. See below.
+ * \return Another SSL error code - in this case you must stop using
+ * the context (see below).
+ *
+ * \warning If this function returns something other than
+ * a positive value,
+ * #MBEDTLS_ERR_SSL_WANT_READ,
+ * #MBEDTLS_ERR_SSL_WANT_WRITE,
+ * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS,
+ * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS or
+ * #MBEDTLS_ERR_SSL_CLIENT_RECONNECT,
+ * you must stop using the SSL context for reading or writing,
+ * and either free it or call \c mbedtls_ssl_session_reset()
+ * on it before re-using it for a new connection; the current
+ * connection must be closed.
+ *
+ * \note When this function returns #MBEDTLS_ERR_SSL_CLIENT_RECONNECT
+ * (which can only happen server-side), it means that a client
+ * is initiating a new connection using the same source port.
+ * You can either treat that as a connection close and wait
+ * for the client to resend a ClientHello, or directly
+ * continue with \c mbedtls_ssl_handshake() with the same
+ * context (as it has been reset internally). Either way, you
+ * must make sure this is seen by the application as a new
+ * connection: application state, if any, should be reset, and
+ * most importantly the identity of the client must be checked
+ * again. WARNING: not validating the identity of the client
+ * again, or not transmitting the new identity to the
+ * application layer, would allow authentication bypass!
+ *
+ * \note Remarks regarding event-driven DTLS:
+ * - If the function returns #MBEDTLS_ERR_SSL_WANT_READ, no datagram
+ * from the underlying transport layer is currently being processed,
+ * and it is safe to idle until the timer or the underlying transport
+ * signal a new event.
+ * - This function may return MBEDTLS_ERR_SSL_WANT_READ even if data was
+ * initially available on the underlying transport, as this data may have
+ * been only e.g. duplicated messages or a renegotiation request.
+ * Therefore, you must be prepared to receive MBEDTLS_ERR_SSL_WANT_READ even
+ * when reacting to an incoming-data event from the underlying transport.
+ * - On success, the datagram of the underlying transport that is currently
+ * being processed may contain further DTLS records. You should call
+ * \c mbedtls_ssl_check_pending to check for remaining records.
+ *
+ */
+int mbedtls_ssl_read(mbedtls_ssl_context *ssl, unsigned char *buf, size_t len);
+
+/**
+ * \brief Try to write exactly 'len' application data bytes
+ *
+ * \warning This function will do partial writes in some cases. If the
+ * return value is non-negative but less than length, the
+ * function must be called again with updated arguments:
+ * buf + ret, len - ret (if ret is the return value) until
+ * it returns a value equal to the last 'len' argument.
+ *
+ * \param ssl SSL context
+ * \param buf buffer holding the data
+ * \param len how many bytes must be written
+ *
+ * \return The (non-negative) number of bytes actually written if
+ * successful (may be less than \p len).
+ * \return #MBEDTLS_ERR_SSL_WANT_READ or #MBEDTLS_ERR_SSL_WANT_WRITE
+ * if the handshake is incomplete and waiting for data to
+ * be available for reading from or writing to the underlying
+ * transport - in this case you must call this function again
+ * when the underlying transport is ready for the operation.
+ * \return #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS if an asynchronous
+ * operation is in progress (see
+ * mbedtls_ssl_conf_async_private_cb()) - in this case you
+ * must call this function again when the operation is ready.
+ * \return #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS if a cryptographic
+ * operation is in progress (see mbedtls_ecp_set_max_ops()) -
+ * in this case you must call this function again to complete
+ * the handshake when you're done attending other tasks.
+ * \return Another SSL error code - in this case you must stop using
+ * the context (see below).
+ *
+ * \warning If this function returns something other than
+ * a non-negative value,
+ * #MBEDTLS_ERR_SSL_WANT_READ,
+ * #MBEDTLS_ERR_SSL_WANT_WRITE,
+ * #MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS or
+ * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS,
+ * you must stop using the SSL context for reading or writing,
+ * and either free it or call \c mbedtls_ssl_session_reset()
+ * on it before re-using it for a new connection; the current
+ * connection must be closed.
+ *
+ * \note When this function returns #MBEDTLS_ERR_SSL_WANT_WRITE/READ,
+ * it must be called later with the *same* arguments,
+ * until it returns a value greater than or equal to 0. When
+ * the function returns #MBEDTLS_ERR_SSL_WANT_WRITE there may be
+ * some partial data in the output buffer, however this is not
+ * yet sent.
+ *
+ * \note If the requested length is greater than the maximum
+ * fragment length (either the built-in limit or the one set
+ * or negotiated with the peer), then:
+ * - with TLS, less bytes than requested are written.
+ * - with DTLS, MBEDTLS_ERR_SSL_BAD_INPUT_DATA is returned.
+ * \c mbedtls_ssl_get_max_out_record_payload() may be used to
+ * query the active maximum fragment length.
+ *
+ * \note Attempting to write 0 bytes will result in an empty TLS
+ * application record being sent.
+ */
+int mbedtls_ssl_write(mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len);
+
+/**
+ * \brief Send an alert message
+ *
+ * \param ssl SSL context
+ * \param level The alert level of the message
+ * (MBEDTLS_SSL_ALERT_LEVEL_WARNING or MBEDTLS_SSL_ALERT_LEVEL_FATAL)
+ * \param message The alert message (SSL_ALERT_MSG_*)
+ *
+ * \return 0 if successful, or a specific SSL error code.
+ *
+ * \note If this function returns something other than 0 or
+ * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using
+ * the SSL context for reading or writing, and either free it or
+ * call \c mbedtls_ssl_session_reset() on it before re-using it
+ * for a new connection; the current connection must be closed.
+ */
+int mbedtls_ssl_send_alert_message(mbedtls_ssl_context *ssl,
+ unsigned char level,
+ unsigned char message);
+/**
+ * \brief Notify the peer that the connection is being closed
+ *
+ * \param ssl SSL context
+ *
+ * \return 0 if successful, or a specific SSL error code.
+ *
+ * \note If this function returns something other than 0 or
+ * MBEDTLS_ERR_SSL_WANT_READ/WRITE, you must stop using
+ * the SSL context for reading or writing, and either free it or
+ * call \c mbedtls_ssl_session_reset() on it before re-using it
+ * for a new connection; the current connection must be closed.
+ */
+int mbedtls_ssl_close_notify(mbedtls_ssl_context *ssl);
+
+#if defined(MBEDTLS_SSL_EARLY_DATA)
+
+#if defined(MBEDTLS_SSL_SRV_C)
+/**
+ * \brief Read at most 'len' application data bytes while performing
+ * the handshake (early data).
+ *
+ * \note This function behaves mainly as mbedtls_ssl_read(). The
+ * specification of mbedtls_ssl_read() relevant to TLS 1.3
+ * (thus not the parts specific to (D)TLS 1.2) applies to this
+ * function and the present documentation is restricted to the
+ * differences with mbedtls_ssl_read().
+ *
+ * \param ssl SSL context
+ * \param buf buffer that will hold the data
+ * \param len maximum number of bytes to read
+ *
+ * \return One additional specific return value:
+ * #MBEDTLS_ERR_SSL_CANNOT_READ_EARLY_DATA.
+ *
+ * #MBEDTLS_ERR_SSL_CANNOT_READ_EARLY_DATA is returned when it
+ * is not possible to read early data for the SSL context
+ * \p ssl.
+ *
+ * It may have been possible and it is not possible
+ * anymore because the server received the End of Early Data
+ * message or the maximum number of allowed early data for the
+ * PSK in use has been reached.
+ *
+ * It may never have been possible and will never be possible
+ * for the SSL context \p ssl because the use of early data
+ * is disabled for that context or more generally the context
+ * is not suitably configured to enable early data or the
+ * client does not use early data or the first call to the
+ * function was done while the handshake was already too
+ * advanced to gather and accept early data.
+ *
+ * It is not possible to read early data for the SSL context
+ * \p ssl but this does not preclude for using it with
+ * mbedtls_ssl_write(), mbedtls_ssl_read() or
+ * mbedtls_ssl_handshake().
+ *
+ * \note When a server wants to retrieve early data, it is expected
+ * that this function starts the handshake for the SSL context
+ * \p ssl. But this is not mandatory.
+ *
+ */
+int mbedtls_ssl_read_early_data(mbedtls_ssl_context *ssl,
+ unsigned char *buf, size_t len);
+#endif /* MBEDTLS_SSL_SRV_C */
+
+#if defined(MBEDTLS_SSL_CLI_C)
+/**
+ * \brief Try to write exactly 'len' application data bytes while
+ * performing the handshake (early data).
+ *
+ * \note This function behaves mainly as mbedtls_ssl_write(). The
+ * specification of mbedtls_ssl_write() relevant to TLS 1.3
+ * (thus not the parts specific to (D)TLS1.2) applies to this
+ * function and the present documentation is restricted to the
+ * differences with mbedtls_ssl_write().
+ *
+ * \param ssl SSL context
+ * \param buf buffer holding the data
+ * \param len how many bytes must be written
+ *
+ * \return One additional specific return value:
+ * #MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA.
+ *
+ * #MBEDTLS_ERR_SSL_CANNOT_WRITE_EARLY_DATA is returned when it
+ * is not possible to write early data for the SSL context
+ * \p ssl.
+ *
+ * It may have been possible and it is not possible
+ * anymore because the client received the server Finished
+ * message, the server rejected early data or the maximum
+ * number of allowed early data for the PSK in use has been
+ * reached.
+ *
+ * It may never have been possible and will never be possible
+ * for the SSL context \p ssl because the use of early data
+ * is disabled for that context or more generally the context
+ * is not suitably configured to enable early data or the first
+ * call to the function was done while the handshake was
+ * already completed.
+ *
+ * It is not possible to write early data for the SSL context
+ * \p ssl but this does not preclude for using it with
+ * mbedtls_ssl_write(), mbedtls_ssl_read() or
+ * mbedtls_ssl_handshake().
+ *
+ * \note This function may write early data only if the SSL context
+ * has been configured for the handshake with a PSK for which
+ * early data is allowed.
+ *
+ * \note To maximize the number of early data that can be written in
+ * the course of the handshake, it is expected that this
+ * function starts the handshake for the SSL context \p ssl.
+ * But this is not mandatory.
+ *
+ * \note This function does not provide any information on whether
+ * the server has accepted or will accept early data or not.
+ * When it returns a positive value, it just means that it
+ * has written early data to the server. To know whether the
+ * server has accepted early data or not, you should call
+ * mbedtls_ssl_get_early_data_status() with the handshake
+ * completed.
+ */
+int mbedtls_ssl_write_early_data(mbedtls_ssl_context *ssl,
+ const unsigned char *buf, size_t len);
+
+#define MBEDTLS_SSL_EARLY_DATA_STATUS_NOT_SENT 0
+#define MBEDTLS_SSL_EARLY_DATA_STATUS_ACCEPTED 1
+#define MBEDTLS_SSL_EARLY_DATA_STATUS_REJECTED 2
+/**
+ * \brief Get the status of the negotiation of the use of early data.
+ *
+ * \param ssl The SSL context to query
+ *
+ * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA if this function is called
+ * from the server-side.
+ *
+ * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA if this function is called
+ * prior to completion of the handshake.
+ *
+ * \return #MBEDTLS_SSL_EARLY_DATA_STATUS_NOT_SENT if the client has
+ * not indicated the use of early data to the server.
+ *
+ * \return #MBEDTLS_SSL_EARLY_DATA_STATUS_ACCEPTED if the client has
+ * indicated the use of early data and the server has accepted
+ * it.
+ *
+ * \return #MBEDTLS_SSL_EARLY_DATA_STATUS_REJECTED if the client has
+ * indicated the use of early data but the server has rejected
+ * it. In this situation, the client may want to re-send the
+ * early data it may have tried to send by calling
+ * mbedtls_ssl_write_early_data() as ordinary post-handshake
+ * application data by calling mbedtls_ssl_write().
+ *
+ */
+int mbedtls_ssl_get_early_data_status(mbedtls_ssl_context *ssl);
+#endif /* MBEDTLS_SSL_CLI_C */
+
+#endif /* MBEDTLS_SSL_EARLY_DATA */
+
+/**
+ * \brief Free referenced items in an SSL context and clear memory
+ *
+ * \param ssl SSL context
+ */
+void mbedtls_ssl_free(mbedtls_ssl_context *ssl);
+
+#if defined(MBEDTLS_SSL_CONTEXT_SERIALIZATION)
+/**
+ * \brief Save an active connection as serialized data in a buffer.
+ * This allows the freeing or re-using of the SSL context
+ * while still picking up the connection later in a way that
+ * it entirely transparent to the peer.
+ *
+ * \see mbedtls_ssl_context_load()
+ *
+ * \note The serialized data only contains the data that is
+ * necessary to resume the connection: negotiated protocol
+ * options, session identifier, keys, etc.
+ * Loading a saved SSL context does not restore settings and
+ * state related to how the application accesses the context,
+ * such as configured callback functions, user data, pending
+ * incoming or outgoing data, etc.
+ *
+ * \note This feature is currently only available under certain
+ * conditions, see the documentation of the return value
+ * #MBEDTLS_ERR_SSL_BAD_INPUT_DATA for details.
+ *
+ * \note When this function succeeds, it calls
+ * mbedtls_ssl_session_reset() on \p ssl which as a result is
+ * no longer associated with the connection that has been
+ * serialized. This avoids creating copies of the connection
+ * state. You're then free to either re-use the context
+ * structure for a different connection, or call
+ * mbedtls_ssl_free() on it. See the documentation of
+ * mbedtls_ssl_session_reset() for more details.
+ *
+ * \param ssl The SSL context to save. On success, it is no longer
+ * associated with the connection that has been serialized.
+ * \param buf The buffer to write the serialized data to. It must be a
+ * writeable buffer of at least \p buf_len bytes, or may be \c
+ * NULL if \p buf_len is \c 0.
+ * \param buf_len The number of bytes available for writing in \p buf.
+ * \param olen The size in bytes of the data that has been or would have
+ * been written. It must point to a valid \c size_t.
+ *
+ * \note \p olen is updated to the correct value regardless of
+ * whether \p buf_len was large enough. This makes it possible
+ * to determine the necessary size by calling this function
+ * with \p buf set to \c NULL and \p buf_len to \c 0. However,
+ * the value of \p olen is only guaranteed to be correct when
+ * the function returns #MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL or
+ * \c 0. If the return value is different, then the value of
+ * \p olen is undefined.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_SSL_BUFFER_TOO_SMALL if \p buf is too small.
+ * \return #MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed
+ * while resetting the context.
+ * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA if a handshake is in
+ * progress, or there is pending data for reading or sending,
+ * or the connection does not use DTLS 1.2 with an AEAD
+ * ciphersuite, or renegotiation is enabled.
+ */
+int mbedtls_ssl_context_save(mbedtls_ssl_context *ssl,
+ unsigned char *buf,
+ size_t buf_len,
+ size_t *olen);
+
+/**
+ * \brief Load serialized connection data to an SSL context.
+ *
+ * \see mbedtls_ssl_context_save()
+ *
+ * \warning The same serialized data must never be loaded into more
+ * that one context. In order to ensure that, after
+ * successfully loading serialized data to an SSL context, you
+ * should immediately destroy or invalidate all copies of the
+ * serialized data that was loaded. Loading the same data in
+ * more than one context would cause severe security failures
+ * including but not limited to loss of confidentiality.
+ *
+ * \note Before calling this function, the SSL context must be
+ * prepared in one of the two following ways. The first way is
+ * to take a context freshly initialised with
+ * mbedtls_ssl_init() and call mbedtls_ssl_setup() on it with
+ * the same ::mbedtls_ssl_config structure that was used in
+ * the original connection. The second way is to
+ * call mbedtls_ssl_session_reset() on a context that was
+ * previously prepared as above but used in the meantime.
+ * Either way, you must not use the context to perform a
+ * handshake between calling mbedtls_ssl_setup() or
+ * mbedtls_ssl_session_reset() and calling this function. You
+ * may however call other setter functions in that time frame
+ * as indicated in the note below.
+ *
+ * \note Before or after calling this function successfully, you
+ * also need to configure some connection-specific callbacks
+ * and settings before you can use the connection again
+ * (unless they were already set before calling
+ * mbedtls_ssl_session_reset() and the values are suitable for
+ * the present connection). Specifically, you want to call
+ * at least mbedtls_ssl_set_bio(),
+ * mbedtls_ssl_set_timer_cb(), and
+ * mbedtls_ssl_set_user_data_n() or
+ * mbedtls_ssl_set_user_data_p() if they were set originally.
+ * All other SSL setter functions
+ * are not necessary to call, either because they're only used
+ * in handshakes, or because the setting is already saved. You
+ * might choose to call them anyway, for example in order to
+ * share code between the cases of establishing a new
+ * connection and the case of loading an already-established
+ * connection.
+ *
+ * \note If you have new information about the path MTU, you want to
+ * call mbedtls_ssl_set_mtu() after calling this function, as
+ * otherwise this function would overwrite your
+ * newly-configured value with the value that was active when
+ * the context was saved.
+ *
+ * \note When this function returns an error code, it calls
+ * mbedtls_ssl_free() on \p ssl. In this case, you need to
+ * prepare the context with the usual sequence starting with a
+ * call to mbedtls_ssl_init() if you want to use it again.
+ *
+ * \param ssl The SSL context structure to be populated. It must have
+ * been prepared as described in the note above.
+ * \param buf The buffer holding the serialized connection data. It must
+ * be a readable buffer of at least \p len bytes.
+ * \param len The size of the serialized data in bytes.
+ *
+ * \return \c 0 if successful.
+ * \return #MBEDTLS_ERR_SSL_ALLOC_FAILED if memory allocation failed.
+ * \return #MBEDTLS_ERR_SSL_VERSION_MISMATCH if the serialized data
+ * comes from a different Mbed TLS version or build.
+ * \return #MBEDTLS_ERR_SSL_BAD_INPUT_DATA if input data is invalid.
+ */
+int mbedtls_ssl_context_load(mbedtls_ssl_context *ssl,
+ const unsigned char *buf,
+ size_t len);
+#endif /* MBEDTLS_SSL_CONTEXT_SERIALIZATION */
+
+/**
+ * \brief Initialize an SSL configuration context
+ * Just makes the context ready for
+ * mbedtls_ssl_config_defaults() or mbedtls_ssl_config_free().
+ *
+ * \note You need to call mbedtls_ssl_config_defaults() unless you
+ * manually set all of the relevant fields yourself.
+ *
+ * \param conf SSL configuration context
+ */
+void mbedtls_ssl_config_init(mbedtls_ssl_config *conf);
+
+/**
+ * \brief Load reasonable default SSL configuration values.
+ * (You need to call mbedtls_ssl_config_init() first.)
+ *
+ * \param conf SSL configuration context
+ * \param endpoint MBEDTLS_SSL_IS_CLIENT or MBEDTLS_SSL_IS_SERVER
+ * \param transport MBEDTLS_SSL_TRANSPORT_STREAM for TLS, or
+ * MBEDTLS_SSL_TRANSPORT_DATAGRAM for DTLS
+ * \param preset a MBEDTLS_SSL_PRESET_XXX value
+ *
+ * \note See \c mbedtls_ssl_conf_transport() for notes on DTLS.
+ *
+ * \return 0 if successful, or
+ * MBEDTLS_ERR_XXX_ALLOC_FAILED on memory allocation error.
+ */
+int mbedtls_ssl_config_defaults(mbedtls_ssl_config *conf,
+ int endpoint, int transport, int preset);
+
+/**
+ * \brief Free an SSL configuration context
+ *
+ * \param conf SSL configuration context
+ */
+void mbedtls_ssl_config_free(mbedtls_ssl_config *conf);
+
+/**
+ * \brief Initialize SSL session structure
+ *
+ * \param session SSL session
+ */
+void mbedtls_ssl_session_init(mbedtls_ssl_session *session);
+
+/**
+ * \brief Free referenced items in an SSL session including the
+ * peer certificate and clear memory
+ *
+ * \note A session object can be freed even if the SSL context
+ * that was used to retrieve the session is still in use.
+ *
+ * \param session SSL session
+ */
+void mbedtls_ssl_session_free(mbedtls_ssl_session *session);
+
+/**
+ * \brief TLS-PRF function for key derivation.
+ *
+ * \param prf The tls_prf type function type to be used.
+ * \param secret Secret for the key derivation function.
+ * \param slen Length of the secret.
+ * \param label String label for the key derivation function,
+ * terminated with null character.
+ * \param random Random bytes.
+ * \param rlen Length of the random bytes buffer.
+ * \param dstbuf The buffer holding the derived key.
+ * \param dlen Length of the output buffer.
+ *
+ * \return 0 on success. An SSL specific error on failure.
+ */
+int mbedtls_ssl_tls_prf(const mbedtls_tls_prf_types prf,
+ const unsigned char *secret, size_t slen,
+ const char *label,
+ const unsigned char *random, size_t rlen,
+ unsigned char *dstbuf, size_t dlen);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ssl.h */
diff --git a/include/mbedtls/ssl_cache.h b/include/mbedtls/ssl_cache.h
new file mode 100644
index 0000000..a1307b4
--- /dev/null
+++ b/include/mbedtls/ssl_cache.h
@@ -0,0 +1,187 @@
+/**
+ * \file ssl_cache.h
+ *
+ * \brief SSL session cache implementation
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_SSL_CACHE_H
+#define MBEDTLS_SSL_CACHE_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/ssl.h"
+
+#if defined(MBEDTLS_THREADING_C)
+#include "mbedtls/threading.h"
+#endif
+
+/**
+ * \name SECTION: Module settings
+ *
+ * The configuration options you can set for this module are in this section.
+ * Either change them in mbedtls_config.h or define them on the compiler command line.
+ * \{
+ */
+
+#if !defined(MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT)
+#define MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT 86400 /*!< 1 day */
+#endif
+
+#if !defined(MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES)
+#define MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES 50 /*!< Maximum entries in cache */
+#endif
+
+/** \} name SECTION: Module settings */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+typedef struct mbedtls_ssl_cache_context mbedtls_ssl_cache_context;
+typedef struct mbedtls_ssl_cache_entry mbedtls_ssl_cache_entry;
+
+/**
+ * \brief This structure is used for storing cache entries
+ */
+struct mbedtls_ssl_cache_entry {
+#if defined(MBEDTLS_HAVE_TIME)
+ mbedtls_time_t MBEDTLS_PRIVATE(timestamp); /*!< entry timestamp */
+#endif
+
+ unsigned char MBEDTLS_PRIVATE(session_id)[32]; /*!< session ID */
+ size_t MBEDTLS_PRIVATE(session_id_len);
+
+ unsigned char *MBEDTLS_PRIVATE(session); /*!< serialized session */
+ size_t MBEDTLS_PRIVATE(session_len);
+
+ mbedtls_ssl_cache_entry *MBEDTLS_PRIVATE(next); /*!< chain pointer */
+};
+
+/**
+ * \brief Cache context
+ */
+struct mbedtls_ssl_cache_context {
+ mbedtls_ssl_cache_entry *MBEDTLS_PRIVATE(chain); /*!< start of the chain */
+ int MBEDTLS_PRIVATE(timeout); /*!< cache entry timeout */
+ int MBEDTLS_PRIVATE(max_entries); /*!< maximum entries */
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_threading_mutex_t MBEDTLS_PRIVATE(mutex); /*!< mutex */
+#endif
+};
+
+/**
+ * \brief Initialize an SSL cache context
+ *
+ * \param cache SSL cache context
+ */
+void mbedtls_ssl_cache_init(mbedtls_ssl_cache_context *cache);
+
+/**
+ * \brief Cache get callback implementation
+ * (Thread-safe if MBEDTLS_THREADING_C is enabled)
+ *
+ * \param data The SSL cache context to use.
+ * \param session_id The pointer to the buffer holding the session ID
+ * for the session to load.
+ * \param session_id_len The length of \p session_id in bytes.
+ * \param session The address at which to store the session
+ * associated with \p session_id, if present.
+ *
+ * \return \c 0 on success.
+ * \return #MBEDTLS_ERR_SSL_CACHE_ENTRY_NOT_FOUND if there is
+ * no cache entry with specified session ID found, or
+ * any other negative error code for other failures.
+ */
+int mbedtls_ssl_cache_get(void *data,
+ unsigned char const *session_id,
+ size_t session_id_len,
+ mbedtls_ssl_session *session);
+
+/**
+ * \brief Cache set callback implementation
+ * (Thread-safe if MBEDTLS_THREADING_C is enabled)
+ *
+ * \param data The SSL cache context to use.
+ * \param session_id The pointer to the buffer holding the session ID
+ * associated to \p session.
+ * \param session_id_len The length of \p session_id in bytes.
+ * \param session The session to store.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ssl_cache_set(void *data,
+ unsigned char const *session_id,
+ size_t session_id_len,
+ const mbedtls_ssl_session *session);
+
+/**
+ * \brief Remove the cache entry by the session ID
+ * (Thread-safe if MBEDTLS_THREADING_C is enabled)
+ *
+ * \param data The SSL cache context to use.
+ * \param session_id The pointer to the buffer holding the session ID
+ * associated to session.
+ * \param session_id_len The length of \p session_id in bytes.
+ *
+ * \return \c 0 on success. This indicates the cache entry for
+ * the session with provided ID is removed or does not
+ * exist.
+ * \return A negative error code on failure.
+ */
+int mbedtls_ssl_cache_remove(void *data,
+ unsigned char const *session_id,
+ size_t session_id_len);
+
+#if defined(MBEDTLS_HAVE_TIME)
+/**
+ * \brief Set the cache timeout
+ * (Default: MBEDTLS_SSL_CACHE_DEFAULT_TIMEOUT (1 day))
+ *
+ * A timeout of 0 indicates no timeout.
+ *
+ * \param cache SSL cache context
+ * \param timeout cache entry timeout in seconds
+ */
+void mbedtls_ssl_cache_set_timeout(mbedtls_ssl_cache_context *cache, int timeout);
+
+/**
+ * \brief Get the cache timeout
+ *
+ * A timeout of 0 indicates no timeout.
+ *
+ * \param cache SSL cache context
+ *
+ * \return cache entry timeout in seconds
+ */
+static inline int mbedtls_ssl_cache_get_timeout(mbedtls_ssl_cache_context *cache)
+{
+ return cache->MBEDTLS_PRIVATE(timeout);
+}
+#endif /* MBEDTLS_HAVE_TIME */
+
+/**
+ * \brief Set the maximum number of cache entries
+ * (Default: MBEDTLS_SSL_CACHE_DEFAULT_MAX_ENTRIES (50))
+ *
+ * \param cache SSL cache context
+ * \param max cache entry maximum
+ */
+void mbedtls_ssl_cache_set_max_entries(mbedtls_ssl_cache_context *cache, int max);
+
+/**
+ * \brief Free referenced items in a cache context and clear memory
+ *
+ * \param cache SSL cache context
+ */
+void mbedtls_ssl_cache_free(mbedtls_ssl_cache_context *cache);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ssl_cache.h */
diff --git a/include/mbedtls/ssl_ciphersuites.h b/include/mbedtls/ssl_ciphersuites.h
new file mode 100644
index 0000000..8cecbb6
--- /dev/null
+++ b/include/mbedtls/ssl_ciphersuites.h
@@ -0,0 +1,616 @@
+/**
+ * \file ssl_ciphersuites.h
+ *
+ * \brief SSL Ciphersuites for Mbed TLS
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_SSL_CIPHERSUITES_H
+#define MBEDTLS_SSL_CIPHERSUITES_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/pk.h"
+#include "mbedtls/cipher.h"
+#include "mbedtls/md.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * Supported ciphersuites (Official IANA names)
+ */
+#define MBEDTLS_TLS_RSA_WITH_NULL_MD5 0x01 /**< Weak! */
+#define MBEDTLS_TLS_RSA_WITH_NULL_SHA 0x02 /**< Weak! */
+
+#define MBEDTLS_TLS_PSK_WITH_NULL_SHA 0x2C /**< Weak! */
+#define MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA 0x2D /**< Weak! */
+#define MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA 0x2E /**< Weak! */
+#define MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA 0x2F
+
+#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA 0x33
+#define MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA 0x35
+#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA 0x39
+
+#define MBEDTLS_TLS_RSA_WITH_NULL_SHA256 0x3B /**< Weak! */
+#define MBEDTLS_TLS_RSA_WITH_AES_128_CBC_SHA256 0x3C /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_WITH_AES_256_CBC_SHA256 0x3D /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA 0x41
+#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA 0x45
+
+#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CBC_SHA256 0x67 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CBC_SHA256 0x6B /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA 0x84
+#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA 0x88
+
+#define MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA 0x8C
+#define MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA 0x8D
+
+#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA 0x90
+#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA 0x91
+
+#define MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA 0x94
+#define MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA 0x95
+
+#define MBEDTLS_TLS_RSA_WITH_AES_128_GCM_SHA256 0x9C /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_WITH_AES_256_GCM_SHA384 0x9D /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_GCM_SHA256 0x9E /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 0x9F /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_PSK_WITH_AES_128_GCM_SHA256 0xA8 /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_AES_256_GCM_SHA384 0xA9 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_GCM_SHA256 0xAA /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_GCM_SHA384 0xAB /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_PSK_WITH_AES_128_GCM_SHA256 0xAC /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_PSK_WITH_AES_256_GCM_SHA384 0xAD /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_PSK_WITH_AES_128_CBC_SHA256 0xAE
+#define MBEDTLS_TLS_PSK_WITH_AES_256_CBC_SHA384 0xAF
+#define MBEDTLS_TLS_PSK_WITH_NULL_SHA256 0xB0 /**< Weak! */
+#define MBEDTLS_TLS_PSK_WITH_NULL_SHA384 0xB1 /**< Weak! */
+
+#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CBC_SHA256 0xB2
+#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CBC_SHA384 0xB3
+#define MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA256 0xB4 /**< Weak! */
+#define MBEDTLS_TLS_DHE_PSK_WITH_NULL_SHA384 0xB5 /**< Weak! */
+
+#define MBEDTLS_TLS_RSA_PSK_WITH_AES_128_CBC_SHA256 0xB6
+#define MBEDTLS_TLS_RSA_PSK_WITH_AES_256_CBC_SHA384 0xB7
+#define MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA256 0xB8 /**< Weak! */
+#define MBEDTLS_TLS_RSA_PSK_WITH_NULL_SHA384 0xB9 /**< Weak! */
+
+#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_CBC_SHA256 0xBA /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0xBE /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_CBC_SHA256 0xC0 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_CBC_SHA256 0xC4 /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_NULL_SHA 0xC001 /**< Weak! */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA 0xC004
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA 0xC005
+
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_NULL_SHA 0xC006 /**< Weak! */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA 0xC009
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA 0xC00A
+
+#define MBEDTLS_TLS_ECDH_RSA_WITH_NULL_SHA 0xC00B /**< Weak! */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA 0xC00E
+#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA 0xC00F
+
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_NULL_SHA 0xC010 /**< Weak! */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA 0xC013
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA 0xC014
+
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA256 0xC023 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA384 0xC024 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_CBC_SHA256 0xC025 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_CBC_SHA384 0xC026 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA256 0xC027 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA384 0xC028 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_CBC_SHA256 0xC029 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_CBC_SHA384 0xC02A /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 0xC02B /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384 0xC02C /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_128_GCM_SHA256 0xC02D /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_AES_256_GCM_SHA384 0xC02E /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 0xC02F /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384 0xC030 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_128_GCM_SHA256 0xC031 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_AES_256_GCM_SHA384 0xC032 /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA 0xC035
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA 0xC036
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_128_CBC_SHA256 0xC037
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_AES_256_CBC_SHA384 0xC038
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA 0xC039
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA256 0xC03A
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_NULL_SHA384 0xC03B
+
+#define MBEDTLS_TLS_RSA_WITH_ARIA_128_CBC_SHA256 0xC03C /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_WITH_ARIA_256_CBC_SHA384 0xC03D /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC044 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC045 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC048 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC049 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_CBC_SHA256 0xC04A /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_CBC_SHA384 0xC04B /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_CBC_SHA256 0xC04C /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_CBC_SHA384 0xC04D /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_CBC_SHA256 0xC04E /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_CBC_SHA384 0xC04F /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_WITH_ARIA_128_GCM_SHA256 0xC050 /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_WITH_ARIA_256_GCM_SHA384 0xC051 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC052 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC053 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05C /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05D /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_128_GCM_SHA256 0xC05E /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_ARIA_256_GCM_SHA384 0xC05F /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_128_GCM_SHA256 0xC060 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_ARIA_256_GCM_SHA384 0xC061 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_128_GCM_SHA256 0xC062 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_ARIA_256_GCM_SHA384 0xC063 /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_ARIA_128_CBC_SHA256 0xC064 /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_ARIA_256_CBC_SHA384 0xC065 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC066 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC067 /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_CBC_SHA256 0xC068 /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_CBC_SHA384 0xC069 /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_ARIA_128_GCM_SHA256 0xC06A /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_ARIA_256_GCM_SHA384 0xC06B /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_128_GCM_SHA256 0xC06C /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_ARIA_256_GCM_SHA384 0xC06D /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_128_GCM_SHA256 0xC06E /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_PSK_WITH_ARIA_256_GCM_SHA384 0xC06F /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_128_CBC_SHA256 0xC070 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_ARIA_256_CBC_SHA384 0xC071 /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC072
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0xC073
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_CBC_SHA256 0xC074
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_CBC_SHA384 0xC075
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_CBC_SHA256 0xC076
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_CBC_SHA384 0xC077
+#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_CBC_SHA256 0xC078
+#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_CBC_SHA384 0xC079
+
+#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_128_GCM_SHA256 0xC07A /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_WITH_CAMELLIA_256_GCM_SHA384 0xC07B /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 0xC07C /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 0xC07D /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 0xC086 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 0xC087 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_128_GCM_SHA256 0xC088 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_ECDSA_WITH_CAMELLIA_256_GCM_SHA384 0xC089 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_128_GCM_SHA256 0xC08A /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_CAMELLIA_256_GCM_SHA384 0xC08B /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_128_GCM_SHA256 0xC08C /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDH_RSA_WITH_CAMELLIA_256_GCM_SHA384 0xC08D /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_GCM_SHA256 0xC08E /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_GCM_SHA384 0xC08F /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_GCM_SHA256 0xC090 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_GCM_SHA384 0xC091 /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_GCM_SHA256 0xC092 /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_GCM_SHA384 0xC093 /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_128_CBC_SHA256 0xC094
+#define MBEDTLS_TLS_PSK_WITH_CAMELLIA_256_CBC_SHA384 0xC095
+#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0xC096
+#define MBEDTLS_TLS_DHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0xC097
+#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_128_CBC_SHA256 0xC098
+#define MBEDTLS_TLS_RSA_PSK_WITH_CAMELLIA_256_CBC_SHA384 0xC099
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_128_CBC_SHA256 0xC09A
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_CAMELLIA_256_CBC_SHA384 0xC09B
+
+#define MBEDTLS_TLS_RSA_WITH_AES_128_CCM 0xC09C /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_WITH_AES_256_CCM 0xC09D /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM 0xC09E /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM 0xC09F /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_WITH_AES_128_CCM_8 0xC0A0 /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_WITH_AES_256_CCM_8 0xC0A1 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_AES_128_CCM_8 0xC0A2 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_AES_256_CCM_8 0xC0A3 /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_AES_128_CCM 0xC0A4 /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_AES_256_CCM 0xC0A5 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM 0xC0A6 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM 0xC0A7 /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8 0xC0A8 /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8 0xC0A9 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_AES_128_CCM_8 0xC0AA /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_AES_256_CCM_8 0xC0AB /**< TLS 1.2 */
+/* The last two are named with PSK_DHE in the RFC, which looks like a typo */
+
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM 0xC0AC /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM 0xC0AD /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_CCM_8 0xC0AE /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_CCM_8 0xC0AF /**< TLS 1.2 */
+
+#define MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 0xC0FF /**< experimental */
+
+/* RFC 7905 */
+#define MBEDTLS_TLS_ECDHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA8 /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_ECDSA_WITH_CHACHA20_POLY1305_SHA256 0xCCA9 /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_RSA_WITH_CHACHA20_POLY1305_SHA256 0xCCAA /**< TLS 1.2 */
+#define MBEDTLS_TLS_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAB /**< TLS 1.2 */
+#define MBEDTLS_TLS_ECDHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAC /**< TLS 1.2 */
+#define MBEDTLS_TLS_DHE_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAD /**< TLS 1.2 */
+#define MBEDTLS_TLS_RSA_PSK_WITH_CHACHA20_POLY1305_SHA256 0xCCAE /**< TLS 1.2 */
+
+/* RFC 8446, Appendix B.4 */
+#define MBEDTLS_TLS1_3_AES_128_GCM_SHA256 0x1301 /**< TLS 1.3 */
+#define MBEDTLS_TLS1_3_AES_256_GCM_SHA384 0x1302 /**< TLS 1.3 */
+#define MBEDTLS_TLS1_3_CHACHA20_POLY1305_SHA256 0x1303 /**< TLS 1.3 */
+#define MBEDTLS_TLS1_3_AES_128_CCM_SHA256 0x1304 /**< TLS 1.3 */
+#define MBEDTLS_TLS1_3_AES_128_CCM_8_SHA256 0x1305 /**< TLS 1.3 */
+
+/* Reminder: update mbedtls_ssl_premaster_secret when adding a new key exchange.
+ * Reminder: update MBEDTLS_KEY_EXCHANGE__xxx below
+ */
+typedef enum {
+ MBEDTLS_KEY_EXCHANGE_NONE = 0,
+ MBEDTLS_KEY_EXCHANGE_RSA,
+ MBEDTLS_KEY_EXCHANGE_DHE_RSA,
+ MBEDTLS_KEY_EXCHANGE_ECDHE_RSA,
+ MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA,
+ MBEDTLS_KEY_EXCHANGE_PSK,
+ MBEDTLS_KEY_EXCHANGE_DHE_PSK,
+ MBEDTLS_KEY_EXCHANGE_RSA_PSK,
+ MBEDTLS_KEY_EXCHANGE_ECDHE_PSK,
+ MBEDTLS_KEY_EXCHANGE_ECDH_RSA,
+ MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA,
+ MBEDTLS_KEY_EXCHANGE_ECJPAKE,
+} mbedtls_key_exchange_type_t;
+
+/* Key exchanges using a certificate */
+#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED
+#endif
+
+/* Key exchanges in either TLS 1.2 or 1.3 which are using an ECDSA
+ * signature */
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
+ defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_WITH_ECDSA_ANY_ENABLED
+#endif
+
+#if defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) || \
+ defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
+#define MBEDTLS_SSL_HANDSHAKE_WITH_CERT_ENABLED
+#endif
+
+/* Key exchanges allowing client certificate requests.
+ *
+ * Note: that's almost the same as MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED
+ * above, except RSA-PSK uses a server certificate but no client cert.
+ *
+ * Note: this difference is specific to TLS 1.2, as with TLS 1.3, things are
+ * more symmetrical: client certs and server certs are either both allowed
+ * (Ephemeral mode) or both disallowed (PSK and PKS-Ephemeral modes).
+ */
+#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED
+#endif
+
+/* Helper to state that certificate-based client authentication through ECDSA
+ * is supported in TLS 1.2 */
+#if defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) && \
+ defined(MBEDTLS_PK_CAN_ECDSA_SIGN) && defined(MBEDTLS_PK_CAN_ECDSA_VERIFY)
+#define MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED
+#endif
+
+/* ECDSA required for certificates in either TLS 1.2 or 1.3 */
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ALLOWED_ENABLED) || \
+ defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_ECDSA_CERT_REQ_ANY_ALLOWED_ENABLED
+#endif
+
+/* Key exchanges involving server signature in ServerKeyExchange */
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED
+#endif
+
+/* Key exchanges using ECDH */
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED
+#endif
+
+/* Key exchanges that don't involve ephemeral keys */
+#if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED
+#endif
+
+/* Key exchanges that involve ephemeral keys */
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED
+#endif
+
+/* Key exchanges using a PSK */
+#if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED
+#endif
+
+/* Key exchanges using DHE */
+#if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED
+#endif
+
+/* Key exchanges using ECDHE */
+#if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED
+#endif
+
+/* TLS 1.2 key exchanges using ECDH or ECDHE*/
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED
+#endif
+
+/* TLS 1.3 PSK key exchanges */
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_ENABLED) || \
+ defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED
+#endif
+
+/* TLS 1.2 or 1.3 key exchanges with PSK */
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) || \
+ defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_PSK_ENABLED)
+#define MBEDTLS_SSL_HANDSHAKE_WITH_PSK_ENABLED
+#endif
+
+/* TLS 1.3 ephemeral key exchanges */
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_EPHEMERAL_ENABLED) || \
+ defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_PSK_EPHEMERAL_ENABLED)
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED
+#endif
+
+/* TLS 1.3 key exchanges using ECDHE */
+#if defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED) && \
+ defined(PSA_WANT_ALG_ECDH)
+#define MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_ECDHE_ENABLED
+#endif
+
+/* TLS 1.2 or 1.3 key exchanges using ECDH or ECDHE */
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
+ defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_ECDHE_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_ANY_ENABLED
+#endif
+
+/* TLS 1.2 XXDH key exchanges: ECDH or ECDHE or FFDH */
+#if (defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) || \
+ defined(MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED))
+#define MBEDTLS_KEY_EXCHANGE_SOME_XXDH_1_2_ENABLED
+#endif
+
+/* The handshake params structure has a set of fields called xxdh_psa which are used:
+ * - by TLS 1.2 with `USE_PSA` to do ECDH or ECDHE;
+ * - by TLS 1.3 to do ECDHE or FFDHE.
+ * The following macros can be used to guard their declaration and use.
+ */
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_OR_ECDHE_1_2_ENABLED) && \
+ defined(MBEDTLS_USE_PSA_CRYPTO)
+#define MBEDTLS_KEY_EXCHANGE_SOME_XXDH_PSA_1_2_ENABLED
+#endif
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_XXDH_PSA_1_2_ENABLED) || \
+ defined(MBEDTLS_SSL_TLS1_3_KEY_EXCHANGE_MODE_SOME_EPHEMERAL_ENABLED)
+#define MBEDTLS_KEY_EXCHANGE_SOME_XXDH_PSA_ANY_ENABLED
+#endif
+
+typedef struct mbedtls_ssl_ciphersuite_t mbedtls_ssl_ciphersuite_t;
+
+#define MBEDTLS_CIPHERSUITE_WEAK 0x01 /**< Weak ciphersuite flag */
+#define MBEDTLS_CIPHERSUITE_SHORT_TAG 0x02 /**< Short authentication tag,
+ eg for CCM_8 */
+#define MBEDTLS_CIPHERSUITE_NODTLS 0x04 /**< Can't be used with DTLS */
+
+/**
+ * \brief This structure is used for storing ciphersuite information
+ *
+ * \note members are defined using integral types instead of enums
+ * in order to pack structure and reduce memory usage by internal
+ * \c ciphersuite_definitions[]
+ */
+struct mbedtls_ssl_ciphersuite_t {
+ int MBEDTLS_PRIVATE(id);
+ const char *MBEDTLS_PRIVATE(name);
+
+ uint8_t MBEDTLS_PRIVATE(cipher); /* mbedtls_cipher_type_t */
+ uint8_t MBEDTLS_PRIVATE(mac); /* mbedtls_md_type_t */
+ uint8_t MBEDTLS_PRIVATE(key_exchange); /* mbedtls_key_exchange_type_t */
+ uint8_t MBEDTLS_PRIVATE(flags);
+
+ uint16_t MBEDTLS_PRIVATE(min_tls_version); /* mbedtls_ssl_protocol_version */
+ uint16_t MBEDTLS_PRIVATE(max_tls_version); /* mbedtls_ssl_protocol_version */
+};
+
+const int *mbedtls_ssl_list_ciphersuites(void);
+
+const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_string(const char *ciphersuite_name);
+const mbedtls_ssl_ciphersuite_t *mbedtls_ssl_ciphersuite_from_id(int ciphersuite_id);
+
+#if defined(MBEDTLS_PK_C)
+mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_pk_alg(const mbedtls_ssl_ciphersuite_t *info);
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+psa_algorithm_t mbedtls_ssl_get_ciphersuite_sig_pk_psa_alg(const mbedtls_ssl_ciphersuite_t *info);
+psa_key_usage_t mbedtls_ssl_get_ciphersuite_sig_pk_psa_usage(const mbedtls_ssl_ciphersuite_t *info);
+#endif
+mbedtls_pk_type_t mbedtls_ssl_get_ciphersuite_sig_alg(const mbedtls_ssl_ciphersuite_t *info);
+#endif
+
+int mbedtls_ssl_ciphersuite_uses_ec(const mbedtls_ssl_ciphersuite_t *info);
+int mbedtls_ssl_ciphersuite_uses_psk(const mbedtls_ssl_ciphersuite_t *info);
+
+static inline const char *mbedtls_ssl_ciphersuite_get_name(const mbedtls_ssl_ciphersuite_t *info)
+{
+ return info->MBEDTLS_PRIVATE(name);
+}
+
+size_t mbedtls_ssl_ciphersuite_get_cipher_key_bitlen(const mbedtls_ssl_ciphersuite_t *info);
+
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED)
+static inline int mbedtls_ssl_ciphersuite_has_pfs(const mbedtls_ssl_ciphersuite_t *info)
+{
+ switch (info->MBEDTLS_PRIVATE(key_exchange)) {
+ case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
+ case MBEDTLS_KEY_EXCHANGE_ECJPAKE:
+ return 1;
+
+ default:
+ return 0;
+ }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED */
+
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED)
+static inline int mbedtls_ssl_ciphersuite_no_pfs(const mbedtls_ssl_ciphersuite_t *info)
+{
+ switch (info->MBEDTLS_PRIVATE(key_exchange)) {
+ case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
+ case MBEDTLS_KEY_EXCHANGE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_PSK:
+ case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
+ return 1;
+
+ default:
+ return 0;
+ }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */
+
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED)
+static inline int mbedtls_ssl_ciphersuite_uses_ecdh(const mbedtls_ssl_ciphersuite_t *info)
+{
+ switch (info->MBEDTLS_PRIVATE(key_exchange)) {
+ case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
+ return 1;
+
+ default:
+ return 0;
+ }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED */
+
+static inline int mbedtls_ssl_ciphersuite_cert_req_allowed(const mbedtls_ssl_ciphersuite_t *info)
+{
+ switch (info->MBEDTLS_PRIVATE(key_exchange)) {
+ case MBEDTLS_KEY_EXCHANGE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
+ return 1;
+
+ default:
+ return 0;
+ }
+}
+
+static inline int mbedtls_ssl_ciphersuite_uses_srv_cert(const mbedtls_ssl_ciphersuite_t *info)
+{
+ switch (info->MBEDTLS_PRIVATE(key_exchange)) {
+ case MBEDTLS_KEY_EXCHANGE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_RSA_PSK:
+ case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDH_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
+ return 1;
+
+ default:
+ return 0;
+ }
+}
+
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED)
+static inline int mbedtls_ssl_ciphersuite_uses_dhe(const mbedtls_ssl_ciphersuite_t *info)
+{
+ switch (info->MBEDTLS_PRIVATE(key_exchange)) {
+ case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_DHE_PSK:
+ return 1;
+
+ default:
+ return 0;
+ }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED) */
+
+#if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED)
+static inline int mbedtls_ssl_ciphersuite_uses_ecdhe(const mbedtls_ssl_ciphersuite_t *info)
+{
+ switch (info->MBEDTLS_PRIVATE(key_exchange)) {
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_PSK:
+ return 1;
+
+ default:
+ return 0;
+ }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED) */
+
+#if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED)
+static inline int mbedtls_ssl_ciphersuite_uses_server_signature(
+ const mbedtls_ssl_ciphersuite_t *info)
+{
+ switch (info->MBEDTLS_PRIVATE(key_exchange)) {
+ case MBEDTLS_KEY_EXCHANGE_DHE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_RSA:
+ case MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA:
+ return 1;
+
+ default:
+ return 0;
+ }
+}
+#endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ssl_ciphersuites.h */
diff --git a/include/mbedtls/ssl_cookie.h b/include/mbedtls/ssl_cookie.h
new file mode 100644
index 0000000..71c258e
--- /dev/null
+++ b/include/mbedtls/ssl_cookie.h
@@ -0,0 +1,106 @@
+/**
+ * \file ssl_cookie.h
+ *
+ * \brief DTLS cookie callbacks implementation
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_SSL_COOKIE_H
+#define MBEDTLS_SSL_COOKIE_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/ssl.h"
+
+#if !defined(MBEDTLS_USE_PSA_CRYPTO)
+#if defined(MBEDTLS_THREADING_C)
+#include "mbedtls/threading.h"
+#endif
+#endif /* !MBEDTLS_USE_PSA_CRYPTO */
+
+/**
+ * \name SECTION: Module settings
+ *
+ * The configuration options you can set for this module are in this section.
+ * Either change them in mbedtls_config.h or define them on the compiler command line.
+ * \{
+ */
+#ifndef MBEDTLS_SSL_COOKIE_TIMEOUT
+#define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */
+#endif
+
+/** \} name SECTION: Module settings */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \brief Context for the default cookie functions.
+ */
+typedef struct mbedtls_ssl_cookie_ctx {
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+ mbedtls_svc_key_id_t MBEDTLS_PRIVATE(psa_hmac_key); /*!< key id for the HMAC portion */
+ psa_algorithm_t MBEDTLS_PRIVATE(psa_hmac_alg); /*!< key algorithm for the HMAC portion */
+#else
+ mbedtls_md_context_t MBEDTLS_PRIVATE(hmac_ctx); /*!< context for the HMAC portion */
+#endif /* MBEDTLS_USE_PSA_CRYPTO */
+#if !defined(MBEDTLS_HAVE_TIME)
+ unsigned long MBEDTLS_PRIVATE(serial); /*!< serial number for expiration */
+#endif
+ unsigned long MBEDTLS_PRIVATE(timeout); /*!< timeout delay, in seconds if HAVE_TIME,
+ or in number of tickets issued */
+
+#if !defined(MBEDTLS_USE_PSA_CRYPTO)
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_threading_mutex_t MBEDTLS_PRIVATE(mutex);
+#endif
+#endif /* !MBEDTLS_USE_PSA_CRYPTO */
+} mbedtls_ssl_cookie_ctx;
+
+/**
+ * \brief Initialize cookie context
+ */
+void mbedtls_ssl_cookie_init(mbedtls_ssl_cookie_ctx *ctx);
+
+/**
+ * \brief Setup cookie context (generate keys)
+ */
+int mbedtls_ssl_cookie_setup(mbedtls_ssl_cookie_ctx *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+/**
+ * \brief Set expiration delay for cookies
+ * (Default MBEDTLS_SSL_COOKIE_TIMEOUT)
+ *
+ * \param ctx Cookie context
+ * \param delay Delay, in seconds if HAVE_TIME, or in number of cookies
+ * issued in the meantime.
+ * 0 to disable expiration (NOT recommended)
+ */
+void mbedtls_ssl_cookie_set_timeout(mbedtls_ssl_cookie_ctx *ctx, unsigned long delay);
+
+/**
+ * \brief Free cookie context
+ */
+void mbedtls_ssl_cookie_free(mbedtls_ssl_cookie_ctx *ctx);
+
+/**
+ * \brief Generate cookie, see \c mbedtls_ssl_cookie_write_t
+ */
+mbedtls_ssl_cookie_write_t mbedtls_ssl_cookie_write;
+
+/**
+ * \brief Verify cookie, see \c mbedtls_ssl_cookie_write_t
+ */
+mbedtls_ssl_cookie_check_t mbedtls_ssl_cookie_check;
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ssl_cookie.h */
diff --git a/include/mbedtls/ssl_ticket.h b/include/mbedtls/ssl_ticket.h
new file mode 100644
index 0000000..6d59c12
--- /dev/null
+++ b/include/mbedtls/ssl_ticket.h
@@ -0,0 +1,181 @@
+/**
+ * \file ssl_ticket.h
+ *
+ * \brief TLS server ticket callbacks implementation
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_SSL_TICKET_H
+#define MBEDTLS_SSL_TICKET_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+/*
+ * This implementation of the session ticket callbacks includes key
+ * management, rotating the keys periodically in order to preserve forward
+ * secrecy, when MBEDTLS_HAVE_TIME is defined.
+ */
+
+#include "mbedtls/ssl.h"
+#include "mbedtls/cipher.h"
+
+#if defined(MBEDTLS_HAVE_TIME)
+#include "mbedtls/platform_time.h"
+#endif
+
+#if defined(MBEDTLS_USE_PSA_CRYPTO)
+#include "psa/crypto.h"
+#endif
+
+#if defined(MBEDTLS_THREADING_C)
+#include "mbedtls/threading.h"
+#endif
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#define MBEDTLS_SSL_TICKET_MAX_KEY_BYTES 32 /*!< Max supported key length in bytes */
+#define MBEDTLS_SSL_TICKET_KEY_NAME_BYTES 4 /*!< key name length in bytes */
+
+/**
+ * \brief Information for session ticket protection
+ */
+typedef struct mbedtls_ssl_ticket_key {
+ unsigned char MBEDTLS_PRIVATE(name)[MBEDTLS_SSL_TICKET_KEY_NAME_BYTES];
+ /*!< random key identifier */
+#if defined(MBEDTLS_HAVE_TIME)
+ mbedtls_time_t MBEDTLS_PRIVATE(generation_time); /*!< key generation timestamp (seconds) */
+#endif
+#if !defined(MBEDTLS_USE_PSA_CRYPTO)
+ mbedtls_cipher_context_t MBEDTLS_PRIVATE(ctx); /*!< context for auth enc/decryption */
+#else
+ mbedtls_svc_key_id_t MBEDTLS_PRIVATE(key); /*!< key used for auth enc/decryption */
+ psa_algorithm_t MBEDTLS_PRIVATE(alg); /*!< algorithm of auth enc/decryption */
+ psa_key_type_t MBEDTLS_PRIVATE(key_type); /*!< key type */
+ size_t MBEDTLS_PRIVATE(key_bits); /*!< key length in bits */
+#endif
+}
+mbedtls_ssl_ticket_key;
+
+/**
+ * \brief Context for session ticket handling functions
+ */
+typedef struct mbedtls_ssl_ticket_context {
+ mbedtls_ssl_ticket_key MBEDTLS_PRIVATE(keys)[2]; /*!< ticket protection keys */
+ unsigned char MBEDTLS_PRIVATE(active); /*!< index of the currently active key */
+
+ uint32_t MBEDTLS_PRIVATE(ticket_lifetime); /*!< lifetime of tickets in seconds */
+
+ /** Callback for getting (pseudo-)random numbers */
+ int(*MBEDTLS_PRIVATE(f_rng))(void *, unsigned char *, size_t);
+ void *MBEDTLS_PRIVATE(p_rng); /*!< context for the RNG function */
+
+#if defined(MBEDTLS_THREADING_C)
+ mbedtls_threading_mutex_t MBEDTLS_PRIVATE(mutex);
+#endif
+}
+mbedtls_ssl_ticket_context;
+
+/**
+ * \brief Initialize a ticket context.
+ * (Just make it ready for mbedtls_ssl_ticket_setup()
+ * or mbedtls_ssl_ticket_free().)
+ *
+ * \param ctx Context to be initialized
+ */
+void mbedtls_ssl_ticket_init(mbedtls_ssl_ticket_context *ctx);
+
+/**
+ * \brief Prepare context to be actually used
+ *
+ * \param ctx Context to be set up
+ * \param f_rng RNG callback function (mandatory)
+ * \param p_rng RNG callback context
+ * \param cipher AEAD cipher to use for ticket protection.
+ * Recommended value: MBEDTLS_CIPHER_AES_256_GCM.
+ * \param lifetime Tickets lifetime in seconds
+ * Recommended value: 86400 (one day).
+ *
+ * \note It is highly recommended to select a cipher that is at
+ * least as strong as the strongest ciphersuite
+ * supported. Usually that means a 256-bit key.
+ *
+ * \note The lifetime of the keys is twice the lifetime of tickets.
+ * It is recommended to pick a reasonable lifetime so as not
+ * to negate the benefits of forward secrecy.
+ *
+ * \return 0 if successful,
+ * or a specific MBEDTLS_ERR_XXX error code
+ */
+int mbedtls_ssl_ticket_setup(mbedtls_ssl_ticket_context *ctx,
+ int (*f_rng)(void *, unsigned char *, size_t), void *p_rng,
+ mbedtls_cipher_type_t cipher,
+ uint32_t lifetime);
+
+/**
+ * \brief Rotate session ticket encryption key to new specified key.
+ * Provides for external control of session ticket encryption
+ * key rotation, e.g. for synchronization between different
+ * machines. If this function is not used, or if not called
+ * before ticket lifetime expires, then a new session ticket
+ * encryption key is generated internally in order to avoid
+ * unbounded session ticket encryption key lifetimes.
+ *
+ * \param ctx Context to be set up
+ * \param name Session ticket encryption key name
+ * \param nlength Session ticket encryption key name length in bytes
+ * \param k Session ticket encryption key
+ * \param klength Session ticket encryption key length in bytes
+ * \param lifetime Tickets lifetime in seconds
+ * Recommended value: 86400 (one day).
+ *
+ * \note \c name and \c k are recommended to be cryptographically
+ * random data.
+ *
+ * \note \c nlength must match sizeof( ctx->name )
+ *
+ * \note \c klength must be sufficient for use by cipher specified
+ * to \c mbedtls_ssl_ticket_setup
+ *
+ * \note The lifetime of the keys is twice the lifetime of tickets.
+ * It is recommended to pick a reasonable lifetime so as not
+ * to negate the benefits of forward secrecy.
+ *
+ * \return 0 if successful,
+ * or a specific MBEDTLS_ERR_XXX error code
+ */
+int mbedtls_ssl_ticket_rotate(mbedtls_ssl_ticket_context *ctx,
+ const unsigned char *name, size_t nlength,
+ const unsigned char *k, size_t klength,
+ uint32_t lifetime);
+
+/**
+ * \brief Implementation of the ticket write callback
+ *
+ * \note See \c mbedtls_ssl_ticket_write_t for description
+ */
+mbedtls_ssl_ticket_write_t mbedtls_ssl_ticket_write;
+
+/**
+ * \brief Implementation of the ticket parse callback
+ *
+ * \note See \c mbedtls_ssl_ticket_parse_t for description
+ */
+mbedtls_ssl_ticket_parse_t mbedtls_ssl_ticket_parse;
+
+/**
+ * \brief Free a context's content and zeroize it.
+ *
+ * \param ctx Context to be cleaned up
+ */
+void mbedtls_ssl_ticket_free(mbedtls_ssl_ticket_context *ctx);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* ssl_ticket.h */
diff --git a/include/mbedtls/threading.h b/include/mbedtls/threading.h
new file mode 100644
index 0000000..ed16a23
--- /dev/null
+++ b/include/mbedtls/threading.h
@@ -0,0 +1,105 @@
+/**
+ * \file threading.h
+ *
+ * \brief Threading abstraction layer
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_THREADING_H
+#define MBEDTLS_THREADING_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stdlib.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** Bad input parameters to function. */
+#define MBEDTLS_ERR_THREADING_BAD_INPUT_DATA -0x001C
+/** Locking / unlocking / free failed with error code. */
+#define MBEDTLS_ERR_THREADING_MUTEX_ERROR -0x001E
+
+#if defined(MBEDTLS_THREADING_PTHREAD)
+#include <pthread.h>
+typedef struct mbedtls_threading_mutex_t {
+ pthread_mutex_t MBEDTLS_PRIVATE(mutex);
+ /* is_valid is 0 after a failed init or a free, and nonzero after a
+ * successful init. This field is not considered part of the public
+ * API of Mbed TLS and may change without notice. */
+ char MBEDTLS_PRIVATE(is_valid);
+} mbedtls_threading_mutex_t;
+#endif
+
+#if defined(MBEDTLS_THREADING_ALT)
+/* You should define the mbedtls_threading_mutex_t type in your header */
+#include "threading_alt.h"
+
+/**
+ * \brief Set your alternate threading implementation function
+ * pointers and initialize global mutexes. If used, this
+ * function must be called once in the main thread before any
+ * other Mbed TLS function is called, and
+ * mbedtls_threading_free_alt() must be called once in the main
+ * thread after all other Mbed TLS functions.
+ *
+ * \note mutex_init() and mutex_free() don't return a status code.
+ * If mutex_init() fails, it should leave its argument (the
+ * mutex) in a state such that mutex_lock() will fail when
+ * called with this argument.
+ *
+ * \param mutex_init the init function implementation
+ * \param mutex_free the free function implementation
+ * \param mutex_lock the lock function implementation
+ * \param mutex_unlock the unlock function implementation
+ */
+void mbedtls_threading_set_alt(void (*mutex_init)(mbedtls_threading_mutex_t *),
+ void (*mutex_free)(mbedtls_threading_mutex_t *),
+ int (*mutex_lock)(mbedtls_threading_mutex_t *),
+ int (*mutex_unlock)(mbedtls_threading_mutex_t *));
+
+/**
+ * \brief Free global mutexes.
+ */
+void mbedtls_threading_free_alt(void);
+#endif /* MBEDTLS_THREADING_ALT */
+
+#if defined(MBEDTLS_THREADING_C)
+/*
+ * The function pointers for mutex_init, mutex_free, mutex_ and mutex_unlock
+ *
+ * All these functions are expected to work or the result will be undefined.
+ */
+extern void (*mbedtls_mutex_init)(mbedtls_threading_mutex_t *mutex);
+extern void (*mbedtls_mutex_free)(mbedtls_threading_mutex_t *mutex);
+extern int (*mbedtls_mutex_lock)(mbedtls_threading_mutex_t *mutex);
+extern int (*mbedtls_mutex_unlock)(mbedtls_threading_mutex_t *mutex);
+
+/*
+ * Global mutexes
+ */
+#if defined(MBEDTLS_FS_IO)
+extern mbedtls_threading_mutex_t mbedtls_threading_readdir_mutex;
+#endif
+
+#if defined(MBEDTLS_HAVE_TIME_DATE) && !defined(MBEDTLS_PLATFORM_GMTIME_R_ALT)
+/* This mutex may or may not be used in the default definition of
+ * mbedtls_platform_gmtime_r(), but in order to determine that,
+ * we need to check POSIX features, hence modify _POSIX_C_SOURCE.
+ * With the current approach, this declaration is orphaned, lacking
+ * an accompanying definition, in case mbedtls_platform_gmtime_r()
+ * doesn't need it, but that's not a problem. */
+extern mbedtls_threading_mutex_t mbedtls_threading_gmtime_mutex;
+#endif /* MBEDTLS_HAVE_TIME_DATE && !MBEDTLS_PLATFORM_GMTIME_R_ALT */
+
+#endif /* MBEDTLS_THREADING_C */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* threading.h */
diff --git a/include/mbedtls/timing.h b/include/mbedtls/timing.h
new file mode 100644
index 0000000..62ae102
--- /dev/null
+++ b/include/mbedtls/timing.h
@@ -0,0 +1,94 @@
+/**
+ * \file timing.h
+ *
+ * \brief Portable interface to timeouts and to the CPU cycle counter
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_TIMING_H
+#define MBEDTLS_TIMING_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include <stdint.h>
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#if !defined(MBEDTLS_TIMING_ALT)
+// Regular implementation
+//
+
+/**
+ * \brief timer structure
+ */
+struct mbedtls_timing_hr_time {
+ uint64_t MBEDTLS_PRIVATE(opaque)[4];
+};
+
+/**
+ * \brief Context for mbedtls_timing_set/get_delay()
+ */
+typedef struct mbedtls_timing_delay_context {
+ struct mbedtls_timing_hr_time MBEDTLS_PRIVATE(timer);
+ uint32_t MBEDTLS_PRIVATE(int_ms);
+ uint32_t MBEDTLS_PRIVATE(fin_ms);
+} mbedtls_timing_delay_context;
+
+#else /* MBEDTLS_TIMING_ALT */
+#include "timing_alt.h"
+#endif /* MBEDTLS_TIMING_ALT */
+
+/* Internal use */
+unsigned long mbedtls_timing_get_timer(struct mbedtls_timing_hr_time *val, int reset);
+
+/**
+ * \brief Set a pair of delays to watch
+ * (See \c mbedtls_timing_get_delay().)
+ *
+ * \param data Pointer to timing data.
+ * Must point to a valid \c mbedtls_timing_delay_context struct.
+ * \param int_ms First (intermediate) delay in milliseconds.
+ * The effect if int_ms > fin_ms is unspecified.
+ * \param fin_ms Second (final) delay in milliseconds.
+ * Pass 0 to cancel the current delay.
+ *
+ * \note To set a single delay, either use \c mbedtls_timing_set_timer
+ * directly or use this function with int_ms == fin_ms.
+ */
+void mbedtls_timing_set_delay(void *data, uint32_t int_ms, uint32_t fin_ms);
+
+/**
+ * \brief Get the status of delays
+ * (Memory helper: number of delays passed.)
+ *
+ * \param data Pointer to timing data
+ * Must point to a valid \c mbedtls_timing_delay_context struct.
+ *
+ * \return -1 if cancelled (fin_ms = 0),
+ * 0 if none of the delays are passed,
+ * 1 if only the intermediate delay is passed,
+ * 2 if the final delay is passed.
+ */
+int mbedtls_timing_get_delay(void *data);
+
+/**
+ * \brief Get the final timing delay
+ *
+ * \param data Pointer to timing data
+ * Must point to a valid \c mbedtls_timing_delay_context struct.
+ *
+ * \return Final timing delay in milliseconds.
+ */
+uint32_t mbedtls_timing_get_final_delay(
+ const mbedtls_timing_delay_context *data);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* timing.h */
diff --git a/include/mbedtls/version.h b/include/mbedtls/version.h
new file mode 100644
index 0000000..637f9d3
--- /dev/null
+++ b/include/mbedtls/version.h
@@ -0,0 +1,78 @@
+/**
+ * \file version.h
+ *
+ * \brief Run-time version information
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+/*
+ * This set of run-time variables can be used to determine the version number of
+ * the Mbed TLS library used. Compile-time version defines for the same can be
+ * found in build_info.h
+ */
+#ifndef MBEDTLS_VERSION_H
+#define MBEDTLS_VERSION_H
+
+#include "mbedtls/build_info.h"
+
+#if defined(MBEDTLS_VERSION_C)
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * Get the version number.
+ *
+ * \return The constructed version number in the format
+ * MMNNPP00 (Major, Minor, Patch).
+ */
+unsigned int mbedtls_version_get_number(void);
+
+/**
+ * Get the version string ("x.y.z").
+ *
+ * \param string The string that will receive the value.
+ * (Should be at least 9 bytes in size)
+ */
+void mbedtls_version_get_string(char *string);
+
+/**
+ * Get the full version string ("Mbed TLS x.y.z").
+ *
+ * \param string The string that will receive the value. The Mbed TLS version
+ * string will use 18 bytes AT MOST including a terminating
+ * null byte.
+ * (So the buffer should be at least 18 bytes to receive this
+ * version string).
+ */
+void mbedtls_version_get_string_full(char *string);
+
+/**
+ * \brief Check if support for a feature was compiled into this
+ * Mbed TLS binary. This allows you to see at runtime if the
+ * library was for instance compiled with or without
+ * Multi-threading support.
+ *
+ * \note only checks against defines in the sections "System
+ * support", "Mbed TLS modules" and "Mbed TLS feature
+ * support" in mbedtls_config.h
+ *
+ * \param feature The string for the define to check (e.g. "MBEDTLS_AES_C")
+ *
+ * \return 0 if the feature is present,
+ * -1 if the feature is not present and
+ * -2 if support for feature checking as a whole was not
+ * compiled in.
+ */
+int mbedtls_version_check_feature(const char *feature);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* MBEDTLS_VERSION_C */
+
+#endif /* version.h */
diff --git a/include/mbedtls/x509.h b/include/mbedtls/x509.h
new file mode 100644
index 0000000..e2e0667
--- /dev/null
+++ b/include/mbedtls/x509.h
@@ -0,0 +1,550 @@
+/**
+ * \file x509.h
+ *
+ * \brief X.509 generic defines and structures
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_X509_H
+#define MBEDTLS_X509_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/asn1.h"
+#include "mbedtls/pk.h"
+
+#if defined(MBEDTLS_RSA_C)
+#include "mbedtls/rsa.h"
+#endif
+
+/**
+ * \addtogroup x509_module
+ * \{
+ */
+
+#if !defined(MBEDTLS_X509_MAX_INTERMEDIATE_CA)
+/**
+ * Maximum number of intermediate CAs in a verification chain.
+ * That is, maximum length of the chain, excluding the end-entity certificate
+ * and the trusted root certificate.
+ *
+ * Set this to a low value to prevent an adversary from making you waste
+ * resources verifying an overlong certificate chain.
+ */
+#define MBEDTLS_X509_MAX_INTERMEDIATE_CA 8
+#endif
+
+/**
+ * \name X509 Error codes
+ * \{
+ */
+/** Unavailable feature, e.g. RSA hashing/encryption combination. */
+#define MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE -0x2080
+/** Requested OID is unknown. */
+#define MBEDTLS_ERR_X509_UNKNOWN_OID -0x2100
+/** The CRT/CRL/CSR format is invalid, e.g. different type expected. */
+#define MBEDTLS_ERR_X509_INVALID_FORMAT -0x2180
+/** The CRT/CRL/CSR version element is invalid. */
+#define MBEDTLS_ERR_X509_INVALID_VERSION -0x2200
+/** The serial tag or value is invalid. */
+#define MBEDTLS_ERR_X509_INVALID_SERIAL -0x2280
+/** The algorithm tag or value is invalid. */
+#define MBEDTLS_ERR_X509_INVALID_ALG -0x2300
+/** The name tag or value is invalid. */
+#define MBEDTLS_ERR_X509_INVALID_NAME -0x2380
+/** The date tag or value is invalid. */
+#define MBEDTLS_ERR_X509_INVALID_DATE -0x2400
+/** The signature tag or value invalid. */
+#define MBEDTLS_ERR_X509_INVALID_SIGNATURE -0x2480
+/** The extension tag or value is invalid. */
+#define MBEDTLS_ERR_X509_INVALID_EXTENSIONS -0x2500
+/** CRT/CRL/CSR has an unsupported version number. */
+#define MBEDTLS_ERR_X509_UNKNOWN_VERSION -0x2580
+/** Signature algorithm (oid) is unsupported. */
+#define MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG -0x2600
+/** Signature algorithms do not match. (see \c ::mbedtls_x509_crt sig_oid) */
+#define MBEDTLS_ERR_X509_SIG_MISMATCH -0x2680
+/** Certificate verification failed, e.g. CRL, CA or signature check failed. */
+#define MBEDTLS_ERR_X509_CERT_VERIFY_FAILED -0x2700
+/** Format not recognized as DER or PEM. */
+#define MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT -0x2780
+/** Input invalid. */
+#define MBEDTLS_ERR_X509_BAD_INPUT_DATA -0x2800
+/** Allocation of memory failed. */
+#define MBEDTLS_ERR_X509_ALLOC_FAILED -0x2880
+/** Read/write of file failed. */
+#define MBEDTLS_ERR_X509_FILE_IO_ERROR -0x2900
+/** Destination buffer is too small. */
+#define MBEDTLS_ERR_X509_BUFFER_TOO_SMALL -0x2980
+/** A fatal error occurred, eg the chain is too long or the vrfy callback failed. */
+#define MBEDTLS_ERR_X509_FATAL_ERROR -0x3000
+/** \} name X509 Error codes */
+
+/**
+ * \name X509 Verify codes
+ * \{
+ */
+/* Reminder: update x509_crt_verify_strings[] in library/x509_crt.c */
+#define MBEDTLS_X509_BADCERT_EXPIRED 0x01 /**< The certificate validity has expired. */
+#define MBEDTLS_X509_BADCERT_REVOKED 0x02 /**< The certificate has been revoked (is on a CRL). */
+#define MBEDTLS_X509_BADCERT_CN_MISMATCH 0x04 /**< The certificate Common Name (CN) does not match with the expected CN. */
+#define MBEDTLS_X509_BADCERT_NOT_TRUSTED 0x08 /**< The certificate is not correctly signed by the trusted CA. */
+#define MBEDTLS_X509_BADCRL_NOT_TRUSTED 0x10 /**< The CRL is not correctly signed by the trusted CA. */
+#define MBEDTLS_X509_BADCRL_EXPIRED 0x20 /**< The CRL is expired. */
+#define MBEDTLS_X509_BADCERT_MISSING 0x40 /**< Certificate was missing. */
+#define MBEDTLS_X509_BADCERT_SKIP_VERIFY 0x80 /**< Certificate verification was skipped. */
+#define MBEDTLS_X509_BADCERT_OTHER 0x0100 /**< Other reason (can be used by verify callback) */
+#define MBEDTLS_X509_BADCERT_FUTURE 0x0200 /**< The certificate validity starts in the future. */
+#define MBEDTLS_X509_BADCRL_FUTURE 0x0400 /**< The CRL is from the future */
+#define MBEDTLS_X509_BADCERT_KEY_USAGE 0x0800 /**< Usage does not match the keyUsage extension. */
+#define MBEDTLS_X509_BADCERT_EXT_KEY_USAGE 0x1000 /**< Usage does not match the extendedKeyUsage extension. */
+#define MBEDTLS_X509_BADCERT_NS_CERT_TYPE 0x2000 /**< Usage does not match the nsCertType extension. */
+#define MBEDTLS_X509_BADCERT_BAD_MD 0x4000 /**< The certificate is signed with an unacceptable hash. */
+#define MBEDTLS_X509_BADCERT_BAD_PK 0x8000 /**< The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA). */
+#define MBEDTLS_X509_BADCERT_BAD_KEY 0x010000 /**< The certificate is signed with an unacceptable key (eg bad curve, RSA too short). */
+#define MBEDTLS_X509_BADCRL_BAD_MD 0x020000 /**< The CRL is signed with an unacceptable hash. */
+#define MBEDTLS_X509_BADCRL_BAD_PK 0x040000 /**< The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA). */
+#define MBEDTLS_X509_BADCRL_BAD_KEY 0x080000 /**< The CRL is signed with an unacceptable key (eg bad curve, RSA too short). */
+
+/** \} name X509 Verify codes */
+/** \} addtogroup x509_module */
+
+/*
+ * X.509 v3 Subject Alternative Name types.
+ * otherName [0] OtherName,
+ * rfc822Name [1] IA5String,
+ * dNSName [2] IA5String,
+ * x400Address [3] ORAddress,
+ * directoryName [4] Name,
+ * ediPartyName [5] EDIPartyName,
+ * uniformResourceIdentifier [6] IA5String,
+ * iPAddress [7] OCTET STRING,
+ * registeredID [8] OBJECT IDENTIFIER
+ */
+#define MBEDTLS_X509_SAN_OTHER_NAME 0
+#define MBEDTLS_X509_SAN_RFC822_NAME 1
+#define MBEDTLS_X509_SAN_DNS_NAME 2
+#define MBEDTLS_X509_SAN_X400_ADDRESS_NAME 3
+#define MBEDTLS_X509_SAN_DIRECTORY_NAME 4
+#define MBEDTLS_X509_SAN_EDI_PARTY_NAME 5
+#define MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER 6
+#define MBEDTLS_X509_SAN_IP_ADDRESS 7
+#define MBEDTLS_X509_SAN_REGISTERED_ID 8
+
+/*
+ * X.509 v3 Key Usage Extension flags
+ * Reminder: update mbedtls_x509_info_key_usage() when adding new flags.
+ */
+#define MBEDTLS_X509_KU_DIGITAL_SIGNATURE (0x80) /* bit 0 */
+#define MBEDTLS_X509_KU_NON_REPUDIATION (0x40) /* bit 1 */
+#define MBEDTLS_X509_KU_KEY_ENCIPHERMENT (0x20) /* bit 2 */
+#define MBEDTLS_X509_KU_DATA_ENCIPHERMENT (0x10) /* bit 3 */
+#define MBEDTLS_X509_KU_KEY_AGREEMENT (0x08) /* bit 4 */
+#define MBEDTLS_X509_KU_KEY_CERT_SIGN (0x04) /* bit 5 */
+#define MBEDTLS_X509_KU_CRL_SIGN (0x02) /* bit 6 */
+#define MBEDTLS_X509_KU_ENCIPHER_ONLY (0x01) /* bit 7 */
+#define MBEDTLS_X509_KU_DECIPHER_ONLY (0x8000) /* bit 8 */
+
+/*
+ * Netscape certificate types
+ * (http://www.mozilla.org/projects/security/pki/nss/tech-notes/tn3.html)
+ */
+
+#define MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT (0x80) /* bit 0 */
+#define MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER (0x40) /* bit 1 */
+#define MBEDTLS_X509_NS_CERT_TYPE_EMAIL (0x20) /* bit 2 */
+#define MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING (0x10) /* bit 3 */
+#define MBEDTLS_X509_NS_CERT_TYPE_RESERVED (0x08) /* bit 4 */
+#define MBEDTLS_X509_NS_CERT_TYPE_SSL_CA (0x04) /* bit 5 */
+#define MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA (0x02) /* bit 6 */
+#define MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA (0x01) /* bit 7 */
+
+/*
+ * X.509 extension types
+ *
+ * Comments refer to the status for using certificates. Status can be
+ * different for writing certificates or reading CRLs or CSRs.
+ *
+ * Those are defined in oid.h as oid.c needs them in a data structure. Since
+ * these were previously defined here, let's have aliases for compatibility.
+ */
+#define MBEDTLS_X509_EXT_AUTHORITY_KEY_IDENTIFIER MBEDTLS_OID_X509_EXT_AUTHORITY_KEY_IDENTIFIER
+#define MBEDTLS_X509_EXT_SUBJECT_KEY_IDENTIFIER MBEDTLS_OID_X509_EXT_SUBJECT_KEY_IDENTIFIER
+#define MBEDTLS_X509_EXT_KEY_USAGE MBEDTLS_OID_X509_EXT_KEY_USAGE
+#define MBEDTLS_X509_EXT_CERTIFICATE_POLICIES MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES
+#define MBEDTLS_X509_EXT_POLICY_MAPPINGS MBEDTLS_OID_X509_EXT_POLICY_MAPPINGS
+#define MBEDTLS_X509_EXT_SUBJECT_ALT_NAME MBEDTLS_OID_X509_EXT_SUBJECT_ALT_NAME /* Supported (DNS) */
+#define MBEDTLS_X509_EXT_ISSUER_ALT_NAME MBEDTLS_OID_X509_EXT_ISSUER_ALT_NAME
+#define MBEDTLS_X509_EXT_SUBJECT_DIRECTORY_ATTRS MBEDTLS_OID_X509_EXT_SUBJECT_DIRECTORY_ATTRS
+#define MBEDTLS_X509_EXT_BASIC_CONSTRAINTS MBEDTLS_OID_X509_EXT_BASIC_CONSTRAINTS /* Supported */
+#define MBEDTLS_X509_EXT_NAME_CONSTRAINTS MBEDTLS_OID_X509_EXT_NAME_CONSTRAINTS
+#define MBEDTLS_X509_EXT_POLICY_CONSTRAINTS MBEDTLS_OID_X509_EXT_POLICY_CONSTRAINTS
+#define MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE
+#define MBEDTLS_X509_EXT_CRL_DISTRIBUTION_POINTS MBEDTLS_OID_X509_EXT_CRL_DISTRIBUTION_POINTS
+#define MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY MBEDTLS_OID_X509_EXT_INIHIBIT_ANYPOLICY
+#define MBEDTLS_X509_EXT_FRESHEST_CRL MBEDTLS_OID_X509_EXT_FRESHEST_CRL
+#define MBEDTLS_X509_EXT_NS_CERT_TYPE MBEDTLS_OID_X509_EXT_NS_CERT_TYPE
+
+/*
+ * Storage format identifiers
+ * Recognized formats: PEM and DER
+ */
+#define MBEDTLS_X509_FORMAT_DER 1
+#define MBEDTLS_X509_FORMAT_PEM 2
+
+#define MBEDTLS_X509_MAX_DN_NAME_SIZE 256 /**< Maximum value size of a DN entry */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup x509_module
+ * \{ */
+
+/**
+ * \name Structures for parsing X.509 certificates, CRLs and CSRs
+ * \{
+ */
+
+/**
+ * Type-length-value structure that allows for ASN1 using DER.
+ */
+typedef mbedtls_asn1_buf mbedtls_x509_buf;
+
+/**
+ * Container for ASN1 bit strings.
+ */
+typedef mbedtls_asn1_bitstring mbedtls_x509_bitstring;
+
+/**
+ * Container for ASN1 named information objects.
+ * It allows for Relative Distinguished Names (e.g. cn=localhost,ou=code,etc.).
+ */
+typedef mbedtls_asn1_named_data mbedtls_x509_name;
+
+/**
+ * Container for a sequence of ASN.1 items
+ */
+typedef mbedtls_asn1_sequence mbedtls_x509_sequence;
+
+/*
+ * Container for the fields of the Authority Key Identifier object
+ */
+typedef struct mbedtls_x509_authority {
+ mbedtls_x509_buf keyIdentifier;
+ mbedtls_x509_sequence authorityCertIssuer;
+ mbedtls_x509_buf authorityCertSerialNumber;
+ mbedtls_x509_buf raw;
+}
+mbedtls_x509_authority;
+
+/** Container for date and time (precision in seconds). */
+typedef struct mbedtls_x509_time {
+ int year, mon, day; /**< Date. */
+ int hour, min, sec; /**< Time. */
+}
+mbedtls_x509_time;
+
+/**
+ * From RFC 5280 section 4.2.1.6:
+ * OtherName ::= SEQUENCE {
+ * type-id OBJECT IDENTIFIER,
+ * value [0] EXPLICIT ANY DEFINED BY type-id }
+ *
+ * Future versions of the library may add new fields to this structure or
+ * to its embedded union and structure.
+ */
+typedef struct mbedtls_x509_san_other_name {
+ /**
+ * The type_id is an OID as defined in RFC 5280.
+ * To check the value of the type id, you should use
+ * \p MBEDTLS_OID_CMP with a known OID mbedtls_x509_buf.
+ */
+ mbedtls_x509_buf type_id; /**< The type id. */
+ union {
+ /**
+ * From RFC 4108 section 5:
+ * HardwareModuleName ::= SEQUENCE {
+ * hwType OBJECT IDENTIFIER,
+ * hwSerialNum OCTET STRING }
+ */
+ struct {
+ mbedtls_x509_buf oid; /**< The object identifier. */
+ mbedtls_x509_buf val; /**< The named value. */
+ }
+ hardware_module_name;
+ }
+ value;
+}
+mbedtls_x509_san_other_name;
+
+/**
+ * A structure for holding the parsed Subject Alternative Name,
+ * according to type.
+ *
+ * Future versions of the library may add new fields to this structure or
+ * to its embedded union and structure.
+ */
+typedef struct mbedtls_x509_subject_alternative_name {
+ int type; /**< The SAN type, value of MBEDTLS_X509_SAN_XXX. */
+ union {
+ mbedtls_x509_san_other_name other_name;
+ mbedtls_x509_name directory_name;
+ mbedtls_x509_buf unstructured_name; /**< The buffer for the unstructured types. rfc822Name, dnsName and uniformResourceIdentifier are currently supported. */
+ }
+ san; /**< A union of the supported SAN types */
+}
+mbedtls_x509_subject_alternative_name;
+
+typedef struct mbedtls_x509_san_list {
+ mbedtls_x509_subject_alternative_name node;
+ struct mbedtls_x509_san_list *next;
+}
+mbedtls_x509_san_list;
+
+/** \} name Structures for parsing X.509 certificates, CRLs and CSRs */
+
+/**
+ * \brief Store the certificate DN in printable form into buf;
+ * no more than size characters will be written.
+ *
+ * \param buf Buffer to write to
+ * \param size Maximum size of buffer
+ * \param dn The X509 name to represent
+ *
+ * \return The length of the string written (not including the
+ * terminated nul byte), or a negative error code.
+ */
+int mbedtls_x509_dn_gets(char *buf, size_t size, const mbedtls_x509_name *dn);
+
+/**
+ * \brief Return the next relative DN in an X509 name.
+ *
+ * \note Intended use is to compare function result to dn->next
+ * in order to detect boundaries of multi-valued RDNs.
+ *
+ * \param dn Current node in the X509 name
+ *
+ * \return Pointer to the first attribute-value pair of the
+ * next RDN in sequence, or NULL if end is reached.
+ */
+static inline mbedtls_x509_name *mbedtls_x509_dn_get_next(
+ mbedtls_x509_name *dn)
+{
+ while (dn->MBEDTLS_PRIVATE(next_merged) && dn->next != NULL) {
+ dn = dn->next;
+ }
+ return dn->next;
+}
+
+/**
+ * \brief Store the certificate serial in printable form into buf;
+ * no more than size characters will be written.
+ *
+ * \param buf Buffer to write to
+ * \param size Maximum size of buffer
+ * \param serial The X509 serial to represent
+ *
+ * \return The length of the string written (not including the
+ * terminated nul byte), or a negative error code.
+ */
+int mbedtls_x509_serial_gets(char *buf, size_t size, const mbedtls_x509_buf *serial);
+
+/**
+ * \brief Compare pair of mbedtls_x509_time.
+ *
+ * \param t1 mbedtls_x509_time to compare
+ * \param t2 mbedtls_x509_time to compare
+ *
+ * \return < 0 if t1 is before t2
+ * 0 if t1 equals t2
+ * > 0 if t1 is after t2
+ */
+int mbedtls_x509_time_cmp(const mbedtls_x509_time *t1, const mbedtls_x509_time *t2);
+
+#if defined(MBEDTLS_HAVE_TIME_DATE)
+/**
+ * \brief Fill mbedtls_x509_time with provided mbedtls_time_t.
+ *
+ * \param tt mbedtls_time_t to convert
+ * \param now mbedtls_x509_time to fill with converted mbedtls_time_t
+ *
+ * \return \c 0 on success
+ * \return A non-zero return value on failure.
+ */
+int mbedtls_x509_time_gmtime(mbedtls_time_t tt, mbedtls_x509_time *now);
+#endif /* MBEDTLS_HAVE_TIME_DATE */
+
+/**
+ * \brief Check a given mbedtls_x509_time against the system time
+ * and tell if it's in the past.
+ *
+ * \note Intended usage is "if( is_past( valid_to ) ) ERROR".
+ * Hence the return value of 1 if on internal errors.
+ *
+ * \param to mbedtls_x509_time to check
+ *
+ * \return 1 if the given time is in the past or an error occurred,
+ * 0 otherwise.
+ */
+int mbedtls_x509_time_is_past(const mbedtls_x509_time *to);
+
+/**
+ * \brief Check a given mbedtls_x509_time against the system time
+ * and tell if it's in the future.
+ *
+ * \note Intended usage is "if( is_future( valid_from ) ) ERROR".
+ * Hence the return value of 1 if on internal errors.
+ *
+ * \param from mbedtls_x509_time to check
+ *
+ * \return 1 if the given time is in the future or an error occurred,
+ * 0 otherwise.
+ */
+int mbedtls_x509_time_is_future(const mbedtls_x509_time *from);
+
+/**
+ * \brief This function parses an item in the SubjectAlternativeNames
+ * extension. Please note that this function might allocate
+ * additional memory for a subject alternative name, thus
+ * mbedtls_x509_free_subject_alt_name has to be called
+ * to dispose of this additional memory afterwards.
+ *
+ * \param san_buf The buffer holding the raw data item of the subject
+ * alternative name.
+ * \param san The target structure to populate with the parsed presentation
+ * of the subject alternative name encoded in \p san_buf.
+ *
+ * \note Supported GeneralName types, as defined in RFC 5280:
+ * "rfc822Name", "dnsName", "directoryName",
+ * "uniformResourceIdentifier" and "hardware_module_name"
+ * of type "otherName", as defined in RFC 4108.
+ *
+ * \note This function should be called on a single raw data of
+ * subject alternative name. For example, after successful
+ * certificate parsing, one must iterate on every item in the
+ * \c crt->subject_alt_names sequence, and pass it to
+ * this function.
+ *
+ * \warning The target structure contains pointers to the raw data of the
+ * parsed certificate, and its lifetime is restricted by the
+ * lifetime of the certificate.
+ *
+ * \return \c 0 on success
+ * \return #MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE for an unsupported
+ * SAN type.
+ * \return Another negative value for any other failure.
+ */
+int mbedtls_x509_parse_subject_alt_name(const mbedtls_x509_buf *san_buf,
+ mbedtls_x509_subject_alternative_name *san);
+/**
+ * \brief Unallocate all data related to subject alternative name
+ *
+ * \param san SAN structure - extra memory owned by this structure will be freed
+ */
+void mbedtls_x509_free_subject_alt_name(mbedtls_x509_subject_alternative_name *san);
+
+/** \} addtogroup x509_module */
+
+/*
+ * Internal module functions. You probably do not want to use these unless you
+ * know you do.
+ */
+int mbedtls_x509_get_name(unsigned char **p, const unsigned char *end,
+ mbedtls_x509_name *cur);
+int mbedtls_x509_get_alg_null(unsigned char **p, const unsigned char *end,
+ mbedtls_x509_buf *alg);
+int mbedtls_x509_get_alg(unsigned char **p, const unsigned char *end,
+ mbedtls_x509_buf *alg, mbedtls_x509_buf *params);
+#if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT)
+int mbedtls_x509_get_rsassa_pss_params(const mbedtls_x509_buf *params,
+ mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md,
+ int *salt_len);
+#endif
+int mbedtls_x509_get_sig(unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig);
+int mbedtls_x509_get_sig_alg(const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params,
+ mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg,
+ void **sig_opts);
+int mbedtls_x509_get_time(unsigned char **p, const unsigned char *end,
+ mbedtls_x509_time *t);
+int mbedtls_x509_get_serial(unsigned char **p, const unsigned char *end,
+ mbedtls_x509_buf *serial);
+int mbedtls_x509_get_ext(unsigned char **p, const unsigned char *end,
+ mbedtls_x509_buf *ext, int tag);
+#if !defined(MBEDTLS_X509_REMOVE_INFO)
+int mbedtls_x509_sig_alg_gets(char *buf, size_t size, const mbedtls_x509_buf *sig_oid,
+ mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg,
+ const void *sig_opts);
+#endif
+int mbedtls_x509_key_size_helper(char *buf, size_t buf_size, const char *name);
+int mbedtls_x509_string_to_names(mbedtls_asn1_named_data **head, const char *name);
+int mbedtls_x509_set_extension(mbedtls_asn1_named_data **head, const char *oid, size_t oid_len,
+ int critical, const unsigned char *val,
+ size_t val_len);
+int mbedtls_x509_write_extensions(unsigned char **p, unsigned char *start,
+ mbedtls_asn1_named_data *first);
+int mbedtls_x509_write_names(unsigned char **p, unsigned char *start,
+ mbedtls_asn1_named_data *first);
+int mbedtls_x509_write_sig(unsigned char **p, unsigned char *start,
+ const char *oid, size_t oid_len,
+ unsigned char *sig, size_t size,
+ mbedtls_pk_type_t pk_alg);
+int mbedtls_x509_get_ns_cert_type(unsigned char **p,
+ const unsigned char *end,
+ unsigned char *ns_cert_type);
+int mbedtls_x509_get_key_usage(unsigned char **p,
+ const unsigned char *end,
+ unsigned int *key_usage);
+int mbedtls_x509_get_subject_alt_name(unsigned char **p,
+ const unsigned char *end,
+ mbedtls_x509_sequence *subject_alt_name);
+int mbedtls_x509_get_subject_alt_name_ext(unsigned char **p,
+ const unsigned char *end,
+ mbedtls_x509_sequence *subject_alt_name);
+int mbedtls_x509_info_subject_alt_name(char **buf, size_t *size,
+ const mbedtls_x509_sequence
+ *subject_alt_name,
+ const char *prefix);
+int mbedtls_x509_info_cert_type(char **buf, size_t *size,
+ unsigned char ns_cert_type);
+int mbedtls_x509_info_key_usage(char **buf, size_t *size,
+ unsigned int key_usage);
+
+int mbedtls_x509_write_set_san_common(mbedtls_asn1_named_data **extensions,
+ const mbedtls_x509_san_list *san_list);
+
+/**
+ * \brief This function parses a CN string as an IP address.
+ *
+ * \param cn The CN string to parse. CN string MUST be null-terminated.
+ * \param dst The target buffer to populate with the binary IP address.
+ * The buffer MUST be 16 bytes to save IPv6, and should be
+ * 4-byte aligned if the result will be used as struct in_addr.
+ * e.g. uint32_t dst[4]
+ *
+ * \note \p cn is parsed as an IPv6 address if string contains ':',
+ * else \p cn is parsed as an IPv4 address.
+ *
+ * \return Length of binary IP address; num bytes written to target.
+ * \return \c 0 on failure to parse CN string as an IP address.
+ */
+size_t mbedtls_x509_crt_parse_cn_inet_pton(const char *cn, void *dst);
+
+#define MBEDTLS_X509_SAFE_SNPRINTF \
+ do { \
+ if (ret < 0 || (size_t) ret >= n) \
+ return MBEDTLS_ERR_X509_BUFFER_TOO_SMALL; \
+ \
+ n -= (size_t) ret; \
+ p += (size_t) ret; \
+ } while (0)
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* x509.h */
diff --git a/include/mbedtls/x509_crl.h b/include/mbedtls/x509_crl.h
new file mode 100644
index 0000000..6625a44
--- /dev/null
+++ b/include/mbedtls/x509_crl.h
@@ -0,0 +1,184 @@
+/**
+ * \file x509_crl.h
+ *
+ * \brief X.509 certificate revocation list parsing
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_X509_CRL_H
+#define MBEDTLS_X509_CRL_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/x509.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup x509_module
+ * \{ */
+
+/**
+ * \name Structures and functions for parsing CRLs
+ * \{
+ */
+
+/**
+ * Certificate revocation list entry.
+ * Contains the CA-specific serial numbers and revocation dates.
+ *
+ * Some fields of this structure are publicly readable. Do not modify
+ * them except via Mbed TLS library functions: the effect of modifying
+ * those fields or the data that those fields points to is unspecified.
+ */
+typedef struct mbedtls_x509_crl_entry {
+ /** Direct access to the whole entry inside the containing buffer. */
+ mbedtls_x509_buf raw;
+ /** The serial number of the revoked certificate. */
+ mbedtls_x509_buf serial;
+ /** The revocation date of this entry. */
+ mbedtls_x509_time revocation_date;
+ /** Direct access to the list of CRL entry extensions
+ * (an ASN.1 constructed sequence).
+ *
+ * If there are no extensions, `entry_ext.len == 0` and
+ * `entry_ext.p == NULL`. */
+ mbedtls_x509_buf entry_ext;
+
+ /** Next element in the linked list of entries.
+ * \p NULL indicates the end of the list.
+ * Do not modify this field directly. */
+ struct mbedtls_x509_crl_entry *next;
+}
+mbedtls_x509_crl_entry;
+
+/**
+ * Certificate revocation list structure.
+ * Every CRL may have multiple entries.
+ */
+typedef struct mbedtls_x509_crl {
+ mbedtls_x509_buf raw; /**< The raw certificate data (DER). */
+ mbedtls_x509_buf tbs; /**< The raw certificate body (DER). The part that is To Be Signed. */
+
+ int version; /**< CRL version (1=v1, 2=v2) */
+ mbedtls_x509_buf sig_oid; /**< CRL signature type identifier */
+
+ mbedtls_x509_buf issuer_raw; /**< The raw issuer data (DER). */
+
+ mbedtls_x509_name issuer; /**< The parsed issuer data (named information object). */
+
+ mbedtls_x509_time this_update;
+ mbedtls_x509_time next_update;
+
+ mbedtls_x509_crl_entry entry; /**< The CRL entries containing the certificate revocation times for this CA. */
+
+ mbedtls_x509_buf crl_ext;
+
+ mbedtls_x509_buf MBEDTLS_PRIVATE(sig_oid2);
+ mbedtls_x509_buf MBEDTLS_PRIVATE(sig);
+ mbedtls_md_type_t MBEDTLS_PRIVATE(sig_md); /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */
+ mbedtls_pk_type_t MBEDTLS_PRIVATE(sig_pk); /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */
+ void *MBEDTLS_PRIVATE(sig_opts); /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */
+
+ /** Next element in the linked list of CRL.
+ * \p NULL indicates the end of the list.
+ * Do not modify this field directly. */
+ struct mbedtls_x509_crl *next;
+}
+mbedtls_x509_crl;
+
+/**
+ * \brief Parse a DER-encoded CRL and append it to the chained list
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param chain points to the start of the chain
+ * \param buf buffer holding the CRL data in DER format
+ * \param buflen size of the buffer
+ * (including the terminating null byte for PEM data)
+ *
+ * \return 0 if successful, or a specific X509 or PEM error code
+ */
+int mbedtls_x509_crl_parse_der(mbedtls_x509_crl *chain,
+ const unsigned char *buf, size_t buflen);
+/**
+ * \brief Parse one or more CRLs and append them to the chained list
+ *
+ * \note Multiple CRLs are accepted only if using PEM format
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param chain points to the start of the chain
+ * \param buf buffer holding the CRL data in PEM or DER format
+ * \param buflen size of the buffer
+ * (including the terminating null byte for PEM data)
+ *
+ * \return 0 if successful, or a specific X509 or PEM error code
+ */
+int mbedtls_x509_crl_parse(mbedtls_x509_crl *chain, const unsigned char *buf, size_t buflen);
+
+#if defined(MBEDTLS_FS_IO)
+/**
+ * \brief Load one or more CRLs and append them to the chained list
+ *
+ * \note Multiple CRLs are accepted only if using PEM format
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param chain points to the start of the chain
+ * \param path filename to read the CRLs from (in PEM or DER encoding)
+ *
+ * \return 0 if successful, or a specific X509 or PEM error code
+ */
+int mbedtls_x509_crl_parse_file(mbedtls_x509_crl *chain, const char *path);
+#endif /* MBEDTLS_FS_IO */
+
+#if !defined(MBEDTLS_X509_REMOVE_INFO)
+/**
+ * \brief Returns an informational string about the CRL.
+ *
+ * \param buf Buffer to write to
+ * \param size Maximum size of buffer
+ * \param prefix A line prefix
+ * \param crl The X509 CRL to represent
+ *
+ * \return The length of the string written (not including the
+ * terminated nul byte), or a negative error code.
+ */
+int mbedtls_x509_crl_info(char *buf, size_t size, const char *prefix,
+ const mbedtls_x509_crl *crl);
+#endif /* !MBEDTLS_X509_REMOVE_INFO */
+
+/**
+ * \brief Initialize a CRL (chain)
+ *
+ * \param crl CRL chain to initialize
+ */
+void mbedtls_x509_crl_init(mbedtls_x509_crl *crl);
+
+/**
+ * \brief Unallocate all CRL data
+ *
+ * \param crl CRL chain to free
+ */
+void mbedtls_x509_crl_free(mbedtls_x509_crl *crl);
+
+/** \} name Structures and functions for parsing CRLs */
+/** \} addtogroup x509_module */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* mbedtls_x509_crl.h */
diff --git a/include/mbedtls/x509_crt.h b/include/mbedtls/x509_crt.h
new file mode 100644
index 0000000..3f1a1e7
--- /dev/null
+++ b/include/mbedtls/x509_crt.h
@@ -0,0 +1,1196 @@
+/**
+ * \file x509_crt.h
+ *
+ * \brief X.509 certificate parsing and writing
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_X509_CRT_H
+#define MBEDTLS_X509_CRT_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/x509.h"
+#include "mbedtls/x509_crl.h"
+#include "mbedtls/bignum.h"
+
+/**
+ * \addtogroup x509_module
+ * \{
+ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \name Structures and functions for parsing and writing X.509 certificates
+ * \{
+ */
+
+/**
+ * Container for an X.509 certificate. The certificate may be chained.
+ *
+ * Some fields of this structure are publicly readable. Do not modify
+ * them except via Mbed TLS library functions: the effect of modifying
+ * those fields or the data that those fields points to is unspecified.
+ */
+typedef struct mbedtls_x509_crt {
+ int MBEDTLS_PRIVATE(own_buffer); /**< Indicates if \c raw is owned
+ * by the structure or not. */
+ mbedtls_x509_buf raw; /**< The raw certificate data (DER). */
+ mbedtls_x509_buf tbs; /**< The raw certificate body (DER). The part that is To Be Signed. */
+
+ int version; /**< The X.509 version. (1=v1, 2=v2, 3=v3) */
+ mbedtls_x509_buf serial; /**< Unique id for certificate issued by a specific CA. */
+ mbedtls_x509_buf sig_oid; /**< Signature algorithm, e.g. sha1RSA */
+
+ mbedtls_x509_buf issuer_raw; /**< The raw issuer data (DER). Used for quick comparison. */
+ mbedtls_x509_buf subject_raw; /**< The raw subject data (DER). Used for quick comparison. */
+
+ mbedtls_x509_name issuer; /**< The parsed issuer data (named information object). */
+ mbedtls_x509_name subject; /**< The parsed subject data (named information object). */
+
+ mbedtls_x509_time valid_from; /**< Start time of certificate validity. */
+ mbedtls_x509_time valid_to; /**< End time of certificate validity. */
+
+ mbedtls_x509_buf pk_raw;
+ mbedtls_pk_context pk; /**< Container for the public key context. */
+
+ mbedtls_x509_buf issuer_id; /**< Optional X.509 v2/v3 issuer unique identifier. */
+ mbedtls_x509_buf subject_id; /**< Optional X.509 v2/v3 subject unique identifier. */
+ mbedtls_x509_buf v3_ext; /**< Optional X.509 v3 extensions. */
+ mbedtls_x509_sequence subject_alt_names; /**< Optional list of raw entries of Subject Alternative Names extension. These can be later parsed by mbedtls_x509_parse_subject_alt_name. */
+ mbedtls_x509_buf subject_key_id; /**< Optional X.509 v3 extension subject key identifier. */
+ mbedtls_x509_authority authority_key_id; /**< Optional X.509 v3 extension authority key identifier. */
+
+ mbedtls_x509_sequence certificate_policies; /**< Optional list of certificate policies (Only anyPolicy is printed and enforced, however the rest of the policies are still listed). */
+
+ int MBEDTLS_PRIVATE(ext_types); /**< Bit string containing detected and parsed extensions */
+ int MBEDTLS_PRIVATE(ca_istrue); /**< Optional Basic Constraint extension value: 1 if this certificate belongs to a CA, 0 otherwise. */
+ int MBEDTLS_PRIVATE(max_pathlen); /**< Optional Basic Constraint extension value: The maximum path length to the root certificate. Path length is 1 higher than RFC 5280 'meaning', so 1+ */
+
+ unsigned int MBEDTLS_PRIVATE(key_usage); /**< Optional key usage extension value: See the values in x509.h */
+
+ mbedtls_x509_sequence ext_key_usage; /**< Optional list of extended key usage OIDs. */
+
+ unsigned char MBEDTLS_PRIVATE(ns_cert_type); /**< Optional Netscape certificate type extension value: See the values in x509.h */
+
+ mbedtls_x509_buf MBEDTLS_PRIVATE(sig); /**< Signature: hash of the tbs part signed with the private key. */
+ mbedtls_md_type_t MBEDTLS_PRIVATE(sig_md); /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */
+ mbedtls_pk_type_t MBEDTLS_PRIVATE(sig_pk); /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */
+ void *MBEDTLS_PRIVATE(sig_opts); /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */
+
+ /** Next certificate in the linked list that constitutes the CA chain.
+ * \p NULL indicates the end of the list.
+ * Do not modify this field directly. */
+ struct mbedtls_x509_crt *next;
+}
+mbedtls_x509_crt;
+
+/**
+ * Build flag from an algorithm/curve identifier (pk, md, ecp)
+ * Since 0 is always XXX_NONE, ignore it.
+ */
+#define MBEDTLS_X509_ID_FLAG(id) (1 << ((id) - 1))
+
+/**
+ * Security profile for certificate verification.
+ *
+ * All lists are bitfields, built by ORing flags from MBEDTLS_X509_ID_FLAG().
+ *
+ * The fields of this structure are part of the public API and can be
+ * manipulated directly by applications. Future versions of the library may
+ * add extra fields or reorder existing fields.
+ *
+ * You can create custom profiles by starting from a copy of
+ * an existing profile, such as mbedtls_x509_crt_profile_default or
+ * mbedtls_x509_ctr_profile_none and then tune it to your needs.
+ *
+ * For example to allow SHA-224 in addition to the default:
+ *
+ * mbedtls_x509_crt_profile my_profile = mbedtls_x509_crt_profile_default;
+ * my_profile.allowed_mds |= MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA224 );
+ *
+ * Or to allow only RSA-3072+ with SHA-256:
+ *
+ * mbedtls_x509_crt_profile my_profile = mbedtls_x509_crt_profile_none;
+ * my_profile.allowed_mds = MBEDTLS_X509_ID_FLAG( MBEDTLS_MD_SHA256 );
+ * my_profile.allowed_pks = MBEDTLS_X509_ID_FLAG( MBEDTLS_PK_RSA );
+ * my_profile.rsa_min_bitlen = 3072;
+ */
+typedef struct mbedtls_x509_crt_profile {
+ uint32_t allowed_mds; /**< MDs for signatures */
+ uint32_t allowed_pks; /**< PK algs for public keys;
+ * this applies to all certificates
+ * in the provided chain. */
+ uint32_t allowed_curves; /**< Elliptic curves for ECDSA */
+ uint32_t rsa_min_bitlen; /**< Minimum size for RSA keys */
+}
+mbedtls_x509_crt_profile;
+
+#define MBEDTLS_X509_CRT_VERSION_1 0
+#define MBEDTLS_X509_CRT_VERSION_2 1
+#define MBEDTLS_X509_CRT_VERSION_3 2
+
+#define MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN 20
+#define MBEDTLS_X509_RFC5280_UTC_TIME_LEN 15
+
+#if !defined(MBEDTLS_X509_MAX_FILE_PATH_LEN)
+#define MBEDTLS_X509_MAX_FILE_PATH_LEN 512
+#endif
+
+/* This macro unfolds to the concatenation of macro invocations
+ * X509_CRT_ERROR_INFO( error code,
+ * error code as string,
+ * human readable description )
+ * where X509_CRT_ERROR_INFO is defined by the user.
+ * See x509_crt.c for an example of how to use this. */
+#define MBEDTLS_X509_CRT_ERROR_INFO_LIST \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_EXPIRED, \
+ "MBEDTLS_X509_BADCERT_EXPIRED", \
+ "The certificate validity has expired") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_REVOKED, \
+ "MBEDTLS_X509_BADCERT_REVOKED", \
+ "The certificate has been revoked (is on a CRL)") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_CN_MISMATCH, \
+ "MBEDTLS_X509_BADCERT_CN_MISMATCH", \
+ "The certificate Common Name (CN) does not match with the expected CN") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_NOT_TRUSTED, \
+ "MBEDTLS_X509_BADCERT_NOT_TRUSTED", \
+ "The certificate is not correctly signed by the trusted CA") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_NOT_TRUSTED, \
+ "MBEDTLS_X509_BADCRL_NOT_TRUSTED", \
+ "The CRL is not correctly signed by the trusted CA") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_EXPIRED, \
+ "MBEDTLS_X509_BADCRL_EXPIRED", \
+ "The CRL is expired") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_MISSING, \
+ "MBEDTLS_X509_BADCERT_MISSING", \
+ "Certificate was missing") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_SKIP_VERIFY, \
+ "MBEDTLS_X509_BADCERT_SKIP_VERIFY", \
+ "Certificate verification was skipped") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_OTHER, \
+ "MBEDTLS_X509_BADCERT_OTHER", \
+ "Other reason (can be used by verify callback)") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_FUTURE, \
+ "MBEDTLS_X509_BADCERT_FUTURE", \
+ "The certificate validity starts in the future") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_FUTURE, \
+ "MBEDTLS_X509_BADCRL_FUTURE", \
+ "The CRL is from the future") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_KEY_USAGE, \
+ "MBEDTLS_X509_BADCERT_KEY_USAGE", \
+ "Usage does not match the keyUsage extension") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_EXT_KEY_USAGE, \
+ "MBEDTLS_X509_BADCERT_EXT_KEY_USAGE", \
+ "Usage does not match the extendedKeyUsage extension") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_NS_CERT_TYPE, \
+ "MBEDTLS_X509_BADCERT_NS_CERT_TYPE", \
+ "Usage does not match the nsCertType extension") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_BAD_MD, \
+ "MBEDTLS_X509_BADCERT_BAD_MD", \
+ "The certificate is signed with an unacceptable hash.") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_BAD_PK, \
+ "MBEDTLS_X509_BADCERT_BAD_PK", \
+ "The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA).") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCERT_BAD_KEY, \
+ "MBEDTLS_X509_BADCERT_BAD_KEY", \
+ "The certificate is signed with an unacceptable key (eg bad curve, RSA too short).") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_BAD_MD, \
+ "MBEDTLS_X509_BADCRL_BAD_MD", \
+ "The CRL is signed with an unacceptable hash.") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_BAD_PK, \
+ "MBEDTLS_X509_BADCRL_BAD_PK", \
+ "The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA).") \
+ X509_CRT_ERROR_INFO(MBEDTLS_X509_BADCRL_BAD_KEY, \
+ "MBEDTLS_X509_BADCRL_BAD_KEY", \
+ "The CRL is signed with an unacceptable key (eg bad curve, RSA too short).")
+
+/**
+ * Container for writing a certificate (CRT)
+ */
+typedef struct mbedtls_x509write_cert {
+ int MBEDTLS_PRIVATE(version);
+ unsigned char MBEDTLS_PRIVATE(serial)[MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN];
+ size_t MBEDTLS_PRIVATE(serial_len);
+ mbedtls_pk_context *MBEDTLS_PRIVATE(subject_key);
+ mbedtls_pk_context *MBEDTLS_PRIVATE(issuer_key);
+ mbedtls_asn1_named_data *MBEDTLS_PRIVATE(subject);
+ mbedtls_asn1_named_data *MBEDTLS_PRIVATE(issuer);
+ mbedtls_md_type_t MBEDTLS_PRIVATE(md_alg);
+ char MBEDTLS_PRIVATE(not_before)[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];
+ char MBEDTLS_PRIVATE(not_after)[MBEDTLS_X509_RFC5280_UTC_TIME_LEN + 1];
+ mbedtls_asn1_named_data *MBEDTLS_PRIVATE(extensions);
+}
+mbedtls_x509write_cert;
+
+/**
+ * \brief Set Subject Alternative Name
+ *
+ * \param ctx Certificate context to use
+ * \param san_list List of SAN values
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
+ *
+ * \note "dnsName", "uniformResourceIdentifier", "IP address",
+ * "otherName", and "DirectoryName", as defined in RFC 5280,
+ * are supported.
+ */
+int mbedtls_x509write_crt_set_subject_alternative_name(mbedtls_x509write_cert *ctx,
+ const mbedtls_x509_san_list *san_list);
+
+/**
+ * Item in a verification chain: cert and flags for it
+ */
+typedef struct {
+ mbedtls_x509_crt *MBEDTLS_PRIVATE(crt);
+ uint32_t MBEDTLS_PRIVATE(flags);
+} mbedtls_x509_crt_verify_chain_item;
+
+/**
+ * Max size of verification chain: end-entity + intermediates + trusted root
+ */
+#define MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE (MBEDTLS_X509_MAX_INTERMEDIATE_CA + 2)
+
+/**
+ * Verification chain as built by \c mbedtls_crt_verify_chain()
+ */
+typedef struct {
+ mbedtls_x509_crt_verify_chain_item MBEDTLS_PRIVATE(items)[MBEDTLS_X509_MAX_VERIFY_CHAIN_SIZE];
+ unsigned MBEDTLS_PRIVATE(len);
+
+#if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
+ /* This stores the list of potential trusted signers obtained from
+ * the CA callback used for the CRT verification, if configured.
+ * We must track it somewhere because the callback passes its
+ * ownership to the caller. */
+ mbedtls_x509_crt *MBEDTLS_PRIVATE(trust_ca_cb_result);
+#endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
+} mbedtls_x509_crt_verify_chain;
+
+#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
+
+/**
+ * \brief Context for resuming X.509 verify operations
+ */
+typedef struct {
+ /* for check_signature() */
+ mbedtls_pk_restart_ctx MBEDTLS_PRIVATE(pk);
+
+ /* for find_parent_in() */
+ mbedtls_x509_crt *MBEDTLS_PRIVATE(parent); /* non-null iff parent_in in progress */
+ mbedtls_x509_crt *MBEDTLS_PRIVATE(fallback_parent);
+ int MBEDTLS_PRIVATE(fallback_signature_is_good);
+
+ /* for find_parent() */
+ int MBEDTLS_PRIVATE(parent_is_trusted); /* -1 if find_parent is not in progress */
+
+ /* for verify_chain() */
+ enum {
+ x509_crt_rs_none,
+ x509_crt_rs_find_parent,
+ } MBEDTLS_PRIVATE(in_progress); /* none if no operation is in progress */
+ int MBEDTLS_PRIVATE(self_cnt);
+ mbedtls_x509_crt_verify_chain MBEDTLS_PRIVATE(ver_chain);
+
+} mbedtls_x509_crt_restart_ctx;
+
+#else /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
+
+/* Now we can declare functions that take a pointer to that */
+typedef void mbedtls_x509_crt_restart_ctx;
+
+#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
+
+#if defined(MBEDTLS_X509_CRT_PARSE_C)
+/**
+ * Default security profile. Should provide a good balance between security
+ * and compatibility with current deployments.
+ *
+ * This profile permits:
+ * - SHA2 hashes with at least 256 bits: SHA-256, SHA-384, SHA-512.
+ * - Elliptic curves with 255 bits and above except secp256k1.
+ * - RSA with 2048 bits and above.
+ *
+ * New minor versions of Mbed TLS may extend this profile, for example if
+ * new algorithms are added to the library. New minor versions of Mbed TLS will
+ * not reduce this profile unless serious security concerns require it.
+ */
+extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_default;
+
+/**
+ * Expected next default profile. Recommended for new deployments.
+ * Currently targets a 128-bit security level, except for allowing RSA-2048.
+ * This profile may change at any time.
+ */
+extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_next;
+
+/**
+ * NSA Suite B profile.
+ */
+extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_suiteb;
+
+/**
+ * Empty profile that allows nothing. Useful as a basis for constructing
+ * custom profiles.
+ */
+extern const mbedtls_x509_crt_profile mbedtls_x509_crt_profile_none;
+
+/**
+ * \brief Parse a single DER formatted certificate and add it
+ * to the end of the provided chained list.
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param chain The pointer to the start of the CRT chain to attach to.
+ * When parsing the first CRT in a chain, this should point
+ * to an instance of ::mbedtls_x509_crt initialized through
+ * mbedtls_x509_crt_init().
+ * \param buf The buffer holding the DER encoded certificate.
+ * \param buflen The size in Bytes of \p buf.
+ *
+ * \note This function makes an internal copy of the CRT buffer
+ * \p buf. In particular, \p buf may be destroyed or reused
+ * after this call returns. To avoid duplicating the CRT
+ * buffer (at the cost of stricter lifetime constraints),
+ * use mbedtls_x509_crt_parse_der_nocopy() instead.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_x509_crt_parse_der(mbedtls_x509_crt *chain,
+ const unsigned char *buf,
+ size_t buflen);
+
+/**
+ * \brief The type of certificate extension callbacks.
+ *
+ * Callbacks of this type are passed to and used by the
+ * mbedtls_x509_crt_parse_der_with_ext_cb() routine when
+ * it encounters either an unsupported extension or a
+ * "certificate policies" extension containing any
+ * unsupported certificate policies.
+ * Future versions of the library may invoke the callback
+ * in other cases, if and when the need arises.
+ *
+ * \param p_ctx An opaque context passed to the callback.
+ * \param crt The certificate being parsed.
+ * \param oid The OID of the extension.
+ * \param critical Whether the extension is critical.
+ * \param p Pointer to the start of the extension value
+ * (the content of the OCTET STRING).
+ * \param end End of extension value.
+ *
+ * \note The callback must fail and return a negative error code
+ * if it can not parse or does not support the extension.
+ * When the callback fails to parse a critical extension
+ * mbedtls_x509_crt_parse_der_with_ext_cb() also fails.
+ * When the callback fails to parse a non critical extension
+ * mbedtls_x509_crt_parse_der_with_ext_cb() simply skips
+ * the extension and continues parsing.
+ *
+ * \return \c 0 on success.
+ * \return A negative error code on failure.
+ */
+typedef int (*mbedtls_x509_crt_ext_cb_t)(void *p_ctx,
+ mbedtls_x509_crt const *crt,
+ mbedtls_x509_buf const *oid,
+ int critical,
+ const unsigned char *p,
+ const unsigned char *end);
+
+/**
+ * \brief Parse a single DER formatted certificate and add it
+ * to the end of the provided chained list.
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param chain The pointer to the start of the CRT chain to attach to.
+ * When parsing the first CRT in a chain, this should point
+ * to an instance of ::mbedtls_x509_crt initialized through
+ * mbedtls_x509_crt_init().
+ * \param buf The buffer holding the DER encoded certificate.
+ * \param buflen The size in Bytes of \p buf.
+ * \param make_copy When not zero this function makes an internal copy of the
+ * CRT buffer \p buf. In particular, \p buf may be destroyed
+ * or reused after this call returns.
+ * When zero this function avoids duplicating the CRT buffer
+ * by taking temporary ownership thereof until the CRT
+ * is destroyed (like mbedtls_x509_crt_parse_der_nocopy())
+ * \param cb A callback invoked for every unsupported certificate
+ * extension.
+ * \param p_ctx An opaque context passed to the callback.
+ *
+ * \note This call is functionally equivalent to
+ * mbedtls_x509_crt_parse_der(), and/or
+ * mbedtls_x509_crt_parse_der_nocopy()
+ * but it calls the callback with every unsupported
+ * certificate extension and additionally the
+ * "certificate policies" extension if it contains any
+ * unsupported certificate policies.
+ * The callback must return a negative error code if it
+ * does not know how to handle such an extension.
+ * When the callback fails to parse a critical extension
+ * mbedtls_x509_crt_parse_der_with_ext_cb() also fails.
+ * When the callback fails to parse a non critical extension
+ * mbedtls_x509_crt_parse_der_with_ext_cb() simply skips
+ * the extension and continues parsing.
+ * Future versions of the library may invoke the callback
+ * in other cases, if and when the need arises.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_x509_crt_parse_der_with_ext_cb(mbedtls_x509_crt *chain,
+ const unsigned char *buf,
+ size_t buflen,
+ int make_copy,
+ mbedtls_x509_crt_ext_cb_t cb,
+ void *p_ctx);
+
+/**
+ * \brief Parse a single DER formatted certificate and add it
+ * to the end of the provided chained list. This is a
+ * variant of mbedtls_x509_crt_parse_der() which takes
+ * temporary ownership of the CRT buffer until the CRT
+ * is destroyed.
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param chain The pointer to the start of the CRT chain to attach to.
+ * When parsing the first CRT in a chain, this should point
+ * to an instance of ::mbedtls_x509_crt initialized through
+ * mbedtls_x509_crt_init().
+ * \param buf The address of the readable buffer holding the DER encoded
+ * certificate to use. On success, this buffer must be
+ * retained and not be changed for the lifetime of the
+ * CRT chain \p chain, that is, until \p chain is destroyed
+ * through a call to mbedtls_x509_crt_free().
+ * \param buflen The size in Bytes of \p buf.
+ *
+ * \note This call is functionally equivalent to
+ * mbedtls_x509_crt_parse_der(), but it avoids creating a
+ * copy of the input buffer at the cost of stronger lifetime
+ * constraints. This is useful in constrained environments
+ * where duplication of the CRT cannot be tolerated.
+ *
+ * \return \c 0 if successful.
+ * \return A negative error code on failure.
+ */
+int mbedtls_x509_crt_parse_der_nocopy(mbedtls_x509_crt *chain,
+ const unsigned char *buf,
+ size_t buflen);
+
+/**
+ * \brief Parse one DER-encoded or one or more concatenated PEM-encoded
+ * certificates and add them to the chained list.
+ *
+ * For CRTs in PEM encoding, the function parses permissively:
+ * if at least one certificate can be parsed, the function
+ * returns the number of certificates for which parsing failed
+ * (hence \c 0 if all certificates were parsed successfully).
+ * If no certificate could be parsed, the function returns
+ * the first (negative) error encountered during parsing.
+ *
+ * PEM encoded certificates may be interleaved by other data
+ * such as human readable descriptions of their content, as
+ * long as the certificates are enclosed in the PEM specific
+ * '-----{BEGIN/END} CERTIFICATE-----' delimiters.
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param chain The chain to which to add the parsed certificates.
+ * \param buf The buffer holding the certificate data in PEM or DER format.
+ * For certificates in PEM encoding, this may be a concatenation
+ * of multiple certificates; for DER encoding, the buffer must
+ * comprise exactly one certificate.
+ * \param buflen The size of \p buf, including the terminating \c NULL byte
+ * in case of PEM encoded data.
+ *
+ * \return \c 0 if all certificates were parsed successfully.
+ * \return The (positive) number of certificates that couldn't
+ * be parsed if parsing was partly successful (see above).
+ * \return A negative X509 or PEM error code otherwise.
+ *
+ */
+int mbedtls_x509_crt_parse(mbedtls_x509_crt *chain, const unsigned char *buf, size_t buflen);
+
+#if defined(MBEDTLS_FS_IO)
+/**
+ * \brief Load one or more certificates and add them
+ * to the chained list. Parses permissively. If some
+ * certificates can be parsed, the result is the number
+ * of failed certificates it encountered. If none complete
+ * correctly, the first error is returned.
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param chain points to the start of the chain
+ * \param path filename to read the certificates from
+ *
+ * \return 0 if all certificates parsed successfully, a positive number
+ * if partly successful or a specific X509 or PEM error code
+ */
+int mbedtls_x509_crt_parse_file(mbedtls_x509_crt *chain, const char *path);
+
+/**
+ * \brief Load one or more certificate files from a path and add them
+ * to the chained list. Parses permissively. If some
+ * certificates can be parsed, the result is the number
+ * of failed certificates it encountered. If none complete
+ * correctly, the first error is returned.
+ *
+ * \param chain points to the start of the chain
+ * \param path directory / folder to read the certificate files from
+ *
+ * \return 0 if all certificates parsed successfully, a positive number
+ * if partly successful or a specific X509 or PEM error code
+ */
+int mbedtls_x509_crt_parse_path(mbedtls_x509_crt *chain, const char *path);
+
+#endif /* MBEDTLS_FS_IO */
+
+#if !defined(MBEDTLS_X509_REMOVE_INFO)
+/**
+ * \brief Returns an informational string about the
+ * certificate.
+ *
+ * \param buf Buffer to write to
+ * \param size Maximum size of buffer
+ * \param prefix A line prefix
+ * \param crt The X509 certificate to represent
+ *
+ * \return The length of the string written (not including the
+ * terminated nul byte), or a negative error code.
+ */
+int mbedtls_x509_crt_info(char *buf, size_t size, const char *prefix,
+ const mbedtls_x509_crt *crt);
+
+/**
+ * \brief Returns an informational string about the
+ * verification status of a certificate.
+ *
+ * \param buf Buffer to write to
+ * \param size Maximum size of buffer
+ * \param prefix A line prefix
+ * \param flags Verification flags created by mbedtls_x509_crt_verify()
+ *
+ * \return The length of the string written (not including the
+ * terminated nul byte), or a negative error code.
+ */
+int mbedtls_x509_crt_verify_info(char *buf, size_t size, const char *prefix,
+ uint32_t flags);
+#endif /* !MBEDTLS_X509_REMOVE_INFO */
+
+/**
+ * \brief Verify a chain of certificates.
+ *
+ * The verify callback is a user-supplied callback that
+ * can clear / modify / add flags for a certificate. If set,
+ * the verification callback is called for each
+ * certificate in the chain (from the trust-ca down to the
+ * presented crt). The parameters for the callback are:
+ * (void *parameter, mbedtls_x509_crt *crt, int certificate_depth,
+ * int *flags). With the flags representing current flags for
+ * that specific certificate and the certificate depth from
+ * the bottom (Peer cert depth = 0).
+ *
+ * All flags left after returning from the callback
+ * are also returned to the application. The function should
+ * return 0 for anything (including invalid certificates)
+ * other than fatal error, as a non-zero return code
+ * immediately aborts the verification process. For fatal
+ * errors, a specific error code should be used (different
+ * from MBEDTLS_ERR_X509_CERT_VERIFY_FAILED which should not
+ * be returned at this point), or MBEDTLS_ERR_X509_FATAL_ERROR
+ * can be used if no better code is available.
+ *
+ * \note In case verification failed, the results can be displayed
+ * using \c mbedtls_x509_crt_verify_info()
+ *
+ * \note Same as \c mbedtls_x509_crt_verify_with_profile() with the
+ * default security profile.
+ *
+ * \note It is your responsibility to provide up-to-date CRLs for
+ * all trusted CAs. If no CRL is provided for the CA that was
+ * used to sign the certificate, CRL verification is skipped
+ * silently, that is *without* setting any flag.
+ *
+ * \note The \c trust_ca list can contain two types of certificates:
+ * (1) those of trusted root CAs, so that certificates
+ * chaining up to those CAs will be trusted, and (2)
+ * self-signed end-entity certificates to be trusted (for
+ * specific peers you know) - in that case, the self-signed
+ * certificate doesn't need to have the CA bit set.
+ *
+ * \param crt The certificate chain to be verified.
+ * \param trust_ca The list of trusted CAs.
+ * \param ca_crl The list of CRLs for trusted CAs.
+ * \param cn The expected Common Name. This will be checked to be
+ * present in the certificate's subjectAltNames extension or,
+ * if this extension is absent, as a CN component in its
+ * Subject name. DNS names and IP addresses are fully
+ * supported, while the URI subtype is partially supported:
+ * only exact matching, without any normalization procedures
+ * described in 7.4 of RFC5280, will result in a positive
+ * URI verification.
+ * This may be \c NULL if the CN need not be verified.
+ * \param flags The address at which to store the result of the verification.
+ * If the verification couldn't be completed, the flag value is
+ * set to (uint32_t) -1.
+ * \param f_vrfy The verification callback to use. See the documentation
+ * of mbedtls_x509_crt_verify() for more information.
+ * \param p_vrfy The context to be passed to \p f_vrfy.
+ *
+ * \return \c 0 if the chain is valid with respect to the
+ * passed CN, CAs, CRLs and security profile.
+ * \return #MBEDTLS_ERR_X509_CERT_VERIFY_FAILED in case the
+ * certificate chain verification failed. In this case,
+ * \c *flags will have one or more
+ * \c MBEDTLS_X509_BADCERT_XXX or \c MBEDTLS_X509_BADCRL_XXX
+ * flags set.
+ * \return Another negative error code in case of a fatal error
+ * encountered during the verification process.
+ */
+int mbedtls_x509_crt_verify(mbedtls_x509_crt *crt,
+ mbedtls_x509_crt *trust_ca,
+ mbedtls_x509_crl *ca_crl,
+ const char *cn, uint32_t *flags,
+ int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
+ void *p_vrfy);
+
+/**
+ * \brief Verify a chain of certificates with respect to
+ * a configurable security profile.
+ *
+ * \note Same as \c mbedtls_x509_crt_verify(), but with explicit
+ * security profile.
+ *
+ * \note The restrictions on keys (RSA minimum size, allowed curves
+ * for ECDSA) apply to all certificates: trusted root,
+ * intermediate CAs if any, and end entity certificate.
+ *
+ * \param crt The certificate chain to be verified.
+ * \param trust_ca The list of trusted CAs.
+ * \param ca_crl The list of CRLs for trusted CAs.
+ * \param profile The security profile to use for the verification.
+ * \param cn The expected Common Name. This may be \c NULL if the
+ * CN need not be verified.
+ * \param flags The address at which to store the result of the verification.
+ * If the verification couldn't be completed, the flag value is
+ * set to (uint32_t) -1.
+ * \param f_vrfy The verification callback to use. See the documentation
+ * of mbedtls_x509_crt_verify() for more information.
+ * \param p_vrfy The context to be passed to \p f_vrfy.
+ *
+ * \return \c 0 if the chain is valid with respect to the
+ * passed CN, CAs, CRLs and security profile.
+ * \return #MBEDTLS_ERR_X509_CERT_VERIFY_FAILED in case the
+ * certificate chain verification failed. In this case,
+ * \c *flags will have one or more
+ * \c MBEDTLS_X509_BADCERT_XXX or \c MBEDTLS_X509_BADCRL_XXX
+ * flags set.
+ * \return Another negative error code in case of a fatal error
+ * encountered during the verification process.
+ */
+int mbedtls_x509_crt_verify_with_profile(mbedtls_x509_crt *crt,
+ mbedtls_x509_crt *trust_ca,
+ mbedtls_x509_crl *ca_crl,
+ const mbedtls_x509_crt_profile *profile,
+ const char *cn, uint32_t *flags,
+ int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
+ void *p_vrfy);
+
+/**
+ * \brief Restartable version of \c mbedtls_crt_verify_with_profile()
+ *
+ * \note Performs the same job as \c mbedtls_crt_verify_with_profile()
+ * but can return early and restart according to the limit
+ * set with \c mbedtls_ecp_set_max_ops() to reduce blocking.
+ *
+ * \param crt The certificate chain to be verified.
+ * \param trust_ca The list of trusted CAs.
+ * \param ca_crl The list of CRLs for trusted CAs.
+ * \param profile The security profile to use for the verification.
+ * \param cn The expected Common Name. This may be \c NULL if the
+ * CN need not be verified.
+ * \param flags The address at which to store the result of the verification.
+ * If the verification couldn't be completed, the flag value is
+ * set to (uint32_t) -1.
+ * \param f_vrfy The verification callback to use. See the documentation
+ * of mbedtls_x509_crt_verify() for more information.
+ * \param p_vrfy The context to be passed to \p f_vrfy.
+ * \param rs_ctx The restart context to use. This may be set to \c NULL
+ * to disable restartable ECC.
+ *
+ * \return See \c mbedtls_crt_verify_with_profile(), or
+ * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of
+ * operations was reached: see \c mbedtls_ecp_set_max_ops().
+ */
+int mbedtls_x509_crt_verify_restartable(mbedtls_x509_crt *crt,
+ mbedtls_x509_crt *trust_ca,
+ mbedtls_x509_crl *ca_crl,
+ const mbedtls_x509_crt_profile *profile,
+ const char *cn, uint32_t *flags,
+ int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
+ void *p_vrfy,
+ mbedtls_x509_crt_restart_ctx *rs_ctx);
+
+/**
+ * \brief The type of trusted certificate callbacks.
+ *
+ * Callbacks of this type are passed to and used by the CRT
+ * verification routine mbedtls_x509_crt_verify_with_ca_cb()
+ * when looking for trusted signers of a given certificate.
+ *
+ * On success, the callback returns a list of trusted
+ * certificates to be considered as potential signers
+ * for the input certificate.
+ *
+ * \param p_ctx An opaque context passed to the callback.
+ * \param child The certificate for which to search a potential signer.
+ * This will point to a readable certificate.
+ * \param candidate_cas The address at which to store the address of the first
+ * entry in the generated linked list of candidate signers.
+ * This will not be \c NULL.
+ *
+ * \note The callback must only return a non-zero value on a
+ * fatal error. If, in contrast, the search for a potential
+ * signer completes without a single candidate, the
+ * callback must return \c 0 and set \c *candidate_cas
+ * to \c NULL.
+ *
+ * \return \c 0 on success. In this case, \c *candidate_cas points
+ * to a heap-allocated linked list of instances of
+ * ::mbedtls_x509_crt, and ownership of this list is passed
+ * to the caller.
+ * \return A negative error code on failure.
+ */
+typedef int (*mbedtls_x509_crt_ca_cb_t)(void *p_ctx,
+ mbedtls_x509_crt const *child,
+ mbedtls_x509_crt **candidate_cas);
+
+#if defined(MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK)
+/**
+ * \brief Version of \c mbedtls_x509_crt_verify_with_profile() which
+ * uses a callback to acquire the list of trusted CA
+ * certificates.
+ *
+ * \param crt The certificate chain to be verified.
+ * \param f_ca_cb The callback to be used to query for potential signers
+ * of a given child certificate. See the documentation of
+ * ::mbedtls_x509_crt_ca_cb_t for more information.
+ * \param p_ca_cb The opaque context to be passed to \p f_ca_cb.
+ * \param profile The security profile for the verification.
+ * \param cn The expected Common Name. This may be \c NULL if the
+ * CN need not be verified.
+ * \param flags The address at which to store the result of the verification.
+ * If the verification couldn't be completed, the flag value is
+ * set to (uint32_t) -1.
+ * \param f_vrfy The verification callback to use. See the documentation
+ * of mbedtls_x509_crt_verify() for more information.
+ * \param p_vrfy The context to be passed to \p f_vrfy.
+ *
+ * \return See \c mbedtls_crt_verify_with_profile().
+ */
+int mbedtls_x509_crt_verify_with_ca_cb(mbedtls_x509_crt *crt,
+ mbedtls_x509_crt_ca_cb_t f_ca_cb,
+ void *p_ca_cb,
+ const mbedtls_x509_crt_profile *profile,
+ const char *cn, uint32_t *flags,
+ int (*f_vrfy)(void *, mbedtls_x509_crt *, int, uint32_t *),
+ void *p_vrfy);
+
+#endif /* MBEDTLS_X509_TRUSTED_CERTIFICATE_CALLBACK */
+
+/**
+ * \brief Check usage of certificate against keyUsage extension.
+ *
+ * \param crt Leaf certificate used.
+ * \param usage Intended usage(s) (eg MBEDTLS_X509_KU_KEY_ENCIPHERMENT
+ * before using the certificate to perform an RSA key
+ * exchange).
+ *
+ * \note Except for decipherOnly and encipherOnly, a bit set in the
+ * usage argument means this bit MUST be set in the
+ * certificate. For decipherOnly and encipherOnly, it means
+ * that bit MAY be set.
+ *
+ * \return 0 is these uses of the certificate are allowed,
+ * MBEDTLS_ERR_X509_BAD_INPUT_DATA if the keyUsage extension
+ * is present but does not match the usage argument.
+ *
+ * \note You should only call this function on leaf certificates, on
+ * (intermediate) CAs the keyUsage extension is automatically
+ * checked by \c mbedtls_x509_crt_verify().
+ */
+int mbedtls_x509_crt_check_key_usage(const mbedtls_x509_crt *crt,
+ unsigned int usage);
+
+/**
+ * \brief Check usage of certificate against extendedKeyUsage.
+ *
+ * \param crt Leaf certificate used.
+ * \param usage_oid Intended usage (eg MBEDTLS_OID_SERVER_AUTH or
+ * MBEDTLS_OID_CLIENT_AUTH).
+ * \param usage_len Length of usage_oid (eg given by MBEDTLS_OID_SIZE()).
+ *
+ * \return 0 if this use of the certificate is allowed,
+ * MBEDTLS_ERR_X509_BAD_INPUT_DATA if not.
+ *
+ * \note Usually only makes sense on leaf certificates.
+ */
+int mbedtls_x509_crt_check_extended_key_usage(const mbedtls_x509_crt *crt,
+ const char *usage_oid,
+ size_t usage_len);
+
+#if defined(MBEDTLS_X509_CRL_PARSE_C)
+/**
+ * \brief Verify the certificate revocation status
+ *
+ * \param crt a certificate to be verified
+ * \param crl the CRL to verify against
+ *
+ * \return 1 if the certificate is revoked, 0 otherwise
+ *
+ */
+int mbedtls_x509_crt_is_revoked(const mbedtls_x509_crt *crt, const mbedtls_x509_crl *crl);
+#endif /* MBEDTLS_X509_CRL_PARSE_C */
+
+/**
+ * \brief Initialize a certificate (chain)
+ *
+ * \param crt Certificate chain to initialize
+ */
+void mbedtls_x509_crt_init(mbedtls_x509_crt *crt);
+
+/**
+ * \brief Unallocate all certificate data
+ *
+ * \param crt Certificate chain to free
+ */
+void mbedtls_x509_crt_free(mbedtls_x509_crt *crt);
+
+#if defined(MBEDTLS_ECDSA_C) && defined(MBEDTLS_ECP_RESTARTABLE)
+/**
+ * \brief Initialize a restart context
+ */
+void mbedtls_x509_crt_restart_init(mbedtls_x509_crt_restart_ctx *ctx);
+
+/**
+ * \brief Free the components of a restart context
+ */
+void mbedtls_x509_crt_restart_free(mbedtls_x509_crt_restart_ctx *ctx);
+#endif /* MBEDTLS_ECDSA_C && MBEDTLS_ECP_RESTARTABLE */
+#endif /* MBEDTLS_X509_CRT_PARSE_C */
+
+/**
+ * \brief Query certificate for given extension type
+ *
+ * \param[in] ctx Certificate context to be queried, must not be \c NULL
+ * \param ext_type Extension type being queried for, must be a valid
+ * extension type. Must be one of the MBEDTLS_X509_EXT_XXX
+ * values
+ *
+ * \return 0 if the given extension type is not present,
+ * non-zero otherwise
+ */
+static inline int mbedtls_x509_crt_has_ext_type(const mbedtls_x509_crt *ctx,
+ int ext_type)
+{
+ return ctx->MBEDTLS_PRIVATE(ext_types) & ext_type;
+}
+
+/** \} name Structures and functions for parsing and writing X.509 certificates */
+
+#if defined(MBEDTLS_X509_CRT_WRITE_C)
+/**
+ * \brief Initialize a CRT writing context
+ *
+ * \param ctx CRT context to initialize
+ */
+void mbedtls_x509write_crt_init(mbedtls_x509write_cert *ctx);
+
+/**
+ * \brief Set the version for a Certificate
+ * Default: MBEDTLS_X509_CRT_VERSION_3
+ *
+ * \param ctx CRT context to use
+ * \param version version to set (MBEDTLS_X509_CRT_VERSION_1, MBEDTLS_X509_CRT_VERSION_2 or
+ * MBEDTLS_X509_CRT_VERSION_3)
+ */
+void mbedtls_x509write_crt_set_version(mbedtls_x509write_cert *ctx, int version);
+
+#if defined(MBEDTLS_BIGNUM_C) && !defined(MBEDTLS_DEPRECATED_REMOVED)
+/**
+ * \brief Set the serial number for a Certificate.
+ *
+ * \deprecated This function is deprecated and will be removed in a
+ * future version of the library. Please use
+ * mbedtls_x509write_crt_set_serial_raw() instead.
+ *
+ * \note Even though the MBEDTLS_BIGNUM_C guard looks redundant since
+ * X509 depends on PK and PK depends on BIGNUM, this emphasizes
+ * a direct dependency between X509 and BIGNUM which is going
+ * to be deprecated in the future.
+ *
+ * \param ctx CRT context to use
+ * \param serial serial number to set
+ *
+ * \return 0 if successful
+ */
+int MBEDTLS_DEPRECATED mbedtls_x509write_crt_set_serial(
+ mbedtls_x509write_cert *ctx, const mbedtls_mpi *serial);
+#endif // MBEDTLS_BIGNUM_C && !MBEDTLS_DEPRECATED_REMOVED
+
+/**
+ * \brief Set the serial number for a Certificate.
+ *
+ * \param ctx CRT context to use
+ * \param serial A raw array of bytes containing the serial number in big
+ * endian format
+ * \param serial_len Length of valid bytes (expressed in bytes) in \p serial
+ * input buffer
+ *
+ * \return 0 if successful, or
+ * MBEDTLS_ERR_X509_BAD_INPUT_DATA if the provided input buffer
+ * is too big (longer than MBEDTLS_X509_RFC5280_MAX_SERIAL_LEN)
+ */
+int mbedtls_x509write_crt_set_serial_raw(mbedtls_x509write_cert *ctx,
+ unsigned char *serial, size_t serial_len);
+
+/**
+ * \brief Set the validity period for a Certificate
+ * Timestamps should be in string format for UTC timezone
+ * i.e. "YYYYMMDDhhmmss"
+ * e.g. "20131231235959" for December 31st 2013
+ * at 23:59:59
+ *
+ * \param ctx CRT context to use
+ * \param not_before not_before timestamp
+ * \param not_after not_after timestamp
+ *
+ * \return 0 if timestamp was parsed successfully, or
+ * a specific error code
+ */
+int mbedtls_x509write_crt_set_validity(mbedtls_x509write_cert *ctx, const char *not_before,
+ const char *not_after);
+
+/**
+ * \brief Set the issuer name for a Certificate
+ * Issuer names should contain a comma-separated list
+ * of OID types and values:
+ * e.g. "C=UK,O=ARM,CN=Mbed TLS CA"
+ *
+ * \param ctx CRT context to use
+ * \param issuer_name issuer name to set
+ *
+ * \return 0 if issuer name was parsed successfully, or
+ * a specific error code
+ */
+int mbedtls_x509write_crt_set_issuer_name(mbedtls_x509write_cert *ctx,
+ const char *issuer_name);
+
+/**
+ * \brief Set the subject name for a Certificate
+ * Subject names should contain a comma-separated list
+ * of OID types and values:
+ * e.g. "C=UK,O=ARM,CN=Mbed TLS Server 1"
+ *
+ * \param ctx CRT context to use
+ * \param subject_name subject name to set
+ *
+ * \return 0 if subject name was parsed successfully, or
+ * a specific error code
+ */
+int mbedtls_x509write_crt_set_subject_name(mbedtls_x509write_cert *ctx,
+ const char *subject_name);
+
+/**
+ * \brief Set the subject public key for the certificate
+ *
+ * \param ctx CRT context to use
+ * \param key public key to include
+ */
+void mbedtls_x509write_crt_set_subject_key(mbedtls_x509write_cert *ctx, mbedtls_pk_context *key);
+
+/**
+ * \brief Set the issuer key used for signing the certificate
+ *
+ * \param ctx CRT context to use
+ * \param key private key to sign with
+ */
+void mbedtls_x509write_crt_set_issuer_key(mbedtls_x509write_cert *ctx, mbedtls_pk_context *key);
+
+/**
+ * \brief Set the MD algorithm to use for the signature
+ * (e.g. MBEDTLS_MD_SHA1)
+ *
+ * \param ctx CRT context to use
+ * \param md_alg MD algorithm to use
+ */
+void mbedtls_x509write_crt_set_md_alg(mbedtls_x509write_cert *ctx, mbedtls_md_type_t md_alg);
+
+/**
+ * \brief Generic function to add to or replace an extension in the
+ * CRT
+ *
+ * \param ctx CRT context to use
+ * \param oid OID of the extension
+ * \param oid_len length of the OID
+ * \param critical if the extension is critical (per the RFC's definition)
+ * \param val value of the extension OCTET STRING
+ * \param val_len length of the value data
+ *
+ * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
+ */
+int mbedtls_x509write_crt_set_extension(mbedtls_x509write_cert *ctx,
+ const char *oid, size_t oid_len,
+ int critical,
+ const unsigned char *val, size_t val_len);
+
+/**
+ * \brief Set the basicConstraints extension for a CRT
+ *
+ * \param ctx CRT context to use
+ * \param is_ca is this a CA certificate
+ * \param max_pathlen maximum length of certificate chains below this
+ * certificate (only for CA certificates, -1 is
+ * unlimited)
+ *
+ * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
+ */
+int mbedtls_x509write_crt_set_basic_constraints(mbedtls_x509write_cert *ctx,
+ int is_ca, int max_pathlen);
+
+#if defined(MBEDTLS_MD_CAN_SHA1)
+/**
+ * \brief Set the subjectKeyIdentifier extension for a CRT
+ * Requires that mbedtls_x509write_crt_set_subject_key() has been
+ * called before
+ *
+ * \param ctx CRT context to use
+ *
+ * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
+ */
+int mbedtls_x509write_crt_set_subject_key_identifier(mbedtls_x509write_cert *ctx);
+
+/**
+ * \brief Set the authorityKeyIdentifier extension for a CRT
+ * Requires that mbedtls_x509write_crt_set_issuer_key() has been
+ * called before
+ *
+ * \param ctx CRT context to use
+ *
+ * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
+ */
+int mbedtls_x509write_crt_set_authority_key_identifier(mbedtls_x509write_cert *ctx);
+#endif /* MBEDTLS_MD_CAN_SHA1 */
+
+/**
+ * \brief Set the Key Usage Extension flags
+ * (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN)
+ *
+ * \param ctx CRT context to use
+ * \param key_usage key usage flags to set
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
+ */
+int mbedtls_x509write_crt_set_key_usage(mbedtls_x509write_cert *ctx,
+ unsigned int key_usage);
+
+/**
+ * \brief Set the Extended Key Usage Extension
+ * (e.g. MBEDTLS_OID_SERVER_AUTH)
+ *
+ * \param ctx CRT context to use
+ * \param exts extended key usage extensions to set, a sequence of
+ * MBEDTLS_ASN1_OID objects
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
+ */
+int mbedtls_x509write_crt_set_ext_key_usage(mbedtls_x509write_cert *ctx,
+ const mbedtls_asn1_sequence *exts);
+
+/**
+ * \brief Set the Netscape Cert Type flags
+ * (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL)
+ *
+ * \param ctx CRT context to use
+ * \param ns_cert_type Netscape Cert Type flags to set
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
+ */
+int mbedtls_x509write_crt_set_ns_cert_type(mbedtls_x509write_cert *ctx,
+ unsigned char ns_cert_type);
+
+/**
+ * \brief Free the contents of a CRT write context
+ *
+ * \param ctx CRT context to free
+ */
+void mbedtls_x509write_crt_free(mbedtls_x509write_cert *ctx);
+
+/**
+ * \brief Write a built up certificate to a X509 DER structure
+ * Note: data is written at the end of the buffer! Use the
+ * return value to determine where you should start
+ * using the buffer
+ *
+ * \param ctx certificate to write away
+ * \param buf buffer to write to
+ * \param size size of the buffer
+ * \param f_rng RNG function. This must not be \c NULL.
+ * \param p_rng RNG parameter
+ *
+ * \return length of data written if successful, or a specific
+ * error code
+ *
+ * \note \p f_rng is used for the signature operation.
+ */
+int mbedtls_x509write_crt_der(mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+#if defined(MBEDTLS_PEM_WRITE_C)
+/**
+ * \brief Write a built up certificate to a X509 PEM string
+ *
+ * \param ctx certificate to write away
+ * \param buf buffer to write to
+ * \param size size of the buffer
+ * \param f_rng RNG function. This must not be \c NULL.
+ * \param p_rng RNG parameter
+ *
+ * \return 0 if successful, or a specific error code
+ *
+ * \note \p f_rng is used for the signature operation.
+ */
+int mbedtls_x509write_crt_pem(mbedtls_x509write_cert *ctx, unsigned char *buf, size_t size,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+#endif /* MBEDTLS_PEM_WRITE_C */
+#endif /* MBEDTLS_X509_CRT_WRITE_C */
+
+/** \} addtogroup x509_module */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* mbedtls_x509_crt.h */
diff --git a/include/mbedtls/x509_csr.h b/include/mbedtls/x509_csr.h
new file mode 100644
index 0000000..e54010b
--- /dev/null
+++ b/include/mbedtls/x509_csr.h
@@ -0,0 +1,319 @@
+/**
+ * \file x509_csr.h
+ *
+ * \brief X.509 certificate signing request parsing and writing
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef MBEDTLS_X509_CSR_H
+#define MBEDTLS_X509_CSR_H
+#include "mbedtls/private_access.h"
+
+#include "mbedtls/build_info.h"
+
+#include "mbedtls/x509.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/**
+ * \addtogroup x509_module
+ * \{ */
+
+/**
+ * \name Structures and functions for X.509 Certificate Signing Requests (CSR)
+ * \{
+ */
+
+/**
+ * Certificate Signing Request (CSR) structure.
+ *
+ * Some fields of this structure are publicly readable. Do not modify
+ * them except via Mbed TLS library functions: the effect of modifying
+ * those fields or the data that those fields point to is unspecified.
+ */
+typedef struct mbedtls_x509_csr {
+ mbedtls_x509_buf raw; /**< The raw CSR data (DER). */
+ mbedtls_x509_buf cri; /**< The raw CertificateRequestInfo body (DER). */
+
+ int version; /**< CSR version (1=v1). */
+
+ mbedtls_x509_buf subject_raw; /**< The raw subject data (DER). */
+ mbedtls_x509_name subject; /**< The parsed subject data (named information object). */
+
+ mbedtls_pk_context pk; /**< Container for the public key context. */
+
+ unsigned int key_usage; /**< Optional key usage extension value: See the values in x509.h */
+ unsigned char ns_cert_type; /**< Optional Netscape certificate type extension value: See the values in x509.h */
+ mbedtls_x509_sequence subject_alt_names; /**< Optional list of raw entries of Subject Alternative Names extension. These can be later parsed by mbedtls_x509_parse_subject_alt_name. */
+
+ int MBEDTLS_PRIVATE(ext_types); /**< Bit string containing detected and parsed extensions */
+
+ mbedtls_x509_buf sig_oid;
+ mbedtls_x509_buf MBEDTLS_PRIVATE(sig);
+ mbedtls_md_type_t MBEDTLS_PRIVATE(sig_md); /**< Internal representation of the MD algorithm of the signature algorithm, e.g. MBEDTLS_MD_SHA256 */
+ mbedtls_pk_type_t MBEDTLS_PRIVATE(sig_pk); /**< Internal representation of the Public Key algorithm of the signature algorithm, e.g. MBEDTLS_PK_RSA */
+ void *MBEDTLS_PRIVATE(sig_opts); /**< Signature options to be passed to mbedtls_pk_verify_ext(), e.g. for RSASSA-PSS */
+}
+mbedtls_x509_csr;
+
+/**
+ * Container for writing a CSR
+ */
+typedef struct mbedtls_x509write_csr {
+ mbedtls_pk_context *MBEDTLS_PRIVATE(key);
+ mbedtls_asn1_named_data *MBEDTLS_PRIVATE(subject);
+ mbedtls_md_type_t MBEDTLS_PRIVATE(md_alg);
+ mbedtls_asn1_named_data *MBEDTLS_PRIVATE(extensions);
+}
+mbedtls_x509write_csr;
+
+#if defined(MBEDTLS_X509_CSR_PARSE_C)
+/**
+ * \brief Load a Certificate Signing Request (CSR) in DER format
+ *
+ * \note CSR attributes (if any) are currently silently ignored.
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param csr CSR context to fill
+ * \param buf buffer holding the CRL data
+ * \param buflen size of the buffer
+ *
+ * \return 0 if successful, or a specific X509 error code
+ */
+int mbedtls_x509_csr_parse_der(mbedtls_x509_csr *csr,
+ const unsigned char *buf, size_t buflen);
+
+/**
+ * \brief Load a Certificate Signing Request (CSR), DER or PEM format
+ *
+ * \note See notes for \c mbedtls_x509_csr_parse_der()
+ *
+ * \note If #MBEDTLS_USE_PSA_CRYPTO is enabled, the PSA crypto
+ * subsystem must have been initialized by calling
+ * psa_crypto_init() before calling this function.
+ *
+ * \param csr CSR context to fill
+ * \param buf buffer holding the CRL data
+ * \param buflen size of the buffer
+ * (including the terminating null byte for PEM data)
+ *
+ * \return 0 if successful, or a specific X509 or PEM error code
+ */
+int mbedtls_x509_csr_parse(mbedtls_x509_csr *csr, const unsigned char *buf, size_t buflen);
+
+#if defined(MBEDTLS_FS_IO)
+/**
+ * \brief Load a Certificate Signing Request (CSR)
+ *
+ * \note See notes for \c mbedtls_x509_csr_parse()
+ *
+ * \param csr CSR context to fill
+ * \param path filename to read the CSR from
+ *
+ * \return 0 if successful, or a specific X509 or PEM error code
+ */
+int mbedtls_x509_csr_parse_file(mbedtls_x509_csr *csr, const char *path);
+#endif /* MBEDTLS_FS_IO */
+
+#if !defined(MBEDTLS_X509_REMOVE_INFO)
+/**
+ * \brief Returns an informational string about the
+ * CSR.
+ *
+ * \param buf Buffer to write to
+ * \param size Maximum size of buffer
+ * \param prefix A line prefix
+ * \param csr The X509 CSR to represent
+ *
+ * \return The length of the string written (not including the
+ * terminated nul byte), or a negative error code.
+ */
+int mbedtls_x509_csr_info(char *buf, size_t size, const char *prefix,
+ const mbedtls_x509_csr *csr);
+#endif /* !MBEDTLS_X509_REMOVE_INFO */
+
+/**
+ * \brief Initialize a CSR
+ *
+ * \param csr CSR to initialize
+ */
+void mbedtls_x509_csr_init(mbedtls_x509_csr *csr);
+
+/**
+ * \brief Unallocate all CSR data
+ *
+ * \param csr CSR to free
+ */
+void mbedtls_x509_csr_free(mbedtls_x509_csr *csr);
+#endif /* MBEDTLS_X509_CSR_PARSE_C */
+
+/** \} name Structures and functions for X.509 Certificate Signing Requests (CSR) */
+
+#if defined(MBEDTLS_X509_CSR_WRITE_C)
+/**
+ * \brief Initialize a CSR context
+ *
+ * \param ctx CSR context to initialize
+ */
+void mbedtls_x509write_csr_init(mbedtls_x509write_csr *ctx);
+
+/**
+ * \brief Set the subject name for a CSR
+ * Subject names should contain a comma-separated list
+ * of OID types and values:
+ * e.g. "C=UK,O=ARM,CN=Mbed TLS Server 1"
+ *
+ * \param ctx CSR context to use
+ * \param subject_name subject name to set
+ *
+ * \return 0 if subject name was parsed successfully, or
+ * a specific error code
+ */
+int mbedtls_x509write_csr_set_subject_name(mbedtls_x509write_csr *ctx,
+ const char *subject_name);
+
+/**
+ * \brief Set the key for a CSR (public key will be included,
+ * private key used to sign the CSR when writing it)
+ *
+ * \param ctx CSR context to use
+ * \param key Asymmetric key to include
+ */
+void mbedtls_x509write_csr_set_key(mbedtls_x509write_csr *ctx, mbedtls_pk_context *key);
+
+/**
+ * \brief Set the MD algorithm to use for the signature
+ * (e.g. MBEDTLS_MD_SHA1)
+ *
+ * \param ctx CSR context to use
+ * \param md_alg MD algorithm to use
+ */
+void mbedtls_x509write_csr_set_md_alg(mbedtls_x509write_csr *ctx, mbedtls_md_type_t md_alg);
+
+/**
+ * \brief Set the Key Usage Extension flags
+ * (e.g. MBEDTLS_X509_KU_DIGITAL_SIGNATURE | MBEDTLS_X509_KU_KEY_CERT_SIGN)
+ *
+ * \param ctx CSR context to use
+ * \param key_usage key usage flags to set
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
+ *
+ * \note The <code>decipherOnly</code> flag from the Key Usage
+ * extension is represented by bit 8 (i.e.
+ * <code>0x8000</code>), which cannot typically be represented
+ * in an unsigned char. Therefore, the flag
+ * <code>decipherOnly</code> (i.e.
+ * #MBEDTLS_X509_KU_DECIPHER_ONLY) cannot be set using this
+ * function.
+ */
+int mbedtls_x509write_csr_set_key_usage(mbedtls_x509write_csr *ctx, unsigned char key_usage);
+
+/**
+ * \brief Set Subject Alternative Name
+ *
+ * \param ctx CSR context to use
+ * \param san_list List of SAN values
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
+ *
+ * \note Only "dnsName", "uniformResourceIdentifier" and "otherName",
+ * as defined in RFC 5280, are supported.
+ */
+int mbedtls_x509write_csr_set_subject_alternative_name(mbedtls_x509write_csr *ctx,
+ const mbedtls_x509_san_list *san_list);
+
+/**
+ * \brief Set the Netscape Cert Type flags
+ * (e.g. MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT | MBEDTLS_X509_NS_CERT_TYPE_EMAIL)
+ *
+ * \param ctx CSR context to use
+ * \param ns_cert_type Netscape Cert Type flags to set
+ *
+ * \return 0 if successful, or MBEDTLS_ERR_X509_ALLOC_FAILED
+ */
+int mbedtls_x509write_csr_set_ns_cert_type(mbedtls_x509write_csr *ctx,
+ unsigned char ns_cert_type);
+
+/**
+ * \brief Generic function to add to or replace an extension in the
+ * CSR
+ *
+ * \param ctx CSR context to use
+ * \param oid OID of the extension
+ * \param oid_len length of the OID
+ * \param critical Set to 1 to mark the extension as critical, 0 otherwise.
+ * \param val value of the extension OCTET STRING
+ * \param val_len length of the value data
+ *
+ * \return 0 if successful, or a MBEDTLS_ERR_X509_ALLOC_FAILED
+ */
+int mbedtls_x509write_csr_set_extension(mbedtls_x509write_csr *ctx,
+ const char *oid, size_t oid_len,
+ int critical,
+ const unsigned char *val, size_t val_len);
+
+/**
+ * \brief Free the contents of a CSR context
+ *
+ * \param ctx CSR context to free
+ */
+void mbedtls_x509write_csr_free(mbedtls_x509write_csr *ctx);
+
+/**
+ * \brief Write a CSR (Certificate Signing Request) to a
+ * DER structure
+ * Note: data is written at the end of the buffer! Use the
+ * return value to determine where you should start
+ * using the buffer
+ *
+ * \param ctx CSR to write away
+ * \param buf buffer to write to
+ * \param size size of the buffer
+ * \param f_rng RNG function. This must not be \c NULL.
+ * \param p_rng RNG parameter
+ *
+ * \return length of data written if successful, or a specific
+ * error code
+ *
+ * \note \p f_rng is used for the signature operation.
+ */
+int mbedtls_x509write_csr_der(mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+
+#if defined(MBEDTLS_PEM_WRITE_C)
+/**
+ * \brief Write a CSR (Certificate Signing Request) to a
+ * PEM string
+ *
+ * \param ctx CSR to write away
+ * \param buf buffer to write to
+ * \param size size of the buffer
+ * \param f_rng RNG function. This must not be \c NULL.
+ * \param p_rng RNG parameter
+ *
+ * \return 0 if successful, or a specific error code
+ *
+ * \note \p f_rng is used for the signature operation.
+ */
+int mbedtls_x509write_csr_pem(mbedtls_x509write_csr *ctx, unsigned char *buf, size_t size,
+ int (*f_rng)(void *, unsigned char *, size_t),
+ void *p_rng);
+#endif /* MBEDTLS_PEM_WRITE_C */
+#endif /* MBEDTLS_X509_CSR_WRITE_C */
+
+/** \} addtogroup x509_module */
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* mbedtls_x509_csr.h */
diff --git a/include/psa/build_info.h b/include/psa/build_info.h
new file mode 100644
index 0000000..3ee6cd7
--- /dev/null
+++ b/include/psa/build_info.h
@@ -0,0 +1,20 @@
+/**
+ * \file psa/build_info.h
+ *
+ * \brief Build-time PSA configuration info
+ *
+ * Include this file if you need to depend on the
+ * configuration options defined in mbedtls_config.h or MBEDTLS_CONFIG_FILE
+ * in PSA cryptography core specific files.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_BUILD_INFO_H
+#define PSA_CRYPTO_BUILD_INFO_H
+
+#include "mbedtls/build_info.h"
+
+#endif /* PSA_CRYPTO_BUILD_INFO_H */
diff --git a/include/psa/crypto.h b/include/psa/crypto.h
new file mode 100644
index 0000000..fe10ee0
--- /dev/null
+++ b/include/psa/crypto.h
@@ -0,0 +1,4685 @@
+/**
+ * \file psa/crypto.h
+ * \brief Platform Security Architecture cryptography module
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_H
+#define PSA_CRYPTO_H
+
+#if defined(MBEDTLS_PSA_CRYPTO_PLATFORM_FILE)
+#include MBEDTLS_PSA_CRYPTO_PLATFORM_FILE
+#else
+#include "crypto_platform.h"
+#endif
+
+#include <stddef.h>
+
+#ifdef __DOXYGEN_ONLY__
+/* This __DOXYGEN_ONLY__ block contains mock definitions for things that
+ * must be defined in the crypto_platform.h header. These mock definitions
+ * are present in this file as a convenience to generate pretty-printed
+ * documentation that includes those definitions. */
+
+/** \defgroup platform Implementation-specific definitions
+ * @{
+ */
+
+/**@}*/
+#endif /* __DOXYGEN_ONLY__ */
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* The file "crypto_types.h" declares types that encode errors,
+ * algorithms, key types, policies, etc. */
+#include "crypto_types.h"
+
+/** \defgroup version API version
+ * @{
+ */
+
+/**
+ * The major version of this implementation of the PSA Crypto API
+ */
+#define PSA_CRYPTO_API_VERSION_MAJOR 1
+
+/**
+ * The minor version of this implementation of the PSA Crypto API
+ */
+#define PSA_CRYPTO_API_VERSION_MINOR 0
+
+/**@}*/
+
+/* The file "crypto_values.h" declares macros to build and analyze values
+ * of integral types defined in "crypto_types.h". */
+#include "crypto_values.h"
+
+/** \defgroup initialization Library initialization
+ * @{
+ */
+
+/**
+ * \brief Library initialization.
+ *
+ * Applications must call this function before calling any other
+ * function in this module.
+ *
+ * Applications may call this function more than once. Once a call
+ * succeeds, subsequent calls are guaranteed to succeed.
+ *
+ * If the application calls other functions before calling psa_crypto_init(),
+ * the behavior is undefined. Implementations are encouraged to either perform
+ * the operation as if the library had been initialized or to return
+ * #PSA_ERROR_BAD_STATE or some other applicable error. In particular,
+ * implementations should not return a success status if the lack of
+ * initialization may have security implications, for example due to improper
+ * seeding of the random number generator.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ */
+psa_status_t psa_crypto_init(void);
+
+/**@}*/
+
+/** \addtogroup attributes
+ * @{
+ */
+
+/** \def PSA_KEY_ATTRIBUTES_INIT
+ *
+ * This macro returns a suitable initializer for a key attribute structure
+ * of type #psa_key_attributes_t.
+ */
+
+/** Return an initial value for a key attributes structure.
+ */
+static psa_key_attributes_t psa_key_attributes_init(void);
+
+/** Declare a key as persistent and set its key identifier.
+ *
+ * If the attribute structure currently declares the key as volatile (which
+ * is the default content of an attribute structure), this function sets
+ * the lifetime attribute to #PSA_KEY_LIFETIME_PERSISTENT.
+ *
+ * This function does not access storage, it merely stores the given
+ * value in the structure.
+ * The persistent key will be written to storage when the attribute
+ * structure is passed to a key creation function such as
+ * psa_import_key(), psa_generate_key(),
+ * psa_key_derivation_output_key() or psa_copy_key().
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate each of its arguments exactly once.
+ *
+ * \param[out] attributes The attribute structure to write to.
+ * \param key The persistent identifier for the key.
+ */
+static void psa_set_key_id(psa_key_attributes_t *attributes,
+ mbedtls_svc_key_id_t key);
+
+#ifdef MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER
+/** Set the owner identifier of a key.
+ *
+ * When key identifiers encode key owner identifiers, psa_set_key_id() does
+ * not allow to define in key attributes the owner of volatile keys as
+ * psa_set_key_id() enforces the key to be persistent.
+ *
+ * This function allows to set in key attributes the owner identifier of a
+ * key. It is intended to be used for volatile keys. For persistent keys,
+ * it is recommended to use the PSA Cryptography API psa_set_key_id() to define
+ * the owner of a key.
+ *
+ * \param[out] attributes The attribute structure to write to.
+ * \param owner The key owner identifier.
+ */
+static void mbedtls_set_key_owner_id(psa_key_attributes_t *attributes,
+ mbedtls_key_owner_id_t owner);
+#endif
+
+/** Set the location of a persistent key.
+ *
+ * To make a key persistent, you must give it a persistent key identifier
+ * with psa_set_key_id(). By default, a key that has a persistent identifier
+ * is stored in the default storage area identifier by
+ * #PSA_KEY_LIFETIME_PERSISTENT. Call this function to choose a storage
+ * area, or to explicitly declare the key as volatile.
+ *
+ * This function does not access storage, it merely stores the given
+ * value in the structure.
+ * The persistent key will be written to storage when the attribute
+ * structure is passed to a key creation function such as
+ * psa_import_key(), psa_generate_key(),
+ * psa_key_derivation_output_key() or psa_copy_key().
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate each of its arguments exactly once.
+ *
+ * \param[out] attributes The attribute structure to write to.
+ * \param lifetime The lifetime for the key.
+ * If this is #PSA_KEY_LIFETIME_VOLATILE, the
+ * key will be volatile, and the key identifier
+ * attribute is reset to 0.
+ */
+static void psa_set_key_lifetime(psa_key_attributes_t *attributes,
+ psa_key_lifetime_t lifetime);
+
+/** Retrieve the key identifier from key attributes.
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate its argument exactly once.
+ *
+ * \param[in] attributes The key attribute structure to query.
+ *
+ * \return The persistent identifier stored in the attribute structure.
+ * This value is unspecified if the attribute structure declares
+ * the key as volatile.
+ */
+static mbedtls_svc_key_id_t psa_get_key_id(
+ const psa_key_attributes_t *attributes);
+
+/** Retrieve the lifetime from key attributes.
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate its argument exactly once.
+ *
+ * \param[in] attributes The key attribute structure to query.
+ *
+ * \return The lifetime value stored in the attribute structure.
+ */
+static psa_key_lifetime_t psa_get_key_lifetime(
+ const psa_key_attributes_t *attributes);
+
+/** Declare usage flags for a key.
+ *
+ * Usage flags are part of a key's usage policy. They encode what
+ * kind of operations are permitted on the key. For more details,
+ * refer to the documentation of the type #psa_key_usage_t.
+ *
+ * This function overwrites any usage flags
+ * previously set in \p attributes.
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate each of its arguments exactly once.
+ *
+ * \param[out] attributes The attribute structure to write to.
+ * \param usage_flags The usage flags to write.
+ */
+static void psa_set_key_usage_flags(psa_key_attributes_t *attributes,
+ psa_key_usage_t usage_flags);
+
+/** Retrieve the usage flags from key attributes.
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate its argument exactly once.
+ *
+ * \param[in] attributes The key attribute structure to query.
+ *
+ * \return The usage flags stored in the attribute structure.
+ */
+static psa_key_usage_t psa_get_key_usage_flags(
+ const psa_key_attributes_t *attributes);
+
+/** Declare the permitted algorithm policy for a key.
+ *
+ * The permitted algorithm policy of a key encodes which algorithm or
+ * algorithms are permitted to be used with this key. The following
+ * algorithm policies are supported:
+ * - 0 does not allow any cryptographic operation with the key. The key
+ * may be used for non-cryptographic actions such as exporting (if
+ * permitted by the usage flags).
+ * - An algorithm value permits this particular algorithm.
+ * - An algorithm wildcard built from #PSA_ALG_ANY_HASH allows the specified
+ * signature scheme with any hash algorithm.
+ * - An algorithm built from #PSA_ALG_AT_LEAST_THIS_LENGTH_MAC allows
+ * any MAC algorithm from the same base class (e.g. CMAC) which
+ * generates/verifies a MAC length greater than or equal to the length
+ * encoded in the wildcard algorithm.
+ * - An algorithm built from #PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG
+ * allows any AEAD algorithm from the same base class (e.g. CCM) which
+ * generates/verifies a tag length greater than or equal to the length
+ * encoded in the wildcard algorithm.
+ *
+ * This function overwrites any algorithm policy
+ * previously set in \p attributes.
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate each of its arguments exactly once.
+ *
+ * \param[out] attributes The attribute structure to write to.
+ * \param alg The permitted algorithm policy to write.
+ */
+static void psa_set_key_algorithm(psa_key_attributes_t *attributes,
+ psa_algorithm_t alg);
+
+
+/** Retrieve the algorithm policy from key attributes.
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate its argument exactly once.
+ *
+ * \param[in] attributes The key attribute structure to query.
+ *
+ * \return The algorithm stored in the attribute structure.
+ */
+static psa_algorithm_t psa_get_key_algorithm(
+ const psa_key_attributes_t *attributes);
+
+/** Declare the type of a key.
+ *
+ * This function overwrites any key type
+ * previously set in \p attributes.
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate each of its arguments exactly once.
+ *
+ * \param[out] attributes The attribute structure to write to.
+ * \param type The key type to write.
+ * If this is 0, the key type in \p attributes
+ * becomes unspecified.
+ */
+static void psa_set_key_type(psa_key_attributes_t *attributes,
+ psa_key_type_t type);
+
+
+/** Declare the size of a key.
+ *
+ * This function overwrites any key size previously set in \p attributes.
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate each of its arguments exactly once.
+ *
+ * \param[out] attributes The attribute structure to write to.
+ * \param bits The key size in bits.
+ * If this is 0, the key size in \p attributes
+ * becomes unspecified. Keys of size 0 are
+ * not supported.
+ */
+static void psa_set_key_bits(psa_key_attributes_t *attributes,
+ size_t bits);
+
+/** Retrieve the key type from key attributes.
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate its argument exactly once.
+ *
+ * \param[in] attributes The key attribute structure to query.
+ *
+ * \return The key type stored in the attribute structure.
+ */
+static psa_key_type_t psa_get_key_type(const psa_key_attributes_t *attributes);
+
+/** Retrieve the key size from key attributes.
+ *
+ * This function may be declared as `static` (i.e. without external
+ * linkage). This function may be provided as a function-like macro,
+ * but in this case it must evaluate its argument exactly once.
+ *
+ * \param[in] attributes The key attribute structure to query.
+ *
+ * \return The key size stored in the attribute structure, in bits.
+ */
+static size_t psa_get_key_bits(const psa_key_attributes_t *attributes);
+
+/** Retrieve the attributes of a key.
+ *
+ * This function first resets the attribute structure as with
+ * psa_reset_key_attributes(). It then copies the attributes of
+ * the given key into the given attribute structure.
+ *
+ * \note This function may allocate memory or other resources.
+ * Once you have called this function on an attribute structure,
+ * you must call psa_reset_key_attributes() to free these resources.
+ *
+ * \param[in] key Identifier of the key to query.
+ * \param[in,out] attributes On success, the attributes of the key.
+ * On failure, equivalent to a
+ * freshly-initialized structure.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_get_key_attributes(mbedtls_svc_key_id_t key,
+ psa_key_attributes_t *attributes);
+
+/** Reset a key attribute structure to a freshly initialized state.
+ *
+ * You must initialize the attribute structure as described in the
+ * documentation of the type #psa_key_attributes_t before calling this
+ * function. Once the structure has been initialized, you may call this
+ * function at any time.
+ *
+ * This function frees any auxiliary resources that the structure
+ * may contain.
+ *
+ * \param[in,out] attributes The attribute structure to reset.
+ */
+void psa_reset_key_attributes(psa_key_attributes_t *attributes);
+
+/**@}*/
+
+/** \defgroup key_management Key management
+ * @{
+ */
+
+/** Remove non-essential copies of key material from memory.
+ *
+ * If the key identifier designates a volatile key, this functions does not do
+ * anything and returns successfully.
+ *
+ * If the key identifier designates a persistent key, then this function will
+ * free all resources associated with the key in volatile memory. The key
+ * data in persistent storage is not affected and the key can still be used.
+ *
+ * \param key Identifier of the key to purge.
+ *
+ * \retval #PSA_SUCCESS
+ * The key material will have been removed from memory if it is not
+ * currently required.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not a valid key identifier.
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_purge_key(mbedtls_svc_key_id_t key);
+
+/** Make a copy of a key.
+ *
+ * Copy key material from one location to another.
+ *
+ * This function is primarily useful to copy a key from one location
+ * to another, since it populates a key using the material from
+ * another key which may have a different lifetime.
+ *
+ * This function may be used to share a key with a different party,
+ * subject to implementation-defined restrictions on key sharing.
+ *
+ * The policy on the source key must have the usage flag
+ * #PSA_KEY_USAGE_COPY set.
+ * This flag is sufficient to permit the copy if the key has the lifetime
+ * #PSA_KEY_LIFETIME_VOLATILE or #PSA_KEY_LIFETIME_PERSISTENT.
+ * Some secure elements do not provide a way to copy a key without
+ * making it extractable from the secure element. If a key is located
+ * in such a secure element, then the key must have both usage flags
+ * #PSA_KEY_USAGE_COPY and #PSA_KEY_USAGE_EXPORT in order to make
+ * a copy of the key outside the secure element.
+ *
+ * The resulting key may only be used in a way that conforms to
+ * both the policy of the original key and the policy specified in
+ * the \p attributes parameter:
+ * - The usage flags on the resulting key are the bitwise-and of the
+ * usage flags on the source policy and the usage flags in \p attributes.
+ * - If both allow the same algorithm or wildcard-based
+ * algorithm policy, the resulting key has the same algorithm policy.
+ * - If either of the policies allows an algorithm and the other policy
+ * allows a wildcard-based algorithm policy that includes this algorithm,
+ * the resulting key allows the same algorithm.
+ * - If the policies do not allow any algorithm in common, this function
+ * fails with the status #PSA_ERROR_INVALID_ARGUMENT.
+ *
+ * The effect of this function on implementation-defined attributes is
+ * implementation-defined.
+ *
+ * \param source_key The key to copy. It must allow the usage
+ * #PSA_KEY_USAGE_COPY. If a private or secret key is
+ * being copied outside of a secure element it must
+ * also allow #PSA_KEY_USAGE_EXPORT.
+ * \param[in] attributes The attributes for the new key.
+ * They are used as follows:
+ * - The key type and size may be 0. If either is
+ * nonzero, it must match the corresponding
+ * attribute of the source key.
+ * - The key location (the lifetime and, for
+ * persistent keys, the key identifier) is
+ * used directly.
+ * - The policy constraints (usage flags and
+ * algorithm policy) are combined from
+ * the source key and \p attributes so that
+ * both sets of restrictions apply, as
+ * described in the documentation of this function.
+ * \param[out] target_key On success, an identifier for the newly created
+ * key. For persistent keys, this is the key
+ * identifier defined in \p attributes.
+ * \c 0 on failure.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_HANDLE
+ * \p source_key is invalid.
+ * \retval #PSA_ERROR_ALREADY_EXISTS
+ * This is an attempt to create a persistent key, and there is
+ * already a persistent key with the given identifier.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The lifetime or identifier in \p attributes are invalid, or
+ * the policy constraints on the source and specified in
+ * \p attributes are incompatible, or
+ * \p attributes specifies a key type or key size
+ * which does not match the attributes of the source key.
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The source key does not have the #PSA_KEY_USAGE_COPY usage flag, or
+ * the source key is not exportable and its lifetime does not
+ * allow copying it to the target's lifetime.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_copy_key(mbedtls_svc_key_id_t source_key,
+ const psa_key_attributes_t *attributes,
+ mbedtls_svc_key_id_t *target_key);
+
+
+/**
+ * \brief Destroy a key.
+ *
+ * This function destroys a key from both volatile
+ * memory and, if applicable, non-volatile storage. Implementations shall
+ * make a best effort to ensure that the key material cannot be recovered.
+ *
+ * This function also erases any metadata such as policies and frees
+ * resources associated with the key.
+ *
+ * If a key is currently in use in a multipart operation, then destroying the
+ * key will cause the multipart operation to fail.
+ *
+ * \param key Identifier of the key to erase. If this is \c 0, do nothing and
+ * return #PSA_SUCCESS.
+ *
+ * \retval #PSA_SUCCESS
+ * \p key was a valid identifier and the key material that it
+ * referred to has been erased. Alternatively, \p key is \c 0.
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The key cannot be erased because it is
+ * read-only, either due to a policy or due to physical restrictions.
+ * \retval #PSA_ERROR_INVALID_HANDLE
+ * \p key is not a valid identifier nor \c 0.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE
+ * There was a failure in communication with the cryptoprocessor.
+ * The key material may still be present in the cryptoprocessor.
+ * \retval #PSA_ERROR_DATA_INVALID
+ * This error is typically a result of either storage corruption on a
+ * cleartext storage backend, or an attempt to read data that was
+ * written by an incompatible version of the library.
+ * \retval #PSA_ERROR_STORAGE_FAILURE
+ * The storage is corrupted. Implementations shall make a best effort
+ * to erase key material even in this stage, however applications
+ * should be aware that it may be impossible to guarantee that the
+ * key material is not recoverable in such cases.
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED
+ * An unexpected condition which is not a storage corruption or
+ * a communication failure occurred. The cryptoprocessor may have
+ * been compromised.
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_destroy_key(mbedtls_svc_key_id_t key);
+
+/**@}*/
+
+/** \defgroup import_export Key import and export
+ * @{
+ */
+
+/**
+ * \brief Import a key in binary format.
+ *
+ * This function supports any output from psa_export_key(). Refer to the
+ * documentation of psa_export_public_key() for the format of public keys
+ * and to the documentation of psa_export_key() for the format for
+ * other key types.
+ *
+ * The key data determines the key size. The attributes may optionally
+ * specify a key size; in this case it must match the size determined
+ * from the key data. A key size of 0 in \p attributes indicates that
+ * the key size is solely determined by the key data.
+ *
+ * Implementations must reject an attempt to import a key of size 0.
+ *
+ * This specification supports a single format for each key type.
+ * Implementations may support other formats as long as the standard
+ * format is supported. Implementations that support other formats
+ * should ensure that the formats are clearly unambiguous so as to
+ * minimize the risk that an invalid input is accidentally interpreted
+ * according to a different format.
+ *
+ * \param[in] attributes The attributes for the new key.
+ * The key size is always determined from the
+ * \p data buffer.
+ * If the key size in \p attributes is nonzero,
+ * it must be equal to the size from \p data.
+ * \param[out] key On success, an identifier to the newly created key.
+ * For persistent keys, this is the key identifier
+ * defined in \p attributes.
+ * \c 0 on failure.
+ * \param[in] data Buffer containing the key data. The content of this
+ * buffer is interpreted according to the type declared
+ * in \p attributes.
+ * All implementations must support at least the format
+ * described in the documentation
+ * of psa_export_key() or psa_export_public_key() for
+ * the chosen type. Implementations may allow other
+ * formats, but should be conservative: implementations
+ * should err on the side of rejecting content if it
+ * may be erroneous (e.g. wrong type or truncated data).
+ * \param data_length Size of the \p data buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * If the key is persistent, the key material and the key's metadata
+ * have been saved to persistent storage.
+ * \retval #PSA_ERROR_ALREADY_EXISTS
+ * This is an attempt to create a persistent key, and there is
+ * already a persistent key with the given identifier.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * The key type or key size is not supported, either by the
+ * implementation in general or in this particular persistent location.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The key attributes, as a whole, are invalid, or
+ * the key data is not correctly formatted, or
+ * the size in \p attributes is nonzero and does not match the size
+ * of the key data.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_import_key(const psa_key_attributes_t *attributes,
+ const uint8_t *data,
+ size_t data_length,
+ mbedtls_svc_key_id_t *key);
+
+
+
+/**
+ * \brief Export a key in binary format.
+ *
+ * The output of this function can be passed to psa_import_key() to
+ * create an equivalent object.
+ *
+ * If the implementation of psa_import_key() supports other formats
+ * beyond the format specified here, the output from psa_export_key()
+ * must use the representation specified here, not the original
+ * representation.
+ *
+ * For standard key types, the output format is as follows:
+ *
+ * - For symmetric keys (including MAC keys), the format is the
+ * raw bytes of the key.
+ * - For DES, the key data consists of 8 bytes. The parity bits must be
+ * correct.
+ * - For Triple-DES, the format is the concatenation of the
+ * two or three DES keys.
+ * - For RSA key pairs (#PSA_KEY_TYPE_RSA_KEY_PAIR), the format
+ * is the non-encrypted DER encoding of the representation defined by
+ * PKCS\#1 (RFC 8017) as `RSAPrivateKey`, version 0.
+ * ```
+ * RSAPrivateKey ::= SEQUENCE {
+ * version INTEGER, -- must be 0
+ * modulus INTEGER, -- n
+ * publicExponent INTEGER, -- e
+ * privateExponent INTEGER, -- d
+ * prime1 INTEGER, -- p
+ * prime2 INTEGER, -- q
+ * exponent1 INTEGER, -- d mod (p-1)
+ * exponent2 INTEGER, -- d mod (q-1)
+ * coefficient INTEGER, -- (inverse of q) mod p
+ * }
+ * ```
+ * - For elliptic curve key pairs (key types for which
+ * #PSA_KEY_TYPE_IS_ECC_KEY_PAIR is true), the format is
+ * a representation of the private value as a `ceiling(m/8)`-byte string
+ * where `m` is the bit size associated with the curve, i.e. the bit size
+ * of the order of the curve's coordinate field. This byte string is
+ * in little-endian order for Montgomery curves (curve types
+ * `PSA_ECC_FAMILY_CURVEXXX`), and in big-endian order for Weierstrass
+ * curves (curve types `PSA_ECC_FAMILY_SECTXXX`, `PSA_ECC_FAMILY_SECPXXX`
+ * and `PSA_ECC_FAMILY_BRAINPOOL_PXXX`).
+ * For Weierstrass curves, this is the content of the `privateKey` field of
+ * the `ECPrivateKey` format defined by RFC 5915. For Montgomery curves,
+ * the format is defined by RFC 7748, and output is masked according to §5.
+ * For twisted Edwards curves, the private key is as defined by RFC 8032
+ * (a 32-byte string for Edwards25519, a 57-byte string for Edwards448).
+ * - For Diffie-Hellman key exchange key pairs (key types for which
+ * #PSA_KEY_TYPE_IS_DH_KEY_PAIR is true), the
+ * format is the representation of the private key `x` as a big-endian byte
+ * string. The length of the byte string is the private key size in bytes
+ * (leading zeroes are not stripped).
+ * - For public keys (key types for which #PSA_KEY_TYPE_IS_PUBLIC_KEY is
+ * true), the format is the same as for psa_export_public_key().
+ *
+ * The policy on the key must have the usage flag #PSA_KEY_USAGE_EXPORT set.
+ *
+ * \param key Identifier of the key to export. It must allow the
+ * usage #PSA_KEY_USAGE_EXPORT, unless it is a public
+ * key.
+ * \param[out] data Buffer where the key data is to be written.
+ * \param data_size Size of the \p data buffer in bytes.
+ * \param[out] data_length On success, the number of bytes
+ * that make up the key data.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The key does not have the #PSA_KEY_USAGE_EXPORT flag.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p data buffer is too small. You can determine a
+ * sufficient buffer size by calling
+ * #PSA_EXPORT_KEY_OUTPUT_SIZE(\c type, \c bits)
+ * where \c type is the key type
+ * and \c bits is the key size in bits.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_export_key(mbedtls_svc_key_id_t key,
+ uint8_t *data,
+ size_t data_size,
+ size_t *data_length);
+
+/**
+ * \brief Export a public key or the public part of a key pair in binary format.
+ *
+ * The output of this function can be passed to psa_import_key() to
+ * create an object that is equivalent to the public key.
+ *
+ * This specification supports a single format for each key type.
+ * Implementations may support other formats as long as the standard
+ * format is supported. Implementations that support other formats
+ * should ensure that the formats are clearly unambiguous so as to
+ * minimize the risk that an invalid input is accidentally interpreted
+ * according to a different format.
+ *
+ * For standard key types, the output format is as follows:
+ * - For RSA public keys (#PSA_KEY_TYPE_RSA_PUBLIC_KEY), the DER encoding of
+ * the representation defined by RFC 3279 &sect;2.3.1 as `RSAPublicKey`.
+ * ```
+ * RSAPublicKey ::= SEQUENCE {
+ * modulus INTEGER, -- n
+ * publicExponent INTEGER } -- e
+ * ```
+ * - For elliptic curve keys on a twisted Edwards curve (key types for which
+ * #PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY is true and #PSA_KEY_TYPE_ECC_GET_FAMILY
+ * returns #PSA_ECC_FAMILY_TWISTED_EDWARDS), the public key is as defined
+ * by RFC 8032
+ * (a 32-byte string for Edwards25519, a 57-byte string for Edwards448).
+ * - For other elliptic curve public keys (key types for which
+ * #PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY is true), the format is the uncompressed
+ * representation defined by SEC1 &sect;2.3.3 as the content of an ECPoint.
+ * Let `m` be the bit size associated with the curve, i.e. the bit size of
+ * `q` for a curve over `F_q`. The representation consists of:
+ * - The byte 0x04;
+ * - `x_P` as a `ceiling(m/8)`-byte string, big-endian;
+ * - `y_P` as a `ceiling(m/8)`-byte string, big-endian.
+ * - For Diffie-Hellman key exchange public keys (key types for which
+ * #PSA_KEY_TYPE_IS_DH_PUBLIC_KEY is true),
+ * the format is the representation of the public key `y = g^x mod p` as a
+ * big-endian byte string. The length of the byte string is the length of the
+ * base prime `p` in bytes.
+ *
+ * Exporting a public key object or the public part of a key pair is
+ * always permitted, regardless of the key's usage flags.
+ *
+ * \param key Identifier of the key to export.
+ * \param[out] data Buffer where the key data is to be written.
+ * \param data_size Size of the \p data buffer in bytes.
+ * \param[out] data_length On success, the number of bytes
+ * that make up the key data.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The key is neither a public key nor a key pair.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p data buffer is too small. You can determine a
+ * sufficient buffer size by calling
+ * #PSA_EXPORT_KEY_OUTPUT_SIZE(#PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(\c type), \c bits)
+ * where \c type is the key type
+ * and \c bits is the key size in bits.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_export_public_key(mbedtls_svc_key_id_t key,
+ uint8_t *data,
+ size_t data_size,
+ size_t *data_length);
+
+
+
+/**@}*/
+
+/** \defgroup hash Message digests
+ * @{
+ */
+
+/** Calculate the hash (digest) of a message.
+ *
+ * \note To verify the hash of a message against an
+ * expected value, use psa_hash_compare() instead.
+ *
+ * \param alg The hash algorithm to compute (\c PSA_ALG_XXX value
+ * such that #PSA_ALG_IS_HASH(\p alg) is true).
+ * \param[in] input Buffer containing the message to hash.
+ * \param input_length Size of the \p input buffer in bytes.
+ * \param[out] hash Buffer where the hash is to be written.
+ * \param hash_size Size of the \p hash buffer in bytes.
+ * \param[out] hash_length On success, the number of bytes
+ * that make up the hash value. This is always
+ * #PSA_HASH_LENGTH(\p alg).
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not a hash algorithm.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * \p hash_size is too small
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_hash_compute(psa_algorithm_t alg,
+ const uint8_t *input,
+ size_t input_length,
+ uint8_t *hash,
+ size_t hash_size,
+ size_t *hash_length);
+
+/** Calculate the hash (digest) of a message and compare it with a
+ * reference value.
+ *
+ * \param alg The hash algorithm to compute (\c PSA_ALG_XXX value
+ * such that #PSA_ALG_IS_HASH(\p alg) is true).
+ * \param[in] input Buffer containing the message to hash.
+ * \param input_length Size of the \p input buffer in bytes.
+ * \param[out] hash Buffer containing the expected hash value.
+ * \param hash_length Size of the \p hash buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * The expected hash is identical to the actual hash of the input.
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The hash of the message was calculated successfully, but it
+ * differs from the expected hash.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not a hash algorithm.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p input_length or \p hash_length do not match the hash size for \p alg
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_hash_compare(psa_algorithm_t alg,
+ const uint8_t *input,
+ size_t input_length,
+ const uint8_t *hash,
+ size_t hash_length);
+
+/** The type of the state data structure for multipart hash operations.
+ *
+ * Before calling any function on a hash operation object, the application must
+ * initialize it by any of the following means:
+ * - Set the structure to all-bits-zero, for example:
+ * \code
+ * psa_hash_operation_t operation;
+ * memset(&operation, 0, sizeof(operation));
+ * \endcode
+ * - Initialize the structure to logical zero values, for example:
+ * \code
+ * psa_hash_operation_t operation = {0};
+ * \endcode
+ * - Initialize the structure to the initializer #PSA_HASH_OPERATION_INIT,
+ * for example:
+ * \code
+ * psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT;
+ * \endcode
+ * - Assign the result of the function psa_hash_operation_init()
+ * to the structure, for example:
+ * \code
+ * psa_hash_operation_t operation;
+ * operation = psa_hash_operation_init();
+ * \endcode
+ *
+ * This is an implementation-defined \c struct. Applications should not
+ * make any assumptions about the content of this structure.
+ * Implementation details can change in future versions without notice. */
+typedef struct psa_hash_operation_s psa_hash_operation_t;
+
+/** \def PSA_HASH_OPERATION_INIT
+ *
+ * This macro returns a suitable initializer for a hash operation object
+ * of type #psa_hash_operation_t.
+ */
+
+/** Return an initial value for a hash operation object.
+ */
+static psa_hash_operation_t psa_hash_operation_init(void);
+
+/** Set up a multipart hash operation.
+ *
+ * The sequence of operations to calculate a hash (message digest)
+ * is as follows:
+ * -# Allocate an operation object which will be passed to all the functions
+ * listed here.
+ * -# Initialize the operation object with one of the methods described in the
+ * documentation for #psa_hash_operation_t, e.g. #PSA_HASH_OPERATION_INIT.
+ * -# Call psa_hash_setup() to specify the algorithm.
+ * -# Call psa_hash_update() zero, one or more times, passing a fragment
+ * of the message each time. The hash that is calculated is the hash
+ * of the concatenation of these messages in order.
+ * -# To calculate the hash, call psa_hash_finish().
+ * To compare the hash with an expected value, call psa_hash_verify().
+ *
+ * If an error occurs at any step after a call to psa_hash_setup(), the
+ * operation will need to be reset by a call to psa_hash_abort(). The
+ * application may call psa_hash_abort() at any time after the operation
+ * has been initialized.
+ *
+ * After a successful call to psa_hash_setup(), the application must
+ * eventually terminate the operation. The following events terminate an
+ * operation:
+ * - A successful call to psa_hash_finish() or psa_hash_verify().
+ * - A call to psa_hash_abort().
+ *
+ * \param[in,out] operation The operation object to set up. It must have
+ * been initialized as per the documentation for
+ * #psa_hash_operation_t and not yet in use.
+ * \param alg The hash algorithm to compute (\c PSA_ALG_XXX value
+ * such that #PSA_ALG_IS_HASH(\p alg) is true).
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not a supported hash algorithm.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p alg is not a hash algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be inactive), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_hash_setup(psa_hash_operation_t *operation,
+ psa_algorithm_t alg);
+
+/** Add a message fragment to a multipart hash operation.
+ *
+ * The application must call psa_hash_setup() before calling this function.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_hash_abort().
+ *
+ * \param[in,out] operation Active hash operation.
+ * \param[in] input Buffer containing the message fragment to hash.
+ * \param input_length Size of the \p input buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_hash_update(psa_hash_operation_t *operation,
+ const uint8_t *input,
+ size_t input_length);
+
+/** Finish the calculation of the hash of a message.
+ *
+ * The application must call psa_hash_setup() before calling this function.
+ * This function calculates the hash of the message formed by concatenating
+ * the inputs passed to preceding calls to psa_hash_update().
+ *
+ * When this function returns successfully, the operation becomes inactive.
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_hash_abort().
+ *
+ * \warning Applications should not call this function if they expect
+ * a specific value for the hash. Call psa_hash_verify() instead.
+ * Beware that comparing integrity or authenticity data such as
+ * hash values with a function such as \c memcmp is risky
+ * because the time taken by the comparison may leak information
+ * about the hashed data which could allow an attacker to guess
+ * a valid hash and thereby bypass security controls.
+ *
+ * \param[in,out] operation Active hash operation.
+ * \param[out] hash Buffer where the hash is to be written.
+ * \param hash_size Size of the \p hash buffer in bytes.
+ * \param[out] hash_length On success, the number of bytes
+ * that make up the hash value. This is always
+ * #PSA_HASH_LENGTH(\c alg) where \c alg is the
+ * hash algorithm that is calculated.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p hash buffer is too small. You can determine a
+ * sufficient buffer size by calling #PSA_HASH_LENGTH(\c alg)
+ * where \c alg is the hash algorithm that is calculated.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_hash_finish(psa_hash_operation_t *operation,
+ uint8_t *hash,
+ size_t hash_size,
+ size_t *hash_length);
+
+/** Finish the calculation of the hash of a message and compare it with
+ * an expected value.
+ *
+ * The application must call psa_hash_setup() before calling this function.
+ * This function calculates the hash of the message formed by concatenating
+ * the inputs passed to preceding calls to psa_hash_update(). It then
+ * compares the calculated hash with the expected hash passed as a
+ * parameter to this function.
+ *
+ * When this function returns successfully, the operation becomes inactive.
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_hash_abort().
+ *
+ * \note Implementations shall make the best effort to ensure that the
+ * comparison between the actual hash and the expected hash is performed
+ * in constant time.
+ *
+ * \param[in,out] operation Active hash operation.
+ * \param[in] hash Buffer containing the expected hash value.
+ * \param hash_length Size of the \p hash buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * The expected hash is identical to the actual hash of the message.
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The hash of the message was calculated successfully, but it
+ * differs from the expected hash.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_hash_verify(psa_hash_operation_t *operation,
+ const uint8_t *hash,
+ size_t hash_length);
+
+/** Abort a hash operation.
+ *
+ * Aborting an operation frees all associated resources except for the
+ * \p operation structure itself. Once aborted, the operation object
+ * can be reused for another operation by calling
+ * psa_hash_setup() again.
+ *
+ * You may call this function any time after the operation object has
+ * been initialized by one of the methods described in #psa_hash_operation_t.
+ *
+ * In particular, calling psa_hash_abort() after the operation has been
+ * terminated by a call to psa_hash_abort(), psa_hash_finish() or
+ * psa_hash_verify() is safe and has no effect.
+ *
+ * \param[in,out] operation Initialized hash operation.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_hash_abort(psa_hash_operation_t *operation);
+
+/** Clone a hash operation.
+ *
+ * This function copies the state of an ongoing hash operation to
+ * a new operation object. In other words, this function is equivalent
+ * to calling psa_hash_setup() on \p target_operation with the same
+ * algorithm that \p source_operation was set up for, then
+ * psa_hash_update() on \p target_operation with the same input that
+ * that was passed to \p source_operation. After this function returns, the
+ * two objects are independent, i.e. subsequent calls involving one of
+ * the objects do not affect the other object.
+ *
+ * \param[in] source_operation The active hash operation to clone.
+ * \param[in,out] target_operation The operation object to set up.
+ * It must be initialized but not active.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The \p source_operation state is not valid (it must be active), or
+ * the \p target_operation state is not valid (it must be inactive), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_hash_clone(const psa_hash_operation_t *source_operation,
+ psa_hash_operation_t *target_operation);
+
+/**@}*/
+
+/** \defgroup MAC Message authentication codes
+ * @{
+ */
+
+/** Calculate the MAC (message authentication code) of a message.
+ *
+ * \note To verify the MAC of a message against an
+ * expected value, use psa_mac_verify() instead.
+ * Beware that comparing integrity or authenticity data such as
+ * MAC values with a function such as \c memcmp is risky
+ * because the time taken by the comparison may leak information
+ * about the MAC value which could allow an attacker to guess
+ * a valid MAC and thereby bypass security controls.
+ *
+ * \param key Identifier of the key to use for the operation. It
+ * must allow the usage PSA_KEY_USAGE_SIGN_MESSAGE.
+ * \param alg The MAC algorithm to compute (\c PSA_ALG_XXX value
+ * such that #PSA_ALG_IS_MAC(\p alg) is true).
+ * \param[in] input Buffer containing the input message.
+ * \param input_length Size of the \p input buffer in bytes.
+ * \param[out] mac Buffer where the MAC value is to be written.
+ * \param mac_size Size of the \p mac buffer in bytes.
+ * \param[out] mac_length On success, the number of bytes
+ * that make up the MAC value.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not a MAC algorithm.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * \p mac_size is too small
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE
+ * The key could not be retrieved from storage.
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_mac_compute(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *input,
+ size_t input_length,
+ uint8_t *mac,
+ size_t mac_size,
+ size_t *mac_length);
+
+/** Calculate the MAC of a message and compare it with a reference value.
+ *
+ * \param key Identifier of the key to use for the operation. It
+ * must allow the usage PSA_KEY_USAGE_VERIFY_MESSAGE.
+ * \param alg The MAC algorithm to compute (\c PSA_ALG_XXX value
+ * such that #PSA_ALG_IS_MAC(\p alg) is true).
+ * \param[in] input Buffer containing the input message.
+ * \param input_length Size of the \p input buffer in bytes.
+ * \param[out] mac Buffer containing the expected MAC value.
+ * \param mac_length Size of the \p mac buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * The expected MAC is identical to the actual MAC of the input.
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The MAC of the message was calculated successfully, but it
+ * differs from the expected value.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not a MAC algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE
+ * The key could not be retrieved from storage.
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_mac_verify(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *input,
+ size_t input_length,
+ const uint8_t *mac,
+ size_t mac_length);
+
+/** The type of the state data structure for multipart MAC operations.
+ *
+ * Before calling any function on a MAC operation object, the application must
+ * initialize it by any of the following means:
+ * - Set the structure to all-bits-zero, for example:
+ * \code
+ * psa_mac_operation_t operation;
+ * memset(&operation, 0, sizeof(operation));
+ * \endcode
+ * - Initialize the structure to logical zero values, for example:
+ * \code
+ * psa_mac_operation_t operation = {0};
+ * \endcode
+ * - Initialize the structure to the initializer #PSA_MAC_OPERATION_INIT,
+ * for example:
+ * \code
+ * psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT;
+ * \endcode
+ * - Assign the result of the function psa_mac_operation_init()
+ * to the structure, for example:
+ * \code
+ * psa_mac_operation_t operation;
+ * operation = psa_mac_operation_init();
+ * \endcode
+ *
+ *
+ * This is an implementation-defined \c struct. Applications should not
+ * make any assumptions about the content of this structure.
+ * Implementation details can change in future versions without notice. */
+typedef struct psa_mac_operation_s psa_mac_operation_t;
+
+/** \def PSA_MAC_OPERATION_INIT
+ *
+ * This macro returns a suitable initializer for a MAC operation object of type
+ * #psa_mac_operation_t.
+ */
+
+/** Return an initial value for a MAC operation object.
+ */
+static psa_mac_operation_t psa_mac_operation_init(void);
+
+/** Set up a multipart MAC calculation operation.
+ *
+ * This function sets up the calculation of the MAC
+ * (message authentication code) of a byte string.
+ * To verify the MAC of a message against an
+ * expected value, use psa_mac_verify_setup() instead.
+ *
+ * The sequence of operations to calculate a MAC is as follows:
+ * -# Allocate an operation object which will be passed to all the functions
+ * listed here.
+ * -# Initialize the operation object with one of the methods described in the
+ * documentation for #psa_mac_operation_t, e.g. #PSA_MAC_OPERATION_INIT.
+ * -# Call psa_mac_sign_setup() to specify the algorithm and key.
+ * -# Call psa_mac_update() zero, one or more times, passing a fragment
+ * of the message each time. The MAC that is calculated is the MAC
+ * of the concatenation of these messages in order.
+ * -# At the end of the message, call psa_mac_sign_finish() to finish
+ * calculating the MAC value and retrieve it.
+ *
+ * If an error occurs at any step after a call to psa_mac_sign_setup(), the
+ * operation will need to be reset by a call to psa_mac_abort(). The
+ * application may call psa_mac_abort() at any time after the operation
+ * has been initialized.
+ *
+ * After a successful call to psa_mac_sign_setup(), the application must
+ * eventually terminate the operation through one of the following methods:
+ * - A successful call to psa_mac_sign_finish().
+ * - A call to psa_mac_abort().
+ *
+ * \param[in,out] operation The operation object to set up. It must have
+ * been initialized as per the documentation for
+ * #psa_mac_operation_t and not yet in use.
+ * \param key Identifier of the key to use for the operation. It
+ * must remain valid until the operation terminates.
+ * It must allow the usage PSA_KEY_USAGE_SIGN_MESSAGE.
+ * \param alg The MAC algorithm to compute (\c PSA_ALG_XXX value
+ * such that #PSA_ALG_IS_MAC(\p alg) is true).
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not a MAC algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE
+ * The key could not be retrieved from storage.
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be inactive), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_mac_sign_setup(psa_mac_operation_t *operation,
+ mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg);
+
+/** Set up a multipart MAC verification operation.
+ *
+ * This function sets up the verification of the MAC
+ * (message authentication code) of a byte string against an expected value.
+ *
+ * The sequence of operations to verify a MAC is as follows:
+ * -# Allocate an operation object which will be passed to all the functions
+ * listed here.
+ * -# Initialize the operation object with one of the methods described in the
+ * documentation for #psa_mac_operation_t, e.g. #PSA_MAC_OPERATION_INIT.
+ * -# Call psa_mac_verify_setup() to specify the algorithm and key.
+ * -# Call psa_mac_update() zero, one or more times, passing a fragment
+ * of the message each time. The MAC that is calculated is the MAC
+ * of the concatenation of these messages in order.
+ * -# At the end of the message, call psa_mac_verify_finish() to finish
+ * calculating the actual MAC of the message and verify it against
+ * the expected value.
+ *
+ * If an error occurs at any step after a call to psa_mac_verify_setup(), the
+ * operation will need to be reset by a call to psa_mac_abort(). The
+ * application may call psa_mac_abort() at any time after the operation
+ * has been initialized.
+ *
+ * After a successful call to psa_mac_verify_setup(), the application must
+ * eventually terminate the operation through one of the following methods:
+ * - A successful call to psa_mac_verify_finish().
+ * - A call to psa_mac_abort().
+ *
+ * \param[in,out] operation The operation object to set up. It must have
+ * been initialized as per the documentation for
+ * #psa_mac_operation_t and not yet in use.
+ * \param key Identifier of the key to use for the operation. It
+ * must remain valid until the operation terminates.
+ * It must allow the usage
+ * PSA_KEY_USAGE_VERIFY_MESSAGE.
+ * \param alg The MAC algorithm to compute (\c PSA_ALG_XXX value
+ * such that #PSA_ALG_IS_MAC(\p alg) is true).
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \c key is not compatible with \c alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \c alg is not supported or is not a MAC algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE
+ * The key could not be retrieved from storage.
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be inactive), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_mac_verify_setup(psa_mac_operation_t *operation,
+ mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg);
+
+/** Add a message fragment to a multipart MAC operation.
+ *
+ * The application must call psa_mac_sign_setup() or psa_mac_verify_setup()
+ * before calling this function.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_mac_abort().
+ *
+ * \param[in,out] operation Active MAC operation.
+ * \param[in] input Buffer containing the message fragment to add to
+ * the MAC calculation.
+ * \param input_length Size of the \p input buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_mac_update(psa_mac_operation_t *operation,
+ const uint8_t *input,
+ size_t input_length);
+
+/** Finish the calculation of the MAC of a message.
+ *
+ * The application must call psa_mac_sign_setup() before calling this function.
+ * This function calculates the MAC of the message formed by concatenating
+ * the inputs passed to preceding calls to psa_mac_update().
+ *
+ * When this function returns successfully, the operation becomes inactive.
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_mac_abort().
+ *
+ * \warning Applications should not call this function if they expect
+ * a specific value for the MAC. Call psa_mac_verify_finish() instead.
+ * Beware that comparing integrity or authenticity data such as
+ * MAC values with a function such as \c memcmp is risky
+ * because the time taken by the comparison may leak information
+ * about the MAC value which could allow an attacker to guess
+ * a valid MAC and thereby bypass security controls.
+ *
+ * \param[in,out] operation Active MAC operation.
+ * \param[out] mac Buffer where the MAC value is to be written.
+ * \param mac_size Size of the \p mac buffer in bytes.
+ * \param[out] mac_length On success, the number of bytes
+ * that make up the MAC value. This is always
+ * #PSA_MAC_LENGTH(\c key_type, \c key_bits, \c alg)
+ * where \c key_type and \c key_bits are the type and
+ * bit-size respectively of the key and \c alg is the
+ * MAC algorithm that is calculated.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p mac buffer is too small. You can determine a
+ * sufficient buffer size by calling PSA_MAC_LENGTH().
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be an active mac sign
+ * operation), or the library has not been previously initialized
+ * by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_mac_sign_finish(psa_mac_operation_t *operation,
+ uint8_t *mac,
+ size_t mac_size,
+ size_t *mac_length);
+
+/** Finish the calculation of the MAC of a message and compare it with
+ * an expected value.
+ *
+ * The application must call psa_mac_verify_setup() before calling this function.
+ * This function calculates the MAC of the message formed by concatenating
+ * the inputs passed to preceding calls to psa_mac_update(). It then
+ * compares the calculated MAC with the expected MAC passed as a
+ * parameter to this function.
+ *
+ * When this function returns successfully, the operation becomes inactive.
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_mac_abort().
+ *
+ * \note Implementations shall make the best effort to ensure that the
+ * comparison between the actual MAC and the expected MAC is performed
+ * in constant time.
+ *
+ * \param[in,out] operation Active MAC operation.
+ * \param[in] mac Buffer containing the expected MAC value.
+ * \param mac_length Size of the \p mac buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * The expected MAC is identical to the actual MAC of the message.
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The MAC of the message was calculated successfully, but it
+ * differs from the expected MAC.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be an active mac verify
+ * operation), or the library has not been previously initialized
+ * by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_mac_verify_finish(psa_mac_operation_t *operation,
+ const uint8_t *mac,
+ size_t mac_length);
+
+/** Abort a MAC operation.
+ *
+ * Aborting an operation frees all associated resources except for the
+ * \p operation structure itself. Once aborted, the operation object
+ * can be reused for another operation by calling
+ * psa_mac_sign_setup() or psa_mac_verify_setup() again.
+ *
+ * You may call this function any time after the operation object has
+ * been initialized by one of the methods described in #psa_mac_operation_t.
+ *
+ * In particular, calling psa_mac_abort() after the operation has been
+ * terminated by a call to psa_mac_abort(), psa_mac_sign_finish() or
+ * psa_mac_verify_finish() is safe and has no effect.
+ *
+ * \param[in,out] operation Initialized MAC operation.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_mac_abort(psa_mac_operation_t *operation);
+
+/**@}*/
+
+/** \defgroup cipher Symmetric ciphers
+ * @{
+ */
+
+/** Encrypt a message using a symmetric cipher.
+ *
+ * This function encrypts a message with a random IV (initialization
+ * vector). Use the multipart operation interface with a
+ * #psa_cipher_operation_t object to provide other forms of IV.
+ *
+ * \param key Identifier of the key to use for the operation.
+ * It must allow the usage #PSA_KEY_USAGE_ENCRYPT.
+ * \param alg The cipher algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_CIPHER(\p alg) is true).
+ * \param[in] input Buffer containing the message to encrypt.
+ * \param input_length Size of the \p input buffer in bytes.
+ * \param[out] output Buffer where the output is to be written.
+ * The output contains the IV followed by
+ * the ciphertext proper.
+ * \param output_size Size of the \p output buffer in bytes.
+ * \param[out] output_length On success, the number of bytes
+ * that make up the output.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not a cipher algorithm.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_cipher_encrypt(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *input,
+ size_t input_length,
+ uint8_t *output,
+ size_t output_size,
+ size_t *output_length);
+
+/** Decrypt a message using a symmetric cipher.
+ *
+ * This function decrypts a message encrypted with a symmetric cipher.
+ *
+ * \param key Identifier of the key to use for the operation.
+ * It must remain valid until the operation
+ * terminates. It must allow the usage
+ * #PSA_KEY_USAGE_DECRYPT.
+ * \param alg The cipher algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_CIPHER(\p alg) is true).
+ * \param[in] input Buffer containing the message to decrypt.
+ * This consists of the IV followed by the
+ * ciphertext proper.
+ * \param input_length Size of the \p input buffer in bytes.
+ * \param[out] output Buffer where the plaintext is to be written.
+ * \param output_size Size of the \p output buffer in bytes.
+ * \param[out] output_length On success, the number of bytes
+ * that make up the output.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not a cipher algorithm.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *input,
+ size_t input_length,
+ uint8_t *output,
+ size_t output_size,
+ size_t *output_length);
+
+/** The type of the state data structure for multipart cipher operations.
+ *
+ * Before calling any function on a cipher operation object, the application
+ * must initialize it by any of the following means:
+ * - Set the structure to all-bits-zero, for example:
+ * \code
+ * psa_cipher_operation_t operation;
+ * memset(&operation, 0, sizeof(operation));
+ * \endcode
+ * - Initialize the structure to logical zero values, for example:
+ * \code
+ * psa_cipher_operation_t operation = {0};
+ * \endcode
+ * - Initialize the structure to the initializer #PSA_CIPHER_OPERATION_INIT,
+ * for example:
+ * \code
+ * psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT;
+ * \endcode
+ * - Assign the result of the function psa_cipher_operation_init()
+ * to the structure, for example:
+ * \code
+ * psa_cipher_operation_t operation;
+ * operation = psa_cipher_operation_init();
+ * \endcode
+ *
+ * This is an implementation-defined \c struct. Applications should not
+ * make any assumptions about the content of this structure.
+ * Implementation details can change in future versions without notice. */
+typedef struct psa_cipher_operation_s psa_cipher_operation_t;
+
+/** \def PSA_CIPHER_OPERATION_INIT
+ *
+ * This macro returns a suitable initializer for a cipher operation object of
+ * type #psa_cipher_operation_t.
+ */
+
+/** Return an initial value for a cipher operation object.
+ */
+static psa_cipher_operation_t psa_cipher_operation_init(void);
+
+/** Set the key for a multipart symmetric encryption operation.
+ *
+ * The sequence of operations to encrypt a message with a symmetric cipher
+ * is as follows:
+ * -# Allocate an operation object which will be passed to all the functions
+ * listed here.
+ * -# Initialize the operation object with one of the methods described in the
+ * documentation for #psa_cipher_operation_t, e.g.
+ * #PSA_CIPHER_OPERATION_INIT.
+ * -# Call psa_cipher_encrypt_setup() to specify the algorithm and key.
+ * -# Call either psa_cipher_generate_iv() or psa_cipher_set_iv() to
+ * generate or set the IV (initialization vector). You should use
+ * psa_cipher_generate_iv() unless the protocol you are implementing
+ * requires a specific IV value.
+ * -# Call psa_cipher_update() zero, one or more times, passing a fragment
+ * of the message each time.
+ * -# Call psa_cipher_finish().
+ *
+ * If an error occurs at any step after a call to psa_cipher_encrypt_setup(),
+ * the operation will need to be reset by a call to psa_cipher_abort(). The
+ * application may call psa_cipher_abort() at any time after the operation
+ * has been initialized.
+ *
+ * After a successful call to psa_cipher_encrypt_setup(), the application must
+ * eventually terminate the operation. The following events terminate an
+ * operation:
+ * - A successful call to psa_cipher_finish().
+ * - A call to psa_cipher_abort().
+ *
+ * \param[in,out] operation The operation object to set up. It must have
+ * been initialized as per the documentation for
+ * #psa_cipher_operation_t and not yet in use.
+ * \param key Identifier of the key to use for the operation.
+ * It must remain valid until the operation
+ * terminates. It must allow the usage
+ * #PSA_KEY_USAGE_ENCRYPT.
+ * \param alg The cipher algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_CIPHER(\p alg) is true).
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not a cipher algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be inactive), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_cipher_encrypt_setup(psa_cipher_operation_t *operation,
+ mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg);
+
+/** Set the key for a multipart symmetric decryption operation.
+ *
+ * The sequence of operations to decrypt a message with a symmetric cipher
+ * is as follows:
+ * -# Allocate an operation object which will be passed to all the functions
+ * listed here.
+ * -# Initialize the operation object with one of the methods described in the
+ * documentation for #psa_cipher_operation_t, e.g.
+ * #PSA_CIPHER_OPERATION_INIT.
+ * -# Call psa_cipher_decrypt_setup() to specify the algorithm and key.
+ * -# Call psa_cipher_set_iv() with the IV (initialization vector) for the
+ * decryption. If the IV is prepended to the ciphertext, you can call
+ * psa_cipher_update() on a buffer containing the IV followed by the
+ * beginning of the message.
+ * -# Call psa_cipher_update() zero, one or more times, passing a fragment
+ * of the message each time.
+ * -# Call psa_cipher_finish().
+ *
+ * If an error occurs at any step after a call to psa_cipher_decrypt_setup(),
+ * the operation will need to be reset by a call to psa_cipher_abort(). The
+ * application may call psa_cipher_abort() at any time after the operation
+ * has been initialized.
+ *
+ * After a successful call to psa_cipher_decrypt_setup(), the application must
+ * eventually terminate the operation. The following events terminate an
+ * operation:
+ * - A successful call to psa_cipher_finish().
+ * - A call to psa_cipher_abort().
+ *
+ * \param[in,out] operation The operation object to set up. It must have
+ * been initialized as per the documentation for
+ * #psa_cipher_operation_t and not yet in use.
+ * \param key Identifier of the key to use for the operation.
+ * It must remain valid until the operation
+ * terminates. It must allow the usage
+ * #PSA_KEY_USAGE_DECRYPT.
+ * \param alg The cipher algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_CIPHER(\p alg) is true).
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not a cipher algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be inactive), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_cipher_decrypt_setup(psa_cipher_operation_t *operation,
+ mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg);
+
+/** Generate an IV for a symmetric encryption operation.
+ *
+ * This function generates a random IV (initialization vector), nonce
+ * or initial counter value for the encryption operation as appropriate
+ * for the chosen algorithm, key type and key size.
+ *
+ * The application must call psa_cipher_encrypt_setup() before
+ * calling this function.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_cipher_abort().
+ *
+ * \param[in,out] operation Active cipher operation.
+ * \param[out] iv Buffer where the generated IV is to be written.
+ * \param iv_size Size of the \p iv buffer in bytes.
+ * \param[out] iv_length On success, the number of bytes of the
+ * generated IV.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p iv buffer is too small.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active, with no IV set),
+ * or the library has not been previously initialized
+ * by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation,
+ uint8_t *iv,
+ size_t iv_size,
+ size_t *iv_length);
+
+/** Set the IV for a symmetric encryption or decryption operation.
+ *
+ * This function sets the IV (initialization vector), nonce
+ * or initial counter value for the encryption or decryption operation.
+ *
+ * The application must call psa_cipher_encrypt_setup() before
+ * calling this function.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_cipher_abort().
+ *
+ * \note When encrypting, applications should use psa_cipher_generate_iv()
+ * instead of this function, unless implementing a protocol that requires
+ * a non-random IV.
+ *
+ * \param[in,out] operation Active cipher operation.
+ * \param[in] iv Buffer containing the IV to use.
+ * \param iv_length Size of the IV in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The size of \p iv is not acceptable for the chosen algorithm,
+ * or the chosen algorithm does not use an IV.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be an active cipher
+ * encrypt operation, with no IV set), or the library has not been
+ * previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation,
+ const uint8_t *iv,
+ size_t iv_length);
+
+/** Encrypt or decrypt a message fragment in an active cipher operation.
+ *
+ * Before calling this function, you must:
+ * 1. Call either psa_cipher_encrypt_setup() or psa_cipher_decrypt_setup().
+ * The choice of setup function determines whether this function
+ * encrypts or decrypts its input.
+ * 2. If the algorithm requires an IV, call psa_cipher_generate_iv()
+ * (recommended when encrypting) or psa_cipher_set_iv().
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_cipher_abort().
+ *
+ * \param[in,out] operation Active cipher operation.
+ * \param[in] input Buffer containing the message fragment to
+ * encrypt or decrypt.
+ * \param input_length Size of the \p input buffer in bytes.
+ * \param[out] output Buffer where the output is to be written.
+ * \param output_size Size of the \p output buffer in bytes.
+ * \param[out] output_length On success, the number of bytes
+ * that make up the returned output.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p output buffer is too small.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active, with an IV set
+ * if required for the algorithm), or the library has not been
+ * previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_cipher_update(psa_cipher_operation_t *operation,
+ const uint8_t *input,
+ size_t input_length,
+ uint8_t *output,
+ size_t output_size,
+ size_t *output_length);
+
+/** Finish encrypting or decrypting a message in a cipher operation.
+ *
+ * The application must call psa_cipher_encrypt_setup() or
+ * psa_cipher_decrypt_setup() before calling this function. The choice
+ * of setup function determines whether this function encrypts or
+ * decrypts its input.
+ *
+ * This function finishes the encryption or decryption of the message
+ * formed by concatenating the inputs passed to preceding calls to
+ * psa_cipher_update().
+ *
+ * When this function returns successfully, the operation becomes inactive.
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_cipher_abort().
+ *
+ * \param[in,out] operation Active cipher operation.
+ * \param[out] output Buffer where the output is to be written.
+ * \param output_size Size of the \p output buffer in bytes.
+ * \param[out] output_length On success, the number of bytes
+ * that make up the returned output.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The total input size passed to this operation is not valid for
+ * this particular algorithm. For example, the algorithm is a based
+ * on block cipher and requires a whole number of blocks, but the
+ * total input size is not a multiple of the block size.
+ * \retval #PSA_ERROR_INVALID_PADDING
+ * This is a decryption operation for an algorithm that includes
+ * padding, and the ciphertext does not contain valid padding.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p output buffer is too small.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active, with an IV set
+ * if required for the algorithm), or the library has not been
+ * previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation,
+ uint8_t *output,
+ size_t output_size,
+ size_t *output_length);
+
+/** Abort a cipher operation.
+ *
+ * Aborting an operation frees all associated resources except for the
+ * \p operation structure itself. Once aborted, the operation object
+ * can be reused for another operation by calling
+ * psa_cipher_encrypt_setup() or psa_cipher_decrypt_setup() again.
+ *
+ * You may call this function any time after the operation object has
+ * been initialized as described in #psa_cipher_operation_t.
+ *
+ * In particular, calling psa_cipher_abort() after the operation has been
+ * terminated by a call to psa_cipher_abort() or psa_cipher_finish()
+ * is safe and has no effect.
+ *
+ * \param[in,out] operation Initialized cipher operation.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation);
+
+/**@}*/
+
+/** \defgroup aead Authenticated encryption with associated data (AEAD)
+ * @{
+ */
+
+/** Process an authenticated encryption operation.
+ *
+ * \param key Identifier of the key to use for the
+ * operation. It must allow the usage
+ * #PSA_KEY_USAGE_ENCRYPT.
+ * \param alg The AEAD algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ * \param[in] nonce Nonce or IV to use.
+ * \param nonce_length Size of the \p nonce buffer in bytes.
+ * \param[in] additional_data Additional data that will be authenticated
+ * but not encrypted.
+ * \param additional_data_length Size of \p additional_data in bytes.
+ * \param[in] plaintext Data that will be authenticated and
+ * encrypted.
+ * \param plaintext_length Size of \p plaintext in bytes.
+ * \param[out] ciphertext Output buffer for the authenticated and
+ * encrypted data. The additional data is not
+ * part of this output. For algorithms where the
+ * encrypted data and the authentication tag
+ * are defined as separate outputs, the
+ * authentication tag is appended to the
+ * encrypted data.
+ * \param ciphertext_size Size of the \p ciphertext buffer in bytes.
+ * This must be appropriate for the selected
+ * algorithm and key:
+ * - A sufficient output size is
+ * #PSA_AEAD_ENCRYPT_OUTPUT_SIZE(\c key_type,
+ * \p alg, \p plaintext_length) where
+ * \c key_type is the type of \p key.
+ * - #PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(\p
+ * plaintext_length) evaluates to the maximum
+ * ciphertext size of any supported AEAD
+ * encryption.
+ * \param[out] ciphertext_length On success, the size of the output
+ * in the \p ciphertext buffer.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not an AEAD algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * \p ciphertext_size is too small.
+ * #PSA_AEAD_ENCRYPT_OUTPUT_SIZE(\c key_type, \p alg,
+ * \p plaintext_length) or
+ * #PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(\p plaintext_length) can be used to
+ * determine the required buffer size.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *nonce,
+ size_t nonce_length,
+ const uint8_t *additional_data,
+ size_t additional_data_length,
+ const uint8_t *plaintext,
+ size_t plaintext_length,
+ uint8_t *ciphertext,
+ size_t ciphertext_size,
+ size_t *ciphertext_length);
+
+/** Process an authenticated decryption operation.
+ *
+ * \param key Identifier of the key to use for the
+ * operation. It must allow the usage
+ * #PSA_KEY_USAGE_DECRYPT.
+ * \param alg The AEAD algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ * \param[in] nonce Nonce or IV to use.
+ * \param nonce_length Size of the \p nonce buffer in bytes.
+ * \param[in] additional_data Additional data that has been authenticated
+ * but not encrypted.
+ * \param additional_data_length Size of \p additional_data in bytes.
+ * \param[in] ciphertext Data that has been authenticated and
+ * encrypted. For algorithms where the
+ * encrypted data and the authentication tag
+ * are defined as separate inputs, the buffer
+ * must contain the encrypted data followed
+ * by the authentication tag.
+ * \param ciphertext_length Size of \p ciphertext in bytes.
+ * \param[out] plaintext Output buffer for the decrypted data.
+ * \param plaintext_size Size of the \p plaintext buffer in bytes.
+ * This must be appropriate for the selected
+ * algorithm and key:
+ * - A sufficient output size is
+ * #PSA_AEAD_DECRYPT_OUTPUT_SIZE(\c key_type,
+ * \p alg, \p ciphertext_length) where
+ * \c key_type is the type of \p key.
+ * - #PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(\p
+ * ciphertext_length) evaluates to the maximum
+ * plaintext size of any supported AEAD
+ * decryption.
+ * \param[out] plaintext_length On success, the size of the output
+ * in the \p plaintext buffer.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The ciphertext is not authentic.
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not an AEAD algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * \p plaintext_size is too small.
+ * #PSA_AEAD_DECRYPT_OUTPUT_SIZE(\c key_type, \p alg,
+ * \p ciphertext_length) or
+ * #PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(\p ciphertext_length) can be used
+ * to determine the required buffer size.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *nonce,
+ size_t nonce_length,
+ const uint8_t *additional_data,
+ size_t additional_data_length,
+ const uint8_t *ciphertext,
+ size_t ciphertext_length,
+ uint8_t *plaintext,
+ size_t plaintext_size,
+ size_t *plaintext_length);
+
+/** The type of the state data structure for multipart AEAD operations.
+ *
+ * Before calling any function on an AEAD operation object, the application
+ * must initialize it by any of the following means:
+ * - Set the structure to all-bits-zero, for example:
+ * \code
+ * psa_aead_operation_t operation;
+ * memset(&operation, 0, sizeof(operation));
+ * \endcode
+ * - Initialize the structure to logical zero values, for example:
+ * \code
+ * psa_aead_operation_t operation = {0};
+ * \endcode
+ * - Initialize the structure to the initializer #PSA_AEAD_OPERATION_INIT,
+ * for example:
+ * \code
+ * psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT;
+ * \endcode
+ * - Assign the result of the function psa_aead_operation_init()
+ * to the structure, for example:
+ * \code
+ * psa_aead_operation_t operation;
+ * operation = psa_aead_operation_init();
+ * \endcode
+ *
+ * This is an implementation-defined \c struct. Applications should not
+ * make any assumptions about the content of this structure.
+ * Implementation details can change in future versions without notice. */
+typedef struct psa_aead_operation_s psa_aead_operation_t;
+
+/** \def PSA_AEAD_OPERATION_INIT
+ *
+ * This macro returns a suitable initializer for an AEAD operation object of
+ * type #psa_aead_operation_t.
+ */
+
+/** Return an initial value for an AEAD operation object.
+ */
+static psa_aead_operation_t psa_aead_operation_init(void);
+
+/** Set the key for a multipart authenticated encryption operation.
+ *
+ * The sequence of operations to encrypt a message with authentication
+ * is as follows:
+ * -# Allocate an operation object which will be passed to all the functions
+ * listed here.
+ * -# Initialize the operation object with one of the methods described in the
+ * documentation for #psa_aead_operation_t, e.g.
+ * #PSA_AEAD_OPERATION_INIT.
+ * -# Call psa_aead_encrypt_setup() to specify the algorithm and key.
+ * -# If needed, call psa_aead_set_lengths() to specify the length of the
+ * inputs to the subsequent calls to psa_aead_update_ad() and
+ * psa_aead_update(). See the documentation of psa_aead_set_lengths()
+ * for details.
+ * -# Call either psa_aead_generate_nonce() or psa_aead_set_nonce() to
+ * generate or set the nonce. You should use
+ * psa_aead_generate_nonce() unless the protocol you are implementing
+ * requires a specific nonce value.
+ * -# Call psa_aead_update_ad() zero, one or more times, passing a fragment
+ * of the non-encrypted additional authenticated data each time.
+ * -# Call psa_aead_update() zero, one or more times, passing a fragment
+ * of the message to encrypt each time.
+ * -# Call psa_aead_finish().
+ *
+ * If an error occurs at any step after a call to psa_aead_encrypt_setup(),
+ * the operation will need to be reset by a call to psa_aead_abort(). The
+ * application may call psa_aead_abort() at any time after the operation
+ * has been initialized.
+ *
+ * After a successful call to psa_aead_encrypt_setup(), the application must
+ * eventually terminate the operation. The following events terminate an
+ * operation:
+ * - A successful call to psa_aead_finish().
+ * - A call to psa_aead_abort().
+ *
+ * \param[in,out] operation The operation object to set up. It must have
+ * been initialized as per the documentation for
+ * #psa_aead_operation_t and not yet in use.
+ * \param key Identifier of the key to use for the operation.
+ * It must remain valid until the operation
+ * terminates. It must allow the usage
+ * #PSA_KEY_USAGE_ENCRYPT.
+ * \param alg The AEAD algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be inactive), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not an AEAD algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_encrypt_setup(psa_aead_operation_t *operation,
+ mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg);
+
+/** Set the key for a multipart authenticated decryption operation.
+ *
+ * The sequence of operations to decrypt a message with authentication
+ * is as follows:
+ * -# Allocate an operation object which will be passed to all the functions
+ * listed here.
+ * -# Initialize the operation object with one of the methods described in the
+ * documentation for #psa_aead_operation_t, e.g.
+ * #PSA_AEAD_OPERATION_INIT.
+ * -# Call psa_aead_decrypt_setup() to specify the algorithm and key.
+ * -# If needed, call psa_aead_set_lengths() to specify the length of the
+ * inputs to the subsequent calls to psa_aead_update_ad() and
+ * psa_aead_update(). See the documentation of psa_aead_set_lengths()
+ * for details.
+ * -# Call psa_aead_set_nonce() with the nonce for the decryption.
+ * -# Call psa_aead_update_ad() zero, one or more times, passing a fragment
+ * of the non-encrypted additional authenticated data each time.
+ * -# Call psa_aead_update() zero, one or more times, passing a fragment
+ * of the ciphertext to decrypt each time.
+ * -# Call psa_aead_verify().
+ *
+ * If an error occurs at any step after a call to psa_aead_decrypt_setup(),
+ * the operation will need to be reset by a call to psa_aead_abort(). The
+ * application may call psa_aead_abort() at any time after the operation
+ * has been initialized.
+ *
+ * After a successful call to psa_aead_decrypt_setup(), the application must
+ * eventually terminate the operation. The following events terminate an
+ * operation:
+ * - A successful call to psa_aead_verify().
+ * - A call to psa_aead_abort().
+ *
+ * \param[in,out] operation The operation object to set up. It must have
+ * been initialized as per the documentation for
+ * #psa_aead_operation_t and not yet in use.
+ * \param key Identifier of the key to use for the operation.
+ * It must remain valid until the operation
+ * terminates. It must allow the usage
+ * #PSA_KEY_USAGE_DECRYPT.
+ * \param alg The AEAD algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not compatible with \p alg.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not supported or is not an AEAD algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be inactive), or the
+ * library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_decrypt_setup(psa_aead_operation_t *operation,
+ mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg);
+
+/** Generate a random nonce for an authenticated encryption operation.
+ *
+ * This function generates a random nonce for the authenticated encryption
+ * operation with an appropriate size for the chosen algorithm, key type
+ * and key size.
+ *
+ * The application must call psa_aead_encrypt_setup() before
+ * calling this function.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_aead_abort().
+ *
+ * \param[in,out] operation Active AEAD operation.
+ * \param[out] nonce Buffer where the generated nonce is to be
+ * written.
+ * \param nonce_size Size of the \p nonce buffer in bytes.
+ * \param[out] nonce_length On success, the number of bytes of the
+ * generated nonce.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p nonce buffer is too small.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be an active aead encrypt
+ * operation, with no nonce set), or the library has not been
+ * previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_generate_nonce(psa_aead_operation_t *operation,
+ uint8_t *nonce,
+ size_t nonce_size,
+ size_t *nonce_length);
+
+/** Set the nonce for an authenticated encryption or decryption operation.
+ *
+ * This function sets the nonce for the authenticated
+ * encryption or decryption operation.
+ *
+ * The application must call psa_aead_encrypt_setup() or
+ * psa_aead_decrypt_setup() before calling this function.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_aead_abort().
+ *
+ * \note When encrypting, applications should use psa_aead_generate_nonce()
+ * instead of this function, unless implementing a protocol that requires
+ * a non-random IV.
+ *
+ * \param[in,out] operation Active AEAD operation.
+ * \param[in] nonce Buffer containing the nonce to use.
+ * \param nonce_length Size of the nonce in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The size of \p nonce is not acceptable for the chosen algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active, with no nonce
+ * set), or the library has not been previously initialized
+ * by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_set_nonce(psa_aead_operation_t *operation,
+ const uint8_t *nonce,
+ size_t nonce_length);
+
+/** Declare the lengths of the message and additional data for AEAD.
+ *
+ * The application must call this function before calling
+ * psa_aead_update_ad() or psa_aead_update() if the algorithm for
+ * the operation requires it. If the algorithm does not require it,
+ * calling this function is optional, but if this function is called
+ * then the implementation must enforce the lengths.
+ *
+ * You may call this function before or after setting the nonce with
+ * psa_aead_set_nonce() or psa_aead_generate_nonce().
+ *
+ * - For #PSA_ALG_CCM, calling this function is required.
+ * - For the other AEAD algorithms defined in this specification, calling
+ * this function is not required.
+ * - For vendor-defined algorithm, refer to the vendor documentation.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_aead_abort().
+ *
+ * \param[in,out] operation Active AEAD operation.
+ * \param ad_length Size of the non-encrypted additional
+ * authenticated data in bytes.
+ * \param plaintext_length Size of the plaintext to encrypt in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * At least one of the lengths is not acceptable for the chosen
+ * algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active, and
+ * psa_aead_update_ad() and psa_aead_update() must not have been
+ * called yet), or the library has not been previously initialized
+ * by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_set_lengths(psa_aead_operation_t *operation,
+ size_t ad_length,
+ size_t plaintext_length);
+
+/** Pass additional data to an active AEAD operation.
+ *
+ * Additional data is authenticated, but not encrypted.
+ *
+ * You may call this function multiple times to pass successive fragments
+ * of the additional data. You may not call this function after passing
+ * data to encrypt or decrypt with psa_aead_update().
+ *
+ * Before calling this function, you must:
+ * 1. Call either psa_aead_encrypt_setup() or psa_aead_decrypt_setup().
+ * 2. Set the nonce with psa_aead_generate_nonce() or psa_aead_set_nonce().
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_aead_abort().
+ *
+ * \warning When decrypting, until psa_aead_verify() has returned #PSA_SUCCESS,
+ * there is no guarantee that the input is valid. Therefore, until
+ * you have called psa_aead_verify() and it has returned #PSA_SUCCESS,
+ * treat the input as untrusted and prepare to undo any action that
+ * depends on the input if psa_aead_verify() returns an error status.
+ *
+ * \param[in,out] operation Active AEAD operation.
+ * \param[in] input Buffer containing the fragment of
+ * additional data.
+ * \param input_length Size of the \p input buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The total input length overflows the additional data length that
+ * was previously specified with psa_aead_set_lengths().
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active, have a nonce
+ * set, have lengths set if required by the algorithm, and
+ * psa_aead_update() must not have been called yet), or the library
+ * has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_update_ad(psa_aead_operation_t *operation,
+ const uint8_t *input,
+ size_t input_length);
+
+/** Encrypt or decrypt a message fragment in an active AEAD operation.
+ *
+ * Before calling this function, you must:
+ * 1. Call either psa_aead_encrypt_setup() or psa_aead_decrypt_setup().
+ * The choice of setup function determines whether this function
+ * encrypts or decrypts its input.
+ * 2. Set the nonce with psa_aead_generate_nonce() or psa_aead_set_nonce().
+ * 3. Call psa_aead_update_ad() to pass all the additional data.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_aead_abort().
+ *
+ * \warning When decrypting, until psa_aead_verify() has returned #PSA_SUCCESS,
+ * there is no guarantee that the input is valid. Therefore, until
+ * you have called psa_aead_verify() and it has returned #PSA_SUCCESS:
+ * - Do not use the output in any way other than storing it in a
+ * confidential location. If you take any action that depends
+ * on the tentative decrypted data, this action will need to be
+ * undone if the input turns out not to be valid. Furthermore,
+ * if an adversary can observe that this action took place
+ * (for example through timing), they may be able to use this
+ * fact as an oracle to decrypt any message encrypted with the
+ * same key.
+ * - In particular, do not copy the output anywhere but to a
+ * memory or storage space that you have exclusive access to.
+ *
+ * This function does not require the input to be aligned to any
+ * particular block boundary. If the implementation can only process
+ * a whole block at a time, it must consume all the input provided, but
+ * it may delay the end of the corresponding output until a subsequent
+ * call to psa_aead_update(), psa_aead_finish() or psa_aead_verify()
+ * provides sufficient input. The amount of data that can be delayed
+ * in this way is bounded by #PSA_AEAD_UPDATE_OUTPUT_SIZE.
+ *
+ * \param[in,out] operation Active AEAD operation.
+ * \param[in] input Buffer containing the message fragment to
+ * encrypt or decrypt.
+ * \param input_length Size of the \p input buffer in bytes.
+ * \param[out] output Buffer where the output is to be written.
+ * \param output_size Size of the \p output buffer in bytes.
+ * This must be appropriate for the selected
+ * algorithm and key:
+ * - A sufficient output size is
+ * #PSA_AEAD_UPDATE_OUTPUT_SIZE(\c key_type,
+ * \c alg, \p input_length) where
+ * \c key_type is the type of key and \c alg is
+ * the algorithm that were used to set up the
+ * operation.
+ * - #PSA_AEAD_UPDATE_OUTPUT_MAX_SIZE(\p
+ * input_length) evaluates to the maximum
+ * output size of any supported AEAD
+ * algorithm.
+ * \param[out] output_length On success, the number of bytes
+ * that make up the returned output.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p output buffer is too small.
+ * #PSA_AEAD_UPDATE_OUTPUT_SIZE(\c key_type, \c alg, \p input_length) or
+ * #PSA_AEAD_UPDATE_OUTPUT_MAX_SIZE(\p input_length) can be used to
+ * determine the required buffer size.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The total length of input to psa_aead_update_ad() so far is
+ * less than the additional data length that was previously
+ * specified with psa_aead_set_lengths(), or
+ * the total input length overflows the plaintext length that
+ * was previously specified with psa_aead_set_lengths().
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active, have a nonce
+ * set, and have lengths set if required by the algorithm), or the
+ * library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_update(psa_aead_operation_t *operation,
+ const uint8_t *input,
+ size_t input_length,
+ uint8_t *output,
+ size_t output_size,
+ size_t *output_length);
+
+/** Finish encrypting a message in an AEAD operation.
+ *
+ * The operation must have been set up with psa_aead_encrypt_setup().
+ *
+ * This function finishes the authentication of the additional data
+ * formed by concatenating the inputs passed to preceding calls to
+ * psa_aead_update_ad() with the plaintext formed by concatenating the
+ * inputs passed to preceding calls to psa_aead_update().
+ *
+ * This function has two output buffers:
+ * - \p ciphertext contains trailing ciphertext that was buffered from
+ * preceding calls to psa_aead_update().
+ * - \p tag contains the authentication tag.
+ *
+ * When this function returns successfully, the operation becomes inactive.
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_aead_abort().
+ *
+ * \param[in,out] operation Active AEAD operation.
+ * \param[out] ciphertext Buffer where the last part of the ciphertext
+ * is to be written.
+ * \param ciphertext_size Size of the \p ciphertext buffer in bytes.
+ * This must be appropriate for the selected
+ * algorithm and key:
+ * - A sufficient output size is
+ * #PSA_AEAD_FINISH_OUTPUT_SIZE(\c key_type,
+ * \c alg) where \c key_type is the type of key
+ * and \c alg is the algorithm that were used to
+ * set up the operation.
+ * - #PSA_AEAD_FINISH_OUTPUT_MAX_SIZE evaluates to
+ * the maximum output size of any supported AEAD
+ * algorithm.
+ * \param[out] ciphertext_length On success, the number of bytes of
+ * returned ciphertext.
+ * \param[out] tag Buffer where the authentication tag is
+ * to be written.
+ * \param tag_size Size of the \p tag buffer in bytes.
+ * This must be appropriate for the selected
+ * algorithm and key:
+ * - The exact tag size is #PSA_AEAD_TAG_LENGTH(\c
+ * key_type, \c key_bits, \c alg) where
+ * \c key_type and \c key_bits are the type and
+ * bit-size of the key, and \c alg is the
+ * algorithm that were used in the call to
+ * psa_aead_encrypt_setup().
+ * - #PSA_AEAD_TAG_MAX_SIZE evaluates to the
+ * maximum tag size of any supported AEAD
+ * algorithm.
+ * \param[out] tag_length On success, the number of bytes
+ * that make up the returned tag.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p ciphertext or \p tag buffer is too small.
+ * #PSA_AEAD_FINISH_OUTPUT_SIZE(\c key_type, \c alg) or
+ * #PSA_AEAD_FINISH_OUTPUT_MAX_SIZE can be used to determine the
+ * required \p ciphertext buffer size. #PSA_AEAD_TAG_LENGTH(\c key_type,
+ * \c key_bits, \c alg) or #PSA_AEAD_TAG_MAX_SIZE can be used to
+ * determine the required \p tag buffer size.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The total length of input to psa_aead_update_ad() so far is
+ * less than the additional data length that was previously
+ * specified with psa_aead_set_lengths(), or
+ * the total length of input to psa_aead_update() so far is
+ * less than the plaintext length that was previously
+ * specified with psa_aead_set_lengths().
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be an active encryption
+ * operation with a nonce set), or the library has not been previously
+ * initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_finish(psa_aead_operation_t *operation,
+ uint8_t *ciphertext,
+ size_t ciphertext_size,
+ size_t *ciphertext_length,
+ uint8_t *tag,
+ size_t tag_size,
+ size_t *tag_length);
+
+/** Finish authenticating and decrypting a message in an AEAD operation.
+ *
+ * The operation must have been set up with psa_aead_decrypt_setup().
+ *
+ * This function finishes the authenticated decryption of the message
+ * components:
+ *
+ * - The additional data consisting of the concatenation of the inputs
+ * passed to preceding calls to psa_aead_update_ad().
+ * - The ciphertext consisting of the concatenation of the inputs passed to
+ * preceding calls to psa_aead_update().
+ * - The tag passed to this function call.
+ *
+ * If the authentication tag is correct, this function outputs any remaining
+ * plaintext and reports success. If the authentication tag is not correct,
+ * this function returns #PSA_ERROR_INVALID_SIGNATURE.
+ *
+ * When this function returns successfully, the operation becomes inactive.
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_aead_abort().
+ *
+ * \note Implementations shall make the best effort to ensure that the
+ * comparison between the actual tag and the expected tag is performed
+ * in constant time.
+ *
+ * \param[in,out] operation Active AEAD operation.
+ * \param[out] plaintext Buffer where the last part of the plaintext
+ * is to be written. This is the remaining data
+ * from previous calls to psa_aead_update()
+ * that could not be processed until the end
+ * of the input.
+ * \param plaintext_size Size of the \p plaintext buffer in bytes.
+ * This must be appropriate for the selected algorithm and key:
+ * - A sufficient output size is
+ * #PSA_AEAD_VERIFY_OUTPUT_SIZE(\c key_type,
+ * \c alg) where \c key_type is the type of key
+ * and \c alg is the algorithm that were used to
+ * set up the operation.
+ * - #PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE evaluates to
+ * the maximum output size of any supported AEAD
+ * algorithm.
+ * \param[out] plaintext_length On success, the number of bytes of
+ * returned plaintext.
+ * \param[in] tag Buffer containing the authentication tag.
+ * \param tag_length Size of the \p tag buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The calculations were successful, but the authentication tag is
+ * not correct.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p plaintext buffer is too small.
+ * #PSA_AEAD_VERIFY_OUTPUT_SIZE(\c key_type, \c alg) or
+ * #PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE can be used to determine the
+ * required buffer size.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The total length of input to psa_aead_update_ad() so far is
+ * less than the additional data length that was previously
+ * specified with psa_aead_set_lengths(), or
+ * the total length of input to psa_aead_update() so far is
+ * less than the plaintext length that was previously
+ * specified with psa_aead_set_lengths().
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be an active decryption
+ * operation with a nonce set), or the library has not been previously
+ * initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_verify(psa_aead_operation_t *operation,
+ uint8_t *plaintext,
+ size_t plaintext_size,
+ size_t *plaintext_length,
+ const uint8_t *tag,
+ size_t tag_length);
+
+/** Abort an AEAD operation.
+ *
+ * Aborting an operation frees all associated resources except for the
+ * \p operation structure itself. Once aborted, the operation object
+ * can be reused for another operation by calling
+ * psa_aead_encrypt_setup() or psa_aead_decrypt_setup() again.
+ *
+ * You may call this function any time after the operation object has
+ * been initialized as described in #psa_aead_operation_t.
+ *
+ * In particular, calling psa_aead_abort() after the operation has been
+ * terminated by a call to psa_aead_abort(), psa_aead_finish() or
+ * psa_aead_verify() is safe and has no effect.
+ *
+ * \param[in,out] operation Initialized AEAD operation.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_aead_abort(psa_aead_operation_t *operation);
+
+/**@}*/
+
+/** \defgroup asymmetric Asymmetric cryptography
+ * @{
+ */
+
+/**
+ * \brief Sign a message with a private key. For hash-and-sign algorithms,
+ * this includes the hashing step.
+ *
+ * \note To perform a multi-part hash-and-sign signature algorithm, first use
+ * a multi-part hash operation and then pass the resulting hash to
+ * psa_sign_hash(). PSA_ALG_GET_HASH(\p alg) can be used to determine the
+ * hash algorithm to use.
+ *
+ * \param[in] key Identifier of the key to use for the operation.
+ * It must be an asymmetric key pair. The key must
+ * allow the usage #PSA_KEY_USAGE_SIGN_MESSAGE.
+ * \param[in] alg An asymmetric signature algorithm (PSA_ALG_XXX
+ * value such that #PSA_ALG_IS_SIGN_MESSAGE(\p alg)
+ * is true), that is compatible with the type of
+ * \p key.
+ * \param[in] input The input message to sign.
+ * \param[in] input_length Size of the \p input buffer in bytes.
+ * \param[out] signature Buffer where the signature is to be written.
+ * \param[in] signature_size Size of the \p signature buffer in bytes. This
+ * must be appropriate for the selected
+ * algorithm and key:
+ * - The required signature size is
+ * #PSA_SIGN_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg)
+ * where \c key_type and \c key_bits are the type and
+ * bit-size respectively of key.
+ * - #PSA_SIGNATURE_MAX_SIZE evaluates to the
+ * maximum signature size of any supported
+ * signature algorithm.
+ * \param[out] signature_length On success, the number of bytes that make up
+ * the returned signature value.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The key does not have the #PSA_KEY_USAGE_SIGN_MESSAGE flag,
+ * or it does not permit the requested algorithm.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p signature buffer is too small. You can
+ * determine a sufficient buffer size by calling
+ * #PSA_SIGN_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg)
+ * where \c key_type and \c key_bits are the type and bit-size
+ * respectively of \p key.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_sign_message(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *input,
+ size_t input_length,
+ uint8_t *signature,
+ size_t signature_size,
+ size_t *signature_length);
+
+/** \brief Verify the signature of a message with a public key, using
+ * a hash-and-sign verification algorithm.
+ *
+ * \note To perform a multi-part hash-and-sign signature verification
+ * algorithm, first use a multi-part hash operation to hash the message
+ * and then pass the resulting hash to psa_verify_hash().
+ * PSA_ALG_GET_HASH(\p alg) can be used to determine the hash algorithm
+ * to use.
+ *
+ * \param[in] key Identifier of the key to use for the operation.
+ * It must be a public key or an asymmetric key
+ * pair. The key must allow the usage
+ * #PSA_KEY_USAGE_VERIFY_MESSAGE.
+ * \param[in] alg An asymmetric signature algorithm (PSA_ALG_XXX
+ * value such that #PSA_ALG_IS_SIGN_MESSAGE(\p alg)
+ * is true), that is compatible with the type of
+ * \p key.
+ * \param[in] input The message whose signature is to be verified.
+ * \param[in] input_length Size of the \p input buffer in bytes.
+ * \param[out] signature Buffer containing the signature to verify.
+ * \param[in] signature_length Size of the \p signature buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The key does not have the #PSA_KEY_USAGE_SIGN_MESSAGE flag,
+ * or it does not permit the requested algorithm.
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The calculation was performed successfully, but the passed signature
+ * is not a valid signature.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_verify_message(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *input,
+ size_t input_length,
+ const uint8_t *signature,
+ size_t signature_length);
+
+/**
+ * \brief Sign a hash or short message with a private key.
+ *
+ * Note that to perform a hash-and-sign signature algorithm, you must
+ * first calculate the hash by calling psa_hash_setup(), psa_hash_update()
+ * and psa_hash_finish(), or alternatively by calling psa_hash_compute().
+ * Then pass the resulting hash as the \p hash
+ * parameter to this function. You can use #PSA_ALG_SIGN_GET_HASH(\p alg)
+ * to determine the hash algorithm to use.
+ *
+ * \param key Identifier of the key to use for the operation.
+ * It must be an asymmetric key pair. The key must
+ * allow the usage #PSA_KEY_USAGE_SIGN_HASH.
+ * \param alg A signature algorithm (PSA_ALG_XXX
+ * value such that #PSA_ALG_IS_SIGN_HASH(\p alg)
+ * is true), that is compatible with
+ * the type of \p key.
+ * \param[in] hash The hash or message to sign.
+ * \param hash_length Size of the \p hash buffer in bytes.
+ * \param[out] signature Buffer where the signature is to be written.
+ * \param signature_size Size of the \p signature buffer in bytes.
+ * \param[out] signature_length On success, the number of bytes
+ * that make up the returned signature value.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p signature buffer is too small. You can
+ * determine a sufficient buffer size by calling
+ * #PSA_SIGN_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg)
+ * where \c key_type and \c key_bits are the type and bit-size
+ * respectively of \p key.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_sign_hash(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *hash,
+ size_t hash_length,
+ uint8_t *signature,
+ size_t signature_size,
+ size_t *signature_length);
+
+/**
+ * \brief Verify the signature of a hash or short message using a public key.
+ *
+ * Note that to perform a hash-and-sign signature algorithm, you must
+ * first calculate the hash by calling psa_hash_setup(), psa_hash_update()
+ * and psa_hash_finish(), or alternatively by calling psa_hash_compute().
+ * Then pass the resulting hash as the \p hash
+ * parameter to this function. You can use #PSA_ALG_SIGN_GET_HASH(\p alg)
+ * to determine the hash algorithm to use.
+ *
+ * \param key Identifier of the key to use for the operation. It
+ * must be a public key or an asymmetric key pair. The
+ * key must allow the usage
+ * #PSA_KEY_USAGE_VERIFY_HASH.
+ * \param alg A signature algorithm (PSA_ALG_XXX
+ * value such that #PSA_ALG_IS_SIGN_HASH(\p alg)
+ * is true), that is compatible with
+ * the type of \p key.
+ * \param[in] hash The hash or message whose signature is to be
+ * verified.
+ * \param hash_length Size of the \p hash buffer in bytes.
+ * \param[in] signature Buffer containing the signature to verify.
+ * \param signature_length Size of the \p signature buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * The signature is valid.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The calculation was performed successfully, but the passed
+ * signature is not a valid signature.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_verify_hash(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *hash,
+ size_t hash_length,
+ const uint8_t *signature,
+ size_t signature_length);
+
+/**
+ * \brief Encrypt a short message with a public key.
+ *
+ * \param key Identifier of the key to use for the operation.
+ * It must be a public key or an asymmetric key
+ * pair. It must allow the usage
+ * #PSA_KEY_USAGE_ENCRYPT.
+ * \param alg An asymmetric encryption algorithm that is
+ * compatible with the type of \p key.
+ * \param[in] input The message to encrypt.
+ * \param input_length Size of the \p input buffer in bytes.
+ * \param[in] salt A salt or label, if supported by the
+ * encryption algorithm.
+ * If the algorithm does not support a
+ * salt, pass \c NULL.
+ * If the algorithm supports an optional
+ * salt and you do not want to pass a salt,
+ * pass \c NULL.
+ *
+ * - For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is
+ * supported.
+ * \param salt_length Size of the \p salt buffer in bytes.
+ * If \p salt is \c NULL, pass 0.
+ * \param[out] output Buffer where the encrypted message is to
+ * be written.
+ * \param output_size Size of the \p output buffer in bytes.
+ * \param[out] output_length On success, the number of bytes
+ * that make up the returned output.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p output buffer is too small. You can
+ * determine a sufficient buffer size by calling
+ * #PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg)
+ * where \c key_type and \c key_bits are the type and bit-size
+ * respectively of \p key.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_asymmetric_encrypt(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *input,
+ size_t input_length,
+ const uint8_t *salt,
+ size_t salt_length,
+ uint8_t *output,
+ size_t output_size,
+ size_t *output_length);
+
+/**
+ * \brief Decrypt a short message with a private key.
+ *
+ * \param key Identifier of the key to use for the operation.
+ * It must be an asymmetric key pair. It must
+ * allow the usage #PSA_KEY_USAGE_DECRYPT.
+ * \param alg An asymmetric encryption algorithm that is
+ * compatible with the type of \p key.
+ * \param[in] input The message to decrypt.
+ * \param input_length Size of the \p input buffer in bytes.
+ * \param[in] salt A salt or label, if supported by the
+ * encryption algorithm.
+ * If the algorithm does not support a
+ * salt, pass \c NULL.
+ * If the algorithm supports an optional
+ * salt and you do not want to pass a salt,
+ * pass \c NULL.
+ *
+ * - For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is
+ * supported.
+ * \param salt_length Size of the \p salt buffer in bytes.
+ * If \p salt is \c NULL, pass 0.
+ * \param[out] output Buffer where the decrypted message is to
+ * be written.
+ * \param output_size Size of the \c output buffer in bytes.
+ * \param[out] output_length On success, the number of bytes
+ * that make up the returned output.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p output buffer is too small. You can
+ * determine a sufficient buffer size by calling
+ * #PSA_ASYMMETRIC_DECRYPT_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg)
+ * where \c key_type and \c key_bits are the type and bit-size
+ * respectively of \p key.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_INVALID_PADDING \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_asymmetric_decrypt(mbedtls_svc_key_id_t key,
+ psa_algorithm_t alg,
+ const uint8_t *input,
+ size_t input_length,
+ const uint8_t *salt,
+ size_t salt_length,
+ uint8_t *output,
+ size_t output_size,
+ size_t *output_length);
+
+/**@}*/
+
+/** \defgroup key_derivation Key derivation and pseudorandom generation
+ * @{
+ */
+
+/** The type of the state data structure for key derivation operations.
+ *
+ * Before calling any function on a key derivation operation object, the
+ * application must initialize it by any of the following means:
+ * - Set the structure to all-bits-zero, for example:
+ * \code
+ * psa_key_derivation_operation_t operation;
+ * memset(&operation, 0, sizeof(operation));
+ * \endcode
+ * - Initialize the structure to logical zero values, for example:
+ * \code
+ * psa_key_derivation_operation_t operation = {0};
+ * \endcode
+ * - Initialize the structure to the initializer #PSA_KEY_DERIVATION_OPERATION_INIT,
+ * for example:
+ * \code
+ * psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT;
+ * \endcode
+ * - Assign the result of the function psa_key_derivation_operation_init()
+ * to the structure, for example:
+ * \code
+ * psa_key_derivation_operation_t operation;
+ * operation = psa_key_derivation_operation_init();
+ * \endcode
+ *
+ * This is an implementation-defined \c struct. Applications should not
+ * make any assumptions about the content of this structure.
+ * Implementation details can change in future versions without notice.
+ */
+typedef struct psa_key_derivation_s psa_key_derivation_operation_t;
+
+/** \def PSA_KEY_DERIVATION_OPERATION_INIT
+ *
+ * This macro returns a suitable initializer for a key derivation operation
+ * object of type #psa_key_derivation_operation_t.
+ */
+
+/** Return an initial value for a key derivation operation object.
+ */
+static psa_key_derivation_operation_t psa_key_derivation_operation_init(void);
+
+/** Set up a key derivation operation.
+ *
+ * A key derivation algorithm takes some inputs and uses them to generate
+ * a byte stream in a deterministic way.
+ * This byte stream can be used to produce keys and other
+ * cryptographic material.
+ *
+ * To derive a key:
+ * -# Start with an initialized object of type #psa_key_derivation_operation_t.
+ * -# Call psa_key_derivation_setup() to select the algorithm.
+ * -# Provide the inputs for the key derivation by calling
+ * psa_key_derivation_input_bytes() or psa_key_derivation_input_key()
+ * as appropriate. Which inputs are needed, in what order, and whether
+ * they may be keys and if so of what type depends on the algorithm.
+ * -# Optionally set the operation's maximum capacity with
+ * psa_key_derivation_set_capacity(). You may do this before, in the middle
+ * of or after providing inputs. For some algorithms, this step is mandatory
+ * because the output depends on the maximum capacity.
+ * -# To derive a key, call psa_key_derivation_output_key().
+ * To derive a byte string for a different purpose, call
+ * psa_key_derivation_output_bytes().
+ * Successive calls to these functions use successive output bytes
+ * calculated by the key derivation algorithm.
+ * -# Clean up the key derivation operation object with
+ * psa_key_derivation_abort().
+ *
+ * If this function returns an error, the key derivation operation object is
+ * not changed.
+ *
+ * If an error occurs at any step after a call to psa_key_derivation_setup(),
+ * the operation will need to be reset by a call to psa_key_derivation_abort().
+ *
+ * Implementations must reject an attempt to derive a key of size 0.
+ *
+ * \param[in,out] operation The key derivation operation object
+ * to set up. It must
+ * have been initialized but not set up yet.
+ * \param alg The key derivation algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_KEY_DERIVATION(\p alg) is true).
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \c alg is not a key derivation algorithm.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \c alg is not supported or is not a key derivation algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be inactive), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_setup(
+ psa_key_derivation_operation_t *operation,
+ psa_algorithm_t alg);
+
+/** Retrieve the current capacity of a key derivation operation.
+ *
+ * The capacity of a key derivation is the maximum number of bytes that it can
+ * return. When you get *N* bytes of output from a key derivation operation,
+ * this reduces its capacity by *N*.
+ *
+ * \param[in] operation The operation to query.
+ * \param[out] capacity On success, the capacity of the operation.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_get_capacity(
+ const psa_key_derivation_operation_t *operation,
+ size_t *capacity);
+
+/** Set the maximum capacity of a key derivation operation.
+ *
+ * The capacity of a key derivation operation is the maximum number of bytes
+ * that the key derivation operation can return from this point onwards.
+ *
+ * \param[in,out] operation The key derivation operation object to modify.
+ * \param capacity The new capacity of the operation.
+ * It must be less or equal to the operation's
+ * current capacity.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p capacity is larger than the operation's current capacity.
+ * In this case, the operation object remains valid and its capacity
+ * remains unchanged.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active), or the
+ * library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_set_capacity(
+ psa_key_derivation_operation_t *operation,
+ size_t capacity);
+
+/** Use the maximum possible capacity for a key derivation operation.
+ *
+ * Use this value as the capacity argument when setting up a key derivation
+ * to indicate that the operation should have the maximum possible capacity.
+ * The value of the maximum possible capacity depends on the key derivation
+ * algorithm.
+ */
+#define PSA_KEY_DERIVATION_UNLIMITED_CAPACITY ((size_t) (-1))
+
+/** Provide an input for key derivation or key agreement.
+ *
+ * Which inputs are required and in what order depends on the algorithm.
+ * Refer to the documentation of each key derivation or key agreement
+ * algorithm for information.
+ *
+ * This function passes direct inputs, which is usually correct for
+ * non-secret inputs. To pass a secret input, which should be in a key
+ * object, call psa_key_derivation_input_key() instead of this function.
+ * Refer to the documentation of individual step types
+ * (`PSA_KEY_DERIVATION_INPUT_xxx` values of type ::psa_key_derivation_step_t)
+ * for more information.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_key_derivation_abort().
+ *
+ * \param[in,out] operation The key derivation operation object to use.
+ * It must have been set up with
+ * psa_key_derivation_setup() and must not
+ * have produced any output yet.
+ * \param step Which step the input data is for.
+ * \param[in] data Input data to use.
+ * \param data_length Size of the \p data buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \c step is not compatible with the operation's algorithm, or
+ * \c step does not allow direct inputs.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid for this input \p step, or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_input_bytes(
+ psa_key_derivation_operation_t *operation,
+ psa_key_derivation_step_t step,
+ const uint8_t *data,
+ size_t data_length);
+
+/** Provide a numeric input for key derivation or key agreement.
+ *
+ * Which inputs are required and in what order depends on the algorithm.
+ * However, when an algorithm requires a particular order, numeric inputs
+ * usually come first as they tend to be configuration parameters.
+ * Refer to the documentation of each key derivation or key agreement
+ * algorithm for information.
+ *
+ * This function is used for inputs which are fixed-size non-negative
+ * integers.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_key_derivation_abort().
+ *
+ * \param[in,out] operation The key derivation operation object to use.
+ * It must have been set up with
+ * psa_key_derivation_setup() and must not
+ * have produced any output yet.
+ * \param step Which step the input data is for.
+ * \param[in] value The value of the numeric input.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \c step is not compatible with the operation's algorithm, or
+ * \c step does not allow numeric inputs.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid for this input \p step, or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_input_integer(
+ psa_key_derivation_operation_t *operation,
+ psa_key_derivation_step_t step,
+ uint64_t value);
+
+/** Provide an input for key derivation in the form of a key.
+ *
+ * Which inputs are required and in what order depends on the algorithm.
+ * Refer to the documentation of each key derivation or key agreement
+ * algorithm for information.
+ *
+ * This function obtains input from a key object, which is usually correct for
+ * secret inputs or for non-secret personalization strings kept in the key
+ * store. To pass a non-secret parameter which is not in the key store,
+ * call psa_key_derivation_input_bytes() instead of this function.
+ * Refer to the documentation of individual step types
+ * (`PSA_KEY_DERIVATION_INPUT_xxx` values of type ::psa_key_derivation_step_t)
+ * for more information.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_key_derivation_abort().
+ *
+ * \param[in,out] operation The key derivation operation object to use.
+ * It must have been set up with
+ * psa_key_derivation_setup() and must not
+ * have produced any output yet.
+ * \param step Which step the input data is for.
+ * \param key Identifier of the key. It must have an
+ * appropriate type for step and must allow the
+ * usage #PSA_KEY_USAGE_DERIVE or
+ * #PSA_KEY_USAGE_VERIFY_DERIVATION (see note)
+ * and the algorithm used by the operation.
+ *
+ * \note Once all inputs steps are completed, the operations will allow:
+ * - psa_key_derivation_output_bytes() if each input was either a direct input
+ * or a key with #PSA_KEY_USAGE_DERIVE set;
+ * - psa_key_derivation_output_key() if the input for step
+ * #PSA_KEY_DERIVATION_INPUT_SECRET or #PSA_KEY_DERIVATION_INPUT_PASSWORD
+ * was from a key slot with #PSA_KEY_USAGE_DERIVE and each other input was
+ * either a direct input or a key with #PSA_KEY_USAGE_DERIVE set;
+ * - psa_key_derivation_verify_bytes() if each input was either a direct input
+ * or a key with #PSA_KEY_USAGE_VERIFY_DERIVATION set;
+ * - psa_key_derivation_verify_key() under the same conditions as
+ * psa_key_derivation_verify_bytes().
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The key allows neither #PSA_KEY_USAGE_DERIVE nor
+ * #PSA_KEY_USAGE_VERIFY_DERIVATION, or it doesn't allow this
+ * algorithm.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \c step is not compatible with the operation's algorithm, or
+ * \c step does not allow key inputs of the given type
+ * or does not allow key inputs at all.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid for this input \p step, or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_input_key(
+ psa_key_derivation_operation_t *operation,
+ psa_key_derivation_step_t step,
+ mbedtls_svc_key_id_t key);
+
+/** Perform a key agreement and use the shared secret as input to a key
+ * derivation.
+ *
+ * A key agreement algorithm takes two inputs: a private key \p private_key
+ * a public key \p peer_key.
+ * The result of this function is passed as input to a key derivation.
+ * The output of this key derivation can be extracted by reading from the
+ * resulting operation to produce keys and other cryptographic material.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_key_derivation_abort().
+ *
+ * \param[in,out] operation The key derivation operation object to use.
+ * It must have been set up with
+ * psa_key_derivation_setup() with a
+ * key agreement and derivation algorithm
+ * \c alg (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_KEY_AGREEMENT(\c alg) is true
+ * and #PSA_ALG_IS_RAW_KEY_AGREEMENT(\c alg)
+ * is false).
+ * The operation must be ready for an
+ * input of the type given by \p step.
+ * \param step Which step the input data is for.
+ * \param private_key Identifier of the private key to use. It must
+ * allow the usage #PSA_KEY_USAGE_DERIVE.
+ * \param[in] peer_key Public key of the peer. The peer key must be in the
+ * same format that psa_import_key() accepts for the
+ * public key type corresponding to the type of
+ * private_key. That is, this function performs the
+ * equivalent of
+ * #psa_import_key(...,
+ * `peer_key`, `peer_key_length`) where
+ * with key attributes indicating the public key
+ * type corresponding to the type of `private_key`.
+ * For example, for EC keys, this means that peer_key
+ * is interpreted as a point on the curve that the
+ * private key is on. The standard formats for public
+ * keys are documented in the documentation of
+ * psa_export_public_key().
+ * \param peer_key_length Size of \p peer_key in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \c private_key is not compatible with \c alg,
+ * or \p peer_key is not valid for \c alg or not compatible with
+ * \c private_key, or \c step does not allow an input resulting
+ * from a key agreement.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \c alg is not supported or is not a key derivation algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid for this key agreement \p step,
+ * or the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_key_agreement(
+ psa_key_derivation_operation_t *operation,
+ psa_key_derivation_step_t step,
+ mbedtls_svc_key_id_t private_key,
+ const uint8_t *peer_key,
+ size_t peer_key_length);
+
+/** Read some data from a key derivation operation.
+ *
+ * This function calculates output bytes from a key derivation algorithm and
+ * return those bytes.
+ * If you view the key derivation's output as a stream of bytes, this
+ * function destructively reads the requested number of bytes from the
+ * stream.
+ * The operation's capacity decreases by the number of bytes read.
+ *
+ * If this function returns an error status other than
+ * #PSA_ERROR_INSUFFICIENT_DATA, the operation enters an error
+ * state and must be aborted by calling psa_key_derivation_abort().
+ *
+ * \param[in,out] operation The key derivation operation object to read from.
+ * \param[out] output Buffer where the output will be written.
+ * \param output_length Number of bytes to output.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * One of the inputs was a key whose policy didn't allow
+ * #PSA_KEY_USAGE_DERIVE.
+ * \retval #PSA_ERROR_INSUFFICIENT_DATA
+ * The operation's capacity was less than
+ * \p output_length bytes. Note that in this case,
+ * no output is written to the output buffer.
+ * The operation's capacity is set to 0, thus
+ * subsequent calls to this function will not
+ * succeed, even with a smaller output buffer.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active and completed
+ * all required input steps), or the library has not been previously
+ * initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_output_bytes(
+ psa_key_derivation_operation_t *operation,
+ uint8_t *output,
+ size_t output_length);
+
+/** Derive a key from an ongoing key derivation operation.
+ *
+ * This function calculates output bytes from a key derivation algorithm
+ * and uses those bytes to generate a key deterministically.
+ * The key's location, usage policy, type and size are taken from
+ * \p attributes.
+ *
+ * If you view the key derivation's output as a stream of bytes, this
+ * function destructively reads as many bytes as required from the
+ * stream.
+ * The operation's capacity decreases by the number of bytes read.
+ *
+ * If this function returns an error status other than
+ * #PSA_ERROR_INSUFFICIENT_DATA, the operation enters an error
+ * state and must be aborted by calling psa_key_derivation_abort().
+ *
+ * How much output is produced and consumed from the operation, and how
+ * the key is derived, depends on the key type and on the key size
+ * (denoted \c bits below):
+ *
+ * - For key types for which the key is an arbitrary sequence of bytes
+ * of a given size, this function is functionally equivalent to
+ * calling #psa_key_derivation_output_bytes
+ * and passing the resulting output to #psa_import_key.
+ * However, this function has a security benefit:
+ * if the implementation provides an isolation boundary then
+ * the key material is not exposed outside the isolation boundary.
+ * As a consequence, for these key types, this function always consumes
+ * exactly (\c bits / 8) bytes from the operation.
+ * The following key types defined in this specification follow this scheme:
+ *
+ * - #PSA_KEY_TYPE_AES;
+ * - #PSA_KEY_TYPE_ARIA;
+ * - #PSA_KEY_TYPE_CAMELLIA;
+ * - #PSA_KEY_TYPE_DERIVE;
+ * - #PSA_KEY_TYPE_HMAC;
+ * - #PSA_KEY_TYPE_PASSWORD_HASH.
+ *
+ * - For ECC keys on a Montgomery elliptic curve
+ * (#PSA_KEY_TYPE_ECC_KEY_PAIR(\c curve) where \c curve designates a
+ * Montgomery curve), this function always draws a byte string whose
+ * length is determined by the curve, and sets the mandatory bits
+ * accordingly. That is:
+ *
+ * - Curve25519 (#PSA_ECC_FAMILY_MONTGOMERY, 255 bits): draw a 32-byte
+ * string and process it as specified in RFC 7748 &sect;5.
+ * - Curve448 (#PSA_ECC_FAMILY_MONTGOMERY, 448 bits): draw a 56-byte
+ * string and process it as specified in RFC 7748 &sect;5.
+ *
+ * - For key types for which the key is represented by a single sequence of
+ * \c bits bits with constraints as to which bit sequences are acceptable,
+ * this function draws a byte string of length (\c bits / 8) bytes rounded
+ * up to the nearest whole number of bytes. If the resulting byte string
+ * is acceptable, it becomes the key, otherwise the drawn bytes are discarded.
+ * This process is repeated until an acceptable byte string is drawn.
+ * The byte string drawn from the operation is interpreted as specified
+ * for the output produced by psa_export_key().
+ * The following key types defined in this specification follow this scheme:
+ *
+ * - #PSA_KEY_TYPE_DES.
+ * Force-set the parity bits, but discard forbidden weak keys.
+ * For 2-key and 3-key triple-DES, the three keys are generated
+ * successively (for example, for 3-key triple-DES,
+ * if the first 8 bytes specify a weak key and the next 8 bytes do not,
+ * discard the first 8 bytes, use the next 8 bytes as the first key,
+ * and continue reading output from the operation to derive the other
+ * two keys).
+ * - Finite-field Diffie-Hellman keys (#PSA_KEY_TYPE_DH_KEY_PAIR(\c group)
+ * where \c group designates any Diffie-Hellman group) and
+ * ECC keys on a Weierstrass elliptic curve
+ * (#PSA_KEY_TYPE_ECC_KEY_PAIR(\c curve) where \c curve designates a
+ * Weierstrass curve).
+ * For these key types, interpret the byte string as integer
+ * in big-endian order. Discard it if it is not in the range
+ * [0, *N* - 2] where *N* is the boundary of the private key domain
+ * (the prime *p* for Diffie-Hellman, the subprime *q* for DSA,
+ * or the order of the curve's base point for ECC).
+ * Add 1 to the resulting integer and use this as the private key *x*.
+ * This method allows compliance to NIST standards, specifically
+ * the methods titled "key-pair generation by testing candidates"
+ * in NIST SP 800-56A &sect;5.6.1.1.4 for Diffie-Hellman,
+ * in FIPS 186-4 &sect;B.1.2 for DSA, and
+ * in NIST SP 800-56A &sect;5.6.1.2.2 or
+ * FIPS 186-4 &sect;B.4.2 for elliptic curve keys.
+ *
+ * - For other key types, including #PSA_KEY_TYPE_RSA_KEY_PAIR,
+ * the way in which the operation output is consumed is
+ * implementation-defined.
+ *
+ * In all cases, the data that is read is discarded from the operation.
+ * The operation's capacity is decreased by the number of bytes read.
+ *
+ * For algorithms that take an input step #PSA_KEY_DERIVATION_INPUT_SECRET,
+ * the input to that step must be provided with psa_key_derivation_input_key().
+ * Future versions of this specification may include additional restrictions
+ * on the derived key based on the attributes and strength of the secret key.
+ *
+ * \param[in] attributes The attributes for the new key.
+ * If the key type to be created is
+ * #PSA_KEY_TYPE_PASSWORD_HASH then the algorithm in
+ * the policy must be the same as in the current
+ * operation.
+ * \param[in,out] operation The key derivation operation object to read from.
+ * \param[out] key On success, an identifier for the newly created
+ * key. For persistent keys, this is the key
+ * identifier defined in \p attributes.
+ * \c 0 on failure.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * If the key is persistent, the key material and the key's metadata
+ * have been saved to persistent storage.
+ * \retval #PSA_ERROR_ALREADY_EXISTS
+ * This is an attempt to create a persistent key, and there is
+ * already a persistent key with the given identifier.
+ * \retval #PSA_ERROR_INSUFFICIENT_DATA
+ * There was not enough data to create the desired key.
+ * Note that in this case, no output is written to the output buffer.
+ * The operation's capacity is set to 0, thus subsequent calls to
+ * this function will not succeed, even with a smaller output buffer.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * The key type or key size is not supported, either by the
+ * implementation in general or in this particular location.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The provided key attributes are not valid for the operation.
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The #PSA_KEY_DERIVATION_INPUT_SECRET or
+ * #PSA_KEY_DERIVATION_INPUT_PASSWORD input was not provided through a
+ * key; or one of the inputs was a key whose policy didn't allow
+ * #PSA_KEY_USAGE_DERIVE.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active and completed
+ * all required input steps), or the library has not been previously
+ * initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_output_key(
+ const psa_key_attributes_t *attributes,
+ psa_key_derivation_operation_t *operation,
+ mbedtls_svc_key_id_t *key);
+
+/** Compare output data from a key derivation operation to an expected value.
+ *
+ * This function calculates output bytes from a key derivation algorithm and
+ * compares those bytes to an expected value in constant time.
+ * If you view the key derivation's output as a stream of bytes, this
+ * function destructively reads the expected number of bytes from the
+ * stream before comparing them.
+ * The operation's capacity decreases by the number of bytes read.
+ *
+ * This is functionally equivalent to the following code:
+ * \code
+ * psa_key_derivation_output_bytes(operation, tmp, output_length);
+ * if (memcmp(output, tmp, output_length) != 0)
+ * return PSA_ERROR_INVALID_SIGNATURE;
+ * \endcode
+ * except (1) it works even if the key's policy does not allow outputting the
+ * bytes, and (2) the comparison will be done in constant time.
+ *
+ * If this function returns an error status other than
+ * #PSA_ERROR_INSUFFICIENT_DATA or #PSA_ERROR_INVALID_SIGNATURE,
+ * the operation enters an error state and must be aborted by calling
+ * psa_key_derivation_abort().
+ *
+ * \param[in,out] operation The key derivation operation object to read from.
+ * \param[in] expected_output Buffer containing the expected derivation output.
+ * \param output_length Length of the expected output; this is also the
+ * number of bytes that will be read.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The output was read successfully, but it differs from the expected
+ * output.
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * One of the inputs was a key whose policy didn't allow
+ * #PSA_KEY_USAGE_VERIFY_DERIVATION.
+ * \retval #PSA_ERROR_INSUFFICIENT_DATA
+ * The operation's capacity was less than
+ * \p output_length bytes. Note that in this case,
+ * the operation's capacity is set to 0, thus
+ * subsequent calls to this function will not
+ * succeed, even with a smaller expected output.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active and completed
+ * all required input steps), or the library has not been previously
+ * initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_verify_bytes(
+ psa_key_derivation_operation_t *operation,
+ const uint8_t *expected_output,
+ size_t output_length);
+
+/** Compare output data from a key derivation operation to an expected value
+ * stored in a key object.
+ *
+ * This function calculates output bytes from a key derivation algorithm and
+ * compares those bytes to an expected value, provided as key of type
+ * #PSA_KEY_TYPE_PASSWORD_HASH.
+ * If you view the key derivation's output as a stream of bytes, this
+ * function destructively reads the number of bytes corresponding to the
+ * length of the expected value from the stream before comparing them.
+ * The operation's capacity decreases by the number of bytes read.
+ *
+ * This is functionally equivalent to exporting the key and calling
+ * psa_key_derivation_verify_bytes() on the result, except that it
+ * works even if the key cannot be exported.
+ *
+ * If this function returns an error status other than
+ * #PSA_ERROR_INSUFFICIENT_DATA or #PSA_ERROR_INVALID_SIGNATURE,
+ * the operation enters an error state and must be aborted by calling
+ * psa_key_derivation_abort().
+ *
+ * \param[in,out] operation The key derivation operation object to read from.
+ * \param[in] expected A key of type #PSA_KEY_TYPE_PASSWORD_HASH
+ * containing the expected output. Its policy must
+ * include the #PSA_KEY_USAGE_VERIFY_DERIVATION flag
+ * and the permitted algorithm must match the
+ * operation. The value of this key was likely
+ * computed by a previous call to
+ * psa_key_derivation_output_key().
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The output was read successfully, but if differs from the expected
+ * output.
+ * \retval #PSA_ERROR_INVALID_HANDLE
+ * The key passed as the expected value does not exist.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The key passed as the expected value has an invalid type.
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The key passed as the expected value does not allow this usage or
+ * this algorithm; or one of the inputs was a key whose policy didn't
+ * allow #PSA_KEY_USAGE_VERIFY_DERIVATION.
+ * \retval #PSA_ERROR_INSUFFICIENT_DATA
+ * The operation's capacity was less than
+ * the length of the expected value. In this case,
+ * the operation's capacity is set to 0, thus
+ * subsequent calls to this function will not
+ * succeed, even with a smaller expected output.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active and completed
+ * all required input steps), or the library has not been previously
+ * initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_verify_key(
+ psa_key_derivation_operation_t *operation,
+ psa_key_id_t expected);
+
+/** Abort a key derivation operation.
+ *
+ * Aborting an operation frees all associated resources except for the \c
+ * operation structure itself. Once aborted, the operation object can be reused
+ * for another operation by calling psa_key_derivation_setup() again.
+ *
+ * This function may be called at any time after the operation
+ * object has been initialized as described in #psa_key_derivation_operation_t.
+ *
+ * In particular, it is valid to call psa_key_derivation_abort() twice, or to
+ * call psa_key_derivation_abort() on an operation that has not been set up.
+ *
+ * \param[in,out] operation The operation to abort.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_key_derivation_abort(
+ psa_key_derivation_operation_t *operation);
+
+/** Perform a key agreement and return the raw shared secret.
+ *
+ * \warning The raw result of a key agreement algorithm such as finite-field
+ * Diffie-Hellman or elliptic curve Diffie-Hellman has biases and should
+ * not be used directly as key material. It should instead be passed as
+ * input to a key derivation algorithm. To chain a key agreement with
+ * a key derivation, use psa_key_derivation_key_agreement() and other
+ * functions from the key derivation interface.
+ *
+ * \param alg The key agreement algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_RAW_KEY_AGREEMENT(\p alg)
+ * is true).
+ * \param private_key Identifier of the private key to use. It must
+ * allow the usage #PSA_KEY_USAGE_DERIVE.
+ * \param[in] peer_key Public key of the peer. It must be
+ * in the same format that psa_import_key()
+ * accepts. The standard formats for public
+ * keys are documented in the documentation
+ * of psa_export_public_key().
+ * \param peer_key_length Size of \p peer_key in bytes.
+ * \param[out] output Buffer where the decrypted message is to
+ * be written.
+ * \param output_size Size of the \c output buffer in bytes.
+ * \param[out] output_length On success, the number of bytes
+ * that make up the returned output.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p alg is not a key agreement algorithm, or
+ * \p private_key is not compatible with \p alg,
+ * or \p peer_key is not valid for \p alg or not compatible with
+ * \p private_key.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * \p output_size is too small
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p alg is not a supported key agreement algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_raw_key_agreement(psa_algorithm_t alg,
+ mbedtls_svc_key_id_t private_key,
+ const uint8_t *peer_key,
+ size_t peer_key_length,
+ uint8_t *output,
+ size_t output_size,
+ size_t *output_length);
+
+/**@}*/
+
+/** \defgroup random Random generation
+ * @{
+ */
+
+/**
+ * \brief Generate random bytes.
+ *
+ * \warning This function **can** fail! Callers MUST check the return status
+ * and MUST NOT use the content of the output buffer if the return
+ * status is not #PSA_SUCCESS.
+ *
+ * \note To generate a key, use psa_generate_key() instead.
+ *
+ * \param[out] output Output buffer for the generated data.
+ * \param output_size Number of bytes to generate and output.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_generate_random(uint8_t *output,
+ size_t output_size);
+
+/**
+ * \brief Generate a key or key pair.
+ *
+ * The key is generated randomly.
+ * Its location, usage policy, type and size are taken from \p attributes.
+ *
+ * Implementations must reject an attempt to generate a key of size 0.
+ *
+ * The following type-specific considerations apply:
+ * - For RSA keys (#PSA_KEY_TYPE_RSA_KEY_PAIR),
+ * the public exponent is 65537.
+ * The modulus is a product of two probabilistic primes
+ * between 2^{n-1} and 2^n where n is the bit size specified in the
+ * attributes.
+ *
+ * \param[in] attributes The attributes for the new key.
+ * \param[out] key On success, an identifier for the newly created
+ * key. For persistent keys, this is the key
+ * identifier defined in \p attributes.
+ * \c 0 on failure.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * If the key is persistent, the key material and the key's metadata
+ * have been saved to persistent storage.
+ * \retval #PSA_ERROR_ALREADY_EXISTS
+ * This is an attempt to create a persistent key, and there is
+ * already a persistent key with the given identifier.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_generate_key(const psa_key_attributes_t *attributes,
+ mbedtls_svc_key_id_t *key);
+
+/**@}*/
+
+/** \defgroup interruptible_hash Interruptible sign/verify hash
+ * @{
+ */
+
+/** The type of the state data structure for interruptible hash
+ * signing operations.
+ *
+ * Before calling any function on a sign hash operation object, the
+ * application must initialize it by any of the following means:
+ * - Set the structure to all-bits-zero, for example:
+ * \code
+ * psa_sign_hash_interruptible_operation_t operation;
+ * memset(&operation, 0, sizeof(operation));
+ * \endcode
+ * - Initialize the structure to logical zero values, for example:
+ * \code
+ * psa_sign_hash_interruptible_operation_t operation = {0};
+ * \endcode
+ * - Initialize the structure to the initializer
+ * #PSA_SIGN_HASH_INTERRUPTIBLE_OPERATION_INIT, for example:
+ * \code
+ * psa_sign_hash_interruptible_operation_t operation =
+ * PSA_SIGN_HASH_INTERRUPTIBLE_OPERATION_INIT;
+ * \endcode
+ * - Assign the result of the function
+ * psa_sign_hash_interruptible_operation_init() to the structure, for
+ * example:
+ * \code
+ * psa_sign_hash_interruptible_operation_t operation;
+ * operation = psa_sign_hash_interruptible_operation_init();
+ * \endcode
+ *
+ * This is an implementation-defined \c struct. Applications should not
+ * make any assumptions about the content of this structure.
+ * Implementation details can change in future versions without notice. */
+typedef struct psa_sign_hash_interruptible_operation_s psa_sign_hash_interruptible_operation_t;
+
+/** The type of the state data structure for interruptible hash
+ * verification operations.
+ *
+ * Before calling any function on a sign hash operation object, the
+ * application must initialize it by any of the following means:
+ * - Set the structure to all-bits-zero, for example:
+ * \code
+ * psa_verify_hash_interruptible_operation_t operation;
+ * memset(&operation, 0, sizeof(operation));
+ * \endcode
+ * - Initialize the structure to logical zero values, for example:
+ * \code
+ * psa_verify_hash_interruptible_operation_t operation = {0};
+ * \endcode
+ * - Initialize the structure to the initializer
+ * #PSA_VERIFY_HASH_INTERRUPTIBLE_OPERATION_INIT, for example:
+ * \code
+ * psa_verify_hash_interruptible_operation_t operation =
+ * PSA_VERIFY_HASH_INTERRUPTIBLE_OPERATION_INIT;
+ * \endcode
+ * - Assign the result of the function
+ * psa_verify_hash_interruptible_operation_init() to the structure, for
+ * example:
+ * \code
+ * psa_verify_hash_interruptible_operation_t operation;
+ * operation = psa_verify_hash_interruptible_operation_init();
+ * \endcode
+ *
+ * This is an implementation-defined \c struct. Applications should not
+ * make any assumptions about the content of this structure.
+ * Implementation details can change in future versions without notice. */
+typedef struct psa_verify_hash_interruptible_operation_s psa_verify_hash_interruptible_operation_t;
+
+/**
+ * \brief Set the maximum number of ops allowed to be
+ * executed by an interruptible function in a
+ * single call.
+ *
+ * \warning This is a beta API, and thus subject to change
+ * at any point. It is not bound by the usual
+ * interface stability promises.
+ *
+ * \note The time taken to execute a single op is
+ * implementation specific and depends on
+ * software, hardware, the algorithm, key type and
+ * curve chosen. Even within a single operation,
+ * successive ops can take differing amounts of
+ * time. The only guarantee is that lower values
+ * for \p max_ops means functions will block for a
+ * lesser maximum amount of time. The functions
+ * \c psa_sign_interruptible_get_num_ops() and
+ * \c psa_verify_interruptible_get_num_ops() are
+ * provided to help with tuning this value.
+ *
+ * \note This value defaults to
+ * #PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED, which
+ * means the whole operation will be done in one
+ * go, regardless of the number of ops required.
+ *
+ * \note If more ops are needed to complete a
+ * computation, #PSA_OPERATION_INCOMPLETE will be
+ * returned by the function performing the
+ * computation. It is then the caller's
+ * responsibility to either call again with the
+ * same operation context until it returns 0 or an
+ * error code; or to call the relevant abort
+ * function if the answer is no longer required.
+ *
+ * \note The interpretation of \p max_ops is also
+ * implementation defined. On a hard real time
+ * system, this can indicate a hard deadline, as a
+ * real-time system needs a guarantee of not
+ * spending more than X time, however care must be
+ * taken in such an implementation to avoid the
+ * situation whereby calls just return, not being
+ * able to do any actual work within the allotted
+ * time. On a non-real-time system, the
+ * implementation can be more relaxed, but again
+ * whether this number should be interpreted as as
+ * hard or soft limit or even whether a less than
+ * or equals as regards to ops executed in a
+ * single call is implementation defined.
+ *
+ * \note For keys in local storage when no accelerator
+ * driver applies, please see also the
+ * documentation for \c mbedtls_ecp_set_max_ops(),
+ * which is the internal implementation in these
+ * cases.
+ *
+ * \warning With implementations that interpret this number
+ * as a hard limit, setting this number too small
+ * may result in an infinite loop, whereby each
+ * call results in immediate return with no ops
+ * done (as there is not enough time to execute
+ * any), and thus no result will ever be achieved.
+ *
+ * \note This only applies to functions whose
+ * documentation mentions they may return
+ * #PSA_OPERATION_INCOMPLETE.
+ *
+ * \param max_ops The maximum number of ops to be executed in a
+ * single call. This can be a number from 0 to
+ * #PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED, where 0
+ * is the least amount of work done per call.
+ */
+void psa_interruptible_set_max_ops(uint32_t max_ops);
+
+/**
+ * \brief Get the maximum number of ops allowed to be
+ * executed by an interruptible function in a
+ * single call. This will return the last
+ * value set by
+ * \c psa_interruptible_set_max_ops() or
+ * #PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED if
+ * that function has never been called.
+ *
+ * \warning This is a beta API, and thus subject to change
+ * at any point. It is not bound by the usual
+ * interface stability promises.
+ *
+ * \return Maximum number of ops allowed to be
+ * executed by an interruptible function in a
+ * single call.
+ */
+uint32_t psa_interruptible_get_max_ops(void);
+
+/**
+ * \brief Get the number of ops that a hash signing
+ * operation has taken so far. If the operation
+ * has completed, then this will represent the
+ * number of ops required for the entire
+ * operation. After initialization or calling
+ * \c psa_sign_hash_interruptible_abort() on
+ * the operation, a value of 0 will be returned.
+ *
+ * \note This interface is guaranteed re-entrant and
+ * thus may be called from driver code.
+ *
+ * \warning This is a beta API, and thus subject to change
+ * at any point. It is not bound by the usual
+ * interface stability promises.
+ *
+ * This is a helper provided to help you tune the
+ * value passed to \c
+ * psa_interruptible_set_max_ops().
+ *
+ * \param operation The \c psa_sign_hash_interruptible_operation_t
+ * to use. This must be initialized first.
+ *
+ * \return Number of ops that the operation has taken so
+ * far.
+ */
+uint32_t psa_sign_hash_get_num_ops(
+ const psa_sign_hash_interruptible_operation_t *operation);
+
+/**
+ * \brief Get the number of ops that a hash verification
+ * operation has taken so far. If the operation
+ * has completed, then this will represent the
+ * number of ops required for the entire
+ * operation. After initialization or calling \c
+ * psa_verify_hash_interruptible_abort() on the
+ * operation, a value of 0 will be returned.
+ *
+ * \warning This is a beta API, and thus subject to change
+ * at any point. It is not bound by the usual
+ * interface stability promises.
+ *
+ * This is a helper provided to help you tune the
+ * value passed to \c
+ * psa_interruptible_set_max_ops().
+ *
+ * \param operation The \c
+ * psa_verify_hash_interruptible_operation_t to
+ * use. This must be initialized first.
+ *
+ * \return Number of ops that the operation has taken so
+ * far.
+ */
+uint32_t psa_verify_hash_get_num_ops(
+ const psa_verify_hash_interruptible_operation_t *operation);
+
+/**
+ * \brief Start signing a hash or short message with a
+ * private key, in an interruptible manner.
+ *
+ * \see \c psa_sign_hash_complete()
+ *
+ * \warning This is a beta API, and thus subject to change
+ * at any point. It is not bound by the usual
+ * interface stability promises.
+ *
+ * \note This function combined with \c
+ * psa_sign_hash_complete() is equivalent to
+ * \c psa_sign_hash() but
+ * \c psa_sign_hash_complete() can return early and
+ * resume according to the limit set with \c
+ * psa_interruptible_set_max_ops() to reduce the
+ * maximum time spent in a function call.
+ *
+ * \note Users should call \c psa_sign_hash_complete()
+ * repeatedly on the same context after a
+ * successful call to this function until \c
+ * psa_sign_hash_complete() either returns 0 or an
+ * error. \c psa_sign_hash_complete() will return
+ * #PSA_OPERATION_INCOMPLETE if there is more work
+ * to do. Alternatively users can call
+ * \c psa_sign_hash_abort() at any point if they no
+ * longer want the result.
+ *
+ * \note If this function returns an error status, the
+ * operation enters an error state and must be
+ * aborted by calling \c psa_sign_hash_abort().
+ *
+ * \param[in, out] operation The \c psa_sign_hash_interruptible_operation_t
+ * to use. This must be initialized first.
+ *
+ * \param key Identifier of the key to use for the operation.
+ * It must be an asymmetric key pair. The key must
+ * allow the usage #PSA_KEY_USAGE_SIGN_HASH.
+ * \param alg A signature algorithm (\c PSA_ALG_XXX
+ * value such that #PSA_ALG_IS_SIGN_HASH(\p alg)
+ * is true), that is compatible with
+ * the type of \p key.
+ * \param[in] hash The hash or message to sign.
+ * \param hash_length Size of the \p hash buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * The operation started successfully - call \c psa_sign_hash_complete()
+ * with the same context to complete the operation
+ *
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The key does not have the #PSA_KEY_USAGE_SIGN_HASH flag, or it does
+ * not permit the requested algorithm.
+ * \retval #PSA_ERROR_BAD_STATE
+ * An operation has previously been started on this context, and is
+ * still in progress.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_sign_hash_start(
+ psa_sign_hash_interruptible_operation_t *operation,
+ mbedtls_svc_key_id_t key, psa_algorithm_t alg,
+ const uint8_t *hash, size_t hash_length);
+
+/**
+ * \brief Continue and eventually complete the action of
+ * signing a hash or short message with a private
+ * key, in an interruptible manner.
+ *
+ * \see \c psa_sign_hash_start()
+ *
+ * \warning This is a beta API, and thus subject to change
+ * at any point. It is not bound by the usual
+ * interface stability promises.
+ *
+ * \note This function combined with \c
+ * psa_sign_hash_start() is equivalent to
+ * \c psa_sign_hash() but this function can return
+ * early and resume according to the limit set with
+ * \c psa_interruptible_set_max_ops() to reduce the
+ * maximum time spent in a function call.
+ *
+ * \note Users should call this function on the same
+ * operation object repeatedly until it either
+ * returns 0 or an error. This function will return
+ * #PSA_OPERATION_INCOMPLETE if there is more work
+ * to do. Alternatively users can call
+ * \c psa_sign_hash_abort() at any point if they no
+ * longer want the result.
+ *
+ * \note When this function returns successfully, the
+ * operation becomes inactive. If this function
+ * returns an error status, the operation enters an
+ * error state and must be aborted by calling
+ * \c psa_sign_hash_abort().
+ *
+ * \param[in, out] operation The \c psa_sign_hash_interruptible_operation_t
+ * to use. This must be initialized first, and have
+ * had \c psa_sign_hash_start() called with it
+ * first.
+ *
+ * \param[out] signature Buffer where the signature is to be written.
+ * \param signature_size Size of the \p signature buffer in bytes. This
+ * must be appropriate for the selected
+ * algorithm and key:
+ * - The required signature size is
+ * #PSA_SIGN_OUTPUT_SIZE(\c key_type, \c
+ * key_bits, \c alg) where \c key_type and \c
+ * key_bits are the type and bit-size
+ * respectively of key.
+ * - #PSA_SIGNATURE_MAX_SIZE evaluates to the
+ * maximum signature size of any supported
+ * signature algorithm.
+ * \param[out] signature_length On success, the number of bytes that make up
+ * the returned signature value.
+ *
+ * \retval #PSA_SUCCESS
+ * Operation completed successfully
+ *
+ * \retval #PSA_OPERATION_INCOMPLETE
+ * Operation was interrupted due to the setting of \c
+ * psa_interruptible_set_max_ops(). There is still work to be done.
+ * Call this function again with the same operation object.
+ *
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p signature buffer is too small. You can
+ * determine a sufficient buffer size by calling
+ * #PSA_SIGN_OUTPUT_SIZE(\c key_type, \c key_bits, \c alg)
+ * where \c key_type and \c key_bits are the type and bit-size
+ * respectively of \c key.
+ *
+ * \retval #PSA_ERROR_BAD_STATE
+ * An operation was not previously started on this context via
+ * \c psa_sign_hash_start().
+ *
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has either not been previously initialized by
+ * psa_crypto_init() or you did not previously call
+ * psa_sign_hash_start() with this operation object. It is
+ * implementation-dependent whether a failure to initialize results in
+ * this error code.
+ */
+psa_status_t psa_sign_hash_complete(
+ psa_sign_hash_interruptible_operation_t *operation,
+ uint8_t *signature, size_t signature_size,
+ size_t *signature_length);
+
+/**
+ * \brief Abort a sign hash operation.
+ *
+ * \warning This is a beta API, and thus subject to change
+ * at any point. It is not bound by the usual
+ * interface stability promises.
+ *
+ * \note This function is the only function that clears
+ * the number of ops completed as part of the
+ * operation. Please ensure you copy this value via
+ * \c psa_sign_hash_get_num_ops() if required
+ * before calling.
+ *
+ * \note Aborting an operation frees all associated
+ * resources except for the \p operation structure
+ * itself. Once aborted, the operation object can
+ * be reused for another operation by calling \c
+ * psa_sign_hash_start() again.
+ *
+ * \note You may call this function any time after the
+ * operation object has been initialized. In
+ * particular, calling \c psa_sign_hash_abort()
+ * after the operation has already been terminated
+ * by a call to \c psa_sign_hash_abort() or
+ * psa_sign_hash_complete() is safe.
+ *
+ * \param[in,out] operation Initialized sign hash operation.
+ *
+ * \retval #PSA_SUCCESS
+ * The operation was aborted successfully.
+ *
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_sign_hash_abort(
+ psa_sign_hash_interruptible_operation_t *operation);
+
+/**
+ * \brief Start reading and verifying a hash or short
+ * message, in an interruptible manner.
+ *
+ * \see \c psa_verify_hash_complete()
+ *
+ * \warning This is a beta API, and thus subject to change
+ * at any point. It is not bound by the usual
+ * interface stability promises.
+ *
+ * \note This function combined with \c
+ * psa_verify_hash_complete() is equivalent to
+ * \c psa_verify_hash() but \c
+ * psa_verify_hash_complete() can return early and
+ * resume according to the limit set with \c
+ * psa_interruptible_set_max_ops() to reduce the
+ * maximum time spent in a function.
+ *
+ * \note Users should call \c psa_verify_hash_complete()
+ * repeatedly on the same operation object after a
+ * successful call to this function until \c
+ * psa_verify_hash_complete() either returns 0 or
+ * an error. \c psa_verify_hash_complete() will
+ * return #PSA_OPERATION_INCOMPLETE if there is
+ * more work to do. Alternatively users can call
+ * \c psa_verify_hash_abort() at any point if they
+ * no longer want the result.
+ *
+ * \note If this function returns an error status, the
+ * operation enters an error state and must be
+ * aborted by calling \c psa_verify_hash_abort().
+ *
+ * \param[in, out] operation The \c psa_verify_hash_interruptible_operation_t
+ * to use. This must be initialized first.
+ *
+ * \param key Identifier of the key to use for the operation.
+ * The key must allow the usage
+ * #PSA_KEY_USAGE_VERIFY_HASH.
+ * \param alg A signature algorithm (\c PSA_ALG_XXX
+ * value such that #PSA_ALG_IS_SIGN_HASH(\p alg)
+ * is true), that is compatible with
+ * the type of \p key.
+ * \param[in] hash The hash whose signature is to be verified.
+ * \param hash_length Size of the \p hash buffer in bytes.
+ * \param[in] signature Buffer containing the signature to verify.
+ * \param signature_length Size of the \p signature buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * The operation started successfully - please call \c
+ * psa_verify_hash_complete() with the same context to complete the
+ * operation.
+ *
+ * \retval #PSA_ERROR_BAD_STATE
+ * Another operation has already been started on this context, and is
+ * still in progress.
+ *
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The key does not have the #PSA_KEY_USAGE_VERIFY_HASH flag, or it does
+ * not permit the requested algorithm.
+ *
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_verify_hash_start(
+ psa_verify_hash_interruptible_operation_t *operation,
+ mbedtls_svc_key_id_t key, psa_algorithm_t alg,
+ const uint8_t *hash, size_t hash_length,
+ const uint8_t *signature, size_t signature_length);
+
+/**
+ * \brief Continue and eventually complete the action of
+ * reading and verifying a hash or short message
+ * signed with a private key, in an interruptible
+ * manner.
+ *
+ * \see \c psa_verify_hash_start()
+ *
+ * \warning This is a beta API, and thus subject to change
+ * at any point. It is not bound by the usual
+ * interface stability promises.
+ *
+ * \note This function combined with \c
+ * psa_verify_hash_start() is equivalent to
+ * \c psa_verify_hash() but this function can
+ * return early and resume according to the limit
+ * set with \c psa_interruptible_set_max_ops() to
+ * reduce the maximum time spent in a function
+ * call.
+ *
+ * \note Users should call this function on the same
+ * operation object repeatedly until it either
+ * returns 0 or an error. This function will return
+ * #PSA_OPERATION_INCOMPLETE if there is more work
+ * to do. Alternatively users can call
+ * \c psa_verify_hash_abort() at any point if they
+ * no longer want the result.
+ *
+ * \note When this function returns successfully, the
+ * operation becomes inactive. If this function
+ * returns an error status, the operation enters an
+ * error state and must be aborted by calling
+ * \c psa_verify_hash_abort().
+ *
+ * \param[in, out] operation The \c psa_verify_hash_interruptible_operation_t
+ * to use. This must be initialized first, and have
+ * had \c psa_verify_hash_start() called with it
+ * first.
+ *
+ * \retval #PSA_SUCCESS
+ * Operation completed successfully, and the passed signature is valid.
+ *
+ * \retval #PSA_OPERATION_INCOMPLETE
+ * Operation was interrupted due to the setting of \c
+ * psa_interruptible_set_max_ops(). There is still work to be done.
+ * Call this function again with the same operation object.
+ *
+ * \retval #PSA_ERROR_INVALID_HANDLE \emptydescription
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The calculation was performed successfully, but the passed
+ * signature is not a valid signature.
+ * \retval #PSA_ERROR_BAD_STATE
+ * An operation was not previously started on this context via
+ * \c psa_verify_hash_start().
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has either not been previously initialized by
+ * psa_crypto_init() or you did not previously call
+ * psa_verify_hash_start() on this object. It is
+ * implementation-dependent whether a failure to initialize results in
+ * this error code.
+ */
+psa_status_t psa_verify_hash_complete(
+ psa_verify_hash_interruptible_operation_t *operation);
+
+/**
+ * \brief Abort a verify hash operation.
+ *
+ * \warning This is a beta API, and thus subject to change at
+ * any point. It is not bound by the usual interface
+ * stability promises.
+ *
+ * \note This function is the only function that clears the
+ * number of ops completed as part of the operation.
+ * Please ensure you copy this value via
+ * \c psa_verify_hash_get_num_ops() if required
+ * before calling.
+ *
+ * \note Aborting an operation frees all associated
+ * resources except for the operation structure
+ * itself. Once aborted, the operation object can be
+ * reused for another operation by calling \c
+ * psa_verify_hash_start() again.
+ *
+ * \note You may call this function any time after the
+ * operation object has been initialized.
+ * In particular, calling \c psa_verify_hash_abort()
+ * after the operation has already been terminated by
+ * a call to \c psa_verify_hash_abort() or
+ * psa_verify_hash_complete() is safe.
+ *
+ * \param[in,out] operation Initialized verify hash operation.
+ *
+ * \retval #PSA_SUCCESS
+ * The operation was aborted successfully.
+ *
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_verify_hash_abort(
+ psa_verify_hash_interruptible_operation_t *operation);
+
+
+/**@}*/
+
+#ifdef __cplusplus
+}
+#endif
+
+/* The file "crypto_sizes.h" contains definitions for size calculation
+ * macros whose definitions are implementation-specific. */
+#include "crypto_sizes.h"
+
+/* The file "crypto_struct.h" contains definitions for
+ * implementation-specific structs that are declared above. */
+#if defined(MBEDTLS_PSA_CRYPTO_STRUCT_FILE)
+#include MBEDTLS_PSA_CRYPTO_STRUCT_FILE
+#else
+#include "crypto_struct.h"
+#endif
+
+/* The file "crypto_extra.h" contains vendor-specific definitions. This
+ * can include vendor-defined algorithms, extra functions, etc. */
+#include "crypto_extra.h"
+
+#endif /* PSA_CRYPTO_H */
diff --git a/include/psa/crypto_adjust_auto_enabled.h b/include/psa/crypto_adjust_auto_enabled.h
new file mode 100644
index 0000000..63fb29e
--- /dev/null
+++ b/include/psa/crypto_adjust_auto_enabled.h
@@ -0,0 +1,21 @@
+/**
+ * \file psa/crypto_adjust_auto_enabled.h
+ * \brief Adjust PSA configuration: enable always-on features
+ *
+ * Always enable certain features which require a negligible amount of code
+ * to implement, to avoid some edge cases in the configuration combinatorics.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_ADJUST_AUTO_ENABLED_H
+#define PSA_CRYPTO_ADJUST_AUTO_ENABLED_H
+
+#define PSA_WANT_KEY_TYPE_DERIVE 1
+#define PSA_WANT_KEY_TYPE_PASSWORD 1
+#define PSA_WANT_KEY_TYPE_PASSWORD_HASH 1
+#define PSA_WANT_KEY_TYPE_RAW_DATA 1
+
+#endif /* PSA_CRYPTO_ADJUST_AUTO_ENABLED_H */
diff --git a/include/psa/crypto_adjust_config_key_pair_types.h b/include/psa/crypto_adjust_config_key_pair_types.h
new file mode 100644
index 0000000..63afc0e
--- /dev/null
+++ b/include/psa/crypto_adjust_config_key_pair_types.h
@@ -0,0 +1,91 @@
+/**
+ * \file psa/crypto_adjust_config_key_pair_types.h
+ * \brief Adjust PSA configuration for key pair types.
+ *
+ * See docs/proposed/psa-conditional-inclusion-c.md.
+ * - Support non-basic operations in a keypair type implicitly enables basic
+ * support for that keypair type.
+ * - Support for a keypair type implicitly enables the corresponding public
+ * key type.
+ * - Basic support for a keypair type implicilty enables import/export support
+ * for that keypair type. Warning: this is implementation-specific (mainly
+ * for the benefit of testing) and may change in the future!
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_ADJUST_KEYPAIR_TYPES_H
+#define PSA_CRYPTO_ADJUST_KEYPAIR_TYPES_H
+
+/*****************************************************************
+ * ANYTHING -> BASIC
+ ****************************************************************/
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT) || \
+ defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT) || \
+ defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE) || \
+ defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT) || \
+ defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT) || \
+ defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE) || \
+ defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE)
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT) || \
+ defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT) || \
+ defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE) || \
+ defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE)
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC 1
+#endif
+
+/*****************************************************************
+ * BASIC -> corresponding PUBLIC
+ ****************************************************************/
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
+#define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC)
+#define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC)
+#define PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY 1
+#endif
+
+/*****************************************************************
+ * BASIC -> IMPORT+EXPORT
+ *
+ * (Implementation-specific, may change in the future.)
+ ****************************************************************/
+
+/* Even though KEY_PAIR symbols' feature several level of support (BASIC, IMPORT,
+ * EXPORT, GENERATE, DERIVE) we're not planning to have support only for BASIC
+ * without IMPORT/EXPORT since these last 2 features are strongly used in tests.
+ * In general it is allowed to include more feature than what is strictly
+ * requested.
+ * As a consequence IMPORT and EXPORT features will be automatically enabled
+ * as soon as the BASIC one is. */
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC)
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC)
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT 1
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT 1
+#endif
+
+#endif /* PSA_CRYPTO_ADJUST_KEYPAIR_TYPES_H */
diff --git a/include/psa/crypto_adjust_config_synonyms.h b/include/psa/crypto_adjust_config_synonyms.h
new file mode 100644
index 0000000..cf33465
--- /dev/null
+++ b/include/psa/crypto_adjust_config_synonyms.h
@@ -0,0 +1,45 @@
+/**
+ * \file psa/crypto_adjust_config_synonyms.h
+ * \brief Adjust PSA configuration: enable quasi-synonyms
+ *
+ * When two features require almost the same code, we automatically enable
+ * both when either one is requested, to reduce the combinatorics of
+ * possible configurations.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_ADJUST_CONFIG_SYNONYMS_H
+#define PSA_CRYPTO_ADJUST_CONFIG_SYNONYMS_H
+
+/****************************************************************/
+/* De facto synonyms */
+/****************************************************************/
+
+#if defined(PSA_WANT_ALG_ECDSA_ANY) && !defined(PSA_WANT_ALG_ECDSA)
+#define PSA_WANT_ALG_ECDSA PSA_WANT_ALG_ECDSA_ANY
+#elif !defined(PSA_WANT_ALG_ECDSA_ANY) && defined(PSA_WANT_ALG_ECDSA)
+#define PSA_WANT_ALG_ECDSA_ANY PSA_WANT_ALG_ECDSA
+#endif
+
+#if defined(PSA_WANT_ALG_CCM_STAR_NO_TAG) && !defined(PSA_WANT_ALG_CCM)
+#define PSA_WANT_ALG_CCM PSA_WANT_ALG_CCM_STAR_NO_TAG
+#elif !defined(PSA_WANT_ALG_CCM_STAR_NO_TAG) && defined(PSA_WANT_ALG_CCM)
+#define PSA_WANT_ALG_CCM_STAR_NO_TAG PSA_WANT_ALG_CCM
+#endif
+
+#if defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW) && !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN)
+#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW
+#elif !defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW) && defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN)
+#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN_RAW PSA_WANT_ALG_RSA_PKCS1V15_SIGN
+#endif
+
+#if defined(PSA_WANT_ALG_RSA_PSS_ANY_SALT) && !defined(PSA_WANT_ALG_RSA_PSS)
+#define PSA_WANT_ALG_RSA_PSS PSA_WANT_ALG_RSA_PSS_ANY_SALT
+#elif !defined(PSA_WANT_ALG_RSA_PSS_ANY_SALT) && defined(PSA_WANT_ALG_RSA_PSS)
+#define PSA_WANT_ALG_RSA_PSS_ANY_SALT PSA_WANT_ALG_RSA_PSS
+#endif
+
+#endif /* PSA_CRYPTO_ADJUST_CONFIG_SYNONYMS_H */
diff --git a/include/psa/crypto_builtin_composites.h b/include/psa/crypto_builtin_composites.h
new file mode 100644
index 0000000..35c2e29
--- /dev/null
+++ b/include/psa/crypto_builtin_composites.h
@@ -0,0 +1,210 @@
+/*
+ * Context structure declaration of the Mbed TLS software-based PSA drivers
+ * called through the PSA Crypto driver dispatch layer.
+ * This file contains the context structures of those algorithms which need to
+ * rely on other algorithms, i.e. are 'composite' algorithms.
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ *
+ * \note This header and its content are not part of the Mbed TLS API and
+ * applications must not depend on it. Its main purpose is to define the
+ * multi-part state objects of the Mbed TLS software-based PSA drivers. The
+ * definitions of these objects are then used by crypto_struct.h to define the
+ * implementation-defined types of PSA multi-part state objects.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_BUILTIN_COMPOSITES_H
+#define PSA_CRYPTO_BUILTIN_COMPOSITES_H
+#include "mbedtls/private_access.h"
+
+#include <psa/crypto_driver_common.h>
+
+#include "mbedtls/cmac.h"
+#include "mbedtls/gcm.h"
+#include "mbedtls/ccm.h"
+#include "mbedtls/chachapoly.h"
+
+/*
+ * MAC multi-part operation definitions.
+ */
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC)
+#define MBEDTLS_PSA_BUILTIN_MAC
+#endif
+
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC) || defined(PSA_CRYPTO_DRIVER_TEST)
+typedef struct {
+ /** The HMAC algorithm in use */
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+ /** The hash context. */
+ struct psa_hash_operation_s hash_ctx;
+ /** The HMAC part of the context. */
+ uint8_t MBEDTLS_PRIVATE(opad)[PSA_HMAC_MAX_HASH_BLOCK_SIZE];
+} mbedtls_psa_hmac_operation_t;
+
+#define MBEDTLS_PSA_HMAC_OPERATION_INIT { 0, PSA_HASH_OPERATION_INIT, { 0 } }
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
+
+typedef struct {
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+ union {
+ unsigned MBEDTLS_PRIVATE(dummy); /* Make the union non-empty even with no supported algorithms. */
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC) || defined(PSA_CRYPTO_DRIVER_TEST)
+ mbedtls_psa_hmac_operation_t MBEDTLS_PRIVATE(hmac);
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC) || defined(PSA_CRYPTO_DRIVER_TEST)
+ mbedtls_cipher_context_t MBEDTLS_PRIVATE(cmac);
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_CMAC */
+ } MBEDTLS_PRIVATE(ctx);
+} mbedtls_psa_mac_operation_t;
+
+#define MBEDTLS_PSA_MAC_OPERATION_INIT { 0, { 0 } }
+
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_CCM) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
+#define MBEDTLS_PSA_BUILTIN_AEAD 1
+#endif
+
+/* Context structure for the Mbed TLS AEAD implementation. */
+typedef struct {
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+ psa_key_type_t MBEDTLS_PRIVATE(key_type);
+
+ unsigned int MBEDTLS_PRIVATE(is_encrypt) : 1;
+
+ uint8_t MBEDTLS_PRIVATE(tag_length);
+
+ union {
+ unsigned dummy; /* Enable easier initializing of the union. */
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CCM)
+ mbedtls_ccm_context MBEDTLS_PRIVATE(ccm);
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_CCM */
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_GCM)
+ mbedtls_gcm_context MBEDTLS_PRIVATE(gcm);
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_GCM */
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305)
+ mbedtls_chachapoly_context MBEDTLS_PRIVATE(chachapoly);
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_CHACHA20_POLY1305 */
+
+ } ctx;
+
+} mbedtls_psa_aead_operation_t;
+
+#define MBEDTLS_PSA_AEAD_OPERATION_INIT { 0, 0, 0, 0, { 0 } }
+
+#include "mbedtls/ecdsa.h"
+
+/* Context structure for the Mbed TLS interruptible sign hash implementation. */
+typedef struct {
+#if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
+ defined(MBEDTLS_ECP_RESTARTABLE)
+ mbedtls_ecdsa_context *MBEDTLS_PRIVATE(ctx);
+ mbedtls_ecdsa_restart_ctx MBEDTLS_PRIVATE(restart_ctx);
+
+ uint32_t MBEDTLS_PRIVATE(num_ops);
+
+ size_t MBEDTLS_PRIVATE(coordinate_bytes);
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+ mbedtls_md_type_t MBEDTLS_PRIVATE(md_alg);
+ uint8_t MBEDTLS_PRIVATE(hash)[PSA_BITS_TO_BYTES(PSA_VENDOR_ECC_MAX_CURVE_BITS)];
+ size_t MBEDTLS_PRIVATE(hash_length);
+
+#else
+ /* Make the struct non-empty if algs not supported. */
+ unsigned MBEDTLS_PRIVATE(dummy);
+
+#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
+ * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
+ * defined( MBEDTLS_ECP_RESTARTABLE ) */
+} mbedtls_psa_sign_hash_interruptible_operation_t;
+
+#if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
+ defined(MBEDTLS_ECP_RESTARTABLE)
+#define MBEDTLS_PSA_SIGN_HASH_INTERRUPTIBLE_OPERATION_INIT { { 0 }, { 0 }, 0, 0, 0, 0, 0, 0 }
+#else
+#define MBEDTLS_PSA_SIGN_HASH_INTERRUPTIBLE_OPERATION_INIT { 0 }
+#endif
+
+/* Context structure for the Mbed TLS interruptible verify hash
+ * implementation.*/
+typedef struct {
+#if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
+ defined(MBEDTLS_ECP_RESTARTABLE)
+
+ mbedtls_ecdsa_context *MBEDTLS_PRIVATE(ctx);
+ mbedtls_ecdsa_restart_ctx MBEDTLS_PRIVATE(restart_ctx);
+
+ uint32_t MBEDTLS_PRIVATE(num_ops);
+
+ uint8_t MBEDTLS_PRIVATE(hash)[PSA_BITS_TO_BYTES(PSA_VENDOR_ECC_MAX_CURVE_BITS)];
+ size_t MBEDTLS_PRIVATE(hash_length);
+
+ mbedtls_mpi MBEDTLS_PRIVATE(r);
+ mbedtls_mpi MBEDTLS_PRIVATE(s);
+
+#else
+ /* Make the struct non-empty if algs not supported. */
+ unsigned MBEDTLS_PRIVATE(dummy);
+
+#endif /* defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) ||
+ * defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA) &&
+ * defined( MBEDTLS_ECP_RESTARTABLE ) */
+
+} mbedtls_psa_verify_hash_interruptible_operation_t;
+
+#if (defined(MBEDTLS_PSA_BUILTIN_ALG_ECDSA) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_DETERMINISTIC_ECDSA)) && \
+ defined(MBEDTLS_ECP_RESTARTABLE)
+#define MBEDTLS_VERIFY_SIGN_HASH_INTERRUPTIBLE_OPERATION_INIT { { 0 }, { 0 }, 0, 0, 0, 0, { 0 }, \
+ { 0 } }
+#else
+#define MBEDTLS_VERIFY_SIGN_HASH_INTERRUPTIBLE_OPERATION_INIT { 0 }
+#endif
+
+
+/* EC-JPAKE operation definitions */
+
+#include "mbedtls/ecjpake.h"
+
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_JPAKE)
+#define MBEDTLS_PSA_BUILTIN_PAKE 1
+#endif
+
+/* Note: the format for mbedtls_ecjpake_read/write function has an extra
+ * length byte for each step, plus an extra 3 bytes for ECParameters in the
+ * server's 2nd round. */
+#define MBEDTLS_PSA_JPAKE_BUFFER_SIZE ((3 + 1 + 65 + 1 + 65 + 1 + 32) * 2)
+
+typedef struct {
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+
+ uint8_t *MBEDTLS_PRIVATE(password);
+ size_t MBEDTLS_PRIVATE(password_len);
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_JPAKE)
+ mbedtls_ecjpake_role MBEDTLS_PRIVATE(role);
+ uint8_t MBEDTLS_PRIVATE(buffer[MBEDTLS_PSA_JPAKE_BUFFER_SIZE]);
+ size_t MBEDTLS_PRIVATE(buffer_length);
+ size_t MBEDTLS_PRIVATE(buffer_offset);
+#endif
+ /* Context structure for the Mbed TLS EC-JPAKE implementation. */
+ union {
+ unsigned int MBEDTLS_PRIVATE(dummy);
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_JPAKE)
+ mbedtls_ecjpake_context MBEDTLS_PRIVATE(jpake);
+#endif
+ } MBEDTLS_PRIVATE(ctx);
+
+} mbedtls_psa_pake_operation_t;
+
+#define MBEDTLS_PSA_PAKE_OPERATION_INIT { { 0 } }
+
+#endif /* PSA_CRYPTO_BUILTIN_COMPOSITES_H */
diff --git a/include/psa/crypto_builtin_key_derivation.h b/include/psa/crypto_builtin_key_derivation.h
new file mode 100644
index 0000000..6b91ae7
--- /dev/null
+++ b/include/psa/crypto_builtin_key_derivation.h
@@ -0,0 +1,118 @@
+/*
+ * Context structure declaration of the Mbed TLS software-based PSA drivers
+ * called through the PSA Crypto driver dispatch layer.
+ * This file contains the context structures of key derivation algorithms
+ * which need to rely on other algorithms.
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ *
+ * \note This header and its content are not part of the Mbed TLS API and
+ * applications must not depend on it. Its main purpose is to define the
+ * multi-part state objects of the Mbed TLS software-based PSA drivers. The
+ * definitions of these objects are then used by crypto_struct.h to define the
+ * implementation-defined types of PSA multi-part state objects.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_BUILTIN_KEY_DERIVATION_H
+#define PSA_CRYPTO_BUILTIN_KEY_DERIVATION_H
+#include "mbedtls/private_access.h"
+
+#include <psa/crypto_driver_common.h>
+
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
+typedef struct {
+ uint8_t *MBEDTLS_PRIVATE(info);
+ size_t MBEDTLS_PRIVATE(info_length);
+#if PSA_HASH_MAX_SIZE > 0xff
+#error "PSA_HASH_MAX_SIZE does not fit in uint8_t"
+#endif
+ uint8_t MBEDTLS_PRIVATE(offset_in_block);
+ uint8_t MBEDTLS_PRIVATE(block_number);
+ unsigned int MBEDTLS_PRIVATE(state) : 2;
+ unsigned int MBEDTLS_PRIVATE(info_set) : 1;
+ uint8_t MBEDTLS_PRIVATE(output_block)[PSA_HASH_MAX_SIZE];
+ uint8_t MBEDTLS_PRIVATE(prk)[PSA_HASH_MAX_SIZE];
+ struct psa_mac_operation_s MBEDTLS_PRIVATE(hmac);
+} psa_hkdf_key_derivation_t;
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF ||
+ MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT ||
+ MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND */
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
+typedef struct {
+ uint8_t MBEDTLS_PRIVATE(data)[PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE];
+} psa_tls12_ecjpake_to_pms_t;
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS */
+
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
+typedef enum {
+ PSA_TLS12_PRF_STATE_INIT, /* no input provided */
+ PSA_TLS12_PRF_STATE_SEED_SET, /* seed has been set */
+ PSA_TLS12_PRF_STATE_OTHER_KEY_SET, /* other key has been set - optional */
+ PSA_TLS12_PRF_STATE_KEY_SET, /* key has been set */
+ PSA_TLS12_PRF_STATE_LABEL_SET, /* label has been set */
+ PSA_TLS12_PRF_STATE_OUTPUT /* output has been started */
+} psa_tls12_prf_key_derivation_state_t;
+
+typedef struct psa_tls12_prf_key_derivation_s {
+#if PSA_HASH_MAX_SIZE > 0xff
+#error "PSA_HASH_MAX_SIZE does not fit in uint8_t"
+#endif
+
+ /* Indicates how many bytes in the current HMAC block have
+ * not yet been read by the user. */
+ uint8_t MBEDTLS_PRIVATE(left_in_block);
+
+ /* The 1-based number of the block. */
+ uint8_t MBEDTLS_PRIVATE(block_number);
+
+ psa_tls12_prf_key_derivation_state_t MBEDTLS_PRIVATE(state);
+
+ uint8_t *MBEDTLS_PRIVATE(secret);
+ size_t MBEDTLS_PRIVATE(secret_length);
+ uint8_t *MBEDTLS_PRIVATE(seed);
+ size_t MBEDTLS_PRIVATE(seed_length);
+ uint8_t *MBEDTLS_PRIVATE(label);
+ size_t MBEDTLS_PRIVATE(label_length);
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
+ uint8_t *MBEDTLS_PRIVATE(other_secret);
+ size_t MBEDTLS_PRIVATE(other_secret_length);
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
+
+ uint8_t MBEDTLS_PRIVATE(Ai)[PSA_HASH_MAX_SIZE];
+
+ /* `HMAC_hash( prk, A( i ) + seed )` in the notation of RFC 5246, Sect. 5. */
+ uint8_t MBEDTLS_PRIVATE(output_block)[PSA_HASH_MAX_SIZE];
+} psa_tls12_prf_key_derivation_t;
+#endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) ||
+ * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */
+#if defined(PSA_HAVE_SOFT_PBKDF2)
+typedef enum {
+ PSA_PBKDF2_STATE_INIT, /* no input provided */
+ PSA_PBKDF2_STATE_INPUT_COST_SET, /* input cost has been set */
+ PSA_PBKDF2_STATE_SALT_SET, /* salt has been set */
+ PSA_PBKDF2_STATE_PASSWORD_SET, /* password has been set */
+ PSA_PBKDF2_STATE_OUTPUT /* output has been started */
+} psa_pbkdf2_key_derivation_state_t;
+
+typedef struct {
+ psa_pbkdf2_key_derivation_state_t MBEDTLS_PRIVATE(state);
+ uint64_t MBEDTLS_PRIVATE(input_cost);
+ uint8_t *MBEDTLS_PRIVATE(salt);
+ size_t MBEDTLS_PRIVATE(salt_length);
+ uint8_t MBEDTLS_PRIVATE(password)[PSA_HMAC_MAX_HASH_BLOCK_SIZE];
+ size_t MBEDTLS_PRIVATE(password_length);
+ uint8_t MBEDTLS_PRIVATE(output_block)[PSA_HASH_MAX_SIZE];
+ uint8_t MBEDTLS_PRIVATE(bytes_used);
+ uint32_t MBEDTLS_PRIVATE(block_number);
+} psa_pbkdf2_key_derivation_t;
+#endif /* PSA_HAVE_SOFT_PBKDF2 */
+
+#endif /* PSA_CRYPTO_BUILTIN_KEY_DERIVATION_H */
diff --git a/include/psa/crypto_builtin_primitives.h b/include/psa/crypto_builtin_primitives.h
new file mode 100644
index 0000000..98ab4d3
--- /dev/null
+++ b/include/psa/crypto_builtin_primitives.h
@@ -0,0 +1,114 @@
+/*
+ * Context structure declaration of the Mbed TLS software-based PSA drivers
+ * called through the PSA Crypto driver dispatch layer.
+ * This file contains the context structures of those algorithms which do not
+ * rely on other algorithms, i.e. are 'primitive' algorithms.
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ *
+ * \note This header and its content are not part of the Mbed TLS API and
+ * applications must not depend on it. Its main purpose is to define the
+ * multi-part state objects of the Mbed TLS software-based PSA drivers. The
+ * definitions of these objects are then used by crypto_struct.h to define the
+ * implementation-defined types of PSA multi-part state objects.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_BUILTIN_PRIMITIVES_H
+#define PSA_CRYPTO_BUILTIN_PRIMITIVES_H
+#include "mbedtls/private_access.h"
+
+#include <psa/crypto_driver_common.h>
+
+/*
+ * Hash multi-part operation definitions.
+ */
+
+#include "mbedtls/md5.h"
+#include "mbedtls/ripemd160.h"
+#include "mbedtls/sha1.h"
+#include "mbedtls/sha256.h"
+#include "mbedtls/sha512.h"
+#include "mbedtls/sha3.h"
+
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA3_224) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA3_256) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA3_384) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA3_512)
+#define MBEDTLS_PSA_BUILTIN_HASH
+#endif
+
+typedef struct {
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+ union {
+ unsigned dummy; /* Make the union non-empty even with no supported algorithms. */
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_MD5)
+ mbedtls_md5_context md5;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160)
+ mbedtls_ripemd160_context ripemd160;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1)
+ mbedtls_sha1_context sha1;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224)
+ mbedtls_sha256_context sha256;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384)
+ mbedtls_sha512_context sha512;
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_SHA3_224) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA3_256) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA3_384) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA3_512)
+ mbedtls_sha3_context sha3;
+#endif
+ } MBEDTLS_PRIVATE(ctx);
+} mbedtls_psa_hash_operation_t;
+
+#define MBEDTLS_PSA_HASH_OPERATION_INIT { 0, { 0 } }
+
+/*
+ * Cipher multi-part operation definitions.
+ */
+
+#include "mbedtls/cipher.h"
+
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_STREAM_CIPHER) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_CTR) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_CFB) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_OFB) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_CCM_STAR_NO_TAG)
+#define MBEDTLS_PSA_BUILTIN_CIPHER 1
+#endif
+
+typedef struct {
+ /* Context structure for the Mbed TLS cipher implementation. */
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+ uint8_t MBEDTLS_PRIVATE(iv_length);
+ uint8_t MBEDTLS_PRIVATE(block_length);
+ union {
+ unsigned int MBEDTLS_PRIVATE(dummy);
+ mbedtls_cipher_context_t MBEDTLS_PRIVATE(cipher);
+ } MBEDTLS_PRIVATE(ctx);
+} mbedtls_psa_cipher_operation_t;
+
+#define MBEDTLS_PSA_CIPHER_OPERATION_INIT { 0, 0, 0, { 0 } }
+
+#endif /* PSA_CRYPTO_BUILTIN_PRIMITIVES_H */
diff --git a/include/psa/crypto_compat.h b/include/psa/crypto_compat.h
new file mode 100644
index 0000000..f896fae
--- /dev/null
+++ b/include/psa/crypto_compat.h
@@ -0,0 +1,153 @@
+/**
+ * \file psa/crypto_compat.h
+ *
+ * \brief PSA cryptography module: Backward compatibility aliases
+ *
+ * This header declares alternative names for macro and functions.
+ * New application code should not use these names.
+ * These names may be removed in a future version of Mbed TLS.
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_COMPAT_H
+#define PSA_CRYPTO_COMPAT_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/*
+ * To support both openless APIs and psa_open_key() temporarily, define
+ * psa_key_handle_t to be equal to mbedtls_svc_key_id_t. Do not mark the
+ * type and its utility macros and functions deprecated yet. This will be done
+ * in a subsequent phase.
+ */
+typedef mbedtls_svc_key_id_t psa_key_handle_t;
+
+#define PSA_KEY_HANDLE_INIT MBEDTLS_SVC_KEY_ID_INIT
+
+/** Check whether a handle is null.
+ *
+ * \param handle Handle
+ *
+ * \return Non-zero if the handle is null, zero otherwise.
+ */
+static inline int psa_key_handle_is_null(psa_key_handle_t handle)
+{
+ return mbedtls_svc_key_id_is_null(handle);
+}
+
+/** Open a handle to an existing persistent key.
+ *
+ * Open a handle to a persistent key. A key is persistent if it was created
+ * with a lifetime other than #PSA_KEY_LIFETIME_VOLATILE. A persistent key
+ * always has a nonzero key identifier, set with psa_set_key_id() when
+ * creating the key. Implementations may provide additional pre-provisioned
+ * keys that can be opened with psa_open_key(). Such keys have an application
+ * key identifier in the vendor range, as documented in the description of
+ * #psa_key_id_t.
+ *
+ * The application must eventually close the handle with psa_close_key() or
+ * psa_destroy_key() to release associated resources. If the application dies
+ * without calling one of these functions, the implementation should perform
+ * the equivalent of a call to psa_close_key().
+ *
+ * Some implementations permit an application to open the same key multiple
+ * times. If this is successful, each call to psa_open_key() will return a
+ * different key handle.
+ *
+ * \note This API is not part of the PSA Cryptography API Release 1.0.0
+ * specification. It was defined in the 1.0 Beta 3 version of the
+ * specification but was removed in the 1.0.0 released version. This API is
+ * kept for the time being to not break applications relying on it. It is not
+ * deprecated yet but will be in the near future.
+ *
+ * \note Applications that rely on opening a key multiple times will not be
+ * portable to implementations that only permit a single key handle to be
+ * opened. See also :ref:\`key-handles\`.
+ *
+ *
+ * \param key The persistent identifier of the key.
+ * \param[out] handle On success, a handle to the key.
+ *
+ * \retval #PSA_SUCCESS
+ * Success. The application can now use the value of `*handle`
+ * to access the key.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY
+ * The implementation does not have sufficient resources to open the
+ * key. This can be due to reaching an implementation limit on the
+ * number of open keys, the number of open key handles, or available
+ * memory.
+ * \retval #PSA_ERROR_DOES_NOT_EXIST
+ * There is no persistent key with key identifier \p key.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p key is not a valid persistent key identifier.
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The specified key exists, but the application does not have the
+ * permission to access it. Note that this specification does not
+ * define any way to create such a key, but it may be possible
+ * through implementation-specific means.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_open_key(mbedtls_svc_key_id_t key,
+ psa_key_handle_t *handle);
+
+/** Close a key handle.
+ *
+ * If the handle designates a volatile key, this will destroy the key material
+ * and free all associated resources, just like psa_destroy_key().
+ *
+ * If this is the last open handle to a persistent key, then closing the handle
+ * will free all resources associated with the key in volatile memory. The key
+ * data in persistent storage is not affected and can be opened again later
+ * with a call to psa_open_key().
+ *
+ * Closing the key handle makes the handle invalid, and the key handle
+ * must not be used again by the application.
+ *
+ * \note This API is not part of the PSA Cryptography API Release 1.0.0
+ * specification. It was defined in the 1.0 Beta 3 version of the
+ * specification but was removed in the 1.0.0 released version. This API is
+ * kept for the time being to not break applications relying on it. It is not
+ * deprecated yet but will be in the near future.
+ *
+ * \note If the key handle was used to set up an active
+ * :ref:\`multipart operation <multipart-operations>\`, then closing the
+ * key handle can cause the multipart operation to fail. Applications should
+ * maintain the key handle until after the multipart operation has finished.
+ *
+ * \param handle The key handle to close.
+ * If this is \c 0, do nothing and return \c PSA_SUCCESS.
+ *
+ * \retval #PSA_SUCCESS
+ * \p handle was a valid handle or \c 0. It is now closed.
+ * \retval #PSA_ERROR_INVALID_HANDLE
+ * \p handle is not a valid handle nor \c 0.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_close_key(psa_key_handle_t handle);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PSA_CRYPTO_COMPAT_H */
diff --git a/include/psa/crypto_config.h b/include/psa/crypto_config.h
new file mode 100644
index 0000000..5bf00f4
--- /dev/null
+++ b/include/psa/crypto_config.h
@@ -0,0 +1,153 @@
+/**
+ * \file psa/crypto_config.h
+ * \brief PSA crypto configuration options (set of defines)
+ *
+ */
+#if defined(MBEDTLS_PSA_CRYPTO_CONFIG)
+/**
+ * When #MBEDTLS_PSA_CRYPTO_CONFIG is enabled in mbedtls_config.h,
+ * this file determines which cryptographic mechanisms are enabled
+ * through the PSA Cryptography API (\c psa_xxx() functions).
+ *
+ * To enable a cryptographic mechanism, uncomment the definition of
+ * the corresponding \c PSA_WANT_xxx preprocessor symbol.
+ * To disable a cryptographic mechanism, comment out the definition of
+ * the corresponding \c PSA_WANT_xxx preprocessor symbol.
+ * The names of cryptographic mechanisms correspond to values
+ * defined in psa/crypto_values.h, with the prefix \c PSA_WANT_ instead
+ * of \c PSA_.
+ *
+ * Note that many cryptographic mechanisms involve two symbols: one for
+ * the key type (\c PSA_WANT_KEY_TYPE_xxx) and one for the algorithm
+ * (\c PSA_WANT_ALG_xxx). Mechanisms with additional parameters may involve
+ * additional symbols.
+ */
+#else
+/**
+ * When \c MBEDTLS_PSA_CRYPTO_CONFIG is disabled in mbedtls_config.h,
+ * this file is not used, and cryptographic mechanisms are supported
+ * through the PSA API if and only if they are supported through the
+ * mbedtls_xxx API.
+ */
+#endif
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_CONFIG_H
+#define PSA_CRYPTO_CONFIG_H
+
+/*
+ * CBC-MAC is not yet supported via the PSA API in Mbed TLS.
+ */
+//#define PSA_WANT_ALG_CBC_MAC 1
+#define PSA_WANT_ALG_CBC_NO_PADDING 1
+#define PSA_WANT_ALG_CBC_PKCS7 1
+#define PSA_WANT_ALG_CCM 1
+#define PSA_WANT_ALG_CCM_STAR_NO_TAG 1
+#define PSA_WANT_ALG_CMAC 1
+#define PSA_WANT_ALG_CFB 1
+#define PSA_WANT_ALG_CHACHA20_POLY1305 1
+#define PSA_WANT_ALG_CTR 1
+#define PSA_WANT_ALG_DETERMINISTIC_ECDSA 1
+#define PSA_WANT_ALG_ECB_NO_PADDING 1
+#define PSA_WANT_ALG_ECDH 1
+#define PSA_WANT_ALG_FFDH 1
+#define PSA_WANT_ALG_ECDSA 1
+#define PSA_WANT_ALG_JPAKE 1
+#define PSA_WANT_ALG_GCM 1
+#define PSA_WANT_ALG_HKDF 1
+#define PSA_WANT_ALG_HKDF_EXTRACT 1
+#define PSA_WANT_ALG_HKDF_EXPAND 1
+#define PSA_WANT_ALG_HMAC 1
+#define PSA_WANT_ALG_MD5 1
+#define PSA_WANT_ALG_OFB 1
+#define PSA_WANT_ALG_PBKDF2_HMAC 1
+#define PSA_WANT_ALG_PBKDF2_AES_CMAC_PRF_128 1
+#define PSA_WANT_ALG_RIPEMD160 1
+#define PSA_WANT_ALG_RSA_OAEP 1
+#define PSA_WANT_ALG_RSA_PKCS1V15_CRYPT 1
+#define PSA_WANT_ALG_RSA_PKCS1V15_SIGN 1
+#define PSA_WANT_ALG_RSA_PSS 1
+#define PSA_WANT_ALG_SHA_1 1
+#define PSA_WANT_ALG_SHA_224 1
+#define PSA_WANT_ALG_SHA_256 1
+#define PSA_WANT_ALG_SHA_384 1
+#define PSA_WANT_ALG_SHA_512 1
+#define PSA_WANT_ALG_SHA3_224 1
+#define PSA_WANT_ALG_SHA3_256 1
+#define PSA_WANT_ALG_SHA3_384 1
+#define PSA_WANT_ALG_SHA3_512 1
+#define PSA_WANT_ALG_STREAM_CIPHER 1
+#define PSA_WANT_ALG_TLS12_PRF 1
+#define PSA_WANT_ALG_TLS12_PSK_TO_MS 1
+#define PSA_WANT_ALG_TLS12_ECJPAKE_TO_PMS 1
+
+/* XTS is not yet supported via the PSA API in Mbed TLS.
+ * Note: when adding support, also adjust include/mbedtls/config_psa.h */
+//#define PSA_WANT_ALG_XTS 1
+
+#define PSA_WANT_ECC_BRAINPOOL_P_R1_256 1
+#define PSA_WANT_ECC_BRAINPOOL_P_R1_384 1
+#define PSA_WANT_ECC_BRAINPOOL_P_R1_512 1
+#define PSA_WANT_ECC_MONTGOMERY_255 1
+#define PSA_WANT_ECC_MONTGOMERY_448 1
+#define PSA_WANT_ECC_SECP_K1_192 1
+/*
+ * SECP224K1 is buggy via the PSA API in Mbed TLS
+ * (https://github.com/Mbed-TLS/mbedtls/issues/3541). Thus, do not enable it by
+ * default.
+ */
+//#define PSA_WANT_ECC_SECP_K1_224 1
+#define PSA_WANT_ECC_SECP_K1_256 1
+#define PSA_WANT_ECC_SECP_R1_192 1
+#define PSA_WANT_ECC_SECP_R1_224 1
+/* For secp256r1, consider enabling #MBEDTLS_PSA_P256M_DRIVER_ENABLED
+ * (see the description in mbedtls/mbedtls_config.h for details). */
+#define PSA_WANT_ECC_SECP_R1_256 1
+#define PSA_WANT_ECC_SECP_R1_384 1
+#define PSA_WANT_ECC_SECP_R1_521 1
+
+#define PSA_WANT_KEY_TYPE_DERIVE 1
+#define PSA_WANT_KEY_TYPE_PASSWORD 1
+#define PSA_WANT_KEY_TYPE_PASSWORD_HASH 1
+#define PSA_WANT_KEY_TYPE_HMAC 1
+#define PSA_WANT_KEY_TYPE_AES 1
+#define PSA_WANT_KEY_TYPE_ARIA 1
+#define PSA_WANT_KEY_TYPE_CAMELLIA 1
+#define PSA_WANT_KEY_TYPE_CHACHA20 1
+#define PSA_WANT_KEY_TYPE_DES 1
+//#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR 1 /* Deprecated */
+#define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1
+#define PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY 1
+#define PSA_WANT_KEY_TYPE_RAW_DATA 1
+//#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR 1 /* Deprecated */
+#define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1
+
+/*
+ * The following symbols extend and deprecate the legacy
+ * PSA_WANT_KEY_TYPE_xxx_KEY_PAIR ones. They include the usage of that key in
+ * the name's suffix. "_USE" is the most generic and it can be used to describe
+ * a generic suport, whereas other ones add more features on top of that and
+ * they are more specific.
+ */
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
+
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1
+//#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_DERIVE 1 /* Not supported */
+
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC 1
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_IMPORT 1
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_EXPORT 1
+#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_GENERATE 1
+//#define PSA_WANT_KEY_TYPE_DH_KEY_PAIR_DERIVE 1 /* Not supported */
+
+#endif /* PSA_CRYPTO_CONFIG_H */
diff --git a/include/psa/crypto_driver_common.h b/include/psa/crypto_driver_common.h
new file mode 100644
index 0000000..cc11d3b
--- /dev/null
+++ b/include/psa/crypto_driver_common.h
@@ -0,0 +1,44 @@
+/**
+ * \file psa/crypto_driver_common.h
+ * \brief Definitions for all PSA crypto drivers
+ *
+ * This file contains common definitions shared by all PSA crypto drivers.
+ * Do not include it directly: instead, include the header file(s) for
+ * the type(s) of driver that you are implementing. For example, if
+ * you are writing a dynamically registered driver for a secure element,
+ * include `psa/crypto_se_driver.h`.
+ *
+ * This file is part of the PSA Crypto Driver Model, containing functions for
+ * driver developers to implement to enable hardware to be called in a
+ * standardized way by a PSA Cryptographic API implementation. The functions
+ * comprising the driver model, which driver authors implement, are not
+ * intended to be called by application developers.
+ */
+
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef PSA_CRYPTO_DRIVER_COMMON_H
+#define PSA_CRYPTO_DRIVER_COMMON_H
+
+#include <stddef.h>
+#include <stdint.h>
+
+/* Include type definitions (psa_status_t, psa_algorithm_t,
+ * psa_key_type_t, etc.) and macros to build and analyze values
+ * of these types. */
+#include "crypto_types.h"
+#include "crypto_values.h"
+/* Include size definitions which are used to size some arrays in operation
+ * structures. */
+#include <psa/crypto_sizes.h>
+
+/** For encrypt-decrypt functions, whether the operation is an encryption
+ * or a decryption. */
+typedef enum {
+ PSA_CRYPTO_DRIVER_DECRYPT,
+ PSA_CRYPTO_DRIVER_ENCRYPT
+} psa_encrypt_or_decrypt_t;
+
+#endif /* PSA_CRYPTO_DRIVER_COMMON_H */
diff --git a/include/psa/crypto_driver_contexts_composites.h b/include/psa/crypto_driver_contexts_composites.h
new file mode 100644
index 0000000..d717c51
--- /dev/null
+++ b/include/psa/crypto_driver_contexts_composites.h
@@ -0,0 +1,151 @@
+/*
+ * Declaration of context structures for use with the PSA driver wrapper
+ * interface. This file contains the context structures for 'composite'
+ * operations, i.e. those operations which need to make use of other operations
+ * from the primitives (crypto_driver_contexts_primitives.h)
+ *
+ * Warning: This file will be auto-generated in the future.
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ *
+ * \note This header and its content are not part of the Mbed TLS API and
+ * applications must not depend on it. Its main purpose is to define the
+ * multi-part state objects of the PSA drivers included in the cryptographic
+ * library. The definitions of these objects are then used by crypto_struct.h
+ * to define the implementation-defined types of PSA multi-part state objects.
+ */
+/* Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_DRIVER_CONTEXTS_COMPOSITES_H
+#define PSA_CRYPTO_DRIVER_CONTEXTS_COMPOSITES_H
+
+#include "psa/crypto_driver_common.h"
+
+/* Include the context structure definitions for the Mbed TLS software drivers */
+#include "psa/crypto_builtin_composites.h"
+
+/* Include the context structure definitions for those drivers that were
+ * declared during the autogeneration process. */
+
+#if defined(MBEDTLS_TEST_LIBTESTDRIVER1)
+#include <libtestdriver1/include/psa/crypto.h>
+#endif
+
+#if defined(PSA_CRYPTO_DRIVER_TEST)
+#if defined(MBEDTLS_TEST_LIBTESTDRIVER1) && \
+ defined(LIBTESTDRIVER1_MBEDTLS_PSA_BUILTIN_MAC)
+typedef libtestdriver1_mbedtls_psa_mac_operation_t
+ mbedtls_transparent_test_driver_mac_operation_t;
+typedef libtestdriver1_mbedtls_psa_mac_operation_t
+ mbedtls_opaque_test_driver_mac_operation_t;
+
+#define MBEDTLS_TRANSPARENT_TEST_DRIVER_MAC_OPERATION_INIT \
+ LIBTESTDRIVER1_MBEDTLS_PSA_MAC_OPERATION_INIT
+#define MBEDTLS_OPAQUE_TEST_DRIVER_MAC_OPERATION_INIT \
+ LIBTESTDRIVER1_MBEDTLS_PSA_MAC_OPERATION_INIT
+
+#else
+typedef mbedtls_psa_mac_operation_t
+ mbedtls_transparent_test_driver_mac_operation_t;
+typedef mbedtls_psa_mac_operation_t
+ mbedtls_opaque_test_driver_mac_operation_t;
+
+#define MBEDTLS_TRANSPARENT_TEST_DRIVER_MAC_OPERATION_INIT \
+ MBEDTLS_PSA_MAC_OPERATION_INIT
+#define MBEDTLS_OPAQUE_TEST_DRIVER_MAC_OPERATION_INIT \
+ MBEDTLS_PSA_MAC_OPERATION_INIT
+
+#endif /* MBEDTLS_TEST_LIBTESTDRIVER1 && LIBTESTDRIVER1_MBEDTLS_PSA_BUILTIN_MAC */
+
+#if defined(MBEDTLS_TEST_LIBTESTDRIVER1) && \
+ defined(LIBTESTDRIVER1_MBEDTLS_PSA_BUILTIN_AEAD)
+typedef libtestdriver1_mbedtls_psa_aead_operation_t
+ mbedtls_transparent_test_driver_aead_operation_t;
+
+#define MBEDTLS_TRANSPARENT_TEST_DRIVER_AEAD_OPERATION_INIT \
+ LIBTESTDRIVER1_MBEDTLS_PSA_AEAD_OPERATION_INIT
+#else
+typedef mbedtls_psa_aead_operation_t
+ mbedtls_transparent_test_driver_aead_operation_t;
+
+#define MBEDTLS_TRANSPARENT_TEST_DRIVER_AEAD_OPERATION_INIT \
+ MBEDTLS_PSA_AEAD_OPERATION_INIT
+
+#endif /* MBEDTLS_TEST_LIBTESTDRIVER1 && LIBTESTDRIVER1_MBEDTLS_PSA_BUILTIN_AEAD */
+
+#if defined(MBEDTLS_TEST_LIBTESTDRIVER1) && \
+ defined(LIBTESTDRIVER1_MBEDTLS_PSA_BUILTIN_PAKE)
+
+typedef libtestdriver1_mbedtls_psa_pake_operation_t
+ mbedtls_transparent_test_driver_pake_operation_t;
+typedef libtestdriver1_mbedtls_psa_pake_operation_t
+ mbedtls_opaque_test_driver_pake_operation_t;
+
+#define MBEDTLS_TRANSPARENT_TEST_DRIVER_PAKE_OPERATION_INIT \
+ LIBTESTDRIVER1_MBEDTLS_PSA_PAKE_OPERATION_INIT
+#define MBEDTLS_OPAQUE_TEST_DRIVER_PAKE_OPERATION_INIT \
+ LIBTESTDRIVER1_MBEDTLS_PSA_PAKE_OPERATION_INIT
+
+#else
+typedef mbedtls_psa_pake_operation_t
+ mbedtls_transparent_test_driver_pake_operation_t;
+typedef mbedtls_psa_pake_operation_t
+ mbedtls_opaque_test_driver_pake_operation_t;
+
+#define MBEDTLS_TRANSPARENT_TEST_DRIVER_PAKE_OPERATION_INIT \
+ MBEDTLS_PSA_PAKE_OPERATION_INIT
+#define MBEDTLS_OPAQUE_TEST_DRIVER_PAKE_OPERATION_INIT \
+ MBEDTLS_PSA_PAKE_OPERATION_INIT
+
+#endif /* MBEDTLS_TEST_LIBTESTDRIVER1 && LIBTESTDRIVER1_MBEDTLS_PSA_BUILTIN_PAKE */
+
+#endif /* PSA_CRYPTO_DRIVER_TEST */
+
+/* Define the context to be used for an operation that is executed through the
+ * PSA Driver wrapper layer as the union of all possible driver's contexts.
+ *
+ * The union members are the driver's context structures, and the member names
+ * are formatted as `'drivername'_ctx`. This allows for procedural generation
+ * of both this file and the content of psa_crypto_driver_wrappers.h */
+
+typedef union {
+ unsigned dummy; /* Make sure this union is always non-empty */
+ mbedtls_psa_mac_operation_t mbedtls_ctx;
+#if defined(PSA_CRYPTO_DRIVER_TEST)
+ mbedtls_transparent_test_driver_mac_operation_t transparent_test_driver_ctx;
+ mbedtls_opaque_test_driver_mac_operation_t opaque_test_driver_ctx;
+#endif
+} psa_driver_mac_context_t;
+
+typedef union {
+ unsigned dummy; /* Make sure this union is always non-empty */
+ mbedtls_psa_aead_operation_t mbedtls_ctx;
+#if defined(PSA_CRYPTO_DRIVER_TEST)
+ mbedtls_transparent_test_driver_aead_operation_t transparent_test_driver_ctx;
+#endif
+} psa_driver_aead_context_t;
+
+typedef union {
+ unsigned dummy; /* Make sure this union is always non-empty */
+ mbedtls_psa_sign_hash_interruptible_operation_t mbedtls_ctx;
+} psa_driver_sign_hash_interruptible_context_t;
+
+typedef union {
+ unsigned dummy; /* Make sure this union is always non-empty */
+ mbedtls_psa_verify_hash_interruptible_operation_t mbedtls_ctx;
+} psa_driver_verify_hash_interruptible_context_t;
+
+typedef union {
+ unsigned dummy; /* Make sure this union is always non-empty */
+ mbedtls_psa_pake_operation_t mbedtls_ctx;
+#if defined(PSA_CRYPTO_DRIVER_TEST)
+ mbedtls_transparent_test_driver_pake_operation_t transparent_test_driver_ctx;
+ mbedtls_opaque_test_driver_pake_operation_t opaque_test_driver_ctx;
+#endif
+} psa_driver_pake_context_t;
+
+#endif /* PSA_CRYPTO_DRIVER_CONTEXTS_COMPOSITES_H */
+/* End of automatically generated file. */
diff --git a/include/psa/crypto_driver_contexts_key_derivation.h b/include/psa/crypto_driver_contexts_key_derivation.h
new file mode 100644
index 0000000..2119051
--- /dev/null
+++ b/include/psa/crypto_driver_contexts_key_derivation.h
@@ -0,0 +1,52 @@
+/*
+ * Declaration of context structures for use with the PSA driver wrapper
+ * interface. This file contains the context structures for key derivation
+ * operations.
+ *
+ * Warning: This file will be auto-generated in the future.
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ *
+ * \note This header and its content are not part of the Mbed TLS API and
+ * applications must not depend on it. Its main purpose is to define the
+ * multi-part state objects of the PSA drivers included in the cryptographic
+ * library. The definitions of these objects are then used by crypto_struct.h
+ * to define the implementation-defined types of PSA multi-part state objects.
+ */
+/* Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_DRIVER_CONTEXTS_KEY_DERIVATION_H
+#define PSA_CRYPTO_DRIVER_CONTEXTS_KEY_DERIVATION_H
+
+#include "psa/crypto_driver_common.h"
+
+/* Include the context structure definitions for the Mbed TLS software drivers */
+#include "psa/crypto_builtin_key_derivation.h"
+
+/* Include the context structure definitions for those drivers that were
+ * declared during the autogeneration process. */
+
+typedef union {
+ unsigned dummy; /* Make sure this union is always non-empty */
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXTRACT) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF_EXPAND)
+ psa_hkdf_key_derivation_t MBEDTLS_PRIVATE(hkdf);
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \
+ defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS)
+ psa_tls12_prf_key_derivation_t MBEDTLS_PRIVATE(tls12_prf);
+#endif
+#if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_ECJPAKE_TO_PMS)
+ psa_tls12_ecjpake_to_pms_t MBEDTLS_PRIVATE(tls12_ecjpake_to_pms);
+#endif
+#if defined(PSA_HAVE_SOFT_PBKDF2)
+ psa_pbkdf2_key_derivation_t MBEDTLS_PRIVATE(pbkdf2);
+#endif
+} psa_driver_key_derivation_context_t;
+
+#endif /* PSA_CRYPTO_DRIVER_CONTEXTS_KEY_DERIVATION_H */
+/* End of automatically generated file. */
diff --git a/include/psa/crypto_driver_contexts_primitives.h b/include/psa/crypto_driver_contexts_primitives.h
new file mode 100644
index 0000000..c90a5fb
--- /dev/null
+++ b/include/psa/crypto_driver_contexts_primitives.h
@@ -0,0 +1,105 @@
+/*
+ * Declaration of context structures for use with the PSA driver wrapper
+ * interface. This file contains the context structures for 'primitive'
+ * operations, i.e. those operations which do not rely on other contexts.
+ *
+ * Warning: This file will be auto-generated in the future.
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ *
+ * \note This header and its content are not part of the Mbed TLS API and
+ * applications must not depend on it. Its main purpose is to define the
+ * multi-part state objects of the PSA drivers included in the cryptographic
+ * library. The definitions of these objects are then used by crypto_struct.h
+ * to define the implementation-defined types of PSA multi-part state objects.
+ */
+/* Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_DRIVER_CONTEXTS_PRIMITIVES_H
+#define PSA_CRYPTO_DRIVER_CONTEXTS_PRIMITIVES_H
+
+#include "psa/crypto_driver_common.h"
+
+/* Include the context structure definitions for the Mbed TLS software drivers */
+#include "psa/crypto_builtin_primitives.h"
+
+/* Include the context structure definitions for those drivers that were
+ * declared during the autogeneration process. */
+
+#if defined(MBEDTLS_TEST_LIBTESTDRIVER1)
+#include <libtestdriver1/include/psa/crypto.h>
+#endif
+
+#if defined(PSA_CRYPTO_DRIVER_TEST)
+
+#if defined(MBEDTLS_TEST_LIBTESTDRIVER1) && \
+ defined(LIBTESTDRIVER1_MBEDTLS_PSA_BUILTIN_CIPHER)
+typedef libtestdriver1_mbedtls_psa_cipher_operation_t
+ mbedtls_transparent_test_driver_cipher_operation_t;
+
+#define MBEDTLS_TRANSPARENT_TEST_DRIVER_CIPHER_OPERATION_INIT \
+ LIBTESTDRIVER1_MBEDTLS_PSA_CIPHER_OPERATION_INIT
+#else
+typedef mbedtls_psa_cipher_operation_t
+ mbedtls_transparent_test_driver_cipher_operation_t;
+
+#define MBEDTLS_TRANSPARENT_TEST_DRIVER_CIPHER_OPERATION_INIT \
+ MBEDTLS_PSA_CIPHER_OPERATION_INIT
+#endif /* MBEDTLS_TEST_LIBTESTDRIVER1 &&
+ LIBTESTDRIVER1_MBEDTLS_PSA_BUILTIN_CIPHER */
+
+#if defined(MBEDTLS_TEST_LIBTESTDRIVER1) && \
+ defined(LIBTESTDRIVER1_MBEDTLS_PSA_BUILTIN_HASH)
+typedef libtestdriver1_mbedtls_psa_hash_operation_t
+ mbedtls_transparent_test_driver_hash_operation_t;
+
+#define MBEDTLS_TRANSPARENT_TEST_DRIVER_HASH_OPERATION_INIT \
+ LIBTESTDRIVER1_MBEDTLS_PSA_HASH_OPERATION_INIT
+#else
+typedef mbedtls_psa_hash_operation_t
+ mbedtls_transparent_test_driver_hash_operation_t;
+
+#define MBEDTLS_TRANSPARENT_TEST_DRIVER_HASH_OPERATION_INIT \
+ MBEDTLS_PSA_HASH_OPERATION_INIT
+#endif /* MBEDTLS_TEST_LIBTESTDRIVER1 &&
+ LIBTESTDRIVER1_MBEDTLS_PSA_BUILTIN_HASH */
+
+typedef struct {
+ unsigned int initialised : 1;
+ mbedtls_transparent_test_driver_cipher_operation_t ctx;
+} mbedtls_opaque_test_driver_cipher_operation_t;
+
+#define MBEDTLS_OPAQUE_TEST_DRIVER_CIPHER_OPERATION_INIT \
+ { 0, MBEDTLS_TRANSPARENT_TEST_DRIVER_CIPHER_OPERATION_INIT }
+
+#endif /* PSA_CRYPTO_DRIVER_TEST */
+
+/* Define the context to be used for an operation that is executed through the
+ * PSA Driver wrapper layer as the union of all possible driver's contexts.
+ *
+ * The union members are the driver's context structures, and the member names
+ * are formatted as `'drivername'_ctx`. This allows for procedural generation
+ * of both this file and the content of psa_crypto_driver_wrappers.h */
+
+typedef union {
+ unsigned dummy; /* Make sure this union is always non-empty */
+ mbedtls_psa_hash_operation_t mbedtls_ctx;
+#if defined(PSA_CRYPTO_DRIVER_TEST)
+ mbedtls_transparent_test_driver_hash_operation_t test_driver_ctx;
+#endif
+} psa_driver_hash_context_t;
+
+typedef union {
+ unsigned dummy; /* Make sure this union is always non-empty */
+ mbedtls_psa_cipher_operation_t mbedtls_ctx;
+#if defined(PSA_CRYPTO_DRIVER_TEST)
+ mbedtls_transparent_test_driver_cipher_operation_t transparent_test_driver_ctx;
+ mbedtls_opaque_test_driver_cipher_operation_t opaque_test_driver_ctx;
+#endif
+} psa_driver_cipher_context_t;
+
+#endif /* PSA_CRYPTO_DRIVER_CONTEXTS_PRIMITIVES_H */
+/* End of automatically generated file. */
diff --git a/include/psa/crypto_extra.h b/include/psa/crypto_extra.h
new file mode 100644
index 0000000..ef29b77
--- /dev/null
+++ b/include/psa/crypto_extra.h
@@ -0,0 +1,2064 @@
+/**
+ * \file psa/crypto_extra.h
+ *
+ * \brief PSA cryptography module: Mbed TLS vendor extensions
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ *
+ * This file is reserved for vendor-specific definitions.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_EXTRA_H
+#define PSA_CRYPTO_EXTRA_H
+#include "mbedtls/private_access.h"
+
+#include "crypto_types.h"
+#include "crypto_compat.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* UID for secure storage seed */
+#define PSA_CRYPTO_ITS_RANDOM_SEED_UID 0xFFFFFF52
+
+/* See mbedtls_config.h for definition */
+#if !defined(MBEDTLS_PSA_KEY_SLOT_COUNT)
+#define MBEDTLS_PSA_KEY_SLOT_COUNT 32
+#endif
+
+/** \addtogroup attributes
+ * @{
+ */
+
+/** \brief Declare the enrollment algorithm for a key.
+ *
+ * An operation on a key may indifferently use the algorithm set with
+ * psa_set_key_algorithm() or with this function.
+ *
+ * \param[out] attributes The attribute structure to write to.
+ * \param alg2 A second algorithm that the key may be used
+ * for, in addition to the algorithm set with
+ * psa_set_key_algorithm().
+ *
+ * \warning Setting an enrollment algorithm is not recommended, because
+ * using the same key with different algorithms can allow some
+ * attacks based on arithmetic relations between different
+ * computations made with the same key, or can escalate harmless
+ * side channels into exploitable ones. Use this function only
+ * if it is necessary to support a protocol for which it has been
+ * verified that the usage of the key with multiple algorithms
+ * is safe.
+ */
+static inline void psa_set_key_enrollment_algorithm(
+ psa_key_attributes_t *attributes,
+ psa_algorithm_t alg2)
+{
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(policy).MBEDTLS_PRIVATE(alg2) = alg2;
+}
+
+/** Retrieve the enrollment algorithm policy from key attributes.
+ *
+ * \param[in] attributes The key attribute structure to query.
+ *
+ * \return The enrollment algorithm stored in the attribute structure.
+ */
+static inline psa_algorithm_t psa_get_key_enrollment_algorithm(
+ const psa_key_attributes_t *attributes)
+{
+ return attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(policy).MBEDTLS_PRIVATE(alg2);
+}
+
+#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
+
+/** Retrieve the slot number where a key is stored.
+ *
+ * A slot number is only defined for keys that are stored in a secure
+ * element.
+ *
+ * This information is only useful if the secure element is not entirely
+ * managed through the PSA Cryptography API. It is up to the secure
+ * element driver to decide how PSA slot numbers map to any other interface
+ * that the secure element may have.
+ *
+ * \param[in] attributes The key attribute structure to query.
+ * \param[out] slot_number On success, the slot number containing the key.
+ *
+ * \retval #PSA_SUCCESS
+ * The key is located in a secure element, and \p *slot_number
+ * indicates the slot number that contains it.
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The caller is not permitted to query the slot number.
+ * Mbed TLS currently does not return this error.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The key is not located in a secure element.
+ */
+psa_status_t psa_get_key_slot_number(
+ const psa_key_attributes_t *attributes,
+ psa_key_slot_number_t *slot_number);
+
+/** Choose the slot number where a key is stored.
+ *
+ * This function declares a slot number in the specified attribute
+ * structure.
+ *
+ * A slot number is only meaningful for keys that are stored in a secure
+ * element. It is up to the secure element driver to decide how PSA slot
+ * numbers map to any other interface that the secure element may have.
+ *
+ * \note Setting a slot number in key attributes for a key creation can
+ * cause the following errors when creating the key:
+ * - #PSA_ERROR_NOT_SUPPORTED if the selected secure element does
+ * not support choosing a specific slot number.
+ * - #PSA_ERROR_NOT_PERMITTED if the caller is not permitted to
+ * choose slot numbers in general or to choose this specific slot.
+ * - #PSA_ERROR_INVALID_ARGUMENT if the chosen slot number is not
+ * valid in general or not valid for this specific key.
+ * - #PSA_ERROR_ALREADY_EXISTS if there is already a key in the
+ * selected slot.
+ *
+ * \param[out] attributes The attribute structure to write to.
+ * \param slot_number The slot number to set.
+ */
+static inline void psa_set_key_slot_number(
+ psa_key_attributes_t *attributes,
+ psa_key_slot_number_t slot_number)
+{
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(flags) |= MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER;
+ attributes->MBEDTLS_PRIVATE(slot_number) = slot_number;
+}
+
+/** Remove the slot number attribute from a key attribute structure.
+ *
+ * This function undoes the action of psa_set_key_slot_number().
+ *
+ * \param[out] attributes The attribute structure to write to.
+ */
+static inline void psa_clear_key_slot_number(
+ psa_key_attributes_t *attributes)
+{
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(flags) &=
+ ~MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER;
+}
+
+/** Register a key that is already present in a secure element.
+ *
+ * The key must be located in a secure element designated by the
+ * lifetime field in \p attributes, in the slot set with
+ * psa_set_key_slot_number() in the attribute structure.
+ * This function makes the key available through the key identifier
+ * specified in \p attributes.
+ *
+ * \param[in] attributes The attributes of the existing key.
+ *
+ * \retval #PSA_SUCCESS
+ * The key was successfully registered.
+ * Note that depending on the design of the driver, this may or may
+ * not guarantee that a key actually exists in the designated slot
+ * and is compatible with the specified attributes.
+ * \retval #PSA_ERROR_ALREADY_EXISTS
+ * There is already a key with the identifier specified in
+ * \p attributes.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * The secure element driver for the specified lifetime does not
+ * support registering a key.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The identifier in \p attributes is invalid, namely the identifier is
+ * not in the user range, or
+ * \p attributes specifies a lifetime which is not located
+ * in a secure element, or no slot number is specified in \p attributes,
+ * or the specified slot number is not valid.
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The caller is not authorized to register the specified key slot.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t mbedtls_psa_register_se_key(
+ const psa_key_attributes_t *attributes);
+
+#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
+
+/**@}*/
+
+/**
+ * \brief Library deinitialization.
+ *
+ * This function clears all data associated with the PSA layer,
+ * including the whole key store.
+ *
+ * This is an Mbed TLS extension.
+ */
+void mbedtls_psa_crypto_free(void);
+
+/** \brief Statistics about
+ * resource consumption related to the PSA keystore.
+ *
+ * \note The content of this structure is not part of the stable API and ABI
+ * of Mbed TLS and may change arbitrarily from version to version.
+ */
+typedef struct mbedtls_psa_stats_s {
+ /** Number of slots containing key material for a volatile key. */
+ size_t MBEDTLS_PRIVATE(volatile_slots);
+ /** Number of slots containing key material for a key which is in
+ * internal persistent storage. */
+ size_t MBEDTLS_PRIVATE(persistent_slots);
+ /** Number of slots containing a reference to a key in a
+ * secure element. */
+ size_t MBEDTLS_PRIVATE(external_slots);
+ /** Number of slots which are occupied, but do not contain
+ * key material yet. */
+ size_t MBEDTLS_PRIVATE(half_filled_slots);
+ /** Number of slots that contain cache data. */
+ size_t MBEDTLS_PRIVATE(cache_slots);
+ /** Number of slots that are not used for anything. */
+ size_t MBEDTLS_PRIVATE(empty_slots);
+ /** Number of slots that are locked. */
+ size_t MBEDTLS_PRIVATE(locked_slots);
+ /** Largest key id value among open keys in internal persistent storage. */
+ psa_key_id_t MBEDTLS_PRIVATE(max_open_internal_key_id);
+ /** Largest key id value among open keys in secure elements. */
+ psa_key_id_t MBEDTLS_PRIVATE(max_open_external_key_id);
+} mbedtls_psa_stats_t;
+
+/** \brief Get statistics about
+ * resource consumption related to the PSA keystore.
+ *
+ * \note When Mbed TLS is built as part of a service, with isolation
+ * between the application and the keystore, the service may or
+ * may not expose this function.
+ */
+void mbedtls_psa_get_stats(mbedtls_psa_stats_t *stats);
+
+/**
+ * \brief Inject an initial entropy seed for the random generator into
+ * secure storage.
+ *
+ * This function injects data to be used as a seed for the random generator
+ * used by the PSA Crypto implementation. On devices that lack a trusted
+ * entropy source (preferably a hardware random number generator),
+ * the Mbed PSA Crypto implementation uses this value to seed its
+ * random generator.
+ *
+ * On devices without a trusted entropy source, this function must be
+ * called exactly once in the lifetime of the device. On devices with
+ * a trusted entropy source, calling this function is optional.
+ * In all cases, this function may only be called before calling any
+ * other function in the PSA Crypto API, including psa_crypto_init().
+ *
+ * When this function returns successfully, it populates a file in
+ * persistent storage. Once the file has been created, this function
+ * can no longer succeed.
+ *
+ * If any error occurs, this function does not change the system state.
+ * You can call this function again after correcting the reason for the
+ * error if possible.
+ *
+ * \warning This function **can** fail! Callers MUST check the return status.
+ *
+ * \warning If you use this function, you should use it as part of a
+ * factory provisioning process. The value of the injected seed
+ * is critical to the security of the device. It must be
+ * *secret*, *unpredictable* and (statistically) *unique per device*.
+ * You should be generate it randomly using a cryptographically
+ * secure random generator seeded from trusted entropy sources.
+ * You should transmit it securely to the device and ensure
+ * that its value is not leaked or stored anywhere beyond the
+ * needs of transmitting it from the point of generation to
+ * the call of this function, and erase all copies of the value
+ * once this function returns.
+ *
+ * This is an Mbed TLS extension.
+ *
+ * \note This function is only available on the following platforms:
+ * * If the compile-time option MBEDTLS_PSA_INJECT_ENTROPY is enabled.
+ * Note that you must provide compatible implementations of
+ * mbedtls_nv_seed_read and mbedtls_nv_seed_write.
+ * * In a client-server integration of PSA Cryptography, on the client side,
+ * if the server supports this feature.
+ * \param[in] seed Buffer containing the seed value to inject.
+ * \param[in] seed_size Size of the \p seed buffer.
+ * The size of the seed in bytes must be greater
+ * or equal to both #MBEDTLS_ENTROPY_BLOCK_SIZE
+ * and the value of \c MBEDTLS_ENTROPY_MIN_PLATFORM
+ * in `library/entropy_poll.h` in the Mbed TLS source
+ * code.
+ * It must be less or equal to
+ * #MBEDTLS_ENTROPY_MAX_SEED_SIZE.
+ *
+ * \retval #PSA_SUCCESS
+ * The seed value was injected successfully. The random generator
+ * of the PSA Crypto implementation is now ready for use.
+ * You may now call psa_crypto_init() and use the PSA Crypto
+ * implementation.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p seed_size is out of range.
+ * \retval #PSA_ERROR_STORAGE_FAILURE
+ * There was a failure reading or writing from storage.
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The library has already been initialized. It is no longer
+ * possible to call this function.
+ */
+psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed,
+ size_t seed_size);
+
+/** \addtogroup crypto_types
+ * @{
+ */
+
+/** DSA public key.
+ *
+ * The import and export format is the
+ * representation of the public key `y = g^x mod p` as a big-endian byte
+ * string. The length of the byte string is the length of the base prime `p`
+ * in bytes.
+ */
+#define PSA_KEY_TYPE_DSA_PUBLIC_KEY ((psa_key_type_t) 0x4002)
+
+/** DSA key pair (private and public key).
+ *
+ * The import and export format is the
+ * representation of the private key `x` as a big-endian byte string. The
+ * length of the byte string is the private key size in bytes (leading zeroes
+ * are not stripped).
+ *
+ * Deterministic DSA key derivation with psa_generate_derived_key follows
+ * FIPS 186-4 &sect;B.1.2: interpret the byte string as integer
+ * in big-endian order. Discard it if it is not in the range
+ * [0, *N* - 2] where *N* is the boundary of the private key domain
+ * (the prime *p* for Diffie-Hellman, the subprime *q* for DSA,
+ * or the order of the curve's base point for ECC).
+ * Add 1 to the resulting integer and use this as the private key *x*.
+ *
+ */
+#define PSA_KEY_TYPE_DSA_KEY_PAIR ((psa_key_type_t) 0x7002)
+
+/** Whether a key type is a DSA key (pair or public-only). */
+#define PSA_KEY_TYPE_IS_DSA(type) \
+ (PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) == PSA_KEY_TYPE_DSA_PUBLIC_KEY)
+
+#define PSA_ALG_DSA_BASE ((psa_algorithm_t) 0x06000400)
+/** DSA signature with hashing.
+ *
+ * This is the signature scheme defined by FIPS 186-4,
+ * with a random per-message secret number (*k*).
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ * This includes #PSA_ALG_ANY_HASH
+ * when specifying the algorithm in a usage policy.
+ *
+ * \return The corresponding DSA signature algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_DSA(hash_alg) \
+ (PSA_ALG_DSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+#define PSA_ALG_DETERMINISTIC_DSA_BASE ((psa_algorithm_t) 0x06000500)
+#define PSA_ALG_DSA_DETERMINISTIC_FLAG PSA_ALG_ECDSA_DETERMINISTIC_FLAG
+/** Deterministic DSA signature with hashing.
+ *
+ * This is the deterministic variant defined by RFC 6979 of
+ * the signature scheme defined by FIPS 186-4.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ * This includes #PSA_ALG_ANY_HASH
+ * when specifying the algorithm in a usage policy.
+ *
+ * \return The corresponding DSA signature algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_DETERMINISTIC_DSA(hash_alg) \
+ (PSA_ALG_DETERMINISTIC_DSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+#define PSA_ALG_IS_DSA(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK & ~PSA_ALG_DSA_DETERMINISTIC_FLAG) == \
+ PSA_ALG_DSA_BASE)
+#define PSA_ALG_DSA_IS_DETERMINISTIC(alg) \
+ (((alg) & PSA_ALG_DSA_DETERMINISTIC_FLAG) != 0)
+#define PSA_ALG_IS_DETERMINISTIC_DSA(alg) \
+ (PSA_ALG_IS_DSA(alg) && PSA_ALG_DSA_IS_DETERMINISTIC(alg))
+#define PSA_ALG_IS_RANDOMIZED_DSA(alg) \
+ (PSA_ALG_IS_DSA(alg) && !PSA_ALG_DSA_IS_DETERMINISTIC(alg))
+
+
+/* We need to expand the sample definition of this macro from
+ * the API definition. */
+#undef PSA_ALG_IS_VENDOR_HASH_AND_SIGN
+#define PSA_ALG_IS_VENDOR_HASH_AND_SIGN(alg) \
+ PSA_ALG_IS_DSA(alg)
+
+/**@}*/
+
+/** \addtogroup attributes
+ * @{
+ */
+
+/** Custom Diffie-Hellman group.
+ *
+ * For keys of type #PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_FAMILY_CUSTOM) or
+ * #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_FAMILY_CUSTOM), the group data comes
+ * from domain parameters set by psa_set_key_domain_parameters().
+ */
+#define PSA_DH_FAMILY_CUSTOM ((psa_dh_family_t) 0x7e)
+
+/** PAKE operation stages. */
+#define PSA_PAKE_OPERATION_STAGE_SETUP 0
+#define PSA_PAKE_OPERATION_STAGE_COLLECT_INPUTS 1
+#define PSA_PAKE_OPERATION_STAGE_COMPUTATION 2
+
+/**
+ * \brief Set domain parameters for a key.
+ *
+ * Some key types require additional domain parameters in addition to
+ * the key type identifier and the key size. Use this function instead
+ * of psa_set_key_type() when you need to specify domain parameters.
+ *
+ * The format for the required domain parameters varies based on the key type.
+ *
+ * - For RSA keys (#PSA_KEY_TYPE_RSA_PUBLIC_KEY or #PSA_KEY_TYPE_RSA_KEY_PAIR),
+ * the domain parameter data consists of the public exponent,
+ * represented as a big-endian integer with no leading zeros.
+ * This information is used when generating an RSA key pair.
+ * When importing a key, the public exponent is read from the imported
+ * key data and the exponent recorded in the attribute structure is ignored.
+ * As an exception, the public exponent 65537 is represented by an empty
+ * byte string.
+ * - For DSA keys (#PSA_KEY_TYPE_DSA_PUBLIC_KEY or #PSA_KEY_TYPE_DSA_KEY_PAIR),
+ * the `Dss-Params` format as defined by RFC 3279 &sect;2.3.2.
+ * ```
+ * Dss-Params ::= SEQUENCE {
+ * p INTEGER,
+ * q INTEGER,
+ * g INTEGER
+ * }
+ * ```
+ * - For Diffie-Hellman key exchange keys
+ * (#PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_FAMILY_CUSTOM) or
+ * #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_FAMILY_CUSTOM)), the
+ * `DomainParameters` format as defined by RFC 3279 &sect;2.3.3.
+ * ```
+ * DomainParameters ::= SEQUENCE {
+ * p INTEGER, -- odd prime, p=jq +1
+ * g INTEGER, -- generator, g
+ * q INTEGER, -- factor of p-1
+ * j INTEGER OPTIONAL, -- subgroup factor
+ * validationParams ValidationParams OPTIONAL
+ * }
+ * ValidationParams ::= SEQUENCE {
+ * seed BIT STRING,
+ * pgenCounter INTEGER
+ * }
+ * ```
+ *
+ * \note This function may allocate memory or other resources.
+ * Once you have called this function on an attribute structure,
+ * you must call psa_reset_key_attributes() to free these resources.
+ *
+ * \note This is an experimental extension to the interface. It may change
+ * in future versions of the library.
+ *
+ * \param[in,out] attributes Attribute structure where the specified domain
+ * parameters will be stored.
+ * If this function fails, the content of
+ * \p attributes is not modified.
+ * \param type Key type (a \c PSA_KEY_TYPE_XXX value).
+ * \param[in] data Buffer containing the key domain parameters.
+ * The content of this buffer is interpreted
+ * according to \p type as described above.
+ * \param data_length Size of the \p data buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_INVALID_ARGUMENT \emptydescription
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ */
+psa_status_t psa_set_key_domain_parameters(psa_key_attributes_t *attributes,
+ psa_key_type_t type,
+ const uint8_t *data,
+ size_t data_length);
+
+/**
+ * \brief Get domain parameters for a key.
+ *
+ * Get the domain parameters for a key with this function, if any. The format
+ * of the domain parameters written to \p data is specified in the
+ * documentation for psa_set_key_domain_parameters().
+ *
+ * \note This is an experimental extension to the interface. It may change
+ * in future versions of the library.
+ *
+ * \param[in] attributes The key attribute structure to query.
+ * \param[out] data On success, the key domain parameters.
+ * \param data_size Size of the \p data buffer in bytes.
+ * The buffer is guaranteed to be large
+ * enough if its size in bytes is at least
+ * the value given by
+ * PSA_KEY_DOMAIN_PARAMETERS_SIZE().
+ * \param[out] data_length On success, the number of bytes
+ * that make up the key domain parameters data.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL \emptydescription
+ */
+psa_status_t psa_get_key_domain_parameters(
+ const psa_key_attributes_t *attributes,
+ uint8_t *data,
+ size_t data_size,
+ size_t *data_length);
+
+/** Safe output buffer size for psa_get_key_domain_parameters().
+ *
+ * This macro returns a compile-time constant if its arguments are
+ * compile-time constants.
+ *
+ * \warning This function may call its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \note This is an experimental extension to the interface. It may change
+ * in future versions of the library.
+ *
+ * \param key_type A supported key type.
+ * \param key_bits The size of the key in bits.
+ *
+ * \return If the parameters are valid and supported, return
+ * a buffer size in bytes that guarantees that
+ * psa_get_key_domain_parameters() will not fail with
+ * #PSA_ERROR_BUFFER_TOO_SMALL.
+ * If the parameters are a valid combination that is not supported
+ * by the implementation, this macro shall return either a
+ * sensible size or 0.
+ * If the parameters are not valid, the
+ * return value is unspecified.
+ */
+#define PSA_KEY_DOMAIN_PARAMETERS_SIZE(key_type, key_bits) \
+ (PSA_KEY_TYPE_IS_RSA(key_type) ? sizeof(int) : \
+ PSA_KEY_TYPE_IS_DH(key_type) ? PSA_DH_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) : \
+ PSA_KEY_TYPE_IS_DSA(key_type) ? PSA_DSA_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) : \
+ 0)
+#define PSA_DH_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) \
+ (4 + (PSA_BITS_TO_BYTES(key_bits) + 5) * 3 /*without optional parts*/)
+#define PSA_DSA_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) \
+ (4 + (PSA_BITS_TO_BYTES(key_bits) + 5) * 2 /*p, g*/ + 34 /*q*/)
+
+/**@}*/
+
+/** \defgroup psa_tls_helpers TLS helper functions
+ * @{
+ */
+#if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY)
+#include <mbedtls/ecp.h>
+
+/** Convert an ECC curve identifier from the Mbed TLS encoding to PSA.
+ *
+ * \note This function is provided solely for the convenience of
+ * Mbed TLS and may be removed at any time without notice.
+ *
+ * \param grpid An Mbed TLS elliptic curve identifier
+ * (`MBEDTLS_ECP_DP_xxx`).
+ * \param[out] bits On success, the bit size of the curve.
+ *
+ * \return The corresponding PSA elliptic curve identifier
+ * (`PSA_ECC_FAMILY_xxx`).
+ * \return \c 0 on failure (\p grpid is not recognized).
+ */
+psa_ecc_family_t mbedtls_ecc_group_to_psa(mbedtls_ecp_group_id grpid,
+ size_t *bits);
+
+/** Convert an ECC curve identifier from the PSA encoding to Mbed TLS.
+ *
+ * \note This function is provided solely for the convenience of
+ * Mbed TLS and may be removed at any time without notice.
+ *
+ * \param curve A PSA elliptic curve identifier
+ * (`PSA_ECC_FAMILY_xxx`).
+ * \param bits The bit-length of a private key on \p curve.
+ * \param bits_is_sloppy If true, \p bits may be the bit-length rounded up
+ * to the nearest multiple of 8. This allows the caller
+ * to infer the exact curve from the length of a key
+ * which is supplied as a byte string.
+ *
+ * \return The corresponding Mbed TLS elliptic curve identifier
+ * (`MBEDTLS_ECP_DP_xxx`).
+ * \return #MBEDTLS_ECP_DP_NONE if \c curve is not recognized.
+ * \return #MBEDTLS_ECP_DP_NONE if \p bits is not
+ * correct for \p curve.
+ */
+mbedtls_ecp_group_id mbedtls_ecc_group_of_psa(psa_ecc_family_t curve,
+ size_t bits,
+ int bits_is_sloppy);
+#endif /* PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY */
+
+/**@}*/
+
+/** \defgroup psa_external_rng External random generator
+ * @{
+ */
+
+#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
+/** External random generator function, implemented by the platform.
+ *
+ * When the compile-time option #MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG is enabled,
+ * this function replaces Mbed TLS's entropy and DRBG modules for all
+ * random generation triggered via PSA crypto interfaces.
+ *
+ * \note This random generator must deliver random numbers with cryptographic
+ * quality and high performance. It must supply unpredictable numbers
+ * with a uniform distribution. The implementation of this function
+ * is responsible for ensuring that the random generator is seeded
+ * with sufficient entropy. If you have a hardware TRNG which is slow
+ * or delivers non-uniform output, declare it as an entropy source
+ * with mbedtls_entropy_add_source() instead of enabling this option.
+ *
+ * \param[in,out] context Pointer to the random generator context.
+ * This is all-bits-zero on the first call
+ * and preserved between successive calls.
+ * \param[out] output Output buffer. On success, this buffer
+ * contains random data with a uniform
+ * distribution.
+ * \param output_size The size of the \p output buffer in bytes.
+ * \param[out] output_length On success, set this value to \p output_size.
+ *
+ * \retval #PSA_SUCCESS
+ * Success. The output buffer contains \p output_size bytes of
+ * cryptographic-quality random data, and \c *output_length is
+ * set to \p output_size.
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY
+ * The random generator requires extra entropy and there is no
+ * way to obtain entropy under current environment conditions.
+ * This error should not happen under normal circumstances since
+ * this function is responsible for obtaining as much entropy as
+ * it needs. However implementations of this function may return
+ * #PSA_ERROR_INSUFFICIENT_ENTROPY if there is no way to obtain
+ * entropy without blocking indefinitely.
+ * \retval #PSA_ERROR_HARDWARE_FAILURE
+ * A failure of the random generator hardware that isn't covered
+ * by #PSA_ERROR_INSUFFICIENT_ENTROPY.
+ */
+psa_status_t mbedtls_psa_external_get_random(
+ mbedtls_psa_external_random_context_t *context,
+ uint8_t *output, size_t output_size, size_t *output_length);
+#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
+
+/**@}*/
+
+/** \defgroup psa_builtin_keys Built-in keys
+ * @{
+ */
+
+/** The minimum value for a key identifier that is built into the
+ * implementation.
+ *
+ * The range of key identifiers from #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN
+ * to #MBEDTLS_PSA_KEY_ID_BUILTIN_MAX within the range from
+ * #PSA_KEY_ID_VENDOR_MIN and #PSA_KEY_ID_VENDOR_MAX and must not intersect
+ * with any other set of implementation-chosen key identifiers.
+ *
+ * This value is part of the library's ABI since changing it would invalidate
+ * the values of built-in key identifiers in applications.
+ */
+#define MBEDTLS_PSA_KEY_ID_BUILTIN_MIN ((psa_key_id_t) 0x7fff0000)
+
+/** The maximum value for a key identifier that is built into the
+ * implementation.
+ *
+ * See #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN for more information.
+ */
+#define MBEDTLS_PSA_KEY_ID_BUILTIN_MAX ((psa_key_id_t) 0x7fffefff)
+
+/** A slot number identifying a key in a driver.
+ *
+ * Values of this type are used to identify built-in keys.
+ */
+typedef uint64_t psa_drv_slot_number_t;
+
+#if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS)
+/** Test whether a key identifier belongs to the builtin key range.
+ *
+ * \param key_id Key identifier to test.
+ *
+ * \retval 1
+ * The key identifier is a builtin key identifier.
+ * \retval 0
+ * The key identifier is not a builtin key identifier.
+ */
+static inline int psa_key_id_is_builtin(psa_key_id_t key_id)
+{
+ return (key_id >= MBEDTLS_PSA_KEY_ID_BUILTIN_MIN) &&
+ (key_id <= MBEDTLS_PSA_KEY_ID_BUILTIN_MAX);
+}
+
+/** Platform function to obtain the location and slot number of a built-in key.
+ *
+ * An application-specific implementation of this function must be provided if
+ * #MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS is enabled. This would typically be provided
+ * as part of a platform's system image.
+ *
+ * #MBEDTLS_SVC_KEY_ID_GET_KEY_ID(\p key_id) needs to be in the range from
+ * #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN to #MBEDTLS_PSA_KEY_ID_BUILTIN_MAX.
+ *
+ * In a multi-application configuration
+ * (\c MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER is defined),
+ * this function should check that #MBEDTLS_SVC_KEY_ID_GET_OWNER_ID(\p key_id)
+ * is allowed to use the given key.
+ *
+ * \param key_id The key ID for which to retrieve the
+ * location and slot attributes.
+ * \param[out] lifetime On success, the lifetime associated with the key
+ * corresponding to \p key_id. Lifetime is a
+ * combination of which driver contains the key,
+ * and with what persistence level the key is
+ * intended to be used. If the platform
+ * implementation does not contain specific
+ * information about the intended key persistence
+ * level, the persistence level may be reported as
+ * #PSA_KEY_PERSISTENCE_DEFAULT.
+ * \param[out] slot_number On success, the slot number known to the driver
+ * registered at the lifetime location reported
+ * through \p lifetime which corresponds to the
+ * requested built-in key.
+ *
+ * \retval #PSA_SUCCESS
+ * The requested key identifier designates a built-in key.
+ * In a multi-application configuration, the requested owner
+ * is allowed to access it.
+ * \retval #PSA_ERROR_DOES_NOT_EXIST
+ * The requested key identifier is not a built-in key which is known
+ * to this function. If a key exists in the key storage with this
+ * identifier, the data from the storage will be used.
+ * \return (any other error)
+ * Any other error is propagated to the function that requested the key.
+ * Common errors include:
+ * - #PSA_ERROR_NOT_PERMITTED: the key exists but the requested owner
+ * is not allowed to access it.
+ */
+psa_status_t mbedtls_psa_platform_get_builtin_key(
+ mbedtls_svc_key_id_t key_id,
+ psa_key_lifetime_t *lifetime,
+ psa_drv_slot_number_t *slot_number);
+#endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */
+
+/** @} */
+
+/** \addtogroup crypto_types
+ * @{
+ */
+
+#define PSA_ALG_CATEGORY_PAKE ((psa_algorithm_t) 0x0a000000)
+
+/** Whether the specified algorithm is a password-authenticated key exchange.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a password-authenticated key exchange (PAKE)
+ * algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_PAKE(alg) \
+ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_PAKE)
+
+/** The Password-authenticated key exchange by juggling (J-PAKE) algorithm.
+ *
+ * This is J-PAKE as defined by RFC 8236, instantiated with the following
+ * parameters:
+ *
+ * - The group can be either an elliptic curve or defined over a finite field.
+ * - Schnorr NIZK proof as defined by RFC 8235 and using the same group as the
+ * J-PAKE algorithm.
+ * - A cryptographic hash function.
+ *
+ * To select these parameters and set up the cipher suite, call these functions
+ * in any order:
+ *
+ * \code
+ * psa_pake_cs_set_algorithm(cipher_suite, PSA_ALG_JPAKE);
+ * psa_pake_cs_set_primitive(cipher_suite,
+ * PSA_PAKE_PRIMITIVE(type, family, bits));
+ * psa_pake_cs_set_hash(cipher_suite, hash);
+ * \endcode
+ *
+ * For more information on how to set a specific curve or field, refer to the
+ * documentation of the individual \c PSA_PAKE_PRIMITIVE_TYPE_XXX constants.
+ *
+ * After initializing a J-PAKE operation, call
+ *
+ * \code
+ * psa_pake_setup(operation, cipher_suite);
+ * psa_pake_set_user(operation, ...);
+ * psa_pake_set_peer(operation, ...);
+ * psa_pake_set_password_key(operation, ...);
+ * \endcode
+ *
+ * The password is provided as a key. This can be the password text itself,
+ * in an agreed character encoding, or some value derived from the password
+ * as required by a higher level protocol.
+ *
+ * (The implementation converts the key material to a number as described in
+ * Section 2.3.8 of _SEC 1: Elliptic Curve Cryptography_
+ * (https://www.secg.org/sec1-v2.pdf), before reducing it modulo \c q. Here
+ * \c q is order of the group defined by the primitive set in the cipher suite.
+ * The \c psa_pake_set_password_key() function returns an error if the result
+ * of the reduction is 0.)
+ *
+ * The key exchange flow for J-PAKE is as follows:
+ * -# To get the first round data that needs to be sent to the peer, call
+ * \code
+ * // Get g1
+ * psa_pake_output(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
+ * // Get the ZKP public key for x1
+ * psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
+ * // Get the ZKP proof for x1
+ * psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
+ * // Get g2
+ * psa_pake_output(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
+ * // Get the ZKP public key for x2
+ * psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
+ * // Get the ZKP proof for x2
+ * psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
+ * \endcode
+ * -# To provide the first round data received from the peer to the operation,
+ * call
+ * \code
+ * // Set g3
+ * psa_pake_input(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
+ * // Set the ZKP public key for x3
+ * psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
+ * // Set the ZKP proof for x3
+ * psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
+ * // Set g4
+ * psa_pake_input(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
+ * // Set the ZKP public key for x4
+ * psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
+ * // Set the ZKP proof for x4
+ * psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
+ * \endcode
+ * -# To get the second round data that needs to be sent to the peer, call
+ * \code
+ * // Get A
+ * psa_pake_output(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
+ * // Get ZKP public key for x2*s
+ * psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
+ * // Get ZKP proof for x2*s
+ * psa_pake_output(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
+ * \endcode
+ * -# To provide the second round data received from the peer to the operation,
+ * call
+ * \code
+ * // Set B
+ * psa_pake_input(operation, #PSA_PAKE_STEP_KEY_SHARE, ...);
+ * // Set ZKP public key for x4*s
+ * psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PUBLIC, ...);
+ * // Set ZKP proof for x4*s
+ * psa_pake_input(operation, #PSA_PAKE_STEP_ZK_PROOF, ...);
+ * \endcode
+ * -# To access the shared secret call
+ * \code
+ * // Get Ka=Kb=K
+ * psa_pake_get_implicit_key()
+ * \endcode
+ *
+ * For more information consult the documentation of the individual
+ * \c PSA_PAKE_STEP_XXX constants.
+ *
+ * At this point there is a cryptographic guarantee that only the authenticated
+ * party who used the same password is able to compute the key. But there is no
+ * guarantee that the peer is the party it claims to be and was able to do so.
+ *
+ * That is, the authentication is only implicit (the peer is not authenticated
+ * at this point, and no action should be taken that assume that they are - like
+ * for example accessing restricted files).
+ *
+ * To make the authentication explicit there are various methods, see Section 5
+ * of RFC 8236 for two examples.
+ *
+ */
+#define PSA_ALG_JPAKE ((psa_algorithm_t) 0x0a000100)
+
+/** @} */
+
+/** \defgroup pake Password-authenticated key exchange (PAKE)
+ *
+ * This is a proposed PAKE interface for the PSA Crypto API. It is not part of
+ * the official PSA Crypto API yet.
+ *
+ * \note The content of this section is not part of the stable API and ABI
+ * of Mbed TLS and may change arbitrarily from version to version.
+ * Same holds for the corresponding macros #PSA_ALG_CATEGORY_PAKE and
+ * #PSA_ALG_JPAKE.
+ * @{
+ */
+
+/** \brief Encoding of the application role of PAKE
+ *
+ * Encodes the application's role in the algorithm is being executed. For more
+ * information see the documentation of individual \c PSA_PAKE_ROLE_XXX
+ * constants.
+ */
+typedef uint8_t psa_pake_role_t;
+
+/** Encoding of input and output indicators for PAKE.
+ *
+ * Some PAKE algorithms need to exchange more data than just a single key share.
+ * This type is for encoding additional input and output data for such
+ * algorithms.
+ */
+typedef uint8_t psa_pake_step_t;
+
+/** Encoding of the type of the PAKE's primitive.
+ *
+ * Values defined by this standard will never be in the range 0x80-0xff.
+ * Vendors who define additional types must use an encoding in this range.
+ *
+ * For more information see the documentation of individual
+ * \c PSA_PAKE_PRIMITIVE_TYPE_XXX constants.
+ */
+typedef uint8_t psa_pake_primitive_type_t;
+
+/** \brief Encoding of the family of the primitive associated with the PAKE.
+ *
+ * For more information see the documentation of individual
+ * \c PSA_PAKE_PRIMITIVE_TYPE_XXX constants.
+ */
+typedef uint8_t psa_pake_family_t;
+
+/** \brief Encoding of the primitive associated with the PAKE.
+ *
+ * For more information see the documentation of the #PSA_PAKE_PRIMITIVE macro.
+ */
+typedef uint32_t psa_pake_primitive_t;
+
+/** A value to indicate no role in a PAKE algorithm.
+ * This value can be used in a call to psa_pake_set_role() for symmetric PAKE
+ * algorithms which do not assign roles.
+ */
+#define PSA_PAKE_ROLE_NONE ((psa_pake_role_t) 0x00)
+
+/** The first peer in a balanced PAKE.
+ *
+ * Although balanced PAKE algorithms are symmetric, some of them needs an
+ * ordering of peers for the transcript calculations. If the algorithm does not
+ * need this, both #PSA_PAKE_ROLE_FIRST and #PSA_PAKE_ROLE_SECOND are
+ * accepted.
+ */
+#define PSA_PAKE_ROLE_FIRST ((psa_pake_role_t) 0x01)
+
+/** The second peer in a balanced PAKE.
+ *
+ * Although balanced PAKE algorithms are symmetric, some of them needs an
+ * ordering of peers for the transcript calculations. If the algorithm does not
+ * need this, either #PSA_PAKE_ROLE_FIRST or #PSA_PAKE_ROLE_SECOND are
+ * accepted.
+ */
+#define PSA_PAKE_ROLE_SECOND ((psa_pake_role_t) 0x02)
+
+/** The client in an augmented PAKE.
+ *
+ * Augmented PAKE algorithms need to differentiate between client and server.
+ */
+#define PSA_PAKE_ROLE_CLIENT ((psa_pake_role_t) 0x11)
+
+/** The server in an augmented PAKE.
+ *
+ * Augmented PAKE algorithms need to differentiate between client and server.
+ */
+#define PSA_PAKE_ROLE_SERVER ((psa_pake_role_t) 0x12)
+
+/** The PAKE primitive type indicating the use of elliptic curves.
+ *
+ * The values of the \c family and \c bits fields of the cipher suite identify a
+ * specific elliptic curve, using the same mapping that is used for ECC
+ * (::psa_ecc_family_t) keys.
+ *
+ * (Here \c family means the value returned by psa_pake_cs_get_family() and
+ * \c bits means the value returned by psa_pake_cs_get_bits().)
+ *
+ * Input and output during the operation can involve group elements and scalar
+ * values:
+ * -# The format for group elements is the same as for public keys on the
+ * specific curve would be. For more information, consult the documentation of
+ * psa_export_public_key().
+ * -# The format for scalars is the same as for private keys on the specific
+ * curve would be. For more information, consult the documentation of
+ * psa_export_key().
+ */
+#define PSA_PAKE_PRIMITIVE_TYPE_ECC ((psa_pake_primitive_type_t) 0x01)
+
+/** The PAKE primitive type indicating the use of Diffie-Hellman groups.
+ *
+ * The values of the \c family and \c bits fields of the cipher suite identify
+ * a specific Diffie-Hellman group, using the same mapping that is used for
+ * Diffie-Hellman (::psa_dh_family_t) keys.
+ *
+ * (Here \c family means the value returned by psa_pake_cs_get_family() and
+ * \c bits means the value returned by psa_pake_cs_get_bits().)
+ *
+ * Input and output during the operation can involve group elements and scalar
+ * values:
+ * -# The format for group elements is the same as for public keys on the
+ * specific group would be. For more information, consult the documentation of
+ * psa_export_public_key().
+ * -# The format for scalars is the same as for private keys on the specific
+ * group would be. For more information, consult the documentation of
+ * psa_export_key().
+ */
+#define PSA_PAKE_PRIMITIVE_TYPE_DH ((psa_pake_primitive_type_t) 0x02)
+
+/** Construct a PAKE primitive from type, family and bit-size.
+ *
+ * \param pake_type The type of the primitive
+ * (value of type ::psa_pake_primitive_type_t).
+ * \param pake_family The family of the primitive
+ * (the type and interpretation of this parameter depends
+ * on \p pake_type, for more information consult the
+ * documentation of individual ::psa_pake_primitive_type_t
+ * constants).
+ * \param pake_bits The bit-size of the primitive
+ * (Value of type \c size_t. The interpretation
+ * of this parameter depends on \p pake_family, for more
+ * information consult the documentation of individual
+ * ::psa_pake_primitive_type_t constants).
+ *
+ * \return The constructed primitive value of type ::psa_pake_primitive_t.
+ * Return 0 if the requested primitive can't be encoded as
+ * ::psa_pake_primitive_t.
+ */
+#define PSA_PAKE_PRIMITIVE(pake_type, pake_family, pake_bits) \
+ ((pake_bits & 0xFFFF) != pake_bits) ? 0 : \
+ ((psa_pake_primitive_t) (((pake_type) << 24 | \
+ (pake_family) << 16) | (pake_bits)))
+
+/** The key share being sent to or received from the peer.
+ *
+ * The format for both input and output at this step is the same as for public
+ * keys on the group determined by the primitive (::psa_pake_primitive_t) would
+ * be.
+ *
+ * For more information on the format, consult the documentation of
+ * psa_export_public_key().
+ *
+ * For information regarding how the group is determined, consult the
+ * documentation #PSA_PAKE_PRIMITIVE.
+ */
+#define PSA_PAKE_STEP_KEY_SHARE ((psa_pake_step_t) 0x01)
+
+/** A Schnorr NIZKP public key.
+ *
+ * This is the ephemeral public key in the Schnorr Non-Interactive
+ * Zero-Knowledge Proof (the value denoted by the letter 'V' in RFC 8235).
+ *
+ * The format for both input and output at this step is the same as for public
+ * keys on the group determined by the primitive (::psa_pake_primitive_t) would
+ * be.
+ *
+ * For more information on the format, consult the documentation of
+ * psa_export_public_key().
+ *
+ * For information regarding how the group is determined, consult the
+ * documentation #PSA_PAKE_PRIMITIVE.
+ */
+#define PSA_PAKE_STEP_ZK_PUBLIC ((psa_pake_step_t) 0x02)
+
+/** A Schnorr NIZKP proof.
+ *
+ * This is the proof in the Schnorr Non-Interactive Zero-Knowledge Proof (the
+ * value denoted by the letter 'r' in RFC 8235).
+ *
+ * Both for input and output, the value at this step is an integer less than
+ * the order of the group selected in the cipher suite. The format depends on
+ * the group as well:
+ *
+ * - For Montgomery curves, the encoding is little endian.
+ * - For everything else the encoding is big endian (see Section 2.3.8 of
+ * _SEC 1: Elliptic Curve Cryptography_ at https://www.secg.org/sec1-v2.pdf).
+ *
+ * In both cases leading zeroes are allowed as long as the length in bytes does
+ * not exceed the byte length of the group order.
+ *
+ * For information regarding how the group is determined, consult the
+ * documentation #PSA_PAKE_PRIMITIVE.
+ */
+#define PSA_PAKE_STEP_ZK_PROOF ((psa_pake_step_t) 0x03)
+
+/** The type of the data structure for PAKE cipher suites.
+ *
+ * This is an implementation-defined \c struct. Applications should not
+ * make any assumptions about the content of this structure.
+ * Implementation details can change in future versions without notice.
+ */
+typedef struct psa_pake_cipher_suite_s psa_pake_cipher_suite_t;
+
+/** Return an initial value for a PAKE cipher suite object.
+ */
+static psa_pake_cipher_suite_t psa_pake_cipher_suite_init(void);
+
+/** Retrieve the PAKE algorithm from a PAKE cipher suite.
+ *
+ * \param[in] cipher_suite The cipher suite structure to query.
+ *
+ * \return The PAKE algorithm stored in the cipher suite structure.
+ */
+static psa_algorithm_t psa_pake_cs_get_algorithm(
+ const psa_pake_cipher_suite_t *cipher_suite);
+
+/** Declare the PAKE algorithm for the cipher suite.
+ *
+ * This function overwrites any PAKE algorithm
+ * previously set in \p cipher_suite.
+ *
+ * \param[out] cipher_suite The cipher suite structure to write to.
+ * \param algorithm The PAKE algorithm to write.
+ * (`PSA_ALG_XXX` values of type ::psa_algorithm_t
+ * such that #PSA_ALG_IS_PAKE(\c alg) is true.)
+ * If this is 0, the PAKE algorithm in
+ * \p cipher_suite becomes unspecified.
+ */
+static void psa_pake_cs_set_algorithm(psa_pake_cipher_suite_t *cipher_suite,
+ psa_algorithm_t algorithm);
+
+/** Retrieve the primitive from a PAKE cipher suite.
+ *
+ * \param[in] cipher_suite The cipher suite structure to query.
+ *
+ * \return The primitive stored in the cipher suite structure.
+ */
+static psa_pake_primitive_t psa_pake_cs_get_primitive(
+ const psa_pake_cipher_suite_t *cipher_suite);
+
+/** Declare the primitive for a PAKE cipher suite.
+ *
+ * This function overwrites any primitive previously set in \p cipher_suite.
+ *
+ * \param[out] cipher_suite The cipher suite structure to write to.
+ * \param primitive The primitive to write. If this is 0, the
+ * primitive type in \p cipher_suite becomes
+ * unspecified.
+ */
+static void psa_pake_cs_set_primitive(psa_pake_cipher_suite_t *cipher_suite,
+ psa_pake_primitive_t primitive);
+
+/** Retrieve the PAKE family from a PAKE cipher suite.
+ *
+ * \param[in] cipher_suite The cipher suite structure to query.
+ *
+ * \return The PAKE family stored in the cipher suite structure.
+ */
+static psa_pake_family_t psa_pake_cs_get_family(
+ const psa_pake_cipher_suite_t *cipher_suite);
+
+/** Retrieve the PAKE primitive bit-size from a PAKE cipher suite.
+ *
+ * \param[in] cipher_suite The cipher suite structure to query.
+ *
+ * \return The PAKE primitive bit-size stored in the cipher suite structure.
+ */
+static uint16_t psa_pake_cs_get_bits(
+ const psa_pake_cipher_suite_t *cipher_suite);
+
+/** Retrieve the hash algorithm from a PAKE cipher suite.
+ *
+ * \param[in] cipher_suite The cipher suite structure to query.
+ *
+ * \return The hash algorithm stored in the cipher suite structure. The return
+ * value is 0 if the PAKE is not parametrised by a hash algorithm or if
+ * the hash algorithm is not set.
+ */
+static psa_algorithm_t psa_pake_cs_get_hash(
+ const psa_pake_cipher_suite_t *cipher_suite);
+
+/** Declare the hash algorithm for a PAKE cipher suite.
+ *
+ * This function overwrites any hash algorithm
+ * previously set in \p cipher_suite.
+ *
+ * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
+ * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
+ * for more information.
+ *
+ * \param[out] cipher_suite The cipher suite structure to write to.
+ * \param hash The hash involved in the cipher suite.
+ * (`PSA_ALG_XXX` values of type ::psa_algorithm_t
+ * such that #PSA_ALG_IS_HASH(\c alg) is true.)
+ * If this is 0, the hash algorithm in
+ * \p cipher_suite becomes unspecified.
+ */
+static void psa_pake_cs_set_hash(psa_pake_cipher_suite_t *cipher_suite,
+ psa_algorithm_t hash);
+
+/** The type of the state data structure for PAKE operations.
+ *
+ * Before calling any function on a PAKE operation object, the application
+ * must initialize it by any of the following means:
+ * - Set the structure to all-bits-zero, for example:
+ * \code
+ * psa_pake_operation_t operation;
+ * memset(&operation, 0, sizeof(operation));
+ * \endcode
+ * - Initialize the structure to logical zero values, for example:
+ * \code
+ * psa_pake_operation_t operation = {0};
+ * \endcode
+ * - Initialize the structure to the initializer #PSA_PAKE_OPERATION_INIT,
+ * for example:
+ * \code
+ * psa_pake_operation_t operation = PSA_PAKE_OPERATION_INIT;
+ * \endcode
+ * - Assign the result of the function psa_pake_operation_init()
+ * to the structure, for example:
+ * \code
+ * psa_pake_operation_t operation;
+ * operation = psa_pake_operation_init();
+ * \endcode
+ *
+ * This is an implementation-defined \c struct. Applications should not
+ * make any assumptions about the content of this structure.
+ * Implementation details can change in future versions without notice. */
+typedef struct psa_pake_operation_s psa_pake_operation_t;
+
+/** The type of input values for PAKE operations. */
+typedef struct psa_crypto_driver_pake_inputs_s psa_crypto_driver_pake_inputs_t;
+
+/** The type of computation stage for J-PAKE operations. */
+typedef struct psa_jpake_computation_stage_s psa_jpake_computation_stage_t;
+
+/** Return an initial value for a PAKE operation object.
+ */
+static psa_pake_operation_t psa_pake_operation_init(void);
+
+/** Get the length of the password in bytes from given inputs.
+ *
+ * \param[in] inputs Operation inputs.
+ * \param[out] password_len Password length.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BAD_STATE
+ * Password hasn't been set yet.
+ */
+psa_status_t psa_crypto_driver_pake_get_password_len(
+ const psa_crypto_driver_pake_inputs_t *inputs,
+ size_t *password_len);
+
+/** Get the password from given inputs.
+ *
+ * \param[in] inputs Operation inputs.
+ * \param[out] buffer Return buffer for password.
+ * \param buffer_size Size of the return buffer in bytes.
+ * \param[out] buffer_length Actual size of the password in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BAD_STATE
+ * Password hasn't been set yet.
+ */
+psa_status_t psa_crypto_driver_pake_get_password(
+ const psa_crypto_driver_pake_inputs_t *inputs,
+ uint8_t *buffer, size_t buffer_size, size_t *buffer_length);
+
+/** Get the length of the user id in bytes from given inputs.
+ *
+ * \param[in] inputs Operation inputs.
+ * \param[out] user_len User id length.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BAD_STATE
+ * User id hasn't been set yet.
+ */
+psa_status_t psa_crypto_driver_pake_get_user_len(
+ const psa_crypto_driver_pake_inputs_t *inputs,
+ size_t *user_len);
+
+/** Get the length of the peer id in bytes from given inputs.
+ *
+ * \param[in] inputs Operation inputs.
+ * \param[out] peer_len Peer id length.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BAD_STATE
+ * Peer id hasn't been set yet.
+ */
+psa_status_t psa_crypto_driver_pake_get_peer_len(
+ const psa_crypto_driver_pake_inputs_t *inputs,
+ size_t *peer_len);
+
+/** Get the user id from given inputs.
+ *
+ * \param[in] inputs Operation inputs.
+ * \param[out] user_id User id.
+ * \param user_id_size Size of \p user_id in bytes.
+ * \param[out] user_id_len Size of the user id in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BAD_STATE
+ * User id hasn't been set yet.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p user_id is too small.
+ */
+psa_status_t psa_crypto_driver_pake_get_user(
+ const psa_crypto_driver_pake_inputs_t *inputs,
+ uint8_t *user_id, size_t user_id_size, size_t *user_id_len);
+
+/** Get the peer id from given inputs.
+ *
+ * \param[in] inputs Operation inputs.
+ * \param[out] peer_id Peer id.
+ * \param peer_id_size Size of \p peer_id in bytes.
+ * \param[out] peer_id_length Size of the peer id in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BAD_STATE
+ * Peer id hasn't been set yet.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p peer_id is too small.
+ */
+psa_status_t psa_crypto_driver_pake_get_peer(
+ const psa_crypto_driver_pake_inputs_t *inputs,
+ uint8_t *peer_id, size_t peer_id_size, size_t *peer_id_length);
+
+/** Get the cipher suite from given inputs.
+ *
+ * \param[in] inputs Operation inputs.
+ * \param[out] cipher_suite Return buffer for role.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BAD_STATE
+ * Cipher_suite hasn't been set yet.
+ */
+psa_status_t psa_crypto_driver_pake_get_cipher_suite(
+ const psa_crypto_driver_pake_inputs_t *inputs,
+ psa_pake_cipher_suite_t *cipher_suite);
+
+/** Set the session information for a password-authenticated key exchange.
+ *
+ * The sequence of operations to set up a password-authenticated key exchange
+ * is as follows:
+ * -# Allocate an operation object which will be passed to all the functions
+ * listed here.
+ * -# Initialize the operation object with one of the methods described in the
+ * documentation for #psa_pake_operation_t, e.g.
+ * #PSA_PAKE_OPERATION_INIT.
+ * -# Call psa_pake_setup() to specify the cipher suite.
+ * -# Call \c psa_pake_set_xxx() functions on the operation to complete the
+ * setup. The exact sequence of \c psa_pake_set_xxx() functions that needs
+ * to be called depends on the algorithm in use.
+ *
+ * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
+ * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
+ * for more information.
+ *
+ * A typical sequence of calls to perform a password-authenticated key
+ * exchange:
+ * -# Call psa_pake_output(operation, #PSA_PAKE_STEP_KEY_SHARE, ...) to get the
+ * key share that needs to be sent to the peer.
+ * -# Call psa_pake_input(operation, #PSA_PAKE_STEP_KEY_SHARE, ...) to provide
+ * the key share that was received from the peer.
+ * -# Depending on the algorithm additional calls to psa_pake_output() and
+ * psa_pake_input() might be necessary.
+ * -# Call psa_pake_get_implicit_key() for accessing the shared secret.
+ *
+ * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
+ * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
+ * for more information.
+ *
+ * If an error occurs at any step after a call to psa_pake_setup(),
+ * the operation will need to be reset by a call to psa_pake_abort(). The
+ * application may call psa_pake_abort() at any time after the operation
+ * has been initialized.
+ *
+ * After a successful call to psa_pake_setup(), the application must
+ * eventually terminate the operation. The following events terminate an
+ * operation:
+ * - A call to psa_pake_abort().
+ * - A successful call to psa_pake_get_implicit_key().
+ *
+ * \param[in,out] operation The operation object to set up. It must have
+ * been initialized but not set up yet.
+ * \param[in] cipher_suite The cipher suite to use. (A cipher suite fully
+ * characterizes a PAKE algorithm and determines
+ * the algorithm as well.)
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The algorithm in \p cipher_suite is not a PAKE algorithm, or the
+ * PAKE primitive in \p cipher_suite is not compatible with the
+ * PAKE algorithm, or the hash algorithm in \p cipher_suite is invalid
+ * or not compatible with the PAKE algorithm and primitive.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * The algorithm in \p cipher_suite is not a supported PAKE algorithm,
+ * or the PAKE primitive in \p cipher_suite is not supported or not
+ * compatible with the PAKE algorithm, or the hash algorithm in
+ * \p cipher_suite is not supported or not compatible with the PAKE
+ * algorithm and primitive.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid, or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_pake_setup(psa_pake_operation_t *operation,
+ const psa_pake_cipher_suite_t *cipher_suite);
+
+/** Set the password for a password-authenticated key exchange from key ID.
+ *
+ * Call this function when the password, or a value derived from the password,
+ * is already present in the key store.
+ *
+ * \param[in,out] operation The operation object to set the password for. It
+ * must have been set up by psa_pake_setup() and
+ * not yet in use (neither psa_pake_output() nor
+ * psa_pake_input() has been called yet). It must
+ * be on operation for which the password hasn't
+ * been set yet (psa_pake_set_password_key()
+ * hasn't been called yet).
+ * \param password Identifier of the key holding the password or a
+ * value derived from the password (eg. by a
+ * memory-hard function). It must remain valid
+ * until the operation terminates. It must be of
+ * type #PSA_KEY_TYPE_PASSWORD or
+ * #PSA_KEY_TYPE_PASSWORD_HASH. It has to allow
+ * the usage #PSA_KEY_USAGE_DERIVE.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_HANDLE
+ * \p password is not a valid key identifier.
+ * \retval #PSA_ERROR_NOT_PERMITTED
+ * The key does not have the #PSA_KEY_USAGE_DERIVE flag, or it does not
+ * permit the \p operation's algorithm.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The key type for \p password is not #PSA_KEY_TYPE_PASSWORD or
+ * #PSA_KEY_TYPE_PASSWORD_HASH, or \p password is not compatible with
+ * the \p operation's cipher suite.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * The key type or key size of \p password is not supported with the
+ * \p operation's cipher suite.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must have been set up.), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_pake_set_password_key(psa_pake_operation_t *operation,
+ mbedtls_svc_key_id_t password);
+
+/** Set the user ID for a password-authenticated key exchange.
+ *
+ * Call this function to set the user ID. For PAKE algorithms that associate a
+ * user identifier with each side of the session you need to call
+ * psa_pake_set_peer() as well. For PAKE algorithms that associate a single
+ * user identifier with the session, call psa_pake_set_user() only.
+ *
+ * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
+ * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
+ * for more information.
+ *
+ * \param[in,out] operation The operation object to set the user ID for. It
+ * must have been set up by psa_pake_setup() and
+ * not yet in use (neither psa_pake_output() nor
+ * psa_pake_input() has been called yet). It must
+ * be on operation for which the user ID hasn't
+ * been set (psa_pake_set_user() hasn't been
+ * called yet).
+ * \param[in] user_id The user ID to authenticate with.
+ * \param user_id_len Size of the \p user_id buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p user_id is not valid for the \p operation's algorithm and cipher
+ * suite.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * The value of \p user_id is not supported by the implementation.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid, or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_pake_set_user(psa_pake_operation_t *operation,
+ const uint8_t *user_id,
+ size_t user_id_len);
+
+/** Set the peer ID for a password-authenticated key exchange.
+ *
+ * Call this function in addition to psa_pake_set_user() for PAKE algorithms
+ * that associate a user identifier with each side of the session. For PAKE
+ * algorithms that associate a single user identifier with the session, call
+ * psa_pake_set_user() only.
+ *
+ * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
+ * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
+ * for more information.
+ *
+ * \param[in,out] operation The operation object to set the peer ID for. It
+ * must have been set up by psa_pake_setup() and
+ * not yet in use (neither psa_pake_output() nor
+ * psa_pake_input() has been called yet). It must
+ * be on operation for which the peer ID hasn't
+ * been set (psa_pake_set_peer() hasn't been
+ * called yet).
+ * \param[in] peer_id The peer's ID to authenticate.
+ * \param peer_id_len Size of the \p peer_id buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p peer_id is not valid for the \p operation's algorithm and cipher
+ * suite.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * The algorithm doesn't associate a second identity with the session.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * Calling psa_pake_set_peer() is invalid with the \p operation's
+ * algorithm, the operation state is not valid, or the library has not
+ * been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_pake_set_peer(psa_pake_operation_t *operation,
+ const uint8_t *peer_id,
+ size_t peer_id_len);
+
+/** Set the application role for a password-authenticated key exchange.
+ *
+ * Not all PAKE algorithms need to differentiate the communicating entities.
+ * It is optional to call this function for PAKEs that don't require a role
+ * to be specified. For such PAKEs the application role parameter is ignored,
+ * or #PSA_PAKE_ROLE_NONE can be passed as \c role.
+ *
+ * Refer to the documentation of individual PAKE algorithm types (`PSA_ALG_XXX`
+ * values of type ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true)
+ * for more information.
+ *
+ * \param[in,out] operation The operation object to specify the
+ * application's role for. It must have been set up
+ * by psa_pake_setup() and not yet in use (neither
+ * psa_pake_output() nor psa_pake_input() has been
+ * called yet). It must be on operation for which
+ * the application's role hasn't been specified
+ * (psa_pake_set_role() hasn't been called yet).
+ * \param role A value of type ::psa_pake_role_t indicating the
+ * application's role in the PAKE the algorithm
+ * that is being set up. For more information see
+ * the documentation of \c PSA_PAKE_ROLE_XXX
+ * constants.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The \p role is not a valid PAKE role in the \p operation’s algorithm.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * The \p role for this algorithm is not supported or is not valid.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid, or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_pake_set_role(psa_pake_operation_t *operation,
+ psa_pake_role_t role);
+
+/** Get output for a step of a password-authenticated key exchange.
+ *
+ * Depending on the algorithm being executed, you might need to call this
+ * function several times or you might not need to call this at all.
+ *
+ * The exact sequence of calls to perform a password-authenticated key
+ * exchange depends on the algorithm in use. Refer to the documentation of
+ * individual PAKE algorithm types (`PSA_ALG_XXX` values of type
+ * ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true) for more
+ * information.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_pake_abort().
+ *
+ * \param[in,out] operation Active PAKE operation.
+ * \param step The step of the algorithm for which the output is
+ * requested.
+ * \param[out] output Buffer where the output is to be written in the
+ * format appropriate for this \p step. Refer to
+ * the documentation of the individual
+ * \c PSA_PAKE_STEP_XXX constants for more
+ * information.
+ * \param output_size Size of the \p output buffer in bytes. This must
+ * be at least #PSA_PAKE_OUTPUT_SIZE(\c alg, \c
+ * primitive, \p output_step) where \c alg and
+ * \p primitive are the PAKE algorithm and primitive
+ * in the operation's cipher suite, and \p step is
+ * the output step.
+ *
+ * \param[out] output_length On success, the number of bytes of the returned
+ * output.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_BUFFER_TOO_SMALL
+ * The size of the \p output buffer is too small.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p step is not compatible with the operation's algorithm.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p step is not supported with the operation's algorithm.
+ * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active, and fully set
+ * up, and this call must conform to the algorithm's requirements
+ * for ordering of input and output steps), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_pake_output(psa_pake_operation_t *operation,
+ psa_pake_step_t step,
+ uint8_t *output,
+ size_t output_size,
+ size_t *output_length);
+
+/** Provide input for a step of a password-authenticated key exchange.
+ *
+ * Depending on the algorithm being executed, you might need to call this
+ * function several times or you might not need to call this at all.
+ *
+ * The exact sequence of calls to perform a password-authenticated key
+ * exchange depends on the algorithm in use. Refer to the documentation of
+ * individual PAKE algorithm types (`PSA_ALG_XXX` values of type
+ * ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true) for more
+ * information.
+ *
+ * If this function returns an error status, the operation enters an error
+ * state and must be aborted by calling psa_pake_abort().
+ *
+ * \param[in,out] operation Active PAKE operation.
+ * \param step The step for which the input is provided.
+ * \param[in] input Buffer containing the input in the format
+ * appropriate for this \p step. Refer to the
+ * documentation of the individual
+ * \c PSA_PAKE_STEP_XXX constants for more
+ * information.
+ * \param input_length Size of the \p input buffer in bytes.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The verification fails for a #PSA_PAKE_STEP_ZK_PROOF input step.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * \p input_length is not compatible with the \p operation’s algorithm,
+ * or the \p input is not valid for the \p operation's algorithm,
+ * cipher suite or \p step.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * \p step p is not supported with the \p operation's algorithm, or the
+ * \p input is not supported for the \p operation's algorithm, cipher
+ * suite or \p step.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The operation state is not valid (it must be active, and fully set
+ * up, and this call must conform to the algorithm's requirements
+ * for ordering of input and output steps), or
+ * the library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_pake_input(psa_pake_operation_t *operation,
+ psa_pake_step_t step,
+ const uint8_t *input,
+ size_t input_length);
+
+/** Get implicitly confirmed shared secret from a PAKE.
+ *
+ * At this point there is a cryptographic guarantee that only the authenticated
+ * party who used the same password is able to compute the key. But there is no
+ * guarantee that the peer is the party it claims to be and was able to do so.
+ *
+ * That is, the authentication is only implicit. Since the peer is not
+ * authenticated yet, no action should be taken yet that assumes that the peer
+ * is who it claims to be. For example, do not access restricted files on the
+ * peer's behalf until an explicit authentication has succeeded.
+ *
+ * This function can be called after the key exchange phase of the operation
+ * has completed. It imports the shared secret output of the PAKE into the
+ * provided derivation operation. The input step
+ * #PSA_KEY_DERIVATION_INPUT_SECRET is used when placing the shared key
+ * material in the key derivation operation.
+ *
+ * The exact sequence of calls to perform a password-authenticated key
+ * exchange depends on the algorithm in use. Refer to the documentation of
+ * individual PAKE algorithm types (`PSA_ALG_XXX` values of type
+ * ::psa_algorithm_t such that #PSA_ALG_IS_PAKE(\c alg) is true) for more
+ * information.
+ *
+ * When this function returns successfully, \p operation becomes inactive.
+ * If this function returns an error status, both \p operation
+ * and \c key_derivation operations enter an error state and must be aborted by
+ * calling psa_pake_abort() and psa_key_derivation_abort() respectively.
+ *
+ * \param[in,out] operation Active PAKE operation.
+ * \param[out] output A key derivation operation that is ready
+ * for an input step of type
+ * #PSA_KEY_DERIVATION_INPUT_SECRET.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * #PSA_KEY_DERIVATION_INPUT_SECRET is not compatible with the
+ * algorithm in the \p output key derivation operation.
+ * \retval #PSA_ERROR_NOT_SUPPORTED
+ * Input from a PAKE is not supported by the algorithm in the \p output
+ * key derivation operation.
+ * \retval #PSA_ERROR_INSUFFICIENT_MEMORY \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_STORAGE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_DATA_CORRUPT \emptydescription
+ * \retval #PSA_ERROR_DATA_INVALID \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The PAKE operation state is not valid (it must be active, but beyond
+ * that validity is specific to the algorithm), or
+ * the library has not been previously initialized by psa_crypto_init(),
+ * or the state of \p output is not valid for
+ * the #PSA_KEY_DERIVATION_INPUT_SECRET step. This can happen if the
+ * step is out of order or the application has done this step already
+ * and it may not be repeated.
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_pake_get_implicit_key(psa_pake_operation_t *operation,
+ psa_key_derivation_operation_t *output);
+
+/** Abort a PAKE operation.
+ *
+ * Aborting an operation frees all associated resources except for the \c
+ * operation structure itself. Once aborted, the operation object can be reused
+ * for another operation by calling psa_pake_setup() again.
+ *
+ * This function may be called at any time after the operation
+ * object has been initialized as described in #psa_pake_operation_t.
+ *
+ * In particular, calling psa_pake_abort() after the operation has been
+ * terminated by a call to psa_pake_abort() or psa_pake_get_implicit_key()
+ * is safe and has no effect.
+ *
+ * \param[in,out] operation The operation to abort.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ * \retval #PSA_ERROR_BAD_STATE
+ * The library has not been previously initialized by psa_crypto_init().
+ * It is implementation-dependent whether a failure to initialize
+ * results in this error code.
+ */
+psa_status_t psa_pake_abort(psa_pake_operation_t *operation);
+
+/**@}*/
+
+/** A sufficient output buffer size for psa_pake_output().
+ *
+ * If the size of the output buffer is at least this large, it is guaranteed
+ * that psa_pake_output() will not fail due to an insufficient output buffer
+ * size. The actual size of the output might be smaller in any given call.
+ *
+ * See also #PSA_PAKE_OUTPUT_MAX_SIZE
+ *
+ * \param alg A PAKE algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_PAKE(\p alg) is true).
+ * \param primitive A primitive of type ::psa_pake_primitive_t that is
+ * compatible with algorithm \p alg.
+ * \param output_step A value of type ::psa_pake_step_t that is valid for the
+ * algorithm \p alg.
+ * \return A sufficient output buffer size for the specified
+ * PAKE algorithm, primitive, and output step. If the
+ * PAKE algorithm, primitive, or output step is not
+ * recognized, or the parameters are incompatible,
+ * return 0.
+ */
+#define PSA_PAKE_OUTPUT_SIZE(alg, primitive, output_step) \
+ (alg == PSA_ALG_JPAKE && \
+ primitive == PSA_PAKE_PRIMITIVE(PSA_PAKE_PRIMITIVE_TYPE_ECC, \
+ PSA_ECC_FAMILY_SECP_R1, 256) ? \
+ ( \
+ output_step == PSA_PAKE_STEP_KEY_SHARE ? 65 : \
+ output_step == PSA_PAKE_STEP_ZK_PUBLIC ? 65 : \
+ 32 \
+ ) : \
+ 0)
+
+/** A sufficient input buffer size for psa_pake_input().
+ *
+ * The value returned by this macro is guaranteed to be large enough for any
+ * valid input to psa_pake_input() in an operation with the specified
+ * parameters.
+ *
+ * See also #PSA_PAKE_INPUT_MAX_SIZE
+ *
+ * \param alg A PAKE algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_PAKE(\p alg) is true).
+ * \param primitive A primitive of type ::psa_pake_primitive_t that is
+ * compatible with algorithm \p alg.
+ * \param input_step A value of type ::psa_pake_step_t that is valid for the
+ * algorithm \p alg.
+ * \return A sufficient input buffer size for the specified
+ * input, cipher suite and algorithm. If the cipher suite,
+ * the input type or PAKE algorithm is not recognized, or
+ * the parameters are incompatible, return 0.
+ */
+#define PSA_PAKE_INPUT_SIZE(alg, primitive, input_step) \
+ (alg == PSA_ALG_JPAKE && \
+ primitive == PSA_PAKE_PRIMITIVE(PSA_PAKE_PRIMITIVE_TYPE_ECC, \
+ PSA_ECC_FAMILY_SECP_R1, 256) ? \
+ ( \
+ input_step == PSA_PAKE_STEP_KEY_SHARE ? 65 : \
+ input_step == PSA_PAKE_STEP_ZK_PUBLIC ? 65 : \
+ 32 \
+ ) : \
+ 0)
+
+/** Output buffer size for psa_pake_output() for any of the supported PAKE
+ * algorithm and primitive suites and output step.
+ *
+ * This macro must expand to a compile-time constant integer.
+ *
+ * The value of this macro must be at least as large as the largest value
+ * returned by PSA_PAKE_OUTPUT_SIZE()
+ *
+ * See also #PSA_PAKE_OUTPUT_SIZE(\p alg, \p primitive, \p output_step).
+ */
+#define PSA_PAKE_OUTPUT_MAX_SIZE 65
+
+/** Input buffer size for psa_pake_input() for any of the supported PAKE
+ * algorithm and primitive suites and input step.
+ *
+ * This macro must expand to a compile-time constant integer.
+ *
+ * The value of this macro must be at least as large as the largest value
+ * returned by PSA_PAKE_INPUT_SIZE()
+ *
+ * See also #PSA_PAKE_INPUT_SIZE(\p alg, \p primitive, \p output_step).
+ */
+#define PSA_PAKE_INPUT_MAX_SIZE 65
+
+/** Returns a suitable initializer for a PAKE cipher suite object of type
+ * psa_pake_cipher_suite_t.
+ */
+#define PSA_PAKE_CIPHER_SUITE_INIT { PSA_ALG_NONE, 0, 0, 0, PSA_ALG_NONE }
+
+/** Returns a suitable initializer for a PAKE operation object of type
+ * psa_pake_operation_t.
+ */
+#define PSA_PAKE_OPERATION_INIT { 0, PSA_ALG_NONE, 0, PSA_PAKE_OPERATION_STAGE_SETUP, \
+ { 0 }, { { 0 } } }
+
+struct psa_pake_cipher_suite_s {
+ psa_algorithm_t algorithm;
+ psa_pake_primitive_type_t type;
+ psa_pake_family_t family;
+ uint16_t bits;
+ psa_algorithm_t hash;
+};
+
+static inline psa_algorithm_t psa_pake_cs_get_algorithm(
+ const psa_pake_cipher_suite_t *cipher_suite)
+{
+ return cipher_suite->algorithm;
+}
+
+static inline void psa_pake_cs_set_algorithm(
+ psa_pake_cipher_suite_t *cipher_suite,
+ psa_algorithm_t algorithm)
+{
+ if (!PSA_ALG_IS_PAKE(algorithm)) {
+ cipher_suite->algorithm = 0;
+ } else {
+ cipher_suite->algorithm = algorithm;
+ }
+}
+
+static inline psa_pake_primitive_t psa_pake_cs_get_primitive(
+ const psa_pake_cipher_suite_t *cipher_suite)
+{
+ return PSA_PAKE_PRIMITIVE(cipher_suite->type, cipher_suite->family,
+ cipher_suite->bits);
+}
+
+static inline void psa_pake_cs_set_primitive(
+ psa_pake_cipher_suite_t *cipher_suite,
+ psa_pake_primitive_t primitive)
+{
+ cipher_suite->type = (psa_pake_primitive_type_t) (primitive >> 24);
+ cipher_suite->family = (psa_pake_family_t) (0xFF & (primitive >> 16));
+ cipher_suite->bits = (uint16_t) (0xFFFF & primitive);
+}
+
+static inline psa_pake_family_t psa_pake_cs_get_family(
+ const psa_pake_cipher_suite_t *cipher_suite)
+{
+ return cipher_suite->family;
+}
+
+static inline uint16_t psa_pake_cs_get_bits(
+ const psa_pake_cipher_suite_t *cipher_suite)
+{
+ return cipher_suite->bits;
+}
+
+static inline psa_algorithm_t psa_pake_cs_get_hash(
+ const psa_pake_cipher_suite_t *cipher_suite)
+{
+ return cipher_suite->hash;
+}
+
+static inline void psa_pake_cs_set_hash(psa_pake_cipher_suite_t *cipher_suite,
+ psa_algorithm_t hash)
+{
+ if (!PSA_ALG_IS_HASH(hash)) {
+ cipher_suite->hash = 0;
+ } else {
+ cipher_suite->hash = hash;
+ }
+}
+
+struct psa_crypto_driver_pake_inputs_s {
+ uint8_t *MBEDTLS_PRIVATE(password);
+ size_t MBEDTLS_PRIVATE(password_len);
+ uint8_t *MBEDTLS_PRIVATE(user);
+ size_t MBEDTLS_PRIVATE(user_len);
+ uint8_t *MBEDTLS_PRIVATE(peer);
+ size_t MBEDTLS_PRIVATE(peer_len);
+ psa_key_attributes_t MBEDTLS_PRIVATE(attributes);
+ psa_pake_cipher_suite_t MBEDTLS_PRIVATE(cipher_suite);
+};
+
+typedef enum psa_crypto_driver_pake_step {
+ PSA_JPAKE_STEP_INVALID = 0, /* Invalid step */
+ PSA_JPAKE_X1_STEP_KEY_SHARE = 1, /* Round 1: input/output key share (for ephemeral private key X1).*/
+ PSA_JPAKE_X1_STEP_ZK_PUBLIC = 2, /* Round 1: input/output Schnorr NIZKP public key for the X1 key */
+ PSA_JPAKE_X1_STEP_ZK_PROOF = 3, /* Round 1: input/output Schnorr NIZKP proof for the X1 key */
+ PSA_JPAKE_X2_STEP_KEY_SHARE = 4, /* Round 1: input/output key share (for ephemeral private key X2).*/
+ PSA_JPAKE_X2_STEP_ZK_PUBLIC = 5, /* Round 1: input/output Schnorr NIZKP public key for the X2 key */
+ PSA_JPAKE_X2_STEP_ZK_PROOF = 6, /* Round 1: input/output Schnorr NIZKP proof for the X2 key */
+ PSA_JPAKE_X2S_STEP_KEY_SHARE = 7, /* Round 2: output X2S key (our key) */
+ PSA_JPAKE_X2S_STEP_ZK_PUBLIC = 8, /* Round 2: output Schnorr NIZKP public key for the X2S key (our key) */
+ PSA_JPAKE_X2S_STEP_ZK_PROOF = 9, /* Round 2: output Schnorr NIZKP proof for the X2S key (our key) */
+ PSA_JPAKE_X4S_STEP_KEY_SHARE = 10, /* Round 2: input X4S key (from peer) */
+ PSA_JPAKE_X4S_STEP_ZK_PUBLIC = 11, /* Round 2: input Schnorr NIZKP public key for the X4S key (from peer) */
+ PSA_JPAKE_X4S_STEP_ZK_PROOF = 12 /* Round 2: input Schnorr NIZKP proof for the X4S key (from peer) */
+} psa_crypto_driver_pake_step_t;
+
+typedef enum psa_jpake_round {
+ PSA_JPAKE_FIRST = 0,
+ PSA_JPAKE_SECOND = 1,
+ PSA_JPAKE_FINISHED = 2
+} psa_jpake_round_t;
+
+typedef enum psa_jpake_io_mode {
+ PSA_JPAKE_INPUT = 0,
+ PSA_JPAKE_OUTPUT = 1
+} psa_jpake_io_mode_t;
+
+struct psa_jpake_computation_stage_s {
+ /* The J-PAKE round we are currently on */
+ psa_jpake_round_t MBEDTLS_PRIVATE(round);
+ /* The 'mode' we are currently in (inputting or outputting) */
+ psa_jpake_io_mode_t MBEDTLS_PRIVATE(io_mode);
+ /* The number of completed inputs so far this round */
+ uint8_t MBEDTLS_PRIVATE(inputs);
+ /* The number of completed outputs so far this round */
+ uint8_t MBEDTLS_PRIVATE(outputs);
+ /* The next expected step (KEY_SHARE, ZK_PUBLIC or ZK_PROOF) */
+ psa_pake_step_t MBEDTLS_PRIVATE(step);
+};
+
+#define PSA_JPAKE_EXPECTED_INPUTS(round) ((round) == PSA_JPAKE_FINISHED ? 0 : \
+ ((round) == PSA_JPAKE_FIRST ? 2 : 1))
+#define PSA_JPAKE_EXPECTED_OUTPUTS(round) ((round) == PSA_JPAKE_FINISHED ? 0 : \
+ ((round) == PSA_JPAKE_FIRST ? 2 : 1))
+
+struct psa_pake_operation_s {
+ /** Unique ID indicating which driver got assigned to do the
+ * operation. Since driver contexts are driver-specific, swapping
+ * drivers halfway through the operation is not supported.
+ * ID values are auto-generated in psa_crypto_driver_wrappers.h
+ * ID value zero means the context is not valid or not assigned to
+ * any driver (i.e. none of the driver contexts are active). */
+ unsigned int MBEDTLS_PRIVATE(id);
+ /* Algorithm of the PAKE operation */
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+ /* A primitive of type compatible with algorithm */
+ psa_pake_primitive_t MBEDTLS_PRIVATE(primitive);
+ /* Stage of the PAKE operation: waiting for the setup, collecting inputs
+ * or computing. */
+ uint8_t MBEDTLS_PRIVATE(stage);
+ /* Holds computation stage of the PAKE algorithms. */
+ union {
+ uint8_t MBEDTLS_PRIVATE(dummy);
+#if defined(PSA_WANT_ALG_JPAKE)
+ psa_jpake_computation_stage_t MBEDTLS_PRIVATE(jpake);
+#endif
+ } MBEDTLS_PRIVATE(computation_stage);
+ union {
+ psa_driver_pake_context_t MBEDTLS_PRIVATE(ctx);
+ psa_crypto_driver_pake_inputs_t MBEDTLS_PRIVATE(inputs);
+ } MBEDTLS_PRIVATE(data);
+};
+
+static inline struct psa_pake_cipher_suite_s psa_pake_cipher_suite_init(void)
+{
+ const struct psa_pake_cipher_suite_s v = PSA_PAKE_CIPHER_SUITE_INIT;
+ return v;
+}
+
+static inline struct psa_pake_operation_s psa_pake_operation_init(void)
+{
+ const struct psa_pake_operation_s v = PSA_PAKE_OPERATION_INIT;
+ return v;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PSA_CRYPTO_EXTRA_H */
diff --git a/include/psa/crypto_legacy.h b/include/psa/crypto_legacy.h
new file mode 100644
index 0000000..7df3614
--- /dev/null
+++ b/include/psa/crypto_legacy.h
@@ -0,0 +1,88 @@
+/**
+ * \file psa/crypto_legacy.h
+ *
+ * \brief Add temporary suppport for deprecated symbols before they are
+ * removed from the library.
+ *
+ * PSA_WANT_KEY_TYPE_xxx_KEY_PAIR and MBEDTLS_PSA_ACCEL_KEY_TYPE_xxx_KEY_PAIR
+ * symbols are deprecated.
+ * New symols add a suffix to that base name in order to clearly state what is
+ * the expected use for the key (use, import, export, generate, derive).
+ * Here we define some backward compatibility support for uses stil using
+ * the legacy symbols.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef MBEDTLS_PSA_CRYPTO_LEGACY_H
+#define MBEDTLS_PSA_CRYPTO_LEGACY_H
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR) //no-check-names
+#if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC)
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC 1
+#endif
+#if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT)
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_IMPORT 1
+#endif
+#if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT)
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_EXPORT 1
+#endif
+#if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_GENERATE 1
+#endif
+#if !defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
+#define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_DERIVE 1
+#endif
+#endif
+
+#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR) //no-check-names
+#if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC)
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC 1
+#endif
+#if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT)
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_IMPORT 1
+#endif
+#if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT)
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_EXPORT 1
+#endif
+#if !defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
+#define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_GENERATE 1
+#endif
+#endif
+
+#if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) //no-check-names
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC)
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_BASIC
+#endif
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT)
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_IMPORT
+#endif
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT)
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_EXPORT
+#endif
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE)
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_GENERATE
+#endif
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE)
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR_DERIVE
+#endif
+#endif
+
+#if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR) //no-check-names
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_BASIC)
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_BASIC
+#endif
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_IMPORT)
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_IMPORT
+#endif
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_EXPORT)
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_EXPORT
+#endif
+#if !defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_GENERATE)
+#define MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR_GENERATE
+#endif
+#endif
+
+#endif /* MBEDTLS_PSA_CRYPTO_LEGACY_H */
diff --git a/include/psa/crypto_platform.h b/include/psa/crypto_platform.h
new file mode 100644
index 0000000..f32a101
--- /dev/null
+++ b/include/psa/crypto_platform.h
@@ -0,0 +1,92 @@
+/**
+ * \file psa/crypto_platform.h
+ *
+ * \brief PSA cryptography module: Mbed TLS platform definitions
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ *
+ * This file contains platform-dependent type definitions.
+ *
+ * In implementations with isolation between the application and the
+ * cryptography module, implementers should take care to ensure that
+ * the definitions that are exposed to applications match what the
+ * module implements.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_PLATFORM_H
+#define PSA_CRYPTO_PLATFORM_H
+#include "mbedtls/private_access.h"
+
+/*
+ * Include the build-time configuration information file. Here, we do not
+ * include `"mbedtls/build_info.h"` directly but `"psa/build_info.h"`, which
+ * is basically just an alias to it. This is to ease the maintenance of the
+ * PSA cryptography repository which has a different build system and
+ * configuration.
+ */
+#include "psa/build_info.h"
+
+/* PSA requires several types which C99 provides in stdint.h. */
+#include <stdint.h>
+
+#if defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
+
+/* Building for the PSA Crypto service on a PSA platform, a key owner is a PSA
+ * partition identifier.
+ *
+ * The function psa_its_identifier_of_slot() in psa_crypto_storage.c that
+ * translates a key identifier to a key storage file name assumes that
+ * mbedtls_key_owner_id_t is a 32-bit integer. This function thus needs
+ * reworking if mbedtls_key_owner_id_t is not defined as a 32-bit integer
+ * here anymore.
+ */
+typedef int32_t mbedtls_key_owner_id_t;
+
+/** Compare two key owner identifiers.
+ *
+ * \param id1 First key owner identifier.
+ * \param id2 Second key owner identifier.
+ *
+ * \return Non-zero if the two key owner identifiers are equal, zero otherwise.
+ */
+static inline int mbedtls_key_owner_id_equal(mbedtls_key_owner_id_t id1,
+ mbedtls_key_owner_id_t id2)
+{
+ return id1 == id2;
+}
+
+#endif /* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */
+
+/*
+ * When MBEDTLS_PSA_CRYPTO_SPM is defined, the code is being built for SPM
+ * (Secure Partition Manager) integration which separates the code into two
+ * parts: NSPE (Non-Secure Processing Environment) and SPE (Secure Processing
+ * Environment). When building for the SPE, an additional header file should be
+ * included.
+ */
+#if defined(MBEDTLS_PSA_CRYPTO_SPM)
+#define PSA_CRYPTO_SECURE 1
+#include "crypto_spe.h"
+#endif // MBEDTLS_PSA_CRYPTO_SPM
+
+#if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG)
+/** The type of the context passed to mbedtls_psa_external_get_random().
+ *
+ * Mbed TLS initializes the context to all-bits-zero before calling
+ * mbedtls_psa_external_get_random() for the first time.
+ *
+ * The definition of this type in the Mbed TLS source code is for
+ * demonstration purposes. Implementers of mbedtls_psa_external_get_random()
+ * are expected to replace it with a custom definition.
+ */
+typedef struct {
+ uintptr_t MBEDTLS_PRIVATE(opaque)[2];
+} mbedtls_psa_external_random_context_t;
+#endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
+
+#endif /* PSA_CRYPTO_PLATFORM_H */
diff --git a/include/psa/crypto_se_driver.h b/include/psa/crypto_se_driver.h
new file mode 100644
index 0000000..9ce14bb
--- /dev/null
+++ b/include/psa/crypto_se_driver.h
@@ -0,0 +1,1383 @@
+/**
+ * \file psa/crypto_se_driver.h
+ * \brief PSA external cryptoprocessor driver module
+ *
+ * This header declares types and function signatures for cryptography
+ * drivers that access key material via opaque references.
+ * This is meant for cryptoprocessors that have a separate key storage from the
+ * space in which the PSA Crypto implementation runs, typically secure
+ * elements (SEs).
+ *
+ * This file is part of the PSA Crypto Driver HAL (hardware abstraction layer),
+ * containing functions for driver developers to implement to enable hardware
+ * to be called in a standardized way by a PSA Cryptography API
+ * implementation. The functions comprising the driver HAL, which driver
+ * authors implement, are not intended to be called by application developers.
+ */
+
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+#ifndef PSA_CRYPTO_SE_DRIVER_H
+#define PSA_CRYPTO_SE_DRIVER_H
+#include "mbedtls/private_access.h"
+
+#include "crypto_driver_common.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** \defgroup se_init Secure element driver initialization
+ */
+/**@{*/
+
+/** \brief Driver context structure
+ *
+ * Driver functions receive a pointer to this structure.
+ * Each registered driver has one instance of this structure.
+ *
+ * Implementations must include the fields specified here and
+ * may include other fields.
+ */
+typedef struct {
+ /** A read-only pointer to the driver's persistent data.
+ *
+ * Drivers typically use this persistent data to keep track of
+ * which slot numbers are available. This is only a guideline:
+ * drivers may use the persistent data for any purpose, keeping
+ * in mind the restrictions on when the persistent data is saved
+ * to storage: the persistent data is only saved after calling
+ * certain functions that receive a writable pointer to the
+ * persistent data.
+ *
+ * The core allocates a memory buffer for the persistent data.
+ * The pointer is guaranteed to be suitably aligned for any data type,
+ * like a pointer returned by `malloc` (but the core can use any
+ * method to allocate the buffer, not necessarily `malloc`).
+ *
+ * The size of this buffer is in the \c persistent_data_size field of
+ * this structure.
+ *
+ * Before the driver is initialized for the first time, the content of
+ * the persistent data is all-bits-zero. After a driver upgrade, if the
+ * size of the persistent data has increased, the original data is padded
+ * on the right with zeros; if the size has decreased, the original data
+ * is truncated to the new size.
+ *
+ * This pointer is to read-only data. Only a few driver functions are
+ * allowed to modify the persistent data. These functions receive a
+ * writable pointer. These functions are:
+ * - psa_drv_se_t::p_init
+ * - psa_drv_se_key_management_t::p_allocate
+ * - psa_drv_se_key_management_t::p_destroy
+ *
+ * The PSA Cryptography core saves the persistent data from one
+ * session to the next. It does this before returning from API functions
+ * that call a driver method that is allowed to modify the persistent
+ * data, specifically:
+ * - psa_crypto_init() causes a call to psa_drv_se_t::p_init, and may call
+ * psa_drv_se_key_management_t::p_destroy to complete an action
+ * that was interrupted by a power failure.
+ * - Key creation functions cause a call to
+ * psa_drv_se_key_management_t::p_allocate, and may cause a call to
+ * psa_drv_se_key_management_t::p_destroy in case an error occurs.
+ * - psa_destroy_key() causes a call to
+ * psa_drv_se_key_management_t::p_destroy.
+ */
+ const void *const MBEDTLS_PRIVATE(persistent_data);
+
+ /** The size of \c persistent_data in bytes.
+ *
+ * This is always equal to the value of the `persistent_data_size` field
+ * of the ::psa_drv_se_t structure when the driver is registered.
+ */
+ const size_t MBEDTLS_PRIVATE(persistent_data_size);
+
+ /** Driver transient data.
+ *
+ * The core initializes this value to 0 and does not read or modify it
+ * afterwards. The driver may store whatever it wants in this field.
+ */
+ uintptr_t MBEDTLS_PRIVATE(transient_data);
+} psa_drv_se_context_t;
+
+/** \brief A driver initialization function.
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in,out] persistent_data A pointer to the persistent data
+ * that allows writing.
+ * \param location The location value for which this driver
+ * is registered. The driver will be invoked
+ * for all keys whose lifetime is in this
+ * location.
+ *
+ * \retval #PSA_SUCCESS
+ * The driver is operational.
+ * The core will update the persistent data in storage.
+ * \return
+ * Any other return value prevents the driver from being used in
+ * this session.
+ * The core will NOT update the persistent data in storage.
+ */
+typedef psa_status_t (*psa_drv_se_init_t)(psa_drv_se_context_t *drv_context,
+ void *persistent_data,
+ psa_key_location_t location);
+
+#if defined(__DOXYGEN_ONLY__) || !defined(MBEDTLS_PSA_CRYPTO_SE_C)
+/* Mbed TLS with secure element support enabled defines this type in
+ * crypto_types.h because it is also visible to applications through an
+ * implementation-specific extension.
+ * For the PSA Cryptography specification, this type is only visible
+ * via crypto_se_driver.h. */
+/** An internal designation of a key slot between the core part of the
+ * PSA Crypto implementation and the driver. The meaning of this value
+ * is driver-dependent. */
+typedef uint64_t psa_key_slot_number_t;
+#endif /* __DOXYGEN_ONLY__ || !MBEDTLS_PSA_CRYPTO_SE_C */
+
+/**@}*/
+
+/** \defgroup se_mac Secure Element Message Authentication Codes
+ * Generation and authentication of Message Authentication Codes (MACs) using
+ * a secure element can be done either as a single function call (via the
+ * `psa_drv_se_mac_generate_t` or `psa_drv_se_mac_verify_t` functions), or in
+ * parts using the following sequence:
+ * - `psa_drv_se_mac_setup_t`
+ * - `psa_drv_se_mac_update_t`
+ * - `psa_drv_se_mac_update_t`
+ * - ...
+ * - `psa_drv_se_mac_finish_t` or `psa_drv_se_mac_finish_verify_t`
+ *
+ * If a previously started secure element MAC operation needs to be terminated,
+ * it should be done so by the `psa_drv_se_mac_abort_t`. Failure to do so may
+ * result in allocated resources not being freed or in other undefined
+ * behavior.
+ */
+/**@{*/
+/** \brief A function that starts a secure element MAC operation for a PSA
+ * Crypto Driver implementation
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in,out] op_context A structure that will contain the
+ * hardware-specific MAC context
+ * \param[in] key_slot The slot of the key to be used for the
+ * operation
+ * \param[in] algorithm The algorithm to be used to underly the MAC
+ * operation
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ */
+typedef psa_status_t (*psa_drv_se_mac_setup_t)(psa_drv_se_context_t *drv_context,
+ void *op_context,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t algorithm);
+
+/** \brief A function that continues a previously started secure element MAC
+ * operation
+ *
+ * \param[in,out] op_context A hardware-specific structure for the
+ * previously-established MAC operation to be
+ * updated
+ * \param[in] p_input A buffer containing the message to be appended
+ * to the MAC operation
+ * \param[in] input_length The size in bytes of the input message buffer
+ */
+typedef psa_status_t (*psa_drv_se_mac_update_t)(void *op_context,
+ const uint8_t *p_input,
+ size_t input_length);
+
+/** \brief a function that completes a previously started secure element MAC
+ * operation by returning the resulting MAC.
+ *
+ * \param[in,out] op_context A hardware-specific structure for the
+ * previously started MAC operation to be
+ * finished
+ * \param[out] p_mac A buffer where the generated MAC will be
+ * placed
+ * \param[in] mac_size The size in bytes of the buffer that has been
+ * allocated for the `output` buffer
+ * \param[out] p_mac_length After completion, will contain the number of
+ * bytes placed in the `p_mac` buffer
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ */
+typedef psa_status_t (*psa_drv_se_mac_finish_t)(void *op_context,
+ uint8_t *p_mac,
+ size_t mac_size,
+ size_t *p_mac_length);
+
+/** \brief A function that completes a previously started secure element MAC
+ * operation by comparing the resulting MAC against a provided value
+ *
+ * \param[in,out] op_context A hardware-specific structure for the previously
+ * started MAC operation to be finished
+ * \param[in] p_mac The MAC value against which the resulting MAC
+ * will be compared against
+ * \param[in] mac_length The size in bytes of the value stored in `p_mac`
+ *
+ * \retval #PSA_SUCCESS
+ * The operation completed successfully and the MACs matched each
+ * other
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The operation completed successfully, but the calculated MAC did
+ * not match the provided MAC
+ */
+typedef psa_status_t (*psa_drv_se_mac_finish_verify_t)(void *op_context,
+ const uint8_t *p_mac,
+ size_t mac_length);
+
+/** \brief A function that aborts a previous started secure element MAC
+ * operation
+ *
+ * \param[in,out] op_context A hardware-specific structure for the previously
+ * started MAC operation to be aborted
+ */
+typedef psa_status_t (*psa_drv_se_mac_abort_t)(void *op_context);
+
+/** \brief A function that performs a secure element MAC operation in one
+ * command and returns the calculated MAC
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in] p_input A buffer containing the message to be MACed
+ * \param[in] input_length The size in bytes of `p_input`
+ * \param[in] key_slot The slot of the key to be used
+ * \param[in] alg The algorithm to be used to underlie the MAC
+ * operation
+ * \param[out] p_mac A buffer where the generated MAC will be
+ * placed
+ * \param[in] mac_size The size in bytes of the `p_mac` buffer
+ * \param[out] p_mac_length After completion, will contain the number of
+ * bytes placed in the `output` buffer
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ */
+typedef psa_status_t (*psa_drv_se_mac_generate_t)(psa_drv_se_context_t *drv_context,
+ const uint8_t *p_input,
+ size_t input_length,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t alg,
+ uint8_t *p_mac,
+ size_t mac_size,
+ size_t *p_mac_length);
+
+/** \brief A function that performs a secure element MAC operation in one
+ * command and compares the resulting MAC against a provided value
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in] p_input A buffer containing the message to be MACed
+ * \param[in] input_length The size in bytes of `input`
+ * \param[in] key_slot The slot of the key to be used
+ * \param[in] alg The algorithm to be used to underlie the MAC
+ * operation
+ * \param[in] p_mac The MAC value against which the resulting MAC will
+ * be compared against
+ * \param[in] mac_length The size in bytes of `mac`
+ *
+ * \retval #PSA_SUCCESS
+ * The operation completed successfully and the MACs matched each
+ * other
+ * \retval #PSA_ERROR_INVALID_SIGNATURE
+ * The operation completed successfully, but the calculated MAC did
+ * not match the provided MAC
+ */
+typedef psa_status_t (*psa_drv_se_mac_verify_t)(psa_drv_se_context_t *drv_context,
+ const uint8_t *p_input,
+ size_t input_length,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t alg,
+ const uint8_t *p_mac,
+ size_t mac_length);
+
+/** \brief A struct containing all of the function pointers needed to
+ * perform secure element MAC operations
+ *
+ * PSA Crypto API implementations should populate the table as appropriate
+ * upon startup.
+ *
+ * If one of the functions is not implemented (such as
+ * `psa_drv_se_mac_generate_t`), it should be set to NULL.
+ *
+ * Driver implementers should ensure that they implement all of the functions
+ * that make sense for their hardware, and that they provide a full solution
+ * (for example, if they support `p_setup`, they should also support
+ * `p_update` and at least one of `p_finish` or `p_finish_verify`).
+ *
+ */
+typedef struct {
+ /**The size in bytes of the hardware-specific secure element MAC context
+ * structure
+ */
+ size_t MBEDTLS_PRIVATE(context_size);
+ /** Function that performs a MAC setup operation
+ */
+ psa_drv_se_mac_setup_t MBEDTLS_PRIVATE(p_setup);
+ /** Function that performs a MAC update operation
+ */
+ psa_drv_se_mac_update_t MBEDTLS_PRIVATE(p_update);
+ /** Function that completes a MAC operation
+ */
+ psa_drv_se_mac_finish_t MBEDTLS_PRIVATE(p_finish);
+ /** Function that completes a MAC operation with a verify check
+ */
+ psa_drv_se_mac_finish_verify_t MBEDTLS_PRIVATE(p_finish_verify);
+ /** Function that aborts a previously started MAC operation
+ */
+ psa_drv_se_mac_abort_t MBEDTLS_PRIVATE(p_abort);
+ /** Function that performs a MAC operation in one call
+ */
+ psa_drv_se_mac_generate_t MBEDTLS_PRIVATE(p_mac);
+ /** Function that performs a MAC and verify operation in one call
+ */
+ psa_drv_se_mac_verify_t MBEDTLS_PRIVATE(p_mac_verify);
+} psa_drv_se_mac_t;
+/**@}*/
+
+/** \defgroup se_cipher Secure Element Symmetric Ciphers
+ *
+ * Encryption and Decryption using secure element keys in block modes other
+ * than ECB must be done in multiple parts, using the following flow:
+ * - `psa_drv_se_cipher_setup_t`
+ * - `psa_drv_se_cipher_set_iv_t` (optional depending upon block mode)
+ * - `psa_drv_se_cipher_update_t`
+ * - `psa_drv_se_cipher_update_t`
+ * - ...
+ * - `psa_drv_se_cipher_finish_t`
+ *
+ * If a previously started secure element Cipher operation needs to be
+ * terminated, it should be done so by the `psa_drv_se_cipher_abort_t`. Failure
+ * to do so may result in allocated resources not being freed or in other
+ * undefined behavior.
+ *
+ * In situations where a PSA Cryptographic API implementation is using a block
+ * mode not-supported by the underlying hardware or driver, it can construct
+ * the block mode itself, while calling the `psa_drv_se_cipher_ecb_t` function
+ * for the cipher operations.
+ */
+/**@{*/
+
+/** \brief A function that provides the cipher setup function for a
+ * secure element driver
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in,out] op_context A structure that will contain the
+ * hardware-specific cipher context.
+ * \param[in] key_slot The slot of the key to be used for the
+ * operation
+ * \param[in] algorithm The algorithm to be used in the cipher
+ * operation
+ * \param[in] direction Indicates whether the operation is an encrypt
+ * or decrypt
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_cipher_setup_t)(psa_drv_se_context_t *drv_context,
+ void *op_context,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t algorithm,
+ psa_encrypt_or_decrypt_t direction);
+
+/** \brief A function that sets the initialization vector (if
+ * necessary) for a secure element cipher operation
+ *
+ * Rationale: The `psa_se_cipher_*` operation in the PSA Cryptographic API has
+ * two IV functions: one to set the IV, and one to generate it internally. The
+ * generate function is not necessary for the drivers to implement as the PSA
+ * Crypto implementation can do the generation using its RNG features.
+ *
+ * \param[in,out] op_context A structure that contains the previously set up
+ * hardware-specific cipher context
+ * \param[in] p_iv A buffer containing the initialization vector
+ * \param[in] iv_length The size (in bytes) of the `p_iv` buffer
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_cipher_set_iv_t)(void *op_context,
+ const uint8_t *p_iv,
+ size_t iv_length);
+
+/** \brief A function that continues a previously started secure element cipher
+ * operation
+ *
+ * \param[in,out] op_context A hardware-specific structure for the
+ * previously started cipher operation
+ * \param[in] p_input A buffer containing the data to be
+ * encrypted/decrypted
+ * \param[in] input_size The size in bytes of the buffer pointed to
+ * by `p_input`
+ * \param[out] p_output The caller-allocated buffer where the
+ * output will be placed
+ * \param[in] output_size The allocated size in bytes of the
+ * `p_output` buffer
+ * \param[out] p_output_length After completion, will contain the number
+ * of bytes placed in the `p_output` buffer
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_cipher_update_t)(void *op_context,
+ const uint8_t *p_input,
+ size_t input_size,
+ uint8_t *p_output,
+ size_t output_size,
+ size_t *p_output_length);
+
+/** \brief A function that completes a previously started secure element cipher
+ * operation
+ *
+ * \param[in,out] op_context A hardware-specific structure for the
+ * previously started cipher operation
+ * \param[out] p_output The caller-allocated buffer where the output
+ * will be placed
+ * \param[in] output_size The allocated size in bytes of the `p_output`
+ * buffer
+ * \param[out] p_output_length After completion, will contain the number of
+ * bytes placed in the `p_output` buffer
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_cipher_finish_t)(void *op_context,
+ uint8_t *p_output,
+ size_t output_size,
+ size_t *p_output_length);
+
+/** \brief A function that aborts a previously started secure element cipher
+ * operation
+ *
+ * \param[in,out] op_context A hardware-specific structure for the
+ * previously started cipher operation
+ */
+typedef psa_status_t (*psa_drv_se_cipher_abort_t)(void *op_context);
+
+/** \brief A function that performs the ECB block mode for secure element
+ * cipher operations
+ *
+ * Note: this function should only be used with implementations that do not
+ * provide a needed higher-level operation.
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in] key_slot The slot of the key to be used for the operation
+ * \param[in] algorithm The algorithm to be used in the cipher operation
+ * \param[in] direction Indicates whether the operation is an encrypt or
+ * decrypt
+ * \param[in] p_input A buffer containing the data to be
+ * encrypted/decrypted
+ * \param[in] input_size The size in bytes of the buffer pointed to by
+ * `p_input`
+ * \param[out] p_output The caller-allocated buffer where the output
+ * will be placed
+ * \param[in] output_size The allocated size in bytes of the `p_output`
+ * buffer
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_cipher_ecb_t)(psa_drv_se_context_t *drv_context,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t algorithm,
+ psa_encrypt_or_decrypt_t direction,
+ const uint8_t *p_input,
+ size_t input_size,
+ uint8_t *p_output,
+ size_t output_size);
+
+/**
+ * \brief A struct containing all of the function pointers needed to implement
+ * cipher operations using secure elements.
+ *
+ * PSA Crypto API implementations should populate instances of the table as
+ * appropriate upon startup or at build time.
+ *
+ * If one of the functions is not implemented (such as
+ * `psa_drv_se_cipher_ecb_t`), it should be set to NULL.
+ */
+typedef struct {
+ /** The size in bytes of the hardware-specific secure element cipher
+ * context structure
+ */
+ size_t MBEDTLS_PRIVATE(context_size);
+ /** Function that performs a cipher setup operation */
+ psa_drv_se_cipher_setup_t MBEDTLS_PRIVATE(p_setup);
+ /** Function that sets a cipher IV (if necessary) */
+ psa_drv_se_cipher_set_iv_t MBEDTLS_PRIVATE(p_set_iv);
+ /** Function that performs a cipher update operation */
+ psa_drv_se_cipher_update_t MBEDTLS_PRIVATE(p_update);
+ /** Function that completes a cipher operation */
+ psa_drv_se_cipher_finish_t MBEDTLS_PRIVATE(p_finish);
+ /** Function that aborts a cipher operation */
+ psa_drv_se_cipher_abort_t MBEDTLS_PRIVATE(p_abort);
+ /** Function that performs ECB mode for a cipher operation
+ * (Danger: ECB mode should not be used directly by clients of the PSA
+ * Crypto Client API)
+ */
+ psa_drv_se_cipher_ecb_t MBEDTLS_PRIVATE(p_ecb);
+} psa_drv_se_cipher_t;
+
+/**@}*/
+
+/** \defgroup se_asymmetric Secure Element Asymmetric Cryptography
+ *
+ * Since the amount of data that can (or should) be encrypted or signed using
+ * asymmetric keys is limited by the key size, asymmetric key operations using
+ * keys in a secure element must be done in single function calls.
+ */
+/**@{*/
+
+/**
+ * \brief A function that signs a hash or short message with a private key in
+ * a secure element
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in] key_slot Key slot of an asymmetric key pair
+ * \param[in] alg A signature algorithm that is compatible
+ * with the type of `key`
+ * \param[in] p_hash The hash to sign
+ * \param[in] hash_length Size of the `p_hash` buffer in bytes
+ * \param[out] p_signature Buffer where the signature is to be written
+ * \param[in] signature_size Size of the `p_signature` buffer in bytes
+ * \param[out] p_signature_length On success, the number of bytes
+ * that make up the returned signature value
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_asymmetric_sign_t)(psa_drv_se_context_t *drv_context,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t alg,
+ const uint8_t *p_hash,
+ size_t hash_length,
+ uint8_t *p_signature,
+ size_t signature_size,
+ size_t *p_signature_length);
+
+/**
+ * \brief A function that verifies the signature a hash or short message using
+ * an asymmetric public key in a secure element
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in] key_slot Key slot of a public key or an asymmetric key
+ * pair
+ * \param[in] alg A signature algorithm that is compatible with
+ * the type of `key`
+ * \param[in] p_hash The hash whose signature is to be verified
+ * \param[in] hash_length Size of the `p_hash` buffer in bytes
+ * \param[in] p_signature Buffer containing the signature to verify
+ * \param[in] signature_length Size of the `p_signature` buffer in bytes
+ *
+ * \retval #PSA_SUCCESS
+ * The signature is valid.
+ */
+typedef psa_status_t (*psa_drv_se_asymmetric_verify_t)(psa_drv_se_context_t *drv_context,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t alg,
+ const uint8_t *p_hash,
+ size_t hash_length,
+ const uint8_t *p_signature,
+ size_t signature_length);
+
+/**
+ * \brief A function that encrypts a short message with an asymmetric public
+ * key in a secure element
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in] key_slot Key slot of a public key or an asymmetric key
+ * pair
+ * \param[in] alg An asymmetric encryption algorithm that is
+ * compatible with the type of `key`
+ * \param[in] p_input The message to encrypt
+ * \param[in] input_length Size of the `p_input` buffer in bytes
+ * \param[in] p_salt A salt or label, if supported by the
+ * encryption algorithm
+ * If the algorithm does not support a
+ * salt, pass `NULL`.
+ * If the algorithm supports an optional
+ * salt and you do not want to pass a salt,
+ * pass `NULL`.
+ * For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is
+ * supported.
+ * \param[in] salt_length Size of the `p_salt` buffer in bytes
+ * If `p_salt` is `NULL`, pass 0.
+ * \param[out] p_output Buffer where the encrypted message is to
+ * be written
+ * \param[in] output_size Size of the `p_output` buffer in bytes
+ * \param[out] p_output_length On success, the number of bytes that make up
+ * the returned output
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_asymmetric_encrypt_t)(psa_drv_se_context_t *drv_context,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t alg,
+ const uint8_t *p_input,
+ size_t input_length,
+ const uint8_t *p_salt,
+ size_t salt_length,
+ uint8_t *p_output,
+ size_t output_size,
+ size_t *p_output_length);
+
+/**
+ * \brief A function that decrypts a short message with an asymmetric private
+ * key in a secure element.
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in] key_slot Key slot of an asymmetric key pair
+ * \param[in] alg An asymmetric encryption algorithm that is
+ * compatible with the type of `key`
+ * \param[in] p_input The message to decrypt
+ * \param[in] input_length Size of the `p_input` buffer in bytes
+ * \param[in] p_salt A salt or label, if supported by the
+ * encryption algorithm
+ * If the algorithm does not support a
+ * salt, pass `NULL`.
+ * If the algorithm supports an optional
+ * salt and you do not want to pass a salt,
+ * pass `NULL`.
+ * For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is
+ * supported.
+ * \param[in] salt_length Size of the `p_salt` buffer in bytes
+ * If `p_salt` is `NULL`, pass 0.
+ * \param[out] p_output Buffer where the decrypted message is to
+ * be written
+ * \param[in] output_size Size of the `p_output` buffer in bytes
+ * \param[out] p_output_length On success, the number of bytes
+ * that make up the returned output
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_asymmetric_decrypt_t)(psa_drv_se_context_t *drv_context,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t alg,
+ const uint8_t *p_input,
+ size_t input_length,
+ const uint8_t *p_salt,
+ size_t salt_length,
+ uint8_t *p_output,
+ size_t output_size,
+ size_t *p_output_length);
+
+/**
+ * \brief A struct containing all of the function pointers needed to implement
+ * asymmetric cryptographic operations using secure elements.
+ *
+ * PSA Crypto API implementations should populate instances of the table as
+ * appropriate upon startup or at build time.
+ *
+ * If one of the functions is not implemented, it should be set to NULL.
+ */
+typedef struct {
+ /** Function that performs an asymmetric sign operation */
+ psa_drv_se_asymmetric_sign_t MBEDTLS_PRIVATE(p_sign);
+ /** Function that performs an asymmetric verify operation */
+ psa_drv_se_asymmetric_verify_t MBEDTLS_PRIVATE(p_verify);
+ /** Function that performs an asymmetric encrypt operation */
+ psa_drv_se_asymmetric_encrypt_t MBEDTLS_PRIVATE(p_encrypt);
+ /** Function that performs an asymmetric decrypt operation */
+ psa_drv_se_asymmetric_decrypt_t MBEDTLS_PRIVATE(p_decrypt);
+} psa_drv_se_asymmetric_t;
+
+/**@}*/
+
+/** \defgroup se_aead Secure Element Authenticated Encryption with Additional Data
+ * Authenticated Encryption with Additional Data (AEAD) operations with secure
+ * elements must be done in one function call. While this creates a burden for
+ * implementers as there must be sufficient space in memory for the entire
+ * message, it prevents decrypted data from being made available before the
+ * authentication operation is complete and the data is known to be authentic.
+ */
+/**@{*/
+
+/** \brief A function that performs a secure element authenticated encryption
+ * operation
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in] key_slot Slot containing the key to use.
+ * \param[in] algorithm The AEAD algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(`alg`) is true)
+ * \param[in] p_nonce Nonce or IV to use
+ * \param[in] nonce_length Size of the `p_nonce` buffer in bytes
+ * \param[in] p_additional_data Additional data that will be
+ * authenticated but not encrypted
+ * \param[in] additional_data_length Size of `p_additional_data` in bytes
+ * \param[in] p_plaintext Data that will be authenticated and
+ * encrypted
+ * \param[in] plaintext_length Size of `p_plaintext` in bytes
+ * \param[out] p_ciphertext Output buffer for the authenticated and
+ * encrypted data. The additional data is
+ * not part of this output. For algorithms
+ * where the encrypted data and the
+ * authentication tag are defined as
+ * separate outputs, the authentication
+ * tag is appended to the encrypted data.
+ * \param[in] ciphertext_size Size of the `p_ciphertext` buffer in
+ * bytes
+ * \param[out] p_ciphertext_length On success, the size of the output in
+ * the `p_ciphertext` buffer
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ */
+typedef psa_status_t (*psa_drv_se_aead_encrypt_t)(psa_drv_se_context_t *drv_context,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t algorithm,
+ const uint8_t *p_nonce,
+ size_t nonce_length,
+ const uint8_t *p_additional_data,
+ size_t additional_data_length,
+ const uint8_t *p_plaintext,
+ size_t plaintext_length,
+ uint8_t *p_ciphertext,
+ size_t ciphertext_size,
+ size_t *p_ciphertext_length);
+
+/** A function that performs a secure element authenticated decryption operation
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in] key_slot Slot containing the key to use
+ * \param[in] algorithm The AEAD algorithm to compute
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(`alg`) is true)
+ * \param[in] p_nonce Nonce or IV to use
+ * \param[in] nonce_length Size of the `p_nonce` buffer in bytes
+ * \param[in] p_additional_data Additional data that has been
+ * authenticated but not encrypted
+ * \param[in] additional_data_length Size of `p_additional_data` in bytes
+ * \param[in] p_ciphertext Data that has been authenticated and
+ * encrypted.
+ * For algorithms where the encrypted data
+ * and the authentication tag are defined
+ * as separate inputs, the buffer must
+ * contain the encrypted data followed by
+ * the authentication tag.
+ * \param[in] ciphertext_length Size of `p_ciphertext` in bytes
+ * \param[out] p_plaintext Output buffer for the decrypted data
+ * \param[in] plaintext_size Size of the `p_plaintext` buffer in
+ * bytes
+ * \param[out] p_plaintext_length On success, the size of the output in
+ * the `p_plaintext` buffer
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ */
+typedef psa_status_t (*psa_drv_se_aead_decrypt_t)(psa_drv_se_context_t *drv_context,
+ psa_key_slot_number_t key_slot,
+ psa_algorithm_t algorithm,
+ const uint8_t *p_nonce,
+ size_t nonce_length,
+ const uint8_t *p_additional_data,
+ size_t additional_data_length,
+ const uint8_t *p_ciphertext,
+ size_t ciphertext_length,
+ uint8_t *p_plaintext,
+ size_t plaintext_size,
+ size_t *p_plaintext_length);
+
+/**
+ * \brief A struct containing all of the function pointers needed to implement
+ * secure element Authenticated Encryption with Additional Data operations
+ *
+ * PSA Crypto API implementations should populate instances of the table as
+ * appropriate upon startup.
+ *
+ * If one of the functions is not implemented, it should be set to NULL.
+ */
+typedef struct {
+ /** Function that performs the AEAD encrypt operation */
+ psa_drv_se_aead_encrypt_t MBEDTLS_PRIVATE(p_encrypt);
+ /** Function that performs the AEAD decrypt operation */
+ psa_drv_se_aead_decrypt_t MBEDTLS_PRIVATE(p_decrypt);
+} psa_drv_se_aead_t;
+/**@}*/
+
+/** \defgroup se_key_management Secure Element Key Management
+ * Currently, key management is limited to importing keys in the clear,
+ * destroying keys, and exporting keys in the clear.
+ * Whether a key may be exported is determined by the key policies in place
+ * on the key slot.
+ */
+/**@{*/
+
+/** An enumeration indicating how a key is created.
+ */
+typedef enum {
+ PSA_KEY_CREATION_IMPORT, /**< During psa_import_key() */
+ PSA_KEY_CREATION_GENERATE, /**< During psa_generate_key() */
+ PSA_KEY_CREATION_DERIVE, /**< During psa_key_derivation_output_key() */
+ PSA_KEY_CREATION_COPY, /**< During psa_copy_key() */
+
+#ifndef __DOXYGEN_ONLY__
+ /** A key is being registered with mbedtls_psa_register_se_key().
+ *
+ * The core only passes this value to
+ * psa_drv_se_key_management_t::p_validate_slot_number, not to
+ * psa_drv_se_key_management_t::p_allocate. The call to
+ * `p_validate_slot_number` is not followed by any other call to the
+ * driver: the key is considered successfully registered if the call to
+ * `p_validate_slot_number` succeeds, or if `p_validate_slot_number` is
+ * null.
+ *
+ * With this creation method, the driver must return #PSA_SUCCESS if
+ * the given attributes are compatible with the existing key in the slot,
+ * and #PSA_ERROR_DOES_NOT_EXIST if the driver can determine that there
+ * is no key with the specified slot number.
+ *
+ * This is an Mbed TLS extension.
+ */
+ PSA_KEY_CREATION_REGISTER,
+#endif
+} psa_key_creation_method_t;
+
+/** \brief A function that allocates a slot for a key.
+ *
+ * To create a key in a specific slot in a secure element, the core
+ * first calls this function to determine a valid slot number,
+ * then calls a function to create the key material in that slot.
+ * In nominal conditions (that is, if no error occurs),
+ * the effect of a call to a key creation function in the PSA Cryptography
+ * API with a lifetime that places the key in a secure element is the
+ * following:
+ * -# The core calls psa_drv_se_key_management_t::p_allocate
+ * (or in some implementations
+ * psa_drv_se_key_management_t::p_validate_slot_number). The driver
+ * selects (or validates) a suitable slot number given the key attributes
+ * and the state of the secure element.
+ * -# The core calls a key creation function in the driver.
+ *
+ * The key creation functions in the PSA Cryptography API are:
+ * - psa_import_key(), which causes
+ * a call to `p_allocate` with \p method = #PSA_KEY_CREATION_IMPORT
+ * then a call to psa_drv_se_key_management_t::p_import.
+ * - psa_generate_key(), which causes
+ * a call to `p_allocate` with \p method = #PSA_KEY_CREATION_GENERATE
+ * then a call to psa_drv_se_key_management_t::p_import.
+ * - psa_key_derivation_output_key(), which causes
+ * a call to `p_allocate` with \p method = #PSA_KEY_CREATION_DERIVE
+ * then a call to psa_drv_se_key_derivation_t::p_derive.
+ * - psa_copy_key(), which causes
+ * a call to `p_allocate` with \p method = #PSA_KEY_CREATION_COPY
+ * then a call to psa_drv_se_key_management_t::p_export.
+ *
+ * In case of errors, other behaviors are possible.
+ * - If the PSA Cryptography subsystem dies after the first step,
+ * for example because the device has lost power abruptly,
+ * the second step may never happen, or may happen after a reset
+ * and re-initialization. Alternatively, after a reset and
+ * re-initialization, the core may call
+ * psa_drv_se_key_management_t::p_destroy on the slot number that
+ * was allocated (or validated) instead of calling a key creation function.
+ * - If an error occurs, the core may call
+ * psa_drv_se_key_management_t::p_destroy on the slot number that
+ * was allocated (or validated) instead of calling a key creation function.
+ *
+ * Errors and system resets also have an impact on the driver's persistent
+ * data. If a reset happens before the overall key creation process is
+ * completed (before or after the second step above), it is unspecified
+ * whether the persistent data after the reset is identical to what it
+ * was before or after the call to `p_allocate` (or `p_validate_slot_number`).
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in,out] persistent_data A pointer to the persistent data
+ * that allows writing.
+ * \param[in] attributes Attributes of the key.
+ * \param method The way in which the key is being created.
+ * \param[out] key_slot Slot where the key will be stored.
+ * This must be a valid slot for a key of the
+ * chosen type. It must be unoccupied.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ * The core will record \c *key_slot as the key slot where the key
+ * is stored and will update the persistent data in storage.
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_INSUFFICIENT_STORAGE \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_allocate_key_t)(
+ psa_drv_se_context_t *drv_context,
+ void *persistent_data,
+ const psa_key_attributes_t *attributes,
+ psa_key_creation_method_t method,
+ psa_key_slot_number_t *key_slot);
+
+/** \brief A function that determines whether a slot number is valid
+ * for a key.
+ *
+ * To create a key in a specific slot in a secure element, the core
+ * first calls this function to validate the choice of slot number,
+ * then calls a function to create the key material in that slot.
+ * See the documentation of #psa_drv_se_allocate_key_t for more details.
+ *
+ * As of the PSA Cryptography API specification version 1.0, there is no way
+ * for applications to trigger a call to this function. However some
+ * implementations offer the capability to create or declare a key in
+ * a specific slot via implementation-specific means, generally for the
+ * sake of initial device provisioning or onboarding. Such a mechanism may
+ * be added to a future version of the PSA Cryptography API specification.
+ *
+ * This function may update the driver's persistent data through
+ * \p persistent_data. The core will save the updated persistent data at the
+ * end of the key creation process. See the description of
+ * ::psa_drv_se_allocate_key_t for more information.
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in,out] persistent_data A pointer to the persistent data
+ * that allows writing.
+ * \param[in] attributes Attributes of the key.
+ * \param method The way in which the key is being created.
+ * \param[in] key_slot Slot where the key is to be stored.
+ *
+ * \retval #PSA_SUCCESS
+ * The given slot number is valid for a key with the given
+ * attributes.
+ * \retval #PSA_ERROR_INVALID_ARGUMENT
+ * The given slot number is not valid for a key with the
+ * given attributes. This includes the case where the slot
+ * number is not valid at all.
+ * \retval #PSA_ERROR_ALREADY_EXISTS
+ * There is already a key with the specified slot number.
+ * Drivers may choose to return this error from the key
+ * creation function instead.
+ */
+typedef psa_status_t (*psa_drv_se_validate_slot_number_t)(
+ psa_drv_se_context_t *drv_context,
+ void *persistent_data,
+ const psa_key_attributes_t *attributes,
+ psa_key_creation_method_t method,
+ psa_key_slot_number_t key_slot);
+
+/** \brief A function that imports a key into a secure element in binary format
+ *
+ * This function can support any output from psa_export_key(). Refer to the
+ * documentation of psa_export_key() for the format for each key type.
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param key_slot Slot where the key will be stored.
+ * This must be a valid slot for a key of the
+ * chosen type. It must be unoccupied.
+ * \param[in] attributes The key attributes, including the lifetime,
+ * the key type and the usage policy.
+ * Drivers should not access the key size stored
+ * in the attributes: it may not match the
+ * data passed in \p data.
+ * Drivers can call psa_get_key_lifetime(),
+ * psa_get_key_type(),
+ * psa_get_key_usage_flags() and
+ * psa_get_key_algorithm() to access this
+ * information.
+ * \param[in] data Buffer containing the key data.
+ * \param[in] data_length Size of the \p data buffer in bytes.
+ * \param[out] bits On success, the key size in bits. The driver
+ * must determine this value after parsing the
+ * key according to the key type.
+ * This value is not used if the function fails.
+ *
+ * \retval #PSA_SUCCESS
+ * Success.
+ */
+typedef psa_status_t (*psa_drv_se_import_key_t)(
+ psa_drv_se_context_t *drv_context,
+ psa_key_slot_number_t key_slot,
+ const psa_key_attributes_t *attributes,
+ const uint8_t *data,
+ size_t data_length,
+ size_t *bits);
+
+/**
+ * \brief A function that destroys a secure element key and restore the slot to
+ * its default state
+ *
+ * This function destroys the content of the key from a secure element.
+ * Implementations shall make a best effort to ensure that any previous content
+ * of the slot is unrecoverable.
+ *
+ * This function returns the specified slot to its default state.
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in,out] persistent_data A pointer to the persistent data
+ * that allows writing.
+ * \param key_slot The key slot to erase.
+ *
+ * \retval #PSA_SUCCESS
+ * The slot's content, if any, has been erased.
+ */
+typedef psa_status_t (*psa_drv_se_destroy_key_t)(
+ psa_drv_se_context_t *drv_context,
+ void *persistent_data,
+ psa_key_slot_number_t key_slot);
+
+/**
+ * \brief A function that exports a secure element key in binary format
+ *
+ * The output of this function can be passed to psa_import_key() to
+ * create an equivalent object.
+ *
+ * If a key is created with `psa_import_key()` and then exported with
+ * this function, it is not guaranteed that the resulting data is
+ * identical: the implementation may choose a different representation
+ * of the same key if the format permits it.
+ *
+ * This function should generate output in the same format that
+ * `psa_export_key()` does. Refer to the
+ * documentation of `psa_export_key()` for the format for each key type.
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in] key Slot whose content is to be exported. This must
+ * be an occupied key slot.
+ * \param[out] p_data Buffer where the key data is to be written.
+ * \param[in] data_size Size of the `p_data` buffer in bytes.
+ * \param[out] p_data_length On success, the number of bytes
+ * that make up the key data.
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ * \retval #PSA_ERROR_DOES_NOT_EXIST \emptydescription
+ * \retval #PSA_ERROR_NOT_PERMITTED \emptydescription
+ * \retval #PSA_ERROR_NOT_SUPPORTED \emptydescription
+ * \retval #PSA_ERROR_COMMUNICATION_FAILURE \emptydescription
+ * \retval #PSA_ERROR_HARDWARE_FAILURE \emptydescription
+ * \retval #PSA_ERROR_CORRUPTION_DETECTED \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_export_key_t)(psa_drv_se_context_t *drv_context,
+ psa_key_slot_number_t key,
+ uint8_t *p_data,
+ size_t data_size,
+ size_t *p_data_length);
+
+/**
+ * \brief A function that generates a symmetric or asymmetric key on a secure
+ * element
+ *
+ * If the key type \c type recorded in \p attributes
+ * is asymmetric (#PSA_KEY_TYPE_IS_ASYMMETRIC(\c type) = 1),
+ * the driver may export the public key at the time of generation,
+ * in the format documented for psa_export_public_key() by writing it
+ * to the \p pubkey buffer.
+ * This is optional, intended for secure elements that output the
+ * public key at generation time and that cannot export the public key
+ * later. Drivers that do not need this feature should leave
+ * \p *pubkey_length set to 0 and should
+ * implement the psa_drv_key_management_t::p_export_public function.
+ * Some implementations do not support this feature, in which case
+ * \p pubkey is \c NULL and \p pubkey_size is 0.
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param key_slot Slot where the key will be stored.
+ * This must be a valid slot for a key of the
+ * chosen type. It must be unoccupied.
+ * \param[in] attributes The key attributes, including the lifetime,
+ * the key type and size, and the usage policy.
+ * Drivers can call psa_get_key_lifetime(),
+ * psa_get_key_type(), psa_get_key_bits(),
+ * psa_get_key_usage_flags() and
+ * psa_get_key_algorithm() to access this
+ * information.
+ * \param[out] pubkey A buffer where the driver can write the
+ * public key, when generating an asymmetric
+ * key pair.
+ * This is \c NULL when generating a symmetric
+ * key or if the core does not support
+ * exporting the public key at generation time.
+ * \param pubkey_size The size of the `pubkey` buffer in bytes.
+ * This is 0 when generating a symmetric
+ * key or if the core does not support
+ * exporting the public key at generation time.
+ * \param[out] pubkey_length On entry, this is always 0.
+ * On success, the number of bytes written to
+ * \p pubkey. If this is 0 or unchanged on return,
+ * the core will not read the \p pubkey buffer,
+ * and will instead call the driver's
+ * psa_drv_key_management_t::p_export_public
+ * function to export the public key when needed.
+ */
+typedef psa_status_t (*psa_drv_se_generate_key_t)(
+ psa_drv_se_context_t *drv_context,
+ psa_key_slot_number_t key_slot,
+ const psa_key_attributes_t *attributes,
+ uint8_t *pubkey, size_t pubkey_size, size_t *pubkey_length);
+
+/**
+ * \brief A struct containing all of the function pointers needed to for secure
+ * element key management
+ *
+ * PSA Crypto API implementations should populate instances of the table as
+ * appropriate upon startup or at build time.
+ *
+ * If one of the functions is not implemented, it should be set to NULL.
+ */
+typedef struct {
+ /** Function that allocates a slot for a key. */
+ psa_drv_se_allocate_key_t MBEDTLS_PRIVATE(p_allocate);
+ /** Function that checks the validity of a slot for a key. */
+ psa_drv_se_validate_slot_number_t MBEDTLS_PRIVATE(p_validate_slot_number);
+ /** Function that performs a key import operation */
+ psa_drv_se_import_key_t MBEDTLS_PRIVATE(p_import);
+ /** Function that performs a generation */
+ psa_drv_se_generate_key_t MBEDTLS_PRIVATE(p_generate);
+ /** Function that performs a key destroy operation */
+ psa_drv_se_destroy_key_t MBEDTLS_PRIVATE(p_destroy);
+ /** Function that performs a key export operation */
+ psa_drv_se_export_key_t MBEDTLS_PRIVATE(p_export);
+ /** Function that performs a public key export operation */
+ psa_drv_se_export_key_t MBEDTLS_PRIVATE(p_export_public);
+} psa_drv_se_key_management_t;
+
+/**@}*/
+
+/** \defgroup driver_derivation Secure Element Key Derivation and Agreement
+ * Key derivation is the process of generating new key material using an
+ * existing key and additional parameters, iterating through a basic
+ * cryptographic function, such as a hash.
+ * Key agreement is a part of cryptographic protocols that allows two parties
+ * to agree on the same key value, but starting from different original key
+ * material.
+ * The flows are similar, and the PSA Crypto Driver Model uses the same functions
+ * for both of the flows.
+ *
+ * There are two different final functions for the flows,
+ * `psa_drv_se_key_derivation_derive` and `psa_drv_se_key_derivation_export`.
+ * `psa_drv_se_key_derivation_derive` is used when the key material should be
+ * placed in a slot on the hardware and not exposed to the caller.
+ * `psa_drv_se_key_derivation_export` is used when the key material should be
+ * returned to the PSA Cryptographic API implementation.
+ *
+ * Different key derivation algorithms require a different number of inputs.
+ * Instead of having an API that takes as input variable length arrays, which
+ * can be problematic to manage on embedded platforms, the inputs are passed
+ * to the driver via a function, `psa_drv_se_key_derivation_collateral`, that
+ * is called multiple times with different `collateral_id`s. Thus, for a key
+ * derivation algorithm that required 3 parameter inputs, the flow would look
+ * something like:
+ * ~~~~~~~~~~~~~{.c}
+ * psa_drv_se_key_derivation_setup(kdf_algorithm, source_key, dest_key_size_bytes);
+ * psa_drv_se_key_derivation_collateral(kdf_algorithm_collateral_id_0,
+ * p_collateral_0,
+ * collateral_0_size);
+ * psa_drv_se_key_derivation_collateral(kdf_algorithm_collateral_id_1,
+ * p_collateral_1,
+ * collateral_1_size);
+ * psa_drv_se_key_derivation_collateral(kdf_algorithm_collateral_id_2,
+ * p_collateral_2,
+ * collateral_2_size);
+ * psa_drv_se_key_derivation_derive();
+ * ~~~~~~~~~~~~~
+ *
+ * key agreement example:
+ * ~~~~~~~~~~~~~{.c}
+ * psa_drv_se_key_derivation_setup(alg, source_key. dest_key_size_bytes);
+ * psa_drv_se_key_derivation_collateral(DHE_PUBKEY, p_pubkey, pubkey_size);
+ * psa_drv_se_key_derivation_export(p_session_key,
+ * session_key_size,
+ * &session_key_length);
+ * ~~~~~~~~~~~~~
+ */
+/**@{*/
+
+/** \brief A function that Sets up a secure element key derivation operation by
+ * specifying the algorithm and the source key sot
+ *
+ * \param[in,out] drv_context The driver context structure.
+ * \param[in,out] op_context A hardware-specific structure containing any
+ * context information for the implementation
+ * \param[in] kdf_alg The algorithm to be used for the key derivation
+ * \param[in] source_key The key to be used as the source material for
+ * the key derivation
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_key_derivation_setup_t)(psa_drv_se_context_t *drv_context,
+ void *op_context,
+ psa_algorithm_t kdf_alg,
+ psa_key_slot_number_t source_key);
+
+/** \brief A function that provides collateral (parameters) needed for a secure
+ * element key derivation or key agreement operation
+ *
+ * Since many key derivation algorithms require multiple parameters, it is
+ * expected that this function may be called multiple times for the same
+ * operation, each with a different algorithm-specific `collateral_id`
+ *
+ * \param[in,out] op_context A hardware-specific structure containing any
+ * context information for the implementation
+ * \param[in] collateral_id An ID for the collateral being provided
+ * \param[in] p_collateral A buffer containing the collateral data
+ * \param[in] collateral_size The size in bytes of the collateral
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_key_derivation_collateral_t)(void *op_context,
+ uint32_t collateral_id,
+ const uint8_t *p_collateral,
+ size_t collateral_size);
+
+/** \brief A function that performs the final secure element key derivation
+ * step and place the generated key material in a slot
+ *
+ * \param[in,out] op_context A hardware-specific structure containing any
+ * context information for the implementation
+ * \param[in] dest_key The slot where the generated key material
+ * should be placed
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_key_derivation_derive_t)(void *op_context,
+ psa_key_slot_number_t dest_key);
+
+/** \brief A function that performs the final step of a secure element key
+ * agreement and place the generated key material in a buffer
+ *
+ * \param[out] p_output Buffer in which to place the generated key
+ * material
+ * \param[in] output_size The size in bytes of `p_output`
+ * \param[out] p_output_length Upon success, contains the number of bytes of
+ * key material placed in `p_output`
+ *
+ * \retval #PSA_SUCCESS \emptydescription
+ */
+typedef psa_status_t (*psa_drv_se_key_derivation_export_t)(void *op_context,
+ uint8_t *p_output,
+ size_t output_size,
+ size_t *p_output_length);
+
+/**
+ * \brief A struct containing all of the function pointers needed to for secure
+ * element key derivation and agreement
+ *
+ * PSA Crypto API implementations should populate instances of the table as
+ * appropriate upon startup.
+ *
+ * If one of the functions is not implemented, it should be set to NULL.
+ */
+typedef struct {
+ /** The driver-specific size of the key derivation context */
+ size_t MBEDTLS_PRIVATE(context_size);
+ /** Function that performs a key derivation setup */
+ psa_drv_se_key_derivation_setup_t MBEDTLS_PRIVATE(p_setup);
+ /** Function that sets key derivation collateral */
+ psa_drv_se_key_derivation_collateral_t MBEDTLS_PRIVATE(p_collateral);
+ /** Function that performs a final key derivation step */
+ psa_drv_se_key_derivation_derive_t MBEDTLS_PRIVATE(p_derive);
+ /** Function that performs a final key derivation or agreement and
+ * exports the key */
+ psa_drv_se_key_derivation_export_t MBEDTLS_PRIVATE(p_export);
+} psa_drv_se_key_derivation_t;
+
+/**@}*/
+
+/** \defgroup se_registration Secure element driver registration
+ */
+/**@{*/
+
+/** A structure containing pointers to all the entry points of a
+ * secure element driver.
+ *
+ * Future versions of this specification may add extra substructures at
+ * the end of this structure.
+ */
+typedef struct {
+ /** The version of the driver HAL that this driver implements.
+ * This is a protection against loading driver binaries built against
+ * a different version of this specification.
+ * Use #PSA_DRV_SE_HAL_VERSION.
+ */
+ uint32_t MBEDTLS_PRIVATE(hal_version);
+
+ /** The size of the driver's persistent data in bytes.
+ *
+ * This can be 0 if the driver does not need persistent data.
+ *
+ * See the documentation of psa_drv_se_context_t::persistent_data
+ * for more information about why and how a driver can use
+ * persistent data.
+ */
+ size_t MBEDTLS_PRIVATE(persistent_data_size);
+
+ /** The driver initialization function.
+ *
+ * This function is called once during the initialization of the
+ * PSA Cryptography subsystem, before any other function of the
+ * driver is called. If this function returns a failure status,
+ * the driver will be unusable, at least until the next system reset.
+ *
+ * If this field is \c NULL, it is equivalent to a function that does
+ * nothing and returns #PSA_SUCCESS.
+ */
+ psa_drv_se_init_t MBEDTLS_PRIVATE(p_init);
+
+ const psa_drv_se_key_management_t *MBEDTLS_PRIVATE(key_management);
+ const psa_drv_se_mac_t *MBEDTLS_PRIVATE(mac);
+ const psa_drv_se_cipher_t *MBEDTLS_PRIVATE(cipher);
+ const psa_drv_se_aead_t *MBEDTLS_PRIVATE(aead);
+ const psa_drv_se_asymmetric_t *MBEDTLS_PRIVATE(asymmetric);
+ const psa_drv_se_key_derivation_t *MBEDTLS_PRIVATE(derivation);
+} psa_drv_se_t;
+
+/** The current version of the secure element driver HAL.
+ */
+/* 0.0.0 patchlevel 5 */
+#define PSA_DRV_SE_HAL_VERSION 0x00000005
+
+/** Register an external cryptoprocessor (secure element) driver.
+ *
+ * This function is only intended to be used by driver code, not by
+ * application code. In implementations with separation between the
+ * PSA cryptography module and applications, this function should
+ * only be available to callers that run in the same memory space as
+ * the cryptography module, and should not be exposed to applications
+ * running in a different memory space.
+ *
+ * This function may be called before psa_crypto_init(). It is
+ * implementation-defined whether this function may be called
+ * after psa_crypto_init().
+ *
+ * \note Implementations store metadata about keys including the lifetime
+ * value, which contains the driver's location indicator. Therefore,
+ * from one instantiation of the PSA Cryptography
+ * library to the next one, if there is a key in storage with a certain
+ * lifetime value, you must always register the same driver (or an
+ * updated version that communicates with the same secure element)
+ * with the same location value.
+ *
+ * \param location The location value through which this driver will
+ * be exposed to applications.
+ * This driver will be used for all keys such that
+ * `location == #PSA_KEY_LIFETIME_GET_LOCATION( lifetime )`.
+ * The value #PSA_KEY_LOCATION_LOCAL_STORAGE is reserved
+ * and may not be used for drivers. Implementations
+ * may reserve other values.
+ * \param[in] methods The method table of the driver. This structure must
+ * remain valid for as long as the cryptography
+ * module keeps running. It is typically a global
+ * constant.
+ *
+ * \return #PSA_SUCCESS
+ * The driver was successfully registered. Applications can now
+ * use \p location to access keys through the methods passed to
+ * this function.
+ * \return #PSA_ERROR_BAD_STATE
+ * This function was called after the initialization of the
+ * cryptography module, and this implementation does not support
+ * driver registration at this stage.
+ * \return #PSA_ERROR_ALREADY_EXISTS
+ * There is already a registered driver for this value of \p location.
+ * \return #PSA_ERROR_INVALID_ARGUMENT
+ * \p location is a reserved value.
+ * \return #PSA_ERROR_NOT_SUPPORTED
+ * `methods->hal_version` is not supported by this implementation.
+ * \return #PSA_ERROR_INSUFFICIENT_MEMORY
+ * \return #PSA_ERROR_NOT_PERMITTED
+ * \return #PSA_ERROR_STORAGE_FAILURE
+ * \return #PSA_ERROR_DATA_CORRUPT
+ */
+psa_status_t psa_register_se_driver(
+ psa_key_location_t location,
+ const psa_drv_se_t *methods);
+
+/**@}*/
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PSA_CRYPTO_SE_DRIVER_H */
diff --git a/include/psa/crypto_sizes.h b/include/psa/crypto_sizes.h
new file mode 100644
index 0000000..d22bf10
--- /dev/null
+++ b/include/psa/crypto_sizes.h
@@ -0,0 +1,1282 @@
+/**
+ * \file psa/crypto_sizes.h
+ *
+ * \brief PSA cryptography module: Mbed TLS buffer size macros
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ *
+ * This file contains the definitions of macros that are useful to
+ * compute buffer sizes. The signatures and semantics of these macros
+ * are standardized, but the definitions are not, because they depend on
+ * the available algorithms and, in some cases, on permitted tolerances
+ * on buffer sizes.
+ *
+ * In implementations with isolation between the application and the
+ * cryptography module, implementers should take care to ensure that
+ * the definitions that are exposed to applications match what the
+ * module implements.
+ *
+ * Macros that compute sizes whose values do not depend on the
+ * implementation are in crypto.h.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_SIZES_H
+#define PSA_CRYPTO_SIZES_H
+
+/*
+ * Include the build-time configuration information file. Here, we do not
+ * include `"mbedtls/build_info.h"` directly but `"psa/build_info.h"`, which
+ * is basically just an alias to it. This is to ease the maintenance of the
+ * PSA cryptography repository which has a different build system and
+ * configuration.
+ */
+#include "psa/build_info.h"
+
+#define PSA_BITS_TO_BYTES(bits) (((bits) + 7u) / 8u)
+#define PSA_BYTES_TO_BITS(bytes) ((bytes) * 8u)
+#define PSA_MAX_OF_THREE(a, b, c) ((a) <= (b) ? (b) <= (c) ? \
+ (c) : (b) : (a) <= (c) ? (c) : (a))
+
+#define PSA_ROUND_UP_TO_MULTIPLE(block_size, length) \
+ (((length) + (block_size) - 1) / (block_size) * (block_size))
+
+/** The size of the output of psa_hash_finish(), in bytes.
+ *
+ * This is also the hash size that psa_hash_verify() expects.
+ *
+ * \param alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p alg) is true), or an HMAC algorithm
+ * (#PSA_ALG_HMAC(\c hash_alg) where \c hash_alg is a
+ * hash algorithm).
+ *
+ * \return The hash size for the specified hash algorithm.
+ * If the hash algorithm is not recognized, return 0.
+ */
+#define PSA_HASH_LENGTH(alg) \
+ ( \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_MD5 ? 16u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_RIPEMD160 ? 20u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_1 ? 20u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_224 ? 28u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_256 ? 32u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_384 ? 48u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512 ? 64u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512_224 ? 28u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512_256 ? 32u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_224 ? 28u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_256 ? 32u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_384 ? 48u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_512 ? 64u : \
+ 0u)
+
+/** The input block size of a hash algorithm, in bytes.
+ *
+ * Hash algorithms process their input data in blocks. Hash operations will
+ * retain any partial blocks until they have enough input to fill the block or
+ * until the operation is finished.
+ * This affects the output from psa_hash_suspend().
+ *
+ * \param alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * PSA_ALG_IS_HASH(\p alg) is true).
+ *
+ * \return The block size in bytes for the specified hash algorithm.
+ * If the hash algorithm is not recognized, return 0.
+ * An implementation can return either 0 or the correct size for a
+ * hash algorithm that it recognizes, but does not support.
+ */
+#define PSA_HASH_BLOCK_LENGTH(alg) \
+ ( \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_MD5 ? 64u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_RIPEMD160 ? 64u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_1 ? 64u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_224 ? 64u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_256 ? 64u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_384 ? 128u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512 ? 128u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512_224 ? 128u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512_256 ? 128u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_224 ? 144u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_256 ? 136u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_384 ? 104u : \
+ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_512 ? 72u : \
+ 0u)
+
+/** \def PSA_HASH_MAX_SIZE
+ *
+ * Maximum size of a hash.
+ *
+ * This macro expands to a compile-time constant integer. This value
+ * is the maximum size of a hash in bytes.
+ */
+/* Note: for HMAC-SHA-3, the block size is 144 bytes for HMAC-SHA3-224,
+ * 136 bytes for HMAC-SHA3-256, 104 bytes for SHA3-384, 72 bytes for
+ * HMAC-SHA3-512. */
+/* Note: PSA_HASH_MAX_SIZE should be kept in sync with MBEDTLS_MD_MAX_SIZE,
+ * see the note on MBEDTLS_MD_MAX_SIZE for details. */
+#if defined(PSA_WANT_ALG_SHA3_224)
+#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 144u
+#elif defined(PSA_WANT_ALG_SHA3_256)
+#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 136u
+#elif defined(PSA_WANT_ALG_SHA_512)
+#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 128u
+#elif defined(PSA_WANT_ALG_SHA_384)
+#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 128u
+#elif defined(PSA_WANT_ALG_SHA3_384)
+#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 104u
+#elif defined(PSA_WANT_ALG_SHA3_512)
+#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 72u
+#elif defined(PSA_WANT_ALG_SHA_256)
+#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 64u
+#elif defined(PSA_WANT_ALG_SHA_224)
+#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 64u
+#else /* SHA-1 or smaller */
+#define PSA_HMAC_MAX_HASH_BLOCK_SIZE 64u
+#endif
+
+#if defined(PSA_WANT_ALG_SHA_512) || defined(PSA_WANT_ALG_SHA3_512)
+#define PSA_HASH_MAX_SIZE 64u
+#elif defined(PSA_WANT_ALG_SHA_384) || defined(PSA_WANT_ALG_SHA3_384)
+#define PSA_HASH_MAX_SIZE 48u
+#elif defined(PSA_WANT_ALG_SHA_256) || defined(PSA_WANT_ALG_SHA3_256)
+#define PSA_HASH_MAX_SIZE 32u
+#elif defined(PSA_WANT_ALG_SHA_224) || defined(PSA_WANT_ALG_SHA3_224)
+#define PSA_HASH_MAX_SIZE 28u
+#else /* SHA-1 or smaller */
+#define PSA_HASH_MAX_SIZE 20u
+#endif
+
+/** \def PSA_MAC_MAX_SIZE
+ *
+ * Maximum size of a MAC.
+ *
+ * This macro expands to a compile-time constant integer. This value
+ * is the maximum size of a MAC in bytes.
+ */
+/* All non-HMAC MACs have a maximum size that's smaller than the
+ * minimum possible value of PSA_HASH_MAX_SIZE in this implementation. */
+/* Note that the encoding of truncated MAC algorithms limits this value
+ * to 64 bytes.
+ */
+#define PSA_MAC_MAX_SIZE PSA_HASH_MAX_SIZE
+
+/** The length of a tag for an AEAD algorithm, in bytes.
+ *
+ * This macro can be used to allocate a buffer of sufficient size to store the
+ * tag output from psa_aead_finish().
+ *
+ * See also #PSA_AEAD_TAG_MAX_SIZE.
+ *
+ * \param key_type The type of the AEAD key.
+ * \param key_bits The size of the AEAD key in bits.
+ * \param alg An AEAD algorithm
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ *
+ * \return The tag length for the specified algorithm and key.
+ * If the AEAD algorithm does not have an identified
+ * tag that can be distinguished from the rest of
+ * the ciphertext, return 0.
+ * If the key type or AEAD algorithm is not
+ * recognized, or the parameters are incompatible,
+ * return 0.
+ */
+#define PSA_AEAD_TAG_LENGTH(key_type, key_bits, alg) \
+ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 ? \
+ PSA_ALG_AEAD_GET_TAG_LENGTH(alg) : \
+ ((void) (key_bits), 0u))
+
+/** The maximum tag size for all supported AEAD algorithms, in bytes.
+ *
+ * See also #PSA_AEAD_TAG_LENGTH(\p key_type, \p key_bits, \p alg).
+ */
+#define PSA_AEAD_TAG_MAX_SIZE 16u
+
+/* The maximum size of an RSA key on this implementation, in bits.
+ * This is a vendor-specific macro.
+ *
+ * Mbed TLS does not set a hard limit on the size of RSA keys: any key
+ * whose parameters fit in a bignum is accepted. However large keys can
+ * induce a large memory usage and long computation times. Unlike other
+ * auxiliary macros in this file and in crypto.h, which reflect how the
+ * library is configured, this macro defines how the library is
+ * configured. This implementation refuses to import or generate an
+ * RSA key whose size is larger than the value defined here.
+ *
+ * Note that an implementation may set different size limits for different
+ * operations, and does not need to accept all key sizes up to the limit. */
+#define PSA_VENDOR_RSA_MAX_KEY_BITS 4096u
+
+/* The minimum size of an RSA key on this implementation, in bits.
+ * This is a vendor-specific macro.
+ *
+ * Limits RSA key generation to a minimum due to avoid accidental misuse.
+ * This value cannot be less than 128 bits.
+ */
+#if defined(MBEDTLS_RSA_GEN_KEY_MIN_BITS)
+#define PSA_VENDOR_RSA_GENERATE_MIN_KEY_BITS MBEDTLS_RSA_GEN_KEY_MIN_BITS
+#else
+#define PSA_VENDOR_RSA_GENERATE_MIN_KEY_BITS 1024
+#endif
+
+/* The maximum size of an DH key on this implementation, in bits.
+ *
+ * Note that an implementation may set different size limits for different
+ * operations, and does not need to accept all key sizes up to the limit. */
+#define PSA_VENDOR_FFDH_MAX_KEY_BITS 8192u
+
+/* The maximum size of an ECC key on this implementation, in bits.
+ * This is a vendor-specific macro. */
+#if defined(PSA_WANT_ECC_SECP_R1_521)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 521u
+#elif defined(PSA_WANT_ECC_BRAINPOOL_P_R1_512)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 512u
+#elif defined(PSA_WANT_ECC_MONTGOMERY_448)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 448u
+#elif defined(PSA_WANT_ECC_SECP_R1_384)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 384u
+#elif defined(PSA_WANT_ECC_BRAINPOOL_P_R1_384)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 384u
+#elif defined(PSA_WANT_ECC_SECP_R1_256)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 256u
+#elif defined(PSA_WANT_ECC_SECP_K1_256)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 256u
+#elif defined(PSA_WANT_ECC_BRAINPOOL_P_R1_256)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 256u
+#elif defined(PSA_WANT_ECC_MONTGOMERY_255)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 255u
+#elif defined(PSA_WANT_ECC_SECP_R1_224)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 224u
+#elif defined(PSA_WANT_ECC_SECP_K1_224)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 224u
+#elif defined(PSA_WANT_ECC_SECP_R1_192)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 192u
+#elif defined(PSA_WANT_ECC_SECP_K1_192)
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 192u
+#else
+#define PSA_VENDOR_ECC_MAX_CURVE_BITS 0u
+#endif
+
+/** This macro returns the maximum supported length of the PSK for the
+ * TLS-1.2 PSK-to-MS key derivation
+ * (#PSA_ALG_TLS12_PSK_TO_MS(\c hash_alg)).
+ *
+ * The maximum supported length does not depend on the chosen hash algorithm.
+ *
+ * Quoting RFC 4279, Sect 5.3:
+ * TLS implementations supporting these ciphersuites MUST support
+ * arbitrary PSK identities up to 128 octets in length, and arbitrary
+ * PSKs up to 64 octets in length. Supporting longer identities and
+ * keys is RECOMMENDED.
+ *
+ * Therefore, no implementation should define a value smaller than 64
+ * for #PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE.
+ */
+#define PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE 128u
+
+/* The expected size of input passed to psa_tls12_ecjpake_to_pms_input,
+ * which is expected to work with P-256 curve only. */
+#define PSA_TLS12_ECJPAKE_TO_PMS_INPUT_SIZE 65u
+
+/* The size of a serialized K.X coordinate to be used in
+ * psa_tls12_ecjpake_to_pms_input. This function only accepts the P-256
+ * curve. */
+#define PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE 32u
+
+/* The maximum number of iterations for PBKDF2 on this implementation, in bits.
+ * This is a vendor-specific macro. This can be configured if necessary */
+#define PSA_VENDOR_PBKDF2_MAX_ITERATIONS 0xffffffffU
+
+/** The maximum size of a block cipher. */
+#define PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE 16u
+
+/** The size of the output of psa_mac_sign_finish(), in bytes.
+ *
+ * This is also the MAC size that psa_mac_verify_finish() expects.
+ *
+ * \warning This macro may evaluate its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \param key_type The type of the MAC key.
+ * \param key_bits The size of the MAC key in bits.
+ * \param alg A MAC algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_MAC(\p alg) is true).
+ *
+ * \return The MAC size for the specified algorithm with
+ * the specified key parameters.
+ * \return 0 if the MAC algorithm is not recognized.
+ * \return Either 0 or the correct size for a MAC algorithm that
+ * the implementation recognizes, but does not support.
+ * \return Unspecified if the key parameters are not consistent
+ * with the algorithm.
+ */
+#define PSA_MAC_LENGTH(key_type, key_bits, alg) \
+ ((alg) & PSA_ALG_MAC_TRUNCATION_MASK ? PSA_MAC_TRUNCATED_LENGTH(alg) : \
+ PSA_ALG_IS_HMAC(alg) ? PSA_HASH_LENGTH(PSA_ALG_HMAC_GET_HASH(alg)) : \
+ PSA_ALG_IS_BLOCK_CIPHER_MAC(alg) ? PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) : \
+ ((void) (key_type), (void) (key_bits), 0u))
+
+/** The maximum size of the output of psa_aead_encrypt(), in bytes.
+ *
+ * If the size of the ciphertext buffer is at least this large, it is
+ * guaranteed that psa_aead_encrypt() will not fail due to an
+ * insufficient buffer size. Depending on the algorithm, the actual size of
+ * the ciphertext may be smaller.
+ *
+ * See also #PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(\p plaintext_length).
+ *
+ * \warning This macro may evaluate its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \param key_type A symmetric key type that is
+ * compatible with algorithm \p alg.
+ * \param alg An AEAD algorithm
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ * \param plaintext_length Size of the plaintext in bytes.
+ *
+ * \return The AEAD ciphertext size for the specified
+ * algorithm.
+ * If the key type or AEAD algorithm is not
+ * recognized, or the parameters are incompatible,
+ * return 0.
+ */
+#define PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, alg, plaintext_length) \
+ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 ? \
+ (plaintext_length) + PSA_ALG_AEAD_GET_TAG_LENGTH(alg) : \
+ 0u)
+
+/** A sufficient output buffer size for psa_aead_encrypt(), for any of the
+ * supported key types and AEAD algorithms.
+ *
+ * If the size of the ciphertext buffer is at least this large, it is guaranteed
+ * that psa_aead_encrypt() will not fail due to an insufficient buffer size.
+ *
+ * \note This macro returns a compile-time constant if its arguments are
+ * compile-time constants.
+ *
+ * See also #PSA_AEAD_ENCRYPT_OUTPUT_SIZE(\p key_type, \p alg,
+ * \p plaintext_length).
+ *
+ * \param plaintext_length Size of the plaintext in bytes.
+ *
+ * \return A sufficient output buffer size for any of the
+ * supported key types and AEAD algorithms.
+ *
+ */
+#define PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(plaintext_length) \
+ ((plaintext_length) + PSA_AEAD_TAG_MAX_SIZE)
+
+
+/** The maximum size of the output of psa_aead_decrypt(), in bytes.
+ *
+ * If the size of the plaintext buffer is at least this large, it is
+ * guaranteed that psa_aead_decrypt() will not fail due to an
+ * insufficient buffer size. Depending on the algorithm, the actual size of
+ * the plaintext may be smaller.
+ *
+ * See also #PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(\p ciphertext_length).
+ *
+ * \warning This macro may evaluate its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \param key_type A symmetric key type that is
+ * compatible with algorithm \p alg.
+ * \param alg An AEAD algorithm
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ * \param ciphertext_length Size of the plaintext in bytes.
+ *
+ * \return The AEAD ciphertext size for the specified
+ * algorithm.
+ * If the key type or AEAD algorithm is not
+ * recognized, or the parameters are incompatible,
+ * return 0.
+ */
+#define PSA_AEAD_DECRYPT_OUTPUT_SIZE(key_type, alg, ciphertext_length) \
+ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 && \
+ (ciphertext_length) > PSA_ALG_AEAD_GET_TAG_LENGTH(alg) ? \
+ (ciphertext_length) - PSA_ALG_AEAD_GET_TAG_LENGTH(alg) : \
+ 0u)
+
+/** A sufficient output buffer size for psa_aead_decrypt(), for any of the
+ * supported key types and AEAD algorithms.
+ *
+ * If the size of the plaintext buffer is at least this large, it is guaranteed
+ * that psa_aead_decrypt() will not fail due to an insufficient buffer size.
+ *
+ * \note This macro returns a compile-time constant if its arguments are
+ * compile-time constants.
+ *
+ * See also #PSA_AEAD_DECRYPT_OUTPUT_SIZE(\p key_type, \p alg,
+ * \p ciphertext_length).
+ *
+ * \param ciphertext_length Size of the ciphertext in bytes.
+ *
+ * \return A sufficient output buffer size for any of the
+ * supported key types and AEAD algorithms.
+ *
+ */
+#define PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(ciphertext_length) \
+ (ciphertext_length)
+
+/** The default nonce size for an AEAD algorithm, in bytes.
+ *
+ * This macro can be used to allocate a buffer of sufficient size to
+ * store the nonce output from #psa_aead_generate_nonce().
+ *
+ * See also #PSA_AEAD_NONCE_MAX_SIZE.
+ *
+ * \note This is not the maximum size of nonce supported as input to
+ * #psa_aead_set_nonce(), #psa_aead_encrypt() or #psa_aead_decrypt(),
+ * just the default size that is generated by #psa_aead_generate_nonce().
+ *
+ * \warning This macro may evaluate its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \param key_type A symmetric key type that is compatible with
+ * algorithm \p alg.
+ *
+ * \param alg An AEAD algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ *
+ * \return The default nonce size for the specified key type and algorithm.
+ * If the key type or AEAD algorithm is not recognized,
+ * or the parameters are incompatible, return 0.
+ */
+#define PSA_AEAD_NONCE_LENGTH(key_type, alg) \
+ (PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) == 16 ? \
+ MBEDTLS_PSA_ALG_AEAD_EQUAL(alg, PSA_ALG_CCM) ? 13u : \
+ MBEDTLS_PSA_ALG_AEAD_EQUAL(alg, PSA_ALG_GCM) ? 12u : \
+ 0u : \
+ (key_type) == PSA_KEY_TYPE_CHACHA20 && \
+ MBEDTLS_PSA_ALG_AEAD_EQUAL(alg, PSA_ALG_CHACHA20_POLY1305) ? 12u : \
+ 0u)
+
+/** The maximum default nonce size among all supported pairs of key types and
+ * AEAD algorithms, in bytes.
+ *
+ * This is equal to or greater than any value that #PSA_AEAD_NONCE_LENGTH()
+ * may return.
+ *
+ * \note This is not the maximum size of nonce supported as input to
+ * #psa_aead_set_nonce(), #psa_aead_encrypt() or #psa_aead_decrypt(),
+ * just the largest size that may be generated by
+ * #psa_aead_generate_nonce().
+ */
+#define PSA_AEAD_NONCE_MAX_SIZE 13u
+
+/** A sufficient output buffer size for psa_aead_update().
+ *
+ * If the size of the output buffer is at least this large, it is
+ * guaranteed that psa_aead_update() will not fail due to an
+ * insufficient buffer size. The actual size of the output may be smaller
+ * in any given call.
+ *
+ * See also #PSA_AEAD_UPDATE_OUTPUT_MAX_SIZE(\p input_length).
+ *
+ * \warning This macro may evaluate its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \param key_type A symmetric key type that is
+ * compatible with algorithm \p alg.
+ * \param alg An AEAD algorithm
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ * \param input_length Size of the input in bytes.
+ *
+ * \return A sufficient output buffer size for the specified
+ * algorithm.
+ * If the key type or AEAD algorithm is not
+ * recognized, or the parameters are incompatible,
+ * return 0.
+ */
+/* For all the AEAD modes defined in this specification, it is possible
+ * to emit output without delay. However, hardware may not always be
+ * capable of this. So for modes based on a block cipher, allow the
+ * implementation to delay the output until it has a full block. */
+#define PSA_AEAD_UPDATE_OUTPUT_SIZE(key_type, alg, input_length) \
+ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 ? \
+ PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER(alg) ? \
+ PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type), (input_length)) : \
+ (input_length) : \
+ 0u)
+
+/** A sufficient output buffer size for psa_aead_update(), for any of the
+ * supported key types and AEAD algorithms.
+ *
+ * If the size of the output buffer is at least this large, it is guaranteed
+ * that psa_aead_update() will not fail due to an insufficient buffer size.
+ *
+ * See also #PSA_AEAD_UPDATE_OUTPUT_SIZE(\p key_type, \p alg, \p input_length).
+ *
+ * \param input_length Size of the input in bytes.
+ */
+#define PSA_AEAD_UPDATE_OUTPUT_MAX_SIZE(input_length) \
+ (PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE, (input_length)))
+
+/** A sufficient ciphertext buffer size for psa_aead_finish().
+ *
+ * If the size of the ciphertext buffer is at least this large, it is
+ * guaranteed that psa_aead_finish() will not fail due to an
+ * insufficient ciphertext buffer size. The actual size of the output may
+ * be smaller in any given call.
+ *
+ * See also #PSA_AEAD_FINISH_OUTPUT_MAX_SIZE.
+ *
+ * \param key_type A symmetric key type that is
+ compatible with algorithm \p alg.
+ * \param alg An AEAD algorithm
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ *
+ * \return A sufficient ciphertext buffer size for the
+ * specified algorithm.
+ * If the key type or AEAD algorithm is not
+ * recognized, or the parameters are incompatible,
+ * return 0.
+ */
+#define PSA_AEAD_FINISH_OUTPUT_SIZE(key_type, alg) \
+ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 && \
+ PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER(alg) ? \
+ PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) : \
+ 0u)
+
+/** A sufficient ciphertext buffer size for psa_aead_finish(), for any of the
+ * supported key types and AEAD algorithms.
+ *
+ * See also #PSA_AEAD_FINISH_OUTPUT_SIZE(\p key_type, \p alg).
+ */
+#define PSA_AEAD_FINISH_OUTPUT_MAX_SIZE (PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE)
+
+/** A sufficient plaintext buffer size for psa_aead_verify().
+ *
+ * If the size of the plaintext buffer is at least this large, it is
+ * guaranteed that psa_aead_verify() will not fail due to an
+ * insufficient plaintext buffer size. The actual size of the output may
+ * be smaller in any given call.
+ *
+ * See also #PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE.
+ *
+ * \param key_type A symmetric key type that is
+ * compatible with algorithm \p alg.
+ * \param alg An AEAD algorithm
+ * (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p alg) is true).
+ *
+ * \return A sufficient plaintext buffer size for the
+ * specified algorithm.
+ * If the key type or AEAD algorithm is not
+ * recognized, or the parameters are incompatible,
+ * return 0.
+ */
+#define PSA_AEAD_VERIFY_OUTPUT_SIZE(key_type, alg) \
+ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 && \
+ PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER(alg) ? \
+ PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) : \
+ 0u)
+
+/** A sufficient plaintext buffer size for psa_aead_verify(), for any of the
+ * supported key types and AEAD algorithms.
+ *
+ * See also #PSA_AEAD_VERIFY_OUTPUT_SIZE(\p key_type, \p alg).
+ */
+#define PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE (PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE)
+
+#define PSA_RSA_MINIMUM_PADDING_SIZE(alg) \
+ (PSA_ALG_IS_RSA_OAEP(alg) ? \
+ 2u * PSA_HASH_LENGTH(PSA_ALG_RSA_OAEP_GET_HASH(alg)) + 1u : \
+ 11u /*PKCS#1v1.5*/)
+
+/**
+ * \brief ECDSA signature size for a given curve bit size
+ *
+ * \param curve_bits Curve size in bits.
+ * \return Signature size in bytes.
+ *
+ * \note This macro returns a compile-time constant if its argument is one.
+ */
+#define PSA_ECDSA_SIGNATURE_SIZE(curve_bits) \
+ (PSA_BITS_TO_BYTES(curve_bits) * 2u)
+
+/** Sufficient signature buffer size for psa_sign_hash().
+ *
+ * This macro returns a sufficient buffer size for a signature using a key
+ * of the specified type and size, with the specified algorithm.
+ * Note that the actual size of the signature may be smaller
+ * (some algorithms produce a variable-size signature).
+ *
+ * \warning This function may call its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \param key_type An asymmetric key type (this may indifferently be a
+ * key pair type or a public key type).
+ * \param key_bits The size of the key in bits.
+ * \param alg The signature algorithm.
+ *
+ * \return If the parameters are valid and supported, return
+ * a buffer size in bytes that guarantees that
+ * psa_sign_hash() will not fail with
+ * #PSA_ERROR_BUFFER_TOO_SMALL.
+ * If the parameters are a valid combination that is not supported,
+ * return either a sensible size or 0.
+ * If the parameters are not valid, the
+ * return value is unspecified.
+ */
+#define PSA_SIGN_OUTPUT_SIZE(key_type, key_bits, alg) \
+ (PSA_KEY_TYPE_IS_RSA(key_type) ? ((void) alg, PSA_BITS_TO_BYTES(key_bits)) : \
+ PSA_KEY_TYPE_IS_ECC(key_type) ? PSA_ECDSA_SIGNATURE_SIZE(key_bits) : \
+ ((void) alg, 0u))
+
+#define PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE \
+ PSA_ECDSA_SIGNATURE_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)
+
+/** \def PSA_SIGNATURE_MAX_SIZE
+ *
+ * Maximum size of an asymmetric signature.
+ *
+ * This macro expands to a compile-time constant integer. This value
+ * is the maximum size of a signature in bytes.
+ */
+#define PSA_SIGNATURE_MAX_SIZE 1
+
+#if (defined(PSA_WANT_ALG_ECDSA) || defined(PSA_WANT_ALG_DETERMINISTIC_ECDSA)) && \
+ (PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE > PSA_SIGNATURE_MAX_SIZE)
+#undef PSA_SIGNATURE_MAX_SIZE
+#define PSA_SIGNATURE_MAX_SIZE PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE
+#endif
+#if (defined(PSA_WANT_ALG_RSA_PKCS1V15_SIGN) || defined(PSA_WANT_ALG_RSA_PSS)) && \
+ (PSA_BITS_TO_BYTES(PSA_VENDOR_RSA_MAX_KEY_BITS) > PSA_SIGNATURE_MAX_SIZE)
+#undef PSA_SIGNATURE_MAX_SIZE
+#define PSA_SIGNATURE_MAX_SIZE PSA_BITS_TO_BYTES(PSA_VENDOR_RSA_MAX_KEY_BITS)
+#endif
+
+/** Sufficient output buffer size for psa_asymmetric_encrypt().
+ *
+ * This macro returns a sufficient buffer size for a ciphertext produced using
+ * a key of the specified type and size, with the specified algorithm.
+ * Note that the actual size of the ciphertext may be smaller, depending
+ * on the algorithm.
+ *
+ * \warning This function may call its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \param key_type An asymmetric key type (this may indifferently be a
+ * key pair type or a public key type).
+ * \param key_bits The size of the key in bits.
+ * \param alg The asymmetric encryption algorithm.
+ *
+ * \return If the parameters are valid and supported, return
+ * a buffer size in bytes that guarantees that
+ * psa_asymmetric_encrypt() will not fail with
+ * #PSA_ERROR_BUFFER_TOO_SMALL.
+ * If the parameters are a valid combination that is not supported,
+ * return either a sensible size or 0.
+ * If the parameters are not valid, the
+ * return value is unspecified.
+ */
+#define PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(key_type, key_bits, alg) \
+ (PSA_KEY_TYPE_IS_RSA(key_type) ? \
+ ((void) alg, PSA_BITS_TO_BYTES(key_bits)) : \
+ 0u)
+
+/** A sufficient output buffer size for psa_asymmetric_encrypt(), for any
+ * supported asymmetric encryption.
+ *
+ * See also #PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(\p key_type, \p key_bits, \p alg).
+ */
+/* This macro assumes that RSA is the only supported asymmetric encryption. */
+#define PSA_ASYMMETRIC_ENCRYPT_OUTPUT_MAX_SIZE \
+ (PSA_BITS_TO_BYTES(PSA_VENDOR_RSA_MAX_KEY_BITS))
+
+/** Sufficient output buffer size for psa_asymmetric_decrypt().
+ *
+ * This macro returns a sufficient buffer size for a plaintext produced using
+ * a key of the specified type and size, with the specified algorithm.
+ * Note that the actual size of the plaintext may be smaller, depending
+ * on the algorithm.
+ *
+ * \warning This function may call its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \param key_type An asymmetric key type (this may indifferently be a
+ * key pair type or a public key type).
+ * \param key_bits The size of the key in bits.
+ * \param alg The asymmetric encryption algorithm.
+ *
+ * \return If the parameters are valid and supported, return
+ * a buffer size in bytes that guarantees that
+ * psa_asymmetric_decrypt() will not fail with
+ * #PSA_ERROR_BUFFER_TOO_SMALL.
+ * If the parameters are a valid combination that is not supported,
+ * return either a sensible size or 0.
+ * If the parameters are not valid, the
+ * return value is unspecified.
+ */
+#define PSA_ASYMMETRIC_DECRYPT_OUTPUT_SIZE(key_type, key_bits, alg) \
+ (PSA_KEY_TYPE_IS_RSA(key_type) ? \
+ PSA_BITS_TO_BYTES(key_bits) - PSA_RSA_MINIMUM_PADDING_SIZE(alg) : \
+ 0u)
+
+/** A sufficient output buffer size for psa_asymmetric_decrypt(), for any
+ * supported asymmetric decryption.
+ *
+ * This macro assumes that RSA is the only supported asymmetric encryption.
+ *
+ * See also #PSA_ASYMMETRIC_DECRYPT_OUTPUT_SIZE(\p key_type, \p key_bits, \p alg).
+ */
+#define PSA_ASYMMETRIC_DECRYPT_OUTPUT_MAX_SIZE \
+ (PSA_BITS_TO_BYTES(PSA_VENDOR_RSA_MAX_KEY_BITS))
+
+/* Maximum size of the ASN.1 encoding of an INTEGER with the specified
+ * number of bits.
+ *
+ * This definition assumes that bits <= 2^19 - 9 so that the length field
+ * is at most 3 bytes. The length of the encoding is the length of the
+ * bit string padded to a whole number of bytes plus:
+ * - 1 type byte;
+ * - 1 to 3 length bytes;
+ * - 0 to 1 bytes of leading 0 due to the sign bit.
+ */
+#define PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(bits) \
+ ((bits) / 8u + 5u)
+
+/* Maximum size of the export encoding of an RSA public key.
+ * Assumes that the public exponent is less than 2^32.
+ *
+ * RSAPublicKey ::= SEQUENCE {
+ * modulus INTEGER, -- n
+ * publicExponent INTEGER } -- e
+ *
+ * - 4 bytes of SEQUENCE overhead;
+ * - n : INTEGER;
+ * - 7 bytes for the public exponent.
+ */
+#define PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(key_bits) \
+ (PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(key_bits) + 11u)
+
+/* Maximum size of the export encoding of an RSA key pair.
+ * Assumes that the public exponent is less than 2^32 and that the size
+ * difference between the two primes is at most 1 bit.
+ *
+ * RSAPrivateKey ::= SEQUENCE {
+ * version Version, -- 0
+ * modulus INTEGER, -- N-bit
+ * publicExponent INTEGER, -- 32-bit
+ * privateExponent INTEGER, -- N-bit
+ * prime1 INTEGER, -- N/2-bit
+ * prime2 INTEGER, -- N/2-bit
+ * exponent1 INTEGER, -- N/2-bit
+ * exponent2 INTEGER, -- N/2-bit
+ * coefficient INTEGER, -- N/2-bit
+ * }
+ *
+ * - 4 bytes of SEQUENCE overhead;
+ * - 3 bytes of version;
+ * - 7 half-size INTEGERs plus 2 full-size INTEGERs,
+ * overapproximated as 9 half-size INTEGERS;
+ * - 7 bytes for the public exponent.
+ */
+#define PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(key_bits) \
+ (9u * PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE((key_bits) / 2u + 1u) + 14u)
+
+/* Maximum size of the export encoding of a DSA public key.
+ *
+ * SubjectPublicKeyInfo ::= SEQUENCE {
+ * algorithm AlgorithmIdentifier,
+ * subjectPublicKey BIT STRING } -- contains DSAPublicKey
+ * AlgorithmIdentifier ::= SEQUENCE {
+ * algorithm OBJECT IDENTIFIER,
+ * parameters Dss-Params } -- SEQUENCE of 3 INTEGERs
+ * DSAPublicKey ::= INTEGER -- public key, Y
+ *
+ * - 3 * 4 bytes of SEQUENCE overhead;
+ * - 1 + 1 + 7 bytes of algorithm (DSA OID);
+ * - 4 bytes of BIT STRING overhead;
+ * - 3 full-size INTEGERs (p, g, y);
+ * - 1 + 1 + 32 bytes for 1 sub-size INTEGER (q <= 256 bits).
+ */
+#define PSA_KEY_EXPORT_DSA_PUBLIC_KEY_MAX_SIZE(key_bits) \
+ (PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(key_bits) * 3u + 59u)
+
+/* Maximum size of the export encoding of a DSA key pair.
+ *
+ * DSAPrivateKey ::= SEQUENCE {
+ * version Version, -- 0
+ * prime INTEGER, -- p
+ * subprime INTEGER, -- q
+ * generator INTEGER, -- g
+ * public INTEGER, -- y
+ * private INTEGER, -- x
+ * }
+ *
+ * - 4 bytes of SEQUENCE overhead;
+ * - 3 bytes of version;
+ * - 3 full-size INTEGERs (p, g, y);
+ * - 2 * (1 + 1 + 32) bytes for 2 sub-size INTEGERs (q, x <= 256 bits).
+ */
+#define PSA_KEY_EXPORT_DSA_KEY_PAIR_MAX_SIZE(key_bits) \
+ (PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(key_bits) * 3u + 75u)
+
+/* Maximum size of the export encoding of an ECC public key.
+ *
+ * The representation of an ECC public key is:
+ * - The byte 0x04;
+ * - `x_P` as a `ceiling(m/8)`-byte string, big-endian;
+ * - `y_P` as a `ceiling(m/8)`-byte string, big-endian;
+ * - where m is the bit size associated with the curve.
+ *
+ * - 1 byte + 2 * point size.
+ */
+#define PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(key_bits) \
+ (2u * PSA_BITS_TO_BYTES(key_bits) + 1u)
+
+/* Maximum size of the export encoding of an ECC key pair.
+ *
+ * An ECC key pair is represented by the secret value.
+ */
+#define PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(key_bits) \
+ (PSA_BITS_TO_BYTES(key_bits))
+
+/* Maximum size of the export encoding of an DH key pair.
+ *
+ * An DH key pair is represented by the secret value.
+ */
+#define PSA_KEY_EXPORT_FFDH_KEY_PAIR_MAX_SIZE(key_bits) \
+ (PSA_BITS_TO_BYTES(key_bits))
+
+/* Maximum size of the export encoding of an DH public key.
+ */
+#define PSA_KEY_EXPORT_FFDH_PUBLIC_KEY_MAX_SIZE(key_bits) \
+ (PSA_BITS_TO_BYTES(key_bits))
+
+/** Sufficient output buffer size for psa_export_key() or
+ * psa_export_public_key().
+ *
+ * This macro returns a compile-time constant if its arguments are
+ * compile-time constants.
+ *
+ * \warning This macro may evaluate its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * The following code illustrates how to allocate enough memory to export
+ * a key by querying the key type and size at runtime.
+ * \code{c}
+ * psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+ * psa_status_t status;
+ * status = psa_get_key_attributes(key, &attributes);
+ * if (status != PSA_SUCCESS) handle_error(...);
+ * psa_key_type_t key_type = psa_get_key_type(&attributes);
+ * size_t key_bits = psa_get_key_bits(&attributes);
+ * size_t buffer_size = PSA_EXPORT_KEY_OUTPUT_SIZE(key_type, key_bits);
+ * psa_reset_key_attributes(&attributes);
+ * uint8_t *buffer = malloc(buffer_size);
+ * if (buffer == NULL) handle_error(...);
+ * size_t buffer_length;
+ * status = psa_export_key(key, buffer, buffer_size, &buffer_length);
+ * if (status != PSA_SUCCESS) handle_error(...);
+ * \endcode
+ *
+ * \param key_type A supported key type.
+ * \param key_bits The size of the key in bits.
+ *
+ * \return If the parameters are valid and supported, return
+ * a buffer size in bytes that guarantees that
+ * psa_export_key() or psa_export_public_key() will not fail with
+ * #PSA_ERROR_BUFFER_TOO_SMALL.
+ * If the parameters are a valid combination that is not supported,
+ * return either a sensible size or 0.
+ * If the parameters are not valid, the return value is unspecified.
+ */
+#define PSA_EXPORT_KEY_OUTPUT_SIZE(key_type, key_bits) \
+ (PSA_KEY_TYPE_IS_UNSTRUCTURED(key_type) ? PSA_BITS_TO_BYTES(key_bits) : \
+ PSA_KEY_TYPE_IS_DH(key_type) ? PSA_BITS_TO_BYTES(key_bits) : \
+ (key_type) == PSA_KEY_TYPE_RSA_KEY_PAIR ? PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(key_bits) : \
+ (key_type) == PSA_KEY_TYPE_RSA_PUBLIC_KEY ? PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(key_bits) : \
+ (key_type) == PSA_KEY_TYPE_DSA_KEY_PAIR ? PSA_KEY_EXPORT_DSA_KEY_PAIR_MAX_SIZE(key_bits) : \
+ (key_type) == PSA_KEY_TYPE_DSA_PUBLIC_KEY ? PSA_KEY_EXPORT_DSA_PUBLIC_KEY_MAX_SIZE(key_bits) : \
+ PSA_KEY_TYPE_IS_ECC_KEY_PAIR(key_type) ? PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(key_bits) : \
+ PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY(key_type) ? PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(key_bits) : \
+ 0u)
+
+/** Sufficient output buffer size for psa_export_public_key().
+ *
+ * This macro returns a compile-time constant if its arguments are
+ * compile-time constants.
+ *
+ * \warning This macro may evaluate its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * The following code illustrates how to allocate enough memory to export
+ * a public key by querying the key type and size at runtime.
+ * \code{c}
+ * psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+ * psa_status_t status;
+ * status = psa_get_key_attributes(key, &attributes);
+ * if (status != PSA_SUCCESS) handle_error(...);
+ * psa_key_type_t key_type = psa_get_key_type(&attributes);
+ * size_t key_bits = psa_get_key_bits(&attributes);
+ * size_t buffer_size = PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(key_type, key_bits);
+ * psa_reset_key_attributes(&attributes);
+ * uint8_t *buffer = malloc(buffer_size);
+ * if (buffer == NULL) handle_error(...);
+ * size_t buffer_length;
+ * status = psa_export_public_key(key, buffer, buffer_size, &buffer_length);
+ * if (status != PSA_SUCCESS) handle_error(...);
+ * \endcode
+ *
+ * \param key_type A public key or key pair key type.
+ * \param key_bits The size of the key in bits.
+ *
+ * \return If the parameters are valid and supported, return
+ * a buffer size in bytes that guarantees that
+ * psa_export_public_key() will not fail with
+ * #PSA_ERROR_BUFFER_TOO_SMALL.
+ * If the parameters are a valid combination that is not
+ * supported, return either a sensible size or 0.
+ * If the parameters are not valid,
+ * the return value is unspecified.
+ *
+ * If the parameters are valid and supported,
+ * return the same result as
+ * #PSA_EXPORT_KEY_OUTPUT_SIZE(
+ * \p #PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(\p key_type),
+ * \p key_bits).
+ */
+#define PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(key_type, key_bits) \
+ (PSA_KEY_TYPE_IS_RSA(key_type) ? PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(key_bits) : \
+ PSA_KEY_TYPE_IS_ECC(key_type) ? PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(key_bits) : \
+ PSA_KEY_TYPE_IS_DH(key_type) ? PSA_BITS_TO_BYTES(key_bits) : \
+ 0u)
+
+/** Sufficient buffer size for exporting any asymmetric key pair.
+ *
+ * This macro expands to a compile-time constant integer. This value is
+ * a sufficient buffer size when calling psa_export_key() to export any
+ * asymmetric key pair, regardless of the exact key type and key size.
+ *
+ * See also #PSA_EXPORT_KEY_OUTPUT_SIZE(\p key_type, \p key_bits).
+ */
+#define PSA_EXPORT_KEY_PAIR_MAX_SIZE 1
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_KEY_PAIR_BASIC) && \
+ (PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS) > \
+ PSA_EXPORT_KEY_PAIR_MAX_SIZE)
+#undef PSA_EXPORT_KEY_PAIR_MAX_SIZE
+#define PSA_EXPORT_KEY_PAIR_MAX_SIZE \
+ PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)
+#endif
+#if defined(PSA_WANT_KEY_TYPE_RSA_KEY_PAIR_BASIC) && \
+ (PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS) > \
+ PSA_EXPORT_KEY_PAIR_MAX_SIZE)
+#undef PSA_EXPORT_KEY_PAIR_MAX_SIZE
+#define PSA_EXPORT_KEY_PAIR_MAX_SIZE \
+ PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS)
+#endif
+#if defined(PSA_WANT_KEY_TYPE_DH_KEY_PAIR_BASIC) && \
+ (PSA_KEY_EXPORT_FFDH_KEY_PAIR_MAX_SIZE(PSA_VENDOR_FFDH_MAX_KEY_BITS) > \
+ PSA_EXPORT_KEY_PAIR_MAX_SIZE)
+#undef PSA_EXPORT_KEY_PAIR_MAX_SIZE
+#define PSA_EXPORT_KEY_PAIR_MAX_SIZE \
+ PSA_KEY_EXPORT_FFDH_KEY_PAIR_MAX_SIZE(PSA_VENDOR_FFDH_MAX_KEY_BITS)
+#endif
+
+/** Sufficient buffer size for exporting any asymmetric public key.
+ *
+ * This macro expands to a compile-time constant integer. This value is
+ * a sufficient buffer size when calling psa_export_key() or
+ * psa_export_public_key() to export any asymmetric public key,
+ * regardless of the exact key type and key size.
+ *
+ * See also #PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(\p key_type, \p key_bits).
+ */
+#define PSA_EXPORT_PUBLIC_KEY_MAX_SIZE 1
+
+#if defined(PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY) && \
+ (PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS) > \
+ PSA_EXPORT_PUBLIC_KEY_MAX_SIZE)
+#undef PSA_EXPORT_PUBLIC_KEY_MAX_SIZE
+#define PSA_EXPORT_PUBLIC_KEY_MAX_SIZE \
+ PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)
+#endif
+#if defined(PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY) && \
+ (PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS) > \
+ PSA_EXPORT_PUBLIC_KEY_MAX_SIZE)
+#undef PSA_EXPORT_PUBLIC_KEY_MAX_SIZE
+#define PSA_EXPORT_PUBLIC_KEY_MAX_SIZE \
+ PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS)
+#endif
+#if defined(PSA_WANT_KEY_TYPE_DH_PUBLIC_KEY) && \
+ (PSA_KEY_EXPORT_FFDH_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_FFDH_MAX_KEY_BITS) > \
+ PSA_EXPORT_PUBLIC_KEY_MAX_SIZE)
+#undef PSA_EXPORT_PUBLIC_KEY_MAX_SIZE
+#define PSA_EXPORT_PUBLIC_KEY_MAX_SIZE \
+ PSA_KEY_EXPORT_FFDH_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_FFDH_MAX_KEY_BITS)
+#endif
+
+/** Sufficient output buffer size for psa_raw_key_agreement().
+ *
+ * This macro returns a compile-time constant if its arguments are
+ * compile-time constants.
+ *
+ * \warning This macro may evaluate its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * See also #PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE.
+ *
+ * \param key_type A supported key type.
+ * \param key_bits The size of the key in bits.
+ *
+ * \return If the parameters are valid and supported, return
+ * a buffer size in bytes that guarantees that
+ * psa_raw_key_agreement() will not fail with
+ * #PSA_ERROR_BUFFER_TOO_SMALL.
+ * If the parameters are a valid combination that
+ * is not supported, return either a sensible size or 0.
+ * If the parameters are not valid,
+ * the return value is unspecified.
+ */
+#define PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(key_type, key_bits) \
+ ((PSA_KEY_TYPE_IS_ECC_KEY_PAIR(key_type) || \
+ PSA_KEY_TYPE_IS_DH_KEY_PAIR(key_type)) ? PSA_BITS_TO_BYTES(key_bits) : 0u)
+
+/** Maximum size of the output from psa_raw_key_agreement().
+ *
+ * This macro expands to a compile-time constant integer. This value is the
+ * maximum size of the output any raw key agreement algorithm, in bytes.
+ *
+ * See also #PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(\p key_type, \p key_bits).
+ */
+#define PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE 1
+
+#if defined(PSA_WANT_ALG_ECDH) && \
+ (PSA_BITS_TO_BYTES(PSA_VENDOR_ECC_MAX_CURVE_BITS) > PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE)
+#undef PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE
+#define PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE PSA_BITS_TO_BYTES(PSA_VENDOR_ECC_MAX_CURVE_BITS)
+#endif
+#if defined(PSA_WANT_ALG_FFDH) && \
+ (PSA_BITS_TO_BYTES(PSA_VENDOR_FFDH_MAX_KEY_BITS) > PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE)
+#undef PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE
+#define PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE PSA_BITS_TO_BYTES(PSA_VENDOR_FFDH_MAX_KEY_BITS)
+#endif
+
+/** The default IV size for a cipher algorithm, in bytes.
+ *
+ * The IV that is generated as part of a call to #psa_cipher_encrypt() is always
+ * the default IV length for the algorithm.
+ *
+ * This macro can be used to allocate a buffer of sufficient size to
+ * store the IV output from #psa_cipher_generate_iv() when using
+ * a multi-part cipher operation.
+ *
+ * See also #PSA_CIPHER_IV_MAX_SIZE.
+ *
+ * \warning This macro may evaluate its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \param key_type A symmetric key type that is compatible with algorithm \p alg.
+ *
+ * \param alg A cipher algorithm (\c PSA_ALG_XXX value such that #PSA_ALG_IS_CIPHER(\p alg) is true).
+ *
+ * \return The default IV size for the specified key type and algorithm.
+ * If the algorithm does not use an IV, return 0.
+ * If the key type or cipher algorithm is not recognized,
+ * or the parameters are incompatible, return 0.
+ */
+#define PSA_CIPHER_IV_LENGTH(key_type, alg) \
+ (PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) > 1 && \
+ ((alg) == PSA_ALG_CTR || \
+ (alg) == PSA_ALG_CFB || \
+ (alg) == PSA_ALG_OFB || \
+ (alg) == PSA_ALG_XTS || \
+ (alg) == PSA_ALG_CBC_NO_PADDING || \
+ (alg) == PSA_ALG_CBC_PKCS7) ? PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) : \
+ (key_type) == PSA_KEY_TYPE_CHACHA20 && \
+ (alg) == PSA_ALG_STREAM_CIPHER ? 12u : \
+ (alg) == PSA_ALG_CCM_STAR_NO_TAG ? 13u : \
+ 0u)
+
+/** The maximum IV size for all supported cipher algorithms, in bytes.
+ *
+ * See also #PSA_CIPHER_IV_LENGTH().
+ */
+#define PSA_CIPHER_IV_MAX_SIZE 16u
+
+/** The maximum size of the output of psa_cipher_encrypt(), in bytes.
+ *
+ * If the size of the output buffer is at least this large, it is guaranteed
+ * that psa_cipher_encrypt() will not fail due to an insufficient buffer size.
+ * Depending on the algorithm, the actual size of the output might be smaller.
+ *
+ * See also #PSA_CIPHER_ENCRYPT_OUTPUT_MAX_SIZE(\p input_length).
+ *
+ * \warning This macro may evaluate its arguments multiple times or
+ * zero times, so you should not pass arguments that contain
+ * side effects.
+ *
+ * \param key_type A symmetric key type that is compatible with algorithm
+ * alg.
+ * \param alg A cipher algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_CIPHER(\p alg) is true).
+ * \param input_length Size of the input in bytes.
+ *
+ * \return A sufficient output size for the specified key type and
+ * algorithm. If the key type or cipher algorithm is not
+ * recognized, or the parameters are incompatible,
+ * return 0.
+ */
+#define PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, input_length) \
+ (alg == PSA_ALG_CBC_PKCS7 ? \
+ (PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) != 0 ? \
+ PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type), \
+ (input_length) + 1u) + \
+ PSA_CIPHER_IV_LENGTH((key_type), (alg)) : 0u) : \
+ (PSA_ALG_IS_CIPHER(alg) ? \
+ (input_length) + PSA_CIPHER_IV_LENGTH((key_type), (alg)) : \
+ 0u))
+
+/** A sufficient output buffer size for psa_cipher_encrypt(), for any of the
+ * supported key types and cipher algorithms.
+ *
+ * If the size of the output buffer is at least this large, it is guaranteed
+ * that psa_cipher_encrypt() will not fail due to an insufficient buffer size.
+ *
+ * See also #PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(\p key_type, \p alg, \p input_length).
+ *
+ * \param input_length Size of the input in bytes.
+ *
+ */
+#define PSA_CIPHER_ENCRYPT_OUTPUT_MAX_SIZE(input_length) \
+ (PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE, \
+ (input_length) + 1u) + \
+ PSA_CIPHER_IV_MAX_SIZE)
+
+/** The maximum size of the output of psa_cipher_decrypt(), in bytes.
+ *
+ * If the size of the output buffer is at least this large, it is guaranteed
+ * that psa_cipher_decrypt() will not fail due to an insufficient buffer size.
+ * Depending on the algorithm, the actual size of the output might be smaller.
+ *
+ * See also #PSA_CIPHER_DECRYPT_OUTPUT_MAX_SIZE(\p input_length).
+ *
+ * \param key_type A symmetric key type that is compatible with algorithm
+ * alg.
+ * \param alg A cipher algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_CIPHER(\p alg) is true).
+ * \param input_length Size of the input in bytes.
+ *
+ * \return A sufficient output size for the specified key type and
+ * algorithm. If the key type or cipher algorithm is not
+ * recognized, or the parameters are incompatible,
+ * return 0.
+ */
+#define PSA_CIPHER_DECRYPT_OUTPUT_SIZE(key_type, alg, input_length) \
+ (PSA_ALG_IS_CIPHER(alg) && \
+ ((key_type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_SYMMETRIC ? \
+ (input_length) : \
+ 0u)
+
+/** A sufficient output buffer size for psa_cipher_decrypt(), for any of the
+ * supported key types and cipher algorithms.
+ *
+ * If the size of the output buffer is at least this large, it is guaranteed
+ * that psa_cipher_decrypt() will not fail due to an insufficient buffer size.
+ *
+ * See also #PSA_CIPHER_DECRYPT_OUTPUT_SIZE(\p key_type, \p alg, \p input_length).
+ *
+ * \param input_length Size of the input in bytes.
+ */
+#define PSA_CIPHER_DECRYPT_OUTPUT_MAX_SIZE(input_length) \
+ (input_length)
+
+/** A sufficient output buffer size for psa_cipher_update().
+ *
+ * If the size of the output buffer is at least this large, it is guaranteed
+ * that psa_cipher_update() will not fail due to an insufficient buffer size.
+ * The actual size of the output might be smaller in any given call.
+ *
+ * See also #PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(\p input_length).
+ *
+ * \param key_type A symmetric key type that is compatible with algorithm
+ * alg.
+ * \param alg A cipher algorithm (PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_CIPHER(\p alg) is true).
+ * \param input_length Size of the input in bytes.
+ *
+ * \return A sufficient output size for the specified key type and
+ * algorithm. If the key type or cipher algorithm is not
+ * recognized, or the parameters are incompatible, return 0.
+ */
+#define PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, input_length) \
+ (PSA_ALG_IS_CIPHER(alg) ? \
+ (PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) != 0 ? \
+ (((alg) == PSA_ALG_CBC_PKCS7 || \
+ (alg) == PSA_ALG_CBC_NO_PADDING || \
+ (alg) == PSA_ALG_ECB_NO_PADDING) ? \
+ PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type), \
+ input_length) : \
+ (input_length)) : 0u) : \
+ 0u)
+
+/** A sufficient output buffer size for psa_cipher_update(), for any of the
+ * supported key types and cipher algorithms.
+ *
+ * If the size of the output buffer is at least this large, it is guaranteed
+ * that psa_cipher_update() will not fail due to an insufficient buffer size.
+ *
+ * See also #PSA_CIPHER_UPDATE_OUTPUT_SIZE(\p key_type, \p alg, \p input_length).
+ *
+ * \param input_length Size of the input in bytes.
+ */
+#define PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(input_length) \
+ (PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE, input_length))
+
+/** A sufficient ciphertext buffer size for psa_cipher_finish().
+ *
+ * If the size of the ciphertext buffer is at least this large, it is
+ * guaranteed that psa_cipher_finish() will not fail due to an insufficient
+ * ciphertext buffer size. The actual size of the output might be smaller in
+ * any given call.
+ *
+ * See also #PSA_CIPHER_FINISH_OUTPUT_MAX_SIZE().
+ *
+ * \param key_type A symmetric key type that is compatible with algorithm
+ * alg.
+ * \param alg A cipher algorithm (PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_CIPHER(\p alg) is true).
+ * \return A sufficient output size for the specified key type and
+ * algorithm. If the key type or cipher algorithm is not
+ * recognized, or the parameters are incompatible, return 0.
+ */
+#define PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg) \
+ (PSA_ALG_IS_CIPHER(alg) ? \
+ (alg == PSA_ALG_CBC_PKCS7 ? \
+ PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) : \
+ 0u) : \
+ 0u)
+
+/** A sufficient ciphertext buffer size for psa_cipher_finish(), for any of the
+ * supported key types and cipher algorithms.
+ *
+ * See also #PSA_CIPHER_FINISH_OUTPUT_SIZE(\p key_type, \p alg).
+ */
+#define PSA_CIPHER_FINISH_OUTPUT_MAX_SIZE \
+ (PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE)
+
+#endif /* PSA_CRYPTO_SIZES_H */
diff --git a/include/psa/crypto_struct.h b/include/psa/crypto_struct.h
new file mode 100644
index 0000000..d5ea8d5
--- /dev/null
+++ b/include/psa/crypto_struct.h
@@ -0,0 +1,460 @@
+/**
+ * \file psa/crypto_struct.h
+ *
+ * \brief PSA cryptography module: Mbed TLS structured type implementations
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h.
+ *
+ * This file contains the definitions of some data structures with
+ * implementation-specific definitions.
+ *
+ * In implementations with isolation between the application and the
+ * cryptography module, it is expected that the front-end and the back-end
+ * would have different versions of this file.
+ *
+ * <h3>Design notes about multipart operation structures</h3>
+ *
+ * For multipart operations without driver delegation support, each multipart
+ * operation structure contains a `psa_algorithm_t alg` field which indicates
+ * which specific algorithm the structure is for. When the structure is not in
+ * use, `alg` is 0. Most of the structure consists of a union which is
+ * discriminated by `alg`.
+ *
+ * For multipart operations with driver delegation support, each multipart
+ * operation structure contains an `unsigned int id` field indicating which
+ * driver got assigned to do the operation. When the structure is not in use,
+ * 'id' is 0. The structure contains also a driver context which is the union
+ * of the contexts of all drivers able to handle the type of multipart
+ * operation.
+ *
+ * Note that when `alg` or `id` is 0, the content of other fields is undefined.
+ * In particular, it is not guaranteed that a freshly-initialized structure
+ * is all-zero: we initialize structures to something like `{0, 0}`, which
+ * is only guaranteed to initializes the first member of the union;
+ * GCC and Clang initialize the whole structure to 0 (at the time of writing),
+ * but MSVC and CompCert don't.
+ *
+ * In Mbed TLS, multipart operation structures live independently from
+ * the key. This allows Mbed TLS to free the key objects when destroying
+ * a key slot. If a multipart operation needs to remember the key after
+ * the setup function returns, the operation structure needs to contain a
+ * copy of the key.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_STRUCT_H
+#define PSA_CRYPTO_STRUCT_H
+#include "mbedtls/private_access.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/* Include the Mbed TLS configuration file, the way Mbed TLS does it
+ * in each of its header files. */
+#include "mbedtls/build_info.h"
+
+/* Include the context definition for the compiled-in drivers for the primitive
+ * algorithms. */
+#include "psa/crypto_driver_contexts_primitives.h"
+
+struct psa_hash_operation_s {
+ /** Unique ID indicating which driver got assigned to do the
+ * operation. Since driver contexts are driver-specific, swapping
+ * drivers halfway through the operation is not supported.
+ * ID values are auto-generated in psa_driver_wrappers.h.
+ * ID value zero means the context is not valid or not assigned to
+ * any driver (i.e. the driver context is not active, in use). */
+ unsigned int MBEDTLS_PRIVATE(id);
+ psa_driver_hash_context_t MBEDTLS_PRIVATE(ctx);
+};
+
+#define PSA_HASH_OPERATION_INIT { 0, { 0 } }
+static inline struct psa_hash_operation_s psa_hash_operation_init(void)
+{
+ const struct psa_hash_operation_s v = PSA_HASH_OPERATION_INIT;
+ return v;
+}
+
+struct psa_cipher_operation_s {
+ /** Unique ID indicating which driver got assigned to do the
+ * operation. Since driver contexts are driver-specific, swapping
+ * drivers halfway through the operation is not supported.
+ * ID values are auto-generated in psa_crypto_driver_wrappers.h
+ * ID value zero means the context is not valid or not assigned to
+ * any driver (i.e. none of the driver contexts are active). */
+ unsigned int MBEDTLS_PRIVATE(id);
+
+ unsigned int MBEDTLS_PRIVATE(iv_required) : 1;
+ unsigned int MBEDTLS_PRIVATE(iv_set) : 1;
+
+ uint8_t MBEDTLS_PRIVATE(default_iv_length);
+
+ psa_driver_cipher_context_t MBEDTLS_PRIVATE(ctx);
+};
+
+#define PSA_CIPHER_OPERATION_INIT { 0, 0, 0, 0, { 0 } }
+static inline struct psa_cipher_operation_s psa_cipher_operation_init(void)
+{
+ const struct psa_cipher_operation_s v = PSA_CIPHER_OPERATION_INIT;
+ return v;
+}
+
+/* Include the context definition for the compiled-in drivers for the composite
+ * algorithms. */
+#include "psa/crypto_driver_contexts_composites.h"
+
+struct psa_mac_operation_s {
+ /** Unique ID indicating which driver got assigned to do the
+ * operation. Since driver contexts are driver-specific, swapping
+ * drivers halfway through the operation is not supported.
+ * ID values are auto-generated in psa_driver_wrappers.h
+ * ID value zero means the context is not valid or not assigned to
+ * any driver (i.e. none of the driver contexts are active). */
+ unsigned int MBEDTLS_PRIVATE(id);
+ uint8_t MBEDTLS_PRIVATE(mac_size);
+ unsigned int MBEDTLS_PRIVATE(is_sign) : 1;
+ psa_driver_mac_context_t MBEDTLS_PRIVATE(ctx);
+};
+
+#define PSA_MAC_OPERATION_INIT { 0, 0, 0, { 0 } }
+static inline struct psa_mac_operation_s psa_mac_operation_init(void)
+{
+ const struct psa_mac_operation_s v = PSA_MAC_OPERATION_INIT;
+ return v;
+}
+
+struct psa_aead_operation_s {
+
+ /** Unique ID indicating which driver got assigned to do the
+ * operation. Since driver contexts are driver-specific, swapping
+ * drivers halfway through the operation is not supported.
+ * ID values are auto-generated in psa_crypto_driver_wrappers.h
+ * ID value zero means the context is not valid or not assigned to
+ * any driver (i.e. none of the driver contexts are active). */
+ unsigned int MBEDTLS_PRIVATE(id);
+
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+ psa_key_type_t MBEDTLS_PRIVATE(key_type);
+
+ size_t MBEDTLS_PRIVATE(ad_remaining);
+ size_t MBEDTLS_PRIVATE(body_remaining);
+
+ unsigned int MBEDTLS_PRIVATE(nonce_set) : 1;
+ unsigned int MBEDTLS_PRIVATE(lengths_set) : 1;
+ unsigned int MBEDTLS_PRIVATE(ad_started) : 1;
+ unsigned int MBEDTLS_PRIVATE(body_started) : 1;
+ unsigned int MBEDTLS_PRIVATE(is_encrypt) : 1;
+
+ psa_driver_aead_context_t MBEDTLS_PRIVATE(ctx);
+};
+
+#define PSA_AEAD_OPERATION_INIT { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, { 0 } }
+static inline struct psa_aead_operation_s psa_aead_operation_init(void)
+{
+ const struct psa_aead_operation_s v = PSA_AEAD_OPERATION_INIT;
+ return v;
+}
+
+/* Include the context definition for the compiled-in drivers for the key
+ * derivation algorithms. */
+#include "psa/crypto_driver_contexts_key_derivation.h"
+
+struct psa_key_derivation_s {
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+ unsigned int MBEDTLS_PRIVATE(can_output_key) : 1;
+ size_t MBEDTLS_PRIVATE(capacity);
+ psa_driver_key_derivation_context_t MBEDTLS_PRIVATE(ctx);
+};
+
+/* This only zeroes out the first byte in the union, the rest is unspecified. */
+#define PSA_KEY_DERIVATION_OPERATION_INIT { 0, 0, 0, { 0 } }
+static inline struct psa_key_derivation_s psa_key_derivation_operation_init(
+ void)
+{
+ const struct psa_key_derivation_s v = PSA_KEY_DERIVATION_OPERATION_INIT;
+ return v;
+}
+
+struct psa_key_policy_s {
+ psa_key_usage_t MBEDTLS_PRIVATE(usage);
+ psa_algorithm_t MBEDTLS_PRIVATE(alg);
+ psa_algorithm_t MBEDTLS_PRIVATE(alg2);
+};
+typedef struct psa_key_policy_s psa_key_policy_t;
+
+#define PSA_KEY_POLICY_INIT { 0, 0, 0 }
+static inline struct psa_key_policy_s psa_key_policy_init(void)
+{
+ const struct psa_key_policy_s v = PSA_KEY_POLICY_INIT;
+ return v;
+}
+
+/* The type used internally for key sizes.
+ * Public interfaces use size_t, but internally we use a smaller type. */
+typedef uint16_t psa_key_bits_t;
+/* The maximum value of the type used to represent bit-sizes.
+ * This is used to mark an invalid key size. */
+#define PSA_KEY_BITS_TOO_LARGE ((psa_key_bits_t) -1)
+/* The maximum size of a key in bits.
+ * Currently defined as the maximum that can be represented, rounded down
+ * to a whole number of bytes.
+ * This is an uncast value so that it can be used in preprocessor
+ * conditionals. */
+#define PSA_MAX_KEY_BITS 0xfff8
+
+/** A mask of flags that can be stored in key attributes.
+ *
+ * This type is also used internally to store flags in slots. Internal
+ * flags are defined in library/psa_crypto_core.h. Internal flags may have
+ * the same value as external flags if they are properly handled during
+ * key creation and in psa_get_key_attributes.
+ */
+typedef uint16_t psa_key_attributes_flag_t;
+
+#define MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER \
+ ((psa_key_attributes_flag_t) 0x0001)
+
+/* A mask of key attribute flags used externally only.
+ * Only meant for internal checks inside the library. */
+#define MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY ( \
+ MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER | \
+ 0)
+
+/* A mask of key attribute flags used both internally and externally.
+ * Currently there aren't any. */
+#define MBEDTLS_PSA_KA_MASK_DUAL_USE ( \
+ 0)
+
+typedef struct {
+ psa_key_type_t MBEDTLS_PRIVATE(type);
+ psa_key_bits_t MBEDTLS_PRIVATE(bits);
+ psa_key_lifetime_t MBEDTLS_PRIVATE(lifetime);
+ mbedtls_svc_key_id_t MBEDTLS_PRIVATE(id);
+ psa_key_policy_t MBEDTLS_PRIVATE(policy);
+ psa_key_attributes_flag_t MBEDTLS_PRIVATE(flags);
+} psa_core_key_attributes_t;
+
+#define PSA_CORE_KEY_ATTRIBUTES_INIT { PSA_KEY_TYPE_NONE, 0, \
+ PSA_KEY_LIFETIME_VOLATILE, \
+ MBEDTLS_SVC_KEY_ID_INIT, \
+ PSA_KEY_POLICY_INIT, 0 }
+
+struct psa_key_attributes_s {
+ psa_core_key_attributes_t MBEDTLS_PRIVATE(core);
+#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
+ psa_key_slot_number_t MBEDTLS_PRIVATE(slot_number);
+#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
+ void *MBEDTLS_PRIVATE(domain_parameters);
+ size_t MBEDTLS_PRIVATE(domain_parameters_size);
+};
+
+#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
+#define PSA_KEY_ATTRIBUTES_INIT { PSA_CORE_KEY_ATTRIBUTES_INIT, 0, NULL, 0 }
+#else
+#define PSA_KEY_ATTRIBUTES_INIT { PSA_CORE_KEY_ATTRIBUTES_INIT, NULL, 0 }
+#endif
+
+static inline struct psa_key_attributes_s psa_key_attributes_init(void)
+{
+ const struct psa_key_attributes_s v = PSA_KEY_ATTRIBUTES_INIT;
+ return v;
+}
+
+static inline void psa_set_key_id(psa_key_attributes_t *attributes,
+ mbedtls_svc_key_id_t key)
+{
+ psa_key_lifetime_t lifetime = attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(lifetime);
+
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(id) = key;
+
+ if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(lifetime) =
+ PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(
+ PSA_KEY_LIFETIME_PERSISTENT,
+ PSA_KEY_LIFETIME_GET_LOCATION(lifetime));
+ }
+}
+
+static inline mbedtls_svc_key_id_t psa_get_key_id(
+ const psa_key_attributes_t *attributes)
+{
+ return attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(id);
+}
+
+#ifdef MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER
+static inline void mbedtls_set_key_owner_id(psa_key_attributes_t *attributes,
+ mbedtls_key_owner_id_t owner)
+{
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(id).MBEDTLS_PRIVATE(owner) = owner;
+}
+#endif
+
+static inline void psa_set_key_lifetime(psa_key_attributes_t *attributes,
+ psa_key_lifetime_t lifetime)
+{
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(lifetime) = lifetime;
+ if (PSA_KEY_LIFETIME_IS_VOLATILE(lifetime)) {
+#ifdef MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(id).MBEDTLS_PRIVATE(key_id) = 0;
+#else
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(id) = 0;
+#endif
+ }
+}
+
+static inline psa_key_lifetime_t psa_get_key_lifetime(
+ const psa_key_attributes_t *attributes)
+{
+ return attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(lifetime);
+}
+
+static inline void psa_extend_key_usage_flags(psa_key_usage_t *usage_flags)
+{
+ if (*usage_flags & PSA_KEY_USAGE_SIGN_HASH) {
+ *usage_flags |= PSA_KEY_USAGE_SIGN_MESSAGE;
+ }
+
+ if (*usage_flags & PSA_KEY_USAGE_VERIFY_HASH) {
+ *usage_flags |= PSA_KEY_USAGE_VERIFY_MESSAGE;
+ }
+}
+
+static inline void psa_set_key_usage_flags(psa_key_attributes_t *attributes,
+ psa_key_usage_t usage_flags)
+{
+ psa_extend_key_usage_flags(&usage_flags);
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(policy).MBEDTLS_PRIVATE(usage) = usage_flags;
+}
+
+static inline psa_key_usage_t psa_get_key_usage_flags(
+ const psa_key_attributes_t *attributes)
+{
+ return attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(policy).MBEDTLS_PRIVATE(usage);
+}
+
+static inline void psa_set_key_algorithm(psa_key_attributes_t *attributes,
+ psa_algorithm_t alg)
+{
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(policy).MBEDTLS_PRIVATE(alg) = alg;
+}
+
+static inline psa_algorithm_t psa_get_key_algorithm(
+ const psa_key_attributes_t *attributes)
+{
+ return attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(policy).MBEDTLS_PRIVATE(alg);
+}
+
+/* This function is declared in crypto_extra.h, which comes after this
+ * header file, but we need the function here, so repeat the declaration. */
+psa_status_t psa_set_key_domain_parameters(psa_key_attributes_t *attributes,
+ psa_key_type_t type,
+ const uint8_t *data,
+ size_t data_length);
+
+static inline void psa_set_key_type(psa_key_attributes_t *attributes,
+ psa_key_type_t type)
+{
+ if (attributes->MBEDTLS_PRIVATE(domain_parameters) == NULL) {
+ /* Common case: quick path */
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(type) = type;
+ } else {
+ /* Call the bigger function to free the old domain parameters.
+ * Ignore any errors which may arise due to type requiring
+ * non-default domain parameters, since this function can't
+ * report errors. */
+ (void) psa_set_key_domain_parameters(attributes, type, NULL, 0);
+ }
+}
+
+static inline psa_key_type_t psa_get_key_type(
+ const psa_key_attributes_t *attributes)
+{
+ return attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(type);
+}
+
+static inline void psa_set_key_bits(psa_key_attributes_t *attributes,
+ size_t bits)
+{
+ if (bits > PSA_MAX_KEY_BITS) {
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(bits) = PSA_KEY_BITS_TOO_LARGE;
+ } else {
+ attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(bits) = (psa_key_bits_t) bits;
+ }
+}
+
+static inline size_t psa_get_key_bits(
+ const psa_key_attributes_t *attributes)
+{
+ return attributes->MBEDTLS_PRIVATE(core).MBEDTLS_PRIVATE(bits);
+}
+
+/**
+ * \brief The context for PSA interruptible hash signing.
+ */
+struct psa_sign_hash_interruptible_operation_s {
+ /** Unique ID indicating which driver got assigned to do the
+ * operation. Since driver contexts are driver-specific, swapping
+ * drivers halfway through the operation is not supported.
+ * ID values are auto-generated in psa_crypto_driver_wrappers.h
+ * ID value zero means the context is not valid or not assigned to
+ * any driver (i.e. none of the driver contexts are active). */
+ unsigned int MBEDTLS_PRIVATE(id);
+
+ psa_driver_sign_hash_interruptible_context_t MBEDTLS_PRIVATE(ctx);
+
+ unsigned int MBEDTLS_PRIVATE(error_occurred) : 1;
+
+ uint32_t MBEDTLS_PRIVATE(num_ops);
+};
+
+#define PSA_SIGN_HASH_INTERRUPTIBLE_OPERATION_INIT { 0, { 0 }, 0, 0 }
+
+static inline struct psa_sign_hash_interruptible_operation_s
+psa_sign_hash_interruptible_operation_init(void)
+{
+ const struct psa_sign_hash_interruptible_operation_s v =
+ PSA_SIGN_HASH_INTERRUPTIBLE_OPERATION_INIT;
+
+ return v;
+}
+
+/**
+ * \brief The context for PSA interruptible hash verification.
+ */
+struct psa_verify_hash_interruptible_operation_s {
+ /** Unique ID indicating which driver got assigned to do the
+ * operation. Since driver contexts are driver-specific, swapping
+ * drivers halfway through the operation is not supported.
+ * ID values are auto-generated in psa_crypto_driver_wrappers.h
+ * ID value zero means the context is not valid or not assigned to
+ * any driver (i.e. none of the driver contexts are active). */
+ unsigned int MBEDTLS_PRIVATE(id);
+
+ psa_driver_verify_hash_interruptible_context_t MBEDTLS_PRIVATE(ctx);
+
+ unsigned int MBEDTLS_PRIVATE(error_occurred) : 1;
+
+ uint32_t MBEDTLS_PRIVATE(num_ops);
+};
+
+#define PSA_VERIFY_HASH_INTERRUPTIBLE_OPERATION_INIT { 0, { 0 }, 0, 0 }
+
+static inline struct psa_verify_hash_interruptible_operation_s
+psa_verify_hash_interruptible_operation_init(void)
+{
+ const struct psa_verify_hash_interruptible_operation_s v =
+ PSA_VERIFY_HASH_INTERRUPTIBLE_OPERATION_INIT;
+
+ return v;
+}
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* PSA_CRYPTO_STRUCT_H */
diff --git a/include/psa/crypto_types.h b/include/psa/crypto_types.h
new file mode 100644
index 0000000..5a1318d
--- /dev/null
+++ b/include/psa/crypto_types.h
@@ -0,0 +1,453 @@
+/**
+ * \file psa/crypto_types.h
+ *
+ * \brief PSA cryptography module: type aliases.
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h. Drivers must include the appropriate driver
+ * header file.
+ *
+ * This file contains portable definitions of integral types for properties
+ * of cryptographic keys, designations of cryptographic algorithms, and
+ * error codes returned by the library.
+ *
+ * This header file does not declare any function.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_TYPES_H
+#define PSA_CRYPTO_TYPES_H
+
+/* Make sure the Mbed TLS configuration is visible. */
+#include "mbedtls/build_info.h"
+/* Define the MBEDTLS_PRIVATE macro. */
+#include "mbedtls/private_access.h"
+
+#if defined(MBEDTLS_PSA_CRYPTO_PLATFORM_FILE)
+#include MBEDTLS_PSA_CRYPTO_PLATFORM_FILE
+#else
+#include "crypto_platform.h"
+#endif
+
+#include <stdint.h>
+
+/** \defgroup error Error codes
+ * @{
+ */
+
+/**
+ * \brief Function return status.
+ *
+ * This is either #PSA_SUCCESS (which is zero), indicating success,
+ * or a small negative value indicating that an error occurred. Errors are
+ * encoded as one of the \c PSA_ERROR_xxx values defined here. */
+/* If #PSA_SUCCESS is already defined, it means that #psa_status_t
+ * is also defined in an external header, so prevent its multiple
+ * definition.
+ */
+#ifndef PSA_SUCCESS
+typedef int32_t psa_status_t;
+#endif
+
+/**@}*/
+
+/** \defgroup crypto_types Key and algorithm types
+ * @{
+ */
+
+/** \brief Encoding of a key type.
+ *
+ * Values of this type are generally constructed by macros called
+ * `PSA_KEY_TYPE_xxx`.
+ *
+ * \note Values of this type are encoded in the persistent key store.
+ * Any changes to existing values will require bumping the storage
+ * format version and providing a translation when reading the old
+ * format.
+ */
+typedef uint16_t psa_key_type_t;
+
+/** The type of PSA elliptic curve family identifiers.
+ *
+ * Values of this type are generally constructed by macros called
+ * `PSA_ECC_FAMILY_xxx`.
+ *
+ * The curve identifier is required to create an ECC key using the
+ * PSA_KEY_TYPE_ECC_KEY_PAIR() or PSA_KEY_TYPE_ECC_PUBLIC_KEY()
+ * macros.
+ *
+ * Values defined by this standard will never be in the range 0x80-0xff.
+ * Vendors who define additional families must use an encoding in this range.
+ *
+ * \note Values of this type are encoded in the persistent key store.
+ * Any changes to existing values will require bumping the storage
+ * format version and providing a translation when reading the old
+ * format.
+ */
+typedef uint8_t psa_ecc_family_t;
+
+/** The type of PSA Diffie-Hellman group family identifiers.
+ *
+ * Values of this type are generally constructed by macros called
+ * `PSA_DH_FAMILY_xxx`.
+ *
+ * The group identifier is required to create a Diffie-Hellman key using the
+ * PSA_KEY_TYPE_DH_KEY_PAIR() or PSA_KEY_TYPE_DH_PUBLIC_KEY()
+ * macros.
+ *
+ * Values defined by this standard will never be in the range 0x80-0xff.
+ * Vendors who define additional families must use an encoding in this range.
+ *
+ * \note Values of this type are encoded in the persistent key store.
+ * Any changes to existing values will require bumping the storage
+ * format version and providing a translation when reading the old
+ * format.
+ */
+typedef uint8_t psa_dh_family_t;
+
+/** \brief Encoding of a cryptographic algorithm.
+ *
+ * Values of this type are generally constructed by macros called
+ * `PSA_ALG_xxx`.
+ *
+ * For algorithms that can be applied to multiple key types, this type
+ * does not encode the key type. For example, for symmetric ciphers
+ * based on a block cipher, #psa_algorithm_t encodes the block cipher
+ * mode and the padding mode while the block cipher itself is encoded
+ * via #psa_key_type_t.
+ *
+ * \note Values of this type are encoded in the persistent key store.
+ * Any changes to existing values will require bumping the storage
+ * format version and providing a translation when reading the old
+ * format.
+ */
+typedef uint32_t psa_algorithm_t;
+
+/**@}*/
+
+/** \defgroup key_lifetimes Key lifetimes
+ * @{
+ */
+
+/** Encoding of key lifetimes.
+ *
+ * The lifetime of a key indicates where it is stored and what system actions
+ * may create and destroy it.
+ *
+ * Lifetime values have the following structure:
+ * - Bits 0-7 (#PSA_KEY_LIFETIME_GET_PERSISTENCE(\c lifetime)):
+ * persistence level. This value indicates what device management
+ * actions can cause it to be destroyed. In particular, it indicates
+ * whether the key is _volatile_ or _persistent_.
+ * See ::psa_key_persistence_t for more information.
+ * - Bits 8-31 (#PSA_KEY_LIFETIME_GET_LOCATION(\c lifetime)):
+ * location indicator. This value indicates which part of the system
+ * has access to the key material and can perform operations using the key.
+ * See ::psa_key_location_t for more information.
+ *
+ * Volatile keys are automatically destroyed when the application instance
+ * terminates or on a power reset of the device. Persistent keys are
+ * preserved until the application explicitly destroys them or until an
+ * integration-specific device management event occurs (for example,
+ * a factory reset).
+ *
+ * Persistent keys have a key identifier of type #mbedtls_svc_key_id_t.
+ * This identifier remains valid throughout the lifetime of the key,
+ * even if the application instance that created the key terminates.
+ * The application can call psa_open_key() to open a persistent key that
+ * it created previously.
+ *
+ * The default lifetime of a key is #PSA_KEY_LIFETIME_VOLATILE. The lifetime
+ * #PSA_KEY_LIFETIME_PERSISTENT is supported if persistent storage is
+ * available. Other lifetime values may be supported depending on the
+ * library configuration.
+ *
+ * Values of this type are generally constructed by macros called
+ * `PSA_KEY_LIFETIME_xxx`.
+ *
+ * \note Values of this type are encoded in the persistent key store.
+ * Any changes to existing values will require bumping the storage
+ * format version and providing a translation when reading the old
+ * format.
+ */
+typedef uint32_t psa_key_lifetime_t;
+
+/** Encoding of key persistence levels.
+ *
+ * What distinguishes different persistence levels is what device management
+ * events may cause keys to be destroyed. _Volatile_ keys are destroyed
+ * by a power reset. Persistent keys may be destroyed by events such as
+ * a transfer of ownership or a factory reset. What management events
+ * actually affect persistent keys at different levels is outside the
+ * scope of the PSA Cryptography specification.
+ *
+ * The PSA Cryptography specification defines the following values of
+ * persistence levels:
+ * - \c 0 = #PSA_KEY_PERSISTENCE_VOLATILE: volatile key.
+ * A volatile key is automatically destroyed by the implementation when
+ * the application instance terminates. In particular, a volatile key
+ * is automatically destroyed on a power reset of the device.
+ * - \c 1 = #PSA_KEY_PERSISTENCE_DEFAULT:
+ * persistent key with a default lifetime.
+ * - \c 2-254: currently not supported by Mbed TLS.
+ * - \c 255 = #PSA_KEY_PERSISTENCE_READ_ONLY:
+ * read-only or write-once key.
+ * A key with this persistence level cannot be destroyed.
+ * Mbed TLS does not currently offer a way to create such keys, but
+ * integrations of Mbed TLS can use it for built-in keys that the
+ * application cannot modify (for example, a hardware unique key (HUK)).
+ *
+ * \note Key persistence levels are 8-bit values. Key management
+ * interfaces operate on lifetimes (type ::psa_key_lifetime_t) which
+ * encode the persistence as the lower 8 bits of a 32-bit value.
+ *
+ * \note Values of this type are encoded in the persistent key store.
+ * Any changes to existing values will require bumping the storage
+ * format version and providing a translation when reading the old
+ * format.
+ */
+typedef uint8_t psa_key_persistence_t;
+
+/** Encoding of key location indicators.
+ *
+ * If an integration of Mbed TLS can make calls to external
+ * cryptoprocessors such as secure elements, the location of a key
+ * indicates which secure element performs the operations on the key.
+ * Depending on the design of the secure element, the key
+ * material may be stored either in the secure element, or
+ * in wrapped (encrypted) form alongside the key metadata in the
+ * primary local storage.
+ *
+ * The PSA Cryptography API specification defines the following values of
+ * location indicators:
+ * - \c 0: primary local storage.
+ * This location is always available.
+ * The primary local storage is typically the same storage area that
+ * contains the key metadata.
+ * - \c 1: primary secure element.
+ * Integrations of Mbed TLS should support this value if there is a secure
+ * element attached to the operating environment.
+ * As a guideline, secure elements may provide higher resistance against
+ * side channel and physical attacks than the primary local storage, but may
+ * have restrictions on supported key types, sizes, policies and operations
+ * and may have different performance characteristics.
+ * - \c 2-0x7fffff: other locations defined by a PSA specification.
+ * The PSA Cryptography API does not currently assign any meaning to these
+ * locations, but future versions of that specification or other PSA
+ * specifications may do so.
+ * - \c 0x800000-0xffffff: vendor-defined locations.
+ * No PSA specification will assign a meaning to locations in this range.
+ *
+ * \note Key location indicators are 24-bit values. Key management
+ * interfaces operate on lifetimes (type ::psa_key_lifetime_t) which
+ * encode the location as the upper 24 bits of a 32-bit value.
+ *
+ * \note Values of this type are encoded in the persistent key store.
+ * Any changes to existing values will require bumping the storage
+ * format version and providing a translation when reading the old
+ * format.
+ */
+typedef uint32_t psa_key_location_t;
+
+/** Encoding of identifiers of persistent keys.
+ *
+ * - Applications may freely choose key identifiers in the range
+ * #PSA_KEY_ID_USER_MIN to #PSA_KEY_ID_USER_MAX.
+ * - The implementation may define additional key identifiers in the range
+ * #PSA_KEY_ID_VENDOR_MIN to #PSA_KEY_ID_VENDOR_MAX.
+ * - 0 is reserved as an invalid key identifier.
+ * - Key identifiers outside these ranges are reserved for future use.
+ *
+ * \note Values of this type are encoded in the persistent key store.
+ * Any changes to how values are allocated must require careful
+ * consideration to allow backward compatibility.
+ */
+typedef uint32_t psa_key_id_t;
+
+/** Encoding of key identifiers as seen inside the PSA Crypto implementation.
+ *
+ * When PSA Crypto is built as a library inside an application, this type
+ * is identical to #psa_key_id_t. When PSA Crypto is built as a service
+ * that can store keys on behalf of multiple clients, this type
+ * encodes the #psa_key_id_t value seen by each client application as
+ * well as extra information that identifies the client that owns
+ * the key.
+ *
+ * \note Values of this type are encoded in the persistent key store.
+ * Any changes to existing values will require bumping the storage
+ * format version and providing a translation when reading the old
+ * format.
+ */
+#if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
+typedef psa_key_id_t mbedtls_svc_key_id_t;
+
+#else /* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */
+/* Implementation-specific: The Mbed TLS library can be built as
+ * part of a multi-client service that exposes the PSA Cryptography API in each
+ * client and encodes the client identity in the key identifier argument of
+ * functions such as psa_open_key().
+ */
+typedef struct {
+ psa_key_id_t MBEDTLS_PRIVATE(key_id);
+ mbedtls_key_owner_id_t MBEDTLS_PRIVATE(owner);
+} mbedtls_svc_key_id_t;
+
+#endif /* !MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */
+
+/**@}*/
+
+/** \defgroup policy Key policies
+ * @{
+ */
+
+/** \brief Encoding of permitted usage on a key.
+ *
+ * Values of this type are generally constructed as bitwise-ors of macros
+ * called `PSA_KEY_USAGE_xxx`.
+ *
+ * \note Values of this type are encoded in the persistent key store.
+ * Any changes to existing values will require bumping the storage
+ * format version and providing a translation when reading the old
+ * format.
+ */
+typedef uint32_t psa_key_usage_t;
+
+/**@}*/
+
+/** \defgroup attributes Key attributes
+ * @{
+ */
+
+/** The type of a structure containing key attributes.
+ *
+ * This is an opaque structure that can represent the metadata of a key
+ * object. Metadata that can be stored in attributes includes:
+ * - The location of the key in storage, indicated by its key identifier
+ * and its lifetime.
+ * - The key's policy, comprising usage flags and a specification of
+ * the permitted algorithm(s).
+ * - Information about the key itself: the key type and its size.
+ * - Additional implementation-defined attributes.
+ *
+ * The actual key material is not considered an attribute of a key.
+ * Key attributes do not contain information that is generally considered
+ * highly confidential.
+ *
+ * An attribute structure works like a simple data structure where each function
+ * `psa_set_key_xxx` sets a field and the corresponding function
+ * `psa_get_key_xxx` retrieves the value of the corresponding field.
+ * However, a future version of the library may report values that are
+ * equivalent to the original one, but have a different encoding. Invalid
+ * values may be mapped to different, also invalid values.
+ *
+ * An attribute structure may contain references to auxiliary resources,
+ * for example pointers to allocated memory or indirect references to
+ * pre-calculated values. In order to free such resources, the application
+ * must call psa_reset_key_attributes(). As an exception, calling
+ * psa_reset_key_attributes() on an attribute structure is optional if
+ * the structure has only been modified by the following functions
+ * since it was initialized or last reset with psa_reset_key_attributes():
+ * - psa_set_key_id()
+ * - psa_set_key_lifetime()
+ * - psa_set_key_type()
+ * - psa_set_key_bits()
+ * - psa_set_key_usage_flags()
+ * - psa_set_key_algorithm()
+ *
+ * Before calling any function on a key attribute structure, the application
+ * must initialize it by any of the following means:
+ * - Set the structure to all-bits-zero, for example:
+ * \code
+ * psa_key_attributes_t attributes;
+ * memset(&attributes, 0, sizeof(attributes));
+ * \endcode
+ * - Initialize the structure to logical zero values, for example:
+ * \code
+ * psa_key_attributes_t attributes = {0};
+ * \endcode
+ * - Initialize the structure to the initializer #PSA_KEY_ATTRIBUTES_INIT,
+ * for example:
+ * \code
+ * psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT;
+ * \endcode
+ * - Assign the result of the function psa_key_attributes_init()
+ * to the structure, for example:
+ * \code
+ * psa_key_attributes_t attributes;
+ * attributes = psa_key_attributes_init();
+ * \endcode
+ *
+ * A freshly initialized attribute structure contains the following
+ * values:
+ *
+ * - lifetime: #PSA_KEY_LIFETIME_VOLATILE.
+ * - key identifier: 0 (which is not a valid key identifier).
+ * - type: \c 0 (meaning that the type is unspecified).
+ * - key size: \c 0 (meaning that the size is unspecified).
+ * - usage flags: \c 0 (which allows no usage except exporting a public key).
+ * - algorithm: \c 0 (which allows no cryptographic usage, but allows
+ * exporting).
+ *
+ * A typical sequence to create a key is as follows:
+ * -# Create and initialize an attribute structure.
+ * -# If the key is persistent, call psa_set_key_id().
+ * Also call psa_set_key_lifetime() to place the key in a non-default
+ * location.
+ * -# Set the key policy with psa_set_key_usage_flags() and
+ * psa_set_key_algorithm().
+ * -# Set the key type with psa_set_key_type().
+ * Skip this step if copying an existing key with psa_copy_key().
+ * -# When generating a random key with psa_generate_key() or deriving a key
+ * with psa_key_derivation_output_key(), set the desired key size with
+ * psa_set_key_bits().
+ * -# Call a key creation function: psa_import_key(), psa_generate_key(),
+ * psa_key_derivation_output_key() or psa_copy_key(). This function reads
+ * the attribute structure, creates a key with these attributes, and
+ * outputs a key identifier to the newly created key.
+ * -# The attribute structure is now no longer necessary.
+ * You may call psa_reset_key_attributes(), although this is optional
+ * with the workflow presented here because the attributes currently
+ * defined in this specification do not require any additional resources
+ * beyond the structure itself.
+ *
+ * A typical sequence to query a key's attributes is as follows:
+ * -# Call psa_get_key_attributes().
+ * -# Call `psa_get_key_xxx` functions to retrieve the attribute(s) that
+ * you are interested in.
+ * -# Call psa_reset_key_attributes() to free any resources that may be
+ * used by the attribute structure.
+ *
+ * Once a key has been created, it is impossible to change its attributes.
+ */
+typedef struct psa_key_attributes_s psa_key_attributes_t;
+
+
+#ifndef __DOXYGEN_ONLY__
+#if defined(MBEDTLS_PSA_CRYPTO_SE_C)
+/* Mbed TLS defines this type in crypto_types.h because it is also
+ * visible to applications through an implementation-specific extension.
+ * For the PSA Cryptography specification, this type is only visible
+ * via crypto_se_driver.h. */
+typedef uint64_t psa_key_slot_number_t;
+#endif /* MBEDTLS_PSA_CRYPTO_SE_C */
+#endif /* !__DOXYGEN_ONLY__ */
+
+/**@}*/
+
+/** \defgroup derivation Key derivation
+ * @{
+ */
+
+/** \brief Encoding of the step of a key derivation.
+ *
+ * Values of this type are generally constructed by macros called
+ * `PSA_KEY_DERIVATION_INPUT_xxx`.
+ */
+typedef uint16_t psa_key_derivation_step_t;
+
+/**@}*/
+
+#endif /* PSA_CRYPTO_TYPES_H */
diff --git a/include/psa/crypto_values.h b/include/psa/crypto_values.h
new file mode 100644
index 0000000..a17879b
--- /dev/null
+++ b/include/psa/crypto_values.h
@@ -0,0 +1,2763 @@
+/**
+ * \file psa/crypto_values.h
+ *
+ * \brief PSA cryptography module: macros to build and analyze integer values.
+ *
+ * \note This file may not be included directly. Applications must
+ * include psa/crypto.h. Drivers must include the appropriate driver
+ * header file.
+ *
+ * This file contains portable definitions of macros to build and analyze
+ * values of integral types that encode properties of cryptographic keys,
+ * designations of cryptographic algorithms, and error codes returned by
+ * the library.
+ *
+ * Note that many of the constants defined in this file are embedded in
+ * the persistent key store, as part of key metadata (including usage
+ * policies). As a consequence, they must not be changed (unless the storage
+ * format version changes).
+ *
+ * This header file only defines preprocessor macros.
+ */
+/*
+ * Copyright The Mbed TLS Contributors
+ * SPDX-License-Identifier: Apache-2.0 OR GPL-2.0-or-later
+ */
+
+#ifndef PSA_CRYPTO_VALUES_H
+#define PSA_CRYPTO_VALUES_H
+#include "mbedtls/private_access.h"
+
+/** \defgroup error Error codes
+ * @{
+ */
+
+/* PSA error codes */
+
+/* Error codes are standardized across PSA domains (framework, crypto, storage,
+ * etc.). Do not change the values in this section or even the expansions
+ * of each macro: it must be possible to `#include` both this header
+ * and some other PSA component's headers in the same C source,
+ * which will lead to duplicate definitions of the `PSA_SUCCESS` and
+ * `PSA_ERROR_xxx` macros, which is ok if and only if the macros expand
+ * to the same sequence of tokens.
+ *
+ * If you must add a new
+ * value, check with the Arm PSA framework group to pick one that other
+ * domains aren't already using. */
+
+/* Tell uncrustify not to touch the constant definitions, otherwise
+ * it might change the spacing to something that is not PSA-compliant
+ * (e.g. adding a space after casts).
+ *
+ * *INDENT-OFF*
+ */
+
+/** The action was completed successfully. */
+#define PSA_SUCCESS ((psa_status_t)0)
+
+/** An error occurred that does not correspond to any defined
+ * failure cause.
+ *
+ * Implementations may use this error code if none of the other standard
+ * error codes are applicable. */
+#define PSA_ERROR_GENERIC_ERROR ((psa_status_t)-132)
+
+/** The requested operation or a parameter is not supported
+ * by this implementation.
+ *
+ * Implementations should return this error code when an enumeration
+ * parameter such as a key type, algorithm, etc. is not recognized.
+ * If a combination of parameters is recognized and identified as
+ * not valid, return #PSA_ERROR_INVALID_ARGUMENT instead. */
+#define PSA_ERROR_NOT_SUPPORTED ((psa_status_t)-134)
+
+/** The requested action is denied by a policy.
+ *
+ * Implementations should return this error code when the parameters
+ * are recognized as valid and supported, and a policy explicitly
+ * denies the requested operation.
+ *
+ * If a subset of the parameters of a function call identify a
+ * forbidden operation, and another subset of the parameters are
+ * not valid or not supported, it is unspecified whether the function
+ * returns #PSA_ERROR_NOT_PERMITTED, #PSA_ERROR_NOT_SUPPORTED or
+ * #PSA_ERROR_INVALID_ARGUMENT. */
+#define PSA_ERROR_NOT_PERMITTED ((psa_status_t)-133)
+
+/** An output buffer is too small.
+ *
+ * Applications can call the \c PSA_xxx_SIZE macro listed in the function
+ * description to determine a sufficient buffer size.
+ *
+ * Implementations should preferably return this error code only
+ * in cases when performing the operation with a larger output
+ * buffer would succeed. However implementations may return this
+ * error if a function has invalid or unsupported parameters in addition
+ * to the parameters that determine the necessary output buffer size. */
+#define PSA_ERROR_BUFFER_TOO_SMALL ((psa_status_t)-138)
+
+/** Asking for an item that already exists
+ *
+ * Implementations should return this error, when attempting
+ * to write an item (like a key) that already exists. */
+#define PSA_ERROR_ALREADY_EXISTS ((psa_status_t)-139)
+
+/** Asking for an item that doesn't exist
+ *
+ * Implementations should return this error, if a requested item (like
+ * a key) does not exist. */
+#define PSA_ERROR_DOES_NOT_EXIST ((psa_status_t)-140)
+
+/** The requested action cannot be performed in the current state.
+ *
+ * Multipart operations return this error when one of the
+ * functions is called out of sequence. Refer to the function
+ * descriptions for permitted sequencing of functions.
+ *
+ * Implementations shall not return this error code to indicate
+ * that a key either exists or not,
+ * but shall instead return #PSA_ERROR_ALREADY_EXISTS or #PSA_ERROR_DOES_NOT_EXIST
+ * as applicable.
+ *
+ * Implementations shall not return this error code to indicate that a
+ * key identifier is invalid, but shall return #PSA_ERROR_INVALID_HANDLE
+ * instead. */
+#define PSA_ERROR_BAD_STATE ((psa_status_t)-137)
+
+/** The parameters passed to the function are invalid.
+ *
+ * Implementations may return this error any time a parameter or
+ * combination of parameters are recognized as invalid.
+ *
+ * Implementations shall not return this error code to indicate that a
+ * key identifier is invalid, but shall return #PSA_ERROR_INVALID_HANDLE
+ * instead.
+ */
+#define PSA_ERROR_INVALID_ARGUMENT ((psa_status_t)-135)
+
+/** There is not enough runtime memory.
+ *
+ * If the action is carried out across multiple security realms, this
+ * error can refer to available memory in any of the security realms. */
+#define PSA_ERROR_INSUFFICIENT_MEMORY ((psa_status_t)-141)
+
+/** There is not enough persistent storage.
+ *
+ * Functions that modify the key storage return this error code if
+ * there is insufficient storage space on the host media. In addition,
+ * many functions that do not otherwise access storage may return this
+ * error code if the implementation requires a mandatory log entry for
+ * the requested action and the log storage space is full. */
+#define PSA_ERROR_INSUFFICIENT_STORAGE ((psa_status_t)-142)
+
+/** There was a communication failure inside the implementation.
+ *
+ * This can indicate a communication failure between the application
+ * and an external cryptoprocessor or between the cryptoprocessor and
+ * an external volatile or persistent memory. A communication failure
+ * may be transient or permanent depending on the cause.
+ *
+ * \warning If a function returns this error, it is undetermined
+ * whether the requested action has completed or not. Implementations
+ * should return #PSA_SUCCESS on successful completion whenever
+ * possible, however functions may return #PSA_ERROR_COMMUNICATION_FAILURE
+ * if the requested action was completed successfully in an external
+ * cryptoprocessor but there was a breakdown of communication before
+ * the cryptoprocessor could report the status to the application.
+ */
+#define PSA_ERROR_COMMUNICATION_FAILURE ((psa_status_t)-145)
+
+/** There was a storage failure that may have led to data loss.
+ *
+ * This error indicates that some persistent storage is corrupted.
+ * It should not be used for a corruption of volatile memory
+ * (use #PSA_ERROR_CORRUPTION_DETECTED), for a communication error
+ * between the cryptoprocessor and its external storage (use
+ * #PSA_ERROR_COMMUNICATION_FAILURE), or when the storage is
+ * in a valid state but is full (use #PSA_ERROR_INSUFFICIENT_STORAGE).
+ *
+ * Note that a storage failure does not indicate that any data that was
+ * previously read is invalid. However this previously read data may no
+ * longer be readable from storage.
+ *
+ * When a storage failure occurs, it is no longer possible to ensure
+ * the global integrity of the keystore. Depending on the global
+ * integrity guarantees offered by the implementation, access to other
+ * data may or may not fail even if the data is still readable but
+ * its integrity cannot be guaranteed.
+ *
+ * Implementations should only use this error code to report a
+ * permanent storage corruption. However application writers should
+ * keep in mind that transient errors while reading the storage may be
+ * reported using this error code. */
+#define PSA_ERROR_STORAGE_FAILURE ((psa_status_t)-146)
+
+/** A hardware failure was detected.
+ *
+ * A hardware failure may be transient or permanent depending on the
+ * cause. */
+#define PSA_ERROR_HARDWARE_FAILURE ((psa_status_t)-147)
+
+/** A tampering attempt was detected.
+ *
+ * If an application receives this error code, there is no guarantee
+ * that previously accessed or computed data was correct and remains
+ * confidential. Applications should not perform any security function
+ * and should enter a safe failure state.
+ *
+ * Implementations may return this error code if they detect an invalid
+ * state that cannot happen during normal operation and that indicates
+ * that the implementation's security guarantees no longer hold. Depending
+ * on the implementation architecture and on its security and safety goals,
+ * the implementation may forcibly terminate the application.
+ *
+ * This error code is intended as a last resort when a security breach
+ * is detected and it is unsure whether the keystore data is still
+ * protected. Implementations shall only return this error code
+ * to report an alarm from a tampering detector, to indicate that
+ * the confidentiality of stored data can no longer be guaranteed,
+ * or to indicate that the integrity of previously returned data is now
+ * considered compromised. Implementations shall not use this error code
+ * to indicate a hardware failure that merely makes it impossible to
+ * perform the requested operation (use #PSA_ERROR_COMMUNICATION_FAILURE,
+ * #PSA_ERROR_STORAGE_FAILURE, #PSA_ERROR_HARDWARE_FAILURE,
+ * #PSA_ERROR_INSUFFICIENT_ENTROPY or other applicable error code
+ * instead).
+ *
+ * This error indicates an attack against the application. Implementations
+ * shall not return this error code as a consequence of the behavior of
+ * the application itself. */
+#define PSA_ERROR_CORRUPTION_DETECTED ((psa_status_t)-151)
+
+/** There is not enough entropy to generate random data needed
+ * for the requested action.
+ *
+ * This error indicates a failure of a hardware random generator.
+ * Application writers should note that this error can be returned not
+ * only by functions whose purpose is to generate random data, such
+ * as key, IV or nonce generation, but also by functions that execute
+ * an algorithm with a randomized result, as well as functions that
+ * use randomization of intermediate computations as a countermeasure
+ * to certain attacks.
+ *
+ * Implementations should avoid returning this error after psa_crypto_init()
+ * has succeeded. Implementations should generate sufficient
+ * entropy during initialization and subsequently use a cryptographically
+ * secure pseudorandom generator (PRNG). However implementations may return
+ * this error at any time if a policy requires the PRNG to be reseeded
+ * during normal operation. */
+#define PSA_ERROR_INSUFFICIENT_ENTROPY ((psa_status_t)-148)
+
+/** The signature, MAC or hash is incorrect.
+ *
+ * Verification functions return this error if the verification
+ * calculations completed successfully, and the value to be verified
+ * was determined to be incorrect.
+ *
+ * If the value to verify has an invalid size, implementations may return
+ * either #PSA_ERROR_INVALID_ARGUMENT or #PSA_ERROR_INVALID_SIGNATURE. */
+#define PSA_ERROR_INVALID_SIGNATURE ((psa_status_t)-149)
+
+/** The decrypted padding is incorrect.
+ *
+ * \warning In some protocols, when decrypting data, it is essential that
+ * the behavior of the application does not depend on whether the padding
+ * is correct, down to precise timing. Applications should prefer
+ * protocols that use authenticated encryption rather than plain
+ * encryption. If the application must perform a decryption of
+ * unauthenticated data, the application writer should take care not
+ * to reveal whether the padding is invalid.
+ *
+ * Implementations should strive to make valid and invalid padding
+ * as close as possible to indistinguishable to an external observer.
+ * In particular, the timing of a decryption operation should not
+ * depend on the validity of the padding. */
+#define PSA_ERROR_INVALID_PADDING ((psa_status_t)-150)
+
+/** Return this error when there's insufficient data when attempting
+ * to read from a resource. */
+#define PSA_ERROR_INSUFFICIENT_DATA ((psa_status_t)-143)
+
+/** The key identifier is not valid. See also :ref:\`key-handles\`.
+ */
+#define PSA_ERROR_INVALID_HANDLE ((psa_status_t)-136)
+
+/** Stored data has been corrupted.
+ *
+ * This error indicates that some persistent storage has suffered corruption.
+ * It does not indicate the following situations, which have specific error
+ * codes:
+ *
+ * - A corruption of volatile memory - use #PSA_ERROR_CORRUPTION_DETECTED.
+ * - A communication error between the cryptoprocessor and its external
+ * storage - use #PSA_ERROR_COMMUNICATION_FAILURE.
+ * - When the storage is in a valid state but is full - use
+ * #PSA_ERROR_INSUFFICIENT_STORAGE.
+ * - When the storage fails for other reasons - use
+ * #PSA_ERROR_STORAGE_FAILURE.
+ * - When the stored data is not valid - use #PSA_ERROR_DATA_INVALID.
+ *
+ * \note A storage corruption does not indicate that any data that was
+ * previously read is invalid. However this previously read data might no
+ * longer be readable from storage.
+ *
+ * When a storage failure occurs, it is no longer possible to ensure the
+ * global integrity of the keystore.
+ */
+#define PSA_ERROR_DATA_CORRUPT ((psa_status_t)-152)
+
+/** Data read from storage is not valid for the implementation.
+ *
+ * This error indicates that some data read from storage does not have a valid
+ * format. It does not indicate the following situations, which have specific
+ * error codes:
+ *
+ * - When the storage or stored data is corrupted - use #PSA_ERROR_DATA_CORRUPT
+ * - When the storage fails for other reasons - use #PSA_ERROR_STORAGE_FAILURE
+ * - An invalid argument to the API - use #PSA_ERROR_INVALID_ARGUMENT
+ *
+ * This error is typically a result of either storage corruption on a
+ * cleartext storage backend, or an attempt to read data that was
+ * written by an incompatible version of the library.
+ */
+#define PSA_ERROR_DATA_INVALID ((psa_status_t)-153)
+
+/** The function that returns this status is defined as interruptible and
+ * still has work to do, thus the user should call the function again with the
+ * same operation context until it either returns #PSA_SUCCESS or any other
+ * error. This is not an error per se, more a notification of status.
+ */
+#define PSA_OPERATION_INCOMPLETE ((psa_status_t)-248)
+
+/* *INDENT-ON* */
+
+/**@}*/
+
+/** \defgroup crypto_types Key and algorithm types
+ * @{
+ */
+
+/* Note that key type values, including ECC family and DH group values, are
+ * embedded in the persistent key store, as part of key metadata. As a
+ * consequence, they must not be changed (unless the storage format version
+ * changes).
+ */
+
+/** An invalid key type value.
+ *
+ * Zero is not the encoding of any key type.
+ */
+#define PSA_KEY_TYPE_NONE ((psa_key_type_t) 0x0000)
+
+/** Vendor-defined key type flag.
+ *
+ * Key types defined by this standard will never have the
+ * #PSA_KEY_TYPE_VENDOR_FLAG bit set. Vendors who define additional key types
+ * must use an encoding with the #PSA_KEY_TYPE_VENDOR_FLAG bit set and should
+ * respect the bitwise structure used by standard encodings whenever practical.
+ */
+#define PSA_KEY_TYPE_VENDOR_FLAG ((psa_key_type_t) 0x8000)
+
+#define PSA_KEY_TYPE_CATEGORY_MASK ((psa_key_type_t) 0x7000)
+#define PSA_KEY_TYPE_CATEGORY_RAW ((psa_key_type_t) 0x1000)
+#define PSA_KEY_TYPE_CATEGORY_SYMMETRIC ((psa_key_type_t) 0x2000)
+#define PSA_KEY_TYPE_CATEGORY_PUBLIC_KEY ((psa_key_type_t) 0x4000)
+#define PSA_KEY_TYPE_CATEGORY_KEY_PAIR ((psa_key_type_t) 0x7000)
+
+#define PSA_KEY_TYPE_CATEGORY_FLAG_PAIR ((psa_key_type_t) 0x3000)
+
+/** Whether a key type is vendor-defined.
+ *
+ * See also #PSA_KEY_TYPE_VENDOR_FLAG.
+ */
+#define PSA_KEY_TYPE_IS_VENDOR_DEFINED(type) \
+ (((type) & PSA_KEY_TYPE_VENDOR_FLAG) != 0)
+
+/** Whether a key type is an unstructured array of bytes.
+ *
+ * This encompasses both symmetric keys and non-key data.
+ */
+#define PSA_KEY_TYPE_IS_UNSTRUCTURED(type) \
+ (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_RAW || \
+ ((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_SYMMETRIC)
+
+/** Whether a key type is asymmetric: either a key pair or a public key. */
+#define PSA_KEY_TYPE_IS_ASYMMETRIC(type) \
+ (((type) & PSA_KEY_TYPE_CATEGORY_MASK \
+ & ~PSA_KEY_TYPE_CATEGORY_FLAG_PAIR) == \
+ PSA_KEY_TYPE_CATEGORY_PUBLIC_KEY)
+/** Whether a key type is the public part of a key pair. */
+#define PSA_KEY_TYPE_IS_PUBLIC_KEY(type) \
+ (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_PUBLIC_KEY)
+/** Whether a key type is a key pair containing a private part and a public
+ * part. */
+#define PSA_KEY_TYPE_IS_KEY_PAIR(type) \
+ (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_KEY_PAIR)
+/** The key pair type corresponding to a public key type.
+ *
+ * You may also pass a key pair type as \p type, it will be left unchanged.
+ *
+ * \param type A public key type or key pair type.
+ *
+ * \return The corresponding key pair type.
+ * If \p type is not a public key or a key pair,
+ * the return value is undefined.
+ */
+#define PSA_KEY_TYPE_KEY_PAIR_OF_PUBLIC_KEY(type) \
+ ((type) | PSA_KEY_TYPE_CATEGORY_FLAG_PAIR)
+/** The public key type corresponding to a key pair type.
+ *
+ * You may also pass a key pair type as \p type, it will be left unchanged.
+ *
+ * \param type A public key type or key pair type.
+ *
+ * \return The corresponding public key type.
+ * If \p type is not a public key or a key pair,
+ * the return value is undefined.
+ */
+#define PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) \
+ ((type) & ~PSA_KEY_TYPE_CATEGORY_FLAG_PAIR)
+
+/** Raw data.
+ *
+ * A "key" of this type cannot be used for any cryptographic operation.
+ * Applications may use this type to store arbitrary data in the keystore. */
+#define PSA_KEY_TYPE_RAW_DATA ((psa_key_type_t) 0x1001)
+
+/** HMAC key.
+ *
+ * The key policy determines which underlying hash algorithm the key can be
+ * used for.
+ *
+ * HMAC keys should generally have the same size as the underlying hash.
+ * This size can be calculated with #PSA_HASH_LENGTH(\c alg) where
+ * \c alg is the HMAC algorithm or the underlying hash algorithm. */
+#define PSA_KEY_TYPE_HMAC ((psa_key_type_t) 0x1100)
+
+/** A secret for key derivation.
+ *
+ * This key type is for high-entropy secrets only. For low-entropy secrets,
+ * #PSA_KEY_TYPE_PASSWORD should be used instead.
+ *
+ * These keys can be used as the #PSA_KEY_DERIVATION_INPUT_SECRET or
+ * #PSA_KEY_DERIVATION_INPUT_PASSWORD input of key derivation algorithms.
+ *
+ * The key policy determines which key derivation algorithm the key
+ * can be used for.
+ */
+#define PSA_KEY_TYPE_DERIVE ((psa_key_type_t) 0x1200)
+
+/** A low-entropy secret for password hashing or key derivation.
+ *
+ * This key type is suitable for passwords and passphrases which are typically
+ * intended to be memorizable by humans, and have a low entropy relative to
+ * their size. It can be used for randomly generated or derived keys with
+ * maximum or near-maximum entropy, but #PSA_KEY_TYPE_DERIVE is more suitable
+ * for such keys. It is not suitable for passwords with extremely low entropy,
+ * such as numerical PINs.
+ *
+ * These keys can be used as the #PSA_KEY_DERIVATION_INPUT_PASSWORD input of
+ * key derivation algorithms. Algorithms that accept such an input were
+ * designed to accept low-entropy secret and are known as password hashing or
+ * key stretching algorithms.
+ *
+ * These keys cannot be used as the #PSA_KEY_DERIVATION_INPUT_SECRET input of
+ * key derivation algorithms, as the algorithms that take such an input expect
+ * it to be high-entropy.
+ *
+ * The key policy determines which key derivation algorithm the key can be
+ * used for, among the permissible subset defined above.
+ */
+#define PSA_KEY_TYPE_PASSWORD ((psa_key_type_t) 0x1203)
+
+/** A secret value that can be used to verify a password hash.
+ *
+ * The key policy determines which key derivation algorithm the key
+ * can be used for, among the same permissible subset as for
+ * #PSA_KEY_TYPE_PASSWORD.
+ */
+#define PSA_KEY_TYPE_PASSWORD_HASH ((psa_key_type_t) 0x1205)
+
+/** A secret value that can be used in when computing a password hash.
+ *
+ * The key policy determines which key derivation algorithm the key
+ * can be used for, among the subset of algorithms that can use pepper.
+ */
+#define PSA_KEY_TYPE_PEPPER ((psa_key_type_t) 0x1206)
+
+/** Key for a cipher, AEAD or MAC algorithm based on the AES block cipher.
+ *
+ * The size of the key can be 16 bytes (AES-128), 24 bytes (AES-192) or
+ * 32 bytes (AES-256).
+ */
+#define PSA_KEY_TYPE_AES ((psa_key_type_t) 0x2400)
+
+/** Key for a cipher, AEAD or MAC algorithm based on the
+ * ARIA block cipher. */
+#define PSA_KEY_TYPE_ARIA ((psa_key_type_t) 0x2406)
+
+/** Key for a cipher or MAC algorithm based on DES or 3DES (Triple-DES).
+ *
+ * The size of the key can be 64 bits (single DES), 128 bits (2-key 3DES) or
+ * 192 bits (3-key 3DES).
+ *
+ * Note that single DES and 2-key 3DES are weak and strongly
+ * deprecated and should only be used to decrypt legacy data. 3-key 3DES
+ * is weak and deprecated and should only be used in legacy protocols.
+ */
+#define PSA_KEY_TYPE_DES ((psa_key_type_t) 0x2301)
+
+/** Key for a cipher, AEAD or MAC algorithm based on the
+ * Camellia block cipher. */
+#define PSA_KEY_TYPE_CAMELLIA ((psa_key_type_t) 0x2403)
+
+/** Key for the ChaCha20 stream cipher or the Chacha20-Poly1305 AEAD algorithm.
+ *
+ * ChaCha20 and the ChaCha20_Poly1305 construction are defined in RFC 7539.
+ *
+ * \note For ChaCha20 and ChaCha20_Poly1305, Mbed TLS only supports
+ * 12-byte nonces.
+ *
+ * \note For ChaCha20, the initial counter value is 0. To encrypt or decrypt
+ * with the initial counter value 1, you can process and discard a
+ * 64-byte block before the real data.
+ */
+#define PSA_KEY_TYPE_CHACHA20 ((psa_key_type_t) 0x2004)
+
+/** RSA public key.
+ *
+ * The size of an RSA key is the bit size of the modulus.
+ */
+#define PSA_KEY_TYPE_RSA_PUBLIC_KEY ((psa_key_type_t) 0x4001)
+/** RSA key pair (private and public key).
+ *
+ * The size of an RSA key is the bit size of the modulus.
+ */
+#define PSA_KEY_TYPE_RSA_KEY_PAIR ((psa_key_type_t) 0x7001)
+/** Whether a key type is an RSA key (pair or public-only). */
+#define PSA_KEY_TYPE_IS_RSA(type) \
+ (PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) == PSA_KEY_TYPE_RSA_PUBLIC_KEY)
+
+#define PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE ((psa_key_type_t) 0x4100)
+#define PSA_KEY_TYPE_ECC_KEY_PAIR_BASE ((psa_key_type_t) 0x7100)
+#define PSA_KEY_TYPE_ECC_CURVE_MASK ((psa_key_type_t) 0x00ff)
+/** Elliptic curve key pair.
+ *
+ * The size of an elliptic curve key is the bit size associated with the curve,
+ * i.e. the bit size of *q* for a curve over a field *F<sub>q</sub>*.
+ * See the documentation of `PSA_ECC_FAMILY_xxx` curve families for details.
+ *
+ * \param curve A value of type ::psa_ecc_family_t that
+ * identifies the ECC curve to be used.
+ */
+#define PSA_KEY_TYPE_ECC_KEY_PAIR(curve) \
+ (PSA_KEY_TYPE_ECC_KEY_PAIR_BASE | (curve))
+/** Elliptic curve public key.
+ *
+ * The size of an elliptic curve public key is the same as the corresponding
+ * private key (see #PSA_KEY_TYPE_ECC_KEY_PAIR and the documentation of
+ * `PSA_ECC_FAMILY_xxx` curve families).
+ *
+ * \param curve A value of type ::psa_ecc_family_t that
+ * identifies the ECC curve to be used.
+ */
+#define PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve) \
+ (PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE | (curve))
+
+/** Whether a key type is an elliptic curve key (pair or public-only). */
+#define PSA_KEY_TYPE_IS_ECC(type) \
+ ((PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) & \
+ ~PSA_KEY_TYPE_ECC_CURVE_MASK) == PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE)
+/** Whether a key type is an elliptic curve key pair. */
+#define PSA_KEY_TYPE_IS_ECC_KEY_PAIR(type) \
+ (((type) & ~PSA_KEY_TYPE_ECC_CURVE_MASK) == \
+ PSA_KEY_TYPE_ECC_KEY_PAIR_BASE)
+/** Whether a key type is an elliptic curve public key. */
+#define PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY(type) \
+ (((type) & ~PSA_KEY_TYPE_ECC_CURVE_MASK) == \
+ PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE)
+
+/** Extract the curve from an elliptic curve key type. */
+#define PSA_KEY_TYPE_ECC_GET_FAMILY(type) \
+ ((psa_ecc_family_t) (PSA_KEY_TYPE_IS_ECC(type) ? \
+ ((type) & PSA_KEY_TYPE_ECC_CURVE_MASK) : \
+ 0))
+
+/** Check if the curve of given family is Weierstrass elliptic curve. */
+#define PSA_ECC_FAMILY_IS_WEIERSTRASS(family) ((family & 0xc0) == 0)
+
+/** SEC Koblitz curves over prime fields.
+ *
+ * This family comprises the following curves:
+ * secp192k1, secp224k1, secp256k1.
+ * They are defined in _Standards for Efficient Cryptography_,
+ * _SEC 2: Recommended Elliptic Curve Domain Parameters_.
+ * https://www.secg.org/sec2-v2.pdf
+ */
+#define PSA_ECC_FAMILY_SECP_K1 ((psa_ecc_family_t) 0x17)
+
+/** SEC random curves over prime fields.
+ *
+ * This family comprises the following curves:
+ * secp192k1, secp224r1, secp256r1, secp384r1, secp521r1.
+ * They are defined in _Standards for Efficient Cryptography_,
+ * _SEC 2: Recommended Elliptic Curve Domain Parameters_.
+ * https://www.secg.org/sec2-v2.pdf
+ */
+#define PSA_ECC_FAMILY_SECP_R1 ((psa_ecc_family_t) 0x12)
+/* SECP160R2 (SEC2 v1, obsolete) */
+#define PSA_ECC_FAMILY_SECP_R2 ((psa_ecc_family_t) 0x1b)
+
+/** SEC Koblitz curves over binary fields.
+ *
+ * This family comprises the following curves:
+ * sect163k1, sect233k1, sect239k1, sect283k1, sect409k1, sect571k1.
+ * They are defined in _Standards for Efficient Cryptography_,
+ * _SEC 2: Recommended Elliptic Curve Domain Parameters_.
+ * https://www.secg.org/sec2-v2.pdf
+ */
+#define PSA_ECC_FAMILY_SECT_K1 ((psa_ecc_family_t) 0x27)
+
+/** SEC random curves over binary fields.
+ *
+ * This family comprises the following curves:
+ * sect163r1, sect233r1, sect283r1, sect409r1, sect571r1.
+ * They are defined in _Standards for Efficient Cryptography_,
+ * _SEC 2: Recommended Elliptic Curve Domain Parameters_.
+ * https://www.secg.org/sec2-v2.pdf
+ */
+#define PSA_ECC_FAMILY_SECT_R1 ((psa_ecc_family_t) 0x22)
+
+/** SEC additional random curves over binary fields.
+ *
+ * This family comprises the following curve:
+ * sect163r2.
+ * It is defined in _Standards for Efficient Cryptography_,
+ * _SEC 2: Recommended Elliptic Curve Domain Parameters_.
+ * https://www.secg.org/sec2-v2.pdf
+ */
+#define PSA_ECC_FAMILY_SECT_R2 ((psa_ecc_family_t) 0x2b)
+
+/** Brainpool P random curves.
+ *
+ * This family comprises the following curves:
+ * brainpoolP160r1, brainpoolP192r1, brainpoolP224r1, brainpoolP256r1,
+ * brainpoolP320r1, brainpoolP384r1, brainpoolP512r1.
+ * It is defined in RFC 5639.
+ */
+#define PSA_ECC_FAMILY_BRAINPOOL_P_R1 ((psa_ecc_family_t) 0x30)
+
+/** Curve25519 and Curve448.
+ *
+ * This family comprises the following Montgomery curves:
+ * - 255-bit: Bernstein et al.,
+ * _Curve25519: new Diffie-Hellman speed records_, LNCS 3958, 2006.
+ * The algorithm #PSA_ALG_ECDH performs X25519 when used with this curve.
+ * - 448-bit: Hamburg,
+ * _Ed448-Goldilocks, a new elliptic curve_, NIST ECC Workshop, 2015.
+ * The algorithm #PSA_ALG_ECDH performs X448 when used with this curve.
+ */
+#define PSA_ECC_FAMILY_MONTGOMERY ((psa_ecc_family_t) 0x41)
+
+/** The twisted Edwards curves Ed25519 and Ed448.
+ *
+ * These curves are suitable for EdDSA (#PSA_ALG_PURE_EDDSA for both curves,
+ * #PSA_ALG_ED25519PH for the 255-bit curve,
+ * #PSA_ALG_ED448PH for the 448-bit curve).
+ *
+ * This family comprises the following twisted Edwards curves:
+ * - 255-bit: Edwards25519, the twisted Edwards curve birationally equivalent
+ * to Curve25519.
+ * Bernstein et al., _Twisted Edwards curves_, Africacrypt 2008.
+ * - 448-bit: Edwards448, the twisted Edwards curve birationally equivalent
+ * to Curve448.
+ * Hamburg, _Ed448-Goldilocks, a new elliptic curve_, NIST ECC Workshop, 2015.
+ */
+#define PSA_ECC_FAMILY_TWISTED_EDWARDS ((psa_ecc_family_t) 0x42)
+
+#define PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE ((psa_key_type_t) 0x4200)
+#define PSA_KEY_TYPE_DH_KEY_PAIR_BASE ((psa_key_type_t) 0x7200)
+#define PSA_KEY_TYPE_DH_GROUP_MASK ((psa_key_type_t) 0x00ff)
+/** Diffie-Hellman key pair.
+ *
+ * \param group A value of type ::psa_dh_family_t that identifies the
+ * Diffie-Hellman group to be used.
+ */
+#define PSA_KEY_TYPE_DH_KEY_PAIR(group) \
+ (PSA_KEY_TYPE_DH_KEY_PAIR_BASE | (group))
+/** Diffie-Hellman public key.
+ *
+ * \param group A value of type ::psa_dh_family_t that identifies the
+ * Diffie-Hellman group to be used.
+ */
+#define PSA_KEY_TYPE_DH_PUBLIC_KEY(group) \
+ (PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE | (group))
+
+/** Whether a key type is a Diffie-Hellman key (pair or public-only). */
+#define PSA_KEY_TYPE_IS_DH(type) \
+ ((PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) & \
+ ~PSA_KEY_TYPE_DH_GROUP_MASK) == PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE)
+/** Whether a key type is a Diffie-Hellman key pair. */
+#define PSA_KEY_TYPE_IS_DH_KEY_PAIR(type) \
+ (((type) & ~PSA_KEY_TYPE_DH_GROUP_MASK) == \
+ PSA_KEY_TYPE_DH_KEY_PAIR_BASE)
+/** Whether a key type is a Diffie-Hellman public key. */
+#define PSA_KEY_TYPE_IS_DH_PUBLIC_KEY(type) \
+ (((type) & ~PSA_KEY_TYPE_DH_GROUP_MASK) == \
+ PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE)
+
+/** Extract the group from a Diffie-Hellman key type. */
+#define PSA_KEY_TYPE_DH_GET_FAMILY(type) \
+ ((psa_dh_family_t) (PSA_KEY_TYPE_IS_DH(type) ? \
+ ((type) & PSA_KEY_TYPE_DH_GROUP_MASK) : \
+ 0))
+
+/** Diffie-Hellman groups defined in RFC 7919 Appendix A.
+ *
+ * This family includes groups with the following key sizes (in bits):
+ * 2048, 3072, 4096, 6144, 8192. A given implementation may support
+ * all of these sizes or only a subset.
+ */
+#define PSA_DH_FAMILY_RFC7919 ((psa_dh_family_t) 0x03)
+
+#define PSA_GET_KEY_TYPE_BLOCK_SIZE_EXPONENT(type) \
+ (((type) >> 8) & 7)
+/** The block size of a block cipher.
+ *
+ * \param type A cipher key type (value of type #psa_key_type_t).
+ *
+ * \return The block size for a block cipher, or 1 for a stream cipher.
+ * The return value is undefined if \p type is not a supported
+ * cipher key type.
+ *
+ * \note It is possible to build stream cipher algorithms on top of a block
+ * cipher, for example CTR mode (#PSA_ALG_CTR).
+ * This macro only takes the key type into account, so it cannot be
+ * used to determine the size of the data that #psa_cipher_update()
+ * might buffer for future processing in general.
+ *
+ * \note This macro returns a compile-time constant if its argument is one.
+ *
+ * \warning This macro may evaluate its argument multiple times.
+ */
+#define PSA_BLOCK_CIPHER_BLOCK_LENGTH(type) \
+ (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_SYMMETRIC ? \
+ 1u << PSA_GET_KEY_TYPE_BLOCK_SIZE_EXPONENT(type) : \
+ 0u)
+
+/* Note that algorithm values are embedded in the persistent key store,
+ * as part of key metadata. As a consequence, they must not be changed
+ * (unless the storage format version changes).
+ */
+
+/** Vendor-defined algorithm flag.
+ *
+ * Algorithms defined by this standard will never have the #PSA_ALG_VENDOR_FLAG
+ * bit set. Vendors who define additional algorithms must use an encoding with
+ * the #PSA_ALG_VENDOR_FLAG bit set and should respect the bitwise structure
+ * used by standard encodings whenever practical.
+ */
+#define PSA_ALG_VENDOR_FLAG ((psa_algorithm_t) 0x80000000)
+
+#define PSA_ALG_CATEGORY_MASK ((psa_algorithm_t) 0x7f000000)
+#define PSA_ALG_CATEGORY_HASH ((psa_algorithm_t) 0x02000000)
+#define PSA_ALG_CATEGORY_MAC ((psa_algorithm_t) 0x03000000)
+#define PSA_ALG_CATEGORY_CIPHER ((psa_algorithm_t) 0x04000000)
+#define PSA_ALG_CATEGORY_AEAD ((psa_algorithm_t) 0x05000000)
+#define PSA_ALG_CATEGORY_SIGN ((psa_algorithm_t) 0x06000000)
+#define PSA_ALG_CATEGORY_ASYMMETRIC_ENCRYPTION ((psa_algorithm_t) 0x07000000)
+#define PSA_ALG_CATEGORY_KEY_DERIVATION ((psa_algorithm_t) 0x08000000)
+#define PSA_ALG_CATEGORY_KEY_AGREEMENT ((psa_algorithm_t) 0x09000000)
+
+/** Whether an algorithm is vendor-defined.
+ *
+ * See also #PSA_ALG_VENDOR_FLAG.
+ */
+#define PSA_ALG_IS_VENDOR_DEFINED(alg) \
+ (((alg) & PSA_ALG_VENDOR_FLAG) != 0)
+
+/** Whether the specified algorithm is a hash algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a hash algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_HASH(alg) \
+ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_HASH)
+
+/** Whether the specified algorithm is a MAC algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a MAC algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_MAC(alg) \
+ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_MAC)
+
+/** Whether the specified algorithm is a symmetric cipher algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a symmetric cipher algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_CIPHER(alg) \
+ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_CIPHER)
+
+/** Whether the specified algorithm is an authenticated encryption
+ * with associated data (AEAD) algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is an AEAD algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_AEAD(alg) \
+ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_AEAD)
+
+/** Whether the specified algorithm is an asymmetric signature algorithm,
+ * also known as public-key signature algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is an asymmetric signature algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_SIGN(alg) \
+ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_SIGN)
+
+/** Whether the specified algorithm is an asymmetric encryption algorithm,
+ * also known as public-key encryption algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is an asymmetric encryption algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_ASYMMETRIC_ENCRYPTION(alg) \
+ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_ASYMMETRIC_ENCRYPTION)
+
+/** Whether the specified algorithm is a key agreement algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a key agreement algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_KEY_AGREEMENT(alg) \
+ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_KEY_AGREEMENT)
+
+/** Whether the specified algorithm is a key derivation algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a key derivation algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_KEY_DERIVATION(alg) \
+ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_KEY_DERIVATION)
+
+/** Whether the specified algorithm is a key stretching / password hashing
+ * algorithm.
+ *
+ * A key stretching / password hashing algorithm is a key derivation algorithm
+ * that is suitable for use with a low-entropy secret such as a password.
+ * Equivalently, it's a key derivation algorithm that uses a
+ * #PSA_KEY_DERIVATION_INPUT_PASSWORD input step.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a key stretching / password hashing algorithm, 0
+ * otherwise. This macro may return either 0 or 1 if \p alg is not a
+ * supported algorithm identifier.
+ */
+#define PSA_ALG_IS_KEY_DERIVATION_STRETCHING(alg) \
+ (PSA_ALG_IS_KEY_DERIVATION(alg) && \
+ (alg) & PSA_ALG_KEY_DERIVATION_STRETCHING_FLAG)
+
+/** An invalid algorithm identifier value. */
+/* *INDENT-OFF* (https://github.com/ARM-software/psa-arch-tests/issues/337) */
+#define PSA_ALG_NONE ((psa_algorithm_t)0)
+/* *INDENT-ON* */
+
+#define PSA_ALG_HASH_MASK ((psa_algorithm_t) 0x000000ff)
+/** MD5 */
+#define PSA_ALG_MD5 ((psa_algorithm_t) 0x02000003)
+/** PSA_ALG_RIPEMD160 */
+#define PSA_ALG_RIPEMD160 ((psa_algorithm_t) 0x02000004)
+/** SHA1 */
+#define PSA_ALG_SHA_1 ((psa_algorithm_t) 0x02000005)
+/** SHA2-224 */
+#define PSA_ALG_SHA_224 ((psa_algorithm_t) 0x02000008)
+/** SHA2-256 */
+#define PSA_ALG_SHA_256 ((psa_algorithm_t) 0x02000009)
+/** SHA2-384 */
+#define PSA_ALG_SHA_384 ((psa_algorithm_t) 0x0200000a)
+/** SHA2-512 */
+#define PSA_ALG_SHA_512 ((psa_algorithm_t) 0x0200000b)
+/** SHA2-512/224 */
+#define PSA_ALG_SHA_512_224 ((psa_algorithm_t) 0x0200000c)
+/** SHA2-512/256 */
+#define PSA_ALG_SHA_512_256 ((psa_algorithm_t) 0x0200000d)
+/** SHA3-224 */
+#define PSA_ALG_SHA3_224 ((psa_algorithm_t) 0x02000010)
+/** SHA3-256 */
+#define PSA_ALG_SHA3_256 ((psa_algorithm_t) 0x02000011)
+/** SHA3-384 */
+#define PSA_ALG_SHA3_384 ((psa_algorithm_t) 0x02000012)
+/** SHA3-512 */
+#define PSA_ALG_SHA3_512 ((psa_algorithm_t) 0x02000013)
+/** The first 512 bits (64 bytes) of the SHAKE256 output.
+ *
+ * This is the prehashing for Ed448ph (see #PSA_ALG_ED448PH). For other
+ * scenarios where a hash function based on SHA3/SHAKE is desired, SHA3-512
+ * has the same output size and a (theoretically) higher security strength.
+ */
+#define PSA_ALG_SHAKE256_512 ((psa_algorithm_t) 0x02000015)
+
+/** In a hash-and-sign algorithm policy, allow any hash algorithm.
+ *
+ * This value may be used to form the algorithm usage field of a policy
+ * for a signature algorithm that is parametrized by a hash. The key
+ * may then be used to perform operations using the same signature
+ * algorithm parametrized with any supported hash.
+ *
+ * That is, suppose that `PSA_xxx_SIGNATURE` is one of the following macros:
+ * - #PSA_ALG_RSA_PKCS1V15_SIGN, #PSA_ALG_RSA_PSS, #PSA_ALG_RSA_PSS_ANY_SALT,
+ * - #PSA_ALG_ECDSA, #PSA_ALG_DETERMINISTIC_ECDSA.
+ * Then you may create and use a key as follows:
+ * - Set the key usage field using #PSA_ALG_ANY_HASH, for example:
+ * ```
+ * psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH); // or VERIFY
+ * psa_set_key_algorithm(&attributes, PSA_xxx_SIGNATURE(PSA_ALG_ANY_HASH));
+ * ```
+ * - Import or generate key material.
+ * - Call psa_sign_hash() or psa_verify_hash(), passing
+ * an algorithm built from `PSA_xxx_SIGNATURE` and a specific hash. Each
+ * call to sign or verify a message may use a different hash.
+ * ```
+ * psa_sign_hash(key, PSA_xxx_SIGNATURE(PSA_ALG_SHA_256), ...);
+ * psa_sign_hash(key, PSA_xxx_SIGNATURE(PSA_ALG_SHA_512), ...);
+ * psa_sign_hash(key, PSA_xxx_SIGNATURE(PSA_ALG_SHA3_256), ...);
+ * ```
+ *
+ * This value may not be used to build other algorithms that are
+ * parametrized over a hash. For any valid use of this macro to build
+ * an algorithm \c alg, #PSA_ALG_IS_HASH_AND_SIGN(\c alg) is true.
+ *
+ * This value may not be used to build an algorithm specification to
+ * perform an operation. It is only valid to build policies.
+ */
+#define PSA_ALG_ANY_HASH ((psa_algorithm_t) 0x020000ff)
+
+#define PSA_ALG_MAC_SUBCATEGORY_MASK ((psa_algorithm_t) 0x00c00000)
+#define PSA_ALG_HMAC_BASE ((psa_algorithm_t) 0x03800000)
+/** Macro to build an HMAC algorithm.
+ *
+ * For example, #PSA_ALG_HMAC(#PSA_ALG_SHA_256) is HMAC-SHA-256.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ *
+ * \return The corresponding HMAC algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_HMAC(hash_alg) \
+ (PSA_ALG_HMAC_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+
+#define PSA_ALG_HMAC_GET_HASH(hmac_alg) \
+ (PSA_ALG_CATEGORY_HASH | ((hmac_alg) & PSA_ALG_HASH_MASK))
+
+/** Whether the specified algorithm is an HMAC algorithm.
+ *
+ * HMAC is a family of MAC algorithms that are based on a hash function.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is an HMAC algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_HMAC(alg) \
+ (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_MAC_SUBCATEGORY_MASK)) == \
+ PSA_ALG_HMAC_BASE)
+
+/* In the encoding of a MAC algorithm, the bits corresponding to
+ * PSA_ALG_MAC_TRUNCATION_MASK encode the length to which the MAC is
+ * truncated. As an exception, the value 0 means the untruncated algorithm,
+ * whatever its length is. The length is encoded in 6 bits, so it can
+ * reach up to 63; the largest MAC is 64 bytes so its trivial truncation
+ * to full length is correctly encoded as 0 and any non-trivial truncation
+ * is correctly encoded as a value between 1 and 63. */
+#define PSA_ALG_MAC_TRUNCATION_MASK ((psa_algorithm_t) 0x003f0000)
+#define PSA_MAC_TRUNCATION_OFFSET 16
+
+/* In the encoding of a MAC algorithm, the bit corresponding to
+ * #PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG encodes the fact that the algorithm
+ * is a wildcard algorithm. A key with such wildcard algorithm as permitted
+ * algorithm policy can be used with any algorithm corresponding to the
+ * same base class and having a (potentially truncated) MAC length greater or
+ * equal than the one encoded in #PSA_ALG_MAC_TRUNCATION_MASK. */
+#define PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ((psa_algorithm_t) 0x00008000)
+
+/** Macro to build a truncated MAC algorithm.
+ *
+ * A truncated MAC algorithm is identical to the corresponding MAC
+ * algorithm except that the MAC value for the truncated algorithm
+ * consists of only the first \p mac_length bytes of the MAC value
+ * for the untruncated algorithm.
+ *
+ * \note This macro may allow constructing algorithm identifiers that
+ * are not valid, either because the specified length is larger
+ * than the untruncated MAC or because the specified length is
+ * smaller than permitted by the implementation.
+ *
+ * \note It is implementation-defined whether a truncated MAC that
+ * is truncated to the same length as the MAC of the untruncated
+ * algorithm is considered identical to the untruncated algorithm
+ * for policy comparison purposes.
+ *
+ * \param mac_alg A MAC algorithm identifier (value of type
+ * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p mac_alg)
+ * is true). This may be a truncated or untruncated
+ * MAC algorithm.
+ * \param mac_length Desired length of the truncated MAC in bytes.
+ * This must be at most the full length of the MAC
+ * and must be at least an implementation-specified
+ * minimum. The implementation-specified minimum
+ * shall not be zero.
+ *
+ * \return The corresponding MAC algorithm with the specified
+ * length.
+ * \return Unspecified if \p mac_alg is not a supported
+ * MAC algorithm or if \p mac_length is too small or
+ * too large for the specified MAC algorithm.
+ */
+#define PSA_ALG_TRUNCATED_MAC(mac_alg, mac_length) \
+ (((mac_alg) & ~(PSA_ALG_MAC_TRUNCATION_MASK | \
+ PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG)) | \
+ ((mac_length) << PSA_MAC_TRUNCATION_OFFSET & PSA_ALG_MAC_TRUNCATION_MASK))
+
+/** Macro to build the base MAC algorithm corresponding to a truncated
+ * MAC algorithm.
+ *
+ * \param mac_alg A MAC algorithm identifier (value of type
+ * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p mac_alg)
+ * is true). This may be a truncated or untruncated
+ * MAC algorithm.
+ *
+ * \return The corresponding base MAC algorithm.
+ * \return Unspecified if \p mac_alg is not a supported
+ * MAC algorithm.
+ */
+#define PSA_ALG_FULL_LENGTH_MAC(mac_alg) \
+ ((mac_alg) & ~(PSA_ALG_MAC_TRUNCATION_MASK | \
+ PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG))
+
+/** Length to which a MAC algorithm is truncated.
+ *
+ * \param mac_alg A MAC algorithm identifier (value of type
+ * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p mac_alg)
+ * is true).
+ *
+ * \return Length of the truncated MAC in bytes.
+ * \return 0 if \p mac_alg is a non-truncated MAC algorithm.
+ * \return Unspecified if \p mac_alg is not a supported
+ * MAC algorithm.
+ */
+#define PSA_MAC_TRUNCATED_LENGTH(mac_alg) \
+ (((mac_alg) & PSA_ALG_MAC_TRUNCATION_MASK) >> PSA_MAC_TRUNCATION_OFFSET)
+
+/** Macro to build a MAC minimum-MAC-length wildcard algorithm.
+ *
+ * A minimum-MAC-length MAC wildcard algorithm permits all MAC algorithms
+ * sharing the same base algorithm, and where the (potentially truncated) MAC
+ * length of the specific algorithm is equal to or larger then the wildcard
+ * algorithm's minimum MAC length.
+ *
+ * \note When setting the minimum required MAC length to less than the
+ * smallest MAC length allowed by the base algorithm, this effectively
+ * becomes an 'any-MAC-length-allowed' policy for that base algorithm.
+ *
+ * \param mac_alg A MAC algorithm identifier (value of type
+ * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p mac_alg)
+ * is true).
+ * \param min_mac_length Desired minimum length of the message authentication
+ * code in bytes. This must be at most the untruncated
+ * length of the MAC and must be at least 1.
+ *
+ * \return The corresponding MAC wildcard algorithm with the
+ * specified minimum length.
+ * \return Unspecified if \p mac_alg is not a supported MAC
+ * algorithm or if \p min_mac_length is less than 1 or
+ * too large for the specified MAC algorithm.
+ */
+#define PSA_ALG_AT_LEAST_THIS_LENGTH_MAC(mac_alg, min_mac_length) \
+ (PSA_ALG_TRUNCATED_MAC(mac_alg, min_mac_length) | \
+ PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG)
+
+#define PSA_ALG_CIPHER_MAC_BASE ((psa_algorithm_t) 0x03c00000)
+/** The CBC-MAC construction over a block cipher
+ *
+ * \warning CBC-MAC is insecure in many cases.
+ * A more secure mode, such as #PSA_ALG_CMAC, is recommended.
+ */
+#define PSA_ALG_CBC_MAC ((psa_algorithm_t) 0x03c00100)
+/** The CMAC construction over a block cipher */
+#define PSA_ALG_CMAC ((psa_algorithm_t) 0x03c00200)
+
+/** Whether the specified algorithm is a MAC algorithm based on a block cipher.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a MAC algorithm based on a block cipher, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_BLOCK_CIPHER_MAC(alg) \
+ (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_MAC_SUBCATEGORY_MASK)) == \
+ PSA_ALG_CIPHER_MAC_BASE)
+
+#define PSA_ALG_CIPHER_STREAM_FLAG ((psa_algorithm_t) 0x00800000)
+#define PSA_ALG_CIPHER_FROM_BLOCK_FLAG ((psa_algorithm_t) 0x00400000)
+
+/** Whether the specified algorithm is a stream cipher.
+ *
+ * A stream cipher is a symmetric cipher that encrypts or decrypts messages
+ * by applying a bitwise-xor with a stream of bytes that is generated
+ * from a key.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a stream cipher algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier or if it is not a symmetric cipher algorithm.
+ */
+#define PSA_ALG_IS_STREAM_CIPHER(alg) \
+ (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_CIPHER_STREAM_FLAG)) == \
+ (PSA_ALG_CATEGORY_CIPHER | PSA_ALG_CIPHER_STREAM_FLAG))
+
+/** The stream cipher mode of a stream cipher algorithm.
+ *
+ * The underlying stream cipher is determined by the key type.
+ * - To use ChaCha20, use a key type of #PSA_KEY_TYPE_CHACHA20.
+ */
+#define PSA_ALG_STREAM_CIPHER ((psa_algorithm_t) 0x04800100)
+
+/** The CTR stream cipher mode.
+ *
+ * CTR is a stream cipher which is built from a block cipher.
+ * The underlying block cipher is determined by the key type.
+ * For example, to use AES-128-CTR, use this algorithm with
+ * a key of type #PSA_KEY_TYPE_AES and a length of 128 bits (16 bytes).
+ */
+#define PSA_ALG_CTR ((psa_algorithm_t) 0x04c01000)
+
+/** The CFB stream cipher mode.
+ *
+ * The underlying block cipher is determined by the key type.
+ */
+#define PSA_ALG_CFB ((psa_algorithm_t) 0x04c01100)
+
+/** The OFB stream cipher mode.
+ *
+ * The underlying block cipher is determined by the key type.
+ */
+#define PSA_ALG_OFB ((psa_algorithm_t) 0x04c01200)
+
+/** The XTS cipher mode.
+ *
+ * XTS is a cipher mode which is built from a block cipher. It requires at
+ * least one full block of input, but beyond this minimum the input
+ * does not need to be a whole number of blocks.
+ */
+#define PSA_ALG_XTS ((psa_algorithm_t) 0x0440ff00)
+
+/** The Electronic Code Book (ECB) mode of a block cipher, with no padding.
+ *
+ * \warning ECB mode does not protect the confidentiality of the encrypted data
+ * except in extremely narrow circumstances. It is recommended that applications
+ * only use ECB if they need to construct an operating mode that the
+ * implementation does not provide. Implementations are encouraged to provide
+ * the modes that applications need in preference to supporting direct access
+ * to ECB.
+ *
+ * The underlying block cipher is determined by the key type.
+ *
+ * This symmetric cipher mode can only be used with messages whose lengths are a
+ * multiple of the block size of the chosen block cipher.
+ *
+ * ECB mode does not accept an initialization vector (IV). When using a
+ * multi-part cipher operation with this algorithm, psa_cipher_generate_iv()
+ * and psa_cipher_set_iv() must not be called.
+ */
+#define PSA_ALG_ECB_NO_PADDING ((psa_algorithm_t) 0x04404400)
+
+/** The CBC block cipher chaining mode, with no padding.
+ *
+ * The underlying block cipher is determined by the key type.
+ *
+ * This symmetric cipher mode can only be used with messages whose lengths
+ * are whole number of blocks for the chosen block cipher.
+ */
+#define PSA_ALG_CBC_NO_PADDING ((psa_algorithm_t) 0x04404000)
+
+/** The CBC block cipher chaining mode with PKCS#7 padding.
+ *
+ * The underlying block cipher is determined by the key type.
+ *
+ * This is the padding method defined by PKCS#7 (RFC 2315) &sect;10.3.
+ */
+#define PSA_ALG_CBC_PKCS7 ((psa_algorithm_t) 0x04404100)
+
+#define PSA_ALG_AEAD_FROM_BLOCK_FLAG ((psa_algorithm_t) 0x00400000)
+
+/** Whether the specified algorithm is an AEAD mode on a block cipher.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is an AEAD algorithm which is an AEAD mode based on
+ * a block cipher, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER(alg) \
+ (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_AEAD_FROM_BLOCK_FLAG)) == \
+ (PSA_ALG_CATEGORY_AEAD | PSA_ALG_AEAD_FROM_BLOCK_FLAG))
+
+/** The CCM authenticated encryption algorithm.
+ *
+ * The underlying block cipher is determined by the key type.
+ */
+#define PSA_ALG_CCM ((psa_algorithm_t) 0x05500100)
+
+/** The CCM* cipher mode without authentication.
+ *
+ * This is CCM* as specified in IEEE 802.15.4 §7, with a tag length of 0.
+ * For CCM* with a nonzero tag length, use the AEAD algorithm #PSA_ALG_CCM.
+ *
+ * The underlying block cipher is determined by the key type.
+ *
+ * Currently only 13-byte long IV's are supported.
+ */
+#define PSA_ALG_CCM_STAR_NO_TAG ((psa_algorithm_t) 0x04c01300)
+
+/** The GCM authenticated encryption algorithm.
+ *
+ * The underlying block cipher is determined by the key type.
+ */
+#define PSA_ALG_GCM ((psa_algorithm_t) 0x05500200)
+
+/** The Chacha20-Poly1305 AEAD algorithm.
+ *
+ * The ChaCha20_Poly1305 construction is defined in RFC 7539.
+ *
+ * Implementations must support 12-byte nonces, may support 8-byte nonces,
+ * and should reject other sizes.
+ *
+ * Implementations must support 16-byte tags and should reject other sizes.
+ */
+#define PSA_ALG_CHACHA20_POLY1305 ((psa_algorithm_t) 0x05100500)
+
+/* In the encoding of an AEAD algorithm, the bits corresponding to
+ * PSA_ALG_AEAD_TAG_LENGTH_MASK encode the length of the AEAD tag.
+ * The constants for default lengths follow this encoding.
+ */
+#define PSA_ALG_AEAD_TAG_LENGTH_MASK ((psa_algorithm_t) 0x003f0000)
+#define PSA_AEAD_TAG_LENGTH_OFFSET 16
+
+/* In the encoding of an AEAD algorithm, the bit corresponding to
+ * #PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG encodes the fact that the algorithm
+ * is a wildcard algorithm. A key with such wildcard algorithm as permitted
+ * algorithm policy can be used with any algorithm corresponding to the
+ * same base class and having a tag length greater than or equal to the one
+ * encoded in #PSA_ALG_AEAD_TAG_LENGTH_MASK. */
+#define PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ((psa_algorithm_t) 0x00008000)
+
+/** Macro to build a shortened AEAD algorithm.
+ *
+ * A shortened AEAD algorithm is similar to the corresponding AEAD
+ * algorithm, but has an authentication tag that consists of fewer bytes.
+ * Depending on the algorithm, the tag length may affect the calculation
+ * of the ciphertext.
+ *
+ * \param aead_alg An AEAD algorithm identifier (value of type
+ * #psa_algorithm_t such that #PSA_ALG_IS_AEAD(\p aead_alg)
+ * is true).
+ * \param tag_length Desired length of the authentication tag in bytes.
+ *
+ * \return The corresponding AEAD algorithm with the specified
+ * length.
+ * \return Unspecified if \p aead_alg is not a supported
+ * AEAD algorithm or if \p tag_length is not valid
+ * for the specified AEAD algorithm.
+ */
+#define PSA_ALG_AEAD_WITH_SHORTENED_TAG(aead_alg, tag_length) \
+ (((aead_alg) & ~(PSA_ALG_AEAD_TAG_LENGTH_MASK | \
+ PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG)) | \
+ ((tag_length) << PSA_AEAD_TAG_LENGTH_OFFSET & \
+ PSA_ALG_AEAD_TAG_LENGTH_MASK))
+
+/** Retrieve the tag length of a specified AEAD algorithm
+ *
+ * \param aead_alg An AEAD algorithm identifier (value of type
+ * #psa_algorithm_t such that #PSA_ALG_IS_AEAD(\p aead_alg)
+ * is true).
+ *
+ * \return The tag length specified by the input algorithm.
+ * \return Unspecified if \p aead_alg is not a supported
+ * AEAD algorithm.
+ */
+#define PSA_ALG_AEAD_GET_TAG_LENGTH(aead_alg) \
+ (((aead_alg) & PSA_ALG_AEAD_TAG_LENGTH_MASK) >> \
+ PSA_AEAD_TAG_LENGTH_OFFSET)
+
+/** Calculate the corresponding AEAD algorithm with the default tag length.
+ *
+ * \param aead_alg An AEAD algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_AEAD(\p aead_alg) is true).
+ *
+ * \return The corresponding AEAD algorithm with the default
+ * tag length for that algorithm.
+ */
+#define PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG(aead_alg) \
+ ( \
+ PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE(aead_alg, PSA_ALG_CCM) \
+ PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE(aead_alg, PSA_ALG_GCM) \
+ PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE(aead_alg, PSA_ALG_CHACHA20_POLY1305) \
+ 0)
+#define PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE(aead_alg, ref) \
+ PSA_ALG_AEAD_WITH_SHORTENED_TAG(aead_alg, 0) == \
+ PSA_ALG_AEAD_WITH_SHORTENED_TAG(ref, 0) ? \
+ ref :
+
+/** Macro to build an AEAD minimum-tag-length wildcard algorithm.
+ *
+ * A minimum-tag-length AEAD wildcard algorithm permits all AEAD algorithms
+ * sharing the same base algorithm, and where the tag length of the specific
+ * algorithm is equal to or larger then the minimum tag length specified by the
+ * wildcard algorithm.
+ *
+ * \note When setting the minimum required tag length to less than the
+ * smallest tag length allowed by the base algorithm, this effectively
+ * becomes an 'any-tag-length-allowed' policy for that base algorithm.
+ *
+ * \param aead_alg An AEAD algorithm identifier (value of type
+ * #psa_algorithm_t such that
+ * #PSA_ALG_IS_AEAD(\p aead_alg) is true).
+ * \param min_tag_length Desired minimum length of the authentication tag in
+ * bytes. This must be at least 1 and at most the largest
+ * allowed tag length of the algorithm.
+ *
+ * \return The corresponding AEAD wildcard algorithm with the
+ * specified minimum length.
+ * \return Unspecified if \p aead_alg is not a supported
+ * AEAD algorithm or if \p min_tag_length is less than 1
+ * or too large for the specified AEAD algorithm.
+ */
+#define PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG(aead_alg, min_tag_length) \
+ (PSA_ALG_AEAD_WITH_SHORTENED_TAG(aead_alg, min_tag_length) | \
+ PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG)
+
+#define PSA_ALG_RSA_PKCS1V15_SIGN_BASE ((psa_algorithm_t) 0x06000200)
+/** RSA PKCS#1 v1.5 signature with hashing.
+ *
+ * This is the signature scheme defined by RFC 8017
+ * (PKCS#1: RSA Cryptography Specifications) under the name
+ * RSASSA-PKCS1-v1_5.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ * This includes #PSA_ALG_ANY_HASH
+ * when specifying the algorithm in a usage policy.
+ *
+ * \return The corresponding RSA PKCS#1 v1.5 signature algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_RSA_PKCS1V15_SIGN(hash_alg) \
+ (PSA_ALG_RSA_PKCS1V15_SIGN_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+/** Raw PKCS#1 v1.5 signature.
+ *
+ * The input to this algorithm is the DigestInfo structure used by
+ * RFC 8017 (PKCS#1: RSA Cryptography Specifications), &sect;9.2
+ * steps 3&ndash;6.
+ */
+#define PSA_ALG_RSA_PKCS1V15_SIGN_RAW PSA_ALG_RSA_PKCS1V15_SIGN_BASE
+#define PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_RSA_PKCS1V15_SIGN_BASE)
+
+#define PSA_ALG_RSA_PSS_BASE ((psa_algorithm_t) 0x06000300)
+#define PSA_ALG_RSA_PSS_ANY_SALT_BASE ((psa_algorithm_t) 0x06001300)
+/** RSA PSS signature with hashing.
+ *
+ * This is the signature scheme defined by RFC 8017
+ * (PKCS#1: RSA Cryptography Specifications) under the name
+ * RSASSA-PSS, with the message generation function MGF1, and with
+ * a salt length equal to the length of the hash, or the largest
+ * possible salt length for the algorithm and key size if that is
+ * smaller than the hash length. The specified hash algorithm is
+ * used to hash the input message, to create the salted hash, and
+ * for the mask generation.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ * This includes #PSA_ALG_ANY_HASH
+ * when specifying the algorithm in a usage policy.
+ *
+ * \return The corresponding RSA PSS signature algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_RSA_PSS(hash_alg) \
+ (PSA_ALG_RSA_PSS_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+
+/** RSA PSS signature with hashing with relaxed verification.
+ *
+ * This algorithm has the same behavior as #PSA_ALG_RSA_PSS when signing,
+ * but allows an arbitrary salt length (including \c 0) when verifying a
+ * signature.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ * This includes #PSA_ALG_ANY_HASH
+ * when specifying the algorithm in a usage policy.
+ *
+ * \return The corresponding RSA PSS signature algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_RSA_PSS_ANY_SALT(hash_alg) \
+ (PSA_ALG_RSA_PSS_ANY_SALT_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+
+/** Whether the specified algorithm is RSA PSS with standard salt.
+ *
+ * \param alg An algorithm value or an algorithm policy wildcard.
+ *
+ * \return 1 if \p alg is of the form
+ * #PSA_ALG_RSA_PSS(\c hash_alg),
+ * where \c hash_alg is a hash algorithm or
+ * #PSA_ALG_ANY_HASH. 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not
+ * a supported algorithm identifier or policy.
+ */
+#define PSA_ALG_IS_RSA_PSS_STANDARD_SALT(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_RSA_PSS_BASE)
+
+/** Whether the specified algorithm is RSA PSS with any salt.
+ *
+ * \param alg An algorithm value or an algorithm policy wildcard.
+ *
+ * \return 1 if \p alg is of the form
+ * #PSA_ALG_RSA_PSS_ANY_SALT_BASE(\c hash_alg),
+ * where \c hash_alg is a hash algorithm or
+ * #PSA_ALG_ANY_HASH. 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not
+ * a supported algorithm identifier or policy.
+ */
+#define PSA_ALG_IS_RSA_PSS_ANY_SALT(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_RSA_PSS_ANY_SALT_BASE)
+
+/** Whether the specified algorithm is RSA PSS.
+ *
+ * This includes any of the RSA PSS algorithm variants, regardless of the
+ * constraints on salt length.
+ *
+ * \param alg An algorithm value or an algorithm policy wildcard.
+ *
+ * \return 1 if \p alg is of the form
+ * #PSA_ALG_RSA_PSS(\c hash_alg) or
+ * #PSA_ALG_RSA_PSS_ANY_SALT_BASE(\c hash_alg),
+ * where \c hash_alg is a hash algorithm or
+ * #PSA_ALG_ANY_HASH. 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not
+ * a supported algorithm identifier or policy.
+ */
+#define PSA_ALG_IS_RSA_PSS(alg) \
+ (PSA_ALG_IS_RSA_PSS_STANDARD_SALT(alg) || \
+ PSA_ALG_IS_RSA_PSS_ANY_SALT(alg))
+
+#define PSA_ALG_ECDSA_BASE ((psa_algorithm_t) 0x06000600)
+/** ECDSA signature with hashing.
+ *
+ * This is the ECDSA signature scheme defined by ANSI X9.62,
+ * with a random per-message secret number (*k*).
+ *
+ * The representation of the signature as a byte string consists of
+ * the concatenation of the signature values *r* and *s*. Each of
+ * *r* and *s* is encoded as an *N*-octet string, where *N* is the length
+ * of the base point of the curve in octets. Each value is represented
+ * in big-endian order (most significant octet first).
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ * This includes #PSA_ALG_ANY_HASH
+ * when specifying the algorithm in a usage policy.
+ *
+ * \return The corresponding ECDSA signature algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_ECDSA(hash_alg) \
+ (PSA_ALG_ECDSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+/** ECDSA signature without hashing.
+ *
+ * This is the same signature scheme as #PSA_ALG_ECDSA(), but
+ * without specifying a hash algorithm. This algorithm may only be
+ * used to sign or verify a sequence of bytes that should be an
+ * already-calculated hash. Note that the input is padded with
+ * zeros on the left or truncated on the left as required to fit
+ * the curve size.
+ */
+#define PSA_ALG_ECDSA_ANY PSA_ALG_ECDSA_BASE
+#define PSA_ALG_DETERMINISTIC_ECDSA_BASE ((psa_algorithm_t) 0x06000700)
+/** Deterministic ECDSA signature with hashing.
+ *
+ * This is the deterministic ECDSA signature scheme defined by RFC 6979.
+ *
+ * The representation of a signature is the same as with #PSA_ALG_ECDSA().
+ *
+ * Note that when this algorithm is used for verification, signatures
+ * made with randomized ECDSA (#PSA_ALG_ECDSA(\p hash_alg)) with the
+ * same private key are accepted. In other words,
+ * #PSA_ALG_DETERMINISTIC_ECDSA(\p hash_alg) differs from
+ * #PSA_ALG_ECDSA(\p hash_alg) only for signature, not for verification.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ * This includes #PSA_ALG_ANY_HASH
+ * when specifying the algorithm in a usage policy.
+ *
+ * \return The corresponding deterministic ECDSA signature
+ * algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_DETERMINISTIC_ECDSA(hash_alg) \
+ (PSA_ALG_DETERMINISTIC_ECDSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+#define PSA_ALG_ECDSA_DETERMINISTIC_FLAG ((psa_algorithm_t) 0x00000100)
+#define PSA_ALG_IS_ECDSA(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK & ~PSA_ALG_ECDSA_DETERMINISTIC_FLAG) == \
+ PSA_ALG_ECDSA_BASE)
+#define PSA_ALG_ECDSA_IS_DETERMINISTIC(alg) \
+ (((alg) & PSA_ALG_ECDSA_DETERMINISTIC_FLAG) != 0)
+#define PSA_ALG_IS_DETERMINISTIC_ECDSA(alg) \
+ (PSA_ALG_IS_ECDSA(alg) && PSA_ALG_ECDSA_IS_DETERMINISTIC(alg))
+#define PSA_ALG_IS_RANDOMIZED_ECDSA(alg) \
+ (PSA_ALG_IS_ECDSA(alg) && !PSA_ALG_ECDSA_IS_DETERMINISTIC(alg))
+
+/** Edwards-curve digital signature algorithm without prehashing (PureEdDSA),
+ * using standard parameters.
+ *
+ * Contexts are not supported in the current version of this specification
+ * because there is no suitable signature interface that can take the
+ * context as a parameter. A future version of this specification may add
+ * suitable functions and extend this algorithm to support contexts.
+ *
+ * PureEdDSA requires an elliptic curve key on a twisted Edwards curve.
+ * In this specification, the following curves are supported:
+ * - #PSA_ECC_FAMILY_TWISTED_EDWARDS, 255-bit: Ed25519 as specified
+ * in RFC 8032.
+ * The curve is Edwards25519.
+ * The hash function used internally is SHA-512.
+ * - #PSA_ECC_FAMILY_TWISTED_EDWARDS, 448-bit: Ed448 as specified
+ * in RFC 8032.
+ * The curve is Edwards448.
+ * The hash function used internally is the first 114 bytes of the
+ * SHAKE256 output.
+ *
+ * This algorithm can be used with psa_sign_message() and
+ * psa_verify_message(). Since there is no prehashing, it cannot be used
+ * with psa_sign_hash() or psa_verify_hash().
+ *
+ * The signature format is the concatenation of R and S as defined by
+ * RFC 8032 §5.1.6 and §5.2.6 (a 64-byte string for Ed25519, a 114-byte
+ * string for Ed448).
+ */
+#define PSA_ALG_PURE_EDDSA ((psa_algorithm_t) 0x06000800)
+
+#define PSA_ALG_HASH_EDDSA_BASE ((psa_algorithm_t) 0x06000900)
+#define PSA_ALG_IS_HASH_EDDSA(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_HASH_EDDSA_BASE)
+
+/** Edwards-curve digital signature algorithm with prehashing (HashEdDSA),
+ * using SHA-512 and the Edwards25519 curve.
+ *
+ * See #PSA_ALG_PURE_EDDSA regarding context support and the signature format.
+ *
+ * This algorithm is Ed25519 as specified in RFC 8032.
+ * The curve is Edwards25519.
+ * The prehash is SHA-512.
+ * The hash function used internally is SHA-512.
+ *
+ * This is a hash-and-sign algorithm: to calculate a signature,
+ * you can either:
+ * - call psa_sign_message() on the message;
+ * - or calculate the SHA-512 hash of the message
+ * with psa_hash_compute()
+ * or with a multi-part hash operation started with psa_hash_setup(),
+ * using the hash algorithm #PSA_ALG_SHA_512,
+ * then sign the calculated hash with psa_sign_hash().
+ * Verifying a signature is similar, using psa_verify_message() or
+ * psa_verify_hash() instead of the signature function.
+ */
+#define PSA_ALG_ED25519PH \
+ (PSA_ALG_HASH_EDDSA_BASE | (PSA_ALG_SHA_512 & PSA_ALG_HASH_MASK))
+
+/** Edwards-curve digital signature algorithm with prehashing (HashEdDSA),
+ * using SHAKE256 and the Edwards448 curve.
+ *
+ * See #PSA_ALG_PURE_EDDSA regarding context support and the signature format.
+ *
+ * This algorithm is Ed448 as specified in RFC 8032.
+ * The curve is Edwards448.
+ * The prehash is the first 64 bytes of the SHAKE256 output.
+ * The hash function used internally is the first 114 bytes of the
+ * SHAKE256 output.
+ *
+ * This is a hash-and-sign algorithm: to calculate a signature,
+ * you can either:
+ * - call psa_sign_message() on the message;
+ * - or calculate the first 64 bytes of the SHAKE256 output of the message
+ * with psa_hash_compute()
+ * or with a multi-part hash operation started with psa_hash_setup(),
+ * using the hash algorithm #PSA_ALG_SHAKE256_512,
+ * then sign the calculated hash with psa_sign_hash().
+ * Verifying a signature is similar, using psa_verify_message() or
+ * psa_verify_hash() instead of the signature function.
+ */
+#define PSA_ALG_ED448PH \
+ (PSA_ALG_HASH_EDDSA_BASE | (PSA_ALG_SHAKE256_512 & PSA_ALG_HASH_MASK))
+
+/* Default definition, to be overridden if the library is extended with
+ * more hash-and-sign algorithms that we want to keep out of this header
+ * file. */
+#define PSA_ALG_IS_VENDOR_HASH_AND_SIGN(alg) 0
+
+/** Whether the specified algorithm is a signature algorithm that can be used
+ * with psa_sign_hash() and psa_verify_hash().
+ *
+ * This encompasses all strict hash-and-sign algorithms categorized by
+ * PSA_ALG_IS_HASH_AND_SIGN(), as well as algorithms that follow the
+ * paradigm more loosely:
+ * - #PSA_ALG_RSA_PKCS1V15_SIGN_RAW (expects its input to be an encoded hash)
+ * - #PSA_ALG_ECDSA_ANY (doesn't specify what kind of hash the input is)
+ *
+ * \param alg An algorithm identifier (value of type psa_algorithm_t).
+ *
+ * \return 1 if alg is a signature algorithm that can be used to sign a
+ * hash. 0 if alg is a signature algorithm that can only be used
+ * to sign a message. 0 if alg is not a signature algorithm.
+ * This macro can return either 0 or 1 if alg is not a
+ * supported algorithm identifier.
+ */
+#define PSA_ALG_IS_SIGN_HASH(alg) \
+ (PSA_ALG_IS_RSA_PSS(alg) || PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) || \
+ PSA_ALG_IS_ECDSA(alg) || PSA_ALG_IS_HASH_EDDSA(alg) || \
+ PSA_ALG_IS_VENDOR_HASH_AND_SIGN(alg))
+
+/** Whether the specified algorithm is a signature algorithm that can be used
+ * with psa_sign_message() and psa_verify_message().
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if alg is a signature algorithm that can be used to sign a
+ * message. 0 if \p alg is a signature algorithm that can only be used
+ * to sign an already-calculated hash. 0 if \p alg is not a signature
+ * algorithm. This macro can return either 0 or 1 if \p alg is not a
+ * supported algorithm identifier.
+ */
+#define PSA_ALG_IS_SIGN_MESSAGE(alg) \
+ (PSA_ALG_IS_SIGN_HASH(alg) || (alg) == PSA_ALG_PURE_EDDSA)
+
+/** Whether the specified algorithm is a hash-and-sign algorithm.
+ *
+ * Hash-and-sign algorithms are asymmetric (public-key) signature algorithms
+ * structured in two parts: first the calculation of a hash in a way that
+ * does not depend on the key, then the calculation of a signature from the
+ * hash value and the key. Hash-and-sign algorithms encode the hash
+ * used for the hashing step, and you can call #PSA_ALG_SIGN_GET_HASH
+ * to extract this algorithm.
+ *
+ * Thus, for a hash-and-sign algorithm,
+ * `psa_sign_message(key, alg, input, ...)` is equivalent to
+ * ```
+ * psa_hash_compute(PSA_ALG_SIGN_GET_HASH(alg), input, ..., hash, ...);
+ * psa_sign_hash(key, alg, hash, ..., signature, ...);
+ * ```
+ * Most usefully, separating the hash from the signature allows the hash
+ * to be calculated in multiple steps with psa_hash_setup(), psa_hash_update()
+ * and psa_hash_finish(). Likewise psa_verify_message() is equivalent to
+ * calculating the hash and then calling psa_verify_hash().
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a hash-and-sign algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_HASH_AND_SIGN(alg) \
+ (PSA_ALG_IS_SIGN_HASH(alg) && \
+ ((alg) & PSA_ALG_HASH_MASK) != 0)
+
+/** Get the hash used by a hash-and-sign signature algorithm.
+ *
+ * A hash-and-sign algorithm is a signature algorithm which is
+ * composed of two phases: first a hashing phase which does not use
+ * the key and produces a hash of the input message, then a signing
+ * phase which only uses the hash and the key and not the message
+ * itself.
+ *
+ * \param alg A signature algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_SIGN(\p alg) is true).
+ *
+ * \return The underlying hash algorithm if \p alg is a hash-and-sign
+ * algorithm.
+ * \return 0 if \p alg is a signature algorithm that does not
+ * follow the hash-and-sign structure.
+ * \return Unspecified if \p alg is not a signature algorithm or
+ * if it is not supported by the implementation.
+ */
+#define PSA_ALG_SIGN_GET_HASH(alg) \
+ (PSA_ALG_IS_HASH_AND_SIGN(alg) ? \
+ ((alg) & PSA_ALG_HASH_MASK) | PSA_ALG_CATEGORY_HASH : \
+ 0)
+
+/** RSA PKCS#1 v1.5 encryption.
+ *
+ * \warning Calling psa_asymmetric_decrypt() with this algorithm as a
+ * parameter is considered an inherently dangerous function
+ * (CWE-242). Unless it is used in a side channel free and safe
+ * way (eg. implementing the TLS protocol as per 7.4.7.1 of
+ * RFC 5246), the calling code is vulnerable.
+ *
+ */
+#define PSA_ALG_RSA_PKCS1V15_CRYPT ((psa_algorithm_t) 0x07000200)
+
+#define PSA_ALG_RSA_OAEP_BASE ((psa_algorithm_t) 0x07000300)
+/** RSA OAEP encryption.
+ *
+ * This is the encryption scheme defined by RFC 8017
+ * (PKCS#1: RSA Cryptography Specifications) under the name
+ * RSAES-OAEP, with the message generation function MGF1.
+ *
+ * \param hash_alg The hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true) to use
+ * for MGF1.
+ *
+ * \return The corresponding RSA OAEP encryption algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_RSA_OAEP(hash_alg) \
+ (PSA_ALG_RSA_OAEP_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+#define PSA_ALG_IS_RSA_OAEP(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_RSA_OAEP_BASE)
+#define PSA_ALG_RSA_OAEP_GET_HASH(alg) \
+ (PSA_ALG_IS_RSA_OAEP(alg) ? \
+ ((alg) & PSA_ALG_HASH_MASK) | PSA_ALG_CATEGORY_HASH : \
+ 0)
+
+#define PSA_ALG_HKDF_BASE ((psa_algorithm_t) 0x08000100)
+/** Macro to build an HKDF algorithm.
+ *
+ * For example, `PSA_ALG_HKDF(PSA_ALG_SHA_256)` is HKDF using HMAC-SHA-256.
+ *
+ * This key derivation algorithm uses the following inputs:
+ * - #PSA_KEY_DERIVATION_INPUT_SALT is the salt used in the "extract" step.
+ * It is optional; if omitted, the derivation uses an empty salt.
+ * - #PSA_KEY_DERIVATION_INPUT_SECRET is the secret key used in the "extract" step.
+ * - #PSA_KEY_DERIVATION_INPUT_INFO is the info string used in the "expand" step.
+ * You must pass #PSA_KEY_DERIVATION_INPUT_SALT before #PSA_KEY_DERIVATION_INPUT_SECRET.
+ * You may pass #PSA_KEY_DERIVATION_INPUT_INFO at any time after steup and before
+ * starting to generate output.
+ *
+ * \warning HKDF processes the salt as follows: first hash it with hash_alg
+ * if the salt is longer than the block size of the hash algorithm; then
+ * pad with null bytes up to the block size. As a result, it is possible
+ * for distinct salt inputs to result in the same outputs. To ensure
+ * unique outputs, it is recommended to use a fixed length for salt values.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ *
+ * \return The corresponding HKDF algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_HKDF(hash_alg) \
+ (PSA_ALG_HKDF_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+/** Whether the specified algorithm is an HKDF algorithm.
+ *
+ * HKDF is a family of key derivation algorithms that are based on a hash
+ * function and the HMAC construction.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \c alg is an HKDF algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \c alg is not a supported
+ * key derivation algorithm identifier.
+ */
+#define PSA_ALG_IS_HKDF(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_HKDF_BASE)
+#define PSA_ALG_HKDF_GET_HASH(hkdf_alg) \
+ (PSA_ALG_CATEGORY_HASH | ((hkdf_alg) & PSA_ALG_HASH_MASK))
+
+#define PSA_ALG_HKDF_EXTRACT_BASE ((psa_algorithm_t) 0x08000400)
+/** Macro to build an HKDF-Extract algorithm.
+ *
+ * For example, `PSA_ALG_HKDF_EXTRACT(PSA_ALG_SHA_256)` is
+ * HKDF-Extract using HMAC-SHA-256.
+ *
+ * This key derivation algorithm uses the following inputs:
+ * - PSA_KEY_DERIVATION_INPUT_SALT is the salt.
+ * - PSA_KEY_DERIVATION_INPUT_SECRET is the input keying material used in the
+ * "extract" step.
+ * The inputs are mandatory and must be passed in the order above.
+ * Each input may only be passed once.
+ *
+ * \warning HKDF-Extract is not meant to be used on its own. PSA_ALG_HKDF
+ * should be used instead if possible. PSA_ALG_HKDF_EXTRACT is provided
+ * as a separate algorithm for the sake of protocols that use it as a
+ * building block. It may also be a slight performance optimization
+ * in applications that use HKDF with the same salt and key but many
+ * different info strings.
+ *
+ * \warning HKDF processes the salt as follows: first hash it with hash_alg
+ * if the salt is longer than the block size of the hash algorithm; then
+ * pad with null bytes up to the block size. As a result, it is possible
+ * for distinct salt inputs to result in the same outputs. To ensure
+ * unique outputs, it is recommended to use a fixed length for salt values.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ *
+ * \return The corresponding HKDF-Extract algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_HKDF_EXTRACT(hash_alg) \
+ (PSA_ALG_HKDF_EXTRACT_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+/** Whether the specified algorithm is an HKDF-Extract algorithm.
+ *
+ * HKDF-Extract is a family of key derivation algorithms that are based
+ * on a hash function and the HMAC construction.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \c alg is an HKDF-Extract algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \c alg is not a supported
+ * key derivation algorithm identifier.
+ */
+#define PSA_ALG_IS_HKDF_EXTRACT(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_HKDF_EXTRACT_BASE)
+
+#define PSA_ALG_HKDF_EXPAND_BASE ((psa_algorithm_t) 0x08000500)
+/** Macro to build an HKDF-Expand algorithm.
+ *
+ * For example, `PSA_ALG_HKDF_EXPAND(PSA_ALG_SHA_256)` is
+ * HKDF-Expand using HMAC-SHA-256.
+ *
+ * This key derivation algorithm uses the following inputs:
+ * - PSA_KEY_DERIVATION_INPUT_SECRET is the pseudorandom key (PRK).
+ * - PSA_KEY_DERIVATION_INPUT_INFO is the info string.
+ *
+ * The inputs are mandatory and must be passed in the order above.
+ * Each input may only be passed once.
+ *
+ * \warning HKDF-Expand is not meant to be used on its own. `PSA_ALG_HKDF`
+ * should be used instead if possible. `PSA_ALG_HKDF_EXPAND` is provided as
+ * a separate algorithm for the sake of protocols that use it as a building
+ * block. It may also be a slight performance optimization in applications
+ * that use HKDF with the same salt and key but many different info strings.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ *
+ * \return The corresponding HKDF-Expand algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_HKDF_EXPAND(hash_alg) \
+ (PSA_ALG_HKDF_EXPAND_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+/** Whether the specified algorithm is an HKDF-Expand algorithm.
+ *
+ * HKDF-Expand is a family of key derivation algorithms that are based
+ * on a hash function and the HMAC construction.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \c alg is an HKDF-Expand algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \c alg is not a supported
+ * key derivation algorithm identifier.
+ */
+#define PSA_ALG_IS_HKDF_EXPAND(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_HKDF_EXPAND_BASE)
+
+/** Whether the specified algorithm is an HKDF or HKDF-Extract or
+ * HKDF-Expand algorithm.
+ *
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \c alg is any HKDF type algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \c alg is not a supported
+ * key derivation algorithm identifier.
+ */
+#define PSA_ALG_IS_ANY_HKDF(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_HKDF_BASE || \
+ ((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_HKDF_EXTRACT_BASE || \
+ ((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_HKDF_EXPAND_BASE)
+
+#define PSA_ALG_TLS12_PRF_BASE ((psa_algorithm_t) 0x08000200)
+/** Macro to build a TLS-1.2 PRF algorithm.
+ *
+ * TLS 1.2 uses a custom pseudorandom function (PRF) for key schedule,
+ * specified in Section 5 of RFC 5246. It is based on HMAC and can be
+ * used with either SHA-256 or SHA-384.
+ *
+ * This key derivation algorithm uses the following inputs, which must be
+ * passed in the order given here:
+ * - #PSA_KEY_DERIVATION_INPUT_SEED is the seed.
+ * - #PSA_KEY_DERIVATION_INPUT_SECRET is the secret key.
+ * - #PSA_KEY_DERIVATION_INPUT_LABEL is the label.
+ *
+ * For the application to TLS-1.2 key expansion, the seed is the
+ * concatenation of ServerHello.Random + ClientHello.Random,
+ * and the label is "key expansion".
+ *
+ * For example, `PSA_ALG_TLS12_PRF(PSA_ALG_SHA_256)` represents the
+ * TLS 1.2 PRF using HMAC-SHA-256.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ *
+ * \return The corresponding TLS-1.2 PRF algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_TLS12_PRF(hash_alg) \
+ (PSA_ALG_TLS12_PRF_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+
+/** Whether the specified algorithm is a TLS-1.2 PRF algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \c alg is a TLS-1.2 PRF algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \c alg is not a supported
+ * key derivation algorithm identifier.
+ */
+#define PSA_ALG_IS_TLS12_PRF(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_TLS12_PRF_BASE)
+#define PSA_ALG_TLS12_PRF_GET_HASH(hkdf_alg) \
+ (PSA_ALG_CATEGORY_HASH | ((hkdf_alg) & PSA_ALG_HASH_MASK))
+
+#define PSA_ALG_TLS12_PSK_TO_MS_BASE ((psa_algorithm_t) 0x08000300)
+/** Macro to build a TLS-1.2 PSK-to-MasterSecret algorithm.
+ *
+ * In a pure-PSK handshake in TLS 1.2, the master secret is derived
+ * from the PreSharedKey (PSK) through the application of padding
+ * (RFC 4279, Section 2) and the TLS-1.2 PRF (RFC 5246, Section 5).
+ * The latter is based on HMAC and can be used with either SHA-256
+ * or SHA-384.
+ *
+ * This key derivation algorithm uses the following inputs, which must be
+ * passed in the order given here:
+ * - #PSA_KEY_DERIVATION_INPUT_SEED is the seed.
+ * - #PSA_KEY_DERIVATION_INPUT_OTHER_SECRET is the other secret for the
+ * computation of the premaster secret. This input is optional;
+ * if omitted, it defaults to a string of null bytes with the same length
+ * as the secret (PSK) input.
+ * - #PSA_KEY_DERIVATION_INPUT_SECRET is the secret key.
+ * - #PSA_KEY_DERIVATION_INPUT_LABEL is the label.
+ *
+ * For the application to TLS-1.2, the seed (which is
+ * forwarded to the TLS-1.2 PRF) is the concatenation of the
+ * ClientHello.Random + ServerHello.Random,
+ * the label is "master secret" or "extended master secret" and
+ * the other secret depends on the key exchange specified in the cipher suite:
+ * - for a plain PSK cipher suite (RFC 4279, Section 2), omit
+ * PSA_KEY_DERIVATION_INPUT_OTHER_SECRET
+ * - for a DHE-PSK (RFC 4279, Section 3) or ECDHE-PSK cipher suite
+ * (RFC 5489, Section 2), the other secret should be the output of the
+ * PSA_ALG_FFDH or PSA_ALG_ECDH key agreement performed with the peer.
+ * The recommended way to pass this input is to use a key derivation
+ * algorithm constructed as
+ * PSA_ALG_KEY_AGREEMENT(ka_alg, PSA_ALG_TLS12_PSK_TO_MS(hash_alg))
+ * and to call psa_key_derivation_key_agreement(). Alternatively,
+ * this input may be an output of `psa_raw_key_agreement()` passed with
+ * psa_key_derivation_input_bytes(), or an equivalent input passed with
+ * psa_key_derivation_input_bytes() or psa_key_derivation_input_key().
+ * - for a RSA-PSK cipher suite (RFC 4279, Section 4), the other secret
+ * should be the 48-byte client challenge (the PreMasterSecret of
+ * (RFC 5246, Section 7.4.7.1)) concatenation of the TLS version and
+ * a 46-byte random string chosen by the client. On the server, this is
+ * typically an output of psa_asymmetric_decrypt() using
+ * PSA_ALG_RSA_PKCS1V15_CRYPT, passed to the key derivation operation
+ * with `psa_key_derivation_input_bytes()`.
+ *
+ * For example, `PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA_256)` represents the
+ * TLS-1.2 PSK to MasterSecret derivation PRF using HMAC-SHA-256.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ *
+ * \return The corresponding TLS-1.2 PSK to MS algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_TLS12_PSK_TO_MS(hash_alg) \
+ (PSA_ALG_TLS12_PSK_TO_MS_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+
+/** Whether the specified algorithm is a TLS-1.2 PSK to MS algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \c alg is a TLS-1.2 PSK to MS algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \c alg is not a supported
+ * key derivation algorithm identifier.
+ */
+#define PSA_ALG_IS_TLS12_PSK_TO_MS(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_TLS12_PSK_TO_MS_BASE)
+#define PSA_ALG_TLS12_PSK_TO_MS_GET_HASH(hkdf_alg) \
+ (PSA_ALG_CATEGORY_HASH | ((hkdf_alg) & PSA_ALG_HASH_MASK))
+
+/* The TLS 1.2 ECJPAKE-to-PMS KDF. It takes the shared secret K (an EC point
+ * in case of EC J-PAKE) and calculates SHA256(K.X) that the rest of TLS 1.2
+ * will use to derive the session secret, as defined by step 2 of
+ * https://datatracker.ietf.org/doc/html/draft-cragie-tls-ecjpake-01#section-8.7.
+ * Uses PSA_ALG_SHA_256.
+ * This function takes a single input:
+ * #PSA_KEY_DERIVATION_INPUT_SECRET is the shared secret K from EC J-PAKE.
+ * The only supported curve is secp256r1 (the 256-bit curve in
+ * #PSA_ECC_FAMILY_SECP_R1), so the input must be exactly 65 bytes.
+ * The output has to be read as a single chunk of 32 bytes, defined as
+ * PSA_TLS12_ECJPAKE_TO_PMS_DATA_SIZE.
+ */
+#define PSA_ALG_TLS12_ECJPAKE_TO_PMS ((psa_algorithm_t) 0x08000609)
+
+/* This flag indicates whether the key derivation algorithm is suitable for
+ * use on low-entropy secrets such as password - these algorithms are also
+ * known as key stretching or password hashing schemes. These are also the
+ * algorithms that accepts inputs of type #PSA_KEY_DERIVATION_INPUT_PASSWORD.
+ *
+ * Those algorithms cannot be combined with a key agreement algorithm.
+ */
+#define PSA_ALG_KEY_DERIVATION_STRETCHING_FLAG ((psa_algorithm_t) 0x00800000)
+
+#define PSA_ALG_PBKDF2_HMAC_BASE ((psa_algorithm_t) 0x08800100)
+/** Macro to build a PBKDF2-HMAC password hashing / key stretching algorithm.
+ *
+ * PBKDF2 is defined by PKCS#5, republished as RFC 8018 (section 5.2).
+ * This macro specifies the PBKDF2 algorithm constructed using a PRF based on
+ * HMAC with the specified hash.
+ * For example, `PSA_ALG_PBKDF2_HMAC(PSA_ALG_SHA_256)` specifies PBKDF2
+ * using the PRF HMAC-SHA-256.
+ *
+ * This key derivation algorithm uses the following inputs, which must be
+ * provided in the following order:
+ * - #PSA_KEY_DERIVATION_INPUT_COST is the iteration count.
+ * This input step must be used exactly once.
+ * - #PSA_KEY_DERIVATION_INPUT_SALT is the salt.
+ * This input step must be used one or more times; if used several times, the
+ * inputs will be concatenated. This can be used to build the final salt
+ * from multiple sources, both public and secret (also known as pepper).
+ * - #PSA_KEY_DERIVATION_INPUT_PASSWORD is the password to be hashed.
+ * This input step must be used exactly once.
+ *
+ * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that
+ * #PSA_ALG_IS_HASH(\p hash_alg) is true).
+ *
+ * \return The corresponding PBKDF2-HMAC-XXX algorithm.
+ * \return Unspecified if \p hash_alg is not a supported
+ * hash algorithm.
+ */
+#define PSA_ALG_PBKDF2_HMAC(hash_alg) \
+ (PSA_ALG_PBKDF2_HMAC_BASE | ((hash_alg) & PSA_ALG_HASH_MASK))
+
+/** Whether the specified algorithm is a PBKDF2-HMAC algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \c alg is a PBKDF2-HMAC algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \c alg is not a supported
+ * key derivation algorithm identifier.
+ */
+#define PSA_ALG_IS_PBKDF2_HMAC(alg) \
+ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_PBKDF2_HMAC_BASE)
+#define PSA_ALG_PBKDF2_HMAC_GET_HASH(pbkdf2_alg) \
+ (PSA_ALG_CATEGORY_HASH | ((pbkdf2_alg) & PSA_ALG_HASH_MASK))
+/** The PBKDF2-AES-CMAC-PRF-128 password hashing / key stretching algorithm.
+ *
+ * PBKDF2 is defined by PKCS#5, republished as RFC 8018 (section 5.2).
+ * This macro specifies the PBKDF2 algorithm constructed using the
+ * AES-CMAC-PRF-128 PRF specified by RFC 4615.
+ *
+ * This key derivation algorithm uses the same inputs as
+ * #PSA_ALG_PBKDF2_HMAC() with the same constraints.
+ */
+#define PSA_ALG_PBKDF2_AES_CMAC_PRF_128 ((psa_algorithm_t) 0x08800200)
+
+#define PSA_ALG_IS_PBKDF2(kdf_alg) \
+ (PSA_ALG_IS_PBKDF2_HMAC(kdf_alg) || \
+ ((kdf_alg) == PSA_ALG_PBKDF2_AES_CMAC_PRF_128))
+
+#define PSA_ALG_KEY_DERIVATION_MASK ((psa_algorithm_t) 0xfe00ffff)
+#define PSA_ALG_KEY_AGREEMENT_MASK ((psa_algorithm_t) 0xffff0000)
+
+/** Macro to build a combined algorithm that chains a key agreement with
+ * a key derivation.
+ *
+ * \param ka_alg A key agreement algorithm (\c PSA_ALG_XXX value such
+ * that #PSA_ALG_IS_KEY_AGREEMENT(\p ka_alg) is true).
+ * \param kdf_alg A key derivation algorithm (\c PSA_ALG_XXX value such
+ * that #PSA_ALG_IS_KEY_DERIVATION(\p kdf_alg) is true).
+ *
+ * \return The corresponding key agreement and derivation
+ * algorithm.
+ * \return Unspecified if \p ka_alg is not a supported
+ * key agreement algorithm or \p kdf_alg is not a
+ * supported key derivation algorithm.
+ */
+#define PSA_ALG_KEY_AGREEMENT(ka_alg, kdf_alg) \
+ ((ka_alg) | (kdf_alg))
+
+#define PSA_ALG_KEY_AGREEMENT_GET_KDF(alg) \
+ (((alg) & PSA_ALG_KEY_DERIVATION_MASK) | PSA_ALG_CATEGORY_KEY_DERIVATION)
+
+#define PSA_ALG_KEY_AGREEMENT_GET_BASE(alg) \
+ (((alg) & PSA_ALG_KEY_AGREEMENT_MASK) | PSA_ALG_CATEGORY_KEY_AGREEMENT)
+
+/** Whether the specified algorithm is a raw key agreement algorithm.
+ *
+ * A raw key agreement algorithm is one that does not specify
+ * a key derivation function.
+ * Usually, raw key agreement algorithms are constructed directly with
+ * a \c PSA_ALG_xxx macro while non-raw key agreement algorithms are
+ * constructed with #PSA_ALG_KEY_AGREEMENT().
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \p alg is a raw key agreement algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \p alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_RAW_KEY_AGREEMENT(alg) \
+ (PSA_ALG_IS_KEY_AGREEMENT(alg) && \
+ PSA_ALG_KEY_AGREEMENT_GET_KDF(alg) == PSA_ALG_CATEGORY_KEY_DERIVATION)
+
+#define PSA_ALG_IS_KEY_DERIVATION_OR_AGREEMENT(alg) \
+ ((PSA_ALG_IS_KEY_DERIVATION(alg) || PSA_ALG_IS_KEY_AGREEMENT(alg)))
+
+/** The finite-field Diffie-Hellman (DH) key agreement algorithm.
+ *
+ * The shared secret produced by key agreement is
+ * `g^{ab}` in big-endian format.
+ * It is `ceiling(m / 8)` bytes long where `m` is the size of the prime `p`
+ * in bits.
+ */
+#define PSA_ALG_FFDH ((psa_algorithm_t) 0x09010000)
+
+/** Whether the specified algorithm is a finite field Diffie-Hellman algorithm.
+ *
+ * This includes the raw finite field Diffie-Hellman algorithm as well as
+ * finite-field Diffie-Hellman followed by any supporter key derivation
+ * algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \c alg is a finite field Diffie-Hellman algorithm, 0 otherwise.
+ * This macro may return either 0 or 1 if \c alg is not a supported
+ * key agreement algorithm identifier.
+ */
+#define PSA_ALG_IS_FFDH(alg) \
+ (PSA_ALG_KEY_AGREEMENT_GET_BASE(alg) == PSA_ALG_FFDH)
+
+/** The elliptic curve Diffie-Hellman (ECDH) key agreement algorithm.
+ *
+ * The shared secret produced by key agreement is the x-coordinate of
+ * the shared secret point. It is always `ceiling(m / 8)` bytes long where
+ * `m` is the bit size associated with the curve, i.e. the bit size of the
+ * order of the curve's coordinate field. When `m` is not a multiple of 8,
+ * the byte containing the most significant bit of the shared secret
+ * is padded with zero bits. The byte order is either little-endian
+ * or big-endian depending on the curve type.
+ *
+ * - For Montgomery curves (curve types `PSA_ECC_FAMILY_CURVEXXX`),
+ * the shared secret is the x-coordinate of `d_A Q_B = d_B Q_A`
+ * in little-endian byte order.
+ * The bit size is 448 for Curve448 and 255 for Curve25519.
+ * - For Weierstrass curves over prime fields (curve types
+ * `PSA_ECC_FAMILY_SECPXXX` and `PSA_ECC_FAMILY_BRAINPOOL_PXXX`),
+ * the shared secret is the x-coordinate of `d_A Q_B = d_B Q_A`
+ * in big-endian byte order.
+ * The bit size is `m = ceiling(log_2(p))` for the field `F_p`.
+ * - For Weierstrass curves over binary fields (curve types
+ * `PSA_ECC_FAMILY_SECTXXX`),
+ * the shared secret is the x-coordinate of `d_A Q_B = d_B Q_A`
+ * in big-endian byte order.
+ * The bit size is `m` for the field `F_{2^m}`.
+ */
+#define PSA_ALG_ECDH ((psa_algorithm_t) 0x09020000)
+
+/** Whether the specified algorithm is an elliptic curve Diffie-Hellman
+ * algorithm.
+ *
+ * This includes the raw elliptic curve Diffie-Hellman algorithm as well as
+ * elliptic curve Diffie-Hellman followed by any supporter key derivation
+ * algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \c alg is an elliptic curve Diffie-Hellman algorithm,
+ * 0 otherwise.
+ * This macro may return either 0 or 1 if \c alg is not a supported
+ * key agreement algorithm identifier.
+ */
+#define PSA_ALG_IS_ECDH(alg) \
+ (PSA_ALG_KEY_AGREEMENT_GET_BASE(alg) == PSA_ALG_ECDH)
+
+/** Whether the specified algorithm encoding is a wildcard.
+ *
+ * Wildcard values may only be used to set the usage algorithm field in
+ * a policy, not to perform an operation.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return 1 if \c alg is a wildcard algorithm encoding.
+ * \return 0 if \c alg is a non-wildcard algorithm encoding (suitable for
+ * an operation).
+ * \return This macro may return either 0 or 1 if \c alg is not a supported
+ * algorithm identifier.
+ */
+#define PSA_ALG_IS_WILDCARD(alg) \
+ (PSA_ALG_IS_HASH_AND_SIGN(alg) ? \
+ PSA_ALG_SIGN_GET_HASH(alg) == PSA_ALG_ANY_HASH : \
+ PSA_ALG_IS_MAC(alg) ? \
+ (alg & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0 : \
+ PSA_ALG_IS_AEAD(alg) ? \
+ (alg & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0 : \
+ (alg) == PSA_ALG_ANY_HASH)
+
+/** Get the hash used by a composite algorithm.
+ *
+ * \param alg An algorithm identifier (value of type #psa_algorithm_t).
+ *
+ * \return The underlying hash algorithm if alg is a composite algorithm that
+ * uses a hash algorithm.
+ *
+ * \return \c 0 if alg is not a composite algorithm that uses a hash.
+ */
+#define PSA_ALG_GET_HASH(alg) \
+ (((alg) & 0x000000ff) == 0 ? ((psa_algorithm_t) 0) : 0x02000000 | ((alg) & 0x000000ff))
+
+/**@}*/
+
+/** \defgroup key_lifetimes Key lifetimes
+ * @{
+ */
+
+/* Note that location and persistence level values are embedded in the
+ * persistent key store, as part of key metadata. As a consequence, they
+ * must not be changed (unless the storage format version changes).
+ */
+
+/** The default lifetime for volatile keys.
+ *
+ * A volatile key only exists as long as the identifier to it is not destroyed.
+ * The key material is guaranteed to be erased on a power reset.
+ *
+ * A key with this lifetime is typically stored in the RAM area of the
+ * PSA Crypto subsystem. However this is an implementation choice.
+ * If an implementation stores data about the key in a non-volatile memory,
+ * it must release all the resources associated with the key and erase the
+ * key material if the calling application terminates.
+ */
+#define PSA_KEY_LIFETIME_VOLATILE ((psa_key_lifetime_t) 0x00000000)
+
+/** The default lifetime for persistent keys.
+ *
+ * A persistent key remains in storage until it is explicitly destroyed or
+ * until the corresponding storage area is wiped. This specification does
+ * not define any mechanism to wipe a storage area, but integrations may
+ * provide their own mechanism (for example to perform a factory reset,
+ * to prepare for device refurbishment, or to uninstall an application).
+ *
+ * This lifetime value is the default storage area for the calling
+ * application. Integrations of Mbed TLS may support other persistent lifetimes.
+ * See ::psa_key_lifetime_t for more information.
+ */
+#define PSA_KEY_LIFETIME_PERSISTENT ((psa_key_lifetime_t) 0x00000001)
+
+/** The persistence level of volatile keys.
+ *
+ * See ::psa_key_persistence_t for more information.
+ */
+#define PSA_KEY_PERSISTENCE_VOLATILE ((psa_key_persistence_t) 0x00)
+
+/** The default persistence level for persistent keys.
+ *
+ * See ::psa_key_persistence_t for more information.
+ */
+#define PSA_KEY_PERSISTENCE_DEFAULT ((psa_key_persistence_t) 0x01)
+
+/** A persistence level indicating that a key is never destroyed.
+ *
+ * See ::psa_key_persistence_t for more information.
+ */
+#define PSA_KEY_PERSISTENCE_READ_ONLY ((psa_key_persistence_t) 0xff)
+
+#define PSA_KEY_LIFETIME_GET_PERSISTENCE(lifetime) \
+ ((psa_key_persistence_t) ((lifetime) & 0x000000ff))
+
+#define PSA_KEY_LIFETIME_GET_LOCATION(lifetime) \
+ ((psa_key_location_t) ((lifetime) >> 8))
+
+/** Whether a key lifetime indicates that the key is volatile.
+ *
+ * A volatile key is automatically destroyed by the implementation when
+ * the application instance terminates. In particular, a volatile key
+ * is automatically destroyed on a power reset of the device.
+ *
+ * A key that is not volatile is persistent. Persistent keys are
+ * preserved until the application explicitly destroys them or until an
+ * implementation-specific device management event occurs (for example,
+ * a factory reset).
+ *
+ * \param lifetime The lifetime value to query (value of type
+ * ::psa_key_lifetime_t).
+ *
+ * \return \c 1 if the key is volatile, otherwise \c 0.
+ */
+#define PSA_KEY_LIFETIME_IS_VOLATILE(lifetime) \
+ (PSA_KEY_LIFETIME_GET_PERSISTENCE(lifetime) == \
+ PSA_KEY_PERSISTENCE_VOLATILE)
+
+/** Whether a key lifetime indicates that the key is read-only.
+ *
+ * Read-only keys cannot be created or destroyed through the PSA Crypto API.
+ * They must be created through platform-specific means that bypass the API.
+ *
+ * Some platforms may offer ways to destroy read-only keys. For example,
+ * consider a platform with multiple levels of privilege, where a
+ * low-privilege application can use a key but is not allowed to destroy
+ * it, and the platform exposes the key to the application with a read-only
+ * lifetime. High-privilege code can destroy the key even though the
+ * application sees the key as read-only.
+ *
+ * \param lifetime The lifetime value to query (value of type
+ * ::psa_key_lifetime_t).
+ *
+ * \return \c 1 if the key is read-only, otherwise \c 0.
+ */
+#define PSA_KEY_LIFETIME_IS_READ_ONLY(lifetime) \
+ (PSA_KEY_LIFETIME_GET_PERSISTENCE(lifetime) == \
+ PSA_KEY_PERSISTENCE_READ_ONLY)
+
+/** Construct a lifetime from a persistence level and a location.
+ *
+ * \param persistence The persistence level
+ * (value of type ::psa_key_persistence_t).
+ * \param location The location indicator
+ * (value of type ::psa_key_location_t).
+ *
+ * \return The constructed lifetime value.
+ */
+#define PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(persistence, location) \
+ ((location) << 8 | (persistence))
+
+/** The local storage area for persistent keys.
+ *
+ * This storage area is available on all systems that can store persistent
+ * keys without delegating the storage to a third-party cryptoprocessor.
+ *
+ * See ::psa_key_location_t for more information.
+ */
+#define PSA_KEY_LOCATION_LOCAL_STORAGE ((psa_key_location_t) 0x000000)
+
+#define PSA_KEY_LOCATION_VENDOR_FLAG ((psa_key_location_t) 0x800000)
+
+/* Note that key identifier values are embedded in the
+ * persistent key store, as part of key metadata. As a consequence, they
+ * must not be changed (unless the storage format version changes).
+ */
+
+/** The null key identifier.
+ */
+/* *INDENT-OFF* (https://github.com/ARM-software/psa-arch-tests/issues/337) */
+#define PSA_KEY_ID_NULL ((psa_key_id_t)0)
+/* *INDENT-ON* */
+/** The minimum value for a key identifier chosen by the application.
+ */
+#define PSA_KEY_ID_USER_MIN ((psa_key_id_t) 0x00000001)
+/** The maximum value for a key identifier chosen by the application.
+ */
+#define PSA_KEY_ID_USER_MAX ((psa_key_id_t) 0x3fffffff)
+/** The minimum value for a key identifier chosen by the implementation.
+ */
+#define PSA_KEY_ID_VENDOR_MIN ((psa_key_id_t) 0x40000000)
+/** The maximum value for a key identifier chosen by the implementation.
+ */
+#define PSA_KEY_ID_VENDOR_MAX ((psa_key_id_t) 0x7fffffff)
+
+
+#if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER)
+
+#define MBEDTLS_SVC_KEY_ID_INIT ((psa_key_id_t) 0)
+#define MBEDTLS_SVC_KEY_ID_GET_KEY_ID(id) (id)
+#define MBEDTLS_SVC_KEY_ID_GET_OWNER_ID(id) (0)
+
+/** Utility to initialize a key identifier at runtime.
+ *
+ * \param unused Unused parameter.
+ * \param key_id Identifier of the key.
+ */
+static inline mbedtls_svc_key_id_t mbedtls_svc_key_id_make(
+ unsigned int unused, psa_key_id_t key_id)
+{
+ (void) unused;
+
+ return key_id;
+}
+
+/** Compare two key identifiers.
+ *
+ * \param id1 First key identifier.
+ * \param id2 Second key identifier.
+ *
+ * \return Non-zero if the two key identifier are equal, zero otherwise.
+ */
+static inline int mbedtls_svc_key_id_equal(mbedtls_svc_key_id_t id1,
+ mbedtls_svc_key_id_t id2)
+{
+ return id1 == id2;
+}
+
+/** Check whether a key identifier is null.
+ *
+ * \param key Key identifier.
+ *
+ * \return Non-zero if the key identifier is null, zero otherwise.
+ */
+static inline int mbedtls_svc_key_id_is_null(mbedtls_svc_key_id_t key)
+{
+ return key == 0;
+}
+
+#else /* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */
+
+#define MBEDTLS_SVC_KEY_ID_INIT ((mbedtls_svc_key_id_t){ 0, 0 })
+#define MBEDTLS_SVC_KEY_ID_GET_KEY_ID(id) ((id).MBEDTLS_PRIVATE(key_id))
+#define MBEDTLS_SVC_KEY_ID_GET_OWNER_ID(id) ((id).MBEDTLS_PRIVATE(owner))
+
+/** Utility to initialize a key identifier at runtime.
+ *
+ * \param owner_id Identifier of the key owner.
+ * \param key_id Identifier of the key.
+ */
+static inline mbedtls_svc_key_id_t mbedtls_svc_key_id_make(
+ mbedtls_key_owner_id_t owner_id, psa_key_id_t key_id)
+{
+ return (mbedtls_svc_key_id_t){ .MBEDTLS_PRIVATE(key_id) = key_id,
+ .MBEDTLS_PRIVATE(owner) = owner_id };
+}
+
+/** Compare two key identifiers.
+ *
+ * \param id1 First key identifier.
+ * \param id2 Second key identifier.
+ *
+ * \return Non-zero if the two key identifier are equal, zero otherwise.
+ */
+static inline int mbedtls_svc_key_id_equal(mbedtls_svc_key_id_t id1,
+ mbedtls_svc_key_id_t id2)
+{
+ return (id1.MBEDTLS_PRIVATE(key_id) == id2.MBEDTLS_PRIVATE(key_id)) &&
+ mbedtls_key_owner_id_equal(id1.MBEDTLS_PRIVATE(owner), id2.MBEDTLS_PRIVATE(owner));
+}
+
+/** Check whether a key identifier is null.
+ *
+ * \param key Key identifier.
+ *
+ * \return Non-zero if the key identifier is null, zero otherwise.
+ */
+static inline int mbedtls_svc_key_id_is_null(mbedtls_svc_key_id_t key)
+{
+ return key.MBEDTLS_PRIVATE(key_id) == 0;
+}
+
+#endif /* !MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */
+
+/**@}*/
+
+/** \defgroup policy Key policies
+ * @{
+ */
+
+/* Note that key usage flags are embedded in the
+ * persistent key store, as part of key metadata. As a consequence, they
+ * must not be changed (unless the storage format version changes).
+ */
+
+/** Whether the key may be exported.
+ *
+ * A public key or the public part of a key pair may always be exported
+ * regardless of the value of this permission flag.
+ *
+ * If a key does not have export permission, implementations shall not
+ * allow the key to be exported in plain form from the cryptoprocessor,
+ * whether through psa_export_key() or through a proprietary interface.
+ * The key may however be exportable in a wrapped form, i.e. in a form
+ * where it is encrypted by another key.
+ */
+#define PSA_KEY_USAGE_EXPORT ((psa_key_usage_t) 0x00000001)
+
+/** Whether the key may be copied.
+ *
+ * This flag allows the use of psa_copy_key() to make a copy of the key
+ * with the same policy or a more restrictive policy.
+ *
+ * For lifetimes for which the key is located in a secure element which
+ * enforce the non-exportability of keys, copying a key outside the secure
+ * element also requires the usage flag #PSA_KEY_USAGE_EXPORT.
+ * Copying the key inside the secure element is permitted with just
+ * #PSA_KEY_USAGE_COPY if the secure element supports it.
+ * For keys with the lifetime #PSA_KEY_LIFETIME_VOLATILE or
+ * #PSA_KEY_LIFETIME_PERSISTENT, the usage flag #PSA_KEY_USAGE_COPY
+ * is sufficient to permit the copy.
+ */
+#define PSA_KEY_USAGE_COPY ((psa_key_usage_t) 0x00000002)
+
+/** Whether the key may be used to encrypt a message.
+ *
+ * This flag allows the key to be used for a symmetric encryption operation,
+ * for an AEAD encryption-and-authentication operation,
+ * or for an asymmetric encryption operation,
+ * if otherwise permitted by the key's type and policy.
+ *
+ * For a key pair, this concerns the public key.
+ */
+#define PSA_KEY_USAGE_ENCRYPT ((psa_key_usage_t) 0x00000100)
+
+/** Whether the key may be used to decrypt a message.
+ *
+ * This flag allows the key to be used for a symmetric decryption operation,
+ * for an AEAD decryption-and-verification operation,
+ * or for an asymmetric decryption operation,
+ * if otherwise permitted by the key's type and policy.
+ *
+ * For a key pair, this concerns the private key.
+ */
+#define PSA_KEY_USAGE_DECRYPT ((psa_key_usage_t) 0x00000200)
+
+/** Whether the key may be used to sign a message.
+ *
+ * This flag allows the key to be used for a MAC calculation operation or for
+ * an asymmetric message signature operation, if otherwise permitted by the
+ * key’s type and policy.
+ *
+ * For a key pair, this concerns the private key.
+ */
+#define PSA_KEY_USAGE_SIGN_MESSAGE ((psa_key_usage_t) 0x00000400)
+
+/** Whether the key may be used to verify a message.
+ *
+ * This flag allows the key to be used for a MAC verification operation or for
+ * an asymmetric message signature verification operation, if otherwise
+ * permitted by the key’s type and policy.
+ *
+ * For a key pair, this concerns the public key.
+ */
+#define PSA_KEY_USAGE_VERIFY_MESSAGE ((psa_key_usage_t) 0x00000800)
+
+/** Whether the key may be used to sign a message.
+ *
+ * This flag allows the key to be used for a MAC calculation operation
+ * or for an asymmetric signature operation,
+ * if otherwise permitted by the key's type and policy.
+ *
+ * For a key pair, this concerns the private key.
+ */
+#define PSA_KEY_USAGE_SIGN_HASH ((psa_key_usage_t) 0x00001000)
+
+/** Whether the key may be used to verify a message signature.
+ *
+ * This flag allows the key to be used for a MAC verification operation
+ * or for an asymmetric signature verification operation,
+ * if otherwise permitted by the key's type and policy.
+ *
+ * For a key pair, this concerns the public key.
+ */
+#define PSA_KEY_USAGE_VERIFY_HASH ((psa_key_usage_t) 0x00002000)
+
+/** Whether the key may be used to derive other keys or produce a password
+ * hash.
+ *
+ * This flag allows the key to be used for a key derivation operation or for
+ * a key agreement operation, if otherwise permitted by the key's type and
+ * policy.
+ *
+ * If this flag is present on all keys used in calls to
+ * psa_key_derivation_input_key() for a key derivation operation, then it
+ * permits calling psa_key_derivation_output_bytes() or
+ * psa_key_derivation_output_key() at the end of the operation.
+ */
+#define PSA_KEY_USAGE_DERIVE ((psa_key_usage_t) 0x00004000)
+
+/** Whether the key may be used to verify the result of a key derivation,
+ * including password hashing.
+ *
+ * This flag allows the key to be used:
+ *
+ * This flag allows the key to be used in a key derivation operation, if
+ * otherwise permitted by the key's type and policy.
+ *
+ * If this flag is present on all keys used in calls to
+ * psa_key_derivation_input_key() for a key derivation operation, then it
+ * permits calling psa_key_derivation_verify_bytes() or
+ * psa_key_derivation_verify_key() at the end of the operation.
+ */
+#define PSA_KEY_USAGE_VERIFY_DERIVATION ((psa_key_usage_t) 0x00008000)
+
+/**@}*/
+
+/** \defgroup derivation Key derivation
+ * @{
+ */
+
+/* Key input steps are not embedded in the persistent storage, so you can
+ * change them if needed: it's only an ABI change. */
+
+/** A secret input for key derivation.
+ *
+ * This should be a key of type #PSA_KEY_TYPE_DERIVE
+ * (passed to psa_key_derivation_input_key())
+ * or the shared secret resulting from a key agreement
+ * (obtained via psa_key_derivation_key_agreement()).
+ *
+ * The secret can also be a direct input (passed to
+ * key_derivation_input_bytes()). In this case, the derivation operation
+ * may not be used to derive keys: the operation will only allow
+ * psa_key_derivation_output_bytes(),
+ * psa_key_derivation_verify_bytes(), or
+ * psa_key_derivation_verify_key(), but not
+ * psa_key_derivation_output_key().
+ */
+#define PSA_KEY_DERIVATION_INPUT_SECRET ((psa_key_derivation_step_t) 0x0101)
+
+/** A low-entropy secret input for password hashing / key stretching.
+ *
+ * This is usually a key of type #PSA_KEY_TYPE_PASSWORD (passed to
+ * psa_key_derivation_input_key()) or a direct input (passed to
+ * psa_key_derivation_input_bytes()) that is a password or passphrase. It can
+ * also be high-entropy secret such as a key of type #PSA_KEY_TYPE_DERIVE or
+ * the shared secret resulting from a key agreement.
+ *
+ * The secret can also be a direct input (passed to
+ * key_derivation_input_bytes()). In this case, the derivation operation
+ * may not be used to derive keys: the operation will only allow
+ * psa_key_derivation_output_bytes(),
+ * psa_key_derivation_verify_bytes(), or
+ * psa_key_derivation_verify_key(), but not
+ * psa_key_derivation_output_key().
+ */
+#define PSA_KEY_DERIVATION_INPUT_PASSWORD ((psa_key_derivation_step_t) 0x0102)
+
+/** A high-entropy additional secret input for key derivation.
+ *
+ * This is typically the shared secret resulting from a key agreement obtained
+ * via `psa_key_derivation_key_agreement()`. It may alternatively be a key of
+ * type `PSA_KEY_TYPE_DERIVE` passed to `psa_key_derivation_input_key()`, or
+ * a direct input passed to `psa_key_derivation_input_bytes()`.
+ */
+#define PSA_KEY_DERIVATION_INPUT_OTHER_SECRET \
+ ((psa_key_derivation_step_t) 0x0103)
+
+/** A label for key derivation.
+ *
+ * This should be a direct input.
+ * It can also be a key of type #PSA_KEY_TYPE_RAW_DATA.
+ */
+#define PSA_KEY_DERIVATION_INPUT_LABEL ((psa_key_derivation_step_t) 0x0201)
+
+/** A salt for key derivation.
+ *
+ * This should be a direct input.
+ * It can also be a key of type #PSA_KEY_TYPE_RAW_DATA or
+ * #PSA_KEY_TYPE_PEPPER.
+ */
+#define PSA_KEY_DERIVATION_INPUT_SALT ((psa_key_derivation_step_t) 0x0202)
+
+/** An information string for key derivation.
+ *
+ * This should be a direct input.
+ * It can also be a key of type #PSA_KEY_TYPE_RAW_DATA.
+ */
+#define PSA_KEY_DERIVATION_INPUT_INFO ((psa_key_derivation_step_t) 0x0203)
+
+/** A seed for key derivation.
+ *
+ * This should be a direct input.
+ * It can also be a key of type #PSA_KEY_TYPE_RAW_DATA.
+ */
+#define PSA_KEY_DERIVATION_INPUT_SEED ((psa_key_derivation_step_t) 0x0204)
+
+/** A cost parameter for password hashing / key stretching.
+ *
+ * This must be a direct input, passed to psa_key_derivation_input_integer().
+ */
+#define PSA_KEY_DERIVATION_INPUT_COST ((psa_key_derivation_step_t) 0x0205)
+
+/**@}*/
+
+/** \defgroup helper_macros Helper macros
+ * @{
+ */
+
+/* Helper macros */
+
+/** Check if two AEAD algorithm identifiers refer to the same AEAD algorithm
+ * regardless of the tag length they encode.
+ *
+ * \param aead_alg_1 An AEAD algorithm identifier.
+ * \param aead_alg_2 An AEAD algorithm identifier.
+ *
+ * \return 1 if both identifiers refer to the same AEAD algorithm,
+ * 0 otherwise.
+ * Unspecified if neither \p aead_alg_1 nor \p aead_alg_2 are
+ * a supported AEAD algorithm.
+ */
+#define MBEDTLS_PSA_ALG_AEAD_EQUAL(aead_alg_1, aead_alg_2) \
+ (!(((aead_alg_1) ^ (aead_alg_2)) & \
+ ~(PSA_ALG_AEAD_TAG_LENGTH_MASK | PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG)))
+
+/**@}*/
+
+/**@}*/
+
+/** \defgroup interruptible Interruptible operations
+ * @{
+ */
+
+/** Maximum value for use with \c psa_interruptible_set_max_ops() to determine
+ * the maximum number of ops allowed to be executed by an interruptible
+ * function in a single call.
+ */
+#define PSA_INTERRUPTIBLE_MAX_OPS_UNLIMITED UINT32_MAX
+
+/**@}*/
+
+#endif /* PSA_CRYPTO_VALUES_H */
diff --git a/include/secp256k1.h b/include/secp256k1.h
new file mode 100644
index 0000000..f4053f2
--- /dev/null
+++ b/include/secp256k1.h
@@ -0,0 +1,909 @@
+#ifndef SECP256K1_H
+#define SECP256K1_H
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+#include <stddef.h>
+
+/** Unless explicitly stated all pointer arguments must not be NULL.
+ *
+ * The following rules specify the order of arguments in API calls:
+ *
+ * 1. Context pointers go first, followed by output arguments, combined
+ * output/input arguments, and finally input-only arguments.
+ * 2. Array lengths always immediately follow the argument whose length
+ * they describe, even if this violates rule 1.
+ * 3. Within the OUT/OUTIN/IN groups, pointers to data that is typically generated
+ * later go first. This means: signatures, public nonces, secret nonces,
+ * messages, public keys, secret keys, tweaks.
+ * 4. Arguments that are not data pointers go last, from more complex to less
+ * complex: function pointers, algorithm names, messages, void pointers,
+ * counts, flags, booleans.
+ * 5. Opaque data pointers follow the function pointer they are to be passed to.
+ */
+
+/** Opaque data structure that holds context information
+ *
+ * The primary purpose of context objects is to store randomization data for
+ * enhanced protection against side-channel leakage. This protection is only
+ * effective if the context is randomized after its creation. See
+ * secp256k1_context_create for creation of contexts and
+ * secp256k1_context_randomize for randomization.
+ *
+ * A secondary purpose of context objects is to store pointers to callback
+ * functions that the library will call when certain error states arise. See
+ * secp256k1_context_set_error_callback as well as
+ * secp256k1_context_set_illegal_callback for details. Future library versions
+ * may use context objects for additional purposes.
+ *
+ * A constructed context can safely be used from multiple threads
+ * simultaneously, but API calls that take a non-const pointer to a context
+ * need exclusive access to it. In particular this is the case for
+ * secp256k1_context_destroy, secp256k1_context_preallocated_destroy,
+ * and secp256k1_context_randomize.
+ *
+ * Regarding randomization, either do it once at creation time (in which case
+ * you do not need any locking for the other calls), or use a read-write lock.
+ */
+typedef struct secp256k1_context_struct secp256k1_context;
+
+/** Opaque data structure that holds rewritable "scratch space"
+ *
+ * The purpose of this structure is to replace dynamic memory allocations,
+ * because we target architectures where this may not be available. It is
+ * essentially a resizable (within specified parameters) block of bytes,
+ * which is initially created either by memory allocation or TODO as a pointer
+ * into some fixed rewritable space.
+ *
+ * Unlike the context object, this cannot safely be shared between threads
+ * without additional synchronization logic.
+ */
+typedef struct secp256k1_scratch_space_struct secp256k1_scratch_space;
+
+/** Opaque data structure that holds a parsed and valid public key.
+ *
+ * The exact representation of data inside is implementation defined and not
+ * guaranteed to be portable between different platforms or versions. It is
+ * however guaranteed to be 64 bytes in size, and can be safely copied/moved.
+ * If you need to convert to a format suitable for storage or transmission,
+ * use secp256k1_ec_pubkey_serialize and secp256k1_ec_pubkey_parse. To
+ * compare keys, use secp256k1_ec_pubkey_cmp.
+ */
+typedef struct {
+ unsigned char data[64];
+} secp256k1_pubkey;
+
+/** Opaque data structured that holds a parsed ECDSA signature.
+ *
+ * The exact representation of data inside is implementation defined and not
+ * guaranteed to be portable between different platforms or versions. It is
+ * however guaranteed to be 64 bytes in size, and can be safely copied/moved.
+ * If you need to convert to a format suitable for storage, transmission, or
+ * comparison, use the secp256k1_ecdsa_signature_serialize_* and
+ * secp256k1_ecdsa_signature_parse_* functions.
+ */
+typedef struct {
+ unsigned char data[64];
+} secp256k1_ecdsa_signature;
+
+/** A pointer to a function to deterministically generate a nonce.
+ *
+ * Returns: 1 if a nonce was successfully generated. 0 will cause signing to fail.
+ * Out: nonce32: pointer to a 32-byte array to be filled by the function.
+ * In: msg32: the 32-byte message hash being verified (will not be NULL)
+ * key32: pointer to a 32-byte secret key (will not be NULL)
+ * algo16: pointer to a 16-byte array describing the signature
+ * algorithm (will be NULL for ECDSA for compatibility).
+ * data: Arbitrary data pointer that is passed through.
+ * attempt: how many iterations we have tried to find a nonce.
+ * This will almost always be 0, but different attempt values
+ * are required to result in a different nonce.
+ *
+ * Except for test cases, this function should compute some cryptographic hash of
+ * the message, the algorithm, the key and the attempt.
+ */
+typedef int (*secp256k1_nonce_function)(
+ unsigned char *nonce32,
+ const unsigned char *msg32,
+ const unsigned char *key32,
+ const unsigned char *algo16,
+ void *data,
+ unsigned int attempt
+);
+
+# if !defined(SECP256K1_GNUC_PREREQ)
+# if defined(__GNUC__)&&defined(__GNUC_MINOR__)
+# define SECP256K1_GNUC_PREREQ(_maj,_min) \
+ ((__GNUC__<<16)+__GNUC_MINOR__>=((_maj)<<16)+(_min))
+# else
+# define SECP256K1_GNUC_PREREQ(_maj,_min) 0
+# endif
+# endif
+
+/* When this header is used at build-time the SECP256K1_BUILD define needs to be set
+ * to correctly setup export attributes and nullness checks. This is normally done
+ * by secp256k1.c but to guard against this header being included before secp256k1.c
+ * has had a chance to set the define (e.g. via test harnesses that just includes
+ * secp256k1.c) we set SECP256K1_NO_BUILD when this header is processed without the
+ * BUILD define so this condition can be caught.
+ */
+#ifndef SECP256K1_BUILD
+# define SECP256K1_NO_BUILD
+#endif
+
+/* Symbol visibility. */
+#if defined(_WIN32)
+ /* GCC for Windows (e.g., MinGW) accepts the __declspec syntax
+ * for MSVC compatibility. A __declspec declaration implies (but is not
+ * exactly equivalent to) __attribute__ ((visibility("default"))), and so we
+ * actually want __declspec even on GCC, see "Microsoft Windows Function
+ * Attributes" in the GCC manual and the recommendations in
+ * https://gcc.gnu.org/wiki/Visibility. */
+# if defined(SECP256K1_BUILD)
+# if defined(DLL_EXPORT) || defined(SECP256K1_DLL_EXPORT)
+ /* Building libsecp256k1 as a DLL.
+ * 1. If using Libtool, it defines DLL_EXPORT automatically.
+ * 2. In other cases, SECP256K1_DLL_EXPORT must be defined. */
+# define SECP256K1_API extern __declspec (dllexport)
+# endif
+ /* The user must define SECP256K1_STATIC when consuming libsecp256k1 as a static
+ * library on Windows. */
+# elif !defined(SECP256K1_STATIC)
+ /* Consuming libsecp256k1 as a DLL. */
+# define SECP256K1_API extern __declspec (dllimport)
+# endif
+#endif
+#ifndef SECP256K1_API
+# if defined(__GNUC__) && (__GNUC__ >= 4) && defined(SECP256K1_BUILD)
+ /* Building libsecp256k1 on non-Windows using GCC or compatible. */
+# define SECP256K1_API extern __attribute__ ((visibility ("default")))
+# else
+ /* All cases not captured above. */
+# define SECP256K1_API extern
+# endif
+#endif
+
+/* Warning attributes
+ * NONNULL is not used if SECP256K1_BUILD is set to avoid the compiler optimizing out
+ * some paranoid null checks. */
+# if defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4)
+# define SECP256K1_WARN_UNUSED_RESULT __attribute__ ((__warn_unused_result__))
+# else
+# define SECP256K1_WARN_UNUSED_RESULT
+# endif
+# if !defined(SECP256K1_BUILD) && defined(__GNUC__) && SECP256K1_GNUC_PREREQ(3, 4)
+# define SECP256K1_ARG_NONNULL(_x) __attribute__ ((__nonnull__(_x)))
+# else
+# define SECP256K1_ARG_NONNULL(_x)
+# endif
+
+/* Attribute for marking functions, types, and variables as deprecated */
+#if !defined(SECP256K1_BUILD) && defined(__has_attribute)
+# if __has_attribute(__deprecated__)
+# define SECP256K1_DEPRECATED(_msg) __attribute__ ((__deprecated__(_msg)))
+# else
+# define SECP256K1_DEPRECATED(_msg)
+# endif
+#else
+# define SECP256K1_DEPRECATED(_msg)
+#endif
+
+/* All flags' lower 8 bits indicate what they're for. Do not use directly. */
+#define SECP256K1_FLAGS_TYPE_MASK ((1 << 8) - 1)
+#define SECP256K1_FLAGS_TYPE_CONTEXT (1 << 0)
+#define SECP256K1_FLAGS_TYPE_COMPRESSION (1 << 1)
+/* The higher bits contain the actual data. Do not use directly. */
+#define SECP256K1_FLAGS_BIT_CONTEXT_VERIFY (1 << 8)
+#define SECP256K1_FLAGS_BIT_CONTEXT_SIGN (1 << 9)
+#define SECP256K1_FLAGS_BIT_CONTEXT_DECLASSIFY (1 << 10)
+#define SECP256K1_FLAGS_BIT_COMPRESSION (1 << 8)
+
+/** Context flags to pass to secp256k1_context_create, secp256k1_context_preallocated_size, and
+ * secp256k1_context_preallocated_create. */
+#define SECP256K1_CONTEXT_NONE (SECP256K1_FLAGS_TYPE_CONTEXT)
+
+/** Deprecated context flags. These flags are treated equivalent to SECP256K1_CONTEXT_NONE. */
+#define SECP256K1_CONTEXT_VERIFY (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_VERIFY)
+#define SECP256K1_CONTEXT_SIGN (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_SIGN)
+
+/* Testing flag. Do not use. */
+#define SECP256K1_CONTEXT_DECLASSIFY (SECP256K1_FLAGS_TYPE_CONTEXT | SECP256K1_FLAGS_BIT_CONTEXT_DECLASSIFY)
+
+/** Flag to pass to secp256k1_ec_pubkey_serialize. */
+#define SECP256K1_EC_COMPRESSED (SECP256K1_FLAGS_TYPE_COMPRESSION | SECP256K1_FLAGS_BIT_COMPRESSION)
+#define SECP256K1_EC_UNCOMPRESSED (SECP256K1_FLAGS_TYPE_COMPRESSION)
+
+/** Prefix byte used to tag various encoded curvepoints for specific purposes */
+#define SECP256K1_TAG_PUBKEY_EVEN 0x02
+#define SECP256K1_TAG_PUBKEY_ODD 0x03
+#define SECP256K1_TAG_PUBKEY_UNCOMPRESSED 0x04
+#define SECP256K1_TAG_PUBKEY_HYBRID_EVEN 0x06
+#define SECP256K1_TAG_PUBKEY_HYBRID_ODD 0x07
+
+/** A built-in constant secp256k1 context object with static storage duration, to be
+ * used in conjunction with secp256k1_selftest.
+ *
+ * This context object offers *only limited functionality* , i.e., it cannot be used
+ * for API functions that perform computations involving secret keys, e.g., signing
+ * and public key generation. If this restriction applies to a specific API function,
+ * it is mentioned in its documentation. See secp256k1_context_create if you need a
+ * full context object that supports all functionality offered by the library.
+ *
+ * It is highly recommended to call secp256k1_selftest before using this context.
+ */
+SECP256K1_API const secp256k1_context *secp256k1_context_static;
+
+/** Deprecated alias for secp256k1_context_static. */
+SECP256K1_API const secp256k1_context *secp256k1_context_no_precomp
+SECP256K1_DEPRECATED("Use secp256k1_context_static instead");
+
+/** Perform basic self tests (to be used in conjunction with secp256k1_context_static)
+ *
+ * This function performs self tests that detect some serious usage errors and
+ * similar conditions, e.g., when the library is compiled for the wrong endianness.
+ * This is a last resort measure to be used in production. The performed tests are
+ * very rudimentary and are not intended as a replacement for running the test
+ * binaries.
+ *
+ * It is highly recommended to call this before using secp256k1_context_static.
+ * It is not necessary to call this function before using a context created with
+ * secp256k1_context_create (or secp256k1_context_preallocated_create), which will
+ * take care of performing the self tests.
+ *
+ * If the tests fail, this function will call the default error handler to abort the
+ * program (see secp256k1_context_set_error_callback).
+ */
+SECP256K1_API void secp256k1_selftest(void);
+
+
+/** Create a secp256k1 context object (in dynamically allocated memory).
+ *
+ * This function uses malloc to allocate memory. It is guaranteed that malloc is
+ * called at most once for every call of this function. If you need to avoid dynamic
+ * memory allocation entirely, see secp256k1_context_static and the functions in
+ * secp256k1_preallocated.h.
+ *
+ * Returns: pointer to a newly created context object.
+ * In: flags: Always set to SECP256K1_CONTEXT_NONE (see below).
+ *
+ * The only valid non-deprecated flag in recent library versions is
+ * SECP256K1_CONTEXT_NONE, which will create a context sufficient for all functionality
+ * offered by the library. All other (deprecated) flags will be treated as equivalent
+ * to the SECP256K1_CONTEXT_NONE flag. Though the flags parameter primarily exists for
+ * historical reasons, future versions of the library may introduce new flags.
+ *
+ * If the context is intended to be used for API functions that perform computations
+ * involving secret keys, e.g., signing and public key generation, then it is highly
+ * recommended to call secp256k1_context_randomize on the context before calling
+ * those API functions. This will provide enhanced protection against side-channel
+ * leakage, see secp256k1_context_randomize for details.
+ *
+ * Do not create a new context object for each operation, as construction and
+ * randomization can take non-negligible time.
+ */
+SECP256K1_API secp256k1_context *secp256k1_context_create(
+ unsigned int flags
+) SECP256K1_WARN_UNUSED_RESULT;
+
+/** Copy a secp256k1 context object (into dynamically allocated memory).
+ *
+ * This function uses malloc to allocate memory. It is guaranteed that malloc is
+ * called at most once for every call of this function. If you need to avoid dynamic
+ * memory allocation entirely, see the functions in secp256k1_preallocated.h.
+ *
+ * Cloning secp256k1_context_static is not possible, and should not be emulated by
+ * the caller (e.g., using memcpy). Create a new context instead.
+ *
+ * Returns: pointer to a newly created context object.
+ * Args: ctx: pointer to a context to copy (not secp256k1_context_static).
+ */
+SECP256K1_API secp256k1_context *secp256k1_context_clone(
+ const secp256k1_context *ctx
+) SECP256K1_ARG_NONNULL(1) SECP256K1_WARN_UNUSED_RESULT;
+
+/** Destroy a secp256k1 context object (created in dynamically allocated memory).
+ *
+ * The context pointer may not be used afterwards.
+ *
+ * The context to destroy must have been created using secp256k1_context_create
+ * or secp256k1_context_clone. If the context has instead been created using
+ * secp256k1_context_preallocated_create or secp256k1_context_preallocated_clone, the
+ * behaviour is undefined. In that case, secp256k1_context_preallocated_destroy must
+ * be used instead.
+ *
+ * Args: ctx: pointer to a context to destroy, constructed using
+ * secp256k1_context_create or secp256k1_context_clone
+ * (i.e., not secp256k1_context_static).
+ */
+SECP256K1_API void secp256k1_context_destroy(
+ secp256k1_context *ctx
+) SECP256K1_ARG_NONNULL(1);
+
+/** Set a callback function to be called when an illegal argument is passed to
+ * an API call. It will only trigger for violations that are mentioned
+ * explicitly in the header.
+ *
+ * The philosophy is that these shouldn't be dealt with through a
+ * specific return value, as calling code should not have branches to deal with
+ * the case that this code itself is broken.
+ *
+ * On the other hand, during debug stage, one would want to be informed about
+ * such mistakes, and the default (crashing) may be inadvisable.
+ * When this callback is triggered, the API function called is guaranteed not
+ * to cause a crash, though its return value and output arguments are
+ * undefined.
+ *
+ * When this function has not been called (or called with fn==NULL), then the
+ * default handler will be used. The library provides a default handler which
+ * writes the message to stderr and calls abort. This default handler can be
+ * replaced at link time if the preprocessor macro
+ * USE_EXTERNAL_DEFAULT_CALLBACKS is defined, which is the case if the build
+ * has been configured with --enable-external-default-callbacks. Then the
+ * following two symbols must be provided to link against:
+ * - void secp256k1_default_illegal_callback_fn(const char *message, void *data);
+ * - void secp256k1_default_error_callback_fn(const char *message, void *data);
+ * The library can call these default handlers even before a proper callback data
+ * pointer could have been set using secp256k1_context_set_illegal_callback or
+ * secp256k1_context_set_error_callback, e.g., when the creation of a context
+ * fails. In this case, the corresponding default handler will be called with
+ * the data pointer argument set to NULL.
+ *
+ * Args: ctx: pointer to a context object.
+ * In: fun: pointer to a function to call when an illegal argument is
+ * passed to the API, taking a message and an opaque pointer.
+ * (NULL restores the default handler.)
+ * data: the opaque pointer to pass to fun above, must be NULL for the default handler.
+ *
+ * See also secp256k1_context_set_error_callback.
+ */
+SECP256K1_API void secp256k1_context_set_illegal_callback(
+ secp256k1_context *ctx,
+ void (*fun)(const char *message, void *data),
+ const void *data
+) SECP256K1_ARG_NONNULL(1);
+
+/** Set a callback function to be called when an internal consistency check
+ * fails.
+ *
+ * The default callback writes an error message to stderr and calls abort
+ * to abort the program.
+ *
+ * This can only trigger in case of a hardware failure, miscompilation,
+ * memory corruption, serious bug in the library, or other error would can
+ * otherwise result in undefined behaviour. It will not trigger due to mere
+ * incorrect usage of the API (see secp256k1_context_set_illegal_callback
+ * for that). After this callback returns, anything may happen, including
+ * crashing.
+ *
+ * Args: ctx: pointer to a context object.
+ * In: fun: pointer to a function to call when an internal error occurs,
+ * taking a message and an opaque pointer (NULL restores the
+ * default handler, see secp256k1_context_set_illegal_callback
+ * for details).
+ * data: the opaque pointer to pass to fun above, must be NULL for the default handler.
+ *
+ * See also secp256k1_context_set_illegal_callback.
+ */
+SECP256K1_API void secp256k1_context_set_error_callback(
+ secp256k1_context *ctx,
+ void (*fun)(const char *message, void *data),
+ const void *data
+) SECP256K1_ARG_NONNULL(1);
+
+/** Create a secp256k1 scratch space object.
+ *
+ * Returns: a newly created scratch space.
+ * Args: ctx: pointer to a context object.
+ * In: size: amount of memory to be available as scratch space. Some extra
+ * (<100 bytes) will be allocated for extra accounting.
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT secp256k1_scratch_space *secp256k1_scratch_space_create(
+ const secp256k1_context *ctx,
+ size_t size
+) SECP256K1_ARG_NONNULL(1);
+
+/** Destroy a secp256k1 scratch space.
+ *
+ * The pointer may not be used afterwards.
+ * Args: ctx: pointer to a context object.
+ * scratch: space to destroy
+ */
+SECP256K1_API void secp256k1_scratch_space_destroy(
+ const secp256k1_context *ctx,
+ secp256k1_scratch_space *scratch
+) SECP256K1_ARG_NONNULL(1);
+
+/** Parse a variable-length public key into the pubkey object.
+ *
+ * Returns: 1 if the public key was fully valid.
+ * 0 if the public key could not be parsed or is invalid.
+ * Args: ctx: pointer to a context object.
+ * Out: pubkey: pointer to a pubkey object. If 1 is returned, it is set to a
+ * parsed version of input. If not, its value is undefined.
+ * In: input: pointer to a serialized public key
+ * inputlen: length of the array pointed to by input
+ *
+ * This function supports parsing compressed (33 bytes, header byte 0x02 or
+ * 0x03), uncompressed (65 bytes, header byte 0x04), or hybrid (65 bytes, header
+ * byte 0x06 or 0x07) format public keys.
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_parse(
+ const secp256k1_context *ctx,
+ secp256k1_pubkey *pubkey,
+ const unsigned char *input,
+ size_t inputlen
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Serialize a pubkey object into a serialized byte sequence.
+ *
+ * Returns: 1 always.
+ * Args: ctx: pointer to a context object.
+ * Out: output: pointer to a 65-byte (if compressed==0) or 33-byte (if
+ * compressed==1) byte array to place the serialized key
+ * in.
+ * In/Out: outputlen: pointer to an integer which is initially set to the
+ * size of output, and is overwritten with the written
+ * size.
+ * In: pubkey: pointer to a secp256k1_pubkey containing an
+ * initialized public key.
+ * flags: SECP256K1_EC_COMPRESSED if serialization should be in
+ * compressed format, otherwise SECP256K1_EC_UNCOMPRESSED.
+ */
+SECP256K1_API int secp256k1_ec_pubkey_serialize(
+ const secp256k1_context *ctx,
+ unsigned char *output,
+ size_t *outputlen,
+ const secp256k1_pubkey *pubkey,
+ unsigned int flags
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
+
+/** Compare two public keys using lexicographic (of compressed serialization) order
+ *
+ * Returns: <0 if the first public key is less than the second
+ * >0 if the first public key is greater than the second
+ * 0 if the two public keys are equal
+ * Args: ctx: pointer to a context object
+ * In: pubkey1: first public key to compare
+ * pubkey2: second public key to compare
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_cmp(
+ const secp256k1_context *ctx,
+ const secp256k1_pubkey *pubkey1,
+ const secp256k1_pubkey *pubkey2
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Parse an ECDSA signature in compact (64 bytes) format.
+ *
+ * Returns: 1 when the signature could be parsed, 0 otherwise.
+ * Args: ctx: pointer to a context object
+ * Out: sig: pointer to a signature object
+ * In: input64: pointer to the 64-byte array to parse
+ *
+ * The signature must consist of a 32-byte big endian R value, followed by a
+ * 32-byte big endian S value. If R or S fall outside of [0..order-1], the
+ * encoding is invalid. R and S with value 0 are allowed in the encoding.
+ *
+ * After the call, sig will always be initialized. If parsing failed or R or
+ * S are zero, the resulting sig value is guaranteed to fail verification for
+ * any message and public key.
+ */
+SECP256K1_API int secp256k1_ecdsa_signature_parse_compact(
+ const secp256k1_context *ctx,
+ secp256k1_ecdsa_signature *sig,
+ const unsigned char *input64
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Parse a DER ECDSA signature.
+ *
+ * Returns: 1 when the signature could be parsed, 0 otherwise.
+ * Args: ctx: pointer to a context object
+ * Out: sig: pointer to a signature object
+ * In: input: pointer to the signature to be parsed
+ * inputlen: the length of the array pointed to be input
+ *
+ * This function will accept any valid DER encoded signature, even if the
+ * encoded numbers are out of range.
+ *
+ * After the call, sig will always be initialized. If parsing failed or the
+ * encoded numbers are out of range, signature verification with it is
+ * guaranteed to fail for every message and public key.
+ */
+SECP256K1_API int secp256k1_ecdsa_signature_parse_der(
+ const secp256k1_context *ctx,
+ secp256k1_ecdsa_signature *sig,
+ const unsigned char *input,
+ size_t inputlen
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Serialize an ECDSA signature in DER format.
+ *
+ * Returns: 1 if enough space was available to serialize, 0 otherwise
+ * Args: ctx: pointer to a context object
+ * Out: output: pointer to an array to store the DER serialization
+ * In/Out: outputlen: pointer to a length integer. Initially, this integer
+ * should be set to the length of output. After the call
+ * it will be set to the length of the serialization (even
+ * if 0 was returned).
+ * In: sig: pointer to an initialized signature object
+ */
+SECP256K1_API int secp256k1_ecdsa_signature_serialize_der(
+ const secp256k1_context *ctx,
+ unsigned char *output,
+ size_t *outputlen,
+ const secp256k1_ecdsa_signature *sig
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
+
+/** Serialize an ECDSA signature in compact (64 byte) format.
+ *
+ * Returns: 1
+ * Args: ctx: pointer to a context object
+ * Out: output64: pointer to a 64-byte array to store the compact serialization
+ * In: sig: pointer to an initialized signature object
+ *
+ * See secp256k1_ecdsa_signature_parse_compact for details about the encoding.
+ */
+SECP256K1_API int secp256k1_ecdsa_signature_serialize_compact(
+ const secp256k1_context *ctx,
+ unsigned char *output64,
+ const secp256k1_ecdsa_signature *sig
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Verify an ECDSA signature.
+ *
+ * Returns: 1: correct signature
+ * 0: incorrect or unparseable signature
+ * Args: ctx: pointer to a context object
+ * In: sig: the signature being verified.
+ * msghash32: the 32-byte message hash being verified.
+ * The verifier must make sure to apply a cryptographic
+ * hash function to the message by itself and not accept an
+ * msghash32 value directly. Otherwise, it would be easy to
+ * create a "valid" signature without knowledge of the
+ * secret key. See also
+ * https://bitcoin.stackexchange.com/a/81116/35586 for more
+ * background on this topic.
+ * pubkey: pointer to an initialized public key to verify with.
+ *
+ * To avoid accepting malleable signatures, only ECDSA signatures in lower-S
+ * form are accepted.
+ *
+ * If you need to accept ECDSA signatures from sources that do not obey this
+ * rule, apply secp256k1_ecdsa_signature_normalize to the signature prior to
+ * verification, but be aware that doing so results in malleable signatures.
+ *
+ * For details, see the comments for that function.
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdsa_verify(
+ const secp256k1_context *ctx,
+ const secp256k1_ecdsa_signature *sig,
+ const unsigned char *msghash32,
+ const secp256k1_pubkey *pubkey
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
+
+/** Convert a signature to a normalized lower-S form.
+ *
+ * Returns: 1 if sigin was not normalized, 0 if it already was.
+ * Args: ctx: pointer to a context object
+ * Out: sigout: pointer to a signature to fill with the normalized form,
+ * or copy if the input was already normalized. (can be NULL if
+ * you're only interested in whether the input was already
+ * normalized).
+ * In: sigin: pointer to a signature to check/normalize (can be identical to sigout)
+ *
+ * With ECDSA a third-party can forge a second distinct signature of the same
+ * message, given a single initial signature, but without knowing the key. This
+ * is done by negating the S value modulo the order of the curve, 'flipping'
+ * the sign of the random point R which is not included in the signature.
+ *
+ * Forgery of the same message isn't universally problematic, but in systems
+ * where message malleability or uniqueness of signatures is important this can
+ * cause issues. This forgery can be blocked by all verifiers forcing signers
+ * to use a normalized form.
+ *
+ * The lower-S form reduces the size of signatures slightly on average when
+ * variable length encodings (such as DER) are used and is cheap to verify,
+ * making it a good choice. Security of always using lower-S is assured because
+ * anyone can trivially modify a signature after the fact to enforce this
+ * property anyway.
+ *
+ * The lower S value is always between 0x1 and
+ * 0x7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0,
+ * inclusive.
+ *
+ * No other forms of ECDSA malleability are known and none seem likely, but
+ * there is no formal proof that ECDSA, even with this additional restriction,
+ * is free of other malleability. Commonly used serialization schemes will also
+ * accept various non-unique encodings, so care should be taken when this
+ * property is required for an application.
+ *
+ * The secp256k1_ecdsa_sign function will by default create signatures in the
+ * lower-S form, and secp256k1_ecdsa_verify will not accept others. In case
+ * signatures come from a system that cannot enforce this property,
+ * secp256k1_ecdsa_signature_normalize must be called before verification.
+ */
+SECP256K1_API int secp256k1_ecdsa_signature_normalize(
+ const secp256k1_context *ctx,
+ secp256k1_ecdsa_signature *sigout,
+ const secp256k1_ecdsa_signature *sigin
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(3);
+
+/** An implementation of RFC6979 (using HMAC-SHA256) as nonce generation function.
+ * If a data pointer is passed, it is assumed to be a pointer to 32 bytes of
+ * extra entropy.
+ */
+SECP256K1_API const secp256k1_nonce_function secp256k1_nonce_function_rfc6979;
+
+/** A default safe nonce generation function (currently equal to secp256k1_nonce_function_rfc6979). */
+SECP256K1_API const secp256k1_nonce_function secp256k1_nonce_function_default;
+
+/** Create an ECDSA signature.
+ *
+ * Returns: 1: signature created
+ * 0: the nonce generation function failed, or the secret key was invalid.
+ * Args: ctx: pointer to a context object (not secp256k1_context_static).
+ * Out: sig: pointer to an array where the signature will be placed.
+ * In: msghash32: the 32-byte message hash being signed.
+ * seckey: pointer to a 32-byte secret key.
+ * noncefp: pointer to a nonce generation function. If NULL,
+ * secp256k1_nonce_function_default is used.
+ * ndata: pointer to arbitrary data used by the nonce generation function
+ * (can be NULL). If it is non-NULL and
+ * secp256k1_nonce_function_default is used, then ndata must be a
+ * pointer to 32-bytes of additional data.
+ *
+ * The created signature is always in lower-S form. See
+ * secp256k1_ecdsa_signature_normalize for more details.
+ */
+SECP256K1_API int secp256k1_ecdsa_sign(
+ const secp256k1_context *ctx,
+ secp256k1_ecdsa_signature *sig,
+ const unsigned char *msghash32,
+ const unsigned char *seckey,
+ secp256k1_nonce_function noncefp,
+ const void *ndata
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
+
+/** Verify an ECDSA secret key.
+ *
+ * A secret key is valid if it is not 0 and less than the secp256k1 curve order
+ * when interpreted as an integer (most significant byte first). The
+ * probability of choosing a 32-byte string uniformly at random which is an
+ * invalid secret key is negligible.
+ *
+ * Returns: 1: secret key is valid
+ * 0: secret key is invalid
+ * Args: ctx: pointer to a context object.
+ * In: seckey: pointer to a 32-byte secret key.
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_verify(
+ const secp256k1_context *ctx,
+ const unsigned char *seckey
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
+
+/** Compute the public key for a secret key.
+ *
+ * Returns: 1: secret was valid, public key stores.
+ * 0: secret was invalid, try again.
+ * Args: ctx: pointer to a context object (not secp256k1_context_static).
+ * Out: pubkey: pointer to the created public key.
+ * In: seckey: pointer to a 32-byte secret key.
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_create(
+ const secp256k1_context *ctx,
+ secp256k1_pubkey *pubkey,
+ const unsigned char *seckey
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Negates a secret key in place.
+ *
+ * Returns: 0 if the given secret key is invalid according to
+ * secp256k1_ec_seckey_verify. 1 otherwise
+ * Args: ctx: pointer to a context object
+ * In/Out: seckey: pointer to the 32-byte secret key to be negated. If the
+ * secret key is invalid according to
+ * secp256k1_ec_seckey_verify, this function returns 0 and
+ * seckey will be set to some unspecified value.
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_negate(
+ const secp256k1_context *ctx,
+ unsigned char *seckey
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
+
+/** Same as secp256k1_ec_seckey_negate, but DEPRECATED. Will be removed in
+ * future versions. */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_negate(
+ const secp256k1_context *ctx,
+ unsigned char *seckey
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2)
+ SECP256K1_DEPRECATED("Use secp256k1_ec_seckey_negate instead");
+
+/** Negates a public key in place.
+ *
+ * Returns: 1 always
+ * Args: ctx: pointer to a context object
+ * In/Out: pubkey: pointer to the public key to be negated.
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_negate(
+ const secp256k1_context *ctx,
+ secp256k1_pubkey *pubkey
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2);
+
+/** Tweak a secret key by adding tweak to it.
+ *
+ * Returns: 0 if the arguments are invalid or the resulting secret key would be
+ * invalid (only when the tweak is the negation of the secret key). 1
+ * otherwise.
+ * Args: ctx: pointer to a context object.
+ * In/Out: seckey: pointer to a 32-byte secret key. If the secret key is
+ * invalid according to secp256k1_ec_seckey_verify, this
+ * function returns 0. seckey will be set to some unspecified
+ * value if this function returns 0.
+ * In: tweak32: pointer to a 32-byte tweak, which must be valid according to
+ * secp256k1_ec_seckey_verify or 32 zero bytes. For uniformly
+ * random 32-byte tweaks, the chance of being invalid is
+ * negligible (around 1 in 2^128).
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_tweak_add(
+ const secp256k1_context *ctx,
+ unsigned char *seckey,
+ const unsigned char *tweak32
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Same as secp256k1_ec_seckey_tweak_add, but DEPRECATED. Will be removed in
+ * future versions. */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_tweak_add(
+ const secp256k1_context *ctx,
+ unsigned char *seckey,
+ const unsigned char *tweak32
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
+ SECP256K1_DEPRECATED("Use secp256k1_ec_seckey_tweak_add instead");
+
+/** Tweak a public key by adding tweak times the generator to it.
+ *
+ * Returns: 0 if the arguments are invalid or the resulting public key would be
+ * invalid (only when the tweak is the negation of the corresponding
+ * secret key). 1 otherwise.
+ * Args: ctx: pointer to a context object.
+ * In/Out: pubkey: pointer to a public key object. pubkey will be set to an
+ * invalid value if this function returns 0.
+ * In: tweak32: pointer to a 32-byte tweak, which must be valid according to
+ * secp256k1_ec_seckey_verify or 32 zero bytes. For uniformly
+ * random 32-byte tweaks, the chance of being invalid is
+ * negligible (around 1 in 2^128).
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_add(
+ const secp256k1_context *ctx,
+ secp256k1_pubkey *pubkey,
+ const unsigned char *tweak32
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Tweak a secret key by multiplying it by a tweak.
+ *
+ * Returns: 0 if the arguments are invalid. 1 otherwise.
+ * Args: ctx: pointer to a context object.
+ * In/Out: seckey: pointer to a 32-byte secret key. If the secret key is
+ * invalid according to secp256k1_ec_seckey_verify, this
+ * function returns 0. seckey will be set to some unspecified
+ * value if this function returns 0.
+ * In: tweak32: pointer to a 32-byte tweak. If the tweak is invalid according to
+ * secp256k1_ec_seckey_verify, this function returns 0. For
+ * uniformly random 32-byte arrays the chance of being invalid
+ * is negligible (around 1 in 2^128).
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_seckey_tweak_mul(
+ const secp256k1_context *ctx,
+ unsigned char *seckey,
+ const unsigned char *tweak32
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Same as secp256k1_ec_seckey_tweak_mul, but DEPRECATED. Will be removed in
+ * future versions. */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_privkey_tweak_mul(
+ const secp256k1_context *ctx,
+ unsigned char *seckey,
+ const unsigned char *tweak32
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3)
+ SECP256K1_DEPRECATED("Use secp256k1_ec_seckey_tweak_mul instead");
+
+/** Tweak a public key by multiplying it by a tweak value.
+ *
+ * Returns: 0 if the arguments are invalid. 1 otherwise.
+ * Args: ctx: pointer to a context object.
+ * In/Out: pubkey: pointer to a public key object. pubkey will be set to an
+ * invalid value if this function returns 0.
+ * In: tweak32: pointer to a 32-byte tweak. If the tweak is invalid according to
+ * secp256k1_ec_seckey_verify, this function returns 0. For
+ * uniformly random 32-byte arrays the chance of being invalid
+ * is negligible (around 1 in 2^128).
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_tweak_mul(
+ const secp256k1_context *ctx,
+ secp256k1_pubkey *pubkey,
+ const unsigned char *tweak32
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Randomizes the context to provide enhanced protection against side-channel leakage.
+ *
+ * Returns: 1: randomization successful
+ * 0: error
+ * Args: ctx: pointer to a context object (not secp256k1_context_static).
+ * In: seed32: pointer to a 32-byte random seed (NULL resets to initial state).
+ *
+ * While secp256k1 code is written and tested to be constant-time no matter what
+ * secret values are, it is possible that a compiler may output code which is not,
+ * and also that the CPU may not emit the same radio frequencies or draw the same
+ * amount of power for all values. Randomization of the context shields against
+ * side-channel observations which aim to exploit secret-dependent behaviour in
+ * certain computations which involve secret keys.
+ *
+ * It is highly recommended to call this function on contexts returned from
+ * secp256k1_context_create or secp256k1_context_clone (or from the corresponding
+ * functions in secp256k1_preallocated.h) before using these contexts to call API
+ * functions that perform computations involving secret keys, e.g., signing and
+ * public key generation. It is possible to call this function more than once on
+ * the same context, and doing so before every few computations involving secret
+ * keys is recommended as a defense-in-depth measure. Randomization of the static
+ * context secp256k1_context_static is not supported.
+ *
+ * Currently, the random seed is mainly used for blinding multiplications of a
+ * secret scalar with the elliptic curve base point. Multiplications of this
+ * kind are performed by exactly those API functions which are documented to
+ * require a context that is not secp256k1_context_static. As a rule of thumb,
+ * these are all functions which take a secret key (or a keypair) as an input.
+ * A notable exception to that rule is the ECDH module, which relies on a different
+ * kind of elliptic curve point multiplication and thus does not benefit from
+ * enhanced protection against side-channel leakage currently.
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_context_randomize(
+ secp256k1_context *ctx,
+ const unsigned char *seed32
+) SECP256K1_ARG_NONNULL(1);
+
+/** Add a number of public keys together.
+ *
+ * Returns: 1: the sum of the public keys is valid.
+ * 0: the sum of the public keys is not valid.
+ * Args: ctx: pointer to a context object.
+ * Out: out: pointer to a public key object for placing the resulting public key.
+ * In: ins: pointer to array of pointers to public keys.
+ * n: the number of public keys to add together (must be at least 1).
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ec_pubkey_combine(
+ const secp256k1_context *ctx,
+ secp256k1_pubkey *out,
+ const secp256k1_pubkey * const *ins,
+ size_t n
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+/** Compute a tagged hash as defined in BIP-340.
+ *
+ * This is useful for creating a message hash and achieving domain separation
+ * through an application-specific tag. This function returns
+ * SHA256(SHA256(tag)||SHA256(tag)||msg). Therefore, tagged hash
+ * implementations optimized for a specific tag can precompute the SHA256 state
+ * after hashing the tag hashes.
+ *
+ * Returns: 1 always.
+ * Args: ctx: pointer to a context object
+ * Out: hash32: pointer to a 32-byte array to store the resulting hash
+ * In: tag: pointer to an array containing the tag
+ * taglen: length of the tag array
+ * msg: pointer to an array containing the message
+ * msglen: length of the message array
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_tagged_sha256(
+ const secp256k1_context *ctx,
+ unsigned char *hash32,
+ const unsigned char *tag,
+ size_t taglen,
+ const unsigned char *msg,
+ size_t msglen
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(5);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* SECP256K1_H */
diff --git a/include/secp256k1_ecdh.h b/include/secp256k1_ecdh.h
new file mode 100644
index 0000000..4d9da34
--- /dev/null
+++ b/include/secp256k1_ecdh.h
@@ -0,0 +1,63 @@
+#ifndef SECP256K1_ECDH_H
+#define SECP256K1_ECDH_H
+
+#include "secp256k1.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+/** A pointer to a function that hashes an EC point to obtain an ECDH secret
+ *
+ * Returns: 1 if the point was successfully hashed.
+ * 0 will cause secp256k1_ecdh to fail and return 0.
+ * Other return values are not allowed, and the behaviour of
+ * secp256k1_ecdh is undefined for other return values.
+ * Out: output: pointer to an array to be filled by the function
+ * In: x32: pointer to a 32-byte x coordinate
+ * y32: pointer to a 32-byte y coordinate
+ * data: arbitrary data pointer that is passed through
+ */
+typedef int (*secp256k1_ecdh_hash_function)(
+ unsigned char *output,
+ const unsigned char *x32,
+ const unsigned char *y32,
+ void *data
+);
+
+/** An implementation of SHA256 hash function that applies to compressed public key.
+ * Populates the output parameter with 32 bytes. */
+SECP256K1_API const secp256k1_ecdh_hash_function secp256k1_ecdh_hash_function_sha256;
+
+/** A default ECDH hash function (currently equal to secp256k1_ecdh_hash_function_sha256).
+ * Populates the output parameter with 32 bytes. */
+SECP256K1_API const secp256k1_ecdh_hash_function secp256k1_ecdh_hash_function_default;
+
+/** Compute an EC Diffie-Hellman secret in constant time
+ *
+ * Returns: 1: exponentiation was successful
+ * 0: scalar was invalid (zero or overflow) or hashfp returned 0
+ * Args: ctx: pointer to a context object.
+ * Out: output: pointer to an array to be filled by hashfp.
+ * In: pubkey: pointer to a secp256k1_pubkey containing an initialized public key.
+ * seckey: a 32-byte scalar with which to multiply the point.
+ * hashfp: pointer to a hash function. If NULL,
+ * secp256k1_ecdh_hash_function_sha256 is used
+ * (in which case, 32 bytes will be written to output).
+ * data: arbitrary data pointer that is passed through to hashfp
+ * (can be NULL for secp256k1_ecdh_hash_function_sha256).
+ */
+SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_ecdh(
+ const secp256k1_context *ctx,
+ unsigned char *output,
+ const secp256k1_pubkey *pubkey,
+ const unsigned char *seckey,
+ secp256k1_ecdh_hash_function hashfp,
+ void *data
+) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* SECP256K1_ECDH_H */
diff --git a/include/secp256k1_extrakeys.h b/include/secp256k1_extrakeys.h
new file mode 100644
index 0000000..4cc6d4f
--- /dev/null
+++ b/include/secp256k1_extrakeys.h
@@ -0,0 +1,247 @@
+#ifndef SECP256K1_EXTRAKEYS_H
+#define SECP256K1_EXTRAKEYS_H
+
+#include "secp256k1.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ /** Opaque data structure that holds a parsed and valid "x-only" public key.
+ * An x-only pubkey encodes a point whose Y coordinate is even. It is
+ * serialized using only its X coordinate (32 bytes). See BIP-340 for more
+ * information about x-only pubkeys.
+ *
+ * The exact representation of data inside is implementation defined and not
+ * guaranteed to be portable between different platforms or versions. It is
+ * however guaranteed to be 64 bytes in size, and can be safely copied/moved.
+ * If you need to convert to a format suitable for storage, transmission, use
+ * use secp256k1_xonly_pubkey_serialize and secp256k1_xonly_pubkey_parse. To
+ * compare keys, use secp256k1_xonly_pubkey_cmp.
+ */
+ typedef struct {
+ unsigned char data[64];
+ } secp256k1_xonly_pubkey;
+
+ /** Opaque data structure that holds a keypair consisting of a secret and a
+ * public key.
+ *
+ * The exact representation of data inside is implementation defined and not
+ * guaranteed to be portable between different platforms or versions. It is
+ * however guaranteed to be 96 bytes in size, and can be safely copied/moved.
+ */
+ typedef struct {
+ unsigned char data[96];
+ } secp256k1_keypair;
+
+ /** Parse a 32-byte sequence into a xonly_pubkey object.
+ *
+ * Returns: 1 if the public key was fully valid.
+ * 0 if the public key could not be parsed or is invalid.
+ *
+ * Args: ctx: pointer to a context object.
+ * Out: pubkey: pointer to a pubkey object. If 1 is returned, it is set to a
+ * parsed version of input. If not, it's set to an invalid value.
+ * In: input32: pointer to a serialized xonly_pubkey.
+ */
+ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_xonly_pubkey_parse(
+ const secp256k1_context* ctx,
+ secp256k1_xonly_pubkey* pubkey,
+ const unsigned char* input32
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+ /** Serialize an xonly_pubkey object into a 32-byte sequence.
+ *
+ * Returns: 1 always.
+ *
+ * Args: ctx: pointer to a context object.
+ * Out: output32: pointer to a 32-byte array to place the serialized key in.
+ * In: pubkey: pointer to a secp256k1_xonly_pubkey containing an initialized public key.
+ */
+ SECP256K1_API int secp256k1_xonly_pubkey_serialize(
+ const secp256k1_context* ctx,
+ unsigned char* output32,
+ const secp256k1_xonly_pubkey* pubkey
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+ /** Compare two x-only public keys using lexicographic order
+ *
+ * Returns: <0 if the first public key is less than the second
+ * >0 if the first public key is greater than the second
+ * 0 if the two public keys are equal
+ * Args: ctx: pointer to a context object.
+ * In: pubkey1: first public key to compare
+ * pubkey2: second public key to compare
+ */
+ SECP256K1_API int secp256k1_xonly_pubkey_cmp(
+ const secp256k1_context* ctx,
+ const secp256k1_xonly_pubkey* pk1,
+ const secp256k1_xonly_pubkey* pk2
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+ /** Converts a secp256k1_pubkey into a secp256k1_xonly_pubkey.
+ *
+ * Returns: 1 always.
+ *
+ * Args: ctx: pointer to a context object.
+ * Out: xonly_pubkey: pointer to an x-only public key object for placing the converted public key.
+ * pk_parity: Ignored if NULL. Otherwise, pointer to an integer that
+ * will be set to 1 if the point encoded by xonly_pubkey is
+ * the negation of the pubkey and set to 0 otherwise.
+ * In: pubkey: pointer to a public key that is converted.
+ */
+ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_xonly_pubkey_from_pubkey(
+ const secp256k1_context* ctx,
+ secp256k1_xonly_pubkey* xonly_pubkey,
+ int* pk_parity,
+ const secp256k1_pubkey* pubkey
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4);
+
+ /** Tweak an x-only public key by adding the generator multiplied with tweak32
+ * to it.
+ *
+ * Note that the resulting point can not in general be represented by an x-only
+ * pubkey because it may have an odd Y coordinate. Instead, the output_pubkey
+ * is a normal secp256k1_pubkey.
+ *
+ * Returns: 0 if the arguments are invalid or the resulting public key would be
+ * invalid (only when the tweak is the negation of the corresponding
+ * secret key). 1 otherwise.
+ *
+ * Args: ctx: pointer to a context object.
+ * Out: output_pubkey: pointer to a public key to store the result. Will be set
+ * to an invalid value if this function returns 0.
+ * In: internal_pubkey: pointer to an x-only pubkey to apply the tweak to.
+ * tweak32: pointer to a 32-byte tweak, which must be valid
+ * according to secp256k1_ec_seckey_verify or 32 zero
+ * bytes. For uniformly random 32-byte tweaks, the chance of
+ * being invalid is negligible (around 1 in 2^128).
+ */
+ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_xonly_pubkey_tweak_add(
+ const secp256k1_context* ctx,
+ secp256k1_pubkey* output_pubkey,
+ const secp256k1_xonly_pubkey* internal_pubkey,
+ const unsigned char* tweak32
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
+
+ /** Checks that a tweaked pubkey is the result of calling
+ * secp256k1_xonly_pubkey_tweak_add with internal_pubkey and tweak32.
+ *
+ * The tweaked pubkey is represented by its 32-byte x-only serialization and
+ * its pk_parity, which can both be obtained by converting the result of
+ * tweak_add to a secp256k1_xonly_pubkey.
+ *
+ * Note that this alone does _not_ verify that the tweaked pubkey is a
+ * commitment. If the tweak is not chosen in a specific way, the tweaked pubkey
+ * can easily be the result of a different internal_pubkey and tweak.
+ *
+ * Returns: 0 if the arguments are invalid or the tweaked pubkey is not the
+ * result of tweaking the internal_pubkey with tweak32. 1 otherwise.
+ * Args: ctx: pointer to a context object.
+ * In: tweaked_pubkey32: pointer to a serialized xonly_pubkey.
+ * tweaked_pk_parity: the parity of the tweaked pubkey (whose serialization
+ * is passed in as tweaked_pubkey32). This must match the
+ * pk_parity value that is returned when calling
+ * secp256k1_xonly_pubkey with the tweaked pubkey, or
+ * this function will fail.
+ * internal_pubkey: pointer to an x-only public key object to apply the tweak to.
+ * tweak32: pointer to a 32-byte tweak.
+ */
+ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_xonly_pubkey_tweak_add_check(
+ const secp256k1_context* ctx,
+ const unsigned char* tweaked_pubkey32,
+ int tweaked_pk_parity,
+ const secp256k1_xonly_pubkey* internal_pubkey,
+ const unsigned char* tweak32
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4) SECP256K1_ARG_NONNULL(5);
+
+ /** Compute the keypair for a secret key.
+ *
+ * Returns: 1: secret was valid, keypair is ready to use
+ * 0: secret was invalid, try again with a different secret
+ * Args: ctx: pointer to a context object (not secp256k1_context_static).
+ * Out: keypair: pointer to the created keypair.
+ * In: seckey: pointer to a 32-byte secret key.
+ */
+ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_keypair_create(
+ const secp256k1_context* ctx,
+ secp256k1_keypair* keypair,
+ const unsigned char* seckey
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+ /** Get the secret key from a keypair.
+ *
+ * Returns: 1 always.
+ * Args: ctx: pointer to a context object.
+ * Out: seckey: pointer to a 32-byte buffer for the secret key.
+ * In: keypair: pointer to a keypair.
+ */
+ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_keypair_sec(
+ const secp256k1_context* ctx,
+ unsigned char* seckey,
+ const secp256k1_keypair* keypair
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+ /** Get the public key from a keypair.
+ *
+ * Returns: 1 always.
+ * Args: ctx: pointer to a context object.
+ * Out: pubkey: pointer to a pubkey object, set to the keypair public key.
+ * In: keypair: pointer to a keypair.
+ */
+ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_keypair_pub(
+ const secp256k1_context* ctx,
+ secp256k1_pubkey* pubkey,
+ const secp256k1_keypair* keypair
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+ /** Get the x-only public key from a keypair.
+ *
+ * This is the same as calling secp256k1_keypair_pub and then
+ * secp256k1_xonly_pubkey_from_pubkey.
+ *
+ * Returns: 1 always.
+ * Args: ctx: pointer to a context object.
+ * Out: pubkey: pointer to an xonly_pubkey object, set to the keypair
+ * public key after converting it to an xonly_pubkey.
+ * pk_parity: Ignored if NULL. Otherwise, pointer to an integer that will be set to the
+ * pk_parity argument of secp256k1_xonly_pubkey_from_pubkey.
+ * In: keypair: pointer to a keypair.
+ */
+ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_keypair_xonly_pub(
+ const secp256k1_context* ctx,
+ secp256k1_xonly_pubkey* pubkey,
+ int* pk_parity,
+ const secp256k1_keypair* keypair
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(4);
+
+ /** Tweak a keypair by adding tweak32 to the secret key and updating the public
+ * key accordingly.
+ *
+ * Calling this function and then secp256k1_keypair_pub results in the same
+ * public key as calling secp256k1_keypair_xonly_pub and then
+ * secp256k1_xonly_pubkey_tweak_add.
+ *
+ * Returns: 0 if the arguments are invalid or the resulting keypair would be
+ * invalid (only when the tweak is the negation of the keypair's
+ * secret key). 1 otherwise.
+ *
+ * Args: ctx: pointer to a context object.
+ * In/Out: keypair: pointer to a keypair to apply the tweak to. Will be set to
+ * an invalid value if this function returns 0.
+ * In: tweak32: pointer to a 32-byte tweak, which must be valid according to
+ * secp256k1_ec_seckey_verify or 32 zero bytes. For uniformly
+ * random 32-byte tweaks, the chance of being invalid is
+ * negligible (around 1 in 2^128).
+ */
+ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_keypair_xonly_tweak_add(
+ const secp256k1_context* ctx,
+ secp256k1_keypair* keypair,
+ const unsigned char* tweak32
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* SECP256K1_EXTRAKEYS_H */ \ No newline at end of file
diff --git a/include/secp256k1_schnorrsig.h b/include/secp256k1_schnorrsig.h
new file mode 100644
index 0000000..5c338f4
--- /dev/null
+++ b/include/secp256k1_schnorrsig.h
@@ -0,0 +1,190 @@
+#ifndef SECP256K1_SCHNORRSIG_H
+#define SECP256K1_SCHNORRSIG_H
+
+#include "secp256k1.h"
+#include "secp256k1_extrakeys.h"
+
+#ifdef __cplusplus
+extern "C" {
+#endif
+
+ /** This module implements a variant of Schnorr signatures compliant with
+ * Bitcoin Improvement Proposal 340 "Schnorr Signatures for secp256k1"
+ * (https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki).
+ */
+
+ /** A pointer to a function to deterministically generate a nonce.
+ *
+ * Same as secp256k1_nonce function with the exception of accepting an
+ * additional pubkey argument and not requiring an attempt argument. The pubkey
+ * argument can protect signature schemes with key-prefixed challenge hash
+ * inputs against reusing the nonce when signing with the wrong precomputed
+ * pubkey.
+ *
+ * Returns: 1 if a nonce was successfully generated. 0 will cause signing to
+ * return an error.
+ * Out: nonce32: pointer to a 32-byte array to be filled by the function
+ * In: msg: the message being verified. Is NULL if and only if msglen
+ * is 0.
+ * msglen: the length of the message
+ * key32: pointer to a 32-byte secret key (will not be NULL)
+ * xonly_pk32: the 32-byte serialized xonly pubkey corresponding to key32
+ * (will not be NULL)
+ * algo: pointer to an array describing the signature
+ * algorithm (will not be NULL)
+ * algolen: the length of the algo array
+ * data: arbitrary data pointer that is passed through
+ *
+ * Except for test cases, this function should compute some cryptographic hash of
+ * the message, the key, the pubkey, the algorithm description, and data.
+ */
+ typedef int (*secp256k1_nonce_function_hardened)(
+ unsigned char* nonce32,
+ const unsigned char* msg,
+ size_t msglen,
+ const unsigned char* key32,
+ const unsigned char* xonly_pk32,
+ const unsigned char* algo,
+ size_t algolen,
+ void* data
+ );
+
+ /** An implementation of the nonce generation function as defined in Bitcoin
+ * Improvement Proposal 340 "Schnorr Signatures for secp256k1"
+ * (https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki).
+ *
+ * If a data pointer is passed, it is assumed to be a pointer to 32 bytes of
+ * auxiliary random data as defined in BIP-340. If the data pointer is NULL,
+ * the nonce derivation procedure follows BIP-340 by setting the auxiliary
+ * random data to zero. The algo argument must be non-NULL, otherwise the
+ * function will fail and return 0. The hash will be tagged with algo.
+ * Therefore, to create BIP-340 compliant signatures, algo must be set to
+ * "BIP0340/nonce" and algolen to 13.
+ */
+ SECP256K1_API const secp256k1_nonce_function_hardened secp256k1_nonce_function_bip340;
+
+ /** Data structure that contains additional arguments for schnorrsig_sign_custom.
+ *
+ * A schnorrsig_extraparams structure object can be initialized correctly by
+ * setting it to SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT.
+ *
+ * Members:
+ * magic: set to SECP256K1_SCHNORRSIG_EXTRAPARAMS_MAGIC at initialization
+ * and has no other function than making sure the object is
+ * initialized.
+ * noncefp: pointer to a nonce generation function. If NULL,
+ * secp256k1_nonce_function_bip340 is used
+ * ndata: pointer to arbitrary data used by the nonce generation function
+ * (can be NULL). If it is non-NULL and
+ * secp256k1_nonce_function_bip340 is used, then ndata must be a
+ * pointer to 32-byte auxiliary randomness as per BIP-340.
+ */
+ typedef struct {
+ unsigned char magic[4];
+ secp256k1_nonce_function_hardened noncefp;
+ void* ndata;
+ } secp256k1_schnorrsig_extraparams;
+
+#define SECP256K1_SCHNORRSIG_EXTRAPARAMS_MAGIC { 0xda, 0x6f, 0xb3, 0x8c }
+#define SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT {\
+ SECP256K1_SCHNORRSIG_EXTRAPARAMS_MAGIC,\
+ NULL,\
+ NULL\
+}
+
+ /** Create a Schnorr signature.
+ *
+ * Does _not_ strictly follow BIP-340 because it does not verify the resulting
+ * signature. Instead, you can manually use secp256k1_schnorrsig_verify and
+ * abort if it fails.
+ *
+ * This function only signs 32-byte messages. If you have messages of a
+ * different size (or the same size but without a context-specific tag
+ * prefix), it is recommended to create a 32-byte message hash with
+ * secp256k1_tagged_sha256 and then sign the hash. Tagged hashing allows
+ * providing an context-specific tag for domain separation. This prevents
+ * signatures from being valid in multiple contexts by accident.
+ *
+ * Returns 1 on success, 0 on failure.
+ * Args: ctx: pointer to a context object (not secp256k1_context_static).
+ * Out: sig64: pointer to a 64-byte array to store the serialized signature.
+ * In: msg32: the 32-byte message being signed.
+ * keypair: pointer to an initialized keypair.
+ * aux_rand32: 32 bytes of fresh randomness. While recommended to provide
+ * this, it is only supplemental to security and can be NULL. A
+ * NULL argument is treated the same as an all-zero one. See
+ * BIP-340 "Default Signing" for a full explanation of this
+ * argument and for guidance if randomness is expensive.
+ */
+ SECP256K1_API int secp256k1_schnorrsig_sign32(
+ const secp256k1_context* ctx,
+ unsigned char* sig64,
+ const unsigned char* msg32,
+ const secp256k1_keypair* keypair,
+ const unsigned char* aux_rand32
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4);
+
+ /** Same as secp256k1_schnorrsig_sign32, but DEPRECATED. Will be removed in
+ * future versions. */
+ SECP256K1_API int secp256k1_schnorrsig_sign(
+ const secp256k1_context* ctx,
+ unsigned char* sig64,
+ const unsigned char* msg32,
+ const secp256k1_keypair* keypair,
+ const unsigned char* aux_rand32
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(3) SECP256K1_ARG_NONNULL(4)
+ SECP256K1_DEPRECATED("Use secp256k1_schnorrsig_sign32 instead");
+
+ /** Create a Schnorr signature with a more flexible API.
+ *
+ * Same arguments as secp256k1_schnorrsig_sign except that it allows signing
+ * variable length messages and accepts a pointer to an extraparams object that
+ * allows customizing signing by passing additional arguments.
+ *
+ * Equivalent to secp256k1_schnorrsig_sign32(..., aux_rand32) if msglen is 32
+ * and extraparams is initialized as follows:
+ * ```
+ * secp256k1_schnorrsig_extraparams extraparams = SECP256K1_SCHNORRSIG_EXTRAPARAMS_INIT;
+ * extraparams.ndata = (unsigned char*)aux_rand32;
+ * ```
+ *
+ * Returns 1 on success, 0 on failure.
+ * Args: ctx: pointer to a context object (not secp256k1_context_static).
+ * Out: sig64: pointer to a 64-byte array to store the serialized signature.
+ * In: msg: the message being signed. Can only be NULL if msglen is 0.
+ * msglen: length of the message.
+ * keypair: pointer to an initialized keypair.
+ * extraparams: pointer to an extraparams object (can be NULL).
+ */
+ SECP256K1_API int secp256k1_schnorrsig_sign_custom(
+ const secp256k1_context* ctx,
+ unsigned char* sig64,
+ const unsigned char* msg,
+ size_t msglen,
+ const secp256k1_keypair* keypair,
+ secp256k1_schnorrsig_extraparams* extraparams
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(5);
+
+ /** Verify a Schnorr signature.
+ *
+ * Returns: 1: correct signature
+ * 0: incorrect signature
+ * Args: ctx: pointer to a context object.
+ * In: sig64: pointer to the 64-byte signature to verify.
+ * msg: the message being verified. Can only be NULL if msglen is 0.
+ * msglen: length of the message
+ * pubkey: pointer to an x-only public key to verify with
+ */
+ SECP256K1_API SECP256K1_WARN_UNUSED_RESULT int secp256k1_schnorrsig_verify(
+ const secp256k1_context* ctx,
+ const unsigned char* sig64,
+ const unsigned char* msg,
+ size_t msglen,
+ const secp256k1_xonly_pubkey* pubkey
+ ) SECP256K1_ARG_NONNULL(1) SECP256K1_ARG_NONNULL(2) SECP256K1_ARG_NONNULL(5);
+
+#ifdef __cplusplus
+}
+#endif
+
+#endif /* SECP256K1_SCHNORRSIG_H */
diff --git a/noscrypt.build.sln b/noscrypt.build.sln
new file mode 100644
index 0000000..58ea566
--- /dev/null
+++ b/noscrypt.build.sln
@@ -0,0 +1,14 @@
+
+Microsoft Visual Studio Solution File, Format Version 12.00
+# Visual Studio Version 17
+VisualStudioVersion = 17.0.31903.59
+MinimumVisualStudioVersion = 10.0.40219.1
+Global
+ GlobalSection(SolutionConfigurationPlatforms) = preSolution
+ Debug|Any CPU = Debug|Any CPU
+ Release|Any CPU = Release|Any CPU
+ EndGlobalSection
+ GlobalSection(SolutionProperties) = preSolution
+ HideSolutionNode = FALSE
+ EndGlobalSection
+EndGlobal
diff --git a/package.json b/package.json
new file mode 100644
index 0000000..87bc50e
--- /dev/null
+++ b/package.json
@@ -0,0 +1,10 @@
+{
+ "name": "noscrypt",
+ "version": "0.1.0",
+ "output_dir": "bin",
+ "author": "Vaughn Nugent",
+ "description": "A compact, C90 cross-platform, cryptography library built specifically for nostr",
+ "copyright": "Copyright \u00A9 2024 Vaughn Nugent",
+ "company": "Vaughn Nugent",
+ "repository": "https://github.com/VnUgE/noscrypt"
+} \ No newline at end of file
diff --git a/src/noscrypt.c b/src/noscrypt.c
new file mode 100644
index 0000000..6ef273f
--- /dev/null
+++ b/src/noscrypt.c
@@ -0,0 +1,865 @@
+/*
+* Copyright (c) 2024 Vaughn Nugent
+*
+* Library: noscrypt
+* Package: noscrypt
+* File: noscrypt.c
+*
+* noscrypt is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published
+* by the Free Software Foundation, either version 2 of the License,
+* or (at your option) any later version.
+*
+* noscrypt is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with noscrypt. If not, see http://www.gnu.org/licenses/.
+*/
+
+#include "noscrypt.h"
+
+#include <secp256k1_ecdh.h>
+#include <secp256k1_schnorrsig.h>
+
+//Setup mbedtls
+#include <mbedtls/platform_util.h>
+#include <mbedtls/md.h>
+#include <mbedtls/hkdf.h>
+#include <mbedtls/chacha20.h>
+#include <mbedtls/sha256.h>
+
+#define CHACHA_NONCE_SIZE 12 //Size of 12 is set by the cipher spec
+#define CHACHA_KEY_SIZE 32
+#define HMAC_KEY_SIZE 32
+
+/*
+* Local macro for secure zero buffer fill
+*/
+#define ZERO_FILL(x, size) mbedtls_platform_zeroize(x, size)
+
+//Include string for memmove
+#include <string.h>
+#define MEMMOV(dst, src, size) memmove(dst, src, size)
+
+struct nc_expand_keys {
+ uint8_t chacha_key[CHACHA_KEY_SIZE];
+ uint8_t chacha_nonce[CHACHA_NONCE_SIZE];
+ uint8_t hamc_key[HMAC_KEY_SIZE];
+};
+
+struct shared_secret {
+ uint8_t value[NC_SHARED_SEC_SIZE];
+};
+
+struct conversation_key {
+ uint8_t value[NC_CONV_KEY_SIZE];
+};
+
+struct message_key {
+ uint8_t value[NC_MESSAGE_KEY_SIZE];
+};
+
+/*
+* Internal helper functions to do common structure conversions
+*/
+
+static inline int _convertToXonly(const NCContext* ctx, const NCPublicKey* compressedPubKey, secp256k1_xonly_pubkey* xonly)
+{
+ DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
+ DEBUG_ASSERT2(compressedPubKey != NULL, "Expected a valid public 32byte key structure")
+ DEBUG_ASSERT2(xonly != NULL, "Expected valid X-only secp256k1 public key structure ")
+
+ //Parse the public key into the x-only structure
+ return secp256k1_xonly_pubkey_parse(ctx->secpCtx, xonly, compressedPubKey->key);
+}
+
+static int _convertToPubKey(const NCContext* ctx, const NCPublicKey* compressedPubKey, secp256k1_pubkey* pubKey)
+{
+ int result;
+ uint8_t compressed[NC_PUBKEY_SIZE + 1];
+
+ DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
+ DEBUG_ASSERT2(compressedPubKey != NULL, "Expected a valid public 32byte key structure")
+ DEBUG_ASSERT2(pubKey != NULL, "Expected valid secp256k1 public key structure")
+
+ //Set the first byte to 0x02 to indicate a compressed public key
+ compressed[0] = BIP340_PUBKEY_HEADER_BYTE;
+
+ //Copy the compressed public key data into a new buffer (offset by 1 to store the header byte)
+ MEMMOV((compressed + 1), compressedPubKey->key, NC_PUBKEY_SIZE);
+
+ result = secp256k1_ec_pubkey_parse(ctx->secpCtx, pubKey, compressed, sizeof(compressed));
+
+ //zero everything
+ ZERO_FILL(compressed, sizeof(compressed));
+
+ return result;
+}
+
+static inline int _convertFromXonly(const NCContext* ctx, const secp256k1_xonly_pubkey* xonly, NCPublicKey* compressedPubKey)
+{
+ DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
+ DEBUG_ASSERT2(xonly != NULL, "Expected valid X-only secp256k1 public key structure.")
+ DEBUG_ASSERT2(compressedPubKey != NULL, "Expected a valid public 32byte pubkey structure")
+
+ return secp256k1_xonly_pubkey_serialize(ctx->secpCtx, compressedPubKey->key, xonly);
+}
+
+/*
+* IMPL NOTES:
+* This callback function will be invoked by the ecdh function to hash the shared point.
+*
+* For nostr, this operation is defined in the new NIP-44 spec here:
+* https://github.com/nostr-protocol/nips/blob/master/44.md#encryption
+*
+* The x coordinate of the shared point is copied directly into the output buffer. No hashing is
+* performed here. The y coordinate is not used, and for this implementation, there is no data
+* pointer.
+*/
+static int _edhHashFuncInternal(
+ unsigned char* output,
+ const uint8_t* x32,
+ const uint8_t* y32,
+ void* data
+)
+{
+ ((void)y32); //unused for nostr
+ ((void)data);
+
+ DEBUG_ASSERT2(output != NULL, "Expected valid output buffer")
+ DEBUG_ASSERT2(x32 != NULL, "Expected a valid public 32byte x-coodinate buffer")
+
+ //Copy the x coordinate of the shared point into the output buffer
+ MEMMOV(output, x32, 32);
+
+ return 32; //Return the number of bytes written to the output buffer
+}
+
+static NCResult _computeSharedSecret(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const NCPublicKey* otherPk,
+ struct shared_secret* sharedPoint
+)
+{
+ int result;
+ secp256k1_pubkey pubKey;
+
+ DEBUG_ASSERT(ctx != NULL)
+ DEBUG_ASSERT(sk != NULL)
+ DEBUG_ASSERT(otherPk != NULL)
+ DEBUG_ASSERT(sharedPoint != NULL)
+
+ //Recover pubkey from compressed public key data
+ if (_convertToPubKey(ctx, otherPk, &pubKey) != 1)
+ {
+ return E_INVALID_ARG;
+ }
+
+ /*
+ * Compute the shared point using the ecdh function.
+ *
+ * The above callback is invoked to "compute" the hash (it
+ * copies the x coord) and it does not use the data pointer
+ * so it is set to NULL.
+ */
+ result = secp256k1_ecdh(
+ ctx->secpCtx,
+ (uint8_t*)sharedPoint,
+ &pubKey,
+ sk->key,
+ &_edhHashFuncInternal,
+ NULL
+ );
+
+ //Clean up sensitive data
+ ZERO_FILL(&pubKey, sizeof(secp256k1_pubkey));
+
+ return (NCResult)result;
+}
+
+static inline const mbedtls_md_info_t* _getSha256MdInfo(void)
+{
+ const mbedtls_md_info_t* info;
+ //Get sha256 md info for hdkf operations
+ info = mbedtls_md_info_from_type(MBEDTLS_MD_SHA256);
+ DEBUG_ASSERT2(info != NULL, "Expected SHA256 md info struct to be valid")
+ return info;
+}
+
+
+static inline NCResult _computeConversationKey(
+ const NCContext* ctx,
+ const mbedtls_md_info_t* mdInfo,
+ const struct shared_secret* sharedSecret,
+ struct conversation_key* ck
+)
+{
+ //Validate internal args
+ DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
+ DEBUG_ASSERT2(sharedSecret != NULL, "Expected a valid shared-point")
+ DEBUG_ASSERT2(mdInfo != NULL, "Expected valid md context")
+ DEBUG_ASSERT2(ck != NULL, "Expected a valid conversation key")
+
+ //Derive the encryption key (returns 0 on success so it can be cast to an NCResult)
+ return (NCResult)mbedtls_hkdf_extract(
+ mdInfo,
+ Nip44ConstantSalt,
+ sizeof(Nip44ConstantSalt),
+ (uint8_t*)sharedSecret, //Shared secret is the input key
+ NC_SHARED_SEC_SIZE,
+ (uint8_t*)ck //Output produces a conversation key
+ );
+}
+
+
+/*
+* Explode the hkdf into the chacha key, chacha nonce, and hmac key.
+*/
+static inline void _expandKeysFromHkdf(const struct message_key* hkdf, struct nc_expand_keys* keys)
+{
+ uint8_t* hkdfBytes;
+
+ DEBUG_ASSERT2(hkdf != NULL, "Expected valid hkdf")
+
+ hkdfBytes = (uint8_t*)hkdf;
+
+ //Copy segments of the hkdf into the keys struct
+ MEMMOV(
+ keys->chacha_key,
+ hkdfBytes,
+ CHACHA_KEY_SIZE
+ );
+
+ MEMMOV(
+ keys->chacha_nonce,
+ (hkdfBytes + CHACHA_KEY_SIZE),
+ CHACHA_NONCE_SIZE
+ );
+
+ MEMMOV(
+ keys->hamc_key,
+ (hkdfBytes + CHACHA_KEY_SIZE + CHACHA_NONCE_SIZE),
+ HMAC_KEY_SIZE
+ );
+}
+
+static int _chachaEncipher(const struct nc_expand_keys* keys, NCCryptoData* args)
+{
+ int result;
+ mbedtls_chacha20_context chachaCtx;
+
+ DEBUG_ASSERT2(keys != NULL, "Expected valid keys")
+ DEBUG_ASSERT2(args != NULL, "Expected valid encryption args")
+ DEBUG_ASSERT2(sizeof(keys->chacha_nonce) == 12, "Chacha nonce must be 12 exactly bytes in length")
+
+ //Init the chacha context
+ mbedtls_chacha20_init(&chachaCtx);
+
+ //Set the key and nonce
+ result = mbedtls_chacha20_setkey(&chachaCtx, keys->chacha_key);
+ DEBUG_ASSERT2(result == 0, "Expected chacha setkey to return 0")
+
+ result = mbedtls_chacha20_starts(&chachaCtx, keys->chacha_nonce, 0);
+ DEBUG_ASSERT2(result == 0, "Expected chacha starts to return 0")
+
+ //Encrypt the plaintext
+ result = mbedtls_chacha20_update(&chachaCtx, args->dataSize, args->inputData, args->outputData);
+ DEBUG_ASSERT2(result == 0, "Expected chacha update to return 0")
+
+ //Clean up the chacha context
+ mbedtls_chacha20_free(&chachaCtx);
+
+ return result;
+}
+
+static inline NCResult _getMessageKey(
+ const mbedtls_md_info_t* mdInfo,
+ const struct conversation_key* converstationKey,
+ const uint8_t* nonce,
+ size_t nonceSize,
+ struct message_key* messageKey
+)
+{
+ DEBUG_ASSERT2(mdInfo != NULL, "Expected valid md context")
+ DEBUG_ASSERT2(nonce != NULL, "Expected valid nonce buffer")
+ DEBUG_ASSERT2(converstationKey != NULL, "Expected valid conversation key")
+ DEBUG_ASSERT2(messageKey != NULL, "Expected valid message key buffer")
+
+ //Another HKDF to derive the message key with nonce
+ return (NCResult)mbedtls_hkdf_expand(
+ mdInfo,
+ (uint8_t*)converstationKey, //Conversation key is the input key
+ NC_CONV_KEY_SIZE,
+ nonce,
+ nonceSize,
+ (uint8_t*)messageKey, //Output produces a message key
+ NC_MESSAGE_KEY_SIZE
+ );
+}
+
+static inline NCResult _encryptEx(
+ const NCContext* ctx,
+ const mbedtls_md_info_t* mdINfo,
+ const struct conversation_key* ck,
+ NCCryptoData* args
+)
+{
+ NCResult result;
+ struct message_key messageKey;
+ struct nc_expand_keys cipherKeys;
+
+ DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
+ DEBUG_ASSERT2(ck != NULL, "Expected valid conversation key")
+ DEBUG_ASSERT2(args != NULL, "Expected valid encryption args")
+
+ //Failure, bail out
+ if ((result = _getMessageKey(mdINfo, ck, args->nonce, NC_ENCRYPTION_NONCE_SIZE, &messageKey)) != NC_SUCCESS)
+ {
+ goto Cleanup;
+ }
+
+ //Expand the keys from the hkdf so we can use them in the cipher
+ _expandKeysFromHkdf(&messageKey, &cipherKeys);
+
+ //CHACHA20
+ result = _chachaEncipher(&cipherKeys, args);
+
+Cleanup:
+ //Clean up sensitive data
+ ZERO_FILL(&messageKey, sizeof(messageKey));
+
+ return result;
+}
+
+static inline NCResult _decryptEx(
+ const NCContext* ctx,
+ const mbedtls_md_info_t* mdInfo,
+ const struct conversation_key* ck,
+ NCCryptoData* args
+)
+{
+ NCResult result;
+ struct message_key messageKey;
+ struct nc_expand_keys cipherKeys;
+
+ //Assume message key buffer is the same size as the expanded key struct
+ DEBUG_ASSERT2(sizeof(messageKey) == sizeof(cipherKeys), "Message key size and expanded key sizes do not match")
+
+ DEBUG_ASSERT2(ctx != NULL, "Expected valid context")
+ DEBUG_ASSERT2(ck != NULL, "Expected valid conversation key")
+ DEBUG_ASSERT2(args != NULL, "Expected valid encryption args")
+ DEBUG_ASSERT2(mdInfo != NULL, "Expected valid md info struct")
+
+ //Failure to get message keys, bail out
+ if ((result = _getMessageKey(mdInfo, ck, args->nonce, NC_ENCRYPTION_NONCE_SIZE, &messageKey)) != NC_SUCCESS)
+ {
+ goto Cleanup;
+ }
+
+ //Expand the keys from the hkdf so we can use them in the cipher
+ _expandKeysFromHkdf(&messageKey, &cipherKeys);
+
+ //CHACHA20
+ result = _chachaEncipher(&cipherKeys, args);
+
+Cleanup:
+ //Clean up sensitive data
+ ZERO_FILL(&messageKey, sizeof(messageKey));
+
+ return result;
+}
+
+/*
+* Compute the sha256 digest of the data. This function should always return 0
+* on success.
+*/
+static inline int _computeSha256Digest(const uint8_t* data, size_t length, uint8_t digest[32])
+{
+ int result;
+ mbedtls_sha256_context sha256;
+
+ DEBUG_ASSERT2(data != NULL, "Expected valid data buffer")
+ DEBUG_ASSERT2(digest != NULL, "Expected valid digest buffer")
+
+ //Init the sha256 context
+ mbedtls_sha256_init(&sha256);
+
+ //starting context should never fail
+ result = mbedtls_sha256_starts(&sha256, 0);
+ DEBUG_ASSERT2(result == 0, "Expected sha256 starts to return 0")
+
+ //may fail if the data is invalid
+ if ((result = mbedtls_sha256_update(&sha256, data, length)) != 0)
+ {
+ goto Cleanup;
+ }
+
+ //Finishing context should never fail
+ result = mbedtls_sha256_finish(&sha256, digest);
+
+Cleanup:
+ //Always free the context
+ mbedtls_sha256_free(&sha256);
+
+ return result;
+}
+
+/*
+* EXTERNAL API FUNCTIONS
+*/
+NC_EXPORT uint32_t NC_CC NCGetContextStructSize(void)
+{
+ return sizeof(NCContext);
+}
+
+NC_EXPORT NCResult NC_CC NCInitContext(
+ NCContext* ctx,
+ const uint8_t entropy[32]
+)
+{
+ CHECK_NULL_PTR(ctx)
+ CHECK_NULL_PTR(entropy)
+
+ ctx->secpCtx = secp256k1_context_create(SECP256K1_CONTEXT_NONE);
+
+ //Randomize once on init
+ return secp256k1_context_randomize(ctx->secpCtx, entropy) ? NC_SUCCESS : E_INVALID_ARG;
+}
+
+NC_EXPORT NCResult NC_CC NCReInitContext(
+ NCContext* ctx,
+ const uint8_t entropy[32]
+)
+{
+ CHECK_NULL_PTR(ctx)
+ CHECK_INVALID_ARG(ctx->secpCtx)
+ CHECK_INVALID_ARG(entropy)
+
+ //Only randomize again
+ return secp256k1_context_randomize(ctx->secpCtx, entropy) ? NC_SUCCESS : E_INVALID_ARG;
+}
+
+NC_EXPORT NCResult NC_CC NCDestroyContext(NCContext* ctx)
+{
+ CHECK_NULL_ARG(ctx, 0);
+ CHECK_INVALID_ARG(ctx->secpCtx);
+
+ //Destroy secp256k1 context
+ secp256k1_context_destroy(ctx->secpCtx);
+
+ //Wipe the context
+ ZERO_FILL(ctx, sizeof(NCContext));
+
+ return NC_SUCCESS;
+}
+
+//KEY Functions
+NC_EXPORT NCResult NC_CC NCGetPublicKey(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ NCPublicKey* pk
+)
+{
+ int result;
+ secp256k1_keypair keyPair;
+ secp256k1_xonly_pubkey xonly;
+
+ CHECK_NULL_ARG(ctx, 0)
+ CHECK_NULL_ARG(sk, 1)
+ CHECK_NULL_ARG(pk, 2)
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ if (secp256k1_keypair_create(ctx->secpCtx, &keyPair, sk->key) != 1)
+ {
+ return E_INVALID_ARG;
+ }
+
+ //Generate the x-only public key, docs say this should always return 1
+ result = secp256k1_keypair_xonly_pub(ctx->secpCtx, &xonly, NULL, &keyPair);
+ DEBUG_ASSERT2(result == 1, "Expected x-only kepair to ALWAYS return 1")
+
+ //Convert to compressed pubkey
+ result = _convertFromXonly(ctx, &xonly, pk);
+ DEBUG_ASSERT2(result == 1, "Expected x-only pubkey serialize to return 1")
+
+ //Clean out keypair
+ ZERO_FILL(&keyPair, sizeof(secp256k1_keypair));
+ ZERO_FILL(&xonly, sizeof(secp256k1_xonly_pubkey));
+
+ return NC_SUCCESS;
+}
+
+NC_EXPORT NCResult NC_CC NCValidateSecretKey(
+ const NCContext* ctx,
+ const NCSecretKey* sk
+)
+{
+ CHECK_NULL_PTR(ctx)
+ CHECK_NULL_PTR(sk)
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ //Validate the secret key
+ return secp256k1_ec_seckey_verify(ctx->secpCtx, sk->key) ? NC_SUCCESS : E_INVALID_ARG;
+}
+
+//Ecdsa Functions
+
+NC_EXPORT NCResult NC_CC NCSignDigest(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const uint8_t random32[32],
+ const uint8_t digest32[32],
+ uint8_t sig64[64]
+)
+{
+ int result;
+ secp256k1_keypair keyPair;
+ secp256k1_xonly_pubkey xonly;
+
+ //Validate arguments
+ CHECK_NULL_ARG(ctx, 0)
+ CHECK_NULL_ARG(sk, 1)
+ CHECK_NULL_ARG(random32, 2)
+ CHECK_NULL_ARG(digest32, 3)
+ CHECK_NULL_ARG(sig64, 4)
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ //Generate the keypair
+ if (secp256k1_keypair_create(ctx->secpCtx, &keyPair, sk->key) != 1)
+ {
+ return E_INVALID_ARG;
+ }
+
+ //Sign the digest
+ result = secp256k1_schnorrsig_sign32(ctx->secpCtx, sig64, digest32, &keyPair, random32);
+ DEBUG_ASSERT2(result == 1, "Expected schnorr signature to return 1");
+
+ //x-only public key from keypair so the signature can be verified
+ result = secp256k1_keypair_xonly_pub(ctx->secpCtx, &xonly, NULL, &keyPair);
+ DEBUG_ASSERT2(result == 1, "Expected x-only public key to ALWAYS return 1");
+
+ //Verify the signature is valid
+ result = secp256k1_schnorrsig_verify(ctx->secpCtx, sig64, digest32, 32, &xonly);
+
+ //cleanup any sensitive data
+ ZERO_FILL(&keyPair, sizeof(secp256k1_keypair));
+ ZERO_FILL(&xonly, sizeof(secp256k1_xonly_pubkey));
+
+ return result == 1 ? NC_SUCCESS : E_INVALID_ARG;
+}
+
+NC_EXPORT NCResult NC_CC NCSignData(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const uint8_t random32[32],
+ const uint8_t* data,
+ size_t dataSize,
+ uint8_t sig64[64]
+)
+{
+ uint8_t digest[32];
+
+ CHECK_NULL_ARG(data, 2)
+ //CHECK_ARG_RANGE(dataSize, 1, UINT32_MAX, 3)
+
+ //Compute sha256 of the data before signing
+ if(_computeSha256Digest(data, dataSize, digest) != 0)
+ {
+ return E_INVALID_ARG;
+ }
+
+ //Sign the freshly computed digest
+ return NCSignDigest(ctx, sk, random32, digest, sig64);
+}
+
+NC_EXPORT NCResult NC_CC NCVerifyDigest(
+ const NCContext* ctx,
+ const NCPublicKey* pk,
+ const uint8_t digest32[32],
+ const uint8_t sig64[64]
+)
+{
+ int result;
+ secp256k1_xonly_pubkey xonly;
+
+ DEBUG_ASSERT(&xonly != NULL)
+
+ CHECK_NULL_ARG(ctx, 0)
+ CHECK_NULL_ARG(sig64, 1)
+ CHECK_NULL_ARG(digest32, 2)
+ CHECK_NULL_ARG(pk, 3)
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ //recover the x-only key from a compressed public key
+ if(_convertToXonly(ctx, pk, &xonly) != 1)
+ {
+ return E_INVALID_ARG;
+ }
+
+ //Verify the signature
+ result = secp256k1_schnorrsig_verify(ctx->secpCtx, sig64, digest32, 32, &xonly);
+
+ //cleanup any sensitive data
+ ZERO_FILL(&xonly, sizeof(secp256k1_xonly_pubkey));
+
+ return result == 1 ? NC_SUCCESS : E_INVALID_ARG;
+}
+
+NC_EXPORT NCResult NC_CC NCVerifyData(
+ const NCContext* ctx,
+ const NCPublicKey* pk,
+ const uint8_t* data,
+ const size_t dataSize,
+ uint8_t sig64[64]
+)
+{
+ uint8_t digest[32];
+
+ CHECK_NULL_ARG(data, 2)
+ //CHECK_ARG_RANGE(dataSize, 1, UINT32_MAX, 3)
+
+ //Compute sha256 of the data before verifying
+ if (_computeSha256Digest(data, dataSize, digest) != 0)
+ {
+ return E_INVALID_ARG;
+ }
+
+ //Verify the freshly computed digest
+ return NCVerifyDigest(ctx, pk, digest, sig64);
+}
+
+//ECDH Functions
+NC_EXPORT NCResult NC_CC NCGetSharedSecret(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const NCPublicKey* otherPk,
+ uint8_t sharedPoint[NC_SHARED_SEC_SIZE]
+)
+{
+ CHECK_NULL_ARG(ctx, 0)
+ CHECK_NULL_ARG(sk, 1)
+ CHECK_NULL_ARG(otherPk, 2)
+ CHECK_NULL_ARG(sharedPoint, 3)
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ return _computeSharedSecret(
+ ctx,
+ sk,
+ otherPk,
+ (struct shared_secret*)sharedPoint
+ );
+}
+
+NC_EXPORT NCResult NC_CC NCGetConversationKeyEx(
+ const NCContext* ctx,
+ const uint8_t sharedPoint[NC_SHARED_SEC_SIZE],
+ uint8_t conversationKey[NC_CONV_KEY_SIZE]
+)
+{
+ CHECK_NULL_ARG(ctx, 0)
+ CHECK_NULL_ARG(sharedPoint, 1)
+ CHECK_NULL_ARG(conversationKey, 2)
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ //Cast the shared point to the shared secret type
+ return _computeConversationKey(
+ ctx,
+ _getSha256MdInfo(),
+ (struct shared_secret*)sharedPoint,
+ (struct conversation_key*)conversationKey
+ );
+}
+
+NC_EXPORT NCResult NC_CC NCGetConversationKey(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const NCPublicKey* pk,
+ uint8_t conversationKey[NC_CONV_KEY_SIZE]
+)
+{
+ NCResult result;
+ struct shared_secret sharedSecret;
+ const mbedtls_md_info_t* mdInfo;
+
+ CHECK_NULL_ARG(ctx, 0)
+ CHECK_NULL_ARG(sk, 1)
+ CHECK_NULL_ARG(pk, 2)
+ CHECK_NULL_ARG(conversationKey, 3)
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ mdInfo = _getSha256MdInfo();
+
+ //Compute the shared point
+ if ((result = _computeSharedSecret(ctx, sk, pk, &sharedSecret)) != NC_SUCCESS)
+ {
+ goto Cleanup;
+ }
+
+ result = _computeConversationKey(
+ ctx,
+ mdInfo,
+ &sharedSecret,
+ (struct conversation_key*)conversationKey
+ );
+
+Cleanup:
+ //Clean up sensitive data
+ ZERO_FILL(&sharedSecret, sizeof(sharedSecret));
+
+ return result;
+}
+
+NC_EXPORT NCResult NC_CC NCEncryptEx(
+ const NCContext* ctx,
+ const uint8_t conversationKey[NC_CONV_KEY_SIZE],
+ NCCryptoData* args
+)
+{
+ CHECK_NULL_ARG(ctx, 0)
+ CHECK_NULL_ARG(conversationKey, 1)
+ CHECK_NULL_ARG(args, 2)
+
+ //Validate the context
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ //Validte ciphertext/plaintext
+ CHECK_INVALID_ARG(args->inputData)
+ CHECK_INVALID_ARG(args->outputData)
+ CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 3)
+
+ return _encryptEx(
+ ctx,
+ _getSha256MdInfo(),
+ (struct conversation_key*)conversationKey,
+ args
+ );
+}
+
+NC_EXPORT NCResult NC_CC NCEncrypt(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const NCPublicKey* pk,
+ NCCryptoData* args
+)
+{
+ NCResult result;
+ const mbedtls_md_info_t* mdInfo;
+ struct shared_secret sharedSecret;
+ struct conversation_key ck;
+
+ CHECK_NULL_ARG(ctx, 0)
+ CHECK_NULL_ARG(sk, 1)
+ CHECK_NULL_ARG(pk, 2)
+ CHECK_NULL_ARG(args, 3)
+
+ //Validate the context
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ //Validate input/output data
+ CHECK_INVALID_ARG(args->inputData)
+ CHECK_INVALID_ARG(args->outputData)
+ CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_ENC_MESSAGE_SIZE, NIP44_MAX_ENC_MESSAGE_SIZE, 3)
+
+ mdInfo = _getSha256MdInfo();
+
+ //Compute the shared point
+ if ((result = _computeSharedSecret(ctx, sk, pk, &sharedSecret)) != NC_SUCCESS)
+ {
+ goto Cleanup;
+ }
+
+ //Compute the conversation key from secret and pubkic keys
+ if ((result = _computeConversationKey(ctx, mdInfo, &sharedSecret, &ck)) != NC_SUCCESS)
+ {
+ goto Cleanup;
+ }
+
+ result = _encryptEx(ctx, mdInfo, &ck, args);
+
+Cleanup:
+ //Clean up sensitive data
+ ZERO_FILL(&sharedSecret, sizeof(sharedSecret));
+ ZERO_FILL(&ck, sizeof(ck));
+
+ return result;
+}
+
+
+NC_EXPORT NCResult NC_CC NCDecryptEx(
+ const NCContext* ctx,
+ const uint8_t conversationKey[NC_CONV_KEY_SIZE],
+ NCCryptoData* args
+)
+{
+ CHECK_NULL_ARG(ctx, 0)
+ CHECK_NULL_ARG(conversationKey, 1)
+ CHECK_NULL_ARG(args, 2)
+
+ //Validate the context
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ //Validte ciphertext/plaintext
+ CHECK_INVALID_ARG(args->inputData)
+ CHECK_INVALID_ARG(args->outputData)
+ CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_DEC_MESSAGE_SIZE, NIP44_MAX_DEC_MESSAGE_SIZE, 3)
+
+ return _decryptEx(
+ ctx,
+ _getSha256MdInfo(),
+ (struct conversation_key*)conversationKey,
+ args
+ );
+}
+
+
+NC_EXPORT NCResult NC_CC NCDecrypt(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const NCPublicKey* pk,
+ NCCryptoData* args
+)
+{
+ NCResult result;
+ struct shared_secret sharedSecret;
+ struct conversation_key conversationKey;
+ const mbedtls_md_info_t* mdInfo;
+
+ CHECK_NULL_ARG(ctx, 0)
+ CHECK_NULL_ARG(sk, 1)
+ CHECK_NULL_ARG(pk, 2)
+ CHECK_NULL_ARG(args, 3)
+
+ //Validate the context
+ CHECK_INVALID_ARG(ctx->secpCtx)
+
+ //Validte ciphertext/plaintext
+ CHECK_INVALID_ARG(args->inputData)
+ CHECK_INVALID_ARG(args->outputData)
+ CHECK_ARG_RANGE(args->dataSize, NIP44_MIN_DEC_MESSAGE_SIZE, NIP44_MAX_DEC_MESSAGE_SIZE, 3)
+
+ mdInfo = _getSha256MdInfo();
+
+ if ((result = _computeSharedSecret(ctx, sk, pk, &sharedSecret)) != NC_SUCCESS)
+ {
+ goto Cleanup;
+ }
+
+ if ((result = _computeConversationKey(ctx, mdInfo, &sharedSecret, &conversationKey)) != NC_SUCCESS)
+ {
+ goto Cleanup;
+ }
+
+ result = _decryptEx(ctx, mdInfo, &conversationKey, args);
+
+Cleanup:
+ //Clean up sensitive data
+ ZERO_FILL(&sharedSecret, sizeof(sharedSecret));
+ ZERO_FILL(&conversationKey, sizeof(conversationKey));
+
+ return result;
+}
+
diff --git a/src/noscrypt.h b/src/noscrypt.h
new file mode 100644
index 0000000..8a43743
--- /dev/null
+++ b/src/noscrypt.h
@@ -0,0 +1,514 @@
+/*
+* Copyright (c) 2024 Vaughn Nugent
+*
+* Library: noscrypt
+* Package: noscrypt
+* File: noscrypt.h
+*
+* noscrypt is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published
+* by the Free Software Foundation, either version 2 of the License,
+* or (at your option) any later version.
+*
+* noscrypt is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with noscrypt. If not, see http://www.gnu.org/licenses/.
+*/
+
+/*
+* noscrypt is a an open-source, strict C89 library that performs the basic
+* cryptographic operations found in the Nostr protocol. It is designed to be
+* portable and easy to use in any C89 compatible environment. It is also designed
+*/
+
+#pragma once
+
+#ifndef NOSCRYPT_H
+#define NOSCRYPT_H
+
+#include <stdint.h>
+#include <stddef.h>
+
+#if defined(_MSC_VER) || defined(WIN32) || defined(_WIN32)
+ #define IS_WINDOWS
+#endif
+
+//Set api export calling convention (allow used to override)
+#ifndef NC_CC
+ #ifdef IS_WINDOWS
+ //STD for importing to other languages such as .NET
+ #define NC_CC __stdcall
+ #else
+ #define NC_CC
+ #endif
+#endif // !NC_CC
+
+#ifndef NC_EXPORT //Allow users to disable the export/impoty macro if using source code directly
+ #ifdef NOSCRYPT_EXPORTING
+ #ifdef IS_WINDOWS
+ #define NC_EXPORT __declspec(dllexport)
+ #else
+ #define NC_EXPORT __attribute__((visibility("default")))
+ #endif // IS_WINDOWS
+ #else
+ #ifdef IS_WINDOWS
+ #define NC_EXPORT __declspec(dllimport)
+ #else
+ #define NC_EXPORT
+ #endif // IS_WINDOWS
+ #endif // !NOSCRYPT_EXPORTING
+#endif // !NC_EXPORT
+
+
+#ifndef IS_WINDOWS
+ #ifndef inline
+ #define inline __inline__
+ #endif // !inline
+#endif // !IS_WINDOWS
+
+//NULL
+#ifndef NULL
+ #define NULL ((void*)0)
+#endif // !NULL
+
+/*
+* CONSTANTS
+*/
+#define BIP340_PUBKEY_HEADER_BYTE 0x02
+#define NIP44_MESSAGE_KEY_SIZE 76
+#define NC_ENCRYPTION_NONCE_SIZE 32
+#define NC_SEC_KEY_SIZE 32
+#define NC_PUBKEY_SIZE 32
+#define NC_SHARED_SEC_SIZE 32
+#define NC_CONV_KEY_SIZE 32
+#define NC_MESSAGE_KEY_SIZE NIP44_MESSAGE_KEY_SIZE
+
+/*
+* From spec
+* https://github.com/nostr-protocol/nips/blob/master/44.md#decryption
+*/
+#define NIP44_MIN_ENC_MESSAGE_SIZE 1
+#define NIP44_MAX_ENC_MESSAGE_SIZE 65535
+#define NIP44_MIN_DEC_MESSAGE_SIZE 99
+#define NIP44_MAX_DEC_MESSAGE_SIZE 65603
+
+/*
+* The Nip44 constant salt
+* https://github.com/nostr-protocol/nips/blob/master/44.md#encryption
+*/
+static const uint8_t Nip44ConstantSalt[8] = { 0x6e, 0x69, 0x70, 0x34, 0x34, 0x2d, 0x76, 0x32 };
+
+/*
+* ERROR CODES
+*
+* Error codes are 64bit integers. The lower 8 bits are reserved for
+* the error code, and the upper 8 bits are reserved for the argument
+* position.
+*
+* NCResult type is 64bit to also allow for positive return values for
+* operations that return a value count.
+*/
+
+#define ARG_POSITION_OFFSET 8
+#define NC_ERROR_CODE_MASK 0xFF
+
+#define NC_SUCCESS 0
+#define E_NULL_PTR -1
+#define E_INVALID_ARG -2
+#define E_INVALID_CONTEXT -3
+#define E_ARGUMENT_OUT_OF_RANGE -4
+
+/*
+* Validation macros
+*/
+
+#define CHECK_NULL_PTR(ptr) if(ptr == NULL) return E_NULL_PTR;
+#define CHECK_INVALID_ARG(x) if(x == NULL) return E_INVALID_ARG;
+#define CHECK_NULL_ARG(x, argPos) if(x == NULL) return NCResultWithArgPosition(E_NULL_PTR, argPos);
+#define CHECK_ARG_RANGE(x, min, max, argPos) if(x < min || x > max) return NCResultWithArgPosition(E_ARGUMENT_OUT_OF_RANGE, argPos);
+
+#ifdef DEBUG
+
+//Must include assert.h for assertions
+#include <assert.h>
+
+#define DEBUG_ASSERT(x) assert(x);
+#define DEBUG_ASSERT2(x, message) assert(x && message);
+#else
+#define DEBUG_ASSERT(x)
+#define DEBUG_ASSERT2(x, message)
+#endif
+
+/* A compressed resul/return value, negative values
+are failure, 0 is success and positive values are
+defined by the operation.
+*/
+typedef int64_t NCResult;
+
+/*
+ An secp256k1 secret key (aka 32byte private key buffer)
+*/
+typedef struct secret_key_struct {
+
+ uint8_t key[NC_SEC_KEY_SIZE];
+
+}NCSecretKey;
+
+/*
+ An x-only secp256k1 public key
+*/
+typedef struct xonly_pubkey_struct {
+
+ uint8_t key[NC_PUBKEY_SIZE];
+
+}NCPublicKey;
+
+/*
+ An opaque full library context object
+*/
+typedef struct ctx_struct {
+
+ void* secpCtx;
+
+}NCContext;
+
+/*
+* The encryption arguments structure. This structure is used to pass
+arguments to the encryption and decryption functions. It stores the
+data buffers and required nonce used for the stream cipher.
+*/
+typedef struct nc_encryption_struct {
+
+ /*
+ * The nonce used for the stream cipher.
+ */
+ uint8_t nonce[NC_ENCRYPTION_NONCE_SIZE];
+
+ /* The input data buffer to encrypt/decrypt */
+ const void* inputData;
+
+ /* The output data buffer to write data to */
+ void* outputData;
+
+ /* The size of the data buffers. Buffers must
+ * be the same size or larger than this value
+ */
+ uint32_t dataSize;
+
+} NCCryptoData;
+
+/*
+ API FUNCTIONS
+*/
+
+static inline NCSecretKey* NCToSecKey(uint8_t key[NC_SEC_KEY_SIZE])
+{
+ return (NCSecretKey*)key;
+}
+
+static inline NCPublicKey* NCToPubKey(uint8_t key[NC_PUBKEY_SIZE])
+{
+ return (NCPublicKey*)key;
+}
+
+static inline NCResult NCResultWithArgPosition(NCResult err, uint8_t argPosition)
+{
+ //Store the error code in the lower 8 bits and the argument position in the upper 24 bits
+ return (err & NC_ERROR_CODE_MASK) | (((uint32_t)argPosition) << ARG_POSITION_OFFSET);
+}
+
+/*
+* Parses an error code and returns the error code and the argument position
+that caused the error.
+* @param result The error code to parse
+* @param code A pointer to the error code to write to
+* @param argPosition A pointer to the argument position to write to
+*/
+NC_EXPORT void NC_CC NCParseErrorCode(NCResult result, int* code, int* argPosition)
+{
+ //Get the error code from the lower 8 bits and the argument position from the upper 8 bits
+ *code = result & NC_ERROR_CODE_MASK;
+ *argPosition = (result >> ARG_POSITION_OFFSET) & 0xFF;
+}
+
+/*--------------------------------------
+* LIB CONTEXT API
+*/
+
+/*
+* Runtime check for the size of the context struct to allow
+for dynamic allocation when context size structure is not known.
+* @return The size of the context struct in bytes
+*/
+NC_EXPORT uint32_t NC_CC NCGetContextStructSize(void);
+/*
+* Initializes a context struct with the given entropy
+* @param ctx A pointer to the context structure to initialize
+* @param entropy The 32byte entropy to initialize the context with
+* @return NC_SUCCESS if the operation was successful, otherwise an error code
+*/
+NC_EXPORT NCResult NC_CC NCInitContext(
+ NCContext* ctx,
+ const uint8_t entropy[32]
+);
+/*
+* Reinitializes a context struct with the given
+* @param ctx A pointer to the context structure to initialize
+* @param entropy The 32byte entropy to initialize the context with
+* @return NC_SUCCESS if the operation was successful, otherwise an error code
+*/
+NC_EXPORT NCResult NC_CC NCReInitContext(
+ NCContext* ctx,
+ const uint8_t entropy[32]
+);
+
+/*
+* Destroys a context struct
+* @param ctx A pointer to the existing context structure to destroy
+* @return NC_SUCCESS if the operation was successful, otherwise an error code
+*/
+NC_EXPORT NCResult NC_CC NCDestroyContext(NCContext* ctx);
+
+
+
+/*--------------------------------------
+* HIGH LEVEL SIGNING API
+*/
+
+/*
+* Gets a 32byte x-only compressed public key from the given secret key
+* @param ctx A pointer to the existing library context
+* @param sk A pointer to the secret key
+* @param pk A pointer to the compressed public key buffer to write to
+* @return NC_SUCCESS if the operation was successful, otherwise an error code
+*/
+NC_EXPORT NCResult NC_CC NCGetPublicKey(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ NCPublicKey* pk
+);
+/*
+* Validates that a given secret key is valid according to the secp256k1 curve. This
+is functionally the same as calling secp256k1_ec_seckey_verify.
+* @param ctx A pointer to the existing library context
+* @param sk A pointer to the secret key to verify
+* @return NC_SUCCESS if the secret key is in a valid format, otherwise an error code
+*/
+NC_EXPORT NCResult NC_CC NCValidateSecretKey(
+ const NCContext* ctx,
+ const NCSecretKey* sk
+);
+
+
+/*
+* Signs a raw message after computing the sha256 checksum using the
+given secret key and writes the signature to the sig64 buffer.
+* @param ctx A pointer to the existing library context
+* @param sk A pointer to the secret key to sign with
+* @param random32 A pointer to the 32byte random32 buffer to use for signing
+* @param data A pointer to the raw data buffer to sign
+* @param dataSize The size of the raw data buffer
+* @param sig64 A pointer to the 64byte buffer to write the signature to
+* @return NC_SUCCESS if the operation was successful, otherwise an error code
+*/
+NC_EXPORT NCResult NC_CC NCSignData(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const uint8_t random32[32],
+ const uint8_t* data,
+ const size_t dataSize,
+ uint8_t sig64[64]
+);
+
+/*
+* Verifies a signature of a raw data buffer matches the output using the given public key.
+* @param ctx A pointer to the existing library context
+* @param sig64 The 64byte signature to verify
+* @param data A pointer to the raw data buffer to verify
+* @param dataSize The size of the raw data buffer
+* @param pk A pointer to the the x-only compressed public key (x-only serialized public key)
+* @return NC_SUCCESS if the signature could be verified, otherwise an error code
+*/
+NC_EXPORT NCResult NC_CC NCVerifyData(
+ const NCContext* ctx,
+ const NCPublicKey* pk,
+ const uint8_t* data,
+ const size_t dataSize,
+ uint8_t sig64[64]
+);
+
+/*--------------------------------------
+* EXTENDED SIGNING API
+*/
+
+/*
+* Signs a message using the given secret key and writes the signature to the sig64 buffer
+* @param ctx A pointer to the existing library context
+* @param sk A pointer to the secret key to sign with
+* @param random32 A pointer to the 32byte random32 buffer to use for signing
+* @param digest32 A pointer to 32byte sha256 digest32 to sign
+* @param sig64 A pointer to the 64byte buffer to write the signature to
+* @return NC_SUCCESS if the operation was successful, otherwise an error code
+*/
+NC_EXPORT NCResult NC_CC NCSignDigest(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const uint8_t random32[32],
+ const uint8_t digest32[32],
+ uint8_t sig64[64]
+);
+
+/*
+* Verifies a signature of a digest32 matches the output using the given public key.
+Equivalent to calling secp256k1_schnorrsig_verify.
+* @param ctx A pointer to the existing library context
+* @param sig64 The 64byte signature to verify
+* @param digest32 The 32byte digest32 to verify
+* @param pk A pointer to the the x-only compressed public key (x-only serialized public key)
+* @return NC_SUCCESS if the signature could be verified, otherwise an error code
+*/
+NC_EXPORT NCResult NC_CC NCVerifyDigest(
+ const NCContext* ctx,
+ const NCPublicKey* pk,
+ const uint8_t digest32[32],
+ const uint8_t sig64[64]
+);
+
+
+
+/*--------------------------------------
+* HIGH LEVEL ENCRYPTION API
+*/
+
+/*
+* NOTES
+*
+* NIP-44 requires that plaintext/ciphertext must be padded in powers of 2.
+* Since this library operates on data at the binary level, and does not do
+* ANY runtime heap allocation, it is up to the user to ensure that the
+* plaintext/ciphertext buffers are padded properly in The NCryptoData struct
+* before calling the encryption/decryption functions.
+*/
+
+/*
+* High level api for encrypting nostr messages using a secret key and a public key. Use
+the NCEncryptEx functions for extended encryption functionality
+* @param ctx The library context
+* @param sk The secret key (the local private key)
+* @param pk The 32byte compressed public key (x-only serialized public key) the other user's public key
+* @param args The encryption arguments
+* @return NC_SUCCESS if the operation was successful, otherwise an error code. Use NCParseErrorCode to
+the error code and positional argument that caused the error
+*/
+NC_EXPORT NCResult NC_CC NCEncrypt(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const NCPublicKey* pk,
+ NCCryptoData* args
+);
+
+/*
+* High level api for decrypting nostr messages using a secret key and a public key. Use
+the NCDecryptEx functions for extended decryption functionality.
+* @param ctx The library context
+* @param sk The secret key (the local private key)
+* @param pk The 32byte compressed public key (x-only serialized public key) the other user's public key
+* @param args The decryption arguments
+* @return NC_SUCCESS if the operation was successful, otherwise an error code. Use NCParseErrorCode to
+the error code and positional argument that caused the error
+*/
+NC_EXPORT NCResult NC_CC NCDecrypt(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const NCPublicKey* pk,
+ NCCryptoData* args
+);
+
+
+/*--------------------------------------
+* EXTENDED ENCRYPTION API
+*/
+
+/*
+* Computes a NIP-44 shared secret from a secret key and a public key and
+stores it in the sharedPoint buffer.
+* @param ctx A pointer to the existing library context
+* @param sk The secret key
+* @param pk The 32byte compressed public key (x-only serialized public key)
+* @param sharedPoint The 32byte buffer to store write the secret data to
+* @return NC_SUCCESS if the operation was successful, otherwise an error code. Use NCParseErrorCode to
+the error code and positional argument that caused the error
+*/
+NC_EXPORT NCResult NC_CC NCGetSharedSecret(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const NCPublicKey* pk,
+ uint8_t sharedPoint[NC_SHARED_SEC_SIZE]
+);
+
+/*
+* Computes a NIP-44 conversation key from the local secret key and the remote
+public key, and stores it in the conversationKey buffer.
+* @param ctx A pointer to the existing library context
+* @param sk A pointer to the 32byte the secret key
+* @param pk A pointer to the 32byte compressed public key (x-only serialized public key)
+* @param conversationKey The 32byte buffer to store write the conversation key to
+* @return NC_SUCCESS if the operation was successful, otherwise an error code. Use NCParseErrorCode to
+the error code and positional argument that caused the error
+*/
+NC_EXPORT NCResult NC_CC NCGetConversationKey(
+ const NCContext* ctx,
+ const NCSecretKey* sk,
+ const NCPublicKey* pk,
+ uint8_t conversationKey[NC_CONV_KEY_SIZE]
+);
+/*
+* Computes a NIP-44 conversation key a shared secret/point, and stores it in the
+conversationKey buffer.
+* @param ctx A pointer to the existing library context
+* @param sharedPoint A pointer to the 32byte shared secret/point
+* @param conversationKey The 32byte buffer to store write the conversation key to
+* @return NC_SUCCESS if the operation was successful, otherwise an error code. Use NCParseErrorCode to
+the error code and positional argument that caused the error
+*/
+NC_EXPORT NCResult NC_CC NCGetConversationKeyEx(
+ const NCContext* ctx,
+ const uint8_t sharedPoint[NC_SHARED_SEC_SIZE],
+ uint8_t conversationKey[NC_CONV_KEY_SIZE]
+);
+
+/*
+* Encrypts a message using the given conversation key and writes the encrypted message to the
+* output buffer. The output buffer must be at least 99 bytes in size.
+* @param ctx A pointer to the existing library context
+* @param conversationKey A pointer to the 32byte conversation key
+* @param args A pointer to the encryption arguments structure
+* @return NC_SUCCESS if the operation was successful, otherwise an error code. Use NCParseErrorCode to
+the error code and positional argument that caused the error.
+*/
+NC_EXPORT NCResult NC_CC NCEncryptEx(
+ const NCContext* ctx,
+ const uint8_t conversationKey[NC_CONV_KEY_SIZE],
+ NCCryptoData* args
+);
+
+/*
+* Decrypts a message using the given conversation key and writes the decrypted message to the
+* output buffer.
+* @param ctx A pointer to the existing library context
+* @param conversationKey A pointer to the 32byte conversation key
+* @param args A pointer to the decryption arguments structure
+* @return NC_SUCCESS if the operation was successful, otherwise an error code. Use NCParseErrorCode to
+the error code and positional argument that caused the error.
+*/
+NC_EXPORT NCResult NC_CC NCDecryptEx(
+ const NCContext* ctx,
+ const uint8_t conversationKey[NC_CONV_KEY_SIZE],
+ NCCryptoData* args
+);
+
+#endif // !NOSCRYPT_H
diff --git a/tests/test.c b/tests/test.c
new file mode 100644
index 0000000..499ef50
--- /dev/null
+++ b/tests/test.c
@@ -0,0 +1,170 @@
+/*
+* Copyright (c) 2024 Vaughn Nugent
+*
+* Library: noscrypt
+* Package: noscrypt
+* File: test.c
+*
+* noscrypt is free software: you can redistribute it and/or modify
+* it under the terms of the GNU General Public License as published
+* by the Free Software Foundation, either version 2 of the License,
+* or (at your option) any later version.
+*
+* noscrypt is distributed in the hope that it will be useful,
+* but WITHOUT ANY WARRANTY; without even the implied warranty of
+* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+* General Public License for more details.
+*
+* You should have received a copy of the GNU General Public License
+* along with noscrypt. If not, see http://www.gnu.org/licenses/.
+*/
+
+#include <stdio.h>
+#include <stdint.h>
+#include <string.h>
+
+#include "../src/noscrypt.h"
+#include "../include/mbedtls/sha256.h"
+
+#if defined(_MSC_VER) || defined(WIN32) || defined(_WIN32)
+ #define IS_WINDOWS
+#endif
+
+#ifdef IS_WINDOWS
+
+ #include <windows.h>
+ #include <wincrypt.h>
+
+ //Prints a string literal to the console
+ #define PRINTL(x) printf(x); printf("\r\n");
+ #define TEST(x) printf("Testing %s\n", #x); if(!(x)) { printf("Test failed!\n"); return 1; } else { printf("Test passed\n\n"); }
+ #define TASSERT(x) if(!(x)) { printf("ERROR! Internal test assumption failed: %s.\n Aborting tests...\n", #x); ExitProcess(1); }
+#else
+ #include <stdlib.h>
+
+ //Prints a string literal to the console
+ #define PRINTL(x) printf(x); printf("\n");
+ #define TEST(x) printf("Testing %s\n", #x); if(!(x)) { printf("Test failed!\n"); return 1; } else { printf("Test passed\n\n"); }
+ #define TASSERT(x) if(!(x)) { printf("Internal assumption failed: %s\n", #x); exit(1); }
+#endif
+
+static void FillRandomData(uint8_t* pbBuffer, size_t length);
+static int TestEcdsa(NCContext* context);
+
+int main(char* argv[], int argc)
+{
+ NCContext ctx;
+ uint8_t ctxRandom[32];
+
+ PRINTL("Begining basic noscrypt tests\n")
+
+ FillRandomData(ctxRandom, 32);
+
+ //Context struct size should aways match the size of the struct returned by NCGetContextStructSize
+ TEST(NCGetContextStructSize() == sizeof(NCContext))
+
+ TEST(NCInitContext(&ctx, ctxRandom) == NC_SUCCESS)
+
+ if (TestEcdsa(&ctx) != 0)
+ {
+ return 1;
+ }
+
+ PRINTL("ECDSA tests passed\n")
+
+ TEST(NCDestroyContext(&ctx) == NC_SUCCESS)
+
+ return 0;
+}
+
+static void _sha256(const uint8_t* data, size_t length, uint8_t digest[32])
+{
+ mbedtls_sha256_context sha256;
+ mbedtls_sha256_init(&sha256);
+ TASSERT(0 == mbedtls_sha256_starts(&sha256, 0))
+ TASSERT(0 == mbedtls_sha256_update(&sha256, data, length))
+ TASSERT(0 == mbedtls_sha256_finish(&sha256, digest))
+ mbedtls_sha256_free(&sha256);
+}
+
+static const char* message = "Test message to sign";
+
+static int TestEcdsa(NCContext* context)
+{
+ uint8_t digestToSign[32];
+ uint8_t secretKey[NC_SEC_KEY_SIZE];
+ uint8_t publicKey[NC_PUBKEY_SIZE];
+ uint8_t sigEntropy[32];
+ uint8_t invalidSig[64];
+ NCSecretKey* secKey;
+ NCPublicKey* pubKey;
+
+ PRINTL("Begining basic Nostr ECDSA tests")
+
+ //Convert to internal key structs
+ secKey = NCToSecKey(secretKey);
+ pubKey = NCToPubKey(publicKey);
+
+ TEST((&secKey->key) == &secretKey);
+
+ //Init a new secret key with random data
+ FillRandomData(secretKey, sizeof(secretKey));
+ FillRandomData(invalidSig, sizeof(invalidSig));
+ FillRandomData(sigEntropy, sizeof(sigEntropy));
+
+ //Verify that the secret key is valid for the curve
+ TEST(NCValidateSecretKey(context, secKey) == NC_SUCCESS);
+
+ //Generate a public key from the secret key
+ TEST(NCGetPublicKey(context, secKey, pubKey) == NC_SUCCESS);
+
+ //Sign and verify digest
+ {
+ uint8_t sig[64];
+
+ //compute sha256 of the test string
+ _sha256((uint8_t*)message, strlen(message), digestToSign);
+
+ TEST(NCSignDigest(context, secKey, sigEntropy, digestToSign, sig) == NC_SUCCESS);
+ TEST(NCVerifyDigest(context, pubKey, digestToSign, sig) == NC_SUCCESS);
+ }
+
+ //Sign and verify raw data
+ {
+ uint8_t sig[64];
+ TEST(NCSignData(context, secKey, sigEntropy, (uint8_t*)message, strlen(message), sig) == NC_SUCCESS);
+ TEST(NCVerifyData(context, pubKey, (uint8_t*)message, strlen(message), sig) == NC_SUCCESS);
+ }
+
+ //test verification of invalid signature
+ {
+ TEST(NCVerifyDigest(context, pubKey, digestToSign, invalidSig) == E_INVALID_ARG);
+ }
+
+ return 0;
+}
+
+static const char* encMessage = "Test message to encrypt";
+
+static int TestEcdh(NCContext* ctx)
+{
+ PRINTL("Begining basic Nostr Encryption tests")
+}
+
+static void FillRandomData(uint8_t* pbBuffer, size_t length)
+{
+
+#ifdef IS_WINDOWS
+
+ HCRYPTPROV hCryptProv;
+
+ TASSERT(CryptAcquireContext(&hCryptProv, NULL, NULL, PROV_RSA_FULL, 0));
+ TASSERT(CryptGenRandom(hCryptProv, (DWORD)length, pbBuffer))
+ TASSERT(CryptReleaseContext(hCryptProv, 0));
+#else
+ FILE* f = fopen("/dev/urandom", "rb");
+ TASSERT(f != NULL);
+ TASSERT(fread(pbBuffer, 1, length, f) == length);
+ fclose(f);
+#endif
+} \ No newline at end of file