cjson
.github
workflows CI.yml ci-fuzz.yml
CONTRIBUTING.md
fuzzing
inputs test1 test10 test11 test2 test3 test3.bu test3.uf test3.uu test4 test5 test6 test7 test8 test9
.gitignore CMakeLists.txt afl-prepare-linux.sh afl.c afl.sh cjson_read_fuzzer.c fuzz_main.c json.dict ossfuzz.sh
library_config cJSONConfig.cmake.in cJSONConfigVersion.cmake.in libcjson.pc.in libcjson_utils.pc.in uninstall.cmake
tests
inputs test1 test1.expected test10 test10.expected test11 test11.expected test2 test2.expected test3 test3.expected test4 test4.expected test5 test5.expected test6 test7 test7.expected test8 test8.expected test9 test9.expected
json-patch-tests .editorconfig .gitignore .npmignore README.md cjson-utils-tests.json package.json spec_tests.json tests.json
unity
auto colour_prompt.rb colour_reporter.rb generate_config.yml generate_module.rb generate_test_runner.rb parse_output.rb stylize_as_junit.rb test_file_filter.rb type_sanitizer.rb unity_test_summary.py unity_test_summary.rb unity_to_junit.py
docs ThrowTheSwitchCodingStandard.md UnityAssertionsCheatSheetSuitableforPrintingandPossiblyFraming.pdf UnityAssertionsReference.md UnityConfigurationGuide.md UnityGettingStartedGuide.md UnityHelperScriptsGuide.md license.txt
examples
example_1
src ProductionCode.c ProductionCode.h ProductionCode2.c ProductionCode2.h
makefile readme.txt
example_2
src ProductionCode.c ProductionCode.h ProductionCode2.c ProductionCode2.h
makefile readme.txt
example_3
helper UnityHelper.c UnityHelper.h
src ProductionCode.c ProductionCode.h ProductionCode2.c ProductionCode2.h
rakefile.rb rakefile_helper.rb readme.txt target_gcc_32.yml
unity_config.h
extras
eclipse error_parsers.txt
fixture
src unity_fixture.c unity_fixture.h unity_fixture_internals.h unity_fixture_malloc_overrides.h
rakefile.rb rakefile_helper.rb readme.txt
release build.info version.info
src unity.c unity.h unity_internals.h
.gitattributes .gitignore .travis.yml README.md
CMakeLists.txt cjson_add.c common.h compare_tests.c json_patch_tests.c minify_tests.c misc_tests.c misc_utils_tests.c old_utils_tests.c parse_array.c parse_examples.c parse_hex4.c parse_number.c parse_object.c parse_string.c parse_value.c parse_with_opts.c print_array.c print_number.c print_object.c print_string.c print_value.c readme_examples.c unity_setup.c
.editorconfig .gitattributes .gitignore .travis.yml CHANGELOG.md CMakeLists.txt CONTRIBUTORS.md LICENSE Makefile README.md SECURITY.md appveyor.yml cJSON.c cJSON.h cJSON_Utils.c cJSON_Utils.h test.c valgrind.supp
curl
.circleci config.yml
.github
ISSUE_TEMPLATE bug_report.yml config.yml docs.yml
scripts cleancmd.pl cmp-config.pl cmp-pkg-config.sh codespell-ignore.words codespell.sh distfiles.sh pyspelling.words pyspelling.yaml randcurl.pl requirements-docs.txt requirements-proselint.txt requirements.txt shellcheck-ci.sh shellcheck.sh spellcheck.curl trimmarkdownheader.pl typos.sh typos.toml verify-examples.pl verify-synopsis.pl yamlcheck.sh yamlcheck.yaml
workflows appveyor-status.yml checkdocs.yml checksrc.yml checkurls.yml codeql.yml configure-vs-cmake.yml curl-for-win.yml distcheck.yml fuzz.yml http3-linux.yml label.yml linux-old.yml linux.yml macos.yml non-native.yml windows.yml
CODEOWNERS CONTRIBUTING.md FUNDING.yml dependabot.yml labeler.yml lock.yml stale.yml
CMake CurlSymbolHiding.cmake CurlTests.c FindBrotli.cmake FindCares.cmake FindGSS.cmake FindGnuTLS.cmake FindLDAP.cmake FindLibbacktrace.cmake FindLibgsasl.cmake FindLibidn2.cmake FindLibpsl.cmake FindLibssh.cmake FindLibssh2.cmake FindLibuv.cmake FindMbedTLS.cmake FindNGHTTP2.cmake FindNGHTTP3.cmake FindNGTCP2.cmake FindNettle.cmake FindQuiche.cmake FindRustls.cmake FindWolfSSL.cmake FindZstd.cmake Macros.cmake OtherTests.cmake PickyWarnings.cmake Utilities.cmake cmake_uninstall.in.cmake curl-config.in.cmake unix-cache.cmake win32-cache.cmake
LICENSES BSD-4-Clause-UC.txt ISC.txt curl.txt
docs
cmdline-opts .gitignore CMakeLists.txt MANPAGE.md Makefile.am Makefile.inc _AUTHORS.md _BUGS.md _DESCRIPTION.md _ENVIRONMENT.md _EXITCODES.md _FILES.md _GLOBBING.md _NAME.md _OPTIONS.md _OUTPUT.md _PROGRESS.md _PROTOCOLS.md _PROXYPREFIX.md _SEEALSO.md _SYNOPSIS.md _URL.md _VARIABLES.md _VERSION.md _WWW.md abstract-unix-socket.md alt-svc.md anyauth.md append.md aws-sigv4.md basic.md ca-native.md cacert.md capath.md cert-status.md cert-type.md cert.md ciphers.md compressed-ssh.md compressed.md config.md connect-timeout.md connect-to.md continue-at.md cookie-jar.md cookie.md create-dirs.md create-file-mode.md crlf.md crlfile.md curves.md data-ascii.md data-binary.md data-raw.md data-urlencode.md data.md delegation.md digest.md disable-eprt.md disable-epsv.md disable.md disallow-username-in-url.md dns-interface.md dns-ipv4-addr.md dns-ipv6-addr.md dns-servers.md doh-cert-status.md doh-insecure.md doh-url.md dump-ca-embed.md dump-header.md ech.md egd-file.md engine.md etag-compare.md etag-save.md expect100-timeout.md fail-early.md fail-with-body.md fail.md false-start.md follow.md form-escape.md form-string.md form.md ftp-account.md ftp-alternative-to-user.md ftp-create-dirs.md ftp-method.md ftp-pasv.md ftp-port.md ftp-pret.md ftp-skip-pasv-ip.md ftp-ssl-ccc-mode.md ftp-ssl-ccc.md ftp-ssl-control.md get.md globoff.md happy-eyeballs-timeout-ms.md haproxy-clientip.md haproxy-protocol.md head.md header.md help.md hostpubmd5.md hostpubsha256.md hsts.md http0.9.md http1.0.md http1.1.md http2-prior-knowledge.md http2.md http3-only.md http3.md ignore-content-length.md insecure.md interface.md ip-tos.md ipfs-gateway.md ipv4.md ipv6.md json.md junk-session-cookies.md keepalive-cnt.md keepalive-time.md key-type.md key.md knownhosts.md krb.md libcurl.md limit-rate.md list-only.md local-port.md location-trusted.md location.md login-options.md mail-auth.md mail-from.md mail-rcpt-allowfails.md mail-rcpt.md mainpage.idx manual.md max-filesize.md max-redirs.md max-time.md metalink.md mptcp.md negotiate.md netrc-file.md netrc-optional.md netrc.md next.md no-alpn.md no-buffer.md no-clobber.md no-keepalive.md no-npn.md no-progress-meter.md no-sessionid.md noproxy.md ntlm-wb.md ntlm.md oauth2-bearer.md out-null.md output-dir.md output.md parallel-immediate.md parallel-max-host.md parallel-max.md parallel.md pass.md path-as-is.md pinnedpubkey.md post301.md post302.md post303.md preproxy.md progress-bar.md proto-default.md proto-redir.md proto.md proxy-anyauth.md proxy-basic.md proxy-ca-native.md proxy-cacert.md proxy-capath.md proxy-cert-type.md proxy-cert.md proxy-ciphers.md proxy-crlfile.md proxy-digest.md proxy-header.md proxy-http2.md proxy-insecure.md proxy-key-type.md proxy-key.md proxy-negotiate.md proxy-ntlm.md proxy-pass.md proxy-pinnedpubkey.md proxy-service-name.md proxy-ssl-allow-beast.md proxy-ssl-auto-client-cert.md proxy-tls13-ciphers.md proxy-tlsauthtype.md proxy-tlspassword.md proxy-tlsuser.md proxy-tlsv1.md proxy-user.md proxy.md proxy1.0.md proxytunnel.md pubkey.md quote.md random-file.md range.md rate.md raw.md referer.md remote-header-name.md remote-name-all.md remote-name.md remote-time.md remove-on-error.md request-target.md request.md resolve.md retry-all-errors.md retry-connrefused.md retry-delay.md retry-max-time.md retry.md sasl-authzid.md sasl-ir.md service-name.md show-error.md show-headers.md sigalgs.md silent.md skip-existing.md socks4.md socks4a.md socks5-basic.md socks5-gssapi-nec.md socks5-gssapi-service.md socks5-gssapi.md socks5-hostname.md socks5.md speed-limit.md speed-time.md ssl-allow-beast.md ssl-auto-client-cert.md ssl-no-revoke.md ssl-reqd.md ssl-revoke-best-effort.md ssl-sessions.md ssl.md sslv2.md sslv3.md stderr.md styled-output.md suppress-connect-headers.md tcp-fastopen.md tcp-nodelay.md telnet-option.md tftp-blksize.md tftp-no-options.md time-cond.md tls-earlydata.md tls-max.md tls13-ciphers.md tlsauthtype.md tlspassword.md tlsuser.md tlsv1.0.md tlsv1.1.md tlsv1.2.md tlsv1.3.md tlsv1.md tr-encoding.md trace-ascii.md trace-config.md trace-ids.md trace-time.md trace.md unix-socket.md upload-file.md upload-flags.md url-query.md url.md use-ascii.md user-agent.md user.md variable.md verbose.md version.md vlan-priority.md write-out.md xattr.md
examples .checksrc .gitignore 10-at-a-time.c CMakeLists.txt Makefile.am Makefile.example Makefile.inc README.md adddocsref.pl address-scope.c altsvc.c anyauthput.c block_ip.c cacertinmem.c certinfo.c chkspeed.c connect-to.c cookie_interface.c crawler.c debug.c default-scheme.c ephiperfifo.c evhiperfifo.c externalsocket.c fileupload.c ftp-delete.c ftp-wildcard.c ftpget.c ftpgetinfo.c ftpgetresp.c ftpsget.c ftpupload.c ftpuploadfrommem.c ftpuploadresume.c getinfo.c getinmemory.c getredirect.c getreferrer.c ghiper.c headerapi.c hiperfifo.c hsts-preload.c htmltidy.c htmltitle.cpp http-options.c http-post.c http2-download.c http2-pushinmemory.c http2-serverpush.c http2-upload.c http3-present.c http3.c httpcustomheader.c httpput-postfields.c httpput.c https.c imap-append.c imap-authzid.c imap-copy.c imap-create.c imap-delete.c imap-examine.c imap-fetch.c imap-list.c imap-lsub.c imap-multi.c imap-noop.c imap-search.c imap-ssl.c imap-store.c imap-tls.c interface.c ipv6.c keepalive.c localport.c log_failed_transfers.c maxconnects.c multi-app.c multi-debugcallback.c multi-double.c multi-event.c multi-formadd.c multi-legacy.c multi-post.c multi-single.c multi-uv.c netrc.c parseurl.c persistent.c pop3-authzid.c pop3-dele.c pop3-list.c pop3-multi.c pop3-noop.c pop3-retr.c pop3-ssl.c pop3-stat.c pop3-tls.c pop3-top.c pop3-uidl.c post-callback.c postinmemory.c postit2-formadd.c postit2.c progressfunc.c protofeats.c range.c resolve.c rtsp-options.c sendrecv.c sepheaders.c sessioninfo.c sftpget.c sftpuploadresume.c shared-connection-cache.c simple.c simplepost.c simplessl.c smooth-gtk-thread.c smtp-authzid.c smtp-expn.c smtp-mail.c smtp-mime.c smtp-multi.c smtp-ssl.c smtp-tls.c smtp-vrfy.c sslbackend.c synctime.c threaded.c unixsocket.c url2file.c urlapi.c usercertinmem.c version-check.pl websocket-cb.c websocket-updown.c websocket.c xmlstream.c
internals BUFQ.md BUFREF.md CHECKSRC.md CLIENT-READERS.md CLIENT-WRITERS.md CODE_STYLE.md CONNECTION-FILTERS.md CREDENTIALS.md CURLX.md DYNBUF.md HASH.md LLIST.md MID.md MQTT.md MULTI-EV.md NEW-PROTOCOL.md PEERS.md PORTING.md RATELIMITS.md README.md SCORECARD.md SPLAY.md STRPARSE.md THRDPOOL-AND-QUEUE.md TIME-KEEPING.md TLS-SESSIONS.md UINT_SETS.md WEBSOCKET.md
libcurl
opts CMakeLists.txt CURLINFO_ACTIVESOCKET.md CURLINFO_APPCONNECT_TIME.md CURLINFO_APPCONNECT_TIME_T.md CURLINFO_CAINFO.md CURLINFO_CAPATH.md CURLINFO_CERTINFO.md CURLINFO_CONDITION_UNMET.md CURLINFO_CONNECT_TIME.md CURLINFO_CONNECT_TIME_T.md CURLINFO_CONN_ID.md CURLINFO_CONTENT_LENGTH_DOWNLOAD.md CURLINFO_CONTENT_LENGTH_DOWNLOAD_T.md CURLINFO_CONTENT_LENGTH_UPLOAD.md CURLINFO_CONTENT_LENGTH_UPLOAD_T.md CURLINFO_CONTENT_TYPE.md CURLINFO_COOKIELIST.md CURLINFO_EARLYDATA_SENT_T.md CURLINFO_EFFECTIVE_METHOD.md CURLINFO_EFFECTIVE_URL.md CURLINFO_FILETIME.md CURLINFO_FILETIME_T.md CURLINFO_FTP_ENTRY_PATH.md CURLINFO_HEADER_SIZE.md CURLINFO_HTTPAUTH_AVAIL.md CURLINFO_HTTPAUTH_USED.md CURLINFO_HTTP_CONNECTCODE.md CURLINFO_HTTP_VERSION.md CURLINFO_LASTSOCKET.md CURLINFO_LOCAL_IP.md CURLINFO_LOCAL_PORT.md CURLINFO_NAMELOOKUP_TIME.md CURLINFO_NAMELOOKUP_TIME_T.md CURLINFO_NUM_CONNECTS.md CURLINFO_OS_ERRNO.md CURLINFO_POSTTRANSFER_TIME_T.md CURLINFO_PRETRANSFER_TIME.md CURLINFO_PRETRANSFER_TIME_T.md CURLINFO_PRIMARY_IP.md CURLINFO_PRIMARY_PORT.md CURLINFO_PRIVATE.md CURLINFO_PROTOCOL.md CURLINFO_PROXYAUTH_AVAIL.md CURLINFO_PROXYAUTH_USED.md CURLINFO_PROXY_ERROR.md CURLINFO_PROXY_SSL_VERIFYRESULT.md CURLINFO_QUEUE_TIME_T.md CURLINFO_REDIRECT_COUNT.md CURLINFO_REDIRECT_TIME.md CURLINFO_REDIRECT_TIME_T.md CURLINFO_REDIRECT_URL.md CURLINFO_REFERER.md CURLINFO_REQUEST_SIZE.md CURLINFO_RESPONSE_CODE.md CURLINFO_RETRY_AFTER.md CURLINFO_RTSP_CLIENT_CSEQ.md CURLINFO_RTSP_CSEQ_RECV.md CURLINFO_RTSP_SERVER_CSEQ.md CURLINFO_RTSP_SESSION_ID.md CURLINFO_SCHEME.md CURLINFO_SIZE_DELIVERED.md CURLINFO_SIZE_DOWNLOAD.md CURLINFO_SIZE_DOWNLOAD_T.md CURLINFO_SIZE_UPLOAD.md CURLINFO_SIZE_UPLOAD_T.md CURLINFO_SPEED_DOWNLOAD.md CURLINFO_SPEED_DOWNLOAD_T.md CURLINFO_SPEED_UPLOAD.md CURLINFO_SPEED_UPLOAD_T.md CURLINFO_SSL_ENGINES.md CURLINFO_SSL_VERIFYRESULT.md CURLINFO_STARTTRANSFER_TIME.md CURLINFO_STARTTRANSFER_TIME_T.md CURLINFO_TLS_SESSION.md CURLINFO_TLS_SSL_PTR.md CURLINFO_TOTAL_TIME.md CURLINFO_TOTAL_TIME_T.md CURLINFO_USED_PROXY.md CURLINFO_XFER_ID.md CURLMINFO_XFERS_ADDED.md CURLMINFO_XFERS_CURRENT.md CURLMINFO_XFERS_DONE.md CURLMINFO_XFERS_PENDING.md CURLMINFO_XFERS_RUNNING.md CURLMOPT_CHUNK_LENGTH_PENALTY_SIZE.md CURLMOPT_CONTENT_LENGTH_PENALTY_SIZE.md CURLMOPT_MAXCONNECTS.md CURLMOPT_MAX_CONCURRENT_STREAMS.md CURLMOPT_MAX_HOST_CONNECTIONS.md CURLMOPT_MAX_PIPELINE_LENGTH.md CURLMOPT_MAX_TOTAL_CONNECTIONS.md CURLMOPT_NETWORK_CHANGED.md CURLMOPT_NOTIFYDATA.md CURLMOPT_NOTIFYFUNCTION.md CURLMOPT_PIPELINING.md CURLMOPT_PIPELINING_SERVER_BL.md CURLMOPT_PIPELINING_SITE_BL.md CURLMOPT_PUSHDATA.md CURLMOPT_PUSHFUNCTION.md CURLMOPT_QUICK_EXIT.md CURLMOPT_RESOLVE_THREADS_MAX.md CURLMOPT_SOCKETDATA.md CURLMOPT_SOCKETFUNCTION.md CURLMOPT_TIMERDATA.md CURLMOPT_TIMERFUNCTION.md CURLOPT_ABSTRACT_UNIX_SOCKET.md CURLOPT_ACCEPTTIMEOUT_MS.md CURLOPT_ACCEPT_ENCODING.md CURLOPT_ADDRESS_SCOPE.md CURLOPT_ALTSVC.md CURLOPT_ALTSVC_CTRL.md CURLOPT_APPEND.md CURLOPT_AUTOREFERER.md CURLOPT_AWS_SIGV4.md CURLOPT_BUFFERSIZE.md CURLOPT_CAINFO.md CURLOPT_CAINFO_BLOB.md CURLOPT_CAPATH.md CURLOPT_CA_CACHE_TIMEOUT.md CURLOPT_CERTINFO.md CURLOPT_CHUNK_BGN_FUNCTION.md CURLOPT_CHUNK_DATA.md CURLOPT_CHUNK_END_FUNCTION.md CURLOPT_CLOSESOCKETDATA.md CURLOPT_CLOSESOCKETFUNCTION.md CURLOPT_CONNECTTIMEOUT.md CURLOPT_CONNECTTIMEOUT_MS.md CURLOPT_CONNECT_ONLY.md CURLOPT_CONNECT_TO.md CURLOPT_CONV_FROM_NETWORK_FUNCTION.md CURLOPT_CONV_FROM_UTF8_FUNCTION.md CURLOPT_CONV_TO_NETWORK_FUNCTION.md CURLOPT_COOKIE.md CURLOPT_COOKIEFILE.md CURLOPT_COOKIEJAR.md CURLOPT_COOKIELIST.md CURLOPT_COOKIESESSION.md CURLOPT_COPYPOSTFIELDS.md CURLOPT_CRLF.md CURLOPT_CRLFILE.md CURLOPT_CURLU.md CURLOPT_CUSTOMREQUEST.md CURLOPT_DEBUGDATA.md CURLOPT_DEBUGFUNCTION.md CURLOPT_DEFAULT_PROTOCOL.md CURLOPT_DIRLISTONLY.md CURLOPT_DISALLOW_USERNAME_IN_URL.md CURLOPT_DNS_CACHE_TIMEOUT.md CURLOPT_DNS_INTERFACE.md CURLOPT_DNS_LOCAL_IP4.md CURLOPT_DNS_LOCAL_IP6.md CURLOPT_DNS_SERVERS.md CURLOPT_DNS_SHUFFLE_ADDRESSES.md CURLOPT_DNS_USE_GLOBAL_CACHE.md CURLOPT_DOH_SSL_VERIFYHOST.md CURLOPT_DOH_SSL_VERIFYPEER.md CURLOPT_DOH_SSL_VERIFYSTATUS.md CURLOPT_DOH_URL.md CURLOPT_ECH.md CURLOPT_EGDSOCKET.md CURLOPT_ERRORBUFFER.md CURLOPT_EXPECT_100_TIMEOUT_MS.md CURLOPT_FAILONERROR.md CURLOPT_FILETIME.md CURLOPT_FNMATCH_DATA.md CURLOPT_FNMATCH_FUNCTION.md CURLOPT_FOLLOWLOCATION.md CURLOPT_FORBID_REUSE.md CURLOPT_FRESH_CONNECT.md CURLOPT_FTPPORT.md CURLOPT_FTPSSLAUTH.md CURLOPT_FTP_ACCOUNT.md CURLOPT_FTP_ALTERNATIVE_TO_USER.md CURLOPT_FTP_CREATE_MISSING_DIRS.md CURLOPT_FTP_FILEMETHOD.md CURLOPT_FTP_SKIP_PASV_IP.md CURLOPT_FTP_SSL_CCC.md CURLOPT_FTP_USE_EPRT.md CURLOPT_FTP_USE_EPSV.md CURLOPT_FTP_USE_PRET.md CURLOPT_GSSAPI_DELEGATION.md CURLOPT_HAPPY_EYEBALLS_TIMEOUT_MS.md CURLOPT_HAPROXYPROTOCOL.md CURLOPT_HAPROXY_CLIENT_IP.md CURLOPT_HEADER.md CURLOPT_HEADERDATA.md CURLOPT_HEADERFUNCTION.md CURLOPT_HEADEROPT.md CURLOPT_HSTS.md CURLOPT_HSTSREADDATA.md CURLOPT_HSTSREADFUNCTION.md CURLOPT_HSTSWRITEDATA.md CURLOPT_HSTSWRITEFUNCTION.md CURLOPT_HSTS_CTRL.md CURLOPT_HTTP09_ALLOWED.md CURLOPT_HTTP200ALIASES.md CURLOPT_HTTPAUTH.md CURLOPT_HTTPGET.md CURLOPT_HTTPHEADER.md CURLOPT_HTTPPOST.md CURLOPT_HTTPPROXYTUNNEL.md CURLOPT_HTTP_CONTENT_DECODING.md CURLOPT_HTTP_TRANSFER_DECODING.md CURLOPT_HTTP_VERSION.md CURLOPT_IGNORE_CONTENT_LENGTH.md CURLOPT_INFILESIZE.md CURLOPT_INFILESIZE_LARGE.md CURLOPT_INTERFACE.md CURLOPT_INTERLEAVEDATA.md CURLOPT_INTERLEAVEFUNCTION.md CURLOPT_IOCTLDATA.md CURLOPT_IOCTLFUNCTION.md CURLOPT_IPRESOLVE.md CURLOPT_ISSUERCERT.md CURLOPT_ISSUERCERT_BLOB.md CURLOPT_KEEP_SENDING_ON_ERROR.md CURLOPT_KEYPASSWD.md CURLOPT_KRBLEVEL.md CURLOPT_LOCALPORT.md CURLOPT_LOCALPORTRANGE.md CURLOPT_LOGIN_OPTIONS.md CURLOPT_LOW_SPEED_LIMIT.md CURLOPT_LOW_SPEED_TIME.md CURLOPT_MAIL_AUTH.md CURLOPT_MAIL_FROM.md CURLOPT_MAIL_RCPT.md CURLOPT_MAIL_RCPT_ALLOWFAILS.md CURLOPT_MAXAGE_CONN.md CURLOPT_MAXCONNECTS.md CURLOPT_MAXFILESIZE.md CURLOPT_MAXFILESIZE_LARGE.md CURLOPT_MAXLIFETIME_CONN.md CURLOPT_MAXREDIRS.md CURLOPT_MAX_RECV_SPEED_LARGE.md CURLOPT_MAX_SEND_SPEED_LARGE.md CURLOPT_MIMEPOST.md CURLOPT_MIME_OPTIONS.md CURLOPT_NETRC.md CURLOPT_NETRC_FILE.md CURLOPT_NEW_DIRECTORY_PERMS.md CURLOPT_NEW_FILE_PERMS.md CURLOPT_NOBODY.md CURLOPT_NOPROGRESS.md CURLOPT_NOPROXY.md CURLOPT_NOSIGNAL.md CURLOPT_OPENSOCKETDATA.md CURLOPT_OPENSOCKETFUNCTION.md CURLOPT_PASSWORD.md CURLOPT_PATH_AS_IS.md CURLOPT_PINNEDPUBLICKEY.md CURLOPT_PIPEWAIT.md CURLOPT_PORT.md CURLOPT_POST.md CURLOPT_POSTFIELDS.md CURLOPT_POSTFIELDSIZE.md CURLOPT_POSTFIELDSIZE_LARGE.md CURLOPT_POSTQUOTE.md CURLOPT_POSTREDIR.md CURLOPT_PREQUOTE.md CURLOPT_PREREQDATA.md CURLOPT_PREREQFUNCTION.md CURLOPT_PRE_PROXY.md CURLOPT_PRIVATE.md CURLOPT_PROGRESSDATA.md CURLOPT_PROGRESSFUNCTION.md CURLOPT_PROTOCOLS.md CURLOPT_PROTOCOLS_STR.md CURLOPT_PROXY.md CURLOPT_PROXYAUTH.md CURLOPT_PROXYHEADER.md CURLOPT_PROXYPASSWORD.md CURLOPT_PROXYPORT.md CURLOPT_PROXYTYPE.md CURLOPT_PROXYUSERNAME.md CURLOPT_PROXYUSERPWD.md CURLOPT_PROXY_CAINFO.md CURLOPT_PROXY_CAINFO_BLOB.md CURLOPT_PROXY_CAPATH.md CURLOPT_PROXY_CRLFILE.md CURLOPT_PROXY_ISSUERCERT.md CURLOPT_PROXY_ISSUERCERT_BLOB.md CURLOPT_PROXY_KEYPASSWD.md CURLOPT_PROXY_PINNEDPUBLICKEY.md CURLOPT_PROXY_SERVICE_NAME.md CURLOPT_PROXY_SSLCERT.md CURLOPT_PROXY_SSLCERTTYPE.md CURLOPT_PROXY_SSLCERT_BLOB.md CURLOPT_PROXY_SSLKEY.md CURLOPT_PROXY_SSLKEYTYPE.md CURLOPT_PROXY_SSLKEY_BLOB.md CURLOPT_PROXY_SSLVERSION.md CURLOPT_PROXY_SSL_CIPHER_LIST.md CURLOPT_PROXY_SSL_OPTIONS.md CURLOPT_PROXY_SSL_VERIFYHOST.md CURLOPT_PROXY_SSL_VERIFYPEER.md CURLOPT_PROXY_TLS13_CIPHERS.md CURLOPT_PROXY_TLSAUTH_PASSWORD.md CURLOPT_PROXY_TLSAUTH_TYPE.md CURLOPT_PROXY_TLSAUTH_USERNAME.md CURLOPT_PROXY_TRANSFER_MODE.md CURLOPT_PUT.md CURLOPT_QUICK_EXIT.md CURLOPT_QUOTE.md CURLOPT_RANDOM_FILE.md CURLOPT_RANGE.md CURLOPT_READDATA.md CURLOPT_READFUNCTION.md CURLOPT_REDIR_PROTOCOLS.md CURLOPT_REDIR_PROTOCOLS_STR.md CURLOPT_REFERER.md CURLOPT_REQUEST_TARGET.md CURLOPT_RESOLVE.md CURLOPT_RESOLVER_START_DATA.md CURLOPT_RESOLVER_START_FUNCTION.md CURLOPT_RESUME_FROM.md CURLOPT_RESUME_FROM_LARGE.md CURLOPT_RTSP_CLIENT_CSEQ.md CURLOPT_RTSP_REQUEST.md CURLOPT_RTSP_SERVER_CSEQ.md CURLOPT_RTSP_SESSION_ID.md CURLOPT_RTSP_STREAM_URI.md CURLOPT_RTSP_TRANSPORT.md CURLOPT_SASL_AUTHZID.md CURLOPT_SASL_IR.md CURLOPT_SEEKDATA.md CURLOPT_SEEKFUNCTION.md CURLOPT_SERVER_RESPONSE_TIMEOUT.md CURLOPT_SERVER_RESPONSE_TIMEOUT_MS.md CURLOPT_SERVICE_NAME.md CURLOPT_SHARE.md CURLOPT_SOCKOPTDATA.md CURLOPT_SOCKOPTFUNCTION.md CURLOPT_SOCKS5_AUTH.md CURLOPT_SOCKS5_GSSAPI_NEC.md CURLOPT_SOCKS5_GSSAPI_SERVICE.md CURLOPT_SSH_AUTH_TYPES.md CURLOPT_SSH_COMPRESSION.md CURLOPT_SSH_HOSTKEYDATA.md CURLOPT_SSH_HOSTKEYFUNCTION.md CURLOPT_SSH_HOST_PUBLIC_KEY_MD5.md CURLOPT_SSH_HOST_PUBLIC_KEY_SHA256.md CURLOPT_SSH_KEYDATA.md CURLOPT_SSH_KEYFUNCTION.md CURLOPT_SSH_KNOWNHOSTS.md CURLOPT_SSH_PRIVATE_KEYFILE.md CURLOPT_SSH_PUBLIC_KEYFILE.md CURLOPT_SSLCERT.md CURLOPT_SSLCERTTYPE.md CURLOPT_SSLCERT_BLOB.md CURLOPT_SSLENGINE.md CURLOPT_SSLENGINE_DEFAULT.md CURLOPT_SSLKEY.md CURLOPT_SSLKEYTYPE.md CURLOPT_SSLKEY_BLOB.md CURLOPT_SSLVERSION.md CURLOPT_SSL_CIPHER_LIST.md CURLOPT_SSL_CTX_DATA.md CURLOPT_SSL_CTX_FUNCTION.md CURLOPT_SSL_EC_CURVES.md CURLOPT_SSL_ENABLE_ALPN.md CURLOPT_SSL_ENABLE_NPN.md CURLOPT_SSL_FALSESTART.md CURLOPT_SSL_OPTIONS.md CURLOPT_SSL_SESSIONID_CACHE.md CURLOPT_SSL_SIGNATURE_ALGORITHMS.md CURLOPT_SSL_VERIFYHOST.md CURLOPT_SSL_VERIFYPEER.md CURLOPT_SSL_VERIFYSTATUS.md CURLOPT_STDERR.md CURLOPT_STREAM_DEPENDS.md CURLOPT_STREAM_DEPENDS_E.md CURLOPT_STREAM_WEIGHT.md CURLOPT_SUPPRESS_CONNECT_HEADERS.md CURLOPT_TCP_FASTOPEN.md CURLOPT_TCP_KEEPALIVE.md CURLOPT_TCP_KEEPCNT.md CURLOPT_TCP_KEEPIDLE.md CURLOPT_TCP_KEEPINTVL.md CURLOPT_TCP_NODELAY.md CURLOPT_TELNETOPTIONS.md CURLOPT_TFTP_BLKSIZE.md CURLOPT_TFTP_NO_OPTIONS.md CURLOPT_TIMECONDITION.md CURLOPT_TIMEOUT.md CURLOPT_TIMEOUT_MS.md CURLOPT_TIMEVALUE.md CURLOPT_TIMEVALUE_LARGE.md CURLOPT_TLS13_CIPHERS.md CURLOPT_TLSAUTH_PASSWORD.md CURLOPT_TLSAUTH_TYPE.md CURLOPT_TLSAUTH_USERNAME.md CURLOPT_TRAILERDATA.md CURLOPT_TRAILERFUNCTION.md CURLOPT_TRANSFERTEXT.md CURLOPT_TRANSFER_ENCODING.md CURLOPT_UNIX_SOCKET_PATH.md CURLOPT_UNRESTRICTED_AUTH.md CURLOPT_UPKEEP_INTERVAL_MS.md CURLOPT_UPLOAD.md CURLOPT_UPLOAD_BUFFERSIZE.md CURLOPT_UPLOAD_FLAGS.md CURLOPT_URL.md CURLOPT_USERAGENT.md CURLOPT_USERNAME.md CURLOPT_USERPWD.md CURLOPT_USE_SSL.md CURLOPT_VERBOSE.md CURLOPT_WILDCARDMATCH.md CURLOPT_WRITEDATA.md CURLOPT_WRITEFUNCTION.md CURLOPT_WS_OPTIONS.md CURLOPT_XFERINFODATA.md CURLOPT_XFERINFOFUNCTION.md CURLOPT_XOAUTH2_BEARER.md CURLSHOPT_LOCKFUNC.md CURLSHOPT_SHARE.md CURLSHOPT_UNLOCKFUNC.md CURLSHOPT_UNSHARE.md CURLSHOPT_USERDATA.md Makefile.am Makefile.inc
.gitignore ABI.md CMakeLists.txt Makefile.am Makefile.inc curl_easy_cleanup.md curl_easy_duphandle.md curl_easy_escape.md curl_easy_getinfo.md curl_easy_header.md curl_easy_init.md curl_easy_nextheader.md curl_easy_option_by_id.md curl_easy_option_by_name.md curl_easy_option_next.md curl_easy_pause.md curl_easy_perform.md curl_easy_recv.md curl_easy_reset.md curl_easy_send.md curl_easy_setopt.md curl_easy_ssls_export.md curl_easy_ssls_import.md curl_easy_strerror.md curl_easy_unescape.md curl_easy_upkeep.md curl_escape.md curl_formadd.md curl_formfree.md curl_formget.md curl_free.md curl_getdate.md curl_getenv.md curl_global_cleanup.md curl_global_init.md curl_global_init_mem.md curl_global_sslset.md curl_global_trace.md curl_mime_addpart.md curl_mime_data.md curl_mime_data_cb.md curl_mime_encoder.md curl_mime_filedata.md curl_mime_filename.md curl_mime_free.md curl_mime_headers.md curl_mime_init.md curl_mime_name.md curl_mime_subparts.md curl_mime_type.md curl_mprintf.md curl_multi_add_handle.md curl_multi_assign.md curl_multi_cleanup.md curl_multi_fdset.md curl_multi_get_handles.md curl_multi_get_offt.md curl_multi_info_read.md curl_multi_init.md curl_multi_notify_disable.md curl_multi_notify_enable.md curl_multi_perform.md curl_multi_poll.md curl_multi_remove_handle.md curl_multi_setopt.md curl_multi_socket.md curl_multi_socket_action.md curl_multi_socket_all.md curl_multi_strerror.md curl_multi_timeout.md curl_multi_wait.md curl_multi_waitfds.md curl_multi_wakeup.md curl_pushheader_byname.md curl_pushheader_bynum.md curl_share_cleanup.md curl_share_init.md curl_share_setopt.md curl_share_strerror.md curl_slist_append.md curl_slist_free_all.md curl_strequal.md curl_strnequal.md curl_unescape.md curl_url.md curl_url_cleanup.md curl_url_dup.md curl_url_get.md curl_url_set.md curl_url_strerror.md curl_version.md curl_version_info.md curl_ws_meta.md curl_ws_recv.md curl_ws_send.md curl_ws_start_frame.md libcurl-easy.md libcurl-env-dbg.md libcurl-env.md libcurl-errors.md libcurl-multi.md libcurl-security.md libcurl-share.md libcurl-thread.md libcurl-tutorial.md libcurl-url.md libcurl-ws.md libcurl.m4 libcurl.md mksymbolsmanpage.pl symbols-in-versions symbols.pl
tests CI.md FILEFORMAT.md HTTP.md TEST-SUITE.md
.gitignore ALTSVC.md BINDINGS.md BUG-BOUNTY.md BUGS.md CIPHERS-TLS12.md CIPHERS.md CMakeLists.txt CODE_OF_CONDUCT.md CODE_REVIEW.md CONTRIBUTE.md CURL-DISABLE.md CURLDOWN.md DEPRECATE.md DISTROS.md EARLY-RELEASE.md ECH.md EXPERIMENTAL.md FAQ.md FEATURES.md GOVERNANCE.md HELP-US.md HISTORY.md HSTS.md HTTP-COOKIES.md HTTP3.md HTTPSRR.md INFRASTRUCTURE.md INSTALL-CMAKE.md INSTALL.md INTERNALS.md IPFS.md KNOWN_BUGS.md KNOWN_RISKS.md MAIL-ETIQUETTE.md MANUAL.md Makefile.am README.md RELEASE-PROCEDURE.md ROADMAP.md RUSTLS.md SECURITY-ADVISORY.md SPONSORS.md SSL-PROBLEMS.md SSLCERTS.md THANKS THANKS-filter TODO.md TheArtOfHttpScripting.md URL-SYNTAX.md VERIFY.md VERSIONS.md VULN-DISCLOSURE-POLICY.md curl-config.md mk-ca-bundle.md options-in-versions runtests.md testcurl.md wcurl.md
include
curl Makefile.am curl.h curlver.h easy.h header.h mprintf.h multi.h options.h stdcheaders.h system.h typecheck-gcc.h urlapi.h websockets.h
Makefile.am README.md
lib
curlx base64.c base64.h basename.c basename.h dynbuf.c dynbuf.h fopen.c fopen.h inet_ntop.c inet_ntop.h inet_pton.c inet_pton.h multibyte.c multibyte.h nonblock.c nonblock.h snprintf.c snprintf.h strcopy.c strcopy.h strdup.c strdup.h strerr.c strerr.h strparse.c strparse.h timediff.c timediff.h timeval.c timeval.h version_win32.c version_win32.h wait.c wait.h warnless.c warnless.h winapi.c winapi.h
vauth cleartext.c cram.c digest.c digest.h digest_sspi.c gsasl.c krb5_gssapi.c krb5_sspi.c ntlm.c ntlm_sspi.c oauth2.c spnego_gssapi.c spnego_sspi.c vauth.c vauth.h
vquic curl_ngtcp2.c curl_ngtcp2.h curl_quiche.c curl_quiche.h vquic-tls.c vquic-tls.h vquic.c vquic.h vquic_int.h
vssh libssh.c libssh2.c ssh.h vssh.c vssh.h
vtls apple.c apple.h cipher_suite.c cipher_suite.h gtls.c gtls.h hostcheck.c hostcheck.h keylog.c keylog.h mbedtls.c mbedtls.h openssl.c openssl.h rustls.c rustls.h schannel.c schannel.h schannel_int.h schannel_verify.c vtls.c vtls.h vtls_int.h vtls_scache.c vtls_scache.h vtls_spack.c vtls_spack.h wolfssl.c wolfssl.h x509asn1.c x509asn1.h
.gitignore CMakeLists.txt Makefile.am Makefile.inc Makefile.soname altsvc.c altsvc.h amigaos.c amigaos.h arpa_telnet.h asyn-ares.c asyn-base.c asyn-thrdd.c asyn.h bufq.c bufq.h bufref.c bufref.h cf-dns.c cf-dns.h cf-h1-proxy.c cf-h1-proxy.h cf-h2-proxy.c cf-h2-proxy.h cf-haproxy.c cf-haproxy.h cf-https-connect.c cf-https-connect.h cf-ip-happy.c cf-ip-happy.h cf-socket.c cf-socket.h cfilters.c cfilters.h config-mac.h config-os400.h config-riscos.h config-win32.h conncache.c conncache.h connect.c connect.h content_encoding.c content_encoding.h cookie.c cookie.h creds.c creds.h cshutdn.c cshutdn.h curl_addrinfo.c curl_addrinfo.h curl_config-cmake.h.in curl_ctype.h curl_endian.c curl_endian.h curl_fnmatch.c curl_fnmatch.h curl_fopen.c curl_fopen.h curl_get_line.c curl_get_line.h curl_gethostname.c curl_gethostname.h curl_gssapi.c curl_gssapi.h curl_hmac.h curl_ldap.h curl_md4.h curl_md5.h curl_memrchr.c curl_memrchr.h curl_ntlm_core.c curl_ntlm_core.h curl_printf.h curl_range.c curl_range.h curl_sasl.c curl_sasl.h curl_setup.h curl_sha256.h curl_sha512_256.c curl_sha512_256.h curl_share.c curl_share.h curl_sspi.c curl_sspi.h curl_threads.c curl_threads.h curl_trc.c curl_trc.h cw-out.c cw-out.h cw-pause.c cw-pause.h dict.c dict.h dllmain.c dnscache.c dnscache.h doh.c doh.h dynhds.c dynhds.h easy.c easy_lock.h easygetopt.c easyif.h easyoptions.c easyoptions.h escape.c escape.h fake_addrinfo.c fake_addrinfo.h file.c file.h fileinfo.c fileinfo.h formdata.c formdata.h ftp-int.h ftp.c ftp.h ftplistparser.c ftplistparser.h functypes.h getenv.c getinfo.c getinfo.h gopher.c gopher.h hash.c hash.h headers.c headers.h hmac.c hostip.c hostip.h hostip4.c hostip6.c hsts.c hsts.h http.c http.h http1.c http1.h http2.c http2.h http_aws_sigv4.c http_aws_sigv4.h http_chunks.c http_chunks.h http_digest.c http_digest.h http_negotiate.c http_negotiate.h http_ntlm.c http_ntlm.h http_proxy.c http_proxy.h httpsrr.c httpsrr.h idn.c idn.h if2ip.c if2ip.h imap.c imap.h ldap.c libcurl.def libcurl.rc libcurl.vers.in llist.c llist.h macos.c macos.h md4.c md5.c memdebug.c mime.c mime.h mprintf.c mqtt.c mqtt.h multi.c multi_ev.c multi_ev.h multi_ntfy.c multi_ntfy.h multihandle.h multiif.h netrc.c netrc.h noproxy.c noproxy.h openldap.c optiontable.pl parsedate.c parsedate.h peer.c peer.h pingpong.c pingpong.h pop3.c pop3.h progress.c progress.h protocol.c protocol.h psl.c psl.h rand.c rand.h ratelimit.c ratelimit.h request.c request.h rtsp.c rtsp.h select.c select.h sendf.c sendf.h setopt.c setopt.h setup-os400.h setup-vms.h setup-win32.h sha256.c sigpipe.h slist.c slist.h smb.c smb.h smtp.c smtp.h sockaddr.h socketpair.c socketpair.h socks.c socks.h socks_gssapi.c socks_sspi.c splay.c splay.h strcase.c strcase.h strequal.c strerror.c strerror.h system_win32.c system_win32.h telnet.c telnet.h tftp.c tftp.h thrdpool.c thrdpool.h thrdqueue.c thrdqueue.h transfer.c transfer.h uint-bset.c uint-bset.h uint-hash.c uint-hash.h uint-spbset.c uint-spbset.h uint-table.c uint-table.h url.c url.h urlapi-int.h urlapi.c urldata.h version.c ws.c ws.h
m4 .gitignore curl-amissl.m4 curl-apple-sectrust.m4 curl-compilers.m4 curl-confopts.m4 curl-functions.m4 curl-gnutls.m4 curl-mbedtls.m4 curl-openssl.m4 curl-override.m4 curl-reentrant.m4 curl-rustls.m4 curl-schannel.m4 curl-sysconfig.m4 curl-wolfssl.m4 xc-am-iface.m4 xc-cc-check.m4 xc-lt-iface.m4 xc-val-flgs.m4 zz40-xc-ovr.m4 zz50-xc-ovr.m4
projects
OS400
rpg-examples HEADERAPI HTTPPOST INMEMORY SIMPLE1 SIMPLE2 SMTPSRCMBR
.checksrc README.OS400 ccsidcurl.c ccsidcurl.h config400.default curl.cmd curl.inc.in curlcl.c curlmain.c initscript.sh make-docs.sh make-include.sh make-lib.sh make-src.sh make-tests.sh makefile.sh os400sys.c os400sys.h
Windows
tmpl .gitattributes README.txt curl-all.sln curl.sln curl.vcxproj curl.vcxproj.filters libcurl.sln libcurl.vcxproj libcurl.vcxproj.filters
.gitignore README.md generate.bat
vms Makefile.am backup_gnv_curl_src.com build_curl-config_script.com build_gnv_curl.com build_gnv_curl_pcsi_desc.com build_gnv_curl_pcsi_text.com build_gnv_curl_release_notes.com build_libcurl_pc.com build_vms.com clean_gnv_curl.com compare_curl_source.com config_h.com curl_crtl_init.c curl_gnv_build_steps.txt curl_release_note_start.txt curl_startup.com curlmsg.h curlmsg.msg curlmsg.sdl curlmsg_vms.h generate_config_vms_h_curl.com generate_vax_transfer.com gnv_conftest.c_first gnv_curl_configure.sh gnv_libcurl_symbols.opt gnv_link_curl.com macro32_exactcase.patch make_gnv_curl_install.sh make_pcsi_curl_kit_name.com pcsi_gnv_curl_file_list.txt pcsi_product_gnv_curl.com readme report_openssl_version.c setup_gnv_curl_build.com stage_curl_install.com vms_eco_level.h
Makefile.am README.md
scripts .checksrc CMakeLists.txt Makefile.am badwords badwords-all badwords.txt cd2cd cd2nroff cdall checksrc-all.pl checksrc.pl cmakelint.sh completion.pl contributors.sh contrithanks.sh coverage.sh delta dmaketgz extract-unit-protos firefox-db2pem.sh installcheck.sh maketgz managen mdlinkcheck mk-ca-bundle.pl mk-unity.pl nroff2cd perlcheck.sh pythonlint.sh randdisable release-notes.pl release-tools.sh schemetable.c singleuse.pl spacecheck.pl top-complexity top-length verify-release wcurl
src
toolx tool_time.c tool_time.h
.checksrc .gitignore CMakeLists.txt Makefile.am Makefile.inc config2setopts.c config2setopts.h curl.rc curlinfo.c mk-file-embed.pl mkhelp.pl slist_wc.c slist_wc.h terminal.c terminal.h tool_cb_dbg.c tool_cb_dbg.h tool_cb_hdr.c tool_cb_hdr.h tool_cb_prg.c tool_cb_prg.h tool_cb_rea.c tool_cb_rea.h tool_cb_see.c tool_cb_see.h tool_cb_soc.c tool_cb_soc.h tool_cb_wrt.c tool_cb_wrt.h tool_cfgable.c tool_cfgable.h tool_dirhie.c tool_dirhie.h tool_doswin.c tool_doswin.h tool_easysrc.c tool_easysrc.h tool_filetime.c tool_filetime.h tool_findfile.c tool_findfile.h tool_formparse.c tool_formparse.h tool_getparam.c tool_getparam.h tool_getpass.c tool_getpass.h tool_help.c tool_help.h tool_helpers.c tool_helpers.h tool_hugehelp.h tool_ipfs.c tool_ipfs.h tool_libinfo.c tool_libinfo.h tool_listhelp.c tool_main.c tool_main.h tool_msgs.c tool_msgs.h tool_operate.c tool_operate.h tool_operhlp.c tool_operhlp.h tool_paramhlp.c tool_paramhlp.h tool_parsecfg.c tool_parsecfg.h tool_progress.c tool_progress.h tool_sdecls.h tool_setopt.c tool_setopt.h tool_setup.h tool_ssls.c tool_ssls.h tool_stderr.c tool_stderr.h tool_urlglob.c tool_urlglob.h tool_util.c tool_util.h tool_version.h tool_vms.c tool_vms.h tool_writeout.c tool_writeout.h tool_writeout_json.c tool_writeout_json.h tool_xattr.c tool_xattr.h var.c var.h
tests
certs .gitignore CMakeLists.txt Makefile.am Makefile.inc genserv.pl srp-verifier-conf srp-verifier-db test-ca.cnf test-ca.prm test-client-cert.prm test-client-eku-only.prm test-localhost-san-first.prm test-localhost-san-last.prm test-localhost.nn.prm test-localhost.prm test-localhost0h.prm
cmake CMakeLists.txt test.c test.cpp test.sh
data .gitignore DISABLED Makefile.am data-xml1 data1400.c data1401.c data1402.c data1403.c data1404.c data1405.c data1406.c data1407.c data1420.c data1461.txt data1463.txt data1465.c data1481.c data1705-1.md data1705-2.md data1705-3.md data1705-4.md data1705-stdout.1 data1706-1.md data1706-2.md data1706-3.md data1706-4.md data1706-stdout.txt data320.html test1 test10 test100 test1000 test1001 test1002 test1003 test1004 test1005 test1006 test1007 test1008 test1009 test101 test1010 test1011 test1012 test1013 test1014 test1015 test1016 test1017 test1018 test1019 test102 test1020 test1021 test1022 test1023 test1024 test1025 test1026 test1027 test1028 test1029 test103 test1030 test1031 test1032 test1033 test1034 test1035 test1036 test1037 test1038 test1039 test104 test1040 test1041 test1042 test1043 test1044 test1045 test1046 test1047 test1048 test1049 test105 test1050 test1051 test1052 test1053 test1054 test1055 test1056 test1057 test1058 test1059 test106 test1060 test1061 test1062 test1063 test1064 test1065 test1066 test1067 test1068 test1069 test107 test1070 test1071 test1072 test1073 test1074 test1075 test1076 test1077 test1078 test1079 test108 test1080 test1081 test1082 test1083 test1084 test1085 test1086 test1087 test1088 test1089 test109 test1090 test1091 test1092 test1093 test1094 test1095 test1096 test1097 test1098 test1099 test11 test110 test1100 test1101 test1102 test1103 test1104 test1105 test1106 test1107 test1108 test1109 test111 test1110 test1111 test1112 test1113 test1114 test1115 test1116 test1117 test1118 test1119 test112 test1120 test1121 test1122 test1123 test1124 test1125 test1126 test1127 test1128 test1129 test113 test1130 test1131 test1132 test1133 test1134 test1135 test1136 test1137 test1138 test1139 test114 test1140 test1141 test1142 test1143 test1144 test1145 test1146 test1147 test1148 test1149 test115 test1150 test1151 test1152 test1153 test1154 test1155 test1156 test1157 test1158 test1159 test116 test1160 test1161 test1162 test1163 test1164 test1165 test1166 test1167 test1168 test1169 test117 test1170 test1171 test1172 test1173 test1174 test1175 test1176 test1177 test1178 test1179 test118 test1180 test1181 test1182 test1183 test1184 test1185 test1186 test1187 test1188 test1189 test119 test1190 test1191 test1192 test1193 test1194 test1195 test1196 test1197 test1198 test1199 test12 test120 test1200 test1201 test1202 test1203 test1204 test1205 test1206 test1207 test1208 test1209 test121 test1210 test1211 test1212 test1213 test1214 test1215 test1216 test1217 test1218 test1219 test122 test1220 test1221 test1222 test1223 test1224 test1225 test1226 test1227 test1228 test1229 test123 test1230 test1231 test1232 test1233 test1234 test1235 test1236 test1237 test1238 test1239 test124 test1240 test1241 test1242 test1243 test1244 test1245 test1246 test1247 test1248 test1249 test125 test1250 test1251 test1252 test1253 test1254 test1255 test1256 test1257 test1258 test1259 test126 test1260 test1261 test1262 test1263 test1264 test1265 test1266 test1267 test1268 test1269 test127 test1270 test1271 test1272 test1273 test1274 test1275 test1276 test1277 test1278 test1279 test128 test1280 test1281 test1282 test1283 test1284 test1285 test1286 test1287 test1288 test1289 test129 test1290 test1291 test1292 test1293 test1294 test1295 test1296 test1297 test1298 test1299 test13 test130 test1300 test1301 test1302 test1303 test1304 test1305 test1306 test1307 test1308 test1309 test131 test1310 test1311 test1312 test1313 test1314 test1315 test1316 test1317 test1318 test1319 test132 test1320 test1321 test1322 test1323 test1324 test1325 test1326 test1327 test1328 test1329 test133 test1330 test1331 test1332 test1333 test1334 test1335 test1336 test1337 test1338 test1339 test134 test1340 test1341 test1342 test1343 test1344 test1345 test1346 test1347 test1348 test1349 test135 test1350 test1351 test1352 test1353 test1354 test1355 test1356 test1357 test1358 test1359 test136 test1360 test1361 test1362 test1363 test1364 test1365 test1366 test1367 test1368 test1369 test137 test1370 test1371 test1372 test1373 test1374 test1375 test1376 test1377 test1378 test1379 test138 test1380 test1381 test1382 test1383 test1384 test1385 test1386 test1387 test1388 test1389 test139 test1390 test1391 test1392 test1393 test1394 test1395 test1396 test1397 test1398 test1399 test14 test140 test1400 test1401 test1402 test1403 test1404 test1405 test1406 test1407 test1408 test1409 test141 test1410 test1411 test1412 test1413 test1414 test1415 test1416 test1417 test1418 test1419 test142 test1420 test1421 test1422 test1423 test1424 test1425 test1426 test1427 test1428 test1429 test143 test1430 test1431 test1432 test1433 test1434 test1435 test1436 test1437 test1438 test1439 test144 test1440 test1441 test1442 test1443 test1444 test1445 test1446 test1447 test1448 test1449 test145 test1450 test1451 test1452 test1453 test1454 test1455 test1456 test1457 test1458 test1459 test146 test1460 test1461 test1462 test1463 test1464 test1465 test1466 test1467 test1468 test1469 test147 test1470 test1471 test1472 test1473 test1474 test1475 test1476 test1477 test1478 test1479 test148 test1480 test1481 test1482 test1483 test1484 test1485 test1486 test1487 test1488 test1489 test149 test1490 test1491 test1492 test1493 test1494 test1495 test1496 test1497 test1498 test1499 test15 test150 test1500 test1501 test1502 test1503 test1504 test1505 test1506 test1507 test1508 test1509 test151 test1510 test1511 test1512 test1513 test1514 test1515 test1516 test1517 test1518 test1519 test152 test1520 test1521 test1522 test1523 test1524 test1525 test1526 test1527 test1528 test1529 test153 test1530 test1531 test1532 test1533 test1534 test1535 test1536 test1537 test1538 test1539 test154 test1540 test1541 test1542 test1543 test1544 test1545 test1546 test1547 test1548 test1549 test155 test1550 test1551 test1552 test1553 test1554 test1555 test1556 test1557 test1558 test1559 test156 test1560 test1561 test1562 test1563 test1564 test1565 test1566 test1567 test1568 test1569 test157 test1570 test1571 test1572 test1573 test1574 test1575 test1576 test1577 test1578 test1579 test158 test1580 test1581 test1582 test1583 test1584 test1585 test1586 test1587 test1588 test1589 test159 test1590 test1591 test1592 test1593 test1594 test1595 test1596 test1597 test1598 test1599 test16 test160 test1600 test1601 test1602 test1603 test1604 test1605 test1606 test1607 test1608 test1609 test161 test1610 test1611 test1612 test1613 test1614 test1615 test1616 test1617 test1618 test1619 test162 test1620 test1621 test1622 test1623 test1624 test1625 test1626 test1627 test1628 test1629 test163 test1630 test1631 test1632 test1633 test1634 test1635 test1636 test1637 test1638 test1639 test164 test1640 test1641 test1642 test1643 test1644 test1645 test165 test1650 test1651 test1652 test1653 test1654 test1655 test1656 test1657 test1658 test1659 test166 test1660 test1661 test1662 test1663 test1664 test1665 test1666 test1667 test1668 test1669 test167 test1670 test1671 test1672 test1673 test1674 test1675 test1676 test168 test1680 test1681 test1682 test1683 test1684 test1685 test169 test17 test170 test1700 test1701 test1702 test1703 test1704 test1705 test1706 test1707 test1708 test1709 test171 test1710 test1711 test1712 test1713 test1714 test1715 test172 test1720 test1721 test173 test174 test175 test176 test177 test178 test179 test18 test180 test1800 test1801 test1802 test181 test182 test183 test184 test1847 test1848 test1849 test185 test1850 test1851 test186 test187 test188 test189 test19 test190 test1900 test1901 test1902 test1903 test1904 test1905 test1906 test1907 test1908 test1909 test191 test1910 test1911 test1912 test1913 test1914 test1915 test1916 test1917 test1918 test1919 test192 test1920 test1921 test193 test1933 test1934 test1935 test1936 test1937 test1938 test1939 test194 test1940 test1941 test1942 test1943 test1944 test1945 test1946 test1947 test1948 test195 test1955 test1956 test1957 test1958 test1959 test196 test1960 test1964 test1965 test1966 test197 test1970 test1971 test1972 test1973 test1974 test1975 test1976 test1977 test1978 test1979 test198 test1980 test1981 test1982 test1983 test1984 test199 test2 test20 test200 test2000 test2001 test2002 test2003 test2004 test2005 test2006 test2007 test2008 test2009 test201 test2010 test2011 test2012 test2013 test2014 test202 test2023 test2024 test2025 test2026 test2027 test2028 test2029 test203 test2030 test2031 test2032 test2033 test2034 test2035 test2037 test2038 test2039 test204 test2040 test2041 test2042 test2043 test2044 test2045 test2046 test2047 test2048 test2049 test205 test2050 test2051 test2052 test2053 test2054 test2055 test2056 test2057 test2058 test2059 test206 test2060 test2061 test2062 test2063 test2064 test2065 test2066 test2067 test2068 test2069 test207 test2070 test2071 test2072 test2073 test2074 test2075 test2076 test2077 test2078 test2079 test208 test2080 test2081 test2082 test2083 test2084 test2085 test2086 test2087 test2088 test2089 test209 test2090 test2091 test2092 test21 test210 test2100 test2101 test2102 test2103 test2104 test211 test212 test213 test214 test215 test216 test217 test218 test219 test22 test220 test2200 test2201 test2202 test2203 test2204 test2205 test2206 test2207 test221 test222 test223 test224 test225 test226 test227 test228 test229 test23 test230 test2300 test2301 test2302 test2303 test2304 test2306 test2307 test2308 test2309 test231 test232 test233 test234 test235 test236 test237 test238 test239 test24 test240 test2400 test2401 test2402 test2403 test2404 test2405 test2406 test2407 test2408 test2409 test241 test2410 test2411 test242 test243 test244 test245 test246 test247 test248 test249 test25 test250 test2500 test2501 test2502 test2503 test2504 test2505 test2506 test251 test252 test253 test254 test255 test256 test257 test258 test259 test26 test260 test2600 test2601 test2602 test2603 test2604 test2605 test261 test262 test263 test264 test265 test266 test267 test268 test269 test27 test270 test2700 test2701 test2702 test2703 test2704 test2705 test2706 test2707 test2708 test2709 test271 test2710 test2711 test2712 test2713 test2714 test2715 test2716 test2717 test2718 test2719 test272 test2720 test2721 test2722 test2723 test273 test274 test275 test276 test277 test278 test279 test28 test280 test281 test282 test283 test284 test285 test286 test287 test288 test289 test29 test290 test291 test292 test293 test294 test295 test296 test297 test298 test299 test3 test30 test300 test3000 test3001 test3002 test3003 test3004 test3005 test3006 test3007 test3008 test3009 test301 test3010 test3011 test3012 test3013 test3014 test3015 test3016 test3017 test3018 test3019 test302 test3020 test3021 test3022 test3023 test3024 test3025 test3026 test3027 test3028 test3029 test303 test3030 test3031 test3032 test3033 test3034 test3035 test3036 test304 test305 test306 test307 test308 test309 test31 test310 test3100 test3101 test3102 test3103 test3104 test3105 test3106 test311 test312 test313 test314 test315 test316 test317 test318 test319 test32 test320 test3200 test3201 test3202 test3203 test3204 test3205 test3206 test3207 test3208 test3209 test321 test3210 test3211 test3212 test3213 test3214 test3215 test3216 test3217 test3218 test3219 test322 test3220 test323 test324 test325 test326 test327 test328 test329 test33 test330 test3300 test3301 test3302 test331 test332 test333 test334 test335 test336 test337 test338 test339 test34 test340 test341 test342 test343 test344 test345 test346 test347 test348 test349 test35 test350 test351 test352 test353 test354 test355 test356 test357 test358 test359 test36 test360 test361 test362 test363 test364 test365 test366 test367 test368 test369 test37 test370 test371 test372 test373 test374 test375 test376 test378 test379 test38 test380 test381 test383 test384 test385 test386 test387 test388 test389 test39 test390 test391 test392 test393 test394 test395 test396 test397 test398 test399 test4 test40 test400 test4000 test4001 test401 test402 test403 test404 test405 test406 test407 test408 test409 test41 test410 test411 test412 test413 test414 test415 test416 test417 test418 test419 test42 test420 test421 test422 test423 test424 test425 test426 test427 test428 test429 test43 test430 test431 test432 test433 test434 test435 test436 test437 test438 test439 test44 test440 test441 test442 test443 test444 test445 test446 test447 test448 test449 test45 test450 test451 test452 test453 test454 test455 test456 test457 test458 test459 test46 test460 test461 test462 test463 test467 test468 test469 test47 test470 test471 test472 test473 test474 test475 test476 test477 test478 test479 test48 test480 test481 test482 test483 test484 test485 test486 test487 test488 test489 test49 test490 test491 test492 test493 test494 test495 test496 test497 test498 test499 test5 test50 test500 test501 test502 test503 test504 test505 test506 test507 test508 test509 test51 test510 test511 test512 test513 test514 test515 test516 test517 test518 test519 test52 test520 test521 test522 test523 test524 test525 test526 test527 test528 test529 test53 test530 test531 test532 test533 test534 test535 test536 test537 test538 test539 test54 test540 test541 test542 test543 test544 test545 test546 test547 test548 test549 test55 test550 test551 test552 test553 test554 test555 test556 test557 test558 test559 test56 test560 test561 test562 test563 test564 test565 test566 test567 test568 test569 test57 test570 test571 test572 test573 test574 test575 test576 test577 test578 test579 test58 test580 test581 test582 test583 test584 test585 test586 test587 test588 test589 test59 test590 test591 test592 test593 test594 test595 test596 test597 test598 test599 test6 test60 test600 test601 test602 test603 test604 test605 test606 test607 test608 test609 test61 test610 test611 test612 test613 test614 test615 test616 test617 test618 test619 test62 test620 test621 test622 test623 test624 test625 test626 test627 test628 test629 test63 test630 test631 test632 test633 test634 test635 test636 test637 test638 test639 test64 test640 test641 test642 test643 test644 test645 test646 test647 test648 test649 test65 test650 test651 test652 test653 test654 test655 test656 test658 test659 test66 test660 test661 test662 test663 test664 test665 test666 test667 test668 test669 test67 test670 test671 test672 test673 test674 test675 test676 test677 test678 test679 test68 test680 test681 test682 test683 test684 test685 test686 test687 test688 test689 test69 test690 test691 test692 test693 test694 test695 test696 test697 test698 test699 test7 test70 test700 test701 test702 test703 test704 test705 test706 test707 test708 test709 test71 test710 test711 test712 test713 test714 test715 test716 test717 test718 test719 test72 test720 test721 test722 test723 test724 test725 test726 test727 test728 test729 test73 test730 test731 test732 test733 test734 test735 test736 test737 test738 test739 test74 test740 test741 test742 test743 test744 test745 test746 test747 test748 test749 test75 test750 test751 test752 test753 test754 test755 test756 test757 test758 test759 test76 test760 test761 test762 test763 test764 test765 test766 test767 test768 test769 test77 test770 test771 test772 test773 test774 test775 test776 test777 test778 test779 test78 test780 test781 test782 test783 test784 test785 test786 test787 test788 test789 test79 test790 test791 test792 test793 test794 test795 test796 test797 test798 test799 test8 test80 test800 test801 test802 test803 test804 test805 test806 test807 test808 test809 test81 test810 test811 test812 test813 test814 test815 test816 test817 test818 test819 test82 test820 test821 test822 test823 test824 test825 test826 test827 test828 test829 test83 test830 test831 test832 test833 test834 test835 test836 test837 test838 test839 test84 test840 test841 test842 test843 test844 test845 test846 test847 test848 test849 test85 test850 test851 test852 test853 test854 test855 test856 test857 test858 test859 test86 test860 test861 test862 test863 test864 test865 test866 test867 test868 test869 test87 test870 test871 test872 test873 test874 test875 test876 test877 test878 test879 test88 test880 test881 test882 test883 test884 test885 test886 test887 test888 test889 test89 test890 test891 test892 test893 test894 test895 test896 test897 test898 test899 test9 test90 test900 test901 test902 test903 test904 test905 test906 test907 test908 test909 test91 test910 test911 test912 test913 test914 test915 test916 test917 test918 test919 test92 test920 test921 test922 test923 test924 test925 test926 test927 test928 test929 test93 test930 test931 test932 test933 test934 test935 test936 test937 test938 test939 test94 test940 test941 test942 test943 test944 test945 test946 test947 test948 test949 test95 test950 test951 test952 test953 test954 test955 test956 test957 test958 test959 test96 test960 test961 test962 test963 test964 test965 test966 test967 test968 test969 test97 test970 test971 test972 test973 test974 test975 test976 test977 test978 test979 test98 test980 test981 test982 test983 test984 test985 test986 test987 test988 test989 test99 test990 test991 test992 test993 test994 test995 test996 test997 test998 test999
http
testenv
mod_curltest .gitignore mod_curltest.c
__init__.py caddy.py certs.py client.py curl.py dante.py dnsd.py env.py httpd.py nghttpx.py ports.py sshd.py vsftpd.py ws_echo_server.py
.gitignore CMakeLists.txt Makefile.am config.ini.in conftest.py requirements.txt scorecard.py test_01_basic.py test_02_download.py test_03_goaway.py test_04_stuttered.py test_05_errors.py test_06_eyeballs.py test_07_upload.py test_08_caddy.py test_09_push.py test_10_proxy.py test_11_unix.py test_12_reuse.py test_13_proxy_auth.py test_14_auth.py test_15_tracing.py test_16_info.py test_17_ssl_use.py test_18_methods.py test_19_shutdown.py test_20_websockets.py test_21_resolve.py test_22_httpsrr.py test_30_vsftpd.py test_31_vsftpds.py test_32_ftps_vsftpd.py test_40_socks.py test_50_scp.py test_51_sftp.py
libtest .gitignore CMakeLists.txt Makefile.am Makefile.inc cli_ftp_upload.c cli_h2_pausing.c cli_h2_serverpush.c cli_h2_upgrade_extreme.c cli_hx_download.c cli_hx_upload.c cli_tls_session_reuse.c cli_upload_pausing.c cli_ws_data.c cli_ws_pingpong.c first.c first.h lib1156.c lib1301.c lib1308.c lib1485.c lib1500.c lib1501.c lib1502.c lib1506.c lib1507.c lib1508.c lib1509.c lib1510.c lib1511.c lib1512.c lib1513.c lib1514.c lib1515.c lib1517.c lib1518.c lib1520.c lib1522.c lib1523.c lib1525.c lib1526.c lib1527.c lib1528.c lib1529.c lib1530.c lib1531.c lib1532.c lib1533.c lib1534.c lib1535.c lib1536.c lib1537.c lib1538.c lib1540.c lib1541.c lib1542.c lib1545.c lib1549.c lib1550.c lib1551.c lib1552.c lib1553.c lib1554.c lib1555.c lib1556.c lib1557.c lib1558.c lib1559.c lib1560.c lib1564.c lib1565.c lib1567.c lib1568.c lib1569.c lib1571.c lib1576.c lib1582.c lib1587.c lib1588.c lib1589.c lib1591.c lib1592.c lib1593.c lib1594.c lib1597.c lib1598.c lib1599.c lib1662.c lib1900.c lib1901.c lib1902.c lib1903.c lib1905.c lib1906.c lib1907.c lib1908.c lib1910.c lib1911.c lib1912.c lib1913.c lib1915.c lib1916.c lib1918.c lib1919.c lib1920.c lib1921.c lib1933.c lib1934.c lib1935.c lib1936.c lib1937.c lib1938.c lib1939.c lib1940.c lib1945.c lib1947.c lib1948.c lib1955.c lib1956.c lib1957.c lib1958.c lib1959.c lib1960.c lib1964.c lib1965.c lib1970.c lib1971.c lib1972.c lib1973.c lib1974.c lib1975.c lib1977.c lib1978.c lib2023.c lib2032.c lib2082.c lib2301.c lib2302.c lib2304.c lib2306.c lib2308.c lib2309.c lib2402.c lib2404.c lib2405.c lib2502.c lib2504.c lib2505.c lib2506.c lib2700.c lib3010.c lib3025.c lib3026.c lib3027.c lib3033.c lib3034.c lib3100.c lib3101.c lib3102.c lib3103.c lib3104.c lib3105.c lib3207.c lib3208.c lib500.c lib501.c lib502.c lib503.c lib504.c lib505.c lib506.c lib507.c lib508.c lib509.c lib510.c lib511.c lib512.c lib513.c lib514.c lib515.c lib516.c lib517.c lib518.c lib519.c lib520.c lib521.c lib523.c lib524.c lib525.c lib526.c lib530.c lib533.c lib536.c lib537.c lib539.c lib540.c lib541.c lib542.c lib543.c lib544.c lib547.c lib549.c lib552.c lib553.c lib554.c lib555.c lib556.c lib557.c lib558.c lib559.c lib560.c lib562.c lib564.c lib566.c lib567.c lib568.c lib569.c lib570.c lib571.c lib572.c lib573.c lib574.c lib575.c lib576.c lib578.c lib579.c lib582.c lib583.c lib586.c lib589.c lib590.c lib591.c lib597.c lib598.c lib599.c lib643.c lib650.c lib651.c lib652.c lib653.c lib654.c lib655.c lib658.c lib659.c lib661.c lib666.c lib667.c lib668.c lib670.c lib674.c lib676.c lib677.c lib678.c lib694.c lib695.c lib751.c lib753.c lib757.c lib758.c lib766.c memptr.c mk-lib1521.pl test1013.pl test1022.pl test307.pl test610.pl test613.pl testtrace.c testtrace.h testutil.c testutil.h unitcheck.h
server .checksrc .gitignore CMakeLists.txt Makefile.am Makefile.inc dnsd.c first.c first.h getpart.c mqttd.c resolve.c rtspd.c sockfilt.c socksd.c sws.c tftpd.c util.c
tunit .gitignore CMakeLists.txt Makefile.am Makefile.inc README.md tool1394.c tool1604.c tool1621.c tool1622.c tool1623.c tool1720.c
unit .gitignore CMakeLists.txt Makefile.am Makefile.inc README.md unit1300.c unit1302.c unit1303.c unit1304.c unit1305.c unit1307.c unit1309.c unit1323.c unit1330.c unit1395.c unit1396.c unit1397.c unit1398.c unit1399.c unit1600.c unit1601.c unit1602.c unit1603.c unit1605.c unit1606.c unit1607.c unit1608.c unit1609.c unit1610.c unit1611.c unit1612.c unit1614.c unit1615.c unit1616.c unit1620.c unit1625.c unit1626.c unit1627.c unit1636.c unit1650.c unit1651.c unit1652.c unit1653.c unit1654.c unit1655.c unit1656.c unit1657.c unit1658.c unit1660.c unit1661.c unit1663.c unit1664.c unit1666.c unit1667.c unit1668.c unit1669.c unit1674.c unit1675.c unit1676.c unit1979.c unit1980.c unit2600.c unit2601.c unit2602.c unit2603.c unit2604.c unit2605.c unit3200.c unit3205.c unit3211.c unit3212.c unit3213.c unit3214.c unit3216.c unit3219.c unit3300.c unit3301.c unit3302.c
.gitignore CMakeLists.txt Makefile.am allversions.pm appveyor.pm azure.pm config.in configurehelp.pm.in devtest.pl dictserver.py directories.pm ech_combos.py ech_tests.sh ftpserver.pl getpart.pm globalconfig.pm http-server.pl http2-server.pl http3-server.pl memanalyze.pl memanalyzer.pm negtelnetserver.py nghttpx.conf pathhelp.pm processhelp.pm requirements.txt rtspserver.pl runner.pm runtests.pl secureserver.pl serverhelp.pm servers.pm smbserver.py sshhelp.pm sshserver.pl test1119.pl test1135.pl test1139.pl test1140.pl test1165.pl test1167.pl test1173.pl test1175.pl test1177.pl test1222.pl test1275.pl test1276.pl test1477.pl test1486.pl test1488.pl test1544.pl test1707.pl test745.pl test971.pl testcurl.pl testutil.pm tftpserver.pl util.py valgrind.pm valgrind.supp
.clang-tidy.yml .dir-locals.el .editorconfig .git-blame-ignore-revs .gitattributes .gitignore .mailmap CHANGES.md CMakeLists.txt COPYING Dockerfile GIT-INFO.md Makefile.am README README.md RELEASE-NOTES REUSE.toml SECURITY.md acinclude.m4 appveyor.sh appveyor.yml configure.ac curl-config.in libcurl.pc.in renovate.json
examples .env config.ini crypto_test.lua env_test.lua fs_example.lua http_server.lua https_test.lua ini_example.lua json.lua log.lua path_fs_example.lua process_example.lua request_download.lua request_test.lua run_all.lua sqlite_example.lua sqlite_http_template.lua stash_test.lua template_test.lua timer.lua websocket.lua
iniparser
.github
ISSUE_TEMPLATE config.yml
workflows disable-pull-requests.yml trigger-gitlab-ci.yml
cmake JoinPaths.cmake config.cmake.in pc.in
example iniexample.c iniwrite.c parse.c twisted-errors.ini twisted-genhuge.py twisted-ofkey.ini twisted-ofval.ini twisted.ini
src dictionary.c dictionary.h iniparser.c iniparser.h
test
ressources
bad_ini ends_well.ini twisted-errors.ini twisted-ofkey.ini twisted-ofval.ini
good_ini empty.ini spaced.ini spaced2.ini twisted.ini
gruezi.ini old.ini quotes.ini utf8.ini
CMakeLists.txt test_dictionary.c test_iniparser.c unity-config.yml unity_config.h
.cmake-format.py .gitignore .gitlab-ci.yml .gitmessage .travis.yml AUTHORS CMakeLists.txt FAQ-en.md FAQ-zhcn.md INSTALL LICENSE README.md compile_commands.json
jinjac
example CMakeLists.txt example.c
jinjac_test_app CMakeLists.txt jinjac_test_app.c
libjinjac
include jinjac.h
src CMakeLists.txt ast.c ast.h block_statement.c block_statement.h buffer.c buffer.h buildin.c buildin.h common.h convert.c convert.h flex_decl.h jfunction.c jfunction.h jinja_expression.l jinja_expression.y jinjac_parse.c jinjac_parse.h jinjac_stream.c jinjac_stream.h jlist.c jlist.h jobject.c jobject.h parameter.c parameter.h str_obj.c str_obj.h trace.c trace.h
CMakeLists.txt
test .gitignore CMakeLists.txt autotest.rb test_01.expected test_01.jinja test_01b.expected test_01b.jinja test_01c.expected test_01c.jinja test_01d.expected test_01d.jinja test_02.expected test_02.jinja test_03.expected test_03.jinja test_04.expected test_04.jinja test_05.expected test_05.jinja test_06.expected test_06.jinja test_07.expected test_07.jinja test_08.expected test_08.jinja test_08b.expected test_08b.jinja test_09.expected test_09.jinja test_10.expected test_10.jinja test_11.expected test_11.jinja test_12.expected test_12.jinja test_13.expected test_13.jinja test_14.expected test_14.jinja test_15.expected test_15.jinja test_16.expected test_16.jinja test_17.expected test_17.jinja test_18.expected test_18.jinja test_18b.expected test_18b.jinja test_18c.expected test_18c.jinja test_19.expected test_19.jinja test_19b.expected test_19b.jinja test_19c.expected test_19c.jinja test_19d.expected test_19d.jinja test_19e.expected test_19e.jinja test_19f.expected test_19f.jinja test_20.expected test_20.jinja test_21.expected test_21.jinja test_22.expected test_22.jinja test_22a.expected test_22a.jinja test_22b.expected test_22b.jinja test_23.expected test_23.jinja test_24.expected test_24.jinja
.gitignore CMakeLists.txt LICENSE.txt README.md build_coverage.sh build_debug.sh build_release.sh cppcheck_analysis.sh
libev Changes LICENSE Makefile Makefile.am Makefile.in README Symbols.ev Symbols.event aclocal.m4 autogen.sh compile config.guess config.h config.h.in config.status config.sub configure configure.ac depcomp ev++.h ev.3 ev.c ev.h ev.pod ev_epoll.c ev_kqueue.c ev_poll.c ev_port.c ev_select.c ev_vars.h ev_win32.c ev_wrap.h event.c event.h install-sh libev.m4 libtool ltmain.sh missing mkinstalldirs stamp-h1
luajit
doc
img contact.png
bluequad-print.css bluequad.css contact.html ext_buffer.html ext_c_api.html ext_ffi.html ext_ffi_api.html ext_ffi_semantics.html ext_ffi_tutorial.html ext_jit.html ext_profiler.html extensions.html install.html luajit.html running.html
dynasm dasm_arm.h dasm_arm.lua dasm_arm64.h dasm_arm64.lua dasm_mips.h dasm_mips.lua dasm_mips64.lua dasm_ppc.h dasm_ppc.lua dasm_proto.h dasm_x64.lua dasm_x86.h dasm_x86.lua dynasm.lua
etc luajit.1 luajit.pc
src
host .gitignore README buildvm.c buildvm.h buildvm_asm.c buildvm_fold.c buildvm_lib.c buildvm_libbc.h buildvm_peobj.c genlibbc.lua genminilua.lua genversion.lua minilua.c
jit .gitignore bc.lua bcsave.lua dis_arm.lua dis_arm64.lua dis_arm64be.lua dis_mips.lua dis_mips64.lua dis_mips64el.lua dis_mips64r6.lua dis_mips64r6el.lua dis_mipsel.lua dis_ppc.lua dis_x64.lua dis_x86.lua dump.lua p.lua v.lua zone.lua
.gitignore Makefile Makefile.dep lauxlib.h lib_aux.c lib_base.c lib_bit.c lib_buffer.c lib_debug.c lib_ffi.c lib_init.c lib_io.c lib_jit.c lib_math.c lib_os.c lib_package.c lib_string.c lib_table.c lj_alloc.c lj_alloc.h lj_api.c lj_arch.h lj_asm.c lj_asm.h lj_asm_arm.h lj_asm_arm64.h lj_asm_mips.h lj_asm_ppc.h lj_asm_x86.h lj_assert.c lj_bc.c lj_bc.h lj_bcdump.h lj_bcread.c lj_bcwrite.c lj_buf.c lj_buf.h lj_carith.c lj_carith.h lj_ccall.c lj_ccall.h lj_ccallback.c lj_ccallback.h lj_cconv.c lj_cconv.h lj_cdata.c lj_cdata.h lj_char.c lj_char.h lj_clib.c lj_clib.h lj_cparse.c lj_cparse.h lj_crecord.c lj_crecord.h lj_ctype.c lj_ctype.h lj_debug.c lj_debug.h lj_def.h lj_dispatch.c lj_dispatch.h lj_emit_arm.h lj_emit_arm64.h lj_emit_mips.h lj_emit_ppc.h lj_emit_x86.h lj_err.c lj_err.h lj_errmsg.h lj_ff.h lj_ffrecord.c lj_ffrecord.h lj_frame.h lj_func.c lj_func.h lj_gc.c lj_gc.h lj_gdbjit.c lj_gdbjit.h lj_ir.c lj_ir.h lj_ircall.h lj_iropt.h lj_jit.h lj_lex.c lj_lex.h lj_lib.c lj_lib.h lj_load.c lj_mcode.c lj_mcode.h lj_meta.c lj_meta.h lj_obj.c lj_obj.h lj_opt_dce.c lj_opt_fold.c lj_opt_loop.c lj_opt_mem.c lj_opt_narrow.c lj_opt_sink.c lj_opt_split.c lj_parse.c lj_parse.h lj_prng.c lj_prng.h lj_profile.c lj_profile.h lj_record.c lj_record.h lj_serialize.c lj_serialize.h lj_snap.c lj_snap.h lj_state.c lj_state.h lj_str.c lj_str.h lj_strfmt.c lj_strfmt.h lj_strfmt_num.c lj_strscan.c lj_strscan.h lj_tab.c lj_tab.h lj_target.h lj_target_arm.h lj_target_arm64.h lj_target_mips.h lj_target_ppc.h lj_target_x86.h lj_trace.c lj_trace.h lj_traceerr.h lj_udata.c lj_udata.h lj_vm.h lj_vmevent.c lj_vmevent.h lj_vmmath.c ljamalg.c lua.h lua.hpp luaconf.h luajit.c luajit_rolling.h lualib.h msvcbuild.bat nxbuild.bat ps4build.bat ps5build.bat psvitabuild.bat vm_arm.dasc vm_arm64.dasc vm_mips.dasc vm_mips64.dasc vm_ppc.dasc vm_x64.dasc vm_x86.dasc xb1build.bat xedkbuild.bat
.gitattributes .gitignore .relver COPYRIGHT Makefile README
sqlite shell.c sqlite3.c sqlite3.h sqlite3ext.h
wolfssl
.github
ISSUE_TEMPLATE bug_report.yaml other.yaml
actions
install-apt-deps action.yml
scripts
zephyr-4.x external_libc.conf zephyr-test.sh
openssl-ech.sh tls-anvil-test.sh
workflows
disabled haproxy.yml hitch.yml hostap.yml
hostap-files
configs
07c9f183ea744ac04585fb6dd10220c75a5e2e74 hostapd.config tests wpa_supplicant.config
b607d2723e927a3446d89aed813f1aa6068186bb hostapd.config tests wpa_supplicant.config
hostap_2_10 extra.patch hostapd.config tests wpa_supplicant.config
Makefile README dbus-wpa_supplicant.conf
ada.yml arduino.yml async-examples.yml async.yml atecc608-sim.yml bind.yml cmake-autoconf.yml cmake.yml codespell.yml coverity-scan-fixes.yml cryptocb-only.yml curl.yml cyrus-sasl.yml disable-pk-algs.yml docker-Espressif.yml docker-OpenWrt.yml emnet-nonblock.yml fil-c.yml freertos-mem-track.yml gencertbuf.yml grpc.yml haproxy.yml hostap-vm.yml intelasm-c-fallback.yml ipmitool.yml jwt-cpp.yml krb5.yml libspdm.yml libssh2.yml libvncserver.yml linuxkm.yml macos-apple-native-cert-validation.yml mbedtls.sh mbedtls.yml membrowse-comment.yml membrowse-onboard.yml membrowse-report.yml memcached.sh memcached.yml mono.yml mosquitto.yml msmtp.yml msys2.yml multi-arch.yml multi-compiler.yml net-snmp.yml nginx.yml no-malloc.yml no-tls.yml nss.sh nss.yml ntp.yml ocsp.yml openldap.yml openssh.yml openssl-ech.yml opensslcoexist.yml openvpn.yml os-check.yml packaging.yml pam-ipmi.yml pq-all.yml pr-commit-check.yml psk.yml puf.yml python.yml rng-tools.yml rust-wrapper.yml se050-sim.yml smallStackSize.yml socat.yml softhsm.yml sssd.yml stm32-sim.yml stsafe-a120-sim.yml stunnel.yml symbol-prefixes.yml threadx.yml tls-anvil.yml trackmemory.yml watcomc.yml win-csharp-test.yml wolfCrypt-Wconversion.yml wolfboot-integration.yml wolfsm.yml xcode.yml zephyr-4.x.yml zephyr.yml
PULL_REQUEST_TEMPLATE.md SECURITY.md membrowse-targets.json
Docker
OpenWrt Dockerfile README.md runTests.sh
packaging
debian Dockerfile
fedora Dockerfile
wolfCLU Dockerfile README.md
yocto Dockerfile buildAndPush.sh
Dockerfile Dockerfile.cross-compiler README.md buildAndPush.sh include.am run.sh
IDE
ARDUINO
sketches
wolfssl_client README.md
wolfssl_server README.md
wolfssl_version README.md
README.md
Arduino_README_prepend.md README.md include.am keywords.txt library.properties.template wolfssl-arduino.cpp wolfssl-arduino.sh wolfssl.h
AURIX Cpu0_Main.c README.md include.am user_settings.h wolf_main.c
Android Android.bp README.md include.am user_settings.h
CRYPTOCELL README.md include.am main.c user_settings.h
CSBENCH include.am user_settings.h
ECLIPSE
DEOS
deos_wolfssl .options
README.md deos_malloc.c include.am tls_wolfssl.c tls_wolfssl.h user_settings.h
MICRIUM README.md client_wolfssl.c client_wolfssl.h include.am server_wolfssl.c server_wolfssl.h user_settings.h wolfsslRunTests.c
RTTHREAD README.md include.am user_settings.h wolfssl_test.c
SIFIVE README.md include.am
Espressif
ESP-IDF
examples
template
VisualGDB wolfssl_template_IDF_v5.1_ESP32.vgdbproj
components
wolfssl
include user_settings.h
CMakeLists.txt Kconfig README.md component.mk
main
include main.h
CMakeLists.txt Kconfig.projbuild component.mk main.c
CMakeLists.txt Makefile README.md partitions_singleapp_large.csv sdkconfig.defaults sdkconfig.defaults.esp8266
wolfssl_benchmark
VisualGDB wolfssl_benchmark_IDF_v4.4_ESP32.sln wolfssl_benchmark_IDF_v4.4_ESP32.vgdbproj wolfssl_benchmark_IDF_v5_ESP32.sln wolfssl_benchmark_IDF_v5_ESP32.vgdbproj wolfssl_benchmark_IDF_v5_ESP32C3.sln wolfssl_benchmark_IDF_v5_ESP32C3.vgdbproj wolfssl_benchmark_IDF_v5_ESP32S3.sln wolfssl_benchmark_IDF_v5_ESP32S3.vgdbproj
components
wolfssl
include user_settings.h
CMakeLists.txt Kconfig README.md component.mk
main
include main.h
CMakeLists.txt Kconfig.projbuild component.mk main.c
CMakeLists.txt Makefile README.md partitions_singleapp_large.csv sdkconfig.defaults sdkconfig.defaults.esp8266
wolfssl_client
VisualGDB README.md wolfssl_client_IDF_v5_ESP32.sln wolfssl_client_IDF_v5_ESP32.vgdbproj
components
wolfssl
include user_settings.h
CMakeLists.txt Kconfig README.md component.mk
main
include client-tls.h main.h time_helper.h wifi_connect.h
CMakeLists.txt Kconfig.projbuild client-tls.c component.mk main.c time_helper.c wifi_connect.c
CMakeLists.txt Makefile README.md README_server_sm.md partitions_singleapp_large.csv sdkconfig.defaults sdkconfig.defaults.esp32c2 sdkconfig.defaults.esp8266 wolfssl_client_ESP8266.vgdbproj
wolfssl_server
VisualGDB README.md wolfssl_server_IDF_v5_ESP32.sln wolfssl_server_IDF_v5_ESP32.vgdbproj
components
wolfssl
include user_settings.h
CMakeLists.txt Kconfig README.md component.mk
main
include main.h server-tls.h time_helper.h wifi_connect.h
CMakeLists.txt Kconfig.projbuild component.mk main.c server-tls.c time_helper.c wifi_connect.c
CMakeLists.txt Makefile README.md README_server_sm.md partitions_singleapp_large.csv sdkconfig.defaults sdkconfig.defaults.esp32c2 sdkconfig.defaults.esp8266 wolfssl_server_ESP8266.vgdbproj
wolfssl_test
VisualGDB wolfssl_test-IDF_v5_ESP32.sln wolfssl_test-IDF_v5_ESP32.vgdbproj wolfssl_test-IDF_v5_ESP32C3.sln wolfssl_test-IDF_v5_ESP32C3.vgdbproj wolfssl_test-IDF_v5_ESP32C6.sln wolfssl_test-IDF_v5_ESP32C6.vgdbproj wolfssl_test_IDF_v5_ESP32S3.sln wolfssl_test_IDF_v5_ESP32S3.vgdbproj
components
wolfssl
include user_settings.h
CMakeLists.txt Kconfig README.md component.mk
main
include main.h
CMakeLists.txt Kconfig.projbuild component.mk main.c
CMakeLists.txt Makefile README.md partitions_singleapp_large.csv sdkconfig.defaults sdkconfig.defaults.esp32 sdkconfig.defaults.esp32c3 sdkconfig.defaults.esp32c6 sdkconfig.defaults.esp32h2 sdkconfig.defaults.esp32s2 sdkconfig.defaults.esp32s3 sdkconfig.defaults.esp8266 testAll.sh testMonitor.sh wolfssl_test_ESP8266.sln wolfssl_test_ESP8266.vgdbproj
wolfssl_test_idf
VisualGDB VisualGDB_wolfssl_test_idf.sln VisualGDB_wolfssl_test_idf.vgdbproj
main CMakeLists.txt Kconfig.projbuild component.mk main.c main_wip.c.ex time_helper.c time_helper.h
CMakeLists.txt Kconfig.projbuild README.md component.mk sdkconfig.defaults
README.md
libs CMakeLists.txt README.md component.mk tigard.cfg
test CMakeLists.txt README.md component.mk test_wolfssl.c
README.md README_32se.md UPDATE.md compileAllExamples.sh dummy_config_h dummy_test_paths.h setup.sh setup_win.bat user_settings.h
README.md include.am
GCC-ARM
Header user_settings.h
Source armtarget.c benchmark_main.c test_main.c tls_client.c tls_server.c wolf_main.c
Makefile Makefile.bench Makefile.client Makefile.common Makefile.server Makefile.static Makefile.test README.md include.am linker.ld linker_fips.ld
Gaisler-BCC README.md include.am
HEXAGON
DSP Makefile wolfssl_dsp.idl
Makefile README.md build.sh ecc-verify-benchmark.c ecc-verify.c include.am user_settings.h
HEXIWEAR
wolfSSL_HW .cwGeneratedFileSetLog user_settings.h
IAR-EWARM
Projects
benchmark benchmark-main.c current_time.c wolfCrypt-benchmark.ewd wolfCrypt-benchmark.ewp
common minimum-startup.c wolfssl.icf
lib wolfSSL-Lib.ewd wolfSSL-Lib.ewp
test test-main.c wolfCrypt-test.ewd wolfCrypt-test.ewp
user_settings.h wolfssl.eww
embOS
SAMV71_XULT
embOS_SAMV71_XULT_Linker_Script samv71q21_wolfssl.icf
embOS_SAMV71_XULT_user_settings user_settings.h user_settings_simple_example.h user_settings_verbose_example.h
embOS_wolfcrypt_benchmark_SAMV71_XULT
Application runBenchmarks.c
README_wolfcrypt_benchmark wolfcrypt_benchmark.ewd wolfcrypt_benchmark.ewp
embOS_wolfcrypt_lib_SAMV71_XULT README_wolfcrypt_lib wolfcrypt_lib.ewd wolfcrypt_lib.ewp
embOS_wolfcrypt_test_SAMV71_XULT
Application runWolfcryptTests.c
README_wolfcrypt_test wolfcrypt_test.ewd wolfcrypt_test.ewp
README_SAMV71
custom_port
custom_port_Linker_Script samv71q21_wolfssl.icf
custom_port_user_settings user_settings.h
wolfcrypt_benchmark_custom_port
Application runBenchmarks.c
wolfcrypt_test_custom_port
Application runWolfcryptTests.c
README_custom_port
extract_trial_here README_extract_trial_here
README
.gitignore README
IAR-MSP430 Makefile README.md include.am main.c user_settings.h
INTIME-RTOS Makefile README.md include.am libwolfssl.c libwolfssl.vcxproj user_settings.h wolfExamples.c wolfExamples.h wolfExamples.sln wolfExamples.vcxproj wolfssl-lib.sln wolfssl-lib.vcxproj
Infineon README.md include.am user_settings.h
KDS
config user_settings.h
include.am
LINUX-SGX README.md build.sh clean.sh include.am sgx_t_static.mk
LPCXPRESSO
lib_wolfssl lpc_18xx_port.c user_settings.h
wolf_example
src lpc_18xx_startup.c wolfssl_example.c
readme.txt
README.md
M68K
benchmark Makefile main.cpp
testwolfcrypt Makefile main.cpp
Makefile README.md include.am user_settings.h
MCUEXPRESSO
RT1170 fsl_caam_c.patch fsl_caam_h.patch user_settings.h
benchmark
source run_benchmark.c
wolfssl liblinks.xml
README.md include.am user_settings.h wolfcrypt_test.c
MDK-ARM
LPC43xx time-LCP43xx.c
MDK-ARM
wolfSSL Retarget.c cert_data.c cert_data.h config-BARE-METAL.h config-FS.h config-RTX-TCP-FS.h config-WOLFLIB.h main.c shell.c time-CortexM3-4.c time-dummy.c wolfssl_MDK_ARM.c wolfssl_MDK_ARM.h
STM32F2xx_StdPeriph_Lib time-STM32F2xx.c
MDK5-ARM
Conf user_settings.h
Inc wolfssl_MDK_ARM.h
Projects
CryptBenchmark Abstract.txt CryptBenchmark.sct CryptBenchmark.uvoptx CryptBenchmark.uvprojx main.c
CryptTest Abstract.txt CryptTest.sct CryptTest.uvoptx CryptTest.uvprojx main.c
EchoClient Abstract.txt EchoClient.uvoptx EchoClient.uvprojx main.c wolfssl-link.sct
EchoServer Abstract.txt EchoServer.uvoptx EchoServer.uvprojx main.c wolfssl-link.sct
SimpleClient Abstract.txt SimpleClient.uvoptx SimpleClient.uvprojx main.c wolfssl-link.sct
SimpleServer Abstract.txt SimpleServer.uvoptx SimpleServer.uvprojx main.c wolfssl-link.sct
wolfSSL-Full Abstract.txt main.c shell.c time-CortexM3-4.c wolfsslFull.uvoptx wolfsslFull.uvprojx
wolfSSL-Lib Abstract.txt wolfSSL-Lib.uvoptx wolfSSL-Lib.uvprojx
Src ssl-dummy.c
README.md include.am
MPLABX16
wolfcrypt_test.X
nbproject
private configurations.xml private.xml
configurations.xml include.am project.xml
Makefile
wolfssl.X
nbproject configurations.xml include.am project.xml
Makefile
README.md include.am main.c user_settings.h
MQX Makefile README-jp.md README.md client-tls.c include.am server-tls.c user_config.h user_settings.h
MSVS-2019-AZSPHERE
client client.c client.h
server server.c server.h
shared util.h
wolfssl_new_azsphere
HardwareDefinitions
avnet_mt3620_sk
inc
hw template_appliance.h
template_appliance.json
mt3620_rdb
inc
hw template_appliance.h
template_appliance.json
seeed_mt3620_mdb
inc
hw template_appliance.h
template_appliance.json
.gitignore CMakeLists.txt CMakeSettings.json app_manifest.json applibs_versions.h launch.vs.json main.c
README.md include.am user_settings.h
MYSQL CMakeLists_wolfCrypt.txt CMakeLists_wolfSSL.txt do.sh
NDS README.md
NETOS Makefile.wolfcrypt.inc README.md include.am user_settings.h user_settings.h-cert2425 user_settings.h-cert3389 wolfssl_netos_custom.c
OPENSTM32 README.md
PlatformIO
examples
wolfssl_benchmark
include README main.h
lib README
src CMakeLists.txt main.c
test README
CMakeLists.txt README.md platformio.ini sdkconfig.defaults wolfssl_benchmark.code-workspace
wolfssl_test
include README main.h
lib README
src CMakeLists.txt main.c
test README
CMakeLists.txt README.md platformio.ini sdkconfig.defaults wolfssl_test.code-workspace
README.md wolfssl_platformio.code-workspace
README.md include.am
QNX
CAAM-DRIVER Makefile
example-client Makefile client-tls.c
example-cmac Makefile cmac-test.c
example-server Makefile server-tls.c
testwolfcrypt Makefile
wolfssl Makefile user_settings.h
README.md include.am
RISCV
SIFIVE-HIFIVE1 Makefile README.md include.am main.c user_settings.h
SIFIVE-UNLEASHED README.md include.am
include.am
ROWLEY-CROSSWORKS-ARM Kinetis_FlashPlacement.xml README.md arm_startup.c benchmark_main.c hw.h include.am kinetis_hw.c retarget.c test_main.c user_settings.h wolfssl.hzp wolfssl_ltc.hzp
Renesas
cs+
Projects
common strings.h unistd.h user_settings.h wolfssl_dummy.c
t4_demo README_en.txt README_jp.txt t4_demo.mtpj wolf_client.c wolf_demo.h wolf_main.c wolf_server.c
test test.mtpj test_main.c
wolfssl_lib wolfssl_lib.mtpj
README include.am
e2studio
DK-S7G2
benchmark-template
src app_entry.c
example_server-template
src app_entry.c
wolfcrypttest-template
src app_entry.c
wolfssl-template-project configuration.xml
README.md include.am user_settings.h
Projects
common strings.h unistd.h user_settings.h wolfssl_dummy.c
test
src key_data.c key_data.h test_main.c wolf_client.c wolf_server.c wolfssl_demo.h
tools generate_rsa_keypair.sh genhexbuf.pl rsa_pss_sign.sh
wolfssl
src .gitkeep
wolfcrypt
src .gitkeep
README include.am
RA6M3
benchmark-wolfcrypt
common .gitkeep
script .gitkeep
src wolfssl_thread_entry.c
client-wolfssl
common
src .gitkeep
script .gitkeep
src wolfssl_thread_entry.c
wolfssl_thread_entry.h
common
ra6m3g README.md
src freertos_tcp_port.c
user_settings.h util.h
server-wolfssl
common
src .gitkeep
script .gitkeep
src wolfssl_thread_entry.c
wolfssl_thread_entry.h
test-wolfcrypt
common .gitkeep
script .gitkeep
src wolfssl_thread_entry.c
wolfssl
src .gitkeep
wolfcrypt .gitkeep
README.md README_APRA6M_en.md README_APRA6M_jp.md include.am
RA6M3G README.md
RA6M4
common user_settings.h wolfssl_demo.h
test
key_data key_data.h key_data_sce.c
src
SEGGER_RTT myprint.c
common .gitignore
test_main.c wolf_client.c wolfssl_sce_unit_test.c
test_RA6M4Debug.launch
tools
example_keys generate_SignedCA.sh rsa_private.pem rsa_public.pem
README.md
README.md include.am
RX65N
GR-ROSE
common strings.h unistd.h user_settings.h wolfssl_dummy.c
smc smc.scfg
test
src key_data.c key_data.h test_main.c wolf_client.c wolf_server.c wolfssl_demo.h
test.rcpc test_HardwareDebug.launch
tools
example_keys generate_SignedCA.sh rsa_private.pem rsa_public.pem
README.md
wolfssl wolfssl.rcpc
README_EN.md README_JP.md include.am
RSK
resource section.esi
wolfssl wolfssl.rcpc
wolfssl_demo key_data.c key_data.h user_settings.h wolfssl_demo.c wolfssl_demo.h
InstructionManualForExample_RSK+RX65N-2MB_EN.pdf InstructionManualForExample_RSK+RX65N-2MB_JP.pdf README_EN.md README_JP.md include.am
RX72N
EnvisionKit
Simple
common sectioninfo.esi wolfssl_dummy.c
test
src
client simple_tcp_client.c simple_tls_tsip_client.c
server simple_tcp_server.c simple_tls_server.c
test_main.c wolfssl_simple_demo.h
test.rcpc test.scfg test_HardwareDebug.launch
wolfssl wolfssl.rcpc
README_EN.md README_JP.md
resource section.esi
tools
example_keys generate_SignedCA.sh rsa_private.pem rsa_public.pem
README.md
wolfssl wolfssl.rcpc
wolfssl_demo key_data.c key_data.h user_settings.h wolfssl_demo.c wolfssl_demo.h wolfssl_tsip_unit_test.c
InstructionManualForExample_RX72N_EnvisonKit_EN.pdf InstructionManualForExample_RX72N_EnvisonKit_JP.pdf README_EN.md README_JP.md include.am
RZN2L
common user_settings.h wolfssl_demo.h
test
src
serial_io app_print.c
test wolf_client.c wolf_server.c wolfssl_rsip_unit_test.c
wolfCrypt .gitignore
wolfSSL .gitignore
local_system_init.c rzn2l_tst_thread_entry.c wolfssl_dummy.c
README.md include.am
SK-S7G2
common user_settings.h
wolfssl_lib configuration.xml
.gitignore README.md include.am
STARCORE README.txt include.am starcore_test.c user_settings.h
STM32Cube README.md STM32_Benchmarks.md default_conf.ftl include.am main.c wolfssl_example.c wolfssl_example.h
SimplicityStudio README.md include.am test_wolf.c user_settings.h
TRUESTUDIO
wolfssl user_settings.h
README include.am
VS-ARM README.md include.am user_settings.h wolfssl.sln wolfssl.vcxproj
VS-AZURE-SPHERE
client app_manifest.json client.c client.h client.vcxproj
server app_manifest.json server.c server.h server.vcxproj
shared util.h
wolfcrypt_test app_manifest.json wolfcrypt_test.vcxproj
README.md include.am user_settings.h wolfssl.sln wolfssl.vcxproj
VisualDSP include.am user_settings.h wolf_tasks.c
WICED-STUDIO README include.am user_settings.h
WIN README.txt include.am test.vcxproj user_settings.h user_settings_dtls.h wolfssl-fips.sln wolfssl-fips.vcxproj
WIN-SGX ReadMe.txt include.am wolfSSL_SGX.edl wolfSSL_SGX.sln wolfSSL_SGX.vcxproj
WIN-SRTP-KDF-140-3 README.txt include.am resource.h test.vcxproj user_settings.h wolfssl-fips.rc wolfssl-fips.sln wolfssl-fips.vcxproj
WIN10 README.txt include.am resource.h test.vcxproj user_settings.h wolfssl-fips.rc wolfssl-fips.sln wolfssl-fips.vcxproj
WINCE README.md include.am user_settings.h user_settings.h.140-2-deprecated
WORKBENCH README.md include.am
XCODE
Benchmark
wolfBench
Assets.xcassets
AppIcon.appiconset Contents.json
Base.lproj LaunchScreen.storyboard Main.storyboard
AppDelegate.h AppDelegate.m Info.plist ViewController.h ViewController.m main.m
wolfBench.xcodeproj project.pbxproj
include.am
wolfssl-FIPS.xcodeproj project.pbxproj
wolfssl.xcodeproj project.pbxproj
wolfssl_testsuite.xcodeproj project.pbxproj
README.md build-for-i386.sh include.am user_settings.h
XCODE-FIPSv2
macOS-C++
Intel user_settings.h
M1 user_settings.h
include.am user_settings.h
XCODE-FIPSv5 README include.am user_settings.h
XCODE-FIPSv6 README include.am user_settings.h
XilinxSDK
2018_2 lscript.ld
2019_2
wolfCrypt_example
src lscript.ld
wolfCrypt_example_system wolfCrypt_example_system.sprj
2022_1
wolfCrypt_FreeRTOS_example wolfCrypt_FreeRTOS_example.prj
wolfCrypt_FreeRTOS_example_system wolfCrypt_FreeRTOS_example_system.sprj
wolfCrypt_example wolfCrypt_example.prj
wolfCrypt_example_system wolfCrypt_example_system.sprj
.gitignore
README.md bench.sh combine.sh eclipse_formatter_profile.xml graph.sh include.am user_settings.h wolfssl_example.c
apple-universal
wolfssl-multiplatform
wolfssl-multiplatform
Assets.xcassets
AccentColor.colorset Contents.json
AppIcon.appiconset Contents.json
Contents.json
ContentView.swift simple_client_example.c simple_client_example.h wolfssl-multiplatform-Bridging-Header.h wolfssl_multiplatform.entitlements wolfssl_multiplatformApp.swift wolfssl_test_driver.c wolfssl_test_driver.h
wolfssl-multiplatform.xcodeproj project.pbxproj
.gitignore README.md build-wolfssl-framework.sh include.am
iotsafe Makefile README.md ca-cert.c devices.c devices.h include.am main.c memory-tls.c startup.c target.ld user_settings.h
iotsafe-raspberrypi Makefile README.md client-tls13.c include.am main.c
mynewt README.md apps.wolfcrypttest.pkg.yml crypto.wolfssl.pkg.yml crypto.wolfssl.syscfg.yml include.am setup.sh
zephyr README.md include.am
include.am
RTOS
nuttx
wolfssl .gitignore Kconfig Make.defs Makefile README.md setup-wolfssl.sh user_settings.h
include.am
bsdkm Makefile README.md bsdkm_wc_port.h include.am wolfkmod.c wolfkmod_aes.c x86_vecreg.c
certs
1024 ca-cert.der ca-cert.pem ca-key.der ca-key.pem client-cert.der client-cert.pem client-key.der client-key.pem client-keyPub.der dh1024.der dh1024.pem dsa-pub-1024.pem dsa1024.der dsa1024.pem include.am rsa1024.der server-cert.der server-cert.pem server-key.der server-key.pem
3072 client-cert.der client-cert.pem client-key.der client-key.pem client-keyPub.der include.am
4096 client-cert.der client-cert.pem client-key.der client-key.pem client-keyPub.der include.am
acert
rsa_pss acert.pem acert_ietf.pem acert_ietf_pubkey.pem acert_pubkey.pem
acert.pem acert_ietf.pem acert_ietf_pubkey.pem acert_pubkey.pem include.am
aia ca-issuers-cert.pem multi-aia-cert.pem overflow-aia-cert.pem
crl
extra-crls ca-int-cert-revoked.pem claim-root.pem crl_critical_entry.pem crlnum_57oct.pem crlnum_64oct.pem general-server-crl.pem large_crlnum.pem large_crlnum2.pem
hash_der 0fdb2da4.r0
hash_pem 0fdb2da4.r0
bad_time_fmt.pem ca-int-ecc.pem ca-int.pem ca-int2-ecc.pem ca-int2.pem caEcc384Crl.pem caEccCrl.der caEccCrl.pem cliCrl.pem client-int-ecc.pem client-int.pem crl.der crl.pem crl.revoked crl2.der crl2.pem crl_reason.pem crl_rsapss.pem eccCliCRL.pem eccSrvCRL.pem gencrls.sh include.am server-goodaltCrl.pem server-goodaltwildCrl.pem server-goodcnCrl.pem server-goodcnwildCrl.pem server-int-ecc.pem server-int.pem wolfssl.cnf
dilithium bench_dilithium_level2_key.der bench_dilithium_level3_key.der bench_dilithium_level5_key.der include.am
ecc bp256r1-key.der bp256r1-key.pem ca-secp256k1-cert.pem ca-secp256k1-key.pem client-bp256r1-cert.der client-bp256r1-cert.pem client-secp256k1-cert.der client-secp256k1-cert.pem genecc.sh include.am secp256k1-key.der secp256k1-key.pem secp256k1-param.pem secp256k1-privkey.der secp256k1-privkey.pem server-bp256r1-cert.der server-bp256r1-cert.pem server-secp256k1-cert.der server-secp256k1-cert.pem server2-secp256k1-cert.der server2-secp256k1-cert.pem wolfssl.cnf wolfssl_384.cnf
ed25519 ca-ed25519-key.der ca-ed25519-key.pem ca-ed25519-priv.der ca-ed25519-priv.pem ca-ed25519.der ca-ed25519.pem client-ed25519-key.der client-ed25519-key.pem client-ed25519-priv.der client-ed25519-priv.pem client-ed25519.der client-ed25519.pem eddsa-ed25519.der eddsa-ed25519.pem gen-ed25519-certs.sh gen-ed25519-keys.sh gen-ed25519.sh include.am root-ed25519-key.der root-ed25519-key.pem root-ed25519-priv.der root-ed25519-priv.pem root-ed25519.der root-ed25519.pem server-ed25519-cert.pem server-ed25519-key.der server-ed25519-key.pem server-ed25519-priv.der server-ed25519-priv.pem server-ed25519.der server-ed25519.pem
ed448 ca-ed448-key.der ca-ed448-key.pem ca-ed448-priv.der ca-ed448-priv.pem ca-ed448.der ca-ed448.pem client-ed448-key.der client-ed448-key.pem client-ed448-priv.der client-ed448-priv.pem client-ed448.der client-ed448.pem gen-ed448-certs.sh gen-ed448-keys.sh include.am root-ed448-key.der root-ed448-key.pem root-ed448-priv.der root-ed448-priv.pem root-ed448.der root-ed448.pem server-ed448-cert.pem server-ed448-key.der server-ed448-key.pem server-ed448-priv.der server-ed448-priv.pem server-ed448.der server-ed448.pem
external DigiCertGlobalRootCA.pem README.txt ca-digicert-ev.pem ca-globalsign-root.pem ca-google-root.pem ca_collection.pem include.am
falcon bench_falcon_level1_key.der bench_falcon_level5_key.der include.am
intermediate
ca_false_intermediate gentestcert.sh int_ca.key server.key test_ca.key test_ca.pem test_int_not_cacert.pem test_sign_bynoca_srv.pem wolfssl_base.conf wolfssl_srv.conf
ca-ecc-bad-aki.der ca-ecc-bad-aki.pem ca-int-cert.der ca-int-cert.pem ca-int-ecc-cert.der ca-int-ecc-cert.pem ca-int-ecc-key.der ca-int-ecc-key.pem ca-int-key.der ca-int-key.pem ca-int2-cert.der ca-int2-cert.pem ca-int2-ecc-cert.der ca-int2-ecc-cert.pem ca-int2-ecc-key.der ca-int2-ecc-key.pem ca-int2-key.der ca-int2-key.pem client-chain-alt-ecc.pem client-chain-alt.pem client-chain-ecc.der client-chain-ecc.pem client-chain.der client-chain.pem client-int-cert.der client-int-cert.pem client-int-ecc-cert.der client-int-ecc-cert.pem genintcerts.sh include.am server-chain-alt-ecc.pem server-chain-alt.pem server-chain-ecc.der server-chain-ecc.pem server-chain-short.pem server-chain.der server-chain.pem server-int-cert.der server-int-cert.pem server-int-ecc-cert.der server-int-ecc-cert.pem
lms bc_hss_L2_H5_W8_root.der bc_hss_L3_H5_W4_root.der bc_lms_chain_ca.der bc_lms_chain_leaf.der bc_lms_native_bc_root.der bc_lms_sha256_h10_w8_root.der bc_lms_sha256_h5_w4_root.der include.am
mldsa README.txt include.am mldsa44-cert.der mldsa44-cert.pem mldsa44-key.pem mldsa44_bare-priv.der mldsa44_bare-seed.der mldsa44_oqskeypair.der mldsa44_priv-only.der mldsa44_pub-spki.der mldsa44_seed-only.der mldsa44_seed-priv.der mldsa65-cert.der mldsa65-cert.pem mldsa65-key.pem mldsa65_bare-priv.der mldsa65_bare-seed.der mldsa65_oqskeypair.der mldsa65_priv-only.der mldsa65_pub-spki.der mldsa65_seed-only.der mldsa65_seed-priv.der mldsa87-cert.der mldsa87-cert.pem mldsa87-key.pem mldsa87_bare-priv.der mldsa87_bare-seed.der mldsa87_oqskeypair.der mldsa87_priv-only.der mldsa87_pub-spki.der mldsa87_seed-only.der mldsa87_seed-priv.der
ocsp imposter-root-ca-cert.der imposter-root-ca-cert.pem imposter-root-ca-key.der imposter-root-ca-key.pem include.am index-ca-and-intermediate-cas.txt index-ca-and-intermediate-cas.txt.attr index-intermediate1-ca-issued-certs.txt index-intermediate1-ca-issued-certs.txt.attr index-intermediate2-ca-issued-certs.txt index-intermediate2-ca-issued-certs.txt.attr index-intermediate3-ca-issued-certs.txt index-intermediate3-ca-issued-certs.txt.attr intermediate1-ca-cert.der intermediate1-ca-cert.pem intermediate1-ca-key.der intermediate1-ca-key.pem intermediate2-ca-cert.der intermediate2-ca-cert.pem intermediate2-ca-key.der intermediate2-ca-key.pem intermediate3-ca-cert.der intermediate3-ca-cert.pem intermediate3-ca-key.der intermediate3-ca-key.pem ocsp-responder-cert.der ocsp-responder-cert.pem ocsp-responder-key.der ocsp-responder-key.pem openssl.cnf renewcerts-for-test.sh renewcerts.sh root-ca-cert.der root-ca-cert.pem root-ca-crl.pem root-ca-key.der root-ca-key.pem server1-cert.der server1-cert.pem server1-chain-noroot.pem server1-key.der server1-key.pem server2-cert.der server2-cert.pem server2-key.der server2-key.pem server3-cert.der server3-cert.pem server3-key.der server3-key.pem server4-cert.der server4-cert.pem server4-key.der server4-key.pem server5-cert.der server5-cert.pem server5-key.der server5-key.pem test-leaf-response.der test-multi-response.der test-response-nointern.der test-response-rsapss.der test-response.der
p521 ca-p521-key.der ca-p521-key.pem ca-p521-priv.der ca-p521-priv.pem ca-p521.der ca-p521.pem client-p521-key.der client-p521-key.pem client-p521-priv.der client-p521-priv.pem client-p521.der client-p521.pem gen-p521-certs.sh gen-p521-keys.sh include.am root-p521-key.der root-p521-key.pem root-p521-priv.der root-p521-priv.pem root-p521.der root-p521.pem server-p521-cert.pem server-p521-key.der server-p521-key.pem server-p521-priv.der server-p521-priv.pem server-p521.der server-p521.pem
renewcerts wolfssl.cnf
rpk client-cert-rpk.der client-ecc-cert-rpk.der include.am server-cert-rpk.der server-ecc-cert-rpk.der
rsapss ca-3072-rsapss-key.der ca-3072-rsapss-key.pem ca-3072-rsapss-priv.der ca-3072-rsapss-priv.pem ca-3072-rsapss.der ca-3072-rsapss.pem ca-rsapss-key.der ca-rsapss-key.pem ca-rsapss-priv.der ca-rsapss-priv.pem ca-rsapss.der ca-rsapss.pem client-3072-rsapss-key.der client-3072-rsapss-key.pem client-3072-rsapss-priv.der client-3072-rsapss-priv.pem client-3072-rsapss.der client-3072-rsapss.pem client-rsapss-key.der client-rsapss-key.pem client-rsapss-priv.der client-rsapss-priv.pem client-rsapss.der client-rsapss.pem gen-rsapss-keys.sh include.am renew-rsapss-certs.sh root-3072-rsapss-key.der root-3072-rsapss-key.pem root-3072-rsapss-priv.der root-3072-rsapss-priv.pem root-3072-rsapss.der root-3072-rsapss.pem root-rsapss-key.der root-rsapss-key.pem root-rsapss-priv.der root-rsapss-priv.pem root-rsapss.der root-rsapss.pem server-3072-rsapss-cert.pem server-3072-rsapss-key.der server-3072-rsapss-key.pem server-3072-rsapss-priv.der server-3072-rsapss-priv.pem server-3072-rsapss.der server-3072-rsapss.pem server-mix-rsapss-cert.pem server-rsapss-cert.pem server-rsapss-key.der server-rsapss-key.pem server-rsapss-priv.der server-rsapss-priv.pem server-rsapss.der server-rsapss.pem
sia timestamping-sia-cert.pem
slhdsa bench_slhdsa_sha2_128f_key.der bench_slhdsa_sha2_128s_key.der bench_slhdsa_sha2_192f_key.der bench_slhdsa_sha2_192s_key.der bench_slhdsa_sha2_256f_key.der bench_slhdsa_sha2_256s_key.der bench_slhdsa_shake128f_key.der bench_slhdsa_shake128s_key.der bench_slhdsa_shake192f_key.der bench_slhdsa_shake192s_key.der bench_slhdsa_shake256f_key.der bench_slhdsa_shake256s_key.der client-mldsa44-priv.pem client-mldsa44-sha2.der client-mldsa44-sha2.pem client-mldsa44-shake.der client-mldsa44-shake.pem gen-slhdsa-mldsa-certs.sh include.am root-slhdsa-sha2-128s-priv.der root-slhdsa-sha2-128s-priv.pem root-slhdsa-sha2-128s.der root-slhdsa-sha2-128s.pem root-slhdsa-shake-128s-priv.der root-slhdsa-shake-128s-priv.pem root-slhdsa-shake-128s.der root-slhdsa-shake-128s.pem server-mldsa44-priv.pem server-mldsa44-sha2.der server-mldsa44-sha2.pem server-mldsa44-shake.der server-mldsa44-shake.pem
sm2 ca-sm2-key.der ca-sm2-key.pem ca-sm2-priv.der ca-sm2-priv.pem ca-sm2.der ca-sm2.pem client-sm2-key.der client-sm2-key.pem client-sm2-priv.der client-sm2-priv.pem client-sm2.der client-sm2.pem fix_sm2_spki.py gen-sm2-certs.sh gen-sm2-keys.sh include.am root-sm2-key.der root-sm2-key.pem root-sm2-priv.der root-sm2-priv.pem root-sm2.der root-sm2.pem self-sm2-cert.pem self-sm2-key.pem self-sm2-priv.pem server-sm2-cert.der server-sm2-cert.pem server-sm2-key.der server-sm2-key.pem server-sm2-priv.der server-sm2-priv.pem server-sm2.der server-sm2.pem
statickeys dh-ffdhe2048-params.pem dh-ffdhe2048-pub.der dh-ffdhe2048-pub.pem dh-ffdhe2048.der dh-ffdhe2048.pem ecc-secp256r1.der ecc-secp256r1.pem gen-static.sh include.am x25519-pub.der x25519-pub.pem x25519.der x25519.pem
test
expired expired-ca.der expired-ca.pem expired-cert.der expired-cert.pem
catalog.txt cert-bad-neg-int.der cert-bad-oid.der cert-bad-utf8.der cert-ext-ia.cfg cert-ext-ia.der cert-ext-ia.pem cert-ext-joi.cfg cert-ext-joi.der cert-ext-joi.pem cert-ext-mnc.der cert-ext-multiple.cfg cert-ext-multiple.der cert-ext-multiple.pem cert-ext-nc-combined.der cert-ext-nc-combined.pem cert-ext-nc.cfg cert-ext-nc.der cert-ext-nc.pem cert-ext-ncdns.der cert-ext-ncdns.pem cert-ext-ncip.der cert-ext-ncip.pem cert-ext-ncmixed.der cert-ext-ncmulti.der cert-ext-ncmulti.pem cert-ext-ncrid.der cert-ext-ncrid.pem cert-ext-nct.cfg cert-ext-nct.der cert-ext-nct.pem cert-ext-ndir-exc.cfg cert-ext-ndir-exc.der cert-ext-ndir-exc.pem cert-ext-ndir.cfg cert-ext-ndir.der cert-ext-ndir.pem cert-ext-ns.der cert-over-max-altnames.cfg cert-over-max-altnames.der cert-over-max-altnames.pem cert-over-max-nc.cfg cert-over-max-nc.der cert-over-max-nc.pem client-ecc-cert-ski.hex cn-ip-literal.der cn-ip-wildcard.der crit-cert.pem crit-key.pem dh1024.der dh1024.pem dh512.der dh512.pem digsigku.pem encrypteddata.msg gen-badsig.sh gen-ext-certs.sh gen-testcerts.sh include.am kari-keyid-cms.msg ktri-keyid-cms.msg ossl-trusted-cert.pem server-badaltname.der server-badaltname.pem server-badaltnull.der server-badaltnull.pem server-badcn.der server-badcn.pem server-badcnnull.der server-badcnnull.pem server-cert-ecc-badsig.der server-cert-ecc-badsig.pem server-cert-rsa-badsig.der server-cert-rsa-badsig.pem server-duplicate-policy.pem server-garbage.der server-garbage.pem server-goodalt.der server-goodalt.pem server-goodaltwild.der server-goodaltwild.pem server-goodcn.der server-goodcn.pem server-goodcnwild.der server-goodcnwild.pem server-localhost.der server-localhost.pem smime-test-canon.p7s smime-test-multipart-badsig.p7s smime-test-multipart.p7s smime-test.p7s
test-pathlen assemble-chains.sh chainA-ICA1-key.pem chainA-ICA1-pathlen0.pem chainA-assembled.pem chainA-entity-key.pem chainA-entity.pem chainB-ICA1-key.pem chainB-ICA1-pathlen0.pem chainB-ICA2-key.pem chainB-ICA2-pathlen1.pem chainB-assembled.pem chainB-entity-key.pem chainB-entity.pem chainC-ICA1-key.pem chainC-ICA1-pathlen1.pem chainC-assembled.pem chainC-entity-key.pem chainC-entity.pem chainD-ICA1-key.pem chainD-ICA1-pathlen127.pem chainD-assembled.pem chainD-entity-key.pem chainD-entity.pem chainE-ICA1-key.pem chainE-ICA1-pathlen128.pem chainE-assembled.pem chainE-entity-key.pem chainE-entity.pem chainF-ICA1-key.pem chainF-ICA1-pathlen1.pem chainF-ICA2-key.pem chainF-ICA2-pathlen0.pem chainF-assembled.pem chainF-entity-key.pem chainF-entity.pem chainG-ICA1-key.pem chainG-ICA1-pathlen0.pem chainG-ICA2-key.pem chainG-ICA2-pathlen1.pem chainG-ICA3-key.pem chainG-ICA3-pathlen99.pem chainG-ICA4-key.pem chainG-ICA4-pathlen5.pem chainG-ICA5-key.pem chainG-ICA5-pathlen20.pem chainG-ICA6-key.pem chainG-ICA6-pathlen10.pem chainG-ICA7-key.pem chainG-ICA7-pathlen100.pem chainG-assembled.pem chainG-entity-key.pem chainG-entity.pem chainH-ICA1-key.pem chainH-ICA1-pathlen0.pem chainH-ICA2-key.pem chainH-ICA2-pathlen2.pem chainH-ICA3-key.pem chainH-ICA3-pathlen2.pem chainH-ICA4-key.pem chainH-ICA4-pathlen2.pem chainH-assembled.pem chainH-entity-key.pem chainH-entity.pem chainI-ICA1-key.pem chainI-ICA1-no_pathlen.pem chainI-ICA2-key.pem chainI-ICA2-no_pathlen.pem chainI-ICA3-key.pem chainI-ICA3-pathlen2.pem chainI-assembled.pem chainI-entity-key.pem chainI-entity.pem chainJ-ICA1-key.pem chainJ-ICA1-no_pathlen.pem chainJ-ICA2-key.pem chainJ-ICA2-no_pathlen.pem chainJ-ICA3-key.pem chainJ-ICA3-no_pathlen.pem chainJ-ICA4-key.pem chainJ-ICA4-pathlen2.pem chainJ-assembled.pem chainJ-entity-key.pem chainJ-entity.pem include.am refreshkeys.sh
test-serial0 ee_normal.pem ee_serial0.pem generate_certs.sh include.am intermediate_serial0.pem root_serial0.pem root_serial0_key.pem selfsigned_nonca_serial0.pem
xmss bc_xmss_chain_ca.der bc_xmss_chain_leaf.der bc_xmss_sha2_10_256_root.der bc_xmss_sha2_16_256_root.der bc_xmssmt_sha2_20_2_256_root.der bc_xmssmt_sha2_20_4_256_root.der bc_xmssmt_sha2_40_8_256_root.der include.am
ca-cert-chain.der ca-cert.der ca-cert.pem ca-ecc-cert.der ca-ecc-cert.pem ca-ecc-key.der ca-ecc-key.pem ca-ecc384-cert.der ca-ecc384-cert.pem ca-ecc384-key.der ca-ecc384-key.pem ca-key-pkcs8-attribute.der ca-key.der ca-key.pem check_dates.sh client-absolute-urn.pem client-ca-cert.der client-ca-cert.pem client-ca.pem client-cert-ext.der client-cert-ext.pem client-cert.der client-cert.pem client-crl-dist.der client-crl-dist.pem client-ecc-ca-cert.der client-ecc-ca-cert.pem client-ecc-cert.der client-ecc-cert.pem client-ecc384-cert.der client-ecc384-cert.pem client-ecc384-key.der client-ecc384-key.pem client-key.der client-key.pem client-keyEnc.pem client-keyPub.der client-keyPub.pem client-relative-uri.pem client-uri-cert.pem csr.attr.der csr.dsa.der csr.dsa.pem csr.ext.der csr.signed.der dh-priv-2048.der dh-priv-2048.pem dh-pub-2048.der dh-pub-2048.pem dh-pubkey-2048.der dh2048.der dh2048.pem dh3072.der dh3072.pem dh4096.der dh4096.pem dsa-pubkey-2048.der dsa2048.der dsa2048.pem dsa3072.der dsaparams.der dsaparams.pem ecc-client-key.der ecc-client-key.pem ecc-client-keyPub.der ecc-client-keyPub.pem ecc-key-comp.pem ecc-keyPkcs8.der ecc-keyPkcs8.pem ecc-keyPkcs8Enc.der ecc-keyPkcs8Enc.pem ecc-keyPub.der ecc-keyPub.pem ecc-params.der ecc-params.pem ecc-privOnlyCert.pem ecc-privOnlyKey.pem ecc-privkey.der ecc-privkey.pem ecc-privkeyPkcs8.der ecc-privkeyPkcs8.pem ecc-rsa-server.p12 empty-issuer-cert.pem entity-no-ca-bool-cert.pem entity-no-ca-bool-key.pem fpki-cert.der fpki-certpol-cert.der gen_revoked.sh include.am renewcerts.sh rid-cert.der rsa-pub-2048.pem rsa2048.der rsa3072.der server-cert-chain.der server-cert.der server-cert.pem server-ecc-comp.der server-ecc-comp.pem server-ecc-rsa.der server-ecc-rsa.pem server-ecc-self.der server-ecc-self.pem server-ecc.der server-ecc.pem server-ecc384-cert.der server-ecc384-cert.pem server-ecc384-key.der server-ecc384-key.pem server-key.der server-key.pem server-keyEnc.pem server-keyPkcs8.der server-keyPkcs8.pem server-keyPkcs8Enc.der server-keyPkcs8Enc.pem server-keyPkcs8Enc12.pem server-keyPkcs8Enc2.pem server-keyPub.der server-keyPub.pem server-revoked-cert.pem server-revoked-key.pem taoCert.txt test-ber-exp02-05-2022.p7b test-degenerate.p7b test-multiple-recipients.p7b test-servercert-rc2.p12 test-servercert.p12 test-stream-dec.p7b test-stream-sign.p7b wolfssl-website-ca.pem x942dh2048.der x942dh2048.pem
cmake
consumer CMakeLists.txt README.md main.c
modules FindARIA.cmake FindOQS.cmake
Config.cmake.in README.md config.in functions.cmake include.am options.h.in wolfssl-config-version.cmake.in wolfssl-targets.cmake.in
debian
source format
changelog.in control.in copyright include.am libwolfssl-dev.install libwolfssl.install rules.in
doc
dox_comments
header_files aes.h arc4.h ascon.h asn.h asn_public.h blake2.h bn.h camellia.h chacha.h chacha20_poly1305.h cmac.h coding.h compress.h cryptocb.h curve25519.h curve448.h des3.h dh.h doxygen_groups.h doxygen_pages.h dsa.h ecc.h eccsi.h ed25519.h ed448.h error-crypt.h evp.h hash.h hmac.h iotsafe.h kdf.h logging.h md2.h md4.h md5.h memory.h ocsp.h pem.h pkcs11.h pkcs7.h poly1305.h psa.h puf.h pwdbased.h quic.h random.h ripemd.h rsa.h sakke.h sha.h sha256.h sha3.h sha512.h signature.h siphash.h srp.h ssl.h tfm.h types.h wc_encrypt.h wc_port.h wc_she.h wc_slhdsa.h wolfio.h
header_files-ja aes.h arc4.h ascon.h asn.h asn_public.h blake2.h bn.h camellia.h chacha.h chacha20_poly1305.h cmac.h coding.h compress.h cryptocb.h curve25519.h curve448.h des3.h dh.h doxygen_groups.h doxygen_pages.h dsa.h ecc.h eccsi.h ed25519.h ed448.h error-crypt.h evp.h hash.h hmac.h iotsafe.h kdf.h logging.h md2.h md4.h md5.h memory.h ocsp.h pem.h pkcs11.h pkcs7.h poly1305.h psa.h pwdbased.h quic.h random.h ripemd.h rsa.h sakke.h sha.h sha256.h sha3.h sha512.h signature.h siphash.h srp.h ssl.h tfm.h types.h wc_encrypt.h wc_port.h wolfio.h
formats
html
html_changes
search search.css search.js
customdoxygen.css doxygen.css menu.js menudata.js tabs.css
Doxyfile footer.html header.html mainpage.dox
pdf Doxyfile header.tex
images wolfssl_logo.png
QUIC.md README.txt README_DOXYGEN check_api.sh generate_documentation.sh include.am
examples
asn1 asn1.c dumpasn1.cfg gen_oid_names.rb include.am oid_names.h
async Makefile README.md async_client.c async_server.c async_tls.c async_tls.h include.am user_settings.h
benchmark include.am tls_bench.c tls_bench.h
client client.c client.h client.sln client.vcproj client.vcxproj include.am
configs README.md include.am user_settings_EBSnet.h user_settings_all.h user_settings_arduino.h user_settings_baremetal.h user_settings_ca.h user_settings_curve25519nonblock.h user_settings_dtls13.h user_settings_eccnonblock.h user_settings_espressif.h user_settings_fipsv2.h user_settings_fipsv5.h user_settings_min_ecc.h user_settings_openssl_compat.h user_settings_pkcs7.h user_settings_platformio.h user_settings_pq.h user_settings_rsa_only.h user_settings_stm32.h user_settings_template.h user_settings_tls12.h user_settings_tls13.h user_settings_wolfboot_keytools.h user_settings_wolfssh.h user_settings_wolftpm.h
crypto_policies
default wolfssl.txt
future wolfssl.txt
legacy wolfssl.txt
echoclient echoclient.c echoclient.h echoclient.sln echoclient.vcproj echoclient.vcxproj include.am quit
echoserver echoserver.c echoserver.h echoserver.sln echoserver.vcproj echoserver.vcxproj include.am
ocsp_responder include.am ocsp_responder.c ocsp_responder.h
pem include.am pem.c
sctp include.am sctp-client-dtls.c sctp-client.c sctp-server-dtls.c sctp-server.c
server include.am server.c server.h server.sln server.vcproj server.vcxproj
README.md include.am
linuxkm
patches
5.10.17 WOLFSSL_LINUXKM_HAVE_GET_RANDOM_CALLBACKS-5v10v17.patch
5.10.236 WOLFSSL_LINUXKM_HAVE_GET_RANDOM_CALLBACKS-5v10v236.patch
5.14.0-570.58.1.el9_6 WOLFSSL_LINUXKM_HAVE_GET_RANDOM_CALLBACKS-5v14-570v58v1-el9_6.patch
5.15 WOLFSSL_LINUXKM_HAVE_GET_RANDOM_CALLBACKS-5v15.patch
5.17 WOLFSSL_LINUXKM_HAVE_GET_RANDOM_CALLBACKS-5v17.patch
5.17-ubuntu-jammy-tegra WOLFSSL_LINUXKM_HAVE_GET_RANDOM_CALLBACKS-5v17-ubuntu-jammy-tegra.patch
6.1.73 WOLFSSL_LINUXKM_HAVE_GET_RANDOM_CALLBACKS-6v1v73.patch
6.12 WOLFSSL_LINUXKM_HAVE_GET_RANDOM_CALLBACKS-6v12.patch
6.15 WOLFSSL_LINUXKM_HAVE_GET_RANDOM_CALLBACKS-6v15.patch
7.0 WOLFSSL_LINUXKM_HAVE_GET_RANDOM_CALLBACKS-7v0.patch
regen-patches.sh
Kbuild Makefile README.md get_thread_size.c include.am linuxkm-fips-hash-wrapper.sh linuxkm-fips-hash.c linuxkm_memory.c linuxkm_memory.h linuxkm_wc_port.h lkcapi_aes_glue.c lkcapi_dh_glue.c lkcapi_ecdh_glue.c lkcapi_ecdsa_glue.c lkcapi_glue.c lkcapi_rsa_glue.c lkcapi_sha_glue.c module_exports.c.template module_hooks.c pie_redirect_table.c wolfcrypt.lds x86_vector_register_glue.c
m4 ax_add_am_macro.m4 ax_am_jobserver.m4 ax_am_macros.m4 ax_append_compile_flags.m4 ax_append_flag.m4 ax_append_link_flags.m4 ax_append_to_file.m4 ax_atomic.m4 ax_bsdkm.m4 ax_check_compile_flag.m4 ax_check_link_flag.m4 ax_compiler_version.m4 ax_count_cpus.m4 ax_create_generic_config.m4 ax_debug.m4 ax_file_escapes.m4 ax_harden_compiler_flags.m4 ax_linuxkm.m4 ax_print_to_file.m4 ax_pthread.m4 ax_require_defined.m4 ax_tls.m4 ax_vcs_checkout.m4 hexversion.m4 lib_socket_nsl.m4 visibility.m4
mcapi
wolfcrypt_mcapi.X
nbproject configurations.xml include.am project.xml
Makefile
wolfcrypt_test.X
nbproject configurations.xml include.am project.xml
Makefile
wolfssl.X
nbproject configurations.xml include.am project.xml
Makefile
zlib.X
nbproject configurations.xml include.am project.xml
Makefile
PIC32MZ-serial.h README crypto.c crypto.h include.am mcapi_test.c user_settings.h
mplabx
wolfcrypt_benchmark.X
nbproject configurations.xml include.am project.xml
Makefile
wolfcrypt_test.X
nbproject configurations.xml include.am project.xml
Makefile
wolfssl.X
nbproject configurations.xml include.am project.xml
Makefile
PIC32MZ-serial.h README benchmark_main.c include.am test_main.c user_settings.h
mqx
util_lib
Sources include.am util.c util.h
wolfcrypt_benchmark
Debugger K70FN1M0.mem init_kinetis.tcl mass_erase_kinetis.tcl
Sources include.am main.c main.h
ReferencedRSESystems.xml wolfcrypt_benchmark_twrk70f120m_Int_Flash_DDRData_Debug_PnE_U-MultiLink.launch wolfcrypt_benchmark_twrk70f120m_Int_Flash_DDRData_Release_PnE_U-MultiLink.launch wolfcrypt_benchmark_twrk70f120m_Int_Flash_SramData_Debug_JTrace.jlink wolfcrypt_benchmark_twrk70f120m_Int_Flash_SramData_Debug_JTrace.launch wolfcrypt_benchmark_twrk70f120m_Int_Flash_SramData_Debug_PnE_U-MultiLink.launch wolfcrypt_benchmark_twrk70f120m_Int_Flash_SramData_Release_PnE_U-MultiLink.launch
wolfcrypt_test
Debugger K70FN1M0.mem init_kinetis.tcl mass_erase_kinetis.tcl
Sources include.am main.c main.h
ReferencedRSESystems.xml wolfcrypt_test_twrk70f120m_Int_Flash_DDRData_Debug_PnE_U-MultiLink.launch wolfcrypt_test_twrk70f120m_Int_Flash_DDRData_Release_PnE_U-MultiLink.launch wolfcrypt_test_twrk70f120m_Int_Flash_SramData_Debug_JTrace.jlink wolfcrypt_test_twrk70f120m_Int_Flash_SramData_Debug_JTrace.launch wolfcrypt_test_twrk70f120m_Int_Flash_SramData_Debug_PnE_U-MultiLink.launch wolfcrypt_test_twrk70f120m_Int_Flash_SramData_Release_PnE_U-MultiLink.launch
wolfssl include.am
wolfssl_client
Debugger K70FN1M0.mem init_kinetis.tcl mass_erase_kinetis.tcl
Sources include.am main.c main.h
ReferencedRSESystems.xml wolfssl_client_twrk70f120m_Int_Flash_DDRData_Debug_PnE_U-MultiLink.launch wolfssl_client_twrk70f120m_Int_Flash_DDRData_Release_PnE_U-MultiLink.launch wolfssl_client_twrk70f120m_Int_Flash_SramData_Debug_JTrace.jlink wolfssl_client_twrk70f120m_Int_Flash_SramData_Debug_JTrace.launch wolfssl_client_twrk70f120m_Int_Flash_SramData_Debug_PnE_U-MultiLink.launch wolfssl_client_twrk70f120m_Int_Flash_SramData_Release_PnE_U-MultiLink.launch
README
rpm include.am spec.in
scripts
bench bench_functions.sh
aria-cmake-build-test.sh asn1_oid_sum.pl benchmark.test benchmark_compare.sh cleanup_testfiles.sh crl-gen-openssl.test crl-revoked.test dertoc.pl dtls.test dtlscid.test external.test google.test include.am makedistsmall.sh memtest.sh ocsp-responder-openssl-interop.test ocsp-stapling-with-ca-as-responder.test ocsp-stapling-with-wolfssl-responder.test ocsp-stapling.test ocsp-stapling2.test ocsp-stapling_tls13multi.test ocsp.test openssl.test openssl_srtp.test pem.test ping.test pkcallbacks.test psk.test resume.test rsapss.test sniffer-gen.sh sniffer-ipv6.pcap sniffer-static-rsa.pcap sniffer-testsuite.test sniffer-tls12-keylog.out sniffer-tls12-keylog.pcap sniffer-tls12-keylog.sslkeylog sniffer-tls13-dh-resume.pcap sniffer-tls13-dh.pcap sniffer-tls13-ecc-resume.pcap sniffer-tls13-ecc.pcap sniffer-tls13-hrr.pcap sniffer-tls13-keylog.out sniffer-tls13-keylog.pcap sniffer-tls13-keylog.sslkeylog sniffer-tls13-x25519-resume.pcap sniffer-tls13-x25519.pcap stm32l4-v4_0_1_build.sh tls13.test trusted_peer.test unit.test.in user_settings_asm.sh
src bio.c conf.c crl.c dtls.c dtls13.c include.am internal.c keys.c ocsp.c pk.c pk_ec.c pk_rsa.c quic.c sniffer.c ssl.c ssl_api_cert.c ssl_api_crl_ocsp.c ssl_api_pk.c ssl_asn1.c ssl_bn.c ssl_certman.c ssl_crypto.c ssl_ech.c ssl_load.c ssl_misc.c ssl_p7p12.c ssl_sess.c ssl_sk.c tls.c tls13.c wolfio.c x509.c x509_str.c
sslSniffer
sslSnifferTest README_WIN.md include.am snifftest.c sslSniffTest.vcproj sslSniffTest.vcxproj
README.md sslSniffer.vcproj sslSniffer.vcxproj
support gen-debug-trace-error-codes.sh include.am wolfssl.pc.in
tests
api api.h api_decl.h create_ocsp_test_blobs.py include.am test_aes.c test_aes.h test_arc4.c test_arc4.h test_ascon.c test_ascon.h test_ascon_kats.h test_asn.c test_asn.h test_blake2.c test_blake2.h test_camellia.c test_camellia.h test_certman.c test_certman.h test_chacha.c test_chacha.h test_chacha20_poly1305.c test_chacha20_poly1305.h test_cmac.c test_cmac.h test_curve25519.c test_curve25519.h test_curve448.c test_curve448.h test_des3.c test_des3.h test_dh.c test_dh.h test_digest.h test_dsa.c test_dsa.h test_dtls.c test_dtls.h test_ecc.c test_ecc.h test_ed25519.c test_ed25519.h test_ed448.c test_ed448.h test_evp.c test_evp.h test_evp_cipher.c test_evp_cipher.h test_evp_digest.c test_evp_digest.h test_evp_pkey.c test_evp_pkey.h test_hash.c test_hash.h test_hmac.c test_hmac.h test_md2.c test_md2.h test_md4.c test_md4.h test_md5.c test_md5.h test_mldsa.c test_mldsa.h test_mlkem.c test_mlkem.h test_ocsp.c test_ocsp.h test_ocsp_test_blobs.h test_ossl_asn1.c test_ossl_asn1.h test_ossl_bio.c test_ossl_bio.h test_ossl_bn.c test_ossl_bn.h test_ossl_cipher.c test_ossl_cipher.h test_ossl_dgst.c test_ossl_dgst.h test_ossl_dh.c test_ossl_dh.h test_ossl_dsa.c test_ossl_dsa.h test_ossl_ec.c test_ossl_ec.h test_ossl_ecx.c test_ossl_ecx.h test_ossl_mac.c test_ossl_mac.h test_ossl_obj.c test_ossl_obj.h test_ossl_p7p12.c test_ossl_p7p12.h test_ossl_pem.c test_ossl_pem.h test_ossl_rand.c test_ossl_rand.h test_ossl_rsa.c test_ossl_rsa.h test_ossl_sk.c test_ossl_sk.h test_ossl_x509.c test_ossl_x509.h test_ossl_x509_acert.c test_ossl_x509_acert.h test_ossl_x509_crypto.c test_ossl_x509_crypto.h test_ossl_x509_ext.c test_ossl_x509_ext.h test_ossl_x509_info.c test_ossl_x509_info.h test_ossl_x509_io.c test_ossl_x509_io.h test_ossl_x509_lu.c test_ossl_x509_lu.h test_ossl_x509_name.c test_ossl_x509_name.h test_ossl_x509_pk.c test_ossl_x509_pk.h test_ossl_x509_str.c test_ossl_x509_str.h test_ossl_x509_vp.c test_ossl_x509_vp.h test_pkcs12.c test_pkcs12.h test_pkcs7.c test_pkcs7.h test_poly1305.c test_poly1305.h test_random.c test_random.h test_rc2.c test_rc2.h test_ripemd.c test_ripemd.h test_rsa.c test_rsa.h test_sha.c test_sha.h test_sha256.c test_sha256.h test_sha3.c test_sha3.h test_sha512.c test_sha512.h test_she.c test_she.h test_signature.c test_signature.h test_slhdsa.c test_slhdsa.h test_sm2.c test_sm2.h test_sm3.c test_sm3.h test_sm4.c test_sm4.h test_tls.c test_tls.h test_tls13.c test_tls13.h test_tls_ext.c test_tls_ext.h test_wc_encrypt.c test_wc_encrypt.h test_wolfmath.c test_wolfmath.h test_x509.c test_x509.h
emnet
IP IP.h
Makefile emnet_nonblock_test.c emnet_shim.c
freertos-mem-track-repro FreeRTOS.h repro.c run.sh semphr.h task.h user_settings.h
swdev .gitignore Makefile README.md swdev.c swdev.h swdev_loader.c swdev_loader.h user_settings.h
CONF_FILES_README.md NCONF_test.cnf README TXT_DB.txt api.c include.am quic.c srp.c suites.c test-altchains.conf test-chains.conf test-dhprime.conf test-dtls-downgrade.conf test-dtls-fails-cipher.conf test-dtls-fails.conf test-dtls-group.conf test-dtls-mtu.conf test-dtls-reneg-client.conf test-dtls-reneg-server.conf test-dtls-resume.conf test-dtls-sha2.conf test-dtls-srtp-fails.conf test-dtls-srtp.conf test-dtls.conf test-dtls13-cid.conf test-dtls13-downgrade-fails.conf test-dtls13-downgrade.conf test-dtls13-pq-hybrid-extra-frag.conf test-dtls13-pq-hybrid-extra.conf test-dtls13-pq-hybrid-frag.conf test-dtls13-pq-standalone-frag.conf test-dtls13-pq-standalone.conf test-dtls13-psk.conf test-dtls13.conf test-ecc-cust-curves.conf test-ed25519.conf test-ed448.conf test-enckeys.conf test-fails.conf test-maxfrag-dtls.conf test-maxfrag.conf test-p521.conf test-psk-no-id-sha2.conf test-psk-no-id.conf test-psk.conf test-rsapss.conf test-sctp-sha2.conf test-sctp.conf test-sha2.conf test-sig.conf test-sm2.conf test-tls-downgrade.conf test-tls13-down.conf test-tls13-ecc.conf test-tls13-pq-hybrid-extra.conf test-tls13-pq-hybrid.conf test-tls13-pq-standalone.conf test-tls13-psk-certs.conf test-tls13-psk.conf test-tls13-slhdsa-fail.conf test-tls13-slhdsa-sha2.conf test-tls13-slhdsa-shake.conf test-tls13.conf test-trustpeer.conf test.conf unit.c unit.h utils.c utils.h w64wrapper.c
testsuite include.am testsuite.c testsuite.sln testsuite.vcproj testsuite.vcxproj utils.c utils.h
tirtos
packages
ti
net
wolfssl
tests
EK_TM4C1294XL
wolfcrypt
benchmark TM4C1294NC.icf benchmark.cfg main.c package.bld.hide package.xdc
test TM4C1294NC.icf main.c package.bld.hide package.xdc test.cfg
package.bld package.xdc package.xs
.gitignore README include.am products.mak wolfssl.bld wolfssl.mak
wolfcrypt
benchmark README.md benchmark-VS2022.sln benchmark-VS2022.vcxproj benchmark-VS2022.vcxproj.user benchmark.c benchmark.h benchmark.sln benchmark.vcproj benchmark.vcxproj include.am
src
port
Espressif
esp_crt_bundle README.md cacrt_all.pem cacrt_deprecated.pem cacrt_local.pem esp_crt_bundle.c gen_crt_bundle.py pio_install_cryptography.py
README.md esp32_aes.c esp32_mp.c esp32_sha.c esp32_util.c esp_sdk_mem_lib.c esp_sdk_time_lib.c esp_sdk_wifi_lib.c
Renesas README.md renesas_common.c renesas_fspsm_aes.c renesas_fspsm_rsa.c renesas_fspsm_sha.c renesas_fspsm_util.c renesas_rx64_hw_sha.c renesas_rx64_hw_util.c renesas_tsip_aes.c renesas_tsip_rsa.c renesas_tsip_sha.c renesas_tsip_util.c
af_alg afalg_aes.c afalg_hash.c wc_afalg.c
aria aria-crypt.c aria-cryptocb.c
arm armv8-32-aes-asm.S armv8-32-aes-asm_c.c armv8-32-chacha-asm.S armv8-32-chacha-asm_c.c armv8-32-curve25519.S armv8-32-curve25519_c.c armv8-32-mlkem-asm.S armv8-32-mlkem-asm_c.c armv8-32-poly1305-asm.S armv8-32-poly1305-asm_c.c armv8-32-sha256-asm.S armv8-32-sha256-asm_c.c armv8-32-sha3-asm.S armv8-32-sha3-asm_c.c armv8-32-sha512-asm.S armv8-32-sha512-asm_c.c armv8-aes-asm.S armv8-aes-asm_c.c armv8-aes.c armv8-chacha-asm.S armv8-chacha-asm_c.c armv8-curve25519.S armv8-curve25519_c.c armv8-mlkem-asm.S armv8-mlkem-asm_c.c armv8-poly1305-asm.S armv8-poly1305-asm_c.c armv8-sha256-asm.S armv8-sha256-asm_c.c armv8-sha256.c armv8-sha3-asm.S armv8-sha3-asm_c.c armv8-sha512-asm.S armv8-sha512-asm_c.c armv8-sha512.c cryptoCell.c cryptoCellHash.c thumb2-aes-asm.S thumb2-aes-asm_c.c thumb2-chacha-asm.S thumb2-chacha-asm_c.c thumb2-curve25519.S thumb2-curve25519_c.c thumb2-mlkem-asm.S thumb2-mlkem-asm_c.c thumb2-poly1305-asm.S thumb2-poly1305-asm_c.c thumb2-sha256-asm.S thumb2-sha256-asm_c.c thumb2-sha3-asm.S thumb2-sha3-asm_c.c thumb2-sha512-asm.S thumb2-sha512-asm_c.c
atmel README.md atmel.c
autosar README.md cryif.c crypto.c csm.c include.am test.c
caam README.md caam_aes.c caam_doc.pdf caam_driver.c caam_error.c caam_integrity.c caam_qnx.c caam_sha.c wolfcaam_aes.c wolfcaam_cmac.c wolfcaam_ecdsa.c wolfcaam_fsl_nxp.c wolfcaam_hash.c wolfcaam_hmac.c wolfcaam_init.c wolfcaam_qnx.c wolfcaam_rsa.c wolfcaam_seco.c wolfcaam_x25519.c
cavium README.md README_Octeon.md cavium_nitrox.c cavium_octeon_sync.c
cuda README.md aes-cuda.cu
cypress README.md psoc6_crypto.c
devcrypto README.md devcrypto_aes.c devcrypto_ecdsa.c devcrypto_hash.c devcrypto_hmac.c devcrypto_rsa.c devcrypto_x25519.c wc_devcrypto.c
intel README.md quickassist.c quickassist_mem.c quickassist_sync.c
iotsafe iotsafe.c
kcapi README.md kcapi_aes.c kcapi_dh.c kcapi_ecc.c kcapi_hash.c kcapi_hmac.c kcapi_rsa.c
liboqs liboqs.c
maxim README.md max3266x.c maxq10xx.c
mynewt mynewt_port.c
nxp README.md README_SE050.md casper_port.c dcp_port.c hashcrypt_port.c ksdk_port.c se050_port.c
pic32 pic32mz-crypt.c
ppc32 ppc32-sha256-asm.S ppc32-sha256-asm_c.c ppc32-sha256-asm_cr.c
psa README.md psa.c psa_aes.c psa_hash.c psa_pkcbs.c
riscv riscv-64-aes.c riscv-64-chacha.c riscv-64-poly1305.c riscv-64-sha256.c riscv-64-sha3.c riscv-64-sha512.c
rpi_pico README.md pico.c
silabs README.md silabs_aes.c silabs_ecc.c silabs_hash.c silabs_random.c
st README.md STM32MP13.md STM32MP25.md stm32.c stsafe.c
ti ti-aes.c ti-ccm.c ti-des3.c ti-hash.c
tropicsquare README.md tropic01.c
xilinx xil-aesgcm.c xil-sha3.c xil-versal-glue.c xil-versal-trng.c
nrf51.c
ASN_TEMPLATE.md aes.c aes_asm.S aes_asm.asm aes_gcm_asm.S aes_gcm_asm.asm aes_gcm_x86_asm.S aes_xts_asm.S aes_xts_asm.asm arc4.c ascon.c asm.c asn.c asn_orig.c async.c blake2b.c blake2s.c camellia.c chacha.c chacha20_poly1305.c chacha_asm.S chacha_asm.asm cmac.c coding.c compress.c cpuid.c cryptocb.c curve25519.c curve448.c des3.c dh.c dilithium.c dsa.c ecc.c ecc_fp.c eccsi.c ed25519.c ed448.c error.c evp.c evp_pk.c falcon.c fe_448.c fe_low_mem.c fe_operations.c fe_x25519_128.h fe_x25519_asm.S fp_mont_small.i fp_mul_comba_12.i fp_mul_comba_17.i fp_mul_comba_20.i fp_mul_comba_24.i fp_mul_comba_28.i fp_mul_comba_3.i fp_mul_comba_32.i fp_mul_comba_4.i fp_mul_comba_48.i fp_mul_comba_6.i fp_mul_comba_64.i fp_mul_comba_7.i fp_mul_comba_8.i fp_mul_comba_9.i fp_mul_comba_small_set.i fp_sqr_comba_12.i fp_sqr_comba_17.i fp_sqr_comba_20.i fp_sqr_comba_24.i fp_sqr_comba_28.i fp_sqr_comba_3.i fp_sqr_comba_32.i fp_sqr_comba_4.i fp_sqr_comba_48.i fp_sqr_comba_6.i fp_sqr_comba_64.i fp_sqr_comba_7.i fp_sqr_comba_8.i fp_sqr_comba_9.i fp_sqr_comba_small_set.i ge_448.c ge_low_mem.c ge_operations.c hash.c hmac.c hpke.c include.am integer.c kdf.c logging.c md2.c md4.c md5.c memory.c misc.c pkcs12.c pkcs7.c poly1305.c poly1305_asm.S poly1305_asm.asm puf.c pwdbased.c random.c rc2.c ripemd.c rng_bank.c rsa.c sakke.c sha.c sha256.c sha256_asm.S sha3.c sha3_asm.S sha512.c sha512_asm.S signature.c siphash.c sm2.c sm3.c sm3_asm.S sm4.c sp_arm32.c sp_arm64.c sp_armthumb.c sp_c32.c sp_c64.c sp_cortexm.c sp_dsp32.c sp_int.c sp_sm2_arm32.c sp_sm2_arm64.c sp_sm2_armthumb.c sp_sm2_c32.c sp_sm2_c64.c sp_sm2_cortexm.c sp_sm2_x86_64.c sp_sm2_x86_64_asm.S sp_x86_64.c sp_x86_64_asm.S sp_x86_64_asm.asm srp.c tfm.c wc_dsp.c wc_encrypt.c wc_lms.c wc_lms_impl.c wc_mldsa_asm.S wc_mlkem.c wc_mlkem_asm.S wc_mlkem_poly.c wc_pkcs11.c wc_port.c wc_she.c wc_slhdsa.c wc_xmss.c wc_xmss_impl.c wolfentropy.c wolfevent.c wolfmath.c
test README.md include.am test-VS2022.sln test-VS2022.vcxproj test-VS2022.vcxproj.user test.c test.h test.sln test.vcproj test_paths.h.in
wolfssl
openssl aes.h asn1.h asn1t.h bio.h bn.h buffer.h camellia.h cmac.h cms.h compat_types.h conf.h crypto.h des.h dh.h dsa.h ec.h ec25519.h ec448.h ecdh.h ecdsa.h ed25519.h ed448.h engine.h err.h evp.h fips_rand.h hmac.h include.am kdf.h lhash.h md4.h md5.h modes.h obj_mac.h objects.h ocsp.h opensslconf.h opensslv.h ossl_typ.h pem.h pkcs12.h pkcs7.h rand.h rc4.h ripemd.h rsa.h safestack.h sha.h sha3.h srp.h ssl.h ssl23.h stack.h tls1.h txt_db.h ui.h x509.h x509_vfy.h x509v3.h
wolfcrypt
port
Espressif esp-sdk-lib.h esp32-crypt.h esp_crt_bundle.h
Renesas renesas-fspsm-crypt.h renesas-fspsm-types.h renesas-rx64-hw-crypt.h renesas-tsip-crypt.h renesas_cmn.h renesas_fspsm_internal.h renesas_sync.h renesas_tsip_internal.h renesas_tsip_types.h
af_alg afalg_hash.h wc_afalg.h
aria aria-crypt.h aria-cryptocb.h
arm cryptoCell.h
atmel atmel.h
autosar CryIf.h Crypto.h Csm.h StandardTypes.h
caam caam_driver.h caam_error.h caam_qnx.h wolfcaam.h wolfcaam_aes.h wolfcaam_cmac.h wolfcaam_ecdsa.h wolfcaam_fsl_nxp.h wolfcaam_hash.h wolfcaam_qnx.h wolfcaam_rsa.h wolfcaam_seco.h wolfcaam_sha.h wolfcaam_x25519.h
cavium cavium_nitrox.h cavium_octeon_sync.h
cypress psoc6_crypto.h
devcrypto wc_devcrypto.h
intel quickassist.h quickassist_mem.h quickassist_sync.h
iotsafe iotsafe.h
kcapi kcapi_dh.h kcapi_ecc.h kcapi_hash.h kcapi_hmac.h kcapi_rsa.h wc_kcapi.h
liboqs liboqs.h
maxim max3266x-cryptocb.h max3266x.h maxq10xx.h
nxp casper_port.h dcp_port.h hashcrypt_port.h ksdk_port.h se050_port.h
pic32 pic32mz-crypt.h
psa psa.h
riscv riscv-64-asm.h
rpi_pico pico.h
silabs silabs_aes.h silabs_ecc.h silabs_hash.h silabs_random.h
st stm32.h stsafe.h
ti ti-ccm.h ti-hash.h
tropicsquare tropic01.h
xilinx xil-sha3.h xil-versal-glue.h xil-versal-trng.h
nrf51.h
aes.h arc4.h ascon.h asn.h asn_public.h async.h blake2-impl.h blake2-int.h blake2.h camellia.h chacha.h chacha20_poly1305.h cmac.h coding.h compress.h cpuid.h cryptocb.h curve25519.h curve448.h des3.h dh.h dilithium.h dsa.h ecc.h eccsi.h ed25519.h ed448.h error-crypt.h falcon.h fe_448.h fe_operations.h fips_test.h ge_448.h ge_operations.h hash.h hmac.h hpke.h include.am integer.h kdf.h libwolfssl_sources.h libwolfssl_sources_asm.h logging.h md2.h md4.h md5.h mem_track.h memory.h misc.h mpi_class.h mpi_superclass.h oid_sum.h pkcs11.h pkcs12.h pkcs7.h poly1305.h puf.h pwdbased.h random.h rc2.h ripemd.h rng_bank.h rsa.h sakke.h selftest.h settings.h sha.h sha256.h sha3.h sha512.h signature.h siphash.h sm2.h sm3.h sm4.h sp.h sp_int.h srp.h tfm.h types.h visibility.h wc_encrypt.h wc_lms.h wc_mlkem.h wc_pkcs11.h wc_port.h wc_she.h wc_slhdsa.h wc_xmss.h wolfentropy.h wolfevent.h wolfmath.h
callbacks.h certs_test.h certs_test_sm.h crl.h error-ssl.h include.am internal.h ocsp.h options.h.in quic.h sniffer.h sniffer_error.h sniffer_error.rc ssl.h test.h version.h version.h.in wolfio.h
wrapper
Ada
examples
src aes_verify_main.adb rsa_verify_main.adb sha256_main.adb spark_sockets.adb spark_sockets.ads spark_terminal.adb spark_terminal.ads tls_client.adb tls_client.ads tls_client_main.adb tls_server.adb tls_server.ads tls_server_main.adb
.gitignore alire.toml examples.gpr
tests
src
support test_support.adb test_support.ads tests_root_suite.adb tests_root_suite.ads
aes_bindings_tests.adb aes_bindings_tests.ads rsa_verify_bindings_tests.adb rsa_verify_bindings_tests.ads sha256_bindings_tests.adb sha256_bindings_tests.ads tests.adb
.gitignore README.md alire.toml tests.gpr valgrind.supp
.gitignore README.md ada_binding.c alire.toml default.gpr include.am restricted.adc user_settings.h wolfssl-full_runtime.adb wolfssl-full_runtime.ads wolfssl.adb wolfssl.ads wolfssl.gpr
CSharp
wolfCrypt-Test
Properties AssemblyInfo.cs
App.config wolfCrypt-Test.cs wolfCrypt-Test.csproj
wolfSSL-DTLS-PSK-Server
Properties AssemblyInfo.cs
App.config wolfSSL-DTLS-PSK-Server.cs wolfSSL-DTLS-PSK-Server.csproj
wolfSSL-DTLS-Server
Properties AssemblyInfo.cs
App.config wolfSSL-DTLS-Server.cs wolfSSL-DTLS-Server.csproj
wolfSSL-Example-IOCallbacks
Properties AssemblyInfo.cs
App.config wolfSSL-Example-IOCallbacks.cs wolfSSL-Example-IOCallbacks.csproj
wolfSSL-TLS-Client
Properties AssemblyInfo.cs
App.config wolfSSL-TLS-Client.cs wolfSSL-TLS-Client.csproj
wolfSSL-TLS-PSK-Client
Properties AssemblyInfo.cs
App.config wolfSSL-TLS-PSK-Client.cs wolfSSL-TLS-PSK-Client.csproj
wolfSSL-TLS-PSK-Server
Properties AssemblyInfo.cs
App.config wolfSSL-TLS-PSK-Server.cs wolfSSL-TLS-PSK-Server.csproj
wolfSSL-TLS-Server
Properties AssemblyInfo.cs
App.config wolfSSL-TLS-Server.cs wolfSSL-TLS-Server.csproj
wolfSSL-TLS-ServerThreaded
Properties AssemblyInfo.cs
App.config wolfSSL-TLS-ServerThreaded.cs wolfSSL-TLS-ServerThreaded.csproj
wolfSSL_CSharp
Properties AssemblyInfo.cs Resources.Designer.cs Resources.resx
X509.cs wolfCrypt.cs wolfSSL.cs wolfSSL_CSharp.csproj
README.md include.am user_settings.h wolfSSL_CSharp.sln wolfssl.vcxproj
python README.md
rust
wolfssl-wolfcrypt
src aes.rs blake2.rs chacha20_poly1305.rs cmac.rs cmac_mac.rs curve25519.rs dh.rs dilithium.rs ecc.rs ecdsa.rs ed25519.rs ed448.rs fips.rs hkdf.rs hmac.rs hmac_mac.rs kdf.rs lib.rs lms.rs mlkem.rs mlkem_kem.rs pbkdf2_password_hash.rs prf.rs random.rs rsa.rs rsa_pkcs1v15.rs sha.rs sha_digest.rs sys.rs
tests
common mod.rs
test_aes.rs test_blake2.rs test_chacha20_poly1305.rs test_cmac.rs test_cmac_mac.rs test_curve25519.rs test_dh.rs test_dilithium.rs test_ecc.rs test_ecdsa.rs test_ed25519.rs test_ed448.rs test_hkdf.rs test_hmac.rs test_hmac_mac.rs test_kdf.rs test_lms.rs test_mlkem.rs test_mlkem_kem.rs test_pbkdf2_password_hash.rs test_prf.rs test_random.rs test_rsa.rs test_rsa_pkcs1v15.rs test_sha.rs test_sha_digest.rs test_wolfcrypt.rs
CHANGELOG.md Cargo.lock Cargo.toml Makefile README.md build.rs headers.h
Makefile README.md include.am
include.am
zephyr
samples
wolfssl_benchmark
boards native_sim.conf nrf5340dk_nrf5340_cpuapp.conf nrf5340dk_nrf5340_cpuapp_ns.conf
CMakeLists.txt README install_test.sh prj.conf sample.yaml zephyr_legacy.conf zephyr_v4.1.conf
wolfssl_test
boards native_sim.conf nrf5340dk_nrf5340_cpuapp.conf nrf5340dk_nrf5340_cpuapp_ns.conf
CMakeLists.txt README install_test.sh prj-no-malloc.conf prj.conf sample.yaml zephyr_legacy.conf zephyr_v4.1.conf
wolfssl_tls_sock
boards native_sim.conf
src tls_sock.c
CMakeLists.txt README install_sample.sh prj-no-malloc.conf prj.conf sample.yaml zephyr_legacy.conf zephyr_v4.1.conf
wolfssl_tls_thread
boards native_sim.conf nrf5340dk_nrf5340_cpuapp.conf nrf5340dk_nrf5340_cpuapp_ns.conf
src tls_threaded.c
CMakeLists.txt README install_sample.sh prj.conf sample.yaml zephyr_legacy.conf zephyr_v4.1.conf
wolfssl options.h
CMakeLists.txt Kconfig Kconfig.tls-generic README.md include.am module.yml user_settings-no-malloc.h user_settings.h zephyr_init.c
.codespellexcludelines .cyignore .editorconfig .gitignore .wolfssl_known_macro_extras AUTHORS CMakeLists.txt CMakePresets.json CMakeSettings.json COPYING ChangeLog.md INSTALL LICENSING LPCExpresso.cproject LPCExpresso.project Makefile.am README README-async.md README.md SCRIPTS-LIST SECURITY-POLICY.md SECURITY-REPORT-TEMPLATE.md Vagrantfile autogen.sh commit-tests.sh configure.ac fips-check.sh fips-hash.sh gencertbuf.pl input pull_to_vagrant.sh quit resource.h stamp-h.in valgrind-bash.supp valgrind-error.sh wnr-example.conf wolfssl-VS2022.vcxproj wolfssl.rc wolfssl.vcproj wolfssl.vcxproj wolfssl64.sln
.clangd .gitignore DOCS.md Makefile README.md assert.c core.c crypto.c env.c fs.c http.c ini.c json.c log.c luna.h main.c makext.mk path.c process.c request.c sqlite.c stash.c template.c util.c
wolfssl/wolfcrypt/src/wc_slhdsa.c raw
   1/* wc_slhdsa.c
   2 *
   3 * Copyright (C) 2006-2026 wolfSSL Inc.
   4 *
   5 * This file is part of wolfSSL.
   6 *
   7 * wolfSSL is free software; you can redistribute it and/or modify
   8 * it under the terms of the GNU General Public License as published by
   9 * the Free Software Foundation; either version 3 of the License, or
  10 * (at your option) any later version.
  11 *
  12 * wolfSSL is distributed in the hope that it will be useful,
  13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
  14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15 * GNU General Public License for more details.
  16 *
  17 * You should have received a copy of the GNU General Public License
  18 * along with this program; if not, write to the Free Software
  19 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1335, USA
  20 */
  21
  22#include <wolfssl/wolfcrypt/libwolfssl_sources.h>
  23
  24#if FIPS_VERSION3_GE(2,0,0)
  25    /* set NO_WRAPPERS before headers, use direct internal f()s not wrappers */
  26    #define FIPS_NO_WRAPPERS
  27#endif
  28
  29#include <wolfssl/wolfcrypt/wc_slhdsa.h>
  30
  31#ifdef WOLFSSL_HAVE_SLHDSA
  32
  33#include <wolfssl/wolfcrypt/asn.h>
  34#include <wolfssl/wolfcrypt/cpuid.h>
  35#include <wolfssl/wolfcrypt/error-crypt.h>
  36#ifdef NO_INLINE
  37    #include <wolfssl/wolfcrypt/misc.h>
  38#else
  39    #define WOLFSSL_MISC_INCLUDED
  40    #include <wolfcrypt/src/misc.c>
  41#endif
  42#include <wolfssl/wolfcrypt/hash.h>
  43#include <wolfssl/wolfcrypt/sha3.h>
  44#ifdef WOLFSSL_SLHDSA_SHA2
  45    #include <wolfssl/wolfcrypt/sha256.h>
  46    #include <wolfssl/wolfcrypt/sha512.h>
  47    #include <wolfssl/wolfcrypt/hmac.h>
  48#endif
  49
  50#ifdef WC_SLHDSA_NO_ASM
  51    #undef USE_INTEL_SPEEDUP
  52    #undef WOLFSSL_ARMASM
  53    #undef WOLFSSL_RISCV_ASM
  54#endif
  55
  56#if defined(USE_INTEL_SPEEDUP)
  57/* CPU information for Intel. */
  58static cpuid_flags_t cpuid_flags = WC_CPUID_INITIALIZER;
  59#endif
  60
  61
  62/* Winternitz number. */
  63#define SLHDSA_W                16
  64/* Number of iterations of hashing itself from Winternitz number. */
  65#define SLHDSA_WM1              (SLHDSA_W - 1)
  66
  67
  68#ifndef WOLFSSL_SLHDSA_PARAM_NO_256
  69    /* Maximum size of hash output. */
  70    #define SLHDSA_MAX_N                32
  71    #ifndef WOLFSSL_SLHDSA_PARAM_NO_FAST
  72        /* Maximum number of indices for FORS signatures. */
  73        #define SLHDSA_MAX_INDICES_SZ   35
  74    #else
  75        /* Maximum number of indices for FORS signatures. */
  76        #define SLHDSA_MAX_INDICES_SZ   22
  77    #endif
  78#elif !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
  79    /* Maximum size of hash output. */
  80    #define SLHDSA_MAX_N                24
  81    #ifndef WOLFSSL_SLHDSA_PARAM_NO_FAST
  82        /* Maximum number of indices for FORS signatures. */
  83        #define SLHDSA_MAX_INDICES_SZ   33
  84    #else
  85        /* Maximum number of indices for FORS signatures. */
  86        #define SLHDSA_MAX_INDICES_SZ   17
  87    #endif
  88#else
  89    /* Maximum size of hash output. */
  90    #define SLHDSA_MAX_N                16
  91    #ifndef WOLFSSL_SLHDSA_PARAM_NO_FAST
  92        /* Maximum number of indices for FORS signatures. */
  93        #define SLHDSA_MAX_INDICES_SZ   33
  94    #else
  95        /* Maximum number of indices for FORS signatures. */
  96        #define SLHDSA_MAX_INDICES_SZ   14
  97    #endif
  98#endif
  99
 100#ifndef WOLFSSL_SLHDSA_PARAM_NO_SMALL
 101    #if !defined(WOLFSSL_SLHDSA_PARAM_NO_256)
 102        /* Maximum number of trees for FORS. */
 103        #define SLHDSA_MAX_A            14
 104    #elif !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
 105        /* Maximum number of trees for FORS. */
 106        #define SLHDSA_MAX_A            14
 107    #else
 108        /* Maximum number of trees for FORS. */
 109        #define SLHDSA_MAX_A            12
 110    #endif
 111#else
 112    #if !defined(WOLFSSL_SLHDSA_PARAM_NO_256)
 113        /* Maximum number of trees for FORS. */
 114        #define SLHDSA_MAX_A            9
 115    #elif !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
 116        /* Maximum number of trees for FORS. */
 117        #define SLHDSA_MAX_A            8
 118    #else
 119        /* Maximum number of trees for FORS. */
 120        #define SLHDSA_MAX_A            6
 121    #endif
 122#endif
 123
 124#ifndef WOLFSSL_SLHDSA_PARAM_NO_SMALL
 125    /* Maximum height of Merkle tree. */
 126    #define SLHDSA_MAX_H_M              9
 127#else
 128    /* Maximum height of Merkle tree. */
 129    #define SLHDSA_MAX_H_M              3
 130#endif
 131
 132/* Maximum message size in nibbles. */
 133#define SLHDSA_MAX_MSG_SZ       ((2 * SLHDSA_MAX_N) + 3)
 134
 135/* SLH-DSA WOTS+ length: len = len_1 + len_2 = 2*n + 3 (for w=16). The chain
 136 * helpers below pass loop indices and chain steps through (byte) casts; this
 137 * assertion documents the invariant they rely on. */
 138wc_static_assert(SLHDSA_MAX_MSG_SZ <= 255);
 139
 140#ifndef WOLFSSL_SLHDSA_PARAM_NO_256F
 141    /* Maximum number of bytes to produce from digest of message. */
 142    #define SLHDSA_MAX_MD               49
 143#elif !defined(WOLFSSL_SLHDSA_PARAM_NO_256S)
 144    /* Maximum number of bytes to produce from digest of message. */
 145    #define SLHDSA_MAX_MD               47
 146#elif !defined(WOLFSSL_SLHDSA_PARAM_NO_192F)
 147    /* Maximum number of bytes to produce from digest of message. */
 148    #define SLHDSA_MAX_MD               42
 149#elif !defined(WOLFSSL_SLHDSA_PARAM_NO_192S)
 150    /* Maximum number of bytes to produce from digest of message. */
 151    #define SLHDSA_MAX_MD               39
 152#elif !defined(WOLFSSL_SLHDSA_PARAM_NO_128F)
 153    /* Maximum number of bytes to produce from digest of message. */
 154    #define SLHDSA_MAX_MD               34
 155#else
 156    /* Maximum number of bytes to produce from digest of message. */
 157    #define SLHDSA_MAX_MD               30
 158#endif
 159
 160
 161/******************************************************************************
 162 * HashAddress
 163 ******************************************************************************/
 164
 165/* HashAddress types. */
 166/* WOTS+ hash. */
 167#define HA_WOTS_HASH    0
 168/* WOTS+ Public Key. */
 169#define HA_WOTS_PK      1
 170/* XMSS tree. */
 171#define HA_TREE         2
 172/* FORS tree. */
 173#define HA_FORS_TREE    3
 174/* FORS Root. */
 175#define HA_FORS_ROOTS   4
 176/* WOTS Pseudo-random function. */
 177#define HA_WOTS_PRF     5
 178/* FORS Pseudo-random function. */
 179#define HA_FORS_PRF     6
 180
 181/* Size of an encoded HashAddress. */
 182#define SLHDSA_HA_SZ    32
 183
 184/* Initialize a HashAddress.
 185 *
 186 * @param [in] a  HashAddress to initialize.
 187 */
 188#define HA_Init(a)                  XMEMSET(a, 0, sizeof(HashAddress))
 189/* Copy a HashAddress.
 190 *
 191 * @param [out] a  HashAddress to copy into.
 192 * @param [in]  b  HashAddress to copy from.
 193 */
 194#define HA_Copy(a, b)               XMEMCPY(a, b, sizeof(HashAddress))
 195/* Set layer address into HashAddress.
 196 *
 197 * FIPS 205. Section 4.3. Table 1. Line 1.
 198 *
 199 * @param [in] a  HashAddress set.
 200 * @param [in] l  Layer address.
 201 */
 202#define HA_SetLayerAddress(a, l)    (a)[0] = (word32)(l)
 203/* Set tree address into HashAddress.
 204 *
 205 * FIPS 205. Section 4.3. Table 1. Line 2.
 206 *
 207 * @param [in] a  HashAddress set.
 208 * @param [in] t  Tree address.
 209 */
 210#define HA_SetTreeAddress(a, t)                                                \
 211    do { (a)[1] = (t)[0]; (a)[2] = (t)[1]; (a)[3] = (t)[2]; } while (0)
 212/* Set type and clear following fields.
 213 *
 214 * FIPS 205. Section 4.3. Table 1. Line 3.
 215 *
 216 * @param [in] a  HashAddress set.
 217 * @param [in] y  HashAddress type.
 218 */
 219#define HA_SetTypeAndClear(a, y)                                               \
 220    do { (a)[4] = (word32)(y); (a)[5] = 0U; (a)[6] = 0U; (a)[7] = 0U; } while (0)
 221/* Set type and clear following fields but not Key Pair Address.
 222 *
 223 * FIPS 205. Section 4.3. Table 1. Line 3. But don't clear Key Pair Address.
 224 *
 225 * @param [in] a  HashAddress set.
 226 * @param [in] y  HashAddress type.
 227 */
 228#define HA_SetTypeAndClearNotKPA(a, y)                                         \
 229    do { (a)[4] = (word32)(y); (a)[6] = 0U; (a)[7] = 0U; } while (0)
 230/* Set key pair address into HashAddress.
 231 *
 232 * FIPS 205. Section 4.3. Table 1. Line 4.
 233 *
 234 * @param [in] a  HashAddress set.
 235 * @param [in] i  Key pair address.
 236 */
 237#define HA_SetKeyPairAddress(a, i)  (a)[5] = (word32)(i)
 238/* Set chain address into HashAddress.
 239 *
 240 * FIPS 205. Section 4.3. Table 1. Line 5.
 241 *
 242 * @param [in] a  HashAddress set.
 243 * @param [in] i  Chain address.
 244 */
 245#define HA_SetChainAddress(a, i)    (a)[6] = (word32)(i)
 246/* Set tree height into HashAddress.
 247 *
 248 * FIPS 205. Section 4.3. Table 1. Line 5.
 249 *
 250 * @param [in] a  HashAddress set.
 251 * @param [in] i  Tree height.
 252 */
 253#define HA_SetTreeHeight(a, i)      (a)[6] = (word32)(i)
 254/* Set tree height as big-endian into HashAddress.
 255 *
 256 * FIPS 205. Section 4.3. Table 1. Line 5. But encode value big-endian.
 257 *
 258 * @param [in] a  HashAddress set.
 259 * @param [in] i  Tree height.
 260 */
 261#define HA_SetTreeHeightBE(a, i)    c32toa((word32)(i), (a) + (6 * 4))
 262/* Set hash address into HashAddress.
 263 *
 264 * FIPS 205. Section 4.3. Table 1. Line 6.
 265 *
 266 * @param [in] a  HashAddress set.
 267 * @param [in] i  Hash address.
 268 */
 269#define HA_SetHashAddress(a, i)     (a)[7] = (word32)(i)
 270/* Set tree index into HashAddress.
 271 *
 272 * FIPS 205. Section 4.3. Table 1. Line 6.
 273 *
 274 * @param [in] a  HashAddress set.
 275 * @param [in] i  Tree index.
 276 */
 277#define HA_SetTreeIndex(a, i)       (a)[7] = (word32)(i)
 278/* Copy key pair address from one HashAddress to another.
 279 *
 280 * FIPS 205. Section 4.3. Table 1. Line 4 and 7.
 281 *
 282 * @param [in] a  HashAddress to copy into.
 283 * @param [in] b  HashAddress to copy from.
 284 */
 285#define HA_CopyKeyPairAddress(a, b) (a)[5] = (b)[5]
 286
 287/* FIPS 205. Section 4.3. Table 1. Line 8 - Get tree index is not needed as
 288 * index is set and index value modified before being set again.
 289 */
 290
 291/* HashAddress type. */
 292typedef word32 HashAddress[8];
 293
 294/* Encode a HashAddress.
 295 *
 296 * @param [in]  adrs     HashAddress to encode.
 297 * @param [out] address  Buffer to encode into.
 298 */
 299static void HA_Encode(const word32* adrs, byte* address)
 300{
 301#ifndef WOLFSSL_WC_SLHDSA_SMALL
 302    c32toa(adrs[0], address + (0 * 4));
 303    c32toa(adrs[1], address + (1 * 4));
 304    c32toa(adrs[2], address + (2 * 4));
 305    c32toa(adrs[3], address + (3 * 4));
 306    c32toa(adrs[4], address + (4 * 4));
 307    c32toa(adrs[5], address + (5 * 4));
 308    c32toa(adrs[6], address + (6 * 4));
 309    c32toa(adrs[7], address + (7 * 4));
 310#else
 311    int i;
 312
 313    for (i = 0; i < 8; i++) {
 314        c32toa(adrs[i], address + (i * 4));
 315    }
 316#endif
 317}
 318
 319/******************************************************************************
 320 * Index Tree - 3 x 32-bit words
 321 ******************************************************************************/
 322
 323/* Mask the tree index.
 324 *
 325 * @param [in] t     Tree index.
 326 * @param [in] mask  Mask to apply to index.
 327 * @return  Masked tree index.
 328 */
 329#define INDEX_TREE_MASK(t, mask)    ((t)[2] & (mask))
 330
 331/* Shift the tree index down by a number of bits.
 332 *
 333 * @param [in] t  Tree index.
 334 * @param [in] b  Number of bits to shift.
 335 */
 336#define INDEX_TREE_SHIFT_DOWN(t, b)                     \
 337    (t)[2] = ((t)[1] << (32 - (b))) | ((t)[2] >> (b));  \
 338    (t)[1] =                           (t)[1] >> (b);
 339
 340/******************************************************************************
 341 * Parameters
 342 ******************************************************************************/
 343
 344/* Create parameter entry.
 345 *
 346 * Other parameters:
 347 *   len = 2 * n + 3
 348 *   dl1 = upper((k * a) / 8)
 349 *   dl2 = upper((h - (h / d)) / 8)
 350 *   dl3 = upper(h / (8 * d))
 351 *   sigLen = Root +     FORS SK + FORS AUTH + d * (XMSS SIG + XMSS AUTH)
 352 *           (   1 +           k +     k * a + d * (      h2 +       len)) * n
 353 *
 354 * @param [in] p    Parameter name.
 355 * @param [in] n    Hash size in bytes.
 356 * @param [in] h    Total tree height.
 357 * @param [in] d    Depth of subtree.
 358 * @param [in] h_m  Height of message tree - XMSS tree.
 359 * @param [in] a    Number of authentication nodes.
 360 * @param [in] k    Number of FORS signatures.
 361 */
 362#define SLHDSA_PARAMETERS(p, n, h, d, h_m, a, k)    \
 363    { (p), (n), (h), (d), (h_m), (a), (k),          \
 364      2 * (n) + 3,                                  \
 365      (((k) * (a)) + 7) / 8,                        \
 366      (((h) - ((h) / (d))) + 7) / 8,                \
 367      ((h) + ((8 * (d)) - 1)) / (8 * (d)),          \
 368      (1 + (k) * (1 + (a)) + (d) * ((h_m) + 2*(n) + 3)) * (n) }
 369
 370/* An array of known parameters.
 371 *
 372 * FIPS 205. Section 11. Table 2.
 373 */
 374static const SlhDsaParameters SlhDsaParams[] =
 375{
 376                                     /*  n,  h,  d, h_m,  a,  k */
 377#ifndef WOLFSSL_SLHDSA_PARAM_NO_128S
 378    SLHDSA_PARAMETERS(SLHDSA_SHAKE128S, 16, 63,  7,   9, 12, 14),
 379#endif
 380#ifndef WOLFSSL_SLHDSA_PARAM_NO_128F
 381    SLHDSA_PARAMETERS(SLHDSA_SHAKE128F, 16, 66, 22,   3,  6, 33),
 382#endif
 383#ifndef WOLFSSL_SLHDSA_PARAM_NO_192S
 384    SLHDSA_PARAMETERS(SLHDSA_SHAKE192S, 24, 63,  7,   9, 14, 17),
 385#endif
 386#ifndef WOLFSSL_SLHDSA_PARAM_NO_192F
 387    SLHDSA_PARAMETERS(SLHDSA_SHAKE192F, 24, 66, 22,   3,  8, 33),
 388#endif
 389#ifndef WOLFSSL_SLHDSA_PARAM_NO_256S
 390    SLHDSA_PARAMETERS(SLHDSA_SHAKE256S, 32, 64,  8,   8, 14, 22),
 391#endif
 392#ifndef WOLFSSL_SLHDSA_PARAM_NO_256F
 393    SLHDSA_PARAMETERS(SLHDSA_SHAKE256F, 32, 68, 17,   4,  9, 35),
 394#endif
 395#ifdef WOLFSSL_SLHDSA_SHA2
 396                                     /*  n,  h,  d, h_m,  a,  k */
 397#ifndef WOLFSSL_SLHDSA_PARAM_NO_SHA2_128S
 398    SLHDSA_PARAMETERS(SLHDSA_SHA2_128S,  16, 63,  7,   9, 12, 14),
 399#endif
 400#ifndef WOLFSSL_SLHDSA_PARAM_NO_SHA2_128F
 401    SLHDSA_PARAMETERS(SLHDSA_SHA2_128F,  16, 66, 22,   3,  6, 33),
 402#endif
 403#ifndef WOLFSSL_SLHDSA_PARAM_NO_SHA2_192S
 404    SLHDSA_PARAMETERS(SLHDSA_SHA2_192S,  24, 63,  7,   9, 14, 17),
 405#endif
 406#ifndef WOLFSSL_SLHDSA_PARAM_NO_SHA2_192F
 407    SLHDSA_PARAMETERS(SLHDSA_SHA2_192F,  24, 66, 22,   3,  8, 33),
 408#endif
 409#ifndef WOLFSSL_SLHDSA_PARAM_NO_SHA2_256S
 410    SLHDSA_PARAMETERS(SLHDSA_SHA2_256S,  32, 64,  8,   8, 14, 22),
 411#endif
 412#ifndef WOLFSSL_SLHDSA_PARAM_NO_SHA2_256F
 413    SLHDSA_PARAMETERS(SLHDSA_SHA2_256F,  32, 68, 17,   4,  9, 35),
 414#endif
 415#endif /* WOLFSSL_SLHDSA_SHA2 */
 416};
 417
 418/* Number of parameters in array. */
 419#define SLHDSA_PARAM_LEN    \
 420    ((int)(sizeof(SlhDsaParams) / sizeof(SlhDsaParameters)))
 421
 422/******************************************************************************
 423 * Hashes
 424 ******************************************************************************/
 425
 426#ifndef WOLFSSL_WC_SLHDSA_SMALL
 427/* Hash three data elements with SHAKE-256.
 428 *
 429 * Will be less than WC_SHA3_256_COUNT * 8 bytes of data.
 430 *
 431 * @param [in]  shake      SHAKE-256 object.
 432 * @param [in]  data1      First block of data to hash.
 433 * @param [in]  data1_len  Length of first block of data.
 434 * @param [in]  adrs       Unencoded HashAddress.
 435 * @param [in]  data2      Second block of data to hash.
 436 * @param [in]  data2_len  Length of second block of data.
 437 * @param [out] hash       Hash output.
 438 * @param [in]  hash_len   Length of hash to output in bytes.
 439 * @return  0 on success.
 440 * @return  SHAKE-256 error return code on digest failure.
 441 */
 442static int slhdsakey_hash_shake_3(wc_Shake* shake, const byte* data1,
 443    byte data1_len, const word32* adrs, const byte* data2, byte data2_len,
 444    byte* hash, byte hash_len)
 445{
 446#ifdef WOLFSSL_SLHDSA_FULL_HASH
 447    int ret;
 448    byte address[SLHDSA_HA_SZ];
 449
 450    /* Encode hash address. */
 451    HA_Encode(adrs, address);
 452
 453    /* Update the SHAKE-256 object with first block of data. */
 454    ret = wc_Shake256_Update(shake, data1, data1_len);
 455    if (ret == 0) {
 456        /* Update the SHAKE-256 object with encoded HashAddress. */
 457        ret = wc_Shake256_Update(shake, address, SLHDSA_HA_SZ);
 458    }
 459    if (ret == 0) {
 460        /* Update the SHAKE-256 object with second block of data. */
 461        ret = wc_Shake256_Update(shake, data2, data2_len);
 462    }
 463    if (ret == 0) {
 464        /* Calculate and output hash. */
 465        ret = wc_Shake256_Final(shake, hash, hash_len);
 466    }
 467
 468    return ret;
 469#elif defined(USE_INTEL_SPEEDUP)
 470    word64* state = shake->s;
 471    word8* state8 = (word8*)shake->s;
 472    word32 o = 0;
 473
 474    /* Move the first block of data into the state. */
 475    XMEMCPY(state8 + o, data1, data1_len);
 476    o += data1_len;
 477    /* Encode the HashAddress into the state next. */
 478    HA_Encode(adrs, state8 + o);
 479    o += SLHDSA_HA_SZ;
 480    /* Move the second block of data into the state next. */
 481    XMEMCPY(state8 + o, data2, data2_len);
 482    o += data2_len;
 483    /* Place SHAKE end-of-content marker. */
 484    state8[o] = 0x1f;
 485    o += 1;
 486    /* Zero out rest of state. */
 487    XMEMSET(state8 + o, 0, sizeof(shake->s) - o);
 488    /* Place SHAKE-256 end-of-data marker. */
 489    state8[WC_SHA3_256_COUNT * 8 - 1] ^= 0x80;
 490
 491#ifndef WC_SHA3_NO_ASM
 492    /* Check availability of AVX2 instructions. */
 493    if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) {
 494        /* Process the state using AVX2 instructions. */
 495        sha3_block_avx2(state);
 496        RESTORE_VECTOR_REGISTERS();
 497    }
 498    /* Check availability of BMI2 instructions. */
 499    else if (IS_INTEL_BMI2(cpuid_flags)) {
 500        /* Process the state using BMI2 instructions. */
 501        sha3_block_bmi2(state);
 502    }
 503    else
 504#endif
 505    {
 506        /* Process the state using C code. */
 507        BlockSha3(state);
 508    }
 509    /* Copy hash result, of the required length, from the state into hash. */
 510    XMEMCPY(hash, shake->s, hash_len);
 511
 512    return 0;
 513#else
 514    /* Copy the first block of data into the cached data buffer. */
 515    XMEMCPY(shake->t, data1, data1_len);
 516    /* Encode HashAddress into the cached data buffer next. */
 517    HA_Encode(adrs, shake->t + data1_len);
 518    /* Copy the second block of data into the cached data buffer next. */
 519    XMEMCPY(shake->t + data1_len + SLHDSA_HA_SZ, data2, data2_len);
 520
 521    /* Update count of bytes cached. */
 522    shake->i = (byte)(data1_len + SLHDSA_HA_SZ + data2_len);
 523
 524    /* Calculate and output hash. */
 525    return wc_Shake256_Final(shake, hash, hash_len);
 526#endif
 527}
 528#endif
 529
 530/* Hash four data elements with SHAKE-256.
 531 *
 532 * Will be less than WC_SHA3_256_COUNT * 8 bytes of data.
 533 *
 534 * @param [in]  shake      SHAKE-256 object.
 535 * @param [in]  data1      First block of data to hash.
 536 * @param [in]  data1_len  Length of first block of data.
 537 * @param [in]  adrs       Unencoded HashAddress.
 538 * @param [in]  data2      Second block of data to hash.
 539 * @param [in]  data2_len  Length of second block of data.
 540 * @param [in]  data3      Third block of data to hash.
 541 * @param [in]  data3_len  Length of third block of data.
 542 * @param [out] hash       Hash output.
 543 * @param [in]  hash_len   Length of hash to output in bytes.
 544 * @return  0 on success.
 545 * @return  SHAKE-256 error return code on digest failure.
 546 */
 547static int slhdsakey_hash_shake_4(wc_Shake* shake, const byte* data1,
 548    byte data1_len, const word32* adrs, const byte* data2, byte data2_len,
 549    const byte* data3, byte data3_len, byte* hash, byte hash_len)
 550{
 551#ifdef WOLFSSL_SLHDSA_FULL_HASH
 552    int ret;
 553    byte address[SLHDSA_HA_SZ];
 554
 555    /* Encode hash address. */
 556    HA_Encode(adrs, address);
 557
 558    /* Update the SHAKE-256 object with first block of data. */
 559    ret = wc_Shake256_Update(shake, data1, data1_len);
 560    if (ret == 0) {
 561        /* Update the SHAKE-256 object with encoded HashAddress. */
 562        ret = wc_Shake256_Update(shake, address, SLHDSA_HA_SZ);
 563    }
 564    if (ret == 0) {
 565        /* Update the SHAKE-256 object with second block of data. */
 566        ret = wc_Shake256_Update(shake, data2, data2_len);
 567    }
 568    if (ret == 0) {
 569        /* Update the SHAKE-256 object with third block of data. */
 570        ret = wc_Shake256_Update(shake, data3, data3_len);
 571    }
 572    if (ret == 0) {
 573        /* Calculate and output hash. */
 574        ret = wc_Shake256_Final(shake, hash, hash_len);
 575    }
 576
 577    return ret;
 578#elif defined(USE_INTEL_SPEEDUP)
 579    word64* state = shake->s;
 580    word8* state8 = (word8*)shake->s;
 581    word32 o = 0;
 582
 583    /* Move the first block of data into the state. */
 584    XMEMCPY(state8 + o, data1, data1_len);
 585    o += data1_len;
 586    /* Encode the HashAddress into the state next. */
 587    HA_Encode(adrs, state8 + o);
 588    o += SLHDSA_HA_SZ;
 589    /* Move the second block of data into the state next. */
 590    XMEMCPY(state8 + o, data2, data2_len);
 591    o += data2_len;
 592    /* Move the third block of data into the state next. */
 593    XMEMCPY(state8 + o, data3, data3_len);
 594    o += data3_len;
 595    /* Place SHAKE end-of-content marker. */
 596    state8[o] = 0x1f;
 597    o += 1;
 598    /* Zero out rest of state. */
 599    XMEMSET(state8 + o, 0, sizeof(shake->s) - o);
 600    /* Place SHAKE-256 end-of-data marker. */
 601    state8[WC_SHA3_256_COUNT * 8 - 1] ^= 0x80;
 602
 603#ifndef WC_SHA3_NO_ASM
 604    /* Check availability of AVX2 instructions. */
 605    if (IS_INTEL_AVX2(cpuid_flags) && (SAVE_VECTOR_REGISTERS2() == 0)) {
 606        /* Process the state using AVX2 instructions. */
 607        sha3_block_avx2(state);
 608        RESTORE_VECTOR_REGISTERS();
 609    }
 610    /* Check availability of BMI2 instructions. */
 611    else if (IS_INTEL_BMI2(cpuid_flags)) {
 612        /* Process the state using BMI2 instructions. */
 613        sha3_block_bmi2(state);
 614    }
 615    else
 616#endif
 617    {
 618        /* Process the state using C code. */
 619        BlockSha3(state);
 620    }
 621    /* Copy hash result, of the required length, from the state into hash. */
 622    XMEMCPY(hash, shake->s, hash_len);
 623
 624    return 0;
 625#else
 626    /* Copy the first block of data into the cached data buffer. */
 627    XMEMCPY(shake->t, data1, data1_len);
 628    /* Encode HashAddress into the cached data buffer next. */
 629    HA_Encode(adrs, shake->t + data1_len);
 630    /* Copy the second block of data into the cached data buffer next. */
 631    XMEMCPY(shake->t + data1_len + SLHDSA_HA_SZ, data2, data2_len);
 632    /* Copy the third block of data into the cached data buffer next. */
 633    XMEMCPY(shake->t + data1_len + SLHDSA_HA_SZ + data2_len, data3, data3_len);
 634
 635    /* Update count of bytes cached. */
 636    shake->i = (byte)(data1_len + SLHDSA_HA_SZ + data2_len + data3_len);
 637
 638    /* Calculate and output hash. */
 639    return wc_Shake256_Final(shake, hash, hash_len);
 640#endif
 641}
 642
 643/******************************************************************************
 644 * SHA2 Hash Functions (FIPS 205, Section 11.2)
 645 ******************************************************************************/
 646
 647#ifdef WOLFSSL_SLHDSA_SHA2
 648
 649/* Size of compressed HashAddress (ADRS^c) per FIPS 205 Section 11.2. */
 650#define SLHDSA_HAC_SZ   22
 651
 652/* Encode a compressed HashAddress (ADRS^c).
 653 *
 654 * FIPS 205. Section 11.2.
 655 *   Byte 0:      low byte of adrs[0] (layer)
 656 *   Bytes 1-8:   adrs[2..3] (low 8 bytes of tree address)
 657 *   Byte 9:      low byte of adrs[4] (type)
 658 *   Bytes 10-21: adrs[5..7] (remaining 12 bytes, verbatim)
 659 *
 660 * @param [in]  adrs     HashAddress to encode (8 x word32).
 661 * @param [out] address  Buffer to encode into (22 bytes).
 662 */
 663static void HA_Encode_Compressed(const word32* adrs, byte* address)
 664{
 665    /* Byte 0: low byte of layer address. */
 666    address[0] = (byte)adrs[0];
 667    /* Bytes 1-4: adrs[2] (tree address high word). */
 668    c32toa(adrs[2], address + 1);
 669    /* Bytes 5-8: adrs[3] (tree address low word). */
 670    c32toa(adrs[3], address + 5);
 671    /* Byte 9: low byte of type. */
 672    address[9] = (byte)adrs[4];
 673    /* Bytes 10-13: adrs[5] (key pair address / padding). */
 674    c32toa(adrs[5], address + 10);
 675    /* Bytes 14-17: adrs[6] (chain address / tree height). */
 676    c32toa(adrs[6], address + 14);
 677    /* Bytes 18-21: adrs[7] (hash address / tree index). */
 678    c32toa(adrs[7], address + 18);
 679}
 680
 681/* Pre-compute SHA2 midstates for PK.seed.
 682 *
 683 * SHA-256: PK.seed || pad(64 - n) is exactly one 64-byte block.
 684 * SHA-512: PK.seed || pad(128 - n) is exactly one 128-byte block.
 685 *
 686 * @param [in, out] key  SLH-DSA key with pk_seed set at key->sk[2*n].
 687 * @return  0 on success.
 688 */
 689static int slhdsakey_precompute_sha2_midstates(SlhDsaKey* key)
 690{
 691    int ret = 0;
 692    byte n = key->params->n;
 693    const byte* pk_seed = key->sk + 2 * n;
 694    byte block[WC_SHA512_BLOCK_SIZE];
 695
 696    /* SHA-256 midstate: PK.seed || zeros to fill 64-byte block. */
 697    XMEMSET(block, 0, WC_SHA256_BLOCK_SIZE);
 698    XMEMCPY(block, pk_seed, n);
 699    if (key->hash.sha2.sha256_mid_inited) {
 700        wc_Sha256Free(&key->hash.sha2.sha256_mid);
 701        key->hash.sha2.sha256_mid_inited = 0;
 702    }
 703    ret = wc_InitSha256(&key->hash.sha2.sha256_mid);
 704    if (ret == 0) {
 705        key->hash.sha2.sha256_mid_inited = 1;
 706        ret = wc_Sha256Update(&key->hash.sha2.sha256_mid, block,
 707            WC_SHA256_BLOCK_SIZE);
 708    }
 709
 710    /* SHA-512 midstate: PK.seed || zeros to fill 128-byte block.
 711     * Only needed for categories 3 and 5 (n > 16). */
 712    if ((ret == 0) && (n > 16)) {
 713        XMEMSET(block, 0, WC_SHA512_BLOCK_SIZE);
 714        XMEMCPY(block, pk_seed, n);
 715        if (key->hash.sha2.sha512_mid_inited) {
 716            wc_Sha512Free(&key->hash.sha2.sha512_mid);
 717            key->hash.sha2.sha512_mid_inited = 0;
 718        }
 719        ret = wc_InitSha512(&key->hash.sha2.sha512_mid);
 720        if (ret == 0) {
 721            key->hash.sha2.sha512_mid_inited = 1;
 722            ret = wc_Sha512Update(&key->hash.sha2.sha512_mid, block,
 723                WC_SHA512_BLOCK_SIZE);
 724        }
 725    }
 726
 727    return ret;
 728}
 729
 730/* SHA2 F function.
 731 *
 732 * FIPS 205. Section 11.2.
 733 *   F(PK.seed, ADRS, M1) = Trunc_n(SHA-256(PK.seed||pad(64-n)||ADRS^c||M1))
 734 *
 735 * Uses pre-computed midstate for the first block.
 736 *
 737 * @param [in]  key      SLH-DSA key (SHA2 hash objects + midstate).
 738 * @param [in]  pk_seed  Public key seed (unused - midstate).
 739 * @param [in]  adrs     HashAddress.
 740 * @param [in]  m        Message of n bytes.
 741 * @param [in]  n        Number of bytes in hash output.
 742 * @param [out] hash     Buffer to hold hash output.
 743 * @return  0 on success.
 744 */
 745static int slhdsakey_hash_f_sha2(SlhDsaKey* key, const byte* pk_seed,
 746    const word32* adrs, const byte* m, byte n, byte* hash)
 747{
 748    int ret;
 749    byte address[SLHDSA_HAC_SZ];
 750    byte digest[WC_SHA256_DIGEST_SIZE];
 751
 752    (void)pk_seed;
 753
 754    /* Encode compressed address. */
 755    HA_Encode_Compressed(adrs, address);
 756
 757    /* Restore SHA-256 midstate. */
 758
 759    if (key->hash.sha2.sha256_inited) {
 760        wc_Sha256Free(&key->hash.sha2.sha256);
 761        key->hash.sha2.sha256_inited = 0;
 762    }
 763    ret = wc_Sha256Copy(&key->hash.sha2.sha256_mid, &key->hash.sha2.sha256);
 764    if (ret == 0) {
 765        key->hash.sha2.sha256_inited = 1;
 766        /* Update with compressed ADRS and message. */
 767        ret = wc_Sha256Update(&key->hash.sha2.sha256, address, SLHDSA_HAC_SZ);
 768    }
 769    if (ret == 0) {
 770        ret = wc_Sha256Update(&key->hash.sha2.sha256, m, n);
 771    }
 772    if (ret == 0) {
 773        ret = wc_Sha256Final(&key->hash.sha2.sha256, digest);
 774    }
 775    if (ret == 0) {
 776        /* Truncate to n bytes. */
 777        XMEMCPY(hash, digest, n);
 778    }
 779
 780    return ret;
 781}
 782
 783#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
 784/* SHA2 H function.
 785 *
 786 * FIPS 205. Section 11.2.
 787 *   Cat 1: H(PK.seed, ADRS, M2) = Trunc_n(SHA-256(PK.seed||pad||ADRS^c||M2))
 788 *   Cat 3,5: H(PK.seed, ADRS, M2) = Trunc_n(SHA-512(PK.seed||pad||ADRS^c||M2))
 789 *
 790 * @param [in]  key      SLH-DSA key.
 791 * @param [in]  pk_seed  Public key seed (unused - midstate).
 792 * @param [in]  adrs     HashAddress.
 793 * @param [in]  node     Message of 2n bytes.
 794 * @param [in]  n        Number of bytes in hash output.
 795 * @param [out] hash     Buffer to hold hash output.
 796 * @return  0 on success.
 797 */
 798static int slhdsakey_hash_h_sha2(SlhDsaKey* key, const byte* pk_seed,
 799    const word32* adrs, const byte* node, byte n, byte* hash)
 800{
 801    int ret;
 802    byte address[SLHDSA_HAC_SZ];
 803
 804    (void)pk_seed;
 805
 806    /* Encode compressed address. */
 807    HA_Encode_Compressed(adrs, address);
 808
 809    if (n == WC_SLHDSA_N_128) {
 810        /* Category 1: use SHA-256. */
 811        byte digest[WC_SHA256_DIGEST_SIZE];
 812
 813        if (key->hash.sha2.sha256_inited) {
 814            wc_Sha256Free(&key->hash.sha2.sha256);
 815            key->hash.sha2.sha256_inited = 0;
 816        }
 817        ret = wc_Sha256Copy(&key->hash.sha2.sha256_mid,
 818            &key->hash.sha2.sha256);
 819        if (ret == 0) {
 820            key->hash.sha2.sha256_inited = 1;
 821            ret = wc_Sha256Update(&key->hash.sha2.sha256, address,
 822                SLHDSA_HAC_SZ);
 823        }
 824        if (ret == 0) {
 825            ret = wc_Sha256Update(&key->hash.sha2.sha256, node, 2U * n);
 826        }
 827        if (ret == 0) {
 828            ret = wc_Sha256Final(&key->hash.sha2.sha256, digest);
 829        }
 830        if (ret == 0) {
 831            XMEMCPY(hash, digest, n);
 832        }
 833    }
 834    else {
 835        /* Categories 3, 5: use SHA-512. */
 836        byte digest[WC_SHA512_DIGEST_SIZE];
 837
 838        if (key->hash.sha2.sha512_inited) {
 839            wc_Sha512Free(&key->hash.sha2.sha512);
 840            key->hash.sha2.sha512_inited = 0;
 841        }
 842        ret = wc_Sha512Copy(&key->hash.sha2.sha512_mid,
 843            &key->hash.sha2.sha512);
 844        if (ret == 0) {
 845            key->hash.sha2.sha512_inited = 1;
 846            ret = wc_Sha512Update(&key->hash.sha2.sha512, address,
 847                SLHDSA_HAC_SZ);
 848        }
 849        if (ret == 0) {
 850            ret = wc_Sha512Update(&key->hash.sha2.sha512, node, 2U * n);
 851        }
 852        if (ret == 0) {
 853            ret = wc_Sha512Final(&key->hash.sha2.sha512, digest);
 854        }
 855        if (ret == 0) {
 856            XMEMCPY(hash, digest, n);
 857        }
 858    }
 859
 860    return ret;
 861}
 862#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
 863
 864/* SHA2 H function with two separate n-byte halves.
 865 *
 866 * Same as slhdsakey_hash_h_sha2 but M2 = m1 || m2.
 867 *
 868 * @param [in]  key      SLH-DSA key.
 869 * @param [in]  pk_seed  Public key seed (unused - midstate).
 870 * @param [in]  adrs     HashAddress.
 871 * @param [in]  m1       First n bytes of message.
 872 * @param [in]  m2       Second n bytes of message.
 873 * @param [in]  n        Number of bytes in hash output.
 874 * @param [out] hash     Buffer to hold hash output.
 875 * @return  0 on success.
 876 */
 877static int slhdsakey_hash_h_2_sha2(SlhDsaKey* key, const byte* pk_seed,
 878    const word32* adrs, const byte* m1, const byte* m2, byte n, byte* hash)
 879{
 880    int ret;
 881    byte address[SLHDSA_HAC_SZ];
 882
 883    (void)pk_seed;
 884
 885    /* Encode compressed address. */
 886    HA_Encode_Compressed(adrs, address);
 887
 888    if (n == WC_SLHDSA_N_128) {
 889        /* Category 1: use SHA-256. */
 890        byte digest[WC_SHA256_DIGEST_SIZE];
 891
 892        if (key->hash.sha2.sha256_inited) {
 893            wc_Sha256Free(&key->hash.sha2.sha256);
 894            key->hash.sha2.sha256_inited = 0;
 895        }
 896        ret = wc_Sha256Copy(&key->hash.sha2.sha256_mid,
 897            &key->hash.sha2.sha256);
 898        if (ret == 0) {
 899            key->hash.sha2.sha256_inited = 1;
 900            ret = wc_Sha256Update(&key->hash.sha2.sha256, address,
 901                SLHDSA_HAC_SZ);
 902        }
 903        if (ret == 0) {
 904            ret = wc_Sha256Update(&key->hash.sha2.sha256, m1, n);
 905        }
 906        if (ret == 0) {
 907            ret = wc_Sha256Update(&key->hash.sha2.sha256, m2, n);
 908        }
 909        if (ret == 0) {
 910            ret = wc_Sha256Final(&key->hash.sha2.sha256, digest);
 911        }
 912        if (ret == 0) {
 913            XMEMCPY(hash, digest, n);
 914        }
 915    }
 916    else {
 917        /* Categories 3, 5: use SHA-512. */
 918        byte digest[WC_SHA512_DIGEST_SIZE];
 919
 920        if (key->hash.sha2.sha512_inited) {
 921            wc_Sha512Free(&key->hash.sha2.sha512);
 922            key->hash.sha2.sha512_inited = 0;
 923        }
 924        ret = wc_Sha512Copy(&key->hash.sha2.sha512_mid,
 925            &key->hash.sha2.sha512);
 926        if (ret == 0) {
 927            key->hash.sha2.sha512_inited = 1;
 928            ret = wc_Sha512Update(&key->hash.sha2.sha512, address,
 929                SLHDSA_HAC_SZ);
 930        }
 931        if (ret == 0) {
 932            ret = wc_Sha512Update(&key->hash.sha2.sha512, m1, n);
 933        }
 934        if (ret == 0) {
 935            ret = wc_Sha512Update(&key->hash.sha2.sha512, m2, n);
 936        }
 937        if (ret == 0) {
 938            ret = wc_Sha512Final(&key->hash.sha2.sha512, digest);
 939        }
 940        if (ret == 0) {
 941            XMEMCPY(hash, digest, n);
 942        }
 943    }
 944
 945    return ret;
 946}
 947
 948#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
 949/* SHA2 PRF function.
 950 *
 951 * FIPS 205. Section 11.2.
 952 *   PRF(PK.seed, SK.seed, ADRS) =
 953 *       Trunc_n(SHA-256(PK.seed || pad(64-n) || ADRS^c || SK.seed))
 954 *
 955 * @param [in]  key      SLH-DSA key.
 956 * @param [in]  pk_seed  Public key seed (unused - midstate).
 957 * @param [in]  sk_seed  Private key seed.
 958 * @param [in]  adrs     HashAddress.
 959 * @param [in]  n        Number of bytes in hash output.
 960 * @param [out] hash     Buffer to hold hash output.
 961 * @return  0 on success.
 962 */
 963static int slhdsakey_hash_prf_sha2(SlhDsaKey* key, const byte* pk_seed,
 964    const byte* sk_seed, const word32* adrs, byte n, byte* hash)
 965{
 966    int ret;
 967    byte address[SLHDSA_HAC_SZ];
 968    byte digest[WC_SHA256_DIGEST_SIZE];
 969
 970    (void)pk_seed;
 971
 972    /* Encode compressed address. */
 973    HA_Encode_Compressed(adrs, address);
 974
 975    /* Restore SHA-256 midstate. */
 976    if (key->hash.sha2.sha256_inited) {
 977        wc_Sha256Free(&key->hash.sha2.sha256);
 978        key->hash.sha2.sha256_inited = 0;
 979    }
 980    ret = wc_Sha256Copy(&key->hash.sha2.sha256_mid, &key->hash.sha2.sha256);
 981    if (ret == 0) {
 982        key->hash.sha2.sha256_inited = 1;
 983        ret = wc_Sha256Update(&key->hash.sha2.sha256, address, SLHDSA_HAC_SZ);
 984    }
 985    if (ret == 0) {
 986        ret = wc_Sha256Update(&key->hash.sha2.sha256, sk_seed, n);
 987    }
 988    if (ret == 0) {
 989        ret = wc_Sha256Final(&key->hash.sha2.sha256, digest);
 990    }
 991    if (ret == 0) {
 992        XMEMCPY(hash, digest, n);
 993    }
 994
 995    return ret;
 996}
 997#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
 998
 999/* SHA2 T_l streaming: start with address.
1000 *
1001 * Restores midstate then updates with compressed ADRS.
1002 *
1003 * @param [in] key      SLH-DSA key.
1004 * @param [in] pk_seed  Public key seed (unused - midstate).
1005 * @param [in] adrs     HashAddress.
1006 * @param [in] n        Number of bytes of hash output (determines cat).
1007 * @return  0 on success.
1008 */
1009static int slhdsakey_hash_start_addr_sha2(SlhDsaKey* key,
1010    const byte* pk_seed, const word32* adrs, byte n)
1011{
1012    int ret;
1013    byte address[SLHDSA_HAC_SZ];
1014
1015    (void)pk_seed;
1016
1017    HA_Encode_Compressed(adrs, address);
1018
1019    if (n == WC_SLHDSA_N_128) {
1020        /* Category 1: SHA-256 -- use sha256_2 (T_l must not collide with
1021         * sha256 which is used by F and H). */
1022        if (key->hash.sha2.sha256_2_inited) {
1023            wc_Sha256Free(&key->hash.sha2.sha256_2);
1024            key->hash.sha2.sha256_2_inited = 0;
1025        }
1026        ret = wc_Sha256Copy(&key->hash.sha2.sha256_mid,
1027            &key->hash.sha2.sha256_2);
1028        if (ret == 0) {
1029            key->hash.sha2.sha256_2_inited = 1;
1030            ret = wc_Sha256Update(&key->hash.sha2.sha256_2, address,
1031                SLHDSA_HAC_SZ);
1032        }
1033    }
1034    else {
1035        /* Categories 3, 5: SHA-512 -- use sha512_2 (T_l must not collide
1036         * with sha512 which is used by H). */
1037        if (key->hash.sha2.sha512_2_inited) {
1038            wc_Sha512Free(&key->hash.sha2.sha512_2);
1039            key->hash.sha2.sha512_2_inited = 0;
1040        }
1041        ret = wc_Sha512Copy(&key->hash.sha2.sha512_mid,
1042            &key->hash.sha2.sha512_2);
1043        if (ret == 0) {
1044            key->hash.sha2.sha512_2_inited = 1;
1045            ret = wc_Sha512Update(&key->hash.sha2.sha512_2, address,
1046                SLHDSA_HAC_SZ);
1047        }
1048    }
1049
1050    return ret;
1051}
1052
1053/* SHA2 T_l streaming: update with data.
1054 *
1055 * @param [in] key   SLH-DSA key.
1056 * @param [in] data  Data to hash.
1057 * @param [in] len   Length of data.
1058 * @return  0 on success.
1059 */
1060static int slhdsakey_hash_update_sha2(SlhDsaKey* key, const byte* data,
1061    word32 len)
1062{
1063    if (key->params->n == WC_SLHDSA_N_128) {
1064        return wc_Sha256Update(&key->hash.sha2.sha256_2, data, len);
1065    }
1066    else {
1067        return wc_Sha512Update(&key->hash.sha2.sha512_2, data, len);
1068    }
1069}
1070
1071/* SHA2 T_l streaming: finalize.
1072 *
1073 * @param [in]  key   SLH-DSA key.
1074 * @param [out] hash  Output buffer.
1075 * @param [in]  len   Desired output length (truncate to n).
1076 * @return  0 on success.
1077 */
1078static int slhdsakey_hash_final_sha2(SlhDsaKey* key, byte* hash, word32 len)
1079{
1080    int ret;
1081    byte n = key->params->n;
1082
1083    if (n == WC_SLHDSA_N_128) {
1084        byte digest[WC_SHA256_DIGEST_SIZE];
1085        ret = wc_Sha256Final(&key->hash.sha2.sha256_2, digest);
1086        if (ret == 0) {
1087            XMEMCPY(hash, digest, (len < n) ? len : n);
1088        }
1089    }
1090    else {
1091        byte digest[WC_SHA512_DIGEST_SIZE];
1092        ret = wc_Sha512Final(&key->hash.sha2.sha512_2, digest);
1093        if (ret == 0) {
1094            XMEMCPY(hash, digest, (len < n) ? len : n);
1095        }
1096    }
1097
1098    return ret;
1099}
1100
1101/* SHA2 T_l streaming: free internal allocations.
1102 *
1103 * @param [in]  key   SLH-DSA key.
1104 */
1105static void slhdsakey_hash_free_sha2(SlhDsaKey* key)
1106{
1107    byte n = key->params->n;
1108
1109    if (n == WC_SLHDSA_N_128) {
1110        wc_Sha256Free(&key->hash.sha2.sha256_2);
1111        key->hash.sha2.sha256_2_inited = 0;
1112    }
1113    else {
1114        wc_Sha512Free(&key->hash.sha2.sha512_2);
1115        key->hash.sha2.sha512_2_inited = 0;
1116    }
1117
1118    return;
1119}
1120
1121/* Local MGF1 implementation for H_msg.
1122 *
1123 * FIPS 205. Section 11.2.
1124 *   H_msg uses MGF1-SHA-256/512(R || PK.seed || digest, m) where m is the
1125 *   required output length.
1126 *
1127 * @param [in]  key       SLH-DSA key (for hash objects).
1128 * @param [in]  seed      Seed data for MGF1.
1129 * @param [in]  seedLen   Length of seed.
1130 * @param [out] out       Output buffer.
1131 * @param [in]  outLen    Required output length.
1132 * @return  0 on success.
1133 */
1134static int slhdsakey_mgf1_sha2(SlhDsaKey* key, const byte* seed,
1135    word32 seedLen, byte* out, word32 outLen)
1136{
1137    int ret = 0;
1138    word32 counter = 0;
1139    word32 done = 0;
1140    byte n = key->params->n;
1141
1142    while ((ret == 0) && (done < outLen)) {
1143        byte cBuf[4];
1144        word32 left = outLen - done;
1145
1146        c32toa(counter, cBuf);
1147
1148        if (n == WC_SLHDSA_N_128) {
1149            /* Category 1: MGF1-SHA-256. */
1150            byte digest[WC_SHA256_DIGEST_SIZE];
1151            word32 cpLen = (left < WC_SHA256_DIGEST_SIZE) ?
1152                left : WC_SHA256_DIGEST_SIZE;
1153
1154            if (! key->hash.sha2.sha256_2_inited) {
1155                ret = wc_InitSha256(&key->hash.sha2.sha256_2);
1156                if (ret == 0)
1157                    key->hash.sha2.sha256_2_inited = 1;
1158            }
1159            if (ret == 0) {
1160                ret = wc_Sha256Update(&key->hash.sha2.sha256_2, seed, seedLen);
1161            }
1162            if (ret == 0) {
1163                ret = wc_Sha256Update(&key->hash.sha2.sha256_2, cBuf, 4);
1164            }
1165            if (ret == 0) {
1166                ret = wc_Sha256Final(&key->hash.sha2.sha256_2, digest);
1167            }
1168            if (ret == 0) {
1169                XMEMCPY(out + done, digest, cpLen);
1170                done += cpLen;
1171            }
1172        }
1173        else {
1174            /* Categories 3, 5: MGF1-SHA-512. */
1175            byte digest[WC_SHA512_DIGEST_SIZE];
1176            word32 cpLen = (left < WC_SHA512_DIGEST_SIZE) ?
1177                left : WC_SHA512_DIGEST_SIZE;
1178
1179            if (! key->hash.sha2.sha512_2_inited) {
1180                ret = wc_InitSha512(&key->hash.sha2.sha512_2);
1181                if (ret == 0)
1182                    key->hash.sha2.sha512_2_inited = 1;
1183            }
1184            if (ret == 0) {
1185                ret = wc_Sha512Update(&key->hash.sha2.sha512_2, seed, seedLen);
1186            }
1187            if (ret == 0) {
1188                ret = wc_Sha512Update(&key->hash.sha2.sha512_2, cBuf, 4);
1189            }
1190            if (ret == 0) {
1191                ret = wc_Sha512Final(&key->hash.sha2.sha512_2, digest);
1192            }
1193            if (ret == 0) {
1194                XMEMCPY(out + done, digest, cpLen);
1195                done += cpLen;
1196            }
1197        }
1198        counter++;
1199    }
1200
1201    return ret;
1202}
1203
1204#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
1205/* SHA2 PRF_msg function.
1206 *
1207 * FIPS 205. Section 11.2.
1208 *   PRF_msg(SK.prf, opt_rand, M) =
1209 *       Trunc_n(HMAC-SHA-256/512(SK.prf, opt_rand || M))
1210 *
1211 * @param [in]  key      SLH-DSA key.
1212 * @param [in]  sk_prf   SK.prf seed.
1213 * @param [in]  opt_rand Random or PK.seed.
1214 * @param [in]  hdr      Message header (2 bytes).
1215 * @param [in]  ctx      Context data (may be NULL).
1216 * @param [in]  ctxSz    Context data length.
1217 * @param [in]  msg      Message data.
1218 * @param [in]  msgSz    Message data length.
1219 * @param [in]  n        Number of bytes in hash output.
1220 * @param [out] hash     Buffer to hold hash output.
1221 * @return  0 on success.
1222 */
1223static int slhdsakey_prf_msg_sha2(SlhDsaKey* key, const byte* sk_prf,
1224    const byte* opt_rand, const byte* hdr, const byte* ctx, byte ctxSz,
1225    const byte* msg, word32 msgSz, byte n, byte* hash)
1226{
1227    int ret;
1228    Hmac hmac;
1229    int hmacType;
1230    byte digest[WC_SHA512_DIGEST_SIZE];
1231
1232    if (n == WC_SLHDSA_N_128) {
1233        hmacType = WC_SHA256;
1234    }
1235    else {
1236        hmacType = WC_SHA512;
1237    }
1238
1239    ret = wc_HmacInit(&hmac, key->heap, INVALID_DEVID);
1240    if (ret == 0) {
1241        ret = wc_HmacSetKey(&hmac, hmacType, sk_prf, n);
1242    }
1243    if (ret == 0) {
1244        ret = wc_HmacUpdate(&hmac, opt_rand, n);
1245    }
1246    if ((ret == 0) && (hdr != NULL)) {
1247        ret = wc_HmacUpdate(&hmac, hdr, 2);
1248    }
1249    if ((ret == 0) && (ctxSz > 0) && (ctx != NULL)) {
1250        ret = wc_HmacUpdate(&hmac, ctx, ctxSz);
1251    }
1252    if (ret == 0) {
1253        ret = wc_HmacUpdate(&hmac, msg, msgSz);
1254    }
1255    if (ret == 0) {
1256        ret = wc_HmacFinal(&hmac, digest);
1257    }
1258    wc_HmacFree(&hmac);
1259
1260    if (ret == 0) {
1261        XMEMCPY(hash, digest, n);
1262    }
1263
1264    return ret;
1265}
1266#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
1267
1268/* SHA2 H_msg function.
1269 *
1270 * FIPS 205. Section 11.2.
1271 *   H_msg(R, PK.seed, PK.root, M) = MGF1-SHA-256/512(
1272 *       R || PK.seed || SHA-256/512(R || PK.seed || PK.root || M), m)
1273 *
1274 * @param [in]  key    SLH-DSA key.
1275 * @param [in]  r      Randomizer (n bytes from signature).
1276 * @param [in]  hdr    Message header (2 bytes).
1277 * @param [in]  ctx    Context data (may be NULL).
1278 * @param [in]  ctxSz  Context data length.
1279 * @param [in]  msg    Message data.
1280 * @param [in]  msgSz  Message data length.
1281 * @param [out] md     Output message digest.
1282 * @param [in]  mdLen  Required digest length (dl1+dl2+dl3).
1283 * @return  0 on success.
1284 */
1285static int slhdsakey_h_msg_sha2(SlhDsaKey* key, const byte* r,
1286    const byte* hdr, const byte* ctx, byte ctxSz, const byte* msg,
1287    word32 msgSz, byte* md, word32 mdLen)
1288{
1289    int ret = 0;
1290    byte n = key->params->n;
1291    const byte* pk_seed = key->sk + 2 * n;
1292    const byte* pk_root = key->sk + 3 * n;
1293
1294    if (n == WC_SLHDSA_N_128) {
1295        /* Category 1: SHA-256 + MGF1-SHA-256. */
1296        byte innerHash[WC_SHA256_DIGEST_SIZE];
1297        /* Seed for MGF1: R || PK.seed || innerHash. */
1298        byte mgfSeed[32 + 16 + WC_SHA256_DIGEST_SIZE];
1299
1300        /* Step 1: innerHash = SHA-256(R || PK.seed || PK.root || M). */
1301        if (! key->hash.sha2.sha256_2_inited) {
1302            ret = wc_InitSha256(&key->hash.sha2.sha256_2);
1303            if (ret == 0)
1304                key->hash.sha2.sha256_2_inited = 1;
1305        }
1306        if (ret == 0) {
1307            ret = wc_Sha256Update(&key->hash.sha2.sha256_2, r, n);
1308        }
1309        if (ret == 0) {
1310            ret = wc_Sha256Update(&key->hash.sha2.sha256_2, pk_seed, n);
1311        }
1312        if (ret == 0) {
1313            ret = wc_Sha256Update(&key->hash.sha2.sha256_2, pk_root, n);
1314        }
1315        if ((ret == 0) && (hdr != NULL)) {
1316            ret = wc_Sha256Update(&key->hash.sha2.sha256_2, hdr, 2);
1317        }
1318        if ((ret == 0) && (ctxSz > 0) && (ctx != NULL)) {
1319            ret = wc_Sha256Update(&key->hash.sha2.sha256_2, ctx, ctxSz);
1320        }
1321        if (ret == 0) {
1322            ret = wc_Sha256Update(&key->hash.sha2.sha256_2, msg, msgSz);
1323        }
1324        if (ret == 0) {
1325            ret = wc_Sha256Final(&key->hash.sha2.sha256_2, innerHash);
1326        }
1327
1328        /* Step 2: MGF1-SHA-256(R || PK.seed || innerHash, mdLen). */
1329        if (ret == 0) {
1330            XMEMCPY(mgfSeed, r, n);
1331            XMEMCPY(mgfSeed + n, pk_seed, n);
1332            XMEMCPY(mgfSeed + 2 * n, innerHash, WC_SHA256_DIGEST_SIZE);
1333            ret = slhdsakey_mgf1_sha2(key, mgfSeed,
1334                2U * n + WC_SHA256_DIGEST_SIZE, md, mdLen);
1335        }
1336    }
1337    else {
1338        /* Categories 3, 5: SHA-512 + MGF1-SHA-512. */
1339        byte innerHash[WC_SHA512_DIGEST_SIZE];
1340        /* Seed for MGF1: R || PK.seed || innerHash. */
1341        byte mgfSeed[32 + 32 + WC_SHA512_DIGEST_SIZE];
1342
1343        /* Step 1: innerHash = SHA-512(R || PK.seed || PK.root || M). */
1344        if (! key->hash.sha2.sha512_2_inited) {
1345            ret = wc_InitSha512(&key->hash.sha2.sha512_2);
1346            if (ret == 0)
1347                key->hash.sha2.sha512_2_inited = 1;
1348        }
1349        if (ret == 0) {
1350            ret = wc_Sha512Update(&key->hash.sha2.sha512_2, r, n);
1351        }
1352        if (ret == 0) {
1353            ret = wc_Sha512Update(&key->hash.sha2.sha512_2, pk_seed, n);
1354        }
1355        if (ret == 0) {
1356            ret = wc_Sha512Update(&key->hash.sha2.sha512_2, pk_root, n);
1357        }
1358        if ((ret == 0) && (hdr != NULL)) {
1359            ret = wc_Sha512Update(&key->hash.sha2.sha512_2, hdr, 2);
1360        }
1361        if ((ret == 0) && (ctxSz > 0) && (ctx != NULL)) {
1362            ret = wc_Sha512Update(&key->hash.sha2.sha512_2, ctx, ctxSz);
1363        }
1364        if (ret == 0) {
1365            ret = wc_Sha512Update(&key->hash.sha2.sha512_2, msg, msgSz);
1366        }
1367        if (ret == 0) {
1368            ret = wc_Sha512Final(&key->hash.sha2.sha512_2, innerHash);
1369        }
1370
1371        /* Step 2: MGF1-SHA-512(R || PK.seed || innerHash, mdLen). */
1372        if (ret == 0) {
1373            XMEMCPY(mgfSeed, r, n);
1374            XMEMCPY(mgfSeed + n, pk_seed, n);
1375            XMEMCPY(mgfSeed + 2 * n, innerHash, WC_SHA512_DIGEST_SIZE);
1376            ret = slhdsakey_mgf1_sha2(key, mgfSeed,
1377                2U * n + WC_SHA512_DIGEST_SIZE, md, mdLen);
1378        }
1379    }
1380
1381    return ret;
1382}
1383
1384#endif /* WOLFSSL_SLHDSA_SHA2 */
1385
1386/******************************************************************************
1387 * Dispatching Hash Macros
1388 ******************************************************************************/
1389
1390/* When WOLFSSL_SLHDSA_SHA2 is defined, macros dispatch between SHAKE and SHA2
1391 * based on the key's parameter set. When not defined, macros call SHAKE
1392 * directly (zero overhead). */
1393
1394#ifdef WOLFSSL_SLHDSA_SHA2
1395
1396/* SHAKE wrapper functions for SHA2 dispatch macros. */
1397static int slhdsakey_hash_f_shake(SlhDsaKey* key, const byte* pk_seed,
1398    const word32* adrs, const byte* m, byte n, byte* hash)
1399{
1400#ifndef WOLFSSL_WC_SLHDSA_SMALL
1401    return slhdsakey_hash_shake_3(&key->hash.shk.shake, pk_seed, n, adrs, m,
1402        n, hash, n);
1403#else
1404    return slhdsakey_hash_shake_4(&key->hash.shk.shake, pk_seed, n, adrs, m,
1405        n, NULL, 0, hash, n);
1406#endif
1407}
1408
1409#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
1410static int slhdsakey_hash_h_shake(SlhDsaKey* key, const byte* pk_seed,
1411    const word32* adrs, const byte* node, byte n, byte* hash)
1412{
1413#ifndef WOLFSSL_WC_SLHDSA_SMALL
1414    return slhdsakey_hash_shake_3(&key->hash.shk.shake, pk_seed, n, adrs, node,
1415        (byte)(2 * n), hash, n);
1416#else
1417    return slhdsakey_hash_shake_4(&key->hash.shk.shake, pk_seed, n, adrs, node,
1418        (byte)(2 * n), NULL, 0, hash, n);
1419#endif
1420}
1421#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
1422
1423static int slhdsakey_hash_h_2_shake(SlhDsaKey* key, const byte* pk_seed,
1424    const word32* adrs, const byte* m1, const byte* m2, byte n, byte* hash)
1425{
1426    return slhdsakey_hash_shake_4(&key->hash.shk.shake, pk_seed, n, adrs, m1,
1427        n, m2, n, hash, n);
1428}
1429
1430#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
1431static int slhdsakey_hash_prf_shake(SlhDsaKey* key, const byte* pk_seed,
1432    const byte* sk_seed, const word32* adrs, byte n, byte* hash)
1433{
1434#ifndef WOLFSSL_WC_SLHDSA_SMALL
1435    return slhdsakey_hash_shake_3(&key->hash.shk.shake, pk_seed, n, adrs,
1436        sk_seed, n, hash, n);
1437#else
1438    return slhdsakey_hash_shake_4(&key->hash.shk.shake, pk_seed, n, adrs,
1439        sk_seed, n, NULL, 0, hash, n);
1440#endif
1441}
1442#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
1443
1444#define HASH_PRF(k, pk_seed, sk_seed, adrs, n, o)                            \
1445    (SLHDSA_IS_SHA2((k)->params->param) ?                                    \
1446        slhdsakey_hash_prf_sha2(k, pk_seed, sk_seed, adrs, n, o) :          \
1447        slhdsakey_hash_prf_shake(k, pk_seed, sk_seed, adrs, n, o))
1448
1449#define HASH_F(k, pk_seed, adrs, m, n, o)                                   \
1450    (SLHDSA_IS_SHA2((k)->params->param) ?                                    \
1451        slhdsakey_hash_f_sha2(k, pk_seed, adrs, m, n, o) :                  \
1452        slhdsakey_hash_f_shake(k, pk_seed, adrs, m, n, o))
1453
1454#define HASH_H(k, pk_seed, adrs, node, n, o)                                \
1455    (SLHDSA_IS_SHA2((k)->params->param) ?                                    \
1456        slhdsakey_hash_h_sha2(k, pk_seed, adrs, node, n, o) :               \
1457        slhdsakey_hash_h_shake(k, pk_seed, adrs, node, n, o))
1458
1459#define HASH_H_2(k, pk_seed, adrs, m1, m2, n, o)                            \
1460    (SLHDSA_IS_SHA2((k)->params->param) ?                                    \
1461        slhdsakey_hash_h_2_sha2(k, pk_seed, adrs, m1, m2, n, o) :           \
1462        slhdsakey_hash_h_2_shake(k, pk_seed, adrs, m1, m2, n, o))
1463
1464#else /* !WOLFSSL_SLHDSA_SHA2 */
1465
1466#ifndef WOLFSSL_WC_SLHDSA_SMALL
1467/* PRF hash.
1468 *
1469 * FIPS 205. Section 4.1.
1470 *   PRF(PK.seed, SK.seed, ADRS) (Bn x Bn x B32 -> Bn) is a PRF that is used to
1471 *   generate the secret values in WOTS+ and FORS private keys.
1472 * FIPS 205. Section 11.1.
1473 *   PRF(PK.seed, SK.seed, ADRS) = SHAKE256(PK.seed || ADRS || SK.seed, 8n)
1474 *
1475 * @param [in]  key      SLH-DSA key.
1476 * @param [in]  pk_seed  Public key seed.
1477 * @param [in]  sk_seed  Private key seed.
1478 * @param [in]  adrs     HashAddress.
1479 * @param [in]  n        Number of bytes in hash output.
1480 * @param [out] hash     Buffer to hold hash output.
1481 * @return  0 on success.
1482 * @return  SHAKE-256 error return code on digest failure.
1483 */
1484#define HASH_PRF(k, pk_seed, sk_seed, adrs, n, o)                            \
1485    slhdsakey_hash_shake_3(&(k)->hash.shk.shake, pk_seed, n, adrs,           \
1486        sk_seed, n, o, n)
1487/* Hash F. */
1488#define HASH_F(k, pk_seed, adrs, m, n, o)                                    \
1489    slhdsakey_hash_shake_3(&(k)->hash.shk.shake, pk_seed, n, adrs, m, n,    \
1490        o, n)
1491/* Hash H. */
1492#define HASH_H(k, pk_seed, adrs, node, n, o)                                \
1493    slhdsakey_hash_shake_3(&(k)->hash.shk.shake, pk_seed, n, adrs, node,    \
1494        (byte)(2 * (n)), o, (n))
1495#else
1496/* PRF hash. */
1497#define HASH_PRF(k, pk_seed, sk_seed, adrs, n, o)                           \
1498    slhdsakey_hash_shake_4(&(k)->hash.shk.shake, pk_seed, n, adrs,          \
1499        sk_seed, n, NULL, 0, o, n)
1500/* Hash F. */
1501#define HASH_F(k, pk_seed, adrs, m, n, o)                                   \
1502    slhdsakey_hash_shake_4(&(k)->hash.shk.shake, pk_seed, n, adrs, m, n,   \
1503        NULL, 0, o, n)
1504/* Hash H. */
1505#define HASH_H(k, pk_seed, adrs, node, n, o)                                \
1506    slhdsakey_hash_shake_4(&(k)->hash.shk.shake, pk_seed, n, adrs, node,   \
1507        (byte)(2 * (n)), NULL, 0, o, n)
1508#endif
1509
1510/* Hash H with 2n byte message as two separate n byte parameters. */
1511#define HASH_H_2(k, pk_seed, adrs, m1, m2, n, o)                            \
1512    slhdsakey_hash_shake_4(&(k)->hash.shk.shake, pk_seed, n, adrs, m1, n,  \
1513        m2, n, o, n)
1514
1515#endif /* WOLFSSL_SLHDSA_SHA2 */
1516
1517/* T_l streaming dispatch macros for the secondary hash (used by WOTS+ pk
1518 * compression and FORS root computation). */
1519#ifdef WOLFSSL_SLHDSA_SHA2
1520
1521#define HASH_T_START_ADDR(k, pk_seed, adrs, n)                              \
1522    (SLHDSA_IS_SHA2((k)->params->param) ?                                    \
1523        slhdsakey_hash_start_addr_sha2(k, pk_seed, adrs, n) :               \
1524        slhdsakey_hash_start_addr(&(k)->hash.shk.shake2, pk_seed, adrs, n))
1525
1526#define HASH_T_UPDATE(k, d, l)                                               \
1527    (SLHDSA_IS_SHA2((k)->params->param) ?                                    \
1528        slhdsakey_hash_update_sha2(k, d, l) :                                \
1529        slhdsakey_hash_update(&(k)->hash.shk.shake2, d, l))
1530
1531#define HASH_T_FINAL(k, o, l)                                                \
1532    (SLHDSA_IS_SHA2((k)->params->param) ?                                    \
1533        slhdsakey_hash_final_sha2(k, o, l) :                                 \
1534        slhdsakey_hash_final(&(k)->hash.shk.shake2, o, l))
1535
1536#define HASH_T_FREE(k)                                                       \
1537    (SLHDSA_IS_SHA2((k)->params->param) ?                                    \
1538        slhdsakey_hash_free_sha2(k) :                                        \
1539        slhdsakey_hash_free(&(k)->hash.shk.shake2))
1540
1541#else
1542
1543#define HASH_T_START_ADDR(k, pk_seed, adrs, n)                               \
1544    slhdsakey_hash_start_addr(&(k)->hash.shk.shake2, pk_seed, adrs, n)
1545
1546#define HASH_T_UPDATE(k, d, l)                                               \
1547    slhdsakey_hash_update(&(k)->hash.shk.shake2, d, l)
1548
1549#define HASH_T_FINAL(k, o, l)                                                \
1550    slhdsakey_hash_final(&(k)->hash.shk.shake2, o, l)
1551
1552#define HASH_T_FREE(k)                                                       \
1553    slhdsakey_hash_free(&(k)->hash.shk.shake2)
1554
1555#endif /* WOLFSSL_SLHDSA_SHA2 */
1556
1557/* Start hashing with SHAKE-256.
1558 *
1559 * @param [in] shake  SHAKE-256 object.
1560 * @param [in] data   First block of data to hash.
1561 * @param [in] len    Length in bytes of first block of data.
1562 * @return  0 on success.
1563 * @return  SHAKE-256 error return code on digest failure.
1564 */
1565static int slhdsakey_hash_start(wc_Shake* shake, const byte* data, byte len)
1566{
1567#if defined(USE_INTEL_SPEEDUP)
1568    /* Clear state for new hash. */
1569    XMEMSET(shake->s, 0, sizeof(shake->s));
1570#endif
1571#ifdef WOLFSSL_SLHDSA_FULL_HASH
1572    /* Update the hash. */
1573    return wc_Shake256_Update(shake, data, len);
1574#else
1575    /* Copy the data to hash into the cache and update cached length. */
1576    XMEMCPY(shake->t, data, len);
1577    shake->i = (byte)len;
1578
1579    return 0;
1580#endif
1581}
1582
1583/* Start hashing with SHAKE-256. HashAddress to update too.
1584 *
1585 * @param [in] shake    SHAKE-256 object.
1586 * @param [in] pk_seed  Public key seed - a hash output.
1587 * @param [in] adrs     HashAddress.
1588 * @param [in] n        Number of bytes in hash output.
1589 * @return  0 on success.
1590 * @return  SHAKE-256 error return code on digest failure.
1591 */
1592static int slhdsakey_hash_start_addr(wc_Shake* shake, const byte* pk_seed,
1593    const word32* adrs, byte n)
1594{
1595#ifdef WOLFSSL_SLHDSA_FULL_HASH
1596    int ret;
1597    byte address[SLHDSA_HA_SZ];
1598
1599    /* Encode HashAddress. */
1600    HA_Encode(adrs, address);
1601
1602#if defined(USE_INTEL_SPEEDUP)
1603    /* Clear state for new hash. */
1604    XMEMSET(shake->s, 0, sizeof(shake->s));
1605#endif
1606    /* Update the hash with the public key seed. */
1607    ret = wc_Shake256_Update(shake, pk_seed, n);
1608    if (ret == 0) {
1609        /* Update the hash with the encoded HashAddress. */
1610        ret = wc_Shake256_Update(shake, address, SLHDSA_HA_SZ);
1611    }
1612
1613    return ret;
1614#else
1615#if defined(USE_INTEL_SPEEDUP)
1616    /* Clear state for new hash. */
1617    XMEMSET(shake->s, 0, sizeof(shake->s));
1618#endif
1619    /* Copy the data to hash into the cache and update cached length. */
1620    XMEMCPY(shake->t, pk_seed, n);
1621    HA_Encode(adrs, shake->t + n);
1622    shake->i = (byte)(n + SLHDSA_HA_SZ);
1623
1624    return 0;
1625#endif
1626}
1627
1628/* Update the hash with more data.
1629 *
1630 * @param [in] shake  SHAKE-256 object.
1631 * @param [in] data   Block of data to hash.
1632 * @param [in] len    Length in bytes of first block of data.
1633 * @return  0 on success.
1634 * @return  SHAKE-256 error return code on digest failure.
1635 */
1636static int slhdsakey_hash_update(wc_Shake* shake, const byte* data, word32 len)
1637{
1638    return wc_Shake256_Update(shake, data, len);
1639}
1640
1641/* Calculate and output hash.
1642 *
1643 * @param [in]  shake  SHAKE-256 object.
1644 * @param [out] hash   Hash output.
1645 * @param [in]  len    Length of hash to output in bytes.
1646 * @return  0 on success.
1647 * @return  SHAKE-256 error return code on digest failure.
1648 */
1649static int slhdsakey_hash_final(wc_Shake* shake, byte* hash, word32 len)
1650{
1651    return wc_Shake256_Final(shake, hash, len);
1652}
1653
1654/* Free internal resources.
1655 *
1656 * @param [in]  shake  SHAKE-256 object.
1657 */
1658static void slhdsakey_hash_free(wc_Shake* shake)
1659{
1660    wc_Shake256_Free(shake);
1661}
1662
1663/******************************************************************************
1664 * Conversion functions
1665 ******************************************************************************/
1666
1667/* Convert array of bytes to array of b-bit values.
1668 *
1669 * b is 6, 8, 9, 12 or 14.
1670 *
1671 * FIPS 205. Section 4.4. Algorithm 4.
1672 * base_2b(X, b, out_len)
1673 *   1: in <- 0
1674 *   2: bits <- 0
1675 *   3: total <- 0
1676 *   4: for out from 0 to out_len - 1 do
1677 *   5:     while bits < b do
1678 *   6:         total <- (total << 8) + X[in]
1679 *   7:         in <- in + 1
1680 *   8:         bits <- bits + 8
1681 *   9:     end while
1682 *  10:     bits <- bits - b
1683 *  11:     baseb[out] <- (total >> bits mod 2^b
1684 *  12: end for
1685 *  13: return baseb
1686 *
1687 * @param [in]  x       Array of bytes.
1688 * @param [in]  b       Number of bits.
1689 * @param [in]  outLen  Length of output array.
1690 * @param [out] baseb   Array of b-bit values.
1691 */
1692static void slhdsakey_base_2b(const byte* x, byte b, byte outLen, word16* baseb)
1693{
1694    int j;
1695    int i = 0;
1696    int bits = 0;
1697    int total = 0;
1698    word16 mask = (word16)((1 << b) - 1);
1699
1700    for (j = 0; j < outLen; j++) {
1701        while (bits < b) {
1702            total = (total << 8) + x[i++];
1703            bits += 8;
1704        }
1705        bits -= b;
1706        baseb[j] = (word16)((total >> bits) & mask);
1707    }
1708}
1709
1710/******************************************************************************
1711 * WOTS+
1712 ******************************************************************************/
1713
1714/* Iterate the hash function s times.
1715 *
1716 * FIPS 205. Section 5. Algorithm 5.
1717 * chain(X, i, s, PK.seed, ADRS)
1718 *   1: tmp <- X
1719 *   2: for j from i to i + s - 1 do
1720 *   3:     ADRS.setHashAddress(j)
1721 *   4:     tmp <- F(PK.seed, ADRS, tmp
1722 *   5: end for
1723 *   6: return tmp
1724 *
1725 * @param [in]  key      SLH-DSA key.
1726 * @param [in]  x        n-byte string.
1727 * @param [in]  i        Start index iterations.
1728 * @param [in]  s        Number of times to iterate.
1729 * @param [in]  pk_seed  Public key seed.
1730 * @param [in]  adrs     HashAddress.
1731 * @param [out] node     Hash output - n bytes.
1732 * @return  0 on success.
1733 * @return  SHAKE-256 error return code on digest failure.
1734 */
1735static int slhdsakey_chain(SlhDsaKey* key, const byte* x, byte i, byte s,
1736    const byte* pk_seed, word32* adrs, byte* node)
1737{
1738    int ret = 0;
1739    int j;
1740    byte n = key->params->n;
1741
1742    /* When no steps, copy. */
1743    if (s == 0) {
1744        /* Only copy when input and output buffers different. */
1745        if (x != node) {
1746            XMEMCPY(node, x, n);
1747        }
1748    }
1749    else {
1750        /* Set the hash address for first iteration. */
1751        HA_SetHashAddress(adrs, i);
1752        /* First iteration of hash using input and writing to output buffers. */
1753        ret = HASH_F(key, pk_seed, adrs, x, n, node);
1754        if (ret == 0) {
1755            for (j = i + 1; j < i + s; j++) {
1756                /* Set the hash address. */
1757                HA_SetHashAddress(adrs, j);
1758                /* Iterate hash using output buffer as input. */
1759                ret = HASH_F(key, pk_seed, adrs, node, n, node);
1760                if (ret != 0) {
1761                    break;
1762                }
1763            }
1764        }
1765    }
1766
1767    return ret;
1768}
1769
1770#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
1771#ifndef WOLFSSL_SLHDSA_PARAM_NO_128
1772/* Set into SHAKE-256 x4 state the 16-byte seed and encoded HashAddress.
1773 *
1774 * @param [in, out] state  SHAKE-256 x4 state.
1775 * @param [in]      seed   Seed at start of each hash.
1776 * @param [in]      addr   Encoded HashAddress for each hash.
1777 */
1778#define SHAKE256_SET_SEED_HA_X4_16(state, seed, addr)                       \
1779do {                                                                        \
1780    /* Set 4 copies of the seed 64-bits at a time. */                       \
1781    (state)[0] = (state)[1] = (state)[2] = (state)[3] =                     \
1782                        readUnalignedWord64((seed) + (0 * sizeof(word64))); \
1783    (state)[4] = (state)[5] = (state)[6] = (state)[7] =                     \
1784                        readUnalignedWord64((seed) + (1 * sizeof(word64))); \
1785    /* 32 bytes copied 8 bytes at a time. */                                \
1786    (state)[ 8] = (state)[ 9] = (state)[10] = (state)[11] =                 \
1787                        readUnalignedWord64((addr) + (0 * sizeof(word64))); \
1788    (state)[12] = (state)[13] = (state)[14] = (state)[15] =                 \
1789                        readUnalignedWord64((addr) + (1 * sizeof(word64))); \
1790    (state)[16] = (state)[17] = (state)[18] = (state)[19] =                 \
1791                        readUnalignedWord64((addr) + (2 * sizeof(word64))); \
1792    (state)[20] = (state)[21] = (state)[22] = (state)[23] =                 \
1793                        readUnalignedWord64((addr) + (3 * sizeof(word64))); \
1794} while (0)
1795
1796/* Append to SHAKE-256 x4 state the 16-byte hash.
1797 *
1798 * @param [in, out] state  SHAKE-256 x4 state.
1799 * @param [in]      hash   Hash data for each hash.
1800 */
1801#define SHAKE256_SET_HASH_X4_16(state, hash)                                \
1802do {                                                                        \
1803    (state)[24] = ((word64*)((hash) + 0 * 16))[0];                          \
1804    (state)[25] = ((word64*)((hash) + 1 * 16))[0];                          \
1805    (state)[26] = ((word64*)((hash) + 2 * 16))[0];                          \
1806    (state)[27] = ((word64*)((hash) + 3 * 16))[0];                          \
1807    (state)[28] = ((word64*)((hash) + 0 * 16))[1];                          \
1808    (state)[29] = ((word64*)((hash) + 1 * 16))[1];                          \
1809    (state)[30] = ((word64*)((hash) + 2 * 16))[1];                          \
1810    (state)[31] = ((word64*)((hash) + 3 * 16))[1];                          \
1811} while (0)
1812
1813/* Get the four SHAKE-256 16-byte hash results.
1814 *
1815 * @param [in]  state  SHAKE-256 x4 state.
1816 * @param [out] hash   Hash buffer to hold 4 16-byte hash results.
1817 */
1818#define SHAKE256_GET_HASH_X4_16(state, hash)                                \
1819do {                                                                        \
1820    ((word64*)((hash) + 0 * 16))[0] = (state)[0];                           \
1821    ((word64*)((hash) + 1 * 16))[0] = (state)[1];                           \
1822    ((word64*)((hash) + 2 * 16))[0] = (state)[2];                           \
1823    ((word64*)((hash) + 3 * 16))[0] = (state)[3];                           \
1824    ((word64*)((hash) + 0 * 16))[1] = (state)[4];                           \
1825    ((word64*)((hash) + 1 * 16))[1] = (state)[5];                           \
1826    ((word64*)((hash) + 2 * 16))[1] = (state)[6];                           \
1827    ((word64*)((hash) + 3 * 16))[1] = (state)[7];                           \
1828} while (0)
1829#endif
1830
1831#ifndef WOLFSSL_SLHDSA_PARAM_NO_192
1832/* Set into SHAKE-256 x4 state the 24-byte seed and encoded HashAddress.
1833 *
1834 * @param [in, out] state  SHAKE-256 x4 state.
1835 * @param [in]      seed   Seed at start of each hash.
1836 * @param [in]      addr   Encoded HashAddress for each hash.
1837 */
1838#define SHAKE256_SET_SEED_HA_X4_24(state, seed, addr)                       \
1839do {                                                                        \
1840    (state)[0] = (state)[1] = (state)[ 2] = (state)[ 3] =                   \
1841                        readUnalignedWord64((seed) + (0 * sizeof(word64))); \
1842    (state)[4] = (state)[5] = (state)[ 6] = (state)[ 7] =                   \
1843                        readUnalignedWord64((seed) + (1 * sizeof(word64))); \
1844    (state)[8] = (state)[9] = (state)[10] = (state)[11] =                   \
1845                        readUnalignedWord64((seed) + (2 * sizeof(word64))); \
1846    /* 32 bytes copied 8 bytes at a time. */                                \
1847    (state)[12] = (state)[13] = (state)[14] = (state)[15] =                 \
1848                        readUnalignedWord64((addr) + (0 * sizeof(word64))); \
1849    (state)[16] = (state)[17] = (state)[18] = (state)[19] =                 \
1850                        readUnalignedWord64((addr) + (1 * sizeof(word64))); \
1851    (state)[20] = (state)[21] = (state)[22] = (state)[23] =                 \
1852                        readUnalignedWord64((addr) + (2 * sizeof(word64))); \
1853    (state)[24] = (state)[25] = (state)[26] = (state)[27] =                 \
1854                        readUnalignedWord64((addr) + (3 * sizeof(word64))); \
1855} while (0)
1856
1857/* Append to SHAKE-256 x4 state the 24-byte hash.
1858 *
1859 * @param [in, out] state  SHAKE-256 x4 state.
1860 * @param [in]      hash   Hash data for each hash.
1861 */
1862#define SHAKE256_SET_HASH_X4_24(state, hash)                                \
1863do {                                                                        \
1864    (state)[28] = ((word64*)((hash) + 0 * 24))[0];                          \
1865    (state)[29] = ((word64*)((hash) + 1 * 24))[0];                          \
1866    (state)[30] = ((word64*)((hash) + 2 * 24))[0];                          \
1867    (state)[31] = ((word64*)((hash) + 3 * 24))[0];                          \
1868    (state)[32] = ((word64*)((hash) + 0 * 24))[1];                          \
1869    (state)[33] = ((word64*)((hash) + 1 * 24))[1];                          \
1870    (state)[34] = ((word64*)((hash) + 2 * 24))[1];                          \
1871    (state)[35] = ((word64*)((hash) + 3 * 24))[1];                          \
1872    (state)[36] = ((word64*)((hash) + 0 * 24))[2];                          \
1873    (state)[37] = ((word64*)((hash) + 1 * 24))[2];                          \
1874    (state)[38] = ((word64*)((hash) + 2 * 24))[2];                          \
1875    (state)[39] = ((word64*)((hash) + 3 * 24))[2];                          \
1876} while (0)
1877
1878/* Get the four SHAKE-256 24-byte (hash) results.
1879 *
1880 * @param [in]  state  SHAKE-256 x4 state.
1881 * @param [out] hash   Hash buffer to hold 4 24-byte hash results.
1882 */
1883#define SHAKE256_GET_HASH_X4_24(state, hash)                                \
1884do {                                                                        \
1885    ((word64*)((hash) + 0 * 24))[0] = (state)[ 0];                          \
1886    ((word64*)((hash) + 1 * 24))[0] = (state)[ 1];                          \
1887    ((word64*)((hash) + 2 * 24))[0] = (state)[ 2];                          \
1888    ((word64*)((hash) + 3 * 24))[0] = (state)[ 3];                          \
1889    ((word64*)((hash) + 0 * 24))[1] = (state)[ 4];                          \
1890    ((word64*)((hash) + 1 * 24))[1] = (state)[ 5];                          \
1891    ((word64*)((hash) + 2 * 24))[1] = (state)[ 6];                          \
1892    ((word64*)((hash) + 3 * 24))[1] = (state)[ 7];                          \
1893    ((word64*)((hash) + 0 * 24))[2] = (state)[ 8];                          \
1894    ((word64*)((hash) + 1 * 24))[2] = (state)[ 9];                          \
1895    ((word64*)((hash) + 2 * 24))[2] = (state)[10];                          \
1896    ((word64*)((hash) + 3 * 24))[2] = (state)[11];                          \
1897} while (0)
1898#endif
1899
1900#ifndef WOLFSSL_SLHDSA_PARAM_NO_256
1901/* Set into SHAKE-256 x4 state the 32-byte seed and encoded HashAddress.
1902 *
1903 * @param [in, out] state  SHAKE-256 x4 state.
1904 * @param [in]      seed   Seed at start of each hash.
1905 * @param [in]      addr   Encoded HashAddress for each hash.
1906 */
1907#define SHAKE256_SET_SEED_HA_X4_32(state, seed, addr)                       \
1908do {                                                                        \
1909    (state)[ 0] = (state)[ 1] = (state)[ 2] = (state)[ 3] =                 \
1910                        readUnalignedWord64((seed) + (0 * sizeof(word64))); \
1911    (state)[ 4] = (state)[ 5] = (state)[ 6] = (state)[ 7] =                 \
1912                        readUnalignedWord64((seed) + (1 * sizeof(word64))); \
1913    (state)[ 8] = (state)[ 9] = (state)[10] = (state)[11] =                 \
1914                        readUnalignedWord64((seed) + (2 * sizeof(word64))); \
1915    (state)[12] = (state)[13] = (state)[14] = (state)[15] =                 \
1916                        readUnalignedWord64((seed) + (3 * sizeof(word64))); \
1917    /* 32 bytes copied 8 bytes at a time. */                                \
1918    (state)[16] = (state)[17] = (state)[18] = (state)[19] =                 \
1919                        readUnalignedWord64((addr) + (0 * sizeof(word64))); \
1920    (state)[20] = (state)[21] = (state)[22] = (state)[23] =                 \
1921                        readUnalignedWord64((addr) + (1 * sizeof(word64))); \
1922    (state)[24] = (state)[25] = (state)[26] = (state)[27] =                 \
1923                        readUnalignedWord64((addr) + (2 * sizeof(word64))); \
1924    (state)[28] = (state)[29] = (state)[30] = (state)[31] =                 \
1925                        readUnalignedWord64((addr) + (3 * sizeof(word64))); \
1926} while (0)
1927
1928/* Append to SHAKE-256 x4 state the 32-byte hash.
1929 *
1930 * @param [in, out] state  SHAKE-256 x4 state.
1931 * @param [in]      hash   Hash data for each hash.
1932 */
1933#define SHAKE256_SET_HASH_X4_32(state, hash)                                \
1934do {                                                                        \
1935    (state)[32] = ((word64*)((hash) + 0 * 32))[0];                          \
1936    (state)[33] = ((word64*)((hash) + 1 * 32))[0];                          \
1937    (state)[34] = ((word64*)((hash) + 2 * 32))[0];                          \
1938    (state)[35] = ((word64*)((hash) + 3 * 32))[0];                          \
1939    (state)[36] = ((word64*)((hash) + 0 * 32))[1];                          \
1940    (state)[37] = ((word64*)((hash) + 1 * 32))[1];                          \
1941    (state)[38] = ((word64*)((hash) + 2 * 32))[1];                          \
1942    (state)[39] = ((word64*)((hash) + 3 * 32))[1];                          \
1943    (state)[40] = ((word64*)((hash) + 0 * 32))[2];                          \
1944    (state)[41] = ((word64*)((hash) + 1 * 32))[2];                          \
1945    (state)[42] = ((word64*)((hash) + 2 * 32))[2];                          \
1946    (state)[43] = ((word64*)((hash) + 3 * 32))[2];                          \
1947    (state)[44] = ((word64*)((hash) + 0 * 32))[3];                          \
1948    (state)[45] = ((word64*)((hash) + 1 * 32))[3];                          \
1949    (state)[46] = ((word64*)((hash) + 2 * 32))[3];                          \
1950    (state)[47] = ((word64*)((hash) + 3 * 32))[3];                          \
1951} while (0)
1952
1953/* Get the four SHAKE-256 32-byte hash results.
1954 *
1955 * @param [in]  state  SHAKE-256 x4 state.
1956 * @param [out] hash   Hash buffer to hold 4 32-byte hash results.
1957 */
1958#define SHAKE256_GET_HASH_X4_32(state, hash)                                \
1959do {                                                                        \
1960    ((word64*)((hash) + 0 * 32))[0] = (state)[ 0];                          \
1961    ((word64*)((hash) + 1 * 32))[0] = (state)[ 1];                          \
1962    ((word64*)((hash) + 2 * 32))[0] = (state)[ 2];                          \
1963    ((word64*)((hash) + 3 * 32))[0] = (state)[ 3];                          \
1964    ((word64*)((hash) + 0 * 32))[1] = (state)[ 4];                          \
1965    ((word64*)((hash) + 1 * 32))[1] = (state)[ 5];                          \
1966    ((word64*)((hash) + 2 * 32))[1] = (state)[ 6];                          \
1967    ((word64*)((hash) + 3 * 32))[1] = (state)[ 7];                          \
1968    ((word64*)((hash) + 0 * 32))[2] = (state)[ 8];                          \
1969    ((word64*)((hash) + 1 * 32))[2] = (state)[ 9];                          \
1970    ((word64*)((hash) + 2 * 32))[2] = (state)[10];                          \
1971    ((word64*)((hash) + 3 * 32))[2] = (state)[11];                          \
1972    ((word64*)((hash) + 0 * 32))[3] = (state)[12];                          \
1973    ((word64*)((hash) + 1 * 32))[3] = (state)[13];                          \
1974    ((word64*)((hash) + 2 * 32))[3] = (state)[14];                          \
1975    ((word64*)((hash) + 3 * 32))[3] = (state)[15];                          \
1976} while (0)
1977#endif
1978
1979/* Set the end of the SHAKE256 x4 state.
1980 *
1981 * @param [in, out] state  SHAKE-256 x4 state.
1982 * @param [in]      o      Offset to end of data.
1983 */
1984#define SHAKE256_SET_END_X4(state, o)                                       \
1985do {                                                                        \
1986    /* Data end marker. */                                                  \
1987    (state)[(o) + 0] = (word64)0x1f;                                        \
1988    (state)[(o) + 1] = (word64)0x1f;                                        \
1989    (state)[(o) + 2] = (word64)0x1f;                                        \
1990    (state)[(o) + 3] = (word64)0x1f;                                        \
1991    XMEMSET((state) + (o) + 4, 0,                                           \
1992        (size_t)(25 * 4 - ((o) + 4)) * sizeof(word64));                     \
1993    /* SHAKE-256 (state) end marker. */                                     \
1994    ((word8*)((state) + 4 * WC_SHA3_256_COUNT - 4))[7] ^= 0x80;             \
1995    ((word8*)((state) + 4 * WC_SHA3_256_COUNT - 3))[7] ^= 0x80;             \
1996    ((word8*)((state) + 4 * WC_SHA3_256_COUNT - 2))[7] ^= 0x80;             \
1997    ((word8*)((state) + 4 * WC_SHA3_256_COUNT - 1))[7] ^= 0x80;             \
1998} while (0)
1999
2000/* Set into SHAKE-256 x4 state the n-byte seed and encoded HashAddress.
2001 *
2002 * @param [in, out] state  SHAKE-256 x4 state.
2003 * @param [in]      seed   Seed at start of each hash.
2004 * @param [in]      addr   Encoded HashAddress for each hash.
2005 * @param [in]      n      Number of bytes of seed.
2006 * @return  Offset after seed and HashAddress.
2007 */
2008static word32 slhdsakey_shake256_set_seed_ha_x4(word64* state,
2009    const byte* seed, const byte* addr, int n)
2010{
2011    int i;
2012    word32 o = 0;
2013
2014    /* Set 4 copies of the seed 64-bits at a time. */
2015    for (i = 0; i < n; i += 8) {
2016        state[o + 0] = state[o + 1] = state[o + 2] = state[o + 3] =
2017                readUnalignedWord64(seed + i);
2018        o += 4;
2019    }
2020    /* 32 bytes copied 8 bytes at a time. */
2021    for (i = 0; i < SLHDSA_HA_SZ; i += 8) {
2022        state[o + 0] = state[o + 1] = state[o + 2] = state[o + 3] =
2023            readUnalignedWord64(addr + i);
2024        o += 4;
2025    }
2026
2027    return o;
2028}
2029
2030#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
2031/* Fill out SHAKE-256 x4 state with n-byte seed, encoded HashAddress and hash.
2032 *
2033 * @param [in, out] state  SHAKE-256 x4 state.
2034 * @param [in]      seed   Seed at start of each hash.
2035 * @param [in]      addr   Encoded HashAddress for each hash.
2036 * @param [in]      hash   Hash data to put into each hash.
2037 * @param [in]      n      Number of bytes of seed.
2038 * @return  Offset after seed and HashAddress.
2039 */
2040static word32 slhdsakey_shake256_set_seed_ha_hash_x4(word64* state,
2041    const byte* seed, const byte* addr, const byte* hash, int n)
2042{
2043    int i;
2044    word32 o;
2045    word32 ret;
2046
2047    ret = o = slhdsakey_shake256_set_seed_ha_x4(state, seed, addr, n);
2048    for (i = 0; i < n; i += 8) {
2049        state[o + 0] = state[o + 1] = state[o + 2] = state[o + 3] =
2050            readUnalignedWord64(hash + i);
2051        o += 4;
2052    }
2053
2054    SHAKE256_SET_END_X4(state, o);
2055
2056    return ret;
2057}
2058#endif /* WOLFSSL_SLHDSA_VERIFY_ONLY */
2059
2060/* Get the four SHAKE-256 n-byte hash results.
2061 *
2062 * @param [in]  state  SHAKE-256 x4 state.
2063 * @param [out] hash   Hash buffer to hold 4 n-byte hash results.
2064 * @param [in]  n      Length of each hash in bytes.
2065 */
2066static void slhdsakey_shake256_get_hash_x4(const word64* state, byte* hash,
2067    int n)
2068{
2069    int i;
2070
2071    for (i = 0; i < (n / 8); i++) {
2072        ((word64*)(hash + 0 * n))[i] = state[4 * i + 0];
2073        ((word64*)(hash + 1 * n))[i] = state[4 * i + 1];
2074        ((word64*)(hash + 2 * n))[i] = state[4 * i + 2];
2075        ((word64*)(hash + 3 * n))[i] = state[4 * i + 3];
2076    }
2077}
2078
2079#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
2080/* Set the chain address into the SHAKE-256 x4 state.
2081 *
2082 * @param [in, out] state  SHAKE-256 x4 state.
2083 * @param [in]      o      Offset of state after HashAddress.
2084 * @param [in]      a      Value to set that increments for each hash.
2085 */
2086#define SHAKE256_SET_CHAIN_ADDRESS(state, o, a)                             \
2087do {                                                                        \
2088    ((word8*)((state) + (o) - 4))[3] = (word8)((a) + 0);                    \
2089    ((word8*)((state) + (o) - 3))[3] = (word8)((a) + 1);                    \
2090    ((word8*)((state) + (o) - 2))[3] = (word8)((a) + 2);                    \
2091    ((word8*)((state) + (o) - 1))[3] = (word8)((a) + 3);                    \
2092} while (0)
2093#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
2094
2095/* Set the chain address indices into the SHAKE-256 x4 state.
2096 *
2097 * @param [in, out] state  SHAKE-256 x4 state.
2098 * @param [in]      o      Offset of state after HashAddress.
2099 * @param [in]      idx    Indices to set for each hash.
2100 */
2101#define SHAKE256_SET_CHAIN_ADDRESS_IDX(state, o, idx)                       \
2102do {                                                                        \
2103    ((word8*)((state) + (o) - 4))[3] = (idx)[0];                            \
2104    ((word8*)((state) + (o) - 3))[3] = (idx)[1];                            \
2105    ((word8*)((state) + (o) - 2))[3] = (idx)[2];                            \
2106    ((word8*)((state) + (o) - 1))[3] = (idx)[3];                            \
2107} while (0)
2108
2109/* Set the hash address into the SHAKE-256 x4 state.
2110 *
2111 * @param [in, out] state  SHAKE-256 x4 state.
2112 * @param [in]      (o)      Offset of state after HashAddress.
2113 * @param [in]      a      Value to set for each hash.
2114 */
2115#define SHAKE256_SET_HASH_ADDRESS(state, o, a)                              \
2116do {                                                                        \
2117    ((word8*)((state) + (o) - 4))[7] = (word8)(a);                          \
2118    ((word8*)((state) + (o) - 3))[7] = (word8)(a);                          \
2119    ((word8*)((state) + (o) - 2))[7] = (word8)(a);                          \
2120    ((word8*)((state) + (o) - 1))[7] = (word8)(a);                          \
2121} while (0)
2122
2123#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
2124/* Set the tree index into the SHAKE-256 x4 state.
2125 *
2126 * @param [in, out] state  SHAKE-256 x4 state.
2127 * @param [in]      (o)      Offset of state after HashAddress.
2128 * @param [in]      ti     Value to encode that increments for each hash.
2129 */
2130#define SHAKE256_SET_TREE_INDEX(state, o, ti)                               \
2131do {                                                                        \
2132    c32toa((word32)((ti) + 0), (byte*)&((word32*)((state) + (o) - 4))[1]);  \
2133    c32toa((word32)((ti) + 1), (byte*)&((word32*)((state) + (o) - 3))[1]);  \
2134    c32toa((word32)((ti) + 2), (byte*)&((word32*)((state) + (o) - 2))[1]);  \
2135    c32toa((word32)((ti) + 3), (byte*)&((word32*)((state) + (o) - 1))[1]);  \
2136} while (0)
2137#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
2138
2139/* Set the tree indices into the SHAKE-256 x4 state.
2140 *
2141 * @param [in, out] state  SHAKE-256 x4 state.
2142 * @param [in]      (o)      Offset of state after HashAddress.
2143 * @param [in]      ti     Indices to encode for each hash.
2144 */
2145#define SHAKE256_SET_TREE_INDEX_IDX(state, o, ti)                           \
2146do {                                                                        \
2147    c32toa((ti)[0], (byte*)&((word32*)((state) + (o) - 4))[1]);             \
2148    c32toa((ti)[1], (byte*)&((word32*)((state) + (o) - 3))[1]);             \
2149    c32toa((ti)[2], (byte*)&((word32*)((state) + (o) - 2))[1]);             \
2150    c32toa((ti)[3], (byte*)&((word32*)((state) + (o) - 1))[1]);             \
2151} while (0)
2152
2153/* Set the tree height into the SHAKE-256 x4 state.
2154 *
2155 * @param [in, out] state  SHAKE-256 x4 state.
2156 * @param [in]      (o)      Offset of state after HashAddress.
2157 * @param [in]      ti     Value to encode for each hash.
2158 */
2159#define SHAKE256_SET_TREE_HEIGHT(state, o, th)                              \
2160do {                                                                        \
2161    c32toa((th), (byte*)&((word32*)((state) + (o) - 4))[0]);                \
2162    c32toa((th), (byte*)&((word32*)((state) + (o) - 3))[0]);                \
2163    c32toa((th), (byte*)&((word32*)((state) + (o) - 2))[0]);                \
2164    c32toa((th), (byte*)&((word32*)((state) + (o) - 1))[0]);                \
2165} while (0)
2166
2167#ifndef WOLFSSL_SLHDSA_PARAM_NO_128
2168/* Iterate the hash function s times with 4 hashes when n=16.
2169 *
2170 * FIPS 205. Section 5. Algorithm 5.
2171 * chain(X, i, s, PK.seed, ADRS)
2172 *   1: tmp <- X
2173 *   2: for j from i to i + s - 1 do
2174 *   3:     ADRS.setHashAddress(j)
2175 *   4:     tmp <- F(PK.seed, ADRS, tmp
2176 *   5: end for
2177 *   6: return tmp
2178 *
2179 * @param [in, out] sk       4 hashes to iterate.
2180 * @param [in]      i        Start index iterations.
2181 * @param [in]      s        Number of times to iterate.
2182 * @param [in]      pk_seed  Public key seed.
2183 * @param [in]      addr     Encoded HashAddress.
2184 * @param [in]      idx      Indices for chain address.
2185 * @param [in]      heap     Dynamic memory allocation hint.
2186 * @return  0 on success.
2187 * @return  MEMORY_E on dynamic memory allocation failure.
2188 */
2189static int slhdsakey_chain_idx_x4_16(byte* sk, word32 i, word32 s,
2190    const byte* pk_seed, byte* addr, byte* idx, void* heap)
2191{
2192    int ret = 0;
2193    word32 j;
2194    WC_DECLARE_VAR(fixed, word64, 6 * 4, heap);
2195    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
2196
2197    (void)heap;
2198
2199    WC_ALLOC_VAR_EX(fixed, word64, 6 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2200        ret = MEMORY_E);
2201    if (ret == 0) {
2202        WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2203            ret = MEMORY_E);
2204    }
2205    if (ret == 0) {
2206        SHAKE256_SET_SEED_HA_X4_16(fixed, pk_seed, addr);
2207        SHAKE256_SET_CHAIN_ADDRESS_IDX(fixed, 24, idx);
2208        SHAKE256_SET_HASH_X4_16(state, sk);
2209
2210        for (j = i; j < i + s; j++) {
2211            if (j != i) {
2212                XMEMCPY(state + 24, state, 16 * 4);
2213            }
2214            XMEMCPY(state, fixed, (6 * 4) * sizeof(word64));
2215            SHAKE256_SET_HASH_ADDRESS(state, 24, j);
2216            SHAKE256_SET_END_X4(state, 32);
2217            ret = SAVE_VECTOR_REGISTERS2();
2218            if (ret != 0)
2219                return ret;
2220            sha3_blocksx4_avx2(state);
2221            RESTORE_VECTOR_REGISTERS();
2222        }
2223
2224        SHAKE256_GET_HASH_X4_16(state, sk);
2225    }
2226
2227    WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
2228    WC_FREE_VAR_EX(fixed, heap, DYNAMIC_TYPE_SLHDSA);
2229    return ret;
2230}
2231#endif
2232#ifndef WOLFSSL_SLHDSA_PARAM_NO_192
2233/* Iterate the hash function s times with 4 hashes when n=24.
2234 *
2235 * FIPS 205. Section 5. Algorithm 5.
2236 * chain(X, i, s, PK.seed, ADRS)
2237 *   1: tmp <- X
2238 *   2: for j from i to i + s - 1 do
2239 *   3:     ADRS.setHashAddress(j)
2240 *   4:     tmp <- F(PK.seed, ADRS, tmp
2241 *   5: end for
2242 *   6: return tmp
2243 *
2244 * @param [in, out] sk       4 hashes to iterate.
2245 * @param [in]      i        Start index iterations.
2246 * @param [in]      s        Number of times to iterate.
2247 * @param [in]      pk_seed  Public key seed.
2248 * @param [in]      addr     Encoded HashAddress.
2249 * @param [in]      idx      Indices for chain address.
2250 * @param [in]      heap     Dynamic memory allocation hint.
2251 * @return  0 on success.
2252 * @return  MEMORY_E on dynamic memory allocation failure.
2253 */
2254static int slhdsakey_chain_idx_x4_24(byte* sk, word32 i, word32 s,
2255    const byte* pk_seed, byte* addr, byte* idx, void* heap)
2256{
2257    int ret = 0;
2258    word32 j;
2259    WC_DECLARE_VAR(fixed, word64, 7 * 4, heap);
2260    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
2261
2262    (void)heap;
2263
2264    WC_ALLOC_VAR_EX(fixed, word64, 7 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2265        ret = MEMORY_E);
2266    if (ret == 0) {
2267        WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2268            ret = MEMORY_E);
2269    }
2270    if (ret == 0) {
2271        SHAKE256_SET_SEED_HA_X4_24(fixed, pk_seed, addr);
2272        SHAKE256_SET_CHAIN_ADDRESS_IDX(fixed, 28, idx);
2273        SHAKE256_SET_HASH_X4_24(state, sk);
2274
2275        for (j = i; j < i + s; j++) {
2276            if (j != i) {
2277                XMEMCPY(state + 28, state, 24 * 4);
2278            }
2279            XMEMCPY(state, fixed, 28 * sizeof(word64));
2280            SHAKE256_SET_HASH_ADDRESS(state, 28, j);
2281            SHAKE256_SET_END_X4(state, 40);
2282            ret = SAVE_VECTOR_REGISTERS2();
2283            if (ret != 0)
2284                return ret;
2285            sha3_blocksx4_avx2(state);
2286            RESTORE_VECTOR_REGISTERS();
2287        }
2288
2289        SHAKE256_GET_HASH_X4_24(state, sk);
2290    }
2291
2292    WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
2293    WC_FREE_VAR_EX(fixed, heap, DYNAMIC_TYPE_SLHDSA);
2294    return ret;
2295}
2296#endif
2297#ifndef WOLFSSL_SLHDSA_PARAM_NO_256
2298/* Iterate the hash function s times with 4 hashes when n=32.
2299 *
2300 * FIPS 205. Section 5. Algorithm 5.
2301 * chain(X, i, s, PK.seed, ADRS)
2302 *   1: tmp <- X
2303 *   2: for j from i to i + s - 1 do
2304 *   3:     ADRS.setHashAddress(j)
2305 *   4:     tmp <- F(PK.seed, ADRS, tmp
2306 *   5: end for
2307 *   6: return tmp
2308 *
2309 * @param [in, out] sk       4 hashes to iterate.
2310 * @param [in]      i        Start index iterations.
2311 * @param [in]      s        Number of times to iterate.
2312 * @param [in]      pk_seed  Public key seed.
2313 * @param [in]      addr     Encoded HashAddress.
2314 * @param [in]      idx      Indices for chain address.
2315 * @param [in]      heap     Dynamic memory allocation hint.
2316 * @return  0 on success.
2317 * @return  MEMORY_E on dynamic memory allocation failure.
2318 */
2319static int slhdsakey_chain_idx_x4_32(byte* sk, word32 i, word32 s,
2320    const byte* pk_seed, byte* addr, byte* idx, void* heap)
2321{
2322    int ret = 0;
2323    word32 j;
2324    WC_DECLARE_VAR(fixed, word64, 8 * 4, heap);
2325    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
2326
2327    (void)heap;
2328
2329    WC_ALLOC_VAR_EX(fixed, word64, 8 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2330        ret = MEMORY_E);
2331    if (ret == 0) {
2332        WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2333            ret = MEMORY_E);
2334    }
2335    if (ret == 0) {
2336        SHAKE256_SET_SEED_HA_X4_32(fixed, pk_seed, addr);
2337        SHAKE256_SET_CHAIN_ADDRESS_IDX(fixed, 32, idx);
2338        SHAKE256_SET_HASH_X4_32(state, sk);
2339
2340        for (j = i; j < i + s; j++) {
2341            if (j != i) {
2342                XMEMCPY(state + 32, state, 32 * 4);
2343            }
2344            XMEMCPY(state, fixed, 32 * sizeof(word64));
2345            SHAKE256_SET_HASH_ADDRESS(state, 32, j);
2346            SHAKE256_SET_END_X4(state, 48);
2347            ret = SAVE_VECTOR_REGISTERS2();
2348            if (ret != 0)
2349                return ret;
2350            sha3_blocksx4_avx2(state);
2351            RESTORE_VECTOR_REGISTERS();
2352        }
2353
2354        SHAKE256_GET_HASH_X4_32(state, sk);
2355    }
2356
2357    WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
2358    WC_FREE_VAR_EX(fixed, heap, DYNAMIC_TYPE_SLHDSA);
2359    return ret;
2360}
2361#endif
2362#endif
2363
2364#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
2365#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
2366/* PRF hash 4 simultaneously.
2367 *
2368 * Each hash varies by the chain address with the first value in sequence passed
2369 * in.
2370 *
2371 * FIPS 205. Section 4.1.
2372 *   PRF(PK.seed, SK.seed, ADRS) (Bn x Bn x B32 -> Bn) is a PRF that is used to
2373 *   generate the secret values in WOTS+ and FORS private keys.
2374 * FIPS 205. Section 11.1.
2375 *   PRF(PK.seed, SK.seed, ADRS) = SHAKE256(PK.seed || ADRS || SK.seed, 8n)
2376 *
2377 * @param [in]  pk_seed  Public key seed.
2378 * @param [in]  sk_seed  Private key seed.
2379 * @param [in]  addr     Encoded HashAddress.
2380 * @param [in]  n        Number of bytes in hash output.
2381 * @param [in]  ca       Chain address start index.
2382 * @param [out] sk       Buffer to hold hash output.
2383 * @param [in]  heap     Dynamic memory allocation hint.
2384 * @return  0 on success.
2385 * @return  MEMORY_E on dynamic memory allocation failure.
2386 * @return  SHAKE-256 error return code on digest failure.
2387 */
2388static int slhdsakey_hash_prf_x4(const byte* pk_seed, const byte* sk_seed,
2389    byte* addr, byte n, byte ca, byte* sk, void* heap)
2390{
2391    int ret = 0;
2392    word32 o = 0;
2393    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
2394
2395    (void)heap;
2396
2397    WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2398        ret = MEMORY_E);
2399    if (ret == 0) {
2400        o = slhdsakey_shake256_set_seed_ha_hash_x4(state, pk_seed, addr,
2401            sk_seed, n);
2402        SHAKE256_SET_CHAIN_ADDRESS(state, o, ca);
2403        ret = SAVE_VECTOR_REGISTERS2();
2404        if (ret == 0) {
2405            sha3_blocksx4_avx2(state);
2406            slhdsakey_shake256_get_hash_x4(state, sk, n);
2407            RESTORE_VECTOR_REGISTERS();
2408        }
2409
2410        WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
2411    }
2412
2413    return ret;
2414}
2415
2416#if !defined(WOLFSSL_SLHDSA_PARAM_NO_128)
2417/* Iterate the hash function 15 times with 4 hashes when n=16.
2418 *
2419 * FIPS 205. Section 5. Algorithm 5.
2420 * chain(X, i, s, PK.seed, ADRS)
2421 *   1: tmp <- X
2422 *   2: for j from i to i + s - 1 do
2423 *   3:     ADRS.setHashAddress(j)
2424 *   4:     tmp <- F(PK.seed, ADRS, tmp
2425 *   5: end for
2426 *   6: return tmp
2427 *
2428 * @param [in, out] sk       4 hashes to iterate.
2429 * @param [in]      pk_seed  Public key seed.
2430 * @param [in]      addr     Encoded HashAddress.
2431 * @param [in]      ca       Chain address start index.
2432 * @param [in]      heap     Dynamic memory allocation hint.
2433 * @return  0 on success.
2434 * @return  MEMORY_E on dynamic memory allocation failure.
2435 */
2436static int slhdsakey_chain_x4_16(byte* sk, const byte* pk_seed, byte* addr,
2437    byte ca, void* heap)
2438{
2439    int ret = 0;
2440    int j;
2441    WC_DECLARE_VAR(fixed, word64, 8 * 4, heap);
2442    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
2443
2444    (void)heap;
2445
2446    WC_ALLOC_VAR_EX(fixed, word64, 8 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2447        ret = MEMORY_E);
2448    if (ret == 0) {
2449        WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2450            ret = MEMORY_E);
2451    }
2452    if (ret == 0) {
2453        SHAKE256_SET_SEED_HA_X4_16(fixed, pk_seed, addr);
2454        SHAKE256_SET_CHAIN_ADDRESS(fixed, 24, ca);
2455        SHAKE256_SET_HASH_X4_16(state, sk);
2456
2457        for (j = 0; j < 15; j++) {
2458            if (j != 0) {
2459                XMEMCPY(state + 24, state, 16 * 4);
2460            }
2461            XMEMCPY(state, fixed, 24 * sizeof(word64));
2462            SHAKE256_SET_HASH_ADDRESS(state, 24, j);
2463            SHAKE256_SET_END_X4(state, 32);
2464            ret = SAVE_VECTOR_REGISTERS2();
2465            if (ret != 0)
2466                break;
2467            sha3_blocksx4_avx2(state);
2468            RESTORE_VECTOR_REGISTERS();
2469        }
2470
2471        if (ret == 0)
2472            SHAKE256_GET_HASH_X4_16(state, sk);
2473    }
2474
2475    WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
2476    WC_FREE_VAR_EX(fixed, heap, DYNAMIC_TYPE_SLHDSA);
2477    return ret;
2478}
2479#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
2480
2481#if !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
2482/* Iterate the hash function 15 times with 4 hashes when n=24.
2483 *
2484 * FIPS 205. Section 5. Algorithm 5.
2485 * chain(X, i, s, PK.seed, ADRS)
2486 *   1: tmp <- X
2487 *   2: for j from i to i + s - 1 do
2488 *   3:     ADRS.setHashAddress(j)
2489 *   4:     tmp <- F(PK.seed, ADRS, tmp
2490 *   5: end for
2491 *   6: return tmp
2492 *
2493 * @param [in, out] sk       4 hashes to iterate.
2494 * @param [in]      pk_seed  Public key seed.
2495 * @param [in]      addr     Encoded HashAddress.
2496 * @param [in]      ca       Chain address start index.
2497 * @param [in]      heap     Dynamic memory allocation hint.
2498 * @return  0 on success.
2499 * @return  MEMORY_E on dynamic memory allocation failure.
2500 */
2501static int slhdsakey_chain_x4_24(byte* sk, const byte* pk_seed, byte* addr,
2502    byte ca, void* heap)
2503{
2504    int ret = 0;
2505    int j;
2506    WC_DECLARE_VAR(fixed, word64, 8 * 4, heap);
2507    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
2508
2509    (void)heap;
2510
2511    WC_ALLOC_VAR_EX(fixed, word64, 8 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2512        ret = MEMORY_E);
2513    if (ret == 0) {
2514        WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2515            ret = MEMORY_E);
2516    }
2517    if (ret == 0) {
2518        SHAKE256_SET_SEED_HA_X4_24(fixed, pk_seed, addr);
2519        SHAKE256_SET_CHAIN_ADDRESS(fixed, 28, ca);
2520        SHAKE256_SET_HASH_X4_24(state, sk);
2521
2522        for (j = 0; j < 15; j++) {
2523            if (j != 0) {
2524                XMEMCPY(state + 28, state, 24 * 4);
2525            }
2526            XMEMCPY(state, fixed, 28 * sizeof(word64));
2527            SHAKE256_SET_HASH_ADDRESS(state, 28, j);
2528            SHAKE256_SET_END_X4(state, 40);
2529            ret = SAVE_VECTOR_REGISTERS2();
2530            if (ret != 0)
2531                break;
2532            sha3_blocksx4_avx2(state);
2533            RESTORE_VECTOR_REGISTERS();
2534        }
2535
2536        if (ret == 0)
2537            SHAKE256_GET_HASH_X4_24(state, sk);
2538    }
2539
2540    WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
2541    WC_FREE_VAR_EX(fixed, heap, DYNAMIC_TYPE_SLHDSA);
2542    return ret;
2543}
2544#endif
2545
2546#if !defined(WOLFSSL_SLHDSA_PARAM_NO_256)
2547/* Iterate the hash function 15 times with 4 hashes when n=32.
2548 *
2549 * FIPS 205. Section 5. Algorithm 5.
2550 * chain(X, i, s, PK.seed, ADRS)
2551 *   1: tmp <- X
2552 *   2: for j from i to i + s - 1 do
2553 *   3:     ADRS.setHashAddress(j)
2554 *   4:     tmp <- F(PK.seed, ADRS, tmp
2555 *   5: end for
2556 *   6: return tmp
2557 *
2558 * @param [in, out] sk       4 hashes to iterate.
2559 * @param [in]      pk_seed  Public key seed.
2560 * @param [in]      addr     Encoded HashAddress.
2561 * @param [in]      ca       Chain address start index.
2562 * @param [in]      heap     Dynamic memory allocation hint.
2563 * @return  0 on success.
2564 * @return  MEMORY_E on dynamic memory allocation failure.
2565 */
2566static int slhdsakey_chain_x4_32(byte* sk, const byte* pk_seed, byte* addr,
2567    byte ca, void* heap)
2568{
2569    int ret = 0;
2570    int j;
2571    WC_DECLARE_VAR(fixed, word64, 8 * 4, heap);
2572    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
2573
2574    (void)heap;
2575
2576    WC_ALLOC_VAR_EX(fixed, word64, 8 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2577        ret = MEMORY_E);
2578    if (ret == 0) {
2579        WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2580            ret = MEMORY_E);
2581    }
2582    if (ret == 0) {
2583        SHAKE256_SET_SEED_HA_X4_32(fixed, pk_seed, addr);
2584        SHAKE256_SET_CHAIN_ADDRESS(fixed, 32, ca);
2585        SHAKE256_SET_HASH_X4_32(state, sk);
2586
2587        for (j = 0; j < 15; j++) {
2588            if (j != 0) {
2589                XMEMCPY(state + 32, state, 32 * 4);
2590            }
2591            XMEMCPY(state, fixed, 32 * sizeof(word64));
2592            SHAKE256_SET_HASH_ADDRESS(state, 32, j);
2593            SHAKE256_SET_END_X4(state, 48);
2594            ret = SAVE_VECTOR_REGISTERS2();
2595            if (ret != 0)
2596                break;
2597            sha3_blocksx4_avx2(state);
2598            RESTORE_VECTOR_REGISTERS();
2599        }
2600
2601        if (ret == 0)
2602            SHAKE256_GET_HASH_X4_32(state, sk);
2603    }
2604
2605    WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
2606    WC_FREE_VAR_EX(fixed, heap, DYNAMIC_TYPE_SLHDSA);
2607    return ret;
2608}
2609#endif
2610
2611/* PRF hash 4 simultaneously.
2612 *
2613 * Each hash varies by the chain address which is passed in as an array.
2614 *
2615 * FIPS 205. Section 4.1.
2616 *   PRF(PK.seed, SK.seed, ADRS) (Bn x Bn x B32 -> Bn) is a PRF that is used to
2617 *   generate the secret values in WOTS+ and FORS private keys.
2618 * FIPS 205. Section 11.1.
2619 *   PRF(PK.seed, SK.seed, ADRS) = SHAKE256(PK.seed || ADRS || SK.seed, 8n)
2620 *
2621 * @param [in]  pk_seed  Public key seed.
2622 * @param [in]  sk_seed  Private key seed.
2623 * @param [in]  addr     Encoded HashAddress.
2624 * @param [in]  n        Number of bytes in hash output.
2625 * @param [in]  idx      Four chain address indices.
2626 * @param [out] sk       Buffer to hold hash output.
2627 * @param [in]  heap     Dynamic memory allocation hint.
2628 * @return  0 on success.
2629 * @return  MEMORY_E on dynamic memory allocation failure.
2630 * @return  SHAKE-256 error return code on digest failure.
2631 */
2632static int slhdsakey_hash_prf_idx_x4(const byte* pk_seed, const byte* sk_seed,
2633    byte* addr, byte n, byte* idx, byte* sk, void* heap)
2634{
2635    int ret = 0;
2636    word32 o = 0;
2637    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
2638
2639    (void)heap;
2640
2641    WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
2642        ret = MEMORY_E);
2643    if (ret == 0) {
2644        o = slhdsakey_shake256_set_seed_ha_hash_x4(state, pk_seed, addr,
2645            sk_seed, n);
2646        SHAKE256_SET_CHAIN_ADDRESS_IDX(state, o, idx);
2647        ret = SAVE_VECTOR_REGISTERS2();
2648        if (ret == 0) {
2649            sha3_blocksx4_avx2(state);
2650            RESTORE_VECTOR_REGISTERS();
2651            slhdsakey_shake256_get_hash_x4(state, sk, n);
2652        }
2653
2654        WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
2655    }
2656
2657    return ret;
2658}
2659
2660#if !defined(WOLFSSL_SLHDSA_PARAM_NO_128)
2661/* Iterate hash function up to index times for each of the hashes when n=16.
2662 *
2663 * FIPS 205. Section 5. Algorithm 5.
2664 * chain(X, i, s, PK.seed, ADRS)
2665 *   1: tmp <- X
2666 *   2: for j from i to i + s - 1 do
2667 *   3:     ADRS.setHashAddress(j)
2668 *   4:     tmp <- F(PK.seed, ADRS, tmp
2669 *   5: end for
2670 *   6: return tmp
2671 *
2672 * @param [in]  key      SLH-DSA key.
2673 * @param [in]  sk       Hashes to iterate. Data modified.
2674 * @param [in]  pk_seed  Public key seed.
2675 * @param [in]  adrs     HashAddress.
2676 * @param [in]  addr     Encoded HashAddress.
2677 * @param [in]  msg      Array of counts.
2678 * @param [in]  idx      Indices into array of counts.
2679 * @param [in]  j        Minimum number of iterations for all 4 hashes.
2680 * @param [in]  cnt      Number of hashes to iterate.
2681 * @param [out] sig      Hash results.
2682 * @return  0 on success.
2683 * @return  MEMORY_E on dynamic memory allocation failure.
2684 */
2685static int slhdsakey_chain_idx_16(SlhDsaKey* key, byte* sk,
2686     const byte* pk_seed, word32* adrs, byte* addr, const byte* msg, byte* idx,
2687     int j, int cnt, byte* sig)
2688{
2689    int ret = 0;
2690
2691    /* Iterate the minimum number of iterations on all hashes. */
2692    if (j != 0) {
2693        ret = slhdsakey_chain_idx_x4_16(sk, 0U, (word32)j, pk_seed, addr, idx,
2694            key->heap);
2695    }
2696    if (ret == 0) {
2697        if (cnt > 3) {
2698            /* Copy out hash at index 3 as it is finished. */
2699            XMEMCPY(sig + idx[3] * 16, sk + 3 * 16, 16);
2700        }
2701        /* Check if more iterations needed for index 2. */
2702        if (msg[idx[2]] != j) {
2703            /* Do 4 as we can't do less. */
2704            ret = slhdsakey_chain_idx_x4_16(sk, (word32)j,
2705                    (word32)(msg[idx[2]] - j), pk_seed, addr, idx, key->heap);
2706            /* Update number of iterations performed. */
2707            j = msg[idx[2]];
2708        }
2709    }
2710    if (ret == 0) {
2711        /* Copy out hash at index 2 as it is finished. */
2712        XMEMCPY(sig + idx[2] * 16, sk + 2 * 16, 16);
2713        /* Check if more iterations needed for index 1. */
2714        if (msg[idx[1]] != j) {
2715            /* Do 4 as we can't do less. */
2716            ret = slhdsakey_chain_idx_x4_16(sk, (word32)j,
2717                    (word32)(msg[idx[1]] - j), pk_seed, addr, idx, key->heap);
2718            /* Update number of iterations performed. */
2719            j = msg[idx[1]];
2720        }
2721    }
2722    if (ret == 0) {
2723        /* Copy out hash at index 1 as it is finished. */
2724        XMEMCPY(sig + idx[1] * 16, sk + 1 * 16, 16);
2725        /* Check if more iterations needed for index 0. */
2726        if (msg[idx[0]] != j) {
2727            /* Iterate 1 hash as it takes less time than doing 4. */
2728            HA_SetChainAddress(adrs, idx[0]);
2729            ret = slhdsakey_chain(key, sk, (byte)j, (byte)(msg[idx[0]] - j),
2730                    pk_seed, adrs, sk);
2731        }
2732    }
2733    if (ret == 0) {
2734        /* Copy out hash at index 0 as it is finished. */
2735        XMEMCPY(sig + idx[0] * 16, sk + 0 * 16, 16);
2736    }
2737
2738    return ret;
2739}
2740#endif
2741
2742#if !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
2743/* Iterate hash function up to index times for each of the hashes when n=24.
2744 *
2745 * FIPS 205. Section 5. Algorithm 5.
2746 * chain(X, i, s, PK.seed, ADRS)
2747 *   1: tmp <- X
2748 *   2: for j from i to i + s - 1 do
2749 *   3:     ADRS.setHashAddress(j)
2750 *   4:     tmp <- F(PK.seed, ADRS, tmp
2751 *   5: end for
2752 *   6: return tmp
2753 *
2754 * @param [in]  key      SLH-DSA key.
2755 * @param [in]  sk       Hashes to iterate. Data modified.
2756 * @param [in]  pk_seed  Public key seed.
2757 * @param [in]  adrs     HashAddress.
2758 * @param [in]  addr     Encoded HashAddress.
2759 * @param [in]  msg      Array of counts.
2760 * @param [in]  idx      Indices into array of counts.
2761 * @param [in]  j        Minimum number of iterations for all 4 hashes.
2762 * @param [in]  cnt      Number of hashes to iterate.
2763 * @param [out] sig      Hash results.
2764 * @return  0 on success.
2765 * @return  MEMORY_E on dynamic memory allocation failure.
2766 */
2767static int slhdsakey_chain_idx_24(SlhDsaKey* key, byte* sk,
2768     const byte* pk_seed, word32* adrs, byte* addr, const byte* msg, byte* idx,
2769     int j, int cnt, byte* sig)
2770{
2771    int ret = 0;
2772
2773    /* Iterate the minimum number of iterations on all hashes. */
2774    if (j != 0) {
2775        ret = slhdsakey_chain_idx_x4_24(sk, 0U, (word32)j, pk_seed, addr, idx,
2776            key->heap);
2777    }
2778    if (ret == 0) {
2779        if (cnt > 3) {
2780            /* Copy out hash at index 3 as it is finished. */
2781            XMEMCPY(sig + idx[3] * 24, sk + 3 * 24, 24);
2782        }
2783        /* Check if more iterations needed for index 2. */
2784        if (msg[idx[2]] != j) {
2785            /* Do 4 as we can't do less. */
2786            ret = slhdsakey_chain_idx_x4_24(sk, (word32)j,
2787                    (word32)(msg[idx[2]] - j), pk_seed, addr, idx, key->heap);
2788            /* Update number of iterations performed. */
2789            j = msg[idx[2]];
2790        }
2791    }
2792    if (ret == 0) {
2793        /* Copy out hash at index 2 as it is finished. */
2794        XMEMCPY(sig + idx[2] * 24, sk + 2 * 24, 24);
2795        /* Check if more iterations needed for index 1. */
2796        if (msg[idx[1]] != j) {
2797            /* Do 4 as we can't do less. */
2798            ret = slhdsakey_chain_idx_x4_24(sk, (word32)j,
2799                    (word32)(msg[idx[1]] - j), pk_seed, addr, idx, key->heap);
2800            /* Update number of iterations performed. */
2801            j = msg[idx[1]];
2802        }
2803    }
2804    if (ret == 0) {
2805        /* Copy out hash at index 1 as it is finished. */
2806        XMEMCPY(sig + idx[1] * 24, sk + 1 * 24, 24);
2807        /* Check if more iterations needed for index 0. */
2808        if (msg[idx[0]] != j) {
2809            /* Iterate 1 hash as it takes less time than doing 4. */
2810            HA_SetChainAddress(adrs, idx[0]);
2811            ret = slhdsakey_chain(key, sk, (byte)j, (byte)(msg[idx[0]] - j),
2812                    pk_seed, adrs, sk);
2813        }
2814    }
2815    if (ret == 0) {
2816        /* Copy out hash at index 0 as it is finished. */
2817        XMEMCPY(sig + idx[0] * 24, sk + 0 * 24, 24);
2818    }
2819
2820    return ret;
2821}
2822#endif
2823
2824#if !defined(WOLFSSL_SLHDSA_PARAM_NO_256)
2825/* Iterate hash function up to index times for each of the hashes when n=32.
2826 *
2827 * FIPS 205. Section 5. Algorithm 5.
2828 * chain(X, i, s, PK.seed, ADRS)
2829 *   1: tmp <- X
2830 *   2: for j from i to i + s - 1 do
2831 *   3:     ADRS.setHashAddress(j)
2832 *   4:     tmp <- F(PK.seed, ADRS, tmp
2833 *   5: end for
2834 *   6: return tmp
2835 *
2836 * @param [in]  key      SLH-DSA key.
2837 * @param [in]  sk       Hashes to iterate. Data modified.
2838 * @param [in]  pk_seed  Public key seed.
2839 * @param [in]  adrs     HashAddress.
2840 * @param [in]  addr     Encoded HashAddress.
2841 * @param [in]  msg      Array of counts.
2842 * @param [in]  idx      Indices into array of counts.
2843 * @param [in]  j        Minimum number of iterations for all 4 hashes.
2844 * @param [in]  cnt      Number of hashes to iterate.
2845 * @param [out] sig      Hash results.
2846 * @return  0 on success.
2847 * @return  MEMORY_E on dynamic memory allocation failure.
2848 */
2849static int slhdsakey_chain_idx_32(SlhDsaKey* key, byte* sk,
2850     const byte* pk_seed, word32* adrs, byte* addr, const byte* msg, byte* idx,
2851     int j, int cnt, byte* sig)
2852{
2853    int ret = 0;
2854
2855    /* Iterate the minimum number of iterations on all hashes. */
2856    if (j != 0) {
2857        ret = slhdsakey_chain_idx_x4_32(sk, 0U, (word32)j, pk_seed, addr, idx,
2858            key->heap);
2859    }
2860    if (ret == 0) {
2861        if (cnt > 3) {
2862            /* Copy out hash at index 3 as it is finished. */
2863            XMEMCPY(sig + idx[3] * 32, sk + 3 * 32, 32);
2864        }
2865        /* Check if more iterations needed for index 2. */
2866        if (msg[idx[2]] != j) {
2867            /* Do 4 as we can't do less. */
2868            ret = slhdsakey_chain_idx_x4_32(sk, (word32)j,
2869                    (word32)(msg[idx[2]] - j), pk_seed, addr, idx, key->heap);
2870            /* Update number of iterations performed. */
2871            j = msg[idx[2]];
2872        }
2873    }
2874    if (ret == 0) {
2875        /* Copy out hash at index 2 as it is finished. */
2876        XMEMCPY(sig + idx[2] * 32, sk + 2 * 32, 32);
2877        /* Check if more iterations needed for index 1. */
2878        if (msg[idx[1]] != j) {
2879            /* Do 4 as we can't do less. */
2880            ret = slhdsakey_chain_idx_x4_32(sk, (word32)j,
2881                    (word32)(msg[idx[1]] - j), pk_seed, addr, idx, key->heap);
2882            /* Update number of iterations performed. */
2883            j = msg[idx[1]];
2884        }
2885    }
2886    if (ret == 0) {
2887        /* Copy out hash at index 1 as it is finished. */
2888        XMEMCPY(sig + idx[1] * 32, sk + 1 * 32, 32);
2889        /* Check if more iterations needed for index 0. */
2890        if (msg[idx[0]] != j) {
2891            /* Iterate 1 hash as it takes less time than doing 4. */
2892            HA_SetChainAddress(adrs, idx[0]);
2893            ret = slhdsakey_chain(key, sk, (byte)j, (byte)(msg[idx[0]] - j),
2894                    pk_seed, adrs, sk);
2895        }
2896    }
2897    if (ret == 0) {
2898        /* Copy out hash at index 0 as it is finished. */
2899        XMEMCPY(sig + idx[0] * 32, sk + 0 * 32, 32);
2900    }
2901
2902    return ret;
2903}
2904#endif
2905#endif
2906
2907#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
2908#if !defined(WOLFSSL_SLHDSA_PARAM_NO_128)
2909/* Generate WOTS+ public key, 16-byte hashes - 4 consecutive at a time.
2910 *
2911 * FIPS 205 Section 5.1. Algorithm 6.
2912 * wots_pkGen(SK.seed, PK.seed, ADRS)
2913 *  ...
2914 *   4: for i from 0 to len - 1 do
2915 *   5:     skADRS.setChainAddress(i)
2916 *   6:     sk <- PRF(PK.seed, SK.seed, skADRS)
2917 *                                            > compute secret value for chain i
2918 *   7:     ADRS.setChainAddress(i)
2919 *   8:     tmp[i] <- chain(sk 0, w - 1, PK.seed, ADRS)
2920 *                                            > compute public value for chain i
2921 *   9: end for
2922 *  10: wotspkADRS <- ADRS     > copy address to create WOTS+ public key address
2923 *  ...
2924 *  13: pk <- Tlen(PK.seed, wotspkADRS, tmp)               > compress public key
2925 *  ...
2926 *
2927 * @param [in] key      SLH-DSA key.
2928 * @param [in] sk_seed  Private key seed.
2929 * @param [in] pk_seed  Public key seed.
2930 * @param [in] addr     Encoded HashAddress.
2931 * @param [in] sk_addr  Encoded WOTS PRF HashAddress.
2932 * @return  0 on success.
2933 * @return  MEMORY_E on dynamic memory allocation failure.
2934 */
2935static int slhdsakey_wots_pkgen_chain_x4_16(SlhDsaKey* key, const byte* sk_seed,
2936    const byte* pk_seed, byte* addr, byte* sk_addr)
2937{
2938    int ret = 0;
2939    int i;
2940    byte len = key->params->len;
2941    WC_DECLARE_VAR(sk, byte, (SLHDSA_MAX_MSG_SZ + 3) * 16, key->heap);
2942
2943    WC_ALLOC_VAR_EX(sk, byte, (SLHDSA_MAX_MSG_SZ + 3) * 16, key->heap,
2944        DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
2945    if (ret == 0) {
2946        for (i = 0; i < len - 3; i += 4) {
2947            ret = slhdsakey_hash_prf_x4(pk_seed, sk_seed, sk_addr, 16, (byte)i,
2948                sk + i * 16, key->heap);
2949            if (ret != 0) {
2950                break;
2951            }
2952            ret = slhdsakey_chain_x4_16(sk + i * 16, pk_seed, addr, (byte)i,
2953                key->heap);
2954            if (ret != 0) {
2955                break;
2956            }
2957        }
2958    }
2959    if (ret == 0) {
2960        ret = slhdsakey_hash_prf_x4(pk_seed, sk_seed, sk_addr, 16, (byte)i,
2961            sk + i * 16, key->heap);
2962        if (ret == 0) {
2963            ret = slhdsakey_chain_x4_16(sk + i * 16, pk_seed, addr, (byte)i,
2964                key->heap);
2965        }
2966    }
2967    if (ret == 0) {
2968        ret = HASH_T_UPDATE(key, sk, (word32)len * 16U);
2969    }
2970
2971    WC_FREE_VAR_EX(sk, key->heap, DYNAMIC_TYPE_SLHDSA);
2972    return ret;
2973}
2974#endif
2975
2976#if !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
2977/* Generate WOTS+ public key, 24-byte hashes - 4 consecutive at a time.
2978 *
2979 * FIPS 205 Section 5.1. Algorithm 6.
2980 * wots_pkGen(SK.seed, PK.seed, ADRS)
2981 *  ...
2982 *   4: for i from 0 to len - 1 do
2983 *   5:     skADRS.setChainAddress(i)
2984 *   6:     sk <- PRF(PK.seed, SK.seed, skADRS)
2985 *                                            > compute secret value for chain i
2986 *   7:     ADRS.setChainAddress(i)
2987 *   8:     tmp[i] <- chain(sk 0, w - 1, PK.seed, ADRS)
2988 *                                            > compute public value for chain i
2989 *   9: end for
2990 *  10: wotspkADRS <- ADRS     > copy address to create WOTS+ public key address
2991 *  ...
2992 *  13: pk <- Tlen(PK.seed, wotspkADRS, tmp)               > compress public key
2993 *  ...
2994 *
2995 * @param [in] key      SLH-DSA key.
2996 * @param [in] sk_seed  Private key seed.
2997 * @param [in] pk_seed  Public key seed.
2998 * @param [in] addr     Encoded HashAddress.
2999 * @param [in] sk_addr  Encoded WOTS PRF HashAddress.
3000 * @return  0 on success.
3001 * @return  MEMORY_E on dynamic memory allocation failure.
3002 */
3003static int slhdsakey_wots_pkgen_chain_x4_24(SlhDsaKey* key, const byte* sk_seed,
3004    const byte* pk_seed, byte* addr, byte* sk_addr)
3005{
3006    int ret = 0;
3007    int i;
3008    byte len = key->params->len;
3009    WC_DECLARE_VAR(sk, byte, (SLHDSA_MAX_MSG_SZ + 3) * 24, key->heap);
3010
3011    WC_ALLOC_VAR_EX(sk, byte, (SLHDSA_MAX_MSG_SZ + 3) * 24, key->heap,
3012        DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
3013    if (ret == 0) {
3014        for (i = 0; i < len - 3; i += 4) {
3015            ret = slhdsakey_hash_prf_x4(pk_seed, sk_seed, sk_addr, 24, (byte)i,
3016                sk + i * 24, key->heap);
3017            if (ret != 0) {
3018                break;
3019            }
3020            ret = slhdsakey_chain_x4_24(sk + i * 24, pk_seed, addr, (byte)i,
3021                key->heap);
3022            if (ret != 0) {
3023                break;
3024            }
3025        }
3026    }
3027    if (ret == 0) {
3028        ret = slhdsakey_hash_prf_x4(pk_seed, sk_seed, sk_addr, 24, (byte)i,
3029            sk + i * 24, key->heap);
3030        if (ret == 0) {
3031            ret = slhdsakey_chain_x4_24(sk + i * 24, pk_seed, addr, (byte)i,
3032                key->heap);
3033        }
3034    }
3035    if (ret == 0) {
3036        ret = HASH_T_UPDATE(key, sk, (word32)len * 24U);
3037    }
3038
3039    WC_FREE_VAR_EX(sk, key->heap, DYNAMIC_TYPE_SLHDSA);
3040    return ret;
3041}
3042#endif
3043
3044#if !defined(WOLFSSL_SLHDSA_PARAM_NO_256)
3045/* Generate WOTS+ public key, 32-byte hashes - 4 consecutive at a time.
3046 *
3047 * FIPS 205 Section 5.1. Algorithm 6.
3048 * wots_pkGen(SK.seed, PK.seed, ADRS)
3049 *  ...
3050 *   4: for i from 0 to len - 1 do
3051 *   5:     skADRS.setChainAddress(i)
3052 *   6:     sk <- PRF(PK.seed, SK.seed, skADRS)
3053 *                                            > compute secret value for chain i
3054 *   7:     ADRS.setChainAddress(i)
3055 *   8:     tmp[i] <- chain(sk 0, w - 1, PK.seed, ADRS)
3056 *                                            > compute public value for chain i
3057 *   9: end for
3058 *  10: wotspkADRS <- ADRS     > copy address to create WOTS+ public key address
3059 *  ...
3060 *  13: pk <- Tlen(PK.seed, wotspkADRS, tmp)               > compress public key
3061 *  ...
3062 *
3063 * @param [in] key      SLH-DSA key.
3064 * @param [in] sk_seed  Private key seed.
3065 * @param [in] pk_seed  Public key seed.
3066 * @param [in] addr     Encoded HashAddress.
3067 * @param [in] sk_addr  Encoded WOTS PRF HashAddress.
3068 * @return  0 on success.
3069 * @return  MEMORY_E on dynamic memory allocation failure.
3070 */
3071static int slhdsakey_wots_pkgen_chain_x4_32(SlhDsaKey* key, const byte* sk_seed,
3072    const byte* pk_seed, byte* addr, byte* sk_addr)
3073{
3074    int ret = 0;
3075    int i;
3076    byte len = key->params->len;
3077    WC_DECLARE_VAR(sk, byte, (SLHDSA_MAX_MSG_SZ + 3) * 32, key->heap);
3078
3079    WC_ALLOC_VAR_EX(sk, byte, (SLHDSA_MAX_MSG_SZ + 3) * 32, key->heap,
3080        DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
3081    if (ret == 0) {
3082        for (i = 0; i < len - 3; i += 4) {
3083            ret = slhdsakey_hash_prf_x4(pk_seed, sk_seed, sk_addr, 32, (byte)i,
3084                sk + i * 32, key->heap);
3085            if (ret != 0) {
3086                break;
3087            }
3088            ret = slhdsakey_chain_x4_32(sk + i * 32, pk_seed, addr, (byte)i,
3089                key->heap);
3090            if (ret != 0) {
3091                break;
3092            }
3093        }
3094    }
3095    if (ret == 0) {
3096        ret = slhdsakey_hash_prf_x4(pk_seed, sk_seed, sk_addr, 32, (byte)i,
3097            sk + i * 32, key->heap);
3098        if (ret == 0) {
3099            ret = slhdsakey_chain_x4_32(sk + i * 32, pk_seed, addr, (byte)i,
3100                key->heap);
3101        }
3102    }
3103    if (ret == 0) {
3104        ret = HASH_T_UPDATE(key, sk, (word32)len * 32U);
3105    }
3106
3107    WC_FREE_VAR_EX(sk, key->heap, DYNAMIC_TYPE_SLHDSA);
3108    return ret;
3109}
3110#endif
3111
3112/* Generate WOTS+ public key - 4 consecutive addresses at a time.
3113 *
3114 * FIPS 205 Section 5.1. Algorithm 6.
3115 * wots_pkGen(SK.seed, PK.seed, ADRS)
3116 *  ...
3117 *   4: for i from 0 to len - 1 do
3118 *   5:     skADRS.setChainAddress(i)
3119 *   6:     sk <- PRF(PK.seed, SK.seed, skADRS)
3120 *                                            > compute secret value for chain i
3121 *   7:     ADRS.setChainAddress(i)
3122 *   8:     tmp[i] <- chain(sk 0, w - 1, PK.seed, ADRS)
3123 *                                            > compute public value for chain i
3124 *   9: end for
3125 *  10: wotspkADRS <- ADRS     > copy address to create WOTS+ public key address
3126 *  ...
3127 *  13: pk <- Tlen(PK.seed, wotspkADRS, tmp)               > compress public key
3128 *  ...
3129 *
3130 * @param [in] key      SLH-DSA key.
3131 * @param [in] sk_seed  Private key seed.
3132 * @param [in] pk_seed  Public key seed.
3133 * @param [in] adrs     HashAddress.
3134 * @param [in] sk_adrs  WOTS PRF HashAddress.
3135 * @return  0 on success.
3136 * @return  MEMORY_E on dynamic memory allocation failure.
3137 */
3138static int slhdsakey_wots_pkgen_chain_x4(SlhDsaKey* key, const byte* sk_seed,
3139    const byte* pk_seed, word32* adrs, word32* sk_adrs)
3140{
3141    int ret = 0;
3142    byte sk_addr[SLHDSA_HA_SZ];
3143    byte addr[SLHDSA_HA_SZ];
3144    byte n = key->params->n;
3145
3146    HA_SetHashAddress(sk_adrs, 0);
3147    HA_Encode(sk_adrs, sk_addr);
3148    HA_Encode(adrs, addr);
3149
3150#if !defined(WOLFSSL_SLHDSA_PARAM_NO_128)
3151    if (n == WC_SLHDSA_N_128) {
3152        ret = slhdsakey_wots_pkgen_chain_x4_16(key, sk_seed, pk_seed, addr,
3153            sk_addr);
3154    }
3155    else
3156#endif
3157#if !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
3158    if (n == 24) {
3159        ret = slhdsakey_wots_pkgen_chain_x4_24(key, sk_seed, pk_seed, addr,
3160            sk_addr);
3161    }
3162    else
3163#endif
3164#if !defined(WOLFSSL_SLHDSA_PARAM_NO_256)
3165    if (n == 32) {
3166        ret = slhdsakey_wots_pkgen_chain_x4_32(key, sk_seed, pk_seed, addr,
3167            sk_addr);
3168    }
3169    else
3170#endif
3171    if (ret == 0) {
3172        ret = NOT_COMPILED_IN;
3173    }
3174
3175    return ret;
3176}
3177#endif
3178
3179/* Generate WOTS+ public key.
3180 *
3181 * FIPS 205 Section 5.1. Algorithm 6.
3182 * wots_pkGen(SK.seed, PK.seed, ADRS)
3183 *  ...
3184 *   4: for i from 0 to len - 1 do
3185 *   5:     skADRS.setChainAddress(i)
3186 *   6:     sk <- PRF(PK.seed, SK.seed, skADRS)
3187 *                                            > compute secret value for chain i
3188 *   7:     ADRS.setChainAddress(i)
3189 *   8:     tmp[i] <- chain(sk 0, w - 1, PK.seed, ADRS)
3190 *                                            > compute public value for chain i
3191 *   9: end for
3192 *  10: wotspkADRS <- ADRS     > copy address to create WOTS+ public key address
3193 *  ...
3194 *  13: pk <- Tlen(PK.seed, wotspkADRS, tmp)               > compress public key
3195 *  ...
3196 *
3197 * @param [in] key      SLH-DSA key.
3198 * @param [in] sk_seed  Private key seed.
3199 * @param [in] pk_seed  Public key seed.
3200 * @param [in] adrs     HashAddress.
3201 * @param [in] sk_adrs  WOTS PRF HashAddress.
3202 * @return  0 on success.
3203 * @return  MEMORY_E on dynamic memory allocation failure.
3204 * @return  SHAKE-256 error return code on digest failure.
3205 */
3206static int slhdsakey_wots_pkgen_chain_c(SlhDsaKey* key, const byte* sk_seed,
3207    const byte* pk_seed, word32* adrs, word32* sk_adrs)
3208{
3209    int ret = 0;
3210    int i;
3211    byte n = key->params->n;
3212    byte len = key->params->len;
3213
3214#if !defined(WOLFSSL_WC_SLHDSA_SMALL_MEM)
3215    WC_DECLARE_VAR(sk, byte, (SLHDSA_MAX_MSG_SZ + 3) * SLHDSA_MAX_N, key->heap);
3216
3217    WC_ALLOC_VAR_EX(sk, byte, (SLHDSA_MAX_MSG_SZ + 3) * SLHDSA_MAX_N,
3218        key->heap, DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
3219    if (ret == 0) {
3220        /* Step 4. len consecutive addresses. */
3221        for (i = 0; i < len; i++) {
3222            /* Step 5. Set chain address for WOTS PRF. */
3223            HA_SetChainAddress(sk_adrs, i);
3224            /* Step 6. PRF hash seeds and chain address. */
3225            ret = HASH_PRF(key, pk_seed, sk_seed, sk_adrs, n,
3226                sk + i * n);
3227            if (ret != 0) {
3228                break;
3229            }
3230            /* Step 7. Set chain address for WOTS HASH. */
3231            HA_SetChainAddress(adrs, i);
3232            /* Step 8. Chain hashes for w-1 iterations. */
3233            ret = slhdsakey_chain(key, sk + i * n, 0, SLHDSA_WM1, pk_seed, adrs,
3234                sk + i * n);
3235            if (ret != 0) {
3236                break;
3237            }
3238        }
3239    }
3240    if (ret == 0) {
3241        /* Step 13: Compress public key. */
3242        ret = HASH_T_UPDATE(key, sk, (word32)len * n);
3243    }
3244    WC_FREE_VAR_EX(sk, key->heap, DYNAMIC_TYPE_SLHDSA);
3245#else
3246    /* Step 4. len consecutive addresses. */
3247    for (i = 0; i < len; i++) {
3248        byte sk[SLHDSA_MAX_N];
3249
3250        /* Step 5. Set chain address for WOTS PRF. */
3251        HA_SetChainAddress(sk_adrs, i);
3252        /* Step 6. PRF hash seeds and chain address. */
3253        ret = HASH_PRF(key, pk_seed, sk_seed, sk_adrs, n, sk);
3254        if (ret != 0) {
3255            break;
3256        }
3257        /* Step 7. Set chain address for WOTS HASH. */
3258        HA_SetChainAddress(adrs, i);
3259        /* Step 8. Chain hashes for w-1 iterations. */
3260        ret = slhdsakey_chain(key, sk, 0, SLHDSA_WM1, pk_seed, adrs, sk);
3261        if (ret != 0) {
3262            break;
3263        }
3264
3265        /* Step 13: Compress public key - for each tmp. */
3266        ret = HASH_T_UPDATE(key, sk, n);
3267        if (ret != 0) {
3268            break;
3269        }
3270    }
3271#endif
3272
3273    return ret;
3274}
3275
3276/* Generate WOTS+ public key.
3277 *
3278 * FIPS 205 Section 5.1. Algorithm 6.
3279 * wots_pkGen(SK.seed, PK.seed, ADRS)
3280 *   1: skADRS <- ADRS       > copy address to create key generation key address
3281 *   2: skADRS.setTypeAndClear(WOTS_PRF)
3282 *   3: skADRS.setKeyPairAddress(ADRS.getKeyPairAddress())
3283 *  ...
3284 *  11: wotspkADRS.setTypeAndClear(WOTS_PK)
3285 *  12: wotspkADRS.setKeyPairAddress(ADRS.getKeyPairAddress())
3286 *  13: pk <- Tlen(PK.seed, wotspkADRS, tmp)               > compress public key
3287 *  14: return pk
3288 *
3289 * @param [in] key      SLH-DSA key.
3290 * @param [in] sk_seed  Private key seed.
3291 * @param [in] pk_seed  Public key seed.
3292 * @param [in] adrs     HashAddress.
3293 * @param [in] sk_adrs  WOTS PRF HashAddress.
3294 * @return  0 on success.
3295 * @return  MEMORY_E on dynamic memory allocation failure.
3296 * @return  SHAKE-256 error return code on digest failure.
3297 */
3298static int slhdsakey_wots_pkgen(SlhDsaKey* key, const byte* sk_seed,
3299    const byte* pk_seed, word32* adrs, byte* node)
3300{
3301    int ret;
3302    byte n = key->params->n;
3303    int hash_t_started = 0;
3304
3305    {
3306        HashAddress wotspk_adrs;
3307
3308        /* Steps 11-12. Copy address and set to WOTS PK. */
3309        HA_Copy(wotspk_adrs, adrs);
3310        HA_SetTypeAndClearNotKPA(wotspk_adrs, HA_WOTS_PK);
3311        /* Step 13. Start hash with public key seed and address. */
3312        ret = HASH_T_START_ADDR(key, pk_seed, wotspk_adrs, n);
3313    }
3314    if (ret == 0) {
3315        HashAddress sk_adrs;
3316
3317        hash_t_started = 1;
3318
3319        /* Steps 1-2. Copy address and set to WOTS PRF. */
3320        HA_Copy(sk_adrs, adrs);
3321        HA_SetTypeAndClearNotKPA(sk_adrs, HA_WOTS_PRF);
3322        /* Steps 4-10,13: Generate hashes and update the public key hash. */
3323#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
3324        if (!SLHDSA_IS_SHA2(key->params->param) &&
3325                IS_INTEL_AVX2(cpuid_flags) &&
3326                (SAVE_VECTOR_REGISTERS2() == 0)) {
3327            ret = slhdsakey_wots_pkgen_chain_x4(key, sk_seed, pk_seed, adrs,
3328                sk_adrs);
3329            RESTORE_VECTOR_REGISTERS();
3330        }
3331        else
3332#endif
3333        {
3334            ret = slhdsakey_wots_pkgen_chain_c(key, sk_seed, pk_seed, adrs,
3335                sk_adrs);
3336        }
3337    }
3338    if (ret == 0) {
3339        /* Step 13: Output hash of compressed public key. */
3340        ret = HASH_T_FINAL(key, node, n);
3341    }
3342
3343    if (hash_t_started) {
3344        HASH_T_FREE(key);
3345    }
3346
3347    return ret;
3348}
3349
3350#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
3351#if !defined(WOLFSSL_SLHDSA_PARAM_NO_128)
3352/* Generate a WOTS+ signature, 32-byte hashed, on msg - iterating 4 hashes.
3353 *
3354 * FIPS 205. Section 5.2. Algorithm 7
3355 * wots_sign(M, SK.seed, PK.seed, ADRS)
3356 *  ...
3357 *  11: for i from 0 to len - 1 do
3358 *  12:     skADRS.setChainAddress(i)
3359 *  13:     sk <- PRF(PK.seed, SK.seed, skADRS)   > compute chain i secret value
3360 *  14:     ADRS.setChainAddress(i)
3361 *  15:     sig[i] <- chain(sk, 0, msg[i], PK.seed, ADRS)
3362 *                                             > compute chain i signature value
3363 *  16: end for
3364 *  17: return sig
3365 *
3366 * @param [in]  key      SLH-DSA key.
3367 * @param [in]  msg      Encoded message with checksum.
3368 * @param [in]  sk_seed  Private key seed.
3369 * @param [in]  pk_seed  Public key seed.
3370 * @param [in]  adrs     HashAddress.
3371 * @param [in]  sk_adrs  PRF HashAddress.
3372 * @param [out] sig      Signature - (2.n + 3) hashes of length n.
3373 * @return  0 on success.
3374 * @return  MEMORY_E on dynamic memory allocation failure.
3375 * @return  SHAKE-256 error return code on digest failure.
3376 */
3377static int slhdsakey_wots_sign_chain_x4_16(SlhDsaKey* key, const byte* msg,
3378    const byte* sk_seed, const byte* pk_seed, word32* adrs, byte* addr,
3379    byte* sk_addr, byte* sig)
3380{
3381    int ret = 0;
3382    int i;
3383    sword8 j;
3384    byte ii;
3385    byte idx[4] = {0};
3386    byte n = key->params->n;
3387    byte len = key->params->len;
3388    WC_DECLARE_VAR(sk, byte, 4 * 16, key->heap);
3389
3390    WC_ALLOC_VAR_EX(sk, byte, 4 * 16, key->heap, DYNAMIC_TYPE_SLHDSA,
3391        ret = MEMORY_E);
3392    if (ret == 0) {
3393        ii = 0;
3394        for (j = (sword8)SLHDSA_WM1; j >= 0; j--) {
3395            for (i = 0; i < len; i++) {
3396                if ((sword8)msg[i] == j) {
3397                    idx[ii++] = (byte)i;
3398                    if (ii == 4) {
3399                        ret = slhdsakey_hash_prf_idx_x4(pk_seed, sk_seed,
3400                            sk_addr, n, idx, sk, key->heap);
3401                        if (ret != 0) {
3402                            break;
3403                        }
3404                        ret = slhdsakey_chain_idx_16(key, sk, pk_seed, adrs,
3405                            addr, msg, idx, j, 4, sig);
3406                        if (ret != 0) {
3407                            break;
3408                        }
3409                        ii = 0;
3410                    }
3411                }
3412            }
3413        }
3414    }
3415
3416    if (ret == 0) {
3417        ret = slhdsakey_hash_prf_idx_x4(pk_seed, sk_seed, sk_addr, n, idx, sk,
3418            key->heap);
3419    }
3420    if (ret == 0) {
3421        j = (sword8)min(min(msg[idx[0]], msg[idx[1]]), msg[idx[2]]);
3422        ret = slhdsakey_chain_idx_16(key, sk, pk_seed, adrs, addr, msg, idx, j,
3423            3, sig);
3424    }
3425
3426    WC_FREE_VAR_EX(sk, key->heap, DYNAMIC_TYPE_SLHDSA);
3427    return ret;
3428}
3429#endif
3430
3431#if !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
3432/* Generate a WOTS+ signature, 32-byte hashed, on msg - iterating 4 hashes.
3433 *
3434 * FIPS 205. Section 5.2. Algorithm 7
3435 * wots_sign(M, SK.seed, PK.seed, ADRS)
3436 *  ...
3437 *  11: for i from 0 to len - 1 do
3438 *  12:     skADRS.setChainAddress(i)
3439 *  13:     sk <- PRF(PK.seed, SK.seed, skADRS)   > compute chain i secret value
3440 *  14:     ADRS.setChainAddress(i)
3441 *  15:     sig[i] <- chain(sk, 0, msg[i], PK.seed, ADRS)
3442 *                                             > compute chain i signature value
3443 *  16: end for
3444 *  17: return sig
3445 *
3446 * @param [in]  key      SLH-DSA key.
3447 * @param [in]  msg      Encoded message with checksum.
3448 * @param [in]  sk_seed  Private key seed.
3449 * @param [in]  pk_seed  Public key seed.
3450 * @param [in]  adrs     HashAddress.
3451 * @param [in]  sk_adrs  PRF HashAddress.
3452 * @param [out] sig      Signature - (2.n + 3) hashes of length n.
3453 * @return  0 on success.
3454 * @return  MEMORY_E on dynamic memory allocation failure.
3455 * @return  SHAKE-256 error return code on digest failure.
3456 */
3457static int slhdsakey_wots_sign_chain_x4_24(SlhDsaKey* key, const byte* msg,
3458    const byte* sk_seed, const byte* pk_seed, word32* adrs, byte* addr,
3459    byte* sk_addr, byte* sig)
3460{
3461    int ret = 0;
3462    int i;
3463    sword8 j;
3464    byte ii;
3465    byte idx[4] = {0};
3466    byte n = key->params->n;
3467    byte len = key->params->len;
3468    WC_DECLARE_VAR(sk, byte, 4 * 24, key->heap);
3469
3470    WC_ALLOC_VAR_EX(sk, byte, 4 * 24, key->heap, DYNAMIC_TYPE_SLHDSA,
3471        ret = MEMORY_E);
3472    if (ret == 0) {
3473        ii = 0;
3474        for (j = (sword8)SLHDSA_WM1; j >= 0; j--) {
3475            for (i = 0; i < len; i++) {
3476                if ((sword8)msg[i] == j) {
3477                    idx[ii++] = (byte)i;
3478                    if (ii == 4) {
3479                        ret = slhdsakey_hash_prf_idx_x4(pk_seed, sk_seed,
3480                            sk_addr, n, idx, sk, key->heap);
3481                        if (ret != 0) {
3482                            break;
3483                        }
3484                        ret = slhdsakey_chain_idx_24(key, sk, pk_seed, adrs,
3485                            addr, msg, idx, j, 4, sig);
3486                        if (ret != 0) {
3487                            break;
3488                        }
3489                        ii = 0;
3490                    }
3491                }
3492            }
3493        }
3494    }
3495
3496    if (ret == 0) {
3497        ret = slhdsakey_hash_prf_idx_x4(pk_seed, sk_seed, sk_addr, n, idx, sk,
3498            key->heap);
3499    }
3500    if (ret == 0) {
3501        j = (sword8)min(min(msg[idx[0]], msg[idx[1]]), msg[idx[2]]);
3502        ret = slhdsakey_chain_idx_24(key, sk, pk_seed, adrs, addr,
3503            msg, idx, j, 3, sig);
3504    }
3505
3506    WC_FREE_VAR_EX(sk, key->heap, DYNAMIC_TYPE_SLHDSA);
3507    return ret;
3508}
3509#endif
3510
3511#if !defined(WOLFSSL_SLHDSA_PARAM_NO_256)
3512/* Generate a WOTS+ signature, 32-byte hashed, on msg - iterating 4 hashes.
3513 *
3514 * FIPS 205. Section 5.2. Algorithm 7
3515 * wots_sign(M, SK.seed, PK.seed, ADRS)
3516 *  ...
3517 *  11: for i from 0 to len - 1 do
3518 *  12:     skADRS.setChainAddress(i)
3519 *  13:     sk <- PRF(PK.seed, SK.seed, skADRS)   > compute chain i secret value
3520 *  14:     ADRS.setChainAddress(i)
3521 *  15:     sig[i] <- chain(sk, 0, msg[i], PK.seed, ADRS)
3522 *                                             > compute chain i signature value
3523 *  16: end for
3524 *  17: return sig
3525 *
3526 * @param [in]  key      SLH-DSA key.
3527 * @param [in]  msg      Encoded message with checksum.
3528 * @param [in]  sk_seed  Private key seed.
3529 * @param [in]  pk_seed  Public key seed.
3530 * @param [in]  adrs     HashAddress.
3531 * @param [in]  sk_adrs  PRF HashAddress.
3532 * @param [out] sig      Signature - (2.n + 3) hashes of length n.
3533 * @return  0 on success.
3534 * @return  MEMORY_E on dynamic memory allocation failure.
3535 * @return  SHAKE-256 error return code on digest failure.
3536 */
3537static int slhdsakey_wots_sign_chain_x4_32(SlhDsaKey* key, const byte* msg,
3538    const byte* sk_seed, const byte* pk_seed, word32* adrs, byte* addr,
3539    byte* sk_addr, byte* sig)
3540{
3541    int ret = 0;
3542    int i;
3543    sword8 j;
3544    byte ii;
3545    byte idx[4] = {0};
3546    byte n = key->params->n;
3547    byte len = key->params->len;
3548    WC_DECLARE_VAR(sk, byte, 4 * 32, key->heap);
3549
3550    WC_ALLOC_VAR_EX(sk, byte, 4 * 32, key->heap, DYNAMIC_TYPE_SLHDSA,
3551        ret = MEMORY_E);
3552    if (ret == 0) {
3553        ii = 0;
3554        for (j = (sword8)SLHDSA_WM1; j >= 0; j--) {
3555            for (i = 0; i < len; i++) {
3556                if ((sword8)msg[i] == j) {
3557                    idx[ii++] = (byte)i;
3558                    if (ii == 4) {
3559                        ret = slhdsakey_hash_prf_idx_x4(pk_seed, sk_seed,
3560                            sk_addr, n, idx, sk, key->heap);
3561                        if (ret != 0) {
3562                            break;
3563                        }
3564                        ret = slhdsakey_chain_idx_32(key, sk, pk_seed, adrs,
3565                            addr, msg, idx, j, 4, sig);
3566                        if (ret != 0) {
3567                            break;
3568                        }
3569                        ii = 0;
3570                    }
3571                }
3572            }
3573        }
3574    }
3575
3576    if (ret == 0) {
3577        ret = slhdsakey_hash_prf_idx_x4(pk_seed, sk_seed, sk_addr, n, idx, sk,
3578            key->heap);
3579    }
3580    if (ret == 0) {
3581        j = (sword8)min(min(msg[idx[0]], msg[idx[1]]), msg[idx[2]]);
3582        ret = slhdsakey_chain_idx_32(key, sk, pk_seed, adrs, addr, msg, idx, j,
3583            3, sig);
3584    }
3585    if (ret == 0) {
3586        sig += len * n;
3587    }
3588
3589    WC_FREE_VAR_EX(sk, key->heap, DYNAMIC_TYPE_SLHDSA);
3590    return ret;
3591}
3592#endif
3593
3594/* Generate a WOTS+ signature on msg - iterating 4 hashes at a time.
3595 *
3596 * FIPS 205. Section 5.2. Algorithm 7
3597 * wots_sign(M, SK.seed, PK.seed, ADRS)
3598 *  ...
3599 *   8: skADRS <- ADRS       > copy address to create key generation key address
3600 *   9: skADRS.setTypeAndClear(WOTS_PRF)
3601 *  10: skADRS.setKeyPairAddress(ADRS.getKeyPairAddress())
3602 *  11: for i from 0 to len - 1 do
3603 *  12:     skADRS.setChainAddress(i)
3604 *  13:     sk <- PRF(PK.seed, SK.seed, skADRS)   > compute chain i secret value
3605 *  14:     ADRS.setChainAddress(i)
3606 *  15:     sig[i] <- chain(sk, 0, msg[i], PK.seed, ADRS)
3607 *                                             > compute chain i signature value
3608 *  16: end for
3609 *  17: return sig
3610 *
3611 * @param [in]  key      SLH-DSA key.
3612 * @param [in]  msg      Encoded message with checksum.
3613 * @param [in]  sk_seed  Private key seed.
3614 * @param [in]  pk_seed  Public key seed.
3615 * @param [in]  adrs     HashAddress.
3616 * @param [in]  sk_adrs  PRF HashAddress.
3617 * @param [out] sig      Signature - (2.n + 3) hashes of length n.
3618 * @return  0 on success.
3619 * @return  MEMORY_E on dynamic memory allocation failure.
3620 * @return  SHAKE-256 error return code on digest failure.
3621 */
3622static int slhdsakey_wots_sign_chain_x4(SlhDsaKey* key, const byte* msg,
3623    const byte* sk_seed, const byte* pk_seed, word32* adrs, word32* sk_adrs,
3624    byte* sig)
3625{
3626    int ret = 0;
3627    byte sk_addr[SLHDSA_HA_SZ];
3628    byte addr[SLHDSA_HA_SZ];
3629    byte n = key->params->n;
3630
3631    HA_SetHashAddress(sk_adrs, 0);
3632    HA_Encode(sk_adrs, sk_addr);
3633    HA_Encode(adrs, addr);
3634
3635#if !defined(WOLFSSL_SLHDSA_PARAM_NO_128)
3636    if (n == WC_SLHDSA_N_128) {
3637        ret = slhdsakey_wots_sign_chain_x4_16(key, msg, sk_seed, pk_seed, adrs,
3638            addr, sk_addr, sig);
3639    }
3640    else
3641#endif
3642#if !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
3643    if (n == 24) {
3644        ret = slhdsakey_wots_sign_chain_x4_24(key, msg, sk_seed, pk_seed, adrs,
3645            addr, sk_addr, sig);
3646    }
3647    else
3648#endif
3649#if !defined(WOLFSSL_SLHDSA_PARAM_NO_256)
3650    if (n == 32) {
3651        ret = slhdsakey_wots_sign_chain_x4_32(key, msg, sk_seed, pk_seed, adrs,
3652             addr, sk_addr, sig);
3653    }
3654    else
3655#endif
3656    if (ret == 0) {
3657        ret = NOT_COMPILED_IN;
3658    }
3659
3660    return ret;
3661}
3662#endif
3663
3664/* Generate a WOTS+ signature on an n-byte message.
3665 *
3666 * FIPS 205. Section 5.2. Algorithm 7
3667 * wots_sign(M, SK.seed, PK.seed, ADRS)
3668 *   1: csum <- 0
3669 *   2: msg <- base_2b(M , lgw , len1 )              > convert message to base w
3670 *   3: for i from 0 to len1 - 1 do
3671 *   4:     csum <- csum + w - 1 - msg[i]
3672 *   5: end for                                               > compute checksum
3673 *   6: csum <- csum << ((8 - ((len2.lgw) mod 8)) mod 8)
3674 *                                                > for lgw = 4, left shift by 4
3675 *   7: msg <- msg || base_2b(toByte(csum, upper(len2.lgw/8)), lgw , len2)
3676 *                                                           > convert to base w
3677 *   8: skADRS <- ADRS       > copy address to create key generation key address
3678 *   9: skADRS.setTypeAndClear(WOTS_PRF)
3679 *  10: skADRS.setKeyPairAddress(ADRS.getKeyPairAddress())
3680 *  11: for i from 0 to len - 1 do
3681 *  12:     skADRS.setChainAddress(i)
3682 *  13:     sk <- PRF(PK.seed, SK.seed, skADRS)   > compute chain i secret value
3683 *  14:     ADRS.setChainAddress(i)
3684 *  15:     sig[i] <- chain(sk, 0, msg[i], PK.seed, ADRS)
3685 *                                             > compute chain i signature value
3686 *  16: end for
3687 *  17: return sig
3688 *
3689 * @param [in]  key      SLH-DSA key.
3690 * @param [in]  m        n-bytes message.
3691 * @param [in]  sk_seed  Private key seed.
3692 * @param [in]  pk_seed  Public key seed.
3693 * @param [in]  adrs     HashAddress.
3694 * @param [out] sig      Signature - (2.n + 3) hashes of length n.
3695 * @return  0 on success.
3696 * @return  MEMORY_E on dynamic memory allocation failure.
3697 * @return  SHAKE-256 error return code on digest failure.
3698 */
3699static int slhdsakey_wots_sign(SlhDsaKey* key, const byte* m,
3700    const byte* sk_seed, const byte* pk_seed, word32* adrs, byte* sig)
3701{
3702    int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
3703    word16 csum;
3704    HashAddress sk_adrs;
3705    byte n = key->params->n;
3706    byte len = key->params->len;
3707    int i;
3708    byte msg[SLHDSA_MAX_MSG_SZ];
3709
3710    /* Step 1: Start csum at 0 */
3711    csum = 0;
3712    /* Step 3: For each byte in message. */
3713    for (i = 0; i < n * 2; i += 2) {
3714        /* Step 2: Append high order 4 bits to msg. */
3715        msg[i+0] = (byte)((m[i / 2] >> 4) & 0xf);
3716        /* Step 4: Calculate checksum with first lgw bits. */
3717        csum = (word16)(csum + SLHDSA_WM1 - msg[i + 0]);
3718        /* Step 2: Append low order 4 bits to msg. */
3719        msg[i+1] = (byte)( m[i / 2]       & 0xf);
3720        /* Step 4: Calculate checksum with next lgw bits. */
3721        csum = (word16)(csum + SLHDSA_WM1 - msg[i + 1]);
3722    }
3723    /* Steps 6-7: Encode bottom 12 bits of csum onto end of msg. */
3724    msg[i + 0] = (byte)((csum >> 8) & 0xf);
3725    msg[i + 1] = (byte)((csum >> 4) & 0xf);
3726    msg[i + 2] = (byte)( csum       & 0xf);
3727
3728    /* Steps 8-10: Copy address for WOTS PRF. */
3729    HA_Copy(sk_adrs, adrs);
3730    HA_SetTypeAndClearNotKPA(sk_adrs, HA_WOTS_PRF);
3731#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
3732    /* Steps 11-17: Generate signature from msg. */
3733    if (!SLHDSA_IS_SHA2(key->params->param) &&
3734            IS_INTEL_AVX2(cpuid_flags) &&
3735            (SAVE_VECTOR_REGISTERS2() == 0)) {
3736        ret = slhdsakey_wots_sign_chain_x4(key, msg, sk_seed, pk_seed, adrs,
3737            sk_adrs, sig);
3738        RESTORE_VECTOR_REGISTERS();
3739    }
3740    else
3741#endif
3742    {
3743        /* Step 11: For each value of msg. */
3744        for (i = 0; i < len; i++) {
3745            /* Step 12: Set chain address for WOTS PRF. */
3746            HA_SetChainAddress(sk_adrs, i);
3747            /* Step 13. PRF hash seeds and chain address. */
3748            ret = HASH_PRF(key, pk_seed, sk_seed, sk_adrs, n, sig);
3749            if (ret != 0) {
3750                break;
3751            }
3752            /* Step 14: Set chain address for WOTS HASH. */
3753            HA_SetChainAddress(adrs, i);
3754            /* Step 15. Chain hashes for msg value iterations. */
3755            ret = slhdsakey_chain(key, sig, 0, msg[i], pk_seed, adrs, sig);
3756            if (ret != 0) {
3757                break;
3758            }
3759            /* Step 15: Move to next hash in signature. */
3760            sig += n;
3761        }
3762    }
3763
3764    return ret;
3765}
3766#endif
3767
3768#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
3769#if !defined(WOLFSSL_SLHDSA_PARAM_NO_128)
3770/* Computes 4 chains simultaneously from starts to w-1 when n=16.
3771 *
3772 * FIPS 205. Section 5.3. Algorithm 8.
3773 * wots_pkFromSig(sig, M, PK.seed, ADRS)
3774 *  ...
3775 *  10:     tmp[i] <- chain(sig[i], msg[i], w - 1 - msg[i], PK.seed, ADRS)
3776 *  ...
3777 *
3778 * @param [in]  key      SLH-DSA key.
3779 * @param [in]  sig      Signature - (2.n + 3) hashes of length n.
3780 * @param [in]  pk_seed  Public key seed.
3781 * @param [in]  adrs     WOTS HASH HashAddress.
3782 * @param [in]  msg      Encoded message with checksum.
3783 * @param [in]  idx      Indices of chains.
3784 * @param [in]  j        Shortest chain length already calculated.
3785 * @param [in]  cnt      Number of chains to complete.
3786 * @param [out] nodes    Buffer to place completed chains.
3787 * @return  0 on success.
3788 * @return  MEMORY_E on dynamic memory allocation failure.
3789 */
3790static int slhdsakey_chain_idx_to_max_16(SlhDsaKey* key, const byte* sig,
3791     const byte* pk_seed, word32* adrs, const byte* msg, byte* idx, int j,
3792     int cnt, byte* nodes)
3793{
3794    int ret = 0;
3795    byte node[4 * 16];
3796    byte addr[SLHDSA_HA_SZ];
3797
3798    HA_SetChainAddress(adrs, idx[0]);
3799    HA_Encode(adrs, addr);
3800
3801    XMEMCPY(node + 0 * 16, sig + idx[0] * 16, 16);
3802    if ((msg[idx[0]] != j) && (msg[idx[0]] != msg[idx[1]])) {
3803        ret = slhdsakey_chain(key, node, msg[idx[0]],
3804            (byte)(msg[idx[1]] - msg[idx[0]]), pk_seed, adrs, node);
3805    }
3806    if (ret == 0) {
3807        XMEMCPY(node + 1 * 16, sig + idx[1] * 16, 16);
3808        XMEMSET(node + 2 * 16, 0, sizeof(node) - 2 * 16);
3809        if ((msg[idx[1]] != j) && (msg[idx[1]] != msg[idx[2]])) {
3810            ret = slhdsakey_chain_idx_x4_16(node, msg[idx[1]],
3811                (word32)(msg[idx[2]] - msg[idx[1]]), pk_seed, addr, idx,
3812                key->heap);
3813        }
3814    }
3815    if (ret == 0) {
3816        XMEMCPY(node + 2 * 16, sig + idx[2] * 16, 16);
3817        if ((cnt > 3) && (msg[idx[2]] != j)) {
3818            ret = slhdsakey_chain_idx_x4_16(node, msg[idx[2]],
3819                (word32)(j - msg[idx[2]]), pk_seed, addr, idx, key->heap);
3820        }
3821    }
3822    if (ret == 0) {
3823        if (cnt > 3) {
3824            XMEMCPY(node + 3 * 16, sig + idx[3] * 16, 16);
3825        }
3826        if (j != SLHDSA_WM1) {
3827            ret = slhdsakey_chain_idx_x4_16(node, (word32)j,
3828                (word32)(SLHDSA_WM1 - j), pk_seed, addr, idx, key->heap);
3829        }
3830    }
3831    if (ret == 0) {
3832        XMEMCPY(nodes + idx[0] * 16, node + 0 * 16, 16);
3833        XMEMCPY(nodes + idx[1] * 16, node + 1 * 16, 16);
3834        XMEMCPY(nodes + idx[2] * 16, node + 2 * 16, 16);
3835        if (cnt > 3) {
3836            XMEMCPY(nodes + idx[3] * 16, node + 3 * 16, 16);
3837        }
3838    }
3839
3840    return ret;
3841}
3842#endif
3843
3844#if !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
3845/* Computes 4 chains simultaneously from starts to w-1 when n=24.
3846 *
3847 * FIPS 205. Section 5.3. Algorithm 8.
3848 * wots_pkFromSig(sig, M, PK.seed, ADRS)
3849 *  ...
3850 *  10:     tmp[i] <- chain(sig[i], msg[i], w - 1 - msg[i], PK.seed, ADRS)
3851 *  ...
3852 *
3853 * @param [in]  key      SLH-DSA key.
3854 * @param [in]  sig      Signature - (2.n + 3) hashes of length n.
3855 * @param [in]  pk_seed  Public key seed.
3856 * @param [in]  adrs     WOTS HASH HashAddress.
3857 * @param [in]  msg      Encoded message with checksum.
3858 * @param [in]  idx      Indices of chains.
3859 * @param [in]  j        Shortest chain length already calculated.
3860 * @param [in]  cnt      Number of chains to complete.
3861 * @param [out] nodes    Buffer to place completed chains.
3862 * @return  0 on success.
3863 * @return  MEMORY_E on dynamic memory allocation failure.
3864 */
3865static int slhdsakey_chain_idx_to_max_24(SlhDsaKey* key, const byte* sig,
3866     const byte* pk_seed, word32* adrs, const byte* msg, byte* idx, int j,
3867     int cnt, byte* nodes)
3868{
3869    int ret = 0;
3870    byte node[4 * 24];
3871    byte addr[SLHDSA_HA_SZ];
3872
3873    HA_SetChainAddress(adrs, idx[0]);
3874    HA_Encode(adrs, addr);
3875
3876    XMEMCPY(node + 0 * 24, sig + idx[0] * 24, 24);
3877    if ((msg[idx[0]] != j) && (msg[idx[0]] != msg[idx[1]])) {
3878        ret = slhdsakey_chain(key, node, msg[idx[0]],
3879            (byte)(msg[idx[1]] - msg[idx[0]]), pk_seed, adrs, node);
3880    }
3881    if (ret == 0) {
3882        XMEMCPY(node + 1 * 24, sig + idx[1] * 24, 24);
3883        XMEMSET(node + 2 * 24, 0, sizeof(node) - 2 * 24);
3884        if ((msg[idx[1]] != j) && (msg[idx[1]] != msg[idx[2]])) {
3885            ret = slhdsakey_chain_idx_x4_24(node, msg[idx[1]],
3886                (word32)(msg[idx[2]] - msg[idx[1]]), pk_seed, addr, idx,
3887                key->heap);
3888        }
3889    }
3890    if (ret == 0) {
3891        XMEMCPY(node + 2 * 24, sig + idx[2] * 24, 24);
3892        if ((cnt > 3) && (msg[idx[2]] != j)) {
3893            ret = slhdsakey_chain_idx_x4_24(node, msg[idx[2]],
3894                (word32)(j - msg[idx[2]]), pk_seed, addr, idx, key->heap);
3895        }
3896    }
3897    if (ret == 0) {
3898        if (cnt > 3) {
3899            XMEMCPY(node + 3 * 24, sig + idx[3] * 24, 24);
3900        }
3901        if (j != SLHDSA_WM1) {
3902            ret = slhdsakey_chain_idx_x4_24(node, (word32)j,
3903                (word32)(SLHDSA_WM1 - j), pk_seed, addr, idx, key->heap);
3904        }
3905    }
3906    if (ret == 0) {
3907        XMEMCPY(nodes + idx[0] * 24, node + 0 * 24, 24);
3908        XMEMCPY(nodes + idx[1] * 24, node + 1 * 24, 24);
3909        XMEMCPY(nodes + idx[2] * 24, node + 2 * 24, 24);
3910        if (cnt > 3) {
3911            XMEMCPY(nodes + idx[3] * 24, node + 3 * 24, 24);
3912        }
3913    }
3914
3915    return ret;
3916}
3917#endif
3918
3919#if !defined(WOLFSSL_SLHDSA_PARAM_NO_256)
3920/* Computes 4 chains simultaneously from starts to w-1 when n=32.
3921 *
3922 * FIPS 205. Section 5.3. Algorithm 8.
3923 * wots_pkFromSig(sig, M, PK.seed, ADRS)
3924 *  ...
3925 *  10:     tmp[i] <- chain(sig[i], msg[i], w - 1 - msg[i], PK.seed, ADRS)
3926 *  ...
3927 *
3928 * @param [in]  key      SLH-DSA key.
3929 * @param [in]  sig      Signature - (2.n + 3) hashes of length n.
3930 * @param [in]  pk_seed  Public key seed.
3931 * @param [in]  adrs     WOTS HASH HashAddress.
3932 * @param [in]  msg      Encoded message with checksum.
3933 * @param [in]  idx      Indices of chains.
3934 * @param [in]  j        Shortest chain length already calculated.
3935 * parama [in]  cnt      Number of chains to complete.
3936 * @param [out] nodes    Buffer to place completed chains.
3937 * @return  0 on success.
3938 * @return  MEMORY_E on dynamic memory allocation failure.
3939 */
3940static int slhdsakey_chain_idx_to_max_32(SlhDsaKey* key, const byte* sig,
3941     const byte* pk_seed, word32* adrs, const byte* msg, byte* idx, int j,
3942     int cnt, byte* nodes)
3943{
3944    int ret = 0;
3945    byte node[4 * 32];
3946    byte addr[SLHDSA_HA_SZ];
3947
3948    HA_SetChainAddress(adrs, idx[0]);
3949    HA_Encode(adrs, addr);
3950
3951    XMEMCPY(node + 0 * 32, sig + idx[0] * 32, 32);
3952    if ((msg[idx[0]] != j) && (msg[idx[0]] != msg[idx[1]])) {
3953        ret = slhdsakey_chain(key, node, msg[idx[0]],
3954            (byte)(msg[idx[1]] - msg[idx[0]]), pk_seed, adrs, node);
3955    }
3956    if (ret == 0) {
3957        XMEMCPY(node + 1 * 32, sig + idx[1] * 32, 32);
3958        XMEMSET(node + 2 * 32, 0, sizeof(node) - 2 * 32);
3959        if ((msg[idx[1]] != j) && (msg[idx[1]] != msg[idx[2]])) {
3960            ret = slhdsakey_chain_idx_x4_32(node, msg[idx[1]],
3961                (word32)(msg[idx[2]] - msg[idx[1]]), pk_seed, addr, idx,
3962                key->heap);
3963        }
3964    }
3965    if (ret == 0) {
3966        XMEMCPY(node + 2 * 32, sig + idx[2] * 32, 32);
3967        if ((cnt > 3) && (msg[idx[2]] != j)) {
3968            ret = slhdsakey_chain_idx_x4_32(node, msg[idx[2]],
3969                (word32)(j - msg[idx[2]]), pk_seed, addr, idx, key->heap);
3970        }
3971    }
3972    if (ret == 0) {
3973        if (cnt > 3) {
3974            XMEMCPY(node + 3 * 32, sig + idx[3] * 32, 32);
3975        }
3976        if (j != SLHDSA_WM1) {
3977            ret = slhdsakey_chain_idx_x4_32(node, (word32)j,
3978                (word32)(SLHDSA_WM1 - j), pk_seed, addr, idx, key->heap);
3979        }
3980    }
3981    if (ret == 0) {
3982        XMEMCPY(nodes + idx[0] * 32, node + 0 * 32, 32);
3983        XMEMCPY(nodes + idx[1] * 32, node + 1 * 32, 32);
3984        XMEMCPY(nodes + idx[2] * 32, node + 2 * 32, 32);
3985        if (cnt > 3) {
3986            XMEMCPY(nodes + idx[3] * 32, node + 3 * 32, 32);
3987        }
3988    }
3989
3990    return ret;
3991}
3992#endif
3993#endif
3994
3995#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
3996/* Computes a WOTS+ public key from a message and its signature.
3997 *
3998 * Computes four iteration hashes simultaneously.
3999 *
4000 * FIPS 205. Section 5.3. Algorithm 8.
4001 * wots_pkFromSig(sig, M, PK.seed, ADRS)
4002 *  ...
4003 *   8: for i from 0 to len - 1 do
4004 *   9:     ADRS.setChainAddress(i)
4005 *  ...
4006 *  11: end for
4007 *  12: wotspkADRS <- ADRS     > copy address to create WOTS+ public key address
4008 *  13: wotspkADRS.setTypeAndClear(WOTS_PK)
4009 *  14: wotspkADRS.setKeyPairAddress(ADRS.getKeyPairAddress())
4010 *  15: pksig <- Tlen (PK.seed, wotspkADRS, tmp)
4011 *  16: return pksig
4012 *
4013 * @param [in]  key      SLH-DSA key.
4014 * @param [in]  sig      Signature - (2.n + 3) hashes of length n.
4015 * @param [in]  msg      Encoded message with checksum.
4016 * @param [in]  pk_seed  Public key seed.
4017 * @param [in]  adrs     WOTS HASH HashAddress.
4018 * @param [out] pk_sig   Root node - public key signature.
4019 * @return  0 on success.
4020 * @return  MEMORY_E on dynamic memory allocation failure.
4021 */
4022static int slhdsakey_wots_pk_from_sig_x4(SlhDsaKey* key, const byte* sig,
4023    const byte* msg, const byte* pk_seed, word32* adrs, byte* pk_sig)
4024{
4025    int ret = 0;
4026    HashAddress wotspk_adrs;
4027    byte n = key->params->n;
4028    byte len = key->params->len;
4029    WC_DECLARE_VAR(nodes, byte, SLHDSA_MAX_MSG_SZ * SLHDSA_MAX_N, key->heap);
4030    int hash_t_started = 0;
4031
4032    WC_ALLOC_VAR_EX(nodes, byte, SLHDSA_MAX_MSG_SZ * SLHDSA_MAX_N, key->heap,
4033        DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
4034#if !defined(WOLFSSL_SLHDSA_PARAM_NO_128)
4035    if ((ret == 0) && (n == WC_SLHDSA_N_128)) {
4036        int i;
4037        sword8 j;
4038        byte ii = 0;
4039        byte idx[4] = {0};
4040        for (j = 0; j <= (sword8)SLHDSA_WM1; j++) {
4041            for (i = 0; i < len; i++) {
4042                if ((sword8)msg[i] == j) {
4043                    idx[ii++] = (byte)i;
4044                    if (ii == 4) {
4045                        ret = slhdsakey_chain_idx_to_max_16(key, sig,
4046                            pk_seed, adrs, msg, idx, j, 4, nodes);
4047                        if (ret != 0) {
4048                            break;
4049                        }
4050                        ii = 0;
4051                    }
4052                }
4053            }
4054        }
4055
4056        if (ret == 0) {
4057            j = (sword8)max(max(msg[idx[0]], msg[idx[1]]), msg[idx[2]]);
4058            ret = slhdsakey_chain_idx_to_max_16(key, sig, pk_seed, adrs, msg,
4059                idx, j, 3, nodes);
4060        }
4061    }
4062    else
4063#endif
4064#if !defined(WOLFSSL_SLHDSA_PARAM_NO_192)
4065    if ((ret == 0) && (n == 24)) {
4066        int i;
4067        sword8 j;
4068        byte ii = 0;
4069        byte idx[4] = {0};
4070        for (j = 0; j <= (sword8)SLHDSA_WM1; j++) {
4071            for (i = 0; i < len; i++) {
4072                if ((sword8)msg[i] == j) {
4073                    idx[ii++] = (byte)i;
4074                    if (ii == 4) {
4075                        ret = slhdsakey_chain_idx_to_max_24(key, sig,
4076                            pk_seed, adrs, msg, idx, j, 4, nodes);
4077                        if (ret != 0) {
4078                            break;
4079                        }
4080                        ii = 0;
4081                    }
4082                }
4083            }
4084        }
4085
4086        if (ret == 0) {
4087            j = (sword8)max(max(msg[idx[0]], msg[idx[1]]), msg[idx[2]]);
4088            ret = slhdsakey_chain_idx_to_max_24(key, sig, pk_seed, adrs, msg,
4089                idx, j, 3, nodes);
4090        }
4091    }
4092    else
4093#endif
4094#if !defined(WOLFSSL_SLHDSA_PARAM_NO_256)
4095    if ((ret == 0) && (n == 32)) {
4096        int i;
4097        sword8 j;
4098        byte ii = 0;
4099        byte idx[4] = {0};
4100        for (j = 0; j <= (sword8)SLHDSA_WM1; j++) {
4101            for (i = 0; i < len; i++) {
4102                if ((sword8)msg[i] == j) {
4103                    idx[ii++] = (byte)i;
4104                    if (ii == 4) {
4105                        ret = slhdsakey_chain_idx_to_max_32(key, sig,
4106                            pk_seed, adrs, msg, idx, j, 4, nodes);
4107                        if (ret != 0) {
4108                            break;
4109                        }
4110                        ii = 0;
4111                    }
4112                }
4113            }
4114        }
4115
4116        if (ret == 0) {
4117            j = (sword8)max(max(msg[idx[0]], msg[idx[1]]), msg[idx[2]]);
4118            ret = slhdsakey_chain_idx_to_max_32(key, sig, pk_seed, adrs, msg,
4119                idx, j, 3, nodes);
4120        }
4121    }
4122    else
4123#endif
4124    {
4125        (void)msg;
4126        (void)key;
4127        if (ret == 0) {
4128            ret = NOT_COMPILED_IN;
4129        }
4130    }
4131
4132    if (ret == 0) {
4133        HA_Copy(wotspk_adrs, adrs);
4134        HA_SetTypeAndClearNotKPA(wotspk_adrs, HA_WOTS_PK);
4135        ret = HASH_T_START_ADDR(key, pk_seed, wotspk_adrs, n);
4136    }
4137    if (ret == 0) {
4138        hash_t_started = 1;
4139        ret = HASH_T_UPDATE(key, nodes, (word32)len * n);
4140        sig += len * n;
4141    }
4142    if (ret == 0) {
4143        ret = HASH_T_FINAL(key, pk_sig, n);
4144    }
4145    if (hash_t_started) {
4146        HASH_T_FREE(key);
4147    }
4148
4149    WC_FREE_VAR_EX(nodes, key->heap, DYNAMIC_TYPE_SLHDSA);
4150    return ret;
4151}
4152#endif
4153
4154#if !defined(WOLFSSL_WC_SLHDSA_SMALL_MEM)
4155/* Computes a WOTS+ public key from a message and its signature.
4156 *
4157 * FIPS 205. Section 5.3. Algorithm 8.
4158 * wots_pkFromSig(sig, M, PK.seed, ADRS)
4159 *  ...
4160 *   8: for i from 0 to len - 1 do
4161 *   9:     ADRS.setChainAddress(i)
4162 *  10:     tmp[i] <- chain(sig[i], msg[i], w - 1 - msg[i], PK.seed, ADRS)
4163 *  11: end for
4164 *  12: wotspkADRS <- ADRS     > copy address to create WOTS+ public key address
4165 *  13: wotspkADRS.setTypeAndClear(WOTS_PK)
4166 *  14: wotspkADRS.setKeyPairAddress(ADRS.getKeyPairAddress())
4167 *  15: pksig <- Tlen(PK.seed, wotspkADRS, tmp)
4168 *  16: return pksig
4169 *
4170 * @param [in]  key      SLH-DSA key.
4171 * @param [in]  sig      Signature - (2.n + 3) hashes of length n.
4172 * @param [in]  msg      Encoded message with checksum.
4173 * @param [in]  pk_seed  Public key seed.
4174 * @param [in]  adrs     WOTS HASH HashAddress.
4175 * @param [out] pk_sig   Root node - public key signature.
4176 * @return  0 on success.
4177 * @return  MEMORY_E on dynamic memory allocation failure.
4178 * @return  SHAKE-256 error return code on digest failure.
4179 */
4180static int slhdsakey_wots_pk_from_sig_c(SlhDsaKey* key, const byte* sig,
4181    const byte* msg, const byte* pk_seed, word32* adrs, byte* pk_sig)
4182{
4183    int ret = 0;
4184    int i;
4185    byte n = key->params->n;
4186    byte len = key->params->len;
4187    HashAddress wotspk_adrs;
4188    WC_DECLARE_VAR(nodes, byte, SLHDSA_MAX_MSG_SZ * SLHDSA_MAX_N, key->heap);
4189    int hash_t_started = 0;
4190
4191    WC_ALLOC_VAR_EX(nodes, byte, SLHDSA_MAX_MSG_SZ * SLHDSA_MAX_N, key->heap,
4192        DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
4193    if (ret == 0) {
4194        /* Step 8: For each value in msg. */
4195        for (i = 0; i < len; i++) {
4196            /* Step 9: Set chain address for WOTS HASH. */
4197            HA_SetChainAddress(adrs, i);
4198            /* Step 10: Chain the hash from the msg value to w-1. */
4199            ret = slhdsakey_chain(key, sig, msg[i], (byte)(SLHDSA_WM1 - msg[i]),
4200                pk_seed, adrs, nodes + i * n);
4201            if (ret != 0) {
4202                break;
4203            }
4204            /* Move on to next signature hash. */
4205            sig += n;
4206        }
4207    }
4208    if (ret == 0) {
4209        /* Step 12-14: Copy the address for WOTS PK. */
4210        HA_Copy(wotspk_adrs, adrs);
4211        HA_SetTypeAndClearNotKPA(wotspk_adrs, HA_WOTS_PK);
4212        /* Step 15: Hash the public key seed and WOTS PK address ... */
4213        ret = HASH_T_START_ADDR(key, pk_seed, wotspk_adrs, n);
4214    }
4215    if (ret == 0) {
4216        hash_t_started = 1;
4217        /* Step 15: Update with the nodes ... */
4218        ret = HASH_T_UPDATE(key, nodes, (word32)len * n);
4219    }
4220    if (ret == 0) {
4221        /* Step 15: Generate root node - public key signature. */
4222        ret = HASH_T_FINAL(key, pk_sig, n);
4223    }
4224    if (hash_t_started) {
4225        HASH_T_FREE(key);
4226    }
4227
4228    WC_FREE_VAR_EX(nodes, key->heap, DYNAMIC_TYPE_SLHDSA);
4229    return ret;
4230}
4231#else
4232/* Computes a WOTS+ public key from a message and its signature.
4233 *
4234 * FIPS 205. Section 5.3. Algorithm 8.
4235 * wots_pkFromSig(sig, M, PK.seed, ADRS)
4236 *  ...
4237 *   8: for i from 0 to len - 1 do
4238 *   9:     ADRS.setChainAddress(i)
4239 *  10:     tmp[i] <- chain(sig[i], msg[i], w - 1 - msg[i], PK.seed, ADRS)
4240 *  11: end for
4241 *  12: wotspkADRS <- ADRS     > copy address to create WOTS+ public key address
4242 *  13: wotspkADRS.setTypeAndClear(WOTS_PK)
4243 *  14: wotspkADRS.setKeyPairAddress(ADRS.getKeyPairAddress())
4244 *  15: pksig <- Tlen (PK.seed, wotspkADRS, tmp)
4245 *  16: return pksig
4246 *
4247 * @param [in]  key      SLH-DSA key.
4248 * @param [in]  sig      Signature - (2.n + 3) hashes of length n.
4249 * @param [in]  msg      Encoded message with checksum.
4250 * @param [in]  pk_seed  Public key seed.
4251 * @param [in]  adrs     WOTS HASH HashAddress.
4252 * @param [out] pk_sig   Root node - public key signature.
4253 * @return  0 on success.
4254 * @return  MEMORY_E on dynamic memory allocation failure.
4255 * @return  SHAKE-256 error return code on digest failure.
4256 */
4257static int slhdsakey_wots_pk_from_sig_c(SlhDsaKey* key, const byte* sig,
4258    const byte* msg, const byte* pk_seed, word32* adrs, byte* pk_sig)
4259{
4260    int ret;
4261    int i;
4262    byte n = key->params->n;
4263    byte len = key->params->len;
4264    HashAddress wotspk_adrs;
4265    byte* node = pk_sig;
4266    int hash_t_started = 0;
4267
4268    /* Step 12-14: Copy the address for WOTS PK. */
4269    HA_Copy(wotspk_adrs, adrs);
4270    HA_SetTypeAndClearNotKPA(wotspk_adrs, HA_WOTS_PK);
4271    /* Step 15: Hash the public key seed and WOTS PK address ... */
4272    ret = HASH_T_START_ADDR(key, pk_seed, wotspk_adrs, n);
4273    if (ret == 0) {
4274        hash_t_started = 1;
4275        /* Step 8: For each value in msg. */
4276        for (i = 0; i < len; i++) {
4277            /* Step 9: Set chain address for WOTS HASH. */
4278            HA_SetChainAddress(adrs, i);
4279            /* Step 10: Chain the hash from the msg value to w-1. */
4280            ret = slhdsakey_chain(key, sig, msg[i], (byte)(SLHDSA_WM1 - msg[i]),
4281                pk_seed, adrs, node);
4282            if (ret != 0) {
4283                break;
4284            }
4285            /* Step 15: Update with node ... */
4286            ret = HASH_T_UPDATE(key, node, n);
4287            if (ret != 0) {
4288                break;
4289            }
4290            /* Move on to next signature hash. */
4291            sig += n;
4292        }
4293    }
4294    if (ret == 0) {
4295        /* Step 15: Generate root node - public key signature. */
4296        ret = HASH_T_FINAL(key, pk_sig, n);
4297    }
4298    if (hash_t_started) {
4299        HASH_T_FREE(key);
4300    }
4301
4302    return ret;
4303}
4304#endif
4305
4306/* Computes a WOTS+ public key from a message and its signature.
4307 *
4308 * FIPS 205. Section 5.3. Algorithm 8.
4309 * wots_pkFromSig(sig, M, PK.seed, ADRS)
4310 *   1: csum <- 0
4311 *   2: msg <- base_2b(M , lgw , len1 )              > convert message to base w
4312 *   3: for i from 0 to len1 - 1 do
4313 *   4:     csum <- csum + w - 1 - msg[i]
4314 *   5: end for                                               > compute checksum
4315 *   6: csum <- csum << ((8 - ((len2.lgw) mod 8)) mod 8)
4316 *                                                > for lgw = 4, left shift by 4
4317 *   7: msg <- msg || base_2b(toByte(csum, upper(len2.lgw/8)), lgw , len2)
4318 *  ...
4319 *
4320 * @param [in]  key      SLH-DSA key.
4321 * @param [in]  sig      Signature - (2.n + 3) hashes of length n.
4322 * @param [in]  m        Message.
4323 * @param [in]  pk_seed  Public key seed.
4324 * @param [in]  adrs     WOTS HASH HashAddress.
4325 * @param [out] pk_sig   Root node - public key signature.
4326 * @return  0 on success.
4327 * @return  MEMORY_E on dynamic memory allocation failure.
4328 * @return  SHAKE-256 error return code on digest failure.
4329 */
4330static int slhdsakey_wots_pk_from_sig(SlhDsaKey* key, const byte* sig,
4331    const byte* m, const byte* pk_seed, word32* adrs, byte* pk_sig)
4332{
4333    int ret;
4334    word16 csum;
4335    byte n = key->params->n;
4336    int i;
4337    byte msg[SLHDSA_MAX_MSG_SZ];
4338
4339    /* Step 1: Start csum at 0 */
4340    csum = 0;
4341    /* Step 3: For each byte in message. */
4342    for (i = 0; i < n * 2; i += 2) {
4343        /* Step 2: Append high order 4 bits to msg. */
4344        msg[i+0] = (byte)((m[i / 2] >> 4) & 0xf);
4345        /* Step 4: Calculate checksum with first lgw bits. */
4346        csum = (word16)(csum + SLHDSA_WM1 - msg[i + 0]);
4347        /* Step 2: Append low order 4 bits to msg. */
4348        msg[i+1] = (byte)( m[i / 2]       & 0xf);
4349        /* Step 4: Calculate checksum with next lgw bits. */
4350        csum = (word16)(csum + SLHDSA_WM1 - msg[i + 1]);
4351    }
4352    /* Steps 6-7: Encode bottom 12 bits of csum onto end of msg. */
4353    msg[i + 0] = (byte)((csum >> 8) & 0xf);
4354    msg[i + 1] = (byte)((csum >> 4) & 0xf);
4355    msg[i + 2] = (byte)( csum       & 0xf);
4356
4357    /* Steps 8-16. */
4358#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
4359    if (!SLHDSA_IS_SHA2(key->params->param) &&
4360            IS_INTEL_AVX2(cpuid_flags) &&
4361            (SAVE_VECTOR_REGISTERS2() == 0)) {
4362        ret = slhdsakey_wots_pk_from_sig_x4(key, sig, msg, pk_seed, adrs,
4363            pk_sig);
4364        RESTORE_VECTOR_REGISTERS();
4365    }
4366    else
4367#endif
4368    {
4369        ret = slhdsakey_wots_pk_from_sig_c(key, sig, msg, pk_seed, adrs,
4370            pk_sig);
4371    }
4372
4373    return ret;
4374}
4375
4376/******************************************************************************
4377 * XMSS
4378 ******************************************************************************/
4379
4380#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
4381#ifndef WOLFSSL_WC_SLHDSA_RECURSIVE
4382/* Compute the root node of Merkle subtree of WOTS+ public keys.
4383 *
4384 * Algorithm 9 xmss_node(SK.seed, i, z, PK.seed, ADRS)
4385 *   1: if z = 0 then
4386 *   2:     ADRS.setTypeAndClear(WOTS_HASH)
4387 *   3:     ADRS.setKeyPairAddress(i)
4388 *   4:     node <- wots_pkGen(SK.seed, PK.seed, ADRS)
4389 *   5: else
4390 *   6:     lnode <- xmss_node(SK.seed, 2i, z - 1, PK.seed, ADRS)
4391 *   7:     rnode <- xmss_node(SK.seed, 2i + 1, z - 1, PK.seed, ADRS)
4392 *   8:     ADRS.setTypeAndClear(TREE)
4393 *   9:     ADRS.setTreeHeight(z)
4394 *  10:     ADRS.setTreeIndex(i)
4395 *  11:     node <- H(PK.seed, ADRS, lnode || rnode)
4396 *  12: end if
4397 *  13: return node
4398 *
4399 * @param [in]       key      SLH-DSA key.
4400 * @param [in]       sk_seed  Private key seed.
4401 * @param [in]       i        Node index.
4402 * @param [in]       z        Node height.
4403 * @param [in]       pk_seed  Public key seed.
4404 * @param [in, out]  adrs     HashAddress - WOTS HASH.
4405 * @param [out]      node     Root node.
4406 * @return  0 on success.
4407 * @return  MEMORY_E on dynamic memory allocation failure.
4408 * @return  SHAKE-256 error return code on digest failure.
4409 */
4410static int slhdsakey_xmss_node(SlhDsaKey* key, const byte* sk_seed, int i,
4411    int z, const byte* pk_seed, word32* adrs, byte* node)
4412{
4413    int ret = 0;
4414
4415    /* Step 1: Are we at the bottom of the subtree. */
4416    if (z == 0) {
4417        /* Step 2: Copy the address for WOTS HASH. */
4418        HA_SetTypeAndClearNotKPA(adrs, HA_WOTS_HASH);
4419        /* Step 3: Set key pair address. */
4420        HA_SetKeyPairAddress(adrs, i);
4421        /* Step 4: Generate WOTS+ public key. */
4422        ret = slhdsakey_wots_pkgen(key, sk_seed, pk_seed, adrs, node);
4423    }
4424    else {
4425        WC_DECLARE_VAR(nodes, byte, (SLHDSA_MAX_H_M + 2) * SLHDSA_MAX_N,
4426            key->heap);
4427        word32 j;
4428        word32 k;
4429        word32 m = (word32)1U << z;
4430        byte n = key->params->n;
4431
4432        WC_ALLOC_VAR_EX(nodes, byte, (SLHDSA_MAX_H_M + 2) * SLHDSA_MAX_N,
4433            key->heap, DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
4434        if (ret == 0) {
4435            /* For each node at bottom of tree. */
4436            for (j = 0; j < m; j++) {
4437                /* Step 2: Copy the address for WOTS HASH. */
4438                HA_SetTypeAndClearNotKPA(adrs, HA_WOTS_HASH);
4439                /* Step 3: Set key pair address. */
4440                HA_SetKeyPairAddress(adrs, m * (word32)i + j);
4441                /* Step 4: Generate WOTS+ public key. */
4442                ret = slhdsakey_wots_pkgen(key, sk_seed, pk_seed, adrs,
4443                    nodes + ((word32)z - 1U + (j & 1U)) * n);
4444                if (ret != 0) {
4445                    break;
4446                }
4447
4448                /* For intermediate nodes. */
4449                for (k = (word32)z - 1U; k > 0; k--) {
4450                    if (((j >> ((word32)z - 1U - k)) & 1U) == 1U) {
4451                        /* Step 6 and 7 have been done.  */
4452                        /* Steps 8-10: Step type, height and index for TREE. */
4453                        HA_SetTypeAndClear(adrs, HA_TREE);
4454                        HA_SetTreeHeight(adrs, (word32)z - k);
4455                        HA_SetTreeIndex(adrs,
4456                                        (m * (word32)i + j) >> ((word32)z - k));
4457                        /* Step 11: Calculate node from two below. */
4458                        ret = HASH_H(key, pk_seed, adrs, nodes + k * n, n,
4459                                nodes +
4460                                  (k - 1U + ((j >> ((word32)z - k)) & 1U)) * n);
4461                        if (ret != 0) {
4462                            break;
4463                        }
4464                    }
4465                    else {
4466                        break;
4467                    }
4468                }
4469                if (ret != 0) {
4470                    break;
4471                }
4472            }
4473            if (ret == 0) {
4474                /* Root node into output. */
4475                /* Steps 8-10: Step type, height and index for TREE. */
4476                HA_SetTypeAndClear(adrs, HA_TREE);
4477                HA_SetTreeHeight(adrs, z);
4478                HA_SetTreeIndex(adrs, i);
4479                /* Step 11: Calculate node from two below. */
4480                ret = HASH_H(key, pk_seed, adrs, nodes, n, node);
4481            }
4482        }
4483
4484        WC_FREE_VAR_EX(nodes, key->heap, DYNAMIC_TYPE_SLHDSA);
4485    }
4486
4487    return ret;
4488}
4489#else
4490/* Compute the root node of Merkle subtree of WOTS+ public keys.
4491 *
4492 * FIPS 205. Section 6.1. Algorithm 9.
4493 * xmss_node(SK.seed, i, z, PK.seed, ADRS)
4494 *   1: if z = 0 then
4495 *   2:     ADRS.setTypeAndClear(WOTS_HASH)
4496 *   3:     ADRS.setKeyPairAddress(i)
4497 *   4:     node <- wots_pkGen(SK.seed, PK.seed, ADRS)
4498 *   5: else
4499 *   6:     lnode <- xmss_node(SK.seed, 2i, z - 1, PK.seed, ADRS)
4500 *   7:     rnode <- xmss_node(SK.seed, 2i + 1, z - 1, PK.seed, ADRS)
4501 *   8:     ADRS.setTypeAndClear(TREE)
4502 *   9:     ADRS.setTreeHeight(z)
4503 *  10:     ADRS.setTreeIndex(i)
4504 *  11:     node <- H(PK.seed, ADRS, lnode || rnode)
4505 *  12: end if
4506 *  13: return node
4507 *
4508 * @param [in]       key      SLH-DSA key.
4509 * @param [in]       sk_seed  Private key seed.
4510 * @param [in]       i        Node index.
4511 * @param [in]       z        Node height.
4512 * @param [in]       pk_seed  Public key seed.
4513 * @param [in, out]  adrs     HashAddress - WOTS HASH.
4514 * @param [out]      node     Root node.
4515 * @return  0 on success.
4516 * @return  MEMORY_E on dynamic memory allocation failure.
4517 * @return  SHAKE-256 error return code on digest failure.
4518 */
4519static int slhdsakey_xmss_node(SlhDsaKey* key, const byte* sk_seed, int i,
4520    int z, const byte* pk_seed, word32* adrs, byte* node)
4521{
4522    int ret;
4523    byte nodes[2 * SLHDSA_MAX_N];
4524
4525    /* Step 1: Are we at the bottom of the subtree. */
4526    if (z == 0) {
4527        /* Step 2: Copy the address for WOTS HASH. */
4528        HA_SetTypeAndClearNotKPA(adrs, HA_WOTS_HASH);
4529        /* Step 3: Set key pair address. */
4530        HA_SetKeyPairAddress(adrs, i);
4531        /* Step 4: Generate WOTS+ public key. */
4532        ret = slhdsakey_wots_pkgen(key, sk_seed, pk_seed, adrs, node);
4533    }
4534    else {
4535        byte n = key->params->n;
4536
4537        /* Step 6: Calculate left node recursively. */
4538        ret = slhdsakey_xmss_node(key, sk_seed, 2 * i, z - 1, pk_seed, adrs,
4539            nodes);
4540        if (ret == 0) {
4541            /* Step 7: Calculate right node recursively. */
4542            ret = slhdsakey_xmss_node(key, sk_seed, 2 * i + 1, z - 1, pk_seed,
4543                adrs, nodes + n);
4544        }
4545        if (ret == 0) {
4546            /* Steps 8-10: Step type, height and index for TREE. */
4547            HA_SetTypeAndClear(adrs, HA_TREE);
4548            HA_SetTreeHeight(adrs, z);
4549            HA_SetTreeIndex(adrs, i);
4550            /* Step 11: Calculate node from two below. */
4551            ret = HASH_H(key, pk_seed, adrs, nodes, n, node);
4552        }
4553    }
4554
4555    return ret;
4556}
4557#endif
4558
4559/* Generate XMSS signature.
4560 *
4561 * FIPS 205. Section 6.2. Algorithm 10.
4562 * xmss_sign(M SK.seed, idx PK.seed, ADRS)
4563 *   1: for j from 0 to h' - 1 do                    > build authentication path
4564 *   2:     k <- lower(idx/2^j) XOR 1
4565 *   3:     AUTH[j] <- xmss_node(SK.seed, k, j, PK.seed, ADRS)
4566 *   4: end for
4567 *   5: ADRS.setTypeAndClear(WOTS_HASH)
4568 *   6: ADRS.setKeyPairAddress(idx)
4569 *   7: sig <- wots_sign(M , SK.seed, PK.seed, ADRS)
4570 *   8: SIGXMSS <- sig || AUTH
4571 *   9: return SIGXMSS
4572 *
4573 * @param [in]  key       SLH-DSA key.
4574 * @param [in]  m         n-byte message.
4575 * @param [in]  sk_seed   Private key seed.
4576 * @param [in]  idx       Key pair address of WOTS hash.
4577 * @param [in]  pk_seed   Public key seed.
4578 * @param [in]  adrs      HashAddress.
4579 * @param [out] sig_xmss  XMSS signature.
4580 *                        len n-byte nodes and h' authentication nodes.
4581 * @return  0 on success.
4582 * @return  MEMORY_E on dynamic memory allocation failure.
4583 * @return  SHAKE-256 error return code on digest failure.
4584 */
4585static int slhdsakey_xmss_sign(SlhDsaKey* key, const byte* m,
4586    const byte* sk_seed, word32 idx, const byte* pk_seed, word32* adrs,
4587    byte* sig_xmss)
4588{
4589    int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
4590    byte n = key->params->n;
4591    byte len = key->params->len;
4592    byte h_m = key->params->h_m;
4593    /* Step 8: Place authentication nodes after WOTS+ signature. */
4594    byte* auth = sig_xmss + (len * n);
4595    word32 i = idx;
4596    int j;
4597
4598    /* Step 1: For each height of XMSS tree. */
4599    for (j = 0; j < h_m; j++) {
4600        /* Step 2: Calculate index of other node. */
4601        word32 k = i ^ 1;
4602        /* Step 3: Calculate authentication node. */
4603        ret = slhdsakey_xmss_node(key, sk_seed, (int)k, j, pk_seed, adrs,
4604            auth);
4605        if (ret != 0) {
4606            break;
4607        }
4608        /* Step 3: Move to next authentication node. */
4609        auth += n;
4610        /* Step 2: Update index. */
4611        i >>= 1;
4612    }
4613
4614    if (ret == 0) {
4615        /* Step 5: Set address of WOTS HASH. */
4616        HA_SetTypeAndClearNotKPA(adrs, HA_WOTS_HASH);
4617        /* Step 6: Set key pair address into address. */
4618        HA_SetKeyPairAddress(adrs, idx);
4619        /* Step 7: WOTS+ sign message. */
4620        ret = slhdsakey_wots_sign(key, m, sk_seed, pk_seed, adrs, sig_xmss);
4621    }
4622
4623    return ret;
4624}
4625#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
4626
4627/* Compute XMSS public key from XMSS signature.
4628 *
4629 * FIPS 205. Section 6.3. Algorithm 11.
4630 * xmss_pkFromSig(idx, SIGXMSS, M PK.seed, ADRS)
4631 *   1: ADRS.setTypeAndClear(WOTS_HASH)        > compute WOTS+ pk from WOTS+ sig
4632 *   2: ADRS.setKeyPairAddress(idx)
4633 *   3: sig <- SIGXMSS.getWOTSSig()                      > SIGXMSS [0 : len . n]
4634 *   4: AUTH <- SIGXMSS.getXMSSAUTH()       > SIGXMSS [len . n : (len + h') . n]
4635 *   5: node[0] <- wots_pkFromSig(sig, M, PK.seed, ADRS)
4636 *   6: ADRS.setTypeAndClear(TREE)         > compute root from WOTS+ pk and AUTH
4637 *   7: ADRS.setTreeIndex(idx
4638 *   8: for k from 0 to h' - 1 do
4639 *   9:     ADRS.setTreeHeight(k + 1)
4640 *  10:     if lower(idx/2^k) is even then
4641 *  11:         ADRS.setTreeIndex(ADRS.getTreeIndex()/2)
4642 *  12:         node[1] <- H(PK.seed, ADRS, node[0] || AUTH[k])
4643 *  13:     else
4644 *  14:         ADRS.setTreeIndex((ADRS.getTreeIndex() - 1)/2)
4645 *  15:         node[1] <- H(PK.seed, ADRS, AUTH[k] || node[0])
4646 *  16:     end if
4647 *  17:     node[0] <- node[1]
4648 *  18: end for
4649 *  19: return node[0]
4650 *
4651 * @param [in]  key       SLH-DSA key.
4652 * @param [in]  idx       Key pair address of WOTS hash.
4653 * @param [in]  sig_xmss  XMSS signature.
4654 *                        len n-byte nodes and h' authentication nodes.
4655 * @param [in]  m         n-byte message.
4656 * @param [in]  pk_seed   Public key seed.
4657 * @param [in]  adrs      HashAddress.
4658 * @param [out] node      XMSS public key.
4659 * @return  0 on success.
4660 * @return  MEMORY_E on dynamic memory allocation failure.
4661 * @return  SHAKE-256 error return code on digest failure.
4662 */
4663static int slhdsakey_xmss_pk_from_sig(SlhDsaKey* key, word32 idx,
4664    const byte* sig_xmss, const byte* m, const byte* pk_seed, word32* adrs,
4665    byte* node)
4666{
4667    int ret;
4668    byte n = key->params->n;
4669    byte h_m = key->params->h_m;
4670    byte len = key->params->len;
4671    /* Step  3: Set pointer to first signature node. */
4672    const byte* sig = sig_xmss;
4673    /* Step 4: Set pointer to first authentication node. */
4674    const byte* auth = sig_xmss + (len * n);
4675    int k;
4676
4677    /* Step 1: Set address type to WOTS HASH. */
4678    HA_SetTypeAndClear(adrs, HA_WOTS_HASH);
4679    /* Step 2: Set key pair address. */
4680    HA_SetKeyPairAddress(adrs, idx);
4681    /* Step 5: Compute WOTS+ public key from signature. */
4682    ret = slhdsakey_wots_pk_from_sig(key, sig, m, pk_seed, adrs, node);
4683    if (ret == 0) {
4684        /* Step 6: Set address type to TREE. */
4685        HA_SetTypeAndClear(adrs, HA_TREE);
4686        /* Step 2: Set key pair address. */
4687        HA_SetTreeIndex(adrs, idx);
4688        /* Step 8: For each height of the XMSS tree. */
4689        for (k = 0; k < h_m; k++) {
4690            /* Calculate which side the current and authentication nodes are. */
4691            byte side = idx & 1;
4692            /* Update tree index. */
4693            idx >>= 1;
4694
4695            /* Step 9: Set tree height. */
4696            HA_SetTreeHeight(adrs, k + 1);
4697            /* Steps 11 and 14: Set tree index. */
4698            HA_SetTreeIndex(adrs, idx);
4699            /* Step 10: Check which order to put nodes. */
4700            if (side == 0) {
4701                /* Steps 12,17: Calculate node with sig node on right. */
4702                ret = HASH_H_2(key, pk_seed, adrs, node, auth, n, node);
4703            }
4704            else {
4705                /* Steps 15,17: Calculate node with sig node on left. */
4706                ret = HASH_H_2(key, pk_seed, adrs, auth, node, n, node);
4707            }
4708            if (ret != 0) {
4709                break;
4710            }
4711            /* Next authentication node. */
4712            auth += n;
4713        }
4714    }
4715
4716    return ret;
4717}
4718
4719/******************************************************************************
4720 * HT - HyperTree
4721 ******************************************************************************/
4722
4723#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
4724/* Generate hypertree signature.
4725 *
4726 * FIPS 205. Section 7.1. Algorithm 12.
4727 * ht_sign(M SK.seed, PK.seed, idxtree, idxleaf)
4728 *   1: ADRS <- toByte(0, 32)
4729 *   2: ADRS.setTreeAddress(idxtree)
4730 *   3: SIGtmp <- xmss_sign(x, SK.seed, idxleaf, PK.seed, ADRS)
4731 *   4: SIGHT <- SIGtmp
4732 *   5: root <- xmss_pkFromSig(idxleaf, SIGtmp, M, PK.seed, ADRS)
4733 *   6: for j from 1 to d - 1 do
4734 *   7:     idxleaf <- idxleaf mod 2^h'   > h' least significant bits of idxtree
4735 *   8:     idxtree <- idxtree >> h'
4736 *                               > remove least significant h' bits from idxtree
4737 *   9:     ADRS.setLayerAddress(j)
4738 *  10:    ADRS.setTreeAddress(idxtree)
4739 *  11:    SIGtmp <- xmss_sign(root, SK.seed, idxleaf, PK.seed, ADRS)
4740 *  12:    SIGHT <- SIGHT || SIGtmp
4741 *  13:    if j < d - 1 then
4742 *  14:        root <- xmss_pkFromSig(idxleaf, SIGtmp, root, PK.seed, ADRS)
4743 *  15:    end if
4744 *  16: end for
4745 *  17: return SIGHT
4746 *
4747 * @param [in]  key       SLH-DSA key.
4748 * @param [in]  pk_fors   FORS public key.
4749 * @param [in]  sk_seed   Private key seed.
4750 * @param [in]  pk_seed   Public key seed.
4751 * @param [in]  idx_tree  Tree address.
4752 * @param [in]  idx_leaf  Key pair address.
4753 * @param [out] sig_ht    Hypertree signature - d x n-byte nodes.
4754 * @return  0 on success.
4755 * @return  MEMORY_E on dynamic memory allocation failure.
4756 * @return  SHAKE-256 error return code on digest failure.
4757 */
4758static int slhdsakey_ht_sign(SlhDsaKey* key, const byte* pk_fors,
4759    const byte* sk_seed, const byte* pk_seed, word32* idx_tree, word32 idx_leaf,
4760    byte* sig_ht)
4761{
4762    int ret;
4763    HashAddress adrs;
4764    byte root[SLHDSA_MAX_N];
4765    byte n = key->params->n;
4766    byte h_m = key->params->h_m;
4767    byte len = key->params->len;
4768    byte d = key->params->d;
4769    int j;
4770    word32 mask = ((word32)1U << h_m) - 1U;
4771
4772    /* Step 1: Set address to all zeros. */
4773    HA_Init(adrs);
4774    /* Step 2: Set tree address. */
4775    HA_SetTreeAddress(adrs, idx_tree);
4776    /* Step 3: Compute XMSS signature. */
4777    ret = slhdsakey_xmss_sign(key, pk_fors, sk_seed, idx_leaf, pk_seed, adrs,
4778        sig_ht);
4779    if (ret == 0) {
4780        /* Step 5: Compute root/public key from signature. */
4781        ret = slhdsakey_xmss_pk_from_sig(key, idx_leaf, sig_ht, pk_fors,
4782            pk_seed, adrs, root);
4783        /* Step 4: Step hypertree signature over XMSS signature. */
4784        sig_ht += (h_m + len) * n;
4785    }
4786    if (ret == 0) {
4787        /* Step 6: For remaining depths. */
4788        for (j = 1; j < d; j++) {
4789            /* Step 7: Get bottom h' bits for index into tree. */
4790            idx_leaf = INDEX_TREE_MASK(idx_tree, mask);
4791            /* Step 8: Update tree index to exclude this subtree. */
4792            INDEX_TREE_SHIFT_DOWN(idx_tree, h_m);
4793            /* Step 9: Set layer address. */
4794            HA_SetLayerAddress(adrs, j);
4795            /* Step 10: Set tree index. */
4796            HA_SetTreeAddress(adrs, idx_tree);
4797            /* Step 11: Compute XMSS signature. */
4798            ret = slhdsakey_xmss_sign(key, root, sk_seed, idx_leaf, pk_seed,
4799                adrs, sig_ht);
4800            if (ret != 0) {
4801                break;
4802            }
4803            /* Step 13: Check if we need to calculate next root. */
4804            if (j < d) {
4805                /* Step 14: Compute root/public key from signature. */
4806                ret = slhdsakey_xmss_pk_from_sig(key, idx_leaf, sig_ht, root,
4807                    pk_seed, adrs, root);
4808                if (ret != 0) {
4809                    break;
4810                }
4811            }
4812            /* Step 12: Step hypertree signature over XMSS signature. */
4813            sig_ht += (h_m + len) * n;
4814        }
4815    }
4816
4817    return ret;
4818}
4819#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
4820
4821/* Verify hypertree signature.
4822 *
4823 * FIPS 205. Section 7.2 Algorithm 13.
4824 * ht_verify(M SIGHT, PK.seed, idxtree, idxleaf, PK.root)
4825 *   1: ADRS <- toByte(0, 32)
4826 *   2: ADRS.setTreeAddress(idxtree)
4827 *   3: SIGtmp <- SIGHT.getXMSSSignature(0)          > SIGHT[0 : (h' + len) . n]
4828 *   4: node <- xmss_pkFromSig(idxleaf, SIGtmp, M, PK.seed, ADRS)
4829 *   5: for j from 1 to d - 1 do
4830 *   6:     idxleaf <- idxtree mod 2^h'   > h' least significant bits of idxtree
4831 *   7:     idxtree <- idxtree >> h'
4832 *                               > remove least significant h' bits from idxtree
4833 *   8:     ADRS.setLayerAddress(j)
4834 *   9:     ADRS.setTreeAddress(idxtree)
4835 *  10:     SIGtmp <- SIGHT .getXMSSSignature(j)
4836 *                            > SIGHT[h . (h' + len) . n : (j + 1)(h' + len . n]
4837 *  11:     node <- xmss_pkFromSig(idxleaf, SIGtmp, node, PK.seed, ADRS)
4838 *  12: end for
4839 *  13: if node = PK.root then
4840 *  14:     return true
4841 *  15: else
4842 *  16:     return false
4843 *  17: end if
4844 *
4845 * @param [in] key       SLH-DSA key.
4846 * @param [in] m         Message to verify.
4847 * @param [in] sig_ht    Hypertree signature.
4848 * @param [in] pk_seed   Public key seed.
4849 * @param [in] idx_tree  Tree address.
4850 * @param [in] idx_leaf  Key pair address.
4851 * @param [in] pk_root   Public key root node.
4852 * @return  0 on success.
4853 * @return  SIG_VERIFY_E when calculated node doesn't match public key node.
4854 * @return  MEMORY_E on dynamic memory allocation failure.
4855 * @return  SHAKE-256 error return code on digest failure.
4856 */
4857static int slhdsakey_ht_verify(SlhDsaKey* key, const byte* m,
4858    const byte* sig_ht, const byte* pk_seed, word32* idx_tree, word32 idx_leaf,
4859    const byte* pk_root)
4860{
4861    int ret;
4862    HashAddress adrs;
4863    byte node[SLHDSA_MAX_N];
4864    byte n = key->params->n;
4865    byte h_m = key->params->h_m;
4866    byte len = key->params->len;
4867    byte d = key->params->d;
4868    int j;
4869    /* For Step 6. */
4870    word32 mask = ((word32)1U << h_m) - 1U;
4871
4872    /* Step 1: Set address to all zeros. */
4873    HA_Init(adrs);
4874    /* Step 2: Set tree address. */
4875    HA_SetTreeAddress(adrs, idx_tree);
4876    /* Step 4: Get public key node from XMSS signature. */
4877    ret = slhdsakey_xmss_pk_from_sig(key, idx_leaf, sig_ht, m, pk_seed, adrs,
4878        node);
4879    /* Step 3: Move over XMSS signature. */
4880    sig_ht += (h_m + len) * n;
4881
4882    if (ret == 0) {
4883        /* Step 5: For remaining depths. */
4884        for (j = 1; j < d; j++) {
4885            /* Step 6: Get bottom h' bits for index into tree. */
4886            idx_leaf = INDEX_TREE_MASK(idx_tree, mask);
4887            /* Step 7: Update tree index to exclude this subtree. */
4888            INDEX_TREE_SHIFT_DOWN(idx_tree, h_m);
4889            /* Step 8: Set layer address. */
4890            HA_SetLayerAddress(adrs, j);
4891            /* Step 9: Set tree index. */
4892            HA_SetTreeAddress(adrs, idx_tree);
4893            /* Step 11: Get public key node from XMSS signature. */
4894            ret = slhdsakey_xmss_pk_from_sig(key, idx_leaf, sig_ht, node,
4895                pk_seed, adrs, node);
4896            if (ret != 0) {
4897                break;
4898            }
4899            /* Step 10: Move over XMSS signature. */
4900            sig_ht += (h_m + len) * n;
4901        }
4902    }
4903    /* Step 13: Compare computed node with public key root. */
4904    if ((ret == 0) && (XMEMCMP(node, pk_root, n) != 0)) {
4905        /* Step 16: Return signature verification failed. */
4906        ret = SIG_VERIFY_E;
4907    }
4908
4909    return ret;
4910}
4911
4912/******************************************************************************
4913 * FORS
4914 ******************************************************************************/
4915
4916#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
4917/* Generate FORS private-key value.
4918 *
4919 * FIPS 205. Section 8.1. Algorithm 14
4920 * fors_skGen(SK.seed, PK.seed, ADRS, idx)
4921 *   1: skADRS <- ADRS           > copy address to create key generation address
4922 *   2: skADRS.setTypeAndClear(FORS_PRF)
4923 *   3: skADRS.setKeyPairAddress(ADRS.getKeyPairAddress())
4924 *   4: skADRS.setTreeIndex(idx)
4925 *   5: return PRF(PK.seed, SK.seed, skADRS)
4926 *
4927 * @param [in]  key      SLH-DSA key.
4928 * @param [in]  sk_seed  Private key seed.
4929 * @param [in]  pk_seed  Public key seed.
4930 * @param [in]  adrs     HashAddress.
4931 * @param [in]  idx      Private key index.
4932 * @param [out] node     FORS private-key value.
4933 * @return  0 on success.
4934 * @return  MEMORY_E on dynamic memory allocation failure.
4935 * @return  SHAKE-256 error return code on digest failure.
4936 */
4937static int slhdsakey_fors_sk_gen(SlhDsaKey* key, const byte* sk_seed,
4938    const byte* pk_seed, word32* adrs, word32 idx, byte* node)
4939{
4940    HashAddress sk_adrs;
4941
4942    /* Step 1: Copy address to FORS PRF. */
4943    HA_Copy(sk_adrs, adrs);
4944    /* Steps 2-3: Set type and keep key pair address. */
4945    HA_SetTypeAndClearNotKPA(sk_adrs, HA_FORS_PRF);
4946    /* Step 4: Set tree index. */
4947    HA_SetTreeIndex(sk_adrs, idx);
4948    /* Step 5: Hash seeds and address. */
4949    return HASH_PRF(key, pk_seed, sk_seed, sk_adrs, key->params->n,
4950        node);
4951}
4952
4953#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
4954/* PRF hash 4 simultaneously.
4955 *
4956 * Each hash varies by the tree index with the first value in sequence passed
4957 * in.
4958 *
4959 * FIPS 205. Section 4.1.
4960 *   PRF(PK.seed, SK.seed, ADRS) (Bn x Bn x B32 -> Bn) is a PRF that is used to
4961 *   generate the secret values in WOTS+ and FORS private keys.
4962 * FIPS 205. Section 11.1.
4963 *   PRF(PK.seed, SK.seed, ADRS) = SHAKE256(PK.seed || ADRS || SK.seed, 8n)
4964 *
4965 * @param [in]  pk_seed  Public key seed.
4966 * @param [in]  sk_seed  Private key seed.
4967 * @param [in]  addr     Encoded HashAddress.
4968 * @param [in]  n        Number of bytes in hash output.
4969 * @param [in]  ti       Tree index start value.
4970 * @param [out] node     Buffer to hold hash output.
4971 * @param [in]  heap     Dynamic memory allocation hint.
4972 * @return  0 on success.
4973 * @return  MEMORY_E on dynamic memory allocation failure.
4974 */
4975static int slhdsakey_hash_prf_ti_x4(const byte* pk_seed, const byte* sk_seed,
4976    byte* addr, byte n, word32 ti, byte* node, void* heap)
4977{
4978    int ret = 0;
4979    word32 o = 0;
4980    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
4981
4982    (void)heap;
4983
4984    WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
4985        ret = MEMORY_E);
4986    if (ret == 0) {
4987        o = slhdsakey_shake256_set_seed_ha_hash_x4(state, pk_seed, addr,
4988            sk_seed, n);
4989        SHAKE256_SET_TREE_INDEX(state, o, ti);
4990        ret = SAVE_VECTOR_REGISTERS2();
4991        if (ret == 0) {
4992            sha3_blocksx4_avx2(state);
4993            RESTORE_VECTOR_REGISTERS();
4994            slhdsakey_shake256_get_hash_x4(state, node, n);
4995        }
4996
4997        WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
4998    }
4999
5000    return ret;
5001}
5002
5003/* F hash 4 simultaneously.
5004 *
5005 * Each hash varies by the tree index with the first value in sequence passed
5006 * in.
5007 *
5008 * FIPS 205. Section 4.1.
5009 *   F(PK.seed, ADRS, M1) (Bn x B32 x Bn -> Bn) is a hash function that takes an
5010 *   n-byte message as input and produces an n-byte output.
5011 * FIPS 205. Section 11.1.
5012 *   F(PK.seed, ADRS, M1) = SHAKE256(PK.seed || ADRS || M1 , 8n)
5013 *
5014 * @param [in]      pk_seed  Public key seed.
5015 * @param [in]      addr     Encoded HashAddress.
5016 * @param [in, out] node     On in, n-byte messages. On out, n-byte outputs.
5017 * @param [in]      n        Number of bytes in hash output.
5018 * @param [in]      ti       Tree index start value.
5019 * @param [in]      heap     Dynamic memory allocation hint.
5020 * @return  0 on success.
5021 * @return  MEMORY_E on dynamic memory allocation failure.
5022 */
5023static int slhdsakey_hash_f_ti_x4(const byte* pk_seed, byte* addr, byte* node,
5024    byte n, word32 ti, void* heap)
5025{
5026    int ret = 0;
5027    int i;
5028    word32 o = 0;
5029    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
5030
5031    (void)heap;
5032
5033    WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
5034        ret = MEMORY_E);
5035    if (ret == 0) {
5036        o = slhdsakey_shake256_set_seed_ha_x4(state, pk_seed, addr, n);
5037        SHAKE256_SET_TREE_INDEX(state, o, ti);
5038        for (i = 0; i < n / 8; i++) {
5039            state[o + 0] = ((word64*)(node + 0 * n))[i];
5040            state[o + 1] = ((word64*)(node + 1 * n))[i];
5041            state[o + 2] = ((word64*)(node + 2 * n))[i];
5042            state[o + 3] = ((word64*)(node + 3 * n))[i];
5043            o += 4;
5044        }
5045        SHAKE256_SET_END_X4(state, o);
5046        ret = SAVE_VECTOR_REGISTERS2();
5047        if (ret == 0) {
5048            sha3_blocksx4_avx2(state);
5049            RESTORE_VECTOR_REGISTERS();
5050            slhdsakey_shake256_get_hash_x4(state, node, n);
5051        }
5052
5053        WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
5054    }
5055
5056    return ret;
5057}
5058
5059/* H hash 4 simultaneously.
5060 *
5061 * Each hash varies by the tree index with the first value in sequence passed
5062 * in.
5063 *
5064 * FIPS 205. Section 4.1.
5065 *   H(PK.seed, ADRS, M2) (Bn x B32 x B2n -> Bn) is a special case of Tl that
5066 *   takes a 2n-byte message as input.
5067 * FIPS 205. Section 11.1.
5068 *   H(PK.seed, ADRS, M2) = SHAKE256(PK.seed || ADRS || M2, 8n)
5069 *
5070 * @param [in]  pk_seed  Public key seed.
5071 * @param [in]  addr     Encoded HashAddress.
5072 * @param [in]  m        2n-byte message.
5073 * @param [in]  n        Number of bytes in hash output.
5074 * @param [in]  ti       Tree index start value.
5075 * @param [out] hash     Buffer to hold hash output.
5076 * @param [in]  heap     Dynamic memory allocation hint.
5077 * @return  0 on success.
5078 * @return  MEMORY_E on dynamic memory allocation failure.
5079 */
5080static int slhdsakey_hash_h_ti_x4(const byte* pk_seed, byte* addr,
5081    const byte* m, byte n, word32 ti, byte* hash, void* heap)
5082{
5083    int ret = 0;
5084    int i;
5085    word32 o = 0;
5086    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
5087
5088    (void)heap;
5089
5090    WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
5091        ret = MEMORY_E);
5092    if (ret == 0) {
5093        o = slhdsakey_shake256_set_seed_ha_x4(state, pk_seed, addr, n);
5094        SHAKE256_SET_TREE_INDEX(state, o, ti);
5095        for (i = 0; i < 2 * n / 8; i++) {
5096            state[o + 0] = ((const word64*)(m + 0 * n))[i];
5097            state[o + 1] = ((const word64*)(m + 2 * n))[i];
5098            state[o + 2] = ((const word64*)(m + 4 * n))[i];
5099            state[o + 3] = ((const word64*)(m + 6 * n))[i];
5100            o += 4;
5101        }
5102        SHAKE256_SET_END_X4(state, o);
5103        ret = SAVE_VECTOR_REGISTERS2();
5104        if (ret == 0) {
5105            sha3_blocksx4_avx2(state);
5106            RESTORE_VECTOR_REGISTERS();
5107            slhdsakey_shake256_get_hash_x4(state, hash, n);
5108        }
5109
5110        WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
5111    }
5112
5113    return ret;
5114}
5115
5116/* A ranges from 6-14. */
5117#if SLHDSA_MAX_A < 9
5118    /* Maximum node depth that determines the number of nodes stored and
5119     * hashed in one call. */
5120    #define SLHDSA_MAX_FORS_NODE_DEPTH      (SLHDSA_MAX_A-1)
5121#else
5122    /* Maximum node depth that determines the number of nodes stored and
5123     * hashed in one call. */
5124    #define SLHDSA_MAX_FORS_NODE_DEPTH      8
5125#endif
5126/* Maximum node depth that determines the number of nodes stored and
5127 * hashed in one call with an 8 depth tree below. */
5128#define SLHDSA_MAX_FORS_NODE_TOP_DEPTH  \
5129    (SLHDSA_MAX_A - SLHDSA_MAX_FORS_NODE_DEPTH)
5130
5131/* Compute the root of a zero height Merkle subtree of FORS public values.
5132 *
5133 * Performs 4 hashes at the same time where possible.
5134 *
5135 * FIPS 205. Section 8.2. Algorithm 15.
5136 * fors_node(SK.seed, i, z, PK.seed, ADRS)
5137 *   1: if z = 0 then
5138 *   2:     sk <- fors_skGen(SK.seed, PK.seed, ADRS, i)
5139 *   3:     ADRS.setTreeHeight(0)
5140 *   4:     ADRS.setTreeIndex(i)
5141 *   5:     node <- F(PK.seed, ADRS, sk)
5142 *   6: else
5143 *  ...
5144 *  13: return node
5145 *
5146 * @param [in]  key      SLH-DSA key.
5147 * @param [in]  sk_seed  Private key seed.
5148 * @param [in]  i        Node index.
5149 * @param [in]  pk_seed  Public key seed.
5150 * @param [in]  adrs     FORS tree HashAddress.
5151 * @param [out] node     n-byte root node.
5152 * @return  0 on success.
5153 * @return  SHAKE-256 error return code on digest failure.
5154 * @return  MEMORY_E on dynamic memory allocation failure.
5155 */
5156static int slhdsakey_fors_node_x4_z0(SlhDsaKey* key, const byte* sk_seed,
5157    word32 i, const byte* pk_seed, word32* adrs, byte* node)
5158{
5159    int ret;
5160    byte n = key->params->n;
5161
5162    /* Step 2: Generate private key value for index. */
5163    ret = slhdsakey_fors_sk_gen(key, sk_seed, pk_seed, adrs, i, node);
5164    if (ret == 0) {
5165        /* Step 3: Set tree height to zero. */
5166        HA_SetTreeHeight(adrs, 0);
5167        /* Step 4: Set tree index. */
5168        HA_SetTreeIndex(adrs, i);
5169        /* Step 5: Compute node from public key seed, address and value. */
5170        ret = HASH_F(key, pk_seed, adrs, node, n, node);
5171    }
5172
5173    return ret;
5174}
5175
5176/* Compute the root of a one height Merkle subtree of FORS public values.
5177 *
5178 * Performs 4 hashes at the same time where possible.
5179 *
5180 * FIPS 205. Section 8.2. Algorithm 15.
5181 * fors_node(SK.seed, i, z, PK.seed, ADRS)
5182 *   1: if z = 0 then
5183 *   2:     sk <- fors_skGen(SK.seed, PK.seed, ADRS, i)
5184 *   3:     ADRS.setTreeHeight(0)
5185 *   4:     ADRS.setTreeIndex(i)
5186 *   5:     node <- F(PK.seed, ADRS, sk)
5187 *   6: else
5188 *   7:     lnode <- fors_node(SK.seed, 2i, z - 1, PK.seed, ADRS)
5189 *   8:     rnode <- fors_node(SK.seed, 2i + 1, z - 1, PK.seed, ADRS)
5190 *   9:     ADRS.setTreeHeight(z)
5191 *  10:     ADRS.setTreeIndex(i)
5192 *  11:     node <- H(PK.seed, ADRS, lnode || rnode)
5193 *  12: end if
5194 *  13: return node
5195 *
5196 * @param [in]  key      SLH-DSA key.
5197 * @param [in]  sk_seed  Private key seed.
5198 * @param [in]  i        Node index.
5199 * @param [in]  pk_seed  Public key seed.
5200 * @param [in]  adrs     FORS tree HashAddress.
5201 * @param [out] node     n-byte root node.
5202 * @return  0 on success.
5203 * @return  SHAKE-256 error return code on digest failure.
5204 * @return  MEMORY_E on dynamic memory allocation failure.
5205 */
5206static int slhdsakey_fors_node_x4_z1(SlhDsaKey* key, const byte* sk_seed,
5207    word32 i, const byte* pk_seed, word32* adrs, byte* node)
5208{
5209    int ret;
5210    byte n = key->params->n;
5211    byte nodes[2 * SLHDSA_MAX_N];
5212
5213    /* Step 7: Compute left node. */
5214    /* Step 2: Generate private key value for index. */
5215    ret = slhdsakey_fors_sk_gen(key, sk_seed, pk_seed, adrs, 2 * i + 0, nodes);
5216    if (ret == 0) {
5217        /* Step 3: Set tree height to zero. */
5218        HA_SetTreeHeight(adrs, 0);
5219        /* Step 4: Set tree index. */
5220        HA_SetTreeIndex(adrs, 2 * i + 0);
5221        /* Step 5: Compute node from public key seed, address and value. */
5222        ret = HASH_F(key, pk_seed, adrs, nodes, n, nodes);
5223    }
5224    /* Step 8: Compute right node. */
5225    if (ret == 0) {
5226        /* Step 2: Generate private key value for index. */
5227        ret = slhdsakey_fors_sk_gen(key, sk_seed, pk_seed, adrs, 2 * i + 1,
5228            nodes + n);
5229    }
5230    if (ret == 0) {
5231        /* Step 4: Set tree index. */
5232        HA_SetTreeIndex(adrs, 2 * i + 1);
5233        /* Step 5: Compute node from public key seed, address and value. */
5234        ret = HASH_F(key, pk_seed, adrs, nodes + n, n, nodes + n);
5235    }
5236    if (ret == 0) {
5237        /* Step 9: Set tree height. */
5238        HA_SetTreeHeight(adrs, 1);
5239        /* Step 10: Set tree index. */
5240        HA_SetTreeIndex(adrs, i);
5241        /* Step 11: Compute node from public key seed, address and nodes. */
5242        ret = HASH_H(key, pk_seed, adrs, nodes, n, node);
5243    }
5244
5245    return ret;
5246}
5247
5248/* Compute the root of a Merkle subtree of FORS public values.
5249 *
5250 * Performs 4 hashes at the same time where possible.
5251 *
5252 * FIPS 205. Section 8.2. Algorithm 15.
5253 * fors_node(SK.seed, i, z, PK.seed, ADRS)
5254 *   1: if z = 0 then
5255 *   2:     sk <- fors_skGen(SK.seed, PK.seed, ADRS, i)
5256 *   3:     ADRS.setTreeHeight(0)
5257 *   4:     ADRS.setTreeIndex(i)
5258 *   5:     node <- F(PK.seed, ADRS, sk)
5259 *   6: else
5260 *   7:     lnode <- fors_node(SK.seed, 2i, z - 1, PK.seed, ADRS)
5261 *   8:     rnode <- fors_node(SK.seed, 2i + 1, z - 1, PK.seed, ADRS)
5262 *   9:     ADRS.setTreeHeight(z)
5263 *  10:     ADRS.setTreeIndex(i)
5264 *  11:     node <- H(PK.seed, ADRS, lnode || rnode)
5265 *  12: end if
5266 *  13: return node
5267 *
5268 * @param [in]  key      SLH-DSA key.
5269 * @param [in]  sk_seed  Private key seed.
5270 * @param [in]  i        Node index.
5271 * @param [in]  z        Node height.
5272 * @param [in]  pk_seed  Public key seed.
5273 * @param [in]  adrs     FORS tree HashAddress.
5274 * @param [out] node     n-byte root node.
5275 * @return  0 on success.
5276 * @return  SHAKE-256 error return code on digest failure.
5277 * @return  MEMORY_E on dynamic memory allocation failure.
5278 */
5279static int slhdsakey_fors_node_x4_low(SlhDsaKey* key, const byte* sk_seed,
5280    word32 i, word32 z, const byte* pk_seed, word32* adrs, byte* node)
5281{
5282    int ret = 0;
5283    byte n = key->params->n;
5284    HashAddress sk_adrs;
5285    byte addr[SLHDSA_HA_SZ];
5286    word32 j;
5287    word32 m = (word32)1U << z;
5288    WC_DECLARE_VAR(nodes, byte, (1 << SLHDSA_MAX_FORS_NODE_DEPTH) *
5289        SLHDSA_MAX_N, key->heap);
5290
5291    WC_ALLOC_VAR_EX(nodes, byte, (1 << SLHDSA_MAX_FORS_NODE_DEPTH) *
5292        SLHDSA_MAX_N, key->heap, DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
5293    if (ret == 0) {
5294        byte sk_addr[SLHDSA_HA_SZ];
5295
5296        HA_SetTreeHeight(adrs, 0);
5297        /* Copy address for FORS PRF. */
5298        HA_Copy(sk_adrs, adrs);
5299        /* Set type and keep key pair address. */
5300        HA_SetTypeAndClearNotKPA(sk_adrs, HA_FORS_PRF);
5301        /* Encode FORS PRF address for hashing. */
5302        HA_Encode(sk_adrs, sk_addr);
5303        /* Encode FORS tree address for hashing. */
5304        HA_Encode(adrs, addr);
5305
5306        /* Step 2: Generate private key values for leaf indices. */
5307        for (j = 0; j < m; j += 4) {
5308            ret = slhdsakey_hash_prf_ti_x4(pk_seed, sk_seed, sk_addr, n,
5309                m * i + j, nodes + j * n, key->heap);
5310            if (ret != 0) {
5311                break;
5312            }
5313        }
5314    }
5315    if (ret == 0) {
5316        /* Step 3: Set tree height to zero. */
5317        HA_SetTreeHeight((word32*)addr, 0);
5318        /* Step 4-5: Set tree indices and compute leaf node. */
5319        for (j = 0; j < m; j += 4) {
5320            ret = slhdsakey_hash_f_ti_x4(pk_seed, addr, nodes + j * n, n,
5321                m * i + j, key->heap);
5322            if (ret != 0) {
5323                break;
5324            }
5325        }
5326    }
5327    if (ret == 0) {
5328        word32 k;
5329        for (k = 1; k < z - 1; k++) {
5330            m >>= 1;
5331            /* Step 9: Set tree height. */
5332            HA_SetTreeHeightBE(addr, k);
5333            /* Step 10-11: Set tree index and compute nodes. */
5334            for (j = 0; j < m; j += 4) {
5335                ret = slhdsakey_hash_h_ti_x4(pk_seed, addr, nodes + 2 * j * n,
5336                    n, m * i + j, nodes + j * n, key->heap);
5337                if (ret != 0) {
5338                    break;
5339                }
5340            }
5341            if (ret != 0) {
5342                break;
5343            }
5344        }
5345    }
5346    /* Step 7: Compute left node. */
5347    if (ret == 0) {
5348        /* Step 9: Set tree height. */
5349        HA_SetTreeHeight(adrs, z - 1);
5350        /* Step 10: Set tree index. */
5351        HA_SetTreeIndex(adrs, 2 * i + 0);
5352        /* Step 11: Compute node from public key seed, address and nodes. */
5353        ret = HASH_H(key, pk_seed, adrs, nodes, n, nodes);
5354    }
5355    /* Step 8: Compute right node. */
5356    if (ret == 0) {
5357        /* Step 10: Set tree index. */
5358        HA_SetTreeIndex(adrs, 2 * i + 1);
5359        /* Step 11: Compute node from public key seed, address and nodes. */
5360        ret = HASH_H(key, pk_seed, adrs, nodes + 2 * n, n,
5361            nodes + 1 * n);
5362    }
5363    if (ret == 0) {
5364        /* Step 9: Set tree height. */
5365        HA_SetTreeHeight(adrs, z);
5366        /* Step 10: Set tree index. */
5367        HA_SetTreeIndex(adrs, i);
5368        /* Step 11: Compute node from public key seed, address and nodes. */
5369        ret = HASH_H(key, pk_seed, adrs, nodes, n, node);
5370    }
5371
5372    WC_FREE_VAR_EX(nodes, key->heap, DYNAMIC_TYPE_SLHDSA);
5373    return ret;
5374}
5375
5376#if SLHDSA_MAX_FORS_NODE_DEPTH < SLHDSA_MAX_A-1
5377/* Compute the root of a Merkle subtree of FORS public values for large heights.
5378 *
5379 * Performs 4 hashes at the same time where possible.
5380 *
5381 * FIPS 205. Section 8.2. Algorithm 15.
5382 * fors_node(SK.seed, i, z, PK.seed, ADRS)
5383 *   1: if z = 0 then
5384 *   2:     sk <- fors_skGen(SK.seed, PK.seed, ADRS, i)
5385 *   3:     ADRS.setTreeHeight(0)
5386 *   4:     ADRS.setTreeIndex(i)
5387 *   5:     node <- F(PK.seed, ADRS, sk)
5388 *   6: else
5389 *   7:     lnode <- fors_node(SK.seed, 2i, z - 1, PK.seed, ADRS)
5390 *   8:     rnode <- fors_node(SK.seed, 2i + 1, z - 1, PK.seed, ADRS)
5391 *   9:     ADRS.setTreeHeight(z)
5392 *  10:     ADRS.setTreeIndex(i)
5393 *  11:     node <- H(PK.seed, ADRS, lnode || rnode)
5394 *  12: end if
5395 *  13: return node
5396 *
5397 * @param [in]  key      SLH-DSA key.
5398 * @param [in]  sk_seed  Private key seed.
5399 * @param [in]  i        Node index.
5400 * @param [in]  z        Node height.
5401 * @param [in]  pk_seed  Public key seed.
5402 * @param [in]  adrs     FORS tree HashAddress.
5403 * @param [out] node     n-byte root node.
5404 * @return  0 on success.
5405 * @return  SHAKE-256 error return code on digest failure.
5406 * @return  MEMORY_E on dynamic memory allocation failure.
5407 */
5408static int slhdsakey_fors_node_x4_high(SlhDsaKey* key, const byte* sk_seed,
5409    word32 i, word32 z, const byte* pk_seed, word32* adrs, byte* node)
5410{
5411    int ret = 0;
5412    byte n = key->params->n;
5413    word32 j;
5414    word32 z2 = z % SLHDSA_MAX_FORS_NODE_DEPTH;
5415    word32 m;
5416    WC_DECLARE_VAR(nodes, byte, (1 << SLHDSA_MAX_FORS_NODE_TOP_DEPTH) *
5417        SLHDSA_MAX_N, key->heap);
5418
5419    WC_ALLOC_VAR_EX(nodes, byte, (1 << SLHDSA_MAX_FORS_NODE_TOP_DEPTH) *
5420        SLHDSA_MAX_N, key->heap, DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
5421    if (ret == 0) {
5422        if (z2 == 0) {
5423            z2 = SLHDSA_MAX_FORS_NODE_DEPTH;
5424        }
5425        m = (word32)1U << z2;
5426        /* Steps 7-8: Compute left and right nodes. */
5427        for (j = 0; j < m; j++) {
5428            ret = slhdsakey_fors_node_x4_low(key, sk_seed, m * i + j, z - z2,
5429                pk_seed, adrs, nodes + j * n);
5430            if (ret != 0) {
5431                break;
5432            }
5433        }
5434    }
5435    if ((ret == 0) && (z2 > 2)) {
5436        word32 k;
5437        for (k = z - z2 + 1; k < z - 1; k++) {
5438            byte addr[SLHDSA_HA_SZ];
5439
5440            m >>= 1;
5441            /* Step 9: Set tree height. */
5442            HA_SetTreeHeight(adrs, k);
5443            /* Encode FORS tree address for hashing. */
5444            HA_Encode(adrs, addr);
5445            /* Step 10-11: Set tree index and compute nodes. */
5446            for (j = 0; j < m; j += 4) {
5447                ret = slhdsakey_hash_h_ti_x4(pk_seed, addr, nodes + 2 * j * n,
5448                    n, m * i + j, nodes + j * n, key->heap);
5449                if (ret != 0) {
5450                    break;
5451                }
5452            }
5453            if (ret != 0) {
5454                break;
5455            }
5456        }
5457    }
5458    /* Step 7: Compute left node. */
5459    if ((ret == 0) && (z2 > 1)) {
5460        /* Step 9: Set tree height. */
5461        HA_SetTreeHeight(adrs, z - 1);
5462        /* Step 10: Set tree index. */
5463        HA_SetTreeIndex(adrs, 2 * i + 0);
5464        /* Step 11: Compute node from public key seed, address and nodes. */
5465        ret = HASH_H(key, pk_seed, adrs, nodes, n, nodes);
5466    }
5467    /* Step 8: Compute right node. */
5468    if ((ret == 0) && (z2 > 1)) {
5469        /* Step 10: Set tree index. */
5470        HA_SetTreeIndex(adrs, 2 * i + 1);
5471        /* Step 11: Compute node from public key seed, address and nodes. */
5472        ret = HASH_H(key, pk_seed, adrs, nodes + 2 * n, n,
5473            nodes + 1 * n);
5474    }
5475    if (ret == 0) {
5476        /* Step 9: Set tree height. */
5477        HA_SetTreeHeight(adrs, z);
5478        /* Step 10: Set tree index. */
5479        HA_SetTreeIndex(adrs, i);
5480        /* Step 11: Compute node from public key seed, address and nodes. */
5481        ret = HASH_H(key, pk_seed, adrs, nodes, n, node);
5482    }
5483
5484    WC_FREE_VAR_EX(nodes, key->heap, DYNAMIC_TYPE_SLHDSA);
5485    return ret;
5486}
5487#endif
5488
5489/* Compute the root of a Merkle subtree of FORS public values.
5490 *
5491 * Performs 4 hashes at the same time where possible.
5492 *
5493 * FIPS 205. Section 8.2. Algorithm 15.
5494 * fors_node(SK.seed, i, z, PK.seed, ADRS)
5495 *   1: if z = 0 then
5496 *   2:     sk <- fors_skGen(SK.seed, PK.seed, ADRS, i)
5497 *   3:     ADRS.setTreeHeight(0)
5498 *   4:     ADRS.setTreeIndex(i)
5499 *   5:     node <- F(PK.seed, ADRS, sk)
5500 *   6: else
5501 *   7:     lnode <- fors_node(SK.seed, 2i, z - 1, PK.seed, ADRS)
5502 *   8:     rnode <- fors_node(SK.seed, 2i + 1, z - 1, PK.seed, ADRS)
5503 *   9:     ADRS.setTreeHeight(z)
5504 *  10:     ADRS.setTreeIndex(i)
5505 *  11:     node <- H(PK.seed, ADRS, lnode || rnode)
5506 *  12: end if
5507 *  13: return node
5508 *
5509 * @param [in]  key      SLH-DSA key.
5510 * @param [in]  sk_seed  Private key seed.
5511 * @param [in]  i        Node index.
5512 * @param [in]  z        Node height.
5513 * @param [in]  pk_seed  Public key seed.
5514 * @param [in]  adrs     FORS tree HashAddress.
5515 * @param [out] node     n-byte root node.
5516 * @return  0 on success.
5517 * @return  SHAKE-256 error return code on digest failure.
5518 * @return  MEMORY_E on dynamic memory allocation failure.
5519 */
5520static int slhdsakey_fors_node_x4(SlhDsaKey* key, const byte* sk_seed, word32 i,
5521    word32 z, const byte* pk_seed, word32* adrs, byte* node)
5522{
5523    int ret = 0;
5524
5525    /* Step 1: Check if we are at leaf node. */
5526    if (z == 0) {
5527        ret = slhdsakey_fors_node_x4_z0(key, sk_seed, i, pk_seed, adrs, node);
5528    }
5529    /* Step 6: 1 level above leaf node. */
5530    else if (z == 1) {
5531        ret = slhdsakey_fors_node_x4_z1(key, sk_seed, i, pk_seed, adrs, node);
5532    }
5533    /* Step 6: 2-MAX_DEPTH levels above leaf node. */
5534    else if ((z >= 2) && (z <= SLHDSA_MAX_FORS_NODE_DEPTH)) {
5535        ret = slhdsakey_fors_node_x4_low(key, sk_seed, i, z, pk_seed, adrs,
5536            node);
5537    }
5538#if SLHDSA_MAX_FORS_NODE_DEPTH < SLHDSA_MAX_A-1
5539    /* Step 6: More than MAX_DEPTH levels above leaf node. */
5540    else {
5541        ret = slhdsakey_fors_node_x4_high(key, sk_seed, i, z, pk_seed, adrs,
5542            node);
5543    }
5544#endif
5545
5546    return ret;
5547}
5548#endif
5549
5550#if !defined(WOLFSSL_WC_SLHDSA_RECURSIVE)
5551/* Compute the root of a Merkle subtree of FORS public values.
5552 *
5553 * Iterative implementation.
5554 *
5555 * FIPS 205. Section 8.2. Algorithm 15.
5556 * fors_node(SK.seed, i, z, PK.seed, ADRS)
5557 *   1: if z = 0 then
5558 *   2:     sk <- fors_skGen(SK.seed, PK.seed, ADRS, i)
5559 *   3:     ADRS.setTreeHeight(0)
5560 *   4:     ADRS.setTreeIndex(i)
5561 *   5:     node <- F(PK.seed, ADRS, sk)
5562 *   6: else
5563 *   7:     lnode <- fors_node(SK.seed, 2i, z - 1, PK.seed, ADRS)
5564 *   8:     rnode <- fors_node(SK.seed, 2i + 1, z - 1, PK.seed, ADRS)
5565 *   9:     ADRS.setTreeHeight(z)
5566 *  10:     ADRS.setTreeIndex(i)
5567 *  11:     node <- H(PK.seed, ADRS, lnode || rnode)
5568 *  12: end if
5569 *  13: return node
5570 *
5571 * @param [in]  key      SLH-DSA key.
5572 * @param [in]  sk_seed  Private key seed.
5573 * @param [in]  i        Node index.
5574 * @param [in]  z        Node height.
5575 * @param [in]  pk_seed  Public key seed.
5576 * @param [in]  adrs     FORS tree HashAddress.
5577 * @param [out] node     n-byte root node.
5578 * @return  0 on success.
5579 * @return  MEMORY_E on dynamic memory allocation failure.
5580 * @return  SHAKE-256 error return code on digest failure.
5581 */
5582static int slhdsakey_fors_node_c(SlhDsaKey* key, const byte* sk_seed, word32 i,
5583    word32 z, const byte* pk_seed, word32* adrs, byte* node)
5584{
5585    int ret = 0;
5586    byte n = key->params->n;
5587
5588    /* Step 1: Check if we are at leaf node. */
5589    if (z == 0) {
5590        /* Step 2: Generate private key value for index. */
5591        ret = slhdsakey_fors_sk_gen(key, sk_seed, pk_seed, adrs, i, node);
5592        if (ret == 0) {
5593            /* Step 3: Set tree height to zero. */
5594            HA_SetTreeHeight(adrs, 0);
5595            /* Step 4: Set tree index. */
5596            HA_SetTreeIndex(adrs, i);
5597            /* Step 5: Compute node from public key seed, address and value. */
5598            ret = HASH_F(key, pk_seed, adrs, node, n, node);
5599        }
5600    }
5601    /* Step 6: Non leaf node. */
5602    else {
5603        WC_DECLARE_VAR(nodes, byte, (SLHDSA_MAX_A + 1) * SLHDSA_MAX_N,
5604            key->heap);
5605        word32 j;
5606        word32 k;
5607        word32 m = (word32)1U << z;
5608
5609        WC_ALLOC_VAR_EX(nodes, byte, (SLHDSA_MAX_A + 1) * SLHDSA_MAX_N,
5610            key->heap, DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
5611        if (ret == 0) {
5612            /* For all leaf nodes. */
5613            for (j = 0; j < m; j++) {
5614                word32 o = ((word32)z - 1U + (j & 1U)) * n;
5615                /* Step 2: Generate private key value for index. */
5616                ret = slhdsakey_fors_sk_gen(key, sk_seed, pk_seed, adrs,
5617                    m * (word32)i + j, nodes + o);
5618                if (ret != 0) {
5619                    break;
5620                }
5621                /* Step 3: Set tree height to zero. */
5622                HA_SetTreeHeight(adrs, 0);
5623                /* Step 4: Set tree index. */
5624                HA_SetTreeIndex(adrs, m * (word32)i + j);
5625                /* Step 5: Compute node from public key seed, address and value.
5626                 */
5627                ret = HASH_F(key, pk_seed, adrs, nodes + o, n,
5628                    nodes + o);
5629                if (ret != 0) {
5630                    break;
5631                }
5632
5633                /* For each intermediate node as soon as left and right have
5634                 * been computed. */
5635                for (k = (word32)z - 1U; k > 0; k--) {
5636                    /* Check if this is the right node at a height. */
5637                    if (((j >> ((word32)z - 1U - k)) & 1U) == 1U) {
5638                        /* Step 9: Set tree height. */
5639                        HA_SetTreeHeight(adrs, (word32)z - k);
5640                        /* Step 10: Set tree index. */
5641                        HA_SetTreeIndex(adrs,
5642                                        (m * (word32)i + j) >> ((word32)z - k));
5643                        /* Step 11: Compute node from public key seed, address
5644                         * and left and right nodes. */
5645                        ret = HASH_H(key, pk_seed, adrs, nodes + k * n, n,
5646                                nodes +
5647                                  (k - 1U + ((j >> ((word32)z - k)) & 1U)) * n);
5648                        if (ret != 0) {
5649                            break;
5650                        }
5651                    }
5652                    /* Left node - can go no higher. */
5653                    else {
5654                        break;
5655                    }
5656                }
5657            }
5658            if (ret == 0) {
5659                /* Step 9: Set tree height. */
5660                HA_SetTreeHeight(adrs, z);
5661                /* Step 10: Set tree index. */
5662                HA_SetTreeIndex(adrs, i);
5663                /* Step 11: Compute node from public key seed, address
5664                 * and nodes. */
5665                ret = HASH_H(key, pk_seed, adrs, nodes, n, node);
5666            }
5667        }
5668
5669        WC_FREE_VAR_EX(nodes, key->heap, DYNAMIC_TYPE_SLHDSA);
5670    }
5671
5672    return ret;
5673}
5674#else
5675/* Compute the root of a Merkle subtree of FORS public values.
5676 *
5677 * Recursive implementation.
5678 *
5679 * FIPS 205. Section 8.2. Algorithm 15.
5680 * fors_node(SK.seed, i, z, PK.seed, ADRS)
5681 *   1: if z = 0 then
5682 *   2:     sk <- fors_skGen(SK.seed, PK.seed, ADRS, i)
5683 *   3:     ADRS.setTreeHeight(0)
5684 *   4:     ADRS.setTreeIndex(i)
5685 *   5:     node <- F(PK.seed, ADRS, sk)
5686 *   6: else
5687 *   7:     lnode <- fors_node(SK.seed, 2i, z - 1, PK.seed, ADRS)
5688 *   8:     rnode <- fors_node(SK.seed, 2i + 1, z - 1, PK.seed, ADRS)
5689 *   9:     ADRS.setTreeHeight(z)
5690 *  10:     ADRS.setTreeIndex(i)
5691 *  11:     node <- H(PK.seed, ADRS, lnode || rnode)
5692 *  12: end if
5693 *  13: return node
5694 *
5695 * @param [in]  key      SLH-DSA key.
5696 * @param [in]  sk_seed  Private key seed.
5697 * @param [in]  i        Node index.
5698 * @param [in]  z        Node height.
5699 * @param [in]  pk_seed  Public key seed.
5700 * @param [in]  adrs     FORS tree HashAddress.
5701 * @param [out] node     n-byte root node.
5702 * @return  0 on success.
5703 * @return  MEMORY_E on dynamic memory allocation failure.
5704 * @return  SHAKE-256 error return code on digest failure.
5705 */
5706static int slhdsakey_fors_node_c(SlhDsaKey* key, const byte* sk_seed, word32 i,
5707    word32 z, const byte* pk_seed, word32* adrs, byte* node)
5708{
5709    int ret;
5710    byte n = key->params->n;
5711
5712    /* Step 1: Check if we are at leaf node. */
5713    if (z == 0) {
5714        /* Step 2: Generate private key value for index. */
5715        ret = slhdsakey_fors_sk_gen(key, sk_seed, pk_seed, adrs, i, node);
5716        if (ret == 0) {
5717            /* Step 3: Set tree height to zero. */
5718            HA_SetTreeHeight(adrs, 0);
5719            /* Step 4: Set tree index. */
5720            HA_SetTreeIndex(adrs, i);
5721            /* Step 5: Compute node from public key seed, address and value. */
5722            ret = HASH_F(key, pk_seed, adrs, node, n, node);
5723        }
5724    }
5725    else {
5726        byte nodes[2 * SLHDSA_MAX_N];
5727
5728        /* Step 7: Compute left node. */
5729        ret = slhdsakey_fors_node_c(key, sk_seed, 2 * i + 0, z - 1, pk_seed,
5730            adrs, nodes);
5731        if (ret == 0) {
5732            /* Step 8: Compute right node. */
5733            ret = slhdsakey_fors_node_c(key, sk_seed, 2 * i + 1, z - 1, pk_seed,
5734                adrs, nodes + n);
5735        }
5736        if (ret == 0) {
5737            /* Step 9: Set tree height. */
5738            HA_SetTreeHeight(adrs, z);
5739            /* Step 10: Set tree index. */
5740            HA_SetTreeIndex(adrs, i);
5741            /* Step 11: Compute node from public key seed, address and nodes. */
5742            ret = HASH_H(key, pk_seed, adrs, nodes, n, node);
5743        }
5744    }
5745
5746    return ret;
5747}
5748#endif
5749
5750/* Generate FORS signature.
5751 *
5752 * FIPS 205. Section 8.3. Algorithm 16.
5753 * fors_sign(md SK.seed, PK.seed, ADRS)
5754 *   1: SIGFORS = NULL         > initialize SIGFORS as a zero-length byte string
5755 *   2: indices <- base_2b(md, a, k)
5756 *   3: for i from 0 to k - 1 do                    > compute signature elements
5757 *   4:     SIGFORS <- SIGFORS ||
5758 *                     fors_skGen(SK.seed, PK.seed, ADRS, i . 2^a + indices)
5759 *   5:     for j from 0 to a - 1 do                         > compute auth path
5760 *   6:         s <- lower(indices[i]/2^j) XOR 1
5761 *   7:         AUTH[j] <- fors_node(SK.seed, i . 2^(a-j) + s, j, PK.seed, ADRS)
5762 *   8:     end for
5763 *   9:     SIGFORS <- SIGFORS || AUTH
5764 *  10: end for
5765 *  11: return SIGFORS
5766 *
5767 * @param [in]       key       SLH-DSA key.
5768 * @param [in]       md        Message digest.
5769 * @param [in]       sk_seed   Private key seed.
5770 * @param [in]       pk_seed   Public key seed.
5771 * @param [inm out]  adrs      FORS tree HashAddress.
5772 * @param [out]      sig_fors  FORS signature.
5773 * @return  0 on success.
5774 * @return  MEMORY_E on dynamic memory allocation failure.
5775 * @return  SHAKE-256 error return code on digest failure.
5776 */
5777static int slhdsakey_fors_sign(SlhDsaKey* key, const byte* md,
5778    const byte* sk_seed, const byte* pk_seed, word32* adrs, byte* sig_fors)
5779{
5780    int ret = WC_NO_ERR_TRACE(BAD_FUNC_ARG);
5781    word16 indices[SLHDSA_MAX_INDICES_SZ];
5782    int i;
5783    int j;
5784    byte n = key->params->n;
5785    byte a = key->params->a;
5786    byte k = key->params->k;
5787
5788    /* Step 2: Convert message digest to base 2^a. */
5789    slhdsakey_base_2b(md, a, k, indices);
5790
5791    /* Step 3: For each index: */
5792    for (i = 0; i < k; i++) {
5793        /* Step 4: Generate FORS private key value into signature. */
5794        ret = slhdsakey_fors_sk_gen(key, sk_seed, pk_seed, adrs,
5795            ((word32)i << a) + indices[i], sig_fors);
5796        if (ret != 0) {
5797            break;
5798        }
5799        /* Step 4: Move over private key value. */
5800        sig_fors += n;
5801
5802    #if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
5803        if (!SLHDSA_IS_SHA2(key->params->param) &&
5804                IS_INTEL_AVX2(cpuid_flags) &&
5805                CAN_SAVE_VECTOR_REGISTERS()) {
5806            word16 idx = indices[i];
5807            /* Step 5: For each bit: */
5808            for (j = 0; j < a; j++) {
5809                /* Calculate side. */
5810                word32 s = idx ^ 1;
5811                /* Step 7: Compute authentication node into signature. */
5812                ret = slhdsakey_fors_node_x4(key, sk_seed,
5813                    ((word32)i << (a - j)) + s, (word32)j, pk_seed, adrs,
5814                    sig_fors);
5815                if (ret != 0) {
5816                    break;
5817                }
5818                /* Step 9: Move signature to after authentication node. */
5819                sig_fors += n;
5820                /* Update tree index. */
5821                idx >>= 1;
5822            }
5823        }
5824        else
5825    #endif
5826        {
5827            word16 idx = indices[i];
5828            /* Step 5: For each bit: */
5829            for (j = 0; j < a; j++) {
5830                /* Calculate side. */
5831                word32 s = idx ^ 1;
5832                /* Step 7: Compute authentication node into signature. */
5833                ret = slhdsakey_fors_node_c(key, sk_seed,
5834                    ((word32)i << (a - j)) + s, (word32)j, pk_seed, adrs,
5835                    sig_fors);
5836                if (ret != 0) {
5837                    break;
5838                }
5839                /* Step 9: Move signature to after authentication node. */
5840                sig_fors += n;
5841                /* Update tree index. */
5842                idx >>= 1;
5843            }
5844        }
5845        if (ret != 0) {
5846            break;
5847        }
5848    }
5849
5850    return ret;
5851}
5852#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
5853
5854#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
5855/* F hash 4 simultaneously.
5856 *
5857 * Each hash varies by the tree index with the values passed in.
5858 * Each n-byte message in sig_fors is offset by so x n bytes.
5859 *
5860 * FIPS 205. Section 4.1.
5861 *   F(PK.seed, ADRS, M1) (Bn x B32 x Bn -> Bn) is a hash function that takes an
5862 *   n-byte message as input and produces an n-byte output.
5863 * FIPS 205. Section 11.1.
5864 *   F(PK.seed, ADRS, M1) = SHAKE256(PK.seed || ADRS || M1 , 8n)
5865 *
5866 * @param [in]  pk_seed   Public key seed.
5867 * @param [in]  addr      Encoded HashAddress.
5868 * @param [in]  sig_fors  n-byte messages.
5869 * @param [in]  so        Tree index start value.
5870 * @param [in]  n         Number of bytes in hash output.
5871 * @param [in]  ti        Tree index start value.
5872 * @param [out] node      n-byte hash outputs.
5873 * @param [in]  heap      Dynamic memory allocation hint.
5874 * @return  0 on success.
5875 * @return  MEMORY_E on dynamic memory allocation failure.
5876 */
5877static int slhdsakey_hash_f_ti4_x4(const byte* pk_seed, byte* addr,
5878    const byte* sig_fors, int so, byte n, word32* ti, byte* node, void* heap)
5879{
5880    int ret = 0;
5881    int i;
5882    word32 o = 0;
5883    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
5884
5885    (void)heap;
5886
5887    WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
5888        ret = MEMORY_E);
5889    if (ret == 0) {
5890        o = slhdsakey_shake256_set_seed_ha_x4(state, pk_seed, addr, n);
5891        SHAKE256_SET_TREE_INDEX_IDX(state, o, ti);
5892        for (i = 0; i < n / 8; i++) {
5893            state[o + 0] = ((const word64*)(sig_fors + 0 * so * n))[i];
5894            state[o + 1] = ((const word64*)(sig_fors + 1 * so * n))[i];
5895            state[o + 2] = ((const word64*)(sig_fors + 2 * so * n))[i];
5896            state[o + 3] = ((const word64*)(sig_fors + 3 * so * n))[i];
5897            o += 4;
5898        }
5899        SHAKE256_SET_END_X4(state, o);
5900        ret = SAVE_VECTOR_REGISTERS2();
5901        if (ret == 0) {
5902            sha3_blocksx4_avx2(state);
5903            RESTORE_VECTOR_REGISTERS();
5904            slhdsakey_shake256_get_hash_x4(state, node, n);
5905        }
5906
5907        WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
5908    }
5909
5910    return ret;
5911}
5912
5913/* H hash 4 simultaneously with two buffers holding two halves of messages.
5914 *
5915 * Each hash varies by the tree index with the first value in sequence passed
5916 * in.
5917 * Each n-byte message in sig_fors is offset by so x n bytes.
5918 *
5919 * FIPS 205. Section 4.1.
5920 *   H(PK.seed, ADRS, M2) (Bn x B32 x B2n -> Bn) is a special case of Tl that
5921 *   takes a 2n-byte message as input.
5922 * FIPS 205. Section 11.1.
5923 *   H(PK.seed, ADRS, M2) = SHAKE256(PK.seed || ADRS || M2, 8n)
5924 *
5925 * @param [in]      pk_seed   Public key seed.
5926 * @param [in]      addr      Encoded HashAddress.
5927 * @param [in, out] node      On in, n-byte messages. On out, hash output.
5928 * @param [in]      sig_fors  n-byte messages.
5929 * @param [in]      so        Tree index start value.
5930 * @param [in]      bit       Bits to indicate which order of node/sig_fors.
5931 * @param [in]      n         Number of bytes in hash output.
5932 * @param [in]      ti        Tree index start value.
5933 * @param [in]      heap      Dynamic memory allocation hint.
5934 * @return  0 on success.
5935 * @return  MEMORY_E on dynamic memory allocation failure.
5936 */
5937static int slhdsakey_hash_h_2_x4(const byte* pk_seed, byte* addr, byte* node,
5938    const byte* sig_fors, int so, word32* bit, byte n, word32 th, word32* ti,
5939    void* heap)
5940{
5941    int ret = 0;
5942    int i;
5943    word32 j;
5944    word32 o = 0;
5945    WC_DECLARE_VAR(state, word64, 25 * 4, heap);
5946
5947    (void)heap;
5948
5949    WC_ALLOC_VAR_EX(state, word64, 25 * 4, heap, DYNAMIC_TYPE_SLHDSA,
5950        ret = MEMORY_E);
5951    if (ret == 0) {
5952        o = slhdsakey_shake256_set_seed_ha_x4(state, pk_seed, addr, n);
5953        SHAKE256_SET_TREE_HEIGHT(state, o, th);
5954        SHAKE256_SET_TREE_INDEX_IDX(state, o, ti);
5955        for (i = 0; i < n / 8; i++) {
5956            for (j = 0; j < 4; j++) {
5957                if (bit[j] == 0) {
5958                    state[o + j] = ((const word64*)(node + j * n))[i];
5959                }
5960                else {
5961                    state[o + j] =
5962                        ((const word64*)(sig_fors + j * (word32)so * n))[i];
5963                }
5964            }
5965            o += 4;
5966        }
5967        for (i = 0; i < n / 8; i++) {
5968            for (j = 0; j < 4; j++) {
5969                if (bit[j] == 0) {
5970                    state[o + j] =
5971                        ((const word64*)(sig_fors + j * (word32)so * n))[i];
5972                }
5973                else {
5974                    state[o + j] = ((const word64*)(node + j * n))[i];
5975                }
5976            }
5977            o += 4;
5978        }
5979        SHAKE256_SET_END_X4(state, o);
5980        ret = SAVE_VECTOR_REGISTERS2();
5981        if (ret == 0) {
5982            sha3_blocksx4_avx2(state);
5983            RESTORE_VECTOR_REGISTERS();
5984            slhdsakey_shake256_get_hash_x4(state, node, n);
5985        }
5986
5987        WC_FREE_VAR_EX(state, heap, DYNAMIC_TYPE_SLHDSA);
5988    }
5989
5990    return ret;
5991}
5992
5993/* Compute ith FORS public key from ith FORS signature.
5994 *
5995 * 4 hashes computed simultaneously.
5996 *
5997 * FIPS 205. Section 8.4 Algorithm 17.
5998 * fors_pkFromSig(SIGFORS, md, PK.seed, ADRS)
5999 *  ...
6000 *   4:     ADRS.setTreeHeight(0)                                 > compute leaf
6001 *   5:     ADRS.setTreeIndex(i . 2^a + indices[i])
6002 *   6:     node[0] <- F(PK.seed, ADRS, sk)
6003 *   7:     auth <- SIGFORS.getAUTH(i)
6004 *                     > SIGFORS [(i . (a + 1) + 1) . n : (i + 1) . (a + 1) . n]
6005 *   8:     for j from 0 to a - 1 do           > compute root from leaf and AUTH
6006 *   9:         ADRS.setTreeHeight(j + 1)
6007 *  10:         if lower(indices[i]/(2^j)) is even then
6008 *  11:             ADRS.setTreeIndex(ADRS.getTreeIndex()/2)
6009 *  12:             node[1] <- H(PK.seed, ADRS, node[0] || auth[i])
6010 *  13:         else
6011 *  14:             ADRS.setTreeIndex((ADRS.getTreeIndex() - 1)/2)
6012 *  15:             node[1] <- H(PK.seed, ADRS, auth[j] || node[0])
6013 *  16:         end if
6014 *  17:         node[0] <- node[1]
6015 *  18:     end for
6016 *  19:     root[i] <- node[0]
6017 *  ...
6018 *
6019 * @param [in]  key       SLH-DSA key.
6020 * @param [in]  sig_fors  FORS signature.
6021 * @param [in]  pk_seed   Public key seed.
6022 * @param [in]  addr      Encoded HashAddress.
6023 * @param [in]  indices   Base 2^a values from message digest.
6024 * @param [in]  i         Index.
6025 * @param [out] node      Root node of ith tree.
6026 * @return  0 on success.
6027 * @return  MEMORY_E on dynamic memory allocation failure.
6028 */
6029static int slhdsakey_fors_pk_from_sig_i_x4(SlhDsaKey* key, const byte* sig_fors,
6030    const byte* pk_seed, byte* addr, const word16* indices, int i, byte* node)
6031{
6032    int ret;
6033    int j;
6034    int k;
6035    byte n = key->params->n;
6036    byte a = key->params->a;
6037    word32 ti[4];
6038    word32 bit[4];
6039
6040    /* Step 5: Calculate the index of each hash ... */
6041    ti[0] = ((word32)(i + 0) << a) + indices[i + 0];
6042    ti[1] = ((word32)(i + 1) << a) + indices[i + 1];
6043    ti[2] = ((word32)(i + 2) << a) + indices[i + 2];
6044    ti[3] = ((word32)(i + 3) << a) + indices[i + 3];
6045    /* Steps 4-6: Compute nodes.  */
6046    ret = slhdsakey_hash_f_ti4_x4(pk_seed, addr, sig_fors, 1 + a, n, ti, node,
6047        key->heap);
6048    if (ret == 0) {
6049        /* Step 7: Move on to authentication nodes. */
6050        sig_fors += n;
6051        /* Step 8: For each level: */
6052        for (j = 0; j < a; j++) {
6053            /* Calculate which order of node and sig_fors for each hash. */
6054            for (k = 0; k < 4; k++) {
6055                bit[k] = ti[k] & 1;
6056                ti[k] /= 2;
6057            }
6058            /* Steps 9-17: 4 hash with tree indices. */
6059            ret = slhdsakey_hash_h_2_x4(pk_seed, addr, node, sig_fors, 1 + a,
6060                bit, n, (word32)(j + 1), ti, key->heap);
6061            if (ret != 0) {
6062                break;
6063            }
6064            /* Move on to next authentication node. */
6065            sig_fors += n;
6066        }
6067    }
6068
6069    return ret;
6070}
6071
6072/* Compute ith FORS public key from ith FORS signature.
6073 *
6074 * 4 hashes computed simultaneously.
6075 *
6076 * FIPS 205. Section 8.4 Algorithm 17.
6077 * fors_pkFromSig(SIGFORS, md, PK.seed, ADRS)
6078 *  ...
6079 *   2: for i from 0 to k - 1 do
6080 *   3:     sk <- SIGFORS.getSK(i)
6081 *                           > SIGFORS [i . (a + 1) . n : (i . (a + 1) + 1) . n]
6082 *   4:     ADRS.setTreeHeight(0)                                 > compute leaf
6083 *   5:     ADRS.setTreeIndex(i . 2^a + indices[i])
6084 *   6:     node[0] <- F(PK.seed, ADRS, sk)
6085 *   7:     auth <- SIGFORS.getAUTH(i)
6086 *                     > SIGFORS [(i . (a + 1) + 1) . n : (i + 1) . (a + 1) . n]
6087 *   8:     for j from 0 to a - 1 do           > compute root from leaf and AUTH
6088 *   9:         ADRS.setTreeHeight(j + 1)
6089 *  10:         if lower(indices[i]/(2^j)) is even then
6090 *  11:             ADRS.setTreeIndex(ADRS.getTreeIndex()/2)
6091 *  12:             node[1] <- H(PK.seed, ADRS, node[0] || auth[i])
6092 *  13:         else
6093 *  14:             ADRS.setTreeIndex((ADRS.getTreeIndex() - 1)/2)
6094 *  15:             node[1] <- H(PK.seed, ADRS, auth[j] || node[0])
6095 *  16:         end if
6096 *  17:         node[0] <- node[1]
6097 *  18:     end for
6098 *  19:     root[i] <- node[0]
6099 *  20: end for
6100 * ...
6101 *  24: pk <- Tk(PK.seed, forspkADRS, root)        > compute the FORS public key
6102 * ...
6103 *
6104 * @param [in]  key       SLH-DSA key.
6105 * @param [in]  sig_fors  FORS signature.
6106 * @param [in]  indices   Base 2^a values from message digest.
6107 * @param [in]  pk_seed   Public key seed.
6108 * @param [in]  adrs      Encoded HashAddress.
6109 * @return  0 on success.
6110 * @return  MEMORY_E on dynamic memory allocation failure.
6111 * @return  SHAKE-256 error return code on digest failure.
6112 */
6113static int slhdsakey_fors_pk_from_sig_x4(SlhDsaKey* key, const byte* sig_fors,
6114    const word16* indices, const byte* pk_seed, word32* adrs)
6115{
6116    int ret = 0;
6117    int i;
6118    int j;
6119    byte n = key->params->n;
6120    byte a = key->params->a;
6121    byte k = key->params->k;
6122    byte addr[SLHDSA_HA_SZ];
6123    WC_DECLARE_VAR(node, byte, SLHDSA_MAX_INDICES_SZ * SLHDSA_MAX_N, key->heap);
6124
6125    WC_ALLOC_VAR_EX(node, byte, SLHDSA_MAX_INDICES_SZ * SLHDSA_MAX_N, key->heap,
6126        DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
6127    if (ret == 0) {
6128        /* Step 4: Set tree height for address.  */
6129        HA_SetTreeHeight(adrs, 0);
6130        /* Encode address for multiple hashing. */
6131        HA_Encode(adrs, addr);
6132
6133        /* Step 2: Do multiple of 4 iterations. */
6134        for (i = 0; i < k-3; i += 4) {
6135            /* Steps 4-19: Compute public key root for signature at index. */
6136            ret = slhdsakey_fors_pk_from_sig_i_x4(key, sig_fors, pk_seed, addr,
6137                indices, i, node + i * n);
6138            if (ret != 0) {
6139                break;
6140            }
6141            /* Move on to next signatures. */
6142            sig_fors += 4 * (1 + a) * n;
6143        }
6144    }
6145    if (ret == 0) {
6146        /* Step 2: Do remaining iterations. */
6147        for (; i < k; i++) {
6148            /* Step 5: Calculate index ...  */
6149            word32 idx = ((word32)i << a) + indices[i];
6150
6151            /* Step 4: Set tree height for address.  */
6152            HA_SetTreeHeight(adrs, 0);
6153            /* Step 5: Set tree index for address.  */
6154            HA_SetTreeIndex(adrs, idx);
6155            /* Step 6: Compute node from public key seed, address and value. */
6156            ret = HASH_F(key, pk_seed, adrs, sig_fors, n, node + i * n);
6157            if (ret != 0) {
6158                break;
6159            }
6160            /* Step 7: Move to authentication nodes. */
6161            sig_fors += n;
6162
6163            /* Step 8: For all heights: */
6164            for (j = 0; j < a; j++) {
6165                /* Step 10: Calculate side ... */
6166                word32 side = idx & 1;
6167
6168                /* Step 11/14: Update tree index value ... */
6169                idx >>= 1;
6170                /* Step 9: Set tree height. */
6171                HA_SetTreeHeight(adrs, j + 1);
6172                /* Step 11/14: Set tree index. */
6173                HA_SetTreeIndex(adrs, idx);
6174                /* Step 10: Check which side node is on. */
6175                if (side == 0) {
6176                    /* Step 12: Hash node || auth node. */
6177                    ret = HASH_H_2(key, pk_seed, adrs, node + i * n,
6178                        sig_fors, n, node + i * n);
6179                }
6180                else {
6181                    /* Step 15: Hash auth node || node. */
6182                    ret = HASH_H_2(key, pk_seed, adrs, sig_fors,
6183                        node + i * n, n, node + i * n);
6184                }
6185                if (ret != 0) {
6186                    break;
6187                }
6188                /* Move on to next authentication node. */
6189                sig_fors += n;
6190            }
6191            if (ret != 0) {
6192                break;
6193            }
6194        }
6195    }
6196    if (ret == 0) {
6197        /* Step 24: Add more root nodes to hash ... */
6198        ret = HASH_T_UPDATE(key, node, (word32)i * n);
6199    }
6200
6201    WC_FREE_VAR_EX(node, key->heap, DYNAMIC_TYPE_SLHDSA);
6202    return ret;
6203}
6204#endif
6205
6206#if !defined(WOLFSSL_WC_SLHDSA_SMALL_MEM)
6207/* Compute FORS public key from FORS signature.
6208 *
6209 * 4 hashes computed simultaneously.
6210 *
6211 * FIPS 205. Section 8.4 Algorithm 17.
6212 * fors_pkFromSig(SIGFORS, md, PK.seed, ADRS)
6213 *  ...
6214 *   2: for i from 0 to k - 1 do
6215 *   3:     sk <- SIGFORS.getSK(i)
6216 *                           > SIGFORS [i . (a + 1) . n : (i . (a + 1) + 1) . n]
6217 *   4:     ADRS.setTreeHeight(0)                                 > compute leaf
6218 *   5:     ADRS.setTreeIndex(i . 2^a + indices[i])
6219 *   6:     node[0] <- F(PK.seed, ADRS, sk)
6220 *   7:     auth <- SIGFORS.getAUTH(i)
6221 *                     > SIGFORS [(i . (a + 1) + 1) . n : (i + 1) . (a + 1) . n]
6222 *   8:     for j from 0 to a - 1 do           > compute root from leaf and AUTH
6223 *   9:         ADRS.setTreeHeight(j + 1)
6224 *  10:         if lower(indices[i]/(2^j)) is even then
6225 *  11:             ADRS.setTreeIndex(ADRS.getTreeIndex()/2)
6226 *  12:             node[1] <- H(PK.seed, ADRS, node[0] || auth[i])
6227 *  13:         else
6228 *  14:             ADRS.setTreeIndex((ADRS.getTreeIndex() - 1)/2)
6229 *  15:             node[1] <- H(PK.seed, ADRS, auth[j] || node[0])
6230 *  16:         end if
6231 *  17:         node[0] <- node[1]
6232 *  18:     end for
6233 *  19:     root[i] <- node[0]
6234 *  20: end for
6235 * ...
6236 *  24: pk <- Tk(PK.seed, forspkADRS, root)        > compute the FORS public key
6237 * ...
6238 *
6239 * @param [in]  key       SLH-DSA key.
6240 * @param [in]  sig_fors  FORS signature.
6241 * @param [in]  indices   Base 2^a values from message digest.
6242 * @param [in]  pk_seed   Public key seed.
6243 * @param [in]  adrs      HashAddress.
6244 * @param [out] pk_fors   FORS public key from signature.
6245 * @return  0 on success.
6246 * @return  MEMORY_E on dynamic memory allocation failure.
6247 * @return  SHAKE-256 error return code on digest failure.
6248 */
6249static int slhdsakey_fors_pk_from_sig_c(SlhDsaKey* key, const byte* sig_fors,
6250    const word16* indices, const byte* pk_seed, word32* adrs, byte* pk_fors)
6251{
6252    int ret = 0;
6253    int i = 0;
6254    int j;
6255    byte n = key->params->n;
6256    byte a = key->params->a;
6257    byte k = key->params->k;
6258    WC_DECLARE_VAR(node, byte, SLHDSA_MAX_INDICES_SZ * SLHDSA_MAX_N, key->heap);
6259
6260    (void)pk_fors;
6261
6262    WC_ALLOC_VAR_EX(node, byte, SLHDSA_MAX_INDICES_SZ * SLHDSA_MAX_N, key->heap,
6263        DYNAMIC_TYPE_SLHDSA, ret = MEMORY_E);
6264    if (ret == 0) {
6265        /* Step 2: For all indices: */
6266        for (i = 0; i < k; i++) {
6267            /* Step 5: Calculate index ...  */
6268            word32 idx = ((word32)i << a) + indices[i];
6269
6270            /* Step 4: Set tree height for address.  */
6271            HA_SetTreeHeight(adrs, 0);
6272            /* Step 5: Set tree index for address.  */
6273            HA_SetTreeIndex(adrs, idx);
6274            /* Step 6: Compute node from public key seed, address and value. */
6275            ret = HASH_F(key, pk_seed, adrs, sig_fors, n, node + i * n);
6276            if (ret != 0) {
6277                break;
6278            }
6279            /* Step 7: Move to authentication nodes. */
6280            sig_fors += n;
6281
6282            /* Step 8: For all heights: */
6283            for (j = 0; j < a; j++) {
6284                /* Step 10: Calculate side ... */
6285                word32 bit = idx & 1;
6286
6287                /* Step 11/14: Update tree index value ... */
6288                idx >>= 1;
6289                /* Step 9: Set tree height. */
6290                HA_SetTreeHeight(adrs, j + 1);
6291                /* Step 11/14: Set tree index. */
6292                HA_SetTreeIndex(adrs, idx);
6293                /* Step 10: Check which side node is on. */
6294                if (bit == 0) {
6295                    /* Step 12: Hash node || auth node. */
6296                    ret = HASH_H_2(key, pk_seed, adrs, node + i * n,
6297                        sig_fors, n, node + i * n);
6298                }
6299                else {
6300                    /* Step 15: Hash auth node || node. */
6301                    ret = HASH_H_2(key, pk_seed, adrs, sig_fors,
6302                        node + i * n, n, node + i * n);
6303                }
6304                if (ret != 0) {
6305                    break;
6306                }
6307                /* Move on to next authentication node. */
6308                sig_fors += n;
6309            }
6310            if (ret != 0) {
6311                break;
6312            }
6313        }
6314    }
6315    if (ret == 0) {
6316        /* Step 24: Add more root nodes to hash ... */
6317        ret = HASH_T_UPDATE(key, node, (word32)i * n);
6318    }
6319
6320    WC_FREE_VAR_EX(node, key->heap, DYNAMIC_TYPE_SLHDSA);
6321    return ret;
6322}
6323#else
6324/* Compute FORS public key from FORS signature.
6325 *
6326 * Update hash one node at a time to save stack.
6327 *
6328 * FIPS 205. Section 8.4 Algorithm 17.
6329 * fors_pkFromSig(SIGFORS, md, PK.seed, ADRS)
6330 *  ...
6331 *   2: for i from 0 to k - 1 do
6332 *   3:     sk <- SIGFORS.getSK(i)
6333 *                           > SIGFORS [i . (a + 1) . n : (i . (a + 1) + 1) . n]
6334 *   4:     ADRS.setTreeHeight(0)                                 > compute leaf
6335 *   5:     ADRS.setTreeIndex(i . 2^a + indices[i])
6336 *   6:     node[0] <- F(PK.seed, ADRS, sk)
6337 *   7:     auth <- SIGFORS.getAUTH(i)
6338 *                     > SIGFORS [(i . (a + 1) + 1) . n : (i + 1) . (a + 1) . n]
6339 *   8:     for j from 0 to a - 1 do           > compute root from leaf and AUTH
6340 *   9:         ADRS.setTreeHeight(j + 1)
6341 *  10:         if lower(indices[i]/(2^j)) is even then
6342 *  11:             ADRS.setTreeIndex(ADRS.getTreeIndex()/2)
6343 *  12:             node[1] <- H(PK.seed, ADRS, node[0] || auth[i])
6344 *  13:         else
6345 *  14:             ADRS.setTreeIndex((ADRS.getTreeIndex() - 1)/2)
6346 *  15:             node[1] <- H(PK.seed, ADRS, auth[j] || node[0])
6347 *  16:         end if
6348 *  17:         node[0] <- node[1]
6349 *  18:     end for
6350 *  19:     root[i] <- node[0]
6351 *  20: end for
6352 * ...
6353 *  24: pk <- Tk(PK.seed, forspkADRS, root)        > compute the FORS public key
6354 * ...
6355 *
6356 * @param [in]  key       SLH-DSA key.
6357 * @param [in]  sig_fors  FORS signature.
6358 * @param [in]  indices   Base 2^a values from message digest.
6359 * @param [in]  pk_seed   Public key seed.
6360 * @param [in]  adrs      HashAddress.
6361 * @param [out] node      Root node of ith tree.
6362 * @return  0 on success.
6363 * @return  MEMORY_E on dynamic memory allocation failure.
6364 * @return  SHAKE-256 error return code on digest failure.
6365 */
6366static int slhdsakey_fors_pk_from_sig_c(SlhDsaKey* key, const byte* sig_fors,
6367    const word16* indices, const byte* pk_seed, word32* adrs, byte* node)
6368{
6369    int ret;
6370    int i;
6371    int j;
6372    byte n = key->params->n;
6373    byte a = key->params->a;
6374    byte k = key->params->k;
6375
6376    /* Step 2: For all indices: */
6377    for (i = 0; i < k; i++) {
6378        /* Step 5: Calculate index ...  */
6379        word32 idx = ((word32)i << a) + indices[i];
6380
6381        /* Step 4: Set tree height for address.  */
6382        HA_SetTreeHeight(adrs, 0);
6383        /* Step 5: Set tree index for address.  */
6384        HA_SetTreeIndex(adrs, idx);
6385        /* Step 6: Compute node from public key seed, address and value. */
6386        ret = HASH_F(key, pk_seed, adrs, sig_fors, n, node);
6387        if (ret != 0) {
6388            break;
6389        }
6390        /* Step 7: Move to authentication nodes. */
6391        sig_fors += n;
6392
6393        /* Step 8: For all heights: */
6394        for (j = 0; j < a; j++) {
6395            /* Step 10: Calculate side ... */
6396            word32 bit = idx & 1;
6397
6398            /* Step 11/14: Update tree index value ... */
6399            idx >>= 1;
6400            /* Step 9: Set tree height. */
6401            HA_SetTreeHeight(adrs, j + 1);
6402            /* Step 11/14: Set tree index. */
6403            HA_SetTreeIndex(adrs, idx);
6404            /* Step 10: Check which side node is on. */
6405            if (bit == 0) {
6406                /* Step 12: Hash node || auth node. */
6407                ret = HASH_H_2(key, pk_seed, adrs, node, sig_fors, n,
6408                    node);
6409            }
6410            else {
6411                /* Step 15: Hash auth node || node. */
6412                ret = HASH_H_2(key, pk_seed, adrs, sig_fors, node, n,
6413                    node);
6414            }
6415            if (ret != 0) {
6416                break;
6417            }
6418            /* Move on to next authentication node. */
6419            sig_fors += n;
6420        }
6421        if (ret == 0) {
6422            /* Step 24: Add root node to hash ... */
6423            ret = HASH_T_UPDATE(key, node, n);
6424        }
6425        if (ret != 0) {
6426            break;
6427        }
6428    }
6429
6430    return ret;
6431}
6432#endif
6433
6434/* Compute FORS public key from FORS signature.
6435 *
6436 * 4 hashes computed simultaneously.
6437 *
6438 * FIPS 205. Section 8.4 Algorithm 17.
6439 * fors_pkFromSig(SIGFORS, md, PK.seed, ADRS)
6440 *   1: indices <- base_2b(md, a, k)
6441 *  ...
6442 *  21: forspkADRS <- ADRS    > copy address to create a FORS public-key address
6443 *  22: forspkADRS.setTypeAndClear(FORS_ROOTS)
6444 *  23: forspkADRS.setKeyPairAddress(ADRS.getKeyPairAddress())
6445 *  24: pk <- Tk(PK.seed, forspkADRS, root)        > compute the FORS public key
6446 *  25: return pk
6447 *
6448 * @param [in]  key       SLH-DSA key.
6449 * @param [in]  sig_fors  FORS signature.
6450 * @param [in]  md        Message digest.
6451 * @param [in]  pk_seed   Public key seed.
6452 * @param [in]  addr      Encoded HashAddress.
6453 * @param [out] pk_fors   FORS public key form signature.
6454 * @return  0 on success.
6455 * @return  MEMORY_E on dynamic memory allocation failure.
6456 * @return  SHAKE-256 error return code on digest failure.
6457 */
6458static int slhdsakey_fors_pk_from_sig(SlhDsaKey* key, const byte* sig_fors,
6459    const byte* md, const byte* pk_seed, word32* adrs, byte* pk_fors)
6460{
6461    int ret;
6462    word16 indices[SLHDSA_MAX_INDICES_SZ];
6463    HashAddress forspk_adrs;
6464    byte n = key->params->n;
6465    byte a = key->params->a;
6466    byte k = key->params->k;
6467    int hash_t_started = 0;
6468
6469    /* Step 1: Get indices from byte array. */
6470    slhdsakey_base_2b(md, a, k, indices);
6471
6472    /* Step 21: Create address to FORS roots */
6473    HA_Copy(forspk_adrs, adrs);
6474    /* Steps 22-23: Set type and clear all but key pair address. */
6475    HA_SetTypeAndClearNotKPA(forspk_adrs, HA_FORS_ROOTS);
6476    /* Step 24: Add public key seed and FORS roots address to hash ... */
6477    ret = HASH_T_START_ADDR(key, pk_seed, forspk_adrs, n);
6478
6479    if (ret == 0) {
6480        hash_t_started = 1;
6481    }
6482
6483    /* Steps 2-20: Compute roots and add to hash. */
6484#if defined(USE_INTEL_SPEEDUP) && !defined(WOLFSSL_WC_SLHDSA_SMALL)
6485    if ((ret == 0) && !SLHDSA_IS_SHA2(key->params->param) &&
6486            IS_INTEL_AVX2(cpuid_flags) &&
6487            (SAVE_VECTOR_REGISTERS2() == 0)) {
6488        ret = slhdsakey_fors_pk_from_sig_x4(key, sig_fors, indices, pk_seed,
6489            adrs);
6490        RESTORE_VECTOR_REGISTERS();
6491    }
6492    else
6493#endif
6494    if (ret == 0) {
6495        ret = slhdsakey_fors_pk_from_sig_c(key, sig_fors, indices, pk_seed,
6496            adrs, pk_fors);
6497    }
6498
6499    if (ret == 0) {
6500        /* Step 24. Compute FORS public key. */
6501        ret = HASH_T_FINAL(key, pk_fors, n);
6502    }
6503
6504    if (hash_t_started) {
6505        HASH_T_FREE(key);
6506    }
6507
6508    return ret;
6509}
6510
6511/******************************************************************************
6512 * SLH-DSA API
6513 ******************************************************************************/
6514
6515/* Initialize an SLH-DSA key.
6516 *
6517 * @param [in] key    SLH-DSA key.
6518 * @param [in] param  SLH-DSA parameter set to use.
6519 * @param [in] heap   Dynamic memory allocation hint.
6520 * @param [in] devId  Device Id.
6521 * @return  0 on success.
6522 * @return  BAD_FUNC_ARG when key is NULL.
6523 * @return  NOT_COMPILED_IN when parameter set not compiled in.
6524 * @return  SHAKE-256 error return code on digest initialization failure.
6525 */
6526int wc_SlhDsaKey_Init(SlhDsaKey* key, enum SlhDsaParam param, void* heap,
6527    int devId)
6528{
6529    int ret = 0;
6530    int idx = -1;
6531
6532    /* Validate parameters. */
6533    if (key == NULL) {
6534        ret = BAD_FUNC_ARG;
6535    }
6536    if (ret == 0) {
6537        int i;
6538
6539        /* Find parameters in available parameter list. */
6540        for (i = 0; i < SLHDSA_PARAM_LEN; i++) {
6541            if (param == SlhDsaParams[i].param) {
6542                idx = i;
6543                break;
6544            }
6545        }
6546        if (idx == -1) {
6547            /* Parameter set not compiled in.  */
6548            ret = NOT_COMPILED_IN;
6549        }
6550    }
6551    if (ret == 0) {
6552        /* Zeroize key. */
6553        XMEMSET(key, 0, sizeof(SlhDsaKey));
6554
6555        /* Set the parameters into key early so SLHDSA_IS_SHA2 works. */
6556        key->params = &SlhDsaParams[idx];
6557        /* Set heap hint to use with all allocations. */
6558        key->heap = heap;
6559    #ifdef WOLF_CRYPTO_CB
6560        /* Set device id. */
6561        key->devId = devId;
6562    #endif
6563
6564#ifdef WOLFSSL_SLHDSA_SHA2
6565        if (SLHDSA_IS_SHA2(param)) {
6566            /* Initialize SHA2 hash objects. */
6567            ret = wc_InitSha256(&key->hash.sha2.sha256);
6568            if (ret == 0)
6569                key->hash.sha2.sha256_inited = 1;
6570            if ((ret == 0) && (key->params->n > 16)) {
6571                ret = wc_InitSha512(&key->hash.sha2.sha512);
6572                if (ret == 0)
6573                    key->hash.sha2.sha512_inited = 1;
6574            }
6575        }
6576        else
6577#endif
6578        {
6579            /* Initialize SHAKE-256 objects. */
6580            ret = wc_InitShake256(&key->hash.shk.shake, key->heap,
6581                INVALID_DEVID);
6582            if (ret == 0) {
6583                ret = wc_InitShake256(&key->hash.shk.shake2, key->heap,
6584                    INVALID_DEVID);
6585            }
6586        }
6587    }
6588    (void)devId;
6589
6590#if defined(USE_INTEL_SPEEDUP)
6591    /* Ensure the CPU features are known. */
6592    cpuid_get_flags_ex(&cpuid_flags);
6593#endif
6594
6595    return ret;
6596}
6597
6598/* Free the SLH-DSA key.
6599 *
6600 * @param [in] key  SLH-DSA key. Cannot be used after this call.
6601 */
6602void wc_SlhDsaKey_Free(SlhDsaKey* key)
6603{
6604    /* Check we have a valid key to free. */
6605    if ((key != NULL) && (key->params != NULL)) {
6606        /* Ensure the private key data is zeroized. */
6607        ForceZero(key->sk, (size_t)key->params->n * 2);
6608#ifdef WOLFSSL_SLHDSA_SHA2
6609        if (SLHDSA_IS_SHA2(key->params->param)) {
6610            /* Dispose of the SHA2 hash objects. */
6611            if (key->hash.sha2.sha256_inited) {
6612                wc_Sha256Free(&key->hash.sha2.sha256);
6613                key->hash.sha2.sha256_inited = 0;
6614            }
6615            if (key->hash.sha2.sha256_2_inited) {
6616                wc_Sha256Free(&key->hash.sha2.sha256_2);
6617                key->hash.sha2.sha256_2_inited = 0;
6618            }
6619            if (key->hash.sha2.sha256_mid_inited) {
6620                wc_Sha256Free(&key->hash.sha2.sha256_mid);
6621                key->hash.sha2.sha256_mid_inited = 0;
6622            }
6623            if (key->hash.sha2.sha512_inited) {
6624                wc_Sha512Free(&key->hash.sha2.sha512);
6625                key->hash.sha2.sha512_inited = 0;
6626            }
6627            if (key->hash.sha2.sha512_2_inited) {
6628                wc_Sha512Free(&key->hash.sha2.sha512_2);
6629                key->hash.sha2.sha512_2_inited = 0;
6630            }
6631            if (key->hash.sha2.sha512_mid_inited) {
6632                wc_Sha512Free(&key->hash.sha2.sha512_mid);
6633                key->hash.sha2.sha512_mid_inited = 0;
6634            }
6635        }
6636        else
6637#endif
6638        {
6639            /* Dispose of the SHAKE-256 objects. */
6640            wc_Shake256_Free(&key->hash.shk.shake2);
6641            wc_Shake256_Free(&key->hash.shk.shake);
6642        }
6643    }
6644}
6645
6646/* Set the HashAddress based on message digest data.
6647 *
6648 * FIPS 205. Section 9.2. Algorithm 19.
6649 * slh_sign_internal(M, SK, addrnd)
6650 *   1: ADRS <- toByte(0, 32)
6651 *  ...
6652 *   7: tmp_idxtree <- digest [upper(k.a / 8) : upper(k.a / 8) +
6653 *                                              upper((h - h/d) / 8)]
6654 *                                             > next upper((h - h/d) / 8) bytes
6655 *   8: tmp_idxleaf <- digest [upper(k.a / 8) + upper((h - h/d) / 8) :
6656 *                             upper(k.a / 8) + upper((h - h/d) / 8) +
6657 *                             upper(h / 8d) ]
6658 *                                                    > next upper(h / 8d) bytes
6659 *   9: idxtree <- toInt(tmp_idxtree, upper((h-h/d) / 8)) mod 2^(h-h/d)
6660 *  10: idxleaf <- toInt(tmp_idxleaf, upper(h / 8d)) mode 2^(h/d)
6661 *  11: ADRS.setTreeAddress(idxtree)
6662 *  12: ADRS.setTypeAndClear(FORS_TREE)
6663 *  13: ADRS.setKeyPairAddress(idxleaf)
6664 *  ...
6665 *
6666 * FIPS 205. Section 9.3. Algorithm 20.
6667 * slh_verify_internal(M, SIG, PK)
6668 *   4: ADRS <- toByte(0, 32)
6669 *  ...
6670 *  10: tmp_idxtree <- digest [upper(k.a / 8) : upper(k.a / 8) +
6671 *                                              upper((h - h/d) / 8)]
6672 *                                             > next upper((h - h/d) / 8) bytes
6673 *  11: tmp_idxleaf <- digest [upper(k.a / 8) + upper((h - h/d) / 8) :
6674 *                             upper(k.a / 8) + upper((h - h/d) / 8) +
6675 *                             upper(h / 8d) ]
6676 *                                                    > next upper(h / 8d) bytes
6677 *  12: idxtree <- toInt(tmp_idxtree, upper((h-h/d) / 8)) mod 2^(h-h/d)
6678 *  13: idxleaf <- toInt(tmp_idxleaf, upper(h / 8d)) mode 2^(h/d)
6679 *  14: ADRS.setTreeAddress(idxtree)
6680 *  15: ADRS.setTypeAndClear(FORS_TREE)
6681 *  16: ADRS.setKeyPairAddress(idxleaf)
6682 *  ...
6683 *
6684 * @param [in]  key   SLH-DSA key.
6685 * @param [in]  md    Message digest.
6686 * @param [out] adrs  FORS tree HashAddress.
6687 * @param [out] t     Tree index as 3 32-bit integers.
6688 * @param [out] l     Tree leaf index.
6689 */
6690static void slhdsakey_set_ha_from_md(SlhDsaKey* key, const byte* md,
6691    HashAddress adrs, word32* t, word32* l)
6692{
6693    const byte* p;
6694    int bits;
6695
6696    /* Step 1/4: Set address to all zeroes. */
6697    HA_Init(adrs);
6698    /* Step 7/10: Get pointer to tree index data. */
6699    p = md + key->params->dl1 + (key->params->dl2 - 8);
6700    /* Step 9/12: Convert tree index data to an integer ... */
6701    t[0] = 0;
6702    ato32(p + 0, &t[1]);
6703    ato32(p + 4, &t[2]);
6704    /* Step 9/12: Mask off any extra high bits. */
6705    bits = key->params->h  - (key->params->h / key->params->d);
6706    if (bits < 64) {
6707        t[1] &= ((word32)1U << (bits - 32)) - 1U;
6708    }
6709
6710    /* Step 8/11: Get pointer to tree leaf index data. */
6711    p = md + key->params->dl1 + key->params->dl2 + (key->params->dl3 - 4);
6712    /* Step 10/13: Convert tree leaf index data to an integer ... */
6713    ato32(p, l);
6714    /* Step 10/13: Mask off any extra high bits. */
6715    bits = key->params->h / key->params->d;
6716    *l &= ((word32)1U << bits) - 1U;
6717
6718    /* Step 11/14: Set the tree index into address. */
6719    HA_SetTreeAddress(adrs, t);
6720    /* Step 12/15: Set type of address and clear except key pair address. */
6721    HA_SetTypeAndClearNotKPA(adrs, HA_FORS_TREE);
6722    /* Step 13/16: Set key pair address. */
6723    HA_SetKeyPairAddress(adrs, *l);
6724}
6725
6726#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
6727/* Generate an SLH-DSA key with a random number generator.
6728 *
6729 * FIPS 205. Section 10.1. Algorithm 21.
6730 * slh_keygen()
6731 *   1: SK.seed <-$- Bn     > set SK.seed, SK.prf, and PK.seed to random n-byte
6732 *   2: SK.prf <-$- Bn          > strings using an approved random bit generator
6733 *   3: PK.seed <-$- Bn
6734 *   4: if SK.seed = NULL or SK.prf = NULL or PK.seed = NULL then
6735 *   5:     return falsity
6736 *                 > return an error indication if random bit generation failed
6737 *   6: end if
6738 *   7: return slh_keygen_internal(SK.seed, SK.prf, PK.seed)
6739 *
6740 * @param [in] key  SLH-DSA key.
6741 * @param [in] rng  Random number generator.
6742 * @return  0 on success.
6743 * @return  RNG error code when random number generation fails.
6744 * @return  MEMORY_E on dynamic memory allocation failure.
6745 * @return  SHAKE-256 error return code on digest failure.
6746 */
6747int wc_SlhDsaKey_MakeKey(SlhDsaKey* key, WC_RNG* rng)
6748{
6749    int ret = 0;
6750
6751    /* Validate parameters. */
6752    if ((key == NULL) || (key->params == NULL) || (rng == NULL)) {
6753        ret = BAD_FUNC_ARG;
6754    }
6755    if (ret == 0) {
6756        /* Steps 1-5: Generate the 3 random hashes. */
6757        ret = wc_RNG_GenerateBlock(rng, key->sk, 3U * key->params->n);
6758    }
6759    if (ret == 0) {
6760        byte n = key->params->n;
6761
6762        /* Step 7: Make the key with the random  */
6763        ret = wc_SlhDsaKey_MakeKeyWithRandom(key, key->sk, n, key->sk + n, n,
6764            key->sk + 2 * n, n);
6765    }
6766
6767    return ret;
6768}
6769
6770/* Generate an SLH-DSA key pair.
6771 *
6772 * FIPS 205. Section 9.1. Algorithm 18.
6773 * slh_keygen_internal(SK.seed, SK.prf, PK.seed)
6774 *   1: ADRS <- toByte(0, 32)
6775 *                        > generate the public key for the top-level XMSS tree
6776 *   2: ADRS.setLayerAddress(d - 1)
6777 *   3: PK.root <- xmss_node(SK.seed, 0, h' , PK.seed, ADRS)
6778 *   4: return ( (SK.seed, SK.prf, PK.seed, PK.root), (PK.seed, PK.root) )
6779 *
6780 * @param [in] key          SLH-DSA key.
6781 * @param [in] sk_seed      Private key seed.
6782 * @param [in] sk_seed_len  Length of private key seed.
6783 * @param [in] sk_prf       Private key PRF seed.
6784 * @param [in] sk_prf_len   Length of private key PRF seed.
6785 * @param [in] pk_seed      Public key seed.
6786 * @param [in] pk_seed_len  Length of public key seed.
6787 * @return  0 on success.
6788 * @return  BAD_FUNC_ARG when key or key's parameters is NULL.
6789 * @return  BAD_FUNC_ARG when sk_seed is NULL or length is not n.
6790 * @return  BAD_FUNC_ARG when sk_prf is NULL or length is not n.
6791 * @return  BAD_FUNC_ARG when pk_seed is NULL or length is not n.
6792 * @return  MEMORY_E on dynamic memory allocation failure.
6793 * @return  SHAKE-256 error return code on digest failure.
6794 */
6795int wc_SlhDsaKey_MakeKeyWithRandom(SlhDsaKey* key, const byte* sk_seed,
6796    word32 sk_seed_len, const byte* sk_prf, word32 sk_prf_len,
6797    const byte* pk_seed, word32 pk_seed_len)
6798{
6799    int ret = 0;
6800
6801    /* Validate parameters. */
6802    if ((key == NULL) || (key->params == NULL)) {
6803        ret = BAD_FUNC_ARG;
6804    }
6805    /* Ensure private key seed is passed in and is the right length. */
6806    else if ((sk_seed == NULL) || (sk_seed_len != key->params->n)) {
6807        ret = BAD_FUNC_ARG;
6808    }
6809    /* Ensure public key PRF seed is passed in and is the right length. */
6810    else if ((sk_prf == NULL) || (sk_prf_len != key->params->n)) {
6811        ret = BAD_FUNC_ARG;
6812    }
6813    /* Ensure public key seed is passed in and is the right length. */
6814    else if ((pk_seed == NULL) || (pk_seed_len != key->params->n)) {
6815        ret = BAD_FUNC_ARG;
6816    }
6817    else {
6818        byte n = key->params->n;
6819        HashAddress adrs;
6820
6821        /* Step 4: Copy the seeds into the key if they didn't come from the key.
6822         */
6823        if (sk_seed != key->sk) {
6824            XMEMCPY(key->sk        , sk_seed, n);
6825            XMEMCPY(key->sk +     n, sk_prf , n);
6826            XMEMCPY(key->sk + 2 * n, pk_seed, n);
6827        }
6828
6829#ifdef WOLFSSL_SLHDSA_SHA2
6830        /* Pre-compute SHA2 midstates now that PK.seed is set. */
6831        if (SLHDSA_IS_SHA2(key->params->param)) {
6832            ret = slhdsakey_precompute_sha2_midstates(key);
6833        }
6834        if (ret != 0) {
6835            return ret;
6836        }
6837#endif
6838
6839        /* Step 1: Set address to all zeroes. */
6840        HA_Init(adrs);
6841        /* Step 2: Set the address layer to the top of the subtree. */
6842        HA_SetLayerAddress(adrs, key->params->d - 1);
6843        /* Step 3: Compute the root node. */
6844        ret = slhdsakey_xmss_node(key, sk_seed, 0, key->params->h_m, pk_seed,
6845             adrs, &key->sk[3 * n]);
6846        if (ret == 0) {
6847            key->flags = WC_SLHDSA_FLAG_BOTH_KEYS;
6848        }
6849    }
6850
6851    return ret;
6852}
6853
6854/* Generate an SLH-DSA signature.
6855 *
6856 * FIPS 205. Section 9.2. Algorithm 19.
6857 * slh_sign_internal(M, SK, addrnd)
6858 *  ...
6859 *                                              upper((h - h/d) / 8)]
6860 *                                             > next upper((h - h/d) / 8) bytes
6861 *   8: tmp_idxleaf <- digest [upper(k.a / 8) + upper((h - h/d) / 8) :
6862 *                             upper(k.a / 8) + upper((h - h/d) / 8) +
6863 *                             upper(h / 8d) ]
6864 *                                                    > next upper(h / 8d) bytes
6865 *   9: idxtree <- toInt(tmp_idxtree, upper((h-h/d) / 8)) mod 2^(h-h/d)
6866 *  10: idxleaf <- toInt(tmp_idxleaf, upper(h / 8d)) mode 2^(h/d)
6867 *  11: ADRS.setTreeAddress(idxtree)
6868 *  12: ADRS.setTypeAndClear(FORS_TREE)
6869 *  13: ADRS.setKeyPairAddress(idxleaf)
6870 *  14: SIGFORS <- fors_sign(md, SK.seed, PK.seed, ADRS)
6871 *  15: SIG <- SIG || SIGFORS
6872 *  16: PKFORS <- fors_pkFromSig(SIGFORS, md, PK.seed, ADRS)      > get FORS key
6873 *  17: SIGHT <- ht_sign(PKFORS , SK.seed, PK.seed, idxtree , idxleaf )
6874 *  18: SIG <- SIG || SIGHT
6875 *  19: return SIG
6876 *
6877 * @param [in]  key  SLH-DSA key.
6878 * @param [in]  md   Message digest.
6879 * @param [out] sig  Signature buffer.
6880 * @return  0 on success.
6881 * @return  MEMORY_E on dynamic memory allocation failure.
6882 * @return  SHAKE-256 error return code on digest failure.
6883 */
6884static int slhdsakey_sign(SlhDsaKey* key, byte* md, byte* sig)
6885{
6886    int ret;
6887    HashAddress adrs;
6888    word32 t[3];
6889    word32 l;
6890    byte pk_fors[SLHDSA_MAX_N];
6891    byte n = key->params->n;
6892
6893    /* Steps 1, 7-13: Set address based on message digest. */
6894    slhdsakey_set_ha_from_md(key, md, adrs, t, &l);
6895
6896    /* Step 14: FORS sign message. */
6897    ret = slhdsakey_fors_sign(key, md, key->sk, key->sk + 2 * n, adrs, sig);
6898    if (ret == 0) {
6899        /* Step 16: FORS public key from signature. */
6900        ret = slhdsakey_fors_pk_from_sig(key, sig, md, key->sk + 2 * n, adrs,
6901            pk_fors);
6902        /* Step 15: Move over signature data. */
6903        sig += key->params->k * (1 + key->params->a) * n;
6904    }
6905    if (ret == 0) {
6906        /* Steps 17-18: Hypertree sign FORS public key. */
6907        ret = slhdsakey_ht_sign(key, pk_fors, key->sk, key->sk + 2 * n, t, l,
6908            sig);
6909    }
6910
6911    return ret;
6912}
6913
6914/* Lower-level sign: slh_sign_internal(M, SK, addrnd).
6915 *
6916 * Takes M directly and performs PRF_msg, H_msg, and the FORS + hypertree
6917 * signing -- Algorithm 19 without the M' construction of Algorithm 22.
6918 *
6919 * FIPS 205. Section 9.2. Algorithm 19.
6920 * slh_sign_internal(M, SK, addrnd)
6921 *   2: opt_rand <- addrnd
6922 *   3: R <- PRFmsg(SK.prf, opt_rand, M)
6923 *   4: SIG <- R
6924 *   5: digest <- Hmsg(R, PK.seed, PK.root, M)
6925 *   6: md <- digest[0 : upper(k*a / 8)]
6926 *  ...
6927 *
6928 * @param [in]      key     SLH-DSA key (private key must be set).
6929 * @param [in]      m       Message (goes directly to PRF_msg and H_msg).
6930 * @param [in]      mSz     Length of message in bytes.
6931 * @param [out]     sig     Buffer to hold signature.
6932 * @param [in, out] sigSz   On in, buffer length. On out, signature length.
6933 * @param [in]      addRnd  opt_rand (PK.seed for deterministic).
6934 * @return  0 on success.
6935 */
6936static int slhdsakey_sign_internal_msg(SlhDsaKey* key, const byte* m,
6937    word32 mSz, byte* sig, word32* sigSz, const byte* addRnd)
6938{
6939    int ret = 0;
6940
6941    /* Validate parameters. */
6942    if ((key == NULL) || (key->params == NULL) || (m == NULL) ||
6943            (sig == NULL) || (sigSz == NULL) || (addRnd == NULL)) {
6944        ret = BAD_FUNC_ARG;
6945    }
6946    else if (*sigSz < key->params->sigLen) {
6947        ret = BAD_LENGTH_E;
6948    }
6949    else if ((key->flags & WC_SLHDSA_FLAG_PRIVATE) == 0) {
6950        ret = MISSING_KEY;
6951    }
6952    if (ret == 0) {
6953        byte md[SLHDSA_MAX_MD];
6954        byte n = key->params->n;
6955
6956#ifdef WOLFSSL_SLHDSA_SHA2
6957        if (SLHDSA_IS_SHA2(key->params->param)) {
6958            /* SHA2: PRF_msg = Trunc_n(HMAC(SK.prf, opt_rand || M)).
6959             * Internal interface: no M' header, pass whole M directly. */
6960            ret = slhdsakey_prf_msg_sha2(key, key->sk + n, addRnd,
6961                NULL, NULL, 0, m, mSz, n, sig);
6962            if (ret == 0) {
6963                /* SHA2: H_msg via MGF1. No header for internal interface. */
6964                ret = slhdsakey_h_msg_sha2(key, sig,
6965                    NULL, NULL, 0, m, mSz,
6966                    md, (word32)key->params->dl1 + key->params->dl2 +
6967                    key->params->dl3);
6968                sig += n;
6969            }
6970        }
6971        else
6972#endif
6973        {
6974            /* SHAKE: PRF_msg = SHAKE256(SK.prf || opt_rand || M, 8n). */
6975            {
6976                wc_Shake tmpShake;
6977                ret = wc_InitShake256(&tmpShake, NULL, INVALID_DEVID);
6978                if (ret == 0) ret = wc_Shake256_Update(&tmpShake, key->sk + n, n);
6979                if (ret == 0) ret = wc_Shake256_Update(&tmpShake, addRnd, n);
6980                if (ret == 0) ret = wc_Shake256_Update(&tmpShake, m, mSz);
6981                if (ret == 0) ret = wc_Shake256_Final(&tmpShake, sig, n);
6982                wc_Shake256_Free(&tmpShake);
6983            }
6984            /* SHAKE: H_msg = SHAKE256(R || PK.seed || PK.root || M, ...). */
6985            if (ret == 0) {
6986                ret = wc_InitShake256(&key->hash.shk.shake, NULL, INVALID_DEVID);
6987            }
6988            if (ret == 0) {
6989                ret = wc_Shake256_Update(&key->hash.shk.shake, sig, n);
6990                sig += n;
6991            }
6992            if (ret == 0) {
6993                ret = wc_Shake256_Update(&key->hash.shk.shake,
6994                    key->sk + 2U * n, 2U * n);
6995            }
6996            if (ret == 0) {
6997                ret = wc_Shake256_Update(&key->hash.shk.shake, m, mSz);
6998            }
6999            if (ret == 0) {
7000                ret = wc_Shake256_Final(&key->hash.shk.shake, md,
7001                    (word32)key->params->dl1 + key->params->dl2 +
7002                    key->params->dl3);
7003            }
7004        }
7005        if (ret == 0) {
7006            ret = slhdsakey_sign(key, md, sig);
7007        }
7008        if (ret == 0) {
7009            *sigSz = key->params->sigLen;
7010        }
7011    }
7012
7013    return ret;
7014}
7015
7016/* Upper-level sign: construct M' from ctx + msg, then call internal.
7017 *
7018 * FIPS 205. Section 10.2.1. Algorithm 22.
7019 * slh_sign(M, ctx, SK)
7020 *   8: M' <- toByte(0, 1) || toByte(|ctx|, 1) || ctx || M
7021 *   9: SIG <- slh_sign_internal(M', SK, addrnd)
7022 *
7023 * @param [in]      key    SLH-DSA key.
7024 * @param [in]      ctx    Context of signing.
7025 * @param [in]      ctxSz  Length of context in bytes.
7026 * @param [in]      msg    Message to sign.
7027 * @param [in]      msgSz  Length of message in bytes.
7028 * @param [out]     sig    Buffer to hold signature.
7029 * @param [in, out] sigSz  On in, length of signature buffer.
7030 *                         On out, length of signature data.
7031 * @param [in]      addRnd opt_rand (PK.seed for deterministic, random otherwise).
7032 * @return  0 on success.
7033 * @return  BAD_FUNC_ARG when key, key's parameters, msg, sig, sigSz or addRnd
7034 *          is NULL.
7035 * @return  BAD_FUNC_ARG when ctx is NULL but ctx length is greater than 0.
7036 * @return  BAD_LENGTH_E when sigSz is less than required signature length.
7037 * @return  MISSING_KEY when private key not set.
7038 * @return  MEMORY_E on dynamic memory allocation failure.
7039 * @return  SHAKE-256 error return code on digest failure.
7040 */
7041static int slhdsakey_sign_external(SlhDsaKey* key, const byte* ctx, byte ctxSz,
7042    const byte* msg, word32 msgSz, byte* sig, word32* sigSz,
7043    const byte* addRnd)
7044{
7045    int ret = 0;
7046
7047    /* Validate parameters. */
7048    if ((key == NULL) || (key->params == NULL) ||
7049            ((ctx == NULL) && (ctxSz > 0)) || (msg == NULL) || (sig == NULL) ||
7050            (sigSz == NULL)) {
7051        ret = BAD_FUNC_ARG;
7052    }
7053    /* Check sig buffer is large enough to hold generated signature. */
7054    else if (*sigSz < key->params->sigLen) {
7055        ret = BAD_LENGTH_E;
7056    }
7057    /* Alg 22, Step 5: Check addrnd is not NULL. */
7058    else if (addRnd == NULL) {
7059        /* Alg 22, Step 6: Return error. */
7060        ret = BAD_FUNC_ARG;
7061    }
7062    /* Check we have a private key to sign with. */
7063    else if ((key->flags & WC_SLHDSA_FLAG_PRIVATE) == 0) {
7064        ret = MISSING_KEY;
7065    }
7066    if (ret == 0) {
7067        byte md[SLHDSA_MAX_MD];
7068        byte hdr[2];
7069        byte n = key->params->n;
7070
7071        /* Alg 22, Step 8: M' = toByte(0,1) || toByte(|ctx|,1) || ctx || M.
7072         * We stream the M' components into PRF_msg and H_msg. */
7073        hdr[0] = 0;
7074        hdr[1] = ctxSz;
7075
7076#ifdef WOLFSSL_SLHDSA_SHA2
7077        if (SLHDSA_IS_SHA2(key->params->param)) {
7078            /* SHA2: PRF_msg via HMAC. */
7079            ret = slhdsakey_prf_msg_sha2(key, key->sk + n, addRnd, hdr, ctx,
7080                ctxSz, msg, msgSz, n, sig);
7081            if (ret == 0) {
7082                /* SHA2: H_msg via MGF1. */
7083                ret = slhdsakey_h_msg_sha2(key, sig, hdr, ctx, ctxSz, msg,
7084                    msgSz, md, (word32)key->params->dl1 + key->params->dl2 +
7085                    key->params->dl3);
7086                /* Move over randomizer. */
7087                sig += n;
7088            }
7089        }
7090        else
7091#endif
7092        {
7093            /* SHAKE: PRF_msg streaming with M' = hdr || ctx || msg. */
7094            ret = slhdsakey_hash_start(&key->hash.shk.shake, key->sk + n, n);
7095            if (ret == 0) {
7096                ret = slhdsakey_hash_update(&key->hash.shk.shake, addRnd, n);
7097            }
7098            if (ret == 0) {
7099                ret = slhdsakey_hash_update(&key->hash.shk.shake, hdr,
7100                    sizeof(hdr));
7101            }
7102            if ((ret == 0) && (ctxSz > 0)) {
7103                ret = slhdsakey_hash_update(&key->hash.shk.shake, ctx, ctxSz);
7104            }
7105            if (ret == 0) {
7106                ret = slhdsakey_hash_update(&key->hash.shk.shake, msg, msgSz);
7107            }
7108            if (ret == 0) {
7109                ret = slhdsakey_hash_final(&key->hash.shk.shake, sig, n);
7110            }
7111            /* SHAKE: H_msg streaming. */
7112            if (ret == 0) {
7113                ret = slhdsakey_hash_start(&key->hash.shk.shake, sig, n);
7114                sig += n;
7115            }
7116            if (ret == 0) {
7117                ret = slhdsakey_hash_update(&key->hash.shk.shake,
7118                    key->sk + 2U * n, 2U * n);
7119            }
7120            if (ret == 0) {
7121                ret = slhdsakey_hash_update(&key->hash.shk.shake, hdr,
7122                    sizeof(hdr));
7123            }
7124            if ((ret == 0) && (ctxSz > 0)) {
7125                ret = slhdsakey_hash_update(&key->hash.shk.shake, ctx, ctxSz);
7126            }
7127            if (ret == 0) {
7128                ret = slhdsakey_hash_update(&key->hash.shk.shake, msg, msgSz);
7129            }
7130            if (ret == 0) {
7131                ret = slhdsakey_hash_final(&key->hash.shk.shake, md,
7132                    (word32)key->params->dl1 + key->params->dl2 +
7133                    key->params->dl3);
7134            }
7135        }
7136        if (ret == 0) {
7137            /* Alg 19. Steps 7-19 */
7138            ret = slhdsakey_sign(key, md, sig);
7139        }
7140        if (ret == 0) {
7141            /* Return the signature size generated. */
7142            *sigSz = key->params->sigLen;
7143        }
7144    }
7145
7146    return ret;
7147}
7148
7149/* Generate a deterministic SLH-DSA signature.
7150 *
7151 * addrnd is the public key seed.
7152 *
7153 * @param [in]      key    SLH-DSA key.
7154 * @param [in]      ctx    Context of signing.
7155 * @param [in]      ctxSz  Length of context in bytes.
7156 * @param [in]      msg    Message to sign.
7157 * @param [in]      msgSz  Length of message in bytes.
7158 * @param [out]     sig    Buffer to hold signature.
7159 * @param [in, out] sigSz  On in, length of signature buffer.
7160 *                         On out, length of signature data.
7161 * @return  0 on success.
7162 * @return  BAD_FUNC_ARG when key, key's parameters, msg or sig is NULL.
7163 * @return  BAD_FUNC_ARG when ctx is NULL but ctx length is greater than 0.
7164 * @return  BAD_LENGTH_E when sigSz is less than required signature length.
7165 * @return  MISSING_KEY when private key not set.
7166 * @return  MEMORY_E on dynamic memory allocation failure.
7167 * @return  SHAKE-256 error return code on digest failure.
7168 */
7169int wc_SlhDsaKey_SignDeterministic(SlhDsaKey* key, const byte* ctx, byte ctxSz,
7170    const byte* msg, word32 msgSz, byte* sig, word32* sigSz)
7171{
7172    int ret;
7173
7174    /* Validate parameters that will be used in this function. */
7175    if ((key == NULL) || (key->params == NULL)) {
7176        ret = BAD_FUNC_ARG;
7177    }
7178    else {
7179        /* Pure sign. */
7180        ret = slhdsakey_sign_external(key, ctx, ctxSz, msg, msgSz, sig, sigSz,
7181            key->sk + 2 * key->params->n);
7182    }
7183
7184    return ret;
7185}
7186
7187/* Generate a pure SLH-DSA signature.
7188 *
7189 * @param [in]      key     SLH-DSA key.
7190 * @param [in]      ctx     Context of signing.
7191 * @param [in]      ctxSz   Length of context in bytes.
7192 * @param [in]      msg     Message to sign.
7193 * @param [in]      msgSz   Length of message in bytes.
7194 * @param [out]     sig     Buffer to hold signature.
7195 * @param [in, out] sigSz   On in, length of signature buffer.
7196 *                          On out, length of signature data.
7197 * @param [in]      addRnd  Additional random for signature.
7198 * @return  0 on success.
7199 * @return  BAD_FUNC_ARG when key, key's parameters, msg, sig or addrnd is NULL.
7200 * @return  BAD_FUNC_ARG when ctx is NULL but ctx length is greater than 0.
7201 * @return  BAD_LENGTH_E when sigSz is less than required signature length.
7202 * @return  MISSING_KEY when private key not set.
7203 * @return  MEMORY_E on dynamic memory allocation failure.
7204 * @return  SHAKE-256 error return code on digest failure.
7205 */
7206int wc_SlhDsaKey_SignWithRandom(SlhDsaKey* key, const byte* ctx, byte ctxSz,
7207    const byte* msg, word32 msgSz, byte* sig, word32* sigSz, const byte* addRnd)
7208{
7209    /* Pure sign. */
7210    return slhdsakey_sign_external(key, ctx, ctxSz, msg, msgSz, sig, sigSz,
7211        addRnd);
7212}
7213
7214/* Generate a pure SLH-DSA signature with a random number generator.
7215 *
7216 * @param [in]      key     SLH-DSA key.
7217 * @param [in]      ctx     Context of signing.
7218 * @param [in]      ctxSz   Length of context in bytes.
7219 * @param [in]      msg     Message to sign.
7220 * @param [in]      msgSz   Length of message in bytes.
7221 * @param [out]     sig     Buffer to hold signature.
7222 * @param [in, out] sigSz   On in, length of signature buffer.
7223 *                          On out, length of signature data.
7224 * @param [in]      rng     Random number generator.
7225 * @return  0 on success.
7226 * @return  BAD_FUNC_ARG when key, key's parameters, msg, sig, sigSz or rng is
7227 *          NULL.
7228 * @return  BAD_FUNC_ARG when ctx is NULL but ctx length is greater than 0.
7229 * @return  BAD_LENGTH_E when sigSz is less than required signature length.
7230 * @return  MISSING_KEY when private key not set.
7231 * @return  MEMORY_E on dynamic memory allocation failure.
7232 * @return  SHAKE-256 error return code on digest failure.
7233 */
7234int wc_SlhDsaKey_Sign(SlhDsaKey* key, const byte* ctx, byte ctxSz,
7235    const byte* msg, word32 msgSz, byte* sig, word32* sigSz, WC_RNG* rng)
7236{
7237    int ret = 0;
7238    byte addRnd[SLHDSA_MAX_N];
7239
7240    /* Validate parameters before generating random. */
7241    if ((key == NULL) || (key->params == NULL) ||
7242            ((ctx == NULL) && (ctxSz > 0)) || (msg == NULL) || (sig == NULL) ||
7243            (sigSz == NULL) || (rng == NULL)) {
7244        ret = BAD_FUNC_ARG;
7245    }
7246    /* Check sig buffer is large enough to hold generated signature. */
7247    else if (*sigSz < key->params->sigLen) {
7248        ret = BAD_LENGTH_E;
7249    }
7250    /* Check we have a private key to sign with. */
7251    else if ((key->flags & WC_SLHDSA_FLAG_PRIVATE) == 0) {
7252        ret = MISSING_KEY;
7253    }
7254    if (ret == 0) {
7255        /* Generate n bytes of random. */
7256        ret = wc_RNG_GenerateBlock(rng, addRnd, key->params->n);
7257    }
7258    if (ret == 0) {
7259        /* Pure sign. */
7260        ret = wc_SlhDsaKey_SignWithRandom(key, ctx, ctxSz, msg, msgSz, sig,
7261            sigSz, addRnd);
7262    }
7263
7264    ForceZero(addRnd, sizeof(addRnd));
7265
7266    return ret;
7267}
7268
7269/* Sign using the FIPS 205 internal interface (Algorithm 19) -- M' provided
7270 * directly by the caller, deterministic variant (opt_rand = PK.seed).
7271 *
7272 * Used for HashSLH-DSA implementations that build M' externally and for ACVP
7273 * signatureInterface=internal test vectors.
7274 *
7275 * @param [in]      key       SLH-DSA key.
7276 * @param [in]      mprime    M' message (already in internal format).
7277 * @param [in]      mprimeSz  Length of M' in bytes.
7278 * @param [out]     sig       Buffer to hold signature.
7279 * @param [in, out] sigSz     On in, buffer length. On out, signature length.
7280 * @return  0 on success.
7281 * @return  BAD_FUNC_ARG when key, key's parameters, mprime, sig or sigSz is
7282 *          NULL.
7283 * @return  BAD_LENGTH_E when sigSz is less than required signature length.
7284 * @return  MISSING_KEY when private key not set.
7285 * @return  MEMORY_E on dynamic memory allocation failure.
7286 * @return  SHAKE-256 error return code on digest failure.
7287 */
7288int wc_SlhDsaKey_SignMsgDeterministic(SlhDsaKey* key, const byte* mprime,
7289    word32 mprimeSz, byte* sig, word32* sigSz)
7290{
7291    int ret = 0;
7292
7293    if ((key == NULL) || (key->params == NULL) || (mprime == NULL) ||
7294            (sig == NULL) || (sigSz == NULL)) {
7295        ret = BAD_FUNC_ARG;
7296    }
7297    else if (*sigSz < key->params->sigLen) {
7298        ret = BAD_LENGTH_E;
7299    }
7300    else if ((key->flags & WC_SLHDSA_FLAG_PRIVATE) == 0) {
7301        ret = MISSING_KEY;
7302    }
7303    if (ret == 0) {
7304        ret = slhdsakey_sign_internal_msg(key, mprime, mprimeSz, sig, sigSz,
7305            key->sk + 2 * key->params->n);
7306    }
7307
7308    return ret;
7309}
7310
7311/* Sign using the FIPS 205 internal interface (Algorithm 19) -- M' provided
7312 * directly by the caller, with explicit randomness.
7313 *
7314 * Used for HashSLH-DSA implementations that build M' externally and for ACVP
7315 * signatureInterface=internal test vectors.
7316 *
7317 * @param [in]      key       SLH-DSA key.
7318 * @param [in]      mprime    M' message (already in internal format).
7319 * @param [in]      mprimeSz  Length of M' in bytes.
7320 * @param [out]     sig       Buffer to hold signature.
7321 * @param [in, out] sigSz     On in, buffer length. On out, signature length.
7322 * @param [in]      addRnd    opt_rand value.
7323 * @return  0 on success.
7324 * @return  BAD_FUNC_ARG when key, key's parameters, mprime, sig, sigSz or
7325 *          addRnd is NULL.
7326 * @return  BAD_LENGTH_E when sigSz is less than required signature length.
7327 * @return  MISSING_KEY when private key not set.
7328 * @return  MEMORY_E on dynamic memory allocation failure.
7329 * @return  SHAKE-256 error return code on digest failure.
7330 */
7331int wc_SlhDsaKey_SignMsgWithRandom(SlhDsaKey* key, const byte* mprime,
7332    word32 mprimeSz, byte* sig, word32* sigSz, const byte* addRnd)
7333{
7334    int ret = 0;
7335
7336    if ((key == NULL) || (key->params == NULL) || (mprime == NULL) ||
7337            (sig == NULL) || (sigSz == NULL) || (addRnd == NULL)) {
7338        ret = BAD_FUNC_ARG;
7339    }
7340    else if (*sigSz < key->params->sigLen) {
7341        ret = BAD_LENGTH_E;
7342    }
7343    else if ((key->flags & WC_SLHDSA_FLAG_PRIVATE) == 0) {
7344        ret = MISSING_KEY;
7345    }
7346    if (ret == 0) {
7347        ret = slhdsakey_sign_internal_msg(key, mprime, mprimeSz, sig, sigSz,
7348            addRnd);
7349    }
7350
7351    return ret;
7352}
7353
7354#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
7355
7356/* Verify SLH-DSA signature.
7357 *
7358 * FIPS 205. Section 9.3. Algorithm 20.
7359 * slh_verify_internal(M, SIG, PK)
7360 *  ...
7361 *   6: SIGFORS <- SIG.getSIG_FORS()               > SIG[n : (1 + k(1 + a)) . n]
7362 *   7: SIGHT <- SIG.getSIG_HT()
7363 *                  > SIG[(1 + k(1 + a)) . n : (1 + k(1 + a) + h + d . len) . n]
7364 *  ...
7365 *  17: PKFORS <- fors_pkFromSig(SIGFORS, md, PK.seed, ADRS)
7366 *  18: return ht_verify(PKFORS, SIGHT, PK.seed, idxtree, idxleaf, PK.root)
7367 *
7368 * @param [in] key  SLH-DSA key.
7369 * @param [in] md   Message digest.
7370 * @param [in] sig  Signature data.
7371 * @return  0 on success.
7372 * @return  MEMORY_E on dynamic memory allocation failure.
7373 * @return  SHAKE-256 error return code on digest failure.
7374 */
7375static int slhdsakey_verify(SlhDsaKey* key, byte* md, const byte* sig)
7376{
7377    int ret;
7378    HashAddress adrs;
7379    word32 t[3];
7380    word32 l;
7381    byte pk_fors[SLHDSA_MAX_N];
7382    byte n = key->params->n;
7383
7384    /* Steps 4, 10-16: Set address based on message digest. */
7385    slhdsakey_set_ha_from_md(key, md, adrs, t, &l);
7386
7387    /* Step 6: Move pointer to FORS signature. */
7388    sig += n;
7389    /* Step 17: Get FORS public key from FORS signature. */
7390    ret = slhdsakey_fors_pk_from_sig(key, sig, md, key->sk + 2 * n, adrs,
7391        pk_fors);
7392    /* Step 7: Move pointer to hypertree signature. */
7393    sig += key->params->k * (1 + key->params->a) * n;
7394    if (ret == 0) {
7395        /* Step 18: Verify hypertree signature. */
7396        ret = slhdsakey_ht_verify(key, pk_fors, sig, key->sk + 2 * n, t, l,
7397            key->sk + 3 * n);
7398    }
7399
7400    return ret;
7401}
7402
7403/* Verify SLH-DSA signature.
7404 *
7405 * FIPS 205. Section 9.3. Algorithm 20.
7406 * slh_verify_internal(M, SIG, PK)
7407 *   1: if |SIG| != (1 + k(1 + a) + h + d . len . n then
7408 *   2:     return false
7409 *   3: end if
7410 *  ...
7411 *   5: R <- SIG.getR()                                             > SIG[0 : n]
7412 *  ...
7413 *   8: digest <- Hmsg (R, PK.seed, PK.root, M)         > compute message digest
7414 *   9: md <- digest [0 : upper(k.a / 8)]           > first upper(k.a / 8) bytes
7415 *  ...
7416 *
7417 * FIPS 205. Section 10.3. Algorithm 24.
7418 * slh_verify(M, SIG, ctx, PK)
7419 *   1: if |ctx| > 255 then
7420 *   2:     return false
7421 *   3: end if
7422 *   4: M' <- toByte(0, 1) || toByte(|ctx|, 1) || ctx
7423 *   5: return slh_verify_internal(M', SIG, PK)
7424 *
7425 * Note: ctx length is of type byte which means it can never be more than 255.
7426 *
7427 * @param [in] key    SLH-DSA key.
7428 * @param [in] ctx    Context of signing.
7429 * @param [in] ctxSz  Length of context in bytes.
7430 * @param [in] msg    Message to sign.
7431 * @param [in] msgSz  Length of message in bytes.
7432 * @param [in] sig    Signature data.
7433 * @param [in] sigSz  Length of signature in bytes.
7434 * @return  0 on success.
7435 * @return  BAD_FUNC_ARG when key, key's parameters, msg or sig is NULL.
7436 * @return  BAD_FUNC_ARG when ctx is NULL but ctxSz is greater than 0.
7437 * @return  BAD_LENGTH_E when signature size does not match parameters.
7438 * @return  MISSING_KEY when public key not set.
7439 * @return  MEMORY_E on dynamic memory allocation failure.
7440 * @return  SHAKE-256 error return code on digest failure.
7441 */
7442int wc_SlhDsaKey_Verify(SlhDsaKey* key, const byte* ctx, byte ctxSz,
7443    const byte* msg, word32 msgSz, const byte* sig, word32 sigSz)
7444{
7445    int ret = 0;
7446
7447    /* Validate parameters. */
7448    if ((key == NULL) || (key->params == NULL) ||
7449            ((ctx == NULL) && (ctxSz > 0)) || (msg == NULL) ||
7450            (sig == NULL)) {
7451        ret = BAD_FUNC_ARG;
7452    }
7453    /* Alg 20, Step 1: Check signature length is the expect length. */
7454    else if (sigSz != key->params->sigLen) {
7455        /* Alg 20, Step 2: Return error  */
7456        ret = BAD_LENGTH_E;
7457    }
7458    /* Check we have a public key to verify with. */
7459    else if ((key->flags & WC_SLHDSA_FLAG_PUBLIC) == 0) {
7460        ret = MISSING_KEY;
7461    }
7462    if (ret == 0) {
7463        byte md[SLHDSA_MAX_MD];
7464        byte n = key->params->n;
7465        byte hdr[2];
7466
7467        /* Alg 24, Step 4: Make M' header. */
7468        hdr[0] = 0;
7469        hdr[1] = ctxSz;
7470
7471#ifdef WOLFSSL_SLHDSA_SHA2
7472        if (SLHDSA_IS_SHA2(key->params->param)) {
7473            /* SHA2: H_msg via MGF1 (no PRF_msg for verify). */
7474            ret = slhdsakey_h_msg_sha2(key, sig, hdr, ctx, ctxSz, msg, msgSz,
7475                md, (word32)key->params->dl1 + key->params->dl2 +
7476                key->params->dl3);
7477        }
7478        else
7479#endif
7480        {
7481            /* SHAKE: H_msg streaming. */
7482            ret = slhdsakey_hash_start(&key->hash.shk.shake, sig, n);
7483            if (ret == 0) {
7484                ret = slhdsakey_hash_update(&key->hash.shk.shake,
7485                    key->sk + 2U * n, 2U * n);
7486            }
7487            if (ret == 0) {
7488                ret = slhdsakey_hash_update(&key->hash.shk.shake, hdr,
7489                    sizeof(hdr));
7490            }
7491            if ((ret == 0) && (ctxSz > 0)) {
7492                ret = slhdsakey_hash_update(&key->hash.shk.shake, ctx, ctxSz);
7493            }
7494            if (ret == 0) {
7495                ret = slhdsakey_hash_update(&key->hash.shk.shake, msg, msgSz);
7496            }
7497            if (ret == 0) {
7498                ret = slhdsakey_hash_final(&key->hash.shk.shake, md,
7499                    (word32)key->params->dl1 + key->params->dl2 +
7500                    key->params->dl3);
7501            }
7502        }
7503        if (ret == 0) {
7504            /* Alg 24, Step 5: Verify M'.
7505             * Alg 20, Steps 4,6-18: Verify digest. */
7506            ret = slhdsakey_verify(key, md, sig);
7507        }
7508    }
7509
7510    return ret;
7511}
7512
7513/* Verify SLH-DSA signature using internal interface -- M' provided directly.
7514 *
7515 * FIPS 205. Section 9.3. Algorithm 20.
7516 * slh_verify_internal(M', SIG, PK)
7517 *
7518 * @param [in] key       SLH-DSA key.
7519 * @param [in] mprime    M' message (already in internal format).
7520 * @param [in] mprimeSz  Length of M' in bytes.
7521 * @param [in] sig       Signature data.
7522 * @param [in] sigSz     Length of signature in bytes.
7523 * @return  0 on success.
7524 * @return  SIG_VERIFY_E on verification failure.
7525 */
7526int wc_SlhDsaKey_VerifyMsg(SlhDsaKey* key, const byte* mprime,
7527    word32 mprimeSz, const byte* sig, word32 sigSz)
7528{
7529    int ret = 0;
7530
7531    /* Validate parameters. */
7532    if ((key == NULL) || (key->params == NULL) || (mprime == NULL) ||
7533            (sig == NULL)) {
7534        ret = BAD_FUNC_ARG;
7535    }
7536    else if (sigSz != key->params->sigLen) {
7537        ret = BAD_LENGTH_E;
7538    }
7539    else if ((key->flags & WC_SLHDSA_FLAG_PUBLIC) == 0) {
7540        ret = MISSING_KEY;
7541    }
7542    if (ret == 0) {
7543        byte md[SLHDSA_MAX_MD];
7544        byte n = key->params->n;
7545
7546#ifdef WOLFSSL_SLHDSA_SHA2
7547        if (SLHDSA_IS_SHA2(key->params->param)) {
7548            /* SHA2: H_msg. Internal interface: no M' header, pass whole
7549             * message directly. */
7550            ret = slhdsakey_h_msg_sha2(key, sig,
7551                NULL, NULL, 0, mprime, mprimeSz,
7552                md, (word32)key->params->dl1 + key->params->dl2 +
7553                key->params->dl3);
7554        }
7555        else
7556#endif
7557        {
7558            /* SHAKE: H_msg = SHAKE(R || PK.seed || PK.root || M). */
7559            ret = slhdsakey_hash_start(&key->hash.shk.shake, sig, n);
7560            if (ret == 0) {
7561                ret = slhdsakey_hash_update(&key->hash.shk.shake,
7562                    key->sk + 2U * n, 2U * n);
7563            }
7564            if (ret == 0) {
7565                ret = slhdsakey_hash_update(&key->hash.shk.shake,
7566                    mprime, mprimeSz);
7567            }
7568            if (ret == 0) {
7569                ret = slhdsakey_hash_final(&key->hash.shk.shake, md,
7570                    (word32)key->params->dl1 + key->params->dl2 +
7571                    key->params->dl3);
7572            }
7573        }
7574        if (ret == 0) {
7575            ret = slhdsakey_verify(key, md, sig);
7576        }
7577    }
7578
7579    return ret;
7580}
7581
7582/* All HashSLH-DSA hash OIDs are DER-encoded as tag(0x06) + length(0x09) + 9
7583 * bytes, so any approved hash OID is exactly 11 bytes. The PRF_msg / H_msg
7584 * input for the SHA-2 path is the concatenation OID || PHM, bounded by
7585 * SLHDSA_OID_MAX_LEN + WC_MAX_DIGEST_SIZE. The PHM buffer fits in
7586 * WC_MAX_DIGEST_SIZE bytes because slhdsakey_validate_prehash enforces
7587 * hashSz == expectedLen[hashType] for every supported hashType and every
7588 * supported expectedLen is <= WC_MAX_DIGEST_SIZE. The largest FIPS 205
7589 * approved PHM is 64 bytes (SHA-512 digest size, also the SHAKE256 PHM
7590 * length fixed at 512 bits per Section 10.2.2). The static assert below
7591 * catches a future hash being added whose digest exceeds the bound. The
7592 * literal 64 is used directly because WC_SHA512_DIGEST_SIZE is only
7593 * defined when SHA-512 is compiled in. */
7594#define SLHDSA_OID_MAX_LEN              11
7595#define SLHDSA_LARGEST_APPROVED_PHM_LEN 64
7596#define SLHDSA_PHMSG_MAX_LEN            (SLHDSA_OID_MAX_LEN + \
7597                                         WC_MAX_DIGEST_SIZE)
7598wc_static_assert(WC_MAX_DIGEST_SIZE >= SLHDSA_LARGEST_APPROVED_PHM_LEN);
7599
7600#ifdef WOLFSSL_SHA224
7601/* OID for SHA-224 for hash signing/verification. */
7602static const byte slhdsakey_oid_sha224[] = {
7603    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x04
7604};
7605#endif
7606#ifndef NO_SHA256
7607/* OID for SHA-256 for hash signing/verification. */
7608static const byte slhdsakey_oid_sha256[] = {
7609    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01
7610};
7611#endif
7612#ifdef WOLFSSL_SHA384
7613/* OID for SHA-384 for hash signing/verification. */
7614static const byte slhdsakey_oid_sha384[] = {
7615    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x02
7616};
7617#endif
7618#ifdef WOLFSSL_SHA512
7619/* OID for SHA-512 for hash signing/verification. */
7620static const byte slhdsakey_oid_sha512[] = {
7621    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x03
7622};
7623#ifndef WOLFSSL_NOSHA512_224
7624/* OID for SHA-512/224 for hash signing/verification. */
7625static const byte slhdsakey_oid_sha512_224[] = {
7626    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x05
7627};
7628#endif
7629#ifndef WOLFSSL_NOSHA512_256
7630/* OID for SHA-512/256 for hash signing/verification. */
7631static const byte slhdsakey_oid_sha512_256[] = {
7632    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x06
7633};
7634#endif
7635#endif
7636#ifdef WOLFSSL_SHAKE128
7637/* OID for SHAKE-128 for hash signing/verification. */
7638static const byte slhdsakey_oid_shake128[] = {
7639    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0b
7640};
7641#endif
7642#ifdef WOLFSSL_SHAKE256
7643/* OID for SHAKE-256 for hash signing/verification. */
7644static const byte slhdsakey_oid_shake256[] = {
7645    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0c
7646};
7647#endif
7648#ifdef WOLFSSL_SHA3
7649#ifndef WOLFSSL_NOSHA3_224
7650/* OID for SHA3-224 for hash signing/verification. */
7651static const byte slhdsakey_oid_sha3_224[] = {
7652    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x07
7653};
7654#endif
7655#ifndef WOLFSSL_NOSHA3_256
7656/* OID for SHA3-256 for hash signing/verification. */
7657static const byte slhdsakey_oid_sha3_256[] = {
7658    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x08
7659};
7660#endif
7661#ifndef WOLFSSL_NOSHA3_384
7662/* OID for SHA3-384 for hash signing/verification. */
7663static const byte slhdsakey_oid_sha3_384[] = {
7664    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x09
7665};
7666#endif
7667#ifndef WOLFSSL_NOSHA3_512
7668/* OID for SHA3-512 for hash signing/verification. */
7669static const byte slhdsakey_oid_sha3_512[] = {
7670    0x06, 0x09, 0x60, 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x0a
7671};
7672#endif
7673#endif
7674
7675/* Validate the caller-supplied pre-hashed digest length and look up the
7676 * corresponding OID for the chosen hash algorithm.
7677 *
7678 * The HashSLH-DSA family takes the digest as input rather than the full
7679 * message. This mirrors the wc_dilithium_*_ctx_hash interface and matches the
7680 * convention used by NIST ACVP signatureInterface=external / preHash test
7681 * vectors and other libraries (OpenSSL HASH-ML-DSA, leancrypto SLH-DSA,
7682 * mldsa-native pre_hash_internal). The expected digest length is fixed by
7683 * FIPS 205 Section 10.2.2 and equals wc_HashGetDigestSize(hashType) for the
7684 * fixed-output hashes; for SHAKE128/256 the standard fixes the XOF output to
7685 * 256/512 bits respectively. Callers feed the caller-supplied digest buffer
7686 * directly into the M' construction -- there is no copy.
7687 *
7688 * @param [in]  hashSz    Length of the caller-supplied digest in bytes.
7689 * @param [in]  hashType  Hash algorithm identifier (selects OID and length).
7690 * @param [out] oid       OID data for hash algorithm.
7691 * @param [out] oidLen    Length of OID data for hash algorithm.
7692 * @return  0 on success.
7693 * @return  BAD_LENGTH_E when hashSz does not equal the expected digest size.
7694 * @return  NOT_COMPILED_IN when hash algorithm not supported.
7695 */
7696static int slhdsakey_validate_prehash(word32 hashSz,
7697    enum wc_HashType hashType, const byte** oid, byte* oidLen)
7698{
7699    int ret = 0;
7700    word32 expectedLen = 0;
7701
7702    switch ((int)hashType) {
7703    #ifdef WOLFSSL_SHA224
7704        case WC_HASH_TYPE_SHA224:
7705            *oid = slhdsakey_oid_sha224;
7706            *oidLen = (byte)sizeof(slhdsakey_oid_sha224);
7707            expectedLen = WC_SHA224_DIGEST_SIZE;
7708            break;
7709    #endif
7710    #ifndef NO_SHA256
7711        case WC_HASH_TYPE_SHA256:
7712            *oid = slhdsakey_oid_sha256;
7713            *oidLen = (byte)sizeof(slhdsakey_oid_sha256);
7714            expectedLen = WC_SHA256_DIGEST_SIZE;
7715            break;
7716    #endif
7717    #ifdef WOLFSSL_SHA384
7718        case WC_HASH_TYPE_SHA384:
7719            *oid = slhdsakey_oid_sha384;
7720            *oidLen = (byte)sizeof(slhdsakey_oid_sha384);
7721            expectedLen = WC_SHA384_DIGEST_SIZE;
7722            break;
7723    #endif
7724#ifdef WOLFSSL_SHA512
7725        case WC_HASH_TYPE_SHA512:
7726            *oid = slhdsakey_oid_sha512;
7727            *oidLen = (byte)sizeof(slhdsakey_oid_sha512);
7728            expectedLen = WC_SHA512_DIGEST_SIZE;
7729            break;
7730    #ifndef WOLFSSL_NOSHA512_224
7731        case WC_HASH_TYPE_SHA512_224:
7732            *oid = slhdsakey_oid_sha512_224;
7733            *oidLen = (byte)sizeof(slhdsakey_oid_sha512_224);
7734            expectedLen = WC_SHA512_224_DIGEST_SIZE;
7735            break;
7736    #endif
7737    #ifndef WOLFSSL_NOSHA512_256
7738        case WC_HASH_TYPE_SHA512_256:
7739            *oid = slhdsakey_oid_sha512_256;
7740            *oidLen = (byte)sizeof(slhdsakey_oid_sha512_256);
7741            expectedLen = WC_SHA512_256_DIGEST_SIZE;
7742            break;
7743    #endif
7744#endif
7745    #ifdef WOLFSSL_SHAKE128
7746        case WC_HASH_TYPE_SHAKE128:
7747            *oid = slhdsakey_oid_shake128;
7748            *oidLen = (byte)sizeof(slhdsakey_oid_shake128);
7749            /* FIPS 205 Section 10.2.2 fixes SHAKE128 PHM length at 256 bits. */
7750            expectedLen = WC_SHA3_256_DIGEST_SIZE;
7751            break;
7752    #endif
7753    #ifdef WOLFSSL_SHAKE256
7754        case WC_HASH_TYPE_SHAKE256:
7755            *oid = slhdsakey_oid_shake256;
7756            *oidLen = (byte)sizeof(slhdsakey_oid_shake256);
7757            /* FIPS 205 Section 10.2.2 fixes SHAKE256 PHM length at 512 bits. */
7758            expectedLen = WC_SHA3_512_DIGEST_SIZE;
7759            break;
7760    #endif
7761    #ifdef WOLFSSL_SHA3
7762    #ifndef WOLFSSL_NOSHA3_224
7763        case WC_HASH_TYPE_SHA3_224:
7764            *oid = slhdsakey_oid_sha3_224;
7765            *oidLen = (byte)sizeof(slhdsakey_oid_sha3_224);
7766            expectedLen = WC_SHA3_224_DIGEST_SIZE;
7767            break;
7768    #endif
7769    #ifndef WOLFSSL_NOSHA3_256
7770        case WC_HASH_TYPE_SHA3_256:
7771            *oid = slhdsakey_oid_sha3_256;
7772            *oidLen = (byte)sizeof(slhdsakey_oid_sha3_256);
7773            expectedLen = WC_SHA3_256_DIGEST_SIZE;
7774            break;
7775    #endif
7776    #ifndef WOLFSSL_NOSHA3_384
7777        case WC_HASH_TYPE_SHA3_384:
7778            *oid = slhdsakey_oid_sha3_384;
7779            *oidLen = (byte)sizeof(slhdsakey_oid_sha3_384);
7780            expectedLen = WC_SHA3_384_DIGEST_SIZE;
7781            break;
7782    #endif
7783    #ifndef WOLFSSL_NOSHA3_512
7784        case WC_HASH_TYPE_SHA3_512:
7785            *oid = slhdsakey_oid_sha3_512;
7786            *oidLen = (byte)sizeof(slhdsakey_oid_sha3_512);
7787            expectedLen = WC_SHA3_512_DIGEST_SIZE;
7788            break;
7789    #endif
7790    #endif
7791        default:
7792            ret = NOT_COMPILED_IN;
7793            break;
7794    }
7795
7796    if ((ret == 0) && (hashSz != expectedLen)) {
7797        ret = BAD_LENGTH_E;
7798    }
7799
7800    return ret;
7801}
7802
7803#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
7804/* Generate pre-hash SLH-DSA signature.
7805 *
7806 * FIPS 205. Section 10.2.2. Algorithm 23.
7807 * hash_slh_sign(M, ctx, PH, SK)
7808 *   1: if |ctx| > 255 then
7809 *   2:  return falsity
7810 *                > return an error indication if the context string is too long
7811 *   3: end if
7812 *   4: addrnd <-$- Bn    > skip lines 4 through 7 for the deterministic variant
7813 *   5: if addrnd = NULL then
7814 *   6:     return falsity
7815 *                  > return an error indication if random bit generation failed
7816 *   7: end if
7817 *   8: switch PH do
7818 *   9:     case SHA-256:
7819 *  10:         OID <- toByte(0x0609608648016503040201, 11)
7820 *                                                      > 2.16.840.1.101.3.4.2.1
7821 *  11:         PHM <- SHA-256(M)
7822 *  12:     case SHA-512:
7823 *  13:         OID <- toByte(0x0609608648016503040203, 11)
7824 *                                                      > 2.16.840.1.101.3.4.2.3
7825 *  14:         PHM <- SHA-512(M)
7826 *  15:     case SHAKE128:
7827 *  16:         OID <- toByte(0x060960864801650304020B, 11)
7828 *                                                     > 2.16.840.1.101.3.4.2.11
7829 *  17:         PHM <- SHAKE128(M, 256)
7830 *  18:     case SHAKE256:
7831 *  19:         OID <- toByte(0x060960864801650304020C, 11)
7832 *                                                     > 2.16.840.1.101.3.4.2.12
7833 *  20:         PHM <- SHAKE256(M , 512)
7834 *  21:     case ...                     > other approved hash functions or XOFs
7835 *  22:         ...
7836 *  23: end switch
7837 *  24: M' <- toByte(1, 1) || toByte(|ctx|, 1) || ctx || OID || PHM
7838 *                                   > omit addrnd for the deterministic variant
7839 *  25: SIG <- slh_sign_internal(M', SK, addrnd)
7840 *  26: return SIG
7841 *
7842 * FIPS 205. Section 9.2. Algorithm 19.
7843 * slh_sign_internal(M, SK, addrnd)
7844 *  ...
7845 *   2: opt_rand <- addrnd
7846 *                > substitute opt_rand <- PK.seed for the deterministic variant
7847 *   3: R <- PRFmsg (SK.prf, opt_rand, M)                  > generate randomizer
7848 *   4: SIG <- R
7849 *   5: digest <- Hmsg(R, PK.seed, PK.root, M)          > compute message digest
7850 *   6: md <- digest [0 : upper(k.a / 8)]          > first upper(k.a / 8)] bytes
7851 *  ...
7852 *
7853 * Note: ctx length is of type byte which means it can never be more than 255.
7854 *
7855 * The caller MUST pre-hash the application message with hashType before
7856 * calling and pass the digest as hash. hashSz must equal the digest size of
7857 * hashType (32 for SHAKE128, 64 for SHAKE256 per FIPS 205 Section 10.2.2).
7858 *
7859 * @param [in]      key       SLH-DSA key.
7860 * @param [in]      ctx       Context of signing.
7861 * @param [in]      ctxSz     Length of context in bytes.
7862 * @param [in]      hash      Pre-hashed message digest to sign.
7863 * @param [in]      hashSz    Length of digest in bytes.
7864 * @param [in]      hashType  Hash algorithm used for pre-hash (selects OID).
7865 * @param [out]     sig       Buffer to hold signature.
7866 * @param [in, out] sigSz     On in, length of signature buffer.
7867 *                            On out, length of signature data.
7868 * @return  0 on success.
7869 * @return  BAD_FUNC_ARG when key, key's parameters, hash, sig, sigSz or addRnd
7870 *          is NULL.
7871 * @return  BAD_FUNC_ARG when ctx is NULL but ctx length is greater than 0.
7872 * @return  BAD_LENGTH_E when sigSz is less than required signature length, or
7873 *          when hashSz does not equal the digest size for hashType.
7874 * @return  NOT_COMPILED_IN when hash algorithm is not supported.
7875 * @return  MEMORY_E on dynamic memory allocation failure.
7876 * @return  SHAKE-256 error return code on digest failure.
7877 */
7878static int slhdsakey_signhash_external(SlhDsaKey* key, const byte* ctx,
7879    byte ctxSz, const byte* hash, word32 hashSz, enum wc_HashType hashType,
7880    byte* sig, word32* sigSz, const byte* addRnd)
7881{
7882    int ret = 0;
7883    const byte* oid = NULL;
7884    byte oidLen = 0;
7885
7886    /* Validate parameters. */
7887    if ((key == NULL) || (key->params == NULL) ||
7888            ((ctx == NULL) && (ctxSz > 0)) || (hash == NULL) || (sig == NULL) ||
7889            (sigSz == NULL)) {
7890        ret = BAD_FUNC_ARG;
7891    }
7892    /* Check sig buffer is large enough to hold generated signature. */
7893    else if (*sigSz < key->params->sigLen) {
7894        ret = BAD_LENGTH_E;
7895    }
7896    /* Alg 23, Step 5: Check addrnd is not NULL. */
7897    else if (addRnd == NULL) {
7898        /* Alg 23, Step 6: Return error. */
7899        ret = BAD_FUNC_ARG;
7900    }
7901    if (ret == 0) {
7902        /* Alg 23, Steps 8-23: Validate caller-supplied pre-hashed digest length
7903         * and select OID for the chosen hash algorithm. */
7904        ret = slhdsakey_validate_prehash(hashSz, hashType, &oid, &oidLen);
7905    }
7906    if (ret == 0) {
7907        byte n = key->params->n;
7908        byte md[SLHDSA_MAX_MD];
7909        byte hdr[2];
7910
7911        /* Alg 23, Step 24: Set first two bytes to pass to hash ... */
7912        hdr[0] = 1;
7913        hdr[1] = ctxSz;
7914
7915#ifdef WOLFSSL_SLHDSA_SHA2
7916        if (SLHDSA_IS_SHA2(key->params->param)) {
7917            /* SHA2: Build oid||hash as message for PRF_msg/H_msg. */
7918            byte phMsg[SLHDSA_PHMSG_MAX_LEN];
7919            word32 phMsgLen = (word32)oidLen + hashSz;
7920
7921            XMEMCPY(phMsg, oid, oidLen);
7922            XMEMCPY(phMsg + oidLen, hash, hashSz);
7923
7924            ret = slhdsakey_prf_msg_sha2(key, key->sk + n, addRnd, hdr, ctx,
7925                ctxSz, phMsg, phMsgLen, n, sig);
7926            if (ret == 0) {
7927                ret = slhdsakey_h_msg_sha2(key, sig, hdr, ctx, ctxSz, phMsg,
7928                    phMsgLen, md, (word32)key->params->dl1 + key->params->dl2 +
7929                    key->params->dl3);
7930                sig += n;
7931            }
7932        }
7933        else
7934#endif
7935        {
7936            /* SHAKE: PRF_msg streaming. */
7937            ret = slhdsakey_hash_start(&key->hash.shk.shake, key->sk + n, n);
7938            if (ret == 0) {
7939                ret = slhdsakey_hash_update(&key->hash.shk.shake, addRnd, n);
7940            }
7941            if (ret == 0) {
7942                ret = slhdsakey_hash_update(&key->hash.shk.shake, hdr,
7943                    sizeof(hdr));
7944            }
7945            if ((ret == 0) && (ctxSz > 0)) {
7946                ret = slhdsakey_hash_update(&key->hash.shk.shake, ctx, ctxSz);
7947            }
7948            if (ret == 0) {
7949                ret = slhdsakey_hash_update(&key->hash.shk.shake, oid, oidLen);
7950            }
7951            if (ret == 0) {
7952                ret = slhdsakey_hash_update(&key->hash.shk.shake, hash, hashSz);
7953            }
7954            if (ret == 0) {
7955                ret = slhdsakey_hash_final(&key->hash.shk.shake, sig, n);
7956            }
7957            /* SHAKE: H_msg streaming. */
7958            if (ret == 0) {
7959                ret = slhdsakey_hash_start(&key->hash.shk.shake, sig, n);
7960                sig += n;
7961            }
7962            if (ret == 0) {
7963                ret = slhdsakey_hash_update(&key->hash.shk.shake,
7964                    key->sk + 2U * n, 2U * n);
7965            }
7966            if (ret == 0) {
7967                ret = slhdsakey_hash_update(&key->hash.shk.shake, hdr,
7968                    sizeof(hdr));
7969            }
7970            if ((ret == 0) && (ctxSz > 0)) {
7971                ret = slhdsakey_hash_update(&key->hash.shk.shake, ctx, ctxSz);
7972            }
7973            if (ret == 0) {
7974                ret = slhdsakey_hash_update(&key->hash.shk.shake, oid, oidLen);
7975            }
7976            if (ret == 0) {
7977                ret = slhdsakey_hash_update(&key->hash.shk.shake, hash, hashSz);
7978            }
7979            if (ret == 0) {
7980                ret = slhdsakey_hash_final(&key->hash.shk.shake, md,
7981                    (word32)key->params->dl1 + key->params->dl2 +
7982                    key->params->dl3);
7983            }
7984        }
7985        if (ret == 0) {
7986            /* Alg 19. Steps 7-19 */
7987            ret = slhdsakey_sign(key, md, sig);
7988        }
7989        if (ret == 0) {
7990            /* Return the signature size generated. */
7991            *sigSz = key->params->sigLen;
7992        }
7993    }
7994
7995    return ret;
7996}
7997
7998/* Generate a deterministic HashSLH-DSA signature.
7999 *
8000 * addrnd is the public key seed. The caller MUST pre-hash the application
8001 * message with hashType before calling and pass the digest as hash; hashSz
8002 * must equal the digest size of hashType (32 for SHAKE128, 64 for SHAKE256
8003 * per FIPS 205 Section 10.2.2).
8004 *
8005 * @param [in]      key       SLH-DSA key.
8006 * @param [in]      ctx       Context of signing.
8007 * @param [in]      ctxSz     Length of context in bytes.
8008 * @param [in]      hash      Pre-hashed message digest to sign.
8009 * @param [in]      hashSz    Length of digest in bytes.
8010 * @param [in]      hashType  Hash algorithm used for pre-hash (selects OID).
8011 * @param [out]     sig       Buffer to hold signature.
8012 * @param [in, out] sigSz     On in, length of signature buffer.
8013 *                            On out, length of signature data.
8014 * @return  0 on success.
8015 * @return  BAD_FUNC_ARG when key, key's parameters, hash, sig or sigSz is NULL.
8016 * @return  BAD_FUNC_ARG when ctx is NULL but ctx length is greater than 0.
8017 * @return  BAD_LENGTH_E when sigSz is less than required signature length, or
8018 *          when hashSz does not equal the digest size for hashType.
8019 * @return  MISSING_KEY when private key not set.
8020 * @return  MEMORY_E on dynamic memory allocation failure.
8021 * @return  SHAKE-256 error return code on digest failure.
8022 */
8023int wc_SlhDsaKey_SignHashDeterministic(SlhDsaKey* key, const byte* ctx,
8024    byte ctxSz, const byte* hash, word32 hashSz, enum wc_HashType hashType,
8025    byte* sig, word32* sigSz)
8026{
8027    int ret;
8028
8029    /* Validate parameters that will be used in this function. */
8030    if ((key == NULL) || (key->params == NULL)) {
8031        ret = BAD_FUNC_ARG;
8032    }
8033    /* Check we have a private key to sign with. */
8034    else if ((key->flags & WC_SLHDSA_FLAG_PRIVATE) == 0) {
8035        ret = MISSING_KEY;
8036    }
8037    else {
8038        /* HashSLH-DSA sign with caller-supplied digest. */
8039        ret = slhdsakey_signhash_external(key, ctx, ctxSz, hash, hashSz,
8040            hashType, sig, sigSz, key->sk + 2 * key->params->n);
8041    }
8042
8043    return ret;
8044}
8045
8046/* Generate a HashSLH-DSA signature with explicit randomness.
8047 *
8048 * The caller MUST pre-hash the application message with hashType before
8049 * calling and pass the digest as hash; hashSz must equal the digest size of
8050 * hashType (32 for SHAKE128, 64 for SHAKE256 per FIPS 205 Section 10.2.2).
8051 *
8052 * @param [in]      key       SLH-DSA key.
8053 * @param [in]      ctx       Context of signing.
8054 * @param [in]      ctxSz     Length of context in bytes.
8055 * @param [in]      hash      Pre-hashed message digest to sign.
8056 * @param [in]      hashSz    Length of digest in bytes.
8057 * @param [in]      hashType  Hash algorithm used for pre-hash (selects OID).
8058 * @param [out]     sig       Buffer to hold signature.
8059 * @param [in, out] sigSz     On in, length of signature buffer.
8060 *                            On out, length of signature data.
8061 * @param [in]      addRnd    Additional random for signature.
8062 * @return  0 on success.
8063 * @return  BAD_FUNC_ARG when key, key's parameters, hash, sig, sigSz or addrnd
8064 *          is NULL.
8065 * @return  BAD_FUNC_ARG when ctx is NULL but ctx length is greater than 0.
8066 * @return  BAD_LENGTH_E when sigSz is less than required signature length, or
8067 *          when hashSz does not equal the digest size for hashType.
8068 * @return  MISSING_KEY when private key not set.
8069 * @return  NOT_COMPILED in when hash algorithm is not supported.
8070 * @return  MEMORY_E on dynamic memory allocation failure.
8071 * @return  SHAKE-256 error return code on digest failure.
8072 */
8073int wc_SlhDsaKey_SignHashWithRandom(SlhDsaKey* key, const byte* ctx, byte ctxSz,
8074    const byte* hash, word32 hashSz, enum wc_HashType hashType, byte* sig,
8075    word32* sigSz, const byte* addRnd)
8076{
8077    /* HashSLH-DSA sign with caller-supplied digest. */
8078    return slhdsakey_signhash_external(key, ctx, ctxSz, hash, hashSz, hashType,
8079        sig, sigSz, addRnd);
8080}
8081
8082/* Generate a HashSLH-DSA signature using an RNG for added randomness.
8083 *
8084 * The caller MUST pre-hash the application message with hashType before
8085 * calling and pass the digest as hash; hashSz must equal the digest size of
8086 * hashType (32 for SHAKE128, 64 for SHAKE256 per FIPS 205 Section 10.2.2).
8087 *
8088 * @param [in]      key     SLH-DSA key.
8089 * @param [in]      ctx     Context of signing.
8090 * @param [in]      ctxSz   Length of context in bytes.
8091 * @param [in]      hash    Pre-hashed message digest to sign.
8092 * @param [in]      hashSz  Length of digest in bytes.
8093 * @param [in]      hashType  Hash algorithm used for pre-hash (selects OID).
8094 * @param [out]     sig     Buffer to hold signature.
8095 * @param [in, out] sigSz   On in, length of signature buffer.
8096 *                          On out, length of signature data.
8097 * @param [in]      rng     Random number generator.
8098 * @return  0 on success.
8099 * @return  BAD_FUNC_ARG when key, key's parameters, hash, sig, sigSz or rng is
8100 *          NULL.
8101 * @return  BAD_FUNC_ARG when ctx is NULL but ctx length is greater than 0.
8102 * @return  BAD_LENGTH_E when hashSz does not equal the digest size for
8103 *          hashType.
8104 * @return  MISSING_KEY when private key not set.
8105 * @return  NOT_COMPILED in when hash algorithm is not supported.
8106 * @return  MEMORY_E on dynamic memory allocation failure.
8107 * @return  SHAKE-256 error return code on digest failure.
8108 */
8109int wc_SlhDsaKey_SignHash(SlhDsaKey* key, const byte* ctx, byte ctxSz,
8110    const byte* hash, word32 hashSz, enum wc_HashType hashType, byte* sig,
8111    word32* sigSz, WC_RNG* rng)
8112{
8113    int ret = 0;
8114    byte addRnd[SLHDSA_MAX_N];
8115
8116    /* Validate parameters before generating random.
8117     * hashSz / hashType validation lives in the internal worker and therefore
8118     * runs after wc_RNG_GenerateBlock. A call with a bad hashSz/hashType will
8119     * waste n bytes of DRBG output before the error is reported (similar to
8120     * ML-DSA pre-hash handling). */
8121    if ((key == NULL) || (key->params == NULL) ||
8122            ((ctx == NULL) && (ctxSz > 0)) || (hash == NULL) || (sig == NULL) ||
8123            (sigSz == NULL) || (rng == NULL)) {
8124        ret = BAD_FUNC_ARG;
8125    }
8126    /* Check sig buffer is large enough to hold generated signature. */
8127    else if (*sigSz < key->params->sigLen) {
8128        ret = BAD_LENGTH_E;
8129    }
8130    /* Check we have a private key to sign with. */
8131    else if ((key->flags & WC_SLHDSA_FLAG_PRIVATE) == 0) {
8132        ret = MISSING_KEY;
8133    }
8134    if (ret == 0) {
8135        /* Generate n bytes of random. */
8136        ret = wc_RNG_GenerateBlock(rng, addRnd, key->params->n);
8137    }
8138    if (ret == 0) {
8139        /* HashSLH-DSA sign with caller-supplied digest. */
8140        ret = wc_SlhDsaKey_SignHashWithRandom(key, ctx, ctxSz, hash, hashSz,
8141            hashType, sig, sigSz, addRnd);
8142    }
8143
8144    ForceZero(addRnd, sizeof(addRnd));
8145
8146    return ret;
8147}
8148#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
8149
8150/* Verify SLH-DSA signature.
8151 *
8152 * FIPS 205. Section 9.3. Algorithm 20.
8153 * slh_verify_internal(M, SIG, PK)
8154 *   1: if |SIG| != (1 + k(1 + a) + h + d . len . n then
8155 *   2:     return false
8156 *   3: end if
8157 *  ...
8158 *   5: R <- SIG.getR()                                             > SIG[0 : n]
8159 *  ...
8160 *   8: digest <- Hmsg (R, PK.seed, PK.root, M)         > compute message digest
8161 *   9: md <- digest [0 : upper(k.a / 8)]           > first upper(k.a / 8) bytes
8162 * ...
8163 *
8164 * FIPS 205. Section 10.3. Algorithm 25.
8165 * hash_slh_verify(M, SIG, ctx, PH, PK)
8166 *   1: if |ctx| > 255 then
8167 *   2:     return false
8168 *   3: end if
8169 *   4: switch PH do
8170 *   5:     case SHA-256:
8171 *   6:         OID <- toByte(0x0609608648016503040201, 11)
8172 *                                                      > 2.16.840.1.101.3.4.2.1
8173 *   7:         PHM <- SHA-256(M)
8174 *   8:     case SHA-512:
8175 *   9:         OID <- toByte(0x0609608648016503040203, 11)
8176 *                                                      > 2.16.840.1.101.3.4.2.3
8177 *  10:         PHM <- SHA-512(M)
8178 *  11:     case SHAKE128:
8179 *  12:         OID <- toByte(0x060960864801650304020B, 11)
8180 *                                                     > 2.16.840.1.101.3.4.2.11
8181 *  13:         PHM <- SHAKE128(M, 256)
8182 *  14:     case SHAKE256:
8183 *  15:         OID <- toByte(0x060960864801650304020C, 11)
8184 *                                                     > 2.16.840.1.101.3.4.2.12
8185 *  16:         PHM <- SHAKE256(M , 512)
8186 *  17:     case ...                     > other approved hash functions or XOFs
8187 *  18:         ...
8188 *  19: end switch
8189 *  20: M' <- toByte(1, 1) || toByte(|ctx|, 1) || ctx || OID || PHM
8190 *  21: return slh_verify_internal(M', SIG, PK)
8191 *
8192 * The caller MUST pre-hash the application message with hashType before
8193 * calling and pass the digest as hash; hashSz must equal the digest size of
8194 * hashType (32 for SHAKE128, 64 for SHAKE256 per FIPS 205 Section 10.2.2).
8195 *
8196 * @param [in] key       SLH-DSA key.
8197 * @param [in] ctx       Context of signing.
8198 * @param [in] ctxSz     Length of context in bytes.
8199 * @param [in] hash      Pre-hashed message digest to verify against.
8200 * @param [in] hashSz    Length of digest in bytes.
8201 * @param [in] hashType  Hash algorithm used for pre-hash (selects OID).
8202 * @param [in] sig       Signature data.
8203 * @param [in] sigSz     Length of signature in bytes.
8204 * @return  0 on success.
8205 * @return  BAD_FUNC_ARG when key, key's parameters, hash or sig is NULL.
8206 * @return  BAD_FUNC_ARG when ctx is NULL but ctx length is greater than 0.
8207 * @return  BAD_LENGTH_E when signature size does not match parameters, or
8208 *          when hashSz does not equal the digest size for hashType.
8209 * @return  MISSING_KEY when public key not set.
8210 * @return  NOT_COMPILED in when hash algorithm is not supported.
8211 * @return  MEMORY_E on dynamic memory allocation failure.
8212 * @return  SHAKE-256 error return code on digest failure.
8213 */
8214int wc_SlhDsaKey_VerifyHash(SlhDsaKey* key, const byte* ctx, byte ctxSz,
8215    const byte* hash, word32 hashSz, enum wc_HashType hashType, const byte* sig,
8216    word32 sigSz)
8217{
8218    int ret = 0;
8219    const byte* oid = NULL;
8220    byte oidLen = 0;
8221
8222    /* Validate parameters. */
8223    if ((key == NULL) || (key->params == NULL) ||
8224            ((ctx == NULL) && (ctxSz > 0)) || (hash == NULL) || (sig == NULL)) {
8225        ret = BAD_FUNC_ARG;
8226    }
8227    /* Alg 20, Step 1: Check signature length is the expect length. */
8228    else if (sigSz != key->params->sigLen) {
8229        /* Alg 20, Step 2: Return error  */
8230        ret = BAD_LENGTH_E;
8231    }
8232    /* Check we have a public key to verify with. */
8233    else if ((key->flags & WC_SLHDSA_FLAG_PUBLIC) == 0) {
8234        ret = MISSING_KEY;
8235    }
8236    if (ret == 0) {
8237        /* Alg 25, Steps 4-19: Validate caller-supplied pre-hashed digest length
8238         * and select OID for the chosen hash algorithm. */
8239        ret = slhdsakey_validate_prehash(hashSz, hashType, &oid, &oidLen);
8240    }
8241    if (ret == 0) {
8242        byte n = key->params->n;
8243        byte md[SLHDSA_MAX_MD];
8244        byte hdr[2];
8245
8246        /* Alg 25, Step 20: Make M' header. */
8247        hdr[0] = 1;
8248        hdr[1] = ctxSz;
8249
8250#ifdef WOLFSSL_SLHDSA_SHA2
8251        if (SLHDSA_IS_SHA2(key->params->param)) {
8252            /* SHA2: Build oid||hash as message for H_msg. */
8253            byte phMsg[SLHDSA_PHMSG_MAX_LEN];
8254            word32 phMsgLen = (word32)oidLen + hashSz;
8255
8256            XMEMCPY(phMsg, oid, oidLen);
8257            XMEMCPY(phMsg + oidLen, hash, hashSz);
8258
8259            ret = slhdsakey_h_msg_sha2(key, sig, hdr, ctx, ctxSz, phMsg,
8260                phMsgLen, md, (word32)key->params->dl1 + key->params->dl2 +
8261                key->params->dl3);
8262        }
8263        else
8264#endif
8265        {
8266            /* SHAKE: H_msg streaming. */
8267            ret = slhdsakey_hash_start(&key->hash.shk.shake, sig, n);
8268            if (ret == 0) {
8269                ret = slhdsakey_hash_update(&key->hash.shk.shake,
8270                    key->sk + 2U * n, 2U * n);
8271            }
8272            if (ret == 0) {
8273                ret = slhdsakey_hash_update(&key->hash.shk.shake, hdr,
8274                    sizeof(hdr));
8275            }
8276            if ((ret == 0) && (ctxSz > 0)) {
8277                ret = slhdsakey_hash_update(&key->hash.shk.shake, ctx, ctxSz);
8278            }
8279            if (ret == 0) {
8280                ret = slhdsakey_hash_update(&key->hash.shk.shake, oid, oidLen);
8281            }
8282            if (ret == 0) {
8283                ret = slhdsakey_hash_update(&key->hash.shk.shake, hash, hashSz);
8284            }
8285            if (ret == 0) {
8286                ret = slhdsakey_hash_final(&key->hash.shk.shake, md,
8287                    (word32)key->params->dl1 + key->params->dl2 +
8288                    key->params->dl3);
8289            }
8290        }
8291        if (ret == 0) {
8292            /* Alg 25, Step 21: Verify M'.
8293             * Alg 20, Steps 4,6-18: Verify digest. */
8294            ret = slhdsakey_verify(key, md, sig);
8295        }
8296    }
8297
8298    return ret;
8299}
8300
8301#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
8302/* Import private key from data.
8303 *
8304 * Includes the public key.
8305 *
8306 * @param [in] key      SLH-DSA key.
8307 * @param [in] priv     Private key data.
8308 * @param [in] privLen  Length of private key data in bytes.
8309 * @return  0 on success.
8310 * @return  BAD_FUNC_ARG when key, key's parameters or priv is NULL.
8311 * @return  BAD_LENGTH_E when inLen does not match parameters.
8312 */
8313int wc_SlhDsaKey_ImportPrivate(SlhDsaKey* key, const byte* priv, word32 privLen)
8314{
8315    int ret = 0;
8316
8317    /* Validate parameters. */
8318    if ((key == NULL) || (key->params == NULL) || (priv == NULL)) {
8319        ret = BAD_FUNC_ARG;
8320    }
8321    /* Check private key data length matches parameters. */
8322    else if ((privLen != 4 * key->params->n)) {
8323        ret = BAD_LENGTH_E;
8324    }
8325    else {
8326        /* Copy private and public key data into SLH-DSA key object. */
8327        XMEMCPY(key->sk, priv, 4U * key->params->n);
8328        key->flags = WC_SLHDSA_FLAG_BOTH_KEYS;
8329#ifdef WOLFSSL_SLHDSA_SHA2
8330        if (SLHDSA_IS_SHA2(key->params->param)) {
8331            ret = slhdsakey_precompute_sha2_midstates(key);
8332        }
8333#endif
8334    }
8335
8336    return ret;
8337}
8338#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
8339
8340/* Import public key from data.
8341 *
8342 * @param [in] key     SLH-DSA key.
8343 * @param [in] pub     Public key data.
8344 * @param [in] pubLen  Length of public key data in bytes.
8345 * @return  0 on success.
8346 * @return  BAD_FUNC_ARG when key, key's parameters or in is NULL.
8347 * @return  BAD_LENGTH_E when inLen does not match parameters.
8348 */
8349int wc_SlhDsaKey_ImportPublic(SlhDsaKey* key, const byte* pub, word32 pubLen)
8350{
8351    int ret = 0;
8352
8353    /* Validate parameters. */
8354    if ((key == NULL) || (key->params == NULL) || (pub == NULL)) {
8355        ret = BAD_FUNC_ARG;
8356    }
8357    /* Check public key data length matches parameters. */
8358    else if ((pubLen != 2 * key->params->n)) {
8359        ret = BAD_LENGTH_E;
8360    }
8361    else {
8362        /* Copy public key data into SLH-DSA key object. */
8363        XMEMCPY(key->sk + 2U * key->params->n, pub, 2U * key->params->n);
8364        key->flags |= WC_SLHDSA_FLAG_PUBLIC;
8365#ifdef WOLFSSL_SLHDSA_SHA2
8366        if (SLHDSA_IS_SHA2(key->params->param)) {
8367            ret = slhdsakey_precompute_sha2_midstates(key);
8368        }
8369#endif
8370    }
8371
8372    return ret;
8373}
8374
8375#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
8376/* Check that the private key is valid.
8377 *
8378 * @param [in] key  SLH-DSA key.
8379 * @return  0 on success.
8380 * @return  BAD_FUNC_ARG when key or key's parameters is NULL.
8381 * @return  MISSING_KEY when private key not set.
8382 * @return  WC_KEY_MISMATCH_E when private key and public seed don't compute
8383 *          public key root.
8384 * @return  MEMORY_E on dynamic memory allocation failure.
8385 * @return  SHAKE-256 error return code on digest failure.
8386 */
8387int wc_SlhDsaKey_CheckKey(SlhDsaKey* key)
8388{
8389    int ret = 0;
8390
8391    /* Validate parameter. */
8392    if ((key == NULL) || (key->params == NULL)) {
8393        ret = BAD_FUNC_ARG;
8394    }
8395    /* Check we have a private key to validate. */
8396    else if ((key->flags & WC_SLHDSA_FLAG_PRIVATE) == 0) {
8397        ret = MISSING_KEY;
8398    }
8399    if (ret == 0) {
8400        byte root[SLHDSA_MAX_N];
8401        byte n = key->params->n;
8402
8403        /* Cache the public key root as making the key overwrites. */
8404        XMEMCPY(root, key->sk + 3 * n, n);
8405        ret = wc_SlhDsaKey_MakeKeyWithRandom(key, key->sk, n, key->sk + n, n,
8406                key->sk + 2 * n, n);
8407        /* Compare computed root with what was cached. */
8408        if ((ret == 0) && (XMEMCMP(root, key->sk + 3 * n, n) != 0)) {
8409            ret = WC_KEY_MISMATCH_E;
8410        }
8411    }
8412
8413    return ret;
8414}
8415
8416/* Export the private key.
8417 *
8418 * Includes the public key.
8419 *
8420 * @param [in]       key      SLH-DSA key.
8421 * @param [out]      priv     Buffer for private key data.
8422 * @param [in, out]  privLen  On in, length of buffer.
8423 *                            On out, length of private key.
8424 * @return  0 on success.
8425 * @return  BAD_FUNC_ARG when key, key's parameters, priv or privLen is NULL.
8426 * @return  BAD_LENGTH_E when privLen is too small for private key.
8427 */
8428int wc_SlhDsaKey_ExportPrivate(SlhDsaKey* key, byte* priv, word32* privLen)
8429{
8430    int ret = 0;
8431
8432    /* Validate parameters. */
8433    if ((key == NULL) || (key->params == NULL) || (priv == NULL) ||
8434            (privLen == NULL)) {
8435        ret = BAD_FUNC_ARG;
8436    }
8437    /* Check private key buffer length. */
8438    else if (*privLen < key->params->n * 4) {
8439        ret = BAD_LENGTH_E;
8440    }
8441    else {
8442        word32 n = (word32)key->params->n;
8443
8444        /* Copy data out and return length. */
8445        XMEMCPY(priv, key->sk, n * 4U);
8446        *privLen = n * 4U;
8447    }
8448
8449    return ret;
8450}
8451#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
8452
8453/* Export the public key.
8454 *
8455 * @param [in]       key     SLH-DSA key.
8456 * @param [out]      pub     Buffer for public key data.
8457 * @param [in, out]  pubLen  On in, length of buffer.
8458 *                           On out, length of public key.
8459 * @return  0 on success.
8460 * @return  BAD_FUNC_ARG when key, key's parameters, pub or pubLen is NULL.
8461 * @return  BAD_LENGTH_E when pubLen is too small for public key.
8462 */
8463int wc_SlhDsaKey_ExportPublic(SlhDsaKey* key, byte* pub, word32* pubLen)
8464{
8465    int ret = 0;
8466
8467    /* Validate parameters. */
8468    if ((key == NULL) || (key->params == NULL) || (pub == NULL) ||
8469            (pubLen == NULL)) {
8470        ret = BAD_FUNC_ARG;
8471    }
8472    /* Check public key buffer length. */
8473    else if (*pubLen < key->params->n * 2) {
8474        ret = BAD_LENGTH_E;
8475    }
8476    else {
8477        word32 n = (word32)key->params->n;
8478
8479        /* Copy data out and return length. */
8480        XMEMCPY(pub, key->sk + n * 2U, n * 2U);
8481        *pubLen = n * 2U;
8482    }
8483
8484    return ret;
8485}
8486
8487#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
8488/* Return the size of the private key for the parameters.
8489 *
8490 * @param [in] key  SLH-DSA key.
8491 * @return  Private key data length in bytes on success.
8492 * @return  BAD_FUNC_ARG when key or key's parameters is NULL.
8493 */
8494int wc_SlhDsaKey_PrivateSize(SlhDsaKey* key)
8495{
8496    int ret;
8497
8498    /* Validate parameters. */
8499    if ((key == NULL) || (key->params == NULL)) {
8500        ret = BAD_FUNC_ARG;
8501    }
8502    else {
8503        /* Length is of 3 seeds and a hash, all n bytes long.  */
8504        ret = key->params->n * 4;
8505    }
8506
8507    return ret;
8508}
8509#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
8510
8511/* Return the size of the public key for the parameters.
8512 *
8513 * @param [in] key  SLH-DSA key.
8514 * @return  Public key data length in bytes on success.
8515 * @return  BAD_FUNC_ARG when key or key's parameters is NULL.
8516 */
8517int wc_SlhDsaKey_PublicSize(SlhDsaKey* key)
8518{
8519    int ret;
8520
8521    /* Validate parameters. */
8522    if ((key == NULL) || (key->params == NULL)) {
8523        ret = BAD_FUNC_ARG;
8524    }
8525    else {
8526        /* Length is of a seed and a hash, both n bytes long.  */
8527        ret = key->params->n * 2;
8528    }
8529
8530    return ret;
8531}
8532
8533/* Return the size of a signature for the parameters.
8534 *
8535 * @param [in] key  SLH-DSA key.
8536 * @return  Signature length in bytes on success.
8537 * @return  BAD_FUNC_ARG when key or key's parameters is NULL.
8538 */
8539int wc_SlhDsaKey_SigSize(SlhDsaKey* key)
8540{
8541    int ret;
8542
8543    /* Validate parameters. */
8544    if ((key == NULL) || (key->params == NULL)) {
8545        ret = BAD_FUNC_ARG;
8546    }
8547    else {
8548        /* Length from the parameters. */
8549        ret = (int)key->params->sigLen;
8550    }
8551
8552    return ret;
8553}
8554
8555#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
8556/* Return the size of the private key for the parameters.
8557 *
8558 * @param [in] param  SLH-DSA parameters.
8559 * @return  Private key data length in bytes on success.
8560 * @return  NOT_COMPILED_IN when parameters not supported.
8561 */
8562int wc_SlhDsaKey_PrivateSizeFromParam(enum SlhDsaParam param)
8563{
8564    int ret;
8565
8566    switch (param) {
8567        case SLHDSA_SHAKE128S:
8568            ret = WC_SLHDSA_SHAKE128S_PRIV_LEN;
8569            break;
8570        case SLHDSA_SHAKE128F:
8571            ret = WC_SLHDSA_SHAKE128F_PRIV_LEN;
8572            break;
8573        case SLHDSA_SHAKE192S:
8574            ret = WC_SLHDSA_SHAKE192S_PRIV_LEN;
8575            break;
8576        case SLHDSA_SHAKE192F:
8577            ret = WC_SLHDSA_SHAKE192F_PRIV_LEN;
8578            break;
8579        case SLHDSA_SHAKE256S:
8580            ret = WC_SLHDSA_SHAKE256S_PRIV_LEN;
8581            break;
8582        case SLHDSA_SHAKE256F:
8583            ret = WC_SLHDSA_SHAKE256F_PRIV_LEN;
8584            break;
8585#ifdef WOLFSSL_SLHDSA_SHA2
8586        case SLHDSA_SHA2_128S:
8587            ret = WC_SLHDSA_SHA2_128S_PRIV_LEN;
8588            break;
8589        case SLHDSA_SHA2_128F:
8590            ret = WC_SLHDSA_SHA2_128F_PRIV_LEN;
8591            break;
8592        case SLHDSA_SHA2_192S:
8593            ret = WC_SLHDSA_SHA2_192S_PRIV_LEN;
8594            break;
8595        case SLHDSA_SHA2_192F:
8596            ret = WC_SLHDSA_SHA2_192F_PRIV_LEN;
8597            break;
8598        case SLHDSA_SHA2_256S:
8599            ret = WC_SLHDSA_SHA2_256S_PRIV_LEN;
8600            break;
8601        case SLHDSA_SHA2_256F:
8602            ret = WC_SLHDSA_SHA2_256F_PRIV_LEN;
8603            break;
8604#endif
8605        default:
8606            ret = NOT_COMPILED_IN;
8607            break;
8608    }
8609
8610    return ret;
8611}
8612#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
8613
8614/* Return the size of the public key for the parameters.
8615 *
8616 * @param [in] param  SLH-DSA parameters.
8617 * @return  Public key data length in bytes on success.
8618 * @return  NOT_COMPILED_IN when parameters not supported.
8619 */
8620int wc_SlhDsaKey_PublicSizeFromParam(enum SlhDsaParam param)
8621{
8622    int ret;
8623
8624    switch (param) {
8625        case SLHDSA_SHAKE128S:
8626            ret = WC_SLHDSA_SHAKE128S_PUB_LEN;
8627            break;
8628        case SLHDSA_SHAKE128F:
8629            ret = WC_SLHDSA_SHAKE128F_PUB_LEN;
8630            break;
8631        case SLHDSA_SHAKE192S:
8632            ret = WC_SLHDSA_SHAKE192S_PUB_LEN;
8633            break;
8634        case SLHDSA_SHAKE192F:
8635            ret = WC_SLHDSA_SHAKE192F_PUB_LEN;
8636            break;
8637        case SLHDSA_SHAKE256S:
8638            ret = WC_SLHDSA_SHAKE256S_PUB_LEN;
8639            break;
8640        case SLHDSA_SHAKE256F:
8641            ret = WC_SLHDSA_SHAKE256F_PUB_LEN;
8642            break;
8643#ifdef WOLFSSL_SLHDSA_SHA2
8644        case SLHDSA_SHA2_128S:
8645            ret = WC_SLHDSA_SHA2_128S_PUB_LEN;
8646            break;
8647        case SLHDSA_SHA2_128F:
8648            ret = WC_SLHDSA_SHA2_128F_PUB_LEN;
8649            break;
8650        case SLHDSA_SHA2_192S:
8651            ret = WC_SLHDSA_SHA2_192S_PUB_LEN;
8652            break;
8653        case SLHDSA_SHA2_192F:
8654            ret = WC_SLHDSA_SHA2_192F_PUB_LEN;
8655            break;
8656        case SLHDSA_SHA2_256S:
8657            ret = WC_SLHDSA_SHA2_256S_PUB_LEN;
8658            break;
8659        case SLHDSA_SHA2_256F:
8660            ret = WC_SLHDSA_SHA2_256F_PUB_LEN;
8661            break;
8662#endif
8663        default:
8664            ret = NOT_COMPILED_IN;
8665            break;
8666    }
8667
8668    return ret;
8669}
8670
8671/* Return the size of a signature for the parameters.
8672 *
8673 * @param [in] param  SLH-DSA parameters.
8674 * @return  Signature length in bytes on success.
8675 * @return  NOT_COMPILED_IN when parameters not supported.
8676 */
8677int wc_SlhDsaKey_SigSizeFromParam(enum SlhDsaParam param)
8678{
8679    int ret;
8680
8681    switch (param) {
8682        case SLHDSA_SHAKE128S:
8683            ret = WC_SLHDSA_SHAKE128S_SIG_LEN;
8684            break;
8685        case SLHDSA_SHAKE128F:
8686            ret = WC_SLHDSA_SHAKE128F_SIG_LEN;
8687            break;
8688        case SLHDSA_SHAKE192S:
8689            ret = WC_SLHDSA_SHAKE192S_SIG_LEN;
8690            break;
8691        case SLHDSA_SHAKE192F:
8692            ret = WC_SLHDSA_SHAKE192F_SIG_LEN;
8693            break;
8694        case SLHDSA_SHAKE256S:
8695            ret = WC_SLHDSA_SHAKE256S_SIG_LEN;
8696            break;
8697        case SLHDSA_SHAKE256F:
8698            ret = WC_SLHDSA_SHAKE256F_SIG_LEN;
8699            break;
8700#ifdef WOLFSSL_SLHDSA_SHA2
8701        case SLHDSA_SHA2_128S:
8702            ret = WC_SLHDSA_SHA2_128S_SIG_LEN;
8703            break;
8704        case SLHDSA_SHA2_128F:
8705            ret = WC_SLHDSA_SHA2_128F_SIG_LEN;
8706            break;
8707        case SLHDSA_SHA2_192S:
8708            ret = WC_SLHDSA_SHA2_192S_SIG_LEN;
8709            break;
8710        case SLHDSA_SHA2_192F:
8711            ret = WC_SLHDSA_SHA2_192F_SIG_LEN;
8712            break;
8713        case SLHDSA_SHA2_256S:
8714            ret = WC_SLHDSA_SHA2_256S_SIG_LEN;
8715            break;
8716        case SLHDSA_SHA2_256F:
8717            ret = WC_SLHDSA_SHA2_256F_SIG_LEN;
8718            break;
8719#endif
8720        default:
8721            ret = NOT_COMPILED_IN;
8722            break;
8723    }
8724
8725    return ret;
8726}
8727
8728/* Find SlhDsaParameters entry for a given param enum. */
8729static const SlhDsaParameters* slhdsa_find_params(enum SlhDsaParam param)
8730{
8731    int i;
8732    for (i = 0; i < SLHDSA_PARAM_LEN; i++) {
8733        if (SlhDsaParams[i].param == param) {
8734            return &SlhDsaParams[i];
8735        }
8736    }
8737    return NULL;
8738}
8739
8740#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
8741/* Decode a DER-encoded SLH-DSA private key (PKCS#8 / OneAsymmetricKey).
8742 *
8743 * RFC 9909 Section 6: The privateKey OCTET STRING contains the raw
8744 * concatenation SK.seed || SK.prf || PK.seed || PK.root (4*n bytes)
8745 * directly, without a nested OCTET STRING wrapper. This differs from
8746 * Ed25519/Ed448 which wrap the key in an additional OCTET STRING.
8747 *
8748 * The parameter set is detected from the AlgorithmIdentifier OID.
8749 * On success, key->params is updated to match the detected parameter set.
8750 *
8751 * @param [in]      input     DER-encoded key data.
8752 * @param [in, out] inOutIdx  Index into input, updated on return.
8753 * @param [in, out] key       SLH-DSA key. Parameter set is auto-detected.
8754 * @param [in]      inSz      Size of input in bytes.
8755 * @return  0 on success.
8756 * @return  BAD_FUNC_ARG when input, inOutIdx, or key is NULL.
8757 * @return  ASN_PARSE_E when the DER cannot be parsed as an SLH-DSA key.
8758 */
8759int wc_SlhDsaKey_PrivateKeyDecode(const byte* input, word32* inOutIdx,
8760    SlhDsaKey* key, word32 inSz)
8761{
8762    int ret = 0;
8763    int length;
8764    int version;
8765    word32 oid = 0;
8766    word32 seqEnd;
8767    word32 savedIdx;
8768    int privSz;
8769    int paramId;
8770    const SlhDsaParameters* params;
8771
8772    if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
8773        return BAD_FUNC_ARG;
8774    }
8775
8776    /* Snapshot the caller's index so failures restore it -- mirrors
8777     * wc_SlhDsaKey_PublicKeyDecode and lets callers chain parsers or
8778     * retry on the same buffer without recomputing the offset. */
8779    savedIdx = *inOutIdx;
8780
8781    /* Parse PKCS#8 OneAsymmetricKey wrapper:
8782     * SEQUENCE { version, AlgorithmIdentifier { OID }, OCTET STRING { key },
8783     *            [0] attributes OPTIONAL, [1] publicKey OPTIONAL }
8784     */
8785    if (GetSequence(input, inOutIdx, &length, inSz) < 0) {
8786        *inOutIdx = savedIdx;
8787        return ASN_PARSE_E;
8788    }
8789    seqEnd = *inOutIdx + (word32)length;
8790
8791    if (GetMyVersion(input, inOutIdx, &version, inSz) < 0) {
8792        *inOutIdx = savedIdx;
8793        return ASN_PARSE_E;
8794    }
8795    if (version != 0 && version != 1) {
8796        *inOutIdx = savedIdx;
8797        return ASN_PARSE_E;
8798    }
8799
8800    if (GetAlgoId(input, inOutIdx, &oid, oidKeyType, inSz) < 0) {
8801        *inOutIdx = savedIdx;
8802        return ASN_PARSE_E;
8803    }
8804
8805    /* Map the OID to an SLH-DSA parameter set.  Pass through NOT_COMPILED_IN
8806     * so callers can distinguish "variant present but not built in" from
8807     * "malformed DER". */
8808    paramId = wc_SlhDsaOidToParam((int)oid);
8809    if (paramId == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) {
8810        *inOutIdx = savedIdx;
8811        return NOT_COMPILED_IN;
8812    }
8813    if (paramId < 0) {
8814        *inOutIdx = savedIdx;
8815        return ASN_PARSE_E;
8816    }
8817    params = slhdsa_find_params((enum SlhDsaParam)paramId);
8818    if (params == NULL) {
8819        *inOutIdx = savedIdx;
8820        return ASN_PARSE_E;
8821    }
8822
8823    /* RFC 9909: privateKey is a single OCTET STRING containing the raw key
8824     * (4*n bytes). Unlike Ed25519/Ed448, there is no nested inner OCTET
8825     * STRING wrapping. */
8826    if (GetOctetString(input, inOutIdx, &privSz, inSz) < 0) {
8827        *inOutIdx = savedIdx;
8828        return ASN_PARSE_E;
8829    }
8830
8831    if (privSz != params->n * 4) {
8832        *inOutIdx = savedIdx;
8833        return ASN_PARSE_E;
8834    }
8835
8836    {
8837        const SlhDsaParameters* oldParams = key->params;
8838        int oldFlags = (int)key->flags;
8839
8840        /* Update the key's parameter set to the detected one. */
8841        key->params = params;
8842
8843        /* Import the raw private key: SK.seed || SK.prf || PK.seed || PK.root */
8844        ret = wc_SlhDsaKey_ImportPrivate(key, input + *inOutIdx,
8845                                         (word32)privSz);
8846        if (ret == 0) {
8847            /* Validate trailing fields per RFC 5958 OneAsymmetricKey:
8848             *   [0] IMPLICIT Attributes  OPTIONAL  -- at most once
8849             *   [1] IMPLICIT PublicKey   OPTIONAL  -- at most once,
8850             *                                        must follow [0]
8851             * Reject duplicates, out-of-order tags, and any other tag.
8852             * The previous code accepted any number of either tag in any
8853             * order. */
8854            const byte tagAttrs = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 0;
8855            const byte tagPub   = ASN_CONTEXT_SPECIFIC | ASN_CONSTRUCTED | 1;
8856            int seenAttrs = 0;
8857            int seenPub   = 0;
8858            *inOutIdx += (word32)privSz;
8859            while (ret == 0 && *inOutIdx < seqEnd) {
8860                byte tlvTag;
8861                int tlvLen;
8862                if (GetASNTag(input, inOutIdx, &tlvTag, inSz) < 0) {
8863                    ret = ASN_PARSE_E;
8864                    break;
8865                }
8866                if (tlvTag == tagAttrs) {
8867                    /* attributes must precede publicKey and appear once */
8868                    if (seenAttrs || seenPub) {
8869                        ret = ASN_PARSE_E;
8870                        break;
8871                    }
8872                    seenAttrs = 1;
8873                }
8874                else if (tlvTag == tagPub) {
8875                    /* publicKey may appear at most once */
8876                    if (seenPub) {
8877                        ret = ASN_PARSE_E;
8878                        break;
8879                    }
8880                    seenPub = 1;
8881                }
8882                else {
8883                    ret = ASN_PARSE_E;
8884                    break;
8885                }
8886                if (GetLength(input, inOutIdx, &tlvLen, inSz) < 0) {
8887                    ret = ASN_PARSE_E;
8888                    break;
8889                }
8890                /* Length must stay within the outer SEQUENCE. */
8891                if (*inOutIdx + (word32)tlvLen > seqEnd) {
8892                    ret = ASN_PARSE_E;
8893                    break;
8894                }
8895                *inOutIdx += (word32)tlvLen;
8896            }
8897            if (ret == 0 && *inOutIdx != seqEnd) {
8898                ret = ASN_PARSE_E;
8899            }
8900            if (ret != 0) {
8901                /* Trailing-field validation failed after ImportPrivate
8902                 * already populated key->sk. Scrub the imported material
8903                 * and roll back state so the caller sees the failure as
8904                 * if the import never happened. Clear FLAG_BOTH_KEYS from
8905                 * the restored flags since we just zeroed the bytes those
8906                 * flags would claim. */
8907                ForceZero(key->sk, (word32)(4 * params->n));
8908                key->params = oldParams;
8909                key->flags = oldFlags & ~((int)WC_SLHDSA_FLAG_BOTH_KEYS);
8910                *inOutIdx = savedIdx;
8911            }
8912        }
8913        else {
8914            /* On failure, restore params/flags. ImportPrivate writes the
8915             * full sk[0..4*n] (private + public material) before any
8916             * SHA-2 precompute step, so a precompute failure can leave
8917             * the entire sk dirty -- clear it and clear the matching
8918             * flags so flags can never claim valid bytes that we zeroed.
8919             * BAD_LENGTH_E is detected before any write, so no zeroing
8920             * (or flag scrubbing) is needed in that case. */
8921            if (ret != WC_NO_ERR_TRACE(BAD_LENGTH_E)) {
8922                ForceZero(key->sk, (word32)(4 * params->n));
8923                key->flags = oldFlags & ~((int)WC_SLHDSA_FLAG_BOTH_KEYS);
8924            }
8925            else {
8926                key->flags = oldFlags;
8927            }
8928            key->params = oldParams;
8929            *inOutIdx = savedIdx;
8930        }
8931    }
8932
8933    return ret;
8934}
8935#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
8936
8937/* Decode a DER-encoded SLH-DSA public key (SubjectPublicKeyInfo).
8938 *
8939 * The parameter set is detected from the AlgorithmIdentifier OID.
8940 * On success, key->params is updated to match the detected parameter set.
8941 *
8942 * @param [in]      input     DER-encoded key data.
8943 * @param [in, out] inOutIdx  Index into input, updated on return.
8944 * @param [in, out] key       SLH-DSA key. Parameter set is auto-detected.
8945 * @param [in]      inSz      Size of input in bytes.
8946 * @return  0 on success.
8947 * @return  BAD_FUNC_ARG when input, inOutIdx, or key is NULL.
8948 * @return  ASN_PARSE_E when the DER cannot be parsed as an SLH-DSA key.
8949 */
8950int wc_SlhDsaKey_PublicKeyDecode(const byte* input, word32* inOutIdx,
8951    SlhDsaKey* key, word32 inSz)
8952{
8953    int ret;
8954    int keytype = ANONk;
8955    int paramId;
8956    const SlhDsaParameters* params;
8957    const SlhDsaParameters* oldParams;
8958    const byte* pubKeyPtr = NULL;
8959    word32 pubKeyLen = 0;
8960    word32 savedIdx;
8961    int oldFlags;
8962
8963    if ((input == NULL) || (inOutIdx == NULL) || (key == NULL) || (inSz == 0)) {
8964        return BAD_FUNC_ARG;
8965    }
8966
8967    savedIdx = *inOutIdx;
8968
8969    /* Fast path: if the caller initialised the key with a parameter set,
8970     * treat the entire window from *inOutIdx to inSz as a candidate raw
8971     * public key and let wc_SlhDsaKey_ImportPublic decide via its length
8972     * check. The window must contain exactly 2*n bytes for the configured
8973     * parameter set -- callers chaining decoders must pass inSz scoped to
8974     * just the public-key buffer or the import will reject the length and
8975     * fall through to SPKI parsing. Mirrors the raw-first fallback in
8976     * wc_Dilithium_PublicKeyDecode and wc_Falcon_PublicKeyDecode so all PQ
8977     * public-key decoders accept either raw bytes or SPKI.
8978     *
8979     * The length check in ImportPublic is the disambiguator: a real SPKI
8980     * for any SLH-DSA variant carries ~19 bytes of AlgorithmIdentifier and
8981     * BIT STRING overhead on top of the 2*n public bytes, so SPKI input
8982     * never collides with the 2*n raw length and falls through cleanly. */
8983    if (key->params != NULL && savedIdx < inSz) {
8984        word32 windowSz = inSz - savedIdx;
8985        int n = key->params->n;
8986        oldFlags = key->flags;
8987        ret = wc_SlhDsaKey_ImportPublic(key, input + savedIdx, windowSz);
8988        if (ret == 0) {
8989            *inOutIdx += windowSz;
8990            return 0;
8991        }
8992        /* Fall through to SPKI parsing. BAD_LENGTH_E is detected before
8993         * any write (typical SPKI input), so there is nothing to scrub.
8994         * On SHA-2 precompute failure ImportPublic has written only the
8995         * public half at sk[2*n .. 4*n] - leave the private half
8996         * sk[0 .. 2*n] untouched in case the caller imported it earlier.
8997         * When we do scrub the public half, also clear FLAG_PUBLIC from
8998         * the restored flags so flags cannot claim a public key over the
8999         * zeroed bytes (the caller may have had FLAG_PUBLIC set from a
9000         * prior import). */
9001        if (ret != WC_NO_ERR_TRACE(BAD_LENGTH_E)) {
9002            ForceZero(key->sk + 2 * n, (word32)(2 * n));
9003            key->flags = oldFlags & ~((int)WC_SLHDSA_FLAG_PUBLIC);
9004        }
9005        else {
9006            key->flags = oldFlags;
9007        }
9008    }
9009
9010    /* Use ANONk to auto-detect the OID from the SPKI AlgorithmIdentifier
9011     * in a single parse. (PrivateKeyDecode parses each DER element
9012     * manually because the PKCS#8 OneAsymmetricKey layout differs from
9013     * SPKI and has no matching helper.) */
9014    ret = DecodeAsymKeyPublic_Assign(input, inOutIdx, inSz, &pubKeyPtr,
9015                                     &pubKeyLen, &keytype);
9016    if (ret != 0) {
9017        return ret;
9018    }
9019
9020    /* Map the detected OID key type to an SLH-DSA parameter set.  Pass
9021     * through NOT_COMPILED_IN so callers see the specific reason
9022     * (unsupported variant) rather than a generic parse error. */
9023    paramId = wc_SlhDsaOidToParam(keytype);
9024    if (paramId == WC_NO_ERR_TRACE(NOT_COMPILED_IN)) {
9025        *inOutIdx = savedIdx;
9026        return NOT_COMPILED_IN;
9027    }
9028    if (paramId < 0) {
9029        *inOutIdx = savedIdx;
9030        return ASN_PARSE_E;
9031    }
9032    params = slhdsa_find_params((enum SlhDsaParam)paramId);
9033    if (params == NULL) {
9034        *inOutIdx = savedIdx;
9035        return ASN_PARSE_E;
9036    }
9037
9038    oldFlags = key->flags;
9039    oldParams = key->params;
9040    key->params = params;
9041    ret = wc_SlhDsaKey_ImportPublic(key, pubKeyPtr, pubKeyLen);
9042    if (ret != 0) {
9043        /* Restore params/flags/inOutIdx. ImportPublic writes only the
9044         * public half (sk[2*n .. 4*n]) and only after the length check
9045         * passes; preserve any prior private bytes the caller may have
9046         * imported into sk[0 .. 2*n]. When we scrub the public half on
9047         * a post-write failure, also clear FLAG_PUBLIC from the restored
9048         * flags so flags cannot claim a public key over the zeroed bytes
9049         * (the caller may have had FLAG_PUBLIC set from a prior import). */
9050        if (ret != WC_NO_ERR_TRACE(BAD_LENGTH_E)) {
9051            ForceZero(key->sk + 2 * params->n, (word32)(2 * params->n));
9052            key->flags = oldFlags & ~((int)WC_SLHDSA_FLAG_PUBLIC);
9053        }
9054        else {
9055            key->flags = oldFlags;
9056        }
9057        key->params = oldParams;
9058        *inOutIdx = savedIdx;
9059    }
9060
9061    return ret;
9062}
9063
9064#ifdef WC_ENABLE_ASYM_KEY_EXPORT
9065/* Encode an SLH-DSA public key to DER.
9066 *
9067 * Pass NULL for output to get the size of the encoding.
9068 *
9069 * @param [in]  key       SLH-DSA key object.
9070 * @param [out] output    Buffer to put encoded data in.
9071 * @param [in]  inLen     Size of buffer in bytes.
9072 * @param [in]  withAlg   Whether to use SubjectPublicKeyInfo format.
9073 * @return  Size of encoded data in bytes on success.
9074 * @return  BAD_FUNC_ARG when key/key->params is NULL or param is unknown.
9075 * @return  NOT_COMPILED_IN when key->params names a known SLH-DSA variant
9076 *          whose parameter set isn't compiled in. In practice unreachable
9077 *          because SlhDsaParams[] is itself gated on the build, but the
9078 *          contract matches wc_SlhDsaOidToParam for forward compatibility.
9079 */
9080int wc_SlhDsaKey_PublicKeyToDer(SlhDsaKey* key, byte* output, word32 inLen,
9081    int withAlg)
9082{
9083    int ret;
9084    byte pubKey[WC_SLHDSA_MAX_PUB_LEN];
9085    word32 pubKeyLen = (word32)sizeof(pubKey);
9086    int keytype;
9087
9088    if ((key == NULL) || (key->params == NULL)) {
9089        return BAD_FUNC_ARG;
9090    }
9091
9092    keytype = wc_SlhDsaParamToOid(key->params->param);
9093    if (keytype < 0) {
9094        return keytype;
9095    }
9096
9097    ret = wc_SlhDsaKey_ExportPublic(key, pubKey, &pubKeyLen);
9098    if (ret == 0) {
9099        ret = SetAsymKeyDerPublic(pubKey, pubKeyLen, output, inLen, keytype,
9100                                  withAlg);
9101    }
9102
9103    return ret;
9104}
9105
9106#ifndef WOLFSSL_SLHDSA_VERIFY_ONLY
9107/* Encode an SLH-DSA private key to DER (PKCS#8 / OneAsymmetricKey).
9108 *
9109 * RFC 9909: The privateKey OCTET STRING contains the raw 4*n bytes
9110 * (SK.seed || SK.prf || PK.seed || PK.root) directly, without a nested
9111 * OCTET STRING wrapper. This differs from Ed25519/Ed448 which use a
9112 * double OCTET STRING wrapping.
9113 *
9114 * Pass NULL for output to get the required buffer size.
9115 *
9116 * @param [in]  key       SLH-DSA key object.
9117 * @param [out] output    Buffer to put encoded data in (or NULL for size).
9118 * @param [in]  inLen     Size of buffer in bytes.
9119 * @return  Size of encoded data in bytes on success.
9120 * @return  BAD_FUNC_ARG when key/key->params is NULL or param is unknown.
9121 * @return  NOT_COMPILED_IN when key->params names a known SLH-DSA variant
9122 *          whose parameter set isn't compiled in (in practice unreachable;
9123 *          SlhDsaParams[] is itself gated on the build).
9124 * @return  MISSING_KEY when private key not set.
9125 * @return  BUFFER_E when output buffer is too small.
9126 * @return  ASN_PARSE_E when SetMyVersion returns an unexpected size
9127 *          (internal encoder consistency check).
9128 */
9129int wc_SlhDsaKey_KeyToDer(SlhDsaKey* key, byte* output, word32 inLen)
9130{
9131    int keytype;
9132    int n;
9133    word32 privSz, algoSz, verSz, seqSz, sz;
9134
9135    if ((key == NULL) || (key->params == NULL)) {
9136        return BAD_FUNC_ARG;
9137    }
9138    if ((key->flags & WC_SLHDSA_FLAG_PRIVATE) == 0) {
9139        return MISSING_KEY;
9140    }
9141
9142    keytype = wc_SlhDsaParamToOid(key->params->param);
9143    if (keytype < 0) {
9144        return keytype;
9145    }
9146
9147    n = key->params->n;
9148    /* RFC 9909: bare OCTET STRING containing 4*n raw key bytes */
9149    privSz = SetOctetString((word32)(n * 4), NULL) + (word32)(n * 4);
9150    algoSz = SetAlgoID(keytype, NULL, oidKeyType, 0);
9151    verSz  = 3; /* ASN_INTEGER(1) + length(1) + version_byte(1) */
9152    seqSz  = SetSequence(verSz + algoSz + privSz, NULL);
9153    sz     = seqSz + verSz + algoSz + privSz;
9154
9155    if (output == NULL) {
9156        return (int)sz;
9157    }
9158    if (sz > inLen) {
9159        return BUFFER_E;
9160    }
9161
9162    {
9163        word32 idx = 0;
9164        int actualVerSz;
9165        idx += SetSequence(verSz + algoSz + privSz, output + idx);
9166        actualVerSz = SetMyVersion(0, output + idx, FALSE);
9167        if (actualVerSz != (int)verSz) {
9168            /* Internal consistency: if SetMyVersion ever returns a size
9169             * different from the verSz we used to compute the total,
9170             * something in the encoder changed -- this is not a caller
9171             * buffer-size issue, so report it as an ASN encoding error. */
9172            return ASN_PARSE_E;
9173        }
9174        idx += (word32)actualVerSz;
9175        idx += SetAlgoID(keytype, output + idx, oidKeyType, 0);
9176        idx += SetOctetString((word32)(n * 4), output + idx);
9177        XMEMCPY(output + idx, key->sk, (word32)(n * 4));
9178        idx += (word32)(n * 4);
9179        return (int)idx;
9180    }
9181}
9182
9183/* Encode an SLH-DSA private key to DER (PKCS#8 / OneAsymmetricKey).
9184 *
9185 * For SLH-DSA, RFC 9909 packs SK.seed || SK.prf || PK.seed || PK.root into
9186 * a single OCTET STRING, so there is no separate "private-only" encoding.
9187 * This function is intentionally an alias of wc_SlhDsaKey_KeyToDer, kept
9188 * for API parity with Ed25519/Ed448 which do have a distinct private form.
9189 *
9190 * @param [in]  key       SLH-DSA key object.
9191 * @param [out] output    Buffer to put encoded data in (or NULL for size).
9192 * @param [in]  inLen     Size of buffer in bytes.
9193 * @return  Size of encoded data in bytes on success.
9194 * @return  BAD_FUNC_ARG when key is NULL.
9195 * @return  MISSING_KEY when private key not set.
9196 * @return  BUFFER_E when output buffer is too small.
9197 */
9198int wc_SlhDsaKey_PrivateKeyToDer(SlhDsaKey* key, byte* output, word32 inLen)
9199{
9200    return wc_SlhDsaKey_KeyToDer(key, output, inLen);
9201}
9202#endif /* !WOLFSSL_SLHDSA_VERIFY_ONLY */
9203#endif /* WC_ENABLE_ASYM_KEY_EXPORT */
9204
9205#endif /* WOLFSSL_HAVE_SLHDSA */