Unnamed: 0
int64
0
0
repo_id
stringlengths
5
186
file_path
stringlengths
15
223
content
stringlengths
1
32.8M
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/test_psa_constant_names.py
#!/usr/bin/env python3 """Test the program psa_constant_names. Gather constant names from header files and test cases. Compile a C program to print out their numerical values, feed these numerical values to psa_constant_names, and check that the output is the original name. Return 0 if all test cases pass, 1 if the output was not always as expected, or 1 (with a Python backtrace) if there was an operational error. """ # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse from collections import namedtuple import os import re import subprocess import sys from typing import Iterable, List, Optional, Tuple import scripts_path # pylint: disable=unused-import from mbedtls_dev import c_build_helper from mbedtls_dev.macro_collector import InputsForTest, PSAMacroEnumerator from mbedtls_dev import typing_util def gather_inputs(headers: Iterable[str], test_suites: Iterable[str], inputs_class=InputsForTest) -> PSAMacroEnumerator: """Read the list of inputs to test psa_constant_names with.""" inputs = inputs_class() for header in headers: inputs.parse_header(header) for test_cases in test_suites: inputs.parse_test_cases(test_cases) inputs.add_numerical_values() inputs.gather_arguments() return inputs def run_c(type_word: str, expressions: Iterable[str], include_path: Optional[str] = None, keep_c: bool = False) -> List[str]: """Generate and run a program to print out numerical values of C expressions.""" if type_word == 'status': cast_to = 'long' printf_format = '%ld' else: cast_to = 'unsigned long' printf_format = '0x%08lx' return c_build_helper.get_c_expression_values( cast_to, printf_format, expressions, caller='test_psa_constant_names.py for {} values'.format(type_word), file_label=type_word, header='#include <psa/crypto.h>', include_path=include_path, keep_c=keep_c ) NORMALIZE_STRIP_RE = re.compile(r'\s+') def normalize(expr: str) -> str: """Normalize the C expression so as not to care about trivial differences. Currently "trivial differences" means whitespace. """ return re.sub(NORMALIZE_STRIP_RE, '', expr) def collect_values(inputs: InputsForTest, type_word: str, include_path: Optional[str] = None, keep_c: bool = False) -> Tuple[List[str], List[str]]: """Generate expressions using known macro names and calculate their values. Return a list of pairs of (expr, value) where expr is an expression and value is a string representation of its integer value. """ names = inputs.get_names(type_word) expressions = sorted(inputs.generate_expressions(names)) values = run_c(type_word, expressions, include_path=include_path, keep_c=keep_c) return expressions, values class Tests: """An object representing tests and their results.""" Error = namedtuple('Error', ['type', 'expression', 'value', 'output']) def __init__(self, options) -> None: self.options = options self.count = 0 self.errors = [] #type: List[Tests.Error] def run_one(self, inputs: InputsForTest, type_word: str) -> None: """Test psa_constant_names for the specified type. Run the program on the names for this type. Use the inputs to figure out what arguments to pass to macros that take arguments. """ expressions, values = collect_values(inputs, type_word, include_path=self.options.include, keep_c=self.options.keep_c) output_bytes = subprocess.check_output([self.options.program, type_word] + values) output = output_bytes.decode('ascii') outputs = output.strip().split('\n') self.count += len(expressions) for expr, value, output in zip(expressions, values, outputs): if self.options.show: sys.stdout.write('{} {}\t{}\n'.format(type_word, value, output)) if normalize(expr) != normalize(output): self.errors.append(self.Error(type=type_word, expression=expr, value=value, output=output)) def run_all(self, inputs: InputsForTest) -> None: """Run psa_constant_names on all the gathered inputs.""" for type_word in ['status', 'algorithm', 'ecc_curve', 'dh_group', 'key_type', 'key_usage']: self.run_one(inputs, type_word) def report(self, out: typing_util.Writable) -> None: """Describe each case where the output is not as expected. Write the errors to ``out``. Also write a total. """ for error in self.errors: out.write('For {} "{}", got "{}" (value: {})\n' .format(error.type, error.expression, error.output, error.value)) out.write('{} test cases'.format(self.count)) if self.errors: out.write(', {} FAIL\n'.format(len(self.errors))) else: out.write(' PASS\n') HEADERS = ['psa/crypto.h', 'psa/crypto_extra.h', 'psa/crypto_values.h'] TEST_SUITES = ['tests/suites/test_suite_psa_crypto_metadata.data'] def main(): parser = argparse.ArgumentParser(description=globals()['__doc__']) parser.add_argument('--include', '-I', action='append', default=['include'], help='Directory for header files') parser.add_argument('--keep-c', action='store_true', dest='keep_c', default=False, help='Keep the intermediate C file') parser.add_argument('--no-keep-c', action='store_false', dest='keep_c', help='Don\'t keep the intermediate C file (default)') parser.add_argument('--program', default='programs/psa/psa_constant_names', help='Program to test') parser.add_argument('--show', action='store_true', help='Show tested values on stdout') parser.add_argument('--no-show', action='store_false', dest='show', help='Don\'t show tested values (default)') options = parser.parse_args() headers = [os.path.join(options.include[0], h) for h in HEADERS] inputs = gather_inputs(headers, TEST_SUITES) tests = Tests(options) tests.run_all(inputs) tests.report(sys.stdout) if tests.errors: sys.exit(1) if __name__ == '__main__': main()
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/gen_pkcs1_v21_sign_verify.pl
#!/usr/bin/env perl # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use strict; my $file = shift; open(TEST_DATA, "$file") or die "Opening test cases '$file': $!"; sub get_val($$) { my $str = shift; my $name = shift; my $val = ""; while(my $line = <TEST_DATA>) { next if($line !~ /^# $str/); last; } while(my $line = <TEST_DATA>) { last if($line eq "\r\n"); $val .= $line; } $val =~ s/[ \r\n]//g; return $val; } my $state = 0; my $val_n = ""; my $val_e = ""; my $val_p = ""; my $val_q = ""; my $mod = 0; my $cnt = 1; while (my $line = <TEST_DATA>) { next if ($line !~ /^# Example/); ( $mod ) = ($line =~ /A (\d+)/); $val_n = get_val("RSA modulus n", "N"); $val_e = get_val("RSA public exponent e", "E"); $val_p = get_val("Prime p", "P"); $val_q = get_val("Prime q", "Q"); for(my $i = 1; $i <= 6; $i++) { my $val_m = get_val("Message to be", "M"); my $val_salt = get_val("Salt", "Salt"); my $val_sig = get_val("Signature", "Sig"); print("RSASSA-PSS Signature Example ${cnt}_${i}\n"); print("pkcs1_rsassa_pss_sign:$mod:16:\"$val_p\":16:\"$val_q\":16:\"$val_n\":16:\"$val_e\":SIG_RSA_SHA1:MBEDTLS_MD_SHA1"); print(":\"$val_m\""); print(":\"$val_salt\""); print(":\"$val_sig\":0"); print("\n\n"); print("RSASSA-PSS Signature Example ${cnt}_${i} (verify)\n"); print("pkcs1_rsassa_pss_verify:$mod:16:\"$val_n\":16:\"$val_e\":SIG_RSA_SHA1:MBEDTLS_MD_SHA1"); print(":\"$val_m\""); print(":\"$val_salt\""); print(":\"$val_sig\":0"); print("\n\n"); } $cnt++; } close(TEST_DATA);
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/test_generate_test_code.py
#!/usr/bin/env python3 # Unit test for generate_test_code.py # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ Unit tests for generate_test_code.py """ from io import StringIO from unittest import TestCase, main as unittest_main from unittest.mock import patch from generate_test_code import gen_dependencies, gen_dependencies_one_line from generate_test_code import gen_function_wrapper, gen_dispatch from generate_test_code import parse_until_pattern, GeneratorInputError from generate_test_code import parse_suite_dependencies from generate_test_code import parse_function_dependencies from generate_test_code import parse_function_arguments, parse_function_code from generate_test_code import parse_functions, END_HEADER_REGEX from generate_test_code import END_SUITE_HELPERS_REGEX, escaped_split from generate_test_code import parse_test_data, gen_dep_check from generate_test_code import gen_expression_check, write_dependencies from generate_test_code import write_parameters, gen_suite_dep_checks from generate_test_code import gen_from_test_data class GenDep(TestCase): """ Test suite for function gen_dep() """ def test_dependencies_list(self): """ Test that gen_dep() correctly creates dependencies for given dependency list. :return: """ dependencies = ['DEP1', 'DEP2'] dep_start, dep_end = gen_dependencies(dependencies) preprocessor1, preprocessor2 = dep_start.splitlines() endif1, endif2 = dep_end.splitlines() self.assertEqual(preprocessor1, '#if defined(DEP1)', 'Preprocessor generated incorrectly') self.assertEqual(preprocessor2, '#if defined(DEP2)', 'Preprocessor generated incorrectly') self.assertEqual(endif1, '#endif /* DEP2 */', 'Preprocessor generated incorrectly') self.assertEqual(endif2, '#endif /* DEP1 */', 'Preprocessor generated incorrectly') def test_disabled_dependencies_list(self): """ Test that gen_dep() correctly creates dependencies for given dependency list. :return: """ dependencies = ['!DEP1', '!DEP2'] dep_start, dep_end = gen_dependencies(dependencies) preprocessor1, preprocessor2 = dep_start.splitlines() endif1, endif2 = dep_end.splitlines() self.assertEqual(preprocessor1, '#if !defined(DEP1)', 'Preprocessor generated incorrectly') self.assertEqual(preprocessor2, '#if !defined(DEP2)', 'Preprocessor generated incorrectly') self.assertEqual(endif1, '#endif /* !DEP2 */', 'Preprocessor generated incorrectly') self.assertEqual(endif2, '#endif /* !DEP1 */', 'Preprocessor generated incorrectly') def test_mixed_dependencies_list(self): """ Test that gen_dep() correctly creates dependencies for given dependency list. :return: """ dependencies = ['!DEP1', 'DEP2'] dep_start, dep_end = gen_dependencies(dependencies) preprocessor1, preprocessor2 = dep_start.splitlines() endif1, endif2 = dep_end.splitlines() self.assertEqual(preprocessor1, '#if !defined(DEP1)', 'Preprocessor generated incorrectly') self.assertEqual(preprocessor2, '#if defined(DEP2)', 'Preprocessor generated incorrectly') self.assertEqual(endif1, '#endif /* DEP2 */', 'Preprocessor generated incorrectly') self.assertEqual(endif2, '#endif /* !DEP1 */', 'Preprocessor generated incorrectly') def test_empty_dependencies_list(self): """ Test that gen_dep() correctly creates dependencies for given dependency list. :return: """ dependencies = [] dep_start, dep_end = gen_dependencies(dependencies) self.assertEqual(dep_start, '', 'Preprocessor generated incorrectly') self.assertEqual(dep_end, '', 'Preprocessor generated incorrectly') def test_large_dependencies_list(self): """ Test that gen_dep() correctly creates dependencies for given dependency list. :return: """ dependencies = [] count = 10 for i in range(count): dependencies.append('DEP%d' % i) dep_start, dep_end = gen_dependencies(dependencies) self.assertEqual(len(dep_start.splitlines()), count, 'Preprocessor generated incorrectly') self.assertEqual(len(dep_end.splitlines()), count, 'Preprocessor generated incorrectly') class GenDepOneLine(TestCase): """ Test Suite for testing gen_dependencies_one_line() """ def test_dependencies_list(self): """ Test that gen_dep() correctly creates dependencies for given dependency list. :return: """ dependencies = ['DEP1', 'DEP2'] dep_str = gen_dependencies_one_line(dependencies) self.assertEqual(dep_str, '#if defined(DEP1) && defined(DEP2)', 'Preprocessor generated incorrectly') def test_disabled_dependencies_list(self): """ Test that gen_dep() correctly creates dependencies for given dependency list. :return: """ dependencies = ['!DEP1', '!DEP2'] dep_str = gen_dependencies_one_line(dependencies) self.assertEqual(dep_str, '#if !defined(DEP1) && !defined(DEP2)', 'Preprocessor generated incorrectly') def test_mixed_dependencies_list(self): """ Test that gen_dep() correctly creates dependencies for given dependency list. :return: """ dependencies = ['!DEP1', 'DEP2'] dep_str = gen_dependencies_one_line(dependencies) self.assertEqual(dep_str, '#if !defined(DEP1) && defined(DEP2)', 'Preprocessor generated incorrectly') def test_empty_dependencies_list(self): """ Test that gen_dep() correctly creates dependencies for given dependency list. :return: """ dependencies = [] dep_str = gen_dependencies_one_line(dependencies) self.assertEqual(dep_str, '', 'Preprocessor generated incorrectly') def test_large_dependencies_list(self): """ Test that gen_dep() correctly creates dependencies for given dependency list. :return: """ dependencies = [] count = 10 for i in range(count): dependencies.append('DEP%d' % i) dep_str = gen_dependencies_one_line(dependencies) expected = '#if ' + ' && '.join(['defined(%s)' % x for x in dependencies]) self.assertEqual(dep_str, expected, 'Preprocessor generated incorrectly') class GenFunctionWrapper(TestCase): """ Test Suite for testing gen_function_wrapper() """ def test_params_unpack(self): """ Test that params are properly unpacked in the function call. :return: """ code = gen_function_wrapper('test_a', '', ('a', 'b', 'c', 'd')) expected = ''' void test_a_wrapper( void ** params ) { test_a( a, b, c, d ); } ''' self.assertEqual(code, expected) def test_local(self): """ Test that params are properly unpacked in the function call. :return: """ code = gen_function_wrapper('test_a', 'int x = 1;', ('x', 'b', 'c', 'd')) expected = ''' void test_a_wrapper( void ** params ) { int x = 1; test_a( x, b, c, d ); } ''' self.assertEqual(code, expected) def test_empty_params(self): """ Test that params are properly unpacked in the function call. :return: """ code = gen_function_wrapper('test_a', '', ()) expected = ''' void test_a_wrapper( void ** params ) { (void)params; test_a( ); } ''' self.assertEqual(code, expected) class GenDispatch(TestCase): """ Test suite for testing gen_dispatch() """ def test_dispatch(self): """ Test that dispatch table entry is generated correctly. :return: """ code = gen_dispatch('test_a', ['DEP1', 'DEP2']) expected = ''' #if defined(DEP1) && defined(DEP2) test_a_wrapper, #else NULL, #endif ''' self.assertEqual(code, expected) def test_empty_dependencies(self): """ Test empty dependency list. :return: """ code = gen_dispatch('test_a', []) expected = ''' test_a_wrapper, ''' self.assertEqual(code, expected) class StringIOWrapper(StringIO): """ file like class to mock file object in tests. """ def __init__(self, file_name, data, line_no=0): """ Init file handle. :param file_name: :param data: :param line_no: """ super(StringIOWrapper, self).__init__(data) self.line_no = line_no self.name = file_name def next(self): """ Iterator method. This method overrides base class's next method and extends the next method to count the line numbers as each line is read. :return: Line read from file. """ parent = super(StringIOWrapper, self) line = parent.__next__() return line def readline(self, _length=0): """ Wrap the base class readline. :param length: :return: """ line = super(StringIOWrapper, self).readline() if line is not None: self.line_no += 1 return line class ParseUntilPattern(TestCase): """ Test Suite for testing parse_until_pattern(). """ def test_suite_headers(self): """ Test that suite headers are parsed correctly. :return: """ data = '''#include "mbedtls/ecp.h" #define ECP_PF_UNKNOWN -1 /* END_HEADER */ ''' expected = '''#line 1 "test_suite_ut.function" #include "mbedtls/ecp.h" #define ECP_PF_UNKNOWN -1 ''' stream = StringIOWrapper('test_suite_ut.function', data, line_no=0) headers = parse_until_pattern(stream, END_HEADER_REGEX) self.assertEqual(headers, expected) def test_line_no(self): """ Test that #line is set to correct line no. in source .function file. :return: """ data = '''#include "mbedtls/ecp.h" #define ECP_PF_UNKNOWN -1 /* END_HEADER */ ''' offset_line_no = 5 expected = '''#line %d "test_suite_ut.function" #include "mbedtls/ecp.h" #define ECP_PF_UNKNOWN -1 ''' % (offset_line_no + 1) stream = StringIOWrapper('test_suite_ut.function', data, offset_line_no) headers = parse_until_pattern(stream, END_HEADER_REGEX) self.assertEqual(headers, expected) def test_no_end_header_comment(self): """ Test that InvalidFileFormat is raised when end header comment is missing. :return: """ data = '''#include "mbedtls/ecp.h" #define ECP_PF_UNKNOWN -1 ''' stream = StringIOWrapper('test_suite_ut.function', data) self.assertRaises(GeneratorInputError, parse_until_pattern, stream, END_HEADER_REGEX) class ParseSuiteDependencies(TestCase): """ Test Suite for testing parse_suite_dependencies(). """ def test_suite_dependencies(self): """ :return: """ data = ''' * depends_on:MBEDTLS_ECP_C * END_DEPENDENCIES */ ''' expected = ['MBEDTLS_ECP_C'] stream = StringIOWrapper('test_suite_ut.function', data) dependencies = parse_suite_dependencies(stream) self.assertEqual(dependencies, expected) def test_no_end_dep_comment(self): """ Test that InvalidFileFormat is raised when end dep comment is missing. :return: """ data = ''' * depends_on:MBEDTLS_ECP_C ''' stream = StringIOWrapper('test_suite_ut.function', data) self.assertRaises(GeneratorInputError, parse_suite_dependencies, stream) def test_dependencies_split(self): """ Test that InvalidFileFormat is raised when end dep comment is missing. :return: """ data = ''' * depends_on:MBEDTLS_ECP_C:A:B: C : D :F : G: !H * END_DEPENDENCIES */ ''' expected = ['MBEDTLS_ECP_C', 'A', 'B', 'C', 'D', 'F', 'G', '!H'] stream = StringIOWrapper('test_suite_ut.function', data) dependencies = parse_suite_dependencies(stream) self.assertEqual(dependencies, expected) class ParseFuncDependencies(TestCase): """ Test Suite for testing parse_function_dependencies() """ def test_function_dependencies(self): """ Test that parse_function_dependencies() correctly parses function dependencies. :return: """ line = '/* BEGIN_CASE ' \ 'depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */' expected = ['MBEDTLS_ENTROPY_NV_SEED', 'MBEDTLS_FS_IO'] dependencies = parse_function_dependencies(line) self.assertEqual(dependencies, expected) def test_no_dependencies(self): """ Test that parse_function_dependencies() correctly parses function dependencies. :return: """ line = '/* BEGIN_CASE */' dependencies = parse_function_dependencies(line) self.assertEqual(dependencies, []) def test_tolerance(self): """ Test that parse_function_dependencies() correctly parses function dependencies. :return: """ line = '/* BEGIN_CASE depends_on:MBEDTLS_FS_IO: A : !B:C : F*/' dependencies = parse_function_dependencies(line) self.assertEqual(dependencies, ['MBEDTLS_FS_IO', 'A', '!B', 'C', 'F']) class ParseFuncSignature(TestCase): """ Test Suite for parse_function_arguments(). """ def test_int_and_char_params(self): """ Test int and char parameters parsing :return: """ line = 'void entropy_threshold( char * a, int b, int result )' args, local, arg_dispatch = parse_function_arguments(line) self.assertEqual(args, ['char*', 'int', 'int']) self.assertEqual(local, '') self.assertEqual(arg_dispatch, ['(char *) params[0]', '*( (int *) params[1] )', '*( (int *) params[2] )']) def test_hex_params(self): """ Test hex parameters parsing :return: """ line = 'void entropy_threshold( char * a, data_t * h, int result )' args, local, arg_dispatch = parse_function_arguments(line) self.assertEqual(args, ['char*', 'hex', 'int']) self.assertEqual(local, ' data_t data1 = {(uint8_t *) params[1], ' '*( (uint32_t *) params[2] )};\n') self.assertEqual(arg_dispatch, ['(char *) params[0]', '&data1', '*( (int *) params[3] )']) def test_unsupported_arg(self): """ Test unsupported arguments (not among int, char * and data_t) :return: """ line = 'void entropy_threshold( char * a, data_t * h, char result )' self.assertRaises(ValueError, parse_function_arguments, line) def test_no_params(self): """ Test no parameters. :return: """ line = 'void entropy_threshold()' args, local, arg_dispatch = parse_function_arguments(line) self.assertEqual(args, []) self.assertEqual(local, '') self.assertEqual(arg_dispatch, []) class ParseFunctionCode(TestCase): """ Test suite for testing parse_function_code() """ def test_no_function(self): """ Test no test function found. :return: """ data = ''' No test function ''' stream = StringIOWrapper('test_suite_ut.function', data) err_msg = 'file: test_suite_ut.function - Test functions not found!' self.assertRaisesRegex(GeneratorInputError, err_msg, parse_function_code, stream, [], []) def test_no_end_case_comment(self): """ Test missing end case. :return: """ data = ''' void test_func() { } ''' stream = StringIOWrapper('test_suite_ut.function', data) err_msg = r'file: test_suite_ut.function - '\ 'end case pattern .*? not found!' self.assertRaisesRegex(GeneratorInputError, err_msg, parse_function_code, stream, [], []) @patch("generate_test_code.parse_function_arguments") def test_function_called(self, parse_function_arguments_mock): """ Test parse_function_code() :return: """ parse_function_arguments_mock.return_value = ([], '', []) data = ''' void test_func() { } ''' stream = StringIOWrapper('test_suite_ut.function', data) self.assertRaises(GeneratorInputError, parse_function_code, stream, [], []) self.assertTrue(parse_function_arguments_mock.called) parse_function_arguments_mock.assert_called_with('void test_func()\n') @patch("generate_test_code.gen_dispatch") @patch("generate_test_code.gen_dependencies") @patch("generate_test_code.gen_function_wrapper") @patch("generate_test_code.parse_function_arguments") def test_return(self, parse_function_arguments_mock, gen_function_wrapper_mock, gen_dependencies_mock, gen_dispatch_mock): """ Test generated code. :return: """ parse_function_arguments_mock.return_value = ([], '', []) gen_function_wrapper_mock.return_value = '' gen_dependencies_mock.side_effect = gen_dependencies gen_dispatch_mock.side_effect = gen_dispatch data = ''' void func() { ba ba black sheep have you any wool } /* END_CASE */ ''' stream = StringIOWrapper('test_suite_ut.function', data) name, arg, code, dispatch_code = parse_function_code(stream, [], []) self.assertTrue(parse_function_arguments_mock.called) parse_function_arguments_mock.assert_called_with('void func()\n') gen_function_wrapper_mock.assert_called_with('test_func', '', []) self.assertEqual(name, 'test_func') self.assertEqual(arg, []) expected = '''#line 1 "test_suite_ut.function" void test_func() { ba ba black sheep have you any wool exit: ; } ''' self.assertEqual(code, expected) self.assertEqual(dispatch_code, "\n test_func_wrapper,\n") @patch("generate_test_code.gen_dispatch") @patch("generate_test_code.gen_dependencies") @patch("generate_test_code.gen_function_wrapper") @patch("generate_test_code.parse_function_arguments") def test_with_exit_label(self, parse_function_arguments_mock, gen_function_wrapper_mock, gen_dependencies_mock, gen_dispatch_mock): """ Test when exit label is present. :return: """ parse_function_arguments_mock.return_value = ([], '', []) gen_function_wrapper_mock.return_value = '' gen_dependencies_mock.side_effect = gen_dependencies gen_dispatch_mock.side_effect = gen_dispatch data = ''' void func() { ba ba black sheep have you any wool exit: yes sir yes sir 3 bags full } /* END_CASE */ ''' stream = StringIOWrapper('test_suite_ut.function', data) _, _, code, _ = parse_function_code(stream, [], []) expected = '''#line 1 "test_suite_ut.function" void test_func() { ba ba black sheep have you any wool exit: yes sir yes sir 3 bags full } ''' self.assertEqual(code, expected) def test_non_void_function(self): """ Test invalid signature (non void). :return: """ data = 'int entropy_threshold( char * a, data_t * h, int result )' err_msg = 'file: test_suite_ut.function - Test functions not found!' stream = StringIOWrapper('test_suite_ut.function', data) self.assertRaisesRegex(GeneratorInputError, err_msg, parse_function_code, stream, [], []) @patch("generate_test_code.gen_dispatch") @patch("generate_test_code.gen_dependencies") @patch("generate_test_code.gen_function_wrapper") @patch("generate_test_code.parse_function_arguments") def test_functio_name_on_newline(self, parse_function_arguments_mock, gen_function_wrapper_mock, gen_dependencies_mock, gen_dispatch_mock): """ Test when exit label is present. :return: """ parse_function_arguments_mock.return_value = ([], '', []) gen_function_wrapper_mock.return_value = '' gen_dependencies_mock.side_effect = gen_dependencies gen_dispatch_mock.side_effect = gen_dispatch data = ''' void func() { ba ba black sheep have you any wool exit: yes sir yes sir 3 bags full } /* END_CASE */ ''' stream = StringIOWrapper('test_suite_ut.function', data) _, _, code, _ = parse_function_code(stream, [], []) expected = '''#line 1 "test_suite_ut.function" void test_func() { ba ba black sheep have you any wool exit: yes sir yes sir 3 bags full } ''' self.assertEqual(code, expected) class ParseFunction(TestCase): """ Test Suite for testing parse_functions() """ @patch("generate_test_code.parse_until_pattern") def test_begin_header(self, parse_until_pattern_mock): """ Test that begin header is checked and parse_until_pattern() is called. :return: """ def stop(*_unused): """Stop when parse_until_pattern is called.""" raise Exception parse_until_pattern_mock.side_effect = stop data = '''/* BEGIN_HEADER */ #include "mbedtls/ecp.h" #define ECP_PF_UNKNOWN -1 /* END_HEADER */ ''' stream = StringIOWrapper('test_suite_ut.function', data) self.assertRaises(Exception, parse_functions, stream) parse_until_pattern_mock.assert_called_with(stream, END_HEADER_REGEX) self.assertEqual(stream.line_no, 1) @patch("generate_test_code.parse_until_pattern") def test_begin_helper(self, parse_until_pattern_mock): """ Test that begin helper is checked and parse_until_pattern() is called. :return: """ def stop(*_unused): """Stop when parse_until_pattern is called.""" raise Exception parse_until_pattern_mock.side_effect = stop data = '''/* BEGIN_SUITE_HELPERS */ void print_hello_world() { printf("Hello World!\n"); } /* END_SUITE_HELPERS */ ''' stream = StringIOWrapper('test_suite_ut.function', data) self.assertRaises(Exception, parse_functions, stream) parse_until_pattern_mock.assert_called_with(stream, END_SUITE_HELPERS_REGEX) self.assertEqual(stream.line_no, 1) @patch("generate_test_code.parse_suite_dependencies") def test_begin_dep(self, parse_suite_dependencies_mock): """ Test that begin dep is checked and parse_suite_dependencies() is called. :return: """ def stop(*_unused): """Stop when parse_until_pattern is called.""" raise Exception parse_suite_dependencies_mock.side_effect = stop data = '''/* BEGIN_DEPENDENCIES * depends_on:MBEDTLS_ECP_C * END_DEPENDENCIES */ ''' stream = StringIOWrapper('test_suite_ut.function', data) self.assertRaises(Exception, parse_functions, stream) parse_suite_dependencies_mock.assert_called_with(stream) self.assertEqual(stream.line_no, 1) @patch("generate_test_code.parse_function_dependencies") def test_begin_function_dep(self, func_mock): """ Test that begin dep is checked and parse_function_dependencies() is called. :return: """ def stop(*_unused): """Stop when parse_until_pattern is called.""" raise Exception func_mock.side_effect = stop dependencies_str = '/* BEGIN_CASE ' \ 'depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */\n' data = '''%svoid test_func() { } ''' % dependencies_str stream = StringIOWrapper('test_suite_ut.function', data) self.assertRaises(Exception, parse_functions, stream) func_mock.assert_called_with(dependencies_str) self.assertEqual(stream.line_no, 1) @patch("generate_test_code.parse_function_code") @patch("generate_test_code.parse_function_dependencies") def test_return(self, func_mock1, func_mock2): """ Test that begin case is checked and parse_function_code() is called. :return: """ func_mock1.return_value = [] in_func_code = '''void test_func() { } ''' func_dispatch = ''' test_func_wrapper, ''' func_mock2.return_value = 'test_func', [],\ in_func_code, func_dispatch dependencies_str = '/* BEGIN_CASE ' \ 'depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */\n' data = '''%svoid test_func() { } ''' % dependencies_str stream = StringIOWrapper('test_suite_ut.function', data) suite_dependencies, dispatch_code, func_code, func_info = \ parse_functions(stream) func_mock1.assert_called_with(dependencies_str) func_mock2.assert_called_with(stream, [], []) self.assertEqual(stream.line_no, 5) self.assertEqual(suite_dependencies, []) expected_dispatch_code = '''/* Function Id: 0 */ test_func_wrapper, ''' self.assertEqual(dispatch_code, expected_dispatch_code) self.assertEqual(func_code, in_func_code) self.assertEqual(func_info, {'test_func': (0, [])}) def test_parsing(self): """ Test case parsing. :return: """ data = '''/* BEGIN_HEADER */ #include "mbedtls/ecp.h" #define ECP_PF_UNKNOWN -1 /* END_HEADER */ /* BEGIN_DEPENDENCIES * depends_on:MBEDTLS_ECP_C * END_DEPENDENCIES */ /* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */ void func1() { } /* END_CASE */ /* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */ void func2() { } /* END_CASE */ ''' stream = StringIOWrapper('test_suite_ut.function', data) suite_dependencies, dispatch_code, func_code, func_info = \ parse_functions(stream) self.assertEqual(stream.line_no, 23) self.assertEqual(suite_dependencies, ['MBEDTLS_ECP_C']) expected_dispatch_code = '''/* Function Id: 0 */ #if defined(MBEDTLS_ECP_C) && defined(MBEDTLS_ENTROPY_NV_SEED) && defined(MBEDTLS_FS_IO) test_func1_wrapper, #else NULL, #endif /* Function Id: 1 */ #if defined(MBEDTLS_ECP_C) && defined(MBEDTLS_ENTROPY_NV_SEED) && defined(MBEDTLS_FS_IO) test_func2_wrapper, #else NULL, #endif ''' self.assertEqual(dispatch_code, expected_dispatch_code) expected_func_code = '''#if defined(MBEDTLS_ECP_C) #line 2 "test_suite_ut.function" #include "mbedtls/ecp.h" #define ECP_PF_UNKNOWN -1 #if defined(MBEDTLS_ENTROPY_NV_SEED) #if defined(MBEDTLS_FS_IO) #line 13 "test_suite_ut.function" void test_func1() { exit: ; } void test_func1_wrapper( void ** params ) { (void)params; test_func1( ); } #endif /* MBEDTLS_FS_IO */ #endif /* MBEDTLS_ENTROPY_NV_SEED */ #if defined(MBEDTLS_ENTROPY_NV_SEED) #if defined(MBEDTLS_FS_IO) #line 19 "test_suite_ut.function" void test_func2() { exit: ; } void test_func2_wrapper( void ** params ) { (void)params; test_func2( ); } #endif /* MBEDTLS_FS_IO */ #endif /* MBEDTLS_ENTROPY_NV_SEED */ #endif /* MBEDTLS_ECP_C */ ''' self.assertEqual(func_code, expected_func_code) self.assertEqual(func_info, {'test_func1': (0, []), 'test_func2': (1, [])}) def test_same_function_name(self): """ Test name conflict. :return: """ data = '''/* BEGIN_HEADER */ #include "mbedtls/ecp.h" #define ECP_PF_UNKNOWN -1 /* END_HEADER */ /* BEGIN_DEPENDENCIES * depends_on:MBEDTLS_ECP_C * END_DEPENDENCIES */ /* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */ void func() { } /* END_CASE */ /* BEGIN_CASE depends_on:MBEDTLS_ENTROPY_NV_SEED:MBEDTLS_FS_IO */ void func() { } /* END_CASE */ ''' stream = StringIOWrapper('test_suite_ut.function', data) self.assertRaises(GeneratorInputError, parse_functions, stream) class EscapedSplit(TestCase): """ Test suite for testing escaped_split(). Note: Since escaped_split() output is used to write back to the intermediate data file. Any escape characters in the input are retained in the output. """ def test_invalid_input(self): """ Test when input split character is not a character. :return: """ self.assertRaises(ValueError, escaped_split, '', 'string') def test_empty_string(self): """ Test empty string input. :return: """ splits = escaped_split('', ':') self.assertEqual(splits, []) def test_no_escape(self): """ Test with no escape character. The behaviour should be same as str.split() :return: """ test_str = 'yahoo:google' splits = escaped_split(test_str, ':') self.assertEqual(splits, test_str.split(':')) def test_escaped_input(self): """ Test input that has escaped delimiter. :return: """ test_str = r'yahoo\:google:facebook' splits = escaped_split(test_str, ':') self.assertEqual(splits, [r'yahoo\:google', 'facebook']) def test_escaped_escape(self): """ Test input that has escaped delimiter. :return: """ test_str = r'yahoo\\:google:facebook' splits = escaped_split(test_str, ':') self.assertEqual(splits, [r'yahoo\\', 'google', 'facebook']) def test_all_at_once(self): """ Test input that has escaped delimiter. :return: """ test_str = r'yahoo\\:google:facebook\:instagram\\:bbc\\:wikipedia' splits = escaped_split(test_str, ':') self.assertEqual(splits, [r'yahoo\\', r'google', r'facebook\:instagram\\', r'bbc\\', r'wikipedia']) class ParseTestData(TestCase): """ Test suite for parse test data. """ def test_parser(self): """ Test that tests are parsed correctly from data file. :return: """ data = """ Diffie-Hellman full exchange #1 dhm_do_dhm:10:"23":10:"5" Diffie-Hellman full exchange #2 dhm_do_dhm:10:"93450983094850938450983409623":10:"9345098304850938450983409622" Diffie-Hellman full exchange #3 dhm_do_dhm:10:"9345098382739712938719287391879381271":10:"9345098792137312973297123912791271" Diffie-Hellman selftest dhm_selftest: """ stream = StringIOWrapper('test_suite_ut.function', data) # List of (name, function_name, dependencies, args) tests = list(parse_test_data(stream)) test1, test2, test3, test4 = tests self.assertEqual(test1[0], 'Diffie-Hellman full exchange #1') self.assertEqual(test1[1], 'dhm_do_dhm') self.assertEqual(test1[2], []) self.assertEqual(test1[3], ['10', '"23"', '10', '"5"']) self.assertEqual(test2[0], 'Diffie-Hellman full exchange #2') self.assertEqual(test2[1], 'dhm_do_dhm') self.assertEqual(test2[2], []) self.assertEqual(test2[3], ['10', '"93450983094850938450983409623"', '10', '"9345098304850938450983409622"']) self.assertEqual(test3[0], 'Diffie-Hellman full exchange #3') self.assertEqual(test3[1], 'dhm_do_dhm') self.assertEqual(test3[2], []) self.assertEqual(test3[3], ['10', '"9345098382739712938719287391879381271"', '10', '"9345098792137312973297123912791271"']) self.assertEqual(test4[0], 'Diffie-Hellman selftest') self.assertEqual(test4[1], 'dhm_selftest') self.assertEqual(test4[2], []) self.assertEqual(test4[3], []) def test_with_dependencies(self): """ Test that tests with dependencies are parsed. :return: """ data = """ Diffie-Hellman full exchange #1 depends_on:YAHOO dhm_do_dhm:10:"23":10:"5" Diffie-Hellman full exchange #2 dhm_do_dhm:10:"93450983094850938450983409623":10:"9345098304850938450983409622" """ stream = StringIOWrapper('test_suite_ut.function', data) # List of (name, function_name, dependencies, args) tests = list(parse_test_data(stream)) test1, test2 = tests self.assertEqual(test1[0], 'Diffie-Hellman full exchange #1') self.assertEqual(test1[1], 'dhm_do_dhm') self.assertEqual(test1[2], ['YAHOO']) self.assertEqual(test1[3], ['10', '"23"', '10', '"5"']) self.assertEqual(test2[0], 'Diffie-Hellman full exchange #2') self.assertEqual(test2[1], 'dhm_do_dhm') self.assertEqual(test2[2], []) self.assertEqual(test2[3], ['10', '"93450983094850938450983409623"', '10', '"9345098304850938450983409622"']) def test_no_args(self): """ Test GeneratorInputError is raised when test function name and args line is missing. :return: """ data = """ Diffie-Hellman full exchange #1 depends_on:YAHOO Diffie-Hellman full exchange #2 dhm_do_dhm:10:"93450983094850938450983409623":10:"9345098304850938450983409622" """ stream = StringIOWrapper('test_suite_ut.function', data) err = None try: for _, _, _, _ in parse_test_data(stream): pass except GeneratorInputError as err: self.assertEqual(type(err), GeneratorInputError) def test_incomplete_data(self): """ Test GeneratorInputError is raised when test function name and args line is missing. :return: """ data = """ Diffie-Hellman full exchange #1 depends_on:YAHOO """ stream = StringIOWrapper('test_suite_ut.function', data) err = None try: for _, _, _, _ in parse_test_data(stream): pass except GeneratorInputError as err: self.assertEqual(type(err), GeneratorInputError) class GenDepCheck(TestCase): """ Test suite for gen_dep_check(). It is assumed this function is called with valid inputs. """ def test_gen_dep_check(self): """ Test that dependency check code generated correctly. :return: """ expected = """ case 5: { #if defined(YAHOO) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break;""" out = gen_dep_check(5, 'YAHOO') self.assertEqual(out, expected) def test_not_defined_dependency(self): """ Test dependency with !. :return: """ expected = """ case 5: { #if !defined(YAHOO) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break;""" out = gen_dep_check(5, '!YAHOO') self.assertEqual(out, expected) def test_empty_dependency(self): """ Test invalid dependency input. :return: """ self.assertRaises(GeneratorInputError, gen_dep_check, 5, '!') def test_negative_dep_id(self): """ Test invalid dependency input. :return: """ self.assertRaises(GeneratorInputError, gen_dep_check, -1, 'YAHOO') class GenExpCheck(TestCase): """ Test suite for gen_expression_check(). It is assumed this function is called with valid inputs. """ def test_gen_exp_check(self): """ Test that expression check code generated correctly. :return: """ expected = """ case 5: { *out_value = YAHOO; } break;""" out = gen_expression_check(5, 'YAHOO') self.assertEqual(out, expected) def test_invalid_expression(self): """ Test invalid expression input. :return: """ self.assertRaises(GeneratorInputError, gen_expression_check, 5, '') def test_negative_exp_id(self): """ Test invalid expression id. :return: """ self.assertRaises(GeneratorInputError, gen_expression_check, -1, 'YAHOO') class WriteDependencies(TestCase): """ Test suite for testing write_dependencies. """ def test_no_test_dependencies(self): """ Test when test dependencies input is empty. :return: """ stream = StringIOWrapper('test_suite_ut.data', '') unique_dependencies = [] dep_check_code = write_dependencies(stream, [], unique_dependencies) self.assertEqual(dep_check_code, '') self.assertEqual(len(unique_dependencies), 0) self.assertEqual(stream.getvalue(), '') def test_unique_dep_ids(self): """ :return: """ stream = StringIOWrapper('test_suite_ut.data', '') unique_dependencies = [] dep_check_code = write_dependencies(stream, ['DEP3', 'DEP2', 'DEP1'], unique_dependencies) expect_dep_check_code = ''' case 0: { #if defined(DEP3) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break; case 1: { #if defined(DEP2) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break; case 2: { #if defined(DEP1) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break;''' self.assertEqual(dep_check_code, expect_dep_check_code) self.assertEqual(len(unique_dependencies), 3) self.assertEqual(stream.getvalue(), 'depends_on:0:1:2\n') def test_dep_id_repeat(self): """ :return: """ stream = StringIOWrapper('test_suite_ut.data', '') unique_dependencies = [] dep_check_code = '' dep_check_code += write_dependencies(stream, ['DEP3', 'DEP2'], unique_dependencies) dep_check_code += write_dependencies(stream, ['DEP2', 'DEP1'], unique_dependencies) dep_check_code += write_dependencies(stream, ['DEP1', 'DEP3'], unique_dependencies) expect_dep_check_code = ''' case 0: { #if defined(DEP3) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break; case 1: { #if defined(DEP2) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break; case 2: { #if defined(DEP1) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break;''' self.assertEqual(dep_check_code, expect_dep_check_code) self.assertEqual(len(unique_dependencies), 3) self.assertEqual(stream.getvalue(), 'depends_on:0:1\ndepends_on:1:2\ndepends_on:2:0\n') class WriteParams(TestCase): """ Test Suite for testing write_parameters(). """ def test_no_params(self): """ Test with empty test_args :return: """ stream = StringIOWrapper('test_suite_ut.data', '') unique_expressions = [] expression_code = write_parameters(stream, [], [], unique_expressions) self.assertEqual(len(unique_expressions), 0) self.assertEqual(expression_code, '') self.assertEqual(stream.getvalue(), '\n') def test_no_exp_param(self): """ Test when there is no macro or expression in the params. :return: """ stream = StringIOWrapper('test_suite_ut.data', '') unique_expressions = [] expression_code = write_parameters(stream, ['"Yahoo"', '"abcdef00"', '0'], ['char*', 'hex', 'int'], unique_expressions) self.assertEqual(len(unique_expressions), 0) self.assertEqual(expression_code, '') self.assertEqual(stream.getvalue(), ':char*:"Yahoo":hex:"abcdef00":int:0\n') def test_hex_format_int_param(self): """ Test int parameter in hex format. :return: """ stream = StringIOWrapper('test_suite_ut.data', '') unique_expressions = [] expression_code = write_parameters(stream, ['"Yahoo"', '"abcdef00"', '0xAA'], ['char*', 'hex', 'int'], unique_expressions) self.assertEqual(len(unique_expressions), 0) self.assertEqual(expression_code, '') self.assertEqual(stream.getvalue(), ':char*:"Yahoo":hex:"abcdef00":int:0xAA\n') def test_with_exp_param(self): """ Test when there is macro or expression in the params. :return: """ stream = StringIOWrapper('test_suite_ut.data', '') unique_expressions = [] expression_code = write_parameters(stream, ['"Yahoo"', '"abcdef00"', '0', 'MACRO1', 'MACRO2', 'MACRO3'], ['char*', 'hex', 'int', 'int', 'int', 'int'], unique_expressions) self.assertEqual(len(unique_expressions), 3) self.assertEqual(unique_expressions, ['MACRO1', 'MACRO2', 'MACRO3']) expected_expression_code = ''' case 0: { *out_value = MACRO1; } break; case 1: { *out_value = MACRO2; } break; case 2: { *out_value = MACRO3; } break;''' self.assertEqual(expression_code, expected_expression_code) self.assertEqual(stream.getvalue(), ':char*:"Yahoo":hex:"abcdef00":int:0:exp:0:exp:1' ':exp:2\n') def test_with_repeat_calls(self): """ Test when write_parameter() is called with same macro or expression. :return: """ stream = StringIOWrapper('test_suite_ut.data', '') unique_expressions = [] expression_code = '' expression_code += write_parameters(stream, ['"Yahoo"', 'MACRO1', 'MACRO2'], ['char*', 'int', 'int'], unique_expressions) expression_code += write_parameters(stream, ['"abcdef00"', 'MACRO2', 'MACRO3'], ['hex', 'int', 'int'], unique_expressions) expression_code += write_parameters(stream, ['0', 'MACRO3', 'MACRO1'], ['int', 'int', 'int'], unique_expressions) self.assertEqual(len(unique_expressions), 3) self.assertEqual(unique_expressions, ['MACRO1', 'MACRO2', 'MACRO3']) expected_expression_code = ''' case 0: { *out_value = MACRO1; } break; case 1: { *out_value = MACRO2; } break; case 2: { *out_value = MACRO3; } break;''' self.assertEqual(expression_code, expected_expression_code) expected_data_file = ''':char*:"Yahoo":exp:0:exp:1 :hex:"abcdef00":exp:1:exp:2 :int:0:exp:2:exp:0 ''' self.assertEqual(stream.getvalue(), expected_data_file) class GenTestSuiteDependenciesChecks(TestCase): """ Test suite for testing gen_suite_dep_checks() """ def test_empty_suite_dependencies(self): """ Test with empty suite_dependencies list. :return: """ dep_check_code, expression_code = \ gen_suite_dep_checks([], 'DEP_CHECK_CODE', 'EXPRESSION_CODE') self.assertEqual(dep_check_code, 'DEP_CHECK_CODE') self.assertEqual(expression_code, 'EXPRESSION_CODE') def test_suite_dependencies(self): """ Test with suite_dependencies list. :return: """ dep_check_code, expression_code = \ gen_suite_dep_checks(['SUITE_DEP'], 'DEP_CHECK_CODE', 'EXPRESSION_CODE') expected_dep_check_code = ''' #if defined(SUITE_DEP) DEP_CHECK_CODE #endif ''' expected_expression_code = ''' #if defined(SUITE_DEP) EXPRESSION_CODE #endif ''' self.assertEqual(dep_check_code, expected_dep_check_code) self.assertEqual(expression_code, expected_expression_code) def test_no_dep_no_exp(self): """ Test when there are no dependency and expression code. :return: """ dep_check_code, expression_code = gen_suite_dep_checks([], '', '') self.assertEqual(dep_check_code, '') self.assertEqual(expression_code, '') class GenFromTestData(TestCase): """ Test suite for gen_from_test_data() """ @staticmethod @patch("generate_test_code.write_dependencies") @patch("generate_test_code.write_parameters") @patch("generate_test_code.gen_suite_dep_checks") def test_intermediate_data_file(func_mock1, write_parameters_mock, write_dependencies_mock): """ Test that intermediate data file is written with expected data. :return: """ data = ''' My test depends_on:DEP1 func1:0 ''' data_f = StringIOWrapper('test_suite_ut.data', data) out_data_f = StringIOWrapper('test_suite_ut.datax', '') func_info = {'test_func1': (1, ('int',))} suite_dependencies = [] write_parameters_mock.side_effect = write_parameters write_dependencies_mock.side_effect = write_dependencies func_mock1.side_effect = gen_suite_dep_checks gen_from_test_data(data_f, out_data_f, func_info, suite_dependencies) write_dependencies_mock.assert_called_with(out_data_f, ['DEP1'], ['DEP1']) write_parameters_mock.assert_called_with(out_data_f, ['0'], ('int',), []) expected_dep_check_code = ''' case 0: { #if defined(DEP1) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break;''' func_mock1.assert_called_with( suite_dependencies, expected_dep_check_code, '') def test_function_not_found(self): """ Test that AssertError is raised when function info in not found. :return: """ data = ''' My test depends_on:DEP1 func1:0 ''' data_f = StringIOWrapper('test_suite_ut.data', data) out_data_f = StringIOWrapper('test_suite_ut.datax', '') func_info = {'test_func2': (1, ('int',))} suite_dependencies = [] self.assertRaises(GeneratorInputError, gen_from_test_data, data_f, out_data_f, func_info, suite_dependencies) def test_different_func_args(self): """ Test that AssertError is raised when no. of parameters and function args differ. :return: """ data = ''' My test depends_on:DEP1 func1:0 ''' data_f = StringIOWrapper('test_suite_ut.data', data) out_data_f = StringIOWrapper('test_suite_ut.datax', '') func_info = {'test_func2': (1, ('int', 'hex'))} suite_dependencies = [] self.assertRaises(GeneratorInputError, gen_from_test_data, data_f, out_data_f, func_info, suite_dependencies) def test_output(self): """ Test that intermediate data file is written with expected data. :return: """ data = ''' My test 1 depends_on:DEP1 func1:0:0xfa:MACRO1:MACRO2 My test 2 depends_on:DEP1:DEP2 func2:"yahoo":88:MACRO1 ''' data_f = StringIOWrapper('test_suite_ut.data', data) out_data_f = StringIOWrapper('test_suite_ut.datax', '') func_info = {'test_func1': (0, ('int', 'int', 'int', 'int')), 'test_func2': (1, ('char*', 'int', 'int'))} suite_dependencies = [] dep_check_code, expression_code = \ gen_from_test_data(data_f, out_data_f, func_info, suite_dependencies) expected_dep_check_code = ''' case 0: { #if defined(DEP1) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break; case 1: { #if defined(DEP2) ret = DEPENDENCY_SUPPORTED; #else ret = DEPENDENCY_NOT_SUPPORTED; #endif } break;''' expected_data = '''My test 1 depends_on:0 0:int:0:int:0xfa:exp:0:exp:1 My test 2 depends_on:0:1 1:char*:"yahoo":int:88:exp:0 ''' expected_expression_code = ''' case 0: { *out_value = MACRO1; } break; case 1: { *out_value = MACRO2; } break;''' self.assertEqual(dep_check_code, expected_dep_check_code) self.assertEqual(out_data_f.getvalue(), expected_data) self.assertEqual(expression_code, expected_expression_code) if __name__ == '__main__': unittest_main()
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/doxygen.sh
#!/bin/sh # Make sure the doxygen documentation builds without warnings # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Abort on errors (and uninitiliased variables) set -eu if [ -d library -a -d include -a -d tests ]; then :; else echo "Must be run from mbed TLS root" >&2 exit 1 fi if scripts/apidoc_full.sh > doc.out 2>doc.err; then :; else cat doc.err echo "FAIL" >&2 exit 1; fi cat doc.out doc.err | \ grep -v "warning: ignoring unsupported tag" \ > doc.filtered if egrep "(warning|error):" doc.filtered; then echo "FAIL" >&2 exit 1; fi make apidoc_clean rm -f doc.out doc.err doc.filtered
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/scripts_path.py
"""Add our Python library directory to the module search path. Usage: import scripts_path # pylint: disable=unused-import """ # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import sys sys.path.append(os.path.join(os.path.dirname(__file__), os.path.pardir, os.path.pardir, 'scripts'))
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/depends-pkalgs.pl
#!/usr/bin/env perl # depends-pkalgs.pl # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Purpose # # To test the code dependencies on individual PK algs (those that can be used # from the PK layer, so currently signature and encryption but not key # exchange) in each test suite. This is a verification step to ensure we don't # ship test suites that do not work for some build options. # # The process is: # for each possible PK alg # build the library and test suites with that alg disabled # execute the test suites # # And any test suite with the wrong dependencies will fail. # # Usage: tests/scripts/depends-pkalgs.pl # # This script should be executed from the root of the project directory. # # For best effect, run either with cmake disabled, or cmake enabled in a mode # that includes -Werror. use warnings; use strict; -d 'library' && -d 'include' && -d 'tests' or die "Must be run from root\n"; my $config_h = 'include/mbedtls/config.h'; # Some algorithms can't be disabled on their own as others depend on them, so # we list those reverse-dependencies here to keep check_config.h happy. my %algs = ( 'MBEDTLS_ECDSA_C' => ['MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED', 'MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED'], 'MBEDTLS_ECP_C' => ['MBEDTLS_ECDSA_C', 'MBEDTLS_ECDH_C', 'MBEDTLS_ECJPAKE_C', 'MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED', 'MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED', 'MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED', 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED', 'MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED'], 'MBEDTLS_X509_RSASSA_PSS_SUPPORT' => [], 'MBEDTLS_PKCS1_V21' => ['MBEDTLS_X509_RSASSA_PSS_SUPPORT'], 'MBEDTLS_PKCS1_V15' => ['MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED', 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED', 'MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED', 'MBEDTLS_KEY_EXCHANGE_RSA_ENABLED'], 'MBEDTLS_RSA_C' => ['MBEDTLS_X509_RSASSA_PSS_SUPPORT', 'MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED', 'MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED', 'MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED', 'MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED', 'MBEDTLS_KEY_EXCHANGE_RSA_ENABLED'], ); system( "cp $config_h $config_h.bak" ) and die; sub abort { system( "mv $config_h.bak $config_h" ) and warn "$config_h not restored\n"; # use an exit code between 1 and 124 for git bisect (die returns 255) warn $_[0]; exit 1; } while( my ($alg, $extras) = each %algs ) { system( "cp $config_h.bak $config_h" ) and die "$config_h not restored\n"; system( "make clean" ) and die; print "\n******************************************\n"; print "* Testing without alg: $alg\n"; print "******************************************\n"; $ENV{MBEDTLS_TEST_CONFIGURATION} = "-$alg"; system( "scripts/config.py unset $alg" ) and abort "Failed to disable $alg\n"; for my $opt (@$extras) { system( "scripts/config.py unset $opt" ) and abort "Failed to disable $opt\n"; } system( "CFLAGS='-Werror -Wall -Wextra' make lib" ) and abort "Failed to build lib: $alg\n"; system( "cd tests && make" ) and abort "Failed to build tests: $alg\n"; system( "make test" ) and abort "Failed test suite: $alg\n"; } system( "mv $config_h.bak $config_h" ) and die "$config_h not restored\n"; system( "make clean" ) and die; exit 0;
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/list-macros.sh
#!/bin/sh # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -eu if [ -d include/mbedtls ]; then :; else echo "$0: must be run from root" >&2 exit 1 fi HEADERS=$( ls include/mbedtls/*.h include/psa/*.h tests/include/test/drivers/*.h | egrep -v 'compat-1\.3\.h' ) HEADERS="$HEADERS library/*.h" HEADERS="$HEADERS 3rdparty/everest/include/everest/everest.h 3rdparty/everest/include/everest/x25519.h" sed -n -e 's/.*#define \([a-zA-Z0-9_]*\).*/\1/p' $HEADERS \ | egrep -v '^(asm|inline|EMIT|_CRT_SECURE_NO_DEPRECATE)$|^MULADDC_' \ | sort -u > macros # For include/mbedtls/config_psa.h need to ignore the MBEDTLS_xxx define # in that file since they may not be defined in include/psa/crypto_config.h # This line renames the potentially missing defines to ones that should # be present. sed -ne 's/^MBEDTLS_PSA_BUILTIN_/MBEDTLS_PSA_ACCEL_/p' <macros >>macros wc -l macros
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/analyze_outcomes.py
#!/usr/bin/env python3 """Analyze the test outcomes from a full CI run. This script can also run on outcomes from a partial run, but the results are less likely to be useful. """ import argparse import re import sys import traceback import check_test_cases class Results: """Process analysis results.""" def __init__(self): self.error_count = 0 self.warning_count = 0 @staticmethod def log(fmt, *args, **kwargs): sys.stderr.write((fmt + '\n').format(*args, **kwargs)) def error(self, fmt, *args, **kwargs): self.log('Error: ' + fmt, *args, **kwargs) self.error_count += 1 def warning(self, fmt, *args, **kwargs): self.log('Warning: ' + fmt, *args, **kwargs) self.warning_count += 1 class TestCaseOutcomes: """The outcomes of one test case across many configurations.""" # pylint: disable=too-few-public-methods def __init__(self): # Collect a list of witnesses of the test case succeeding or failing. # Currently we don't do anything with witnesses except count them. # The format of a witness is determined by the read_outcome_file # function; it's the platform and configuration joined by ';'. self.successes = [] self.failures = [] def hits(self): """Return the number of times a test case has been run. This includes passes and failures, but not skips. """ return len(self.successes) + len(self.failures) class TestDescriptions(check_test_cases.TestDescriptionExplorer): """Collect the available test cases.""" def __init__(self): super().__init__() self.descriptions = set() def process_test_case(self, _per_file_state, file_name, _line_number, description): """Record an available test case.""" base_name = re.sub(r'\.[^.]*$', '', re.sub(r'.*/', '', file_name)) key = ';'.join([base_name, description.decode('utf-8')]) self.descriptions.add(key) def collect_available_test_cases(): """Collect the available test cases.""" explorer = TestDescriptions() explorer.walk_all() return sorted(explorer.descriptions) def analyze_coverage(results, outcomes): """Check that all available test cases are executed at least once.""" available = collect_available_test_cases() for key in available: hits = outcomes[key].hits() if key in outcomes else 0 if hits == 0: # Make this a warning, not an error, as long as we haven't # fixed this branch to have full coverage of test cases. results.warning('Test case not executed: {}', key) def analyze_outcomes(outcomes): """Run all analyses on the given outcome collection.""" results = Results() analyze_coverage(results, outcomes) return results def read_outcome_file(outcome_file): """Parse an outcome file and return an outcome collection. An outcome collection is a dictionary mapping keys to TestCaseOutcomes objects. The keys are the test suite name and the test case description, separated by a semicolon. """ outcomes = {} with open(outcome_file, 'r', encoding='utf-8') as input_file: for line in input_file: (platform, config, suite, case, result, _cause) = line.split(';') key = ';'.join([suite, case]) setup = ';'.join([platform, config]) if key not in outcomes: outcomes[key] = TestCaseOutcomes() if result == 'PASS': outcomes[key].successes.append(setup) elif result == 'FAIL': outcomes[key].failures.append(setup) return outcomes def analyze_outcome_file(outcome_file): """Analyze the given outcome file.""" outcomes = read_outcome_file(outcome_file) return analyze_outcomes(outcomes) def main(): try: parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('outcomes', metavar='OUTCOMES.CSV', help='Outcome file to analyze') options = parser.parse_args() results = analyze_outcome_file(options.outcomes) if results.error_count > 0: sys.exit(1) except Exception: # pylint: disable=broad-except # Print the backtrace and exit explicitly with our chosen status. traceback.print_exc() sys.exit(120) if __name__ == '__main__': main()
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/check_files.py
#!/usr/bin/env python3 # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """ This script checks the current state of the source code for minor issues, including incorrect file permissions, presence of tabs, non-Unix line endings, trailing whitespace, and presence of UTF-8 BOM. Note: requires python 3, must be run from Mbed TLS root. """ import os import argparse import logging import codecs import re import subprocess import sys try: from typing import FrozenSet, Optional, Pattern # pylint: disable=unused-import except ImportError: pass class FileIssueTracker: """Base class for file-wide issue tracking. To implement a checker that processes a file as a whole, inherit from this class and implement `check_file_for_issue` and define ``heading``. ``suffix_exemptions``: files whose name ends with a string in this set will not be checked. ``path_exemptions``: files whose path (relative to the root of the source tree) matches this regular expression will not be checked. This can be ``None`` to match no path. Paths are normalized and converted to ``/`` separators before matching. ``heading``: human-readable description of the issue """ suffix_exemptions = frozenset() #type: FrozenSet[str] path_exemptions = None #type: Optional[Pattern[str]] # heading must be defined in derived classes. # pylint: disable=no-member def __init__(self): self.files_with_issues = {} @staticmethod def normalize_path(filepath): """Normalize ``filepath`` with / as the directory separator.""" filepath = os.path.normpath(filepath) # On Windows, we may have backslashes to separate directories. # We need slashes to match exemption lists. seps = os.path.sep if os.path.altsep is not None: seps += os.path.altsep return '/'.join(filepath.split(seps)) def should_check_file(self, filepath): """Whether the given file name should be checked. Files whose name ends with a string listed in ``self.suffix_exemptions`` or whose path matches ``self.path_exemptions`` will not be checked. """ for files_exemption in self.suffix_exemptions: if filepath.endswith(files_exemption): return False if self.path_exemptions and \ re.match(self.path_exemptions, self.normalize_path(filepath)): return False return True def check_file_for_issue(self, filepath): """Check the specified file for the issue that this class is for. Subclasses must implement this method. """ raise NotImplementedError def record_issue(self, filepath, line_number): """Record that an issue was found at the specified location.""" if filepath not in self.files_with_issues.keys(): self.files_with_issues[filepath] = [] self.files_with_issues[filepath].append(line_number) def output_file_issues(self, logger): """Log all the locations where the issue was found.""" if self.files_with_issues.values(): logger.info(self.heading) for filename, lines in sorted(self.files_with_issues.items()): if lines: logger.info("{}: {}".format( filename, ", ".join(str(x) for x in lines) )) else: logger.info(filename) logger.info("") BINARY_FILE_PATH_RE_LIST = [ r'docs/.*\.pdf\Z', r'programs/fuzz/corpuses/[^.]+\Z', r'tests/data_files/[^.]+\Z', r'tests/data_files/.*\.(crt|csr|db|der|key|pubkey)\Z', r'tests/data_files/.*\.req\.[^/]+\Z', r'tests/data_files/.*malformed[^/]+\Z', r'tests/data_files/format_pkcs12\.fmt\Z', ] BINARY_FILE_PATH_RE = re.compile('|'.join(BINARY_FILE_PATH_RE_LIST)) class LineIssueTracker(FileIssueTracker): """Base class for line-by-line issue tracking. To implement a checker that processes files line by line, inherit from this class and implement `line_with_issue`. """ # Exclude binary files. path_exemptions = BINARY_FILE_PATH_RE def issue_with_line(self, line, filepath): """Check the specified line for the issue that this class is for. Subclasses must implement this method. """ raise NotImplementedError def check_file_line(self, filepath, line, line_number): if self.issue_with_line(line, filepath): self.record_issue(filepath, line_number) def check_file_for_issue(self, filepath): """Check the lines of the specified file. Subclasses must implement the ``issue_with_line`` method. """ with open(filepath, "rb") as f: for i, line in enumerate(iter(f.readline, b"")): self.check_file_line(filepath, line, i + 1) def is_windows_file(filepath): _root, ext = os.path.splitext(filepath) return ext in ('.bat', '.dsp', '.dsw', '.sln', '.vcxproj') class PermissionIssueTracker(FileIssueTracker): """Track files with bad permissions. Files that are not executable scripts must not be executable.""" heading = "Incorrect permissions:" # .py files can be either full scripts or modules, so they may or may # not be executable. suffix_exemptions = frozenset({".py"}) def check_file_for_issue(self, filepath): is_executable = os.access(filepath, os.X_OK) should_be_executable = filepath.endswith((".sh", ".pl")) if is_executable != should_be_executable: self.files_with_issues[filepath] = None class ShebangIssueTracker(FileIssueTracker): """Track files with a bad, missing or extraneous shebang line. Executable scripts must start with a valid shebang (#!) line. """ heading = "Invalid shebang line:" # Allow either /bin/sh, /bin/bash, or /usr/bin/env. # Allow at most one argument (this is a Linux limitation). # For sh and bash, the argument if present must be options. # For env, the argument must be the base name of the interpeter. _shebang_re = re.compile(rb'^#! ?(?:/bin/(bash|sh)(?: -[^\n ]*)?' rb'|/usr/bin/env ([^\n /]+))$') _extensions = { b'bash': 'sh', b'perl': 'pl', b'python3': 'py', b'sh': 'sh', } def is_valid_shebang(self, first_line, filepath): m = re.match(self._shebang_re, first_line) if not m: return False interpreter = m.group(1) or m.group(2) if interpreter not in self._extensions: return False if not filepath.endswith('.' + self._extensions[interpreter]): return False return True def check_file_for_issue(self, filepath): is_executable = os.access(filepath, os.X_OK) with open(filepath, "rb") as f: first_line = f.readline() if first_line.startswith(b'#!'): if not is_executable: # Shebang on a non-executable file self.files_with_issues[filepath] = None elif not self.is_valid_shebang(first_line, filepath): self.files_with_issues[filepath] = [1] elif is_executable: # Executable without a shebang self.files_with_issues[filepath] = None class EndOfFileNewlineIssueTracker(FileIssueTracker): """Track files that end with an incomplete line (no newline character at the end of the last line).""" heading = "Missing newline at end of file:" path_exemptions = BINARY_FILE_PATH_RE def check_file_for_issue(self, filepath): with open(filepath, "rb") as f: try: f.seek(-1, 2) except OSError: # This script only works on regular files. If we can't seek # 1 before the end, it means that this position is before # the beginning of the file, i.e. that the file is empty. return if f.read(1) != b"\n": self.files_with_issues[filepath] = None class Utf8BomIssueTracker(FileIssueTracker): """Track files that start with a UTF-8 BOM. Files should be ASCII or UTF-8. Valid UTF-8 does not start with a BOM.""" heading = "UTF-8 BOM present:" suffix_exemptions = frozenset([".vcxproj", ".sln"]) path_exemptions = BINARY_FILE_PATH_RE def check_file_for_issue(self, filepath): with open(filepath, "rb") as f: if f.read().startswith(codecs.BOM_UTF8): self.files_with_issues[filepath] = None class UnixLineEndingIssueTracker(LineIssueTracker): """Track files with non-Unix line endings (i.e. files with CR).""" heading = "Non-Unix line endings:" def should_check_file(self, filepath): if not super().should_check_file(filepath): return False return not is_windows_file(filepath) def issue_with_line(self, line, _filepath): return b"\r" in line class WindowsLineEndingIssueTracker(LineIssueTracker): """Track files with non-Windows line endings (i.e. CR or LF not in CRLF).""" heading = "Non-Windows line endings:" def should_check_file(self, filepath): if not super().should_check_file(filepath): return False return is_windows_file(filepath) def issue_with_line(self, line, _filepath): return not line.endswith(b"\r\n") or b"\r" in line[:-2] class TrailingWhitespaceIssueTracker(LineIssueTracker): """Track lines with trailing whitespace.""" heading = "Trailing whitespace:" suffix_exemptions = frozenset([".dsp", ".md"]) def issue_with_line(self, line, _filepath): return line.rstrip(b"\r\n") != line.rstrip() class TabIssueTracker(LineIssueTracker): """Track lines with tabs.""" heading = "Tabs present:" suffix_exemptions = frozenset([ ".pem", # some openssl dumps have tabs ".sln", "/Makefile", "/Makefile.inc", "/generate_visualc_files.pl", ]) def issue_with_line(self, line, _filepath): return b"\t" in line class MergeArtifactIssueTracker(LineIssueTracker): """Track lines with merge artifacts. These are leftovers from a ``git merge`` that wasn't fully edited.""" heading = "Merge artifact:" def issue_with_line(self, line, _filepath): # Detect leftover git conflict markers. if line.startswith(b'<<<<<<< ') or line.startswith(b'>>>>>>> '): return True if line.startswith(b'||||||| '): # from merge.conflictStyle=diff3 return True if line.rstrip(b'\r\n') == b'=======' and \ not _filepath.endswith('.md'): return True return False class IntegrityChecker: """Sanity-check files under the current directory.""" def __init__(self, log_file): """Instantiate the sanity checker. Check files under the current directory. Write a report of issues to log_file.""" self.check_repo_path() self.logger = None self.setup_logger(log_file) self.issues_to_check = [ PermissionIssueTracker(), ShebangIssueTracker(), EndOfFileNewlineIssueTracker(), Utf8BomIssueTracker(), UnixLineEndingIssueTracker(), WindowsLineEndingIssueTracker(), TrailingWhitespaceIssueTracker(), TabIssueTracker(), MergeArtifactIssueTracker(), ] @staticmethod def check_repo_path(): if not all(os.path.isdir(d) for d in ["include", "library", "tests"]): raise Exception("Must be run from Mbed TLS root") def setup_logger(self, log_file, level=logging.INFO): self.logger = logging.getLogger() self.logger.setLevel(level) if log_file: handler = logging.FileHandler(log_file) self.logger.addHandler(handler) else: console = logging.StreamHandler() self.logger.addHandler(console) @staticmethod def collect_files(): bytes_output = subprocess.check_output(['git', 'ls-files', '-z']) bytes_filepaths = bytes_output.split(b'\0')[:-1] ascii_filepaths = map(lambda fp: fp.decode('ascii'), bytes_filepaths) # Prepend './' to files in the top-level directory so that # something like `'/Makefile' in fp` matches in the top-level # directory as well as in subdirectories. return [fp if os.path.dirname(fp) else os.path.join(os.curdir, fp) for fp in ascii_filepaths] def check_files(self): for issue_to_check in self.issues_to_check: for filepath in self.collect_files(): if issue_to_check.should_check_file(filepath): issue_to_check.check_file_for_issue(filepath) def output_issues(self): integrity_return_code = 0 for issue_to_check in self.issues_to_check: if issue_to_check.files_with_issues: integrity_return_code = 1 issue_to_check.output_file_issues(self.logger) return integrity_return_code def run_main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument( "-l", "--log_file", type=str, help="path to optional output log", ) check_args = parser.parse_args() integrity_check = IntegrityChecker(check_args.log_file) integrity_check.check_files() return_code = integrity_check.output_issues() sys.exit(return_code) if __name__ == "__main__": run_main()
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/docker_env.sh
#!/bin/bash -eu # docker_env.sh # # Purpose # ------- # # This is a helper script to enable running tests under a Docker container, # thus making it easier to get set up as well as isolating test dependencies # (which include legacy/insecure configurations of openssl and gnutls). # # Notes for users # --------------- # This script expects a Linux x86_64 system with a recent version of Docker # installed and available for use, as well as http/https access. If a proxy # server must be used, invoke this script with the usual environment variables # (http_proxy and https_proxy) set appropriately. If an alternate Docker # registry is needed, specify MBEDTLS_DOCKER_REGISTRY to point at the # host name. # # # Running this script directly will check for Docker availability and set up # the Docker image. # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # default values, can be overridden by the environment : ${MBEDTLS_DOCKER_GUEST:=bionic} DOCKER_IMAGE_TAG="armmbed/mbedtls-test:${MBEDTLS_DOCKER_GUEST}" # Make sure docker is available if ! which docker > /dev/null; then echo "Docker is required but doesn't seem to be installed. See https://www.docker.com/ to get started" exit 1 fi # Figure out if we need to 'sudo docker' if groups | grep docker > /dev/null; then DOCKER="docker" else echo "Using sudo to invoke docker since you're not a member of the docker group..." DOCKER="sudo docker" fi # Figure out the number of processors available if [ "$(uname)" == "Darwin" ]; then NUM_PROC="$(sysctl -n hw.logicalcpu)" else NUM_PROC="$(nproc)" fi # Build the Docker image echo "Getting docker image up to date (this may take a few minutes)..." ${DOCKER} image build \ -t ${DOCKER_IMAGE_TAG} \ --cache-from=${DOCKER_IMAGE_TAG} \ --build-arg MAKEFLAGS_PARALLEL="-j ${NUM_PROC}" \ --network host \ ${http_proxy+--build-arg http_proxy=${http_proxy}} \ ${https_proxy+--build-arg https_proxy=${https_proxy}} \ ${MBEDTLS_DOCKER_REGISTRY+--build-arg MY_REGISTRY="${MBEDTLS_DOCKER_REGISTRY}/"} \ tests/docker/${MBEDTLS_DOCKER_GUEST} run_in_docker() { ENV_ARGS="" while [ "$1" == "-e" ]; do ENV_ARGS="${ENV_ARGS} $1 $2" shift 2 done ${DOCKER} container run -it --rm \ --cap-add SYS_PTRACE \ --user "$(id -u):$(id -g)" \ --volume $PWD:$PWD \ --workdir $PWD \ -e MAKEFLAGS \ -e PYLINTHOME=/tmp/.pylintd \ ${ENV_ARGS} \ ${DOCKER_IMAGE_TAG} \ $@ }
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/all-in-docker.sh
#!/bin/bash -eu # all-in-docker.sh # # Purpose # ------- # This runs all.sh (except for armcc) in a Docker container. # # Notes for users # --------------- # See docker_env.sh for prerequisites and other information. # # See also all.sh for notes about invocation of that script. # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. source tests/scripts/docker_env.sh # Run tests that are possible with openly available compilers run_in_docker tests/scripts/all.sh \ --no-armcc \ $@
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/list-identifiers.sh
#!/bin/bash # # Create a file named identifiers containing identifiers from internal header # files or all header files, based on --internal flag. # Outputs the line count of the file to stdout. # # Usage: list-identifiers.sh [ -i | --internal ] # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -eu if [ -d include/mbedtls ]; then :; else echo "$0: must be run from root" >&2 exit 1 fi INTERNAL="" until [ -z "${1-}" ] do case "$1" in -i|--internal) INTERNAL="1" ;; *) # print error echo "Unknown argument: '$1'" exit 1 ;; esac shift done if [ $INTERNAL ] then HEADERS=$( ls include/mbedtls/*_internal.h library/*.h | egrep -v 'compat-1\.3\.h|bn_mul' ) else HEADERS=$( ls include/mbedtls/*.h include/psa/*.h library/*.h | egrep -v 'compat-1\.3\.h|bn_mul' ) HEADERS="$HEADERS 3rdparty/everest/include/everest/everest.h 3rdparty/everest/include/everest/x25519.h" fi rm -f identifiers grep '^[^ /#{]' $HEADERS | \ sed -e 's/^[^:]*://' | \ egrep -v '^(extern "C"|(typedef )?(struct|union|enum)( {)?$|};?$)' \ > _decls if true; then sed -n -e 's/.* \**\([a-zA-Z_][a-zA-Z0-9_]*\)(.*/\1/p' \ -e 's/.*(\*\(.*\))(.*/\1/p' _decls grep -v '(' _decls | sed -e 's/\([a-zA-Z0-9_]*\)[;[].*/\1/' -e 's/.* \**//' fi > _identifiers if [ $( wc -l < _identifiers ) -eq $( wc -l < _decls ) ]; then rm _decls egrep -v '^(u?int(16|32|64)_t)$' _identifiers | sort > identifiers rm _identifiers else echo "$0: oops, lost some identifiers" 2>&1 exit 1 fi wc -l identifiers
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/run-test-suites.pl
#!/usr/bin/env perl # run-test-suites.pl # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. =head1 SYNOPSIS Execute all the test suites and print a summary of the results. run-test-suites.pl [[-v|--verbose] [VERBOSITY]] [--skip=SUITE[...]] Options: -v|--verbose Print detailed failure information. -v 2|--verbose=2 Print detailed failure information and summary messages. -v 3|--verbose=3 Print detailed information about every test case. --skip=SUITE[,SUITE...] Skip the specified SUITE(s). This option can be used multiple times. =cut use warnings; use strict; use utf8; use open qw(:std utf8); use Getopt::Long qw(:config auto_help gnu_compat); use Pod::Usage; my $verbose = 0; my @skip_patterns = (); GetOptions( 'skip=s' => \@skip_patterns, 'verbose|v:1' => \$verbose, ) or die; # All test suites = executable files, excluding source files, debug # and profiling information, etc. We can't just grep {! /\./} because # some of our test cases' base names contain a dot. my @suites = grep { -x $_ || /\.exe$/ } glob 'test_suite_*'; @suites = grep { !/\.c$/ && !/\.data$/ && -f } @suites; die "$0: no test suite found\n" unless @suites; # "foo" as a skip pattern skips "test_suite_foo" and "test_suite_foo.bar" # but not "test_suite_foobar". my $skip_re = ( '\Atest_suite_(' . join('|', map { s/[ ,;]/|/g; # allow any of " ,;|" as separators s/\./\./g; # "." in the input means ".", not "any character" $_ } @skip_patterns) . ')(\z|\.)' ); # in case test suites are linked dynamically $ENV{'LD_LIBRARY_PATH'} = '../library'; $ENV{'DYLD_LIBRARY_PATH'} = '../library'; my $prefix = $^O eq "MSWin32" ? '' : './'; my ($failed_suites, $total_tests_run, $failed, $suite_cases_passed, $suite_cases_failed, $suite_cases_skipped, $total_cases_passed, $total_cases_failed, $total_cases_skipped ); my $suites_skipped = 0; sub pad_print_center { my( $width, $padchar, $string ) = @_; my $padlen = ( $width - length( $string ) - 2 ) / 2; print $padchar x( $padlen ), " $string ", $padchar x( $padlen ), "\n"; } for my $suite (@suites) { print "$suite ", "." x ( 72 - length($suite) - 2 - 4 ), " "; if( $suite =~ /$skip_re/o ) { print "SKIP\n"; ++$suites_skipped; next; } my $command = "$prefix$suite"; if( $verbose ) { $command .= ' -v'; } my $result = `$command`; $suite_cases_passed = () = $result =~ /.. PASS/g; $suite_cases_failed = () = $result =~ /.. FAILED/g; $suite_cases_skipped = () = $result =~ /.. ----/g; if( $? == 0 ) { print "PASS\n"; if( $verbose > 2 ) { pad_print_center( 72, '-', "Begin $suite" ); print $result; pad_print_center( 72, '-', "End $suite" ); } } else { $failed_suites++; print "FAIL\n"; if( $verbose ) { pad_print_center( 72, '-', "Begin $suite" ); print $result; pad_print_center( 72, '-', "End $suite" ); } } my ($passed, $tests, $skipped) = $result =~ /([0-9]*) \/ ([0-9]*) tests.*?([0-9]*) skipped/; $total_tests_run += $tests - $skipped; if( $verbose > 1 ) { print "(test cases passed:", $suite_cases_passed, " failed:", $suite_cases_failed, " skipped:", $suite_cases_skipped, " of total:", ($suite_cases_passed + $suite_cases_failed + $suite_cases_skipped), ")\n" } $total_cases_passed += $suite_cases_passed; $total_cases_failed += $suite_cases_failed; $total_cases_skipped += $suite_cases_skipped; } print "-" x 72, "\n"; print $failed_suites ? "FAILED" : "PASSED"; printf( " (%d suites, %d tests run%s)\n", scalar(@suites) - $suites_skipped, $total_tests_run, $suites_skipped ? ", $suites_skipped suites skipped" : "" ); if( $verbose > 1 ) { print " test cases passed :", $total_cases_passed, "\n"; print " failed :", $total_cases_failed, "\n"; print " skipped :", $total_cases_skipped, "\n"; print " of tests executed :", ( $total_cases_passed + $total_cases_failed ), "\n"; print " of available tests :", ( $total_cases_passed + $total_cases_failed + $total_cases_skipped ), "\n"; if( $suites_skipped != 0 ) { print "Note: $suites_skipped suites were skipped.\n"; } } exit( $failed_suites ? 1 : 0 );
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/check-generated-files.sh
#! /usr/bin/env sh # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Purpose # # Check if generated files are up-to-date. set -eu if [ $# -ne 0 ] && [ "$1" = "--help" ]; then cat <<EOF $0 [-u] This script checks that all generated file are up-to-date. If some aren't, by default the scripts reports it and exits in error; with the -u option, it just updates them instead. -u Update the files rather than return an error for out-of-date files. EOF exit fi if [ -d library -a -d include -a -d tests ]; then :; else echo "Must be run from mbed TLS root" >&2 exit 1 fi UPDATE= if [ $# -ne 0 ] && [ "$1" = "-u" ]; then shift UPDATE='y' fi # check SCRIPT FILENAME[...] # check SCRIPT DIRECTORY # Run SCRIPT and check that it does not modify any of the specified files. # In the first form, there can be any number of FILENAMEs, which must be # regular files. # In the second form, there must be a single DIRECTORY, standing for the # list of files in the directory. Running SCRIPT must not modify any file # in the directory and must not add or remove files either. # If $UPDATE is empty, abort with an error status if a file is modified. check() { SCRIPT=$1 shift directory= if [ -d "$1" ]; then directory="$1" set -- "$1"/* fi for FILE in "$@"; do cp "$FILE" "$FILE.bak" done "$SCRIPT" # Compare the script output to the old files and remove backups for FILE in "$@"; do if ! diff "$FILE" "$FILE.bak" >/dev/null 2>&1; then echo "'$FILE' was either modified or deleted by '$SCRIPT'" if [ -z "$UPDATE" ]; then exit 1 fi fi if [ -z "$UPDATE" ]; then mv "$FILE.bak" "$FILE" else rm "$FILE.bak" fi done if [ -n "$directory" ]; then old_list="$*" set -- "$directory"/* new_list="$*" # Check if there are any new files if [ "$old_list" != "$new_list" ]; then echo "Files were deleted or created by '$SCRIPT'" echo "Before: $old_list" echo "After: $new_list" if [ -z "$UPDATE" ]; then exit 1 fi fi fi } check scripts/generate_errors.pl library/error.c check scripts/generate_query_config.pl programs/test/query_config.c check scripts/generate_features.pl library/version_features.c check scripts/generate_visualc_files.pl visualc/VS2010 check scripts/generate_psa_constants.py programs/psa/psa_constant_names_generated.c check tests/scripts/generate_psa_tests.py $(tests/scripts/generate_psa_tests.py --list)
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/test_config_script.py
#!/usr/bin/env python3 """Test helper for the Mbed TLS configuration file tool Run config.py with various parameters and write the results to files. This is a harness to help regression testing, not a functional tester. Sample usage: test_config_script.py -d old ## Modify config.py and/or config.h ## test_config_script.py -d new diff -ru old new """ ## Copyright The Mbed TLS Contributors ## SPDX-License-Identifier: Apache-2.0 ## ## Licensed under the Apache License, Version 2.0 (the "License"); you may ## not use this file except in compliance with the License. ## You may obtain a copy of the License at ## ## http://www.apache.org/licenses/LICENSE-2.0 ## ## Unless required by applicable law or agreed to in writing, software ## distributed under the License is distributed on an "AS IS" BASIS, WITHOUT ## WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. ## See the License for the specific language governing permissions and ## limitations under the License. import argparse import glob import os import re import shutil import subprocess OUTPUT_FILE_PREFIX = 'config-' def output_file_name(directory, stem, extension): return os.path.join(directory, '{}{}.{}'.format(OUTPUT_FILE_PREFIX, stem, extension)) def cleanup_directory(directory): """Remove old output files.""" for extension in []: pattern = output_file_name(directory, '*', extension) filenames = glob.glob(pattern) for filename in filenames: os.remove(filename) def prepare_directory(directory): """Create the output directory if it doesn't exist yet. If there are old output files, remove them. """ if os.path.exists(directory): cleanup_directory(directory) else: os.makedirs(directory) def guess_presets_from_help(help_text): """Figure out what presets the script supports. help_text should be the output from running the script with --help. """ # Try the output format from config.py hits = re.findall(r'\{([-\w,]+)\}', help_text) for hit in hits: words = set(hit.split(',')) if 'get' in words and 'set' in words and 'unset' in words: words.remove('get') words.remove('set') words.remove('unset') return words # Try the output format from config.pl hits = re.findall(r'\n +([-\w]+) +- ', help_text) if hits: return hits raise Exception("Unable to figure out supported presets. Pass the '-p' option.") def list_presets(options): """Return the list of presets to test. The list is taken from the command line if present, otherwise it is extracted from running the config script with --help. """ if options.presets: return re.split(r'[ ,]+', options.presets) else: help_text = subprocess.run([options.script, '--help'], check=False, # config.pl --help returns 255 stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout return guess_presets_from_help(help_text.decode('ascii')) def run_one(options, args, stem_prefix='', input_file=None): """Run the config script with the given arguments. Take the original content from input_file if specified, defaulting to options.input_file if input_file is None. Write the following files, where xxx contains stem_prefix followed by a filename-friendly encoding of args: * config-xxx.h: modified file. * config-xxx.out: standard output. * config-xxx.err: standard output. * config-xxx.status: exit code. Return ("xxx+", "path/to/config-xxx.h") which can be used as stem_prefix and input_file to call this function again with new args. """ if input_file is None: input_file = options.input_file stem = stem_prefix + '-'.join(args) data_filename = output_file_name(options.output_directory, stem, 'h') stdout_filename = output_file_name(options.output_directory, stem, 'out') stderr_filename = output_file_name(options.output_directory, stem, 'err') status_filename = output_file_name(options.output_directory, stem, 'status') shutil.copy(input_file, data_filename) # Pass only the file basename, not the full path, to avoid getting the # directory name in error messages, which would make comparisons # between output directories more difficult. cmd = [os.path.abspath(options.script), '-f', os.path.basename(data_filename)] with open(stdout_filename, 'wb') as out: with open(stderr_filename, 'wb') as err: status = subprocess.call(cmd + args, cwd=options.output_directory, stdin=subprocess.DEVNULL, stdout=out, stderr=err) with open(status_filename, 'w') as status_file: status_file.write('{}\n'.format(status)) return stem + "+", data_filename ### A list of symbols to test with. ### This script currently tests what happens when you change a symbol from ### having a value to not having a value or vice versa. This is not ### necessarily useful behavior, and we may not consider it a bug if ### config.py stops handling that case correctly. TEST_SYMBOLS = [ 'CUSTOM_SYMBOL', # does not exist 'MBEDTLS_AES_C', # set, no value 'MBEDTLS_MPI_MAX_SIZE', # unset, has a value 'MBEDTLS_NO_UDBL_DIVISION', # unset, in "System support" 'MBEDTLS_PLATFORM_ZEROIZE_ALT', # unset, in "Customisation configuration options" ] def run_all(options): """Run all the command lines to test.""" presets = list_presets(options) for preset in presets: run_one(options, [preset]) for symbol in TEST_SYMBOLS: run_one(options, ['get', symbol]) (stem, filename) = run_one(options, ['set', symbol]) run_one(options, ['get', symbol], stem_prefix=stem, input_file=filename) run_one(options, ['--force', 'set', symbol]) (stem, filename) = run_one(options, ['set', symbol, 'value']) run_one(options, ['get', symbol], stem_prefix=stem, input_file=filename) run_one(options, ['--force', 'set', symbol, 'value']) run_one(options, ['unset', symbol]) def main(): """Command line entry point.""" parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter) parser.add_argument('-d', metavar='DIR', dest='output_directory', required=True, help="""Output directory.""") parser.add_argument('-f', metavar='FILE', dest='input_file', default='include/mbedtls/config.h', help="""Config file (default: %(default)s).""") parser.add_argument('-p', metavar='PRESET,...', dest='presets', help="""Presets to test (default: guessed from --help).""") parser.add_argument('-s', metavar='FILE', dest='script', default='scripts/config.py', help="""Configuration script (default: %(default)s).""") options = parser.parse_args() prepare_directory(options.output_directory) run_all(options) if __name__ == '__main__': main()
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/gen_ctr_drbg.pl
#!/usr/bin/env perl # # Based on NIST CTR_DRBG.rsp validation file # Only uses AES-256-CTR cases that use a Derivation function # and concats nonce and personalization for initialization. # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use strict; my $file = shift; open(TEST_DATA, "$file") or die "Opening test cases '$file': $!"; sub get_suite_val($) { my $name = shift; my $val = ""; my $line = <TEST_DATA>; ($val) = ($line =~ /\[$name\s\=\s(\w+)\]/); return $val; } sub get_val($) { my $name = shift; my $val = ""; my $line; while($line = <TEST_DATA>) { next if($line !~ /=/); last; } ($val) = ($line =~ /^$name = (\w+)/); return $val; } my $cnt = 1;; while (my $line = <TEST_DATA>) { next if ($line !~ /^\[AES-256 use df/); my $PredictionResistanceStr = get_suite_val("PredictionResistance"); my $PredictionResistance = 0; $PredictionResistance = 1 if ($PredictionResistanceStr eq 'True'); my $EntropyInputLen = get_suite_val("EntropyInputLen"); my $NonceLen = get_suite_val("NonceLen"); my $PersonalizationStringLen = get_suite_val("PersonalizationStringLen"); my $AdditionalInputLen = get_suite_val("AdditionalInputLen"); for ($cnt = 0; $cnt < 15; $cnt++) { my $Count = get_val("COUNT"); my $EntropyInput = get_val("EntropyInput"); my $Nonce = get_val("Nonce"); my $PersonalizationString = get_val("PersonalizationString"); my $AdditionalInput1 = get_val("AdditionalInput"); my $EntropyInputPR1 = get_val("EntropyInputPR") if ($PredictionResistance == 1); my $EntropyInputReseed = get_val("EntropyInputReseed") if ($PredictionResistance == 0); my $AdditionalInputReseed = get_val("AdditionalInputReseed") if ($PredictionResistance == 0); my $AdditionalInput2 = get_val("AdditionalInput"); my $EntropyInputPR2 = get_val("EntropyInputPR") if ($PredictionResistance == 1); my $ReturnedBits = get_val("ReturnedBits"); if ($PredictionResistance == 1) { print("CTR_DRBG NIST Validation (AES-256 use df,$PredictionResistanceStr,$EntropyInputLen,$NonceLen,$PersonalizationStringLen,$AdditionalInputLen) #$Count\n"); print("ctr_drbg_validate_pr"); print(":\"$Nonce$PersonalizationString\""); print(":\"$EntropyInput$EntropyInputPR1$EntropyInputPR2\""); print(":\"$AdditionalInput1\""); print(":\"$AdditionalInput2\""); print(":\"$ReturnedBits\""); print("\n\n"); } else { print("CTR_DRBG NIST Validation (AES-256 use df,$PredictionResistanceStr,$EntropyInputLen,$NonceLen,$PersonalizationStringLen,$AdditionalInputLen) #$Count\n"); print("ctr_drbg_validate_nopr"); print(":\"$Nonce$PersonalizationString\""); print(":\"$EntropyInput$EntropyInputReseed\""); print(":\"$AdditionalInput1\""); print(":\"$AdditionalInputReseed\""); print(":\"$AdditionalInput2\""); print(":\"$ReturnedBits\""); print("\n\n"); } } } close(TEST_DATA);
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/basic-build-test.sh
#!/bin/sh # basic-build-tests.sh # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Purpose # # Executes the basic test suites, captures the results, and generates a simple # test report and code coverage report. # # The tests include: # * Unit tests - executed using tests/scripts/run-test-suite.pl # * Self-tests - executed using the test suites above # * System tests - executed using tests/ssl-opt.sh # * Interoperability tests - executed using tests/compat.sh # # The tests focus on functionality and do not consider performance. # # Note the tests self-adapt due to configurations in include/mbedtls/config.h # which can lead to some tests being skipped, and can cause the number of # available tests to fluctuate. # # This script has been written to be generic and should work on any shell. # # Usage: basic-build-tests.sh # # Abort on errors (and uninitiliased variables) set -eu if [ -d library -a -d include -a -d tests ]; then :; else echo "Must be run from mbed TLS root" >&2 exit 1 fi : ${OPENSSL:="openssl"} : ${OPENSSL_LEGACY:="$OPENSSL"} : ${GNUTLS_CLI:="gnutls-cli"} : ${GNUTLS_SERV:="gnutls-serv"} : ${GNUTLS_LEGACY_CLI:="$GNUTLS_CLI"} : ${GNUTLS_LEGACY_SERV:="$GNUTLS_SERV"} # Used to make ssl-opt.sh deterministic. # # See also RELEASE_SEED in all.sh. Debugging is easier if both values are kept # in sync. If you change the value here because it breaks some tests, you'll # definitely want to change it in all.sh as well. : ${SEED:=1} export SEED # To avoid setting OpenSSL and GnuTLS for each call to compat.sh and ssl-opt.sh # we just export the variables they require export OPENSSL_CMD="$OPENSSL" export GNUTLS_CLI="$GNUTLS_CLI" export GNUTLS_SERV="$GNUTLS_SERV" CONFIG_H='include/mbedtls/config.h' CONFIG_BAK="$CONFIG_H.bak" # Step 0 - print build environment info OPENSSL="$OPENSSL" \ OPENSSL_LEGACY="$OPENSSL_LEGACY" \ GNUTLS_CLI="$GNUTLS_CLI" \ GNUTLS_SERV="$GNUTLS_SERV" \ GNUTLS_LEGACY_CLI="$GNUTLS_LEGACY_CLI" \ GNUTLS_LEGACY_SERV="$GNUTLS_LEGACY_SERV" \ scripts/output_env.sh echo # Step 1 - Make and instrumented build for code coverage export CFLAGS=' --coverage -g3 -O0 ' export LDFLAGS=' --coverage' make clean cp "$CONFIG_H" "$CONFIG_BAK" scripts/config.py full make -j # Step 2 - Execute the tests TEST_OUTPUT=out_${PPID} cd tests if [ ! -f "seedfile" ]; then dd if=/dev/urandom of="seedfile" bs=64 count=1 fi echo # Step 2a - Unit Tests (keep going even if some tests fail) echo '################ Unit tests ################' perl scripts/run-test-suites.pl -v 2 |tee unit-test-$TEST_OUTPUT echo '^^^^^^^^^^^^^^^^ Unit tests ^^^^^^^^^^^^^^^^' echo # Step 2b - System Tests (keep going even if some tests fail) echo echo '################ ssl-opt.sh ################' sh ssl-opt.sh |tee sys-test-$TEST_OUTPUT echo '^^^^^^^^^^^^^^^^ ssl-opt.sh ^^^^^^^^^^^^^^^^' echo # Step 2c - Compatibility tests (keep going even if some tests fail) echo '################ compat.sh ################' { echo '#### compat.sh: Default versions' sh compat.sh -m 'tls1 tls1_1 tls1_2 dtls1 dtls1_2' echo echo '#### compat.sh: legacy (SSLv3)' OPENSSL_CMD="$OPENSSL_LEGACY" sh compat.sh -m 'ssl3' echo echo '#### compat.sh: legacy (null, DES, RC4)' OPENSSL_CMD="$OPENSSL_LEGACY" \ GNUTLS_CLI="$GNUTLS_LEGACY_CLI" GNUTLS_SERV="$GNUTLS_LEGACY_SERV" \ sh compat.sh -e '^$' -f 'NULL\|DES\|RC4\|ARCFOUR' echo echo '#### compat.sh: next (ARIA, ChaCha)' OPENSSL_CMD="$OPENSSL_NEXT" sh compat.sh -e '^$' -f 'ARIA\|CHACHA' echo } | tee compat-test-$TEST_OUTPUT echo '^^^^^^^^^^^^^^^^ compat.sh ^^^^^^^^^^^^^^^^' echo # Step 3 - Process the coverage report cd .. { make lcov echo SUCCESS } | tee tests/cov-$TEST_OUTPUT if [ "$(tail -n1 tests/cov-$TEST_OUTPUT)" != "SUCCESS" ]; then echo >&2 "Fatal: 'make lcov' failed" exit 2 fi # Step 4 - Summarise the test report echo echo "=========================================================================" echo "Test Report Summary" echo cd tests # Step 4a - Unit tests echo "Unit tests - tests/scripts/run-test-suites.pl" PASSED_TESTS=$(tail -n6 unit-test-$TEST_OUTPUT|sed -n -e 's/test cases passed :[\t]*\([0-9]*\)/\1/p'| tr -d ' ') SKIPPED_TESTS=$(tail -n6 unit-test-$TEST_OUTPUT|sed -n -e 's/skipped :[ \t]*\([0-9]*\)/\1/p'| tr -d ' ') TOTAL_SUITES=$(tail -n6 unit-test-$TEST_OUTPUT|sed -n -e 's/.* (\([0-9]*\) .*, [0-9]* tests run)/\1/p'| tr -d ' ') FAILED_TESTS=$(tail -n6 unit-test-$TEST_OUTPUT|sed -n -e 's/failed :[\t]*\([0-9]*\)/\1/p' |tr -d ' ') echo "No test suites : $TOTAL_SUITES" echo "Passed : $PASSED_TESTS" echo "Failed : $FAILED_TESTS" echo "Skipped : $SKIPPED_TESTS" echo "Total exec'd tests : $(($PASSED_TESTS + $FAILED_TESTS))" echo "Total avail tests : $(($PASSED_TESTS + $FAILED_TESTS + $SKIPPED_TESTS))" echo TOTAL_PASS=$PASSED_TESTS TOTAL_FAIL=$FAILED_TESTS TOTAL_SKIP=$SKIPPED_TESTS TOTAL_AVAIL=$(($PASSED_TESTS + $FAILED_TESTS + $SKIPPED_TESTS)) TOTAL_EXED=$(($PASSED_TESTS + $FAILED_TESTS)) # Step 4b - TLS Options tests echo "TLS Options tests - tests/ssl-opt.sh" PASSED_TESTS=$(tail -n5 sys-test-$TEST_OUTPUT|sed -n -e 's/.* (\([0-9]*\) \/ [0-9]* tests ([0-9]* skipped))$/\1/p') SKIPPED_TESTS=$(tail -n5 sys-test-$TEST_OUTPUT|sed -n -e 's/.* ([0-9]* \/ [0-9]* tests (\([0-9]*\) skipped))$/\1/p') TOTAL_TESTS=$(tail -n5 sys-test-$TEST_OUTPUT|sed -n -e 's/.* ([0-9]* \/ \([0-9]*\) tests ([0-9]* skipped))$/\1/p') FAILED_TESTS=$(($TOTAL_TESTS - $PASSED_TESTS)) echo "Passed : $PASSED_TESTS" echo "Failed : $FAILED_TESTS" echo "Skipped : $SKIPPED_TESTS" echo "Total exec'd tests : $TOTAL_TESTS" echo "Total avail tests : $(($TOTAL_TESTS + $SKIPPED_TESTS))" echo TOTAL_PASS=$(($TOTAL_PASS+$PASSED_TESTS)) TOTAL_FAIL=$(($TOTAL_FAIL+$FAILED_TESTS)) TOTAL_SKIP=$(($TOTAL_SKIP+$SKIPPED_TESTS)) TOTAL_AVAIL=$(($TOTAL_AVAIL + $TOTAL_TESTS + $SKIPPED_TESTS)) TOTAL_EXED=$(($TOTAL_EXED + $TOTAL_TESTS)) # Step 4c - System Compatibility tests echo "System/Compatibility tests - tests/compat.sh" PASSED_TESTS=$(cat compat-test-$TEST_OUTPUT | sed -n -e 's/.* (\([0-9]*\) \/ [0-9]* tests ([0-9]* skipped))$/\1/p' | awk 'BEGIN{ s = 0 } { s += $1 } END{ print s }') SKIPPED_TESTS=$(cat compat-test-$TEST_OUTPUT | sed -n -e 's/.* ([0-9]* \/ [0-9]* tests (\([0-9]*\) skipped))$/\1/p' | awk 'BEGIN{ s = 0 } { s += $1 } END{ print s }') EXED_TESTS=$(cat compat-test-$TEST_OUTPUT | sed -n -e 's/.* ([0-9]* \/ \([0-9]*\) tests ([0-9]* skipped))$/\1/p' | awk 'BEGIN{ s = 0 } { s += $1 } END{ print s }') FAILED_TESTS=$(($EXED_TESTS - $PASSED_TESTS)) echo "Passed : $PASSED_TESTS" echo "Failed : $FAILED_TESTS" echo "Skipped : $SKIPPED_TESTS" echo "Total exec'd tests : $EXED_TESTS" echo "Total avail tests : $(($EXED_TESTS + $SKIPPED_TESTS))" echo TOTAL_PASS=$(($TOTAL_PASS+$PASSED_TESTS)) TOTAL_FAIL=$(($TOTAL_FAIL+$FAILED_TESTS)) TOTAL_SKIP=$(($TOTAL_SKIP+$SKIPPED_TESTS)) TOTAL_AVAIL=$(($TOTAL_AVAIL + $EXED_TESTS + $SKIPPED_TESTS)) TOTAL_EXED=$(($TOTAL_EXED + $EXED_TESTS)) # Step 4d - Grand totals echo "-------------------------------------------------------------------------" echo "Total tests" echo "Total Passed : $TOTAL_PASS" echo "Total Failed : $TOTAL_FAIL" echo "Total Skipped : $TOTAL_SKIP" echo "Total exec'd tests : $TOTAL_EXED" echo "Total avail tests : $TOTAL_AVAIL" echo # Step 4e - Coverage echo "Coverage" LINES_TESTED=$(tail -n4 cov-$TEST_OUTPUT|sed -n -e 's/ lines......: [0-9]*.[0-9]% (\([0-9]*\) of [0-9]* lines)/\1/p') LINES_TOTAL=$(tail -n4 cov-$TEST_OUTPUT|sed -n -e 's/ lines......: [0-9]*.[0-9]% ([0-9]* of \([0-9]*\) lines)/\1/p') FUNCS_TESTED=$(tail -n4 cov-$TEST_OUTPUT|sed -n -e 's/ functions..: [0-9]*.[0-9]% (\([0-9]*\) of [0-9]* functions)$/\1/p') FUNCS_TOTAL=$(tail -n4 cov-$TEST_OUTPUT|sed -n -e 's/ functions..: [0-9]*.[0-9]% ([0-9]* of \([0-9]*\) functions)$/\1/p') BRANCHES_TESTED=$(tail -n4 cov-$TEST_OUTPUT|sed -n -e 's/ branches...: [0-9]*.[0-9]% (\([0-9]*\) of [0-9]* branches)$/\1/p') BRANCHES_TOTAL=$(tail -n4 cov-$TEST_OUTPUT|sed -n -e 's/ branches...: [0-9]*.[0-9]% ([0-9]* of \([0-9]*\) branches)$/\1/p') LINES_PERCENT=$((1000*$LINES_TESTED/$LINES_TOTAL)) LINES_PERCENT="$(($LINES_PERCENT/10)).$(($LINES_PERCENT-($LINES_PERCENT/10)*10))" FUNCS_PERCENT=$((1000*$FUNCS_TESTED/$FUNCS_TOTAL)) FUNCS_PERCENT="$(($FUNCS_PERCENT/10)).$(($FUNCS_PERCENT-($FUNCS_PERCENT/10)*10))" BRANCHES_PERCENT=$((1000*$BRANCHES_TESTED/$BRANCHES_TOTAL)) BRANCHES_PERCENT="$(($BRANCHES_PERCENT/10)).$(($BRANCHES_PERCENT-($BRANCHES_PERCENT/10)*10))" echo "Lines Tested : $LINES_TESTED of $LINES_TOTAL $LINES_PERCENT%" echo "Functions Tested : $FUNCS_TESTED of $FUNCS_TOTAL $FUNCS_PERCENT%" echo "Branches Tested : $BRANCHES_TESTED of $BRANCHES_TOTAL $BRANCHES_PERCENT%" echo rm unit-test-$TEST_OUTPUT rm sys-test-$TEST_OUTPUT rm compat-test-$TEST_OUTPUT rm cov-$TEST_OUTPUT cd .. make clean if [ -f "$CONFIG_BAK" ]; then mv "$CONFIG_BAK" "$CONFIG_H" fi if [ $TOTAL_FAIL -ne 0 ]; then exit 1 fi
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/check_test_cases.py
#!/usr/bin/env python3 """Sanity checks for test data. This program contains a class for traversing test cases that can be used independently of the checks. """ # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import argparse import glob import os import re import sys class Results: """Store file and line information about errors or warnings in test suites.""" def __init__(self, options): self.errors = 0 self.warnings = 0 self.ignore_warnings = options.quiet def error(self, file_name, line_number, fmt, *args): sys.stderr.write(('{}:{}:ERROR:' + fmt + '\n'). format(file_name, line_number, *args)) self.errors += 1 def warning(self, file_name, line_number, fmt, *args): if not self.ignore_warnings: sys.stderr.write(('{}:{}:Warning:' + fmt + '\n') .format(file_name, line_number, *args)) self.warnings += 1 class TestDescriptionExplorer: """An iterator over test cases with descriptions. The test cases that have descriptions are: * Individual unit tests (entries in a .data file) in test suites. * Individual test cases in ssl-opt.sh. This is an abstract class. To use it, derive a class that implements the process_test_case method, and call walk_all(). """ def process_test_case(self, per_file_state, file_name, line_number, description): """Process a test case. per_file_state: an object created by new_per_file_state() at the beginning of each file. file_name: a relative path to the file containing the test case. line_number: the line number in the given file. description: the test case description as a byte string. """ raise NotImplementedError def new_per_file_state(self): """Return a new per-file state object. The default per-file state object is None. Child classes that require per-file state may override this method. """ #pylint: disable=no-self-use return None def walk_test_suite(self, data_file_name): """Iterate over the test cases in the given unit test data file.""" in_paragraph = False descriptions = self.new_per_file_state() # pylint: disable=assignment-from-none with open(data_file_name, 'rb') as data_file: for line_number, line in enumerate(data_file, 1): line = line.rstrip(b'\r\n') if not line: in_paragraph = False continue if line.startswith(b'#'): continue if not in_paragraph: # This is a test case description line. self.process_test_case(descriptions, data_file_name, line_number, line) in_paragraph = True def walk_ssl_opt_sh(self, file_name): """Iterate over the test cases in ssl-opt.sh or a file with a similar format.""" descriptions = self.new_per_file_state() # pylint: disable=assignment-from-none with open(file_name, 'rb') as file_contents: for line_number, line in enumerate(file_contents, 1): # Assume that all run_test calls have the same simple form # with the test description entirely on the same line as the # function name. m = re.match(br'\s*run_test\s+"((?:[^\\"]|\\.)*)"', line) if not m: continue description = m.group(1) self.process_test_case(descriptions, file_name, line_number, description) @staticmethod def collect_test_directories(): """Get the relative path for the TLS and Crypto test directories.""" if os.path.isdir('tests'): tests_dir = 'tests' elif os.path.isdir('suites'): tests_dir = '.' elif os.path.isdir('../suites'): tests_dir = '..' directories = [tests_dir] return directories def walk_all(self): """Iterate over all named test cases.""" test_directories = self.collect_test_directories() for directory in test_directories: for data_file_name in glob.glob(os.path.join(directory, 'suites', '*.data')): self.walk_test_suite(data_file_name) ssl_opt_sh = os.path.join(directory, 'ssl-opt.sh') if os.path.exists(ssl_opt_sh): self.walk_ssl_opt_sh(ssl_opt_sh) class DescriptionChecker(TestDescriptionExplorer): """Check all test case descriptions. * Check that each description is valid (length, allowed character set, etc.). * Check that there is no duplicated description inside of one test suite. """ def __init__(self, results): self.results = results def new_per_file_state(self): """Dictionary mapping descriptions to their line number.""" return {} def process_test_case(self, per_file_state, file_name, line_number, description): """Check test case descriptions for errors.""" results = self.results seen = per_file_state if description in seen: results.error(file_name, line_number, 'Duplicate description (also line {})', seen[description]) return if re.search(br'[\t;]', description): results.error(file_name, line_number, 'Forbidden character \'{}\' in description', re.search(br'[\t;]', description).group(0).decode('ascii')) if re.search(br'[^ -~]', description): results.error(file_name, line_number, 'Non-ASCII character in description') if len(description) > 66: results.warning(file_name, line_number, 'Test description too long ({} > 66)', len(description)) seen[description] = line_number def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--quiet', '-q', action='store_true', help='Hide warnings') parser.add_argument('--verbose', '-v', action='store_false', dest='quiet', help='Show warnings (default: on; undoes --quiet)') options = parser.parse_args() results = Results(options) checker = DescriptionChecker(results) checker.walk_all() if (results.warnings or results.errors) and not options.quiet: sys.stderr.write('{}: {} errors, {} warnings\n' .format(sys.argv[0], results.errors, results.warnings)) sys.exit(1 if results.errors else 0) if __name__ == '__main__': main()
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/basic-in-docker.sh
#!/bin/bash -eu # basic-in-docker.sh # # Purpose # ------- # This runs sanity checks and library tests in a Docker container. The tests # are run for both clang and gcc. The testing includes a full test run # in the default configuration, partial test runs in the reference # configurations, and some dependency tests. # # Notes for users # --------------- # See docker_env.sh for prerequisites and other information. # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. source tests/scripts/docker_env.sh run_in_docker tests/scripts/all.sh 'check_*' for compiler in clang gcc; do run_in_docker -e CC=${compiler} cmake -D CMAKE_BUILD_TYPE:String="Check" . run_in_docker -e CC=${compiler} make run_in_docker -e CC=${compiler} make test run_in_docker programs/test/selftest run_in_docker -e OSSL_NO_DTLS=1 tests/compat.sh run_in_docker tests/ssl-opt.sh -e '\(DTLS\|SCSV\).*openssl' run_in_docker tests/scripts/test-ref-configs.pl run_in_docker tests/scripts/curves.pl run_in_docker tests/scripts/key-exchanges.pl done
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/gen_gcm_encrypt.pl
#!/usr/bin/env perl # # Based on NIST gcmEncryptIntIVxxx.rsp validation files # Only first 3 of every set used for compile time saving # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use strict; my $file = shift; open(TEST_DATA, "$file") or die "Opening test cases '$file': $!"; sub get_suite_val($) { my $name = shift; my $val = ""; while(my $line = <TEST_DATA>) { next if ($line !~ /^\[/); ($val) = ($line =~ /\[$name\s\=\s(\w+)\]/); last; } return $val; } sub get_val($) { my $name = shift; my $val = ""; my $line; while($line = <TEST_DATA>) { next if($line !~ /=/); last; } ($val) = ($line =~ /^$name = (\w+)/); return $val; } my $cnt = 1;; while (my $line = <TEST_DATA>) { my $key_len = get_suite_val("Keylen"); next if ($key_len !~ /\d+/); my $iv_len = get_suite_val("IVlen"); my $pt_len = get_suite_val("PTlen"); my $add_len = get_suite_val("AADlen"); my $tag_len = get_suite_val("Taglen"); for ($cnt = 0; $cnt < 3; $cnt++) { my $Count = get_val("Count"); my $key = get_val("Key"); my $pt = get_val("PT"); my $add = get_val("AAD"); my $iv = get_val("IV"); my $ct = get_val("CT"); my $tag = get_val("Tag"); print("GCM NIST Validation (AES-$key_len,$iv_len,$pt_len,$add_len,$tag_len) #$Count\n"); print("gcm_encrypt_and_tag"); print(":\"$key\""); print(":\"$pt\""); print(":\"$iv\""); print(":\"$add\""); print(":\"$ct\""); print(":$tag_len"); print(":\"$tag\""); print(":0"); print("\n\n"); } } print("GCM Selftest\n"); print("gcm_selftest:\n\n"); close(TEST_DATA);
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/set_psa_test_dependencies.py
#!/usr/bin/env python3 """Edit test cases to use PSA dependencies instead of classic dependencies. """ # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import os import re import sys CLASSIC_DEPENDENCIES = frozenset([ # This list is manually filtered from config.h. # Mbed TLS feature support. # Only features that affect what can be done are listed here. # Options that control optimizations or alternative implementations # are omitted. 'MBEDTLS_CIPHER_MODE_CBC', 'MBEDTLS_CIPHER_MODE_CFB', 'MBEDTLS_CIPHER_MODE_CTR', 'MBEDTLS_CIPHER_MODE_OFB', 'MBEDTLS_CIPHER_MODE_XTS', 'MBEDTLS_CIPHER_NULL_CIPHER', 'MBEDTLS_CIPHER_PADDING_PKCS7', 'MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS', 'MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN', 'MBEDTLS_CIPHER_PADDING_ZEROS', #curve#'MBEDTLS_ECP_DP_SECP192R1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP224R1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP256R1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP384R1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP521R1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP192K1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP224K1_ENABLED', #curve#'MBEDTLS_ECP_DP_SECP256K1_ENABLED', #curve#'MBEDTLS_ECP_DP_BP256R1_ENABLED', #curve#'MBEDTLS_ECP_DP_BP384R1_ENABLED', #curve#'MBEDTLS_ECP_DP_BP512R1_ENABLED', #curve#'MBEDTLS_ECP_DP_CURVE25519_ENABLED', #curve#'MBEDTLS_ECP_DP_CURVE448_ENABLED', 'MBEDTLS_ECDSA_DETERMINISTIC', #'MBEDTLS_GENPRIME', #needed for RSA key generation 'MBEDTLS_PKCS1_V15', 'MBEDTLS_PKCS1_V21', 'MBEDTLS_SHA512_NO_SHA384', # Mbed TLS modules. # Only modules that provide cryptographic mechanisms are listed here. # Platform, data formatting, X.509 or TLS modules are omitted. 'MBEDTLS_AES_C', 'MBEDTLS_ARC4_C', 'MBEDTLS_BIGNUM_C', #cipher#'MBEDTLS_BLOWFISH_C', 'MBEDTLS_CAMELLIA_C', 'MBEDTLS_ARIA_C', 'MBEDTLS_CCM_C', 'MBEDTLS_CHACHA20_C', 'MBEDTLS_CHACHAPOLY_C', 'MBEDTLS_CMAC_C', 'MBEDTLS_CTR_DRBG_C', 'MBEDTLS_DES_C', 'MBEDTLS_DHM_C', 'MBEDTLS_ECDH_C', 'MBEDTLS_ECDSA_C', 'MBEDTLS_ECJPAKE_C', 'MBEDTLS_ECP_C', 'MBEDTLS_ENTROPY_C', 'MBEDTLS_GCM_C', 'MBEDTLS_HKDF_C', 'MBEDTLS_HMAC_DRBG_C', 'MBEDTLS_NIST_KW_C', 'MBEDTLS_MD2_C', 'MBEDTLS_MD4_C', 'MBEDTLS_MD5_C', 'MBEDTLS_PKCS5_C', 'MBEDTLS_PKCS12_C', 'MBEDTLS_POLY1305_C', 'MBEDTLS_RIPEMD160_C', 'MBEDTLS_RSA_C', 'MBEDTLS_SHA1_C', 'MBEDTLS_SHA256_C', 'MBEDTLS_SHA512_C', 'MBEDTLS_XTEA_C', ]) def is_classic_dependency(dep): """Whether dep is a classic dependency that PSA test cases should not use.""" if dep.startswith('!'): dep = dep[1:] return dep in CLASSIC_DEPENDENCIES def is_systematic_dependency(dep): """Whether dep is a PSA dependency which is determined systematically.""" if dep.startswith('PSA_WANT_ECC_'): return False return dep.startswith('PSA_WANT_') WITHOUT_SYSTEMATIC_DEPENDENCIES = frozenset([ 'PSA_ALG_AEAD_WITH_SHORTENED_TAG', # only a modifier 'PSA_ALG_ANY_HASH', # only meaningful in policies 'PSA_ALG_KEY_AGREEMENT', # only a way to combine algorithms 'PSA_ALG_TRUNCATED_MAC', # only a modifier 'PSA_KEY_TYPE_NONE', # not a real key type 'PSA_KEY_TYPE_DERIVE', # always supported, don't list it to reduce noise 'PSA_KEY_TYPE_RAW_DATA', # always supported, don't list it to reduce noise 'PSA_ALG_AT_LEAST_THIS_LENGTH_MAC', #only a modifier 'PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG', #only a modifier ]) SPECIAL_SYSTEMATIC_DEPENDENCIES = { 'PSA_ALG_ECDSA_ANY': frozenset(['PSA_WANT_ALG_ECDSA']), 'PSA_ALG_RSA_PKCS1V15_SIGN_RAW': frozenset(['PSA_WANT_ALG_RSA_PKCS1V15_SIGN']), } def dependencies_of_symbol(symbol): """Return the dependencies for a symbol that designates a cryptographic mechanism.""" if symbol in WITHOUT_SYSTEMATIC_DEPENDENCIES: return frozenset() if symbol in SPECIAL_SYSTEMATIC_DEPENDENCIES: return SPECIAL_SYSTEMATIC_DEPENDENCIES[symbol] if symbol.startswith('PSA_ALG_CATEGORY_') or \ symbol.startswith('PSA_KEY_TYPE_CATEGORY_'): # Categories are used in test data when an unsupported but plausible # mechanism number needed. They have no associated dependency. return frozenset() return {symbol.replace('_', '_WANT_', 1)} def systematic_dependencies(file_name, function_name, arguments): """List the systematically determined dependency for a test case.""" deps = set() # Run key policy negative tests even if the algorithm to attempt performing # is not supported but in the case where the test is to check an # incompatibility between a requested algorithm for a cryptographic # operation and a key policy. In the latter, we want to filter out the # cases # where PSA_ERROR_NOT_SUPPORTED is returned instead of # PSA_ERROR_NOT_PERMITTED. if function_name.endswith('_key_policy') and \ arguments[-1].startswith('PSA_ERROR_') and \ arguments[-1] != ('PSA_ERROR_NOT_PERMITTED'): arguments[-2] = '' if function_name == 'copy_fail' and \ arguments[-1].startswith('PSA_ERROR_'): arguments[-2] = '' arguments[-3] = '' # Storage format tests that only look at how the file is structured and # don't care about the format of the key material don't depend on any # cryptographic mechanisms. if os.path.basename(file_name) == 'test_suite_psa_crypto_persistent_key.data' and \ function_name in {'format_storage_data_check', 'parse_storage_data_check'}: return [] for arg in arguments: for symbol in re.findall(r'PSA_(?:ALG|KEY_TYPE)_\w+', arg): deps.update(dependencies_of_symbol(symbol)) return sorted(deps) def updated_dependencies(file_name, function_name, arguments, dependencies): """Rework the list of dependencies into PSA_WANT_xxx. Remove classic crypto dependencies such as MBEDTLS_RSA_C, MBEDTLS_PKCS1_V15, etc. Add systematic PSA_WANT_xxx dependencies based on the called function and its arguments, replacing existing PSA_WANT_xxx dependencies. """ automatic = systematic_dependencies(file_name, function_name, arguments) manual = [dep for dep in dependencies if not (is_systematic_dependency(dep) or is_classic_dependency(dep))] return automatic + manual def keep_manual_dependencies(file_name, function_name, arguments): #pylint: disable=unused-argument """Declare test functions with unusual dependencies here.""" # If there are no arguments, we can't do any useful work. Assume that if # there are dependencies, they are warranted. if not arguments: return True # When PSA_ERROR_NOT_SUPPORTED is expected, usually, at least one of the # constants mentioned in the test should not be supported. It isn't # possible to determine which one in a systematic way. So let the programmer # decide. if arguments[-1] == 'PSA_ERROR_NOT_SUPPORTED': return True return False def process_data_stanza(stanza, file_name, test_case_number): """Update PSA crypto dependencies in one Mbed TLS test case. stanza is the test case text (including the description, the dependencies, the line with the function and arguments, and optionally comments). Return a new stanza with an updated dependency line, preserving everything else (description, comments, arguments, etc.). """ if not stanza.lstrip('\n'): # Just blank lines return stanza # Expect 2 or 3 non-comment lines: description, optional dependencies, # function-and-arguments. content_matches = list(re.finditer(r'^[\t ]*([^\t #].*)$', stanza, re.M)) if len(content_matches) < 2: raise Exception('Not enough content lines in paragraph {} in {}' .format(test_case_number, file_name)) if len(content_matches) > 3: raise Exception('Too many content lines in paragraph {} in {}' .format(test_case_number, file_name)) arguments = content_matches[-1].group(0).split(':') function_name = arguments.pop(0) if keep_manual_dependencies(file_name, function_name, arguments): return stanza if len(content_matches) == 2: # Insert a line for the dependencies. If it turns out that there are # no dependencies, we'll remove that empty line below. dependencies_location = content_matches[-1].start() text_before = stanza[:dependencies_location] text_after = '\n' + stanza[dependencies_location:] old_dependencies = [] dependencies_leader = 'depends_on:' else: dependencies_match = content_matches[-2] text_before = stanza[:dependencies_match.start()] text_after = stanza[dependencies_match.end():] old_dependencies = dependencies_match.group(0).split(':') dependencies_leader = old_dependencies.pop(0) + ':' if dependencies_leader != 'depends_on:': raise Exception('Next-to-last line does not start with "depends_on:"' ' in paragraph {} in {}' .format(test_case_number, file_name)) new_dependencies = updated_dependencies(file_name, function_name, arguments, old_dependencies) if new_dependencies: stanza = (text_before + dependencies_leader + ':'.join(new_dependencies) + text_after) else: # The dependencies have become empty. Remove the depends_on: line. assert text_after[0] == '\n' stanza = text_before + text_after[1:] return stanza def process_data_file(file_name, old_content): """Update PSA crypto dependencies in an Mbed TLS test suite data file. Process old_content (the old content of the file) and return the new content. """ old_stanzas = old_content.split('\n\n') new_stanzas = [process_data_stanza(stanza, file_name, n) for n, stanza in enumerate(old_stanzas, start=1)] return '\n\n'.join(new_stanzas) def update_file(file_name, old_content, new_content): """Update the given file with the given new content. Replace the existing file. The previous version is renamed to *.bak. Don't modify the file if the content was unchanged. """ if new_content == old_content: return backup = file_name + '.bak' tmp = file_name + '.tmp' with open(tmp, 'w', encoding='utf-8') as new_file: new_file.write(new_content) os.replace(file_name, backup) os.replace(tmp, file_name) def process_file(file_name): """Update PSA crypto dependencies in an Mbed TLS test suite data file. Replace the existing file. The previous version is renamed to *.bak. Don't modify the file if the content was unchanged. """ old_content = open(file_name, encoding='utf-8').read() if file_name.endswith('.data'): new_content = process_data_file(file_name, old_content) else: raise Exception('File type not recognized: {}' .format(file_name)) update_file(file_name, old_content, new_content) def main(args): for file_name in args: process_file(file_name) if __name__ == '__main__': main(sys.argv[1:])
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/depends-hashes.pl
#!/usr/bin/env perl # depends-hashes.pl # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Purpose # # To test the code dependencies on individual hashes in each test suite. This # is a verification step to ensure we don't ship test suites that do not work # for some build options. # # The process is: # for each possible hash # build the library and test suites with the hash disabled # execute the test suites # # And any test suite with the wrong dependencies will fail. # # Usage: tests/scripts/depends-hashes.pl # # This script should be executed from the root of the project directory. # # For best effect, run either with cmake disabled, or cmake enabled in a mode # that includes -Werror. use warnings; use strict; -d 'library' && -d 'include' && -d 'tests' or die "Must be run from root\n"; my $config_h = 'include/mbedtls/config.h'; # as many SSL options depend on specific hashes, # and SSL is not in the test suites anyways, # disable it to avoid dependcies issues my $ssl_sed_cmd = 's/^#define \(MBEDTLS_SSL.*\)/\1/p'; my @ssl = split( /\s+/, `sed -n -e '$ssl_sed_cmd' $config_h` ); # for md we want to catch MD5_C but not MD_C, hence the extra dot my $mdx_sed_cmd = 's/^#define \(MBEDTLS_MD..*_C\)/\1/p'; my $sha_sed_cmd = 's/^#define \(MBEDTLS_SHA.*_C\)/\1/p'; my @hash_modules = split( /\s+/, `sed -n -e '$mdx_sed_cmd' -e '$sha_sed_cmd' $config_h` ); # there are also negative options for truncated variants, disabled by default my $sha_trunc_sed_cmd = 's/^\/\/#define \(MBEDTLS_SHA..._NO_.*\)/\1/p'; my @hash_negatives = split( /\s+/, `sed -n -e '$sha_trunc_sed_cmd' $config_h` ); # list hash options with corresponding actions my @hashes = ((map { "unset $_" } @hash_modules), (map { "set $_" } @hash_negatives)); system( "cp $config_h $config_h.bak" ) and die; sub abort { system( "mv $config_h.bak $config_h" ) and warn "$config_h not restored\n"; # use an exit code between 1 and 124 for git bisect (die returns 255) warn $_[0]; exit 1; } for my $hash (@hashes) { system( "cp $config_h.bak $config_h" ) and die "$config_h not restored\n"; system( "make clean" ) and die; print "\n******************************************\n"; print "* Testing hash option: $hash\n"; print "******************************************\n"; $ENV{MBEDTLS_TEST_CONFIGURATION} = "-$hash"; system( "scripts/config.py $hash" ) and abort "Failed to $hash\n"; for my $opt (@ssl) { system( "scripts/config.py unset $opt" ) and abort "Failed to disable $opt\n"; } system( "CFLAGS='-Werror -Wall -Wextra' make lib" ) and abort "Failed to build lib: $hash\n"; system( "cd tests && make" ) and abort "Failed to build tests: $hash\n"; system( "make test" ) and abort "Failed test suite: $hash\n"; } system( "mv $config_h.bak $config_h" ) and die "$config_h not restored\n"; system( "make clean" ) and die; exit 0;
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/check-doxy-blocks.pl
#!/usr/bin/env perl # Detect comment blocks that are likely meant to be doxygen blocks but aren't. # # More precisely, look for normal comment block containing '\'. # Of course one could use doxygen warnings, eg with: # sed -e '/EXTRACT/s/YES/NO/' doxygen/mbedtls.doxyfile | doxygen - # but that would warn about any undocumented item, while our goal is to find # items that are documented, but not marked as such by mistake. # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use warnings; use strict; use File::Basename; # C/header files in the following directories will be checked my @directories = qw(include/mbedtls library doxygen/input); # very naive pattern to find directives: # everything with a backslach except '\0' and backslash at EOL my $doxy_re = qr/\\(?!0|\n)/; # Return an error code to the environment if a potential error in the # source code is found. my $exit_code = 0; sub check_file { my ($fname) = @_; open my $fh, '<', $fname or die "Failed to open '$fname': $!\n"; # first line of the last normal comment block, # or 0 if not in a normal comment block my $block_start = 0; while (my $line = <$fh>) { $block_start = $. if $line =~ m/\/\*(?![*!])/; $block_start = 0 if $line =~ m/\*\//; if ($block_start and $line =~ m/$doxy_re/) { print "$fname:$block_start: directive on line $.\n"; $block_start = 0; # report only one directive per block $exit_code = 1; } } close $fh; } sub check_dir { my ($dirname) = @_; for my $file (<$dirname/*.[ch]>) { check_file($file); } } # Check that the script is being run from the project's root directory. for my $dir (@directories) { if (! -d $dir) { die "This script must be run from the mbed TLS root directory"; } else { check_dir($dir) } } exit $exit_code; __END__
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/all.sh
#! /usr/bin/env sh # all.sh # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. ################################################################ #### Documentation ################################################################ # Purpose # ------- # # To run all tests possible or available on the platform. # # Notes for users # --------------- # # Warning: the test is destructive. It includes various build modes and # configurations, and can and will arbitrarily change the current CMake # configuration. The following files must be committed into git: # * include/mbedtls/config.h # * Makefile, library/Makefile, programs/Makefile, tests/Makefile, # programs/fuzz/Makefile # After running this script, the CMake cache will be lost and CMake # will no longer be initialised. # # The script assumes the presence of a number of tools: # * Basic Unix tools (Windows users note: a Unix-style find must be before # the Windows find in the PATH) # * Perl # * GNU Make # * CMake # * GCC and Clang (recent enough for using ASan with gcc and MemSan with clang, or valgrind) # * G++ # * arm-gcc and mingw-gcc # * ArmCC 5 and ArmCC 6, unless invoked with --no-armcc # * OpenSSL and GnuTLS command line tools, recent enough for the # interoperability tests. If they don't support SSLv3 then a legacy # version of these tools must be present as well (search for LEGACY # below). # See the invocation of check_tools below for details. # # This script must be invoked from the toplevel directory of a git # working copy of Mbed TLS. # # Note that the output is not saved. You may want to run # script -c tests/scripts/all.sh # or # tests/scripts/all.sh >all.log 2>&1 # # Notes for maintainers # --------------------- # # The bulk of the code is organized into functions that follow one of the # following naming conventions: # * pre_XXX: things to do before running the tests, in order. # * component_XXX: independent components. They can be run in any order. # * component_check_XXX: quick tests that aren't worth parallelizing. # * component_build_XXX: build things but don't run them. # * component_test_XXX: build and test. # * support_XXX: if support_XXX exists and returns false then # component_XXX is not run by default. # * post_XXX: things to do after running the tests. # * other: miscellaneous support functions. # # Each component must start by invoking `msg` with a short informative message. # # The framework performs some cleanup tasks after each component. This # means that components can assume that the working directory is in a # cleaned-up state, and don't need to perform the cleanup themselves. # * Run `make clean`. # * Restore `include/mbedtks/config.h` from a backup made before running # the component. # * Check out `Makefile`, `library/Makefile`, `programs/Makefile`, # `tests/Makefile` and `programs/fuzz/Makefile` from git. # This cleans up after an in-tree use of CMake. # # Any command that is expected to fail must be protected so that the # script keeps running in --keep-going mode despite `set -e`. In keep-going # mode, if a protected command fails, this is logged as a failure and the # script will exit with a failure status once it has run all components. # Commands can be protected in any of the following ways: # * `make` is a function which runs the `make` command with protection. # Note that you must write `make VAR=value`, not `VAR=value make`, # because the `VAR=value make` syntax doesn't work with functions. # * Put `report_status` before the command to protect it. # * Put `if_build_successful` before a command. This protects it, and # additionally skips it if a prior invocation of `make` in the same # component failed. # # The tests are roughly in order from fastest to slowest. This doesn't # have to be exact, but in general you should add slower tests towards # the end and fast checks near the beginning. ################################################################ #### Initialization and command line parsing ################################################################ # Abort on errors (and uninitialised variables) set -eu pre_check_environment () { if [ -d library -a -d include -a -d tests ]; then :; else echo "Must be run from mbed TLS root" >&2 exit 1 fi } pre_initialize_variables () { CONFIG_H='include/mbedtls/config.h' CONFIG_BAK="$CONFIG_H.bak" CRYPTO_CONFIG_H='include/psa/crypto_config.h' CRYPTO_CONFIG_BAK="$CRYPTO_CONFIG_H.bak" append_outcome=0 MEMORY=0 FORCE=0 QUIET=0 KEEP_GOING=0 # Seed value used with the --release-test option. # # See also RELEASE_SEED in basic-build-test.sh. Debugging is easier if # both values are kept in sync. If you change the value here because it # breaks some tests, you'll definitely want to change it in # basic-build-test.sh as well. RELEASE_SEED=1 : ${MBEDTLS_TEST_OUTCOME_FILE=} : ${MBEDTLS_TEST_PLATFORM="$(uname -s | tr -c \\n0-9A-Za-z _)-$(uname -m | tr -c \\n0-9A-Za-z _)"} export MBEDTLS_TEST_OUTCOME_FILE export MBEDTLS_TEST_PLATFORM # Default commands, can be overridden by the environment : ${OPENSSL:="openssl"} : ${OPENSSL_LEGACY:="$OPENSSL"} : ${OPENSSL_NEXT:="$OPENSSL"} : ${GNUTLS_CLI:="gnutls-cli"} : ${GNUTLS_SERV:="gnutls-serv"} : ${GNUTLS_LEGACY_CLI:="$GNUTLS_CLI"} : ${GNUTLS_LEGACY_SERV:="$GNUTLS_SERV"} : ${OUT_OF_SOURCE_DIR:=./mbedtls_out_of_source_build} : ${ARMC5_BIN_DIR:=/usr/bin} : ${ARMC6_BIN_DIR:=/usr/bin} : ${ARM_NONE_EABI_GCC_PREFIX:=arm-none-eabi-} # if MAKEFLAGS is not set add the -j option to speed up invocations of make if [ -z "${MAKEFLAGS+set}" ]; then export MAKEFLAGS="-j" fi # Include more verbose output for failing tests run by CMake export CTEST_OUTPUT_ON_FAILURE=1 # CFLAGS and LDFLAGS for Asan builds that don't use CMake ASAN_CFLAGS='-Werror -Wall -Wextra -fsanitize=address,undefined -fno-sanitize-recover=all' # Gather the list of available components. These are the functions # defined in this script whose name starts with "component_". # Parse the script with sed, because in sh there is no way to list # defined functions. ALL_COMPONENTS=$(sed -n 's/^ *component_\([0-9A-Z_a-z]*\) *().*/\1/p' <"$0") # Exclude components that are not supported on this platform. SUPPORTED_COMPONENTS= for component in $ALL_COMPONENTS; do case $(type "support_$component" 2>&1) in *' function'*) if ! support_$component; then continue; fi;; esac SUPPORTED_COMPONENTS="$SUPPORTED_COMPONENTS $component" done } # Test whether the component $1 is included in the command line patterns. is_component_included() { set -f for pattern in $COMMAND_LINE_COMPONENTS; do set +f case ${1#component_} in $pattern) return 0;; esac done set +f return 1 } usage() { cat <<EOF Usage: $0 [OPTION]... [COMPONENT]... Run mbedtls release validation tests. By default, run all tests. With one or more COMPONENT, run only those. COMPONENT can be the name of a component or a shell wildcard pattern. Examples: $0 "check_*" Run all sanity checks. $0 --no-armcc --except test_memsan Run everything except builds that require armcc and MemSan. Special options: -h|--help Print this help and exit. --list-all-components List all available test components and exit. --list-components List components supported on this platform and exit. General options: -q|--quiet Only output component names, and errors if any. -f|--force Force the tests to overwrite any modified files. -k|--keep-going Run all tests and report errors at the end. -m|--memory Additional optional memory tests. --append-outcome Append to the outcome file (if used). --arm-none-eabi-gcc-prefix=<string> Prefix for a cross-compiler for arm-none-eabi (default: "${ARM_NONE_EABI_GCC_PREFIX}") --armcc Run ARM Compiler builds (on by default). --except Exclude the COMPONENTs listed on the command line, instead of running only those. --no-append-outcome Write a new outcome file and analyze it (default). --no-armcc Skip ARM Compiler builds. --no-force Refuse to overwrite modified files (default). --no-keep-going Stop at the first error (default). --no-memory No additional memory tests (default). --no-quiet Print full ouput from components. --out-of-source-dir=<path> Directory used for CMake out-of-source build tests. --outcome-file=<path> File where test outcomes are written (not done if empty; default: \$MBEDTLS_TEST_OUTCOME_FILE). --random-seed Use a random seed value for randomized tests (default). -r|--release-test Run this script in release mode. This fixes the seed value to ${RELEASE_SEED}. -s|--seed Integer seed value to use for this test run. Tool path options: --armc5-bin-dir=<ARMC5_bin_dir_path> ARM Compiler 5 bin directory. --armc6-bin-dir=<ARMC6_bin_dir_path> ARM Compiler 6 bin directory. --gnutls-cli=<GnuTLS_cli_path> GnuTLS client executable to use for most tests. --gnutls-serv=<GnuTLS_serv_path> GnuTLS server executable to use for most tests. --gnutls-legacy-cli=<GnuTLS_cli_path> GnuTLS client executable to use for legacy tests. --gnutls-legacy-serv=<GnuTLS_serv_path> GnuTLS server executable to use for legacy tests. --openssl=<OpenSSL_path> OpenSSL executable to use for most tests. --openssl-legacy=<OpenSSL_path> OpenSSL executable to use for legacy tests e.g. SSLv3. --openssl-next=<OpenSSL_path> OpenSSL executable to use for recent things like ARIA EOF } # remove built files as well as the cmake cache/config cleanup() { if [ -n "${MBEDTLS_ROOT_DIR+set}" ]; then cd "$MBEDTLS_ROOT_DIR" fi command make clean # Remove CMake artefacts find . -name .git -prune -o \ -iname CMakeFiles -exec rm -rf {} \+ -o \ \( -iname cmake_install.cmake -o \ -iname CTestTestfile.cmake -o \ -iname CMakeCache.txt \) -exec rm {} \+ # Recover files overwritten by in-tree CMake builds rm -f include/Makefile include/mbedtls/Makefile programs/*/Makefile git update-index --no-skip-worktree Makefile library/Makefile programs/Makefile tests/Makefile programs/fuzz/Makefile git checkout -- Makefile library/Makefile programs/Makefile tests/Makefile programs/fuzz/Makefile # Remove any artifacts from the component_test_cmake_as_subdirectory test. rm -rf programs/test/cmake_subproject/build rm -f programs/test/cmake_subproject/Makefile rm -f programs/test/cmake_subproject/cmake_subproject if [ -f "$CONFIG_BAK" ]; then mv "$CONFIG_BAK" "$CONFIG_H" fi if [ -f "$CRYPTO_CONFIG_BAK" ]; then mv "$CRYPTO_CONFIG_BAK" "$CRYPTO_CONFIG_H" fi } # Executed on exit. May be redefined depending on command line options. final_report () { : } fatal_signal () { cleanup final_report $1 trap - $1 kill -$1 $$ } trap 'fatal_signal HUP' HUP trap 'fatal_signal INT' INT trap 'fatal_signal TERM' TERM msg() { if [ -n "${current_component:-}" ]; then current_section="${current_component#component_}: $1" else current_section="$1" fi if [ $QUIET -eq 1 ]; then return fi echo "" echo "******************************************************************" echo "* $current_section " printf "* "; date echo "******************************************************************" } armc6_build_test() { FLAGS="$1" msg "build: ARM Compiler 6 ($FLAGS)" ARM_TOOL_VARIANT="ult" CC="$ARMC6_CC" AR="$ARMC6_AR" CFLAGS="$FLAGS" \ WARNING_CFLAGS='-xc -std=c99' make lib msg "size: ARM Compiler 6 ($FLAGS)" "$ARMC6_FROMELF" -z library/*.o make clean } err_msg() { echo "$1" >&2 } check_tools() { for TOOL in "$@"; do if ! `type "$TOOL" >/dev/null 2>&1`; then err_msg "$TOOL not found!" exit 1 fi done } check_headers_in_cpp () { ls include/mbedtls | grep "\.h$" >headers.txt <programs/test/cpp_dummy_build.cpp sed -n 's/"$//; s!^#include "mbedtls/!!p' | sort | diff headers.txt - rm headers.txt } pre_parse_command_line () { COMMAND_LINE_COMPONENTS= all_except=0 no_armcc= # Note that legacy options are ignored instead of being omitted from this # list of options, so invocations that worked with previous version of # all.sh will still run and work properly. while [ $# -gt 0 ]; do case "$1" in --append-outcome) append_outcome=1;; --arm-none-eabi-gcc-prefix) shift; ARM_NONE_EABI_GCC_PREFIX="$1";; --armcc) no_armcc=;; --armc5-bin-dir) shift; ARMC5_BIN_DIR="$1";; --armc6-bin-dir) shift; ARMC6_BIN_DIR="$1";; --except) all_except=1;; --force|-f) FORCE=1;; --gnutls-cli) shift; GNUTLS_CLI="$1";; --gnutls-legacy-cli) shift; GNUTLS_LEGACY_CLI="$1";; --gnutls-legacy-serv) shift; GNUTLS_LEGACY_SERV="$1";; --gnutls-serv) shift; GNUTLS_SERV="$1";; --help|-h) usage; exit;; --keep-going|-k) KEEP_GOING=1;; --list-all-components) printf '%s\n' $ALL_COMPONENTS; exit;; --list-components) printf '%s\n' $SUPPORTED_COMPONENTS; exit;; --memory|-m) MEMORY=1;; --no-append-outcome) append_outcome=0;; --no-armcc) no_armcc=1;; --no-force) FORCE=0;; --no-keep-going) KEEP_GOING=0;; --no-memory) MEMORY=0;; --no-quiet) QUIET=0;; --openssl) shift; OPENSSL="$1";; --openssl-legacy) shift; OPENSSL_LEGACY="$1";; --openssl-next) shift; OPENSSL_NEXT="$1";; --outcome-file) shift; MBEDTLS_TEST_OUTCOME_FILE="$1";; --out-of-source-dir) shift; OUT_OF_SOURCE_DIR="$1";; --quiet|-q) QUIET=1;; --random-seed) unset SEED;; --release-test|-r) SEED=$RELEASE_SEED;; --seed|-s) shift; SEED="$1";; -*) echo >&2 "Unknown option: $1" echo >&2 "Run $0 --help for usage." exit 120 ;; *) COMMAND_LINE_COMPONENTS="$COMMAND_LINE_COMPONENTS $1";; esac shift done # With no list of components, run everything. if [ -z "$COMMAND_LINE_COMPONENTS" ]; then all_except=1 fi # --no-armcc is a legacy option. The modern way is --except '*_armcc*'. # Ignore it if components are listed explicitly on the command line. if [ -n "$no_armcc" ] && [ $all_except -eq 1 ]; then COMMAND_LINE_COMPONENTS="$COMMAND_LINE_COMPONENTS *_armcc*" fi # Build the list of components to run. RUN_COMPONENTS= for component in $SUPPORTED_COMPONENTS; do if is_component_included "$component"; [ $? -eq $all_except ]; then RUN_COMPONENTS="$RUN_COMPONENTS $component" fi done unset all_except unset no_armcc } pre_check_git () { if [ $FORCE -eq 1 ]; then rm -rf "$OUT_OF_SOURCE_DIR" git checkout-index -f -q $CONFIG_H cleanup else if [ -d "$OUT_OF_SOURCE_DIR" ]; then echo "Warning - there is an existing directory at '$OUT_OF_SOURCE_DIR'" >&2 echo "You can either delete this directory manually, or force the test by rerunning" echo "the script as: $0 --force --out-of-source-dir $OUT_OF_SOURCE_DIR" exit 1 fi if ! git diff --quiet include/mbedtls/config.h; then err_msg "Warning - the configuration file 'include/mbedtls/config.h' has been edited. " echo "You can either delete or preserve your work, or force the test by rerunning the" echo "script as: $0 --force" exit 1 fi fi } pre_setup_keep_going () { failure_summary= failure_count=0 start_red= end_color= if [ -t 1 ]; then case "${TERM:-}" in *color*|cygwin|linux|rxvt*|screen|[Eex]term*) start_red=$(printf '\033[31m') end_color=$(printf '\033[0m') ;; esac fi record_status () { if "$@"; then last_status=0 else last_status=$? text="$current_section: $* -> $last_status" failure_summary="$failure_summary $text" failure_count=$((failure_count + 1)) echo "${start_red}^^^^$text^^^^${end_color}" >&2 fi } make () { case "$*" in *test|*check) if [ $build_status -eq 0 ]; then record_status command make "$@" else echo "(skipped because the build failed)" fi ;; *) record_status command make "$@" build_status=$last_status ;; esac } final_report () { if [ $failure_count -gt 0 ]; then echo echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" echo "${start_red}FAILED: $failure_count${end_color}$failure_summary" echo "!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!" exit 1 elif [ -z "${1-}" ]; then echo "SUCCESS :)" fi if [ -n "${1-}" ]; then echo "Killed by SIG$1." fi } } if_build_succeeded () { if [ $build_status -eq 0 ]; then record_status "$@" fi } # to be used instead of ! for commands run with # record_status or if_build_succeeded not() { ! "$@" } pre_setup_quiet_redirect () { if [ $QUIET -ne 1 ]; then redirect_out () { "$@" } redirect_err () { "$@" } else redirect_out () { "$@" >/dev/null } redirect_err () { "$@" 2>/dev/null } fi } pre_prepare_outcome_file () { case "$MBEDTLS_TEST_OUTCOME_FILE" in [!/]*) MBEDTLS_TEST_OUTCOME_FILE="$PWD/$MBEDTLS_TEST_OUTCOME_FILE";; esac if [ -n "$MBEDTLS_TEST_OUTCOME_FILE" ] && [ "$append_outcome" -eq 0 ]; then rm -f "$MBEDTLS_TEST_OUTCOME_FILE" fi } pre_print_configuration () { if [ $QUIET -eq 1 ]; then return fi msg "info: $0 configuration" echo "MEMORY: $MEMORY" echo "FORCE: $FORCE" echo "MBEDTLS_TEST_OUTCOME_FILE: ${MBEDTLS_TEST_OUTCOME_FILE:-(none)}" echo "SEED: ${SEED-"UNSET"}" echo echo "OPENSSL: $OPENSSL" echo "OPENSSL_LEGACY: $OPENSSL_LEGACY" echo "OPENSSL_NEXT: $OPENSSL_NEXT" echo "GNUTLS_CLI: $GNUTLS_CLI" echo "GNUTLS_SERV: $GNUTLS_SERV" echo "GNUTLS_LEGACY_CLI: $GNUTLS_LEGACY_CLI" echo "GNUTLS_LEGACY_SERV: $GNUTLS_LEGACY_SERV" echo "ARMC5_BIN_DIR: $ARMC5_BIN_DIR" echo "ARMC6_BIN_DIR: $ARMC6_BIN_DIR" } # Make sure the tools we need are available. pre_check_tools () { # Build the list of variables to pass to output_env.sh. set env case " $RUN_COMPONENTS " in # Require OpenSSL and GnuTLS if running any tests (as opposed to # only doing builds). Not all tests run OpenSSL and GnuTLS, but this # is a good enough approximation in practice. *" test_"*) # To avoid setting OpenSSL and GnuTLS for each call to compat.sh # and ssl-opt.sh, we just export the variables they require. export OPENSSL_CMD="$OPENSSL" export GNUTLS_CLI="$GNUTLS_CLI" export GNUTLS_SERV="$GNUTLS_SERV" # Avoid passing --seed flag in every call to ssl-opt.sh if [ -n "${SEED-}" ]; then export SEED fi set "$@" OPENSSL="$OPENSSL" OPENSSL_LEGACY="$OPENSSL_LEGACY" set "$@" GNUTLS_CLI="$GNUTLS_CLI" GNUTLS_SERV="$GNUTLS_SERV" set "$@" GNUTLS_LEGACY_CLI="$GNUTLS_LEGACY_CLI" set "$@" GNUTLS_LEGACY_SERV="$GNUTLS_LEGACY_SERV" check_tools "$OPENSSL" "$OPENSSL_LEGACY" "$OPENSSL_NEXT" \ "$GNUTLS_CLI" "$GNUTLS_SERV" \ "$GNUTLS_LEGACY_CLI" "$GNUTLS_LEGACY_SERV" ;; esac case " $RUN_COMPONENTS " in *_doxygen[_\ ]*) check_tools "doxygen" "dot";; esac case " $RUN_COMPONENTS " in *_arm_none_eabi_gcc[_\ ]*) check_tools "${ARM_NONE_EABI_GCC_PREFIX}gcc";; esac case " $RUN_COMPONENTS " in *_mingw[_\ ]*) check_tools "i686-w64-mingw32-gcc";; esac case " $RUN_COMPONENTS " in *" test_zeroize "*) check_tools "gdb";; esac case " $RUN_COMPONENTS " in *_armcc*) ARMC5_CC="$ARMC5_BIN_DIR/armcc" ARMC5_AR="$ARMC5_BIN_DIR/armar" ARMC5_FROMELF="$ARMC5_BIN_DIR/fromelf" ARMC6_CC="$ARMC6_BIN_DIR/armclang" ARMC6_AR="$ARMC6_BIN_DIR/armar" ARMC6_FROMELF="$ARMC6_BIN_DIR/fromelf" check_tools "$ARMC5_CC" "$ARMC5_AR" "$ARMC5_FROMELF" \ "$ARMC6_CC" "$ARMC6_AR" "$ARMC6_FROMELF";; esac # past this point, no call to check_tool, only printing output if [ $QUIET -eq 1 ]; then return fi msg "info: output_env.sh" case $RUN_COMPONENTS in *_armcc*) set "$@" ARMC5_CC="$ARMC5_CC" ARMC6_CC="$ARMC6_CC" RUN_ARMCC=1;; *) set "$@" RUN_ARMCC=0;; esac "$@" scripts/output_env.sh } ################################################################ #### Basic checks ################################################################ # # Test Suites to be executed # # The test ordering tries to optimize for the following criteria: # 1. Catch possible problems early, by running first tests that run quickly # and/or are more likely to fail than others (eg I use Clang most of the # time, so start with a GCC build). # 2. Minimize total running time, by avoiding useless rebuilds # # Indicative running times are given for reference. component_check_recursion () { msg "Check: recursion.pl" # < 1s record_status tests/scripts/recursion.pl library/*.c } component_check_generated_files () { msg "Check: freshness of generated source files" # < 1s record_status tests/scripts/check-generated-files.sh } component_check_doxy_blocks () { msg "Check: doxygen markup outside doxygen blocks" # < 1s record_status tests/scripts/check-doxy-blocks.pl } component_check_files () { msg "Check: file sanity checks (permissions, encodings)" # < 1s record_status tests/scripts/check_files.py } component_check_changelog () { msg "Check: changelog entries" # < 1s rm -f ChangeLog.new record_status scripts/assemble_changelog.py -o ChangeLog.new if [ -e ChangeLog.new ]; then # Show the diff for information. It isn't an error if the diff is # non-empty. diff -u ChangeLog ChangeLog.new || true rm ChangeLog.new fi } component_check_names () { msg "Check: declared and exported names (builds the library)" # < 3s record_status tests/scripts/check-names.sh -v } component_check_test_cases () { msg "Check: test case descriptions" # < 1s if [ $QUIET -eq 1 ]; then opt='--quiet' else opt='' fi record_status tests/scripts/check_test_cases.py $opt unset opt } component_check_doxygen_warnings () { msg "Check: doxygen warnings (builds the documentation)" # ~ 3s record_status tests/scripts/doxygen.sh } ################################################################ #### Build and test many configurations and targets ################################################################ component_test_default_out_of_box () { msg "build: make, default config (out-of-box)" # ~1min make # Disable fancy stuff SAVE_MBEDTLS_TEST_OUTCOME_FILE="$MBEDTLS_TEST_OUTCOME_FILE" unset MBEDTLS_TEST_OUTCOME_FILE msg "test: main suites make, default config (out-of-box)" # ~10s make test msg "selftest: make, default config (out-of-box)" # ~10s if_build_succeeded programs/test/selftest export MBEDTLS_TEST_OUTCOME_FILE="$SAVE_MBEDTLS_TEST_OUTCOME_FILE" unset SAVE_MBEDTLS_TEST_OUTCOME_FILE } component_test_default_cmake_gcc_asan () { msg "build: cmake, gcc, ASan" # ~ 1 min 50s CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: main suites (inc. selftests) (ASan build)" # ~ 50s make test msg "test: selftest (ASan build)" # ~ 10s if_build_succeeded programs/test/selftest msg "test: ssl-opt.sh (ASan build)" # ~ 1 min if_build_succeeded tests/ssl-opt.sh msg "test: compat.sh (ASan build)" # ~ 6 min if_build_succeeded tests/compat.sh msg "test: context-info.sh (ASan build)" # ~ 15 sec if_build_succeeded tests/context-info.sh } component_test_full_cmake_gcc_asan () { msg "build: full config, cmake, gcc, ASan" scripts/config.py full CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: main suites (inc. selftests) (full config, ASan build)" make test msg "test: selftest (ASan build)" # ~ 10s if_build_succeeded programs/test/selftest msg "test: ssl-opt.sh (full config, ASan build)" if_build_succeeded tests/ssl-opt.sh msg "test: compat.sh (full config, ASan build)" if_build_succeeded tests/compat.sh msg "test: context-info.sh (full config, ASan build)" # ~ 15 sec if_build_succeeded tests/context-info.sh } component_test_psa_crypto_key_id_encodes_owner () { msg "build: full config - USE_PSA_CRYPTO + PSA_CRYPTO_KEY_ID_ENCODES_OWNER, cmake, gcc, ASan" scripts/config.py full scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py set MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: full config - USE_PSA_CRYPTO + PSA_CRYPTO_KEY_ID_ENCODES_OWNER, cmake, gcc, ASan" make test } # check_renamed_symbols HEADER LIB # Check that if HEADER contains '#define MACRO ...' then MACRO is not a symbol # name is LIB. check_renamed_symbols () { ! nm "$2" | sed 's/.* //' | grep -x -F "$(sed -n 's/^ *# *define *\([A-Z_a-z][0-9A-Z_a-z]*\)..*/\1/p' "$1")" } component_build_psa_crypto_spm () { msg "build: full config - USE_PSA_CRYPTO + PSA_CRYPTO_KEY_ID_ENCODES_OWNER + PSA_CRYPTO_SPM, make, gcc" scripts/config.py full scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py unset MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS scripts/config.py set MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER scripts/config.py set MBEDTLS_PSA_CRYPTO_SPM # We can only compile, not link, since our test and sample programs # aren't equipped for the modified names used when MBEDTLS_PSA_CRYPTO_SPM # is active. make CC=gcc CFLAGS='-Werror -Wall -Wextra -I../tests/include/spe' lib # Check that if a symbol is renamed by crypto_spe.h, the non-renamed # version is not present. echo "Checking for renamed symbols in the library" if_build_succeeded check_renamed_symbols tests/include/spe/crypto_spe.h library/libmbedcrypto.a } component_test_psa_crypto_client () { msg "build: default config - PSA_CRYPTO_C + PSA_CRYPTO_CLIENT, make" scripts/config.py unset MBEDTLS_PSA_CRYPTO_C scripts/config.py unset MBEDTLS_PSA_CRYPTO_STORAGE_C scripts/config.py set MBEDTLS_PSA_CRYPTO_CLIENT make msg "test: default config - PSA_CRYPTO_C + PSA_CRYPTO_CLIENT, make" make test } component_test_zlib_make() { msg "build: zlib enabled, make" scripts/config.py set MBEDTLS_ZLIB_SUPPORT make ZLIB=1 CFLAGS='-Werror -O1' msg "test: main suites (zlib, make)" make test msg "test: ssl-opt.sh (zlib, make)" if_build_succeeded tests/ssl-opt.sh } support_test_zlib_make () { base=support_test_zlib_$$ cat <<'EOF' > ${base}.c #include "zlib.h" int main(void) { return 0; } EOF gcc -o ${base}.exe ${base}.c -lz 2>/dev/null ret=$? rm -f ${base}.* return $ret } component_test_zlib_cmake() { msg "build: zlib enabled, cmake" scripts/config.py set MBEDTLS_ZLIB_SUPPORT cmake -D ENABLE_ZLIB_SUPPORT=On -D CMAKE_BUILD_TYPE:String=Check . make msg "test: main suites (zlib, cmake)" make test msg "test: ssl-opt.sh (zlib, cmake)" if_build_succeeded tests/ssl-opt.sh } support_test_zlib_cmake () { support_test_zlib_make "$@" } component_test_psa_crypto_rsa_no_genprime() { msg "build: default config minus MBEDTLS_GENPRIME" scripts/config.py unset MBEDTLS_GENPRIME make msg "test: default config minus MBEDTLS_GENPRIME" make test } component_test_ref_configs () { msg "test/build: ref-configs (ASan build)" # ~ 6 min 20s CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . record_status tests/scripts/test-ref-configs.pl } component_test_sslv3 () { msg "build: Default + SSLv3 (ASan build)" # ~ 6 min scripts/config.py set MBEDTLS_SSL_PROTO_SSL3 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: SSLv3 - main suites (inc. selftests) (ASan build)" # ~ 50s make test msg "build: SSLv3 - compat.sh (ASan build)" # ~ 6 min if_build_succeeded tests/compat.sh -m 'tls1 tls1_1 tls1_2 dtls1 dtls1_2' if_build_succeeded env OPENSSL_CMD="$OPENSSL_LEGACY" tests/compat.sh -m 'ssl3' msg "build: SSLv3 - ssl-opt.sh (ASan build)" # ~ 6 min if_build_succeeded tests/ssl-opt.sh msg "build: SSLv3 - context-info.sh (ASan build)" # ~ 15 sec if_build_succeeded tests/context-info.sh } component_test_no_renegotiation () { msg "build: Default + !MBEDTLS_SSL_RENEGOTIATION (ASan build)" # ~ 6 min scripts/config.py unset MBEDTLS_SSL_RENEGOTIATION CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: !MBEDTLS_SSL_RENEGOTIATION - main suites (inc. selftests) (ASan build)" # ~ 50s make test msg "test: !MBEDTLS_SSL_RENEGOTIATION - ssl-opt.sh (ASan build)" # ~ 6 min if_build_succeeded tests/ssl-opt.sh } component_test_no_pem_no_fs () { msg "build: Default + !MBEDTLS_PEM_PARSE_C + !MBEDTLS_FS_IO (ASan build)" scripts/config.py unset MBEDTLS_PEM_PARSE_C scripts/config.py unset MBEDTLS_FS_IO scripts/config.py unset MBEDTLS_PSA_ITS_FILE_C # requires a filesystem scripts/config.py unset MBEDTLS_PSA_CRYPTO_STORAGE_C # requires PSA ITS CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: !MBEDTLS_PEM_PARSE_C !MBEDTLS_FS_IO - main suites (inc. selftests) (ASan build)" # ~ 50s make test msg "test: !MBEDTLS_PEM_PARSE_C !MBEDTLS_FS_IO - ssl-opt.sh (ASan build)" # ~ 6 min if_build_succeeded tests/ssl-opt.sh } component_test_rsa_no_crt () { msg "build: Default + RSA_NO_CRT (ASan build)" # ~ 6 min scripts/config.py set MBEDTLS_RSA_NO_CRT CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: RSA_NO_CRT - main suites (inc. selftests) (ASan build)" # ~ 50s make test msg "test: RSA_NO_CRT - RSA-related part of ssl-opt.sh (ASan build)" # ~ 5s if_build_succeeded tests/ssl-opt.sh -f RSA msg "test: RSA_NO_CRT - RSA-related part of compat.sh (ASan build)" # ~ 3 min if_build_succeeded tests/compat.sh -t RSA msg "test: RSA_NO_CRT - RSA-related part of context-info.sh (ASan build)" # ~ 15 sec if_build_succeeded tests/context-info.sh } component_test_no_ctr_drbg_classic () { msg "build: Full minus CTR_DRBG, classic crypto in TLS" scripts/config.py full scripts/config.py unset MBEDTLS_CTR_DRBG_C scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: Full minus CTR_DRBG, classic crypto - main suites" make test # In this configuration, the TLS test programs use HMAC_DRBG. # The SSL tests are slow, so run a small subset, just enough to get # confidence that the SSL code copes with HMAC_DRBG. msg "test: Full minus CTR_DRBG, classic crypto - ssl-opt.sh (subset)" if_build_succeeded tests/ssl-opt.sh -f 'Default\|SSL async private.*delay=\|tickets enabled on server' msg "test: Full minus CTR_DRBG, classic crypto - compat.sh (subset)" if_build_succeeded tests/compat.sh -m tls1_2 -t 'ECDSA PSK' -V NO -p OpenSSL } component_test_no_ctr_drbg_use_psa () { msg "build: Full minus CTR_DRBG, PSA crypto in TLS" scripts/config.py full scripts/config.py unset MBEDTLS_CTR_DRBG_C scripts/config.py set MBEDTLS_USE_PSA_CRYPTO CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: Full minus CTR_DRBG, USE_PSA_CRYPTO - main suites" make test # In this configuration, the TLS test programs use HMAC_DRBG. # The SSL tests are slow, so run a small subset, just enough to get # confidence that the SSL code copes with HMAC_DRBG. msg "test: Full minus CTR_DRBG, USE_PSA_CRYPTO - ssl-opt.sh (subset)" if_build_succeeded tests/ssl-opt.sh -f 'Default\|SSL async private.*delay=\|tickets enabled on server' msg "test: Full minus CTR_DRBG, USE_PSA_CRYPTO - compat.sh (subset)" if_build_succeeded tests/compat.sh -m tls1_2 -t 'ECDSA PSK' -V NO -p OpenSSL } component_test_no_hmac_drbg_classic () { msg "build: Full minus HMAC_DRBG, classic crypto in TLS" scripts/config.py full scripts/config.py unset MBEDTLS_HMAC_DRBG_C scripts/config.py unset MBEDTLS_ECDSA_DETERMINISTIC # requires HMAC_DRBG scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: Full minus HMAC_DRBG, classic crypto - main suites" make test # Normally our ECDSA implementation uses deterministic ECDSA. But since # HMAC_DRBG is disabled in this configuration, randomized ECDSA is used # instead. # Test SSL with non-deterministic ECDSA. Only test features that # might be affected by how ECDSA signature is performed. msg "test: Full minus HMAC_DRBG, classic crypto - ssl-opt.sh (subset)" if_build_succeeded tests/ssl-opt.sh -f 'Default\|SSL async private: sign' # To save time, only test one protocol version, since this part of # the protocol is identical in (D)TLS up to 1.2. msg "test: Full minus HMAC_DRBG, classic crypto - compat.sh (ECDSA)" if_build_succeeded tests/compat.sh -m tls1_2 -t 'ECDSA' } component_test_no_hmac_drbg_use_psa () { msg "build: Full minus HMAC_DRBG, PSA crypto in TLS" scripts/config.py full scripts/config.py unset MBEDTLS_HMAC_DRBG_C scripts/config.py unset MBEDTLS_ECDSA_DETERMINISTIC # requires HMAC_DRBG scripts/config.py set MBEDTLS_USE_PSA_CRYPTO CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: Full minus HMAC_DRBG, USE_PSA_CRYPTO - main suites" make test # Normally our ECDSA implementation uses deterministic ECDSA. But since # HMAC_DRBG is disabled in this configuration, randomized ECDSA is used # instead. # Test SSL with non-deterministic ECDSA. Only test features that # might be affected by how ECDSA signature is performed. msg "test: Full minus HMAC_DRBG, USE_PSA_CRYPTO - ssl-opt.sh (subset)" if_build_succeeded tests/ssl-opt.sh -f 'Default\|SSL async private: sign' # To save time, only test one protocol version, since this part of # the protocol is identical in (D)TLS up to 1.2. msg "test: Full minus HMAC_DRBG, USE_PSA_CRYPTO - compat.sh (ECDSA)" if_build_succeeded tests/compat.sh -m tls1_2 -t 'ECDSA' } component_test_psa_external_rng_no_drbg_classic () { msg "build: PSA_CRYPTO_EXTERNAL_RNG minus *_DRBG, classic crypto in TLS" scripts/config.py full scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py set MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG scripts/config.py unset MBEDTLS_ENTROPY_C scripts/config.py unset MBEDTLS_ENTROPY_NV_SEED scripts/config.py unset MBEDTLS_PLATFORM_NV_SEED_ALT scripts/config.py unset MBEDTLS_CTR_DRBG_C scripts/config.py unset MBEDTLS_HMAC_DRBG_C scripts/config.py unset MBEDTLS_ECDSA_DETERMINISTIC # requires HMAC_DRBG scripts/config.py set MBEDTLS_ECP_NO_INTERNAL_RNG # When MBEDTLS_USE_PSA_CRYPTO is disabled and there is no DRBG, # the SSL test programs don't have an RNG and can't work. Explicitly # make them use the PSA RNG with -DMBEDTLS_TEST_USE_PSA_CRYPTO_RNG. make CFLAGS="$ASAN_CFLAGS -O2 -DMBEDTLS_TEST_USE_PSA_CRYPTO_RNG" LDFLAGS="$ASAN_CFLAGS" msg "test: PSA_CRYPTO_EXTERNAL_RNG minus *_DRBG, classic crypto - main suites" make test msg "test: PSA_CRYPTO_EXTERNAL_RNG minus *_DRBG, classic crypto - ssl-opt.sh (subset)" if_build_succeeded tests/ssl-opt.sh -f 'Default' } component_test_psa_external_rng_no_drbg_use_psa () { msg "build: PSA_CRYPTO_EXTERNAL_RNG minus *_DRBG, PSA crypto in TLS" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG scripts/config.py unset MBEDTLS_ENTROPY_C scripts/config.py unset MBEDTLS_ENTROPY_NV_SEED scripts/config.py unset MBEDTLS_PLATFORM_NV_SEED_ALT scripts/config.py unset MBEDTLS_CTR_DRBG_C scripts/config.py unset MBEDTLS_HMAC_DRBG_C scripts/config.py unset MBEDTLS_ECDSA_DETERMINISTIC # requires HMAC_DRBG scripts/config.py set MBEDTLS_ECP_NO_INTERNAL_RNG make CFLAGS="$ASAN_CFLAGS -O2" LDFLAGS="$ASAN_CFLAGS" msg "test: PSA_CRYPTO_EXTERNAL_RNG minus *_DRBG, PSA crypto - main suites" make test msg "test: PSA_CRYPTO_EXTERNAL_RNG minus *_DRBG, PSA crypto - ssl-opt.sh (subset)" if_build_succeeded tests/ssl-opt.sh -f 'Default\|opaque' } component_test_psa_external_rng_use_psa_crypto () { msg "build: full + PSA_CRYPTO_EXTERNAL_RNG + USE_PSA_CRYPTO minus CTR_DRBG" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG scripts/config.py set MBEDTLS_USE_PSA_CRYPTO scripts/config.py unset MBEDTLS_CTR_DRBG_C make CFLAGS="$ASAN_CFLAGS -O2" LDFLAGS="$ASAN_CFLAGS" msg "test: full + PSA_CRYPTO_EXTERNAL_RNG + USE_PSA_CRYPTO minus CTR_DRBG" make test msg "test: full + PSA_CRYPTO_EXTERNAL_RNG + USE_PSA_CRYPTO minus CTR_DRBG" if_build_succeeded tests/ssl-opt.sh -f 'Default\|opaque' } component_test_ecp_no_internal_rng () { msg "build: Default plus ECP_NO_INTERNAL_RNG minus DRBG modules" scripts/config.py set MBEDTLS_ECP_NO_INTERNAL_RNG scripts/config.py unset MBEDTLS_CTR_DRBG_C scripts/config.py unset MBEDTLS_HMAC_DRBG_C scripts/config.py unset MBEDTLS_ECDSA_DETERMINISTIC # requires HMAC_DRBG scripts/config.py unset MBEDTLS_PSA_CRYPTO_C # requires a DRBG scripts/config.py unset MBEDTLS_PSA_CRYPTO_STORAGE_C # requires PSA Crypto CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: ECP_NO_INTERNAL_RNG, no DRBG module" make test # no SSL tests as they all depend on having a DRBG } component_test_ecp_restartable_no_internal_rng () { msg "build: Default plus ECP_RESTARTABLE and ECP_NO_INTERNAL_RNG, no DRBG" scripts/config.py set MBEDTLS_ECP_NO_INTERNAL_RNG scripts/config.py set MBEDTLS_ECP_RESTARTABLE scripts/config.py unset MBEDTLS_CTR_DRBG_C scripts/config.py unset MBEDTLS_HMAC_DRBG_C scripts/config.py unset MBEDTLS_ECDSA_DETERMINISTIC # requires HMAC_DRBG scripts/config.py unset MBEDTLS_PSA_CRYPTO_C # requires CTR_DRBG scripts/config.py unset MBEDTLS_PSA_CRYPTO_STORAGE_C # requires PSA Crypto CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: ECP_RESTARTABLE and ECP_NO_INTERNAL_RNG, no DRBG module" make test # no SSL tests as they all depend on having a DRBG } component_test_new_ecdh_context () { msg "build: new ECDH context (ASan build)" # ~ 6 min scripts/config.py unset MBEDTLS_ECDH_LEGACY_CONTEXT CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: new ECDH context - main suites (inc. selftests) (ASan build)" # ~ 50s make test msg "test: new ECDH context - ECDH-related part of ssl-opt.sh (ASan build)" # ~ 5s if_build_succeeded tests/ssl-opt.sh -f ECDH msg "test: new ECDH context - compat.sh with some ECDH ciphersuites (ASan build)" # ~ 3 min # Exclude some symmetric ciphers that are redundant here to gain time. if_build_succeeded tests/compat.sh -f ECDH -V NO -e 'ARCFOUR\|ARIA\|CAMELLIA\|CHACHA\|DES\|RC4' } component_test_everest () { msg "build: Everest ECDH context (ASan build)" # ~ 6 min scripts/config.py unset MBEDTLS_ECDH_LEGACY_CONTEXT scripts/config.py set MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED CC=clang cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: Everest ECDH context - main suites (inc. selftests) (ASan build)" # ~ 50s make test msg "test: Everest ECDH context - ECDH-related part of ssl-opt.sh (ASan build)" # ~ 5s if_build_succeeded tests/ssl-opt.sh -f ECDH msg "test: Everest ECDH context - compat.sh with some ECDH ciphersuites (ASan build)" # ~ 3 min # Exclude some symmetric ciphers that are redundant here to gain time. if_build_succeeded tests/compat.sh -f ECDH -V NO -e 'ARCFOUR\|ARIA\|CAMELLIA\|CHACHA\|DES\|RC4' } component_test_everest_curve25519_only () { msg "build: Everest ECDH context, only Curve25519" # ~ 6 min scripts/config.py unset MBEDTLS_ECDH_LEGACY_CONTEXT scripts/config.py set MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED scripts/config.py unset MBEDTLS_ECDSA_C scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED # Disable all curves for c in $(sed -n 's/#define \(MBEDTLS_ECP_DP_[0-9A-Z_a-z]*_ENABLED\).*/\1/p' <"$CONFIG_H"); do scripts/config.py unset "$c" done scripts/config.py set MBEDTLS_ECP_DP_CURVE25519_ENABLED make CFLAGS="$ASAN_CFLAGS -O2" LDFLAGS="$ASAN_CFLAGS" msg "test: Everest ECDH context, only Curve25519" # ~ 50s make test } component_test_small_ssl_out_content_len () { msg "build: small SSL_OUT_CONTENT_LEN (ASan build)" scripts/config.py set MBEDTLS_SSL_IN_CONTENT_LEN 16384 scripts/config.py set MBEDTLS_SSL_OUT_CONTENT_LEN 4096 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: small SSL_OUT_CONTENT_LEN - ssl-opt.sh MFL and large packet tests" if_build_succeeded tests/ssl-opt.sh -f "Max fragment\|Large packet" } component_test_small_ssl_in_content_len () { msg "build: small SSL_IN_CONTENT_LEN (ASan build)" scripts/config.py set MBEDTLS_SSL_IN_CONTENT_LEN 4096 scripts/config.py set MBEDTLS_SSL_OUT_CONTENT_LEN 16384 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: small SSL_IN_CONTENT_LEN - ssl-opt.sh MFL tests" if_build_succeeded tests/ssl-opt.sh -f "Max fragment" } component_test_small_ssl_dtls_max_buffering () { msg "build: small MBEDTLS_SSL_DTLS_MAX_BUFFERING #0" scripts/config.py set MBEDTLS_SSL_DTLS_MAX_BUFFERING 1000 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: small MBEDTLS_SSL_DTLS_MAX_BUFFERING #0 - ssl-opt.sh specific reordering test" if_build_succeeded tests/ssl-opt.sh -f "DTLS reordering: Buffer out-of-order hs msg before reassembling next, free buffered msg" } component_test_small_mbedtls_ssl_dtls_max_buffering () { msg "build: small MBEDTLS_SSL_DTLS_MAX_BUFFERING #1" scripts/config.py set MBEDTLS_SSL_DTLS_MAX_BUFFERING 190 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: small MBEDTLS_SSL_DTLS_MAX_BUFFERING #1 - ssl-opt.sh specific reordering test" if_build_succeeded tests/ssl-opt.sh -f "DTLS reordering: Buffer encrypted Finished message, drop for fragmented NewSessionTicket" } component_test_psa_collect_statuses () { msg "build+test: psa_collect_statuses" # ~30s scripts/config.py full record_status tests/scripts/psa_collect_statuses.py # Check that psa_crypto_init() succeeded at least once record_status grep -q '^0:psa_crypto_init:' tests/statuses.log rm -f tests/statuses.log } component_test_full_cmake_clang () { msg "build: cmake, full config, clang" # ~ 50s scripts/config.py full CC=clang cmake -D CMAKE_BUILD_TYPE:String=Check -D ENABLE_TESTING=On . make msg "test: main suites (full config, clang)" # ~ 5s make test msg "test: psa_constant_names (full config, clang)" # ~ 1s record_status tests/scripts/test_psa_constant_names.py msg "test: ssl-opt.sh default, ECJPAKE, SSL async (full config)" # ~ 1s if_build_succeeded tests/ssl-opt.sh -f 'Default\|ECJPAKE\|SSL async private' msg "test: compat.sh RC4, DES, 3DES & NULL (full config)" # ~ 2 min if_build_succeeded env OPENSSL_CMD="$OPENSSL_LEGACY" GNUTLS_CLI="$GNUTLS_LEGACY_CLI" GNUTLS_SERV="$GNUTLS_LEGACY_SERV" tests/compat.sh -e '^$' -f 'NULL\|DES\|RC4\|ARCFOUR' msg "test: compat.sh ARIA + ChachaPoly" if_build_succeeded env OPENSSL_CMD="$OPENSSL_NEXT" tests/compat.sh -e '^$' -f 'ARIA\|CHACHA' } component_test_memsan_constant_flow () { # This tests both (1) accesses to undefined memory, and (2) branches or # memory access depending on secret values. To distinguish between those: # - unset MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN - does the failure persist? # - or alternatively, change the build type to MemSanDbg, which enables # origin tracking and nicer stack traces (which are useful for debugging # anyway), and check if the origin was TEST_CF_SECRET() or something else. msg "build: cmake MSan (clang), full config with constant flow testing" scripts/config.py full scripts/config.py set MBEDTLS_TEST_CONSTANT_FLOW_MEMSAN scripts/config.py unset MBEDTLS_AESNI_C # memsan doesn't grok asm CC=clang cmake -D CMAKE_BUILD_TYPE:String=MemSan . make msg "test: main suites (Msan + constant flow)" make test } component_test_valgrind_constant_flow () { # This tests both (1) everything that valgrind's memcheck usually checks # (heap buffer overflows, use of uninitialized memory, use-after-free, # etc.) and (2) branches or memory access depending on secret values, # which will be reported as uninitialized memory. To distinguish between # secret and actually uninitialized: # - unset MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND - does the failure persist? # - or alternatively, build with debug info and manually run the offending # test suite with valgrind --track-origins=yes, then check if the origin # was TEST_CF_SECRET() or something else. msg "build: cmake release GCC, full config with constant flow testing" scripts/config.py full scripts/config.py set MBEDTLS_TEST_CONSTANT_FLOW_VALGRIND cmake -D CMAKE_BUILD_TYPE:String=Release . make # this only shows a summary of the results (how many of each type) # details are left in Testing/<date>/DynamicAnalysis.xml msg "test: main suites (valgrind + constant flow)" make memcheck } component_test_default_no_deprecated () { # Test that removing the deprecated features from the default # configuration leaves something consistent. msg "build: make, default + MBEDTLS_DEPRECATED_REMOVED" # ~ 30s scripts/config.py set MBEDTLS_DEPRECATED_REMOVED make CC=gcc CFLAGS='-O -Werror -Wall -Wextra' msg "test: make, default + MBEDTLS_DEPRECATED_REMOVED" # ~ 5s make test } component_test_full_no_deprecated () { msg "build: make, full_no_deprecated config" # ~ 30s scripts/config.py full_no_deprecated make CC=gcc CFLAGS='-O -Werror -Wall -Wextra' msg "test: make, full_no_deprecated config" # ~ 5s make test } component_test_full_no_deprecated_deprecated_warning () { # Test that there is nothing deprecated in "full_no_deprecated". # A deprecated feature would trigger a warning (made fatal) from # MBEDTLS_DEPRECATED_WARNING. msg "build: make, full_no_deprecated config, MBEDTLS_DEPRECATED_WARNING" # ~ 30s scripts/config.py full_no_deprecated scripts/config.py unset MBEDTLS_DEPRECATED_REMOVED scripts/config.py set MBEDTLS_DEPRECATED_WARNING make CC=gcc CFLAGS='-O -Werror -Wall -Wextra' msg "test: make, full_no_deprecated config, MBEDTLS_DEPRECATED_WARNING" # ~ 5s make test } component_test_full_deprecated_warning () { # Test that when MBEDTLS_DEPRECATED_WARNING is enabled, the build passes # with only certain whitelisted types of warnings. msg "build: make, full config + MBEDTLS_DEPRECATED_WARNING, expect warnings" # ~ 30s scripts/config.py full scripts/config.py set MBEDTLS_DEPRECATED_WARNING # Expect warnings from '#warning' directives in check_config.h. make CC=gcc CFLAGS='-O -Werror -Wall -Wextra -Wno-error=cpp' lib programs msg "build: make tests, full config + MBEDTLS_DEPRECATED_WARNING, expect warnings" # ~ 30s # Set MBEDTLS_TEST_DEPRECATED to enable tests for deprecated features. # By default those are disabled when MBEDTLS_DEPRECATED_WARNING is set. # Expect warnings from '#warning' directives in check_config.h and # from the use of deprecated functions in test suites. make CC=gcc CFLAGS='-O -Werror -Wall -Wextra -Wno-error=deprecated-declarations -Wno-error=cpp -DMBEDTLS_TEST_DEPRECATED' tests msg "test: full config + MBEDTLS_TEST_DEPRECATED" # ~ 30s make test } # Check that the specified libraries exist and are empty. are_empty_libraries () { nm "$@" >/dev/null 2>/dev/null ! nm "$@" 2>/dev/null | grep -v ':$' | grep . } component_build_crypto_default () { msg "build: make, crypto only" scripts/config.py crypto make CFLAGS='-O1 -Werror' if_build_succeeded are_empty_libraries library/libmbedx509.* library/libmbedtls.* } component_build_crypto_full () { msg "build: make, crypto only, full config" scripts/config.py crypto_full make CFLAGS='-O1 -Werror' if_build_succeeded are_empty_libraries library/libmbedx509.* library/libmbedtls.* } component_build_crypto_baremetal () { msg "build: make, crypto only, baremetal config" scripts/config.py crypto_baremetal make CFLAGS='-O1 -Werror' if_build_succeeded are_empty_libraries library/libmbedx509.* library/libmbedtls.* } component_test_depends_curves () { msg "test/build: curves.pl (gcc)" # ~ 4 min record_status tests/scripts/curves.pl } component_test_depends_curves_psa () { msg "test/build: curves.pl with MBEDTLS_USE_PSA_CRYPTO defined (gcc)" scripts/config.py set MBEDTLS_USE_PSA_CRYPTO record_status tests/scripts/curves.pl } component_test_depends_hashes () { msg "test/build: depends-hashes.pl (gcc)" # ~ 2 min record_status tests/scripts/depends-hashes.pl } component_test_depends_hashes_psa () { msg "test/build: depends-hashes.pl with MBEDTLS_USE_PSA_CRYPTO defined (gcc)" scripts/config.py set MBEDTLS_USE_PSA_CRYPTO record_status tests/scripts/depends-hashes.pl } component_test_depends_pkalgs () { msg "test/build: depends-pkalgs.pl (gcc)" # ~ 2 min record_status tests/scripts/depends-pkalgs.pl } component_test_depends_pkalgs_psa () { msg "test/build: depends-pkalgs.pl with MBEDTLS_USE_PSA_CRYPTO defined (gcc)" scripts/config.py set MBEDTLS_USE_PSA_CRYPTO record_status tests/scripts/depends-pkalgs.pl } component_build_key_exchanges () { msg "test/build: key-exchanges (gcc)" # ~ 1 min record_status tests/scripts/key-exchanges.pl } component_build_default_make_gcc_and_cxx () { msg "build: Unix make, -Os (gcc)" # ~ 30s make CC=gcc CFLAGS='-Werror -Wall -Wextra -Os' msg "test: verify header list in cpp_dummy_build.cpp" record_status check_headers_in_cpp msg "build: Unix make, incremental g++" make TEST_CPP=1 } component_test_no_use_psa_crypto_full_cmake_asan() { # full minus MBEDTLS_USE_PSA_CRYPTO: run the same set of tests as basic-build-test.sh msg "build: cmake, full config minus MBEDTLS_USE_PSA_CRYPTO, ASan" scripts/config.py full scripts/config.py set MBEDTLS_ECP_RESTARTABLE # not using PSA, so enable restartable ECC scripts/config.py unset MBEDTLS_PSA_CRYPTO_C scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py unset MBEDTLS_PSA_ITS_FILE_C scripts/config.py unset MBEDTLS_PSA_CRYPTO_SE_C scripts/config.py unset MBEDTLS_PSA_CRYPTO_STORAGE_C CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: main suites (full minus MBEDTLS_USE_PSA_CRYPTO)" make test msg "test: ssl-opt.sh (full minus MBEDTLS_USE_PSA_CRYPTO)" if_build_succeeded tests/ssl-opt.sh msg "test: compat.sh default (full minus MBEDTLS_USE_PSA_CRYPTO)" if_build_succeeded tests/compat.sh msg "test: compat.sh RC4, DES & NULL (full minus MBEDTLS_USE_PSA_CRYPTO)" if_build_succeeded env OPENSSL_CMD="$OPENSSL_LEGACY" GNUTLS_CLI="$GNUTLS_LEGACY_CLI" GNUTLS_SERV="$GNUTLS_LEGACY_SERV" tests/compat.sh -e '3DES\|DES-CBC3' -f 'NULL\|DES\|RC4\|ARCFOUR' msg "test: compat.sh ARIA + ChachaPoly (full minus MBEDTLS_USE_PSA_CRYPTO)" if_build_succeeded env OPENSSL_CMD="$OPENSSL_NEXT" tests/compat.sh -e '^$' -f 'ARIA\|CHACHA' } component_test_psa_crypto_config_basic() { # Test the library excluding all Mbed TLS cryptographic support for which # we have an accelerator support. Acceleration is faked with the # transparent test driver. msg "test: full + MBEDTLS_PSA_CRYPTO_CONFIG + as much acceleration as supported" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO # There is no intended accelerator support for ALG STREAM_CIPHER and # ALG_ECB_NO_PADDING. Therefore, asking for them in the build implies the # inclusion of the Mbed TLS cipher operations. As we want to test here with # cipher operations solely supported by accelerators, disabled those # PSA configuration options. scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_STREAM_CIPHER scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_ECB_NO_PADDING # Don't test DES encryption as: # 1) It is not an issue if we don't test all cipher types here. # 2) That way we don't have to modify in psa_crypto.c the compilation # guards MBEDTLS_PSA_BUILTIN_KEY_TYPE_DES for the code they guard to be # available to the test driver. Modifications that we would need to # revert when we move to compile the test driver separately. # We also disable MBEDTLS_DES_C as the dependencies on DES in PSA test # suites are still based on MBEDTLS_DES_C and not PSA_WANT_KEY_TYPE_DES. scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_KEY_TYPE_DES scripts/config.py unset MBEDTLS_DES_C # Need to define the correct symbol and include the test driver header path in order to build with the test driver loc_cflags="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_KEY_TYPE_AES" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_KEY_TYPE_CAMELLIA" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_CBC_NO_PADDING" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_CBC_PKCS7" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_CTR" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_CFB" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_ECDSA" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_DETERMINISTIC_ECDSA" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_MD2" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_MD4" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_MD5" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_OFB" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_RIPEMD160" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_SIGN" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_RSA_PSS" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_SHA_1" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_SHA_224" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_SHA_256" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_SHA_384" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_SHA_512" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_XTS" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_CMAC" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_HMAC" loc_cflags="${loc_cflags} -I../tests/include -O2" make CC=gcc CFLAGS="$loc_cflags" LDFLAGS="$ASAN_CFLAGS" unset loc_cflags msg "test: full + MBEDTLS_PSA_CRYPTO_CONFIG" make test } component_test_psa_crypto_config_no_driver() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG minus MBEDTLS_PSA_CRYPTO_DRIVERS" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py unset MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO make CC=gcc CFLAGS="$ASAN_CFLAGS -O2" LDFLAGS="$ASAN_CFLAGS" msg "test: full + MBEDTLS_PSA_CRYPTO_CONFIG minus MBEDTLS_PSA_CRYPTO_DRIVERS" make test } # This should be renamed to test and updated once the accelerator ECDSA code is in place and ready to test. component_build_psa_accel_alg_ecdsa() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_ECDSA # without MBEDTLS_ECDSA_C # PSA_WANT_ALG_ECDSA and PSA_WANT_ALG_DETERMINISTIC_ECDSA are already # set in include/psa/crypto_config.h msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_ECDSA without MBEDTLS_ECDSA_C" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py unset MBEDTLS_ECDSA_C scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_ECDSA -DMBEDTLS_PSA_ACCEL_ALG_DETERMINISTIC_ECDSA -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator ECDH code is in place and ready to test. component_build_psa_accel_alg_ecdh() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_ECDH # without MBEDTLS_ECDH_C msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_ECDH without MBEDTLS_ECDH_C" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py unset MBEDTLS_ECDH_C scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_ECDH -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator ECC key pair code is in place and ready to test. component_build_psa_accel_key_type_ecc_key_pair() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_KEY_TYPE_ECC_KEY_PAIR msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_KEY_TYPE_ECC_KEY_PAIR" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_KEY_TYPE_ECC_KEY_PAIR 1 scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator ECC public key code is in place and ready to test. component_build_psa_accel_key_type_ecc_public_key() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_KEY_TYPE_ECC_KEY_PAIR # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator HMAC code is in place and ready to test. component_build_psa_accel_alg_hmac() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_HMAC msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_HMAC" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_HMAC -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator HKDF code is in place and ready to test. component_build_psa_accel_alg_hkdf() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_HKDF # without MBEDTLS_HKDF_C msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_HKDF without MBEDTLS_HKDF_C" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py unset MBEDTLS_HKDF_C # Make sure to unset TLS1_3_EXPERIMENTAL since it requires HKDF_C and will not build properly without it. scripts/config.py unset MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_HKDF -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator MD2 code is in place and ready to test. component_build_psa_accel_alg_md2() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_MD2 without other hashes msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_MD2 - other hashes" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD4 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD5 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RIPEMD160 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_224 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_256 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_384 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_512 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_MD2 -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator MD4 code is in place and ready to test. component_build_psa_accel_alg_md4() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_MD4 without other hashes msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_MD4 - other hashes" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD2 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD5 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RIPEMD160 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_224 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_256 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_384 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_512 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_MD4 -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator MD5 code is in place and ready to test. component_build_psa_accel_alg_md5() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_MD5 without other hashes msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_MD5 - other hashes" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD2 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD4 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RIPEMD160 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_224 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_256 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_384 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_512 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_MD5 -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator RIPEMD160 code is in place and ready to test. component_build_psa_accel_alg_ripemd160() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_RIPEMD160 without other hashes msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_RIPEMD160 - other hashes" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD2 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD4 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD5 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_224 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_256 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_384 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_512 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_RIPEMD160 -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator SHA1 code is in place and ready to test. component_build_psa_accel_alg_sha1() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_SHA_1 without other hashes msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_SHA_1 - other hashes" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD2 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD4 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD5 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RIPEMD160 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_224 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_256 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_384 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_512 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_SHA_1 -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator SHA224 code is in place and ready to test. component_build_psa_accel_alg_sha224() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_SHA_224 without other hashes msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_SHA_224 - other hashes" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD2 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD4 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD5 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RIPEMD160 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_384 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_512 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_SHA_224 -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator SHA256 code is in place and ready to test. component_build_psa_accel_alg_sha256() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_SHA_256 without other hashes msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_SHA_256 - other hashes" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD2 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD4 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD5 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RIPEMD160 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_224 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_384 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_512 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_SHA_256 -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator SHA384 code is in place and ready to test. component_build_psa_accel_alg_sha384() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_SHA_384 without other hashes msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_SHA_384 - other hashes" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD2 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD4 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD5 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RIPEMD160 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_224 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_256 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_SHA_384 -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator SHA512 code is in place and ready to test. component_build_psa_accel_alg_sha512() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_SHA_512 without other hashes msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_SHA_512 - other hashes" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD2 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD4 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_MD5 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RIPEMD160 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_224 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_256 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_SHA_384 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_SHA_512 -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator RSA code is in place and ready to test. component_build_psa_accel_alg_rsa_pkcs1v15_crypt() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_RSA_PKCS1V15_CRYPT msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_RSA_PKCS1V15_CRYPT + PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_ALG_RSA_PKCS1V15_CRYPT 1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_PKCS1V15_SIGN scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_OAEP scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_PSS # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_CRYPT -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator RSA code is in place and ready to test. component_build_psa_accel_alg_rsa_pkcs1v15_sign() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_RSA_PKCS1V15_SIGN and PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_RSA_PKCS1V15_SIGN + PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_ALG_RSA_PKCS1V15_SIGN 1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_PKCS1V15_CRYPT scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_OAEP scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_PSS # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_SIGN -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator RSA code is in place and ready to test. component_build_psa_accel_alg_rsa_oaep() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_RSA_OAEP and PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_RSA_OAEP + PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_ALG_RSA_OAEP 1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_PKCS1V15_CRYPT scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_PKCS1V15_SIGN scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_PSS # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_RSA_OAEP -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator RSA code is in place and ready to test. component_build_psa_accel_alg_rsa_pss() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_ALG_RSA_PSS and PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_ALG_RSA_PSS + PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_ALG_RSA_PSS 1 scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_PKCS1V15_CRYPT scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_PKCS1V15_SIGN scripts/config.py -f include/psa/crypto_config.h unset PSA_WANT_ALG_RSA_OAEP # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_ALG_RSA_PSS -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator RSA code is in place and ready to test. component_build_psa_accel_key_type_rsa_key_pair() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_KEY_TYPE_RSA_KEY_PAIR and PSA_WANT_ALG_RSA_PSS msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_KEY_TYPE_RSA_KEY_PAIR + PSA_WANT_ALG_RSA_PSS" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_ALG_RSA_PSS 1 scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_KEY_TYPE_RSA_KEY_PAIR 1 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } # This should be renamed to test and updated once the accelerator RSA code is in place and ready to test. component_build_psa_accel_key_type_rsa_public_key() { # full plus MBEDTLS_PSA_CRYPTO_CONFIG with PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY and PSA_WANT_ALG_RSA_PSS msg "build: full + MBEDTLS_PSA_CRYPTO_CONFIG + PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY + PSA_WANT_ALG_RSA_PSS" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_CONFIG scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py unset MBEDTLS_USE_PSA_CRYPTO scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_ALG_RSA_PSS 1 scripts/config.py -f include/psa/crypto_config.h set PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1 # Need to define the correct symbol and include the test driver header path in order to build with the test driver make CC=gcc CFLAGS="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST -DMBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_PUBLIC_KEY -I../tests/include -O2" LDFLAGS="$ASAN_CFLAGS" } component_test_check_params_functionality () { msg "build+test: MBEDTLS_CHECK_PARAMS functionality" scripts/config.py full # includes CHECK_PARAMS # Make MBEDTLS_PARAM_FAILED call mbedtls_param_failed(). scripts/config.py unset MBEDTLS_CHECK_PARAMS_ASSERT make CC=gcc CFLAGS='-Werror -O1' all test } component_test_check_params_without_platform () { msg "build+test: MBEDTLS_CHECK_PARAMS without MBEDTLS_PLATFORM_C" scripts/config.py full # includes CHECK_PARAMS # Keep MBEDTLS_PARAM_FAILED as assert. scripts/config.py unset MBEDTLS_PLATFORM_EXIT_ALT scripts/config.py unset MBEDTLS_PLATFORM_TIME_ALT scripts/config.py unset MBEDTLS_PLATFORM_FPRINTF_ALT scripts/config.py unset MBEDTLS_PLATFORM_MEMORY scripts/config.py unset MBEDTLS_PLATFORM_NV_SEED_ALT scripts/config.py unset MBEDTLS_PLATFORM_PRINTF_ALT scripts/config.py unset MBEDTLS_PLATFORM_SNPRINTF_ALT scripts/config.py unset MBEDTLS_ENTROPY_NV_SEED scripts/config.py unset MBEDTLS_PLATFORM_C make CC=gcc CFLAGS='-Werror -O1' all test } component_test_check_params_silent () { msg "build+test: MBEDTLS_CHECK_PARAMS with alternative MBEDTLS_PARAM_FAILED()" scripts/config.py full # includes CHECK_PARAMS # Set MBEDTLS_PARAM_FAILED to nothing. sed -i 's/.*\(#define MBEDTLS_PARAM_FAILED( cond )\).*/\1/' "$CONFIG_H" make CC=gcc CFLAGS='-Werror -O1' all test } component_test_no_platform () { # Full configuration build, without platform support, file IO and net sockets. # This should catch missing mbedtls_printf definitions, and by disabling file # IO, it should catch missing '#include <stdio.h>' msg "build: full config except platform/fsio/net, make, gcc, C99" # ~ 30s scripts/config.py full scripts/config.py unset MBEDTLS_PLATFORM_C scripts/config.py unset MBEDTLS_NET_C scripts/config.py unset MBEDTLS_PLATFORM_MEMORY scripts/config.py unset MBEDTLS_PLATFORM_PRINTF_ALT scripts/config.py unset MBEDTLS_PLATFORM_FPRINTF_ALT scripts/config.py unset MBEDTLS_PLATFORM_SNPRINTF_ALT scripts/config.py unset MBEDTLS_PLATFORM_TIME_ALT scripts/config.py unset MBEDTLS_PLATFORM_EXIT_ALT scripts/config.py unset MBEDTLS_PLATFORM_NV_SEED_ALT scripts/config.py unset MBEDTLS_ENTROPY_NV_SEED scripts/config.py unset MBEDTLS_FS_IO scripts/config.py unset MBEDTLS_PSA_CRYPTO_SE_C scripts/config.py unset MBEDTLS_PSA_CRYPTO_STORAGE_C scripts/config.py unset MBEDTLS_PSA_ITS_FILE_C # Note, _DEFAULT_SOURCE needs to be defined for platforms using glibc version >2.19, # to re-enable platform integration features otherwise disabled in C99 builds make CC=gcc CFLAGS='-Werror -Wall -Wextra -std=c99 -pedantic -Os -D_DEFAULT_SOURCE' lib programs make CC=gcc CFLAGS='-Werror -Wall -Wextra -Os' test } component_build_no_std_function () { # catch compile bugs in _uninit functions msg "build: full config with NO_STD_FUNCTION, make, gcc" # ~ 30s scripts/config.py full scripts/config.py set MBEDTLS_PLATFORM_NO_STD_FUNCTIONS scripts/config.py unset MBEDTLS_ENTROPY_NV_SEED scripts/config.py unset MBEDTLS_PLATFORM_NV_SEED_ALT make CC=gcc CFLAGS='-Werror -Wall -Wextra -Os' } component_build_no_ssl_srv () { msg "build: full config except ssl_srv.c, make, gcc" # ~ 30s scripts/config.py full scripts/config.py unset MBEDTLS_SSL_SRV_C make CC=gcc CFLAGS='-Werror -Wall -Wextra -O1' } component_build_no_ssl_cli () { msg "build: full config except ssl_cli.c, make, gcc" # ~ 30s scripts/config.py full scripts/config.py unset MBEDTLS_SSL_CLI_C make CC=gcc CFLAGS='-Werror -Wall -Wextra -O1' } component_build_no_sockets () { # Note, C99 compliance can also be tested with the sockets support disabled, # as that requires a POSIX platform (which isn't the same as C99). msg "build: full config except net_sockets.c, make, gcc -std=c99 -pedantic" # ~ 30s scripts/config.py full scripts/config.py unset MBEDTLS_NET_C # getaddrinfo() undeclared, etc. scripts/config.py set MBEDTLS_NO_PLATFORM_ENTROPY # uses syscall() on GNU/Linux make CC=gcc CFLAGS='-Werror -Wall -Wextra -O1 -std=c99 -pedantic' lib } component_test_memory_buffer_allocator_backtrace () { msg "build: default config with memory buffer allocator and backtrace enabled" scripts/config.py set MBEDTLS_MEMORY_BUFFER_ALLOC_C scripts/config.py set MBEDTLS_PLATFORM_MEMORY scripts/config.py set MBEDTLS_MEMORY_BACKTRACE scripts/config.py set MBEDTLS_MEMORY_DEBUG CC=gcc cmake . make msg "test: MBEDTLS_MEMORY_BUFFER_ALLOC_C and MBEDTLS_MEMORY_BACKTRACE" make test } component_test_memory_buffer_allocator () { msg "build: default config with memory buffer allocator" scripts/config.py set MBEDTLS_MEMORY_BUFFER_ALLOC_C scripts/config.py set MBEDTLS_PLATFORM_MEMORY CC=gcc cmake . make msg "test: MBEDTLS_MEMORY_BUFFER_ALLOC_C" make test msg "test: ssl-opt.sh, MBEDTLS_MEMORY_BUFFER_ALLOC_C" # MBEDTLS_MEMORY_BUFFER_ALLOC is slow. Skip tests that tend to time out. if_build_succeeded tests/ssl-opt.sh -e '^DTLS proxy' } component_test_no_max_fragment_length () { # Run max fragment length tests with MFL disabled msg "build: default config except MFL extension (ASan build)" # ~ 30s scripts/config.py unset MBEDTLS_SSL_MAX_FRAGMENT_LENGTH CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: ssl-opt.sh, MFL-related tests" if_build_succeeded tests/ssl-opt.sh -f "Max fragment length" } component_test_asan_remove_peer_certificate () { msg "build: default config with MBEDTLS_SSL_KEEP_PEER_CERTIFICATE disabled (ASan build)" scripts/config.py unset MBEDTLS_SSL_KEEP_PEER_CERTIFICATE CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE" make test msg "test: ssl-opt.sh, !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE" if_build_succeeded tests/ssl-opt.sh msg "test: compat.sh, !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE" if_build_succeeded tests/compat.sh msg "test: context-info.sh, !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE" if_build_succeeded tests/context-info.sh } component_test_no_max_fragment_length_small_ssl_out_content_len () { msg "build: no MFL extension, small SSL_OUT_CONTENT_LEN (ASan build)" scripts/config.py unset MBEDTLS_SSL_MAX_FRAGMENT_LENGTH scripts/config.py set MBEDTLS_SSL_IN_CONTENT_LEN 16384 scripts/config.py set MBEDTLS_SSL_OUT_CONTENT_LEN 4096 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: MFL tests (disabled MFL extension case) & large packet tests" if_build_succeeded tests/ssl-opt.sh -f "Max fragment length\|Large buffer" msg "test: context-info.sh (disabled MFL extension case)" if_build_succeeded tests/context-info.sh } component_test_variable_ssl_in_out_buffer_len () { msg "build: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH enabled (ASan build)" scripts/config.py set MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH enabled" make test msg "test: ssl-opt.sh, MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH enabled" if_build_succeeded tests/ssl-opt.sh msg "test: compat.sh, MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH enabled" if_build_succeeded tests/compat.sh } component_test_variable_ssl_in_out_buffer_len_CID () { msg "build: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH and MBEDTLS_SSL_DTLS_CONNECTION_ID enabled (ASan build)" scripts/config.py set MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH scripts/config.py set MBEDTLS_SSL_DTLS_CONNECTION_ID CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH and MBEDTLS_SSL_DTLS_CONNECTION_ID" make test msg "test: ssl-opt.sh, MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH and MBEDTLS_SSL_DTLS_CONNECTION_ID enabled" if_build_succeeded tests/ssl-opt.sh msg "test: compat.sh, MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH and MBEDTLS_SSL_DTLS_CONNECTION_ID enabled" if_build_succeeded tests/compat.sh } component_test_variable_ssl_in_out_buffer_len_record_splitting () { msg "build: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH and MBEDTLS_SSL_CBC_RECORD_SPLITTING enabled (ASan build)" scripts/config.py set MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH scripts/config.py set MBEDTLS_SSL_CBC_RECORD_SPLITTING CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH and MBEDTLS_SSL_CBC_RECORD_SPLITTING" make test msg "test: ssl-opt.sh, MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH and MBEDTLS_SSL_CBC_RECORD_SPLITTING enabled" if_build_succeeded tests/ssl-opt.sh msg "test: compat.sh, MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH and MBEDTLS_SSL_CBC_RECORD_SPLITTING enabled" if_build_succeeded tests/compat.sh } component_test_ssl_alloc_buffer_and_mfl () { msg "build: default config with memory buffer allocator and MFL extension" scripts/config.py set MBEDTLS_MEMORY_BUFFER_ALLOC_C scripts/config.py set MBEDTLS_PLATFORM_MEMORY scripts/config.py set MBEDTLS_MEMORY_DEBUG scripts/config.py set MBEDTLS_SSL_MAX_FRAGMENT_LENGTH scripts/config.py set MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH CC=gcc cmake . make msg "test: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH, MBEDTLS_MEMORY_BUFFER_ALLOC_C, MBEDTLS_MEMORY_DEBUG and MBEDTLS_SSL_MAX_FRAGMENT_LENGTH" make test msg "test: MBEDTLS_SSL_VARIABLE_BUFFER_LENGTH, MBEDTLS_MEMORY_BUFFER_ALLOC_C, MBEDTLS_MEMORY_DEBUG and MBEDTLS_SSL_MAX_FRAGMENT_LENGTH" if_build_succeeded tests/ssl-opt.sh -f "Handshake memory usage" } component_test_when_no_ciphersuites_have_mac () { msg "build: when no ciphersuites have MAC" scripts/config.py unset MBEDTLS_CIPHER_NULL_CIPHER scripts/config.py unset MBEDTLS_ARC4_C scripts/config.py unset MBEDTLS_CIPHER_MODE_CBC make msg "test: !MBEDTLS_SSL_SOME_MODES_USE_MAC" make test msg "test ssl-opt.sh: !MBEDTLS_SSL_SOME_MODES_USE_MAC" if_build_succeeded tests/ssl-opt.sh -f 'Default\|EtM' -e 'without EtM' } component_test_null_entropy () { msg "build: default config with MBEDTLS_TEST_NULL_ENTROPY (ASan build)" scripts/config.py set MBEDTLS_TEST_NULL_ENTROPY scripts/config.py set MBEDTLS_NO_DEFAULT_ENTROPY_SOURCES scripts/config.py set MBEDTLS_ENTROPY_C scripts/config.py unset MBEDTLS_ENTROPY_NV_SEED scripts/config.py unset MBEDTLS_PLATFORM_NV_SEED_ALT scripts/config.py unset MBEDTLS_ENTROPY_HARDWARE_ALT scripts/config.py unset MBEDTLS_HAVEGE_C CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan -D UNSAFE_BUILD=ON . make msg "test: MBEDTLS_TEST_NULL_ENTROPY - main suites (inc. selftests) (ASan build)" make test } component_test_no_date_time () { msg "build: default config without MBEDTLS_HAVE_TIME_DATE" scripts/config.py unset MBEDTLS_HAVE_TIME_DATE CC=gcc cmake make msg "test: !MBEDTLS_HAVE_TIME_DATE - main suites" make test } component_test_platform_calloc_macro () { msg "build: MBEDTLS_PLATFORM_{CALLOC/FREE}_MACRO enabled (ASan build)" scripts/config.py set MBEDTLS_PLATFORM_MEMORY scripts/config.py set MBEDTLS_PLATFORM_CALLOC_MACRO calloc scripts/config.py set MBEDTLS_PLATFORM_FREE_MACRO free CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: MBEDTLS_PLATFORM_{CALLOC/FREE}_MACRO enabled (ASan build)" make test } component_test_malloc_0_null () { msg "build: malloc(0) returns NULL (ASan+UBSan build)" scripts/config.py full make CC=gcc CFLAGS="'-DMBEDTLS_CONFIG_FILE=\"$PWD/tests/configs/config-wrapper-malloc-0-null.h\"' $ASAN_CFLAGS -O" LDFLAGS="$ASAN_CFLAGS" msg "test: malloc(0) returns NULL (ASan+UBSan build)" make test msg "selftest: malloc(0) returns NULL (ASan+UBSan build)" # Just the calloc selftest. "make test" ran the others as part of the # test suites. if_build_succeeded programs/test/selftest calloc msg "test ssl-opt.sh: malloc(0) returns NULL (ASan+UBSan build)" # Run a subset of the tests. The choice is a balance between coverage # and time (including time indirectly wasted due to flaky tests). # The current choice is to skip tests whose description includes # "proxy", which is an approximation of skipping tests that use the # UDP proxy, which tend to be slower and flakier. if_build_succeeded tests/ssl-opt.sh -e 'proxy' } component_test_aes_fewer_tables () { msg "build: default config with AES_FEWER_TABLES enabled" scripts/config.py set MBEDTLS_AES_FEWER_TABLES make CC=gcc CFLAGS='-Werror -Wall -Wextra' msg "test: AES_FEWER_TABLES" make test } component_test_aes_rom_tables () { msg "build: default config with AES_ROM_TABLES enabled" scripts/config.py set MBEDTLS_AES_ROM_TABLES make CC=gcc CFLAGS='-Werror -Wall -Wextra' msg "test: AES_ROM_TABLES" make test } component_test_aes_fewer_tables_and_rom_tables () { msg "build: default config with AES_ROM_TABLES and AES_FEWER_TABLES enabled" scripts/config.py set MBEDTLS_AES_FEWER_TABLES scripts/config.py set MBEDTLS_AES_ROM_TABLES make CC=gcc CFLAGS='-Werror -Wall -Wextra' msg "test: AES_FEWER_TABLES + AES_ROM_TABLES" make test } component_test_ctr_drbg_aes_256_sha_256 () { msg "build: full + MBEDTLS_ENTROPY_FORCE_SHA256 (ASan build)" scripts/config.py full scripts/config.py unset MBEDTLS_MEMORY_BUFFER_ALLOC_C scripts/config.py set MBEDTLS_ENTROPY_FORCE_SHA256 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: full + MBEDTLS_ENTROPY_FORCE_SHA256 (ASan build)" make test } component_test_ctr_drbg_aes_128_sha_512 () { msg "build: full + MBEDTLS_CTR_DRBG_USE_128_BIT_KEY (ASan build)" scripts/config.py full scripts/config.py unset MBEDTLS_MEMORY_BUFFER_ALLOC_C scripts/config.py set MBEDTLS_CTR_DRBG_USE_128_BIT_KEY CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: full + MBEDTLS_CTR_DRBG_USE_128_BIT_KEY (ASan build)" make test } component_test_ctr_drbg_aes_128_sha_256 () { msg "build: full + MBEDTLS_CTR_DRBG_USE_128_BIT_KEY + MBEDTLS_ENTROPY_FORCE_SHA256 (ASan build)" scripts/config.py full scripts/config.py unset MBEDTLS_MEMORY_BUFFER_ALLOC_C scripts/config.py set MBEDTLS_CTR_DRBG_USE_128_BIT_KEY scripts/config.py set MBEDTLS_ENTROPY_FORCE_SHA256 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: full + MBEDTLS_CTR_DRBG_USE_128_BIT_KEY + MBEDTLS_ENTROPY_FORCE_SHA256 (ASan build)" make test } component_test_se_default () { msg "build: default config + MBEDTLS_PSA_CRYPTO_SE_C" scripts/config.py set MBEDTLS_PSA_CRYPTO_SE_C make CC=clang CFLAGS="$ASAN_CFLAGS -Os" LDFLAGS="$ASAN_CFLAGS" msg "test: default config + MBEDTLS_PSA_CRYPTO_SE_C" make test } component_test_psa_crypto_drivers () { msg "build: MBEDTLS_PSA_CRYPTO_DRIVERS w/ driver hooks" scripts/config.py full scripts/config.py set MBEDTLS_PSA_CRYPTO_DRIVERS scripts/config.py set MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS # Need to define the correct symbol and include the test driver header path in order to build with the test driver loc_cflags="$ASAN_CFLAGS -DPSA_CRYPTO_DRIVER_TEST" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_KEY_TYPE_AES" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_KEY_TYPE_CAMELLIA" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_CBC_NO_PADDING" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_CBC_PKCS7" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_CTR" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_CFB" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_ECDSA" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_DETERMINISTIC_ECDSA" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_MD2" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_MD4" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_MD5" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_OFB" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_RIPEMD160" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_SIGN" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_RSA_PSS" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_SHA_1" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_SHA_224" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_SHA_256" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_SHA_384" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_SHA_512" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_XTS" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_CMAC" loc_cflags="${loc_cflags} -DMBEDTLS_PSA_ACCEL_ALG_HMAC" loc_cflags="${loc_cflags} -I../tests/include -O2" make CC=gcc CFLAGS="${loc_cflags}" LDFLAGS="$ASAN_CFLAGS" unset loc_cflags msg "test: full + MBEDTLS_PSA_CRYPTO_DRIVERS" make test } component_test_make_shared () { msg "build/test: make shared" # ~ 40s make SHARED=1 all check ldd programs/util/strerror | grep libmbedcrypto } component_test_cmake_shared () { msg "build/test: cmake shared" # ~ 2min cmake -DUSE_SHARED_MBEDTLS_LIBRARY=On . make ldd programs/util/strerror | grep libmbedcrypto make test } test_build_opt () { info=$1 cc=$2; shift 2 for opt in "$@"; do msg "build/test: $cc $opt, $info" # ~ 30s make CC="$cc" CFLAGS="$opt -std=c99 -pedantic -Wall -Wextra -Werror" # We're confident enough in compilers to not run _all_ the tests, # but at least run the unit tests. In particular, runs with # optimizations use inline assembly whereas runs with -O0 # skip inline assembly. make test # ~30s make clean done } component_test_clang_opt () { scripts/config.py full test_build_opt 'full config' clang -O0 -Os -O2 } component_test_gcc_opt () { scripts/config.py full test_build_opt 'full config' gcc -O0 -Os -O2 } component_build_mbedtls_config_file () { msg "build: make with MBEDTLS_CONFIG_FILE" # ~40s # Use the full config so as to catch a maximum of places where # the check of MBEDTLS_CONFIG_FILE might be missing. scripts/config.py full sed 's!"check_config.h"!"mbedtls/check_config.h"!' <"$CONFIG_H" >full_config.h echo '#error "MBEDTLS_CONFIG_FILE is not working"' >"$CONFIG_H" make CFLAGS="-I '$PWD' -DMBEDTLS_CONFIG_FILE='\"full_config.h\"'" rm -f full_config.h } component_test_m32_o0 () { # Build once with -O0, to compile out the i386 specific inline assembly msg "build: i386, make, gcc -O0 (ASan build)" # ~ 30s scripts/config.py full make CC=gcc CFLAGS="$ASAN_CFLAGS -m32 -O0" LDFLAGS="-m32 $ASAN_CFLAGS" msg "test: i386, make, gcc -O0 (ASan build)" make test } support_test_m32_o0 () { case $(uname -m) in *64*) true;; *) false;; esac } component_test_m32_o1 () { # Build again with -O1, to compile in the i386 specific inline assembly msg "build: i386, make, gcc -O1 (ASan build)" # ~ 30s scripts/config.py full make CC=gcc CFLAGS="$ASAN_CFLAGS -m32 -O1" LDFLAGS="-m32 $ASAN_CFLAGS" msg "test: i386, make, gcc -O1 (ASan build)" make test msg "test ssl-opt.sh, i386, make, gcc-O1" if_build_succeeded tests/ssl-opt.sh } support_test_m32_o1 () { support_test_m32_o0 "$@" } component_test_m32_everest () { msg "build: i386, Everest ECDH context (ASan build)" # ~ 6 min scripts/config.py unset MBEDTLS_ECDH_LEGACY_CONTEXT scripts/config.py set MBEDTLS_ECDH_VARIANT_EVEREST_ENABLED make CC=gcc CFLAGS="$ASAN_CFLAGS -m32 -O2" LDFLAGS="-m32 $ASAN_CFLAGS" msg "test: i386, Everest ECDH context - main suites (inc. selftests) (ASan build)" # ~ 50s make test msg "test: i386, Everest ECDH context - ECDH-related part of ssl-opt.sh (ASan build)" # ~ 5s if_build_succeeded tests/ssl-opt.sh -f ECDH msg "test: i386, Everest ECDH context - compat.sh with some ECDH ciphersuites (ASan build)" # ~ 3 min # Exclude some symmetric ciphers that are redundant here to gain time. if_build_succeeded tests/compat.sh -f ECDH -V NO -e 'ARCFOUR\|ARIA\|CAMELLIA\|CHACHA\|DES\|RC4' } support_test_m32_everest () { support_test_m32_o0 "$@" } component_test_mx32 () { msg "build: 64-bit ILP32, make, gcc" # ~ 30s scripts/config.py full make CC=gcc CFLAGS='-Werror -Wall -Wextra -mx32' LDFLAGS='-mx32' msg "test: 64-bit ILP32, make, gcc" make test } support_test_mx32 () { case $(uname -m) in amd64|x86_64) true;; *) false;; esac } component_test_min_mpi_window_size () { msg "build: Default + MBEDTLS_MPI_WINDOW_SIZE=1 (ASan build)" # ~ 10s scripts/config.py set MBEDTLS_MPI_WINDOW_SIZE 1 CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: MBEDTLS_MPI_WINDOW_SIZE=1 - main suites (inc. selftests) (ASan build)" # ~ 10s make test } component_test_have_int32 () { msg "build: gcc, force 32-bit bignum limbs" scripts/config.py unset MBEDTLS_HAVE_ASM scripts/config.py unset MBEDTLS_AESNI_C scripts/config.py unset MBEDTLS_PADLOCK_C make CC=gcc CFLAGS='-Werror -Wall -Wextra -DMBEDTLS_HAVE_INT32' msg "test: gcc, force 32-bit bignum limbs" make test } component_test_have_int64 () { msg "build: gcc, force 64-bit bignum limbs" scripts/config.py unset MBEDTLS_HAVE_ASM scripts/config.py unset MBEDTLS_AESNI_C scripts/config.py unset MBEDTLS_PADLOCK_C make CC=gcc CFLAGS='-Werror -Wall -Wextra -DMBEDTLS_HAVE_INT64' msg "test: gcc, force 64-bit bignum limbs" make test } component_test_no_udbl_division () { msg "build: MBEDTLS_NO_UDBL_DIVISION native" # ~ 10s scripts/config.py full scripts/config.py set MBEDTLS_NO_UDBL_DIVISION make CFLAGS='-Werror -O1' msg "test: MBEDTLS_NO_UDBL_DIVISION native" # ~ 10s make test } component_test_no_64bit_multiplication () { msg "build: MBEDTLS_NO_64BIT_MULTIPLICATION native" # ~ 10s scripts/config.py full scripts/config.py set MBEDTLS_NO_64BIT_MULTIPLICATION make CFLAGS='-Werror -O1' msg "test: MBEDTLS_NO_64BIT_MULTIPLICATION native" # ~ 10s make test } component_test_no_strings () { msg "build: no strings" # ~10s scripts/config.py full # Disable options that activate a large amount of string constants. scripts/config.py unset MBEDTLS_DEBUG_C scripts/config.py unset MBEDTLS_ERROR_C scripts/config.py set MBEDTLS_ERROR_STRERROR_DUMMY scripts/config.py unset MBEDTLS_VERSION_FEATURES make CFLAGS='-Werror -Os' msg "test: no strings" # ~ 10s make test } component_build_arm_none_eabi_gcc () { msg "build: ${ARM_NONE_EABI_GCC_PREFIX}gcc -O1" # ~ 10s scripts/config.py baremetal make CC="${ARM_NONE_EABI_GCC_PREFIX}gcc" AR="${ARM_NONE_EABI_GCC_PREFIX}ar" LD="${ARM_NONE_EABI_GCC_PREFIX}ld" CFLAGS='-std=c99 -Werror -Wall -Wextra -O1' lib msg "size: ${ARM_NONE_EABI_GCC_PREFIX}gcc -O1" ${ARM_NONE_EABI_GCC_PREFIX}size library/*.o } component_build_arm_none_eabi_gcc_arm5vte () { msg "build: ${ARM_NONE_EABI_GCC_PREFIX}gcc -march=arm5vte" # ~ 10s scripts/config.py baremetal # Build for a target platform that's close to what Debian uses # for its "armel" distribution (https://wiki.debian.org/ArmEabiPort). # See https://github.com/ARMmbed/mbedtls/pull/2169 and comments. # It would be better to build with arm-linux-gnueabi-gcc but # we don't have that on our CI at this time. make CC="${ARM_NONE_EABI_GCC_PREFIX}gcc" AR="${ARM_NONE_EABI_GCC_PREFIX}ar" CFLAGS='-std=c99 -Werror -Wall -Wextra -march=armv5te -O1' LDFLAGS='-march=armv5te' SHELL='sh -x' lib msg "size: ${ARM_NONE_EABI_GCC_PREFIX}gcc -march=armv5te -O1" ${ARM_NONE_EABI_GCC_PREFIX}size library/*.o } component_build_arm_none_eabi_gcc_m0plus () { msg "build: ${ARM_NONE_EABI_GCC_PREFIX}gcc -mthumb -mcpu=cortex-m0plus" # ~ 10s scripts/config.py baremetal make CC="${ARM_NONE_EABI_GCC_PREFIX}gcc" AR="${ARM_NONE_EABI_GCC_PREFIX}ar" LD="${ARM_NONE_EABI_GCC_PREFIX}ld" CFLAGS='-std=c99 -Werror -Wall -Wextra -mthumb -mcpu=cortex-m0plus -Os' lib msg "size: ${ARM_NONE_EABI_GCC_PREFIX}gcc -mthumb -mcpu=cortex-m0plus -Os" ${ARM_NONE_EABI_GCC_PREFIX}size library/*.o } component_build_arm_none_eabi_gcc_no_udbl_division () { msg "build: ${ARM_NONE_EABI_GCC_PREFIX}gcc -DMBEDTLS_NO_UDBL_DIVISION, make" # ~ 10s scripts/config.py baremetal scripts/config.py set MBEDTLS_NO_UDBL_DIVISION make CC="${ARM_NONE_EABI_GCC_PREFIX}gcc" AR="${ARM_NONE_EABI_GCC_PREFIX}ar" LD="${ARM_NONE_EABI_GCC_PREFIX}ld" CFLAGS='-std=c99 -Werror -Wall -Wextra' lib echo "Checking that software 64-bit division is not required" if_build_succeeded not grep __aeabi_uldiv library/*.o } component_build_arm_none_eabi_gcc_no_64bit_multiplication () { msg "build: ${ARM_NONE_EABI_GCC_PREFIX}gcc MBEDTLS_NO_64BIT_MULTIPLICATION, make" # ~ 10s scripts/config.py baremetal scripts/config.py set MBEDTLS_NO_64BIT_MULTIPLICATION make CC="${ARM_NONE_EABI_GCC_PREFIX}gcc" AR="${ARM_NONE_EABI_GCC_PREFIX}ar" LD="${ARM_NONE_EABI_GCC_PREFIX}ld" CFLAGS='-std=c99 -Werror -O1 -march=armv6-m -mthumb' lib echo "Checking that software 64-bit multiplication is not required" if_build_succeeded not grep __aeabi_lmul library/*.o } component_build_armcc () { msg "build: ARM Compiler 5" scripts/config.py baremetal make CC="$ARMC5_CC" AR="$ARMC5_AR" WARNING_CFLAGS='--strict --c99' lib msg "size: ARM Compiler 5" "$ARMC5_FROMELF" -z library/*.o make clean # ARM Compiler 6 - Target ARMv7-A armc6_build_test "--target=arm-arm-none-eabi -march=armv7-a" # ARM Compiler 6 - Target ARMv7-M armc6_build_test "--target=arm-arm-none-eabi -march=armv7-m" # ARM Compiler 6 - Target ARMv8-A - AArch32 armc6_build_test "--target=arm-arm-none-eabi -march=armv8.2-a" # ARM Compiler 6 - Target ARMv8-M armc6_build_test "--target=arm-arm-none-eabi -march=armv8-m.main" # ARM Compiler 6 - Target ARMv8-A - AArch64 armc6_build_test "--target=aarch64-arm-none-eabi -march=armv8.2-a" } component_build_ssl_hw_record_accel() { msg "build: default config with MBEDTLS_SSL_HW_RECORD_ACCEL enabled" scripts/config.pl set MBEDTLS_SSL_HW_RECORD_ACCEL make CFLAGS='-Werror -O1' } component_test_allow_sha1 () { msg "build: allow SHA1 in certificates by default" scripts/config.py set MBEDTLS_TLS_DEFAULT_ALLOW_SHA1_IN_CERTIFICATES make CFLAGS='-Werror -Wall -Wextra' msg "test: allow SHA1 in certificates by default" make test if_build_succeeded tests/ssl-opt.sh -f SHA-1 } component_test_tls13_experimental () { msg "build: default config with MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL enabled" scripts/config.pl set MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL CC=gcc cmake -D CMAKE_BUILD_TYPE:String=Asan . make msg "test: default config with MBEDTLS_SSL_PROTO_TLS1_3_EXPERIMENTAL enabled" make test } component_build_mingw () { msg "build: Windows cross build - mingw64, make (Link Library)" # ~ 30s make CC=i686-w64-mingw32-gcc AR=i686-w64-mingw32-ar LD=i686-w64-minggw32-ld CFLAGS='-Werror -Wall -Wextra' WINDOWS_BUILD=1 lib programs # note Make tests only builds the tests, but doesn't run them make CC=i686-w64-mingw32-gcc AR=i686-w64-mingw32-ar LD=i686-w64-minggw32-ld CFLAGS='-Werror' WINDOWS_BUILD=1 tests make WINDOWS_BUILD=1 clean msg "build: Windows cross build - mingw64, make (DLL)" # ~ 30s make CC=i686-w64-mingw32-gcc AR=i686-w64-mingw32-ar LD=i686-w64-minggw32-ld CFLAGS='-Werror -Wall -Wextra' WINDOWS_BUILD=1 SHARED=1 lib programs make CC=i686-w64-mingw32-gcc AR=i686-w64-mingw32-ar LD=i686-w64-minggw32-ld CFLAGS='-Werror -Wall -Wextra' WINDOWS_BUILD=1 SHARED=1 tests make WINDOWS_BUILD=1 clean } support_build_mingw() { case $(i686-w64-mingw32-gcc -dumpversion) in [0-5]*) false;; *) true;; esac } component_test_memsan () { msg "build: MSan (clang)" # ~ 1 min 20s scripts/config.py unset MBEDTLS_AESNI_C # memsan doesn't grok asm CC=clang cmake -D CMAKE_BUILD_TYPE:String=MemSan . make msg "test: main suites (MSan)" # ~ 10s make test msg "test: ssl-opt.sh (MSan)" # ~ 1 min if_build_succeeded tests/ssl-opt.sh # Optional part(s) if [ "$MEMORY" -gt 0 ]; then msg "test: compat.sh (MSan)" # ~ 6 min 20s if_build_succeeded tests/compat.sh fi } component_test_valgrind () { msg "build: Release (clang)" CC=clang cmake -D CMAKE_BUILD_TYPE:String=Release . make msg "test: main suites valgrind (Release)" make memcheck # Optional parts (slow; currently broken on OS X because programs don't # seem to receive signals under valgrind on OS X). if [ "$MEMORY" -gt 0 ]; then msg "test: ssl-opt.sh --memcheck (Release)" if_build_succeeded tests/ssl-opt.sh --memcheck fi if [ "$MEMORY" -gt 1 ]; then msg "test: compat.sh --memcheck (Release)" if_build_succeeded tests/compat.sh --memcheck fi if [ "$MEMORY" -gt 0 ]; then msg "test: context-info.sh --memcheck (Release)" if_build_succeeded tests/context-info.sh --memcheck fi } component_test_cmake_out_of_source () { msg "build: cmake 'out-of-source' build" MBEDTLS_ROOT_DIR="$PWD" mkdir "$OUT_OF_SOURCE_DIR" cd "$OUT_OF_SOURCE_DIR" cmake "$MBEDTLS_ROOT_DIR" make msg "test: cmake 'out-of-source' build" make test # Test an SSL option that requires an auxiliary script in test/scripts/. # Also ensure that there are no error messages such as # "No such file or directory", which would indicate that some required # file is missing (ssl-opt.sh tolerates the absence of some files so # may exit with status 0 but emit errors). if_build_succeeded ./tests/ssl-opt.sh -f 'Fallback SCSV: beginning of list' 2>ssl-opt.err if [ -s ssl-opt.err ]; then cat ssl-opt.err >&2 record_status [ ! -s ssl-opt.err ] rm ssl-opt.err fi cd "$MBEDTLS_ROOT_DIR" rm -rf "$OUT_OF_SOURCE_DIR" unset MBEDTLS_ROOT_DIR } component_test_cmake_as_subdirectory () { msg "build: cmake 'as-subdirectory' build" MBEDTLS_ROOT_DIR="$PWD" cd programs/test/cmake_subproject cmake . make if_build_succeeded ./cmake_subproject cd "$MBEDTLS_ROOT_DIR" unset MBEDTLS_ROOT_DIR } component_test_zeroize () { # Test that the function mbedtls_platform_zeroize() is not optimized away by # different combinations of compilers and optimization flags by using an # auxiliary GDB script. Unfortunately, GDB does not return error values to the # system in all cases that the script fails, so we must manually search the # output to check whether the pass string is present and no failure strings # were printed. # Don't try to disable ASLR. We don't care about ASLR here. We do care # about a spurious message if Gdb tries and fails, so suppress that. gdb_disable_aslr= if [ -z "$(gdb -batch -nw -ex 'set disable-randomization off' 2>&1)" ]; then gdb_disable_aslr='set disable-randomization off' fi for optimization_flag in -O2 -O3 -Ofast -Os; do for compiler in clang gcc; do msg "test: $compiler $optimization_flag, mbedtls_platform_zeroize()" make programs CC="$compiler" DEBUG=1 CFLAGS="$optimization_flag" if_build_succeeded gdb -ex "$gdb_disable_aslr" -x tests/scripts/test_zeroize.gdb -nw -batch -nx 2>&1 | tee test_zeroize.log if_build_succeeded grep "The buffer was correctly zeroized" test_zeroize.log if_build_succeeded not grep -i "error" test_zeroize.log rm -f test_zeroize.log make clean done done unset gdb_disable_aslr } component_check_python_files () { msg "Lint: Python scripts" record_status tests/scripts/check-python-files.sh } component_check_generate_test_code () { msg "uint test: generate_test_code.py" # unittest writes out mundane stuff like number or tests run on stderr. # Our convention is to reserve stderr for actual errors, and write # harmless info on stdout so it can be suppress with --quiet. record_status ./tests/scripts/test_generate_test_code.py 2>&1 } ################################################################ #### Termination ################################################################ post_report () { msg "Done, cleaning up" cleanup final_report } ################################################################ #### Run all the things ################################################################ # Run one component and clean up afterwards. run_component () { # Back up the configuration in case the component modifies it. # The cleanup function will restore it. cp -p "$CONFIG_H" "$CONFIG_BAK" cp -p "$CRYPTO_CONFIG_H" "$CRYPTO_CONFIG_BAK" current_component="$1" export MBEDTLS_TEST_CONFIGURATION="$current_component" # Unconditionally create a seedfile that's sufficiently long. # Do this before each component, because a previous component may # have messed it up or shortened it. redirect_err dd if=/dev/urandom of=./tests/seedfile bs=64 count=1 # Run the component code. if [ $QUIET -eq 1 ]; then # msg() is silenced, so just print the component name here echo "${current_component#component_}" fi redirect_out "$@" # Restore the build tree to a clean state. cleanup unset current_component } # Preliminary setup pre_check_environment pre_initialize_variables pre_parse_command_line "$@" pre_check_git build_status=0 if [ $KEEP_GOING -eq 1 ]; then pre_setup_keep_going else record_status () { "$@" } fi pre_setup_quiet_redirect pre_prepare_outcome_file pre_print_configuration pre_check_tools cleanup # Run the requested tests. for component in $RUN_COMPONENTS; do run_component "component_$component" done # We're done. post_report
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/gen_gcm_decrypt.pl
#!/usr/bin/env perl # # Based on NIST gcmDecryptxxx.rsp validation files # Only first 3 of every set used for compile time saving # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use strict; my $file = shift; open(TEST_DATA, "$file") or die "Opening test cases '$file': $!"; sub get_suite_val($) { my $name = shift; my $val = ""; while(my $line = <TEST_DATA>) { next if ($line !~ /^\[/); ($val) = ($line =~ /\[$name\s\=\s(\w+)\]/); last; } return $val; } sub get_val($) { my $name = shift; my $val = ""; my $line; while($line = <TEST_DATA>) { next if($line !~ /=/); last; } ($val) = ($line =~ /^$name = (\w+)/); return $val; } sub get_val_or_fail($) { my $name = shift; my $val = "FAIL"; my $line; while($line = <TEST_DATA>) { next if($line !~ /=/ && $line !~ /FAIL/); last; } ($val) = ($line =~ /^$name = (\w+)/) if ($line =~ /=/); return $val; } my $cnt = 1;; while (my $line = <TEST_DATA>) { my $key_len = get_suite_val("Keylen"); next if ($key_len !~ /\d+/); my $iv_len = get_suite_val("IVlen"); my $pt_len = get_suite_val("PTlen"); my $add_len = get_suite_val("AADlen"); my $tag_len = get_suite_val("Taglen"); for ($cnt = 0; $cnt < 3; $cnt++) { my $Count = get_val("Count"); my $key = get_val("Key"); my $iv = get_val("IV"); my $ct = get_val("CT"); my $add = get_val("AAD"); my $tag = get_val("Tag"); my $pt = get_val_or_fail("PT"); print("GCM NIST Validation (AES-$key_len,$iv_len,$pt_len,$add_len,$tag_len) #$Count\n"); print("gcm_decrypt_and_verify"); print(":\"$key\""); print(":\"$ct\""); print(":\"$iv\""); print(":\"$add\""); print(":$tag_len"); print(":\"$tag\""); print(":\"$pt\""); print(":0"); print("\n\n"); } } print("GCM Selftest\n"); print("gcm_selftest:\n\n"); close(TEST_DATA);
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/test-ref-configs.pl
#!/usr/bin/env perl # test-ref-configs.pl # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Purpose # # For each reference configuration file in the configs directory, build the # configuration, run the test suites and compat.sh # # Usage: tests/scripts/test-ref-configs.pl [config-name [...]] use warnings; use strict; my %configs = ( 'config-ccm-psk-tls1_2.h' => { 'compat' => '-m tls1_2 -f \'^TLS-PSK-WITH-AES-...-CCM-8\'', }, 'config-mini-tls1_1.h' => { 'compat' => '-m tls1_1 -f \'^DES-CBC3-SHA$\|^TLS-RSA-WITH-3DES-EDE-CBC-SHA$\'', #' }, 'config-no-entropy.h' => { }, 'config-suite-b.h' => { 'compat' => "-m tls1_2 -f 'ECDHE-ECDSA.*AES.*GCM' -p mbedTLS", }, 'config-symmetric-only.h' => { }, 'config-thread.h' => { 'opt' => '-f ECJPAKE.*nolog', }, ); # If no config-name is provided, use all known configs. # Otherwise, use the provided names only. if ($#ARGV >= 0) { my %configs_ori = ( %configs ); %configs = (); foreach my $conf_name (@ARGV) { if( ! exists $configs_ori{$conf_name} ) { die "Unknown configuration: $conf_name\n"; } else { $configs{$conf_name} = $configs_ori{$conf_name}; } } } -d 'library' && -d 'include' && -d 'tests' or die "Must be run from root\n"; my $config_h = 'include/mbedtls/config.h'; system( "cp $config_h $config_h.bak" ) and die; sub abort { system( "mv $config_h.bak $config_h" ) and warn "$config_h not restored\n"; # use an exit code between 1 and 124 for git bisect (die returns 255) warn $_[0]; exit 1; } # Create a seedfile for configurations that enable MBEDTLS_ENTROPY_NV_SEED. # For test purposes, this doesn't have to be cryptographically random. if (!-e "tests/seedfile" || -s "tests/seedfile" < 64) { local *SEEDFILE; open SEEDFILE, ">tests/seedfile" or die; print SEEDFILE "*" x 64 or die; close SEEDFILE or die; } while( my ($conf, $data) = each %configs ) { system( "cp $config_h.bak $config_h" ) and die; system( "make clean" ) and die; print "\n******************************************\n"; print "* Testing configuration: $conf\n"; print "******************************************\n"; $ENV{MBEDTLS_TEST_CONFIGURATION} = $conf; system( "cp configs/$conf $config_h" ) and abort "Failed to activate $conf\n"; system( "CFLAGS='-Os -Werror -Wall -Wextra' make" ) and abort "Failed to build: $conf\n"; system( "make test" ) and abort "Failed test suite: $conf\n"; my $compat = $data->{'compat'}; if( $compat ) { print "\nrunning compat.sh $compat\n"; system( "tests/compat.sh $compat" ) and abort "Failed compat.sh: $conf\n"; } else { print "\nskipping compat.sh\n"; } my $opt = $data->{'opt'}; if( $opt ) { print "\nrunning ssl-opt.sh $opt\n"; system( "tests/ssl-opt.sh $opt" ) and abort "Failed ssl-opt.sh: $conf\n"; } else { print "\nskipping ssl-opt.sh\n"; } } system( "mv $config_h.bak $config_h" ) and warn "$config_h not restored\n"; system( "make clean" ); exit 0;
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/generate-afl-tests.sh
#!/bin/sh # This script splits the data test files containing the test cases into # individual files (one test case per file) suitable for use with afl # (American Fuzzy Lop). http://lcamtuf.coredump.cx/afl/ # # Usage: generate-afl-tests.sh <test data file path> # <test data file path> - should be the path to one of the test suite files # such as 'test_suite_mpi.data' # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Abort on errors set -e if [ -z $1 ] then echo " [!] No test file specified" >&2 echo "Usage: $0 <test data file>" >&2 exit 1 fi SRC_FILEPATH=$(dirname $1)/$(basename $1) TESTSUITE=$(basename $1 .data) THIS_DIR=$(basename $PWD) if [ -d ../library -a -d ../include -a -d ../tests -a $THIS_DIR == "tests" ]; then :; else echo " [!] Must be run from mbed TLS tests directory" >&2 exit 1 fi DEST_TESTCASE_DIR=$TESTSUITE-afl-tests DEST_OUTPUT_DIR=$TESTSUITE-afl-out echo " [+] Creating output directories" >&2 if [ -e $DEST_OUTPUT_DIR/* ]; then : echo " [!] Test output files already exist." >&2 exit 1 else mkdir -p $DEST_OUTPUT_DIR fi if [ -e $DEST_TESTCASE_DIR/* ]; then : echo " [!] Test output files already exist." >&2 else mkdir -p $DEST_TESTCASE_DIR fi echo " [+] Creating test cases" >&2 cd $DEST_TESTCASE_DIR split -p '^\s*$' ../$SRC_FILEPATH for f in *; do # Strip out any blank lines (no trim on OS X) sed '/^\s*$/d' $f >testcase_$f rm $f done cd .. echo " [+] Test cases in $DEST_TESTCASE_DIR" >&2
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/check-python-files.sh
#! /usr/bin/env sh # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Purpose: check Python files for potential programming errors or maintenance # hurdles. Run pylint to detect some potential mistakes and enforce PEP8 # coding standards. If available, run mypy to perform static type checking. # We'll keep going on errors and report the status at the end. ret=0 if type python3 >/dev/null 2>/dev/null; then PYTHON=python3 else PYTHON=python fi check_version () { $PYTHON - "$2" <<EOF import packaging.version import sys import $1 as package actual = package.__version__ wanted = sys.argv[1] if packaging.version.parse(actual) < packaging.version.parse(wanted): sys.stderr.write("$1: version %s is too old (want %s)\n" % (actual, wanted)) exit(1) EOF } can_pylint () { # Pylint 1.5.2 from Ubuntu 16.04 is too old: # E: 34, 0: Unable to import 'mbedtls_dev' (import-error) # Pylint 1.8.3 from Ubuntu 18.04 passed on the first commit containing this line. check_version pylint 1.8.3 } can_mypy () { # mypy 0.770 is too old: # tests/scripts/test_psa_constant_names.py:34: error: Cannot find implementation or library stub for module named 'mbedtls_dev' # mypy 0.780 from pip passed on the first commit containing this line. check_version mypy.version 0.780 } # With just a --can-xxx option, check whether the tool for xxx is available # with an acceptable version, and exit without running any checks. The exit # status is true if the tool is available and acceptable and false otherwise. if [ "$1" = "--can-pylint" ]; then can_pylint exit elif [ "$1" = "--can-mypy" ]; then can_mypy exit fi echo 'Running pylint ...' $PYTHON -m pylint -j 2 scripts/mbedtls_dev/*.py scripts/*.py tests/scripts/*.py || { echo >&2 "pylint reported errors" ret=1 } # Check types if mypy is available if can_mypy; then echo echo 'Running mypy ...' $PYTHON -m mypy scripts/*.py tests/scripts/*.py || ret=1 fi exit $ret
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/list-symbols.sh
#!/bin/sh # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -eu if [ -d include/mbedtls ]; then :; else echo "$0: must be run from root" >&2 exit 1 fi if grep -i cmake Makefile >/dev/null; then echo "$0: not compatible with cmake" >&2 exit 1 fi cp include/mbedtls/config.h include/mbedtls/config.h.bak scripts/config.py full make clean make_ret= CFLAGS=-fno-asynchronous-unwind-tables make lib \ >list-symbols.make.log 2>&1 || { make_ret=$? echo "Build failure: CFLAGS=-fno-asynchronous-unwind-tables make lib" cat list-symbols.make.log >&2 } rm list-symbols.make.log mv include/mbedtls/config.h.bak include/mbedtls/config.h if [ -n "$make_ret" ]; then exit "$make_ret" fi if uname | grep -F Darwin >/dev/null; then nm -gUj library/libmbed*.a 2>/dev/null | sed -n -e 's/^_//p' | grep -v -e ^FStar -e ^Hacl elif uname | grep -F Linux >/dev/null; then nm -og library/libmbed*.a | grep -v '^[^ ]*: *U \|^$\|^[^ ]*:$' | sed 's/^[^ ]* . //' | grep -v -e ^FStar -e ^Hacl fi | sort > exported-symbols make clean wc -l exported-symbols
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/curves.pl
#!/usr/bin/env perl # curves.pl # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Purpose # # The purpose of this test script is to validate that the library works # with any combination of elliptic curves. To this effect, build the library # and run the test suite with each tested combination of elliptic curves. # # Testing all 2^n combinations would be too much, so we only test 2*n: # # 1. Test with a single curve, for each curve. This validates that the # library works with any curve, and in particular that curve-specific # code is guarded by the proper preprocessor conditionals. # 2. Test with all curves except one, for each curve. This validates that # the test cases have correct dependencies. Testing with a single curve # doesn't validate this for tests that require more than one curve. # Usage: tests/scripts/curves.pl # # This script should be executed from the root of the project directory. # # Only curves that are enabled in config.h will be tested. # # For best effect, run either with cmake disabled, or cmake enabled in a mode # that includes -Werror. use warnings; use strict; -d 'library' && -d 'include' && -d 'tests' or die "Must be run from root\n"; my $sed_cmd = 's/^#define \(MBEDTLS_ECP_DP.*_ENABLED\)/\1/p'; my $config_h = 'include/mbedtls/config.h'; my @curves = split( /\s+/, `sed -n -e '$sed_cmd' $config_h` ); # Determine which curves support ECDSA by checking the dependencies of # ECDSA in check_config.h. my %curve_supports_ecdsa = (); { local $/ = ""; local *CHECK_CONFIG; open(CHECK_CONFIG, '<', 'include/mbedtls/check_config.h') or die "open include/mbedtls/check_config.h: $!"; while (my $stanza = <CHECK_CONFIG>) { if ($stanza =~ /\A#if defined\(MBEDTLS_ECDSA_C\)/) { for my $curve ($stanza =~ /(?<=\()MBEDTLS_ECP_DP_\w+_ENABLED(?=\))/g) { $curve_supports_ecdsa{$curve} = 1; } last; } } close(CHECK_CONFIG); } system( "cp $config_h $config_h.bak" ) and die; sub abort { system( "mv $config_h.bak $config_h" ) and warn "$config_h not restored\n"; # use an exit code between 1 and 124 for git bisect (die returns 255) warn $_[0]; exit 1; } # Disable all the curves. We'll then re-enable them one by one. for my $curve (@curves) { system( "scripts/config.pl unset $curve" ) and abort "Failed to disable $curve\n"; } # Depends on a specific curve. Also, ignore error if it wasn't enabled. system( "scripts/config.pl unset MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED" ); # Test with only $curve enabled, for each $curve. for my $curve (@curves) { system( "make clean" ) and die; print "\n******************************************\n"; print "* Testing with only curve: $curve\n"; print "******************************************\n"; $ENV{MBEDTLS_TEST_CONFIGURATION} = "$curve"; system( "scripts/config.pl set $curve" ) and abort "Failed to enable $curve\n"; my $ecdsa = $curve_supports_ecdsa{$curve} ? "set" : "unset"; for my $dep (qw(MBEDTLS_ECDSA_C MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED)) { system( "scripts/config.pl $ecdsa $dep" ) and abort "Failed to $ecdsa $dep\n"; } system( "CFLAGS='-Werror -Wall -Wextra' make" ) and abort "Failed to build: only $curve\n"; system( "make test" ) and abort "Failed test suite: only $curve\n"; system( "scripts/config.pl unset $curve" ) and abort "Failed to disable $curve\n"; } system( "cp $config_h.bak $config_h" ) and die "$config_h not restored\n"; # Test with $curve disabled but the others enabled, for each $curve. for my $curve (@curves) { system( "cp $config_h.bak $config_h" ) and die "$config_h not restored\n"; system( "make clean" ) and die; # depends on a specific curve. Also, ignore error if it wasn't enabled system( "scripts/config.py unset MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED" ); print "\n******************************************\n"; print "* Testing without curve: $curve\n"; print "******************************************\n"; $ENV{MBEDTLS_TEST_CONFIGURATION} = "-$curve"; system( "scripts/config.py unset $curve" ) and abort "Failed to disable $curve\n"; system( "CFLAGS='-Werror -Wall -Wextra' make" ) and abort "Failed to build: all but $curve\n"; system( "make test" ) and abort "Failed test suite: all but $curve\n"; } system( "mv $config_h.bak $config_h" ) and die "$config_h not restored\n"; system( "make clean" ) and die; exit 0;
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/recursion.pl
#!/usr/bin/env perl # Find functions making recursive calls to themselves. # (Multiple recursion where a() calls b() which calls a() not covered.) # # When the recursion depth might depend on data controlled by the attacker in # an unbounded way, those functions should use interation instead. # # Typical usage: scripts/recursion.pl library/*.c # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. use warnings; use strict; use utf8; use open qw(:std utf8); # exclude functions that are ok: # - mpi_write_hlp: bounded by size of mbedtls_mpi, a compile-time constant # - x509_crt_verify_child: bounded by MBEDTLS_X509_MAX_INTERMEDIATE_CA my $known_ok = qr/mpi_write_hlp|x509_crt_verify_child/; my $cur_name; my $inside; my @funcs; die "Usage: $0 file.c [...]\n" unless @ARGV; while (<>) { if( /^[^\/#{}\s]/ && ! /\[.*]/ ) { chomp( $cur_name = $_ ) unless $inside; } elsif( /^{/ && $cur_name ) { $inside = 1; $cur_name =~ s/.* ([^ ]*)\(.*/$1/; } elsif( /^}/ && $inside ) { undef $inside; undef $cur_name; } elsif( $inside && /\b\Q$cur_name\E\([^)]/ ) { push @funcs, $cur_name unless /$known_ok/; } } print "$_\n" for @funcs; exit @funcs;
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/check-names.sh
#!/bin/sh # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. set -eu if [ $# -ne 0 ] && [ "$1" = "--help" ]; then cat <<EOF $0 [-v] This script confirms that the naming of all symbols and identifiers in mbed TLS are consistent with the house style and are also self-consistent. -v If the script fails unexpectedly, print a command trace. EOF exit fi trace= if [ $# -ne 0 ] && [ "$1" = "-v" ]; then shift trace='-x' exec 2>check-names.err trap 'echo "FAILED UNEXPECTEDLY, status=$?"; cat check-names.err' EXIT set -x fi printf "Analysing source code...\n" sh $trace tests/scripts/list-macros.sh tests/scripts/list-enum-consts.pl sh $trace tests/scripts/list-identifiers.sh sh $trace tests/scripts/list-symbols.sh FAIL=0 printf "\nExported symbols declared in header: " UNDECLARED=$( diff exported-symbols identifiers | sed -n -e 's/^< //p' ) if [ "x$UNDECLARED" = "x" ]; then echo "PASS" else echo "FAIL" echo "$UNDECLARED" FAIL=1 fi diff macros identifiers | sed -n -e 's/< //p' > actual-macros for THING in actual-macros enum-consts; do printf 'Names of %s: ' "$THING" test -r $THING BAD=$( grep -E -v '^(MBEDTLS|PSA)_[0-9A-Z_]*[0-9A-Z]$' $THING || true ) UNDERSCORES=$( grep -E '.*__.*' $THING || true ) if [ "x$BAD" = "x" ] && [ "x$UNDERSCORES" = "x" ]; then echo "PASS" else echo "FAIL" echo "$BAD" echo "$UNDERSCORES" FAIL=1 fi done for THING in identifiers; do printf 'Names of %s: ' "$THING" test -r $THING BAD=$( grep -E -v '^(mbedtls|psa)_[0-9a-z_]*[0-9a-z]$' $THING || true ) if [ "x$BAD" = "x" ]; then echo "PASS" else echo "FAIL" echo "$BAD" FAIL=1 fi done printf "Likely typos: " sort -u actual-macros enum-consts > _caps HEADERS=$( ls include/mbedtls/*.h include/psa/*.h | egrep -v 'compat-1\.3\.h' ) HEADERS="$HEADERS library/*.h" HEADERS="$HEADERS 3rdparty/everest/include/everest/everest.h 3rdparty/everest/include/everest/x25519.h" LIBRARY="$( ls library/*.c )" LIBRARY="$LIBRARY 3rdparty/everest/library/everest.c 3rdparty/everest/library/x25519.c" NL=' ' sed -n 's/MBED..._[A-Z0-9_]*/\'"$NL"'&\'"$NL"/gp \ $HEADERS $LIBRARY \ | grep MBEDTLS | sort -u > _MBEDTLS_XXX TYPOS=$( diff _caps _MBEDTLS_XXX | sed -n 's/^> //p' \ | egrep -v 'XXX|__|_$|^MBEDTLS_.*CONFIG_FILE$' || true ) rm _MBEDTLS_XXX _caps if [ "x$TYPOS" = "x" ]; then echo "PASS" else echo "FAIL" echo "$TYPOS" FAIL=1 fi if [ -n "$trace" ]; then set +x trap - EXIT rm check-names.err fi printf "\nOverall: " if [ "$FAIL" -eq 0 ]; then rm macros actual-macros enum-consts identifiers exported-symbols echo "PASSED" exit 0 else echo "FAILED" exit 1 fi
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/scripts/key-exchanges.pl
#!/usr/bin/env perl # key-exchanges.pl # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Purpose # # To test the code dependencies on individual key exchanges in the SSL module. # is a verification step to ensure we don't ship SSL code that do not work # for some build options. # # The process is: # for each possible key exchange # build the library with all but that key exchange disabled # # Usage: tests/scripts/key-exchanges.pl # # This script should be executed from the root of the project directory. # # For best effect, run either with cmake disabled, or cmake enabled in a mode # that includes -Werror. use warnings; use strict; -d 'library' && -d 'include' && -d 'tests' or die "Must be run from root\n"; my $sed_cmd = 's/^#define \(MBEDTLS_KEY_EXCHANGE_.*_ENABLED\)/\1/p'; my $config_h = 'include/mbedtls/config.h'; my @kexes = split( /\s+/, `sed -n -e '$sed_cmd' $config_h` ); system( "cp $config_h $config_h.bak" ) and die; sub abort { system( "mv $config_h.bak $config_h" ) and warn "$config_h not restored\n"; # use an exit code between 1 and 124 for git bisect (die returns 255) warn $_[0]; exit 1; } for my $kex (@kexes) { system( "cp $config_h.bak $config_h" ) and die "$config_h not restored\n"; system( "make clean" ) and die; print "\n******************************************\n"; print "* Testing with key exchange: $kex\n"; print "******************************************\n"; $ENV{MBEDTLS_TEST_CONFIGURATION} = $kex; # full config with all key exchanges disabled except one system( "scripts/config.py full" ) and abort "Failed config full\n"; for my $k (@kexes) { next if $k eq $kex; system( "scripts/config.py unset $k" ) and abort "Failed to disable $k\n"; } system( "make lib CFLAGS='-Os -Werror'" ) and abort "Failed to build lib: $kex\n"; } system( "mv $config_h.bak $config_h" ) and die "$config_h not restored\n"; system( "make clean" ) and die; exit 0;
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/git-scripts/pre-push.sh
#!/bin/sh # pre-push.sh # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # # Purpose # # Called by "git push" after it has checked the remote status, but before anything has been # pushed. If this script exits with a non-zero status nothing will be pushed. # This script can also be used independently, not using git. # # This hook is called with the following parameters: # # $1 -- Name of the remote to which the push is being done # $2 -- URL to which the push is being done # # If pushing without using a named remote those arguments will be equal. # # Information about the commits which are being pushed is supplied as lines to # the standard input in the form: # # <local ref> <local sha1> <remote ref> <remote sha1> # REMOTE="$1" URL="$2" echo "REMOTE is $REMOTE" echo "URL is $URL" set -eu tests/scripts/all.sh -q -k 'check_*'
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/git-scripts/pre-commit.sh
#!/bin/sh # pre-commit.sh # # Copyright The Mbed TLS Contributors # SPDX-License-Identifier: Apache-2.0 # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # Purpose # # This script does quick sanity checks before commiting: # - check that generated files are up-to-date. # # It is meant to be called as a git pre-commit hook, see README.md. # # From the git sample pre-commit hook: # Called by "git commit" with no arguments. The hook should # exit with non-zero status after issuing an appropriate message if # it wants to stop the commit. set -eu tests/scripts/check-generated-files.sh
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/git-scripts/README.md
README for git hooks script =========================== git has a way to run scripts, which are invoked by specific git commands. The git hooks are located in `<mbed TLS root>/.git/hooks`, and as such are not under version control for more information, see the [git documentation](https://git-scm.com/docs/githooks). The mbed TLS git hooks are located in `<mbed TLS root>/tests/git-scripts` directory, and one must create a soft link from `<mbed TLS root>/.git/hooks` to `<mbed TLS root>/tesst/git-scripts`, in order to make the hook scripts successfully work. Example: Execute the following command to create a link on linux from the mbed TLS `.git/hooks` directory: `ln -s ../../tests/git-scripts/pre-push.sh pre-push` **Note: Currently the mbed TLS git hooks work only on a GNU platform. If using a non-GNU platform, don't enable these hooks!** These scripts can also be used independently.
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/psa_exercise_key.c
/** Code to exercise a PSA key object, i.e. validate that it seems well-formed * and can do what it is supposed to do. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <test/helpers.h> #include <test/macros.h> #include <test/psa_exercise_key.h> #if defined(MBEDTLS_PSA_CRYPTO_C) #include <mbedtls/asn1.h> #include <psa/crypto.h> #include <test/asn1_helpers.h> #include <test/psa_crypto_helpers.h> #if defined(MBEDTLS_PSA_CRYPTO_SE_C) static int lifetime_is_dynamic_secure_element( psa_key_lifetime_t lifetime ) { return( PSA_KEY_LIFETIME_GET_LOCATION( lifetime ) != PSA_KEY_LOCATION_LOCAL_STORAGE ); } #endif static int check_key_attributes_sanity( mbedtls_svc_key_id_t key ) { int ok = 0; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; psa_key_lifetime_t lifetime; mbedtls_svc_key_id_t id; psa_key_type_t type; size_t bits; PSA_ASSERT( psa_get_key_attributes( key, &attributes ) ); lifetime = psa_get_key_lifetime( &attributes ); id = psa_get_key_id( &attributes ); type = psa_get_key_type( &attributes ); bits = psa_get_key_bits( &attributes ); /* Persistence */ if( PSA_KEY_LIFETIME_IS_VOLATILE( lifetime ) ) { TEST_ASSERT( ( PSA_KEY_ID_VOLATILE_MIN <= MBEDTLS_SVC_KEY_ID_GET_KEY_ID( id ) ) && ( MBEDTLS_SVC_KEY_ID_GET_KEY_ID( id ) <= PSA_KEY_ID_VOLATILE_MAX ) ); } else { TEST_ASSERT( ( PSA_KEY_ID_USER_MIN <= MBEDTLS_SVC_KEY_ID_GET_KEY_ID( id ) ) && ( MBEDTLS_SVC_KEY_ID_GET_KEY_ID( id ) <= PSA_KEY_ID_USER_MAX ) ); } #if defined(MBEDTLS_PSA_CRYPTO_SE_C) /* randomly-generated 64-bit constant, should never appear in test data */ psa_key_slot_number_t slot_number = 0xec94d4a5058a1a21; psa_status_t status = psa_get_key_slot_number( &attributes, &slot_number ); if( lifetime_is_dynamic_secure_element( lifetime ) ) { /* Mbed Crypto currently always exposes the slot number to * applications. This is not mandated by the PSA specification * and may change in future versions. */ TEST_EQUAL( status, 0 ); TEST_ASSERT( slot_number != 0xec94d4a5058a1a21 ); } else { TEST_EQUAL( status, PSA_ERROR_INVALID_ARGUMENT ); } #endif /* Type and size */ TEST_ASSERT( type != 0 ); TEST_ASSERT( bits != 0 ); TEST_ASSERT( bits <= PSA_MAX_KEY_BITS ); if( PSA_KEY_TYPE_IS_UNSTRUCTURED( type ) ) TEST_ASSERT( bits % 8 == 0 ); /* MAX macros concerning specific key types */ if( PSA_KEY_TYPE_IS_ECC( type ) ) TEST_ASSERT( bits <= PSA_VENDOR_ECC_MAX_CURVE_BITS ); else if( PSA_KEY_TYPE_IS_RSA( type ) ) TEST_ASSERT( bits <= PSA_VENDOR_RSA_MAX_KEY_BITS ); TEST_ASSERT( PSA_BLOCK_CIPHER_BLOCK_LENGTH( type ) <= PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE ); ok = 1; exit: /* * Key attributes may have been returned by psa_get_key_attributes() * thus reset them as required. */ psa_reset_key_attributes( &attributes ); return( ok ); } static int exercise_mac_key( mbedtls_svc_key_id_t key, psa_key_usage_t usage, psa_algorithm_t alg ) { psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT; const unsigned char input[] = "foo"; unsigned char mac[PSA_MAC_MAX_SIZE] = {0}; size_t mac_length = sizeof( mac ); /* Convert wildcard algorithm to exercisable algorithm */ if( alg & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) { alg = PSA_ALG_TRUNCATED_MAC( alg, PSA_MAC_TRUNCATED_LENGTH( alg ) ); } if( usage & PSA_KEY_USAGE_SIGN_HASH ) { PSA_ASSERT( psa_mac_sign_setup( &operation, key, alg ) ); PSA_ASSERT( psa_mac_update( &operation, input, sizeof( input ) ) ); PSA_ASSERT( psa_mac_sign_finish( &operation, mac, sizeof( mac ), &mac_length ) ); } if( usage & PSA_KEY_USAGE_VERIFY_HASH ) { psa_status_t verify_status = ( usage & PSA_KEY_USAGE_SIGN_HASH ? PSA_SUCCESS : PSA_ERROR_INVALID_SIGNATURE ); PSA_ASSERT( psa_mac_verify_setup( &operation, key, alg ) ); PSA_ASSERT( psa_mac_update( &operation, input, sizeof( input ) ) ); TEST_EQUAL( psa_mac_verify_finish( &operation, mac, mac_length ), verify_status ); } return( 1 ); exit: psa_mac_abort( &operation ); return( 0 ); } static int exercise_cipher_key( mbedtls_svc_key_id_t key, psa_key_usage_t usage, psa_algorithm_t alg ) { psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT; unsigned char iv[16] = {0}; size_t iv_length = sizeof( iv ); const unsigned char plaintext[16] = "Hello, world..."; unsigned char ciphertext[32] = "(wabblewebblewibblewobblewubble)"; size_t ciphertext_length = sizeof( ciphertext ); unsigned char decrypted[sizeof( ciphertext )]; size_t part_length; if( usage & PSA_KEY_USAGE_ENCRYPT ) { PSA_ASSERT( psa_cipher_encrypt_setup( &operation, key, alg ) ); PSA_ASSERT( psa_cipher_generate_iv( &operation, iv, sizeof( iv ), &iv_length ) ); PSA_ASSERT( psa_cipher_update( &operation, plaintext, sizeof( plaintext ), ciphertext, sizeof( ciphertext ), &ciphertext_length ) ); PSA_ASSERT( psa_cipher_finish( &operation, ciphertext + ciphertext_length, sizeof( ciphertext ) - ciphertext_length, &part_length ) ); ciphertext_length += part_length; } if( usage & PSA_KEY_USAGE_DECRYPT ) { psa_status_t status; int maybe_invalid_padding = 0; if( ! ( usage & PSA_KEY_USAGE_ENCRYPT ) ) { psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; PSA_ASSERT( psa_get_key_attributes( key, &attributes ) ); /* This should be PSA_CIPHER_GET_IV_SIZE but the API doesn't * have this macro yet. */ iv_length = PSA_BLOCK_CIPHER_BLOCK_LENGTH( psa_get_key_type( &attributes ) ); maybe_invalid_padding = ! PSA_ALG_IS_STREAM_CIPHER( alg ); psa_reset_key_attributes( &attributes ); } PSA_ASSERT( psa_cipher_decrypt_setup( &operation, key, alg ) ); PSA_ASSERT( psa_cipher_set_iv( &operation, iv, iv_length ) ); PSA_ASSERT( psa_cipher_update( &operation, ciphertext, ciphertext_length, decrypted, sizeof( decrypted ), &part_length ) ); status = psa_cipher_finish( &operation, decrypted + part_length, sizeof( decrypted ) - part_length, &part_length ); /* For a stream cipher, all inputs are valid. For a block cipher, * if the input is some aribtrary data rather than an actual ciphertext, a padding error is likely. */ if( maybe_invalid_padding ) TEST_ASSERT( status == PSA_SUCCESS || status == PSA_ERROR_INVALID_PADDING ); else PSA_ASSERT( status ); } return( 1 ); exit: psa_cipher_abort( &operation ); return( 0 ); } static int exercise_aead_key( mbedtls_svc_key_id_t key, psa_key_usage_t usage, psa_algorithm_t alg ) { unsigned char nonce[16] = {0}; size_t nonce_length = sizeof( nonce ); unsigned char plaintext[16] = "Hello, world..."; unsigned char ciphertext[48] = "(wabblewebblewibblewobblewubble)"; size_t ciphertext_length = sizeof( ciphertext ); size_t plaintext_length = sizeof( ciphertext ); /* Convert wildcard algorithm to exercisable algorithm */ if( alg & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) { alg = PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg, PSA_ALG_AEAD_GET_TAG_LENGTH( alg ) ); } /* Default IV length for AES-GCM is 12 bytes */ if( PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg, 0 ) == PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_GCM, 0 ) ) { nonce_length = 12; } /* IV length for CCM needs to be between 7 and 13 bytes */ if( PSA_ALG_AEAD_WITH_SHORTENED_TAG( alg, 0 ) == PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, 0 ) ) { nonce_length = 12; } if( usage & PSA_KEY_USAGE_ENCRYPT ) { PSA_ASSERT( psa_aead_encrypt( key, alg, nonce, nonce_length, NULL, 0, plaintext, sizeof( plaintext ), ciphertext, sizeof( ciphertext ), &ciphertext_length ) ); } if( usage & PSA_KEY_USAGE_DECRYPT ) { psa_status_t verify_status = ( usage & PSA_KEY_USAGE_ENCRYPT ? PSA_SUCCESS : PSA_ERROR_INVALID_SIGNATURE ); TEST_EQUAL( psa_aead_decrypt( key, alg, nonce, nonce_length, NULL, 0, ciphertext, ciphertext_length, plaintext, sizeof( plaintext ), &plaintext_length ), verify_status ); } return( 1 ); exit: return( 0 ); } static int exercise_signature_key( mbedtls_svc_key_id_t key, psa_key_usage_t usage, psa_algorithm_t alg ) { if( usage & ( PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH ) ) { unsigned char payload[PSA_HASH_MAX_SIZE] = {1}; size_t payload_length = 16; unsigned char signature[PSA_SIGNATURE_MAX_SIZE] = {0}; size_t signature_length = sizeof( signature ); psa_algorithm_t hash_alg = PSA_ALG_SIGN_GET_HASH( alg ); /* If the policy allows signing with any hash, just pick one. */ if( PSA_ALG_IS_HASH_AND_SIGN( alg ) && hash_alg == PSA_ALG_ANY_HASH ) { #if defined(KNOWN_SUPPORTED_HASH_ALG) hash_alg = KNOWN_SUPPORTED_HASH_ALG; alg ^= PSA_ALG_ANY_HASH ^ hash_alg; #else TEST_ASSERT( ! "No hash algorithm for hash-and-sign testing" ); #endif } /* Some algorithms require the payload to have the size of * the hash encoded in the algorithm. Use this input size * even for algorithms that allow other input sizes. */ if( hash_alg != 0 ) payload_length = PSA_HASH_LENGTH( hash_alg ); if( usage & PSA_KEY_USAGE_SIGN_HASH ) { PSA_ASSERT( psa_sign_hash( key, alg, payload, payload_length, signature, sizeof( signature ), &signature_length ) ); } if( usage & PSA_KEY_USAGE_VERIFY_HASH ) { psa_status_t verify_status = ( usage & PSA_KEY_USAGE_SIGN_HASH ? PSA_SUCCESS : PSA_ERROR_INVALID_SIGNATURE ); TEST_EQUAL( psa_verify_hash( key, alg, payload, payload_length, signature, signature_length ), verify_status ); } } if( usage & ( PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_VERIFY_MESSAGE ) ) { unsigned char message[256] = "Hello, world..."; unsigned char signature[PSA_SIGNATURE_MAX_SIZE] = {0}; size_t message_length = 16; size_t signature_length = sizeof( signature ); if( usage & PSA_KEY_USAGE_SIGN_MESSAGE ) { PSA_ASSERT( psa_sign_message( key, alg, message, message_length, signature, sizeof( signature ), &signature_length ) ); } if( usage & PSA_KEY_USAGE_VERIFY_MESSAGE ) { psa_status_t verify_status = ( usage & PSA_KEY_USAGE_SIGN_MESSAGE ? PSA_SUCCESS : PSA_ERROR_INVALID_SIGNATURE ); TEST_EQUAL( psa_verify_message( key, alg, message, message_length, signature, signature_length ), verify_status ); } } return( 1 ); exit: return( 0 ); } static int exercise_asymmetric_encryption_key( mbedtls_svc_key_id_t key, psa_key_usage_t usage, psa_algorithm_t alg ) { unsigned char plaintext[256] = "Hello, world..."; unsigned char ciphertext[256] = "(wabblewebblewibblewobblewubble)"; size_t ciphertext_length = sizeof( ciphertext ); size_t plaintext_length = 16; if( usage & PSA_KEY_USAGE_ENCRYPT ) { PSA_ASSERT( psa_asymmetric_encrypt( key, alg, plaintext, plaintext_length, NULL, 0, ciphertext, sizeof( ciphertext ), &ciphertext_length ) ); } if( usage & PSA_KEY_USAGE_DECRYPT ) { psa_status_t status = psa_asymmetric_decrypt( key, alg, ciphertext, ciphertext_length, NULL, 0, plaintext, sizeof( plaintext ), &plaintext_length ); TEST_ASSERT( status == PSA_SUCCESS || ( ( usage & PSA_KEY_USAGE_ENCRYPT ) == 0 && ( status == PSA_ERROR_INVALID_ARGUMENT || status == PSA_ERROR_INVALID_PADDING ) ) ); } return( 1 ); exit: return( 0 ); } int mbedtls_test_psa_setup_key_derivation_wrap( psa_key_derivation_operation_t* operation, mbedtls_svc_key_id_t key, psa_algorithm_t alg, const unsigned char* input1, size_t input1_length, const unsigned char* input2, size_t input2_length, size_t capacity ) { PSA_ASSERT( psa_key_derivation_setup( operation, alg ) ); if( PSA_ALG_IS_HKDF( alg ) ) { PSA_ASSERT( psa_key_derivation_input_bytes( operation, PSA_KEY_DERIVATION_INPUT_SALT, input1, input1_length ) ); PSA_ASSERT( psa_key_derivation_input_key( operation, PSA_KEY_DERIVATION_INPUT_SECRET, key ) ); PSA_ASSERT( psa_key_derivation_input_bytes( operation, PSA_KEY_DERIVATION_INPUT_INFO, input2, input2_length ) ); } else if( PSA_ALG_IS_TLS12_PRF( alg ) || PSA_ALG_IS_TLS12_PSK_TO_MS( alg ) ) { PSA_ASSERT( psa_key_derivation_input_bytes( operation, PSA_KEY_DERIVATION_INPUT_SEED, input1, input1_length ) ); PSA_ASSERT( psa_key_derivation_input_key( operation, PSA_KEY_DERIVATION_INPUT_SECRET, key ) ); PSA_ASSERT( psa_key_derivation_input_bytes( operation, PSA_KEY_DERIVATION_INPUT_LABEL, input2, input2_length ) ); } else { TEST_ASSERT( ! "Key derivation algorithm not supported" ); } if( capacity != SIZE_MAX ) PSA_ASSERT( psa_key_derivation_set_capacity( operation, capacity ) ); return( 1 ); exit: return( 0 ); } static int exercise_key_derivation_key( mbedtls_svc_key_id_t key, psa_key_usage_t usage, psa_algorithm_t alg ) { psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT; unsigned char input1[] = "Input 1"; size_t input1_length = sizeof( input1 ); unsigned char input2[] = "Input 2"; size_t input2_length = sizeof( input2 ); unsigned char output[1]; size_t capacity = sizeof( output ); if( usage & PSA_KEY_USAGE_DERIVE ) { if( !mbedtls_test_psa_setup_key_derivation_wrap( &operation, key, alg, input1, input1_length, input2, input2_length, capacity ) ) goto exit; PSA_ASSERT( psa_key_derivation_output_bytes( &operation, output, capacity ) ); PSA_ASSERT( psa_key_derivation_abort( &operation ) ); } return( 1 ); exit: return( 0 ); } /* We need two keys to exercise key agreement. Exercise the * private key against its own public key. */ psa_status_t mbedtls_test_psa_key_agreement_with_self( psa_key_derivation_operation_t *operation, mbedtls_svc_key_id_t key ) { psa_key_type_t private_key_type; psa_key_type_t public_key_type; size_t key_bits; uint8_t *public_key = NULL; size_t public_key_length; /* Return GENERIC_ERROR if something other than the final call to * psa_key_derivation_key_agreement fails. This isn't fully satisfactory, * but it's good enough: callers will report it as a failed test anyway. */ psa_status_t status = PSA_ERROR_GENERIC_ERROR; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; PSA_ASSERT( psa_get_key_attributes( key, &attributes ) ); private_key_type = psa_get_key_type( &attributes ); key_bits = psa_get_key_bits( &attributes ); public_key_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR( private_key_type ); public_key_length = PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE( public_key_type, key_bits ); ASSERT_ALLOC( public_key, public_key_length ); PSA_ASSERT( psa_export_public_key( key, public_key, public_key_length, &public_key_length ) ); status = psa_key_derivation_key_agreement( operation, PSA_KEY_DERIVATION_INPUT_SECRET, key, public_key, public_key_length ); exit: /* * Key attributes may have been returned by psa_get_key_attributes() * thus reset them as required. */ psa_reset_key_attributes( &attributes ); mbedtls_free( public_key ); return( status ); } /* We need two keys to exercise key agreement. Exercise the * private key against its own public key. */ psa_status_t mbedtls_test_psa_raw_key_agreement_with_self( psa_algorithm_t alg, mbedtls_svc_key_id_t key ) { psa_key_type_t private_key_type; psa_key_type_t public_key_type; size_t key_bits; uint8_t *public_key = NULL; size_t public_key_length; uint8_t output[1024]; size_t output_length; /* Return GENERIC_ERROR if something other than the final call to * psa_key_derivation_key_agreement fails. This isn't fully satisfactory, * but it's good enough: callers will report it as a failed test anyway. */ psa_status_t status = PSA_ERROR_GENERIC_ERROR; psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; PSA_ASSERT( psa_get_key_attributes( key, &attributes ) ); private_key_type = psa_get_key_type( &attributes ); key_bits = psa_get_key_bits( &attributes ); public_key_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR( private_key_type ); public_key_length = PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE( public_key_type, key_bits ); ASSERT_ALLOC( public_key, public_key_length ); PSA_ASSERT( psa_export_public_key( key, public_key, public_key_length, &public_key_length ) ); status = psa_raw_key_agreement( alg, key, public_key, public_key_length, output, sizeof( output ), &output_length ); if ( status == PSA_SUCCESS ) { TEST_ASSERT( output_length <= PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE( private_key_type, key_bits ) ); TEST_ASSERT( output_length <= PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE ); } exit: /* * Key attributes may have been returned by psa_get_key_attributes() * thus reset them as required. */ psa_reset_key_attributes( &attributes ); mbedtls_free( public_key ); return( status ); } static int exercise_raw_key_agreement_key( mbedtls_svc_key_id_t key, psa_key_usage_t usage, psa_algorithm_t alg ) { int ok = 0; if( usage & PSA_KEY_USAGE_DERIVE ) { /* We need two keys to exercise key agreement. Exercise the * private key against its own public key. */ PSA_ASSERT( mbedtls_test_psa_raw_key_agreement_with_self( alg, key ) ); } ok = 1; exit: return( ok ); } static int exercise_key_agreement_key( mbedtls_svc_key_id_t key, psa_key_usage_t usage, psa_algorithm_t alg ) { psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT; unsigned char output[1]; int ok = 0; if( usage & PSA_KEY_USAGE_DERIVE ) { /* We need two keys to exercise key agreement. Exercise the * private key against its own public key. */ PSA_ASSERT( psa_key_derivation_setup( &operation, alg ) ); PSA_ASSERT( mbedtls_test_psa_key_agreement_with_self( &operation, key ) ); PSA_ASSERT( psa_key_derivation_output_bytes( &operation, output, sizeof( output ) ) ); PSA_ASSERT( psa_key_derivation_abort( &operation ) ); } ok = 1; exit: return( ok ); } int mbedtls_test_psa_exported_key_sanity_check( psa_key_type_t type, size_t bits, const uint8_t *exported, size_t exported_length ) { TEST_ASSERT( exported_length <= PSA_EXPORT_KEY_OUTPUT_SIZE( type, bits ) ); if( PSA_KEY_TYPE_IS_UNSTRUCTURED( type ) ) TEST_EQUAL( exported_length, PSA_BITS_TO_BYTES( bits ) ); else #if defined(MBEDTLS_RSA_C) && defined(MBEDTLS_PK_PARSE_C) if( type == PSA_KEY_TYPE_RSA_KEY_PAIR ) { uint8_t *p = (uint8_t*) exported; const uint8_t *end = exported + exported_length; size_t len; /* RSAPrivateKey ::= SEQUENCE { * version INTEGER, -- must be 0 * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p-1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER, -- (inverse of q) mod p * } */ TEST_EQUAL( mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED ), 0 ); TEST_EQUAL( p + len, end ); if( ! mbedtls_test_asn1_skip_integer( &p, end, 0, 0, 0 ) ) goto exit; if( ! mbedtls_test_asn1_skip_integer( &p, end, bits, bits, 1 ) ) goto exit; if( ! mbedtls_test_asn1_skip_integer( &p, end, 2, bits, 1 ) ) goto exit; /* Require d to be at least half the size of n. */ if( ! mbedtls_test_asn1_skip_integer( &p, end, bits / 2, bits, 1 ) ) goto exit; /* Require p and q to be at most half the size of n, rounded up. */ if( ! mbedtls_test_asn1_skip_integer( &p, end, bits / 2, bits / 2 + 1, 1 ) ) goto exit; if( ! mbedtls_test_asn1_skip_integer( &p, end, bits / 2, bits / 2 + 1, 1 ) ) goto exit; if( ! mbedtls_test_asn1_skip_integer( &p, end, 1, bits / 2 + 1, 0 ) ) goto exit; if( ! mbedtls_test_asn1_skip_integer( &p, end, 1, bits / 2 + 1, 0 ) ) goto exit; if( ! mbedtls_test_asn1_skip_integer( &p, end, 1, bits / 2 + 1, 0 ) ) goto exit; TEST_EQUAL( p, end ); TEST_ASSERT( exported_length <= PSA_EXPORT_KEY_PAIR_MAX_SIZE ); } else #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECP_C) if( PSA_KEY_TYPE_IS_ECC_KEY_PAIR( type ) ) { /* Just the secret value */ TEST_EQUAL( exported_length, PSA_BITS_TO_BYTES( bits ) ); TEST_ASSERT( exported_length <= PSA_EXPORT_KEY_PAIR_MAX_SIZE ); } else #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_RSA_C) if( type == PSA_KEY_TYPE_RSA_PUBLIC_KEY ) { uint8_t *p = (uint8_t*) exported; const uint8_t *end = exported + exported_length; size_t len; /* RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER } -- e */ TEST_EQUAL( mbedtls_asn1_get_tag( &p, end, &len, MBEDTLS_ASN1_SEQUENCE | MBEDTLS_ASN1_CONSTRUCTED ), 0 ); TEST_EQUAL( p + len, end ); if( ! mbedtls_test_asn1_skip_integer( &p, end, bits, bits, 1 ) ) goto exit; if( ! mbedtls_test_asn1_skip_integer( &p, end, 2, bits, 1 ) ) goto exit; TEST_EQUAL( p, end ); TEST_ASSERT( exported_length <= PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE( type, bits ) ); TEST_ASSERT( exported_length <= PSA_EXPORT_PUBLIC_KEY_MAX_SIZE ); } else #endif /* MBEDTLS_RSA_C */ #if defined(MBEDTLS_ECP_C) if( PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY( type ) ) { TEST_ASSERT( exported_length <= PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE( type, bits ) ); TEST_ASSERT( exported_length <= PSA_EXPORT_PUBLIC_KEY_MAX_SIZE ); if( PSA_KEY_TYPE_ECC_GET_FAMILY( type ) == PSA_ECC_FAMILY_MONTGOMERY ) { /* The representation of an ECC Montgomery public key is * the raw compressed point */ TEST_EQUAL( PSA_BITS_TO_BYTES( bits ), exported_length ); } else { /* The representation of an ECC Weierstrass public key is: * - The byte 0x04; * - `x_P` as a `ceiling(m/8)`-byte string, big-endian; * - `y_P` as a `ceiling(m/8)`-byte string, big-endian; * - where m is the bit size associated with the curve. */ TEST_EQUAL( 1 + 2 * PSA_BITS_TO_BYTES( bits ), exported_length ); TEST_EQUAL( exported[0], 4 ); } } else #endif /* MBEDTLS_ECP_C */ { TEST_ASSERT( ! "Sanity check not implemented for this key type" ); } #if defined(MBEDTLS_DES_C) if( type == PSA_KEY_TYPE_DES ) { /* Check the parity bits. */ unsigned i; for( i = 0; i < bits / 8; i++ ) { unsigned bit_count = 0; unsigned m; for( m = 1; m <= 0x100; m <<= 1 ) { if( exported[i] & m ) ++bit_count; } TEST_ASSERT( bit_count % 2 != 0 ); } } #endif return( 1 ); exit: return( 0 ); } static int exercise_export_key( mbedtls_svc_key_id_t key, psa_key_usage_t usage ) { psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; uint8_t *exported = NULL; size_t exported_size = 0; size_t exported_length = 0; int ok = 0; PSA_ASSERT( psa_get_key_attributes( key, &attributes ) ); exported_size = PSA_EXPORT_KEY_OUTPUT_SIZE( psa_get_key_type( &attributes ), psa_get_key_bits( &attributes ) ); ASSERT_ALLOC( exported, exported_size ); if( ( usage & PSA_KEY_USAGE_EXPORT ) == 0 && ! PSA_KEY_TYPE_IS_PUBLIC_KEY( psa_get_key_type( &attributes ) ) ) { TEST_EQUAL( psa_export_key( key, exported, exported_size, &exported_length ), PSA_ERROR_NOT_PERMITTED ); ok = 1; goto exit; } PSA_ASSERT( psa_export_key( key, exported, exported_size, &exported_length ) ); ok = mbedtls_test_psa_exported_key_sanity_check( psa_get_key_type( &attributes ), psa_get_key_bits( &attributes ), exported, exported_length ); exit: /* * Key attributes may have been returned by psa_get_key_attributes() * thus reset them as required. */ psa_reset_key_attributes( &attributes ); mbedtls_free( exported ); return( ok ); } static int exercise_export_public_key( mbedtls_svc_key_id_t key ) { psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; psa_key_type_t public_type; uint8_t *exported = NULL; size_t exported_size = 0; size_t exported_length = 0; int ok = 0; PSA_ASSERT( psa_get_key_attributes( key, &attributes ) ); if( ! PSA_KEY_TYPE_IS_ASYMMETRIC( psa_get_key_type( &attributes ) ) ) { exported_size = PSA_EXPORT_KEY_OUTPUT_SIZE( psa_get_key_type( &attributes ), psa_get_key_bits( &attributes ) ); ASSERT_ALLOC( exported, exported_size ); TEST_EQUAL( psa_export_public_key( key, exported, exported_size, &exported_length ), PSA_ERROR_INVALID_ARGUMENT ); ok = 1; goto exit; } public_type = PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR( psa_get_key_type( &attributes ) ); exported_size = PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE( public_type, psa_get_key_bits( &attributes ) ); ASSERT_ALLOC( exported, exported_size ); PSA_ASSERT( psa_export_public_key( key, exported, exported_size, &exported_length ) ); ok = mbedtls_test_psa_exported_key_sanity_check( public_type, psa_get_key_bits( &attributes ), exported, exported_length ); exit: /* * Key attributes may have been returned by psa_get_key_attributes() * thus reset them as required. */ psa_reset_key_attributes( &attributes ); mbedtls_free( exported ); return( ok ); } int mbedtls_test_psa_exercise_key( mbedtls_svc_key_id_t key, psa_key_usage_t usage, psa_algorithm_t alg ) { int ok = 0; if( ! check_key_attributes_sanity( key ) ) return( 0 ); if( alg == 0 ) ok = 1; /* If no algorihm, do nothing (used for raw data "keys"). */ else if( PSA_ALG_IS_MAC( alg ) ) ok = exercise_mac_key( key, usage, alg ); else if( PSA_ALG_IS_CIPHER( alg ) ) ok = exercise_cipher_key( key, usage, alg ); else if( PSA_ALG_IS_AEAD( alg ) ) ok = exercise_aead_key( key, usage, alg ); else if( PSA_ALG_IS_SIGN( alg ) ) ok = exercise_signature_key( key, usage, alg ); else if( PSA_ALG_IS_ASYMMETRIC_ENCRYPTION( alg ) ) ok = exercise_asymmetric_encryption_key( key, usage, alg ); else if( PSA_ALG_IS_KEY_DERIVATION( alg ) ) ok = exercise_key_derivation_key( key, usage, alg ); else if( PSA_ALG_IS_RAW_KEY_AGREEMENT( alg ) ) ok = exercise_raw_key_agreement_key( key, usage, alg ); else if( PSA_ALG_IS_KEY_AGREEMENT( alg ) ) ok = exercise_key_agreement_key( key, usage, alg ); else TEST_ASSERT( ! "No code to exercise this category of algorithm" ); ok = ok && exercise_export_key( key, usage ); ok = ok && exercise_export_public_key( key ); exit: return( ok ); } psa_key_usage_t mbedtls_test_psa_usage_to_exercise( psa_key_type_t type, psa_algorithm_t alg ) { if( PSA_ALG_IS_MAC( alg ) || PSA_ALG_IS_SIGN( alg ) ) { if( PSA_ALG_IS_HASH_AND_SIGN( alg ) ) { if( PSA_ALG_SIGN_GET_HASH( alg ) ) return( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) ? PSA_KEY_USAGE_VERIFY_HASH | PSA_KEY_USAGE_VERIFY_MESSAGE: PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH | PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_VERIFY_MESSAGE ); } else if( PSA_ALG_IS_SIGN_MESSAGE( alg) ) return( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) ? PSA_KEY_USAGE_VERIFY_MESSAGE : PSA_KEY_USAGE_SIGN_MESSAGE | PSA_KEY_USAGE_VERIFY_MESSAGE ); return( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) ? PSA_KEY_USAGE_VERIFY_HASH : PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH ); } else if( PSA_ALG_IS_CIPHER( alg ) || PSA_ALG_IS_AEAD( alg ) || PSA_ALG_IS_ASYMMETRIC_ENCRYPTION( alg ) ) { return( PSA_KEY_TYPE_IS_PUBLIC_KEY( type ) ? PSA_KEY_USAGE_ENCRYPT : PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT ); } else if( PSA_ALG_IS_KEY_DERIVATION( alg ) || PSA_ALG_IS_KEY_AGREEMENT( alg ) ) { return( PSA_KEY_USAGE_DERIVE ); } else { return( 0 ); } } #endif /* MBEDTLS_PSA_CRYPTO_C */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/fake_external_rng_for_test.c
/** \file fake_external_rng_for_test.c * * \brief Helper functions to test PSA crypto functionality. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <test/fake_external_rng_for_test.h> #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) #include <test/random.h> #include <psa/crypto.h> static int test_insecure_external_rng_enabled = 0; void mbedtls_test_enable_insecure_external_rng( void ) { test_insecure_external_rng_enabled = 1; } void mbedtls_test_disable_insecure_external_rng( void ) { test_insecure_external_rng_enabled = 0; } psa_status_t mbedtls_psa_external_get_random( mbedtls_psa_external_random_context_t *context, uint8_t *output, size_t output_size, size_t *output_length ) { (void) context; if( !test_insecure_external_rng_enabled ) return( PSA_ERROR_INSUFFICIENT_ENTROPY ); /* This implementation is for test purposes only! * Use the libc non-cryptographic random generator. */ mbedtls_test_rnd_std_rand( NULL, output, output_size ); *output_length = output_size; return( PSA_SUCCESS ); } #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/random.c
/** * \file random.c * * \brief This file contains the helper functions to generate random numbers * for the purpose of testing. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * for arc4random_buf() from <stdlib.h> */ #if defined(__NetBSD__) #define _NETBSD_SOURCE 1 #elif defined(__OpenBSD__) #define _BSD_SOURCE 1 #endif #include <test/macros.h> #include <test/random.h> #include <string.h> #include <mbedtls/entropy.h> int mbedtls_test_rnd_std_rand( void *rng_state, unsigned char *output, size_t len ) { #if !defined(__OpenBSD__) && !defined(__NetBSD__) size_t i; if( rng_state != NULL ) rng_state = NULL; for( i = 0; i < len; ++i ) output[i] = rand(); #else if( rng_state != NULL ) rng_state = NULL; arc4random_buf( output, len ); #endif /* !OpenBSD && !NetBSD */ return( 0 ); } int mbedtls_test_rnd_zero_rand( void *rng_state, unsigned char *output, size_t len ) { if( rng_state != NULL ) rng_state = NULL; memset( output, 0, len ); return( 0 ); } int mbedtls_test_rnd_buffer_rand( void *rng_state, unsigned char *output, size_t len ) { mbedtls_test_rnd_buf_info *info = (mbedtls_test_rnd_buf_info *) rng_state; size_t use_len; if( rng_state == NULL ) return( mbedtls_test_rnd_std_rand( NULL, output, len ) ); use_len = len; if( len > info->length ) use_len = info->length; if( use_len ) { memcpy( output, info->buf, use_len ); info->buf += use_len; info->length -= use_len; } if( len - use_len > 0 ) { if( info->fallback_f_rng != NULL ) { return( info->fallback_f_rng( info->fallback_p_rng, output + use_len, len - use_len ) ); } else return( MBEDTLS_ERR_ENTROPY_SOURCE_FAILED ); } return( 0 ); } int mbedtls_test_rnd_pseudo_rand( void *rng_state, unsigned char *output, size_t len ) { mbedtls_test_rnd_pseudo_info *info = (mbedtls_test_rnd_pseudo_info *) rng_state; uint32_t i, *k, sum, delta=0x9E3779B9; unsigned char result[4], *out = output; if( rng_state == NULL ) return( mbedtls_test_rnd_std_rand( NULL, output, len ) ); k = info->key; while( len > 0 ) { size_t use_len = ( len > 4 ) ? 4 : len; sum = 0; for( i = 0; i < 32; i++ ) { info->v0 += ( ( ( info->v1 << 4 ) ^ ( info->v1 >> 5 ) ) + info->v1 ) ^ ( sum + k[sum & 3] ); sum += delta; info->v1 += ( ( ( info->v0 << 4 ) ^ ( info->v0 >> 5 ) ) + info->v0 ) ^ ( sum + k[( sum>>11 ) & 3] ); } PUT_UINT32_BE( info->v0, result, 0 ); memcpy( out, result, use_len ); len -= use_len; out += 4; } return( 0 ); }
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/psa_crypto_helpers.c
/** \file psa_crypto_helpers.c * * \brief Helper functions to test PSA crypto functionality. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <test/helpers.h> #include <test/macros.h> #include <test/psa_crypto_helpers.h> #if defined(MBEDTLS_PSA_CRYPTO_C) #include <psa/crypto.h> #if defined(MBEDTLS_PSA_CRYPTO_STORAGE_C) #include <psa_crypto_storage.h> static mbedtls_svc_key_id_t key_ids_used_in_test[9]; static size_t num_key_ids_used; int mbedtls_test_uses_key_id( mbedtls_svc_key_id_t key_id ) { size_t i; if( MBEDTLS_SVC_KEY_ID_GET_KEY_ID( key_id ) > PSA_MAX_PERSISTENT_KEY_IDENTIFIER ) { /* Don't touch key id values that designate non-key files. */ return( 1 ); } for( i = 0; i < num_key_ids_used ; i++ ) { if( mbedtls_svc_key_id_equal( key_id, key_ids_used_in_test[i] ) ) return( 1 ); } if( num_key_ids_used == ARRAY_LENGTH( key_ids_used_in_test ) ) return( 0 ); key_ids_used_in_test[num_key_ids_used] = key_id; ++num_key_ids_used; return( 1 ); } void mbedtls_test_psa_purge_key_storage( void ) { size_t i; for( i = 0; i < num_key_ids_used; i++ ) psa_destroy_persistent_key( key_ids_used_in_test[i] ); num_key_ids_used = 0; } void mbedtls_test_psa_purge_key_cache( void ) { size_t i; for( i = 0; i < num_key_ids_used; i++ ) psa_purge_key( key_ids_used_in_test[i] ); } #endif /* MBEDTLS_PSA_CRYPTO_STORAGE_C */ const char *mbedtls_test_helper_is_psa_leaking( void ) { mbedtls_psa_stats_t stats; mbedtls_psa_get_stats( &stats ); if( stats.volatile_slots != 0 ) return( "A volatile slot has not been closed properly." ); if( stats.persistent_slots != 0 ) return( "A persistent slot has not been closed properly." ); if( stats.external_slots != 0 ) return( "An external slot has not been closed properly." ); if( stats.half_filled_slots != 0 ) return( "A half-filled slot has not been cleared properly." ); if( stats.locked_slots != 0 ) return( "Some slots are still marked as locked." ); return( NULL ); } #if defined(RECORD_PSA_STATUS_COVERAGE_LOG) /** Name of the file where return statuses are logged by #RECORD_STATUS. */ #define STATUS_LOG_FILE_NAME "statuses.log" psa_status_t mbedtls_test_record_status( psa_status_t status, const char *func, const char *file, int line, const char *expr ) { /* We open the log file on first use. * We never close the log file, so the record_status feature is not * compatible with resource leak detectors such as Asan. */ static FILE *log; if( log == NULL ) log = fopen( STATUS_LOG_FILE_NAME, "a" ); fprintf( log, "%d:%s:%s:%d:%s\n", (int) status, func, file, line, expr ); return( status ); } #endif /* defined(RECORD_PSA_STATUS_COVERAGE_LOG) */ psa_key_usage_t mbedtls_test_update_key_usage_flags( psa_key_usage_t usage_flags ) { psa_key_usage_t updated_usage = usage_flags; if( usage_flags & PSA_KEY_USAGE_SIGN_HASH ) updated_usage |= PSA_KEY_USAGE_SIGN_MESSAGE; if( usage_flags & PSA_KEY_USAGE_VERIFY_HASH ) updated_usage |= PSA_KEY_USAGE_VERIFY_MESSAGE; return( updated_usage ); } #endif /* MBEDTLS_PSA_CRYPTO_C */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/threading_helpers.c
/** Mutex usage verification framework. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <test/helpers.h> #include <test/macros.h> #if defined(MBEDTLS_TEST_MUTEX_USAGE) #include "mbedtls/threading.h" /** Mutex usage verification framework. * * The mutex usage verification code below aims to detect bad usage of * Mbed TLS's mutex abstraction layer at runtime. Note that this is solely * about the use of the mutex itself, not about checking whether the mutex * correctly protects whatever it is supposed to protect. * * The normal usage of a mutex is: * ``` * digraph mutex_states { * "UNINITIALIZED"; // the initial state * "IDLE"; * "FREED"; * "LOCKED"; * "UNINITIALIZED" -> "IDLE" [label="init"]; * "FREED" -> "IDLE" [label="init"]; * "IDLE" -> "LOCKED" [label="lock"]; * "LOCKED" -> "IDLE" [label="unlock"]; * "IDLE" -> "FREED" [label="free"]; * } * ``` * * All bad transitions that can be unambiguously detected are reported. * An attempt to use an uninitialized mutex cannot be detected in general * since the memory content may happen to denote a valid state. For the same * reason, a double init cannot be detected. * All-bits-zero is the state of a freed mutex, which is distinct from an * initialized mutex, so attempting to use zero-initialized memory as a mutex * without calling the init function is detected. * * The framework attempts to detect missing calls to init and free by counting * calls to init and free. If there are more calls to init than free, this * means that a mutex is not being freed somewhere, which is a memory leak * on platforms where a mutex consumes resources other than the * mbedtls_threading_mutex_t object itself. If there are more calls to free * than init, this indicates a missing init, which is likely to be detected * by an attempt to lock the mutex as well. A limitation of this framework is * that it cannot detect scenarios where there is exactly the same number of * calls to init and free but the calls don't match. A bug like this is * unlikely to happen uniformly throughout the whole test suite though. * * If an error is detected, this framework will report what happened and the * test case will be marked as failed. Unfortunately, the error report cannot * indicate the exact location of the problematic call. To locate the error, * use a debugger and set a breakpoint on mbedtls_test_mutex_usage_error(). */ enum value_of_mutex_is_valid_field { /* Potential values for the is_valid field of mbedtls_threading_mutex_t. * Note that MUTEX_FREED must be 0 and MUTEX_IDLE must be 1 for * compatibility with threading_mutex_init_pthread() and * threading_mutex_free_pthread(). MUTEX_LOCKED could be any nonzero * value. */ MUTEX_FREED = 0, //!< Set by threading_mutex_free_pthread MUTEX_IDLE = 1, //!< Set by threading_mutex_init_pthread and by our unlock MUTEX_LOCKED = 2, //!< Set by our lock }; typedef struct { void (*init)( mbedtls_threading_mutex_t * ); void (*free)( mbedtls_threading_mutex_t * ); int (*lock)( mbedtls_threading_mutex_t * ); int (*unlock)( mbedtls_threading_mutex_t * ); } mutex_functions_t; static mutex_functions_t mutex_functions; /** The total number of calls to mbedtls_mutex_init(), minus the total number * of calls to mbedtls_mutex_free(). * * Reset to 0 after each test case. */ static int live_mutexes; static void mbedtls_test_mutex_usage_error( mbedtls_threading_mutex_t *mutex, const char *msg ) { (void) mutex; if( mbedtls_test_info.mutex_usage_error == NULL ) mbedtls_test_info.mutex_usage_error = msg; mbedtls_fprintf( stdout, "[mutex: %s] ", msg ); /* Don't mark the test as failed yet. This way, if the test fails later * for a functional reason, the test framework will report the message * and location for this functional reason. If the test passes, * mbedtls_test_mutex_usage_check() will mark it as failed. */ } static void mbedtls_test_wrap_mutex_init( mbedtls_threading_mutex_t *mutex ) { mutex_functions.init( mutex ); if( mutex->is_valid ) ++live_mutexes; } static void mbedtls_test_wrap_mutex_free( mbedtls_threading_mutex_t *mutex ) { switch( mutex->is_valid ) { case MUTEX_FREED: mbedtls_test_mutex_usage_error( mutex, "free without init or double free" ); break; case MUTEX_IDLE: /* Do nothing. The underlying free function will reset is_valid * to 0. */ break; case MUTEX_LOCKED: mbedtls_test_mutex_usage_error( mutex, "free without unlock" ); break; default: mbedtls_test_mutex_usage_error( mutex, "corrupted state" ); break; } if( mutex->is_valid ) --live_mutexes; mutex_functions.free( mutex ); } static int mbedtls_test_wrap_mutex_lock( mbedtls_threading_mutex_t *mutex ) { int ret = mutex_functions.lock( mutex ); switch( mutex->is_valid ) { case MUTEX_FREED: mbedtls_test_mutex_usage_error( mutex, "lock without init" ); break; case MUTEX_IDLE: if( ret == 0 ) mutex->is_valid = 2; break; case MUTEX_LOCKED: mbedtls_test_mutex_usage_error( mutex, "double lock" ); break; default: mbedtls_test_mutex_usage_error( mutex, "corrupted state" ); break; } return( ret ); } static int mbedtls_test_wrap_mutex_unlock( mbedtls_threading_mutex_t *mutex ) { int ret = mutex_functions.unlock( mutex ); switch( mutex->is_valid ) { case MUTEX_FREED: mbedtls_test_mutex_usage_error( mutex, "unlock without init" ); break; case MUTEX_IDLE: mbedtls_test_mutex_usage_error( mutex, "unlock without lock" ); break; case MUTEX_LOCKED: if( ret == 0 ) mutex->is_valid = MUTEX_IDLE; break; default: mbedtls_test_mutex_usage_error( mutex, "corrupted state" ); break; } return( ret ); } void mbedtls_test_mutex_usage_init( void ) { mutex_functions.init = mbedtls_mutex_init; mutex_functions.free = mbedtls_mutex_free; mutex_functions.lock = mbedtls_mutex_lock; mutex_functions.unlock = mbedtls_mutex_unlock; mbedtls_mutex_init = &mbedtls_test_wrap_mutex_init; mbedtls_mutex_free = &mbedtls_test_wrap_mutex_free; mbedtls_mutex_lock = &mbedtls_test_wrap_mutex_lock; mbedtls_mutex_unlock = &mbedtls_test_wrap_mutex_unlock; } void mbedtls_test_mutex_usage_check( void ) { if( live_mutexes != 0 ) { /* A positive number (more init than free) means that a mutex resource * is leaking (on platforms where a mutex consumes more than the * mbedtls_threading_mutex_t object itself). The rare case of a * negative number means a missing init somewhere. */ mbedtls_fprintf( stdout, "[mutex: %d leaked] ", live_mutexes ); live_mutexes = 0; if( mbedtls_test_info.mutex_usage_error == NULL ) mbedtls_test_info.mutex_usage_error = "missing free"; } if( mbedtls_test_info.mutex_usage_error != NULL && mbedtls_test_info.result != MBEDTLS_TEST_RESULT_FAILED ) { /* Functionally, the test passed. But there was a mutex usage error, * so mark the test as failed after all. */ mbedtls_test_fail( "Mutex usage error", __LINE__, __FILE__ ); } mbedtls_test_info.mutex_usage_error = NULL; } #endif /* MBEDTLS_TEST_MUTEX_USAGE */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/asn1_helpers.c
/** \file asn1_helpers.c * * \brief Helper functions for tests that manipulate ASN.1 data. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <test/helpers.h> #include <test/macros.h> #if defined(MBEDTLS_ASN1_PARSE_C) #include <mbedtls/asn1.h> int mbedtls_test_asn1_skip_integer( unsigned char **p, const unsigned char *end, size_t min_bits, size_t max_bits, int must_be_odd ) { size_t len; size_t actual_bits; unsigned char msb; TEST_EQUAL( mbedtls_asn1_get_tag( p, end, &len, MBEDTLS_ASN1_INTEGER ), 0 ); /* Check if the retrieved length doesn't extend the actual buffer's size. * It is assumed here, that end >= p, which validates casting to size_t. */ TEST_ASSERT( len <= (size_t)( end - *p) ); /* Tolerate a slight departure from DER encoding: * - 0 may be represented by an empty string or a 1-byte string. * - The sign bit may be used as a value bit. */ if( ( len == 1 && ( *p )[0] == 0 ) || ( len > 1 && ( *p )[0] == 0 && ( ( *p )[1] & 0x80 ) != 0 ) ) { ++( *p ); --len; } if( min_bits == 0 && len == 0 ) return( 1 ); msb = ( *p )[0]; TEST_ASSERT( msb != 0 ); actual_bits = 8 * ( len - 1 ); while( msb != 0 ) { msb >>= 1; ++actual_bits; } TEST_ASSERT( actual_bits >= min_bits ); TEST_ASSERT( actual_bits <= max_bits ); if( must_be_odd ) TEST_ASSERT( ( ( *p )[len-1] & 1 ) != 0 ); *p += len; return( 1 ); exit: return( 0 ); } #endif /* MBEDTLS_ASN1_PARSE_C */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/helpers.c
/* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <test/helpers.h> #include <test/macros.h> #include <string.h> #if defined(MBEDTLS_CHECK_PARAMS) #include <setjmp.h> #endif /*----------------------------------------------------------------------------*/ /* Static global variables */ #if defined(MBEDTLS_CHECK_PARAMS) typedef struct { uint8_t expected_call; uint8_t expected_call_happened; jmp_buf state; mbedtls_test_param_failed_location_record_t location_record; } param_failed_ctx_t; static param_failed_ctx_t param_failed_ctx; #endif #if defined(MBEDTLS_PLATFORM_C) static mbedtls_platform_context platform_ctx; #endif mbedtls_test_info_t mbedtls_test_info; /*----------------------------------------------------------------------------*/ /* Helper Functions */ int mbedtls_test_platform_setup( void ) { int ret = 0; #if defined(MBEDTLS_PLATFORM_C) ret = mbedtls_platform_setup( &platform_ctx ); #endif /* MBEDTLS_PLATFORM_C */ return( ret ); } void mbedtls_test_platform_teardown( void ) { #if defined(MBEDTLS_PLATFORM_C) mbedtls_platform_teardown( &platform_ctx ); #endif /* MBEDTLS_PLATFORM_C */ } static int ascii2uc(const char c, unsigned char *uc) { if( ( c >= '0' ) && ( c <= '9' ) ) *uc = c - '0'; else if( ( c >= 'a' ) && ( c <= 'f' ) ) *uc = c - 'a' + 10; else if( ( c >= 'A' ) && ( c <= 'F' ) ) *uc = c - 'A' + 10; else return( -1 ); return( 0 ); } void mbedtls_test_fail( const char *test, int line_no, const char* filename ) { if( mbedtls_test_info.result == MBEDTLS_TEST_RESULT_FAILED ) { /* We've already recorded the test as having failed. Don't * overwrite any previous information about the failure. */ return; } mbedtls_test_info.result = MBEDTLS_TEST_RESULT_FAILED; mbedtls_test_info.test = test; mbedtls_test_info.line_no = line_no; mbedtls_test_info.filename = filename; } void mbedtls_test_skip( const char *test, int line_no, const char* filename ) { mbedtls_test_info.result = MBEDTLS_TEST_RESULT_SKIPPED; mbedtls_test_info.test = test; mbedtls_test_info.line_no = line_no; mbedtls_test_info.filename = filename; } void mbedtls_test_set_step( unsigned long step ) { mbedtls_test_info.step = step; } void mbedtls_test_info_reset( void ) { mbedtls_test_info.result = MBEDTLS_TEST_RESULT_SUCCESS; mbedtls_test_info.step = (unsigned long)( -1 ); mbedtls_test_info.test = 0; mbedtls_test_info.line_no = 0; mbedtls_test_info.filename = 0; } int mbedtls_test_unhexify( unsigned char *obuf, size_t obufmax, const char *ibuf, size_t *len ) { unsigned char uc, uc2; *len = strlen( ibuf ); /* Must be even number of bytes. */ if ( ( *len ) & 1 ) return( -1 ); *len /= 2; if ( (*len) > obufmax ) return( -1 ); while( *ibuf != 0 ) { if ( ascii2uc( *(ibuf++), &uc ) != 0 ) return( -1 ); if ( ascii2uc( *(ibuf++), &uc2 ) != 0 ) return( -1 ); *(obuf++) = ( uc << 4 ) | uc2; } return( 0 ); } void mbedtls_test_hexify( unsigned char *obuf, const unsigned char *ibuf, int len ) { unsigned char l, h; while( len != 0 ) { h = *ibuf / 16; l = *ibuf % 16; if( h < 10 ) *obuf++ = '0' + h; else *obuf++ = 'a' + h - 10; if( l < 10 ) *obuf++ = '0' + l; else *obuf++ = 'a' + l - 10; ++ibuf; len--; } } unsigned char *mbedtls_test_zero_alloc( size_t len ) { void *p; size_t actual_len = ( len != 0 ) ? len : 1; p = mbedtls_calloc( 1, actual_len ); TEST_HELPER_ASSERT( p != NULL ); memset( p, 0x00, actual_len ); return( p ); } unsigned char *mbedtls_test_unhexify_alloc( const char *ibuf, size_t *olen ) { unsigned char *obuf; size_t len; *olen = strlen( ibuf ) / 2; if( *olen == 0 ) return( mbedtls_test_zero_alloc( *olen ) ); obuf = mbedtls_calloc( 1, *olen ); TEST_HELPER_ASSERT( obuf != NULL ); TEST_HELPER_ASSERT( mbedtls_test_unhexify( obuf, *olen, ibuf, &len ) == 0 ); return( obuf ); } int mbedtls_test_hexcmp( uint8_t * a, uint8_t * b, uint32_t a_len, uint32_t b_len ) { int ret = 0; uint32_t i = 0; if( a_len != b_len ) return( -1 ); for( i = 0; i < a_len; i++ ) { if( a[i] != b[i] ) { ret = -1; break; } } return ret; } #if defined(MBEDTLS_CHECK_PARAMS) void mbedtls_test_param_failed_get_location_record( mbedtls_test_param_failed_location_record_t *location_record ) { *location_record = param_failed_ctx.location_record; } void mbedtls_test_param_failed_expect_call( void ) { param_failed_ctx.expected_call_happened = 0; param_failed_ctx.expected_call = 1; } int mbedtls_test_param_failed_check_expected_call( void ) { param_failed_ctx.expected_call = 0; if( param_failed_ctx.expected_call_happened != 0 ) return( 0 ); return( -1 ); } void* mbedtls_test_param_failed_get_state_buf( void ) { return &param_failed_ctx.state; } void mbedtls_test_param_failed_reset_state( void ) { memset( param_failed_ctx.state, 0, sizeof( param_failed_ctx.state ) ); } void mbedtls_param_failed( const char *failure_condition, const char *file, int line ) { /* Record the location of the failure */ param_failed_ctx.location_record.failure_condition = failure_condition; param_failed_ctx.location_record.file = file; param_failed_ctx.location_record.line = line; /* If we are testing the callback function... */ if( param_failed_ctx.expected_call != 0 ) { param_failed_ctx.expected_call = 0; param_failed_ctx.expected_call_happened = 1; } else { /* ...else try a long jump. If the execution state has not been set-up * or reset then the long jump buffer is all zero's and the call will * with high probability fault, emphasizing there is something to look * at. */ longjmp( param_failed_ctx.state, 1 ); } } #endif /* MBEDTLS_CHECK_PARAMS */ #if defined(MBEDTLS_TEST_HOOKS) void mbedtls_test_err_add_check( int high, int low, const char *file, int line ) { /* Error codes are always negative (a value of zero is a success) however * their positive opposites can be easier to understand. The following * examples given in comments have been made positive for ease of * understanding. The structure of an error code is such: * * shhhhhhhhlllllll * * s = sign bit. * h = high level error code (includes high level module ID (bits 12..14) * and module-dependent error code (bits 7..11)). * l = low level error code. */ if ( high > -0x1000 && high != 0 ) /* high < 0001000000000000 * No high level module ID bits are set. */ { mbedtls_test_fail( "'high' is not a high-level error code", line, file ); } else if ( high < -0x7F80 ) /* high > 0111111110000000 * Error code is greater than the largest allowed high level module ID. */ { mbedtls_test_fail( "'high' error code is greater than 15 bits", line, file ); } else if ( ( high & 0x7F ) != 0 ) /* high & 0000000001111111 * Error code contains low level error code bits. */ { mbedtls_test_fail( "'high' contains a low-level error code", line, file ); } else if ( low < -0x007F ) /* low > 0000000001111111 * Error code contains high or module level error code bits. */ { mbedtls_test_fail( "'low' error code is greater than 7 bits", line, file ); } else if ( low > 0 ) { mbedtls_test_fail( "'low' error code is greater than zero", line, file ); } } #endif /* MBEDTLS_TEST_HOOKS */ #if defined(MBEDTLS_BIGNUM_C) int mbedtls_test_read_mpi( mbedtls_mpi *X, int radix, const char *s ) { /* mbedtls_mpi_read_string() currently retains leading zeros. * It always allocates at least one limb for the value 0. */ if( s[0] == 0 ) { mbedtls_mpi_free( X ); return( 0 ); } else return( mbedtls_mpi_read_string( X, radix, s ) ); } #endif
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/drivers/test_driver_size.c
/* * Test driver for retrieving key context size. * Only used by opaque drivers. */ /* Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_PSA_CRYPTO_DRIVERS) && defined(PSA_CRYPTO_DRIVER_TEST) #include "test/drivers/size.h" #include "psa/crypto.h" typedef struct { unsigned int context; } test_driver_key_context_t; /* * This macro returns the base size for the key context. It is the size of the * driver specific information stored in each key context. */ #define TEST_DRIVER_KEY_CONTEXT_BASE_SIZE sizeof( test_driver_key_context_t ) /* * Number of bytes included in every key context for a key pair. * * This pair size is for an ECC 256-bit private/public key pair. * Based on this value, the size of the private key can be derived by * subtracting the public key size below from this one. */ #define TEST_DRIVER_KEY_CONTEXT_KEY_PAIR_SIZE 65 /* * Number of bytes included in every key context for a public key. * * For ECC public keys, it needs 257 bits so 33 bytes. */ #define TEST_DRIVER_KEY_CONTEXT_PUBLIC_KEY_SIZE 33 /* * Every key context for a symmetric key includes this many times the key size. */ #define TEST_DRIVER_KEY_CONTEXT_SYMMETRIC_FACTOR 0 /* * If this is true for a key pair, the key context includes space for the public key. * If this is false, no additional space is added for the public key. * * For this instance, store the public key with the private one. */ #define TEST_DRIVER_KEY_CONTEXT_STORE_PUBLIC_KEY 1 size_t mbedtls_test_size_function( const psa_key_type_t key_type, const size_t key_bits ) { size_t key_buffer_size = 0; if( PSA_KEY_TYPE_IS_KEY_PAIR( key_type ) ) { int public_key_overhead = ( ( TEST_DRIVER_KEY_CONTEXT_STORE_PUBLIC_KEY == 1 ) ? PSA_EXPORT_KEY_OUTPUT_SIZE( key_type, key_bits ) : 0 ); key_buffer_size = TEST_DRIVER_KEY_CONTEXT_BASE_SIZE + TEST_DRIVER_KEY_CONTEXT_PUBLIC_KEY_SIZE + public_key_overhead; } else if( PSA_KEY_TYPE_IS_PUBLIC_KEY( key_type ) ) { key_buffer_size = TEST_DRIVER_KEY_CONTEXT_BASE_SIZE + TEST_DRIVER_KEY_CONTEXT_PUBLIC_KEY_SIZE; } else if ( !PSA_KEY_TYPE_IS_KEY_PAIR( key_type ) && !PSA_KEY_TYPE_IS_PUBLIC_KEY ( key_type ) ) { key_buffer_size = TEST_DRIVER_KEY_CONTEXT_BASE_SIZE + ( TEST_DRIVER_KEY_CONTEXT_SYMMETRIC_FACTOR * ( ( key_bits + 7 ) / 8 ) ); } return( key_buffer_size ); } #endif /* MBEDTLS_PSA_CRYPTO_DRIVERS && PSA_CRYPTO_DRIVER_TEST */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/drivers/test_driver_mac.c
/* * Test driver for MAC entry points. */ /* Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_PSA_CRYPTO_DRIVERS) && defined(PSA_CRYPTO_DRIVER_TEST) #include "psa_crypto_mac.h" #include "test/drivers/mac.h" mbedtls_test_driver_mac_hooks_t mbedtls_test_driver_mac_hooks = MBEDTLS_TEST_DRIVER_MAC_INIT; psa_status_t mbedtls_test_transparent_mac_compute( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *mac, size_t mac_size, size_t *mac_length ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_transparent_test_driver_mac_compute( attributes, key_buffer, key_buffer_size, alg, input, input_length, mac, mac_size, mac_length ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_mac_sign_setup( mbedtls_transparent_test_driver_mac_operation_t *operation, const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_transparent_test_driver_mac_sign_setup( operation, attributes, key_buffer, key_buffer_size, alg ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_mac_verify_setup( mbedtls_transparent_test_driver_mac_operation_t *operation, const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_transparent_test_driver_mac_verify_setup( operation, attributes, key_buffer, key_buffer_size, alg ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_mac_update( mbedtls_transparent_test_driver_mac_operation_t *operation, const uint8_t *input, size_t input_length ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_transparent_test_driver_mac_update( operation, input, input_length ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_mac_sign_finish( mbedtls_transparent_test_driver_mac_operation_t *operation, uint8_t *mac, size_t mac_size, size_t *mac_length ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_transparent_test_driver_mac_sign_finish( operation, mac, mac_size, mac_length ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_mac_verify_finish( mbedtls_transparent_test_driver_mac_operation_t *operation, const uint8_t *mac, size_t mac_length ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_transparent_test_driver_mac_verify_finish( operation, mac, mac_length ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_mac_abort( mbedtls_transparent_test_driver_mac_operation_t *operation ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_transparent_test_driver_mac_abort( operation ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_opaque_mac_compute( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *mac, size_t mac_size, size_t *mac_length ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_opaque_test_driver_mac_compute( attributes, key_buffer, key_buffer_size, alg, input, input_length, mac, mac_size, mac_length ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_opaque_mac_sign_setup( mbedtls_opaque_test_driver_mac_operation_t *operation, const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_opaque_test_driver_mac_sign_setup( operation, attributes, key_buffer, key_buffer_size, alg ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_opaque_mac_verify_setup( mbedtls_opaque_test_driver_mac_operation_t *operation, const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_opaque_test_driver_mac_verify_setup( operation, attributes, key_buffer, key_buffer_size, alg ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_opaque_mac_update( mbedtls_opaque_test_driver_mac_operation_t *operation, const uint8_t *input, size_t input_length ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_opaque_test_driver_mac_update( operation, input, input_length ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_opaque_mac_sign_finish( mbedtls_opaque_test_driver_mac_operation_t *operation, uint8_t *mac, size_t mac_size, size_t *mac_length ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_opaque_test_driver_mac_sign_finish( operation, mac, mac_size, mac_length ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_opaque_mac_verify_finish( mbedtls_opaque_test_driver_mac_operation_t *operation, const uint8_t *mac, size_t mac_length ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_opaque_test_driver_mac_verify_finish( operation, mac, mac_length ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } psa_status_t mbedtls_test_opaque_mac_abort( mbedtls_opaque_test_driver_mac_operation_t *operation ) { mbedtls_test_driver_mac_hooks.hits++; if( mbedtls_test_driver_mac_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_test_driver_mac_hooks.forced_status; } else { mbedtls_test_driver_mac_hooks.driver_status = mbedtls_opaque_test_driver_mac_abort( operation ); } return( mbedtls_test_driver_mac_hooks.driver_status ); } #endif /* MBEDTLS_PSA_CRYPTO_DRIVERS && PSA_CRYPTO_DRIVER_TEST */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/drivers/platform_builtin_keys.c
/** \file platform_builtin_keys.c * * \brief Test driver implementation of the builtin key support */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #include <psa/crypto.h> #include <psa/crypto_extra.h> #if defined(PSA_CRYPTO_DRIVER_TEST) #include <test/drivers/test_driver.h> #endif typedef struct { psa_key_id_t builtin_key_id; psa_key_lifetime_t lifetime; psa_drv_slot_number_t slot_number; } mbedtls_psa_builtin_key_description_t; static const mbedtls_psa_builtin_key_description_t builtin_keys[] = { #if defined(PSA_CRYPTO_DRIVER_TEST) /* For testing, assign the AES builtin key slot to the boundary values. * ECDSA can be exercised on key ID MBEDTLS_PSA_KEY_ID_BUILTIN_MIN + 1. */ { MBEDTLS_PSA_KEY_ID_BUILTIN_MIN - 1, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION( PSA_KEY_PERSISTENCE_READ_ONLY, PSA_CRYPTO_TEST_DRIVER_LOCATION ), PSA_CRYPTO_TEST_DRIVER_BUILTIN_AES_KEY_SLOT }, { MBEDTLS_PSA_KEY_ID_BUILTIN_MIN, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION( PSA_KEY_PERSISTENCE_READ_ONLY, PSA_CRYPTO_TEST_DRIVER_LOCATION ), PSA_CRYPTO_TEST_DRIVER_BUILTIN_AES_KEY_SLOT }, { MBEDTLS_PSA_KEY_ID_BUILTIN_MIN + 1, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION( PSA_KEY_PERSISTENCE_READ_ONLY, PSA_CRYPTO_TEST_DRIVER_LOCATION ), PSA_CRYPTO_TEST_DRIVER_BUILTIN_ECDSA_KEY_SLOT}, { MBEDTLS_PSA_KEY_ID_BUILTIN_MAX - 1, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION( PSA_KEY_PERSISTENCE_READ_ONLY, PSA_CRYPTO_TEST_DRIVER_LOCATION ), PSA_CRYPTO_TEST_DRIVER_BUILTIN_AES_KEY_SLOT}, { MBEDTLS_PSA_KEY_ID_BUILTIN_MAX, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION( PSA_KEY_PERSISTENCE_READ_ONLY, PSA_CRYPTO_TEST_DRIVER_LOCATION ), PSA_CRYPTO_TEST_DRIVER_BUILTIN_AES_KEY_SLOT}, { MBEDTLS_PSA_KEY_ID_BUILTIN_MAX + 1, PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION( PSA_KEY_PERSISTENCE_READ_ONLY, PSA_CRYPTO_TEST_DRIVER_LOCATION ), PSA_CRYPTO_TEST_DRIVER_BUILTIN_AES_KEY_SLOT}, #else {0, 0, 0} #endif }; psa_status_t mbedtls_psa_platform_get_builtin_key( mbedtls_svc_key_id_t key_id, psa_key_lifetime_t *lifetime, psa_drv_slot_number_t *slot_number ) { psa_key_id_t app_key_id = MBEDTLS_SVC_KEY_ID_GET_KEY_ID( key_id ); const mbedtls_psa_builtin_key_description_t *builtin_key; for( size_t i = 0; i < ( sizeof( builtin_keys ) / sizeof( builtin_keys[0] ) ); i++ ) { builtin_key = &builtin_keys[i]; if( builtin_key->builtin_key_id == app_key_id ) { *lifetime = builtin_key->lifetime; *slot_number = builtin_key->slot_number; return( PSA_SUCCESS ); } } return( PSA_ERROR_DOES_NOT_EXIST ); }
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/drivers/test_driver_cipher.c
/* * Test driver for cipher functions. * Currently only supports multi-part operations using AES-CTR. */ /* Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_PSA_CRYPTO_DRIVERS) && defined(PSA_CRYPTO_DRIVER_TEST) #include "psa/crypto.h" #include "psa_crypto_cipher.h" #include "psa_crypto_core.h" #include "mbedtls/cipher.h" #include "test/drivers/cipher.h" #include "test/random.h" #include <string.h> mbedtls_test_driver_cipher_hooks_t mbedtls_test_driver_cipher_hooks = MBEDTLS_TEST_DRIVER_CIPHER_INIT; psa_status_t mbedtls_test_transparent_cipher_encrypt( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *output, size_t output_size, size_t *output_length ) { mbedtls_test_driver_cipher_hooks.hits++; if( mbedtls_test_driver_cipher_hooks.forced_output != NULL ) { if( output_size < mbedtls_test_driver_cipher_hooks.forced_output_length ) return( PSA_ERROR_BUFFER_TOO_SMALL ); memcpy( output, mbedtls_test_driver_cipher_hooks.forced_output, mbedtls_test_driver_cipher_hooks.forced_output_length ); *output_length = mbedtls_test_driver_cipher_hooks.forced_output_length; return( mbedtls_test_driver_cipher_hooks.forced_status ); } if( mbedtls_test_driver_cipher_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_cipher_hooks.forced_status ); psa_generate_random( output, PSA_CIPHER_IV_LENGTH( attributes->core.type, alg ) ); return( mbedtls_transparent_test_driver_cipher_encrypt( attributes, key_buffer, key_buffer_size, alg, input, input_length, output, output_size, output_length ) ); } psa_status_t mbedtls_test_transparent_cipher_decrypt( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *output, size_t output_size, size_t *output_length ) { mbedtls_test_driver_cipher_hooks.hits++; if( mbedtls_test_driver_cipher_hooks.forced_output != NULL ) { if( output_size < mbedtls_test_driver_cipher_hooks.forced_output_length ) return( PSA_ERROR_BUFFER_TOO_SMALL ); memcpy( output, mbedtls_test_driver_cipher_hooks.forced_output, mbedtls_test_driver_cipher_hooks.forced_output_length ); *output_length = mbedtls_test_driver_cipher_hooks.forced_output_length; return( mbedtls_test_driver_cipher_hooks.forced_status ); } if( mbedtls_test_driver_cipher_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_cipher_hooks.forced_status ); return( mbedtls_transparent_test_driver_cipher_decrypt( attributes, key_buffer, key_buffer_size, alg, input, input_length, output, output_size, output_length ) ); } psa_status_t mbedtls_test_transparent_cipher_encrypt_setup( mbedtls_transparent_test_driver_cipher_operation_t *operation, const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, psa_algorithm_t alg) { mbedtls_test_driver_cipher_hooks.hits++; /* Wiping the entire struct here, instead of member-by-member. This is * useful for the test suite, since it gives a chance of catching memory * corruption errors should the core not have allocated (enough) memory for * our context struct. */ memset( operation, 0, sizeof( *operation ) ); if( mbedtls_test_driver_cipher_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_cipher_hooks.forced_status ); return ( mbedtls_transparent_test_driver_cipher_encrypt_setup( operation, attributes, key, key_length, alg ) ); } psa_status_t mbedtls_test_transparent_cipher_decrypt_setup( mbedtls_transparent_test_driver_cipher_operation_t *operation, const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, psa_algorithm_t alg) { mbedtls_test_driver_cipher_hooks.hits++; if( mbedtls_test_driver_cipher_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_cipher_hooks.forced_status ); return ( mbedtls_transparent_test_driver_cipher_decrypt_setup( operation, attributes, key, key_length, alg ) ); } psa_status_t mbedtls_test_transparent_cipher_abort( mbedtls_transparent_test_driver_cipher_operation_t *operation) { mbedtls_test_driver_cipher_hooks.hits++; if( operation->alg == 0 ) return( PSA_SUCCESS ); mbedtls_transparent_test_driver_cipher_abort( operation ); /* Wiping the entire struct here, instead of member-by-member. This is * useful for the test suite, since it gives a chance of catching memory * corruption errors should the core not have allocated (enough) memory for * our context struct. */ memset( operation, 0, sizeof( *operation ) ); return( mbedtls_test_driver_cipher_hooks.forced_status ); } psa_status_t mbedtls_test_transparent_cipher_set_iv( mbedtls_transparent_test_driver_cipher_operation_t *operation, const uint8_t *iv, size_t iv_length) { mbedtls_test_driver_cipher_hooks.hits++; if( mbedtls_test_driver_cipher_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_cipher_hooks.forced_status ); return( mbedtls_transparent_test_driver_cipher_set_iv( operation, iv, iv_length ) ); } psa_status_t mbedtls_test_transparent_cipher_update( mbedtls_transparent_test_driver_cipher_operation_t *operation, const uint8_t *input, size_t input_length, uint8_t *output, size_t output_size, size_t *output_length) { mbedtls_test_driver_cipher_hooks.hits++; if( mbedtls_test_driver_cipher_hooks.forced_output != NULL ) { if( output_size < mbedtls_test_driver_cipher_hooks.forced_output_length ) return PSA_ERROR_BUFFER_TOO_SMALL; memcpy( output, mbedtls_test_driver_cipher_hooks.forced_output, mbedtls_test_driver_cipher_hooks.forced_output_length ); *output_length = mbedtls_test_driver_cipher_hooks.forced_output_length; return( mbedtls_test_driver_cipher_hooks.forced_status ); } if( mbedtls_test_driver_cipher_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_cipher_hooks.forced_status ); return( mbedtls_transparent_test_driver_cipher_update( operation, input, input_length, output, output_size, output_length ) ); } psa_status_t mbedtls_test_transparent_cipher_finish( mbedtls_transparent_test_driver_cipher_operation_t *operation, uint8_t *output, size_t output_size, size_t *output_length) { mbedtls_test_driver_cipher_hooks.hits++; if( mbedtls_test_driver_cipher_hooks.forced_output != NULL ) { if( output_size < mbedtls_test_driver_cipher_hooks.forced_output_length ) return PSA_ERROR_BUFFER_TOO_SMALL; memcpy( output, mbedtls_test_driver_cipher_hooks.forced_output, mbedtls_test_driver_cipher_hooks.forced_output_length ); *output_length = mbedtls_test_driver_cipher_hooks.forced_output_length; return( mbedtls_test_driver_cipher_hooks.forced_status ); } if( mbedtls_test_driver_cipher_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_cipher_hooks.forced_status ); return( mbedtls_transparent_test_driver_cipher_finish( operation, output, output_size, output_length ) ); } /* * opaque versions, to do */ psa_status_t mbedtls_test_opaque_cipher_encrypt( const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *output, size_t output_size, size_t *output_length) { (void) attributes; (void) key; (void) key_length; (void) alg; (void) input; (void) input_length; (void) output; (void) output_size; (void) output_length; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_opaque_cipher_decrypt( const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *output, size_t output_size, size_t *output_length) { (void) attributes; (void) key; (void) key_length; (void) alg; (void) input; (void) input_length; (void) output; (void) output_size; (void) output_length; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_opaque_cipher_encrypt_setup( mbedtls_opaque_test_driver_cipher_operation_t *operation, const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, psa_algorithm_t alg) { (void) operation; (void) attributes; (void) key; (void) key_length; (void) alg; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_opaque_cipher_decrypt_setup( mbedtls_opaque_test_driver_cipher_operation_t *operation, const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, psa_algorithm_t alg) { (void) operation; (void) attributes; (void) key; (void) key_length; (void) alg; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_opaque_cipher_abort( mbedtls_opaque_test_driver_cipher_operation_t *operation ) { (void) operation; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_opaque_cipher_set_iv( mbedtls_opaque_test_driver_cipher_operation_t *operation, const uint8_t *iv, size_t iv_length) { (void) operation; (void) iv; (void) iv_length; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_opaque_cipher_update( mbedtls_opaque_test_driver_cipher_operation_t *operation, const uint8_t *input, size_t input_length, uint8_t *output, size_t output_size, size_t *output_length) { (void) operation; (void) input; (void) input_length; (void) output; (void) output_size; (void) output_length; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_opaque_cipher_finish( mbedtls_opaque_test_driver_cipher_operation_t *operation, uint8_t *output, size_t output_size, size_t *output_length) { (void) operation; (void) output; (void) output_size; (void) output_length; return( PSA_ERROR_NOT_SUPPORTED ); } #endif /* MBEDTLS_PSA_CRYPTO_DRIVERS && PSA_CRYPTO_DRIVER_TEST */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/drivers/test_driver_key_management.c
/* * Test driver for generating and verifying keys. * Currently only supports generating and verifying ECC keys. */ /* Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_PSA_CRYPTO_DRIVERS) && defined(PSA_CRYPTO_DRIVER_TEST) #include "psa/crypto.h" #include "psa_crypto_core.h" #include "psa_crypto_ecp.h" #include "psa_crypto_rsa.h" #include "mbedtls/ecp.h" #include "mbedtls/error.h" #include "test/drivers/key_management.h" #include "test/random.h" #include <string.h> mbedtls_test_driver_key_management_hooks_t mbedtls_test_driver_key_management_hooks = MBEDTLS_TEST_DRIVER_KEY_MANAGEMENT_INIT; const uint8_t mbedtls_test_driver_aes_key[16] = { 0x36, 0x77, 0x39, 0x7A, 0x24, 0x43, 0x26, 0x46, 0x29, 0x4A, 0x40, 0x4E, 0x63, 0x52, 0x66, 0x55 }; const uint8_t mbedtls_test_driver_ecdsa_key[32] = { 0xdc, 0x7d, 0x9d, 0x26, 0xd6, 0x7a, 0x4f, 0x63, 0x2c, 0x34, 0xc2, 0xdc, 0x0b, 0x69, 0x86, 0x18, 0x38, 0x82, 0xc2, 0x06, 0xdf, 0x04, 0xcd, 0xb7, 0xd6, 0x9a, 0xab, 0xe2, 0x8b, 0xe4, 0xf8, 0x1a }; const uint8_t mbedtls_test_driver_ecdsa_pubkey[65] = { 0x04, 0x85, 0xf6, 0x4d, 0x89, 0xf0, 0x0b, 0xe6, 0x6c, 0x88, 0xdd, 0x93, 0x7e, 0xfd, 0x6d, 0x7c, 0x44, 0x56, 0x48, 0xdc, 0xb7, 0x01, 0x15, 0x0b, 0x8a, 0x95, 0x09, 0x29, 0x58, 0x50, 0xf4, 0x1c, 0x19, 0x31, 0xe5, 0x71, 0xfb, 0x8f, 0x8c, 0x78, 0x31, 0x7a, 0x20, 0xb3, 0x80, 0xe8, 0x66, 0x58, 0x4b, 0xbc, 0x25, 0x16, 0xc3, 0xd2, 0x70, 0x2d, 0x79, 0x2f, 0x13, 0x1a, 0x92, 0x20, 0x95, 0xfd, 0x6c }; psa_status_t mbedtls_test_transparent_generate_key( const psa_key_attributes_t *attributes, uint8_t *key, size_t key_size, size_t *key_length ) { ++mbedtls_test_driver_key_management_hooks.hits; if( mbedtls_test_driver_key_management_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_key_management_hooks.forced_status ); if( mbedtls_test_driver_key_management_hooks.forced_output != NULL ) { if( mbedtls_test_driver_key_management_hooks.forced_output_length > key_size ) return( PSA_ERROR_BUFFER_TOO_SMALL ); memcpy( key, mbedtls_test_driver_key_management_hooks.forced_output, mbedtls_test_driver_key_management_hooks.forced_output_length ); *key_length = mbedtls_test_driver_key_management_hooks.forced_output_length; return( PSA_SUCCESS ); } /* Copied from psa_crypto.c */ #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) if ( PSA_KEY_TYPE_IS_ECC( psa_get_key_type( attributes ) ) && PSA_KEY_TYPE_IS_KEY_PAIR( psa_get_key_type( attributes ) ) ) { return( mbedtls_transparent_test_driver_ecp_generate_key( attributes, key, key_size, key_length ) ); } else #endif /* defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) */ #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR) if ( psa_get_key_type( attributes ) == PSA_KEY_TYPE_RSA_KEY_PAIR ) return( mbedtls_transparent_test_driver_rsa_generate_key( attributes, key, key_size, key_length ) ); else #endif /* defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR) */ { (void)attributes; return( PSA_ERROR_NOT_SUPPORTED ); } } psa_status_t mbedtls_test_opaque_generate_key( const psa_key_attributes_t *attributes, uint8_t *key, size_t key_size, size_t *key_length ) { (void) attributes; (void) key; (void) key_size; (void) key_length; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_transparent_import_key( const psa_key_attributes_t *attributes, const uint8_t *data, size_t data_length, uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length, size_t *bits) { ++mbedtls_test_driver_key_management_hooks.hits; if( mbedtls_test_driver_key_management_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_key_management_hooks.forced_status ); psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED; psa_key_type_t type = psa_get_key_type( attributes ); #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) || \ defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) if( PSA_KEY_TYPE_IS_ECC( type ) ) { status = mbedtls_transparent_test_driver_ecp_import_key( attributes, data, data_length, key_buffer, key_buffer_size, key_buffer_length, bits ); } else #endif #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR) || \ defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_PUBLIC_KEY) if( PSA_KEY_TYPE_IS_RSA( type ) ) { status = mbedtls_transparent_test_driver_rsa_import_key( attributes, data, data_length, key_buffer, key_buffer_size, key_buffer_length, bits ); } else #endif { status = PSA_ERROR_NOT_SUPPORTED; (void)data; (void)data_length; (void)key_buffer; (void)key_buffer_size; (void)key_buffer_length; (void)bits; (void)type; } return( status ); } psa_status_t mbedtls_test_opaque_export_key( const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, uint8_t *data, size_t data_size, size_t *data_length ) { if( key_length != sizeof( psa_drv_slot_number_t ) ) { /* Test driver does not support generic opaque key handling yet. */ return( PSA_ERROR_NOT_SUPPORTED ); } /* Assume this is a builtin key based on the key material length. */ psa_drv_slot_number_t slot_number = *( ( psa_drv_slot_number_t* ) key ); switch( slot_number ) { case PSA_CRYPTO_TEST_DRIVER_BUILTIN_ECDSA_KEY_SLOT: /* This is the ECDSA slot. Verify the key's attributes before * returning the private key. */ if( psa_get_key_type( attributes ) != PSA_KEY_TYPE_ECC_KEY_PAIR( PSA_ECC_FAMILY_SECP_R1 ) ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( psa_get_key_bits( attributes ) != 256 ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( psa_get_key_algorithm( attributes ) != PSA_ALG_ECDSA( PSA_ALG_ANY_HASH ) ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( ( psa_get_key_usage_flags( attributes ) & PSA_KEY_USAGE_EXPORT ) == 0 ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( data_size < sizeof( mbedtls_test_driver_ecdsa_key ) ) return( PSA_ERROR_BUFFER_TOO_SMALL ); memcpy( data, mbedtls_test_driver_ecdsa_key, sizeof( mbedtls_test_driver_ecdsa_key ) ); *data_length = sizeof( mbedtls_test_driver_ecdsa_key ); return( PSA_SUCCESS ); case PSA_CRYPTO_TEST_DRIVER_BUILTIN_AES_KEY_SLOT: /* This is the AES slot. Verify the key's attributes before * returning the key. */ if( psa_get_key_type( attributes ) != PSA_KEY_TYPE_AES ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( psa_get_key_bits( attributes ) != 128 ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( psa_get_key_algorithm( attributes ) != PSA_ALG_CTR ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( ( psa_get_key_usage_flags( attributes ) & PSA_KEY_USAGE_EXPORT ) == 0 ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( data_size < sizeof( mbedtls_test_driver_aes_key ) ) return( PSA_ERROR_BUFFER_TOO_SMALL ); memcpy( data, mbedtls_test_driver_aes_key, sizeof( mbedtls_test_driver_aes_key ) ); *data_length = sizeof( mbedtls_test_driver_aes_key ); return( PSA_SUCCESS ); default: return( PSA_ERROR_DOES_NOT_EXIST ); } } psa_status_t mbedtls_test_transparent_export_public_key( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, uint8_t *data, size_t data_size, size_t *data_length ) { ++mbedtls_test_driver_key_management_hooks.hits; if( mbedtls_test_driver_key_management_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_key_management_hooks.forced_status ); if( mbedtls_test_driver_key_management_hooks.forced_output != NULL ) { if( mbedtls_test_driver_key_management_hooks.forced_output_length > data_size ) return( PSA_ERROR_BUFFER_TOO_SMALL ); memcpy( data, mbedtls_test_driver_key_management_hooks.forced_output, mbedtls_test_driver_key_management_hooks.forced_output_length ); *data_length = mbedtls_test_driver_key_management_hooks.forced_output_length; return( PSA_SUCCESS ); } psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED; psa_key_type_t key_type = psa_get_key_type( attributes ); #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_KEY_PAIR) || \ defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_ECC_PUBLIC_KEY) if( PSA_KEY_TYPE_IS_ECC( key_type ) ) { status = mbedtls_transparent_test_driver_ecp_export_public_key( attributes, key_buffer, key_buffer_size, data, data_size, data_length ); } else #endif #if defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_KEY_PAIR) || \ defined(MBEDTLS_PSA_ACCEL_KEY_TYPE_RSA_PUBLIC_KEY) if( PSA_KEY_TYPE_IS_RSA( key_type ) ) { status = mbedtls_transparent_test_driver_rsa_export_public_key( attributes, key_buffer, key_buffer_size, data, data_size, data_length ); } else #endif { status = PSA_ERROR_NOT_SUPPORTED; (void)key_buffer; (void)key_buffer_size; (void)key_type; } return( status ); } psa_status_t mbedtls_test_opaque_export_public_key( const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, uint8_t *data, size_t data_size, size_t *data_length ) { if( key_length != sizeof( psa_drv_slot_number_t ) ) { /* Test driver does not support generic opaque key handling yet. */ return( PSA_ERROR_NOT_SUPPORTED ); } /* Assume this is a builtin key based on the key material length. */ psa_drv_slot_number_t slot_number = *( ( psa_drv_slot_number_t* ) key ); switch( slot_number ) { case PSA_CRYPTO_TEST_DRIVER_BUILTIN_ECDSA_KEY_SLOT: /* This is the ECDSA slot. Verify the key's attributes before * returning the public key. */ if( psa_get_key_type( attributes ) != PSA_KEY_TYPE_ECC_KEY_PAIR( PSA_ECC_FAMILY_SECP_R1 ) ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( psa_get_key_bits( attributes ) != 256 ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( psa_get_key_algorithm( attributes ) != PSA_ALG_ECDSA( PSA_ALG_ANY_HASH ) ) return( PSA_ERROR_CORRUPTION_DETECTED ); if( data_size < sizeof( mbedtls_test_driver_ecdsa_pubkey ) ) return( PSA_ERROR_BUFFER_TOO_SMALL ); memcpy( data, mbedtls_test_driver_ecdsa_pubkey, sizeof( mbedtls_test_driver_ecdsa_pubkey ) ); *data_length = sizeof( mbedtls_test_driver_ecdsa_pubkey ); return( PSA_SUCCESS ); default: return( PSA_ERROR_DOES_NOT_EXIST ); } } /* The opaque test driver exposes two built-in keys when builtin key support is * compiled in. * The key in slot #PSA_CRYPTO_TEST_DRIVER_BUILTIN_AES_KEY_SLOT is an AES-128 * key which allows CTR mode. * The key in slot #PSA_CRYPTO_TEST_DRIVER_BUILTIN_ECDSA_KEY_SLOT is a secp256r1 * private key which allows ECDSA sign & verify. * The key buffer format for these is the raw format of psa_drv_slot_number_t * (i.e. for an actual driver this would mean 'builtin_key_size' = * sizeof(psa_drv_slot_number_t)). */ psa_status_t mbedtls_test_opaque_get_builtin_key( psa_drv_slot_number_t slot_number, psa_key_attributes_t *attributes, uint8_t *key_buffer, size_t key_buffer_size, size_t *key_buffer_length ) { switch( slot_number ) { case PSA_CRYPTO_TEST_DRIVER_BUILTIN_AES_KEY_SLOT: psa_set_key_type( attributes, PSA_KEY_TYPE_AES ); psa_set_key_bits( attributes, 128 ); psa_set_key_usage_flags( attributes, PSA_KEY_USAGE_ENCRYPT | PSA_KEY_USAGE_DECRYPT | PSA_KEY_USAGE_EXPORT ); psa_set_key_algorithm( attributes, PSA_ALG_CTR ); if( key_buffer_size < sizeof( psa_drv_slot_number_t ) ) return( PSA_ERROR_BUFFER_TOO_SMALL ); *( (psa_drv_slot_number_t*) key_buffer ) = PSA_CRYPTO_TEST_DRIVER_BUILTIN_AES_KEY_SLOT; *key_buffer_length = sizeof( psa_drv_slot_number_t ); return( PSA_SUCCESS ); case PSA_CRYPTO_TEST_DRIVER_BUILTIN_ECDSA_KEY_SLOT: psa_set_key_type( attributes, PSA_KEY_TYPE_ECC_KEY_PAIR( PSA_ECC_FAMILY_SECP_R1 ) ); psa_set_key_bits( attributes, 256 ); psa_set_key_usage_flags( attributes, PSA_KEY_USAGE_SIGN_HASH | PSA_KEY_USAGE_VERIFY_HASH | PSA_KEY_USAGE_EXPORT ); psa_set_key_algorithm( attributes, PSA_ALG_ECDSA( PSA_ALG_ANY_HASH ) ); if( key_buffer_size < sizeof( psa_drv_slot_number_t ) ) return( PSA_ERROR_BUFFER_TOO_SMALL ); *( (psa_drv_slot_number_t*) key_buffer ) = PSA_CRYPTO_TEST_DRIVER_BUILTIN_ECDSA_KEY_SLOT; *key_buffer_length = sizeof( psa_drv_slot_number_t ); return( PSA_SUCCESS ); default: return( PSA_ERROR_DOES_NOT_EXIST ); } } #endif /* MBEDTLS_PSA_CRYPTO_DRIVERS && PSA_CRYPTO_DRIVER_TEST */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/drivers/test_driver_signature.c
/* * Test driver for signature functions. * Currently supports signing and verifying precalculated hashes, using * only deterministic ECDSA on curves secp256r1, secp384r1 and secp521r1. */ /* Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_PSA_CRYPTO_DRIVERS) && defined(PSA_CRYPTO_DRIVER_TEST) #include "psa/crypto.h" #include "psa_crypto_core.h" #include "psa_crypto_ecp.h" #include "psa_crypto_hash.h" #include "psa_crypto_rsa.h" #include "mbedtls/ecp.h" #include "test/drivers/signature.h" #include "mbedtls/md.h" #include "mbedtls/ecdsa.h" #include "test/random.h" #include <string.h> mbedtls_test_driver_signature_hooks_t mbedtls_test_driver_signature_sign_hooks = MBEDTLS_TEST_DRIVER_SIGNATURE_INIT; mbedtls_test_driver_signature_hooks_t mbedtls_test_driver_signature_verify_hooks = MBEDTLS_TEST_DRIVER_SIGNATURE_INIT; psa_status_t sign_hash( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *hash, size_t hash_length, uint8_t *signature, size_t signature_size, size_t *signature_length ) { #if defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_SIGN) || \ defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PSS) if( attributes->core.type == PSA_KEY_TYPE_RSA_KEY_PAIR ) { return( mbedtls_transparent_test_driver_rsa_sign_hash( attributes, key_buffer, key_buffer_size, alg, hash, hash_length, signature, signature_size, signature_length ) ); } else #endif /* defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_SIGN) || * defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PSS) */ #if defined(MBEDTLS_PSA_ACCEL_ALG_ECDSA) || \ defined(MBEDTLS_PSA_ACCEL_ALG_DETERMINISTIC_ECDSA) if( PSA_KEY_TYPE_IS_ECC( attributes->core.type ) ) { if( #if defined(MBEDTLS_PSA_ACCEL_ALG_DETERMINISTIC_ECDSA) PSA_ALG_IS_ECDSA( alg ) #else PSA_ALG_IS_RANDOMIZED_ECDSA( alg ) #endif ) { return( mbedtls_transparent_test_driver_ecdsa_sign_hash( attributes, key_buffer, key_buffer_size, alg, hash, hash_length, signature, signature_size, signature_length ) ); } else { return( PSA_ERROR_INVALID_ARGUMENT ); } } else #endif /* defined(MBEDTLS_PSA_ACCEL_ALG_ECDSA) || * defined(MBEDTLS_PSA_ACCEL_ALG_DETERMINISTIC_ECDSA) */ { (void)attributes; (void)key_buffer; (void)key_buffer_size; (void)alg; (void)hash; (void)hash_length; (void)signature; (void)signature_size; (void)signature_length; return( PSA_ERROR_NOT_SUPPORTED ); } } psa_status_t verify_hash( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *hash, size_t hash_length, const uint8_t *signature, size_t signature_length ) { #if defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_SIGN) || \ defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PSS) if( PSA_KEY_TYPE_IS_RSA( attributes->core.type ) ) { return( mbedtls_transparent_test_driver_rsa_verify_hash( attributes, key_buffer, key_buffer_size, alg, hash, hash_length, signature, signature_length ) ); } else #endif /* defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PKCS1V15_SIGN) || * defined(MBEDTLS_PSA_ACCEL_ALG_RSA_PSS) */ #if defined(MBEDTLS_PSA_ACCEL_ALG_ECDSA) || \ defined(MBEDTLS_PSA_ACCEL_ALG_DETERMINISTIC_ECDSA) if( PSA_KEY_TYPE_IS_ECC( attributes->core.type ) ) { if( PSA_ALG_IS_ECDSA( alg ) ) { return( mbedtls_transparent_test_driver_ecdsa_verify_hash( attributes, key_buffer, key_buffer_size, alg, hash, hash_length, signature, signature_length ) ); } else { return( PSA_ERROR_INVALID_ARGUMENT ); } } else #endif /* defined(MBEDTLS_PSA_ACCEL_ALG_ECDSA) || * defined(MBEDTLS_PSA_ACCEL_ALG_DETERMINISTIC_ECDSA) */ { (void)attributes; (void)key_buffer; (void)key_buffer_size; (void)alg; (void)hash; (void)hash_length; (void)signature; (void)signature_length; return( PSA_ERROR_NOT_SUPPORTED ); } } psa_status_t mbedtls_test_transparent_signature_sign_message( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *signature, size_t signature_size, size_t *signature_length ) { psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED; size_t hash_length; uint8_t hash[PSA_HASH_MAX_SIZE]; ++mbedtls_test_driver_signature_sign_hooks.hits; if( mbedtls_test_driver_signature_sign_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_signature_sign_hooks.forced_status ); if( mbedtls_test_driver_signature_sign_hooks.forced_output != NULL ) { if( mbedtls_test_driver_signature_sign_hooks.forced_output_length > signature_size ) return( PSA_ERROR_BUFFER_TOO_SMALL ); memcpy( signature, mbedtls_test_driver_signature_sign_hooks.forced_output, mbedtls_test_driver_signature_sign_hooks.forced_output_length ); *signature_length = mbedtls_test_driver_signature_sign_hooks.forced_output_length; return( PSA_SUCCESS ); } status = mbedtls_transparent_test_driver_hash_compute( PSA_ALG_SIGN_GET_HASH( alg ), input, input_length, hash, sizeof( hash ), &hash_length ); if( status != PSA_SUCCESS ) return status; return sign_hash( attributes, key_buffer, key_buffer_size, alg, hash, hash_length, signature, signature_size, signature_length ); } psa_status_t mbedtls_test_opaque_signature_sign_message( const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *signature, size_t signature_size, size_t *signature_length ) { (void) attributes; (void) key; (void) key_length; (void) alg; (void) input; (void) input_length; (void) signature; (void) signature_size; (void) signature_length; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_transparent_signature_verify_message( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *input, size_t input_length, const uint8_t *signature, size_t signature_length ) { psa_status_t status = PSA_ERROR_CORRUPTION_DETECTED; size_t hash_length; uint8_t hash[PSA_HASH_MAX_SIZE]; ++mbedtls_test_driver_signature_verify_hooks.hits; if( mbedtls_test_driver_signature_verify_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_signature_verify_hooks.forced_status ); status = mbedtls_transparent_test_driver_hash_compute( PSA_ALG_SIGN_GET_HASH( alg ), input, input_length, hash, sizeof( hash ), &hash_length ); if( status != PSA_SUCCESS ) return status; return verify_hash( attributes, key_buffer, key_buffer_size, alg, hash, hash_length, signature, signature_length ); } psa_status_t mbedtls_test_opaque_signature_verify_message( const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, psa_algorithm_t alg, const uint8_t *input, size_t input_length, const uint8_t *signature, size_t signature_length ) { (void) attributes; (void) key; (void) key_length; (void) alg; (void) input; (void) input_length; (void) signature; (void) signature_length; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_transparent_signature_sign_hash( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *hash, size_t hash_length, uint8_t *signature, size_t signature_size, size_t *signature_length ) { ++mbedtls_test_driver_signature_sign_hooks.hits; if( mbedtls_test_driver_signature_sign_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_signature_sign_hooks.forced_status ); if( mbedtls_test_driver_signature_sign_hooks.forced_output != NULL ) { if( mbedtls_test_driver_signature_sign_hooks.forced_output_length > signature_size ) return( PSA_ERROR_BUFFER_TOO_SMALL ); memcpy( signature, mbedtls_test_driver_signature_sign_hooks.forced_output, mbedtls_test_driver_signature_sign_hooks.forced_output_length ); *signature_length = mbedtls_test_driver_signature_sign_hooks.forced_output_length; return( PSA_SUCCESS ); } return sign_hash( attributes, key_buffer, key_buffer_size, alg, hash, hash_length, signature, signature_size, signature_length ); } psa_status_t mbedtls_test_opaque_signature_sign_hash( const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, psa_algorithm_t alg, const uint8_t *hash, size_t hash_length, uint8_t *signature, size_t signature_size, size_t *signature_length ) { (void) attributes; (void) key; (void) key_length; (void) alg; (void) hash; (void) hash_length; (void) signature; (void) signature_size; (void) signature_length; return( PSA_ERROR_NOT_SUPPORTED ); } psa_status_t mbedtls_test_transparent_signature_verify_hash( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *hash, size_t hash_length, const uint8_t *signature, size_t signature_length ) { ++mbedtls_test_driver_signature_verify_hooks.hits; if( mbedtls_test_driver_signature_verify_hooks.forced_status != PSA_SUCCESS ) return( mbedtls_test_driver_signature_verify_hooks.forced_status ); return verify_hash( attributes, key_buffer, key_buffer_size, alg, hash, hash_length, signature, signature_length ); } psa_status_t mbedtls_test_opaque_signature_verify_hash( const psa_key_attributes_t *attributes, const uint8_t *key, size_t key_length, psa_algorithm_t alg, const uint8_t *hash, size_t hash_length, const uint8_t *signature, size_t signature_length ) { (void) attributes; (void) key; (void) key_length; (void) alg; (void) hash; (void) hash_length; (void) signature; (void) signature_length; return( PSA_ERROR_NOT_SUPPORTED ); } #endif /* MBEDTLS_PSA_CRYPTO_DRIVERS && PSA_CRYPTO_DRIVER_TEST */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/drivers/hash.c
/* * Test driver for hash entry points. */ /* Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_PSA_CRYPTO_DRIVERS) && defined(PSA_CRYPTO_DRIVER_TEST) #include "psa_crypto_hash.h" #include "test/drivers/hash.h" mbedtls_test_driver_hash_hooks_t mbedtls_test_driver_hash_hooks = MBEDTLS_TEST_DRIVER_HASH_INIT; psa_status_t mbedtls_test_transparent_hash_compute( psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *hash, size_t hash_size, size_t *hash_length ) { mbedtls_test_driver_hash_hooks.hits++; if( mbedtls_test_driver_hash_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_test_driver_hash_hooks.forced_status; } else { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_transparent_test_driver_hash_compute( alg, input, input_length, hash, hash_size, hash_length ); } return( mbedtls_test_driver_hash_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_hash_setup( mbedtls_transparent_test_driver_hash_operation_t *operation, psa_algorithm_t alg ) { mbedtls_test_driver_hash_hooks.hits++; if( mbedtls_test_driver_hash_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_test_driver_hash_hooks.forced_status; } else { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_transparent_test_driver_hash_setup( operation, alg ); } return( mbedtls_test_driver_hash_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_hash_clone( const mbedtls_transparent_test_driver_hash_operation_t *source_operation, mbedtls_transparent_test_driver_hash_operation_t *target_operation ) { mbedtls_test_driver_hash_hooks.hits++; if( mbedtls_test_driver_hash_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_test_driver_hash_hooks.forced_status; } else { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_transparent_test_driver_hash_clone( source_operation, target_operation ); } return( mbedtls_test_driver_hash_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_hash_update( mbedtls_transparent_test_driver_hash_operation_t *operation, const uint8_t *input, size_t input_length ) { mbedtls_test_driver_hash_hooks.hits++; if( mbedtls_test_driver_hash_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_test_driver_hash_hooks.forced_status; } else { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_transparent_test_driver_hash_update( operation, input, input_length ); } return( mbedtls_test_driver_hash_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_hash_finish( mbedtls_transparent_test_driver_hash_operation_t *operation, uint8_t *hash, size_t hash_size, size_t *hash_length ) { mbedtls_test_driver_hash_hooks.hits++; if( mbedtls_test_driver_hash_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_test_driver_hash_hooks.forced_status; } else { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_transparent_test_driver_hash_finish( operation, hash, hash_size, hash_length ); } return( mbedtls_test_driver_hash_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_hash_abort( mbedtls_transparent_test_driver_hash_operation_t *operation ) { mbedtls_test_driver_hash_hooks.hits++; if( mbedtls_test_driver_hash_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_test_driver_hash_hooks.forced_status; } else { mbedtls_test_driver_hash_hooks.driver_status = mbedtls_transparent_test_driver_hash_abort( operation ); } return( mbedtls_test_driver_hash_hooks.driver_status ); } #endif /* MBEDTLS_PSA_CRYPTO_DRIVERS && PSA_CRYPTO_DRIVER_TEST */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/tests/src/drivers/test_driver_aead.c
/* * Test driver for AEAD entry points. */ /* Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_PSA_CRYPTO_DRIVERS) && defined(PSA_CRYPTO_DRIVER_TEST) #include "psa_crypto_aead.h" #include "test/drivers/aead.h" mbedtls_test_driver_aead_hooks_t mbedtls_test_driver_aead_hooks = MBEDTLS_TEST_DRIVER_AEAD_INIT; psa_status_t mbedtls_test_transparent_aead_encrypt( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *nonce, size_t nonce_length, const uint8_t *additional_data, size_t additional_data_length, const uint8_t *plaintext, size_t plaintext_length, uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length ) { mbedtls_test_driver_aead_hooks.hits++; if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_aead_hooks.driver_status = mbedtls_test_driver_aead_hooks.forced_status; } else { mbedtls_test_driver_aead_hooks.driver_status = mbedtls_psa_aead_encrypt( attributes, key_buffer, key_buffer_size, alg, nonce, nonce_length, additional_data, additional_data_length, plaintext, plaintext_length, ciphertext, ciphertext_size, ciphertext_length ); } return( mbedtls_test_driver_aead_hooks.driver_status ); } psa_status_t mbedtls_test_transparent_aead_decrypt( const psa_key_attributes_t *attributes, const uint8_t *key_buffer, size_t key_buffer_size, psa_algorithm_t alg, const uint8_t *nonce, size_t nonce_length, const uint8_t *additional_data, size_t additional_data_length, const uint8_t *ciphertext, size_t ciphertext_length, uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length ) { mbedtls_test_driver_aead_hooks.hits++; if( mbedtls_test_driver_aead_hooks.forced_status != PSA_SUCCESS ) { mbedtls_test_driver_aead_hooks.driver_status = mbedtls_test_driver_aead_hooks.forced_status; } else { mbedtls_test_driver_aead_hooks.driver_status = mbedtls_psa_aead_decrypt( attributes, key_buffer, key_buffer_size, alg, nonce, nonce_length, additional_data, additional_data_length, ciphertext, ciphertext_length, plaintext, plaintext_size, plaintext_length ); } return( mbedtls_test_driver_aead_hooks.driver_status ); } #endif /* MBEDTLS_PSA_CRYPTO_DRIVERS && PSA_CRYPTO_DRIVER_TEST */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/configs/config-suite-b.h
/** * \file config-suite-b.h * * \brief Minimal configuration for TLS NSA Suite B Profile (RFC 6460) */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Minimal configuration for TLS NSA Suite B Profile (RFC 6460) * * Distinguishing features: * - no RSA or classic DH, fully based on ECC * - optimized for low RAM usage * * Possible improvements: * - if 128-bit security is enough, disable secp384r1 and SHA-512 * - use embedded certs in DER format and disable PEM_PARSE_C and BASE64_C * * See README.txt for usage instructions. */ #ifndef MBEDTLS_CONFIG_H #define MBEDTLS_CONFIG_H /* System support */ #define MBEDTLS_HAVE_ASM #define MBEDTLS_HAVE_TIME /* mbed TLS feature support */ #define MBEDTLS_ECP_DP_SECP256R1_ENABLED #define MBEDTLS_ECP_DP_SECP384R1_ENABLED #define MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED #define MBEDTLS_SSL_PROTO_TLS1_2 /* mbed TLS modules */ #define MBEDTLS_AES_C #define MBEDTLS_ASN1_PARSE_C #define MBEDTLS_ASN1_WRITE_C #define MBEDTLS_BIGNUM_C #define MBEDTLS_CIPHER_C #define MBEDTLS_CTR_DRBG_C #define MBEDTLS_ECDH_C #define MBEDTLS_ECDSA_C #define MBEDTLS_ECP_C #define MBEDTLS_ENTROPY_C #define MBEDTLS_GCM_C #define MBEDTLS_MD_C #define MBEDTLS_NET_C #define MBEDTLS_OID_C #define MBEDTLS_PK_C #define MBEDTLS_PK_PARSE_C #define MBEDTLS_SHA256_C #define MBEDTLS_SHA512_C #define MBEDTLS_SSL_CLI_C #define MBEDTLS_SSL_SRV_C #define MBEDTLS_SSL_TLS_C #define MBEDTLS_X509_CRT_PARSE_C #define MBEDTLS_X509_USE_C /* For test certificates */ #define MBEDTLS_BASE64_C #define MBEDTLS_CERTS_C #define MBEDTLS_PEM_PARSE_C /* Save RAM at the expense of ROM */ #define MBEDTLS_AES_ROM_TABLES /* Save RAM by adjusting to our exact needs */ #define MBEDTLS_MPI_MAX_SIZE 48 // 48 bytes for a 384-bit elliptic curve /* Save RAM at the expense of speed, see ecp.h */ #define MBEDTLS_ECP_WINDOW_SIZE 2 #define MBEDTLS_ECP_FIXED_POINT_OPTIM 0 /* Significant speed benefit at the expense of some ROM */ #define MBEDTLS_ECP_NIST_OPTIM /* * You should adjust this to the exact number of sources you're using: default * is the "mbedtls_platform_entropy_poll" source, but you may want to add other ones. * Minimum is 2 for the entropy test suite. */ #define MBEDTLS_ENTROPY_MAX_SOURCES 2 /* Save ROM and a few bytes of RAM by specifying our own ciphersuite list */ #define MBEDTLS_SSL_CIPHERSUITES \ MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_256_GCM_SHA384, \ MBEDTLS_TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256 /* * Save RAM at the expense of interoperability: do this only if you control * both ends of the connection! (See coments in "mbedtls/ssl.h".) * The minimum size here depends on the certificate chain used as well as the * typical size of records. */ #define MBEDTLS_SSL_MAX_CONTENT_LEN 1024 #include "mbedtls/check_config.h" #endif /* MBEDTLS_CONFIG_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/configs/config-symmetric-only.h
/** * \file config-symmetric-only.h * * \brief Configuration without any asymmetric cryptography. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_CONFIG_H #define MBEDTLS_CONFIG_H /* System support */ //#define MBEDTLS_HAVE_ASM #define MBEDTLS_HAVE_TIME #define MBEDTLS_HAVE_TIME_DATE /* Mbed Crypto feature support */ #define MBEDTLS_CIPHER_MODE_CBC #define MBEDTLS_CIPHER_MODE_CFB #define MBEDTLS_CIPHER_MODE_CTR #define MBEDTLS_CIPHER_MODE_OFB #define MBEDTLS_CIPHER_MODE_XTS #define MBEDTLS_CIPHER_PADDING_PKCS7 #define MBEDTLS_CIPHER_PADDING_ONE_AND_ZEROS #define MBEDTLS_CIPHER_PADDING_ZEROS_AND_LEN #define MBEDTLS_CIPHER_PADDING_ZEROS #define MBEDTLS_ERROR_STRERROR_DUMMY #define MBEDTLS_FS_IO #define MBEDTLS_ENTROPY_NV_SEED #define MBEDTLS_SELF_TEST #define MBEDTLS_USE_PSA_CRYPTO #define MBEDTLS_VERSION_FEATURES /* Mbed Crypto modules */ #define MBEDTLS_AES_C #define MBEDTLS_ARC4_C #define MBEDTLS_ASN1_PARSE_C #define MBEDTLS_ASN1_WRITE_C #define MBEDTLS_BASE64_C #define MBEDTLS_BLOWFISH_C #define MBEDTLS_CAMELLIA_C #define MBEDTLS_ARIA_C #define MBEDTLS_CCM_C #define MBEDTLS_CHACHA20_C #define MBEDTLS_CHACHAPOLY_C #define MBEDTLS_CIPHER_C #define MBEDTLS_CMAC_C #define MBEDTLS_CTR_DRBG_C #define MBEDTLS_DES_C #define MBEDTLS_ENTROPY_C #define MBEDTLS_ERROR_C #define MBEDTLS_GCM_C //#define MBEDTLS_HAVEGE_C #define MBEDTLS_HKDF_C #define MBEDTLS_HMAC_DRBG_C #define MBEDTLS_NIST_KW_C #define MBEDTLS_MD_C #define MBEDTLS_MD2_C #define MBEDTLS_MD4_C #define MBEDTLS_MD5_C #define MBEDTLS_OID_C #define MBEDTLS_PEM_PARSE_C #define MBEDTLS_PEM_WRITE_C #define MBEDTLS_PKCS5_C #define MBEDTLS_PKCS12_C #define MBEDTLS_PLATFORM_C #define MBEDTLS_POLY1305_C #define MBEDTLS_PSA_CRYPTO_C #define MBEDTLS_PSA_CRYPTO_SE_C #define MBEDTLS_PSA_CRYPTO_STORAGE_C #define MBEDTLS_PSA_ITS_FILE_C #define MBEDTLS_RIPEMD160_C #define MBEDTLS_SHA1_C #define MBEDTLS_SHA256_C #define MBEDTLS_SHA512_C //#define MBEDTLS_THREADING_C #define MBEDTLS_TIMING_C #define MBEDTLS_VERSION_C #define MBEDTLS_XTEA_C #include "mbedtls/config_psa.h" #include "check_config.h" #endif /* MBEDTLS_CONFIG_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/configs/config-thread.h
/** * \file config-thread.h * * \brief Minimal configuration for using TLS as part of Thread */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Minimal configuration for using TLS a part of Thread * http://threadgroup.org/ * * Distinguishing features: * - no RSA or classic DH, fully based on ECC * - no X.509 * - support for experimental EC J-PAKE key exchange * * See README.txt for usage instructions. */ #ifndef MBEDTLS_CONFIG_H #define MBEDTLS_CONFIG_H /* System support */ #define MBEDTLS_HAVE_ASM /* mbed TLS feature support */ #define MBEDTLS_AES_ROM_TABLES #define MBEDTLS_ECP_DP_SECP256R1_ENABLED #define MBEDTLS_ECP_NIST_OPTIM #define MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED #define MBEDTLS_SSL_MAX_FRAGMENT_LENGTH #define MBEDTLS_SSL_PROTO_TLS1_2 #define MBEDTLS_SSL_PROTO_DTLS #define MBEDTLS_SSL_DTLS_ANTI_REPLAY #define MBEDTLS_SSL_DTLS_HELLO_VERIFY #define MBEDTLS_SSL_EXPORT_KEYS /* mbed TLS modules */ #define MBEDTLS_AES_C #define MBEDTLS_ASN1_PARSE_C #define MBEDTLS_ASN1_WRITE_C #define MBEDTLS_BIGNUM_C #define MBEDTLS_CCM_C #define MBEDTLS_CIPHER_C #define MBEDTLS_CTR_DRBG_C #define MBEDTLS_CMAC_C #define MBEDTLS_ECJPAKE_C #define MBEDTLS_ECP_C #define MBEDTLS_ENTROPY_C #define MBEDTLS_HMAC_DRBG_C #define MBEDTLS_MD_C #define MBEDTLS_OID_C #define MBEDTLS_PK_C #define MBEDTLS_PK_PARSE_C #define MBEDTLS_SHA256_C #define MBEDTLS_SSL_COOKIE_C #define MBEDTLS_SSL_CLI_C #define MBEDTLS_SSL_SRV_C #define MBEDTLS_SSL_TLS_C /* For tests using ssl-opt.sh */ #define MBEDTLS_NET_C #define MBEDTLS_TIMING_C /* Save RAM at the expense of ROM */ #define MBEDTLS_AES_ROM_TABLES /* Save RAM by adjusting to our exact needs */ #define MBEDTLS_MPI_MAX_SIZE 32 // 32 bytes for a 256-bit elliptic curve /* Save ROM and a few bytes of RAM by specifying our own ciphersuite list */ #define MBEDTLS_SSL_CIPHERSUITES MBEDTLS_TLS_ECJPAKE_WITH_AES_128_CCM_8 #include "mbedtls/check_config.h" #endif /* MBEDTLS_CONFIG_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/configs/config-mini-tls1_1.h
/** * \file config-mini-tls1_1.h * * \brief Minimal configuration for TLS 1.1 (RFC 4346) */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Minimal configuration for TLS 1.1 (RFC 4346), implementing only the * required ciphersuite: MBEDTLS_TLS_RSA_WITH_3DES_EDE_CBC_SHA * * See README.txt for usage instructions. */ #ifndef MBEDTLS_CONFIG_H #define MBEDTLS_CONFIG_H /* System support */ #define MBEDTLS_HAVE_ASM #define MBEDTLS_HAVE_TIME /* mbed TLS feature support */ #define MBEDTLS_CIPHER_MODE_CBC #define MBEDTLS_PKCS1_V15 #define MBEDTLS_KEY_EXCHANGE_RSA_ENABLED #define MBEDTLS_SSL_PROTO_TLS1_1 /* mbed TLS modules */ #define MBEDTLS_AES_C #define MBEDTLS_ASN1_PARSE_C #define MBEDTLS_ASN1_WRITE_C #define MBEDTLS_BIGNUM_C #define MBEDTLS_CIPHER_C #define MBEDTLS_CTR_DRBG_C #define MBEDTLS_DES_C #define MBEDTLS_ENTROPY_C #define MBEDTLS_MD_C #define MBEDTLS_MD5_C #define MBEDTLS_NET_C #define MBEDTLS_OID_C #define MBEDTLS_PK_C #define MBEDTLS_PK_PARSE_C #define MBEDTLS_RSA_C #define MBEDTLS_SHA1_C #define MBEDTLS_SHA256_C #define MBEDTLS_SSL_CLI_C #define MBEDTLS_SSL_SRV_C #define MBEDTLS_SSL_TLS_C #define MBEDTLS_X509_CRT_PARSE_C #define MBEDTLS_X509_USE_C /* For test certificates */ #define MBEDTLS_BASE64_C #define MBEDTLS_CERTS_C #define MBEDTLS_PEM_PARSE_C /* For testing with compat.sh */ #define MBEDTLS_FS_IO #include "mbedtls/check_config.h" #endif /* MBEDTLS_CONFIG_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/configs/README.txt
This directory contains example configuration files. The examples are generally focused on a particular usage case (eg, support for a restricted number of ciphersuites) and aim at minimizing resource usage for this target. They can be used as a basis for custom configurations. These files are complete replacements for the default config.h. To use one of them, you can pick one of the following methods: 1. Replace the default file include/mbedtls/config.h with the chosen one. (Depending on your compiler, you may need to adjust the line with #include "mbedtls/check_config.h" then.) 2. Define MBEDTLS_CONFIG_FILE and adjust the include path accordingly. For example, using make: CFLAGS="-I$PWD/configs -DMBEDTLS_CONFIG_FILE='<foo.h>'" make Or, using cmake: find . -iname '*cmake*' -not -name CMakeLists.txt -exec rm -rf {} + CFLAGS="-I$PWD/configs -DMBEDTLS_CONFIG_FILE='<foo.h>'" cmake . make Note that the second method also works if you want to keep your custom configuration file outside the mbed TLS tree.
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/configs/config-ccm-psk-tls1_2.h
/** * \file config-ccm-psk-tls1_2.h * * \brief Minimal configuration for TLS 1.2 with PSK and AES-CCM ciphersuites */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Minimal configuration for TLS 1.2 with PSK and AES-CCM ciphersuites * Distinguishing features: * - no bignum, no PK, no X509 * - fully modern and secure (provided the pre-shared keys have high entropy) * - very low record overhead with CCM-8 * - optimized for low RAM usage * * See README.txt for usage instructions. */ #ifndef MBEDTLS_CONFIG_H #define MBEDTLS_CONFIG_H /* System support */ //#define MBEDTLS_HAVE_TIME /* Optionally used in Hello messages */ /* Other MBEDTLS_HAVE_XXX flags irrelevant for this configuration */ /* mbed TLS feature support */ #define MBEDTLS_KEY_EXCHANGE_PSK_ENABLED #define MBEDTLS_SSL_PROTO_TLS1_2 /* mbed TLS modules */ #define MBEDTLS_AES_C #define MBEDTLS_CCM_C #define MBEDTLS_CIPHER_C #define MBEDTLS_CTR_DRBG_C #define MBEDTLS_ENTROPY_C #define MBEDTLS_MD_C #define MBEDTLS_NET_C #define MBEDTLS_SHA256_C #define MBEDTLS_SSL_CLI_C #define MBEDTLS_SSL_SRV_C #define MBEDTLS_SSL_TLS_C /* Save RAM at the expense of ROM */ #define MBEDTLS_AES_ROM_TABLES /* Save some RAM by adjusting to your exact needs */ #define MBEDTLS_PSK_MAX_LEN 16 /* 128-bits keys are generally enough */ /* * You should adjust this to the exact number of sources you're using: default * is the "platform_entropy_poll" source, but you may want to add other ones * Minimum is 2 for the entropy test suite. */ #define MBEDTLS_ENTROPY_MAX_SOURCES 2 /* * Use only CCM_8 ciphersuites, and * save ROM and a few bytes of RAM by specifying our own ciphersuite list */ #define MBEDTLS_SSL_CIPHERSUITES \ MBEDTLS_TLS_PSK_WITH_AES_256_CCM_8, \ MBEDTLS_TLS_PSK_WITH_AES_128_CCM_8 /* * Save RAM at the expense of interoperability: do this only if you control * both ends of the connection! (See comments in "mbedtls/ssl.h".) * The optimal size here depends on the typical size of records. */ #define MBEDTLS_SSL_MAX_CONTENT_LEN 1024 #include "mbedtls/check_config.h" #endif /* MBEDTLS_CONFIG_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/configs/config-no-entropy.h
/** * \file config-no-entropy.h * * \brief Minimal configuration of features that do not require an entropy source */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /* * Minimal configuration of features that do not require an entropy source * Distinguishing reatures: * - no entropy module * - no TLS protocol implementation available due to absence of an entropy * source * * See README.txt for usage instructions. */ #ifndef MBEDTLS_CONFIG_H #define MBEDTLS_CONFIG_H /* System support */ #define MBEDTLS_HAVE_ASM #define MBEDTLS_HAVE_TIME /* mbed TLS feature support */ #define MBEDTLS_CIPHER_MODE_CBC #define MBEDTLS_CIPHER_PADDING_PKCS7 #define MBEDTLS_REMOVE_ARC4_CIPHERSUITES #define MBEDTLS_ECP_DP_SECP256R1_ENABLED #define MBEDTLS_ECP_DP_SECP384R1_ENABLED #define MBEDTLS_ECP_DP_CURVE25519_ENABLED #define MBEDTLS_ECP_NIST_OPTIM #define MBEDTLS_ECDSA_DETERMINISTIC #define MBEDTLS_PK_RSA_ALT_SUPPORT #define MBEDTLS_PKCS1_V15 #define MBEDTLS_PKCS1_V21 #define MBEDTLS_SELF_TEST #define MBEDTLS_VERSION_FEATURES #define MBEDTLS_X509_CHECK_KEY_USAGE #define MBEDTLS_X509_CHECK_EXTENDED_KEY_USAGE /* mbed TLS modules */ #define MBEDTLS_AES_C #define MBEDTLS_ASN1_PARSE_C #define MBEDTLS_ASN1_WRITE_C #define MBEDTLS_BASE64_C #define MBEDTLS_BIGNUM_C #define MBEDTLS_CCM_C #define MBEDTLS_CIPHER_C #define MBEDTLS_ECDSA_C #define MBEDTLS_ECP_C #define MBEDTLS_ERROR_C #define MBEDTLS_GCM_C #define MBEDTLS_HMAC_DRBG_C #define MBEDTLS_MD_C #define MBEDTLS_OID_C #define MBEDTLS_PEM_PARSE_C #define MBEDTLS_PK_C #define MBEDTLS_PK_PARSE_C #define MBEDTLS_PK_WRITE_C #define MBEDTLS_PLATFORM_C #define MBEDTLS_RSA_C #define MBEDTLS_SHA256_C #define MBEDTLS_SHA512_C #define MBEDTLS_VERSION_C #define MBEDTLS_X509_USE_C #define MBEDTLS_X509_CRT_PARSE_C #define MBEDTLS_X509_CRL_PARSE_C //#define MBEDTLS_CMAC_C /* Miscellaneous options */ #define MBEDTLS_AES_ROM_TABLES #include "mbedtls/check_config.h" #endif /* MBEDTLS_CONFIG_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen/input/doc_rng.h
/** * \file doc_rng.h * * \brief Random number generator (RNG) module documentation file. */ /* * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @addtogroup rng_module Random number generator (RNG) module * * The Random number generator (RNG) module provides random number * generation, see \c mbedtls_ctr_drbg_random(). * * The block-cipher counter-mode based deterministic random * bit generator (CTR_DBRG) as specified in NIST SP800-90. It needs an external * source of entropy. For these purposes \c mbedtls_entropy_func() can be used. * This is an implementation based on a simple entropy accumulator design. * * The other number generator that is included is less strong and uses the * HAVEGE (HArdware Volatile Entropy Gathering and Expansion) software heuristic * which considered unsafe for primary usage, but provides additional random * to the entropy pool if enables. * * Meaning that there seems to be no practical algorithm that can guess * the next bit with a probability larger than 1/2 in an output sequence. * * This module can be used to generate random numbers. */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen/input/doc_hashing.h
/** * \file doc_hashing.h * * \brief Hashing module documentation file. */ /* * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @addtogroup hashing_module Hashing module * * The Message Digest (MD) or Hashing module provides one-way hashing * functions. Such functions can be used for creating a hash message * authentication code (HMAC) when sending a message. Such a HMAC can be used * in combination with a private key for authentication, which is a message * integrity control. * * All hash algorithms can be accessed via the generic MD layer (see * \c mbedtls_md_setup()) * * The following hashing-algorithms are provided: * - MD2, MD4, MD5 128-bit one-way hash functions by Ron Rivest. * - SHA-1, SHA-256, SHA-384/512 160-bit or more one-way hash functions by * NIST and NSA. * * This module provides one-way hashing which can be used for authentication. */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen/input/doc_ssltls.h
/** * \file doc_ssltls.h * * \brief SSL/TLS communication module documentation file. */ /* * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @addtogroup ssltls_communication_module SSL/TLS communication module * * The SSL/TLS communication module provides the means to create an SSL/TLS * communication channel. * * The basic provisions are: * - initialise an SSL/TLS context (see \c mbedtls_ssl_init()). * - perform an SSL/TLS handshake (see \c mbedtls_ssl_handshake()). * - read/write (see \c mbedtls_ssl_read() and \c mbedtls_ssl_write()). * - notify a peer that connection is being closed (see \c mbedtls_ssl_close_notify()). * * Many aspects of such a channel are set through parameters and callback * functions: * - the endpoint role: client or server. * - the authentication mode. Should verification take place. * - the Host-to-host communication channel. A TCP/IP module is provided. * - the random number generator (RNG). * - the ciphers to use for encryption/decryption. * - session control functions. * - X.509 parameters for certificate-handling and key exchange. * * This module can be used to create an SSL/TLS server and client and to provide a basic * framework to setup and communicate through an SSL/TLS communication channel.\n * Note that you need to provide for several aspects yourself as mentioned above. */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen/input/doc_tcpip.h
/** * \file doc_tcpip.h * * \brief TCP/IP communication module documentation file. */ /* * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @addtogroup tcpip_communication_module TCP/IP communication module * * The TCP/IP communication module provides for a channel of * communication for the \link ssltls_communication_module SSL/TLS communication * module\endlink to use. * In the TCP/IP-model it provides for communication up to the Transport * (or Host-to-host) layer. * SSL/TLS resides on top of that, in the Application layer, and makes use of * its basic provisions: * - listening on a port (see \c mbedtls_net_bind()). * - accepting a connection (through \c mbedtls_net_accept()). * - read/write (through \c mbedtls_net_recv()/\c mbedtls_net_send()). * - close a connection (through \c mbedtls_net_close()). * * This way you have the means to, for example, implement and use an UDP or * IPSec communication solution as a basis. * * This module can be used at server- and clientside to provide a basic * means of communication over the internet. */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen/input/doc_mainpage.h
/** * \file doc_mainpage.h * * \brief Main page documentation file. */ /* * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @mainpage mbed TLS v2.27.0 source code documentation * * This documentation describes the internal structure of mbed TLS. It was * automatically generated from specially formatted comment blocks in * mbed TLS's source code using Doxygen. (See * http://www.stack.nl/~dimitri/doxygen/ for more information on Doxygen) * * mbed TLS has a simple setup: it provides the ingredients for an SSL/TLS * implementation. These ingredients are listed as modules in the * \ref mainpage_modules "Modules section". This "Modules section" introduces * the high-level module concepts used throughout this documentation.\n * Some examples of mbed TLS usage can be found in the \ref mainpage_examples * "Examples section". * * @section mainpage_modules Modules * * mbed TLS supports SSLv3 up to TLSv1.2 communication by providing the * following: * - TCP/IP communication functions: listen, connect, accept, read/write. * - SSL/TLS communication functions: init, handshake, read/write. * - X.509 functions: CRT, CRL and key handling * - Random number generation * - Hashing * - Encryption/decryption * * Above functions are split up neatly into logical interfaces. These can be * used separately to provide any of the above functions or to mix-and-match * into an SSL server/client solution that utilises a X.509 PKI. Examples of * such implementations are amply provided with the source code. * * Note that mbed TLS does not provide a control channel or (multiple) session * handling without additional work from the developer. * * @section mainpage_examples Examples * * Example server setup: * * \b Prerequisites: * - X.509 certificate and private key * - session handling functions * * \b Setup: * - Load your certificate and your private RSA key (X.509 interface) * - Setup the listening TCP socket (TCP/IP interface) * - Accept incoming client connection (TCP/IP interface) * - Initialise as an SSL-server (SSL/TLS interface) * - Set parameters, e.g. authentication, ciphers, CA-chain, key exchange * - Set callback functions RNG, IO, session handling * - Perform an SSL-handshake (SSL/TLS interface) * - Read/write data (SSL/TLS interface) * - Close and cleanup (all interfaces) * * Example client setup: * * \b Prerequisites: * - X.509 certificate and private key * - X.509 trusted CA certificates * * \b Setup: * - Load the trusted CA certificates (X.509 interface) * - Load your certificate and your private RSA key (X.509 interface) * - Setup a TCP/IP connection (TCP/IP interface) * - Initialise as an SSL-client (SSL/TLS interface) * - Set parameters, e.g. authentication mode, ciphers, CA-chain, session * - Set callback functions RNG, IO * - Perform an SSL-handshake (SSL/TLS interface) * - Verify the server certificate (SSL/TLS interface) * - Write/read data (SSL/TLS interface) * - Close and cleanup (all interfaces) */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen/input/doc_encdec.h
/** * \file doc_encdec.h * * \brief Encryption/decryption module documentation file. */ /* * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @addtogroup encdec_module Encryption/decryption module * * The Encryption/decryption module provides encryption/decryption functions. * One can differentiate between symmetric and asymmetric algorithms; the * symmetric ones are mostly used for message confidentiality and the asymmetric * ones for key exchange and message integrity. * Some symmetric algorithms provide different block cipher modes, mainly * Electronic Code Book (ECB) which is used for short (64-bit) messages and * Cipher Block Chaining (CBC) which provides the structure needed for longer * messages. In addition the Cipher Feedback Mode (CFB-128) stream cipher mode, * Counter mode (CTR) and Galois Counter Mode (GCM) are implemented for * specific algorithms. * * All symmetric encryption algorithms are accessible via the generic cipher layer * (see \c mbedtls_cipher_setup()). * * The asymmetric encryptrion algorithms are accessible via the generic public * key layer (see \c mbedtls_pk_init()). * * The following algorithms are provided: * - Symmetric: * - AES (see \c mbedtls_aes_crypt_ecb(), \c mbedtls_aes_crypt_cbc(), \c mbedtls_aes_crypt_cfb128() and * \c mbedtls_aes_crypt_ctr()). * - ARCFOUR (see \c mbedtls_arc4_crypt()). * - Blowfish / BF (see \c mbedtls_blowfish_crypt_ecb(), \c mbedtls_blowfish_crypt_cbc(), * \c mbedtls_blowfish_crypt_cfb64() and \c mbedtls_blowfish_crypt_ctr()) * - Camellia (see \c mbedtls_camellia_crypt_ecb(), \c mbedtls_camellia_crypt_cbc(), * \c mbedtls_camellia_crypt_cfb128() and \c mbedtls_camellia_crypt_ctr()). * - DES/3DES (see \c mbedtls_des_crypt_ecb(), \c mbedtls_des_crypt_cbc(), \c mbedtls_des3_crypt_ecb() * and \c mbedtls_des3_crypt_cbc()). * - GCM (AES-GCM and CAMELLIA-GCM) (see \c mbedtls_gcm_init()) * - XTEA (see \c mbedtls_xtea_crypt_ecb()). * - Asymmetric: * - Diffie-Hellman-Merkle (see \c mbedtls_dhm_read_public(), \c mbedtls_dhm_make_public() * and \c mbedtls_dhm_calc_secret()). * - RSA (see \c mbedtls_rsa_public() and \c mbedtls_rsa_private()). * - Elliptic Curves over GF(p) (see \c mbedtls_ecp_point_init()). * - Elliptic Curve Digital Signature Algorithm (ECDSA) (see \c mbedtls_ecdsa_init()). * - Elliptic Curve Diffie Hellman (ECDH) (see \c mbedtls_ecdh_init()). * * This module provides encryption/decryption which can be used to provide * secrecy. * * It also provides asymmetric key functions which can be used for * confidentiality, integrity, authentication and non-repudiation. */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/doxygen/input/doc_x509.h
/** * \file doc_x509.h * * \brief X.509 module documentation file. */ /* * * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * @addtogroup x509_module X.509 module * * The X.509 module provides X.509 support for reading, writing and verification * of certificates. * In summary: * - X.509 certificate (CRT) reading (see \c mbedtls_x509_crt_parse(), * \c mbedtls_x509_crt_parse_der(), \c mbedtls_x509_crt_parse_file()). * - X.509 certificate revocation list (CRL) reading (see * \c mbedtls_x509_crl_parse(), \c mbedtls_x509_crl_parse_der(), * and \c mbedtls_x509_crl_parse_file()). * - X.509 certificate signature verification (see \c * mbedtls_x509_crt_verify() and \c mbedtls_x509_crt_verify_with_profile(). * - X.509 certificate writing and certificate request writing (see * \c mbedtls_x509write_crt_der() and \c mbedtls_x509write_csr_der()). * * This module can be used to build a certificate authority (CA) chain and * verify its signature. It is also used to generate Certificate Signing * Requests and X.509 certificates just as a CA would do. */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/CMakeLists.txt
option(INSTALL_MBEDTLS_HEADERS "Install mbed TLS headers." ON) if(INSTALL_MBEDTLS_HEADERS) file(GLOB headers "mbedtls/*.h") file(GLOB psa_headers "psa/*.h") install(FILES ${headers} DESTINATION include/mbedtls PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ) install(FILES ${psa_headers} DESTINATION include/psa PERMISSIONS OWNER_READ OWNER_WRITE GROUP_READ WORLD_READ) endif(INSTALL_MBEDTLS_HEADERS) # Make config.h available in an out-of-source build. ssl-opt.sh requires it. if (ENABLE_TESTING AND NOT ${CMAKE_CURRENT_BINARY_DIR} STREQUAL ${CMAKE_CURRENT_SOURCE_DIR}) link_to_source(mbedtls) link_to_source(psa) endif()
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_config.h
/** * \file psa/crypto_config.h * \brief PSA crypto configuration options (set of defines) * */ #if defined(MBEDTLS_PSA_CRYPTO_CONFIG) /** * When #MBEDTLS_PSA_CRYPTO_CONFIG is enabled in config.h, * this file determines which cryptographic mechanisms are enabled * through the PSA Cryptography API (\c psa_xxx() functions). * * To enable a cryptographic mechanism, uncomment the definition of * the corresponding \c PSA_WANT_xxx preprocessor symbol. * To disable a cryptographic mechanism, comment out the definition of * the corresponding \c PSA_WANT_xxx preprocessor symbol. * The names of cryptographic mechanisms correspond to values * defined in psa/crypto_values.h, with the prefix \c PSA_WANT_ instead * of \c PSA_. * * Note that many cryptographic mechanisms involve two symbols: one for * the key type (\c PSA_WANT_KEY_TYPE_xxx) and one for the algorithm * (\c PSA_WANT_ALG_xxx). Mechanisms with additional parameters may involve * additional symbols. */ #else /** * When \c MBEDTLS_PSA_CRYPTO_CONFIG is disabled in config.h, * this file is not used, and cryptographic mechanisms are supported * through the PSA API if and only if they are supported through the * mbedtls_xxx API. */ #endif /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_CONFIG_H #define PSA_CRYPTO_CONFIG_H /* * CBC-MAC is not yet supported via the PSA API in Mbed TLS. */ //#define PSA_WANT_ALG_CBC_MAC 1 #define PSA_WANT_ALG_CBC_NO_PADDING 1 #define PSA_WANT_ALG_CBC_PKCS7 1 #define PSA_WANT_ALG_CCM 1 #define PSA_WANT_ALG_CMAC 1 #define PSA_WANT_ALG_CFB 1 #define PSA_WANT_ALG_CHACHA20_POLY1305 1 #define PSA_WANT_ALG_CMAC 1 #define PSA_WANT_ALG_CTR 1 #define PSA_WANT_ALG_DETERMINISTIC_ECDSA 1 #define PSA_WANT_ALG_ECB_NO_PADDING 1 #define PSA_WANT_ALG_ECDH 1 #define PSA_WANT_ALG_ECDSA 1 #define PSA_WANT_ALG_GCM 1 #define PSA_WANT_ALG_HKDF 1 #define PSA_WANT_ALG_HMAC 1 #define PSA_WANT_ALG_MD2 1 #define PSA_WANT_ALG_MD4 1 #define PSA_WANT_ALG_MD5 1 #define PSA_WANT_ALG_OFB 1 #define PSA_WANT_ALG_RIPEMD160 1 #define PSA_WANT_ALG_RSA_OAEP 1 #define PSA_WANT_ALG_RSA_PKCS1V15_CRYPT 1 #define PSA_WANT_ALG_RSA_PKCS1V15_SIGN 1 #define PSA_WANT_ALG_RSA_PSS 1 #define PSA_WANT_ALG_SHA_1 1 #define PSA_WANT_ALG_SHA_224 1 #define PSA_WANT_ALG_SHA_256 1 #define PSA_WANT_ALG_SHA_384 1 #define PSA_WANT_ALG_SHA_512 1 #define PSA_WANT_ALG_STREAM_CIPHER 1 #define PSA_WANT_ALG_TLS12_PRF 1 #define PSA_WANT_ALG_TLS12_PSK_TO_MS 1 #define PSA_WANT_ALG_XTS 1 #define PSA_WANT_ECC_BRAINPOOL_P_R1_256 1 #define PSA_WANT_ECC_BRAINPOOL_P_R1_384 1 #define PSA_WANT_ECC_BRAINPOOL_P_R1_512 1 #define PSA_WANT_ECC_MONTGOMERY_255 1 /* * Curve448 is not yet supported via the PSA API in Mbed TLS * (https://github.com/ARMmbed/mbedtls/issues/4249). Thus, do not enable it by * default. */ //#define PSA_WANT_ECC_MONTGOMERY_448 1 #define PSA_WANT_ECC_SECP_K1_192 1 /* * SECP224K1 is buggy via the PSA API in Mbed TLS * (https://github.com/ARMmbed/mbedtls/issues/3541). Thus, do not enable it by * default. */ //#define PSA_WANT_ECC_SECP_K1_224 1 #define PSA_WANT_ECC_SECP_K1_256 1 #define PSA_WANT_ECC_SECP_R1_192 1 #define PSA_WANT_ECC_SECP_R1_224 1 #define PSA_WANT_ECC_SECP_R1_256 1 #define PSA_WANT_ECC_SECP_R1_384 1 #define PSA_WANT_ECC_SECP_R1_521 1 #define PSA_WANT_KEY_TYPE_DERIVE 1 #define PSA_WANT_KEY_TYPE_HMAC 1 #define PSA_WANT_KEY_TYPE_AES 1 #define PSA_WANT_KEY_TYPE_ARC4 1 #define PSA_WANT_KEY_TYPE_CAMELLIA 1 #define PSA_WANT_KEY_TYPE_CHACHA20 1 #define PSA_WANT_KEY_TYPE_DES 1 #define PSA_WANT_KEY_TYPE_ECC_KEY_PAIR 1 #define PSA_WANT_KEY_TYPE_ECC_PUBLIC_KEY 1 #define PSA_WANT_KEY_TYPE_RAW_DATA 1 #define PSA_WANT_KEY_TYPE_RSA_KEY_PAIR 1 #define PSA_WANT_KEY_TYPE_RSA_PUBLIC_KEY 1 #endif /* PSA_CRYPTO_CONFIG_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_builtin_primitives.h
/* * Context structure declaration of the Mbed TLS software-based PSA drivers * called through the PSA Crypto driver dispatch layer. * This file contains the context structures of those algorithms which do not * rely on other algorithms, i.e. are 'primitive' algorithms. * * \note This file may not be included directly. Applications must * include psa/crypto.h. * * \note This header and its content is not part of the Mbed TLS API and * applications must not depend on it. Its main purpose is to define the * multi-part state objects of the Mbed TLS software-based PSA drivers. The * definition of these objects are then used by crypto_struct.h to define the * implementation-defined types of PSA multi-part state objects. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_BUILTIN_PRIMITIVES_H #define PSA_CRYPTO_BUILTIN_PRIMITIVES_H #include <psa/crypto_driver_common.h> /* * Hash multi-part operation definitions. */ #include "mbedtls/md2.h" #include "mbedtls/md4.h" #include "mbedtls/md5.h" #include "mbedtls/ripemd160.h" #include "mbedtls/sha1.h" #include "mbedtls/sha256.h" #include "mbedtls/sha512.h" #if defined(MBEDTLS_PSA_BUILTIN_ALG_MD2) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_MD4) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_MD5) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_RIPEMD160) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_1) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_224) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_256) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_384) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_SHA_512) #define MBEDTLS_PSA_BUILTIN_HASH #endif typedef struct { psa_algorithm_t alg; union { unsigned dummy; /* Make the union non-empty even with no supported algorithms. */ #if defined(MBEDTLS_MD2_C) mbedtls_md2_context md2; #endif #if defined(MBEDTLS_MD4_C) mbedtls_md4_context md4; #endif #if defined(MBEDTLS_MD5_C) mbedtls_md5_context md5; #endif #if defined(MBEDTLS_RIPEMD160_C) mbedtls_ripemd160_context ripemd160; #endif #if defined(MBEDTLS_SHA1_C) mbedtls_sha1_context sha1; #endif #if defined(MBEDTLS_SHA256_C) mbedtls_sha256_context sha256; #endif #if defined(MBEDTLS_SHA512_C) mbedtls_sha512_context sha512; #endif } ctx; } mbedtls_psa_hash_operation_t; #define MBEDTLS_PSA_HASH_OPERATION_INIT {0, {0}} /* * Cipher multi-part operation definitions. */ #include "mbedtls/cipher.h" #if defined(MBEDTLS_PSA_BUILTIN_ALG_STREAM_CIPHER) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_CTR) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_CFB) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_OFB) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_XTS) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_ECB_NO_PADDING) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_NO_PADDING) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_CBC_PKCS7) #define MBEDTLS_PSA_BUILTIN_CIPHER 1 #endif typedef struct { /* Context structure for the Mbed TLS cipher implementation. */ psa_algorithm_t alg; uint8_t iv_length; uint8_t block_length; union { unsigned int dummy; mbedtls_cipher_context_t cipher; } ctx; } mbedtls_psa_cipher_operation_t; #define MBEDTLS_PSA_CIPHER_OPERATION_INIT {0, 0, 0, {0}} /* * BEYOND THIS POINT, TEST DRIVER DECLARATIONS ONLY. */ #if defined(PSA_CRYPTO_DRIVER_TEST) typedef mbedtls_psa_hash_operation_t mbedtls_transparent_test_driver_hash_operation_t; #define MBEDTLS_TRANSPARENT_TEST_DRIVER_HASH_OPERATION_INIT MBEDTLS_PSA_HASH_OPERATION_INIT typedef mbedtls_psa_cipher_operation_t mbedtls_transparent_test_driver_cipher_operation_t; typedef struct { unsigned int initialised : 1; mbedtls_transparent_test_driver_cipher_operation_t ctx; } mbedtls_opaque_test_driver_cipher_operation_t; #define MBEDTLS_TRANSPARENT_TEST_DRIVER_CIPHER_OPERATION_INIT \ MBEDTLS_PSA_CIPHER_OPERATION_INIT #define MBEDTLS_OPAQUE_TEST_DRIVER_CIPHER_OPERATION_INIT \ { 0, MBEDTLS_TRANSPARENT_TEST_DRIVER_CIPHER_OPERATION_INIT } #endif /* PSA_CRYPTO_DRIVER_TEST */ #endif /* PSA_CRYPTO_BUILTIN_PRIMITIVES_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_extra.h
/** * \file psa/crypto_extra.h * * \brief PSA cryptography module: Mbed TLS vendor extensions * * \note This file may not be included directly. Applications must * include psa/crypto.h. * * This file is reserved for vendor-specific definitions. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_EXTRA_H #define PSA_CRYPTO_EXTRA_H #include "mbedtls/platform_util.h" #include "crypto_compat.h" #ifdef __cplusplus extern "C" { #endif /* UID for secure storage seed */ #define PSA_CRYPTO_ITS_RANDOM_SEED_UID 0xFFFFFF52 /* See config.h for definition */ #if !defined(MBEDTLS_PSA_KEY_SLOT_COUNT) #define MBEDTLS_PSA_KEY_SLOT_COUNT 32 #endif /** \addtogroup attributes * @{ */ /** \brief Declare the enrollment algorithm for a key. * * An operation on a key may indifferently use the algorithm set with * psa_set_key_algorithm() or with this function. * * \param[out] attributes The attribute structure to write to. * \param alg2 A second algorithm that the key may be used * for, in addition to the algorithm set with * psa_set_key_algorithm(). * * \warning Setting an enrollment algorithm is not recommended, because * using the same key with different algorithms can allow some * attacks based on arithmetic relations between different * computations made with the same key, or can escalate harmless * side channels into exploitable ones. Use this function only * if it is necessary to support a protocol for which it has been * verified that the usage of the key with multiple algorithms * is safe. */ static inline void psa_set_key_enrollment_algorithm( psa_key_attributes_t *attributes, psa_algorithm_t alg2) { attributes->core.policy.alg2 = alg2; } /** Retrieve the enrollment algorithm policy from key attributes. * * \param[in] attributes The key attribute structure to query. * * \return The enrollment algorithm stored in the attribute structure. */ static inline psa_algorithm_t psa_get_key_enrollment_algorithm( const psa_key_attributes_t *attributes) { return( attributes->core.policy.alg2 ); } #if defined(MBEDTLS_PSA_CRYPTO_SE_C) /** Retrieve the slot number where a key is stored. * * A slot number is only defined for keys that are stored in a secure * element. * * This information is only useful if the secure element is not entirely * managed through the PSA Cryptography API. It is up to the secure * element driver to decide how PSA slot numbers map to any other interface * that the secure element may have. * * \param[in] attributes The key attribute structure to query. * \param[out] slot_number On success, the slot number containing the key. * * \retval #PSA_SUCCESS * The key is located in a secure element, and \p *slot_number * indicates the slot number that contains it. * \retval #PSA_ERROR_NOT_PERMITTED * The caller is not permitted to query the slot number. * Mbed Crypto currently does not return this error. * \retval #PSA_ERROR_INVALID_ARGUMENT * The key is not located in a secure element. */ psa_status_t psa_get_key_slot_number( const psa_key_attributes_t *attributes, psa_key_slot_number_t *slot_number ); /** Choose the slot number where a key is stored. * * This function declares a slot number in the specified attribute * structure. * * A slot number is only meaningful for keys that are stored in a secure * element. It is up to the secure element driver to decide how PSA slot * numbers map to any other interface that the secure element may have. * * \note Setting a slot number in key attributes for a key creation can * cause the following errors when creating the key: * - #PSA_ERROR_NOT_SUPPORTED if the selected secure element does * not support choosing a specific slot number. * - #PSA_ERROR_NOT_PERMITTED if the caller is not permitted to * choose slot numbers in general or to choose this specific slot. * - #PSA_ERROR_INVALID_ARGUMENT if the chosen slot number is not * valid in general or not valid for this specific key. * - #PSA_ERROR_ALREADY_EXISTS if there is already a key in the * selected slot. * * \param[out] attributes The attribute structure to write to. * \param slot_number The slot number to set. */ static inline void psa_set_key_slot_number( psa_key_attributes_t *attributes, psa_key_slot_number_t slot_number ) { attributes->core.flags |= MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER; attributes->slot_number = slot_number; } /** Remove the slot number attribute from a key attribute structure. * * This function undoes the action of psa_set_key_slot_number(). * * \param[out] attributes The attribute structure to write to. */ static inline void psa_clear_key_slot_number( psa_key_attributes_t *attributes ) { attributes->core.flags &= ~MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER; } /** Register a key that is already present in a secure element. * * The key must be located in a secure element designated by the * lifetime field in \p attributes, in the slot set with * psa_set_key_slot_number() in the attribute structure. * This function makes the key available through the key identifier * specified in \p attributes. * * \param[in] attributes The attributes of the existing key. * * \retval #PSA_SUCCESS * The key was successfully registered. * Note that depending on the design of the driver, this may or may * not guarantee that a key actually exists in the designated slot * and is compatible with the specified attributes. * \retval #PSA_ERROR_ALREADY_EXISTS * There is already a key with the identifier specified in * \p attributes. * \retval #PSA_ERROR_NOT_SUPPORTED * The secure element driver for the specified lifetime does not * support registering a key. * \retval #PSA_ERROR_INVALID_ARGUMENT * The identifier in \p attributes is invalid, namely the identifier is * not in the user range. * \retval #PSA_ERROR_INVALID_ARGUMENT * \p attributes specifies a lifetime which is not located * in a secure element. * \retval #PSA_ERROR_INVALID_ARGUMENT * No slot number is specified in \p attributes, * or the specified slot number is not valid. * \retval #PSA_ERROR_NOT_PERMITTED * The caller is not authorized to register the specified key slot. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_INSUFFICIENT_STORAGE * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_DATA_INVALID * \retval #PSA_ERROR_DATA_CORRUPT * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t mbedtls_psa_register_se_key( const psa_key_attributes_t *attributes); #endif /* MBEDTLS_PSA_CRYPTO_SE_C */ /**@}*/ /** * \brief Library deinitialization. * * This function clears all data associated with the PSA layer, * including the whole key store. * * This is an Mbed TLS extension. */ void mbedtls_psa_crypto_free( void ); /** \brief Statistics about * resource consumption related to the PSA keystore. * * \note The content of this structure is not part of the stable API and ABI * of Mbed Crypto and may change arbitrarily from version to version. */ typedef struct mbedtls_psa_stats_s { /** Number of slots containing key material for a volatile key. */ size_t volatile_slots; /** Number of slots containing key material for a key which is in * internal persistent storage. */ size_t persistent_slots; /** Number of slots containing a reference to a key in a * secure element. */ size_t external_slots; /** Number of slots which are occupied, but do not contain * key material yet. */ size_t half_filled_slots; /** Number of slots that contain cache data. */ size_t cache_slots; /** Number of slots that are not used for anything. */ size_t empty_slots; /** Number of slots that are locked. */ size_t locked_slots; /** Largest key id value among open keys in internal persistent storage. */ psa_key_id_t max_open_internal_key_id; /** Largest key id value among open keys in secure elements. */ psa_key_id_t max_open_external_key_id; } mbedtls_psa_stats_t; /** \brief Get statistics about * resource consumption related to the PSA keystore. * * \note When Mbed Crypto is built as part of a service, with isolation * between the application and the keystore, the service may or * may not expose this function. */ void mbedtls_psa_get_stats( mbedtls_psa_stats_t *stats ); /** * \brief Inject an initial entropy seed for the random generator into * secure storage. * * This function injects data to be used as a seed for the random generator * used by the PSA Crypto implementation. On devices that lack a trusted * entropy source (preferably a hardware random number generator), * the Mbed PSA Crypto implementation uses this value to seed its * random generator. * * On devices without a trusted entropy source, this function must be * called exactly once in the lifetime of the device. On devices with * a trusted entropy source, calling this function is optional. * In all cases, this function may only be called before calling any * other function in the PSA Crypto API, including psa_crypto_init(). * * When this function returns successfully, it populates a file in * persistent storage. Once the file has been created, this function * can no longer succeed. * * If any error occurs, this function does not change the system state. * You can call this function again after correcting the reason for the * error if possible. * * \warning This function **can** fail! Callers MUST check the return status. * * \warning If you use this function, you should use it as part of a * factory provisioning process. The value of the injected seed * is critical to the security of the device. It must be * *secret*, *unpredictable* and (statistically) *unique per device*. * You should be generate it randomly using a cryptographically * secure random generator seeded from trusted entropy sources. * You should transmit it securely to the device and ensure * that its value is not leaked or stored anywhere beyond the * needs of transmitting it from the point of generation to * the call of this function, and erase all copies of the value * once this function returns. * * This is an Mbed TLS extension. * * \note This function is only available on the following platforms: * * If the compile-time option MBEDTLS_PSA_INJECT_ENTROPY is enabled. * Note that you must provide compatible implementations of * mbedtls_nv_seed_read and mbedtls_nv_seed_write. * * In a client-server integration of PSA Cryptography, on the client side, * if the server supports this feature. * \param[in] seed Buffer containing the seed value to inject. * \param[in] seed_size Size of the \p seed buffer. * The size of the seed in bytes must be greater * or equal to both #MBEDTLS_ENTROPY_MIN_PLATFORM * and #MBEDTLS_ENTROPY_BLOCK_SIZE. * It must be less or equal to * #MBEDTLS_ENTROPY_MAX_SEED_SIZE. * * \retval #PSA_SUCCESS * The seed value was injected successfully. The random generator * of the PSA Crypto implementation is now ready for use. * You may now call psa_crypto_init() and use the PSA Crypto * implementation. * \retval #PSA_ERROR_INVALID_ARGUMENT * \p seed_size is out of range. * \retval #PSA_ERROR_STORAGE_FAILURE * There was a failure reading or writing from storage. * \retval #PSA_ERROR_NOT_PERMITTED * The library has already been initialized. It is no longer * possible to call this function. */ psa_status_t mbedtls_psa_inject_entropy(const uint8_t *seed, size_t seed_size); /** \addtogroup crypto_types * @{ */ /** DSA public key. * * The import and export format is the * representation of the public key `y = g^x mod p` as a big-endian byte * string. The length of the byte string is the length of the base prime `p` * in bytes. */ #define PSA_KEY_TYPE_DSA_PUBLIC_KEY ((psa_key_type_t)0x4002) /** DSA key pair (private and public key). * * The import and export format is the * representation of the private key `x` as a big-endian byte string. The * length of the byte string is the private key size in bytes (leading zeroes * are not stripped). * * Determinstic DSA key derivation with psa_generate_derived_key follows * FIPS 186-4 &sect;B.1.2: interpret the byte string as integer * in big-endian order. Discard it if it is not in the range * [0, *N* - 2] where *N* is the boundary of the private key domain * (the prime *p* for Diffie-Hellman, the subprime *q* for DSA, * or the order of the curve's base point for ECC). * Add 1 to the resulting integer and use this as the private key *x*. * */ #define PSA_KEY_TYPE_DSA_KEY_PAIR ((psa_key_type_t)0x7002) /** Whether a key type is an DSA key (pair or public-only). */ #define PSA_KEY_TYPE_IS_DSA(type) \ (PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) == PSA_KEY_TYPE_DSA_PUBLIC_KEY) #define PSA_ALG_DSA_BASE ((psa_algorithm_t)0x06000400) /** DSA signature with hashing. * * This is the signature scheme defined by FIPS 186-4, * with a random per-message secret number (*k*). * * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true). * This includes #PSA_ALG_ANY_HASH * when specifying the algorithm in a usage policy. * * \return The corresponding DSA signature algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_DSA(hash_alg) \ (PSA_ALG_DSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) #define PSA_ALG_DETERMINISTIC_DSA_BASE ((psa_algorithm_t)0x06000500) #define PSA_ALG_DSA_DETERMINISTIC_FLAG PSA_ALG_ECDSA_DETERMINISTIC_FLAG /** Deterministic DSA signature with hashing. * * This is the deterministic variant defined by RFC 6979 of * the signature scheme defined by FIPS 186-4. * * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true). * This includes #PSA_ALG_ANY_HASH * when specifying the algorithm in a usage policy. * * \return The corresponding DSA signature algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_DETERMINISTIC_DSA(hash_alg) \ (PSA_ALG_DETERMINISTIC_DSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) #define PSA_ALG_IS_DSA(alg) \ (((alg) & ~PSA_ALG_HASH_MASK & ~PSA_ALG_DSA_DETERMINISTIC_FLAG) == \ PSA_ALG_DSA_BASE) #define PSA_ALG_DSA_IS_DETERMINISTIC(alg) \ (((alg) & PSA_ALG_DSA_DETERMINISTIC_FLAG) != 0) #define PSA_ALG_IS_DETERMINISTIC_DSA(alg) \ (PSA_ALG_IS_DSA(alg) && PSA_ALG_DSA_IS_DETERMINISTIC(alg)) #define PSA_ALG_IS_RANDOMIZED_DSA(alg) \ (PSA_ALG_IS_DSA(alg) && !PSA_ALG_DSA_IS_DETERMINISTIC(alg)) /* We need to expand the sample definition of this macro from * the API definition. */ #undef PSA_ALG_IS_VENDOR_HASH_AND_SIGN #define PSA_ALG_IS_VENDOR_HASH_AND_SIGN(alg) \ PSA_ALG_IS_DSA(alg) /**@}*/ /** \addtogroup attributes * @{ */ /** Custom Diffie-Hellman group. * * For keys of type #PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_FAMILY_CUSTOM) or * #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_FAMILY_CUSTOM), the group data comes * from domain parameters set by psa_set_key_domain_parameters(). */ #define PSA_DH_FAMILY_CUSTOM ((psa_dh_family_t) 0x7e) /** * \brief Set domain parameters for a key. * * Some key types require additional domain parameters in addition to * the key type identifier and the key size. Use this function instead * of psa_set_key_type() when you need to specify domain parameters. * * The format for the required domain parameters varies based on the key type. * * - For RSA keys (#PSA_KEY_TYPE_RSA_PUBLIC_KEY or #PSA_KEY_TYPE_RSA_KEY_PAIR), * the domain parameter data consists of the public exponent, * represented as a big-endian integer with no leading zeros. * This information is used when generating an RSA key pair. * When importing a key, the public exponent is read from the imported * key data and the exponent recorded in the attribute structure is ignored. * As an exception, the public exponent 65537 is represented by an empty * byte string. * - For DSA keys (#PSA_KEY_TYPE_DSA_PUBLIC_KEY or #PSA_KEY_TYPE_DSA_KEY_PAIR), * the `Dss-Parms` format as defined by RFC 3279 &sect;2.3.2. * ``` * Dss-Parms ::= SEQUENCE { * p INTEGER, * q INTEGER, * g INTEGER * } * ``` * - For Diffie-Hellman key exchange keys * (#PSA_KEY_TYPE_DH_PUBLIC_KEY(#PSA_DH_FAMILY_CUSTOM) or * #PSA_KEY_TYPE_DH_KEY_PAIR(#PSA_DH_FAMILY_CUSTOM)), the * `DomainParameters` format as defined by RFC 3279 &sect;2.3.3. * ``` * DomainParameters ::= SEQUENCE { * p INTEGER, -- odd prime, p=jq +1 * g INTEGER, -- generator, g * q INTEGER, -- factor of p-1 * j INTEGER OPTIONAL, -- subgroup factor * validationParms ValidationParms OPTIONAL * } * ValidationParms ::= SEQUENCE { * seed BIT STRING, * pgenCounter INTEGER * } * ``` * * \note This function may allocate memory or other resources. * Once you have called this function on an attribute structure, * you must call psa_reset_key_attributes() to free these resources. * * \note This is an experimental extension to the interface. It may change * in future versions of the library. * * \param[in,out] attributes Attribute structure where the specified domain * parameters will be stored. * If this function fails, the content of * \p attributes is not modified. * \param type Key type (a \c PSA_KEY_TYPE_XXX value). * \param[in] data Buffer containing the key domain parameters. * The content of this buffer is interpreted * according to \p type as described above. * \param data_length Size of the \p data buffer in bytes. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_ARGUMENT * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_INSUFFICIENT_MEMORY */ psa_status_t psa_set_key_domain_parameters(psa_key_attributes_t *attributes, psa_key_type_t type, const uint8_t *data, size_t data_length); /** * \brief Get domain parameters for a key. * * Get the domain parameters for a key with this function, if any. The format * of the domain parameters written to \p data is specified in the * documentation for psa_set_key_domain_parameters(). * * \note This is an experimental extension to the interface. It may change * in future versions of the library. * * \param[in] attributes The key attribute structure to query. * \param[out] data On success, the key domain parameters. * \param data_size Size of the \p data buffer in bytes. * The buffer is guaranteed to be large * enough if its size in bytes is at least * the value given by * PSA_KEY_DOMAIN_PARAMETERS_SIZE(). * \param[out] data_length On success, the number of bytes * that make up the key domain parameters data. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_BUFFER_TOO_SMALL */ psa_status_t psa_get_key_domain_parameters( const psa_key_attributes_t *attributes, uint8_t *data, size_t data_size, size_t *data_length); /** Safe output buffer size for psa_get_key_domain_parameters(). * * This macro returns a compile-time constant if its arguments are * compile-time constants. * * \warning This function may call its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \note This is an experimental extension to the interface. It may change * in future versions of the library. * * \param key_type A supported key type. * \param key_bits The size of the key in bits. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that * psa_get_key_domain_parameters() will not fail with * #PSA_ERROR_BUFFER_TOO_SMALL. * If the parameters are a valid combination that is not supported * by the implementation, this macro shall return either a * sensible size or 0. * If the parameters are not valid, the * return value is unspecified. */ #define PSA_KEY_DOMAIN_PARAMETERS_SIZE(key_type, key_bits) \ (PSA_KEY_TYPE_IS_RSA(key_type) ? sizeof(int) : \ PSA_KEY_TYPE_IS_DH(key_type) ? PSA_DH_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) : \ PSA_KEY_TYPE_IS_DSA(key_type) ? PSA_DSA_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) : \ 0) #define PSA_DH_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) \ (4 + (PSA_BITS_TO_BYTES(key_bits) + 5) * 3 /*without optional parts*/) #define PSA_DSA_KEY_DOMAIN_PARAMETERS_SIZE(key_bits) \ (4 + (PSA_BITS_TO_BYTES(key_bits) + 5) * 2 /*p, g*/ + 34 /*q*/) /**@}*/ /** \defgroup psa_tls_helpers TLS helper functions * @{ */ #if defined(MBEDTLS_ECP_C) #include <mbedtls/ecp.h> /** Convert an ECC curve identifier from the Mbed TLS encoding to PSA. * * \note This function is provided solely for the convenience of * Mbed TLS and may be removed at any time without notice. * * \param grpid An Mbed TLS elliptic curve identifier * (`MBEDTLS_ECP_DP_xxx`). * \param[out] bits On success, the bit size of the curve. * * \return The corresponding PSA elliptic curve identifier * (`PSA_ECC_FAMILY_xxx`). * \return \c 0 on failure (\p grpid is not recognized). */ static inline psa_ecc_family_t mbedtls_ecc_group_to_psa( mbedtls_ecp_group_id grpid, size_t *bits ) { switch( grpid ) { case MBEDTLS_ECP_DP_SECP192R1: *bits = 192; return( PSA_ECC_FAMILY_SECP_R1 ); case MBEDTLS_ECP_DP_SECP224R1: *bits = 224; return( PSA_ECC_FAMILY_SECP_R1 ); case MBEDTLS_ECP_DP_SECP256R1: *bits = 256; return( PSA_ECC_FAMILY_SECP_R1 ); case MBEDTLS_ECP_DP_SECP384R1: *bits = 384; return( PSA_ECC_FAMILY_SECP_R1 ); case MBEDTLS_ECP_DP_SECP521R1: *bits = 521; return( PSA_ECC_FAMILY_SECP_R1 ); case MBEDTLS_ECP_DP_BP256R1: *bits = 256; return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); case MBEDTLS_ECP_DP_BP384R1: *bits = 384; return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); case MBEDTLS_ECP_DP_BP512R1: *bits = 512; return( PSA_ECC_FAMILY_BRAINPOOL_P_R1 ); case MBEDTLS_ECP_DP_CURVE25519: *bits = 255; return( PSA_ECC_FAMILY_MONTGOMERY ); case MBEDTLS_ECP_DP_SECP192K1: *bits = 192; return( PSA_ECC_FAMILY_SECP_K1 ); case MBEDTLS_ECP_DP_SECP224K1: *bits = 224; return( PSA_ECC_FAMILY_SECP_K1 ); case MBEDTLS_ECP_DP_SECP256K1: *bits = 256; return( PSA_ECC_FAMILY_SECP_K1 ); case MBEDTLS_ECP_DP_CURVE448: *bits = 448; return( PSA_ECC_FAMILY_MONTGOMERY ); default: *bits = 0; return( 0 ); } } /** Convert an ECC curve identifier from the PSA encoding to Mbed TLS. * * \note This function is provided solely for the convenience of * Mbed TLS and may be removed at any time without notice. * * \param curve A PSA elliptic curve identifier * (`PSA_ECC_FAMILY_xxx`). * \param bits The bit-length of a private key on \p curve. * \param bits_is_sloppy If true, \p bits may be the bit-length rounded up * to the nearest multiple of 8. This allows the caller * to infer the exact curve from the length of a key * which is supplied as a byte string. * * \return The corresponding Mbed TLS elliptic curve identifier * (`MBEDTLS_ECP_DP_xxx`). * \return #MBEDTLS_ECP_DP_NONE if \c curve is not recognized. * \return #MBEDTLS_ECP_DP_NONE if \p bits is not * correct for \p curve. */ mbedtls_ecp_group_id mbedtls_ecc_group_of_psa( psa_ecc_family_t curve, size_t bits, int bits_is_sloppy ); #endif /* MBEDTLS_ECP_C */ /**@}*/ /** \defgroup psa_external_rng External random generator * @{ */ #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) /** External random generator function, implemented by the platform. * * When the compile-time option #MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG is enabled, * this function replaces Mbed TLS's entropy and DRBG modules for all * random generation triggered via PSA crypto interfaces. * * \note This random generator must deliver random numbers with cryptographic * quality and high performance. It must supply unpredictable numbers * with a uniform distribution. The implementation of this function * is responsible for ensuring that the random generator is seeded * with sufficient entropy. If you have a hardware TRNG which is slow * or delivers non-uniform output, declare it as an entropy source * with mbedtls_entropy_add_source() instead of enabling this option. * * \param[in,out] context Pointer to the random generator context. * This is all-bits-zero on the first call * and preserved between successive calls. * \param[out] output Output buffer. On success, this buffer * contains random data with a uniform * distribution. * \param output_size The size of the \p output buffer in bytes. * \param[out] output_length On success, set this value to \p output_size. * * \retval #PSA_SUCCESS * Success. The output buffer contains \p output_size bytes of * cryptographic-quality random data, and \c *output_length is * set to \p output_size. * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY * The random generator requires extra entropy and there is no * way to obtain entropy under current environment conditions. * This error should not happen under normal circumstances since * this function is responsible for obtaining as much entropy as * it needs. However implementations of this function may return * #PSA_ERROR_INSUFFICIENT_ENTROPY if there is no way to obtain * entropy without blocking indefinitely. * \retval #PSA_ERROR_HARDWARE_FAILURE * A failure of the random generator hardware that isn't covered * by #PSA_ERROR_INSUFFICIENT_ENTROPY. */ psa_status_t mbedtls_psa_external_get_random( mbedtls_psa_external_random_context_t *context, uint8_t *output, size_t output_size, size_t *output_length ); #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */ /**@}*/ /** \defgroup psa_builtin_keys Built-in keys * @{ */ /** The minimum value for a key identifier that is built into the * implementation. * * The range of key identifiers from #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN * to #MBEDTLS_PSA_KEY_ID_BUILTIN_MAX within the range from * #PSA_KEY_ID_VENDOR_MIN and #PSA_KEY_ID_VENDOR_MAX and must not intersect * with any other set of implementation-chosen key identifiers. * * This value is part of the library's ABI since changing it would invalidate * the values of built-in key identifiers in applications. */ #define MBEDTLS_PSA_KEY_ID_BUILTIN_MIN ((psa_key_id_t)0x7fff0000) /** The maximum value for a key identifier that is built into the * implementation. * * See #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN for more information. */ #define MBEDTLS_PSA_KEY_ID_BUILTIN_MAX ((psa_key_id_t)0x7fffefff) /** A slot number identifying a key in a driver. * * Values of this type are used to identify built-in keys. */ typedef uint64_t psa_drv_slot_number_t; #if defined(MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS) /** Test whether a key identifier belongs to the builtin key range. * * \param key_id Key identifier to test. * * \retval 1 * The key identifier is a builtin key identifier. * \retval 0 * The key identifier is not a builtin key identifier. */ static inline int psa_key_id_is_builtin( psa_key_id_t key_id ) { return( ( key_id >= MBEDTLS_PSA_KEY_ID_BUILTIN_MIN ) && ( key_id <= MBEDTLS_PSA_KEY_ID_BUILTIN_MAX ) ); } /** Platform function to obtain the location and slot number of a built-in key. * * An application-specific implementation of this function must be provided if * #MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS is enabled. This would typically be provided * as part of a platform's system image. * * #MBEDTLS_SVC_KEY_ID_GET_KEY_ID(\p key_id) needs to be in the range from * #MBEDTLS_PSA_KEY_ID_BUILTIN_MIN to #MBEDTLS_PSA_KEY_ID_BUILTIN_MAX. * * In a multi-application configuration * (\c MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER is defined), * this function should check that #MBEDTLS_SVC_KEY_ID_GET_OWNER_ID(\p key_id) * is allowed to use the given key. * * \param key_id The key ID for which to retrieve the * location and slot attributes. * \param[out] lifetime On success, the lifetime associated with the key * corresponding to \p key_id. Lifetime is a * combination of which driver contains the key, * and with what persistence level the key is * intended to be used. If the platform * implementation does not contain specific * information about the intended key persistence * level, the persistence level may be reported as * #PSA_KEY_PERSISTENCE_DEFAULT. * \param[out] slot_number On success, the slot number known to the driver * registered at the lifetime location reported * through \p lifetime which corresponds to the * requested built-in key. * * \retval #PSA_SUCCESS * The requested key identifier designates a built-in key. * In a multi-application configuration, the requested owner * is allowed to access it. * \retval #PSA_ERROR_DOES_NOT_EXIST * The requested key identifier is not a built-in key which is known * to this function. If a key exists in the key storage with this * identifier, the data from the storage will be used. * \return (any other error) * Any other error is propagated to the function that requested the key. * Common errors include: * - #PSA_ERROR_NOT_PERMITTED: the key exists but the requested owner * is not allowed to access it. */ psa_status_t mbedtls_psa_platform_get_builtin_key( mbedtls_svc_key_id_t key_id, psa_key_lifetime_t *lifetime, psa_drv_slot_number_t *slot_number ); #endif /* MBEDTLS_PSA_CRYPTO_BUILTIN_KEYS */ /** @} */ #ifdef __cplusplus } #endif #endif /* PSA_CRYPTO_EXTRA_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_types.h
/** * \file psa/crypto_types.h * * \brief PSA cryptography module: type aliases. * * \note This file may not be included directly. Applications must * include psa/crypto.h. Drivers must include the appropriate driver * header file. * * This file contains portable definitions of integral types for properties * of cryptographic keys, designations of cryptographic algorithms, and * error codes returned by the library. * * This header file does not declare any function. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_TYPES_H #define PSA_CRYPTO_TYPES_H #include "crypto_platform.h" /* If MBEDTLS_PSA_CRYPTO_C is defined, make sure MBEDTLS_PSA_CRYPTO_CLIENT * is defined as well to include all PSA code. */ #if defined(MBEDTLS_PSA_CRYPTO_C) #define MBEDTLS_PSA_CRYPTO_CLIENT #endif /* MBEDTLS_PSA_CRYPTO_C */ #include <stdint.h> /** \defgroup error Error codes * @{ */ /** * \brief Function return status. * * This is either #PSA_SUCCESS (which is zero), indicating success, * or a small negative value indicating that an error occurred. Errors are * encoded as one of the \c PSA_ERROR_xxx values defined here. */ /* If #PSA_SUCCESS is already defined, it means that #psa_status_t * is also defined in an external header, so prevent its multiple * definition. */ #ifndef PSA_SUCCESS typedef int32_t psa_status_t; #endif /**@}*/ /** \defgroup crypto_types Key and algorithm types * @{ */ /** \brief Encoding of a key type. */ typedef uint16_t psa_key_type_t; /** The type of PSA elliptic curve family identifiers. * * The curve identifier is required to create an ECC key using the * PSA_KEY_TYPE_ECC_KEY_PAIR() or PSA_KEY_TYPE_ECC_PUBLIC_KEY() * macros. * * Values defined by this standard will never be in the range 0x80-0xff. * Vendors who define additional families must use an encoding in this range. */ typedef uint8_t psa_ecc_family_t; /** The type of PSA Diffie-Hellman group family identifiers. * * The group identifier is required to create an Diffie-Hellman key using the * PSA_KEY_TYPE_DH_KEY_PAIR() or PSA_KEY_TYPE_DH_PUBLIC_KEY() * macros. * * Values defined by this standard will never be in the range 0x80-0xff. * Vendors who define additional families must use an encoding in this range. */ typedef uint8_t psa_dh_family_t; /** \brief Encoding of a cryptographic algorithm. * * For algorithms that can be applied to multiple key types, this type * does not encode the key type. For example, for symmetric ciphers * based on a block cipher, #psa_algorithm_t encodes the block cipher * mode and the padding mode while the block cipher itself is encoded * via #psa_key_type_t. */ typedef uint32_t psa_algorithm_t; /**@}*/ /** \defgroup key_lifetimes Key lifetimes * @{ */ /** Encoding of key lifetimes. * * The lifetime of a key indicates where it is stored and what system actions * may create and destroy it. * * Lifetime values have the following structure: * - Bits 0-7 (#PSA_KEY_LIFETIME_GET_PERSISTENCE(\c lifetime)): * persistence level. This value indicates what device management * actions can cause it to be destroyed. In particular, it indicates * whether the key is _volatile_ or _persistent_. * See ::psa_key_persistence_t for more information. * - Bits 8-31 (#PSA_KEY_LIFETIME_GET_LOCATION(\c lifetime)): * location indicator. This value indicates which part of the system * has access to the key material and can perform operations using the key. * See ::psa_key_location_t for more information. * * Volatile keys are automatically destroyed when the application instance * terminates or on a power reset of the device. Persistent keys are * preserved until the application explicitly destroys them or until an * integration-specific device management event occurs (for example, * a factory reset). * * Persistent keys have a key identifier of type #mbedtls_svc_key_id_t. * This identifier remains valid throughout the lifetime of the key, * even if the application instance that created the key terminates. * The application can call psa_open_key() to open a persistent key that * it created previously. * * The default lifetime of a key is #PSA_KEY_LIFETIME_VOLATILE. The lifetime * #PSA_KEY_LIFETIME_PERSISTENT is supported if persistent storage is * available. Other lifetime values may be supported depending on the * library configuration. */ typedef uint32_t psa_key_lifetime_t; /** Encoding of key persistence levels. * * What distinguishes different persistence levels is what device management * events may cause keys to be destroyed. _Volatile_ keys are destroyed * by a power reset. Persistent keys may be destroyed by events such as * a transfer of ownership or a factory reset. What management events * actually affect persistent keys at different levels is outside the * scope of the PSA Cryptography specification. * * The PSA Cryptography specification defines the following values of * persistence levels: * - \c 0 = #PSA_KEY_PERSISTENCE_VOLATILE: volatile key. * A volatile key is automatically destroyed by the implementation when * the application instance terminates. In particular, a volatile key * is automatically destroyed on a power reset of the device. * - \c 1 = #PSA_KEY_PERSISTENCE_DEFAULT: * persistent key with a default lifetime. * - \c 2-254: currently not supported by Mbed TLS. * - \c 255 = #PSA_KEY_PERSISTENCE_READ_ONLY: * read-only or write-once key. * A key with this persistence level cannot be destroyed. * Mbed TLS does not currently offer a way to create such keys, but * integrations of Mbed TLS can use it for built-in keys that the * application cannot modify (for example, a hardware unique key (HUK)). * * \note Key persistence levels are 8-bit values. Key management * interfaces operate on lifetimes (type ::psa_key_lifetime_t) which * encode the persistence as the lower 8 bits of a 32-bit value. */ typedef uint8_t psa_key_persistence_t; /** Encoding of key location indicators. * * If an integration of Mbed TLS can make calls to external * cryptoprocessors such as secure elements, the location of a key * indicates which secure element performs the operations on the key. * Depending on the design of the secure element, the key * material may be stored either in the secure element, or * in wrapped (encrypted) form alongside the key metadata in the * primary local storage. * * The PSA Cryptography API specification defines the following values of * location indicators: * - \c 0: primary local storage. * This location is always available. * The primary local storage is typically the same storage area that * contains the key metadata. * - \c 1: primary secure element. * Integrations of Mbed TLS should support this value if there is a secure * element attached to the operating environment. * As a guideline, secure elements may provide higher resistance against * side channel and physical attacks than the primary local storage, but may * have restrictions on supported key types, sizes, policies and operations * and may have different performance characteristics. * - \c 2-0x7fffff: other locations defined by a PSA specification. * The PSA Cryptography API does not currently assign any meaning to these * locations, but future versions of that specification or other PSA * specifications may do so. * - \c 0x800000-0xffffff: vendor-defined locations. * No PSA specification will assign a meaning to locations in this range. * * \note Key location indicators are 24-bit values. Key management * interfaces operate on lifetimes (type ::psa_key_lifetime_t) which * encode the location as the upper 24 bits of a 32-bit value. */ typedef uint32_t psa_key_location_t; /** Encoding of identifiers of persistent keys. * * - Applications may freely choose key identifiers in the range * #PSA_KEY_ID_USER_MIN to #PSA_KEY_ID_USER_MAX. * - The implementation may define additional key identifiers in the range * #PSA_KEY_ID_VENDOR_MIN to #PSA_KEY_ID_VENDOR_MAX. * - 0 is reserved as an invalid key identifier. * - Key identifiers outside these ranges are reserved for future use. */ typedef uint32_t psa_key_id_t; #if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER) typedef psa_key_id_t mbedtls_svc_key_id_t; #else /* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */ /* Implementation-specific: The Mbed Cryptography library can be built as * part of a multi-client service that exposes the PSA Cryptograpy API in each * client and encodes the client identity in the key identifier argument of * functions such as psa_open_key(). */ typedef struct { psa_key_id_t key_id; mbedtls_key_owner_id_t owner; } mbedtls_svc_key_id_t; #endif /* !MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */ /**@}*/ /** \defgroup policy Key policies * @{ */ /** \brief Encoding of permitted usage on a key. */ typedef uint32_t psa_key_usage_t; /**@}*/ /** \defgroup attributes Key attributes * @{ */ /** The type of a structure containing key attributes. * * This is an opaque structure that can represent the metadata of a key * object. Metadata that can be stored in attributes includes: * - The location of the key in storage, indicated by its key identifier * and its lifetime. * - The key's policy, comprising usage flags and a specification of * the permitted algorithm(s). * - Information about the key itself: the key type and its size. * - Additional implementation-defined attributes. * * The actual key material is not considered an attribute of a key. * Key attributes do not contain information that is generally considered * highly confidential. * * An attribute structure works like a simple data structure where each function * `psa_set_key_xxx` sets a field and the corresponding function * `psa_get_key_xxx` retrieves the value of the corresponding field. * However, a future version of the library may report values that are * equivalent to the original one, but have a different encoding. Invalid * values may be mapped to different, also invalid values. * * An attribute structure may contain references to auxiliary resources, * for example pointers to allocated memory or indirect references to * pre-calculated values. In order to free such resources, the application * must call psa_reset_key_attributes(). As an exception, calling * psa_reset_key_attributes() on an attribute structure is optional if * the structure has only been modified by the following functions * since it was initialized or last reset with psa_reset_key_attributes(): * - psa_set_key_id() * - psa_set_key_lifetime() * - psa_set_key_type() * - psa_set_key_bits() * - psa_set_key_usage_flags() * - psa_set_key_algorithm() * * Before calling any function on a key attribute structure, the application * must initialize it by any of the following means: * - Set the structure to all-bits-zero, for example: * \code * psa_key_attributes_t attributes; * memset(&attributes, 0, sizeof(attributes)); * \endcode * - Initialize the structure to logical zero values, for example: * \code * psa_key_attributes_t attributes = {0}; * \endcode * - Initialize the structure to the initializer #PSA_KEY_ATTRIBUTES_INIT, * for example: * \code * psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; * \endcode * - Assign the result of the function psa_key_attributes_init() * to the structure, for example: * \code * psa_key_attributes_t attributes; * attributes = psa_key_attributes_init(); * \endcode * * A freshly initialized attribute structure contains the following * values: * * - lifetime: #PSA_KEY_LIFETIME_VOLATILE. * - key identifier: 0 (which is not a valid key identifier). * - type: \c 0 (meaning that the type is unspecified). * - key size: \c 0 (meaning that the size is unspecified). * - usage flags: \c 0 (which allows no usage except exporting a public key). * - algorithm: \c 0 (which allows no cryptographic usage, but allows * exporting). * * A typical sequence to create a key is as follows: * -# Create and initialize an attribute structure. * -# If the key is persistent, call psa_set_key_id(). * Also call psa_set_key_lifetime() to place the key in a non-default * location. * -# Set the key policy with psa_set_key_usage_flags() and * psa_set_key_algorithm(). * -# Set the key type with psa_set_key_type(). * Skip this step if copying an existing key with psa_copy_key(). * -# When generating a random key with psa_generate_key() or deriving a key * with psa_key_derivation_output_key(), set the desired key size with * psa_set_key_bits(). * -# Call a key creation function: psa_import_key(), psa_generate_key(), * psa_key_derivation_output_key() or psa_copy_key(). This function reads * the attribute structure, creates a key with these attributes, and * outputs a key identifier to the newly created key. * -# The attribute structure is now no longer necessary. * You may call psa_reset_key_attributes(), although this is optional * with the workflow presented here because the attributes currently * defined in this specification do not require any additional resources * beyond the structure itself. * * A typical sequence to query a key's attributes is as follows: * -# Call psa_get_key_attributes(). * -# Call `psa_get_key_xxx` functions to retrieve the attribute(s) that * you are interested in. * -# Call psa_reset_key_attributes() to free any resources that may be * used by the attribute structure. * * Once a key has been created, it is impossible to change its attributes. */ typedef struct psa_key_attributes_s psa_key_attributes_t; #ifndef __DOXYGEN_ONLY__ #if defined(MBEDTLS_PSA_CRYPTO_SE_C) /* Mbed Crypto defines this type in crypto_types.h because it is also * visible to applications through an implementation-specific extension. * For the PSA Cryptography specification, this type is only visible * via crypto_se_driver.h. */ typedef uint64_t psa_key_slot_number_t; #endif /* MBEDTLS_PSA_CRYPTO_SE_C */ #endif /* !__DOXYGEN_ONLY__ */ /**@}*/ /** \defgroup derivation Key derivation * @{ */ /** \brief Encoding of the step of a key derivation. */ typedef uint16_t psa_key_derivation_step_t; /**@}*/ #endif /* PSA_CRYPTO_TYPES_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_driver_common.h
/** * \file psa/crypto_driver_common.h * \brief Definitions for all PSA crypto drivers * * This file contains common definitions shared by all PSA crypto drivers. * Do not include it directly: instead, include the header file(s) for * the type(s) of driver that you are implementing. For example, if * you are writing a dynamically registered driver for a secure element, * include `psa/crypto_se_driver.h`. * * This file is part of the PSA Crypto Driver Model, containing functions for * driver developers to implement to enable hardware to be called in a * standardized way by a PSA Cryptographic API implementation. The functions * comprising the driver model, which driver authors implement, are not * intended to be called by application developers. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_DRIVER_COMMON_H #define PSA_CRYPTO_DRIVER_COMMON_H #include <stddef.h> #include <stdint.h> /* Include type definitions (psa_status_t, psa_algorithm_t, * psa_key_type_t, etc.) and macros to build and analyze values * of these types. */ #include "crypto_types.h" #include "crypto_values.h" /** For encrypt-decrypt functions, whether the operation is an encryption * or a decryption. */ typedef enum { PSA_CRYPTO_DRIVER_DECRYPT, PSA_CRYPTO_DRIVER_ENCRYPT } psa_encrypt_or_decrypt_t; #endif /* PSA_CRYPTO_DRIVER_COMMON_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_values.h
/** * \file psa/crypto_values.h * * \brief PSA cryptography module: macros to build and analyze integer values. * * \note This file may not be included directly. Applications must * include psa/crypto.h. Drivers must include the appropriate driver * header file. * * This file contains portable definitions of macros to build and analyze * values of integral types that encode properties of cryptographic keys, * designations of cryptographic algorithms, and error codes returned by * the library. * * This header file only defines preprocessor macros. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_VALUES_H #define PSA_CRYPTO_VALUES_H /** \defgroup error Error codes * @{ */ /* PSA error codes */ /** The action was completed successfully. */ #define PSA_SUCCESS ((psa_status_t)0) /** An error occurred that does not correspond to any defined * failure cause. * * Implementations may use this error code if none of the other standard * error codes are applicable. */ #define PSA_ERROR_GENERIC_ERROR ((psa_status_t)-132) /** The requested operation or a parameter is not supported * by this implementation. * * Implementations should return this error code when an enumeration * parameter such as a key type, algorithm, etc. is not recognized. * If a combination of parameters is recognized and identified as * not valid, return #PSA_ERROR_INVALID_ARGUMENT instead. */ #define PSA_ERROR_NOT_SUPPORTED ((psa_status_t)-134) /** The requested action is denied by a policy. * * Implementations should return this error code when the parameters * are recognized as valid and supported, and a policy explicitly * denies the requested operation. * * If a subset of the parameters of a function call identify a * forbidden operation, and another subset of the parameters are * not valid or not supported, it is unspecified whether the function * returns #PSA_ERROR_NOT_PERMITTED, #PSA_ERROR_NOT_SUPPORTED or * #PSA_ERROR_INVALID_ARGUMENT. */ #define PSA_ERROR_NOT_PERMITTED ((psa_status_t)-133) /** An output buffer is too small. * * Applications can call the \c PSA_xxx_SIZE macro listed in the function * description to determine a sufficient buffer size. * * Implementations should preferably return this error code only * in cases when performing the operation with a larger output * buffer would succeed. However implementations may return this * error if a function has invalid or unsupported parameters in addition * to the parameters that determine the necessary output buffer size. */ #define PSA_ERROR_BUFFER_TOO_SMALL ((psa_status_t)-138) /** Asking for an item that already exists * * Implementations should return this error, when attempting * to write an item (like a key) that already exists. */ #define PSA_ERROR_ALREADY_EXISTS ((psa_status_t)-139) /** Asking for an item that doesn't exist * * Implementations should return this error, if a requested item (like * a key) does not exist. */ #define PSA_ERROR_DOES_NOT_EXIST ((psa_status_t)-140) /** The requested action cannot be performed in the current state. * * Multipart operations return this error when one of the * functions is called out of sequence. Refer to the function * descriptions for permitted sequencing of functions. * * Implementations shall not return this error code to indicate * that a key either exists or not, * but shall instead return #PSA_ERROR_ALREADY_EXISTS or #PSA_ERROR_DOES_NOT_EXIST * as applicable. * * Implementations shall not return this error code to indicate that a * key identifier is invalid, but shall return #PSA_ERROR_INVALID_HANDLE * instead. */ #define PSA_ERROR_BAD_STATE ((psa_status_t)-137) /** The parameters passed to the function are invalid. * * Implementations may return this error any time a parameter or * combination of parameters are recognized as invalid. * * Implementations shall not return this error code to indicate that a * key identifier is invalid, but shall return #PSA_ERROR_INVALID_HANDLE * instead. */ #define PSA_ERROR_INVALID_ARGUMENT ((psa_status_t)-135) /** There is not enough runtime memory. * * If the action is carried out across multiple security realms, this * error can refer to available memory in any of the security realms. */ #define PSA_ERROR_INSUFFICIENT_MEMORY ((psa_status_t)-141) /** There is not enough persistent storage. * * Functions that modify the key storage return this error code if * there is insufficient storage space on the host media. In addition, * many functions that do not otherwise access storage may return this * error code if the implementation requires a mandatory log entry for * the requested action and the log storage space is full. */ #define PSA_ERROR_INSUFFICIENT_STORAGE ((psa_status_t)-142) /** There was a communication failure inside the implementation. * * This can indicate a communication failure between the application * and an external cryptoprocessor or between the cryptoprocessor and * an external volatile or persistent memory. A communication failure * may be transient or permanent depending on the cause. * * \warning If a function returns this error, it is undetermined * whether the requested action has completed or not. Implementations * should return #PSA_SUCCESS on successful completion whenever * possible, however functions may return #PSA_ERROR_COMMUNICATION_FAILURE * if the requested action was completed successfully in an external * cryptoprocessor but there was a breakdown of communication before * the cryptoprocessor could report the status to the application. */ #define PSA_ERROR_COMMUNICATION_FAILURE ((psa_status_t)-145) /** There was a storage failure that may have led to data loss. * * This error indicates that some persistent storage is corrupted. * It should not be used for a corruption of volatile memory * (use #PSA_ERROR_CORRUPTION_DETECTED), for a communication error * between the cryptoprocessor and its external storage (use * #PSA_ERROR_COMMUNICATION_FAILURE), or when the storage is * in a valid state but is full (use #PSA_ERROR_INSUFFICIENT_STORAGE). * * Note that a storage failure does not indicate that any data that was * previously read is invalid. However this previously read data may no * longer be readable from storage. * * When a storage failure occurs, it is no longer possible to ensure * the global integrity of the keystore. Depending on the global * integrity guarantees offered by the implementation, access to other * data may or may not fail even if the data is still readable but * its integrity cannot be guaranteed. * * Implementations should only use this error code to report a * permanent storage corruption. However application writers should * keep in mind that transient errors while reading the storage may be * reported using this error code. */ #define PSA_ERROR_STORAGE_FAILURE ((psa_status_t)-146) /** A hardware failure was detected. * * A hardware failure may be transient or permanent depending on the * cause. */ #define PSA_ERROR_HARDWARE_FAILURE ((psa_status_t)-147) /** A tampering attempt was detected. * * If an application receives this error code, there is no guarantee * that previously accessed or computed data was correct and remains * confidential. Applications should not perform any security function * and should enter a safe failure state. * * Implementations may return this error code if they detect an invalid * state that cannot happen during normal operation and that indicates * that the implementation's security guarantees no longer hold. Depending * on the implementation architecture and on its security and safety goals, * the implementation may forcibly terminate the application. * * This error code is intended as a last resort when a security breach * is detected and it is unsure whether the keystore data is still * protected. Implementations shall only return this error code * to report an alarm from a tampering detector, to indicate that * the confidentiality of stored data can no longer be guaranteed, * or to indicate that the integrity of previously returned data is now * considered compromised. Implementations shall not use this error code * to indicate a hardware failure that merely makes it impossible to * perform the requested operation (use #PSA_ERROR_COMMUNICATION_FAILURE, * #PSA_ERROR_STORAGE_FAILURE, #PSA_ERROR_HARDWARE_FAILURE, * #PSA_ERROR_INSUFFICIENT_ENTROPY or other applicable error code * instead). * * This error indicates an attack against the application. Implementations * shall not return this error code as a consequence of the behavior of * the application itself. */ #define PSA_ERROR_CORRUPTION_DETECTED ((psa_status_t)-151) /** There is not enough entropy to generate random data needed * for the requested action. * * This error indicates a failure of a hardware random generator. * Application writers should note that this error can be returned not * only by functions whose purpose is to generate random data, such * as key, IV or nonce generation, but also by functions that execute * an algorithm with a randomized result, as well as functions that * use randomization of intermediate computations as a countermeasure * to certain attacks. * * Implementations should avoid returning this error after psa_crypto_init() * has succeeded. Implementations should generate sufficient * entropy during initialization and subsequently use a cryptographically * secure pseudorandom generator (PRNG). However implementations may return * this error at any time if a policy requires the PRNG to be reseeded * during normal operation. */ #define PSA_ERROR_INSUFFICIENT_ENTROPY ((psa_status_t)-148) /** The signature, MAC or hash is incorrect. * * Verification functions return this error if the verification * calculations completed successfully, and the value to be verified * was determined to be incorrect. * * If the value to verify has an invalid size, implementations may return * either #PSA_ERROR_INVALID_ARGUMENT or #PSA_ERROR_INVALID_SIGNATURE. */ #define PSA_ERROR_INVALID_SIGNATURE ((psa_status_t)-149) /** The decrypted padding is incorrect. * * \warning In some protocols, when decrypting data, it is essential that * the behavior of the application does not depend on whether the padding * is correct, down to precise timing. Applications should prefer * protocols that use authenticated encryption rather than plain * encryption. If the application must perform a decryption of * unauthenticated data, the application writer should take care not * to reveal whether the padding is invalid. * * Implementations should strive to make valid and invalid padding * as close as possible to indistinguishable to an external observer. * In particular, the timing of a decryption operation should not * depend on the validity of the padding. */ #define PSA_ERROR_INVALID_PADDING ((psa_status_t)-150) /** Return this error when there's insufficient data when attempting * to read from a resource. */ #define PSA_ERROR_INSUFFICIENT_DATA ((psa_status_t)-143) /** The key identifier is not valid. See also :ref:\`key-handles\`. */ #define PSA_ERROR_INVALID_HANDLE ((psa_status_t)-136) /** Stored data has been corrupted. * * This error indicates that some persistent storage has suffered corruption. * It does not indicate the following situations, which have specific error * codes: * * - A corruption of volatile memory - use #PSA_ERROR_CORRUPTION_DETECTED. * - A communication error between the cryptoprocessor and its external * storage - use #PSA_ERROR_COMMUNICATION_FAILURE. * - When the storage is in a valid state but is full - use * #PSA_ERROR_INSUFFICIENT_STORAGE. * - When the storage fails for other reasons - use * #PSA_ERROR_STORAGE_FAILURE. * - When the stored data is not valid - use #PSA_ERROR_DATA_INVALID. * * \note A storage corruption does not indicate that any data that was * previously read is invalid. However this previously read data might no * longer be readable from storage. * * When a storage failure occurs, it is no longer possible to ensure the * global integrity of the keystore. */ #define PSA_ERROR_DATA_CORRUPT ((psa_status_t)-152) /** Data read from storage is not valid for the implementation. * * This error indicates that some data read from storage does not have a valid * format. It does not indicate the following situations, which have specific * error codes: * * - When the storage or stored data is corrupted - use #PSA_ERROR_DATA_CORRUPT * - When the storage fails for other reasons - use #PSA_ERROR_STORAGE_FAILURE * - An invalid argument to the API - use #PSA_ERROR_INVALID_ARGUMENT * * This error is typically a result of either storage corruption on a * cleartext storage backend, or an attempt to read data that was * written by an incompatible version of the library. */ #define PSA_ERROR_DATA_INVALID ((psa_status_t)-153) /**@}*/ /** \defgroup crypto_types Key and algorithm types * @{ */ /** An invalid key type value. * * Zero is not the encoding of any key type. */ #define PSA_KEY_TYPE_NONE ((psa_key_type_t)0x0000) /** Vendor-defined key type flag. * * Key types defined by this standard will never have the * #PSA_KEY_TYPE_VENDOR_FLAG bit set. Vendors who define additional key types * must use an encoding with the #PSA_KEY_TYPE_VENDOR_FLAG bit set and should * respect the bitwise structure used by standard encodings whenever practical. */ #define PSA_KEY_TYPE_VENDOR_FLAG ((psa_key_type_t)0x8000) #define PSA_KEY_TYPE_CATEGORY_MASK ((psa_key_type_t)0x7000) #define PSA_KEY_TYPE_CATEGORY_RAW ((psa_key_type_t)0x1000) #define PSA_KEY_TYPE_CATEGORY_SYMMETRIC ((psa_key_type_t)0x2000) #define PSA_KEY_TYPE_CATEGORY_PUBLIC_KEY ((psa_key_type_t)0x4000) #define PSA_KEY_TYPE_CATEGORY_KEY_PAIR ((psa_key_type_t)0x7000) #define PSA_KEY_TYPE_CATEGORY_FLAG_PAIR ((psa_key_type_t)0x3000) /** Whether a key type is vendor-defined. * * See also #PSA_KEY_TYPE_VENDOR_FLAG. */ #define PSA_KEY_TYPE_IS_VENDOR_DEFINED(type) \ (((type) & PSA_KEY_TYPE_VENDOR_FLAG) != 0) /** Whether a key type is an unstructured array of bytes. * * This encompasses both symmetric keys and non-key data. */ #define PSA_KEY_TYPE_IS_UNSTRUCTURED(type) \ (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_RAW || \ ((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_SYMMETRIC) /** Whether a key type is asymmetric: either a key pair or a public key. */ #define PSA_KEY_TYPE_IS_ASYMMETRIC(type) \ (((type) & PSA_KEY_TYPE_CATEGORY_MASK \ & ~PSA_KEY_TYPE_CATEGORY_FLAG_PAIR) == \ PSA_KEY_TYPE_CATEGORY_PUBLIC_KEY) /** Whether a key type is the public part of a key pair. */ #define PSA_KEY_TYPE_IS_PUBLIC_KEY(type) \ (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_PUBLIC_KEY) /** Whether a key type is a key pair containing a private part and a public * part. */ #define PSA_KEY_TYPE_IS_KEY_PAIR(type) \ (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_KEY_PAIR) /** The key pair type corresponding to a public key type. * * You may also pass a key pair type as \p type, it will be left unchanged. * * \param type A public key type or key pair type. * * \return The corresponding key pair type. * If \p type is not a public key or a key pair, * the return value is undefined. */ #define PSA_KEY_TYPE_KEY_PAIR_OF_PUBLIC_KEY(type) \ ((type) | PSA_KEY_TYPE_CATEGORY_FLAG_PAIR) /** The public key type corresponding to a key pair type. * * You may also pass a key pair type as \p type, it will be left unchanged. * * \param type A public key type or key pair type. * * \return The corresponding public key type. * If \p type is not a public key or a key pair, * the return value is undefined. */ #define PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) \ ((type) & ~PSA_KEY_TYPE_CATEGORY_FLAG_PAIR) /** Raw data. * * A "key" of this type cannot be used for any cryptographic operation. * Applications may use this type to store arbitrary data in the keystore. */ #define PSA_KEY_TYPE_RAW_DATA ((psa_key_type_t)0x1001) /** HMAC key. * * The key policy determines which underlying hash algorithm the key can be * used for. * * HMAC keys should generally have the same size as the underlying hash. * This size can be calculated with #PSA_HASH_LENGTH(\c alg) where * \c alg is the HMAC algorithm or the underlying hash algorithm. */ #define PSA_KEY_TYPE_HMAC ((psa_key_type_t)0x1100) /** A secret for key derivation. * * The key policy determines which key derivation algorithm the key * can be used for. */ #define PSA_KEY_TYPE_DERIVE ((psa_key_type_t)0x1200) /** Key for a cipher, AEAD or MAC algorithm based on the AES block cipher. * * The size of the key can be 16 bytes (AES-128), 24 bytes (AES-192) or * 32 bytes (AES-256). */ #define PSA_KEY_TYPE_AES ((psa_key_type_t)0x2400) /** Key for a cipher or MAC algorithm based on DES or 3DES (Triple-DES). * * The size of the key can be 64 bits (single DES), 128 bits (2-key 3DES) or * 192 bits (3-key 3DES). * * Note that single DES and 2-key 3DES are weak and strongly * deprecated and should only be used to decrypt legacy data. 3-key 3DES * is weak and deprecated and should only be used in legacy protocols. */ #define PSA_KEY_TYPE_DES ((psa_key_type_t)0x2301) /** Key for a cipher, AEAD or MAC algorithm based on the * Camellia block cipher. */ #define PSA_KEY_TYPE_CAMELLIA ((psa_key_type_t)0x2403) /** Key for the RC4 stream cipher. * * Note that RC4 is weak and deprecated and should only be used in * legacy protocols. */ #define PSA_KEY_TYPE_ARC4 ((psa_key_type_t)0x2002) /** Key for the ChaCha20 stream cipher or the Chacha20-Poly1305 AEAD algorithm. * * ChaCha20 and the ChaCha20_Poly1305 construction are defined in RFC 7539. * * Implementations must support 12-byte nonces, may support 8-byte nonces, * and should reject other sizes. */ #define PSA_KEY_TYPE_CHACHA20 ((psa_key_type_t)0x2004) /** RSA public key. * * The size of an RSA key is the bit size of the modulus. */ #define PSA_KEY_TYPE_RSA_PUBLIC_KEY ((psa_key_type_t)0x4001) /** RSA key pair (private and public key). * * The size of an RSA key is the bit size of the modulus. */ #define PSA_KEY_TYPE_RSA_KEY_PAIR ((psa_key_type_t)0x7001) /** Whether a key type is an RSA key (pair or public-only). */ #define PSA_KEY_TYPE_IS_RSA(type) \ (PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) == PSA_KEY_TYPE_RSA_PUBLIC_KEY) #define PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE ((psa_key_type_t)0x4100) #define PSA_KEY_TYPE_ECC_KEY_PAIR_BASE ((psa_key_type_t)0x7100) #define PSA_KEY_TYPE_ECC_CURVE_MASK ((psa_key_type_t)0x00ff) /** Elliptic curve key pair. * * The size of an elliptic curve key is the bit size associated with the curve, * i.e. the bit size of *q* for a curve over a field *F<sub>q</sub>*. * See the documentation of `PSA_ECC_FAMILY_xxx` curve families for details. * * \param curve A value of type ::psa_ecc_family_t that * identifies the ECC curve to be used. */ #define PSA_KEY_TYPE_ECC_KEY_PAIR(curve) \ (PSA_KEY_TYPE_ECC_KEY_PAIR_BASE | (curve)) /** Elliptic curve public key. * * The size of an elliptic curve public key is the same as the corresponding * private key (see #PSA_KEY_TYPE_ECC_KEY_PAIR and the documentation of * `PSA_ECC_FAMILY_xxx` curve families). * * \param curve A value of type ::psa_ecc_family_t that * identifies the ECC curve to be used. */ #define PSA_KEY_TYPE_ECC_PUBLIC_KEY(curve) \ (PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE | (curve)) /** Whether a key type is an elliptic curve key (pair or public-only). */ #define PSA_KEY_TYPE_IS_ECC(type) \ ((PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) & \ ~PSA_KEY_TYPE_ECC_CURVE_MASK) == PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE) /** Whether a key type is an elliptic curve key pair. */ #define PSA_KEY_TYPE_IS_ECC_KEY_PAIR(type) \ (((type) & ~PSA_KEY_TYPE_ECC_CURVE_MASK) == \ PSA_KEY_TYPE_ECC_KEY_PAIR_BASE) /** Whether a key type is an elliptic curve public key. */ #define PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY(type) \ (((type) & ~PSA_KEY_TYPE_ECC_CURVE_MASK) == \ PSA_KEY_TYPE_ECC_PUBLIC_KEY_BASE) /** Extract the curve from an elliptic curve key type. */ #define PSA_KEY_TYPE_ECC_GET_FAMILY(type) \ ((psa_ecc_family_t) (PSA_KEY_TYPE_IS_ECC(type) ? \ ((type) & PSA_KEY_TYPE_ECC_CURVE_MASK) : \ 0)) /** SEC Koblitz curves over prime fields. * * This family comprises the following curves: * secp192k1, secp224k1, secp256k1. * They are defined in _Standards for Efficient Cryptography_, * _SEC 2: Recommended Elliptic Curve Domain Parameters_. * https://www.secg.org/sec2-v2.pdf */ #define PSA_ECC_FAMILY_SECP_K1 ((psa_ecc_family_t) 0x17) /** SEC random curves over prime fields. * * This family comprises the following curves: * secp192k1, secp224r1, secp256r1, secp384r1, secp521r1. * They are defined in _Standards for Efficient Cryptography_, * _SEC 2: Recommended Elliptic Curve Domain Parameters_. * https://www.secg.org/sec2-v2.pdf */ #define PSA_ECC_FAMILY_SECP_R1 ((psa_ecc_family_t) 0x12) /* SECP160R2 (SEC2 v1, obsolete) */ #define PSA_ECC_FAMILY_SECP_R2 ((psa_ecc_family_t) 0x1b) /** SEC Koblitz curves over binary fields. * * This family comprises the following curves: * sect163k1, sect233k1, sect239k1, sect283k1, sect409k1, sect571k1. * They are defined in _Standards for Efficient Cryptography_, * _SEC 2: Recommended Elliptic Curve Domain Parameters_. * https://www.secg.org/sec2-v2.pdf */ #define PSA_ECC_FAMILY_SECT_K1 ((psa_ecc_family_t) 0x27) /** SEC random curves over binary fields. * * This family comprises the following curves: * sect163r1, sect233r1, sect283r1, sect409r1, sect571r1. * They are defined in _Standards for Efficient Cryptography_, * _SEC 2: Recommended Elliptic Curve Domain Parameters_. * https://www.secg.org/sec2-v2.pdf */ #define PSA_ECC_FAMILY_SECT_R1 ((psa_ecc_family_t) 0x22) /** SEC additional random curves over binary fields. * * This family comprises the following curve: * sect163r2. * It is defined in _Standards for Efficient Cryptography_, * _SEC 2: Recommended Elliptic Curve Domain Parameters_. * https://www.secg.org/sec2-v2.pdf */ #define PSA_ECC_FAMILY_SECT_R2 ((psa_ecc_family_t) 0x2b) /** Brainpool P random curves. * * This family comprises the following curves: * brainpoolP160r1, brainpoolP192r1, brainpoolP224r1, brainpoolP256r1, * brainpoolP320r1, brainpoolP384r1, brainpoolP512r1. * It is defined in RFC 5639. */ #define PSA_ECC_FAMILY_BRAINPOOL_P_R1 ((psa_ecc_family_t) 0x30) /** Curve25519 and Curve448. * * This family comprises the following Montgomery curves: * - 255-bit: Bernstein et al., * _Curve25519: new Diffie-Hellman speed records_, LNCS 3958, 2006. * The algorithm #PSA_ALG_ECDH performs X25519 when used with this curve. * - 448-bit: Hamburg, * _Ed448-Goldilocks, a new elliptic curve_, NIST ECC Workshop, 2015. * The algorithm #PSA_ALG_ECDH performs X448 when used with this curve. */ #define PSA_ECC_FAMILY_MONTGOMERY ((psa_ecc_family_t) 0x41) /** The twisted Edwards curves Ed25519 and Ed448. * * These curves are suitable for EdDSA (#PSA_ALG_PURE_EDDSA for both curves, * #PSA_ALG_ED25519PH for the 255-bit curve, * #PSA_ALG_ED448PH for the 448-bit curve). * * This family comprises the following twisted Edwards curves: * - 255-bit: Edwards25519, the twisted Edwards curve birationally equivalent * to Curve25519. * Bernstein et al., _Twisted Edwards curves_, Africacrypt 2008. * - 448-bit: Edwards448, the twisted Edwards curve birationally equivalent * to Curve448. * Hamburg, _Ed448-Goldilocks, a new elliptic curve_, NIST ECC Workshop, 2015. */ #define PSA_ECC_FAMILY_TWISTED_EDWARDS ((psa_ecc_family_t) 0x42) #define PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE ((psa_key_type_t)0x4200) #define PSA_KEY_TYPE_DH_KEY_PAIR_BASE ((psa_key_type_t)0x7200) #define PSA_KEY_TYPE_DH_GROUP_MASK ((psa_key_type_t)0x00ff) /** Diffie-Hellman key pair. * * \param group A value of type ::psa_dh_family_t that identifies the * Diffie-Hellman group to be used. */ #define PSA_KEY_TYPE_DH_KEY_PAIR(group) \ (PSA_KEY_TYPE_DH_KEY_PAIR_BASE | (group)) /** Diffie-Hellman public key. * * \param group A value of type ::psa_dh_family_t that identifies the * Diffie-Hellman group to be used. */ #define PSA_KEY_TYPE_DH_PUBLIC_KEY(group) \ (PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE | (group)) /** Whether a key type is a Diffie-Hellman key (pair or public-only). */ #define PSA_KEY_TYPE_IS_DH(type) \ ((PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(type) & \ ~PSA_KEY_TYPE_DH_GROUP_MASK) == PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE) /** Whether a key type is a Diffie-Hellman key pair. */ #define PSA_KEY_TYPE_IS_DH_KEY_PAIR(type) \ (((type) & ~PSA_KEY_TYPE_DH_GROUP_MASK) == \ PSA_KEY_TYPE_DH_KEY_PAIR_BASE) /** Whether a key type is a Diffie-Hellman public key. */ #define PSA_KEY_TYPE_IS_DH_PUBLIC_KEY(type) \ (((type) & ~PSA_KEY_TYPE_DH_GROUP_MASK) == \ PSA_KEY_TYPE_DH_PUBLIC_KEY_BASE) /** Extract the group from a Diffie-Hellman key type. */ #define PSA_KEY_TYPE_DH_GET_FAMILY(type) \ ((psa_dh_family_t) (PSA_KEY_TYPE_IS_DH(type) ? \ ((type) & PSA_KEY_TYPE_DH_GROUP_MASK) : \ 0)) /** Diffie-Hellman groups defined in RFC 7919 Appendix A. * * This family includes groups with the following key sizes (in bits): * 2048, 3072, 4096, 6144, 8192. A given implementation may support * all of these sizes or only a subset. */ #define PSA_DH_FAMILY_RFC7919 ((psa_dh_family_t) 0x03) #define PSA_GET_KEY_TYPE_BLOCK_SIZE_EXPONENT(type) \ (((type) >> 8) & 7) /** The block size of a block cipher. * * \param type A cipher key type (value of type #psa_key_type_t). * * \return The block size for a block cipher, or 1 for a stream cipher. * The return value is undefined if \p type is not a supported * cipher key type. * * \note It is possible to build stream cipher algorithms on top of a block * cipher, for example CTR mode (#PSA_ALG_CTR). * This macro only takes the key type into account, so it cannot be * used to determine the size of the data that #psa_cipher_update() * might buffer for future processing in general. * * \note This macro returns a compile-time constant if its argument is one. * * \warning This macro may evaluate its argument multiple times. */ #define PSA_BLOCK_CIPHER_BLOCK_LENGTH(type) \ (((type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_SYMMETRIC ? \ 1u << PSA_GET_KEY_TYPE_BLOCK_SIZE_EXPONENT(type) : \ 0u) /** Vendor-defined algorithm flag. * * Algorithms defined by this standard will never have the #PSA_ALG_VENDOR_FLAG * bit set. Vendors who define additional algorithms must use an encoding with * the #PSA_ALG_VENDOR_FLAG bit set and should respect the bitwise structure * used by standard encodings whenever practical. */ #define PSA_ALG_VENDOR_FLAG ((psa_algorithm_t)0x80000000) #define PSA_ALG_CATEGORY_MASK ((psa_algorithm_t)0x7f000000) #define PSA_ALG_CATEGORY_HASH ((psa_algorithm_t)0x02000000) #define PSA_ALG_CATEGORY_MAC ((psa_algorithm_t)0x03000000) #define PSA_ALG_CATEGORY_CIPHER ((psa_algorithm_t)0x04000000) #define PSA_ALG_CATEGORY_AEAD ((psa_algorithm_t)0x05000000) #define PSA_ALG_CATEGORY_SIGN ((psa_algorithm_t)0x06000000) #define PSA_ALG_CATEGORY_ASYMMETRIC_ENCRYPTION ((psa_algorithm_t)0x07000000) #define PSA_ALG_CATEGORY_KEY_DERIVATION ((psa_algorithm_t)0x08000000) #define PSA_ALG_CATEGORY_KEY_AGREEMENT ((psa_algorithm_t)0x09000000) /** Whether an algorithm is vendor-defined. * * See also #PSA_ALG_VENDOR_FLAG. */ #define PSA_ALG_IS_VENDOR_DEFINED(alg) \ (((alg) & PSA_ALG_VENDOR_FLAG) != 0) /** Whether the specified algorithm is a hash algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is a hash algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_HASH(alg) \ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_HASH) /** Whether the specified algorithm is a MAC algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is a MAC algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_MAC(alg) \ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_MAC) /** Whether the specified algorithm is a symmetric cipher algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is a symmetric cipher algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_CIPHER(alg) \ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_CIPHER) /** Whether the specified algorithm is an authenticated encryption * with associated data (AEAD) algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is an AEAD algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_AEAD(alg) \ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_AEAD) /** Whether the specified algorithm is an asymmetric signature algorithm, * also known as public-key signature algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is an asymmetric signature algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_SIGN(alg) \ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_SIGN) /** Whether the specified algorithm is an asymmetric encryption algorithm, * also known as public-key encryption algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is an asymmetric encryption algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_ASYMMETRIC_ENCRYPTION(alg) \ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_ASYMMETRIC_ENCRYPTION) /** Whether the specified algorithm is a key agreement algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is a key agreement algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_KEY_AGREEMENT(alg) \ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_KEY_AGREEMENT) /** Whether the specified algorithm is a key derivation algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is a key derivation algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_KEY_DERIVATION(alg) \ (((alg) & PSA_ALG_CATEGORY_MASK) == PSA_ALG_CATEGORY_KEY_DERIVATION) #define PSA_ALG_HASH_MASK ((psa_algorithm_t)0x000000ff) /** MD2 */ #define PSA_ALG_MD2 ((psa_algorithm_t)0x02000001) /** MD4 */ #define PSA_ALG_MD4 ((psa_algorithm_t)0x02000002) /** MD5 */ #define PSA_ALG_MD5 ((psa_algorithm_t)0x02000003) /** PSA_ALG_RIPEMD160 */ #define PSA_ALG_RIPEMD160 ((psa_algorithm_t)0x02000004) /** SHA1 */ #define PSA_ALG_SHA_1 ((psa_algorithm_t)0x02000005) /** SHA2-224 */ #define PSA_ALG_SHA_224 ((psa_algorithm_t)0x02000008) /** SHA2-256 */ #define PSA_ALG_SHA_256 ((psa_algorithm_t)0x02000009) /** SHA2-384 */ #define PSA_ALG_SHA_384 ((psa_algorithm_t)0x0200000a) /** SHA2-512 */ #define PSA_ALG_SHA_512 ((psa_algorithm_t)0x0200000b) /** SHA2-512/224 */ #define PSA_ALG_SHA_512_224 ((psa_algorithm_t)0x0200000c) /** SHA2-512/256 */ #define PSA_ALG_SHA_512_256 ((psa_algorithm_t)0x0200000d) /** SHA3-224 */ #define PSA_ALG_SHA3_224 ((psa_algorithm_t)0x02000010) /** SHA3-256 */ #define PSA_ALG_SHA3_256 ((psa_algorithm_t)0x02000011) /** SHA3-384 */ #define PSA_ALG_SHA3_384 ((psa_algorithm_t)0x02000012) /** SHA3-512 */ #define PSA_ALG_SHA3_512 ((psa_algorithm_t)0x02000013) /** The first 512 bits (64 bytes) of the SHAKE256 output. * * This is the prehashing for Ed448ph (see #PSA_ALG_ED448PH). For other * scenarios where a hash function based on SHA3/SHAKE is desired, SHA3-512 * has the same output size and a (theoretically) higher security strength. */ #define PSA_ALG_SHAKE256_512 ((psa_algorithm_t)0x02000015) /** In a hash-and-sign algorithm policy, allow any hash algorithm. * * This value may be used to form the algorithm usage field of a policy * for a signature algorithm that is parametrized by a hash. The key * may then be used to perform operations using the same signature * algorithm parametrized with any supported hash. * * That is, suppose that `PSA_xxx_SIGNATURE` is one of the following macros: * - #PSA_ALG_RSA_PKCS1V15_SIGN, #PSA_ALG_RSA_PSS, * - #PSA_ALG_ECDSA, #PSA_ALG_DETERMINISTIC_ECDSA. * Then you may create and use a key as follows: * - Set the key usage field using #PSA_ALG_ANY_HASH, for example: * ``` * psa_set_key_usage_flags(&attributes, PSA_KEY_USAGE_SIGN_HASH); // or VERIFY * psa_set_key_algorithm(&attributes, PSA_xxx_SIGNATURE(PSA_ALG_ANY_HASH)); * ``` * - Import or generate key material. * - Call psa_sign_hash() or psa_verify_hash(), passing * an algorithm built from `PSA_xxx_SIGNATURE` and a specific hash. Each * call to sign or verify a message may use a different hash. * ``` * psa_sign_hash(key, PSA_xxx_SIGNATURE(PSA_ALG_SHA_256), ...); * psa_sign_hash(key, PSA_xxx_SIGNATURE(PSA_ALG_SHA_512), ...); * psa_sign_hash(key, PSA_xxx_SIGNATURE(PSA_ALG_SHA3_256), ...); * ``` * * This value may not be used to build other algorithms that are * parametrized over a hash. For any valid use of this macro to build * an algorithm \c alg, #PSA_ALG_IS_HASH_AND_SIGN(\c alg) is true. * * This value may not be used to build an algorithm specification to * perform an operation. It is only valid to build policies. */ #define PSA_ALG_ANY_HASH ((psa_algorithm_t)0x020000ff) #define PSA_ALG_MAC_SUBCATEGORY_MASK ((psa_algorithm_t)0x00c00000) #define PSA_ALG_HMAC_BASE ((psa_algorithm_t)0x03800000) /** Macro to build an HMAC algorithm. * * For example, #PSA_ALG_HMAC(#PSA_ALG_SHA_256) is HMAC-SHA-256. * * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true). * * \return The corresponding HMAC algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_HMAC(hash_alg) \ (PSA_ALG_HMAC_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) #define PSA_ALG_HMAC_GET_HASH(hmac_alg) \ (PSA_ALG_CATEGORY_HASH | ((hmac_alg) & PSA_ALG_HASH_MASK)) /** Whether the specified algorithm is an HMAC algorithm. * * HMAC is a family of MAC algorithms that are based on a hash function. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is an HMAC algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_HMAC(alg) \ (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_MAC_SUBCATEGORY_MASK)) == \ PSA_ALG_HMAC_BASE) /* In the encoding of a MAC algorithm, the bits corresponding to * PSA_ALG_MAC_TRUNCATION_MASK encode the length to which the MAC is * truncated. As an exception, the value 0 means the untruncated algorithm, * whatever its length is. The length is encoded in 6 bits, so it can * reach up to 63; the largest MAC is 64 bytes so its trivial truncation * to full length is correctly encoded as 0 and any non-trivial truncation * is correctly encoded as a value between 1 and 63. */ #define PSA_ALG_MAC_TRUNCATION_MASK ((psa_algorithm_t)0x003f0000) #define PSA_MAC_TRUNCATION_OFFSET 16 /* In the encoding of a MAC algorithm, the bit corresponding to * #PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG encodes the fact that the algorithm * is a wildcard algorithm. A key with such wildcard algorithm as permitted * algorithm policy can be used with any algorithm corresponding to the * same base class and having a (potentially truncated) MAC length greater or * equal than the one encoded in #PSA_ALG_MAC_TRUNCATION_MASK. */ #define PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ((psa_algorithm_t)0x00008000) /** Macro to build a truncated MAC algorithm. * * A truncated MAC algorithm is identical to the corresponding MAC * algorithm except that the MAC value for the truncated algorithm * consists of only the first \p mac_length bytes of the MAC value * for the untruncated algorithm. * * \note This macro may allow constructing algorithm identifiers that * are not valid, either because the specified length is larger * than the untruncated MAC or because the specified length is * smaller than permitted by the implementation. * * \note It is implementation-defined whether a truncated MAC that * is truncated to the same length as the MAC of the untruncated * algorithm is considered identical to the untruncated algorithm * for policy comparison purposes. * * \param mac_alg A MAC algorithm identifier (value of type * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p mac_alg) * is true). This may be a truncated or untruncated * MAC algorithm. * \param mac_length Desired length of the truncated MAC in bytes. * This must be at most the full length of the MAC * and must be at least an implementation-specified * minimum. The implementation-specified minimum * shall not be zero. * * \return The corresponding MAC algorithm with the specified * length. * \return Unspecified if \p mac_alg is not a supported * MAC algorithm or if \p mac_length is too small or * too large for the specified MAC algorithm. */ #define PSA_ALG_TRUNCATED_MAC(mac_alg, mac_length) \ (((mac_alg) & ~(PSA_ALG_MAC_TRUNCATION_MASK | \ PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG)) | \ ((mac_length) << PSA_MAC_TRUNCATION_OFFSET & PSA_ALG_MAC_TRUNCATION_MASK)) /** Macro to build the base MAC algorithm corresponding to a truncated * MAC algorithm. * * \param mac_alg A MAC algorithm identifier (value of type * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p mac_alg) * is true). This may be a truncated or untruncated * MAC algorithm. * * \return The corresponding base MAC algorithm. * \return Unspecified if \p mac_alg is not a supported * MAC algorithm. */ #define PSA_ALG_FULL_LENGTH_MAC(mac_alg) \ ((mac_alg) & ~(PSA_ALG_MAC_TRUNCATION_MASK | \ PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG)) /** Length to which a MAC algorithm is truncated. * * \param mac_alg A MAC algorithm identifier (value of type * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p mac_alg) * is true). * * \return Length of the truncated MAC in bytes. * \return 0 if \p mac_alg is a non-truncated MAC algorithm. * \return Unspecified if \p mac_alg is not a supported * MAC algorithm. */ #define PSA_MAC_TRUNCATED_LENGTH(mac_alg) \ (((mac_alg) & PSA_ALG_MAC_TRUNCATION_MASK) >> PSA_MAC_TRUNCATION_OFFSET) /** Macro to build a MAC minimum-MAC-length wildcard algorithm. * * A minimum-MAC-length MAC wildcard algorithm permits all MAC algorithms * sharing the same base algorithm, and where the (potentially truncated) MAC * length of the specific algorithm is equal to or larger then the wildcard * algorithm's minimum MAC length. * * \note When setting the minimum required MAC length to less than the * smallest MAC length allowed by the base algorithm, this effectively * becomes an 'any-MAC-length-allowed' policy for that base algorithm. * * \param mac_alg A MAC algorithm identifier (value of type * #psa_algorithm_t such that #PSA_ALG_IS_MAC(\p mac_alg) * is true). * \param min_mac_length Desired minimum length of the message authentication * code in bytes. This must be at most the untruncated * length of the MAC and must be at least 1. * * \return The corresponding MAC wildcard algorithm with the * specified minimum length. * \return Unspecified if \p mac_alg is not a supported MAC * algorithm or if \p min_mac_length is less than 1 or * too large for the specified MAC algorithm. */ #define PSA_ALG_AT_LEAST_THIS_LENGTH_MAC(mac_alg, min_mac_length) \ ( PSA_ALG_TRUNCATED_MAC(mac_alg, min_mac_length) | \ PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG ) #define PSA_ALG_CIPHER_MAC_BASE ((psa_algorithm_t)0x03c00000) /** The CBC-MAC construction over a block cipher * * \warning CBC-MAC is insecure in many cases. * A more secure mode, such as #PSA_ALG_CMAC, is recommended. */ #define PSA_ALG_CBC_MAC ((psa_algorithm_t)0x03c00100) /** The CMAC construction over a block cipher */ #define PSA_ALG_CMAC ((psa_algorithm_t)0x03c00200) /** Whether the specified algorithm is a MAC algorithm based on a block cipher. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is a MAC algorithm based on a block cipher, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_BLOCK_CIPHER_MAC(alg) \ (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_MAC_SUBCATEGORY_MASK)) == \ PSA_ALG_CIPHER_MAC_BASE) #define PSA_ALG_CIPHER_STREAM_FLAG ((psa_algorithm_t)0x00800000) #define PSA_ALG_CIPHER_FROM_BLOCK_FLAG ((psa_algorithm_t)0x00400000) /** Whether the specified algorithm is a stream cipher. * * A stream cipher is a symmetric cipher that encrypts or decrypts messages * by applying a bitwise-xor with a stream of bytes that is generated * from a key. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is a stream cipher algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier or if it is not a symmetric cipher algorithm. */ #define PSA_ALG_IS_STREAM_CIPHER(alg) \ (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_CIPHER_STREAM_FLAG)) == \ (PSA_ALG_CATEGORY_CIPHER | PSA_ALG_CIPHER_STREAM_FLAG)) /** The stream cipher mode of a stream cipher algorithm. * * The underlying stream cipher is determined by the key type. * - To use ChaCha20, use a key type of #PSA_KEY_TYPE_CHACHA20. * - To use ARC4, use a key type of #PSA_KEY_TYPE_ARC4. */ #define PSA_ALG_STREAM_CIPHER ((psa_algorithm_t)0x04800100) /** The CTR stream cipher mode. * * CTR is a stream cipher which is built from a block cipher. * The underlying block cipher is determined by the key type. * For example, to use AES-128-CTR, use this algorithm with * a key of type #PSA_KEY_TYPE_AES and a length of 128 bits (16 bytes). */ #define PSA_ALG_CTR ((psa_algorithm_t)0x04c01000) /** The CFB stream cipher mode. * * The underlying block cipher is determined by the key type. */ #define PSA_ALG_CFB ((psa_algorithm_t)0x04c01100) /** The OFB stream cipher mode. * * The underlying block cipher is determined by the key type. */ #define PSA_ALG_OFB ((psa_algorithm_t)0x04c01200) /** The XTS cipher mode. * * XTS is a cipher mode which is built from a block cipher. It requires at * least one full block of input, but beyond this minimum the input * does not need to be a whole number of blocks. */ #define PSA_ALG_XTS ((psa_algorithm_t)0x0440ff00) /** The Electronic Code Book (ECB) mode of a block cipher, with no padding. * * \warning ECB mode does not protect the confidentiality of the encrypted data * except in extremely narrow circumstances. It is recommended that applications * only use ECB if they need to construct an operating mode that the * implementation does not provide. Implementations are encouraged to provide * the modes that applications need in preference to supporting direct access * to ECB. * * The underlying block cipher is determined by the key type. * * This symmetric cipher mode can only be used with messages whose lengths are a * multiple of the block size of the chosen block cipher. * * ECB mode does not accept an initialization vector (IV). When using a * multi-part cipher operation with this algorithm, psa_cipher_generate_iv() * and psa_cipher_set_iv() must not be called. */ #define PSA_ALG_ECB_NO_PADDING ((psa_algorithm_t)0x04404400) /** The CBC block cipher chaining mode, with no padding. * * The underlying block cipher is determined by the key type. * * This symmetric cipher mode can only be used with messages whose lengths * are whole number of blocks for the chosen block cipher. */ #define PSA_ALG_CBC_NO_PADDING ((psa_algorithm_t)0x04404000) /** The CBC block cipher chaining mode with PKCS#7 padding. * * The underlying block cipher is determined by the key type. * * This is the padding method defined by PKCS#7 (RFC 2315) &sect;10.3. */ #define PSA_ALG_CBC_PKCS7 ((psa_algorithm_t)0x04404100) #define PSA_ALG_AEAD_FROM_BLOCK_FLAG ((psa_algorithm_t)0x00400000) /** Whether the specified algorithm is an AEAD mode on a block cipher. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is an AEAD algorithm which is an AEAD mode based on * a block cipher, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER(alg) \ (((alg) & (PSA_ALG_CATEGORY_MASK | PSA_ALG_AEAD_FROM_BLOCK_FLAG)) == \ (PSA_ALG_CATEGORY_AEAD | PSA_ALG_AEAD_FROM_BLOCK_FLAG)) /** The CCM authenticated encryption algorithm. * * The underlying block cipher is determined by the key type. */ #define PSA_ALG_CCM ((psa_algorithm_t)0x05500100) /** The GCM authenticated encryption algorithm. * * The underlying block cipher is determined by the key type. */ #define PSA_ALG_GCM ((psa_algorithm_t)0x05500200) /** The Chacha20-Poly1305 AEAD algorithm. * * The ChaCha20_Poly1305 construction is defined in RFC 7539. * * Implementations must support 12-byte nonces, may support 8-byte nonces, * and should reject other sizes. * * Implementations must support 16-byte tags and should reject other sizes. */ #define PSA_ALG_CHACHA20_POLY1305 ((psa_algorithm_t)0x05100500) /* In the encoding of a AEAD algorithm, the bits corresponding to * PSA_ALG_AEAD_TAG_LENGTH_MASK encode the length of the AEAD tag. * The constants for default lengths follow this encoding. */ #define PSA_ALG_AEAD_TAG_LENGTH_MASK ((psa_algorithm_t)0x003f0000) #define PSA_AEAD_TAG_LENGTH_OFFSET 16 /* In the encoding of an AEAD algorithm, the bit corresponding to * #PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG encodes the fact that the algorithm * is a wildcard algorithm. A key with such wildcard algorithm as permitted * algorithm policy can be used with any algorithm corresponding to the * same base class and having a tag length greater than or equal to the one * encoded in #PSA_ALG_AEAD_TAG_LENGTH_MASK. */ #define PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ((psa_algorithm_t)0x00008000) /** Macro to build a shortened AEAD algorithm. * * A shortened AEAD algorithm is similar to the corresponding AEAD * algorithm, but has an authentication tag that consists of fewer bytes. * Depending on the algorithm, the tag length may affect the calculation * of the ciphertext. * * \param aead_alg An AEAD algorithm identifier (value of type * #psa_algorithm_t such that #PSA_ALG_IS_AEAD(\p aead_alg) * is true). * \param tag_length Desired length of the authentication tag in bytes. * * \return The corresponding AEAD algorithm with the specified * length. * \return Unspecified if \p aead_alg is not a supported * AEAD algorithm or if \p tag_length is not valid * for the specified AEAD algorithm. */ #define PSA_ALG_AEAD_WITH_SHORTENED_TAG(aead_alg, tag_length) \ (((aead_alg) & ~(PSA_ALG_AEAD_TAG_LENGTH_MASK | \ PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG)) | \ ((tag_length) << PSA_AEAD_TAG_LENGTH_OFFSET & \ PSA_ALG_AEAD_TAG_LENGTH_MASK)) /** Retrieve the tag length of a specified AEAD algorithm * * \param aead_alg An AEAD algorithm identifier (value of type * #psa_algorithm_t such that #PSA_ALG_IS_AEAD(\p aead_alg) * is true). * * \return The tag length specified by the input algorithm. * \return Unspecified if \p aead_alg is not a supported * AEAD algorithm. */ #define PSA_ALG_AEAD_GET_TAG_LENGTH(aead_alg) \ (((aead_alg) & PSA_ALG_AEAD_TAG_LENGTH_MASK) >> \ PSA_AEAD_TAG_LENGTH_OFFSET ) /** Calculate the corresponding AEAD algorithm with the default tag length. * * \param aead_alg An AEAD algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p aead_alg) is true). * * \return The corresponding AEAD algorithm with the default * tag length for that algorithm. */ #define PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG(aead_alg) \ ( \ PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE(aead_alg, PSA_ALG_CCM) \ PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE(aead_alg, PSA_ALG_GCM) \ PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE(aead_alg, PSA_ALG_CHACHA20_POLY1305) \ 0) #define PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG_CASE(aead_alg, ref) \ PSA_ALG_AEAD_WITH_SHORTENED_TAG(aead_alg, 0) == \ PSA_ALG_AEAD_WITH_SHORTENED_TAG(ref, 0) ? \ ref : /** Macro to build an AEAD minimum-tag-length wildcard algorithm. * * A minimum-tag-length AEAD wildcard algorithm permits all AEAD algorithms * sharing the same base algorithm, and where the tag length of the specific * algorithm is equal to or larger then the minimum tag length specified by the * wildcard algorithm. * * \note When setting the minimum required tag length to less than the * smallest tag length allowed by the base algorithm, this effectively * becomes an 'any-tag-length-allowed' policy for that base algorithm. * * \param aead_alg An AEAD algorithm identifier (value of type * #psa_algorithm_t such that * #PSA_ALG_IS_AEAD(\p aead_alg) is true). * \param min_tag_length Desired minimum length of the authentication tag in * bytes. This must be at least 1 and at most the largest * allowed tag length of the algorithm. * * \return The corresponding AEAD wildcard algorithm with the * specified minimum length. * \return Unspecified if \p aead_alg is not a supported * AEAD algorithm or if \p min_tag_length is less than 1 * or too large for the specified AEAD algorithm. */ #define PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG(aead_alg, min_tag_length) \ ( PSA_ALG_AEAD_WITH_SHORTENED_TAG(aead_alg, min_tag_length) | \ PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG ) #define PSA_ALG_RSA_PKCS1V15_SIGN_BASE ((psa_algorithm_t)0x06000200) /** RSA PKCS#1 v1.5 signature with hashing. * * This is the signature scheme defined by RFC 8017 * (PKCS#1: RSA Cryptography Specifications) under the name * RSASSA-PKCS1-v1_5. * * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true). * This includes #PSA_ALG_ANY_HASH * when specifying the algorithm in a usage policy. * * \return The corresponding RSA PKCS#1 v1.5 signature algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_RSA_PKCS1V15_SIGN(hash_alg) \ (PSA_ALG_RSA_PKCS1V15_SIGN_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) /** Raw PKCS#1 v1.5 signature. * * The input to this algorithm is the DigestInfo structure used by * RFC 8017 (PKCS#1: RSA Cryptography Specifications), &sect;9.2 * steps 3&ndash;6. */ #define PSA_ALG_RSA_PKCS1V15_SIGN_RAW PSA_ALG_RSA_PKCS1V15_SIGN_BASE #define PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) \ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_RSA_PKCS1V15_SIGN_BASE) #define PSA_ALG_RSA_PSS_BASE ((psa_algorithm_t)0x06000300) /** RSA PSS signature with hashing. * * This is the signature scheme defined by RFC 8017 * (PKCS#1: RSA Cryptography Specifications) under the name * RSASSA-PSS, with the message generation function MGF1, and with * a salt length equal to the length of the hash. The specified * hash algorithm is used to hash the input message, to create the * salted hash, and for the mask generation. * * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true). * This includes #PSA_ALG_ANY_HASH * when specifying the algorithm in a usage policy. * * \return The corresponding RSA PSS signature algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_RSA_PSS(hash_alg) \ (PSA_ALG_RSA_PSS_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) #define PSA_ALG_IS_RSA_PSS(alg) \ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_RSA_PSS_BASE) #define PSA_ALG_ECDSA_BASE ((psa_algorithm_t)0x06000600) /** ECDSA signature with hashing. * * This is the ECDSA signature scheme defined by ANSI X9.62, * with a random per-message secret number (*k*). * * The representation of the signature as a byte string consists of * the concatentation of the signature values *r* and *s*. Each of * *r* and *s* is encoded as an *N*-octet string, where *N* is the length * of the base point of the curve in octets. Each value is represented * in big-endian order (most significant octet first). * * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true). * This includes #PSA_ALG_ANY_HASH * when specifying the algorithm in a usage policy. * * \return The corresponding ECDSA signature algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_ECDSA(hash_alg) \ (PSA_ALG_ECDSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) /** ECDSA signature without hashing. * * This is the same signature scheme as #PSA_ALG_ECDSA(), but * without specifying a hash algorithm. This algorithm may only be * used to sign or verify a sequence of bytes that should be an * already-calculated hash. Note that the input is padded with * zeros on the left or truncated on the left as required to fit * the curve size. */ #define PSA_ALG_ECDSA_ANY PSA_ALG_ECDSA_BASE #define PSA_ALG_DETERMINISTIC_ECDSA_BASE ((psa_algorithm_t)0x06000700) /** Deterministic ECDSA signature with hashing. * * This is the deterministic ECDSA signature scheme defined by RFC 6979. * * The representation of a signature is the same as with #PSA_ALG_ECDSA(). * * Note that when this algorithm is used for verification, signatures * made with randomized ECDSA (#PSA_ALG_ECDSA(\p hash_alg)) with the * same private key are accepted. In other words, * #PSA_ALG_DETERMINISTIC_ECDSA(\p hash_alg) differs from * #PSA_ALG_ECDSA(\p hash_alg) only for signature, not for verification. * * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true). * This includes #PSA_ALG_ANY_HASH * when specifying the algorithm in a usage policy. * * \return The corresponding deterministic ECDSA signature * algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_DETERMINISTIC_ECDSA(hash_alg) \ (PSA_ALG_DETERMINISTIC_ECDSA_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) #define PSA_ALG_ECDSA_DETERMINISTIC_FLAG ((psa_algorithm_t)0x00000100) #define PSA_ALG_IS_ECDSA(alg) \ (((alg) & ~PSA_ALG_HASH_MASK & ~PSA_ALG_ECDSA_DETERMINISTIC_FLAG) == \ PSA_ALG_ECDSA_BASE) #define PSA_ALG_ECDSA_IS_DETERMINISTIC(alg) \ (((alg) & PSA_ALG_ECDSA_DETERMINISTIC_FLAG) != 0) #define PSA_ALG_IS_DETERMINISTIC_ECDSA(alg) \ (PSA_ALG_IS_ECDSA(alg) && PSA_ALG_ECDSA_IS_DETERMINISTIC(alg)) #define PSA_ALG_IS_RANDOMIZED_ECDSA(alg) \ (PSA_ALG_IS_ECDSA(alg) && !PSA_ALG_ECDSA_IS_DETERMINISTIC(alg)) /** Edwards-curve digital signature algorithm without prehashing (PureEdDSA), * using standard parameters. * * Contexts are not supported in the current version of this specification * because there is no suitable signature interface that can take the * context as a parameter. A future version of this specification may add * suitable functions and extend this algorithm to support contexts. * * PureEdDSA requires an elliptic curve key on a twisted Edwards curve. * In this specification, the following curves are supported: * - #PSA_ECC_FAMILY_TWISTED_EDWARDS, 255-bit: Ed25519 as specified * in RFC 8032. * The curve is Edwards25519. * The hash function used internally is SHA-512. * - #PSA_ECC_FAMILY_TWISTED_EDWARDS, 448-bit: Ed448 as specified * in RFC 8032. * The curve is Edwards448. * The hash function used internally is the first 114 bytes of the * SHAKE256 output. * * This algorithm can be used with psa_sign_message() and * psa_verify_message(). Since there is no prehashing, it cannot be used * with psa_sign_hash() or psa_verify_hash(). * * The signature format is the concatenation of R and S as defined by * RFC 8032 §5.1.6 and §5.2.6 (a 64-byte string for Ed25519, a 114-byte * string for Ed448). */ #define PSA_ALG_PURE_EDDSA ((psa_algorithm_t)0x06000800) #define PSA_ALG_HASH_EDDSA_BASE ((psa_algorithm_t)0x06000900) #define PSA_ALG_IS_HASH_EDDSA(alg) \ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_HASH_EDDSA_BASE) /** Edwards-curve digital signature algorithm with prehashing (HashEdDSA), * using SHA-512 and the Edwards25519 curve. * * See #PSA_ALG_PURE_EDDSA regarding context support and the signature format. * * This algorithm is Ed25519 as specified in RFC 8032. * The curve is Edwards25519. * The prehash is SHA-512. * The hash function used internally is SHA-512. * * This is a hash-and-sign algorithm: to calculate a signature, * you can either: * - call psa_sign_message() on the message; * - or calculate the SHA-512 hash of the message * with psa_hash_compute() * or with a multi-part hash operation started with psa_hash_setup(), * using the hash algorithm #PSA_ALG_SHA_512, * then sign the calculated hash with psa_sign_hash(). * Verifying a signature is similar, using psa_verify_message() or * psa_verify_hash() instead of the signature function. */ #define PSA_ALG_ED25519PH \ (PSA_ALG_HASH_EDDSA_BASE | (PSA_ALG_SHA_512 & PSA_ALG_HASH_MASK)) /** Edwards-curve digital signature algorithm with prehashing (HashEdDSA), * using SHAKE256 and the Edwards448 curve. * * See #PSA_ALG_PURE_EDDSA regarding context support and the signature format. * * This algorithm is Ed448 as specified in RFC 8032. * The curve is Edwards448. * The prehash is the first 64 bytes of the SHAKE256 output. * The hash function used internally is the first 114 bytes of the * SHAKE256 output. * * This is a hash-and-sign algorithm: to calculate a signature, * you can either: * - call psa_sign_message() on the message; * - or calculate the first 64 bytes of the SHAKE256 output of the message * with psa_hash_compute() * or with a multi-part hash operation started with psa_hash_setup(), * using the hash algorithm #PSA_ALG_SHAKE256_512, * then sign the calculated hash with psa_sign_hash(). * Verifying a signature is similar, using psa_verify_message() or * psa_verify_hash() instead of the signature function. */ #define PSA_ALG_ED448PH \ (PSA_ALG_HASH_EDDSA_BASE | (PSA_ALG_SHAKE256_512 & PSA_ALG_HASH_MASK)) /* Default definition, to be overridden if the library is extended with * more hash-and-sign algorithms that we want to keep out of this header * file. */ #define PSA_ALG_IS_VENDOR_HASH_AND_SIGN(alg) 0 /** Whether the specified algorithm is a hash-and-sign algorithm. * * Hash-and-sign algorithms are asymmetric (public-key) signature algorithms * structured in two parts: first the calculation of a hash in a way that * does not depend on the key, then the calculation of a signature from the * hash value and the key. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is a hash-and-sign algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_HASH_AND_SIGN(alg) \ (PSA_ALG_IS_RSA_PSS(alg) || PSA_ALG_IS_RSA_PKCS1V15_SIGN(alg) || \ PSA_ALG_IS_ECDSA(alg) || PSA_ALG_IS_HASH_EDDSA(alg) || \ PSA_ALG_IS_VENDOR_HASH_AND_SIGN(alg)) /** Whether the specified algorithm is a signature algorithm that can be used * with psa_sign_message() and psa_verify_message(). * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if alg is a signature algorithm that can be used to sign a * message. 0 if \p alg is a signature algorithm that can only be used * to sign an already-calculated hash. 0 if \p alg is not a signature * algorithm. This macro can return either 0 or 1 if \p alg is not a * supported algorithm identifier. */ #define PSA_ALG_IS_SIGN_MESSAGE(alg) \ (PSA_ALG_IS_HASH_AND_SIGN(alg) || (alg) == PSA_ALG_PURE_EDDSA ) /** Get the hash used by a hash-and-sign signature algorithm. * * A hash-and-sign algorithm is a signature algorithm which is * composed of two phases: first a hashing phase which does not use * the key and produces a hash of the input message, then a signing * phase which only uses the hash and the key and not the message * itself. * * \param alg A signature algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_SIGN(\p alg) is true). * * \return The underlying hash algorithm if \p alg is a hash-and-sign * algorithm. * \return 0 if \p alg is a signature algorithm that does not * follow the hash-and-sign structure. * \return Unspecified if \p alg is not a signature algorithm or * if it is not supported by the implementation. */ #define PSA_ALG_SIGN_GET_HASH(alg) \ (PSA_ALG_IS_HASH_AND_SIGN(alg) ? \ ((alg) & PSA_ALG_HASH_MASK) == 0 ? /*"raw" algorithm*/ 0 : \ ((alg) & PSA_ALG_HASH_MASK) | PSA_ALG_CATEGORY_HASH : \ 0) /** RSA PKCS#1 v1.5 encryption. */ #define PSA_ALG_RSA_PKCS1V15_CRYPT ((psa_algorithm_t)0x07000200) #define PSA_ALG_RSA_OAEP_BASE ((psa_algorithm_t)0x07000300) /** RSA OAEP encryption. * * This is the encryption scheme defined by RFC 8017 * (PKCS#1: RSA Cryptography Specifications) under the name * RSAES-OAEP, with the message generation function MGF1. * * \param hash_alg The hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true) to use * for MGF1. * * \return The corresponding RSA OAEP encryption algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_RSA_OAEP(hash_alg) \ (PSA_ALG_RSA_OAEP_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) #define PSA_ALG_IS_RSA_OAEP(alg) \ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_RSA_OAEP_BASE) #define PSA_ALG_RSA_OAEP_GET_HASH(alg) \ (PSA_ALG_IS_RSA_OAEP(alg) ? \ ((alg) & PSA_ALG_HASH_MASK) | PSA_ALG_CATEGORY_HASH : \ 0) #define PSA_ALG_HKDF_BASE ((psa_algorithm_t)0x08000100) /** Macro to build an HKDF algorithm. * * For example, `PSA_ALG_HKDF(PSA_ALG_SHA256)` is HKDF using HMAC-SHA-256. * * This key derivation algorithm uses the following inputs: * - #PSA_KEY_DERIVATION_INPUT_SALT is the salt used in the "extract" step. * It is optional; if omitted, the derivation uses an empty salt. * - #PSA_KEY_DERIVATION_INPUT_SECRET is the secret key used in the "extract" step. * - #PSA_KEY_DERIVATION_INPUT_INFO is the info string used in the "expand" step. * You must pass #PSA_KEY_DERIVATION_INPUT_SALT before #PSA_KEY_DERIVATION_INPUT_SECRET. * You may pass #PSA_KEY_DERIVATION_INPUT_INFO at any time after steup and before * starting to generate output. * * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true). * * \return The corresponding HKDF algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_HKDF(hash_alg) \ (PSA_ALG_HKDF_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) /** Whether the specified algorithm is an HKDF algorithm. * * HKDF is a family of key derivation algorithms that are based on a hash * function and the HMAC construction. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \c alg is an HKDF algorithm, 0 otherwise. * This macro may return either 0 or 1 if \c alg is not a supported * key derivation algorithm identifier. */ #define PSA_ALG_IS_HKDF(alg) \ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_HKDF_BASE) #define PSA_ALG_HKDF_GET_HASH(hkdf_alg) \ (PSA_ALG_CATEGORY_HASH | ((hkdf_alg) & PSA_ALG_HASH_MASK)) #define PSA_ALG_TLS12_PRF_BASE ((psa_algorithm_t)0x08000200) /** Macro to build a TLS-1.2 PRF algorithm. * * TLS 1.2 uses a custom pseudorandom function (PRF) for key schedule, * specified in Section 5 of RFC 5246. It is based on HMAC and can be * used with either SHA-256 or SHA-384. * * This key derivation algorithm uses the following inputs, which must be * passed in the order given here: * - #PSA_KEY_DERIVATION_INPUT_SEED is the seed. * - #PSA_KEY_DERIVATION_INPUT_SECRET is the secret key. * - #PSA_KEY_DERIVATION_INPUT_LABEL is the label. * * For the application to TLS-1.2 key expansion, the seed is the * concatenation of ServerHello.Random + ClientHello.Random, * and the label is "key expansion". * * For example, `PSA_ALG_TLS12_PRF(PSA_ALG_SHA256)` represents the * TLS 1.2 PRF using HMAC-SHA-256. * * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true). * * \return The corresponding TLS-1.2 PRF algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_TLS12_PRF(hash_alg) \ (PSA_ALG_TLS12_PRF_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) /** Whether the specified algorithm is a TLS-1.2 PRF algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \c alg is a TLS-1.2 PRF algorithm, 0 otherwise. * This macro may return either 0 or 1 if \c alg is not a supported * key derivation algorithm identifier. */ #define PSA_ALG_IS_TLS12_PRF(alg) \ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_TLS12_PRF_BASE) #define PSA_ALG_TLS12_PRF_GET_HASH(hkdf_alg) \ (PSA_ALG_CATEGORY_HASH | ((hkdf_alg) & PSA_ALG_HASH_MASK)) #define PSA_ALG_TLS12_PSK_TO_MS_BASE ((psa_algorithm_t)0x08000300) /** Macro to build a TLS-1.2 PSK-to-MasterSecret algorithm. * * In a pure-PSK handshake in TLS 1.2, the master secret is derived * from the PreSharedKey (PSK) through the application of padding * (RFC 4279, Section 2) and the TLS-1.2 PRF (RFC 5246, Section 5). * The latter is based on HMAC and can be used with either SHA-256 * or SHA-384. * * This key derivation algorithm uses the following inputs, which must be * passed in the order given here: * - #PSA_KEY_DERIVATION_INPUT_SEED is the seed. * - #PSA_KEY_DERIVATION_INPUT_SECRET is the secret key. * - #PSA_KEY_DERIVATION_INPUT_LABEL is the label. * * For the application to TLS-1.2, the seed (which is * forwarded to the TLS-1.2 PRF) is the concatenation of the * ClientHello.Random + ServerHello.Random, * and the label is "master secret" or "extended master secret". * * For example, `PSA_ALG_TLS12_PSK_TO_MS(PSA_ALG_SHA256)` represents the * TLS-1.2 PSK to MasterSecret derivation PRF using HMAC-SHA-256. * * \param hash_alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p hash_alg) is true). * * \return The corresponding TLS-1.2 PSK to MS algorithm. * \return Unspecified if \p hash_alg is not a supported * hash algorithm. */ #define PSA_ALG_TLS12_PSK_TO_MS(hash_alg) \ (PSA_ALG_TLS12_PSK_TO_MS_BASE | ((hash_alg) & PSA_ALG_HASH_MASK)) /** Whether the specified algorithm is a TLS-1.2 PSK to MS algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \c alg is a TLS-1.2 PSK to MS algorithm, 0 otherwise. * This macro may return either 0 or 1 if \c alg is not a supported * key derivation algorithm identifier. */ #define PSA_ALG_IS_TLS12_PSK_TO_MS(alg) \ (((alg) & ~PSA_ALG_HASH_MASK) == PSA_ALG_TLS12_PSK_TO_MS_BASE) #define PSA_ALG_TLS12_PSK_TO_MS_GET_HASH(hkdf_alg) \ (PSA_ALG_CATEGORY_HASH | ((hkdf_alg) & PSA_ALG_HASH_MASK)) #define PSA_ALG_KEY_DERIVATION_MASK ((psa_algorithm_t)0xfe00ffff) #define PSA_ALG_KEY_AGREEMENT_MASK ((psa_algorithm_t)0xffff0000) /** Macro to build a combined algorithm that chains a key agreement with * a key derivation. * * \param ka_alg A key agreement algorithm (\c PSA_ALG_XXX value such * that #PSA_ALG_IS_KEY_AGREEMENT(\p ka_alg) is true). * \param kdf_alg A key derivation algorithm (\c PSA_ALG_XXX value such * that #PSA_ALG_IS_KEY_DERIVATION(\p kdf_alg) is true). * * \return The corresponding key agreement and derivation * algorithm. * \return Unspecified if \p ka_alg is not a supported * key agreement algorithm or \p kdf_alg is not a * supported key derivation algorithm. */ #define PSA_ALG_KEY_AGREEMENT(ka_alg, kdf_alg) \ ((ka_alg) | (kdf_alg)) #define PSA_ALG_KEY_AGREEMENT_GET_KDF(alg) \ (((alg) & PSA_ALG_KEY_DERIVATION_MASK) | PSA_ALG_CATEGORY_KEY_DERIVATION) #define PSA_ALG_KEY_AGREEMENT_GET_BASE(alg) \ (((alg) & PSA_ALG_KEY_AGREEMENT_MASK) | PSA_ALG_CATEGORY_KEY_AGREEMENT) /** Whether the specified algorithm is a raw key agreement algorithm. * * A raw key agreement algorithm is one that does not specify * a key derivation function. * Usually, raw key agreement algorithms are constructed directly with * a \c PSA_ALG_xxx macro while non-raw key agreement algorithms are * constructed with #PSA_ALG_KEY_AGREEMENT(). * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \p alg is a raw key agreement algorithm, 0 otherwise. * This macro may return either 0 or 1 if \p alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_RAW_KEY_AGREEMENT(alg) \ (PSA_ALG_IS_KEY_AGREEMENT(alg) && \ PSA_ALG_KEY_AGREEMENT_GET_KDF(alg) == PSA_ALG_CATEGORY_KEY_DERIVATION) #define PSA_ALG_IS_KEY_DERIVATION_OR_AGREEMENT(alg) \ ((PSA_ALG_IS_KEY_DERIVATION(alg) || PSA_ALG_IS_KEY_AGREEMENT(alg))) /** The finite-field Diffie-Hellman (DH) key agreement algorithm. * * The shared secret produced by key agreement is * `g^{ab}` in big-endian format. * It is `ceiling(m / 8)` bytes long where `m` is the size of the prime `p` * in bits. */ #define PSA_ALG_FFDH ((psa_algorithm_t)0x09010000) /** Whether the specified algorithm is a finite field Diffie-Hellman algorithm. * * This includes the raw finite field Diffie-Hellman algorithm as well as * finite-field Diffie-Hellman followed by any supporter key derivation * algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \c alg is a finite field Diffie-Hellman algorithm, 0 otherwise. * This macro may return either 0 or 1 if \c alg is not a supported * key agreement algorithm identifier. */ #define PSA_ALG_IS_FFDH(alg) \ (PSA_ALG_KEY_AGREEMENT_GET_BASE(alg) == PSA_ALG_FFDH) /** The elliptic curve Diffie-Hellman (ECDH) key agreement algorithm. * * The shared secret produced by key agreement is the x-coordinate of * the shared secret point. It is always `ceiling(m / 8)` bytes long where * `m` is the bit size associated with the curve, i.e. the bit size of the * order of the curve's coordinate field. When `m` is not a multiple of 8, * the byte containing the most significant bit of the shared secret * is padded with zero bits. The byte order is either little-endian * or big-endian depending on the curve type. * * - For Montgomery curves (curve types `PSA_ECC_FAMILY_CURVEXXX`), * the shared secret is the x-coordinate of `d_A Q_B = d_B Q_A` * in little-endian byte order. * The bit size is 448 for Curve448 and 255 for Curve25519. * - For Weierstrass curves over prime fields (curve types * `PSA_ECC_FAMILY_SECPXXX` and `PSA_ECC_FAMILY_BRAINPOOL_PXXX`), * the shared secret is the x-coordinate of `d_A Q_B = d_B Q_A` * in big-endian byte order. * The bit size is `m = ceiling(log_2(p))` for the field `F_p`. * - For Weierstrass curves over binary fields (curve types * `PSA_ECC_FAMILY_SECTXXX`), * the shared secret is the x-coordinate of `d_A Q_B = d_B Q_A` * in big-endian byte order. * The bit size is `m` for the field `F_{2^m}`. */ #define PSA_ALG_ECDH ((psa_algorithm_t)0x09020000) /** Whether the specified algorithm is an elliptic curve Diffie-Hellman * algorithm. * * This includes the raw elliptic curve Diffie-Hellman algorithm as well as * elliptic curve Diffie-Hellman followed by any supporter key derivation * algorithm. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \c alg is an elliptic curve Diffie-Hellman algorithm, * 0 otherwise. * This macro may return either 0 or 1 if \c alg is not a supported * key agreement algorithm identifier. */ #define PSA_ALG_IS_ECDH(alg) \ (PSA_ALG_KEY_AGREEMENT_GET_BASE(alg) == PSA_ALG_ECDH) /** Whether the specified algorithm encoding is a wildcard. * * Wildcard values may only be used to set the usage algorithm field in * a policy, not to perform an operation. * * \param alg An algorithm identifier (value of type #psa_algorithm_t). * * \return 1 if \c alg is a wildcard algorithm encoding. * \return 0 if \c alg is a non-wildcard algorithm encoding (suitable for * an operation). * \return This macro may return either 0 or 1 if \c alg is not a supported * algorithm identifier. */ #define PSA_ALG_IS_WILDCARD(alg) \ (PSA_ALG_IS_HASH_AND_SIGN(alg) ? \ PSA_ALG_SIGN_GET_HASH(alg) == PSA_ALG_ANY_HASH : \ PSA_ALG_IS_MAC(alg) ? \ (alg & PSA_ALG_MAC_AT_LEAST_THIS_LENGTH_FLAG) != 0 : \ PSA_ALG_IS_AEAD(alg) ? \ (alg & PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG) != 0 : \ (alg) == PSA_ALG_ANY_HASH) /**@}*/ /** \defgroup key_lifetimes Key lifetimes * @{ */ /** The default lifetime for volatile keys. * * A volatile key only exists as long as the identifier to it is not destroyed. * The key material is guaranteed to be erased on a power reset. * * A key with this lifetime is typically stored in the RAM area of the * PSA Crypto subsystem. However this is an implementation choice. * If an implementation stores data about the key in a non-volatile memory, * it must release all the resources associated with the key and erase the * key material if the calling application terminates. */ #define PSA_KEY_LIFETIME_VOLATILE ((psa_key_lifetime_t)0x00000000) /** The default lifetime for persistent keys. * * A persistent key remains in storage until it is explicitly destroyed or * until the corresponding storage area is wiped. This specification does * not define any mechanism to wipe a storage area, but integrations may * provide their own mechanism (for example to perform a factory reset, * to prepare for device refurbishment, or to uninstall an application). * * This lifetime value is the default storage area for the calling * application. Integrations of Mbed TLS may support other persistent lifetimes. * See ::psa_key_lifetime_t for more information. */ #define PSA_KEY_LIFETIME_PERSISTENT ((psa_key_lifetime_t)0x00000001) /** The persistence level of volatile keys. * * See ::psa_key_persistence_t for more information. */ #define PSA_KEY_PERSISTENCE_VOLATILE ((psa_key_persistence_t)0x00) /** The default persistence level for persistent keys. * * See ::psa_key_persistence_t for more information. */ #define PSA_KEY_PERSISTENCE_DEFAULT ((psa_key_persistence_t)0x01) /** A persistence level indicating that a key is never destroyed. * * See ::psa_key_persistence_t for more information. */ #define PSA_KEY_PERSISTENCE_READ_ONLY ((psa_key_persistence_t)0xff) #define PSA_KEY_LIFETIME_GET_PERSISTENCE(lifetime) \ ((psa_key_persistence_t)((lifetime) & 0x000000ff)) #define PSA_KEY_LIFETIME_GET_LOCATION(lifetime) \ ((psa_key_location_t)((lifetime) >> 8)) /** Whether a key lifetime indicates that the key is volatile. * * A volatile key is automatically destroyed by the implementation when * the application instance terminates. In particular, a volatile key * is automatically destroyed on a power reset of the device. * * A key that is not volatile is persistent. Persistent keys are * preserved until the application explicitly destroys them or until an * implementation-specific device management event occurs (for example, * a factory reset). * * \param lifetime The lifetime value to query (value of type * ::psa_key_lifetime_t). * * \return \c 1 if the key is volatile, otherwise \c 0. */ #define PSA_KEY_LIFETIME_IS_VOLATILE(lifetime) \ (PSA_KEY_LIFETIME_GET_PERSISTENCE(lifetime) == \ PSA_KEY_PERSISTENCE_VOLATILE) /** Whether a key lifetime indicates that the key is read-only. * * Read-only keys cannot be created or destroyed through the PSA Crypto API. * They must be created through platform-specific means that bypass the API. * * Some platforms may offer ways to destroy read-only keys. For example, * consider a platform with multiple levels of privilege, where a * low-privilege application can use a key but is not allowed to destroy * it, and the platform exposes the key to the application with a read-only * lifetime. High-privilege code can destroy the key even though the * application sees the key as read-only. * * \param lifetime The lifetime value to query (value of type * ::psa_key_lifetime_t). * * \return \c 1 if the key is read-only, otherwise \c 0. */ #define PSA_KEY_LIFETIME_IS_READ_ONLY(lifetime) \ (PSA_KEY_LIFETIME_GET_PERSISTENCE(lifetime) == \ PSA_KEY_PERSISTENCE_READ_ONLY) /** Construct a lifetime from a persistence level and a location. * * \param persistence The persistence level * (value of type ::psa_key_persistence_t). * \param location The location indicator * (value of type ::psa_key_location_t). * * \return The constructed lifetime value. */ #define PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION(persistence, location) \ ((location) << 8 | (persistence)) /** The local storage area for persistent keys. * * This storage area is available on all systems that can store persistent * keys without delegating the storage to a third-party cryptoprocessor. * * See ::psa_key_location_t for more information. */ #define PSA_KEY_LOCATION_LOCAL_STORAGE ((psa_key_location_t)0x000000) #define PSA_KEY_LOCATION_VENDOR_FLAG ((psa_key_location_t)0x800000) /** The minimum value for a key identifier chosen by the application. */ #define PSA_KEY_ID_USER_MIN ((psa_key_id_t)0x00000001) /** The maximum value for a key identifier chosen by the application. */ #define PSA_KEY_ID_USER_MAX ((psa_key_id_t)0x3fffffff) /** The minimum value for a key identifier chosen by the implementation. */ #define PSA_KEY_ID_VENDOR_MIN ((psa_key_id_t)0x40000000) /** The maximum value for a key identifier chosen by the implementation. */ #define PSA_KEY_ID_VENDOR_MAX ((psa_key_id_t)0x7fffffff) #if !defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER) #define MBEDTLS_SVC_KEY_ID_INIT ( (psa_key_id_t)0 ) #define MBEDTLS_SVC_KEY_ID_GET_KEY_ID( id ) ( id ) #define MBEDTLS_SVC_KEY_ID_GET_OWNER_ID( id ) ( 0 ) /** Utility to initialize a key identifier at runtime. * * \param unused Unused parameter. * \param key_id Identifier of the key. */ static inline mbedtls_svc_key_id_t mbedtls_svc_key_id_make( unsigned int unused, psa_key_id_t key_id ) { (void)unused; return( key_id ); } /** Compare two key identifiers. * * \param id1 First key identifier. * \param id2 Second key identifier. * * \return Non-zero if the two key identifier are equal, zero otherwise. */ static inline int mbedtls_svc_key_id_equal( mbedtls_svc_key_id_t id1, mbedtls_svc_key_id_t id2 ) { return( id1 == id2 ); } /** Check whether a key identifier is null. * * \param key Key identifier. * * \return Non-zero if the key identifier is null, zero otherwise. */ static inline int mbedtls_svc_key_id_is_null( mbedtls_svc_key_id_t key ) { return( key == 0 ); } #else /* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */ #define MBEDTLS_SVC_KEY_ID_INIT ( (mbedtls_svc_key_id_t){ 0, 0 } ) #define MBEDTLS_SVC_KEY_ID_GET_KEY_ID( id ) ( ( id ).key_id ) #define MBEDTLS_SVC_KEY_ID_GET_OWNER_ID( id ) ( ( id ).owner ) /** Utility to initialize a key identifier at runtime. * * \param owner_id Identifier of the key owner. * \param key_id Identifier of the key. */ static inline mbedtls_svc_key_id_t mbedtls_svc_key_id_make( mbedtls_key_owner_id_t owner_id, psa_key_id_t key_id ) { return( (mbedtls_svc_key_id_t){ .key_id = key_id, .owner = owner_id } ); } /** Compare two key identifiers. * * \param id1 First key identifier. * \param id2 Second key identifier. * * \return Non-zero if the two key identifier are equal, zero otherwise. */ static inline int mbedtls_svc_key_id_equal( mbedtls_svc_key_id_t id1, mbedtls_svc_key_id_t id2 ) { return( ( id1.key_id == id2.key_id ) && mbedtls_key_owner_id_equal( id1.owner, id2.owner ) ); } /** Check whether a key identifier is null. * * \param key Key identifier. * * \return Non-zero if the key identifier is null, zero otherwise. */ static inline int mbedtls_svc_key_id_is_null( mbedtls_svc_key_id_t key ) { return( key.key_id == 0 ); } #endif /* !MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */ /**@}*/ /** \defgroup policy Key policies * @{ */ /** Whether the key may be exported. * * A public key or the public part of a key pair may always be exported * regardless of the value of this permission flag. * * If a key does not have export permission, implementations shall not * allow the key to be exported in plain form from the cryptoprocessor, * whether through psa_export_key() or through a proprietary interface. * The key may however be exportable in a wrapped form, i.e. in a form * where it is encrypted by another key. */ #define PSA_KEY_USAGE_EXPORT ((psa_key_usage_t)0x00000001) /** Whether the key may be copied. * * This flag allows the use of psa_copy_key() to make a copy of the key * with the same policy or a more restrictive policy. * * For lifetimes for which the key is located in a secure element which * enforce the non-exportability of keys, copying a key outside the secure * element also requires the usage flag #PSA_KEY_USAGE_EXPORT. * Copying the key inside the secure element is permitted with just * #PSA_KEY_USAGE_COPY if the secure element supports it. * For keys with the lifetime #PSA_KEY_LIFETIME_VOLATILE or * #PSA_KEY_LIFETIME_PERSISTENT, the usage flag #PSA_KEY_USAGE_COPY * is sufficient to permit the copy. */ #define PSA_KEY_USAGE_COPY ((psa_key_usage_t)0x00000002) /** Whether the key may be used to encrypt a message. * * This flag allows the key to be used for a symmetric encryption operation, * for an AEAD encryption-and-authentication operation, * or for an asymmetric encryption operation, * if otherwise permitted by the key's type and policy. * * For a key pair, this concerns the public key. */ #define PSA_KEY_USAGE_ENCRYPT ((psa_key_usage_t)0x00000100) /** Whether the key may be used to decrypt a message. * * This flag allows the key to be used for a symmetric decryption operation, * for an AEAD decryption-and-verification operation, * or for an asymmetric decryption operation, * if otherwise permitted by the key's type and policy. * * For a key pair, this concerns the private key. */ #define PSA_KEY_USAGE_DECRYPT ((psa_key_usage_t)0x00000200) /** Whether the key may be used to sign a message. * * This flag allows the key to be used for a MAC calculation operation or for * an asymmetric message signature operation, if otherwise permitted by the * key’s type and policy. * * For a key pair, this concerns the private key. */ #define PSA_KEY_USAGE_SIGN_MESSAGE ((psa_key_usage_t)0x00000400) /** Whether the key may be used to verify a message. * * This flag allows the key to be used for a MAC verification operation or for * an asymmetric message signature verification operation, if otherwise * permitted by the key’s type and policy. * * For a key pair, this concerns the public key. */ #define PSA_KEY_USAGE_VERIFY_MESSAGE ((psa_key_usage_t)0x00000800) /** Whether the key may be used to sign a message. * * This flag allows the key to be used for a MAC calculation operation * or for an asymmetric signature operation, * if otherwise permitted by the key's type and policy. * * For a key pair, this concerns the private key. */ #define PSA_KEY_USAGE_SIGN_HASH ((psa_key_usage_t)0x00001000) /** Whether the key may be used to verify a message signature. * * This flag allows the key to be used for a MAC verification operation * or for an asymmetric signature verification operation, * if otherwise permitted by by the key's type and policy. * * For a key pair, this concerns the public key. */ #define PSA_KEY_USAGE_VERIFY_HASH ((psa_key_usage_t)0x00002000) /** Whether the key may be used to derive other keys. */ #define PSA_KEY_USAGE_DERIVE ((psa_key_usage_t)0x00004000) /**@}*/ /** \defgroup derivation Key derivation * @{ */ /** A secret input for key derivation. * * This should be a key of type #PSA_KEY_TYPE_DERIVE * (passed to psa_key_derivation_input_key()) * or the shared secret resulting from a key agreement * (obtained via psa_key_derivation_key_agreement()). * * The secret can also be a direct input (passed to * key_derivation_input_bytes()). In this case, the derivation operation * may not be used to derive keys: the operation will only allow * psa_key_derivation_output_bytes(), not psa_key_derivation_output_key(). */ #define PSA_KEY_DERIVATION_INPUT_SECRET ((psa_key_derivation_step_t)0x0101) /** A label for key derivation. * * This should be a direct input. * It can also be a key of type #PSA_KEY_TYPE_RAW_DATA. */ #define PSA_KEY_DERIVATION_INPUT_LABEL ((psa_key_derivation_step_t)0x0201) /** A salt for key derivation. * * This should be a direct input. * It can also be a key of type #PSA_KEY_TYPE_RAW_DATA. */ #define PSA_KEY_DERIVATION_INPUT_SALT ((psa_key_derivation_step_t)0x0202) /** An information string for key derivation. * * This should be a direct input. * It can also be a key of type #PSA_KEY_TYPE_RAW_DATA. */ #define PSA_KEY_DERIVATION_INPUT_INFO ((psa_key_derivation_step_t)0x0203) /** A seed for key derivation. * * This should be a direct input. * It can also be a key of type #PSA_KEY_TYPE_RAW_DATA. */ #define PSA_KEY_DERIVATION_INPUT_SEED ((psa_key_derivation_step_t)0x0204) /**@}*/ /** \defgroup helper_macros Helper macros * @{ */ /* Helper macros */ /** Check if two AEAD algorithm identifiers refer to the same AEAD algorithm * regardless of the tag length they encode. * * \param aead_alg_1 An AEAD algorithm identifier. * \param aead_alg_2 An AEAD algorithm identifier. * * \return 1 if both identifiers refer to the same AEAD algorithm, * 0 otherwise. * Unspecified if neither \p aead_alg_1 nor \p aead_alg_2 are * a supported AEAD algorithm. */ #define MBEDTLS_PSA_ALG_AEAD_EQUAL(aead_alg_1, aead_alg_2) \ (!(((aead_alg_1) ^ (aead_alg_2)) & \ ~(PSA_ALG_AEAD_TAG_LENGTH_MASK | PSA_ALG_AEAD_AT_LEAST_THIS_LENGTH_FLAG))) /**@}*/ #endif /* PSA_CRYPTO_VALUES_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_compat.h
/** * \file psa/crypto_compat.h * * \brief PSA cryptography module: Backward compatibility aliases * * This header declares alternative names for macro and functions. * New application code should not use these names. * These names may be removed in a future version of Mbed Crypto. * * \note This file may not be included directly. Applications must * include psa/crypto.h. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_COMPAT_H #define PSA_CRYPTO_COMPAT_H #ifdef __cplusplus extern "C" { #endif /* * To support both openless APIs and psa_open_key() temporarily, define * psa_key_handle_t to be equal to mbedtls_svc_key_id_t. Do not mark the * type and its utility macros and functions deprecated yet. This will be done * in a subsequent phase. */ typedef mbedtls_svc_key_id_t psa_key_handle_t; #define PSA_KEY_HANDLE_INIT MBEDTLS_SVC_KEY_ID_INIT /** Check whether an handle is null. * * \param handle Handle * * \return Non-zero if the handle is null, zero otherwise. */ static inline int psa_key_handle_is_null( psa_key_handle_t handle ) { return( mbedtls_svc_key_id_is_null( handle ) ); } #if !defined(MBEDTLS_DEPRECATED_REMOVED) /* * Mechanism for declaring deprecated values */ #if defined(MBEDTLS_DEPRECATED_WARNING) && !defined(MBEDTLS_PSA_DEPRECATED) #define MBEDTLS_PSA_DEPRECATED __attribute__((deprecated)) #else #define MBEDTLS_PSA_DEPRECATED #endif typedef MBEDTLS_PSA_DEPRECATED size_t mbedtls_deprecated_size_t; typedef MBEDTLS_PSA_DEPRECATED psa_status_t mbedtls_deprecated_psa_status_t; typedef MBEDTLS_PSA_DEPRECATED psa_key_usage_t mbedtls_deprecated_psa_key_usage_t; typedef MBEDTLS_PSA_DEPRECATED psa_ecc_family_t mbedtls_deprecated_psa_ecc_family_t; typedef MBEDTLS_PSA_DEPRECATED psa_dh_family_t mbedtls_deprecated_psa_dh_family_t; typedef MBEDTLS_PSA_DEPRECATED psa_ecc_family_t psa_ecc_curve_t; typedef MBEDTLS_PSA_DEPRECATED psa_dh_family_t psa_dh_group_t; typedef MBEDTLS_PSA_DEPRECATED psa_algorithm_t mbedtls_deprecated_psa_algorithm_t; #define PSA_KEY_TYPE_GET_CURVE PSA_KEY_TYPE_ECC_GET_FAMILY #define PSA_KEY_TYPE_GET_GROUP PSA_KEY_TYPE_DH_GET_FAMILY #define MBEDTLS_DEPRECATED_CONSTANT( type, value ) \ ( (mbedtls_deprecated_##type) ( value ) ) /* * Deprecated PSA Crypto error code definitions (PSA Crypto API <= 1.0 beta2) */ #define PSA_ERROR_UNKNOWN_ERROR \ MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_GENERIC_ERROR ) #define PSA_ERROR_OCCUPIED_SLOT \ MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_ALREADY_EXISTS ) #define PSA_ERROR_EMPTY_SLOT \ MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_DOES_NOT_EXIST ) #define PSA_ERROR_INSUFFICIENT_CAPACITY \ MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_INSUFFICIENT_DATA ) #define PSA_ERROR_TAMPERING_DETECTED \ MBEDTLS_DEPRECATED_CONSTANT( psa_status_t, PSA_ERROR_CORRUPTION_DETECTED ) /* * Deprecated PSA Crypto numerical encodings (PSA Crypto API <= 1.0 beta3) */ #define PSA_KEY_USAGE_SIGN \ MBEDTLS_DEPRECATED_CONSTANT( psa_key_usage_t, PSA_KEY_USAGE_SIGN_HASH ) #define PSA_KEY_USAGE_VERIFY \ MBEDTLS_DEPRECATED_CONSTANT( psa_key_usage_t, PSA_KEY_USAGE_VERIFY_HASH ) /* * Deprecated PSA Crypto size calculation macros (PSA Crypto API <= 1.0 beta3) */ #define PSA_ASYMMETRIC_SIGNATURE_MAX_SIZE \ MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_SIGNATURE_MAX_SIZE ) #define PSA_ASYMMETRIC_SIGN_OUTPUT_SIZE( key_type, key_bits, alg ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_SIGN_OUTPUT_SIZE( key_type, key_bits, alg ) ) #define PSA_KEY_EXPORT_MAX_SIZE( key_type, key_bits ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_EXPORT_KEY_OUTPUT_SIZE( key_type, key_bits ) ) #define PSA_BLOCK_CIPHER_BLOCK_SIZE( type ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_BLOCK_CIPHER_BLOCK_LENGTH( type ) ) #define PSA_MAX_BLOCK_CIPHER_BLOCK_SIZE \ MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE ) #define PSA_HASH_SIZE( alg ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_HASH_LENGTH( alg ) ) #define PSA_MAC_FINAL_SIZE( key_type, key_bits, alg ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_MAC_LENGTH( key_type, key_bits, alg ) ) #define PSA_ALG_TLS12_PSK_TO_MS_MAX_PSK_LEN \ MBEDTLS_DEPRECATED_CONSTANT( size_t, PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE ) /* * Deprecated PSA Crypto function names (PSA Crypto API <= 1.0 beta3) */ MBEDTLS_PSA_DEPRECATED static inline psa_status_t psa_asymmetric_sign( psa_key_handle_t key, psa_algorithm_t alg, const uint8_t *hash, size_t hash_length, uint8_t *signature, size_t signature_size, size_t *signature_length ) { return psa_sign_hash( key, alg, hash, hash_length, signature, signature_size, signature_length ); } MBEDTLS_PSA_DEPRECATED static inline psa_status_t psa_asymmetric_verify( psa_key_handle_t key, psa_algorithm_t alg, const uint8_t *hash, size_t hash_length, const uint8_t *signature, size_t signature_length ) { return psa_verify_hash( key, alg, hash, hash_length, signature, signature_length ); } /* * Size-specific elliptic curve families. */ #define PSA_ECC_CURVE_SECP160K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) #define PSA_ECC_CURVE_SECP192K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) #define PSA_ECC_CURVE_SECP224K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) #define PSA_ECC_CURVE_SECP256K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) #define PSA_ECC_CURVE_SECP160R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP192R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP224R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP256R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP384R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP521R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP160R2 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R2 ) #define PSA_ECC_CURVE_SECT163K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT233K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT239K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT283K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT409K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT571K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT163R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT193R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT233R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT283R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT409R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT571R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT163R2 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R2 ) #define PSA_ECC_CURVE_SECT193R2 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R2 ) #define PSA_ECC_CURVE_BRAINPOOL_P256R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) #define PSA_ECC_CURVE_BRAINPOOL_P384R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) #define PSA_ECC_CURVE_BRAINPOOL_P512R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) #define PSA_ECC_CURVE_CURVE25519 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_MONTGOMERY ) #define PSA_ECC_CURVE_CURVE448 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_MONTGOMERY ) /* * Curves that changed name due to PSA specification. */ #define PSA_ECC_CURVE_SECP_K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_K1 ) #define PSA_ECC_CURVE_SECP_R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R1 ) #define PSA_ECC_CURVE_SECP_R2 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECP_R2 ) #define PSA_ECC_CURVE_SECT_K1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_K1 ) #define PSA_ECC_CURVE_SECT_R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R1 ) #define PSA_ECC_CURVE_SECT_R2 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_SECT_R2 ) #define PSA_ECC_CURVE_BRAINPOOL_P_R1 \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_BRAINPOOL_P_R1 ) #define PSA_ECC_CURVE_MONTGOMERY \ MBEDTLS_DEPRECATED_CONSTANT( psa_ecc_family_t, PSA_ECC_FAMILY_MONTGOMERY ) /* * Finite-field Diffie-Hellman families. */ #define PSA_DH_GROUP_FFDHE2048 \ MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) #define PSA_DH_GROUP_FFDHE3072 \ MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) #define PSA_DH_GROUP_FFDHE4096 \ MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) #define PSA_DH_GROUP_FFDHE6144 \ MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) #define PSA_DH_GROUP_FFDHE8192 \ MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) /* * Diffie-Hellman families that changed name due to PSA specification. */ #define PSA_DH_GROUP_RFC7919 \ MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_RFC7919 ) #define PSA_DH_GROUP_CUSTOM \ MBEDTLS_DEPRECATED_CONSTANT( psa_dh_family_t, PSA_DH_FAMILY_CUSTOM ) /* * Deprecated PSA Crypto stream cipher algorithms (PSA Crypto API <= 1.0 beta3) */ #define PSA_ALG_ARC4 \ MBEDTLS_DEPRECATED_CONSTANT( psa_algorithm_t, PSA_ALG_STREAM_CIPHER ) #define PSA_ALG_CHACHA20 \ MBEDTLS_DEPRECATED_CONSTANT( psa_algorithm_t, PSA_ALG_STREAM_CIPHER ) /* * Renamed AEAD tag length macros (PSA Crypto API <= 1.0 beta3) */ #define PSA_ALG_AEAD_WITH_DEFAULT_TAG_LENGTH( aead_alg ) \ MBEDTLS_DEPRECATED_CONSTANT( psa_algorithm_t, PSA_ALG_AEAD_WITH_DEFAULT_LENGTH_TAG( aead_alg ) ) #define PSA_ALG_AEAD_WITH_TAG_LENGTH( aead_alg, tag_length ) \ MBEDTLS_DEPRECATED_CONSTANT( psa_algorithm_t, PSA_ALG_AEAD_WITH_SHORTENED_TAG( aead_alg, tag_length ) ) /* * Deprecated PSA AEAD output size macros (PSA Crypto API <= 1.0 beta3) */ /** The tag size for an AEAD algorithm, in bytes. * * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * * \return The tag size for the specified algorithm. * If the AEAD algorithm does not have an identified * tag that can be distinguished from the rest of * the ciphertext, return 0. * If the AEAD algorithm is not recognized, return 0. */ #define PSA_AEAD_TAG_LENGTH_1_ARG( alg ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, \ PSA_ALG_IS_AEAD( alg ) ? \ PSA_ALG_AEAD_GET_TAG_LENGTH( alg ) : \ 0 ) /** The maximum size of the output of psa_aead_encrypt(), in bytes. * * If the size of the ciphertext buffer is at least this large, it is * guaranteed that psa_aead_encrypt() will not fail due to an * insufficient buffer size. Depending on the algorithm, the actual size of * the ciphertext may be smaller. * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * \param plaintext_length Size of the plaintext in bytes. * * \return The AEAD ciphertext size for the specified * algorithm. * If the AEAD algorithm is not recognized, return 0. */ #define PSA_AEAD_ENCRYPT_OUTPUT_SIZE_2_ARG( alg, plaintext_length ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, \ PSA_ALG_IS_AEAD( alg ) ? \ (plaintext_length) + PSA_ALG_AEAD_GET_TAG_LENGTH( alg ) : \ 0 ) /** The maximum size of the output of psa_aead_decrypt(), in bytes. * * If the size of the plaintext buffer is at least this large, it is * guaranteed that psa_aead_decrypt() will not fail due to an * insufficient buffer size. Depending on the algorithm, the actual size of * the plaintext may be smaller. * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * \param ciphertext_length Size of the plaintext in bytes. * * \return The AEAD ciphertext size for the specified * algorithm. * If the AEAD algorithm is not recognized, return 0. */ #define PSA_AEAD_DECRYPT_OUTPUT_SIZE_2_ARG( alg, ciphertext_length ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, \ PSA_ALG_IS_AEAD( alg ) && \ (ciphertext_length) > PSA_ALG_AEAD_GET_TAG_LENGTH( alg ) ? \ (ciphertext_length) - PSA_ALG_AEAD_GET_TAG_LENGTH( alg ) : \ 0 ) /** A sufficient output buffer size for psa_aead_update(). * * If the size of the output buffer is at least this large, it is * guaranteed that psa_aead_update() will not fail due to an * insufficient buffer size. The actual size of the output may be smaller * in any given call. * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * \param input_length Size of the input in bytes. * * \return A sufficient output buffer size for the specified * algorithm. * If the AEAD algorithm is not recognized, return 0. */ /* For all the AEAD modes defined in this specification, it is possible * to emit output without delay. However, hardware may not always be * capable of this. So for modes based on a block cipher, allow the * implementation to delay the output until it has a full block. */ #define PSA_AEAD_UPDATE_OUTPUT_SIZE_2_ARG( alg, input_length ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, \ PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER( alg ) ? \ PSA_ROUND_UP_TO_MULTIPLE( PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE, (input_length) ) : \ (input_length) ) /** A sufficient ciphertext buffer size for psa_aead_finish(). * * If the size of the ciphertext buffer is at least this large, it is * guaranteed that psa_aead_finish() will not fail due to an * insufficient ciphertext buffer size. The actual size of the output may * be smaller in any given call. * * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * * \return A sufficient ciphertext buffer size for the * specified algorithm. * If the AEAD algorithm is not recognized, return 0. */ #define PSA_AEAD_FINISH_OUTPUT_SIZE_1_ARG( alg ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, \ PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER( alg ) ? \ PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE : \ 0 ) /** A sufficient plaintext buffer size for psa_aead_verify(). * * If the size of the plaintext buffer is at least this large, it is * guaranteed that psa_aead_verify() will not fail due to an * insufficient plaintext buffer size. The actual size of the output may * be smaller in any given call. * * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * * \return A sufficient plaintext buffer size for the * specified algorithm. * If the AEAD algorithm is not recognized, return 0. */ #define PSA_AEAD_VERIFY_OUTPUT_SIZE_1_ARG( alg ) \ MBEDTLS_DEPRECATED_CONSTANT( size_t, \ PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER( alg ) ? \ PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE : \ 0 ) #endif /* MBEDTLS_DEPRECATED_REMOVED */ /** Open a handle to an existing persistent key. * * Open a handle to a persistent key. A key is persistent if it was created * with a lifetime other than #PSA_KEY_LIFETIME_VOLATILE. A persistent key * always has a nonzero key identifier, set with psa_set_key_id() when * creating the key. Implementations may provide additional pre-provisioned * keys that can be opened with psa_open_key(). Such keys have an application * key identifier in the vendor range, as documented in the description of * #psa_key_id_t. * * The application must eventually close the handle with psa_close_key() or * psa_destroy_key() to release associated resources. If the application dies * without calling one of these functions, the implementation should perform * the equivalent of a call to psa_close_key(). * * Some implementations permit an application to open the same key multiple * times. If this is successful, each call to psa_open_key() will return a * different key handle. * * \note This API is not part of the PSA Cryptography API Release 1.0.0 * specification. It was defined in the 1.0 Beta 3 version of the * specification but was removed in the 1.0.0 released version. This API is * kept for the time being to not break applications relying on it. It is not * deprecated yet but will be in the near future. * * \note Applications that rely on opening a key multiple times will not be * portable to implementations that only permit a single key handle to be * opened. See also :ref:\`key-handles\`. * * * \param key The persistent identifier of the key. * \param[out] handle On success, a handle to the key. * * \retval #PSA_SUCCESS * Success. The application can now use the value of `*handle` * to access the key. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * The implementation does not have sufficient resources to open the * key. This can be due to reaching an implementation limit on the * number of open keys, the number of open key handles, or available * memory. * \retval #PSA_ERROR_DOES_NOT_EXIST * There is no persistent key with key identifier \p key. * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not a valid persistent key identifier. * \retval #PSA_ERROR_NOT_PERMITTED * The specified key exists, but the application does not have the * permission to access it. Note that this specification does not * define any way to create such a key, but it may be possible * through implementation-specific means. * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_DATA_INVALID * \retval #PSA_ERROR_DATA_CORRUPT * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_open_key( mbedtls_svc_key_id_t key, psa_key_handle_t *handle ); /** Close a key handle. * * If the handle designates a volatile key, this will destroy the key material * and free all associated resources, just like psa_destroy_key(). * * If this is the last open handle to a persistent key, then closing the handle * will free all resources associated with the key in volatile memory. The key * data in persistent storage is not affected and can be opened again later * with a call to psa_open_key(). * * Closing the key handle makes the handle invalid, and the key handle * must not be used again by the application. * * \note This API is not part of the PSA Cryptography API Release 1.0.0 * specification. It was defined in the 1.0 Beta 3 version of the * specification but was removed in the 1.0.0 released version. This API is * kept for the time being to not break applications relying on it. It is not * deprecated yet but will be in the near future. * * \note If the key handle was used to set up an active * :ref:\`multipart operation <multipart-operations>\`, then closing the * key handle can cause the multipart operation to fail. Applications should * maintain the key handle until after the multipart operation has finished. * * \param handle The key handle to close. * If this is \c 0, do nothing and return \c PSA_SUCCESS. * * \retval #PSA_SUCCESS * \p handle was a valid handle or \c 0. It is now closed. * \retval #PSA_ERROR_INVALID_HANDLE * \p handle is not a valid handle nor \c 0. * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_close_key(psa_key_handle_t handle); #ifdef __cplusplus } #endif #endif /* PSA_CRYPTO_COMPAT_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_se_driver.h
/** * \file psa/crypto_se_driver.h * \brief PSA external cryptoprocessor driver module * * This header declares types and function signatures for cryptography * drivers that access key material via opaque references. * This is meant for cryptoprocessors that have a separate key storage from the * space in which the PSA Crypto implementation runs, typically secure * elements (SEs). * * This file is part of the PSA Crypto Driver HAL (hardware abstraction layer), * containing functions for driver developers to implement to enable hardware * to be called in a standardized way by a PSA Cryptography API * implementation. The functions comprising the driver HAL, which driver * authors implement, are not intended to be called by application developers. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_SE_DRIVER_H #define PSA_CRYPTO_SE_DRIVER_H #include "crypto_driver_common.h" #ifdef __cplusplus extern "C" { #endif /** \defgroup se_init Secure element driver initialization */ /**@{*/ /** \brief Driver context structure * * Driver functions receive a pointer to this structure. * Each registered driver has one instance of this structure. * * Implementations must include the fields specified here and * may include other fields. */ typedef struct { /** A read-only pointer to the driver's persistent data. * * Drivers typically use this persistent data to keep track of * which slot numbers are available. This is only a guideline: * drivers may use the persistent data for any purpose, keeping * in mind the restrictions on when the persistent data is saved * to storage: the persistent data is only saved after calling * certain functions that receive a writable pointer to the * persistent data. * * The core allocates a memory buffer for the persistent data. * The pointer is guaranteed to be suitably aligned for any data type, * like a pointer returned by `malloc` (but the core can use any * method to allocate the buffer, not necessarily `malloc`). * * The size of this buffer is in the \c persistent_data_size field of * this structure. * * Before the driver is initialized for the first time, the content of * the persistent data is all-bits-zero. After a driver upgrade, if the * size of the persistent data has increased, the original data is padded * on the right with zeros; if the size has decreased, the original data * is truncated to the new size. * * This pointer is to read-only data. Only a few driver functions are * allowed to modify the persistent data. These functions receive a * writable pointer. These functions are: * - psa_drv_se_t::p_init * - psa_drv_se_key_management_t::p_allocate * - psa_drv_se_key_management_t::p_destroy * * The PSA Cryptography core saves the persistent data from one * session to the next. It does this before returning from API functions * that call a driver method that is allowed to modify the persistent * data, specifically: * - psa_crypto_init() causes a call to psa_drv_se_t::p_init, and may call * psa_drv_se_key_management_t::p_destroy to complete an action * that was interrupted by a power failure. * - Key creation functions cause a call to * psa_drv_se_key_management_t::p_allocate, and may cause a call to * psa_drv_se_key_management_t::p_destroy in case an error occurs. * - psa_destroy_key() causes a call to * psa_drv_se_key_management_t::p_destroy. */ const void *const persistent_data; /** The size of \c persistent_data in bytes. * * This is always equal to the value of the `persistent_data_size` field * of the ::psa_drv_se_t structure when the driver is registered. */ const size_t persistent_data_size; /** Driver transient data. * * The core initializes this value to 0 and does not read or modify it * afterwards. The driver may store whatever it wants in this field. */ uintptr_t transient_data; } psa_drv_se_context_t; /** \brief A driver initialization function. * * \param[in,out] drv_context The driver context structure. * \param[in,out] persistent_data A pointer to the persistent data * that allows writing. * \param location The location value for which this driver * is registered. The driver will be invoked * for all keys whose lifetime is in this * location. * * \retval #PSA_SUCCESS * The driver is operational. * The core will update the persistent data in storage. * \return * Any other return value prevents the driver from being used in * this session. * The core will NOT update the persistent data in storage. */ typedef psa_status_t (*psa_drv_se_init_t)(psa_drv_se_context_t *drv_context, void *persistent_data, psa_key_location_t location); #if defined(__DOXYGEN_ONLY__) || !defined(MBEDTLS_PSA_CRYPTO_SE_C) /* Mbed Crypto with secure element support enabled defines this type in * crypto_types.h because it is also visible to applications through an * implementation-specific extension. * For the PSA Cryptography specification, this type is only visible * via crypto_se_driver.h. */ /** An internal designation of a key slot between the core part of the * PSA Crypto implementation and the driver. The meaning of this value * is driver-dependent. */ typedef uint64_t psa_key_slot_number_t; #endif /* __DOXYGEN_ONLY__ || !MBEDTLS_PSA_CRYPTO_SE_C */ /**@}*/ /** \defgroup se_mac Secure Element Message Authentication Codes * Generation and authentication of Message Authentication Codes (MACs) using * a secure element can be done either as a single function call (via the * `psa_drv_se_mac_generate_t` or `psa_drv_se_mac_verify_t` functions), or in * parts using the following sequence: * - `psa_drv_se_mac_setup_t` * - `psa_drv_se_mac_update_t` * - `psa_drv_se_mac_update_t` * - ... * - `psa_drv_se_mac_finish_t` or `psa_drv_se_mac_finish_verify_t` * * If a previously started secure element MAC operation needs to be terminated, * it should be done so by the `psa_drv_se_mac_abort_t`. Failure to do so may * result in allocated resources not being freed or in other undefined * behavior. */ /**@{*/ /** \brief A function that starts a secure element MAC operation for a PSA * Crypto Driver implementation * * \param[in,out] drv_context The driver context structure. * \param[in,out] op_context A structure that will contain the * hardware-specific MAC context * \param[in] key_slot The slot of the key to be used for the * operation * \param[in] algorithm The algorithm to be used to underly the MAC * operation * * \retval #PSA_SUCCESS * Success. */ typedef psa_status_t (*psa_drv_se_mac_setup_t)(psa_drv_se_context_t *drv_context, void *op_context, psa_key_slot_number_t key_slot, psa_algorithm_t algorithm); /** \brief A function that continues a previously started secure element MAC * operation * * \param[in,out] op_context A hardware-specific structure for the * previously-established MAC operation to be * updated * \param[in] p_input A buffer containing the message to be appended * to the MAC operation * \param[in] input_length The size in bytes of the input message buffer */ typedef psa_status_t (*psa_drv_se_mac_update_t)(void *op_context, const uint8_t *p_input, size_t input_length); /** \brief a function that completes a previously started secure element MAC * operation by returning the resulting MAC. * * \param[in,out] op_context A hardware-specific structure for the * previously started MAC operation to be * finished * \param[out] p_mac A buffer where the generated MAC will be * placed * \param[in] mac_size The size in bytes of the buffer that has been * allocated for the `output` buffer * \param[out] p_mac_length After completion, will contain the number of * bytes placed in the `p_mac` buffer * * \retval #PSA_SUCCESS * Success. */ typedef psa_status_t (*psa_drv_se_mac_finish_t)(void *op_context, uint8_t *p_mac, size_t mac_size, size_t *p_mac_length); /** \brief A function that completes a previously started secure element MAC * operation by comparing the resulting MAC against a provided value * * \param[in,out] op_context A hardware-specific structure for the previously * started MAC operation to be fiinished * \param[in] p_mac The MAC value against which the resulting MAC * will be compared against * \param[in] mac_length The size in bytes of the value stored in `p_mac` * * \retval #PSA_SUCCESS * The operation completed successfully and the MACs matched each * other * \retval #PSA_ERROR_INVALID_SIGNATURE * The operation completed successfully, but the calculated MAC did * not match the provided MAC */ typedef psa_status_t (*psa_drv_se_mac_finish_verify_t)(void *op_context, const uint8_t *p_mac, size_t mac_length); /** \brief A function that aborts a previous started secure element MAC * operation * * \param[in,out] op_context A hardware-specific structure for the previously * started MAC operation to be aborted */ typedef psa_status_t (*psa_drv_se_mac_abort_t)(void *op_context); /** \brief A function that performs a secure element MAC operation in one * command and returns the calculated MAC * * \param[in,out] drv_context The driver context structure. * \param[in] p_input A buffer containing the message to be MACed * \param[in] input_length The size in bytes of `p_input` * \param[in] key_slot The slot of the key to be used * \param[in] alg The algorithm to be used to underlie the MAC * operation * \param[out] p_mac A buffer where the generated MAC will be * placed * \param[in] mac_size The size in bytes of the `p_mac` buffer * \param[out] p_mac_length After completion, will contain the number of * bytes placed in the `output` buffer * * \retval #PSA_SUCCESS * Success. */ typedef psa_status_t (*psa_drv_se_mac_generate_t)(psa_drv_se_context_t *drv_context, const uint8_t *p_input, size_t input_length, psa_key_slot_number_t key_slot, psa_algorithm_t alg, uint8_t *p_mac, size_t mac_size, size_t *p_mac_length); /** \brief A function that performs a secure element MAC operation in one * command and compares the resulting MAC against a provided value * * \param[in,out] drv_context The driver context structure. * \param[in] p_input A buffer containing the message to be MACed * \param[in] input_length The size in bytes of `input` * \param[in] key_slot The slot of the key to be used * \param[in] alg The algorithm to be used to underlie the MAC * operation * \param[in] p_mac The MAC value against which the resulting MAC will * be compared against * \param[in] mac_length The size in bytes of `mac` * * \retval #PSA_SUCCESS * The operation completed successfully and the MACs matched each * other * \retval #PSA_ERROR_INVALID_SIGNATURE * The operation completed successfully, but the calculated MAC did * not match the provided MAC */ typedef psa_status_t (*psa_drv_se_mac_verify_t)(psa_drv_se_context_t *drv_context, const uint8_t *p_input, size_t input_length, psa_key_slot_number_t key_slot, psa_algorithm_t alg, const uint8_t *p_mac, size_t mac_length); /** \brief A struct containing all of the function pointers needed to * perform secure element MAC operations * * PSA Crypto API implementations should populate the table as appropriate * upon startup. * * If one of the functions is not implemented (such as * `psa_drv_se_mac_generate_t`), it should be set to NULL. * * Driver implementers should ensure that they implement all of the functions * that make sense for their hardware, and that they provide a full solution * (for example, if they support `p_setup`, they should also support * `p_update` and at least one of `p_finish` or `p_finish_verify`). * */ typedef struct { /**The size in bytes of the hardware-specific secure element MAC context * structure */ size_t context_size; /** Function that performs a MAC setup operation */ psa_drv_se_mac_setup_t p_setup; /** Function that performs a MAC update operation */ psa_drv_se_mac_update_t p_update; /** Function that completes a MAC operation */ psa_drv_se_mac_finish_t p_finish; /** Function that completes a MAC operation with a verify check */ psa_drv_se_mac_finish_verify_t p_finish_verify; /** Function that aborts a previoustly started MAC operation */ psa_drv_se_mac_abort_t p_abort; /** Function that performs a MAC operation in one call */ psa_drv_se_mac_generate_t p_mac; /** Function that performs a MAC and verify operation in one call */ psa_drv_se_mac_verify_t p_mac_verify; } psa_drv_se_mac_t; /**@}*/ /** \defgroup se_cipher Secure Element Symmetric Ciphers * * Encryption and Decryption using secure element keys in block modes other * than ECB must be done in multiple parts, using the following flow: * - `psa_drv_se_cipher_setup_t` * - `psa_drv_se_cipher_set_iv_t` (optional depending upon block mode) * - `psa_drv_se_cipher_update_t` * - `psa_drv_se_cipher_update_t` * - ... * - `psa_drv_se_cipher_finish_t` * * If a previously started secure element Cipher operation needs to be * terminated, it should be done so by the `psa_drv_se_cipher_abort_t`. Failure * to do so may result in allocated resources not being freed or in other * undefined behavior. * * In situations where a PSA Cryptographic API implementation is using a block * mode not-supported by the underlying hardware or driver, it can construct * the block mode itself, while calling the `psa_drv_se_cipher_ecb_t` function * for the cipher operations. */ /**@{*/ /** \brief A function that provides the cipher setup function for a * secure element driver * * \param[in,out] drv_context The driver context structure. * \param[in,out] op_context A structure that will contain the * hardware-specific cipher context. * \param[in] key_slot The slot of the key to be used for the * operation * \param[in] algorithm The algorithm to be used in the cipher * operation * \param[in] direction Indicates whether the operation is an encrypt * or decrypt * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_NOT_SUPPORTED */ typedef psa_status_t (*psa_drv_se_cipher_setup_t)(psa_drv_se_context_t *drv_context, void *op_context, psa_key_slot_number_t key_slot, psa_algorithm_t algorithm, psa_encrypt_or_decrypt_t direction); /** \brief A function that sets the initialization vector (if * necessary) for an secure element cipher operation * * Rationale: The `psa_se_cipher_*` operation in the PSA Cryptographic API has * two IV functions: one to set the IV, and one to generate it internally. The * generate function is not necessary for the drivers to implement as the PSA * Crypto implementation can do the generation using its RNG features. * * \param[in,out] op_context A structure that contains the previously set up * hardware-specific cipher context * \param[in] p_iv A buffer containing the initialization vector * \param[in] iv_length The size (in bytes) of the `p_iv` buffer * * \retval #PSA_SUCCESS */ typedef psa_status_t (*psa_drv_se_cipher_set_iv_t)(void *op_context, const uint8_t *p_iv, size_t iv_length); /** \brief A function that continues a previously started secure element cipher * operation * * \param[in,out] op_context A hardware-specific structure for the * previously started cipher operation * \param[in] p_input A buffer containing the data to be * encrypted/decrypted * \param[in] input_size The size in bytes of the buffer pointed to * by `p_input` * \param[out] p_output The caller-allocated buffer where the * output will be placed * \param[in] output_size The allocated size in bytes of the * `p_output` buffer * \param[out] p_output_length After completion, will contain the number * of bytes placed in the `p_output` buffer * * \retval #PSA_SUCCESS */ typedef psa_status_t (*psa_drv_se_cipher_update_t)(void *op_context, const uint8_t *p_input, size_t input_size, uint8_t *p_output, size_t output_size, size_t *p_output_length); /** \brief A function that completes a previously started secure element cipher * operation * * \param[in,out] op_context A hardware-specific structure for the * previously started cipher operation * \param[out] p_output The caller-allocated buffer where the output * will be placed * \param[in] output_size The allocated size in bytes of the `p_output` * buffer * \param[out] p_output_length After completion, will contain the number of * bytes placed in the `p_output` buffer * * \retval #PSA_SUCCESS */ typedef psa_status_t (*psa_drv_se_cipher_finish_t)(void *op_context, uint8_t *p_output, size_t output_size, size_t *p_output_length); /** \brief A function that aborts a previously started secure element cipher * operation * * \param[in,out] op_context A hardware-specific structure for the * previously started cipher operation */ typedef psa_status_t (*psa_drv_se_cipher_abort_t)(void *op_context); /** \brief A function that performs the ECB block mode for secure element * cipher operations * * Note: this function should only be used with implementations that do not * provide a needed higher-level operation. * * \param[in,out] drv_context The driver context structure. * \param[in] key_slot The slot of the key to be used for the operation * \param[in] algorithm The algorithm to be used in the cipher operation * \param[in] direction Indicates whether the operation is an encrypt or * decrypt * \param[in] p_input A buffer containing the data to be * encrypted/decrypted * \param[in] input_size The size in bytes of the buffer pointed to by * `p_input` * \param[out] p_output The caller-allocated buffer where the output * will be placed * \param[in] output_size The allocated size in bytes of the `p_output` * buffer * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_NOT_SUPPORTED */ typedef psa_status_t (*psa_drv_se_cipher_ecb_t)(psa_drv_se_context_t *drv_context, psa_key_slot_number_t key_slot, psa_algorithm_t algorithm, psa_encrypt_or_decrypt_t direction, const uint8_t *p_input, size_t input_size, uint8_t *p_output, size_t output_size); /** * \brief A struct containing all of the function pointers needed to implement * cipher operations using secure elements. * * PSA Crypto API implementations should populate instances of the table as * appropriate upon startup or at build time. * * If one of the functions is not implemented (such as * `psa_drv_se_cipher_ecb_t`), it should be set to NULL. */ typedef struct { /** The size in bytes of the hardware-specific secure element cipher * context structure */ size_t context_size; /** Function that performs a cipher setup operation */ psa_drv_se_cipher_setup_t p_setup; /** Function that sets a cipher IV (if necessary) */ psa_drv_se_cipher_set_iv_t p_set_iv; /** Function that performs a cipher update operation */ psa_drv_se_cipher_update_t p_update; /** Function that completes a cipher operation */ psa_drv_se_cipher_finish_t p_finish; /** Function that aborts a cipher operation */ psa_drv_se_cipher_abort_t p_abort; /** Function that performs ECB mode for a cipher operation * (Danger: ECB mode should not be used directly by clients of the PSA * Crypto Client API) */ psa_drv_se_cipher_ecb_t p_ecb; } psa_drv_se_cipher_t; /**@}*/ /** \defgroup se_asymmetric Secure Element Asymmetric Cryptography * * Since the amount of data that can (or should) be encrypted or signed using * asymmetric keys is limited by the key size, asymmetric key operations using * keys in a secure element must be done in single function calls. */ /**@{*/ /** * \brief A function that signs a hash or short message with a private key in * a secure element * * \param[in,out] drv_context The driver context structure. * \param[in] key_slot Key slot of an asymmetric key pair * \param[in] alg A signature algorithm that is compatible * with the type of `key` * \param[in] p_hash The hash to sign * \param[in] hash_length Size of the `p_hash` buffer in bytes * \param[out] p_signature Buffer where the signature is to be written * \param[in] signature_size Size of the `p_signature` buffer in bytes * \param[out] p_signature_length On success, the number of bytes * that make up the returned signature value * * \retval #PSA_SUCCESS */ typedef psa_status_t (*psa_drv_se_asymmetric_sign_t)(psa_drv_se_context_t *drv_context, psa_key_slot_number_t key_slot, psa_algorithm_t alg, const uint8_t *p_hash, size_t hash_length, uint8_t *p_signature, size_t signature_size, size_t *p_signature_length); /** * \brief A function that verifies the signature a hash or short message using * an asymmetric public key in a secure element * * \param[in,out] drv_context The driver context structure. * \param[in] key_slot Key slot of a public key or an asymmetric key * pair * \param[in] alg A signature algorithm that is compatible with * the type of `key` * \param[in] p_hash The hash whose signature is to be verified * \param[in] hash_length Size of the `p_hash` buffer in bytes * \param[in] p_signature Buffer containing the signature to verify * \param[in] signature_length Size of the `p_signature` buffer in bytes * * \retval #PSA_SUCCESS * The signature is valid. */ typedef psa_status_t (*psa_drv_se_asymmetric_verify_t)(psa_drv_se_context_t *drv_context, psa_key_slot_number_t key_slot, psa_algorithm_t alg, const uint8_t *p_hash, size_t hash_length, const uint8_t *p_signature, size_t signature_length); /** * \brief A function that encrypts a short message with an asymmetric public * key in a secure element * * \param[in,out] drv_context The driver context structure. * \param[in] key_slot Key slot of a public key or an asymmetric key * pair * \param[in] alg An asymmetric encryption algorithm that is * compatible with the type of `key` * \param[in] p_input The message to encrypt * \param[in] input_length Size of the `p_input` buffer in bytes * \param[in] p_salt A salt or label, if supported by the * encryption algorithm * If the algorithm does not support a * salt, pass `NULL`. * If the algorithm supports an optional * salt and you do not want to pass a salt, * pass `NULL`. * For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is * supported. * \param[in] salt_length Size of the `p_salt` buffer in bytes * If `p_salt` is `NULL`, pass 0. * \param[out] p_output Buffer where the encrypted message is to * be written * \param[in] output_size Size of the `p_output` buffer in bytes * \param[out] p_output_length On success, the number of bytes that make up * the returned output * * \retval #PSA_SUCCESS */ typedef psa_status_t (*psa_drv_se_asymmetric_encrypt_t)(psa_drv_se_context_t *drv_context, psa_key_slot_number_t key_slot, psa_algorithm_t alg, const uint8_t *p_input, size_t input_length, const uint8_t *p_salt, size_t salt_length, uint8_t *p_output, size_t output_size, size_t *p_output_length); /** * \brief A function that decrypts a short message with an asymmetric private * key in a secure element. * * \param[in,out] drv_context The driver context structure. * \param[in] key_slot Key slot of an asymmetric key pair * \param[in] alg An asymmetric encryption algorithm that is * compatible with the type of `key` * \param[in] p_input The message to decrypt * \param[in] input_length Size of the `p_input` buffer in bytes * \param[in] p_salt A salt or label, if supported by the * encryption algorithm * If the algorithm does not support a * salt, pass `NULL`. * If the algorithm supports an optional * salt and you do not want to pass a salt, * pass `NULL`. * For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is * supported. * \param[in] salt_length Size of the `p_salt` buffer in bytes * If `p_salt` is `NULL`, pass 0. * \param[out] p_output Buffer where the decrypted message is to * be written * \param[in] output_size Size of the `p_output` buffer in bytes * \param[out] p_output_length On success, the number of bytes * that make up the returned output * * \retval #PSA_SUCCESS */ typedef psa_status_t (*psa_drv_se_asymmetric_decrypt_t)(psa_drv_se_context_t *drv_context, psa_key_slot_number_t key_slot, psa_algorithm_t alg, const uint8_t *p_input, size_t input_length, const uint8_t *p_salt, size_t salt_length, uint8_t *p_output, size_t output_size, size_t *p_output_length); /** * \brief A struct containing all of the function pointers needed to implement * asymmetric cryptographic operations using secure elements. * * PSA Crypto API implementations should populate instances of the table as * appropriate upon startup or at build time. * * If one of the functions is not implemented, it should be set to NULL. */ typedef struct { /** Function that performs an asymmetric sign operation */ psa_drv_se_asymmetric_sign_t p_sign; /** Function that performs an asymmetric verify operation */ psa_drv_se_asymmetric_verify_t p_verify; /** Function that performs an asymmetric encrypt operation */ psa_drv_se_asymmetric_encrypt_t p_encrypt; /** Function that performs an asymmetric decrypt operation */ psa_drv_se_asymmetric_decrypt_t p_decrypt; } psa_drv_se_asymmetric_t; /**@}*/ /** \defgroup se_aead Secure Element Authenticated Encryption with Additional Data * Authenticated Encryption with Additional Data (AEAD) operations with secure * elements must be done in one function call. While this creates a burden for * implementers as there must be sufficient space in memory for the entire * message, it prevents decrypted data from being made available before the * authentication operation is complete and the data is known to be authentic. */ /**@{*/ /** \brief A function that performs a secure element authenticated encryption * operation * * \param[in,out] drv_context The driver context structure. * \param[in] key_slot Slot containing the key to use. * \param[in] algorithm The AEAD algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(`alg`) is true) * \param[in] p_nonce Nonce or IV to use * \param[in] nonce_length Size of the `p_nonce` buffer in bytes * \param[in] p_additional_data Additional data that will be * authenticated but not encrypted * \param[in] additional_data_length Size of `p_additional_data` in bytes * \param[in] p_plaintext Data that will be authenticated and * encrypted * \param[in] plaintext_length Size of `p_plaintext` in bytes * \param[out] p_ciphertext Output buffer for the authenticated and * encrypted data. The additional data is * not part of this output. For algorithms * where the encrypted data and the * authentication tag are defined as * separate outputs, the authentication * tag is appended to the encrypted data. * \param[in] ciphertext_size Size of the `p_ciphertext` buffer in * bytes * \param[out] p_ciphertext_length On success, the size of the output in * the `p_ciphertext` buffer * * \retval #PSA_SUCCESS * Success. */ typedef psa_status_t (*psa_drv_se_aead_encrypt_t)(psa_drv_se_context_t *drv_context, psa_key_slot_number_t key_slot, psa_algorithm_t algorithm, const uint8_t *p_nonce, size_t nonce_length, const uint8_t *p_additional_data, size_t additional_data_length, const uint8_t *p_plaintext, size_t plaintext_length, uint8_t *p_ciphertext, size_t ciphertext_size, size_t *p_ciphertext_length); /** A function that peforms a secure element authenticated decryption operation * * \param[in,out] drv_context The driver context structure. * \param[in] key_slot Slot containing the key to use * \param[in] algorithm The AEAD algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(`alg`) is true) * \param[in] p_nonce Nonce or IV to use * \param[in] nonce_length Size of the `p_nonce` buffer in bytes * \param[in] p_additional_data Additional data that has been * authenticated but not encrypted * \param[in] additional_data_length Size of `p_additional_data` in bytes * \param[in] p_ciphertext Data that has been authenticated and * encrypted. * For algorithms where the encrypted data * and the authentication tag are defined * as separate inputs, the buffer must * contain the encrypted data followed by * the authentication tag. * \param[in] ciphertext_length Size of `p_ciphertext` in bytes * \param[out] p_plaintext Output buffer for the decrypted data * \param[in] plaintext_size Size of the `p_plaintext` buffer in * bytes * \param[out] p_plaintext_length On success, the size of the output in * the `p_plaintext` buffer * * \retval #PSA_SUCCESS * Success. */ typedef psa_status_t (*psa_drv_se_aead_decrypt_t)(psa_drv_se_context_t *drv_context, psa_key_slot_number_t key_slot, psa_algorithm_t algorithm, const uint8_t *p_nonce, size_t nonce_length, const uint8_t *p_additional_data, size_t additional_data_length, const uint8_t *p_ciphertext, size_t ciphertext_length, uint8_t *p_plaintext, size_t plaintext_size, size_t *p_plaintext_length); /** * \brief A struct containing all of the function pointers needed to implement * secure element Authenticated Encryption with Additional Data operations * * PSA Crypto API implementations should populate instances of the table as * appropriate upon startup. * * If one of the functions is not implemented, it should be set to NULL. */ typedef struct { /** Function that performs the AEAD encrypt operation */ psa_drv_se_aead_encrypt_t p_encrypt; /** Function that performs the AEAD decrypt operation */ psa_drv_se_aead_decrypt_t p_decrypt; } psa_drv_se_aead_t; /**@}*/ /** \defgroup se_key_management Secure Element Key Management * Currently, key management is limited to importing keys in the clear, * destroying keys, and exporting keys in the clear. * Whether a key may be exported is determined by the key policies in place * on the key slot. */ /**@{*/ /** An enumeration indicating how a key is created. */ typedef enum { PSA_KEY_CREATION_IMPORT, /**< During psa_import_key() */ PSA_KEY_CREATION_GENERATE, /**< During psa_generate_key() */ PSA_KEY_CREATION_DERIVE, /**< During psa_key_derivation_output_key() */ PSA_KEY_CREATION_COPY, /**< During psa_copy_key() */ #ifndef __DOXYGEN_ONLY__ /** A key is being registered with mbedtls_psa_register_se_key(). * * The core only passes this value to * psa_drv_se_key_management_t::p_validate_slot_number, not to * psa_drv_se_key_management_t::p_allocate. The call to * `p_validate_slot_number` is not followed by any other call to the * driver: the key is considered successfully registered if the call to * `p_validate_slot_number` succeeds, or if `p_validate_slot_number` is * null. * * With this creation method, the driver must return #PSA_SUCCESS if * the given attributes are compatible with the existing key in the slot, * and #PSA_ERROR_DOES_NOT_EXIST if the driver can determine that there * is no key with the specified slot number. * * This is an Mbed Crypto extension. */ PSA_KEY_CREATION_REGISTER, #endif } psa_key_creation_method_t; /** \brief A function that allocates a slot for a key. * * To create a key in a specific slot in a secure element, the core * first calls this function to determine a valid slot number, * then calls a function to create the key material in that slot. * In nominal conditions (that is, if no error occurs), * the effect of a call to a key creation function in the PSA Cryptography * API with a lifetime that places the key in a secure element is the * following: * -# The core calls psa_drv_se_key_management_t::p_allocate * (or in some implementations * psa_drv_se_key_management_t::p_validate_slot_number). The driver * selects (or validates) a suitable slot number given the key attributes * and the state of the secure element. * -# The core calls a key creation function in the driver. * * The key creation functions in the PSA Cryptography API are: * - psa_import_key(), which causes * a call to `p_allocate` with \p method = #PSA_KEY_CREATION_IMPORT * then a call to psa_drv_se_key_management_t::p_import. * - psa_generate_key(), which causes * a call to `p_allocate` with \p method = #PSA_KEY_CREATION_GENERATE * then a call to psa_drv_se_key_management_t::p_import. * - psa_key_derivation_output_key(), which causes * a call to `p_allocate` with \p method = #PSA_KEY_CREATION_DERIVE * then a call to psa_drv_se_key_derivation_t::p_derive. * - psa_copy_key(), which causes * a call to `p_allocate` with \p method = #PSA_KEY_CREATION_COPY * then a call to psa_drv_se_key_management_t::p_export. * * In case of errors, other behaviors are possible. * - If the PSA Cryptography subsystem dies after the first step, * for example because the device has lost power abruptly, * the second step may never happen, or may happen after a reset * and re-initialization. Alternatively, after a reset and * re-initialization, the core may call * psa_drv_se_key_management_t::p_destroy on the slot number that * was allocated (or validated) instead of calling a key creation function. * - If an error occurs, the core may call * psa_drv_se_key_management_t::p_destroy on the slot number that * was allocated (or validated) instead of calling a key creation function. * * Errors and system resets also have an impact on the driver's persistent * data. If a reset happens before the overall key creation process is * completed (before or after the second step above), it is unspecified * whether the persistent data after the reset is identical to what it * was before or after the call to `p_allocate` (or `p_validate_slot_number`). * * \param[in,out] drv_context The driver context structure. * \param[in,out] persistent_data A pointer to the persistent data * that allows writing. * \param[in] attributes Attributes of the key. * \param method The way in which the key is being created. * \param[out] key_slot Slot where the key will be stored. * This must be a valid slot for a key of the * chosen type. It must be unoccupied. * * \retval #PSA_SUCCESS * Success. * The core will record \c *key_slot as the key slot where the key * is stored and will update the persistent data in storage. * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_INSUFFICIENT_STORAGE */ typedef psa_status_t (*psa_drv_se_allocate_key_t)( psa_drv_se_context_t *drv_context, void *persistent_data, const psa_key_attributes_t *attributes, psa_key_creation_method_t method, psa_key_slot_number_t *key_slot); /** \brief A function that determines whether a slot number is valid * for a key. * * To create a key in a specific slot in a secure element, the core * first calls this function to validate the choice of slot number, * then calls a function to create the key material in that slot. * See the documentation of #psa_drv_se_allocate_key_t for more details. * * As of the PSA Cryptography API specification version 1.0, there is no way * for applications to trigger a call to this function. However some * implementations offer the capability to create or declare a key in * a specific slot via implementation-specific means, generally for the * sake of initial device provisioning or onboarding. Such a mechanism may * be added to a future version of the PSA Cryptography API specification. * * This function may update the driver's persistent data through * \p persistent_data. The core will save the updated persistent data at the * end of the key creation process. See the description of * ::psa_drv_se_allocate_key_t for more information. * * \param[in,out] drv_context The driver context structure. * \param[in,out] persistent_data A pointer to the persistent data * that allows writing. * \param[in] attributes Attributes of the key. * \param method The way in which the key is being created. * \param[in] key_slot Slot where the key is to be stored. * * \retval #PSA_SUCCESS * The given slot number is valid for a key with the given * attributes. * \retval #PSA_ERROR_INVALID_ARGUMENT * The given slot number is not valid for a key with the * given attributes. This includes the case where the slot * number is not valid at all. * \retval #PSA_ERROR_ALREADY_EXISTS * There is already a key with the specified slot number. * Drivers may choose to return this error from the key * creation function instead. */ typedef psa_status_t (*psa_drv_se_validate_slot_number_t)( psa_drv_se_context_t *drv_context, void *persistent_data, const psa_key_attributes_t *attributes, psa_key_creation_method_t method, psa_key_slot_number_t key_slot); /** \brief A function that imports a key into a secure element in binary format * * This function can support any output from psa_export_key(). Refer to the * documentation of psa_export_key() for the format for each key type. * * \param[in,out] drv_context The driver context structure. * \param key_slot Slot where the key will be stored. * This must be a valid slot for a key of the * chosen type. It must be unoccupied. * \param[in] attributes The key attributes, including the lifetime, * the key type and the usage policy. * Drivers should not access the key size stored * in the attributes: it may not match the * data passed in \p data. * Drivers can call psa_get_key_lifetime(), * psa_get_key_type(), * psa_get_key_usage_flags() and * psa_get_key_algorithm() to access this * information. * \param[in] data Buffer containing the key data. * \param[in] data_length Size of the \p data buffer in bytes. * \param[out] bits On success, the key size in bits. The driver * must determine this value after parsing the * key according to the key type. * This value is not used if the function fails. * * \retval #PSA_SUCCESS * Success. */ typedef psa_status_t (*psa_drv_se_import_key_t)( psa_drv_se_context_t *drv_context, psa_key_slot_number_t key_slot, const psa_key_attributes_t *attributes, const uint8_t *data, size_t data_length, size_t *bits); /** * \brief A function that destroys a secure element key and restore the slot to * its default state * * This function destroys the content of the key from a secure element. * Implementations shall make a best effort to ensure that any previous content * of the slot is unrecoverable. * * This function returns the specified slot to its default state. * * \param[in,out] drv_context The driver context structure. * \param[in,out] persistent_data A pointer to the persistent data * that allows writing. * \param key_slot The key slot to erase. * * \retval #PSA_SUCCESS * The slot's content, if any, has been erased. */ typedef psa_status_t (*psa_drv_se_destroy_key_t)( psa_drv_se_context_t *drv_context, void *persistent_data, psa_key_slot_number_t key_slot); /** * \brief A function that exports a secure element key in binary format * * The output of this function can be passed to psa_import_key() to * create an equivalent object. * * If a key is created with `psa_import_key()` and then exported with * this function, it is not guaranteed that the resulting data is * identical: the implementation may choose a different representation * of the same key if the format permits it. * * This function should generate output in the same format that * `psa_export_key()` does. Refer to the * documentation of `psa_export_key()` for the format for each key type. * * \param[in,out] drv_context The driver context structure. * \param[in] key Slot whose content is to be exported. This must * be an occupied key slot. * \param[out] p_data Buffer where the key data is to be written. * \param[in] data_size Size of the `p_data` buffer in bytes. * \param[out] p_data_length On success, the number of bytes * that make up the key data. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_DOES_NOT_EXIST * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED */ typedef psa_status_t (*psa_drv_se_export_key_t)(psa_drv_se_context_t *drv_context, psa_key_slot_number_t key, uint8_t *p_data, size_t data_size, size_t *p_data_length); /** * \brief A function that generates a symmetric or asymmetric key on a secure * element * * If the key type \c type recorded in \p attributes * is asymmetric (#PSA_KEY_TYPE_IS_ASYMMETRIC(\c type) = 1), * the driver may export the public key at the time of generation, * in the format documented for psa_export_public_key() by writing it * to the \p pubkey buffer. * This is optional, intended for secure elements that output the * public key at generation time and that cannot export the public key * later. Drivers that do not need this feature should leave * \p *pubkey_length set to 0 and should * implement the psa_drv_key_management_t::p_export_public function. * Some implementations do not support this feature, in which case * \p pubkey is \c NULL and \p pubkey_size is 0. * * \param[in,out] drv_context The driver context structure. * \param key_slot Slot where the key will be stored. * This must be a valid slot for a key of the * chosen type. It must be unoccupied. * \param[in] attributes The key attributes, including the lifetime, * the key type and size, and the usage policy. * Drivers can call psa_get_key_lifetime(), * psa_get_key_type(), psa_get_key_bits(), * psa_get_key_usage_flags() and * psa_get_key_algorithm() to access this * information. * \param[out] pubkey A buffer where the driver can write the * public key, when generating an asymmetric * key pair. * This is \c NULL when generating a symmetric * key or if the core does not support * exporting the public key at generation time. * \param pubkey_size The size of the `pubkey` buffer in bytes. * This is 0 when generating a symmetric * key or if the core does not support * exporting the public key at generation time. * \param[out] pubkey_length On entry, this is always 0. * On success, the number of bytes written to * \p pubkey. If this is 0 or unchanged on return, * the core will not read the \p pubkey buffer, * and will instead call the driver's * psa_drv_key_management_t::p_export_public * function to export the public key when needed. */ typedef psa_status_t (*psa_drv_se_generate_key_t)( psa_drv_se_context_t *drv_context, psa_key_slot_number_t key_slot, const psa_key_attributes_t *attributes, uint8_t *pubkey, size_t pubkey_size, size_t *pubkey_length); /** * \brief A struct containing all of the function pointers needed to for secure * element key management * * PSA Crypto API implementations should populate instances of the table as * appropriate upon startup or at build time. * * If one of the functions is not implemented, it should be set to NULL. */ typedef struct { /** Function that allocates a slot for a key. */ psa_drv_se_allocate_key_t p_allocate; /** Function that checks the validity of a slot for a key. */ psa_drv_se_validate_slot_number_t p_validate_slot_number; /** Function that performs a key import operation */ psa_drv_se_import_key_t p_import; /** Function that performs a generation */ psa_drv_se_generate_key_t p_generate; /** Function that performs a key destroy operation */ psa_drv_se_destroy_key_t p_destroy; /** Function that performs a key export operation */ psa_drv_se_export_key_t p_export; /** Function that performs a public key export operation */ psa_drv_se_export_key_t p_export_public; } psa_drv_se_key_management_t; /**@}*/ /** \defgroup driver_derivation Secure Element Key Derivation and Agreement * Key derivation is the process of generating new key material using an * existing key and additional parameters, iterating through a basic * cryptographic function, such as a hash. * Key agreement is a part of cryptographic protocols that allows two parties * to agree on the same key value, but starting from different original key * material. * The flows are similar, and the PSA Crypto Driver Model uses the same functions * for both of the flows. * * There are two different final functions for the flows, * `psa_drv_se_key_derivation_derive` and `psa_drv_se_key_derivation_export`. * `psa_drv_se_key_derivation_derive` is used when the key material should be * placed in a slot on the hardware and not exposed to the caller. * `psa_drv_se_key_derivation_export` is used when the key material should be * returned to the PSA Cryptographic API implementation. * * Different key derivation algorithms require a different number of inputs. * Instead of having an API that takes as input variable length arrays, which * can be problemmatic to manage on embedded platforms, the inputs are passed * to the driver via a function, `psa_drv_se_key_derivation_collateral`, that * is called multiple times with different `collateral_id`s. Thus, for a key * derivation algorithm that required 3 parameter inputs, the flow would look * something like: * ~~~~~~~~~~~~~{.c} * psa_drv_se_key_derivation_setup(kdf_algorithm, source_key, dest_key_size_bytes); * psa_drv_se_key_derivation_collateral(kdf_algorithm_collateral_id_0, * p_collateral_0, * collateral_0_size); * psa_drv_se_key_derivation_collateral(kdf_algorithm_collateral_id_1, * p_collateral_1, * collateral_1_size); * psa_drv_se_key_derivation_collateral(kdf_algorithm_collateral_id_2, * p_collateral_2, * collateral_2_size); * psa_drv_se_key_derivation_derive(); * ~~~~~~~~~~~~~ * * key agreement example: * ~~~~~~~~~~~~~{.c} * psa_drv_se_key_derivation_setup(alg, source_key. dest_key_size_bytes); * psa_drv_se_key_derivation_collateral(DHE_PUBKEY, p_pubkey, pubkey_size); * psa_drv_se_key_derivation_export(p_session_key, * session_key_size, * &session_key_length); * ~~~~~~~~~~~~~ */ /**@{*/ /** \brief A function that Sets up a secure element key derivation operation by * specifying the algorithm and the source key sot * * \param[in,out] drv_context The driver context structure. * \param[in,out] op_context A hardware-specific structure containing any * context information for the implementation * \param[in] kdf_alg The algorithm to be used for the key derivation * \param[in] source_key The key to be used as the source material for * the key derivation * * \retval #PSA_SUCCESS */ typedef psa_status_t (*psa_drv_se_key_derivation_setup_t)(psa_drv_se_context_t *drv_context, void *op_context, psa_algorithm_t kdf_alg, psa_key_slot_number_t source_key); /** \brief A function that provides collateral (parameters) needed for a secure * element key derivation or key agreement operation * * Since many key derivation algorithms require multiple parameters, it is * expected that this function may be called multiple times for the same * operation, each with a different algorithm-specific `collateral_id` * * \param[in,out] op_context A hardware-specific structure containing any * context information for the implementation * \param[in] collateral_id An ID for the collateral being provided * \param[in] p_collateral A buffer containing the collateral data * \param[in] collateral_size The size in bytes of the collateral * * \retval #PSA_SUCCESS */ typedef psa_status_t (*psa_drv_se_key_derivation_collateral_t)(void *op_context, uint32_t collateral_id, const uint8_t *p_collateral, size_t collateral_size); /** \brief A function that performs the final secure element key derivation * step and place the generated key material in a slot * * \param[in,out] op_context A hardware-specific structure containing any * context information for the implementation * \param[in] dest_key The slot where the generated key material * should be placed * * \retval #PSA_SUCCESS */ typedef psa_status_t (*psa_drv_se_key_derivation_derive_t)(void *op_context, psa_key_slot_number_t dest_key); /** \brief A function that performs the final step of a secure element key * agreement and place the generated key material in a buffer * * \param[out] p_output Buffer in which to place the generated key * material * \param[in] output_size The size in bytes of `p_output` * \param[out] p_output_length Upon success, contains the number of bytes of * key material placed in `p_output` * * \retval #PSA_SUCCESS */ typedef psa_status_t (*psa_drv_se_key_derivation_export_t)(void *op_context, uint8_t *p_output, size_t output_size, size_t *p_output_length); /** * \brief A struct containing all of the function pointers needed to for secure * element key derivation and agreement * * PSA Crypto API implementations should populate instances of the table as * appropriate upon startup. * * If one of the functions is not implemented, it should be set to NULL. */ typedef struct { /** The driver-specific size of the key derivation context */ size_t context_size; /** Function that performs a key derivation setup */ psa_drv_se_key_derivation_setup_t p_setup; /** Function that sets key derivation collateral */ psa_drv_se_key_derivation_collateral_t p_collateral; /** Function that performs a final key derivation step */ psa_drv_se_key_derivation_derive_t p_derive; /** Function that perforsm a final key derivation or agreement and * exports the key */ psa_drv_se_key_derivation_export_t p_export; } psa_drv_se_key_derivation_t; /**@}*/ /** \defgroup se_registration Secure element driver registration */ /**@{*/ /** A structure containing pointers to all the entry points of a * secure element driver. * * Future versions of this specification may add extra substructures at * the end of this structure. */ typedef struct { /** The version of the driver HAL that this driver implements. * This is a protection against loading driver binaries built against * a different version of this specification. * Use #PSA_DRV_SE_HAL_VERSION. */ uint32_t hal_version; /** The size of the driver's persistent data in bytes. * * This can be 0 if the driver does not need persistent data. * * See the documentation of psa_drv_se_context_t::persistent_data * for more information about why and how a driver can use * persistent data. */ size_t persistent_data_size; /** The driver initialization function. * * This function is called once during the initialization of the * PSA Cryptography subsystem, before any other function of the * driver is called. If this function returns a failure status, * the driver will be unusable, at least until the next system reset. * * If this field is \c NULL, it is equivalent to a function that does * nothing and returns #PSA_SUCCESS. */ psa_drv_se_init_t p_init; const psa_drv_se_key_management_t *key_management; const psa_drv_se_mac_t *mac; const psa_drv_se_cipher_t *cipher; const psa_drv_se_aead_t *aead; const psa_drv_se_asymmetric_t *asymmetric; const psa_drv_se_key_derivation_t *derivation; } psa_drv_se_t; /** The current version of the secure element driver HAL. */ /* 0.0.0 patchlevel 5 */ #define PSA_DRV_SE_HAL_VERSION 0x00000005 /** Register an external cryptoprocessor (secure element) driver. * * This function is only intended to be used by driver code, not by * application code. In implementations with separation between the * PSA cryptography module and applications, this function should * only be available to callers that run in the same memory space as * the cryptography module, and should not be exposed to applications * running in a different memory space. * * This function may be called before psa_crypto_init(). It is * implementation-defined whether this function may be called * after psa_crypto_init(). * * \note Implementations store metadata about keys including the lifetime * value, which contains the driver's location indicator. Therefore, * from one instantiation of the PSA Cryptography * library to the next one, if there is a key in storage with a certain * lifetime value, you must always register the same driver (or an * updated version that communicates with the same secure element) * with the same location value. * * \param location The location value through which this driver will * be exposed to applications. * This driver will be used for all keys such that * `location == #PSA_KEY_LIFETIME_GET_LOCATION( lifetime )`. * The value #PSA_KEY_LOCATION_LOCAL_STORAGE is reserved * and may not be used for drivers. Implementations * may reserve other values. * \param[in] methods The method table of the driver. This structure must * remain valid for as long as the cryptography * module keeps running. It is typically a global * constant. * * \return #PSA_SUCCESS * The driver was successfully registered. Applications can now * use \p location to access keys through the methods passed to * this function. * \return #PSA_ERROR_BAD_STATE * This function was called after the initialization of the * cryptography module, and this implementation does not support * driver registration at this stage. * \return #PSA_ERROR_ALREADY_EXISTS * There is already a registered driver for this value of \p location. * \return #PSA_ERROR_INVALID_ARGUMENT * \p location is a reserved value. * \return #PSA_ERROR_NOT_SUPPORTED * `methods->hal_version` is not supported by this implementation. * \return #PSA_ERROR_INSUFFICIENT_MEMORY * \return #PSA_ERROR_NOT_PERMITTED * \return #PSA_ERROR_STORAGE_FAILURE * \return #PSA_ERROR_DATA_CORRUPT */ psa_status_t psa_register_se_driver( psa_key_location_t location, const psa_drv_se_t *methods); /**@}*/ #ifdef __cplusplus } #endif #endif /* PSA_CRYPTO_SE_DRIVER_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_builtin_composites.h
/* * Context structure declaration of the Mbed TLS software-based PSA drivers * called through the PSA Crypto driver dispatch layer. * This file contains the context structures of those algorithms which need to * rely on other algorithms, i.e. are 'composite' algorithms. * * \note This file may not be included directly. Applications must * include psa/crypto.h. * * \note This header and its content is not part of the Mbed TLS API and * applications must not depend on it. Its main purpose is to define the * multi-part state objects of the Mbed TLS software-based PSA drivers. The * definition of these objects are then used by crypto_struct.h to define the * implementation-defined types of PSA multi-part state objects. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_BUILTIN_COMPOSITES_H #define PSA_CRYPTO_BUILTIN_COMPOSITES_H #include <psa/crypto_driver_common.h> /* * MAC multi-part operation definitions. */ #if defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC) #define MBEDTLS_PSA_BUILTIN_MAC #endif #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC) || defined(PSA_CRYPTO_DRIVER_TEST) typedef struct { /** The HMAC algorithm in use */ psa_algorithm_t alg; /** The hash context. */ struct psa_hash_operation_s hash_ctx; /** The HMAC part of the context. */ uint8_t opad[PSA_HMAC_MAX_HASH_BLOCK_SIZE]; } mbedtls_psa_hmac_operation_t; #define MBEDTLS_PSA_HMAC_OPERATION_INIT {0, PSA_HASH_OPERATION_INIT, {0}} #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */ #include "mbedtls/cmac.h" typedef struct { psa_algorithm_t alg; union { unsigned dummy; /* Make the union non-empty even with no supported algorithms. */ #if defined(MBEDTLS_PSA_BUILTIN_ALG_HMAC) || defined(PSA_CRYPTO_DRIVER_TEST) mbedtls_psa_hmac_operation_t hmac; #endif /* MBEDTLS_PSA_BUILTIN_ALG_HMAC */ #if defined(MBEDTLS_PSA_BUILTIN_ALG_CMAC) || defined(PSA_CRYPTO_DRIVER_TEST) mbedtls_cipher_context_t cmac; #endif /* MBEDTLS_PSA_BUILTIN_ALG_CMAC */ } ctx; } mbedtls_psa_mac_operation_t; #define MBEDTLS_PSA_MAC_OPERATION_INIT {0, {0}} /* * BEYOND THIS POINT, TEST DRIVER DECLARATIONS ONLY. */ #if defined(PSA_CRYPTO_DRIVER_TEST) typedef mbedtls_psa_mac_operation_t mbedtls_transparent_test_driver_mac_operation_t; typedef mbedtls_psa_mac_operation_t mbedtls_opaque_test_driver_mac_operation_t; #define MBEDTLS_TRANSPARENT_TEST_DRIVER_MAC_OPERATION_INIT MBEDTLS_PSA_MAC_OPERATION_INIT #define MBEDTLS_OPAQUE_TEST_DRIVER_MAC_OPERATION_INIT MBEDTLS_PSA_MAC_OPERATION_INIT #endif /* PSA_CRYPTO_DRIVER_TEST */ #endif /* PSA_CRYPTO_BUILTIN_COMPOSITES_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto.h
/** * \file psa/crypto.h * \brief Platform Security Architecture cryptography module */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_H #define PSA_CRYPTO_H #include "crypto_platform.h" #include <stddef.h> #ifdef __DOXYGEN_ONLY__ /* This __DOXYGEN_ONLY__ block contains mock definitions for things that * must be defined in the crypto_platform.h header. These mock definitions * are present in this file as a convenience to generate pretty-printed * documentation that includes those definitions. */ /** \defgroup platform Implementation-specific definitions * @{ */ /**@}*/ #endif /* __DOXYGEN_ONLY__ */ #ifdef __cplusplus extern "C" { #endif /* The file "crypto_types.h" declares types that encode errors, * algorithms, key types, policies, etc. */ #include "crypto_types.h" /** \defgroup version API version * @{ */ /** * The major version of this implementation of the PSA Crypto API */ #define PSA_CRYPTO_API_VERSION_MAJOR 1 /** * The minor version of this implementation of the PSA Crypto API */ #define PSA_CRYPTO_API_VERSION_MINOR 0 /**@}*/ /* The file "crypto_values.h" declares macros to build and analyze values * of integral types defined in "crypto_types.h". */ #include "crypto_values.h" /** \defgroup initialization Library initialization * @{ */ /** * \brief Library initialization. * * Applications must call this function before calling any other * function in this module. * * Applications may call this function more than once. Once a call * succeeds, subsequent calls are guaranteed to succeed. * * If the application calls other functions before calling psa_crypto_init(), * the behavior is undefined. Implementations are encouraged to either perform * the operation as if the library had been initialized or to return * #PSA_ERROR_BAD_STATE or some other applicable error. In particular, * implementations should not return a success status if the lack of * initialization may have security implications, for example due to improper * seeding of the random number generator. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_INSUFFICIENT_STORAGE * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_DATA_INVALID * \retval #PSA_ERROR_DATA_CORRUPT */ psa_status_t psa_crypto_init(void); /**@}*/ /** \addtogroup attributes * @{ */ /** \def PSA_KEY_ATTRIBUTES_INIT * * This macro returns a suitable initializer for a key attribute structure * of type #psa_key_attributes_t. */ #ifdef __DOXYGEN_ONLY__ /* This is an example definition for documentation purposes. * Implementations should define a suitable value in `crypto_struct.h`. */ #define PSA_KEY_ATTRIBUTES_INIT {0} #endif /** Return an initial value for a key attributes structure. */ static psa_key_attributes_t psa_key_attributes_init(void); /** Declare a key as persistent and set its key identifier. * * If the attribute structure currently declares the key as volatile (which * is the default content of an attribute structure), this function sets * the lifetime attribute to #PSA_KEY_LIFETIME_PERSISTENT. * * This function does not access storage, it merely stores the given * value in the structure. * The persistent key will be written to storage when the attribute * structure is passed to a key creation function such as * psa_import_key(), psa_generate_key(), * psa_key_derivation_output_key() or psa_copy_key(). * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate each of its arguments exactly once. * * \param[out] attributes The attribute structure to write to. * \param key The persistent identifier for the key. */ static void psa_set_key_id( psa_key_attributes_t *attributes, mbedtls_svc_key_id_t key ); #ifdef MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER /** Set the owner identifier of a key. * * When key identifiers encode key owner identifiers, psa_set_key_id() does * not allow to define in key attributes the owner of volatile keys as * psa_set_key_id() enforces the key to be persistent. * * This function allows to set in key attributes the owner identifier of a * key. It is intended to be used for volatile keys. For persistent keys, * it is recommended to use the PSA Cryptography API psa_set_key_id() to define * the owner of a key. * * \param[out] attributes The attribute structure to write to. * \param owner_id The key owner identifier. */ static void mbedtls_set_key_owner_id( psa_key_attributes_t *attributes, mbedtls_key_owner_id_t owner_id ); #endif /** Set the location of a persistent key. * * To make a key persistent, you must give it a persistent key identifier * with psa_set_key_id(). By default, a key that has a persistent identifier * is stored in the default storage area identifier by * #PSA_KEY_LIFETIME_PERSISTENT. Call this function to choose a storage * area, or to explicitly declare the key as volatile. * * This function does not access storage, it merely stores the given * value in the structure. * The persistent key will be written to storage when the attribute * structure is passed to a key creation function such as * psa_import_key(), psa_generate_key(), * psa_key_derivation_output_key() or psa_copy_key(). * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate each of its arguments exactly once. * * \param[out] attributes The attribute structure to write to. * \param lifetime The lifetime for the key. * If this is #PSA_KEY_LIFETIME_VOLATILE, the * key will be volatile, and the key identifier * attribute is reset to 0. */ static void psa_set_key_lifetime(psa_key_attributes_t *attributes, psa_key_lifetime_t lifetime); /** Retrieve the key identifier from key attributes. * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate its argument exactly once. * * \param[in] attributes The key attribute structure to query. * * \return The persistent identifier stored in the attribute structure. * This value is unspecified if the attribute structure declares * the key as volatile. */ static mbedtls_svc_key_id_t psa_get_key_id( const psa_key_attributes_t *attributes); /** Retrieve the lifetime from key attributes. * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate its argument exactly once. * * \param[in] attributes The key attribute structure to query. * * \return The lifetime value stored in the attribute structure. */ static psa_key_lifetime_t psa_get_key_lifetime( const psa_key_attributes_t *attributes); /** Declare usage flags for a key. * * Usage flags are part of a key's usage policy. They encode what * kind of operations are permitted on the key. For more details, * refer to the documentation of the type #psa_key_usage_t. * * This function overwrites any usage flags * previously set in \p attributes. * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate each of its arguments exactly once. * * \param[out] attributes The attribute structure to write to. * \param usage_flags The usage flags to write. */ static void psa_set_key_usage_flags(psa_key_attributes_t *attributes, psa_key_usage_t usage_flags); /** Retrieve the usage flags from key attributes. * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate its argument exactly once. * * \param[in] attributes The key attribute structure to query. * * \return The usage flags stored in the attribute structure. */ static psa_key_usage_t psa_get_key_usage_flags( const psa_key_attributes_t *attributes); /** Declare the permitted algorithm policy for a key. * * The permitted algorithm policy of a key encodes which algorithm or * algorithms are permitted to be used with this key. The following * algorithm policies are supported: * - 0 does not allow any cryptographic operation with the key. The key * may be used for non-cryptographic actions such as exporting (if * permitted by the usage flags). * - An algorithm value permits this particular algorithm. * - An algorithm wildcard built from #PSA_ALG_ANY_HASH allows the specified * signature scheme with any hash algorithm. * - An algorithm built from #PSA_ALG_AT_LEAST_THIS_LENGTH_MAC allows * any MAC algorithm from the same base class (e.g. CMAC) which * generates/verifies a MAC length greater than or equal to the length * encoded in the wildcard algorithm. * - An algorithm built from #PSA_ALG_AEAD_WITH_AT_LEAST_THIS_LENGTH_TAG * allows any AEAD algorithm from the same base class (e.g. CCM) which * generates/verifies a tag length greater than or equal to the length * encoded in the wildcard algorithm. * * This function overwrites any algorithm policy * previously set in \p attributes. * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate each of its arguments exactly once. * * \param[out] attributes The attribute structure to write to. * \param alg The permitted algorithm policy to write. */ static void psa_set_key_algorithm(psa_key_attributes_t *attributes, psa_algorithm_t alg); /** Retrieve the algorithm policy from key attributes. * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate its argument exactly once. * * \param[in] attributes The key attribute structure to query. * * \return The algorithm stored in the attribute structure. */ static psa_algorithm_t psa_get_key_algorithm( const psa_key_attributes_t *attributes); /** Declare the type of a key. * * This function overwrites any key type * previously set in \p attributes. * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate each of its arguments exactly once. * * \param[out] attributes The attribute structure to write to. * \param type The key type to write. * If this is 0, the key type in \p attributes * becomes unspecified. */ static void psa_set_key_type(psa_key_attributes_t *attributes, psa_key_type_t type); /** Declare the size of a key. * * This function overwrites any key size previously set in \p attributes. * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate each of its arguments exactly once. * * \param[out] attributes The attribute structure to write to. * \param bits The key size in bits. * If this is 0, the key size in \p attributes * becomes unspecified. Keys of size 0 are * not supported. */ static void psa_set_key_bits(psa_key_attributes_t *attributes, size_t bits); /** Retrieve the key type from key attributes. * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate its argument exactly once. * * \param[in] attributes The key attribute structure to query. * * \return The key type stored in the attribute structure. */ static psa_key_type_t psa_get_key_type(const psa_key_attributes_t *attributes); /** Retrieve the key size from key attributes. * * This function may be declared as `static` (i.e. without external * linkage). This function may be provided as a function-like macro, * but in this case it must evaluate its argument exactly once. * * \param[in] attributes The key attribute structure to query. * * \return The key size stored in the attribute structure, in bits. */ static size_t psa_get_key_bits(const psa_key_attributes_t *attributes); /** Retrieve the attributes of a key. * * This function first resets the attribute structure as with * psa_reset_key_attributes(). It then copies the attributes of * the given key into the given attribute structure. * * \note This function may allocate memory or other resources. * Once you have called this function on an attribute structure, * you must call psa_reset_key_attributes() to free these resources. * * \param[in] key Identifier of the key to query. * \param[in,out] attributes On success, the attributes of the key. * On failure, equivalent to a * freshly-initialized structure. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_DATA_CORRUPT * \retval #PSA_ERROR_DATA_INVALID * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_get_key_attributes(mbedtls_svc_key_id_t key, psa_key_attributes_t *attributes); /** Reset a key attribute structure to a freshly initialized state. * * You must initialize the attribute structure as described in the * documentation of the type #psa_key_attributes_t before calling this * function. Once the structure has been initialized, you may call this * function at any time. * * This function frees any auxiliary resources that the structure * may contain. * * \param[in,out] attributes The attribute structure to reset. */ void psa_reset_key_attributes(psa_key_attributes_t *attributes); /**@}*/ /** \defgroup key_management Key management * @{ */ /** Remove non-essential copies of key material from memory. * * If the key identifier designates a volatile key, this functions does not do * anything and returns successfully. * * If the key identifier designates a persistent key, then this function will * free all resources associated with the key in volatile memory. The key * data in persistent storage is not affected and the key can still be used. * * \param key Identifier of the key to purge. * * \retval #PSA_SUCCESS * The key material will have been removed from memory if it is not * currently required. * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not a valid key identifier. * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_purge_key(mbedtls_svc_key_id_t key); /** Make a copy of a key. * * Copy key material from one location to another. * * This function is primarily useful to copy a key from one location * to another, since it populates a key using the material from * another key which may have a different lifetime. * * This function may be used to share a key with a different party, * subject to implementation-defined restrictions on key sharing. * * The policy on the source key must have the usage flag * #PSA_KEY_USAGE_COPY set. * This flag is sufficient to permit the copy if the key has the lifetime * #PSA_KEY_LIFETIME_VOLATILE or #PSA_KEY_LIFETIME_PERSISTENT. * Some secure elements do not provide a way to copy a key without * making it extractable from the secure element. If a key is located * in such a secure element, then the key must have both usage flags * #PSA_KEY_USAGE_COPY and #PSA_KEY_USAGE_EXPORT in order to make * a copy of the key outside the secure element. * * The resulting key may only be used in a way that conforms to * both the policy of the original key and the policy specified in * the \p attributes parameter: * - The usage flags on the resulting key are the bitwise-and of the * usage flags on the source policy and the usage flags in \p attributes. * - If both allow the same algorithm or wildcard-based * algorithm policy, the resulting key has the same algorithm policy. * - If either of the policies allows an algorithm and the other policy * allows a wildcard-based algorithm policy that includes this algorithm, * the resulting key allows the same algorithm. * - If the policies do not allow any algorithm in common, this function * fails with the status #PSA_ERROR_INVALID_ARGUMENT. * * The effect of this function on implementation-defined attributes is * implementation-defined. * * \param source_key The key to copy. It must allow the usage * #PSA_KEY_USAGE_COPY. If a private or secret key is * being copied outside of a secure element it must * also allow #PSA_KEY_USAGE_EXPORT. * \param[in] attributes The attributes for the new key. * They are used as follows: * - The key type and size may be 0. If either is * nonzero, it must match the corresponding * attribute of the source key. * - The key location (the lifetime and, for * persistent keys, the key identifier) is * used directly. * - The policy constraints (usage flags and * algorithm policy) are combined from * the source key and \p attributes so that * both sets of restrictions apply, as * described in the documentation of this function. * \param[out] target_key On success, an identifier for the newly created * key. For persistent keys, this is the key * identifier defined in \p attributes. * \c 0 on failure. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_HANDLE * \p source_key is invalid. * \retval #PSA_ERROR_ALREADY_EXISTS * This is an attempt to create a persistent key, and there is * already a persistent key with the given identifier. * \retval #PSA_ERROR_INVALID_ARGUMENT * The lifetime or identifier in \p attributes are invalid. * \retval #PSA_ERROR_INVALID_ARGUMENT * The policy constraints on the source and specified in * \p attributes are incompatible. * \retval #PSA_ERROR_INVALID_ARGUMENT * \p attributes specifies a key type or key size * which does not match the attributes of the source key. * \retval #PSA_ERROR_NOT_PERMITTED * The source key does not have the #PSA_KEY_USAGE_COPY usage flag. * \retval #PSA_ERROR_NOT_PERMITTED * The source key is not exportable and its lifetime does not * allow copying it to the target's lifetime. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_INSUFFICIENT_STORAGE * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_DATA_INVALID * \retval #PSA_ERROR_DATA_CORRUPT * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_copy_key(mbedtls_svc_key_id_t source_key, const psa_key_attributes_t *attributes, mbedtls_svc_key_id_t *target_key); /** * \brief Destroy a key. * * This function destroys a key from both volatile * memory and, if applicable, non-volatile storage. Implementations shall * make a best effort to ensure that that the key material cannot be recovered. * * This function also erases any metadata such as policies and frees * resources associated with the key. * * If a key is currently in use in a multipart operation, then destroying the * key will cause the multipart operation to fail. * * \param key Identifier of the key to erase. If this is \c 0, do nothing and * return #PSA_SUCCESS. * * \retval #PSA_SUCCESS * \p key was a valid identifier and the key material that it * referred to has been erased. Alternatively, \p key is \c 0. * \retval #PSA_ERROR_NOT_PERMITTED * The key cannot be erased because it is * read-only, either due to a policy or due to physical restrictions. * \retval #PSA_ERROR_INVALID_HANDLE * \p key is not a valid identifier nor \c 0. * \retval #PSA_ERROR_COMMUNICATION_FAILURE * There was an failure in communication with the cryptoprocessor. * The key material may still be present in the cryptoprocessor. * \retval #PSA_ERROR_DATA_INVALID * This error is typically a result of either storage corruption on a * cleartext storage backend, or an attempt to read data that was * written by an incompatible version of the library. * \retval #PSA_ERROR_STORAGE_FAILURE * The storage is corrupted. Implementations shall make a best effort * to erase key material even in this stage, however applications * should be aware that it may be impossible to guarantee that the * key material is not recoverable in such cases. * \retval #PSA_ERROR_CORRUPTION_DETECTED * An unexpected condition which is not a storage corruption or * a communication failure occurred. The cryptoprocessor may have * been compromised. * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_destroy_key(mbedtls_svc_key_id_t key); /**@}*/ /** \defgroup import_export Key import and export * @{ */ /** * \brief Import a key in binary format. * * This function supports any output from psa_export_key(). Refer to the * documentation of psa_export_public_key() for the format of public keys * and to the documentation of psa_export_key() for the format for * other key types. * * The key data determines the key size. The attributes may optionally * specify a key size; in this case it must match the size determined * from the key data. A key size of 0 in \p attributes indicates that * the key size is solely determined by the key data. * * Implementations must reject an attempt to import a key of size 0. * * This specification supports a single format for each key type. * Implementations may support other formats as long as the standard * format is supported. Implementations that support other formats * should ensure that the formats are clearly unambiguous so as to * minimize the risk that an invalid input is accidentally interpreted * according to a different format. * * \param[in] attributes The attributes for the new key. * The key size is always determined from the * \p data buffer. * If the key size in \p attributes is nonzero, * it must be equal to the size from \p data. * \param[out] key On success, an identifier to the newly created key. * For persistent keys, this is the key identifier * defined in \p attributes. * \c 0 on failure. * \param[in] data Buffer containing the key data. The content of this * buffer is interpreted according to the type declared * in \p attributes. * All implementations must support at least the format * described in the documentation * of psa_export_key() or psa_export_public_key() for * the chosen type. Implementations may allow other * formats, but should be conservative: implementations * should err on the side of rejecting content if it * may be erroneous (e.g. wrong type or truncated data). * \param data_length Size of the \p data buffer in bytes. * * \retval #PSA_SUCCESS * Success. * If the key is persistent, the key material and the key's metadata * have been saved to persistent storage. * \retval #PSA_ERROR_ALREADY_EXISTS * This is an attempt to create a persistent key, and there is * already a persistent key with the given identifier. * \retval #PSA_ERROR_NOT_SUPPORTED * The key type or key size is not supported, either by the * implementation in general or in this particular persistent location. * \retval #PSA_ERROR_INVALID_ARGUMENT * The key attributes, as a whole, are invalid. * \retval #PSA_ERROR_INVALID_ARGUMENT * The key data is not correctly formatted. * \retval #PSA_ERROR_INVALID_ARGUMENT * The size in \p attributes is nonzero and does not match the size * of the key data. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_INSUFFICIENT_STORAGE * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_DATA_CORRUPT * \retval #PSA_ERROR_DATA_INVALID * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_import_key(const psa_key_attributes_t *attributes, const uint8_t *data, size_t data_length, mbedtls_svc_key_id_t *key); /** * \brief Export a key in binary format. * * The output of this function can be passed to psa_import_key() to * create an equivalent object. * * If the implementation of psa_import_key() supports other formats * beyond the format specified here, the output from psa_export_key() * must use the representation specified here, not the original * representation. * * For standard key types, the output format is as follows: * * - For symmetric keys (including MAC keys), the format is the * raw bytes of the key. * - For DES, the key data consists of 8 bytes. The parity bits must be * correct. * - For Triple-DES, the format is the concatenation of the * two or three DES keys. * - For RSA key pairs (#PSA_KEY_TYPE_RSA_KEY_PAIR), the format * is the non-encrypted DER encoding of the representation defined by * PKCS\#1 (RFC 8017) as `RSAPrivateKey`, version 0. * ``` * RSAPrivateKey ::= SEQUENCE { * version INTEGER, -- must be 0 * modulus INTEGER, -- n * publicExponent INTEGER, -- e * privateExponent INTEGER, -- d * prime1 INTEGER, -- p * prime2 INTEGER, -- q * exponent1 INTEGER, -- d mod (p-1) * exponent2 INTEGER, -- d mod (q-1) * coefficient INTEGER, -- (inverse of q) mod p * } * ``` * - For elliptic curve key pairs (key types for which * #PSA_KEY_TYPE_IS_ECC_KEY_PAIR is true), the format is * a representation of the private value as a `ceiling(m/8)`-byte string * where `m` is the bit size associated with the curve, i.e. the bit size * of the order of the curve's coordinate field. This byte string is * in little-endian order for Montgomery curves (curve types * `PSA_ECC_FAMILY_CURVEXXX`), and in big-endian order for Weierstrass * curves (curve types `PSA_ECC_FAMILY_SECTXXX`, `PSA_ECC_FAMILY_SECPXXX` * and `PSA_ECC_FAMILY_BRAINPOOL_PXXX`). * For Weierstrass curves, this is the content of the `privateKey` field of * the `ECPrivateKey` format defined by RFC 5915. For Montgomery curves, * the format is defined by RFC 7748, and output is masked according to §5. * For twisted Edwards curves, the private key is as defined by RFC 8032 * (a 32-byte string for Edwards25519, a 57-byte string for Edwards448). * - For Diffie-Hellman key exchange key pairs (key types for which * #PSA_KEY_TYPE_IS_DH_KEY_PAIR is true), the * format is the representation of the private key `x` as a big-endian byte * string. The length of the byte string is the private key size in bytes * (leading zeroes are not stripped). * - For public keys (key types for which #PSA_KEY_TYPE_IS_PUBLIC_KEY is * true), the format is the same as for psa_export_public_key(). * * The policy on the key must have the usage flag #PSA_KEY_USAGE_EXPORT set. * * \param key Identifier of the key to export. It must allow the * usage #PSA_KEY_USAGE_EXPORT, unless it is a public * key. * \param[out] data Buffer where the key data is to be written. * \param data_size Size of the \p data buffer in bytes. * \param[out] data_length On success, the number of bytes * that make up the key data. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * The key does not have the #PSA_KEY_USAGE_EXPORT flag. * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p data buffer is too small. You can determine a * sufficient buffer size by calling * #PSA_EXPORT_KEY_OUTPUT_SIZE(\c type, \c bits) * where \c type is the key type * and \c bits is the key size in bits. * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_export_key(mbedtls_svc_key_id_t key, uint8_t *data, size_t data_size, size_t *data_length); /** * \brief Export a public key or the public part of a key pair in binary format. * * The output of this function can be passed to psa_import_key() to * create an object that is equivalent to the public key. * * This specification supports a single format for each key type. * Implementations may support other formats as long as the standard * format is supported. Implementations that support other formats * should ensure that the formats are clearly unambiguous so as to * minimize the risk that an invalid input is accidentally interpreted * according to a different format. * * For standard key types, the output format is as follows: * - For RSA public keys (#PSA_KEY_TYPE_RSA_PUBLIC_KEY), the DER encoding of * the representation defined by RFC 3279 &sect;2.3.1 as `RSAPublicKey`. * ``` * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER } -- e * ``` * - For elliptic curve keys on a twisted Edwards curve (key types for which * #PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY is true and #PSA_KEY_TYPE_ECC_GET_FAMILY * returns #PSA_ECC_FAMILY_TWISTED_EDWARDS), the public key is as defined * by RFC 8032 * (a 32-byte string for Edwards25519, a 57-byte string for Edwards448). * - For other elliptic curve public keys (key types for which * #PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY is true), the format is the uncompressed * representation defined by SEC1 &sect;2.3.3 as the content of an ECPoint. * Let `m` be the bit size associated with the curve, i.e. the bit size of * `q` for a curve over `F_q`. The representation consists of: * - The byte 0x04; * - `x_P` as a `ceiling(m/8)`-byte string, big-endian; * - `y_P` as a `ceiling(m/8)`-byte string, big-endian. * - For Diffie-Hellman key exchange public keys (key types for which * #PSA_KEY_TYPE_IS_DH_PUBLIC_KEY is true), * the format is the representation of the public key `y = g^x mod p` as a * big-endian byte string. The length of the byte string is the length of the * base prime `p` in bytes. * * Exporting a public key object or the public part of a key pair is * always permitted, regardless of the key's usage flags. * * \param key Identifier of the key to export. * \param[out] data Buffer where the key data is to be written. * \param data_size Size of the \p data buffer in bytes. * \param[out] data_length On success, the number of bytes * that make up the key data. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_INVALID_ARGUMENT * The key is neither a public key nor a key pair. * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p data buffer is too small. You can determine a * sufficient buffer size by calling * #PSA_EXPORT_KEY_OUTPUT_SIZE(#PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(\c type), \c bits) * where \c type is the key type * and \c bits is the key size in bits. * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_export_public_key(mbedtls_svc_key_id_t key, uint8_t *data, size_t data_size, size_t *data_length); /**@}*/ /** \defgroup hash Message digests * @{ */ /** Calculate the hash (digest) of a message. * * \note To verify the hash of a message against an * expected value, use psa_hash_compare() instead. * * \param alg The hash algorithm to compute (\c PSA_ALG_XXX value * such that #PSA_ALG_IS_HASH(\p alg) is true). * \param[in] input Buffer containing the message to hash. * \param input_length Size of the \p input buffer in bytes. * \param[out] hash Buffer where the hash is to be written. * \param hash_size Size of the \p hash buffer in bytes. * \param[out] hash_length On success, the number of bytes * that make up the hash value. This is always * #PSA_HASH_LENGTH(\p alg). * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not a hash algorithm. * \retval #PSA_ERROR_INVALID_ARGUMENT * \retval #PSA_ERROR_BUFFER_TOO_SMALL * \p hash_size is too small * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_hash_compute(psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *hash, size_t hash_size, size_t *hash_length); /** Calculate the hash (digest) of a message and compare it with a * reference value. * * \param alg The hash algorithm to compute (\c PSA_ALG_XXX value * such that #PSA_ALG_IS_HASH(\p alg) is true). * \param[in] input Buffer containing the message to hash. * \param input_length Size of the \p input buffer in bytes. * \param[out] hash Buffer containing the expected hash value. * \param hash_length Size of the \p hash buffer in bytes. * * \retval #PSA_SUCCESS * The expected hash is identical to the actual hash of the input. * \retval #PSA_ERROR_INVALID_SIGNATURE * The hash of the message was calculated successfully, but it * differs from the expected hash. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not a hash algorithm. * \retval #PSA_ERROR_INVALID_ARGUMENT * \p input_length or \p hash_length do not match the hash size for \p alg * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_hash_compare(psa_algorithm_t alg, const uint8_t *input, size_t input_length, const uint8_t *hash, size_t hash_length); /** The type of the state data structure for multipart hash operations. * * Before calling any function on a hash operation object, the application must * initialize it by any of the following means: * - Set the structure to all-bits-zero, for example: * \code * psa_hash_operation_t operation; * memset(&operation, 0, sizeof(operation)); * \endcode * - Initialize the structure to logical zero values, for example: * \code * psa_hash_operation_t operation = {0}; * \endcode * - Initialize the structure to the initializer #PSA_HASH_OPERATION_INIT, * for example: * \code * psa_hash_operation_t operation = PSA_HASH_OPERATION_INIT; * \endcode * - Assign the result of the function psa_hash_operation_init() * to the structure, for example: * \code * psa_hash_operation_t operation; * operation = psa_hash_operation_init(); * \endcode * * This is an implementation-defined \c struct. Applications should not * make any assumptions about the content of this structure except * as directed by the documentation of a specific implementation. */ typedef struct psa_hash_operation_s psa_hash_operation_t; /** \def PSA_HASH_OPERATION_INIT * * This macro returns a suitable initializer for a hash operation object * of type #psa_hash_operation_t. */ #ifdef __DOXYGEN_ONLY__ /* This is an example definition for documentation purposes. * Implementations should define a suitable value in `crypto_struct.h`. */ #define PSA_HASH_OPERATION_INIT {0} #endif /** Return an initial value for a hash operation object. */ static psa_hash_operation_t psa_hash_operation_init(void); /** Set up a multipart hash operation. * * The sequence of operations to calculate a hash (message digest) * is as follows: * -# Allocate an operation object which will be passed to all the functions * listed here. * -# Initialize the operation object with one of the methods described in the * documentation for #psa_hash_operation_t, e.g. #PSA_HASH_OPERATION_INIT. * -# Call psa_hash_setup() to specify the algorithm. * -# Call psa_hash_update() zero, one or more times, passing a fragment * of the message each time. The hash that is calculated is the hash * of the concatenation of these messages in order. * -# To calculate the hash, call psa_hash_finish(). * To compare the hash with an expected value, call psa_hash_verify(). * * If an error occurs at any step after a call to psa_hash_setup(), the * operation will need to be reset by a call to psa_hash_abort(). The * application may call psa_hash_abort() at any time after the operation * has been initialized. * * After a successful call to psa_hash_setup(), the application must * eventually terminate the operation. The following events terminate an * operation: * - A successful call to psa_hash_finish() or psa_hash_verify(). * - A call to psa_hash_abort(). * * \param[in,out] operation The operation object to set up. It must have * been initialized as per the documentation for * #psa_hash_operation_t and not yet in use. * \param alg The hash algorithm to compute (\c PSA_ALG_XXX value * such that #PSA_ALG_IS_HASH(\p alg) is true). * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not a supported hash algorithm. * \retval #PSA_ERROR_INVALID_ARGUMENT * \p alg is not a hash algorithm. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be inactive). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_hash_setup(psa_hash_operation_t *operation, psa_algorithm_t alg); /** Add a message fragment to a multipart hash operation. * * The application must call psa_hash_setup() before calling this function. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_hash_abort(). * * \param[in,out] operation Active hash operation. * \param[in] input Buffer containing the message fragment to hash. * \param input_length Size of the \p input buffer in bytes. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it muct be active). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_hash_update(psa_hash_operation_t *operation, const uint8_t *input, size_t input_length); /** Finish the calculation of the hash of a message. * * The application must call psa_hash_setup() before calling this function. * This function calculates the hash of the message formed by concatenating * the inputs passed to preceding calls to psa_hash_update(). * * When this function returns successfuly, the operation becomes inactive. * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_hash_abort(). * * \warning Applications should not call this function if they expect * a specific value for the hash. Call psa_hash_verify() instead. * Beware that comparing integrity or authenticity data such as * hash values with a function such as \c memcmp is risky * because the time taken by the comparison may leak information * about the hashed data which could allow an attacker to guess * a valid hash and thereby bypass security controls. * * \param[in,out] operation Active hash operation. * \param[out] hash Buffer where the hash is to be written. * \param hash_size Size of the \p hash buffer in bytes. * \param[out] hash_length On success, the number of bytes * that make up the hash value. This is always * #PSA_HASH_LENGTH(\c alg) where \c alg is the * hash algorithm that is calculated. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active). * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p hash buffer is too small. You can determine a * sufficient buffer size by calling #PSA_HASH_LENGTH(\c alg) * where \c alg is the hash algorithm that is calculated. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_hash_finish(psa_hash_operation_t *operation, uint8_t *hash, size_t hash_size, size_t *hash_length); /** Finish the calculation of the hash of a message and compare it with * an expected value. * * The application must call psa_hash_setup() before calling this function. * This function calculates the hash of the message formed by concatenating * the inputs passed to preceding calls to psa_hash_update(). It then * compares the calculated hash with the expected hash passed as a * parameter to this function. * * When this function returns successfuly, the operation becomes inactive. * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_hash_abort(). * * \note Implementations shall make the best effort to ensure that the * comparison between the actual hash and the expected hash is performed * in constant time. * * \param[in,out] operation Active hash operation. * \param[in] hash Buffer containing the expected hash value. * \param hash_length Size of the \p hash buffer in bytes. * * \retval #PSA_SUCCESS * The expected hash is identical to the actual hash of the message. * \retval #PSA_ERROR_INVALID_SIGNATURE * The hash of the message was calculated successfully, but it * differs from the expected hash. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_hash_verify(psa_hash_operation_t *operation, const uint8_t *hash, size_t hash_length); /** Abort a hash operation. * * Aborting an operation frees all associated resources except for the * \p operation structure itself. Once aborted, the operation object * can be reused for another operation by calling * psa_hash_setup() again. * * You may call this function any time after the operation object has * been initialized by one of the methods described in #psa_hash_operation_t. * * In particular, calling psa_hash_abort() after the operation has been * terminated by a call to psa_hash_abort(), psa_hash_finish() or * psa_hash_verify() is safe and has no effect. * * \param[in,out] operation Initialized hash operation. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_hash_abort(psa_hash_operation_t *operation); /** Clone a hash operation. * * This function copies the state of an ongoing hash operation to * a new operation object. In other words, this function is equivalent * to calling psa_hash_setup() on \p target_operation with the same * algorithm that \p source_operation was set up for, then * psa_hash_update() on \p target_operation with the same input that * that was passed to \p source_operation. After this function returns, the * two objects are independent, i.e. subsequent calls involving one of * the objects do not affect the other object. * * \param[in] source_operation The active hash operation to clone. * \param[in,out] target_operation The operation object to set up. * It must be initialized but not active. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_BAD_STATE * The \p source_operation state is not valid (it must be active). * \retval #PSA_ERROR_BAD_STATE * The \p target_operation state is not valid (it must be inactive). * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_hash_clone(const psa_hash_operation_t *source_operation, psa_hash_operation_t *target_operation); /**@}*/ /** \defgroup MAC Message authentication codes * @{ */ /** Calculate the MAC (message authentication code) of a message. * * \note To verify the MAC of a message against an * expected value, use psa_mac_verify() instead. * Beware that comparing integrity or authenticity data such as * MAC values with a function such as \c memcmp is risky * because the time taken by the comparison may leak information * about the MAC value which could allow an attacker to guess * a valid MAC and thereby bypass security controls. * * \param key Identifier of the key to use for the operation. It * must allow the usage PSA_KEY_USAGE_SIGN_MESSAGE. * \param alg The MAC algorithm to compute (\c PSA_ALG_XXX value * such that #PSA_ALG_IS_MAC(\p alg) is true). * \param[in] input Buffer containing the input message. * \param input_length Size of the \p input buffer in bytes. * \param[out] mac Buffer where the MAC value is to be written. * \param mac_size Size of the \p mac buffer in bytes. * \param[out] mac_length On success, the number of bytes * that make up the MAC value. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not a MAC algorithm. * \retval #PSA_ERROR_BUFFER_TOO_SMALL * \p mac_size is too small * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * The key could not be retrieved from storage. * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_mac_compute(mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *mac, size_t mac_size, size_t *mac_length); /** Calculate the MAC of a message and compare it with a reference value. * * \param key Identifier of the key to use for the operation. It * must allow the usage PSA_KEY_USAGE_VERIFY_MESSAGE. * \param alg The MAC algorithm to compute (\c PSA_ALG_XXX value * such that #PSA_ALG_IS_MAC(\p alg) is true). * \param[in] input Buffer containing the input message. * \param input_length Size of the \p input buffer in bytes. * \param[out] mac Buffer containing the expected MAC value. * \param mac_length Size of the \p mac buffer in bytes. * * \retval #PSA_SUCCESS * The expected MAC is identical to the actual MAC of the input. * \retval #PSA_ERROR_INVALID_SIGNATURE * The MAC of the message was calculated successfully, but it * differs from the expected value. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not a MAC algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * The key could not be retrieved from storage. * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_mac_verify(mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t *input, size_t input_length, const uint8_t *mac, size_t mac_length); /** The type of the state data structure for multipart MAC operations. * * Before calling any function on a MAC operation object, the application must * initialize it by any of the following means: * - Set the structure to all-bits-zero, for example: * \code * psa_mac_operation_t operation; * memset(&operation, 0, sizeof(operation)); * \endcode * - Initialize the structure to logical zero values, for example: * \code * psa_mac_operation_t operation = {0}; * \endcode * - Initialize the structure to the initializer #PSA_MAC_OPERATION_INIT, * for example: * \code * psa_mac_operation_t operation = PSA_MAC_OPERATION_INIT; * \endcode * - Assign the result of the function psa_mac_operation_init() * to the structure, for example: * \code * psa_mac_operation_t operation; * operation = psa_mac_operation_init(); * \endcode * * This is an implementation-defined \c struct. Applications should not * make any assumptions about the content of this structure except * as directed by the documentation of a specific implementation. */ typedef struct psa_mac_operation_s psa_mac_operation_t; /** \def PSA_MAC_OPERATION_INIT * * This macro returns a suitable initializer for a MAC operation object of type * #psa_mac_operation_t. */ #ifdef __DOXYGEN_ONLY__ /* This is an example definition for documentation purposes. * Implementations should define a suitable value in `crypto_struct.h`. */ #define PSA_MAC_OPERATION_INIT {0} #endif /** Return an initial value for a MAC operation object. */ static psa_mac_operation_t psa_mac_operation_init(void); /** Set up a multipart MAC calculation operation. * * This function sets up the calculation of the MAC * (message authentication code) of a byte string. * To verify the MAC of a message against an * expected value, use psa_mac_verify_setup() instead. * * The sequence of operations to calculate a MAC is as follows: * -# Allocate an operation object which will be passed to all the functions * listed here. * -# Initialize the operation object with one of the methods described in the * documentation for #psa_mac_operation_t, e.g. #PSA_MAC_OPERATION_INIT. * -# Call psa_mac_sign_setup() to specify the algorithm and key. * -# Call psa_mac_update() zero, one or more times, passing a fragment * of the message each time. The MAC that is calculated is the MAC * of the concatenation of these messages in order. * -# At the end of the message, call psa_mac_sign_finish() to finish * calculating the MAC value and retrieve it. * * If an error occurs at any step after a call to psa_mac_sign_setup(), the * operation will need to be reset by a call to psa_mac_abort(). The * application may call psa_mac_abort() at any time after the operation * has been initialized. * * After a successful call to psa_mac_sign_setup(), the application must * eventually terminate the operation through one of the following methods: * - A successful call to psa_mac_sign_finish(). * - A call to psa_mac_abort(). * * \param[in,out] operation The operation object to set up. It must have * been initialized as per the documentation for * #psa_mac_operation_t and not yet in use. * \param key Identifier of the key to use for the operation. It * must remain valid until the operation terminates. * It must allow the usage PSA_KEY_USAGE_SIGN_MESSAGE. * \param alg The MAC algorithm to compute (\c PSA_ALG_XXX value * such that #PSA_ALG_IS_MAC(\p alg) is true). * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not a MAC algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * The key could not be retrieved from storage. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be inactive). * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_mac_sign_setup(psa_mac_operation_t *operation, mbedtls_svc_key_id_t key, psa_algorithm_t alg); /** Set up a multipart MAC verification operation. * * This function sets up the verification of the MAC * (message authentication code) of a byte string against an expected value. * * The sequence of operations to verify a MAC is as follows: * -# Allocate an operation object which will be passed to all the functions * listed here. * -# Initialize the operation object with one of the methods described in the * documentation for #psa_mac_operation_t, e.g. #PSA_MAC_OPERATION_INIT. * -# Call psa_mac_verify_setup() to specify the algorithm and key. * -# Call psa_mac_update() zero, one or more times, passing a fragment * of the message each time. The MAC that is calculated is the MAC * of the concatenation of these messages in order. * -# At the end of the message, call psa_mac_verify_finish() to finish * calculating the actual MAC of the message and verify it against * the expected value. * * If an error occurs at any step after a call to psa_mac_verify_setup(), the * operation will need to be reset by a call to psa_mac_abort(). The * application may call psa_mac_abort() at any time after the operation * has been initialized. * * After a successful call to psa_mac_verify_setup(), the application must * eventually terminate the operation through one of the following methods: * - A successful call to psa_mac_verify_finish(). * - A call to psa_mac_abort(). * * \param[in,out] operation The operation object to set up. It must have * been initialized as per the documentation for * #psa_mac_operation_t and not yet in use. * \param key Identifier of the key to use for the operation. It * must remain valid until the operation terminates. * It must allow the usage * PSA_KEY_USAGE_VERIFY_MESSAGE. * \param alg The MAC algorithm to compute (\c PSA_ALG_XXX value * such that #PSA_ALG_IS_MAC(\p alg) is true). * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \c key is not compatible with \c alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \c alg is not supported or is not a MAC algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * The key could not be retrieved from storage * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be inactive). * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_mac_verify_setup(psa_mac_operation_t *operation, mbedtls_svc_key_id_t key, psa_algorithm_t alg); /** Add a message fragment to a multipart MAC operation. * * The application must call psa_mac_sign_setup() or psa_mac_verify_setup() * before calling this function. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_mac_abort(). * * \param[in,out] operation Active MAC operation. * \param[in] input Buffer containing the message fragment to add to * the MAC calculation. * \param input_length Size of the \p input buffer in bytes. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_mac_update(psa_mac_operation_t *operation, const uint8_t *input, size_t input_length); /** Finish the calculation of the MAC of a message. * * The application must call psa_mac_sign_setup() before calling this function. * This function calculates the MAC of the message formed by concatenating * the inputs passed to preceding calls to psa_mac_update(). * * When this function returns successfuly, the operation becomes inactive. * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_mac_abort(). * * \warning Applications should not call this function if they expect * a specific value for the MAC. Call psa_mac_verify_finish() instead. * Beware that comparing integrity or authenticity data such as * MAC values with a function such as \c memcmp is risky * because the time taken by the comparison may leak information * about the MAC value which could allow an attacker to guess * a valid MAC and thereby bypass security controls. * * \param[in,out] operation Active MAC operation. * \param[out] mac Buffer where the MAC value is to be written. * \param mac_size Size of the \p mac buffer in bytes. * \param[out] mac_length On success, the number of bytes * that make up the MAC value. This is always * #PSA_MAC_LENGTH(\c key_type, \c key_bits, \c alg) * where \c key_type and \c key_bits are the type and * bit-size respectively of the key and \c alg is the * MAC algorithm that is calculated. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be an active mac sign * operation). * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p mac buffer is too small. You can determine a * sufficient buffer size by calling PSA_MAC_LENGTH(). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_mac_sign_finish(psa_mac_operation_t *operation, uint8_t *mac, size_t mac_size, size_t *mac_length); /** Finish the calculation of the MAC of a message and compare it with * an expected value. * * The application must call psa_mac_verify_setup() before calling this function. * This function calculates the MAC of the message formed by concatenating * the inputs passed to preceding calls to psa_mac_update(). It then * compares the calculated MAC with the expected MAC passed as a * parameter to this function. * * When this function returns successfuly, the operation becomes inactive. * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_mac_abort(). * * \note Implementations shall make the best effort to ensure that the * comparison between the actual MAC and the expected MAC is performed * in constant time. * * \param[in,out] operation Active MAC operation. * \param[in] mac Buffer containing the expected MAC value. * \param mac_length Size of the \p mac buffer in bytes. * * \retval #PSA_SUCCESS * The expected MAC is identical to the actual MAC of the message. * \retval #PSA_ERROR_INVALID_SIGNATURE * The MAC of the message was calculated successfully, but it * differs from the expected MAC. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be an active mac verify * operation). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_mac_verify_finish(psa_mac_operation_t *operation, const uint8_t *mac, size_t mac_length); /** Abort a MAC operation. * * Aborting an operation frees all associated resources except for the * \p operation structure itself. Once aborted, the operation object * can be reused for another operation by calling * psa_mac_sign_setup() or psa_mac_verify_setup() again. * * You may call this function any time after the operation object has * been initialized by one of the methods described in #psa_mac_operation_t. * * In particular, calling psa_mac_abort() after the operation has been * terminated by a call to psa_mac_abort(), psa_mac_sign_finish() or * psa_mac_verify_finish() is safe and has no effect. * * \param[in,out] operation Initialized MAC operation. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_mac_abort(psa_mac_operation_t *operation); /**@}*/ /** \defgroup cipher Symmetric ciphers * @{ */ /** Encrypt a message using a symmetric cipher. * * This function encrypts a message with a random IV (initialization * vector). Use the multipart operation interface with a * #psa_cipher_operation_t object to provide other forms of IV. * * \param key Identifier of the key to use for the operation. * It must allow the usage #PSA_KEY_USAGE_ENCRYPT. * \param alg The cipher algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_CIPHER(\p alg) is true). * \param[in] input Buffer containing the message to encrypt. * \param input_length Size of the \p input buffer in bytes. * \param[out] output Buffer where the output is to be written. * The output contains the IV followed by * the ciphertext proper. * \param output_size Size of the \p output buffer in bytes. * \param[out] output_length On success, the number of bytes * that make up the output. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not a cipher algorithm. * \retval #PSA_ERROR_BUFFER_TOO_SMALL * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_cipher_encrypt(mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *output, size_t output_size, size_t *output_length); /** Decrypt a message using a symmetric cipher. * * This function decrypts a message encrypted with a symmetric cipher. * * \param key Identifier of the key to use for the operation. * It must remain valid until the operation * terminates. It must allow the usage * #PSA_KEY_USAGE_DECRYPT. * \param alg The cipher algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_CIPHER(\p alg) is true). * \param[in] input Buffer containing the message to decrypt. * This consists of the IV followed by the * ciphertext proper. * \param input_length Size of the \p input buffer in bytes. * \param[out] output Buffer where the plaintext is to be written. * \param output_size Size of the \p output buffer in bytes. * \param[out] output_length On success, the number of bytes * that make up the output. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not a cipher algorithm. * \retval #PSA_ERROR_BUFFER_TOO_SMALL * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_cipher_decrypt(mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t *input, size_t input_length, uint8_t *output, size_t output_size, size_t *output_length); /** The type of the state data structure for multipart cipher operations. * * Before calling any function on a cipher operation object, the application * must initialize it by any of the following means: * - Set the structure to all-bits-zero, for example: * \code * psa_cipher_operation_t operation; * memset(&operation, 0, sizeof(operation)); * \endcode * - Initialize the structure to logical zero values, for example: * \code * psa_cipher_operation_t operation = {0}; * \endcode * - Initialize the structure to the initializer #PSA_CIPHER_OPERATION_INIT, * for example: * \code * psa_cipher_operation_t operation = PSA_CIPHER_OPERATION_INIT; * \endcode * - Assign the result of the function psa_cipher_operation_init() * to the structure, for example: * \code * psa_cipher_operation_t operation; * operation = psa_cipher_operation_init(); * \endcode * * This is an implementation-defined \c struct. Applications should not * make any assumptions about the content of this structure except * as directed by the documentation of a specific implementation. */ typedef struct psa_cipher_operation_s psa_cipher_operation_t; /** \def PSA_CIPHER_OPERATION_INIT * * This macro returns a suitable initializer for a cipher operation object of * type #psa_cipher_operation_t. */ #ifdef __DOXYGEN_ONLY__ /* This is an example definition for documentation purposes. * Implementations should define a suitable value in `crypto_struct.h`. */ #define PSA_CIPHER_OPERATION_INIT {0} #endif /** Return an initial value for a cipher operation object. */ static psa_cipher_operation_t psa_cipher_operation_init(void); /** Set the key for a multipart symmetric encryption operation. * * The sequence of operations to encrypt a message with a symmetric cipher * is as follows: * -# Allocate an operation object which will be passed to all the functions * listed here. * -# Initialize the operation object with one of the methods described in the * documentation for #psa_cipher_operation_t, e.g. * #PSA_CIPHER_OPERATION_INIT. * -# Call psa_cipher_encrypt_setup() to specify the algorithm and key. * -# Call either psa_cipher_generate_iv() or psa_cipher_set_iv() to * generate or set the IV (initialization vector). You should use * psa_cipher_generate_iv() unless the protocol you are implementing * requires a specific IV value. * -# Call psa_cipher_update() zero, one or more times, passing a fragment * of the message each time. * -# Call psa_cipher_finish(). * * If an error occurs at any step after a call to psa_cipher_encrypt_setup(), * the operation will need to be reset by a call to psa_cipher_abort(). The * application may call psa_cipher_abort() at any time after the operation * has been initialized. * * After a successful call to psa_cipher_encrypt_setup(), the application must * eventually terminate the operation. The following events terminate an * operation: * - A successful call to psa_cipher_finish(). * - A call to psa_cipher_abort(). * * \param[in,out] operation The operation object to set up. It must have * been initialized as per the documentation for * #psa_cipher_operation_t and not yet in use. * \param key Identifier of the key to use for the operation. * It must remain valid until the operation * terminates. It must allow the usage * #PSA_KEY_USAGE_ENCRYPT. * \param alg The cipher algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_CIPHER(\p alg) is true). * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not a cipher algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be inactive). * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_cipher_encrypt_setup(psa_cipher_operation_t *operation, mbedtls_svc_key_id_t key, psa_algorithm_t alg); /** Set the key for a multipart symmetric decryption operation. * * The sequence of operations to decrypt a message with a symmetric cipher * is as follows: * -# Allocate an operation object which will be passed to all the functions * listed here. * -# Initialize the operation object with one of the methods described in the * documentation for #psa_cipher_operation_t, e.g. * #PSA_CIPHER_OPERATION_INIT. * -# Call psa_cipher_decrypt_setup() to specify the algorithm and key. * -# Call psa_cipher_set_iv() with the IV (initialization vector) for the * decryption. If the IV is prepended to the ciphertext, you can call * psa_cipher_update() on a buffer containing the IV followed by the * beginning of the message. * -# Call psa_cipher_update() zero, one or more times, passing a fragment * of the message each time. * -# Call psa_cipher_finish(). * * If an error occurs at any step after a call to psa_cipher_decrypt_setup(), * the operation will need to be reset by a call to psa_cipher_abort(). The * application may call psa_cipher_abort() at any time after the operation * has been initialized. * * After a successful call to psa_cipher_decrypt_setup(), the application must * eventually terminate the operation. The following events terminate an * operation: * - A successful call to psa_cipher_finish(). * - A call to psa_cipher_abort(). * * \param[in,out] operation The operation object to set up. It must have * been initialized as per the documentation for * #psa_cipher_operation_t and not yet in use. * \param key Identifier of the key to use for the operation. * It must remain valid until the operation * terminates. It must allow the usage * #PSA_KEY_USAGE_DECRYPT. * \param alg The cipher algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_CIPHER(\p alg) is true). * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not a cipher algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be inactive). * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_cipher_decrypt_setup(psa_cipher_operation_t *operation, mbedtls_svc_key_id_t key, psa_algorithm_t alg); /** Generate an IV for a symmetric encryption operation. * * This function generates a random IV (initialization vector), nonce * or initial counter value for the encryption operation as appropriate * for the chosen algorithm, key type and key size. * * The application must call psa_cipher_encrypt_setup() before * calling this function. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_cipher_abort(). * * \param[in,out] operation Active cipher operation. * \param[out] iv Buffer where the generated IV is to be written. * \param iv_size Size of the \p iv buffer in bytes. * \param[out] iv_length On success, the number of bytes of the * generated IV. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active, with no IV set). * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p iv buffer is too small. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_cipher_generate_iv(psa_cipher_operation_t *operation, uint8_t *iv, size_t iv_size, size_t *iv_length); /** Set the IV for a symmetric encryption or decryption operation. * * This function sets the IV (initialization vector), nonce * or initial counter value for the encryption or decryption operation. * * The application must call psa_cipher_encrypt_setup() before * calling this function. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_cipher_abort(). * * \note When encrypting, applications should use psa_cipher_generate_iv() * instead of this function, unless implementing a protocol that requires * a non-random IV. * * \param[in,out] operation Active cipher operation. * \param[in] iv Buffer containing the IV to use. * \param iv_length Size of the IV in bytes. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be an active cipher * encrypt operation, with no IV set). * \retval #PSA_ERROR_INVALID_ARGUMENT * The size of \p iv is not acceptable for the chosen algorithm, * or the chosen algorithm does not use an IV. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_cipher_set_iv(psa_cipher_operation_t *operation, const uint8_t *iv, size_t iv_length); /** Encrypt or decrypt a message fragment in an active cipher operation. * * Before calling this function, you must: * 1. Call either psa_cipher_encrypt_setup() or psa_cipher_decrypt_setup(). * The choice of setup function determines whether this function * encrypts or decrypts its input. * 2. If the algorithm requires an IV, call psa_cipher_generate_iv() * (recommended when encrypting) or psa_cipher_set_iv(). * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_cipher_abort(). * * \param[in,out] operation Active cipher operation. * \param[in] input Buffer containing the message fragment to * encrypt or decrypt. * \param input_length Size of the \p input buffer in bytes. * \param[out] output Buffer where the output is to be written. * \param output_size Size of the \p output buffer in bytes. * \param[out] output_length On success, the number of bytes * that make up the returned output. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active, with an IV set * if required for the algorithm). * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p output buffer is too small. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_cipher_update(psa_cipher_operation_t *operation, const uint8_t *input, size_t input_length, uint8_t *output, size_t output_size, size_t *output_length); /** Finish encrypting or decrypting a message in a cipher operation. * * The application must call psa_cipher_encrypt_setup() or * psa_cipher_decrypt_setup() before calling this function. The choice * of setup function determines whether this function encrypts or * decrypts its input. * * This function finishes the encryption or decryption of the message * formed by concatenating the inputs passed to preceding calls to * psa_cipher_update(). * * When this function returns successfuly, the operation becomes inactive. * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_cipher_abort(). * * \param[in,out] operation Active cipher operation. * \param[out] output Buffer where the output is to be written. * \param output_size Size of the \p output buffer in bytes. * \param[out] output_length On success, the number of bytes * that make up the returned output. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_ARGUMENT * The total input size passed to this operation is not valid for * this particular algorithm. For example, the algorithm is a based * on block cipher and requires a whole number of blocks, but the * total input size is not a multiple of the block size. * \retval #PSA_ERROR_INVALID_PADDING * This is a decryption operation for an algorithm that includes * padding, and the ciphertext does not contain valid padding. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active, with an IV set * if required for the algorithm). * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p output buffer is too small. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_cipher_finish(psa_cipher_operation_t *operation, uint8_t *output, size_t output_size, size_t *output_length); /** Abort a cipher operation. * * Aborting an operation frees all associated resources except for the * \p operation structure itself. Once aborted, the operation object * can be reused for another operation by calling * psa_cipher_encrypt_setup() or psa_cipher_decrypt_setup() again. * * You may call this function any time after the operation object has * been initialized as described in #psa_cipher_operation_t. * * In particular, calling psa_cipher_abort() after the operation has been * terminated by a call to psa_cipher_abort() or psa_cipher_finish() * is safe and has no effect. * * \param[in,out] operation Initialized cipher operation. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_cipher_abort(psa_cipher_operation_t *operation); /**@}*/ /** \defgroup aead Authenticated encryption with associated data (AEAD) * @{ */ /** Process an authenticated encryption operation. * * \param key Identifier of the key to use for the * operation. It must allow the usage * #PSA_KEY_USAGE_ENCRYPT. * \param alg The AEAD algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * \param[in] nonce Nonce or IV to use. * \param nonce_length Size of the \p nonce buffer in bytes. * \param[in] additional_data Additional data that will be authenticated * but not encrypted. * \param additional_data_length Size of \p additional_data in bytes. * \param[in] plaintext Data that will be authenticated and * encrypted. * \param plaintext_length Size of \p plaintext in bytes. * \param[out] ciphertext Output buffer for the authenticated and * encrypted data. The additional data is not * part of this output. For algorithms where the * encrypted data and the authentication tag * are defined as separate outputs, the * authentication tag is appended to the * encrypted data. * \param ciphertext_size Size of the \p ciphertext buffer in bytes. * This must be appropriate for the selected * algorithm and key: * - A sufficient output size is * #PSA_AEAD_ENCRYPT_OUTPUT_SIZE(\c key_type, * \p alg, \p plaintext_length) where * \c key_type is the type of \p key. * - #PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(\p * plaintext_length) evaluates to the maximum * ciphertext size of any supported AEAD * encryption. * \param[out] ciphertext_length On success, the size of the output * in the \p ciphertext buffer. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not an AEAD algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_BUFFER_TOO_SMALL * \p ciphertext_size is too small. * #PSA_AEAD_ENCRYPT_OUTPUT_SIZE(\c key_type, \p alg, * \p plaintext_length) or * #PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(\p plaintext_length) can be used to * determine the required buffer size. * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_encrypt(mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t *nonce, size_t nonce_length, const uint8_t *additional_data, size_t additional_data_length, const uint8_t *plaintext, size_t plaintext_length, uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length); /** Process an authenticated decryption operation. * * \param key Identifier of the key to use for the * operation. It must allow the usage * #PSA_KEY_USAGE_DECRYPT. * \param alg The AEAD algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * \param[in] nonce Nonce or IV to use. * \param nonce_length Size of the \p nonce buffer in bytes. * \param[in] additional_data Additional data that has been authenticated * but not encrypted. * \param additional_data_length Size of \p additional_data in bytes. * \param[in] ciphertext Data that has been authenticated and * encrypted. For algorithms where the * encrypted data and the authentication tag * are defined as separate inputs, the buffer * must contain the encrypted data followed * by the authentication tag. * \param ciphertext_length Size of \p ciphertext in bytes. * \param[out] plaintext Output buffer for the decrypted data. * \param plaintext_size Size of the \p plaintext buffer in bytes. * This must be appropriate for the selected * algorithm and key: * - A sufficient output size is * #PSA_AEAD_DECRYPT_OUTPUT_SIZE(\c key_type, * \p alg, \p ciphertext_length) where * \c key_type is the type of \p key. * - #PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(\p * ciphertext_length) evaluates to the maximum * plaintext size of any supported AEAD * decryption. * \param[out] plaintext_length On success, the size of the output * in the \p plaintext buffer. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_INVALID_SIGNATURE * The ciphertext is not authentic. * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not an AEAD algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_BUFFER_TOO_SMALL * \p plaintext_size is too small. * #PSA_AEAD_DECRYPT_OUTPUT_SIZE(\c key_type, \p alg, * \p ciphertext_length) or * #PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(\p ciphertext_length) can be used * to determine the required buffer size. * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_decrypt(mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t *nonce, size_t nonce_length, const uint8_t *additional_data, size_t additional_data_length, const uint8_t *ciphertext, size_t ciphertext_length, uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length); /** The type of the state data structure for multipart AEAD operations. * * Before calling any function on an AEAD operation object, the application * must initialize it by any of the following means: * - Set the structure to all-bits-zero, for example: * \code * psa_aead_operation_t operation; * memset(&operation, 0, sizeof(operation)); * \endcode * - Initialize the structure to logical zero values, for example: * \code * psa_aead_operation_t operation = {0}; * \endcode * - Initialize the structure to the initializer #PSA_AEAD_OPERATION_INIT, * for example: * \code * psa_aead_operation_t operation = PSA_AEAD_OPERATION_INIT; * \endcode * - Assign the result of the function psa_aead_operation_init() * to the structure, for example: * \code * psa_aead_operation_t operation; * operation = psa_aead_operation_init(); * \endcode * * This is an implementation-defined \c struct. Applications should not * make any assumptions about the content of this structure except * as directed by the documentation of a specific implementation. */ typedef struct psa_aead_operation_s psa_aead_operation_t; /** \def PSA_AEAD_OPERATION_INIT * * This macro returns a suitable initializer for an AEAD operation object of * type #psa_aead_operation_t. */ #ifdef __DOXYGEN_ONLY__ /* This is an example definition for documentation purposes. * Implementations should define a suitable value in `crypto_struct.h`. */ #define PSA_AEAD_OPERATION_INIT {0} #endif /** Return an initial value for an AEAD operation object. */ static psa_aead_operation_t psa_aead_operation_init(void); /** Set the key for a multipart authenticated encryption operation. * * The sequence of operations to encrypt a message with authentication * is as follows: * -# Allocate an operation object which will be passed to all the functions * listed here. * -# Initialize the operation object with one of the methods described in the * documentation for #psa_aead_operation_t, e.g. * #PSA_AEAD_OPERATION_INIT. * -# Call psa_aead_encrypt_setup() to specify the algorithm and key. * -# If needed, call psa_aead_set_lengths() to specify the length of the * inputs to the subsequent calls to psa_aead_update_ad() and * psa_aead_update(). See the documentation of psa_aead_set_lengths() * for details. * -# Call either psa_aead_generate_nonce() or psa_aead_set_nonce() to * generate or set the nonce. You should use * psa_aead_generate_nonce() unless the protocol you are implementing * requires a specific nonce value. * -# Call psa_aead_update_ad() zero, one or more times, passing a fragment * of the non-encrypted additional authenticated data each time. * -# Call psa_aead_update() zero, one or more times, passing a fragment * of the message to encrypt each time. * -# Call psa_aead_finish(). * * If an error occurs at any step after a call to psa_aead_encrypt_setup(), * the operation will need to be reset by a call to psa_aead_abort(). The * application may call psa_aead_abort() at any time after the operation * has been initialized. * * After a successful call to psa_aead_encrypt_setup(), the application must * eventually terminate the operation. The following events terminate an * operation: * - A successful call to psa_aead_finish(). * - A call to psa_aead_abort(). * * \param[in,out] operation The operation object to set up. It must have * been initialized as per the documentation for * #psa_aead_operation_t and not yet in use. * \param key Identifier of the key to use for the operation. * It must remain valid until the operation * terminates. It must allow the usage * #PSA_KEY_USAGE_ENCRYPT. * \param alg The AEAD algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be inactive). * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not an AEAD algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_encrypt_setup(psa_aead_operation_t *operation, mbedtls_svc_key_id_t key, psa_algorithm_t alg); /** Set the key for a multipart authenticated decryption operation. * * The sequence of operations to decrypt a message with authentication * is as follows: * -# Allocate an operation object which will be passed to all the functions * listed here. * -# Initialize the operation object with one of the methods described in the * documentation for #psa_aead_operation_t, e.g. * #PSA_AEAD_OPERATION_INIT. * -# Call psa_aead_decrypt_setup() to specify the algorithm and key. * -# If needed, call psa_aead_set_lengths() to specify the length of the * inputs to the subsequent calls to psa_aead_update_ad() and * psa_aead_update(). See the documentation of psa_aead_set_lengths() * for details. * -# Call psa_aead_set_nonce() with the nonce for the decryption. * -# Call psa_aead_update_ad() zero, one or more times, passing a fragment * of the non-encrypted additional authenticated data each time. * -# Call psa_aead_update() zero, one or more times, passing a fragment * of the ciphertext to decrypt each time. * -# Call psa_aead_verify(). * * If an error occurs at any step after a call to psa_aead_decrypt_setup(), * the operation will need to be reset by a call to psa_aead_abort(). The * application may call psa_aead_abort() at any time after the operation * has been initialized. * * After a successful call to psa_aead_decrypt_setup(), the application must * eventually terminate the operation. The following events terminate an * operation: * - A successful call to psa_aead_verify(). * - A call to psa_aead_abort(). * * \param[in,out] operation The operation object to set up. It must have * been initialized as per the documentation for * #psa_aead_operation_t and not yet in use. * \param key Identifier of the key to use for the operation. * It must remain valid until the operation * terminates. It must allow the usage * #PSA_KEY_USAGE_DECRYPT. * \param alg The AEAD algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be inactive). * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p key is not compatible with \p alg. * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not supported or is not an AEAD algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_decrypt_setup(psa_aead_operation_t *operation, mbedtls_svc_key_id_t key, psa_algorithm_t alg); /** Generate a random nonce for an authenticated encryption operation. * * This function generates a random nonce for the authenticated encryption * operation with an appropriate size for the chosen algorithm, key type * and key size. * * The application must call psa_aead_encrypt_setup() before * calling this function. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_aead_abort(). * * \param[in,out] operation Active AEAD operation. * \param[out] nonce Buffer where the generated nonce is to be * written. * \param nonce_size Size of the \p nonce buffer in bytes. * \param[out] nonce_length On success, the number of bytes of the * generated nonce. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be an active aead encrypt * operation, with no nonce set). * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p nonce buffer is too small. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_generate_nonce(psa_aead_operation_t *operation, uint8_t *nonce, size_t nonce_size, size_t *nonce_length); /** Set the nonce for an authenticated encryption or decryption operation. * * This function sets the nonce for the authenticated * encryption or decryption operation. * * The application must call psa_aead_encrypt_setup() or * psa_aead_decrypt_setup() before calling this function. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_aead_abort(). * * \note When encrypting, applications should use psa_aead_generate_nonce() * instead of this function, unless implementing a protocol that requires * a non-random IV. * * \param[in,out] operation Active AEAD operation. * \param[in] nonce Buffer containing the nonce to use. * \param nonce_length Size of the nonce in bytes. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active, with no nonce * set). * \retval #PSA_ERROR_INVALID_ARGUMENT * The size of \p nonce is not acceptable for the chosen algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_set_nonce(psa_aead_operation_t *operation, const uint8_t *nonce, size_t nonce_length); /** Declare the lengths of the message and additional data for AEAD. * * The application must call this function before calling * psa_aead_update_ad() or psa_aead_update() if the algorithm for * the operation requires it. If the algorithm does not require it, * calling this function is optional, but if this function is called * then the implementation must enforce the lengths. * * You may call this function before or after setting the nonce with * psa_aead_set_nonce() or psa_aead_generate_nonce(). * * - For #PSA_ALG_CCM, calling this function is required. * - For the other AEAD algorithms defined in this specification, calling * this function is not required. * - For vendor-defined algorithm, refer to the vendor documentation. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_aead_abort(). * * \param[in,out] operation Active AEAD operation. * \param ad_length Size of the non-encrypted additional * authenticated data in bytes. * \param plaintext_length Size of the plaintext to encrypt in bytes. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active, and * psa_aead_update_ad() and psa_aead_update() must not have been * called yet). * \retval #PSA_ERROR_INVALID_ARGUMENT * At least one of the lengths is not acceptable for the chosen * algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_set_lengths(psa_aead_operation_t *operation, size_t ad_length, size_t plaintext_length); /** Pass additional data to an active AEAD operation. * * Additional data is authenticated, but not encrypted. * * You may call this function multiple times to pass successive fragments * of the additional data. You may not call this function after passing * data to encrypt or decrypt with psa_aead_update(). * * Before calling this function, you must: * 1. Call either psa_aead_encrypt_setup() or psa_aead_decrypt_setup(). * 2. Set the nonce with psa_aead_generate_nonce() or psa_aead_set_nonce(). * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_aead_abort(). * * \warning When decrypting, until psa_aead_verify() has returned #PSA_SUCCESS, * there is no guarantee that the input is valid. Therefore, until * you have called psa_aead_verify() and it has returned #PSA_SUCCESS, * treat the input as untrusted and prepare to undo any action that * depends on the input if psa_aead_verify() returns an error status. * * \param[in,out] operation Active AEAD operation. * \param[in] input Buffer containing the fragment of * additional data. * \param input_length Size of the \p input buffer in bytes. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active, have a nonce * set, have lengths set if required by the algorithm, and * psa_aead_update() must not have been called yet). * \retval #PSA_ERROR_INVALID_ARGUMENT * The total input length overflows the additional data length that * was previously specified with psa_aead_set_lengths(). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_update_ad(psa_aead_operation_t *operation, const uint8_t *input, size_t input_length); /** Encrypt or decrypt a message fragment in an active AEAD operation. * * Before calling this function, you must: * 1. Call either psa_aead_encrypt_setup() or psa_aead_decrypt_setup(). * The choice of setup function determines whether this function * encrypts or decrypts its input. * 2. Set the nonce with psa_aead_generate_nonce() or psa_aead_set_nonce(). * 3. Call psa_aead_update_ad() to pass all the additional data. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_aead_abort(). * * \warning When decrypting, until psa_aead_verify() has returned #PSA_SUCCESS, * there is no guarantee that the input is valid. Therefore, until * you have called psa_aead_verify() and it has returned #PSA_SUCCESS: * - Do not use the output in any way other than storing it in a * confidential location. If you take any action that depends * on the tentative decrypted data, this action will need to be * undone if the input turns out not to be valid. Furthermore, * if an adversary can observe that this action took place * (for example through timing), they may be able to use this * fact as an oracle to decrypt any message encrypted with the * same key. * - In particular, do not copy the output anywhere but to a * memory or storage space that you have exclusive access to. * * This function does not require the input to be aligned to any * particular block boundary. If the implementation can only process * a whole block at a time, it must consume all the input provided, but * it may delay the end of the corresponding output until a subsequent * call to psa_aead_update(), psa_aead_finish() or psa_aead_verify() * provides sufficient input. The amount of data that can be delayed * in this way is bounded by #PSA_AEAD_UPDATE_OUTPUT_SIZE. * * \param[in,out] operation Active AEAD operation. * \param[in] input Buffer containing the message fragment to * encrypt or decrypt. * \param input_length Size of the \p input buffer in bytes. * \param[out] output Buffer where the output is to be written. * \param output_size Size of the \p output buffer in bytes. * This must be appropriate for the selected * algorithm and key: * - A sufficient output size is * #PSA_AEAD_UPDATE_OUTPUT_SIZE(\c key_type, * \c alg, \p input_length) where * \c key_type is the type of key and \c alg is * the algorithm that were used to set up the * operation. * - #PSA_AEAD_UPDATE_OUTPUT_MAX_SIZE(\p * input_length) evaluates to the maximum * output size of any supported AEAD * algorithm. * \param[out] output_length On success, the number of bytes * that make up the returned output. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active, have a nonce * set, and have lengths set if required by the algorithm). * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p output buffer is too small. * #PSA_AEAD_UPDATE_OUTPUT_SIZE(\c key_type, \c alg, \p input_length) or * #PSA_AEAD_UPDATE_OUTPUT_MAX_SIZE(\p input_length) can be used to * determine the required buffer size. * \retval #PSA_ERROR_INVALID_ARGUMENT * The total length of input to psa_aead_update_ad() so far is * less than the additional data length that was previously * specified with psa_aead_set_lengths(). * \retval #PSA_ERROR_INVALID_ARGUMENT * The total input length overflows the plaintext length that * was previously specified with psa_aead_set_lengths(). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_update(psa_aead_operation_t *operation, const uint8_t *input, size_t input_length, uint8_t *output, size_t output_size, size_t *output_length); /** Finish encrypting a message in an AEAD operation. * * The operation must have been set up with psa_aead_encrypt_setup(). * * This function finishes the authentication of the additional data * formed by concatenating the inputs passed to preceding calls to * psa_aead_update_ad() with the plaintext formed by concatenating the * inputs passed to preceding calls to psa_aead_update(). * * This function has two output buffers: * - \p ciphertext contains trailing ciphertext that was buffered from * preceding calls to psa_aead_update(). * - \p tag contains the authentication tag. * * When this function returns successfuly, the operation becomes inactive. * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_aead_abort(). * * \param[in,out] operation Active AEAD operation. * \param[out] ciphertext Buffer where the last part of the ciphertext * is to be written. * \param ciphertext_size Size of the \p ciphertext buffer in bytes. * This must be appropriate for the selected * algorithm and key: * - A sufficient output size is * #PSA_AEAD_FINISH_OUTPUT_SIZE(\c key_type, * \c alg) where \c key_type is the type of key * and \c alg is the algorithm that were used to * set up the operation. * - #PSA_AEAD_FINISH_OUTPUT_MAX_SIZE evaluates to * the maximum output size of any supported AEAD * algorithm. * \param[out] ciphertext_length On success, the number of bytes of * returned ciphertext. * \param[out] tag Buffer where the authentication tag is * to be written. * \param tag_size Size of the \p tag buffer in bytes. * This must be appropriate for the selected * algorithm and key: * - The exact tag size is #PSA_AEAD_TAG_LENGTH(\c * key_type, \c key_bits, \c alg) where * \c key_type and \c key_bits are the type and * bit-size of the key, and \c alg is the * algorithm that were used in the call to * psa_aead_encrypt_setup(). * - #PSA_AEAD_TAG_MAX_SIZE evaluates to the * maximum tag size of any supported AEAD * algorithm. * \param[out] tag_length On success, the number of bytes * that make up the returned tag. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be an active encryption * operation with a nonce set). * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p ciphertext or \p tag buffer is too small. * #PSA_AEAD_FINISH_OUTPUT_SIZE(\c key_type, \c alg) or * #PSA_AEAD_FINISH_OUTPUT_MAX_SIZE can be used to determine the * required \p ciphertext buffer size. #PSA_AEAD_TAG_LENGTH(\c key_type, * \c key_bits, \c alg) or #PSA_AEAD_TAG_MAX_SIZE can be used to * determine the required \p tag buffer size. * \retval #PSA_ERROR_INVALID_ARGUMENT * The total length of input to psa_aead_update_ad() so far is * less than the additional data length that was previously * specified with psa_aead_set_lengths(). * \retval #PSA_ERROR_INVALID_ARGUMENT * The total length of input to psa_aead_update() so far is * less than the plaintext length that was previously * specified with psa_aead_set_lengths(). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_finish(psa_aead_operation_t *operation, uint8_t *ciphertext, size_t ciphertext_size, size_t *ciphertext_length, uint8_t *tag, size_t tag_size, size_t *tag_length); /** Finish authenticating and decrypting a message in an AEAD operation. * * The operation must have been set up with psa_aead_decrypt_setup(). * * This function finishes the authenticated decryption of the message * components: * * - The additional data consisting of the concatenation of the inputs * passed to preceding calls to psa_aead_update_ad(). * - The ciphertext consisting of the concatenation of the inputs passed to * preceding calls to psa_aead_update(). * - The tag passed to this function call. * * If the authentication tag is correct, this function outputs any remaining * plaintext and reports success. If the authentication tag is not correct, * this function returns #PSA_ERROR_INVALID_SIGNATURE. * * When this function returns successfuly, the operation becomes inactive. * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_aead_abort(). * * \note Implementations shall make the best effort to ensure that the * comparison between the actual tag and the expected tag is performed * in constant time. * * \param[in,out] operation Active AEAD operation. * \param[out] plaintext Buffer where the last part of the plaintext * is to be written. This is the remaining data * from previous calls to psa_aead_update() * that could not be processed until the end * of the input. * \param plaintext_size Size of the \p plaintext buffer in bytes. * This must be appropriate for the selected algorithm and key: * - A sufficient output size is * #PSA_AEAD_VERIFY_OUTPUT_SIZE(\c key_type, * \c alg) where \c key_type is the type of key * and \c alg is the algorithm that were used to * set up the operation. * - #PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE evaluates to * the maximum output size of any supported AEAD * algorithm. * \param[out] plaintext_length On success, the number of bytes of * returned plaintext. * \param[in] tag Buffer containing the authentication tag. * \param tag_length Size of the \p tag buffer in bytes. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_SIGNATURE * The calculations were successful, but the authentication tag is * not correct. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be an active decryption * operation with a nonce set). * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p plaintext buffer is too small. * #PSA_AEAD_VERIFY_OUTPUT_SIZE(\c key_type, \c alg) or * #PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE can be used to determine the * required buffer size. * \retval #PSA_ERROR_INVALID_ARGUMENT * The total length of input to psa_aead_update_ad() so far is * less than the additional data length that was previously * specified with psa_aead_set_lengths(). * \retval #PSA_ERROR_INVALID_ARGUMENT * The total length of input to psa_aead_update() so far is * less than the plaintext length that was previously * specified with psa_aead_set_lengths(). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_verify(psa_aead_operation_t *operation, uint8_t *plaintext, size_t plaintext_size, size_t *plaintext_length, const uint8_t *tag, size_t tag_length); /** Abort an AEAD operation. * * Aborting an operation frees all associated resources except for the * \p operation structure itself. Once aborted, the operation object * can be reused for another operation by calling * psa_aead_encrypt_setup() or psa_aead_decrypt_setup() again. * * You may call this function any time after the operation object has * been initialized as described in #psa_aead_operation_t. * * In particular, calling psa_aead_abort() after the operation has been * terminated by a call to psa_aead_abort(), psa_aead_finish() or * psa_aead_verify() is safe and has no effect. * * \param[in,out] operation Initialized AEAD operation. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_aead_abort(psa_aead_operation_t *operation); /**@}*/ /** \defgroup asymmetric Asymmetric cryptography * @{ */ /** * \brief Sign a message with a private key. For hash-and-sign algorithms, * this includes the hashing step. * * \note To perform a multi-part hash-and-sign signature algorithm, first use * a multi-part hash operation and then pass the resulting hash to * psa_sign_hash(). PSA_ALG_GET_HASH(\p alg) can be used to determine the * hash algorithm to use. * * \param[in] key Identifier of the key to use for the operation. * It must be an asymmetric key pair. The key must * allow the usage #PSA_KEY_USAGE_SIGN_MESSAGE. * \param[in] alg An asymmetric signature algorithm (PSA_ALG_XXX * value such that #PSA_ALG_IS_SIGN_MESSAGE(\p alg) * is true), that is compatible with the type of * \p key. * \param[in] input The input message to sign. * \param[in] input_length Size of the \p input buffer in bytes. * \param[out] signature Buffer where the signature is to be written. * \param[in] signature_size Size of the \p signature buffer in bytes. This * must be appropriate for the selected * algorithm and key: * - The required signature size is * #PSA_SIGN_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg) * where \c key_type and \c key_bits are the type and * bit-size respectively of key. * - #PSA_SIGNATURE_MAX_SIZE evaluates to the * maximum signature size of any supported * signature algorithm. * \param[out] signature_length On success, the number of bytes that make up * the returned signature value. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * The key does not have the #PSA_KEY_USAGE_SIGN_MESSAGE flag, * or it does not permit the requested algorithm. * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p signature buffer is too small. You can * determine a sufficient buffer size by calling * #PSA_SIGN_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg) * where \c key_type and \c key_bits are the type and bit-size * respectively of \p key. * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_DATA_CORRUPT * \retval #PSA_ERROR_DATA_INVALID * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_sign_message( mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t * input, size_t input_length, uint8_t * signature, size_t signature_size, size_t * signature_length ); /** \brief Verify the signature of a message with a public key, using * a hash-and-sign verification algorithm. * * \note To perform a multi-part hash-and-sign signature verification * algorithm, first use a multi-part hash operation to hash the message * and then pass the resulting hash to psa_verify_hash(). * PSA_ALG_GET_HASH(\p alg) can be used to determine the hash algorithm * to use. * * \param[in] key Identifier of the key to use for the operation. * It must be a public key or an asymmetric key * pair. The key must allow the usage * #PSA_KEY_USAGE_VERIFY_MESSAGE. * \param[in] alg An asymmetric signature algorithm (PSA_ALG_XXX * value such that #PSA_ALG_IS_SIGN_MESSAGE(\p alg) * is true), that is compatible with the type of * \p key. * \param[in] input The message whose signature is to be verified. * \param[in] input_length Size of the \p input buffer in bytes. * \param[out] signature Buffer containing the signature to verify. * \param[in] signature_length Size of the \p signature buffer in bytes. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * The key does not have the #PSA_KEY_USAGE_SIGN_MESSAGE flag, * or it does not permit the requested algorithm. * \retval #PSA_ERROR_INVALID_SIGNATURE * The calculation was performed successfully, but the passed signature * is not a valid signature. * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_DATA_CORRUPT * \retval #PSA_ERROR_DATA_INVALID * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_verify_message( mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t * input, size_t input_length, const uint8_t * signature, size_t signature_length ); /** * \brief Sign a hash or short message with a private key. * * Note that to perform a hash-and-sign signature algorithm, you must * first calculate the hash by calling psa_hash_setup(), psa_hash_update() * and psa_hash_finish(), or alternatively by calling psa_hash_compute(). * Then pass the resulting hash as the \p hash * parameter to this function. You can use #PSA_ALG_SIGN_GET_HASH(\p alg) * to determine the hash algorithm to use. * * \param key Identifier of the key to use for the operation. * It must be an asymmetric key pair. The key must * allow the usage #PSA_KEY_USAGE_SIGN_HASH. * \param alg A signature algorithm that is compatible with * the type of \p key. * \param[in] hash The hash or message to sign. * \param hash_length Size of the \p hash buffer in bytes. * \param[out] signature Buffer where the signature is to be written. * \param signature_size Size of the \p signature buffer in bytes. * \param[out] signature_length On success, the number of bytes * that make up the returned signature value. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p signature buffer is too small. You can * determine a sufficient buffer size by calling * #PSA_SIGN_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg) * where \c key_type and \c key_bits are the type and bit-size * respectively of \p key. * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_sign_hash(mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t *hash, size_t hash_length, uint8_t *signature, size_t signature_size, size_t *signature_length); /** * \brief Verify the signature of a hash or short message using a public key. * * Note that to perform a hash-and-sign signature algorithm, you must * first calculate the hash by calling psa_hash_setup(), psa_hash_update() * and psa_hash_finish(), or alternatively by calling psa_hash_compute(). * Then pass the resulting hash as the \p hash * parameter to this function. You can use #PSA_ALG_SIGN_GET_HASH(\p alg) * to determine the hash algorithm to use. * * \param key Identifier of the key to use for the operation. It * must be a public key or an asymmetric key pair. The * key must allow the usage * #PSA_KEY_USAGE_VERIFY_HASH. * \param alg A signature algorithm that is compatible with * the type of \p key. * \param[in] hash The hash or message whose signature is to be * verified. * \param hash_length Size of the \p hash buffer in bytes. * \param[in] signature Buffer containing the signature to verify. * \param signature_length Size of the \p signature buffer in bytes. * * \retval #PSA_SUCCESS * The signature is valid. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_SIGNATURE * The calculation was perfomed successfully, but the passed * signature is not a valid signature. * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_verify_hash(mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t *hash, size_t hash_length, const uint8_t *signature, size_t signature_length); /** * \brief Encrypt a short message with a public key. * * \param key Identifer of the key to use for the operation. * It must be a public key or an asymmetric key * pair. It must allow the usage * #PSA_KEY_USAGE_ENCRYPT. * \param alg An asymmetric encryption algorithm that is * compatible with the type of \p key. * \param[in] input The message to encrypt. * \param input_length Size of the \p input buffer in bytes. * \param[in] salt A salt or label, if supported by the * encryption algorithm. * If the algorithm does not support a * salt, pass \c NULL. * If the algorithm supports an optional * salt and you do not want to pass a salt, * pass \c NULL. * * - For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is * supported. * \param salt_length Size of the \p salt buffer in bytes. * If \p salt is \c NULL, pass 0. * \param[out] output Buffer where the encrypted message is to * be written. * \param output_size Size of the \p output buffer in bytes. * \param[out] output_length On success, the number of bytes * that make up the returned output. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p output buffer is too small. You can * determine a sufficient buffer size by calling * #PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg) * where \c key_type and \c key_bits are the type and bit-size * respectively of \p key. * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_asymmetric_encrypt(mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t *input, size_t input_length, const uint8_t *salt, size_t salt_length, uint8_t *output, size_t output_size, size_t *output_length); /** * \brief Decrypt a short message with a private key. * * \param key Identifier of the key to use for the operation. * It must be an asymmetric key pair. It must * allow the usage #PSA_KEY_USAGE_DECRYPT. * \param alg An asymmetric encryption algorithm that is * compatible with the type of \p key. * \param[in] input The message to decrypt. * \param input_length Size of the \p input buffer in bytes. * \param[in] salt A salt or label, if supported by the * encryption algorithm. * If the algorithm does not support a * salt, pass \c NULL. * If the algorithm supports an optional * salt and you do not want to pass a salt, * pass \c NULL. * * - For #PSA_ALG_RSA_PKCS1V15_CRYPT, no salt is * supported. * \param salt_length Size of the \p salt buffer in bytes. * If \p salt is \c NULL, pass 0. * \param[out] output Buffer where the decrypted message is to * be written. * \param output_size Size of the \c output buffer in bytes. * \param[out] output_length On success, the number of bytes * that make up the returned output. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_BUFFER_TOO_SMALL * The size of the \p output buffer is too small. You can * determine a sufficient buffer size by calling * #PSA_ASYMMETRIC_DECRYPT_OUTPUT_SIZE(\c key_type, \c key_bits, \p alg) * where \c key_type and \c key_bits are the type and bit-size * respectively of \p key. * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY * \retval #PSA_ERROR_INVALID_PADDING * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_asymmetric_decrypt(mbedtls_svc_key_id_t key, psa_algorithm_t alg, const uint8_t *input, size_t input_length, const uint8_t *salt, size_t salt_length, uint8_t *output, size_t output_size, size_t *output_length); /**@}*/ /** \defgroup key_derivation Key derivation and pseudorandom generation * @{ */ /** The type of the state data structure for key derivation operations. * * Before calling any function on a key derivation operation object, the * application must initialize it by any of the following means: * - Set the structure to all-bits-zero, for example: * \code * psa_key_derivation_operation_t operation; * memset(&operation, 0, sizeof(operation)); * \endcode * - Initialize the structure to logical zero values, for example: * \code * psa_key_derivation_operation_t operation = {0}; * \endcode * - Initialize the structure to the initializer #PSA_KEY_DERIVATION_OPERATION_INIT, * for example: * \code * psa_key_derivation_operation_t operation = PSA_KEY_DERIVATION_OPERATION_INIT; * \endcode * - Assign the result of the function psa_key_derivation_operation_init() * to the structure, for example: * \code * psa_key_derivation_operation_t operation; * operation = psa_key_derivation_operation_init(); * \endcode * * This is an implementation-defined \c struct. Applications should not * make any assumptions about the content of this structure except * as directed by the documentation of a specific implementation. */ typedef struct psa_key_derivation_s psa_key_derivation_operation_t; /** \def PSA_KEY_DERIVATION_OPERATION_INIT * * This macro returns a suitable initializer for a key derivation operation * object of type #psa_key_derivation_operation_t. */ #ifdef __DOXYGEN_ONLY__ /* This is an example definition for documentation purposes. * Implementations should define a suitable value in `crypto_struct.h`. */ #define PSA_KEY_DERIVATION_OPERATION_INIT {0} #endif /** Return an initial value for a key derivation operation object. */ static psa_key_derivation_operation_t psa_key_derivation_operation_init(void); /** Set up a key derivation operation. * * A key derivation algorithm takes some inputs and uses them to generate * a byte stream in a deterministic way. * This byte stream can be used to produce keys and other * cryptographic material. * * To derive a key: * -# Start with an initialized object of type #psa_key_derivation_operation_t. * -# Call psa_key_derivation_setup() to select the algorithm. * -# Provide the inputs for the key derivation by calling * psa_key_derivation_input_bytes() or psa_key_derivation_input_key() * as appropriate. Which inputs are needed, in what order, and whether * they may be keys and if so of what type depends on the algorithm. * -# Optionally set the operation's maximum capacity with * psa_key_derivation_set_capacity(). You may do this before, in the middle * of or after providing inputs. For some algorithms, this step is mandatory * because the output depends on the maximum capacity. * -# To derive a key, call psa_key_derivation_output_key(). * To derive a byte string for a different purpose, call * psa_key_derivation_output_bytes(). * Successive calls to these functions use successive output bytes * calculated by the key derivation algorithm. * -# Clean up the key derivation operation object with * psa_key_derivation_abort(). * * If this function returns an error, the key derivation operation object is * not changed. * * If an error occurs at any step after a call to psa_key_derivation_setup(), * the operation will need to be reset by a call to psa_key_derivation_abort(). * * Implementations must reject an attempt to derive a key of size 0. * * \param[in,out] operation The key derivation operation object * to set up. It must * have been initialized but not set up yet. * \param alg The key derivation algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_KEY_DERIVATION(\p alg) is true). * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_ARGUMENT * \c alg is not a key derivation algorithm. * \retval #PSA_ERROR_NOT_SUPPORTED * \c alg is not supported or is not a key derivation algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be inactive). * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_key_derivation_setup( psa_key_derivation_operation_t *operation, psa_algorithm_t alg); /** Retrieve the current capacity of a key derivation operation. * * The capacity of a key derivation is the maximum number of bytes that it can * return. When you get *N* bytes of output from a key derivation operation, * this reduces its capacity by *N*. * * \param[in] operation The operation to query. * \param[out] capacity On success, the capacity of the operation. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active). * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_key_derivation_get_capacity( const psa_key_derivation_operation_t *operation, size_t *capacity); /** Set the maximum capacity of a key derivation operation. * * The capacity of a key derivation operation is the maximum number of bytes * that the key derivation operation can return from this point onwards. * * \param[in,out] operation The key derivation operation object to modify. * \param capacity The new capacity of the operation. * It must be less or equal to the operation's * current capacity. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INVALID_ARGUMENT * \p capacity is larger than the operation's current capacity. * In this case, the operation object remains valid and its capacity * remains unchanged. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active). * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_key_derivation_set_capacity( psa_key_derivation_operation_t *operation, size_t capacity); /** Use the maximum possible capacity for a key derivation operation. * * Use this value as the capacity argument when setting up a key derivation * to indicate that the operation should have the maximum possible capacity. * The value of the maximum possible capacity depends on the key derivation * algorithm. */ #define PSA_KEY_DERIVATION_UNLIMITED_CAPACITY ((size_t)(-1)) /** Provide an input for key derivation or key agreement. * * Which inputs are required and in what order depends on the algorithm. * Refer to the documentation of each key derivation or key agreement * algorithm for information. * * This function passes direct inputs, which is usually correct for * non-secret inputs. To pass a secret input, which should be in a key * object, call psa_key_derivation_input_key() instead of this function. * Refer to the documentation of individual step types * (`PSA_KEY_DERIVATION_INPUT_xxx` values of type ::psa_key_derivation_step_t) * for more information. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_key_derivation_abort(). * * \param[in,out] operation The key derivation operation object to use. * It must have been set up with * psa_key_derivation_setup() and must not * have produced any output yet. * \param step Which step the input data is for. * \param[in] data Input data to use. * \param data_length Size of the \p data buffer in bytes. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_ARGUMENT * \c step is not compatible with the operation's algorithm. * \retval #PSA_ERROR_INVALID_ARGUMENT * \c step does not allow direct inputs. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid for this input \p step. * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_key_derivation_input_bytes( psa_key_derivation_operation_t *operation, psa_key_derivation_step_t step, const uint8_t *data, size_t data_length); /** Provide an input for key derivation in the form of a key. * * Which inputs are required and in what order depends on the algorithm. * Refer to the documentation of each key derivation or key agreement * algorithm for information. * * This function obtains input from a key object, which is usually correct for * secret inputs or for non-secret personalization strings kept in the key * store. To pass a non-secret parameter which is not in the key store, * call psa_key_derivation_input_bytes() instead of this function. * Refer to the documentation of individual step types * (`PSA_KEY_DERIVATION_INPUT_xxx` values of type ::psa_key_derivation_step_t) * for more information. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_key_derivation_abort(). * * \param[in,out] operation The key derivation operation object to use. * It must have been set up with * psa_key_derivation_setup() and must not * have produced any output yet. * \param step Which step the input data is for. * \param key Identifier of the key. It must have an * appropriate type for step and must allow the * usage #PSA_KEY_USAGE_DERIVE. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \c step is not compatible with the operation's algorithm. * \retval #PSA_ERROR_INVALID_ARGUMENT * \c step does not allow key inputs of the given type * or does not allow key inputs at all. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid for this input \p step. * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_key_derivation_input_key( psa_key_derivation_operation_t *operation, psa_key_derivation_step_t step, mbedtls_svc_key_id_t key); /** Perform a key agreement and use the shared secret as input to a key * derivation. * * A key agreement algorithm takes two inputs: a private key \p private_key * a public key \p peer_key. * The result of this function is passed as input to a key derivation. * The output of this key derivation can be extracted by reading from the * resulting operation to produce keys and other cryptographic material. * * If this function returns an error status, the operation enters an error * state and must be aborted by calling psa_key_derivation_abort(). * * \param[in,out] operation The key derivation operation object to use. * It must have been set up with * psa_key_derivation_setup() with a * key agreement and derivation algorithm * \c alg (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_KEY_AGREEMENT(\c alg) is true * and #PSA_ALG_IS_RAW_KEY_AGREEMENT(\c alg) * is false). * The operation must be ready for an * input of the type given by \p step. * \param step Which step the input data is for. * \param private_key Identifier of the private key to use. It must * allow the usage #PSA_KEY_USAGE_DERIVE. * \param[in] peer_key Public key of the peer. The peer key must be in the * same format that psa_import_key() accepts for the * public key type corresponding to the type of * private_key. That is, this function performs the * equivalent of * #psa_import_key(..., * `peer_key`, `peer_key_length`) where * with key attributes indicating the public key * type corresponding to the type of `private_key`. * For example, for EC keys, this means that peer_key * is interpreted as a point on the curve that the * private key is on. The standard formats for public * keys are documented in the documentation of * psa_export_public_key(). * \param peer_key_length Size of \p peer_key in bytes. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid for this key agreement \p step. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \c private_key is not compatible with \c alg, * or \p peer_key is not valid for \c alg or not compatible with * \c private_key. * \retval #PSA_ERROR_NOT_SUPPORTED * \c alg is not supported or is not a key derivation algorithm. * \retval #PSA_ERROR_INVALID_ARGUMENT * \c step does not allow an input resulting from a key agreement. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_key_derivation_key_agreement( psa_key_derivation_operation_t *operation, psa_key_derivation_step_t step, mbedtls_svc_key_id_t private_key, const uint8_t *peer_key, size_t peer_key_length); /** Read some data from a key derivation operation. * * This function calculates output bytes from a key derivation algorithm and * return those bytes. * If you view the key derivation's output as a stream of bytes, this * function destructively reads the requested number of bytes from the * stream. * The operation's capacity decreases by the number of bytes read. * * If this function returns an error status other than * #PSA_ERROR_INSUFFICIENT_DATA, the operation enters an error * state and must be aborted by calling psa_key_derivation_abort(). * * \param[in,out] operation The key derivation operation object to read from. * \param[out] output Buffer where the output will be written. * \param output_length Number of bytes to output. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_INSUFFICIENT_DATA * The operation's capacity was less than * \p output_length bytes. Note that in this case, * no output is written to the output buffer. * The operation's capacity is set to 0, thus * subsequent calls to this function will not * succeed, even with a smaller output buffer. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active and completed * all required input steps). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_key_derivation_output_bytes( psa_key_derivation_operation_t *operation, uint8_t *output, size_t output_length); /** Derive a key from an ongoing key derivation operation. * * This function calculates output bytes from a key derivation algorithm * and uses those bytes to generate a key deterministically. * The key's location, usage policy, type and size are taken from * \p attributes. * * If you view the key derivation's output as a stream of bytes, this * function destructively reads as many bytes as required from the * stream. * The operation's capacity decreases by the number of bytes read. * * If this function returns an error status other than * #PSA_ERROR_INSUFFICIENT_DATA, the operation enters an error * state and must be aborted by calling psa_key_derivation_abort(). * * How much output is produced and consumed from the operation, and how * the key is derived, depends on the key type and on the key size * (denoted \c bits below): * * - For key types for which the key is an arbitrary sequence of bytes * of a given size, this function is functionally equivalent to * calling #psa_key_derivation_output_bytes * and passing the resulting output to #psa_import_key. * However, this function has a security benefit: * if the implementation provides an isolation boundary then * the key material is not exposed outside the isolation boundary. * As a consequence, for these key types, this function always consumes * exactly (\c bits / 8) bytes from the operation. * The following key types defined in this specification follow this scheme: * * - #PSA_KEY_TYPE_AES; * - #PSA_KEY_TYPE_ARC4; * - #PSA_KEY_TYPE_CAMELLIA; * - #PSA_KEY_TYPE_DERIVE; * - #PSA_KEY_TYPE_HMAC. * * - For ECC keys on a Montgomery elliptic curve * (#PSA_KEY_TYPE_ECC_KEY_PAIR(\c curve) where \c curve designates a * Montgomery curve), this function always draws a byte string whose * length is determined by the curve, and sets the mandatory bits * accordingly. That is: * * - Curve25519 (#PSA_ECC_FAMILY_MONTGOMERY, 255 bits): draw a 32-byte * string and process it as specified in RFC 7748 &sect;5. * - Curve448 (#PSA_ECC_FAMILY_MONTGOMERY, 448 bits): draw a 56-byte * string and process it as specified in RFC 7748 &sect;5. * * - For key types for which the key is represented by a single sequence of * \c bits bits with constraints as to which bit sequences are acceptable, * this function draws a byte string of length (\c bits / 8) bytes rounded * up to the nearest whole number of bytes. If the resulting byte string * is acceptable, it becomes the key, otherwise the drawn bytes are discarded. * This process is repeated until an acceptable byte string is drawn. * The byte string drawn from the operation is interpreted as specified * for the output produced by psa_export_key(). * The following key types defined in this specification follow this scheme: * * - #PSA_KEY_TYPE_DES. * Force-set the parity bits, but discard forbidden weak keys. * For 2-key and 3-key triple-DES, the three keys are generated * successively (for example, for 3-key triple-DES, * if the first 8 bytes specify a weak key and the next 8 bytes do not, * discard the first 8 bytes, use the next 8 bytes as the first key, * and continue reading output from the operation to derive the other * two keys). * - Finite-field Diffie-Hellman keys (#PSA_KEY_TYPE_DH_KEY_PAIR(\c group) * where \c group designates any Diffie-Hellman group) and * ECC keys on a Weierstrass elliptic curve * (#PSA_KEY_TYPE_ECC_KEY_PAIR(\c curve) where \c curve designates a * Weierstrass curve). * For these key types, interpret the byte string as integer * in big-endian order. Discard it if it is not in the range * [0, *N* - 2] where *N* is the boundary of the private key domain * (the prime *p* for Diffie-Hellman, the subprime *q* for DSA, * or the order of the curve's base point for ECC). * Add 1 to the resulting integer and use this as the private key *x*. * This method allows compliance to NIST standards, specifically * the methods titled "key-pair generation by testing candidates" * in NIST SP 800-56A &sect;5.6.1.1.4 for Diffie-Hellman, * in FIPS 186-4 &sect;B.1.2 for DSA, and * in NIST SP 800-56A &sect;5.6.1.2.2 or * FIPS 186-4 &sect;B.4.2 for elliptic curve keys. * * - For other key types, including #PSA_KEY_TYPE_RSA_KEY_PAIR, * the way in which the operation output is consumed is * implementation-defined. * * In all cases, the data that is read is discarded from the operation. * The operation's capacity is decreased by the number of bytes read. * * For algorithms that take an input step #PSA_KEY_DERIVATION_INPUT_SECRET, * the input to that step must be provided with psa_key_derivation_input_key(). * Future versions of this specification may include additional restrictions * on the derived key based on the attributes and strength of the secret key. * * \param[in] attributes The attributes for the new key. * \param[in,out] operation The key derivation operation object to read from. * \param[out] key On success, an identifier for the newly created * key. For persistent keys, this is the key * identifier defined in \p attributes. * \c 0 on failure. * * \retval #PSA_SUCCESS * Success. * If the key is persistent, the key material and the key's metadata * have been saved to persistent storage. * \retval #PSA_ERROR_ALREADY_EXISTS * This is an attempt to create a persistent key, and there is * already a persistent key with the given identifier. * \retval #PSA_ERROR_INSUFFICIENT_DATA * There was not enough data to create the desired key. * Note that in this case, no output is written to the output buffer. * The operation's capacity is set to 0, thus subsequent calls to * this function will not succeed, even with a smaller output buffer. * \retval #PSA_ERROR_NOT_SUPPORTED * The key type or key size is not supported, either by the * implementation in general or in this particular location. * \retval #PSA_ERROR_INVALID_ARGUMENT * The provided key attributes are not valid for the operation. * \retval #PSA_ERROR_NOT_PERMITTED * The #PSA_KEY_DERIVATION_INPUT_SECRET input was not provided through * a key. * \retval #PSA_ERROR_BAD_STATE * The operation state is not valid (it must be active and completed * all required input steps). * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_INSUFFICIENT_STORAGE * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_DATA_INVALID * \retval #PSA_ERROR_DATA_CORRUPT * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_key_derivation_output_key( const psa_key_attributes_t *attributes, psa_key_derivation_operation_t *operation, mbedtls_svc_key_id_t *key); /** Abort a key derivation operation. * * Aborting an operation frees all associated resources except for the \c * operation structure itself. Once aborted, the operation object can be reused * for another operation by calling psa_key_derivation_setup() again. * * This function may be called at any time after the operation * object has been initialized as described in #psa_key_derivation_operation_t. * * In particular, it is valid to call psa_key_derivation_abort() twice, or to * call psa_key_derivation_abort() on an operation that has not been set up. * * \param[in,out] operation The operation to abort. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_key_derivation_abort( psa_key_derivation_operation_t *operation); /** Perform a key agreement and return the raw shared secret. * * \warning The raw result of a key agreement algorithm such as finite-field * Diffie-Hellman or elliptic curve Diffie-Hellman has biases and should * not be used directly as key material. It should instead be passed as * input to a key derivation algorithm. To chain a key agreement with * a key derivation, use psa_key_derivation_key_agreement() and other * functions from the key derivation interface. * * \param alg The key agreement algorithm to compute * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_RAW_KEY_AGREEMENT(\p alg) * is true). * \param private_key Identifier of the private key to use. It must * allow the usage #PSA_KEY_USAGE_DERIVE. * \param[in] peer_key Public key of the peer. It must be * in the same format that psa_import_key() * accepts. The standard formats for public * keys are documented in the documentation * of psa_export_public_key(). * \param peer_key_length Size of \p peer_key in bytes. * \param[out] output Buffer where the decrypted message is to * be written. * \param output_size Size of the \c output buffer in bytes. * \param[out] output_length On success, the number of bytes * that make up the returned output. * * \retval #PSA_SUCCESS * Success. * \retval #PSA_ERROR_INVALID_HANDLE * \retval #PSA_ERROR_NOT_PERMITTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \p alg is not a key agreement algorithm * \retval #PSA_ERROR_INVALID_ARGUMENT * \p private_key is not compatible with \p alg, * or \p peer_key is not valid for \p alg or not compatible with * \p private_key. * \retval #PSA_ERROR_BUFFER_TOO_SMALL * \p output_size is too small * \retval #PSA_ERROR_NOT_SUPPORTED * \p alg is not a supported key agreement algorithm. * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_raw_key_agreement(psa_algorithm_t alg, mbedtls_svc_key_id_t private_key, const uint8_t *peer_key, size_t peer_key_length, uint8_t *output, size_t output_size, size_t *output_length); /**@}*/ /** \defgroup random Random generation * @{ */ /** * \brief Generate random bytes. * * \warning This function **can** fail! Callers MUST check the return status * and MUST NOT use the content of the output buffer if the return * status is not #PSA_SUCCESS. * * \note To generate a key, use psa_generate_key() instead. * * \param[out] output Output buffer for the generated data. * \param output_size Number of bytes to generate and output. * * \retval #PSA_SUCCESS * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_generate_random(uint8_t *output, size_t output_size); /** * \brief Generate a key or key pair. * * The key is generated randomly. * Its location, usage policy, type and size are taken from \p attributes. * * Implementations must reject an attempt to generate a key of size 0. * * The following type-specific considerations apply: * - For RSA keys (#PSA_KEY_TYPE_RSA_KEY_PAIR), * the public exponent is 65537. * The modulus is a product of two probabilistic primes * between 2^{n-1} and 2^n where n is the bit size specified in the * attributes. * * \param[in] attributes The attributes for the new key. * \param[out] key On success, an identifier for the newly created * key. For persistent keys, this is the key * identifier defined in \p attributes. * \c 0 on failure. * * \retval #PSA_SUCCESS * Success. * If the key is persistent, the key material and the key's metadata * have been saved to persistent storage. * \retval #PSA_ERROR_ALREADY_EXISTS * This is an attempt to create a persistent key, and there is * already a persistent key with the given identifier. * \retval #PSA_ERROR_NOT_SUPPORTED * \retval #PSA_ERROR_INVALID_ARGUMENT * \retval #PSA_ERROR_INSUFFICIENT_MEMORY * \retval #PSA_ERROR_INSUFFICIENT_ENTROPY * \retval #PSA_ERROR_COMMUNICATION_FAILURE * \retval #PSA_ERROR_HARDWARE_FAILURE * \retval #PSA_ERROR_CORRUPTION_DETECTED * \retval #PSA_ERROR_INSUFFICIENT_STORAGE * \retval #PSA_ERROR_DATA_INVALID * \retval #PSA_ERROR_DATA_CORRUPT * \retval #PSA_ERROR_STORAGE_FAILURE * \retval #PSA_ERROR_BAD_STATE * The library has not been previously initialized by psa_crypto_init(). * It is implementation-dependent whether a failure to initialize * results in this error code. */ psa_status_t psa_generate_key(const psa_key_attributes_t *attributes, mbedtls_svc_key_id_t *key); /**@}*/ #ifdef __cplusplus } #endif /* The file "crypto_sizes.h" contains definitions for size calculation * macros whose definitions are implementation-specific. */ #include "crypto_sizes.h" /* The file "crypto_struct.h" contains definitions for * implementation-specific structs that are declared above. */ #include "crypto_struct.h" /* The file "crypto_extra.h" contains vendor-specific definitions. This * can include vendor-defined algorithms, extra functions, etc. */ #include "crypto_extra.h" #endif /* PSA_CRYPTO_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_driver_contexts_primitives.h
/* * Declaration of context structures for use with the PSA driver wrapper * interface. This file contains the context structures for 'primitive' * operations, i.e. those operations which do not rely on other contexts. * * Warning: This file will be auto-generated in the future. * * \note This file may not be included directly. Applications must * include psa/crypto.h. * * \note This header and its content is not part of the Mbed TLS API and * applications must not depend on it. Its main purpose is to define the * multi-part state objects of the PSA drivers included in the cryptographic * library. The definition of these objects are then used by crypto_struct.h * to define the implementation-defined types of PSA multi-part state objects. */ /* Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_DRIVER_CONTEXTS_PRIMITIVES_H #define PSA_CRYPTO_DRIVER_CONTEXTS_PRIMITIVES_H #include "psa/crypto_driver_common.h" /* Include the context structure definitions for those drivers that were * declared during the autogeneration process. */ /* Include the context structure definitions for the Mbed TLS software drivers */ #include "psa/crypto_builtin_primitives.h" /* Define the context to be used for an operation that is executed through the * PSA Driver wrapper layer as the union of all possible driver's contexts. * * The union members are the driver's context structures, and the member names * are formatted as `'drivername'_ctx`. This allows for procedural generation * of both this file and the content of psa_crypto_driver_wrappers.c */ typedef union { unsigned dummy; /* Make sure this union is always non-empty */ mbedtls_psa_hash_operation_t mbedtls_ctx; #if defined(PSA_CRYPTO_DRIVER_TEST) mbedtls_transparent_test_driver_hash_operation_t test_driver_ctx; #endif } psa_driver_hash_context_t; typedef union { unsigned dummy; /* Make sure this union is always non-empty */ mbedtls_psa_cipher_operation_t mbedtls_ctx; #if defined(PSA_CRYPTO_DRIVER_TEST) mbedtls_transparent_test_driver_cipher_operation_t transparent_test_driver_ctx; mbedtls_opaque_test_driver_cipher_operation_t opaque_test_driver_ctx; #endif } psa_driver_cipher_context_t; #endif /* PSA_CRYPTO_DRIVER_CONTEXTS_PRIMITIVES_H */ /* End of automatically generated file. */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_platform.h
/** * \file psa/crypto_platform.h * * \brief PSA cryptography module: Mbed TLS platform definitions * * \note This file may not be included directly. Applications must * include psa/crypto.h. * * This file contains platform-dependent type definitions. * * In implementations with isolation between the application and the * cryptography module, implementers should take care to ensure that * the definitions that are exposed to applications match what the * module implements. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_PLATFORM_H #define PSA_CRYPTO_PLATFORM_H /* Include the Mbed TLS configuration file, the way Mbed TLS does it * in each of its header files. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif /* Translate between classic MBEDTLS_xxx feature symbols and PSA_xxx * feature symbols. */ #include "mbedtls/config_psa.h" /* PSA requires several types which C99 provides in stdint.h. */ #include <stdint.h> #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ !defined(inline) && !defined(__cplusplus) #define inline __inline #endif #if defined(MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER) /* Building for the PSA Crypto service on a PSA platform, a key owner is a PSA * partition identifier. * * The function psa_its_identifier_of_slot() in psa_crypto_storage.c that * translates a key identifier to a key storage file name assumes that * mbedtls_key_owner_id_t is an 32 bits integer. This function thus needs * reworking if mbedtls_key_owner_id_t is not defined as a 32 bits integer * here anymore. */ typedef int32_t mbedtls_key_owner_id_t; /** Compare two key owner identifiers. * * \param id1 First key owner identifier. * \param id2 Second key owner identifier. * * \return Non-zero if the two key owner identifiers are equal, zero otherwise. */ static inline int mbedtls_key_owner_id_equal( mbedtls_key_owner_id_t id1, mbedtls_key_owner_id_t id2 ) { return( id1 == id2 ); } #endif /* MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER */ /* * When MBEDTLS_PSA_CRYPTO_SPM is defined, the code is being built for SPM * (Secure Partition Manager) integration which separates the code into two * parts: NSPE (Non-Secure Processing Environment) and SPE (Secure Processing * Environment). When building for the SPE, an additional header file should be * included. */ #if defined(MBEDTLS_PSA_CRYPTO_SPM) #define PSA_CRYPTO_SECURE 1 #include "crypto_spe.h" #endif // MBEDTLS_PSA_CRYPTO_SPM #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) /** The type of the context passed to mbedtls_psa_external_get_random(). * * Mbed TLS initializes the context to all-bits-zero before calling * mbedtls_psa_external_get_random() for the first time. * * The definition of this type in the Mbed TLS source code is for * demonstration purposes. Implementers of mbedtls_psa_external_get_random() * are expected to replace it with a custom definition. */ typedef struct { uintptr_t opaque[2]; } mbedtls_psa_external_random_context_t; #endif /* MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG */ #endif /* PSA_CRYPTO_PLATFORM_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_struct.h
/** * \file psa/crypto_struct.h * * \brief PSA cryptography module: Mbed TLS structured type implementations * * \note This file may not be included directly. Applications must * include psa/crypto.h. * * This file contains the definitions of some data structures with * implementation-specific definitions. * * In implementations with isolation between the application and the * cryptography module, it is expected that the front-end and the back-end * would have different versions of this file. * * <h3>Design notes about multipart operation structures</h3> * * For multipart operations without driver delegation support, each multipart * operation structure contains a `psa_algorithm_t alg` field which indicates * which specific algorithm the structure is for. When the structure is not in * use, `alg` is 0. Most of the structure consists of a union which is * discriminated by `alg`. * * For multipart operations with driver delegation support, each multipart * operation structure contains an `unsigned int id` field indicating which * driver got assigned to do the operation. When the structure is not in use, * 'id' is 0. The structure contains also a driver context which is the union * of the contexts of all drivers able to handle the type of multipart * operation. * * Note that when `alg` or `id` is 0, the content of other fields is undefined. * In particular, it is not guaranteed that a freshly-initialized structure * is all-zero: we initialize structures to something like `{0, 0}`, which * is only guaranteed to initializes the first member of the union; * GCC and Clang initialize the whole structure to 0 (at the time of writing), * but MSVC and CompCert don't. * * In Mbed Crypto, multipart operation structures live independently from * the key. This allows Mbed Crypto to free the key objects when destroying * a key slot. If a multipart operation needs to remember the key after * the setup function returns, the operation structure needs to contain a * copy of the key. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_STRUCT_H #define PSA_CRYPTO_STRUCT_H #ifdef __cplusplus extern "C" { #endif /* Include the Mbed TLS configuration file, the way Mbed TLS does it * in each of its header files. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/cmac.h" #include "mbedtls/gcm.h" /* Include the context definition for the compiled-in drivers for the primitive * algorithms. */ #include "psa/crypto_driver_contexts_primitives.h" struct psa_hash_operation_s { /** Unique ID indicating which driver got assigned to do the * operation. Since driver contexts are driver-specific, swapping * drivers halfway through the operation is not supported. * ID values are auto-generated in psa_driver_wrappers.h. * ID value zero means the context is not valid or not assigned to * any driver (i.e. the driver context is not active, in use). */ unsigned int id; psa_driver_hash_context_t ctx; }; #define PSA_HASH_OPERATION_INIT {0, {0}} static inline struct psa_hash_operation_s psa_hash_operation_init( void ) { const struct psa_hash_operation_s v = PSA_HASH_OPERATION_INIT; return( v ); } struct psa_cipher_operation_s { /** Unique ID indicating which driver got assigned to do the * operation. Since driver contexts are driver-specific, swapping * drivers halfway through the operation is not supported. * ID values are auto-generated in psa_crypto_driver_wrappers.h * ID value zero means the context is not valid or not assigned to * any driver (i.e. none of the driver contexts are active). */ unsigned int id; unsigned int iv_required : 1; unsigned int iv_set : 1; uint8_t default_iv_length; psa_driver_cipher_context_t ctx; }; #define PSA_CIPHER_OPERATION_INIT {0, 0, 0, 0, {0}} static inline struct psa_cipher_operation_s psa_cipher_operation_init( void ) { const struct psa_cipher_operation_s v = PSA_CIPHER_OPERATION_INIT; return( v ); } /* Include the context definition for the compiled-in drivers for the composite * algorithms. */ #include "psa/crypto_driver_contexts_composites.h" struct psa_mac_operation_s { /** Unique ID indicating which driver got assigned to do the * operation. Since driver contexts are driver-specific, swapping * drivers halfway through the operation is not supported. * ID values are auto-generated in psa_driver_wrappers.h * ID value zero means the context is not valid or not assigned to * any driver (i.e. none of the driver contexts are active). */ unsigned int id; uint8_t mac_size; unsigned int is_sign : 1; psa_driver_mac_context_t ctx; }; #define PSA_MAC_OPERATION_INIT {0, 0, 0, {0}} static inline struct psa_mac_operation_s psa_mac_operation_init( void ) { const struct psa_mac_operation_s v = PSA_MAC_OPERATION_INIT; return( v ); } struct psa_aead_operation_s { psa_algorithm_t alg; unsigned int key_set : 1; unsigned int iv_set : 1; uint8_t iv_size; uint8_t block_size; union { unsigned dummy; /* Enable easier initializing of the union. */ mbedtls_cipher_context_t cipher; } ctx; }; #define PSA_AEAD_OPERATION_INIT {0, 0, 0, 0, 0, {0}} static inline struct psa_aead_operation_s psa_aead_operation_init( void ) { const struct psa_aead_operation_s v = PSA_AEAD_OPERATION_INIT; return( v ); } #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) typedef struct { uint8_t *info; size_t info_length; psa_mac_operation_t hmac; uint8_t prk[PSA_HASH_MAX_SIZE]; uint8_t output_block[PSA_HASH_MAX_SIZE]; #if PSA_HASH_MAX_SIZE > 0xff #error "PSA_HASH_MAX_SIZE does not fit in uint8_t" #endif uint8_t offset_in_block; uint8_t block_number; unsigned int state : 2; unsigned int info_set : 1; } psa_hkdf_key_derivation_t; #endif /* MBEDTLS_PSA_BUILTIN_ALG_HKDF */ #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) typedef enum { PSA_TLS12_PRF_STATE_INIT, /* no input provided */ PSA_TLS12_PRF_STATE_SEED_SET, /* seed has been set */ PSA_TLS12_PRF_STATE_KEY_SET, /* key has been set */ PSA_TLS12_PRF_STATE_LABEL_SET, /* label has been set */ PSA_TLS12_PRF_STATE_OUTPUT /* output has been started */ } psa_tls12_prf_key_derivation_state_t; typedef struct psa_tls12_prf_key_derivation_s { #if PSA_HASH_MAX_SIZE > 0xff #error "PSA_HASH_MAX_SIZE does not fit in uint8_t" #endif /* Indicates how many bytes in the current HMAC block have * not yet been read by the user. */ uint8_t left_in_block; /* The 1-based number of the block. */ uint8_t block_number; psa_tls12_prf_key_derivation_state_t state; uint8_t *secret; size_t secret_length; uint8_t *seed; size_t seed_length; uint8_t *label; size_t label_length; uint8_t Ai[PSA_HASH_MAX_SIZE]; /* `HMAC_hash( prk, A(i) + seed )` in the notation of RFC 5246, Sect. 5. */ uint8_t output_block[PSA_HASH_MAX_SIZE]; } psa_tls12_prf_key_derivation_t; #endif /* MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || * MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS */ struct psa_key_derivation_s { psa_algorithm_t alg; unsigned int can_output_key : 1; size_t capacity; union { /* Make the union non-empty even with no supported algorithms. */ uint8_t dummy; #if defined(MBEDTLS_PSA_BUILTIN_ALG_HKDF) psa_hkdf_key_derivation_t hkdf; #endif #if defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PRF) || \ defined(MBEDTLS_PSA_BUILTIN_ALG_TLS12_PSK_TO_MS) psa_tls12_prf_key_derivation_t tls12_prf; #endif } ctx; }; /* This only zeroes out the first byte in the union, the rest is unspecified. */ #define PSA_KEY_DERIVATION_OPERATION_INIT {0, 0, 0, {0}} static inline struct psa_key_derivation_s psa_key_derivation_operation_init( void ) { const struct psa_key_derivation_s v = PSA_KEY_DERIVATION_OPERATION_INIT; return( v ); } struct psa_key_policy_s { psa_key_usage_t usage; psa_algorithm_t alg; psa_algorithm_t alg2; }; typedef struct psa_key_policy_s psa_key_policy_t; #define PSA_KEY_POLICY_INIT {0, 0, 0} static inline struct psa_key_policy_s psa_key_policy_init( void ) { const struct psa_key_policy_s v = PSA_KEY_POLICY_INIT; return( v ); } /* The type used internally for key sizes. * Public interfaces use size_t, but internally we use a smaller type. */ typedef uint16_t psa_key_bits_t; /* The maximum value of the type used to represent bit-sizes. * This is used to mark an invalid key size. */ #define PSA_KEY_BITS_TOO_LARGE ( (psa_key_bits_t) ( -1 ) ) /* The maximum size of a key in bits. * Currently defined as the maximum that can be represented, rounded down * to a whole number of bytes. * This is an uncast value so that it can be used in preprocessor * conditionals. */ #define PSA_MAX_KEY_BITS 0xfff8 /** A mask of flags that can be stored in key attributes. * * This type is also used internally to store flags in slots. Internal * flags are defined in library/psa_crypto_core.h. Internal flags may have * the same value as external flags if they are properly handled during * key creation and in psa_get_key_attributes. */ typedef uint16_t psa_key_attributes_flag_t; #define MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER \ ( (psa_key_attributes_flag_t) 0x0001 ) /* A mask of key attribute flags used externally only. * Only meant for internal checks inside the library. */ #define MBEDTLS_PSA_KA_MASK_EXTERNAL_ONLY ( \ MBEDTLS_PSA_KA_FLAG_HAS_SLOT_NUMBER | \ 0 ) /* A mask of key attribute flags used both internally and externally. * Currently there aren't any. */ #define MBEDTLS_PSA_KA_MASK_DUAL_USE ( \ 0 ) typedef struct { psa_key_type_t type; psa_key_bits_t bits; psa_key_lifetime_t lifetime; mbedtls_svc_key_id_t id; psa_key_policy_t policy; psa_key_attributes_flag_t flags; } psa_core_key_attributes_t; #define PSA_CORE_KEY_ATTRIBUTES_INIT {PSA_KEY_TYPE_NONE, 0, PSA_KEY_LIFETIME_VOLATILE, MBEDTLS_SVC_KEY_ID_INIT, PSA_KEY_POLICY_INIT, 0} struct psa_key_attributes_s { psa_core_key_attributes_t core; #if defined(MBEDTLS_PSA_CRYPTO_SE_C) psa_key_slot_number_t slot_number; #endif /* MBEDTLS_PSA_CRYPTO_SE_C */ void *domain_parameters; size_t domain_parameters_size; }; #if defined(MBEDTLS_PSA_CRYPTO_SE_C) #define PSA_KEY_ATTRIBUTES_INIT {PSA_CORE_KEY_ATTRIBUTES_INIT, 0, NULL, 0} #else #define PSA_KEY_ATTRIBUTES_INIT {PSA_CORE_KEY_ATTRIBUTES_INIT, NULL, 0} #endif static inline struct psa_key_attributes_s psa_key_attributes_init( void ) { const struct psa_key_attributes_s v = PSA_KEY_ATTRIBUTES_INIT; return( v ); } static inline void psa_set_key_id( psa_key_attributes_t *attributes, mbedtls_svc_key_id_t key ) { psa_key_lifetime_t lifetime = attributes->core.lifetime; attributes->core.id = key; if( PSA_KEY_LIFETIME_IS_VOLATILE( lifetime ) ) { attributes->core.lifetime = PSA_KEY_LIFETIME_FROM_PERSISTENCE_AND_LOCATION( PSA_KEY_LIFETIME_PERSISTENT, PSA_KEY_LIFETIME_GET_LOCATION( lifetime ) ); } } static inline mbedtls_svc_key_id_t psa_get_key_id( const psa_key_attributes_t *attributes) { return( attributes->core.id ); } #ifdef MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER static inline void mbedtls_set_key_owner_id( psa_key_attributes_t *attributes, mbedtls_key_owner_id_t owner ) { attributes->core.id.owner = owner; } #endif static inline void psa_set_key_lifetime(psa_key_attributes_t *attributes, psa_key_lifetime_t lifetime) { attributes->core.lifetime = lifetime; if( PSA_KEY_LIFETIME_IS_VOLATILE( lifetime ) ) { #ifdef MBEDTLS_PSA_CRYPTO_KEY_ID_ENCODES_OWNER attributes->core.id.key_id = 0; #else attributes->core.id = 0; #endif } } static inline psa_key_lifetime_t psa_get_key_lifetime( const psa_key_attributes_t *attributes) { return( attributes->core.lifetime ); } static inline void psa_extend_key_usage_flags( psa_key_usage_t *usage_flags ) { if( *usage_flags & PSA_KEY_USAGE_SIGN_HASH ) *usage_flags |= PSA_KEY_USAGE_SIGN_MESSAGE; if( *usage_flags & PSA_KEY_USAGE_VERIFY_HASH ) *usage_flags |= PSA_KEY_USAGE_VERIFY_MESSAGE; } static inline void psa_set_key_usage_flags(psa_key_attributes_t *attributes, psa_key_usage_t usage_flags) { psa_extend_key_usage_flags( &usage_flags ); attributes->core.policy.usage = usage_flags; } static inline psa_key_usage_t psa_get_key_usage_flags( const psa_key_attributes_t *attributes) { return( attributes->core.policy.usage ); } static inline void psa_set_key_algorithm(psa_key_attributes_t *attributes, psa_algorithm_t alg) { attributes->core.policy.alg = alg; } static inline psa_algorithm_t psa_get_key_algorithm( const psa_key_attributes_t *attributes) { return( attributes->core.policy.alg ); } /* This function is declared in crypto_extra.h, which comes after this * header file, but we need the function here, so repeat the declaration. */ psa_status_t psa_set_key_domain_parameters(psa_key_attributes_t *attributes, psa_key_type_t type, const uint8_t *data, size_t data_length); static inline void psa_set_key_type(psa_key_attributes_t *attributes, psa_key_type_t type) { if( attributes->domain_parameters == NULL ) { /* Common case: quick path */ attributes->core.type = type; } else { /* Call the bigger function to free the old domain paramteres. * Ignore any errors which may arise due to type requiring * non-default domain parameters, since this function can't * report errors. */ (void) psa_set_key_domain_parameters( attributes, type, NULL, 0 ); } } static inline psa_key_type_t psa_get_key_type( const psa_key_attributes_t *attributes) { return( attributes->core.type ); } static inline void psa_set_key_bits(psa_key_attributes_t *attributes, size_t bits) { if( bits > PSA_MAX_KEY_BITS ) attributes->core.bits = PSA_KEY_BITS_TOO_LARGE; else attributes->core.bits = (psa_key_bits_t) bits; } static inline size_t psa_get_key_bits( const psa_key_attributes_t *attributes) { return( attributes->core.bits ); } #ifdef __cplusplus } #endif #endif /* PSA_CRYPTO_STRUCT_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_sizes.h
/** * \file psa/crypto_sizes.h * * \brief PSA cryptography module: Mbed TLS buffer size macros * * \note This file may not be included directly. Applications must * include psa/crypto.h. * * This file contains the definitions of macros that are useful to * compute buffer sizes. The signatures and semantics of these macros * are standardized, but the definitions are not, because they depend on * the available algorithms and, in some cases, on permitted tolerances * on buffer sizes. * * In implementations with isolation between the application and the * cryptography module, implementers should take care to ensure that * the definitions that are exposed to applications match what the * module implements. * * Macros that compute sizes whose values do not depend on the * implementation are in crypto.h. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_SIZES_H #define PSA_CRYPTO_SIZES_H /* Include the Mbed TLS configuration file, the way Mbed TLS does it * in each of its header files. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #define PSA_BITS_TO_BYTES(bits) (((bits) + 7) / 8) #define PSA_BYTES_TO_BITS(bytes) ((bytes) * 8) #define PSA_ROUND_UP_TO_MULTIPLE(block_size, length) \ (((length) + (block_size) - 1) / (block_size) * (block_size)) /** The size of the output of psa_hash_finish(), in bytes. * * This is also the hash size that psa_hash_verify() expects. * * \param alg A hash algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_HASH(\p alg) is true), or an HMAC algorithm * (#PSA_ALG_HMAC(\c hash_alg) where \c hash_alg is a * hash algorithm). * * \return The hash size for the specified hash algorithm. * If the hash algorithm is not recognized, return 0. */ #define PSA_HASH_LENGTH(alg) \ ( \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_MD2 ? 16 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_MD4 ? 16 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_MD5 ? 16 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_RIPEMD160 ? 20 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_1 ? 20 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_224 ? 28 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_256 ? 32 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_384 ? 48 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512 ? 64 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512_224 ? 28 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA_512_256 ? 32 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_224 ? 28 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_256 ? 32 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_384 ? 48 : \ PSA_ALG_HMAC_GET_HASH(alg) == PSA_ALG_SHA3_512 ? 64 : \ 0) /** \def PSA_HASH_MAX_SIZE * * Maximum size of a hash. * * This macro expands to a compile-time constant integer. This value * is the maximum size of a hash in bytes. */ /* Note: for HMAC-SHA-3, the block size is 144 bytes for HMAC-SHA3-226, * 136 bytes for HMAC-SHA3-256, 104 bytes for SHA3-384, 72 bytes for * HMAC-SHA3-512. */ #if defined(MBEDTLS_SHA512_C) #define PSA_HASH_MAX_SIZE 64 #define PSA_HMAC_MAX_HASH_BLOCK_SIZE 128 #else #define PSA_HASH_MAX_SIZE 32 #define PSA_HMAC_MAX_HASH_BLOCK_SIZE 64 #endif /** \def PSA_MAC_MAX_SIZE * * Maximum size of a MAC. * * This macro expands to a compile-time constant integer. This value * is the maximum size of a MAC in bytes. */ /* All non-HMAC MACs have a maximum size that's smaller than the * minimum possible value of PSA_HASH_MAX_SIZE in this implementation. */ /* Note that the encoding of truncated MAC algorithms limits this value * to 64 bytes. */ #define PSA_MAC_MAX_SIZE PSA_HASH_MAX_SIZE /** The length of a tag for an AEAD algorithm, in bytes. * * This macro can be used to allocate a buffer of sufficient size to store the * tag output from psa_aead_finish(). * * See also #PSA_AEAD_TAG_MAX_SIZE. * * \param key_type The type of the AEAD key. * \param key_bits The size of the AEAD key in bits. * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * * \return The tag length for the specified algorithm and key. * If the AEAD algorithm does not have an identified * tag that can be distinguished from the rest of * the ciphertext, return 0. * If the key type or AEAD algorithm is not * recognized, or the parameters are incompatible, * return 0. */ #define PSA_AEAD_TAG_LENGTH(key_type, key_bits, alg) \ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 ? \ PSA_ALG_AEAD_GET_TAG_LENGTH(alg) : \ ((void) (key_bits), 0)) /** The maximum tag size for all supported AEAD algorithms, in bytes. * * See also #PSA_AEAD_TAG_LENGTH(\p key_type, \p key_bits, \p alg). */ #define PSA_AEAD_TAG_MAX_SIZE 16 /* The maximum size of an RSA key on this implementation, in bits. * This is a vendor-specific macro. * * Mbed TLS does not set a hard limit on the size of RSA keys: any key * whose parameters fit in a bignum is accepted. However large keys can * induce a large memory usage and long computation times. Unlike other * auxiliary macros in this file and in crypto.h, which reflect how the * library is configured, this macro defines how the library is * configured. This implementation refuses to import or generate an * RSA key whose size is larger than the value defined here. * * Note that an implementation may set different size limits for different * operations, and does not need to accept all key sizes up to the limit. */ #define PSA_VENDOR_RSA_MAX_KEY_BITS 4096 /* The maximum size of an ECC key on this implementation, in bits. * This is a vendor-specific macro. */ #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 521 #elif defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 512 #elif defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 448 #elif defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 384 #elif defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 384 #elif defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 256 #elif defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 256 #elif defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 256 #elif defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 255 #elif defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 224 #elif defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 224 #elif defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 192 #elif defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) #define PSA_VENDOR_ECC_MAX_CURVE_BITS 192 #else #define PSA_VENDOR_ECC_MAX_CURVE_BITS 0 #endif /** This macro returns the maximum supported length of the PSK for the * TLS-1.2 PSK-to-MS key derivation * (#PSA_ALG_TLS12_PSK_TO_MS(\c hash_alg)). * * The maximum supported length does not depend on the chosen hash algorithm. * * Quoting RFC 4279, Sect 5.3: * TLS implementations supporting these ciphersuites MUST support * arbitrary PSK identities up to 128 octets in length, and arbitrary * PSKs up to 64 octets in length. Supporting longer identities and * keys is RECOMMENDED. * * Therefore, no implementation should define a value smaller than 64 * for #PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE. */ #define PSA_TLS12_PSK_TO_MS_PSK_MAX_SIZE 128 /** The maximum size of a block cipher. */ #define PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE 16 /** The size of the output of psa_mac_sign_finish(), in bytes. * * This is also the MAC size that psa_mac_verify_finish() expects. * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param key_type The type of the MAC key. * \param key_bits The size of the MAC key in bits. * \param alg A MAC algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_MAC(\p alg) is true). * * \return The MAC size for the specified algorithm with * the specified key parameters. * \return 0 if the MAC algorithm is not recognized. * \return Either 0 or the correct size for a MAC algorithm that * the implementation recognizes, but does not support. * \return Unspecified if the key parameters are not consistent * with the algorithm. */ #define PSA_MAC_LENGTH(key_type, key_bits, alg) \ ((alg) & PSA_ALG_MAC_TRUNCATION_MASK ? PSA_MAC_TRUNCATED_LENGTH(alg) : \ PSA_ALG_IS_HMAC(alg) ? PSA_HASH_LENGTH(PSA_ALG_HMAC_GET_HASH(alg)) : \ PSA_ALG_IS_BLOCK_CIPHER_MAC(alg) ? PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) : \ ((void)(key_type), (void)(key_bits), 0)) /** The maximum size of the output of psa_aead_encrypt(), in bytes. * * If the size of the ciphertext buffer is at least this large, it is * guaranteed that psa_aead_encrypt() will not fail due to an * insufficient buffer size. Depending on the algorithm, the actual size of * the ciphertext may be smaller. * * See also #PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(\p plaintext_length). * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param key_type A symmetric key type that is * compatible with algorithm \p alg. * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * \param plaintext_length Size of the plaintext in bytes. * * \return The AEAD ciphertext size for the specified * algorithm. * If the key type or AEAD algorithm is not * recognized, or the parameters are incompatible, * return 0. */ #define PSA_AEAD_ENCRYPT_OUTPUT_SIZE(key_type, alg, plaintext_length) \ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 ? \ (plaintext_length) + PSA_ALG_AEAD_GET_TAG_LENGTH(alg) : \ 0) /** A sufficient output buffer size for psa_aead_encrypt(), for any of the * supported key types and AEAD algorithms. * * If the size of the ciphertext buffer is at least this large, it is guaranteed * that psa_aead_encrypt() will not fail due to an insufficient buffer size. * * \note This macro returns a compile-time constant if its arguments are * compile-time constants. * * See also #PSA_AEAD_ENCRYPT_OUTPUT_SIZE(\p key_type, \p alg, * \p plaintext_length). * * \param plaintext_length Size of the plaintext in bytes. * * \return A sufficient output buffer size for any of the * supported key types and AEAD algorithms. * */ #define PSA_AEAD_ENCRYPT_OUTPUT_MAX_SIZE(plaintext_length) \ ((plaintext_length) + PSA_AEAD_TAG_MAX_SIZE) /** The maximum size of the output of psa_aead_decrypt(), in bytes. * * If the size of the plaintext buffer is at least this large, it is * guaranteed that psa_aead_decrypt() will not fail due to an * insufficient buffer size. Depending on the algorithm, the actual size of * the plaintext may be smaller. * * See also #PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(\p ciphertext_length). * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param key_type A symmetric key type that is * compatible with algorithm \p alg. * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * \param ciphertext_length Size of the plaintext in bytes. * * \return The AEAD ciphertext size for the specified * algorithm. * If the key type or AEAD algorithm is not * recognized, or the parameters are incompatible, * return 0. */ #define PSA_AEAD_DECRYPT_OUTPUT_SIZE(key_type, alg, ciphertext_length) \ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 && \ (ciphertext_length) > PSA_ALG_AEAD_GET_TAG_LENGTH(alg) ? \ (ciphertext_length) - PSA_ALG_AEAD_GET_TAG_LENGTH(alg) : \ 0) /** A sufficient output buffer size for psa_aead_decrypt(), for any of the * supported key types and AEAD algorithms. * * If the size of the plaintext buffer is at least this large, it is guaranteed * that psa_aead_decrypt() will not fail due to an insufficient buffer size. * * \note This macro returns a compile-time constant if its arguments are * compile-time constants. * * See also #PSA_AEAD_DECRYPT_OUTPUT_SIZE(\p key_type, \p alg, * \p ciphertext_length). * * \param ciphertext_length Size of the ciphertext in bytes. * * \return A sufficient output buffer size for any of the * supported key types and AEAD algorithms. * */ #define PSA_AEAD_DECRYPT_OUTPUT_MAX_SIZE(ciphertext_length) \ (ciphertext_length) /** The default nonce size for an AEAD algorithm, in bytes. * * This macro can be used to allocate a buffer of sufficient size to * store the nonce output from #psa_aead_generate_nonce(). * * See also #PSA_AEAD_NONCE_MAX_SIZE. * * \note This is not the maximum size of nonce supported as input to * #psa_aead_set_nonce(), #psa_aead_encrypt() or #psa_aead_decrypt(), * just the default size that is generated by #psa_aead_generate_nonce(). * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param key_type A symmetric key type that is compatible with * algorithm \p alg. * * \param alg An AEAD algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * * \return The default nonce size for the specified key type and algorithm. * If the key type or AEAD algorithm is not recognized, * or the parameters are incompatible, return 0. */ #define PSA_AEAD_NONCE_LENGTH(key_type, alg) \ (PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) == 16 ? \ MBEDTLS_PSA_ALG_AEAD_EQUAL(alg, PSA_ALG_CCM) ? 13 : \ MBEDTLS_PSA_ALG_AEAD_EQUAL(alg, PSA_ALG_GCM) ? 12 : \ 0 : \ (key_type) == PSA_KEY_TYPE_CHACHA20 && \ MBEDTLS_PSA_ALG_AEAD_EQUAL(alg, PSA_ALG_CHACHA20_POLY1305) ? 12 : \ 0) /** The maximum default nonce size among all supported pairs of key types and * AEAD algorithms, in bytes. * * This is equal to or greater than any value that #PSA_AEAD_NONCE_LENGTH() * may return. * * \note This is not the maximum size of nonce supported as input to * #psa_aead_set_nonce(), #psa_aead_encrypt() or #psa_aead_decrypt(), * just the largest size that may be generated by * #psa_aead_generate_nonce(). */ #define PSA_AEAD_NONCE_MAX_SIZE 13 /** A sufficient output buffer size for psa_aead_update(). * * If the size of the output buffer is at least this large, it is * guaranteed that psa_aead_update() will not fail due to an * insufficient buffer size. The actual size of the output may be smaller * in any given call. * * See also #PSA_AEAD_UPDATE_OUTPUT_MAX_SIZE(\p input_length). * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param key_type A symmetric key type that is * compatible with algorithm \p alg. * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * \param input_length Size of the input in bytes. * * \return A sufficient output buffer size for the specified * algorithm. * If the key type or AEAD algorithm is not * recognized, or the parameters are incompatible, * return 0. */ /* For all the AEAD modes defined in this specification, it is possible * to emit output without delay. However, hardware may not always be * capable of this. So for modes based on a block cipher, allow the * implementation to delay the output until it has a full block. */ #define PSA_AEAD_UPDATE_OUTPUT_SIZE(key_type, alg, input_length) \ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 ? \ PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER(alg) ? \ PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type), (input_length)) : \ (input_length) : \ 0) /** A sufficient output buffer size for psa_aead_update(), for any of the * supported key types and AEAD algorithms. * * If the size of the output buffer is at least this large, it is guaranteed * that psa_aead_update() will not fail due to an insufficient buffer size. * * See also #PSA_AEAD_UPDATE_OUTPUT_SIZE(\p key_type, \p alg, \p input_length). * * \param input_length Size of the input in bytes. */ #define PSA_AEAD_UPDATE_OUTPUT_MAX_SIZE(input_length) \ (PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE, (input_length))) /** A sufficient ciphertext buffer size for psa_aead_finish(). * * If the size of the ciphertext buffer is at least this large, it is * guaranteed that psa_aead_finish() will not fail due to an * insufficient ciphertext buffer size. The actual size of the output may * be smaller in any given call. * * See also #PSA_AEAD_FINISH_OUTPUT_MAX_SIZE. * * \param key_type A symmetric key type that is compatible with algorithm \p alg. * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * * \return A sufficient ciphertext buffer size for the * specified algorithm. * If the key type or AEAD algorithm is not * recognized, or the parameters are incompatible, * return 0. */ #define PSA_AEAD_FINISH_OUTPUT_SIZE(key_type, alg) \ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 && \ PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER(alg) ? \ PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) : \ 0) /** A sufficient ciphertext buffer size for psa_aead_finish(), for any of the * supported key types and AEAD algorithms. * * See also #PSA_AEAD_FINISH_OUTPUT_SIZE(\p key_type, \p alg). */ #define PSA_AEAD_FINISH_OUTPUT_MAX_SIZE (PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE) /** A sufficient plaintext buffer size for psa_aead_verify(). * * If the size of the plaintext buffer is at least this large, it is * guaranteed that psa_aead_verify() will not fail due to an * insufficient plaintext buffer size. The actual size of the output may * be smaller in any given call. * * See also #PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE. * * \param key_type A symmetric key type that is * compatible with algorithm \p alg. * \param alg An AEAD algorithm * (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_AEAD(\p alg) is true). * * \return A sufficient plaintext buffer size for the * specified algorithm. * If the key type or AEAD algorithm is not * recognized, or the parameters are incompatible, * return 0. */ #define PSA_AEAD_VERIFY_OUTPUT_SIZE(key_type, alg) \ (PSA_AEAD_NONCE_LENGTH(key_type, alg) != 0 && \ PSA_ALG_IS_AEAD_ON_BLOCK_CIPHER(alg) ? \ PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) : \ 0) /** A sufficient plaintext buffer size for psa_aead_verify(), for any of the * supported key types and AEAD algorithms. * * See also #PSA_AEAD_VERIFY_OUTPUT_SIZE(\p key_type, \p alg). */ #define PSA_AEAD_VERIFY_OUTPUT_MAX_SIZE (PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE) #define PSA_RSA_MINIMUM_PADDING_SIZE(alg) \ (PSA_ALG_IS_RSA_OAEP(alg) ? \ 2 * PSA_HASH_LENGTH(PSA_ALG_RSA_OAEP_GET_HASH(alg)) + 1 : \ 11 /*PKCS#1v1.5*/) /** * \brief ECDSA signature size for a given curve bit size * * \param curve_bits Curve size in bits. * \return Signature size in bytes. * * \note This macro returns a compile-time constant if its argument is one. */ #define PSA_ECDSA_SIGNATURE_SIZE(curve_bits) \ (PSA_BITS_TO_BYTES(curve_bits) * 2) /** Sufficient signature buffer size for psa_sign_hash(). * * This macro returns a sufficient buffer size for a signature using a key * of the specified type and size, with the specified algorithm. * Note that the actual size of the signature may be smaller * (some algorithms produce a variable-size signature). * * \warning This function may call its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param key_type An asymmetric key type (this may indifferently be a * key pair type or a public key type). * \param key_bits The size of the key in bits. * \param alg The signature algorithm. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that * psa_sign_hash() will not fail with * #PSA_ERROR_BUFFER_TOO_SMALL. * If the parameters are a valid combination that is not supported, * return either a sensible size or 0. * If the parameters are not valid, the * return value is unspecified. */ #define PSA_SIGN_OUTPUT_SIZE(key_type, key_bits, alg) \ (PSA_KEY_TYPE_IS_RSA(key_type) ? ((void)alg, PSA_BITS_TO_BYTES(key_bits)) : \ PSA_KEY_TYPE_IS_ECC(key_type) ? PSA_ECDSA_SIGNATURE_SIZE(key_bits) : \ ((void)alg, 0)) #define PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE \ PSA_ECDSA_SIGNATURE_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS) /** \def PSA_SIGNATURE_MAX_SIZE * * Maximum size of an asymmetric signature. * * This macro expands to a compile-time constant integer. This value * is the maximum size of a signature in bytes. */ #define PSA_SIGNATURE_MAX_SIZE \ (PSA_BITS_TO_BYTES(PSA_VENDOR_RSA_MAX_KEY_BITS) > PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE ? \ PSA_BITS_TO_BYTES(PSA_VENDOR_RSA_MAX_KEY_BITS) : \ PSA_VENDOR_ECDSA_SIGNATURE_MAX_SIZE) /** Sufficient output buffer size for psa_asymmetric_encrypt(). * * This macro returns a sufficient buffer size for a ciphertext produced using * a key of the specified type and size, with the specified algorithm. * Note that the actual size of the ciphertext may be smaller, depending * on the algorithm. * * \warning This function may call its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param key_type An asymmetric key type (this may indifferently be a * key pair type or a public key type). * \param key_bits The size of the key in bits. * \param alg The asymmetric encryption algorithm. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that * psa_asymmetric_encrypt() will not fail with * #PSA_ERROR_BUFFER_TOO_SMALL. * If the parameters are a valid combination that is not supported, * return either a sensible size or 0. * If the parameters are not valid, the * return value is unspecified. */ #define PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(key_type, key_bits, alg) \ (PSA_KEY_TYPE_IS_RSA(key_type) ? \ ((void)alg, PSA_BITS_TO_BYTES(key_bits)) : \ 0) /** A sufficient output buffer size for psa_asymmetric_encrypt(), for any * supported asymmetric encryption. * * See also #PSA_ASYMMETRIC_ENCRYPT_OUTPUT_SIZE(\p key_type, \p key_bits, \p alg). */ /* This macro assumes that RSA is the only supported asymmetric encryption. */ #define PSA_ASYMMETRIC_ENCRYPT_OUTPUT_MAX_SIZE \ (PSA_BITS_TO_BYTES(PSA_VENDOR_RSA_MAX_KEY_BITS)) /** Sufficient output buffer size for psa_asymmetric_decrypt(). * * This macro returns a sufficient buffer size for a plaintext produced using * a key of the specified type and size, with the specified algorithm. * Note that the actual size of the plaintext may be smaller, depending * on the algorithm. * * \warning This function may call its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param key_type An asymmetric key type (this may indifferently be a * key pair type or a public key type). * \param key_bits The size of the key in bits. * \param alg The asymmetric encryption algorithm. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that * psa_asymmetric_decrypt() will not fail with * #PSA_ERROR_BUFFER_TOO_SMALL. * If the parameters are a valid combination that is not supported, * return either a sensible size or 0. * If the parameters are not valid, the * return value is unspecified. */ #define PSA_ASYMMETRIC_DECRYPT_OUTPUT_SIZE(key_type, key_bits, alg) \ (PSA_KEY_TYPE_IS_RSA(key_type) ? \ PSA_BITS_TO_BYTES(key_bits) - PSA_RSA_MINIMUM_PADDING_SIZE(alg) : \ 0) /** A sufficient output buffer size for psa_asymmetric_decrypt(), for any * supported asymmetric decryption. * * This macro assumes that RSA is the only supported asymmetric encryption. * * See also #PSA_ASYMMETRIC_DECRYPT_OUTPUT_SIZE(\p key_type, \p key_bits, \p alg). */ #define PSA_ASYMMETRIC_DECRYPT_OUTPUT_MAX_SIZE \ (PSA_BITS_TO_BYTES(PSA_VENDOR_RSA_MAX_KEY_BITS)) /* Maximum size of the ASN.1 encoding of an INTEGER with the specified * number of bits. * * This definition assumes that bits <= 2^19 - 9 so that the length field * is at most 3 bytes. The length of the encoding is the length of the * bit string padded to a whole number of bytes plus: * - 1 type byte; * - 1 to 3 length bytes; * - 0 to 1 bytes of leading 0 due to the sign bit. */ #define PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(bits) \ ((bits) / 8 + 5) /* Maximum size of the export encoding of an RSA public key. * Assumes that the public exponent is less than 2^32. * * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER } -- e * * - 4 bytes of SEQUENCE overhead; * - n : INTEGER; * - 7 bytes for the public exponent. */ #define PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(key_bits) \ (PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(key_bits) + 11) /* Maximum size of the export encoding of an RSA key pair. * Assumes thatthe public exponent is less than 2^32 and that the size * difference between the two primes is at most 1 bit. * * RSAPrivateKey ::= SEQUENCE { * version Version, -- 0 * modulus INTEGER, -- N-bit * publicExponent INTEGER, -- 32-bit * privateExponent INTEGER, -- N-bit * prime1 INTEGER, -- N/2-bit * prime2 INTEGER, -- N/2-bit * exponent1 INTEGER, -- N/2-bit * exponent2 INTEGER, -- N/2-bit * coefficient INTEGER, -- N/2-bit * } * * - 4 bytes of SEQUENCE overhead; * - 3 bytes of version; * - 7 half-size INTEGERs plus 2 full-size INTEGERs, * overapproximated as 9 half-size INTEGERS; * - 7 bytes for the public exponent. */ #define PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(key_bits) \ (9 * PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE((key_bits) / 2 + 1) + 14) /* Maximum size of the export encoding of a DSA public key. * * SubjectPublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * subjectPublicKey BIT STRING } -- contains DSAPublicKey * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters Dss-Parms } -- SEQUENCE of 3 INTEGERs * DSAPublicKey ::= INTEGER -- public key, Y * * - 3 * 4 bytes of SEQUENCE overhead; * - 1 + 1 + 7 bytes of algorithm (DSA OID); * - 4 bytes of BIT STRING overhead; * - 3 full-size INTEGERs (p, g, y); * - 1 + 1 + 32 bytes for 1 sub-size INTEGER (q <= 256 bits). */ #define PSA_KEY_EXPORT_DSA_PUBLIC_KEY_MAX_SIZE(key_bits) \ (PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(key_bits) * 3 + 59) /* Maximum size of the export encoding of a DSA key pair. * * DSAPrivateKey ::= SEQUENCE { * version Version, -- 0 * prime INTEGER, -- p * subprime INTEGER, -- q * generator INTEGER, -- g * public INTEGER, -- y * private INTEGER, -- x * } * * - 4 bytes of SEQUENCE overhead; * - 3 bytes of version; * - 3 full-size INTEGERs (p, g, y); * - 2 * (1 + 1 + 32) bytes for 2 sub-size INTEGERs (q, x <= 256 bits). */ #define PSA_KEY_EXPORT_DSA_KEY_PAIR_MAX_SIZE(key_bits) \ (PSA_KEY_EXPORT_ASN1_INTEGER_MAX_SIZE(key_bits) * 3 + 75) /* Maximum size of the export encoding of an ECC public key. * * The representation of an ECC public key is: * - The byte 0x04; * - `x_P` as a `ceiling(m/8)`-byte string, big-endian; * - `y_P` as a `ceiling(m/8)`-byte string, big-endian; * - where m is the bit size associated with the curve. * * - 1 byte + 2 * point size. */ #define PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(key_bits) \ (2 * PSA_BITS_TO_BYTES(key_bits) + 1) /* Maximum size of the export encoding of an ECC key pair. * * An ECC key pair is represented by the secret value. */ #define PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(key_bits) \ (PSA_BITS_TO_BYTES(key_bits)) /** Sufficient output buffer size for psa_export_key() or * psa_export_public_key(). * * This macro returns a compile-time constant if its arguments are * compile-time constants. * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * The following code illustrates how to allocate enough memory to export * a key by querying the key type and size at runtime. * \code{c} * psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; * psa_status_t status; * status = psa_get_key_attributes(key, &attributes); * if (status != PSA_SUCCESS) handle_error(...); * psa_key_type_t key_type = psa_get_key_type(&attributes); * size_t key_bits = psa_get_key_bits(&attributes); * size_t buffer_size = PSA_EXPORT_KEY_OUTPUT_SIZE(key_type, key_bits); * psa_reset_key_attributes(&attributes); * uint8_t *buffer = malloc(buffer_size); * if (buffer == NULL) handle_error(...); * size_t buffer_length; * status = psa_export_key(key, buffer, buffer_size, &buffer_length); * if (status != PSA_SUCCESS) handle_error(...); * \endcode * * \param key_type A supported key type. * \param key_bits The size of the key in bits. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that * psa_export_key() or psa_export_public_key() will not fail with * #PSA_ERROR_BUFFER_TOO_SMALL. * If the parameters are a valid combination that is not supported, * return either a sensible size or 0. * If the parameters are not valid, the return value is unspecified. */ #define PSA_EXPORT_KEY_OUTPUT_SIZE(key_type, key_bits) \ (PSA_KEY_TYPE_IS_UNSTRUCTURED(key_type) ? PSA_BITS_TO_BYTES(key_bits) : \ (key_type) == PSA_KEY_TYPE_RSA_KEY_PAIR ? PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(key_bits) : \ (key_type) == PSA_KEY_TYPE_RSA_PUBLIC_KEY ? PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(key_bits) : \ (key_type) == PSA_KEY_TYPE_DSA_KEY_PAIR ? PSA_KEY_EXPORT_DSA_KEY_PAIR_MAX_SIZE(key_bits) : \ (key_type) == PSA_KEY_TYPE_DSA_PUBLIC_KEY ? PSA_KEY_EXPORT_DSA_PUBLIC_KEY_MAX_SIZE(key_bits) : \ PSA_KEY_TYPE_IS_ECC_KEY_PAIR(key_type) ? PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(key_bits) : \ PSA_KEY_TYPE_IS_ECC_PUBLIC_KEY(key_type) ? PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(key_bits) : \ 0) /** Sufficient output buffer size for psa_export_public_key(). * * This macro returns a compile-time constant if its arguments are * compile-time constants. * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * The following code illustrates how to allocate enough memory to export * a public key by querying the key type and size at runtime. * \code{c} * psa_key_attributes_t attributes = PSA_KEY_ATTRIBUTES_INIT; * psa_status_t status; * status = psa_get_key_attributes(key, &attributes); * if (status != PSA_SUCCESS) handle_error(...); * psa_key_type_t key_type = psa_get_key_type(&attributes); * size_t key_bits = psa_get_key_bits(&attributes); * size_t buffer_size = PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(key_type, key_bits); * psa_reset_key_attributes(&attributes); * uint8_t *buffer = malloc(buffer_size); * if (buffer == NULL) handle_error(...); * size_t buffer_length; * status = psa_export_public_key(key, buffer, buffer_size, &buffer_length); * if (status != PSA_SUCCESS) handle_error(...); * \endcode * * \param key_type A public key or key pair key type. * \param key_bits The size of the key in bits. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that * psa_export_public_key() will not fail with * #PSA_ERROR_BUFFER_TOO_SMALL. * If the parameters are a valid combination that is not * supported, return either a sensible size or 0. * If the parameters are not valid, * the return value is unspecified. * * If the parameters are valid and supported, * return the same result as * #PSA_EXPORT_KEY_OUTPUT_SIZE( * \p #PSA_KEY_TYPE_PUBLIC_KEY_OF_KEY_PAIR(\p key_type), * \p key_bits). */ #define PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(key_type, key_bits) \ (PSA_KEY_TYPE_IS_RSA(key_type) ? PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(key_bits) : \ PSA_KEY_TYPE_IS_ECC(key_type) ? PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(key_bits) : \ 0) /** Sufficient buffer size for exporting any asymmetric key pair. * * This macro expands to a compile-time constant integer. This value is * a sufficient buffer size when calling psa_export_key() to export any * asymmetric key pair, regardless of the exact key type and key size. * * See also #PSA_EXPORT_KEY_OUTPUT_SIZE(\p key_type, \p key_bits). */ #define PSA_EXPORT_KEY_PAIR_MAX_SIZE \ (PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS) > \ PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS) ? \ PSA_KEY_EXPORT_RSA_KEY_PAIR_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS) : \ PSA_KEY_EXPORT_ECC_KEY_PAIR_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)) /** Sufficient buffer size for exporting any asymmetric public key. * * This macro expands to a compile-time constant integer. This value is * a sufficient buffer size when calling psa_export_key() or * psa_export_public_key() to export any asymmetric public key, * regardless of the exact key type and key size. * * See also #PSA_EXPORT_PUBLIC_KEY_OUTPUT_SIZE(\p key_type, \p key_bits). */ #define PSA_EXPORT_PUBLIC_KEY_MAX_SIZE \ (PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS) > \ PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS) ? \ PSA_KEY_EXPORT_RSA_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_RSA_MAX_KEY_BITS) : \ PSA_KEY_EXPORT_ECC_PUBLIC_KEY_MAX_SIZE(PSA_VENDOR_ECC_MAX_CURVE_BITS)) /** Sufficient output buffer size for psa_raw_key_agreement(). * * This macro returns a compile-time constant if its arguments are * compile-time constants. * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * See also #PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE. * * \param key_type A supported key type. * \param key_bits The size of the key in bits. * * \return If the parameters are valid and supported, return * a buffer size in bytes that guarantees that * psa_raw_key_agreement() will not fail with * #PSA_ERROR_BUFFER_TOO_SMALL. * If the parameters are a valid combination that * is not supported, return either a sensible size or 0. * If the parameters are not valid, * the return value is unspecified. */ /* FFDH is not yet supported in PSA. */ #define PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(key_type, key_bits) \ (PSA_KEY_TYPE_IS_ECC_KEY_PAIR(key_type) ? \ PSA_BITS_TO_BYTES(key_bits) : \ 0) /** Maximum size of the output from psa_raw_key_agreement(). * * This macro expands to a compile-time constant integer. This value is the * maximum size of the output any raw key agreement algorithm, in bytes. * * See also #PSA_RAW_KEY_AGREEMENT_OUTPUT_SIZE(\p key_type, \p key_bits). */ #define PSA_RAW_KEY_AGREEMENT_OUTPUT_MAX_SIZE \ (PSA_BITS_TO_BYTES(PSA_VENDOR_ECC_MAX_CURVE_BITS)) /** The default IV size for a cipher algorithm, in bytes. * * The IV that is generated as part of a call to #psa_cipher_encrypt() is always * the default IV length for the algorithm. * * This macro can be used to allocate a buffer of sufficient size to * store the IV output from #psa_cipher_generate_iv() when using * a multi-part cipher operation. * * See also #PSA_CIPHER_IV_MAX_SIZE. * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param key_type A symmetric key type that is compatible with algorithm \p alg. * * \param alg A cipher algorithm (\c PSA_ALG_XXX value such that #PSA_ALG_IS_CIPHER(\p alg) is true). * * \return The default IV size for the specified key type and algorithm. * If the algorithm does not use an IV, return 0. * If the key type or cipher algorithm is not recognized, * or the parameters are incompatible, return 0. */ #define PSA_CIPHER_IV_LENGTH(key_type, alg) \ (PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) > 1 && \ ((alg) == PSA_ALG_CTR || \ (alg) == PSA_ALG_CFB || \ (alg) == PSA_ALG_OFB || \ (alg) == PSA_ALG_XTS || \ (alg) == PSA_ALG_CBC_NO_PADDING || \ (alg) == PSA_ALG_CBC_PKCS7) ? PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) : \ (key_type) == PSA_KEY_TYPE_CHACHA20 && \ (alg) == PSA_ALG_STREAM_CIPHER ? 12 : \ 0) /** The maximum IV size for all supported cipher algorithms, in bytes. * * See also #PSA_CIPHER_IV_LENGTH(). */ #define PSA_CIPHER_IV_MAX_SIZE 16 /** The maximum size of the output of psa_cipher_encrypt(), in bytes. * * If the size of the output buffer is at least this large, it is guaranteed * that psa_cipher_encrypt() will not fail due to an insufficient buffer size. * Depending on the algorithm, the actual size of the output might be smaller. * * See also #PSA_CIPHER_ENCRYPT_OUTPUT_MAX_SIZE(\p input_length). * * \warning This macro may evaluate its arguments multiple times or * zero times, so you should not pass arguments that contain * side effects. * * \param key_type A symmetric key type that is compatible with algorithm * alg. * \param alg A cipher algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_CIPHER(\p alg) is true). * \param input_length Size of the input in bytes. * * \return A sufficient output size for the specified key type and * algorithm. If the key type or cipher algorithm is not * recognized, or the parameters are incompatible, * return 0. */ #define PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(key_type, alg, input_length) \ (alg == PSA_ALG_CBC_PKCS7 ? \ PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type), \ (input_length) + 1) + \ PSA_CIPHER_IV_LENGTH((key_type), (alg)) : \ (PSA_ALG_IS_CIPHER(alg) ? \ (input_length) + PSA_CIPHER_IV_LENGTH((key_type), (alg)) : \ 0)) /** A sufficient output buffer size for psa_cipher_encrypt(), for any of the * supported key types and cipher algorithms. * * If the size of the output buffer is at least this large, it is guaranteed * that psa_cipher_encrypt() will not fail due to an insufficient buffer size. * * See also #PSA_CIPHER_ENCRYPT_OUTPUT_SIZE(\p key_type, \p alg, \p input_length). * * \param input_length Size of the input in bytes. * */ #define PSA_CIPHER_ENCRYPT_OUTPUT_MAX_SIZE(input_length) \ (PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE, \ (input_length) + 1) + \ PSA_CIPHER_IV_MAX_SIZE) /** The maximum size of the output of psa_cipher_decrypt(), in bytes. * * If the size of the output buffer is at least this large, it is guaranteed * that psa_cipher_decrypt() will not fail due to an insufficient buffer size. * Depending on the algorithm, the actual size of the output might be smaller. * * See also #PSA_CIPHER_DECRYPT_OUTPUT_MAX_SIZE(\p input_length). * * \param key_type A symmetric key type that is compatible with algorithm * alg. * \param alg A cipher algorithm (\c PSA_ALG_XXX value such that * #PSA_ALG_IS_CIPHER(\p alg) is true). * \param input_length Size of the input in bytes. * * \return A sufficient output size for the specified key type and * algorithm. If the key type or cipher algorithm is not * recognized, or the parameters are incompatible, * return 0. */ #define PSA_CIPHER_DECRYPT_OUTPUT_SIZE(key_type, alg, input_length) \ (PSA_ALG_IS_CIPHER(alg) && \ ((key_type) & PSA_KEY_TYPE_CATEGORY_MASK) == PSA_KEY_TYPE_CATEGORY_SYMMETRIC ? \ (input_length) : \ 0) /** A sufficient output buffer size for psa_cipher_decrypt(), for any of the * supported key types and cipher algorithms. * * If the size of the output buffer is at least this large, it is guaranteed * that psa_cipher_decrypt() will not fail due to an insufficient buffer size. * * See also #PSA_CIPHER_DECRYPT_OUTPUT_SIZE(\p key_type, \p alg, \p input_length). * * \param input_length Size of the input in bytes. */ #define PSA_CIPHER_DECRYPT_OUTPUT_MAX_SIZE(input_length) \ (input_length) /** A sufficient output buffer size for psa_cipher_update(). * * If the size of the output buffer is at least this large, it is guaranteed * that psa_cipher_update() will not fail due to an insufficient buffer size. * The actual size of the output might be smaller in any given call. * * See also #PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(\p input_length). * * \param key_type A symmetric key type that is compatible with algorithm * alg. * \param alg A cipher algorithm (PSA_ALG_XXX value such that * #PSA_ALG_IS_CIPHER(\p alg) is true). * \param input_length Size of the input in bytes. * * \return A sufficient output size for the specified key type and * algorithm. If the key type or cipher algorithm is not * recognized, or the parameters are incompatible, return 0. */ #define PSA_CIPHER_UPDATE_OUTPUT_SIZE(key_type, alg, input_length) \ (PSA_ALG_IS_CIPHER(alg) ? \ (((alg) == PSA_ALG_CBC_PKCS7 || \ (alg) == PSA_ALG_CBC_NO_PADDING || \ (alg) == PSA_ALG_ECB_NO_PADDING) ? \ PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type), \ input_length) : \ (input_length)) : \ 0) /** A sufficient output buffer size for psa_cipher_update(), for any of the * supported key types and cipher algorithms. * * If the size of the output buffer is at least this large, it is guaranteed * that psa_cipher_update() will not fail due to an insufficient buffer size. * * See also #PSA_CIPHER_UPDATE_OUTPUT_SIZE(\p key_type, \p alg, \p input_length). * * \param input_length Size of the input in bytes. */ #define PSA_CIPHER_UPDATE_OUTPUT_MAX_SIZE(input_length) \ (PSA_ROUND_UP_TO_MULTIPLE(PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE, input_length)) /** A sufficient ciphertext buffer size for psa_cipher_finish(). * * If the size of the ciphertext buffer is at least this large, it is * guaranteed that psa_cipher_finish() will not fail due to an insufficient * ciphertext buffer size. The actual size of the output might be smaller in * any given call. * * See also #PSA_CIPHER_FINISH_OUTPUT_MAX_SIZE(). * * \param key_type A symmetric key type that is compatible with algorithm * alg. * \param alg A cipher algorithm (PSA_ALG_XXX value such that * #PSA_ALG_IS_CIPHER(\p alg) is true). * \return A sufficient output size for the specified key type and * algorithm. If the key type or cipher algorithm is not * recognized, or the parameters are incompatible, return 0. */ #define PSA_CIPHER_FINISH_OUTPUT_SIZE(key_type, alg) \ (PSA_ALG_IS_CIPHER(alg) ? \ (alg == PSA_ALG_CBC_PKCS7 ? \ PSA_BLOCK_CIPHER_BLOCK_LENGTH(key_type) : \ 0) : \ 0) /** A sufficient ciphertext buffer size for psa_cipher_finish(), for any of the * supported key types and cipher algorithms. * * See also #PSA_CIPHER_FINISH_OUTPUT_SIZE(\p key_type, \p alg). */ #define PSA_CIPHER_FINISH_OUTPUT_MAX_SIZE \ (PSA_BLOCK_CIPHER_BLOCK_MAX_SIZE) #endif /* PSA_CRYPTO_SIZES_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/psa/crypto_driver_contexts_composites.h
/* * Declaration of context structures for use with the PSA driver wrapper * interface. This file contains the context structures for 'composite' * operations, i.e. those operations which need to make use of other operations * from the primitives (crypto_driver_contexts_primitives.h) * * Warning: This file will be auto-generated in the future. * * \note This file may not be included directly. Applications must * include psa/crypto.h. * * \note This header and its content is not part of the Mbed TLS API and * applications must not depend on it. Its main purpose is to define the * multi-part state objects of the PSA drivers included in the cryptographic * library. The definition of these objects are then used by crypto_struct.h * to define the implementation-defined types of PSA multi-part state objects. */ /* Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef PSA_CRYPTO_DRIVER_CONTEXTS_COMPOSITES_H #define PSA_CRYPTO_DRIVER_CONTEXTS_COMPOSITES_H #include "psa/crypto_driver_common.h" /* Include the context structure definitions for those drivers that were * declared during the autogeneration process. */ /* Include the context structure definitions for the Mbed TLS software drivers */ #include "psa/crypto_builtin_composites.h" /* Define the context to be used for an operation that is executed through the * PSA Driver wrapper layer as the union of all possible driver's contexts. * * The union members are the driver's context structures, and the member names * are formatted as `'drivername'_ctx`. This allows for procedural generation * of both this file and the content of psa_crypto_driver_wrappers.c */ typedef union { unsigned dummy; /* Make sure this union is always non-empty */ mbedtls_psa_mac_operation_t mbedtls_ctx; #if defined(PSA_CRYPTO_DRIVER_TEST) mbedtls_transparent_test_driver_mac_operation_t transparent_test_driver_ctx; mbedtls_opaque_test_driver_mac_operation_t opaque_test_driver_ctx; #endif } psa_driver_mac_context_t; #endif /* PSA_CRYPTO_DRIVER_CONTEXTS_COMPOSITES_H */ /* End of automatically generated file. */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/aes.h
/** * \file aes.h * * \brief This file contains AES definitions and functions. * * The Advanced Encryption Standard (AES) specifies a FIPS-approved * cryptographic algorithm that can be used to protect electronic * data. * * The AES algorithm is a symmetric block cipher that can * encrypt and decrypt information. For more information, see * <em>FIPS Publication 197: Advanced Encryption Standard</em> and * <em>ISO/IEC 18033-2:2006: Information technology -- Security * techniques -- Encryption algorithms -- Part 2: Asymmetric * ciphers</em>. * * The AES-XTS block mode is standardized by NIST SP 800-38E * <https://nvlpubs.nist.gov/nistpubs/legacy/sp/nistspecialpublication800-38e.pdf> * and described in detail by IEEE P1619 * <https://ieeexplore.ieee.org/servlet/opac?punumber=4375278>. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_AES_H #define MBEDTLS_AES_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include <stddef.h> #include <stdint.h> /* padlock.c and aesni.c rely on these values! */ #define MBEDTLS_AES_ENCRYPT 1 /**< AES encryption. */ #define MBEDTLS_AES_DECRYPT 0 /**< AES decryption. */ /* Error codes in range 0x0020-0x0022 */ #define MBEDTLS_ERR_AES_INVALID_KEY_LENGTH -0x0020 /**< Invalid key length. */ #define MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH -0x0022 /**< Invalid data input length. */ /* Error codes in range 0x0021-0x0025 */ #define MBEDTLS_ERR_AES_BAD_INPUT_DATA -0x0021 /**< Invalid input data. */ /* MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE is deprecated and should not be used. */ #define MBEDTLS_ERR_AES_FEATURE_UNAVAILABLE -0x0023 /**< Feature not available. For example, an unsupported AES key size. */ /* MBEDTLS_ERR_AES_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_AES_HW_ACCEL_FAILED -0x0025 /**< AES hardware accelerator failed. */ #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ !defined(inline) && !defined(__cplusplus) #define inline __inline #endif #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_AES_ALT) // Regular implementation // /** * \brief The AES context-type definition. */ typedef struct mbedtls_aes_context { int nr; /*!< The number of rounds. */ uint32_t *rk; /*!< AES round keys. */ uint32_t buf[68]; /*!< Unaligned data buffer. This buffer can hold 32 extra Bytes, which can be used for one of the following purposes: <ul><li>Alignment if VIA padlock is used.</li> <li>Simplifying key expansion in the 256-bit case by generating an extra round key. </li></ul> */ } mbedtls_aes_context; #if defined(MBEDTLS_CIPHER_MODE_XTS) /** * \brief The AES XTS context-type definition. */ typedef struct mbedtls_aes_xts_context { mbedtls_aes_context crypt; /*!< The AES context to use for AES block encryption or decryption. */ mbedtls_aes_context tweak; /*!< The AES context used for tweak computation. */ } mbedtls_aes_xts_context; #endif /* MBEDTLS_CIPHER_MODE_XTS */ #else /* MBEDTLS_AES_ALT */ #include "aes_alt.h" #endif /* MBEDTLS_AES_ALT */ /** * \brief This function initializes the specified AES context. * * It must be the first API called before using * the context. * * \param ctx The AES context to initialize. This must not be \c NULL. */ void mbedtls_aes_init( mbedtls_aes_context *ctx ); /** * \brief This function releases and clears the specified AES context. * * \param ctx The AES context to clear. * If this is \c NULL, this function does nothing. * Otherwise, the context must have been at least initialized. */ void mbedtls_aes_free( mbedtls_aes_context *ctx ); #if defined(MBEDTLS_CIPHER_MODE_XTS) /** * \brief This function initializes the specified AES XTS context. * * It must be the first API called before using * the context. * * \param ctx The AES XTS context to initialize. This must not be \c NULL. */ void mbedtls_aes_xts_init( mbedtls_aes_xts_context *ctx ); /** * \brief This function releases and clears the specified AES XTS context. * * \param ctx The AES XTS context to clear. * If this is \c NULL, this function does nothing. * Otherwise, the context must have been at least initialized. */ void mbedtls_aes_xts_free( mbedtls_aes_xts_context *ctx ); #endif /* MBEDTLS_CIPHER_MODE_XTS */ /** * \brief This function sets the encryption key. * * \param ctx The AES context to which the key should be bound. * It must be initialized. * \param key The encryption key. * This must be a readable buffer of size \p keybits bits. * \param keybits The size of data passed in bits. Valid options are: * <ul><li>128 bits</li> * <li>192 bits</li> * <li>256 bits</li></ul> * * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ int mbedtls_aes_setkey_enc( mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits ); /** * \brief This function sets the decryption key. * * \param ctx The AES context to which the key should be bound. * It must be initialized. * \param key The decryption key. * This must be a readable buffer of size \p keybits bits. * \param keybits The size of data passed. Valid options are: * <ul><li>128 bits</li> * <li>192 bits</li> * <li>256 bits</li></ul> * * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ int mbedtls_aes_setkey_dec( mbedtls_aes_context *ctx, const unsigned char *key, unsigned int keybits ); #if defined(MBEDTLS_CIPHER_MODE_XTS) /** * \brief This function prepares an XTS context for encryption and * sets the encryption key. * * \param ctx The AES XTS context to which the key should be bound. * It must be initialized. * \param key The encryption key. This is comprised of the XTS key1 * concatenated with the XTS key2. * This must be a readable buffer of size \p keybits bits. * \param keybits The size of \p key passed in bits. Valid options are: * <ul><li>256 bits (each of key1 and key2 is a 128-bit key)</li> * <li>512 bits (each of key1 and key2 is a 256-bit key)</li></ul> * * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ int mbedtls_aes_xts_setkey_enc( mbedtls_aes_xts_context *ctx, const unsigned char *key, unsigned int keybits ); /** * \brief This function prepares an XTS context for decryption and * sets the decryption key. * * \param ctx The AES XTS context to which the key should be bound. * It must be initialized. * \param key The decryption key. This is comprised of the XTS key1 * concatenated with the XTS key2. * This must be a readable buffer of size \p keybits bits. * \param keybits The size of \p key passed in bits. Valid options are: * <ul><li>256 bits (each of key1 and key2 is a 128-bit key)</li> * <li>512 bits (each of key1 and key2 is a 256-bit key)</li></ul> * * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_KEY_LENGTH on failure. */ int mbedtls_aes_xts_setkey_dec( mbedtls_aes_xts_context *ctx, const unsigned char *key, unsigned int keybits ); #endif /* MBEDTLS_CIPHER_MODE_XTS */ /** * \brief This function performs an AES single-block encryption or * decryption operation. * * It performs the operation defined in the \p mode parameter * (encrypt or decrypt), on the input data buffer defined in * the \p input parameter. * * mbedtls_aes_init(), and either mbedtls_aes_setkey_enc() or * mbedtls_aes_setkey_dec() must be called before the first * call to this API with the same context. * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or * #MBEDTLS_AES_DECRYPT. * \param input The buffer holding the input data. * It must be readable and at least \c 16 Bytes long. * \param output The buffer where the output data will be written. * It must be writeable and at least \c 16 Bytes long. * \return \c 0 on success. */ int mbedtls_aes_crypt_ecb( mbedtls_aes_context *ctx, int mode, const unsigned char input[16], unsigned char output[16] ); #if defined(MBEDTLS_CIPHER_MODE_CBC) /** * \brief This function performs an AES-CBC encryption or decryption operation * on full blocks. * * It performs the operation defined in the \p mode * parameter (encrypt/decrypt), on the input data buffer defined in * the \p input parameter. * * It can be called as many times as needed, until all the input * data is processed. mbedtls_aes_init(), and either * mbedtls_aes_setkey_enc() or mbedtls_aes_setkey_dec() must be called * before the first call to this API with the same context. * * \note This function operates on full blocks, that is, the input size * must be a multiple of the AES block size of \c 16 Bytes. * * \note Upon exit, the content of the IV is updated so that you can * call the same function again on the next * block(s) of data and get the same result as if it was * encrypted in one call. This allows a "streaming" usage. * If you need to retain the contents of the IV, you should * either save it manually or use the cipher module instead. * * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or * #MBEDTLS_AES_DECRYPT. * \param length The length of the input data in Bytes. This must be a * multiple of the block size (\c 16 Bytes). * \param iv Initialization vector (updated after use). * It must be a readable and writeable buffer of \c 16 Bytes. * \param input The buffer holding the input data. * It must be readable and of size \p length Bytes. * \param output The buffer holding the output data. * It must be writeable and of size \p length Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH * on failure. */ int mbedtls_aes_crypt_cbc( mbedtls_aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_XTS) /** * \brief This function performs an AES-XTS encryption or decryption * operation for an entire XTS data unit. * * AES-XTS encrypts or decrypts blocks based on their location as * defined by a data unit number. The data unit number must be * provided by \p data_unit. * * NIST SP 800-38E limits the maximum size of a data unit to 2^20 * AES blocks. If the data unit is larger than this, this function * returns #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH. * * \param ctx The AES XTS context to use for AES XTS operations. * It must be initialized and bound to a key. * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or * #MBEDTLS_AES_DECRYPT. * \param length The length of a data unit in Bytes. This can be any * length between 16 bytes and 2^24 bytes inclusive * (between 1 and 2^20 block cipher blocks). * \param data_unit The address of the data unit encoded as an array of 16 * bytes in little-endian format. For disk encryption, this * is typically the index of the block device sector that * contains the data. * \param input The buffer holding the input data (which is an entire * data unit). This function reads \p length Bytes from \p * input. * \param output The buffer holding the output data (which is an entire * data unit). This function writes \p length Bytes to \p * output. * * \return \c 0 on success. * \return #MBEDTLS_ERR_AES_INVALID_INPUT_LENGTH if \p length is * smaller than an AES block in size (16 Bytes) or if \p * length is larger than 2^20 blocks (16 MiB). */ int mbedtls_aes_crypt_xts( mbedtls_aes_xts_context *ctx, int mode, size_t length, const unsigned char data_unit[16], const unsigned char *input, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_XTS */ #if defined(MBEDTLS_CIPHER_MODE_CFB) /** * \brief This function performs an AES-CFB128 encryption or decryption * operation. * * It performs the operation defined in the \p mode * parameter (encrypt or decrypt), on the input data buffer * defined in the \p input parameter. * * For CFB, you must set up the context with mbedtls_aes_setkey_enc(), * regardless of whether you are performing an encryption or decryption * operation, that is, regardless of the \p mode parameter. This is * because CFB mode uses the same key schedule for encryption and * decryption. * * \note Upon exit, the content of the IV is updated so that you can * call the same function again on the next * block(s) of data and get the same result as if it was * encrypted in one call. This allows a "streaming" usage. * If you need to retain the contents of the * IV, you must either save it manually or use the cipher * module instead. * * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or * #MBEDTLS_AES_DECRYPT. * \param length The length of the input data in Bytes. * \param iv_off The offset in IV (updated after use). * It must point to a valid \c size_t. * \param iv The initialization vector (updated after use). * It must be a readable and writeable buffer of \c 16 Bytes. * \param input The buffer holding the input data. * It must be readable and of size \p length Bytes. * \param output The buffer holding the output data. * It must be writeable and of size \p length Bytes. * * \return \c 0 on success. */ int mbedtls_aes_crypt_cfb128( mbedtls_aes_context *ctx, int mode, size_t length, size_t *iv_off, unsigned char iv[16], const unsigned char *input, unsigned char *output ); /** * \brief This function performs an AES-CFB8 encryption or decryption * operation. * * It performs the operation defined in the \p mode * parameter (encrypt/decrypt), on the input data buffer defined * in the \p input parameter. * * Due to the nature of CFB, you must use the same key schedule for * both encryption and decryption operations. Therefore, you must * use the context initialized with mbedtls_aes_setkey_enc() for * both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT. * * \note Upon exit, the content of the IV is updated so that you can * call the same function again on the next * block(s) of data and get the same result as if it was * encrypted in one call. This allows a "streaming" usage. * If you need to retain the contents of the * IV, you should either save it manually or use the cipher * module instead. * * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param mode The AES operation: #MBEDTLS_AES_ENCRYPT or * #MBEDTLS_AES_DECRYPT * \param length The length of the input data. * \param iv The initialization vector (updated after use). * It must be a readable and writeable buffer of \c 16 Bytes. * \param input The buffer holding the input data. * It must be readable and of size \p length Bytes. * \param output The buffer holding the output data. * It must be writeable and of size \p length Bytes. * * \return \c 0 on success. */ int mbedtls_aes_crypt_cfb8( mbedtls_aes_context *ctx, int mode, size_t length, unsigned char iv[16], const unsigned char *input, unsigned char *output ); #endif /*MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_OFB) /** * \brief This function performs an AES-OFB (Output Feedback Mode) * encryption or decryption operation. * * For OFB, you must set up the context with * mbedtls_aes_setkey_enc(), regardless of whether you are * performing an encryption or decryption operation. This is * because OFB mode uses the same key schedule for encryption and * decryption. * * The OFB operation is identical for encryption or decryption, * therefore no operation mode needs to be specified. * * \note Upon exit, the content of iv, the Initialisation Vector, is * updated so that you can call the same function again on the next * block(s) of data and get the same result as if it was encrypted * in one call. This allows a "streaming" usage, by initialising * iv_off to 0 before the first call, and preserving its value * between calls. * * For non-streaming use, the iv should be initialised on each call * to a unique value, and iv_off set to 0 on each call. * * If you need to retain the contents of the initialisation vector, * you must either save it manually or use the cipher module * instead. * * \warning For the OFB mode, the initialisation vector must be unique * every encryption operation. Reuse of an initialisation vector * will compromise security. * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param length The length of the input data. * \param iv_off The offset in IV (updated after use). * It must point to a valid \c size_t. * \param iv The initialization vector (updated after use). * It must be a readable and writeable buffer of \c 16 Bytes. * \param input The buffer holding the input data. * It must be readable and of size \p length Bytes. * \param output The buffer holding the output data. * It must be writeable and of size \p length Bytes. * * \return \c 0 on success. */ int mbedtls_aes_crypt_ofb( mbedtls_aes_context *ctx, size_t length, size_t *iv_off, unsigned char iv[16], const unsigned char *input, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_OFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) /** * \brief This function performs an AES-CTR encryption or decryption * operation. * * This function performs the operation defined in the \p mode * parameter (encrypt/decrypt), on the input data buffer * defined in the \p input parameter. * * Due to the nature of CTR, you must use the same key schedule * for both encryption and decryption operations. Therefore, you * must use the context initialized with mbedtls_aes_setkey_enc() * for both #MBEDTLS_AES_ENCRYPT and #MBEDTLS_AES_DECRYPT. * * \warning You must never reuse a nonce value with the same key. Doing so * would void the encryption for the two messages encrypted with * the same nonce and key. * * There are two common strategies for managing nonces with CTR: * * 1. You can handle everything as a single message processed over * successive calls to this function. In that case, you want to * set \p nonce_counter and \p nc_off to 0 for the first call, and * then preserve the values of \p nonce_counter, \p nc_off and \p * stream_block across calls to this function as they will be * updated by this function. * * With this strategy, you must not encrypt more than 2**128 * blocks of data with the same key. * * 2. You can encrypt separate messages by dividing the \p * nonce_counter buffer in two areas: the first one used for a * per-message nonce, handled by yourself, and the second one * updated by this function internally. * * For example, you might reserve the first 12 bytes for the * per-message nonce, and the last 4 bytes for internal use. In that * case, before calling this function on a new message you need to * set the first 12 bytes of \p nonce_counter to your chosen nonce * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p * stream_block to be ignored). That way, you can encrypt at most * 2**96 messages of up to 2**32 blocks each with the same key. * * The per-message nonce (or information sufficient to reconstruct * it) needs to be communicated with the ciphertext and must be unique. * The recommended way to ensure uniqueness is to use a message * counter. An alternative is to generate random nonces, but this * limits the number of messages that can be securely encrypted: * for example, with 96-bit random nonces, you should not encrypt * more than 2**32 messages with the same key. * * Note that for both stategies, sizes are measured in blocks and * that an AES block is 16 bytes. * * \warning Upon return, \p stream_block contains sensitive data. Its * content must not be written to insecure storage and should be * securely discarded as soon as it's no longer needed. * * \param ctx The AES context to use for encryption or decryption. * It must be initialized and bound to a key. * \param length The length of the input data. * \param nc_off The offset in the current \p stream_block, for * resuming within the current cipher stream. The * offset pointer should be 0 at the start of a stream. * It must point to a valid \c size_t. * \param nonce_counter The 128-bit nonce and counter. * It must be a readable-writeable buffer of \c 16 Bytes. * \param stream_block The saved stream block for resuming. This is * overwritten by the function. * It must be a readable-writeable buffer of \c 16 Bytes. * \param input The buffer holding the input data. * It must be readable and of size \p length Bytes. * \param output The buffer holding the output data. * It must be writeable and of size \p length Bytes. * * \return \c 0 on success. */ int mbedtls_aes_crypt_ctr( mbedtls_aes_context *ctx, size_t length, size_t *nc_off, unsigned char nonce_counter[16], unsigned char stream_block[16], const unsigned char *input, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CTR */ /** * \brief Internal AES block encryption function. This is only * exposed to allow overriding it using * \c MBEDTLS_AES_ENCRYPT_ALT. * * \param ctx The AES context to use for encryption. * \param input The plaintext block. * \param output The output (ciphertext) block. * * \return \c 0 on success. */ int mbedtls_internal_aes_encrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ); /** * \brief Internal AES block decryption function. This is only * exposed to allow overriding it using see * \c MBEDTLS_AES_DECRYPT_ALT. * * \param ctx The AES context to use for decryption. * \param input The ciphertext block. * \param output The output (plaintext) block. * * \return \c 0 on success. */ int mbedtls_internal_aes_decrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ); #if !defined(MBEDTLS_DEPRECATED_REMOVED) #if defined(MBEDTLS_DEPRECATED_WARNING) #define MBEDTLS_DEPRECATED __attribute__((deprecated)) #else #define MBEDTLS_DEPRECATED #endif /** * \brief Deprecated internal AES block encryption function * without return value. * * \deprecated Superseded by mbedtls_internal_aes_encrypt() * * \param ctx The AES context to use for encryption. * \param input Plaintext block. * \param output Output (ciphertext) block. */ MBEDTLS_DEPRECATED void mbedtls_aes_encrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ); /** * \brief Deprecated internal AES block decryption function * without return value. * * \deprecated Superseded by mbedtls_internal_aes_decrypt() * * \param ctx The AES context to use for decryption. * \param input Ciphertext block. * \param output Output (plaintext) block. */ MBEDTLS_DEPRECATED void mbedtls_aes_decrypt( mbedtls_aes_context *ctx, const unsigned char input[16], unsigned char output[16] ); #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_aes_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* aes.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/gcm.h
/** * \file gcm.h * * \brief This file contains GCM definitions and functions. * * The Galois/Counter Mode (GCM) for 128-bit block ciphers is defined * in <em>D. McGrew, J. Viega, The Galois/Counter Mode of Operation * (GCM), Natl. Inst. Stand. Technol.</em> * * For more information on GCM, see <em>NIST SP 800-38D: Recommendation for * Block Cipher Modes of Operation: Galois/Counter Mode (GCM) and GMAC</em>. * */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_GCM_H #define MBEDTLS_GCM_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/cipher.h" #include <stdint.h> #define MBEDTLS_GCM_ENCRYPT 1 #define MBEDTLS_GCM_DECRYPT 0 #define MBEDTLS_ERR_GCM_AUTH_FAILED -0x0012 /**< Authenticated decryption failed. */ /* MBEDTLS_ERR_GCM_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_GCM_HW_ACCEL_FAILED -0x0013 /**< GCM hardware accelerator failed. */ #define MBEDTLS_ERR_GCM_BAD_INPUT -0x0014 /**< Bad input parameters to function. */ #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_GCM_ALT) /** * \brief The GCM context structure. */ typedef struct mbedtls_gcm_context { mbedtls_cipher_context_t cipher_ctx; /*!< The cipher context used. */ uint64_t HL[16]; /*!< Precalculated HTable low. */ uint64_t HH[16]; /*!< Precalculated HTable high. */ uint64_t len; /*!< The total length of the encrypted data. */ uint64_t add_len; /*!< The total length of the additional data. */ unsigned char base_ectr[16]; /*!< The first ECTR for tag. */ unsigned char y[16]; /*!< The Y working value. */ unsigned char buf[16]; /*!< The buf working value. */ int mode; /*!< The operation to perform: #MBEDTLS_GCM_ENCRYPT or #MBEDTLS_GCM_DECRYPT. */ } mbedtls_gcm_context; #else /* !MBEDTLS_GCM_ALT */ #include "gcm_alt.h" #endif /* !MBEDTLS_GCM_ALT */ /** * \brief This function initializes the specified GCM context, * to make references valid, and prepares the context * for mbedtls_gcm_setkey() or mbedtls_gcm_free(). * * The function does not bind the GCM context to a particular * cipher, nor set the key. For this purpose, use * mbedtls_gcm_setkey(). * * \param ctx The GCM context to initialize. This must not be \c NULL. */ void mbedtls_gcm_init( mbedtls_gcm_context *ctx ); /** * \brief This function associates a GCM context with a * cipher algorithm and a key. * * \param ctx The GCM context. This must be initialized. * \param cipher The 128-bit block cipher to use. * \param key The encryption key. This must be a readable buffer of at * least \p keybits bits. * \param keybits The key size in bits. Valid options are: * <ul><li>128 bits</li> * <li>192 bits</li> * <li>256 bits</li></ul> * * \return \c 0 on success. * \return A cipher-specific error code on failure. */ int mbedtls_gcm_setkey( mbedtls_gcm_context *ctx, mbedtls_cipher_id_t cipher, const unsigned char *key, unsigned int keybits ); /** * \brief This function performs GCM encryption or decryption of a buffer. * * \note For encryption, the output buffer can be the same as the * input buffer. For decryption, the output buffer cannot be * the same as input buffer. If the buffers overlap, the output * buffer must trail at least 8 Bytes behind the input buffer. * * \warning When this function performs a decryption, it outputs the * authentication tag and does not verify that the data is * authentic. You should use this function to perform encryption * only. For decryption, use mbedtls_gcm_auth_decrypt() instead. * * \param ctx The GCM context to use for encryption or decryption. This * must be initialized. * \param mode The operation to perform: * - #MBEDTLS_GCM_ENCRYPT to perform authenticated encryption. * The ciphertext is written to \p output and the * authentication tag is written to \p tag. * - #MBEDTLS_GCM_DECRYPT to perform decryption. * The plaintext is written to \p output and the * authentication tag is written to \p tag. * Note that this mode is not recommended, because it does * not verify the authenticity of the data. For this reason, * you should use mbedtls_gcm_auth_decrypt() instead of * calling this function in decryption mode. * \param length The length of the input data, which is equal to the length * of the output data. * \param iv The initialization vector. This must be a readable buffer of * at least \p iv_len Bytes. * \param iv_len The length of the IV. * \param add The buffer holding the additional data. This must be of at * least that size in Bytes. * \param add_len The length of the additional data. * \param input The buffer holding the input data. If \p length is greater * than zero, this must be a readable buffer of at least that * size in Bytes. * \param output The buffer for holding the output data. If \p length is greater * than zero, this must be a writable buffer of at least that * size in Bytes. * \param tag_len The length of the tag to generate. * \param tag The buffer for holding the tag. This must be a writable * buffer of at least \p tag_len Bytes. * * \return \c 0 if the encryption or decryption was performed * successfully. Note that in #MBEDTLS_GCM_DECRYPT mode, * this does not indicate that the data is authentic. * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths or pointers are * not valid or a cipher-specific error code if the encryption * or decryption failed. */ int mbedtls_gcm_crypt_and_tag( mbedtls_gcm_context *ctx, int mode, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *input, unsigned char *output, size_t tag_len, unsigned char *tag ); /** * \brief This function performs a GCM authenticated decryption of a * buffer. * * \note For decryption, the output buffer cannot be the same as * input buffer. If the buffers overlap, the output buffer * must trail at least 8 Bytes behind the input buffer. * * \param ctx The GCM context. This must be initialized. * \param length The length of the ciphertext to decrypt, which is also * the length of the decrypted plaintext. * \param iv The initialization vector. This must be a readable buffer * of at least \p iv_len Bytes. * \param iv_len The length of the IV. * \param add The buffer holding the additional data. This must be of at * least that size in Bytes. * \param add_len The length of the additional data. * \param tag The buffer holding the tag to verify. This must be a * readable buffer of at least \p tag_len Bytes. * \param tag_len The length of the tag to verify. * \param input The buffer holding the ciphertext. If \p length is greater * than zero, this must be a readable buffer of at least that * size. * \param output The buffer for holding the decrypted plaintext. If \p length * is greater than zero, this must be a writable buffer of at * least that size. * * \return \c 0 if successful and authenticated. * \return #MBEDTLS_ERR_GCM_AUTH_FAILED if the tag does not match. * \return #MBEDTLS_ERR_GCM_BAD_INPUT if the lengths or pointers are * not valid or a cipher-specific error code if the decryption * failed. */ int mbedtls_gcm_auth_decrypt( mbedtls_gcm_context *ctx, size_t length, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len, const unsigned char *tag, size_t tag_len, const unsigned char *input, unsigned char *output ); /** * \brief This function starts a GCM encryption or decryption * operation. * * \param ctx The GCM context. This must be initialized. * \param mode The operation to perform: #MBEDTLS_GCM_ENCRYPT or * #MBEDTLS_GCM_DECRYPT. * \param iv The initialization vector. This must be a readable buffer of * at least \p iv_len Bytes. * \param iv_len The length of the IV. * \param add The buffer holding the additional data, or \c NULL * if \p add_len is \c 0. * \param add_len The length of the additional data. If \c 0, * \p add may be \c NULL. * * \return \c 0 on success. */ int mbedtls_gcm_starts( mbedtls_gcm_context *ctx, int mode, const unsigned char *iv, size_t iv_len, const unsigned char *add, size_t add_len ); /** * \brief This function feeds an input buffer into an ongoing GCM * encryption or decryption operation. * * ` The function expects input to be a multiple of 16 * Bytes. Only the last call before calling * mbedtls_gcm_finish() can be less than 16 Bytes. * * \note For decryption, the output buffer cannot be the same as * input buffer. If the buffers overlap, the output buffer * must trail at least 8 Bytes behind the input buffer. * * \param ctx The GCM context. This must be initialized. * \param length The length of the input data. This must be a multiple of * 16 except in the last call before mbedtls_gcm_finish(). * \param input The buffer holding the input data. If \p length is greater * than zero, this must be a readable buffer of at least that * size in Bytes. * \param output The buffer for holding the output data. If \p length is * greater than zero, this must be a writable buffer of at * least that size in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure. */ int mbedtls_gcm_update( mbedtls_gcm_context *ctx, size_t length, const unsigned char *input, unsigned char *output ); /** * \brief This function finishes the GCM operation and generates * the authentication tag. * * It wraps up the GCM stream, and generates the * tag. The tag can have a maximum length of 16 Bytes. * * \param ctx The GCM context. This must be initialized. * \param tag The buffer for holding the tag. This must be a writable * buffer of at least \p tag_len Bytes. * \param tag_len The length of the tag to generate. This must be at least * four. * * \return \c 0 on success. * \return #MBEDTLS_ERR_GCM_BAD_INPUT on failure. */ int mbedtls_gcm_finish( mbedtls_gcm_context *ctx, unsigned char *tag, size_t tag_len ); /** * \brief This function clears a GCM context and the underlying * cipher sub-context. * * \param ctx The GCM context to clear. If this is \c NULL, the call has * no effect. Otherwise, this must be initialized. */ void mbedtls_gcm_free( mbedtls_gcm_context *ctx ); #if defined(MBEDTLS_SELF_TEST) /** * \brief The GCM checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_gcm_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* gcm.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/error.h
/** * \file error.h * * \brief Error to string translation */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_ERROR_H #define MBEDTLS_ERROR_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include <stddef.h> #if ( defined(__ARMCC_VERSION) || defined(_MSC_VER) ) && \ !defined(inline) && !defined(__cplusplus) #define inline __inline #endif /** * Error code layout. * * Currently we try to keep all error codes within the negative space of 16 * bits signed integers to support all platforms (-0x0001 - -0x7FFF). In * addition we'd like to give two layers of information on the error if * possible. * * For that purpose the error codes are segmented in the following manner: * * 16 bit error code bit-segmentation * * 1 bit - Unused (sign bit) * 3 bits - High level module ID * 5 bits - Module-dependent error code * 7 bits - Low level module errors * * For historical reasons, low-level error codes are divided in even and odd, * even codes were assigned first, and -1 is reserved for other errors. * * Low-level module errors (0x0002-0x007E, 0x0001-0x007F) * * Module Nr Codes assigned * ERROR 2 0x006E 0x0001 * MPI 7 0x0002-0x0010 * GCM 3 0x0012-0x0014 0x0013-0x0013 * BLOWFISH 3 0x0016-0x0018 0x0017-0x0017 * THREADING 3 0x001A-0x001E * AES 5 0x0020-0x0022 0x0021-0x0025 * CAMELLIA 3 0x0024-0x0026 0x0027-0x0027 * XTEA 2 0x0028-0x0028 0x0029-0x0029 * BASE64 2 0x002A-0x002C * OID 1 0x002E-0x002E 0x000B-0x000B * PADLOCK 1 0x0030-0x0030 * DES 2 0x0032-0x0032 0x0033-0x0033 * CTR_DBRG 4 0x0034-0x003A * ENTROPY 3 0x003C-0x0040 0x003D-0x003F * NET 13 0x0042-0x0052 0x0043-0x0049 * ARIA 4 0x0058-0x005E * ASN1 7 0x0060-0x006C * CMAC 1 0x007A-0x007A * PBKDF2 1 0x007C-0x007C * HMAC_DRBG 4 0x0003-0x0009 * CCM 3 0x000D-0x0011 * ARC4 1 0x0019-0x0019 * MD2 1 0x002B-0x002B * MD4 1 0x002D-0x002D * MD5 1 0x002F-0x002F * RIPEMD160 1 0x0031-0x0031 * SHA1 1 0x0035-0x0035 0x0073-0x0073 * SHA256 1 0x0037-0x0037 0x0074-0x0074 * SHA512 1 0x0039-0x0039 0x0075-0x0075 * CHACHA20 3 0x0051-0x0055 * POLY1305 3 0x0057-0x005B * CHACHAPOLY 2 0x0054-0x0056 * PLATFORM 2 0x0070-0x0072 * * High-level module nr (3 bits - 0x0...-0x7...) * Name ID Nr of Errors * PEM 1 9 * PKCS#12 1 4 (Started from top) * X509 2 20 * PKCS5 2 4 (Started from top) * DHM 3 11 * PK 3 15 (Started from top) * RSA 4 11 * ECP 4 10 (Started from top) * MD 5 5 * HKDF 5 1 (Started from top) * SSL 5 2 (Started from 0x5F00) * CIPHER 6 8 (Started from 0x6080) * SSL 6 24 (Started from top, plus 0x6000) * SSL 7 32 * * Module dependent error code (5 bits 0x.00.-0x.F8.) */ #ifdef __cplusplus extern "C" { #endif #define MBEDTLS_ERR_ERROR_GENERIC_ERROR -0x0001 /**< Generic error */ #define MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED -0x006E /**< This is a bug in the library */ /** * \brief Combines a high-level and low-level error code together. * * Wrapper macro for mbedtls_error_add(). See that function for * more details. */ #define MBEDTLS_ERROR_ADD( high, low ) \ mbedtls_error_add( high, low, __FILE__, __LINE__ ) #if defined(MBEDTLS_TEST_HOOKS) /** * \brief Testing hook called before adding/combining two error codes together. * Only used when invasive testing is enabled via MBEDTLS_TEST_HOOKS. */ extern void (*mbedtls_test_hook_error_add)( int, int, const char *, int ); #endif /** * \brief Combines a high-level and low-level error code together. * * This function can be called directly however it is usually * called via the #MBEDTLS_ERROR_ADD macro. * * While a value of zero is not a negative error code, it is still an * error code (that denotes success) and can be combined with both a * negative error code or another value of zero. * * \note When invasive testing is enabled via #MBEDTLS_TEST_HOOKS, also try to * call \link mbedtls_test_hook_error_add \endlink. * * \param high high-level error code. See error.h for more details. * \param low low-level error code. See error.h for more details. * \param file file where this error code addition occurred. * \param line line where this error code addition occurred. */ static inline int mbedtls_error_add( int high, int low, const char *file, int line ) { #if defined(MBEDTLS_TEST_HOOKS) if( *mbedtls_test_hook_error_add != NULL ) ( *mbedtls_test_hook_error_add )( high, low, file, line ); #endif (void)file; (void)line; return( high + low ); } /** * \brief Translate a mbed TLS error code into a string representation, * Result is truncated if necessary and always includes a terminating * null byte. * * \param errnum error code * \param buffer buffer to place representation in * \param buflen length of the buffer */ void mbedtls_strerror( int errnum, char *buffer, size_t buflen ); /** * \brief Translate the high-level part of an Mbed TLS error code into a string * representation. * * This function returns a const pointer to an un-modifiable string. The caller * must not try to modify the string. It is intended to be used mostly for * logging purposes. * * \param error_code error code * * \return The string representation of the error code, or \c NULL if the error * code is unknown. */ const char * mbedtls_high_level_strerr( int error_code ); /** * \brief Translate the low-level part of an Mbed TLS error code into a string * representation. * * This function returns a const pointer to an un-modifiable string. The caller * must not try to modify the string. It is intended to be used mostly for * logging purposes. * * \param error_code error code * * \return The string representation of the error code, or \c NULL if the error * code is unknown. */ const char * mbedtls_low_level_strerr( int error_code ); #ifdef __cplusplus } #endif #endif /* error.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/aria.h
/** * \file aria.h * * \brief ARIA block cipher * * The ARIA algorithm is a symmetric block cipher that can encrypt and * decrypt information. It is defined by the Korean Agency for * Technology and Standards (KATS) in <em>KS X 1213:2004</em> (in * Korean, but see http://210.104.33.10/ARIA/index-e.html in English) * and also described by the IETF in <em>RFC 5794</em>. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_ARIA_H #define MBEDTLS_ARIA_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include <stddef.h> #include <stdint.h> #include "mbedtls/platform_util.h" #define MBEDTLS_ARIA_ENCRYPT 1 /**< ARIA encryption. */ #define MBEDTLS_ARIA_DECRYPT 0 /**< ARIA decryption. */ #define MBEDTLS_ARIA_BLOCKSIZE 16 /**< ARIA block size in bytes. */ #define MBEDTLS_ARIA_MAX_ROUNDS 16 /**< Maxiumum number of rounds in ARIA. */ #define MBEDTLS_ARIA_MAX_KEYSIZE 32 /**< Maximum size of an ARIA key in bytes. */ #if !defined(MBEDTLS_DEPRECATED_REMOVED) #define MBEDTLS_ERR_ARIA_INVALID_KEY_LENGTH MBEDTLS_DEPRECATED_NUMERIC_CONSTANT( -0x005C ) #endif /* !MBEDTLS_DEPRECATED_REMOVED */ #define MBEDTLS_ERR_ARIA_BAD_INPUT_DATA -0x005C /**< Bad input data. */ #define MBEDTLS_ERR_ARIA_INVALID_INPUT_LENGTH -0x005E /**< Invalid data input length. */ /* MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE is deprecated and should not be used. */ #define MBEDTLS_ERR_ARIA_FEATURE_UNAVAILABLE -0x005A /**< Feature not available. For example, an unsupported ARIA key size. */ /* MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_ARIA_HW_ACCEL_FAILED -0x0058 /**< ARIA hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_ARIA_ALT) // Regular implementation // /** * \brief The ARIA context-type definition. */ typedef struct mbedtls_aria_context { unsigned char nr; /*!< The number of rounds (12, 14 or 16) */ /*! The ARIA round keys. */ uint32_t rk[MBEDTLS_ARIA_MAX_ROUNDS + 1][MBEDTLS_ARIA_BLOCKSIZE / 4]; } mbedtls_aria_context; #else /* MBEDTLS_ARIA_ALT */ #include "aria_alt.h" #endif /* MBEDTLS_ARIA_ALT */ /** * \brief This function initializes the specified ARIA context. * * It must be the first API called before using * the context. * * \param ctx The ARIA context to initialize. This must not be \c NULL. */ void mbedtls_aria_init( mbedtls_aria_context *ctx ); /** * \brief This function releases and clears the specified ARIA context. * * \param ctx The ARIA context to clear. This may be \c NULL, in which * case this function returns immediately. If it is not \c NULL, * it must point to an initialized ARIA context. */ void mbedtls_aria_free( mbedtls_aria_context *ctx ); /** * \brief This function sets the encryption key. * * \param ctx The ARIA context to which the key should be bound. * This must be initialized. * \param key The encryption key. This must be a readable buffer * of size \p keybits Bits. * \param keybits The size of \p key in Bits. Valid options are: * <ul><li>128 bits</li> * <li>192 bits</li> * <li>256 bits</li></ul> * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_aria_setkey_enc( mbedtls_aria_context *ctx, const unsigned char *key, unsigned int keybits ); /** * \brief This function sets the decryption key. * * \param ctx The ARIA context to which the key should be bound. * This must be initialized. * \param key The decryption key. This must be a readable buffer * of size \p keybits Bits. * \param keybits The size of data passed. Valid options are: * <ul><li>128 bits</li> * <li>192 bits</li> * <li>256 bits</li></ul> * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_aria_setkey_dec( mbedtls_aria_context *ctx, const unsigned char *key, unsigned int keybits ); /** * \brief This function performs an ARIA single-block encryption or * decryption operation. * * It performs encryption or decryption (depending on whether * the key was set for encryption on decryption) on the input * data buffer defined in the \p input parameter. * * mbedtls_aria_init(), and either mbedtls_aria_setkey_enc() or * mbedtls_aria_setkey_dec() must be called before the first * call to this API with the same context. * * \param ctx The ARIA context to use for encryption or decryption. * This must be initialized and bound to a key. * \param input The 16-Byte buffer holding the input data. * \param output The 16-Byte buffer holding the output data. * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_aria_crypt_ecb( mbedtls_aria_context *ctx, const unsigned char input[MBEDTLS_ARIA_BLOCKSIZE], unsigned char output[MBEDTLS_ARIA_BLOCKSIZE] ); #if defined(MBEDTLS_CIPHER_MODE_CBC) /** * \brief This function performs an ARIA-CBC encryption or decryption operation * on full blocks. * * It performs the operation defined in the \p mode * parameter (encrypt/decrypt), on the input data buffer defined in * the \p input parameter. * * It can be called as many times as needed, until all the input * data is processed. mbedtls_aria_init(), and either * mbedtls_aria_setkey_enc() or mbedtls_aria_setkey_dec() must be called * before the first call to this API with the same context. * * \note This function operates on aligned blocks, that is, the input size * must be a multiple of the ARIA block size of 16 Bytes. * * \note Upon exit, the content of the IV is updated so that you can * call the same function again on the next * block(s) of data and get the same result as if it was * encrypted in one call. This allows a "streaming" usage. * If you need to retain the contents of the IV, you should * either save it manually or use the cipher module instead. * * * \param ctx The ARIA context to use for encryption or decryption. * This must be initialized and bound to a key. * \param mode The mode of operation. This must be either * #MBEDTLS_ARIA_ENCRYPT for encryption, or * #MBEDTLS_ARIA_DECRYPT for decryption. * \param length The length of the input data in Bytes. This must be a * multiple of the block size (16 Bytes). * \param iv Initialization vector (updated after use). * This must be a readable buffer of size 16 Bytes. * \param input The buffer holding the input data. This must * be a readable buffer of length \p length Bytes. * \param output The buffer holding the output data. This must * be a writable buffer of length \p length Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_aria_crypt_cbc( mbedtls_aria_context *ctx, int mode, size_t length, unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], const unsigned char *input, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_CIPHER_MODE_CFB) /** * \brief This function performs an ARIA-CFB128 encryption or decryption * operation. * * It performs the operation defined in the \p mode * parameter (encrypt or decrypt), on the input data buffer * defined in the \p input parameter. * * For CFB, you must set up the context with mbedtls_aria_setkey_enc(), * regardless of whether you are performing an encryption or decryption * operation, that is, regardless of the \p mode parameter. This is * because CFB mode uses the same key schedule for encryption and * decryption. * * \note Upon exit, the content of the IV is updated so that you can * call the same function again on the next * block(s) of data and get the same result as if it was * encrypted in one call. This allows a "streaming" usage. * If you need to retain the contents of the * IV, you must either save it manually or use the cipher * module instead. * * * \param ctx The ARIA context to use for encryption or decryption. * This must be initialized and bound to a key. * \param mode The mode of operation. This must be either * #MBEDTLS_ARIA_ENCRYPT for encryption, or * #MBEDTLS_ARIA_DECRYPT for decryption. * \param length The length of the input data \p input in Bytes. * \param iv_off The offset in IV (updated after use). * This must not be larger than 15. * \param iv The initialization vector (updated after use). * This must be a readable buffer of size 16 Bytes. * \param input The buffer holding the input data. This must * be a readable buffer of length \p length Bytes. * \param output The buffer holding the output data. This must * be a writable buffer of length \p length Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_aria_crypt_cfb128( mbedtls_aria_context *ctx, int mode, size_t length, size_t *iv_off, unsigned char iv[MBEDTLS_ARIA_BLOCKSIZE], const unsigned char *input, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CFB */ #if defined(MBEDTLS_CIPHER_MODE_CTR) /** * \brief This function performs an ARIA-CTR encryption or decryption * operation. * * This function performs the operation defined in the \p mode * parameter (encrypt/decrypt), on the input data buffer * defined in the \p input parameter. * * Due to the nature of CTR, you must use the same key schedule * for both encryption and decryption operations. Therefore, you * must use the context initialized with mbedtls_aria_setkey_enc() * for both #MBEDTLS_ARIA_ENCRYPT and #MBEDTLS_ARIA_DECRYPT. * * \warning You must never reuse a nonce value with the same key. Doing so * would void the encryption for the two messages encrypted with * the same nonce and key. * * There are two common strategies for managing nonces with CTR: * * 1. You can handle everything as a single message processed over * successive calls to this function. In that case, you want to * set \p nonce_counter and \p nc_off to 0 for the first call, and * then preserve the values of \p nonce_counter, \p nc_off and \p * stream_block across calls to this function as they will be * updated by this function. * * With this strategy, you must not encrypt more than 2**128 * blocks of data with the same key. * * 2. You can encrypt separate messages by dividing the \p * nonce_counter buffer in two areas: the first one used for a * per-message nonce, handled by yourself, and the second one * updated by this function internally. * * For example, you might reserve the first 12 bytes for the * per-message nonce, and the last 4 bytes for internal use. In that * case, before calling this function on a new message you need to * set the first 12 bytes of \p nonce_counter to your chosen nonce * value, the last 4 to 0, and \p nc_off to 0 (which will cause \p * stream_block to be ignored). That way, you can encrypt at most * 2**96 messages of up to 2**32 blocks each with the same key. * * The per-message nonce (or information sufficient to reconstruct * it) needs to be communicated with the ciphertext and must be unique. * The recommended way to ensure uniqueness is to use a message * counter. An alternative is to generate random nonces, but this * limits the number of messages that can be securely encrypted: * for example, with 96-bit random nonces, you should not encrypt * more than 2**32 messages with the same key. * * Note that for both stategies, sizes are measured in blocks and * that an ARIA block is 16 bytes. * * \warning Upon return, \p stream_block contains sensitive data. Its * content must not be written to insecure storage and should be * securely discarded as soon as it's no longer needed. * * \param ctx The ARIA context to use for encryption or decryption. * This must be initialized and bound to a key. * \param length The length of the input data \p input in Bytes. * \param nc_off The offset in Bytes in the current \p stream_block, * for resuming within the current cipher stream. The * offset pointer should be \c 0 at the start of a * stream. This must not be larger than \c 15 Bytes. * \param nonce_counter The 128-bit nonce and counter. This must point to * a read/write buffer of length \c 16 bytes. * \param stream_block The saved stream block for resuming. This must * point to a read/write buffer of length \c 16 bytes. * This is overwritten by the function. * \param input The buffer holding the input data. This must * be a readable buffer of length \p length Bytes. * \param output The buffer holding the output data. This must * be a writable buffer of length \p length Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_aria_crypt_ctr( mbedtls_aria_context *ctx, size_t length, size_t *nc_off, unsigned char nonce_counter[MBEDTLS_ARIA_BLOCKSIZE], unsigned char stream_block[MBEDTLS_ARIA_BLOCKSIZE], const unsigned char *input, unsigned char *output ); #endif /* MBEDTLS_CIPHER_MODE_CTR */ #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine. * * \return \c 0 on success, or \c 1 on failure. */ int mbedtls_aria_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* aria.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/sha512.h
/** * \file sha512.h * \brief This file contains SHA-384 and SHA-512 definitions and functions. * * The Secure Hash Algorithms 384 and 512 (SHA-384 and SHA-512) cryptographic * hash functions are defined in <em>FIPS 180-4: Secure Hash Standard (SHS)</em>. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_SHA512_H #define MBEDTLS_SHA512_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include <stddef.h> #include <stdint.h> /* MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_SHA512_HW_ACCEL_FAILED -0x0039 /**< SHA-512 hardware accelerator failed */ #define MBEDTLS_ERR_SHA512_BAD_INPUT_DATA -0x0075 /**< SHA-512 input data was malformed. */ #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_SHA512_ALT) // Regular implementation // /** * \brief The SHA-512 context structure. * * The structure is used both for SHA-384 and for SHA-512 * checksum calculations. The choice between these two is * made in the call to mbedtls_sha512_starts_ret(). */ typedef struct mbedtls_sha512_context { uint64_t total[2]; /*!< The number of Bytes processed. */ uint64_t state[8]; /*!< The intermediate digest state. */ unsigned char buffer[128]; /*!< The data block being processed. */ #if !defined(MBEDTLS_SHA512_NO_SHA384) int is384; /*!< Determines which function to use: 0: Use SHA-512, or 1: Use SHA-384. */ #endif } mbedtls_sha512_context; #else /* MBEDTLS_SHA512_ALT */ #include "sha512_alt.h" #endif /* MBEDTLS_SHA512_ALT */ /** * \brief This function initializes a SHA-512 context. * * \param ctx The SHA-512 context to initialize. This must * not be \c NULL. */ void mbedtls_sha512_init( mbedtls_sha512_context *ctx ); /** * \brief This function clears a SHA-512 context. * * \param ctx The SHA-512 context to clear. This may be \c NULL, * in which case this function does nothing. If it * is not \c NULL, it must point to an initialized * SHA-512 context. */ void mbedtls_sha512_free( mbedtls_sha512_context *ctx ); /** * \brief This function clones the state of a SHA-512 context. * * \param dst The destination context. This must be initialized. * \param src The context to clone. This must be initialized. */ void mbedtls_sha512_clone( mbedtls_sha512_context *dst, const mbedtls_sha512_context *src ); /** * \brief This function starts a SHA-384 or SHA-512 checksum * calculation. * * \param ctx The SHA-512 context to use. This must be initialized. * \param is384 Determines which function to use. This must be * either \c 0 for SHA-512, or \c 1 for SHA-384. * * \note When \c MBEDTLS_SHA512_NO_SHA384 is defined, \p is384 must * be \c 0, or the function will return * #MBEDTLS_ERR_SHA512_BAD_INPUT_DATA. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha512_starts_ret( mbedtls_sha512_context *ctx, int is384 ); /** * \brief This function feeds an input buffer into an ongoing * SHA-512 checksum calculation. * * \param ctx The SHA-512 context. This must be initialized * and have a hash operation started. * \param input The buffer holding the input data. This must * be a readable buffer of length \p ilen Bytes. * \param ilen The length of the input data in Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha512_update_ret( mbedtls_sha512_context *ctx, const unsigned char *input, size_t ilen ); /** * \brief This function finishes the SHA-512 operation, and writes * the result to the output buffer. * * \param ctx The SHA-512 context. This must be initialized * and have a hash operation started. * \param output The SHA-384 or SHA-512 checksum result. * This must be a writable buffer of length \c 64 Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha512_finish_ret( mbedtls_sha512_context *ctx, unsigned char output[64] ); /** * \brief This function processes a single data block within * the ongoing SHA-512 computation. * This function is for internal use only. * * \param ctx The SHA-512 context. This must be initialized. * \param data The buffer holding one block of data. This * must be a readable buffer of length \c 128 Bytes. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_internal_sha512_process( mbedtls_sha512_context *ctx, const unsigned char data[128] ); #if !defined(MBEDTLS_DEPRECATED_REMOVED) #if defined(MBEDTLS_DEPRECATED_WARNING) #define MBEDTLS_DEPRECATED __attribute__((deprecated)) #else #define MBEDTLS_DEPRECATED #endif /** * \brief This function starts a SHA-384 or SHA-512 checksum * calculation. * * \deprecated Superseded by mbedtls_sha512_starts_ret() in 2.7.0 * * \param ctx The SHA-512 context to use. This must be initialized. * \param is384 Determines which function to use. This must be either * \c 0 for SHA-512 or \c 1 for SHA-384. * * \note When \c MBEDTLS_SHA512_NO_SHA384 is defined, \p is384 must * be \c 0, or the function will fail to work. */ MBEDTLS_DEPRECATED void mbedtls_sha512_starts( mbedtls_sha512_context *ctx, int is384 ); /** * \brief This function feeds an input buffer into an ongoing * SHA-512 checksum calculation. * * \deprecated Superseded by mbedtls_sha512_update_ret() in 2.7.0. * * \param ctx The SHA-512 context. This must be initialized * and have a hash operation started. * \param input The buffer holding the data. This must be a readable * buffer of length \p ilen Bytes. * \param ilen The length of the input data in Bytes. */ MBEDTLS_DEPRECATED void mbedtls_sha512_update( mbedtls_sha512_context *ctx, const unsigned char *input, size_t ilen ); /** * \brief This function finishes the SHA-512 operation, and writes * the result to the output buffer. * * \deprecated Superseded by mbedtls_sha512_finish_ret() in 2.7.0. * * \param ctx The SHA-512 context. This must be initialized * and have a hash operation started. * \param output The SHA-384 or SHA-512 checksum result. This must * be a writable buffer of size \c 64 Bytes. */ MBEDTLS_DEPRECATED void mbedtls_sha512_finish( mbedtls_sha512_context *ctx, unsigned char output[64] ); /** * \brief This function processes a single data block within * the ongoing SHA-512 computation. This function is for * internal use only. * * \deprecated Superseded by mbedtls_internal_sha512_process() in 2.7.0. * * \param ctx The SHA-512 context. This must be initialized. * \param data The buffer holding one block of data. This must be * a readable buffer of length \c 128 Bytes. */ MBEDTLS_DEPRECATED void mbedtls_sha512_process( mbedtls_sha512_context *ctx, const unsigned char data[128] ); #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** * \brief This function calculates the SHA-512 or SHA-384 * checksum of a buffer. * * The function allocates the context, performs the * calculation, and frees the context. * * The SHA-512 result is calculated as * output = SHA-512(input buffer). * * \param input The buffer holding the input data. This must be * a readable buffer of length \p ilen Bytes. * \param ilen The length of the input data in Bytes. * \param output The SHA-384 or SHA-512 checksum result. * This must be a writable buffer of length \c 64 Bytes. * \param is384 Determines which function to use. This must be either * \c 0 for SHA-512, or \c 1 for SHA-384. * * \note When \c MBEDTLS_SHA512_NO_SHA384 is defined, \p is384 must * be \c 0, or the function will return * #MBEDTLS_ERR_SHA512_BAD_INPUT_DATA. * * \return \c 0 on success. * \return A negative error code on failure. */ int mbedtls_sha512_ret( const unsigned char *input, size_t ilen, unsigned char output[64], int is384 ); #if !defined(MBEDTLS_DEPRECATED_REMOVED) #if defined(MBEDTLS_DEPRECATED_WARNING) #define MBEDTLS_DEPRECATED __attribute__((deprecated)) #else #define MBEDTLS_DEPRECATED #endif /** * \brief This function calculates the SHA-512 or SHA-384 * checksum of a buffer. * * The function allocates the context, performs the * calculation, and frees the context. * * The SHA-512 result is calculated as * output = SHA-512(input buffer). * * \deprecated Superseded by mbedtls_sha512_ret() in 2.7.0 * * \param input The buffer holding the data. This must be a * readable buffer of length \p ilen Bytes. * \param ilen The length of the input data in Bytes. * \param output The SHA-384 or SHA-512 checksum result. This must * be a writable buffer of length \c 64 Bytes. * \param is384 Determines which function to use. This must be either * \c 0 for SHA-512, or \c 1 for SHA-384. * * \note When \c MBEDTLS_SHA512_NO_SHA384 is defined, \p is384 must * be \c 0, or the function will fail to work. */ MBEDTLS_DEPRECATED void mbedtls_sha512( const unsigned char *input, size_t ilen, unsigned char output[64], int is384 ); #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ #if defined(MBEDTLS_SELF_TEST) /** * \brief The SHA-384 or SHA-512 checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_sha512_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* mbedtls_sha512.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/ecjpake.h
/** * \file ecjpake.h * * \brief Elliptic curve J-PAKE */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_ECJPAKE_H #define MBEDTLS_ECJPAKE_H /* * J-PAKE is a password-authenticated key exchange that allows deriving a * strong shared secret from a (potentially low entropy) pre-shared * passphrase, with forward secrecy and mutual authentication. * https://en.wikipedia.org/wiki/Password_Authenticated_Key_Exchange_by_Juggling * * This file implements the Elliptic Curve variant of J-PAKE, * as defined in Chapter 7.4 of the Thread v1.0 Specification, * available to members of the Thread Group http://threadgroup.org/ * * As the J-PAKE algorithm is inherently symmetric, so is our API. * Each party needs to send its first round message, in any order, to the * other party, then each sends its second round message, in any order. * The payloads are serialized in a way suitable for use in TLS, but could * also be use outside TLS. */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/ecp.h" #include "mbedtls/md.h" #ifdef __cplusplus extern "C" { #endif /** * Roles in the EC J-PAKE exchange */ typedef enum { MBEDTLS_ECJPAKE_CLIENT = 0, /**< Client */ MBEDTLS_ECJPAKE_SERVER, /**< Server */ } mbedtls_ecjpake_role; #if !defined(MBEDTLS_ECJPAKE_ALT) /** * EC J-PAKE context structure. * * J-PAKE is a symmetric protocol, except for the identifiers used in * Zero-Knowledge Proofs, and the serialization of the second message * (KeyExchange) as defined by the Thread spec. * * In order to benefit from this symmetry, we choose a different naming * convetion from the Thread v1.0 spec. Correspondance is indicated in the * description as a pair C: client name, S: server name */ typedef struct mbedtls_ecjpake_context { const mbedtls_md_info_t *md_info; /**< Hash to use */ mbedtls_ecp_group grp; /**< Elliptic curve */ mbedtls_ecjpake_role role; /**< Are we client or server? */ int point_format; /**< Format for point export */ mbedtls_ecp_point Xm1; /**< My public key 1 C: X1, S: X3 */ mbedtls_ecp_point Xm2; /**< My public key 2 C: X2, S: X4 */ mbedtls_ecp_point Xp1; /**< Peer public key 1 C: X3, S: X1 */ mbedtls_ecp_point Xp2; /**< Peer public key 2 C: X4, S: X2 */ mbedtls_ecp_point Xp; /**< Peer public key C: Xs, S: Xc */ mbedtls_mpi xm1; /**< My private key 1 C: x1, S: x3 */ mbedtls_mpi xm2; /**< My private key 2 C: x2, S: x4 */ mbedtls_mpi s; /**< Pre-shared secret (passphrase) */ } mbedtls_ecjpake_context; #else /* MBEDTLS_ECJPAKE_ALT */ #include "ecjpake_alt.h" #endif /* MBEDTLS_ECJPAKE_ALT */ /** * \brief Initialize an ECJPAKE context. * * \param ctx The ECJPAKE context to initialize. * This must not be \c NULL. */ void mbedtls_ecjpake_init( mbedtls_ecjpake_context *ctx ); /** * \brief Set up an ECJPAKE context for use. * * \note Currently the only values for hash/curve allowed by the * standard are #MBEDTLS_MD_SHA256/#MBEDTLS_ECP_DP_SECP256R1. * * \param ctx The ECJPAKE context to set up. This must be initialized. * \param role The role of the caller. This must be either * #MBEDTLS_ECJPAKE_CLIENT or #MBEDTLS_ECJPAKE_SERVER. * \param hash The identifier of the hash function to use, * for example #MBEDTLS_MD_SHA256. * \param curve The identifier of the elliptic curve to use, * for example #MBEDTLS_ECP_DP_SECP256R1. * \param secret The pre-shared secret (passphrase). This must be * a readable buffer of length \p len Bytes. It need * only be valid for the duration of this call. * \param len The length of the pre-shared secret \p secret. * * \return \c 0 if successful. * \return A negative error code on failure. */ int mbedtls_ecjpake_setup( mbedtls_ecjpake_context *ctx, mbedtls_ecjpake_role role, mbedtls_md_type_t hash, mbedtls_ecp_group_id curve, const unsigned char *secret, size_t len ); /** * \brief Check if an ECJPAKE context is ready for use. * * \param ctx The ECJPAKE context to check. This must be * initialized. * * \return \c 0 if the context is ready for use. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA otherwise. */ int mbedtls_ecjpake_check( const mbedtls_ecjpake_context *ctx ); /** * \brief Generate and write the first round message * (TLS: contents of the Client/ServerHello extension, * excluding extension type and length bytes). * * \param ctx The ECJPAKE context to use. This must be * initialized and set up. * \param buf The buffer to write the contents to. This must be a * writable buffer of length \p len Bytes. * \param len The length of \p buf in Bytes. * \param olen The address at which to store the total number * of Bytes written to \p buf. This must not be \c NULL. * \param f_rng The RNG function to use. This must not be \c NULL. * \param p_rng The RNG parameter to be passed to \p f_rng. This * may be \c NULL if \p f_rng doesn't use a context. * * \return \c 0 if successful. * \return A negative error code on failure. */ int mbedtls_ecjpake_write_round_one( mbedtls_ecjpake_context *ctx, unsigned char *buf, size_t len, size_t *olen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief Read and process the first round message * (TLS: contents of the Client/ServerHello extension, * excluding extension type and length bytes). * * \param ctx The ECJPAKE context to use. This must be initialized * and set up. * \param buf The buffer holding the first round message. This must * be a readable buffer of length \p len Bytes. * \param len The length in Bytes of \p buf. * * \return \c 0 if successful. * \return A negative error code on failure. */ int mbedtls_ecjpake_read_round_one( mbedtls_ecjpake_context *ctx, const unsigned char *buf, size_t len ); /** * \brief Generate and write the second round message * (TLS: contents of the Client/ServerKeyExchange). * * \param ctx The ECJPAKE context to use. This must be initialized, * set up, and already have performed round one. * \param buf The buffer to write the round two contents to. * This must be a writable buffer of length \p len Bytes. * \param len The size of \p buf in Bytes. * \param olen The address at which to store the total number of Bytes * written to \p buf. This must not be \c NULL. * \param f_rng The RNG function to use. This must not be \c NULL. * \param p_rng The RNG parameter to be passed to \p f_rng. This * may be \c NULL if \p f_rng doesn't use a context. * * \return \c 0 if successful. * \return A negative error code on failure. */ int mbedtls_ecjpake_write_round_two( mbedtls_ecjpake_context *ctx, unsigned char *buf, size_t len, size_t *olen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief Read and process the second round message * (TLS: contents of the Client/ServerKeyExchange). * * \param ctx The ECJPAKE context to use. This must be initialized * and set up and already have performed round one. * \param buf The buffer holding the second round message. This must * be a readable buffer of length \p len Bytes. * \param len The length in Bytes of \p buf. * * \return \c 0 if successful. * \return A negative error code on failure. */ int mbedtls_ecjpake_read_round_two( mbedtls_ecjpake_context *ctx, const unsigned char *buf, size_t len ); /** * \brief Derive the shared secret * (TLS: Pre-Master Secret). * * \param ctx The ECJPAKE context to use. This must be initialized, * set up and have performed both round one and two. * \param buf The buffer to write the derived secret to. This must * be a writable buffer of length \p len Bytes. * \param len The length of \p buf in Bytes. * \param olen The address at which to store the total number of Bytes * written to \p buf. This must not be \c NULL. * \param f_rng The RNG function to use. This must not be \c NULL. * \param p_rng The RNG parameter to be passed to \p f_rng. This * may be \c NULL if \p f_rng doesn't use a context. * * \return \c 0 if successful. * \return A negative error code on failure. */ int mbedtls_ecjpake_derive_secret( mbedtls_ecjpake_context *ctx, unsigned char *buf, size_t len, size_t *olen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This clears an ECJPAKE context and frees any * embedded data structure. * * \param ctx The ECJPAKE context to free. This may be \c NULL, * in which case this function does nothing. If it is not * \c NULL, it must point to an initialized ECJPAKE context. */ void mbedtls_ecjpake_free( mbedtls_ecjpake_context *ctx ); #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine * * \return 0 if successful, or 1 if a test failed */ int mbedtls_ecjpake_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* ecjpake.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/xtea.h
/** * \file xtea.h * * \brief XTEA block cipher (32-bit) */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_XTEA_H #define MBEDTLS_XTEA_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include <stddef.h> #include <stdint.h> #define MBEDTLS_XTEA_ENCRYPT 1 #define MBEDTLS_XTEA_DECRYPT 0 #define MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH -0x0028 /**< The data input has an invalid length. */ /* MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_XTEA_HW_ACCEL_FAILED -0x0029 /**< XTEA hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_XTEA_ALT) // Regular implementation // /** * \brief XTEA context structure */ typedef struct mbedtls_xtea_context { uint32_t k[4]; /*!< key */ } mbedtls_xtea_context; #else /* MBEDTLS_XTEA_ALT */ #include "xtea_alt.h" #endif /* MBEDTLS_XTEA_ALT */ /** * \brief Initialize XTEA context * * \param ctx XTEA context to be initialized */ void mbedtls_xtea_init( mbedtls_xtea_context *ctx ); /** * \brief Clear XTEA context * * \param ctx XTEA context to be cleared */ void mbedtls_xtea_free( mbedtls_xtea_context *ctx ); /** * \brief XTEA key schedule * * \param ctx XTEA context to be initialized * \param key the secret key */ void mbedtls_xtea_setup( mbedtls_xtea_context *ctx, const unsigned char key[16] ); /** * \brief XTEA cipher function * * \param ctx XTEA context * \param mode MBEDTLS_XTEA_ENCRYPT or MBEDTLS_XTEA_DECRYPT * \param input 8-byte input block * \param output 8-byte output block * * \return 0 if successful */ int mbedtls_xtea_crypt_ecb( mbedtls_xtea_context *ctx, int mode, const unsigned char input[8], unsigned char output[8] ); #if defined(MBEDTLS_CIPHER_MODE_CBC) /** * \brief XTEA CBC cipher function * * \param ctx XTEA context * \param mode MBEDTLS_XTEA_ENCRYPT or MBEDTLS_XTEA_DECRYPT * \param length the length of input, multiple of 8 * \param iv initialization vector for CBC mode * \param input input block * \param output output block * * \return 0 if successful, * MBEDTLS_ERR_XTEA_INVALID_INPUT_LENGTH if the length % 8 != 0 */ int mbedtls_xtea_crypt_cbc( mbedtls_xtea_context *ctx, int mode, size_t length, unsigned char iv[8], const unsigned char *input, unsigned char *output); #endif /* MBEDTLS_CIPHER_MODE_CBC */ #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int mbedtls_xtea_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* xtea.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/ecp.h
/** * \file ecp.h * * \brief This file provides an API for Elliptic Curves over GF(P) (ECP). * * The use of ECP in cryptography and TLS is defined in * <em>Standards for Efficient Cryptography Group (SECG): SEC1 * Elliptic Curve Cryptography</em> and * <em>RFC-4492: Elliptic Curve Cryptography (ECC) Cipher Suites * for Transport Layer Security (TLS)</em>. * * <em>RFC-2409: The Internet Key Exchange (IKE)</em> defines ECP * group types. * */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_ECP_H #define MBEDTLS_ECP_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/bignum.h" /* * ECP error codes */ #define MBEDTLS_ERR_ECP_BAD_INPUT_DATA -0x4F80 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL -0x4F00 /**< The buffer is too small to write to. */ #define MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE -0x4E80 /**< The requested feature is not available, for example, the requested curve is not supported. */ #define MBEDTLS_ERR_ECP_VERIFY_FAILED -0x4E00 /**< The signature is not valid. */ #define MBEDTLS_ERR_ECP_ALLOC_FAILED -0x4D80 /**< Memory allocation failed. */ #define MBEDTLS_ERR_ECP_RANDOM_FAILED -0x4D00 /**< Generation of random value, such as ephemeral key, failed. */ #define MBEDTLS_ERR_ECP_INVALID_KEY -0x4C80 /**< Invalid private or public key. */ #define MBEDTLS_ERR_ECP_SIG_LEN_MISMATCH -0x4C00 /**< The buffer contains a valid signature followed by more data. */ /* MBEDTLS_ERR_ECP_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_ECP_HW_ACCEL_FAILED -0x4B80 /**< The ECP hardware accelerator failed. */ #define MBEDTLS_ERR_ECP_IN_PROGRESS -0x4B00 /**< Operation in progress, call again with the same parameters to continue. */ /* Flags indicating whether to include code that is specific to certain * types of curves. These flags are for internal library use only. */ #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) || \ defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) #define MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED #endif #if defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) || \ defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) #define MBEDTLS_ECP_MONTGOMERY_ENABLED #endif #ifdef __cplusplus extern "C" { #endif /** * Domain-parameter identifiers: curve, subgroup, and generator. * * \note Only curves over prime fields are supported. * * \warning This library does not support validation of arbitrary domain * parameters. Therefore, only standardized domain parameters from trusted * sources should be used. See mbedtls_ecp_group_load(). */ /* Note: when adding a new curve: * - Add it at the end of this enum, otherwise you'll break the ABI by * changing the numerical value for existing curves. * - Increment MBEDTLS_ECP_DP_MAX below if needed. * - Update the calculation of MBEDTLS_ECP_MAX_BITS_MIN below. * - Add the corresponding MBEDTLS_ECP_DP_xxx_ENABLED macro definition to * config.h. * - List the curve as a dependency of MBEDTLS_ECP_C and * MBEDTLS_ECDSA_C if supported in check_config.h. * - Add the curve to the appropriate curve type macro * MBEDTLS_ECP_yyy_ENABLED above. * - Add the necessary definitions to ecp_curves.c. * - Add the curve to the ecp_supported_curves array in ecp.c. * - Add the curve to applicable profiles in x509_crt.c if applicable. */ typedef enum { MBEDTLS_ECP_DP_NONE = 0, /*!< Curve not defined. */ MBEDTLS_ECP_DP_SECP192R1, /*!< Domain parameters for the 192-bit curve defined by FIPS 186-4 and SEC1. */ MBEDTLS_ECP_DP_SECP224R1, /*!< Domain parameters for the 224-bit curve defined by FIPS 186-4 and SEC1. */ MBEDTLS_ECP_DP_SECP256R1, /*!< Domain parameters for the 256-bit curve defined by FIPS 186-4 and SEC1. */ MBEDTLS_ECP_DP_SECP384R1, /*!< Domain parameters for the 384-bit curve defined by FIPS 186-4 and SEC1. */ MBEDTLS_ECP_DP_SECP521R1, /*!< Domain parameters for the 521-bit curve defined by FIPS 186-4 and SEC1. */ MBEDTLS_ECP_DP_BP256R1, /*!< Domain parameters for 256-bit Brainpool curve. */ MBEDTLS_ECP_DP_BP384R1, /*!< Domain parameters for 384-bit Brainpool curve. */ MBEDTLS_ECP_DP_BP512R1, /*!< Domain parameters for 512-bit Brainpool curve. */ MBEDTLS_ECP_DP_CURVE25519, /*!< Domain parameters for Curve25519. */ MBEDTLS_ECP_DP_SECP192K1, /*!< Domain parameters for 192-bit "Koblitz" curve. */ MBEDTLS_ECP_DP_SECP224K1, /*!< Domain parameters for 224-bit "Koblitz" curve. */ MBEDTLS_ECP_DP_SECP256K1, /*!< Domain parameters for 256-bit "Koblitz" curve. */ MBEDTLS_ECP_DP_CURVE448, /*!< Domain parameters for Curve448. */ } mbedtls_ecp_group_id; /** * The number of supported curves, plus one for #MBEDTLS_ECP_DP_NONE. * * \note Montgomery curves are currently excluded. */ #define MBEDTLS_ECP_DP_MAX 12 /* * Curve types */ typedef enum { MBEDTLS_ECP_TYPE_NONE = 0, MBEDTLS_ECP_TYPE_SHORT_WEIERSTRASS, /* y^2 = x^3 + a x + b */ MBEDTLS_ECP_TYPE_MONTGOMERY, /* y^2 = x^3 + a x^2 + x */ } mbedtls_ecp_curve_type; /** * Curve information, for use by other modules. */ typedef struct mbedtls_ecp_curve_info { mbedtls_ecp_group_id grp_id; /*!< An internal identifier. */ uint16_t tls_id; /*!< The TLS NamedCurve identifier. */ uint16_t bit_size; /*!< The curve size in bits. */ const char *name; /*!< A human-friendly name. */ } mbedtls_ecp_curve_info; /** * \brief The ECP point structure, in Jacobian coordinates. * * \note All functions expect and return points satisfying * the following condition: <code>Z == 0</code> or * <code>Z == 1</code>. Other values of \p Z are * used only by internal functions. * The point is zero, or "at infinity", if <code>Z == 0</code>. * Otherwise, \p X and \p Y are its standard (affine) * coordinates. */ typedef struct mbedtls_ecp_point { mbedtls_mpi X; /*!< The X coordinate of the ECP point. */ mbedtls_mpi Y; /*!< The Y coordinate of the ECP point. */ mbedtls_mpi Z; /*!< The Z coordinate of the ECP point. */ } mbedtls_ecp_point; /* Determine the minimum safe value of MBEDTLS_ECP_MAX_BITS. */ #if !defined(MBEDTLS_ECP_C) #define MBEDTLS_ECP_MAX_BITS_MIN 0 /* Note: the curves must be listed in DECREASING size! */ #elif defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 521 #elif defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 512 #elif defined(MBEDTLS_ECP_DP_CURVE448_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 448 #elif defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 384 #elif defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 384 #elif defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 256 #elif defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 256 #elif defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 256 #elif defined(MBEDTLS_ECP_DP_CURVE25519_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 255 #elif defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 225 // n is slightly above 2^224 #elif defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 224 #elif defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 192 #elif defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) #define MBEDTLS_ECP_MAX_BITS_MIN 192 #else #error "MBEDTLS_ECP_C enabled, but no curve?" #endif #if !defined(MBEDTLS_ECP_ALT) /* * default mbed TLS elliptic curve arithmetic implementation * * (in case MBEDTLS_ECP_ALT is defined then the developer has to provide an * alternative implementation for the whole module and it will replace this * one.) */ /** * \brief The ECP group structure. * * We consider two types of curve equations: * <ul><li>Short Weierstrass: <code>y^2 = x^3 + A x + B mod P</code> * (SEC1 + RFC-4492)</li> * <li>Montgomery: <code>y^2 = x^3 + A x^2 + x mod P</code> (Curve25519, * Curve448)</li></ul> * In both cases, the generator (\p G) for a prime-order subgroup is fixed. * * For Short Weierstrass, this subgroup is the whole curve, and its * cardinality is denoted by \p N. Our code requires that \p N is an * odd prime as mbedtls_ecp_mul() requires an odd number, and * mbedtls_ecdsa_sign() requires that it is prime for blinding purposes. * * For Montgomery curves, we do not store \p A, but <code>(A + 2) / 4</code>, * which is the quantity used in the formulas. Additionally, \p nbits is * not the size of \p N but the required size for private keys. * * If \p modp is NULL, reduction modulo \p P is done using a generic algorithm. * Otherwise, \p modp must point to a function that takes an \p mbedtls_mpi in the * range of <code>0..2^(2*pbits)-1</code>, and transforms it in-place to an integer * which is congruent mod \p P to the given MPI, and is close enough to \p pbits * in size, so that it may be efficiently brought in the 0..P-1 range by a few * additions or subtractions. Therefore, it is only an approximative modular * reduction. It must return 0 on success and non-zero on failure. * * \note Alternative implementations must keep the group IDs distinct. If * two group structures have the same ID, then they must be * identical. * */ typedef struct mbedtls_ecp_group { mbedtls_ecp_group_id id; /*!< An internal group identifier. */ mbedtls_mpi P; /*!< The prime modulus of the base field. */ mbedtls_mpi A; /*!< For Short Weierstrass: \p A in the equation. For Montgomery curves: <code>(A + 2) / 4</code>. */ mbedtls_mpi B; /*!< For Short Weierstrass: \p B in the equation. For Montgomery curves: unused. */ mbedtls_ecp_point G; /*!< The generator of the subgroup used. */ mbedtls_mpi N; /*!< The order of \p G. */ size_t pbits; /*!< The number of bits in \p P.*/ size_t nbits; /*!< For Short Weierstrass: The number of bits in \p P. For Montgomery curves: the number of bits in the private keys. */ unsigned int h; /*!< \internal 1 if the constants are static. */ int (*modp)(mbedtls_mpi *); /*!< The function for fast pseudo-reduction mod \p P (see above).*/ int (*t_pre)(mbedtls_ecp_point *, void *); /*!< Unused. */ int (*t_post)(mbedtls_ecp_point *, void *); /*!< Unused. */ void *t_data; /*!< Unused. */ mbedtls_ecp_point *T; /*!< Pre-computed points for ecp_mul_comb(). */ size_t T_size; /*!< The number of pre-computed points. */ } mbedtls_ecp_group; /** * \name SECTION: Module settings * * The configuration options you can set for this module are in this section. * Either change them in config.h, or define them using the compiler command line. * \{ */ #if defined(MBEDTLS_ECP_MAX_BITS) #if MBEDTLS_ECP_MAX_BITS < MBEDTLS_ECP_MAX_BITS_MIN #error "MBEDTLS_ECP_MAX_BITS is smaller than the largest supported curve" #endif #elif defined(MBEDTLS_ECP_C) /** * The maximum size of the groups, that is, of \c N and \c P. */ #define MBEDTLS_ECP_MAX_BITS MBEDTLS_ECP_MAX_BITS_MIN #else /* MBEDTLS_ECP_MAX_BITS is not relevant without MBEDTLS_ECP_C, but set it * to a nonzero value so that code that unconditionally allocates an array * of a size based on it keeps working if built without ECC support. */ #define MBEDTLS_ECP_MAX_BITS 1 #endif #define MBEDTLS_ECP_MAX_BYTES ( ( MBEDTLS_ECP_MAX_BITS + 7 ) / 8 ) #define MBEDTLS_ECP_MAX_PT_LEN ( 2 * MBEDTLS_ECP_MAX_BYTES + 1 ) #if !defined(MBEDTLS_ECP_WINDOW_SIZE) /* * Maximum "window" size used for point multiplication. * Default: a point where higher memory usage yields disminishing performance * returns. * Minimum value: 2. Maximum value: 7. * * Result is an array of at most ( 1 << ( MBEDTLS_ECP_WINDOW_SIZE - 1 ) ) * points used for point multiplication. This value is directly tied to EC * peak memory usage, so decreasing it by one should roughly cut memory usage * by two (if large curves are in use). * * Reduction in size may reduce speed, but larger curves are impacted first. * Sample performances (in ECDHE handshakes/s, with FIXED_POINT_OPTIM = 1): * w-size: 6 5 4 3 2 * 521 145 141 135 120 97 * 384 214 209 198 177 146 * 256 320 320 303 262 226 * 224 475 475 453 398 342 * 192 640 640 633 587 476 */ #define MBEDTLS_ECP_WINDOW_SIZE 4 /**< The maximum window size used. */ #endif /* MBEDTLS_ECP_WINDOW_SIZE */ #if !defined(MBEDTLS_ECP_FIXED_POINT_OPTIM) /* * Trade memory for speed on fixed-point multiplication. * * This speeds up repeated multiplication of the generator (that is, the * multiplication in ECDSA signatures, and half of the multiplications in * ECDSA verification and ECDHE) by a factor roughly 3 to 4. * * The cost is increasing EC peak memory usage by a factor roughly 2. * * Change this value to 0 to reduce peak memory usage. */ #define MBEDTLS_ECP_FIXED_POINT_OPTIM 1 /**< Enable fixed-point speed-up. */ #endif /* MBEDTLS_ECP_FIXED_POINT_OPTIM */ /* \} name SECTION: Module settings */ #else /* MBEDTLS_ECP_ALT */ #include "ecp_alt.h" #endif /* MBEDTLS_ECP_ALT */ #if defined(MBEDTLS_ECP_RESTARTABLE) /** * \brief Internal restart context for multiplication * * \note Opaque struct */ typedef struct mbedtls_ecp_restart_mul mbedtls_ecp_restart_mul_ctx; /** * \brief Internal restart context for ecp_muladd() * * \note Opaque struct */ typedef struct mbedtls_ecp_restart_muladd mbedtls_ecp_restart_muladd_ctx; /** * \brief General context for resuming ECC operations */ typedef struct { unsigned ops_done; /*!< current ops count */ unsigned depth; /*!< call depth (0 = top-level) */ mbedtls_ecp_restart_mul_ctx *rsm; /*!< ecp_mul_comb() sub-context */ mbedtls_ecp_restart_muladd_ctx *ma; /*!< ecp_muladd() sub-context */ } mbedtls_ecp_restart_ctx; /* * Operation counts for restartable functions */ #define MBEDTLS_ECP_OPS_CHK 3 /*!< basic ops count for ecp_check_pubkey() */ #define MBEDTLS_ECP_OPS_DBL 8 /*!< basic ops count for ecp_double_jac() */ #define MBEDTLS_ECP_OPS_ADD 11 /*!< basic ops count for see ecp_add_mixed() */ #define MBEDTLS_ECP_OPS_INV 120 /*!< empirical equivalent for mpi_mod_inv() */ /** * \brief Internal; for restartable functions in other modules. * Check and update basic ops budget. * * \param grp Group structure * \param rs_ctx Restart context * \param ops Number of basic ops to do * * \return \c 0 if doing \p ops basic ops is still allowed, * \return #MBEDTLS_ERR_ECP_IN_PROGRESS otherwise. */ int mbedtls_ecp_check_budget( const mbedtls_ecp_group *grp, mbedtls_ecp_restart_ctx *rs_ctx, unsigned ops ); /* Utility macro for checking and updating ops budget */ #define MBEDTLS_ECP_BUDGET( ops ) \ MBEDTLS_MPI_CHK( mbedtls_ecp_check_budget( grp, rs_ctx, \ (unsigned) (ops) ) ); #else /* MBEDTLS_ECP_RESTARTABLE */ #define MBEDTLS_ECP_BUDGET( ops ) /* no-op; for compatibility */ /* We want to declare restartable versions of existing functions anyway */ typedef void mbedtls_ecp_restart_ctx; #endif /* MBEDTLS_ECP_RESTARTABLE */ /** * \brief The ECP key-pair structure. * * A generic key-pair that may be used for ECDSA and fixed ECDH, for example. * * \note Members are deliberately in the same order as in the * ::mbedtls_ecdsa_context structure. */ typedef struct mbedtls_ecp_keypair { mbedtls_ecp_group grp; /*!< Elliptic curve and base point */ mbedtls_mpi d; /*!< our secret value */ mbedtls_ecp_point Q; /*!< our public value */ } mbedtls_ecp_keypair; /* * Point formats, from RFC 4492's enum ECPointFormat */ #define MBEDTLS_ECP_PF_UNCOMPRESSED 0 /**< Uncompressed point format. */ #define MBEDTLS_ECP_PF_COMPRESSED 1 /**< Compressed point format. */ /* * Some other constants from RFC 4492 */ #define MBEDTLS_ECP_TLS_NAMED_CURVE 3 /**< The named_curve of ECCurveType. */ #if defined(MBEDTLS_ECP_RESTARTABLE) /** * \brief Set the maximum number of basic operations done in a row. * * If more operations are needed to complete a computation, * #MBEDTLS_ERR_ECP_IN_PROGRESS will be returned by the * function performing the computation. It is then the * caller's responsibility to either call again with the same * parameters until it returns 0 or an error code; or to free * the restart context if the operation is to be aborted. * * It is strictly required that all input parameters and the * restart context be the same on successive calls for the * same operation, but output parameters need not be the * same; they must not be used until the function finally * returns 0. * * This only applies to functions whose documentation * mentions they may return #MBEDTLS_ERR_ECP_IN_PROGRESS (or * #MBEDTLS_ERR_SSL_CRYPTO_IN_PROGRESS for functions in the * SSL module). For functions that accept a "restart context" * argument, passing NULL disables restart and makes the * function equivalent to the function with the same name * with \c _restartable removed. For functions in the ECDH * module, restart is disabled unless the function accepts * an "ECDH context" argument and * mbedtls_ecdh_enable_restart() was previously called on * that context. For function in the SSL module, restart is * only enabled for specific sides and key exchanges * (currently only for clients and ECDHE-ECDSA). * * \param max_ops Maximum number of basic operations done in a row. * Default: 0 (unlimited). * Lower (non-zero) values mean ECC functions will block for * a lesser maximum amount of time. * * \note A "basic operation" is defined as a rough equivalent of a * multiplication in GF(p) for the NIST P-256 curve. * As an indication, with default settings, a scalar * multiplication (full run of \c mbedtls_ecp_mul()) is: * - about 3300 basic operations for P-256 * - about 9400 basic operations for P-384 * * \note Very low values are not always respected: sometimes * functions need to block for a minimum number of * operations, and will do so even if max_ops is set to a * lower value. That minimum depends on the curve size, and * can be made lower by decreasing the value of * \c MBEDTLS_ECP_WINDOW_SIZE. As an indication, here is the * lowest effective value for various curves and values of * that parameter (w for short): * w=6 w=5 w=4 w=3 w=2 * P-256 208 208 160 136 124 * P-384 682 416 320 272 248 * P-521 1364 832 640 544 496 * * \note This setting is currently ignored by Curve25519. */ void mbedtls_ecp_set_max_ops( unsigned max_ops ); /** * \brief Check if restart is enabled (max_ops != 0) * * \return \c 0 if \c max_ops == 0 (restart disabled) * \return \c 1 otherwise (restart enabled) */ int mbedtls_ecp_restart_is_enabled( void ); #endif /* MBEDTLS_ECP_RESTARTABLE */ /* * Get the type of a curve */ mbedtls_ecp_curve_type mbedtls_ecp_get_type( const mbedtls_ecp_group *grp ); /** * \brief This function retrieves the information defined in * mbedtls_ecp_curve_info() for all supported curves. * * \note This function returns information about all curves * supported by the library. Some curves may not be * supported for all algorithms. Call mbedtls_ecdh_can_do() * or mbedtls_ecdsa_can_do() to check if a curve is * supported for ECDH or ECDSA. * * \return A statically allocated array. The last entry is 0. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_list( void ); /** * \brief This function retrieves the list of internal group * identifiers of all supported curves in the order of * preference. * * \note This function returns information about all curves * supported by the library. Some curves may not be * supported for all algorithms. Call mbedtls_ecdh_can_do() * or mbedtls_ecdsa_can_do() to check if a curve is * supported for ECDH or ECDSA. * * \return A statically allocated array, * terminated with MBEDTLS_ECP_DP_NONE. */ const mbedtls_ecp_group_id *mbedtls_ecp_grp_id_list( void ); /** * \brief This function retrieves curve information from an internal * group identifier. * * \param grp_id An \c MBEDTLS_ECP_DP_XXX value. * * \return The associated curve information on success. * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_grp_id( mbedtls_ecp_group_id grp_id ); /** * \brief This function retrieves curve information from a TLS * NamedCurve value. * * \param tls_id An \c MBEDTLS_ECP_DP_XXX value. * * \return The associated curve information on success. * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_tls_id( uint16_t tls_id ); /** * \brief This function retrieves curve information from a * human-readable name. * * \param name The human-readable name. * * \return The associated curve information on success. * \return NULL on failure. */ const mbedtls_ecp_curve_info *mbedtls_ecp_curve_info_from_name( const char *name ); /** * \brief This function initializes a point as zero. * * \param pt The point to initialize. */ void mbedtls_ecp_point_init( mbedtls_ecp_point *pt ); /** * \brief This function initializes an ECP group context * without loading any domain parameters. * * \note After this function is called, domain parameters * for various ECP groups can be loaded through the * mbedtls_ecp_group_load() or mbedtls_ecp_tls_read_group() * functions. */ void mbedtls_ecp_group_init( mbedtls_ecp_group *grp ); /** * \brief This function initializes a key pair as an invalid one. * * \param key The key pair to initialize. */ void mbedtls_ecp_keypair_init( mbedtls_ecp_keypair *key ); /** * \brief This function frees the components of a point. * * \param pt The point to free. */ void mbedtls_ecp_point_free( mbedtls_ecp_point *pt ); /** * \brief This function frees the components of an ECP group. * * \param grp The group to free. This may be \c NULL, in which * case this function returns immediately. If it is not * \c NULL, it must point to an initialized ECP group. */ void mbedtls_ecp_group_free( mbedtls_ecp_group *grp ); /** * \brief This function frees the components of a key pair. * * \param key The key pair to free. This may be \c NULL, in which * case this function returns immediately. If it is not * \c NULL, it must point to an initialized ECP key pair. */ void mbedtls_ecp_keypair_free( mbedtls_ecp_keypair *key ); #if defined(MBEDTLS_ECP_RESTARTABLE) /** * \brief Initialize a restart context. * * \param ctx The restart context to initialize. This must * not be \c NULL. */ void mbedtls_ecp_restart_init( mbedtls_ecp_restart_ctx *ctx ); /** * \brief Free the components of a restart context. * * \param ctx The restart context to free. This may be \c NULL, in which * case this function returns immediately. If it is not * \c NULL, it must point to an initialized restart context. */ void mbedtls_ecp_restart_free( mbedtls_ecp_restart_ctx *ctx ); #endif /* MBEDTLS_ECP_RESTARTABLE */ /** * \brief This function copies the contents of point \p Q into * point \p P. * * \param P The destination point. This must be initialized. * \param Q The source point. This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return Another negative error code for other kinds of failure. */ int mbedtls_ecp_copy( mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ); /** * \brief This function copies the contents of group \p src into * group \p dst. * * \param dst The destination group. This must be initialized. * \param src The source group. This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_group_copy( mbedtls_ecp_group *dst, const mbedtls_ecp_group *src ); /** * \brief This function sets a point to the point at infinity. * * \param pt The point to set. This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_set_zero( mbedtls_ecp_point *pt ); /** * \brief This function checks if a point is the point at infinity. * * \param pt The point to test. This must be initialized. * * \return \c 1 if the point is zero. * \return \c 0 if the point is non-zero. * \return A negative error code on failure. */ int mbedtls_ecp_is_zero( mbedtls_ecp_point *pt ); /** * \brief This function compares two points. * * \note This assumes that the points are normalized. Otherwise, * they may compare as "not equal" even if they are. * * \param P The first point to compare. This must be initialized. * \param Q The second point to compare. This must be initialized. * * \return \c 0 if the points are equal. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the points are not equal. */ int mbedtls_ecp_point_cmp( const mbedtls_ecp_point *P, const mbedtls_ecp_point *Q ); /** * \brief This function imports a non-zero point from two ASCII * strings. * * \param P The destination point. This must be initialized. * \param radix The numeric base of the input. * \param x The first affine coordinate, as a null-terminated string. * \param y The second affine coordinate, as a null-terminated string. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_MPI_XXX error code on failure. */ int mbedtls_ecp_point_read_string( mbedtls_ecp_point *P, int radix, const char *x, const char *y ); /** * \brief This function exports a point into unsigned binary data. * * \param grp The group to which the point should belong. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param P The point to export. This must be initialized. * \param format The point format. This must be either * #MBEDTLS_ECP_PF_COMPRESSED or #MBEDTLS_ECP_PF_UNCOMPRESSED. * (For groups without these formats, this parameter is * ignored. But it still has to be either of the above * values.) * \param olen The address at which to store the length of * the output in Bytes. This must not be \c NULL. * \param buf The output buffer. This must be a writable buffer * of length \p buflen Bytes. * \param buflen The length of the output buffer \p buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the output buffer * is too small to hold the point. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the point format * or the export for the given group is not implemented. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_point_write_binary( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *P, int format, size_t *olen, unsigned char *buf, size_t buflen ); /** * \brief This function imports a point from unsigned binary data. * * \note This function does not check that the point actually * belongs to the given group, see mbedtls_ecp_check_pubkey() * for that. * * \param grp The group to which the point should belong. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param P The destination context to import the point to. * This must be initialized. * \param buf The input buffer. This must be a readable buffer * of length \p ilen Bytes. * \param ilen The length of the input buffer \p buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the input is invalid. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the import for the * given group is not implemented. */ int mbedtls_ecp_point_read_binary( const mbedtls_ecp_group *grp, mbedtls_ecp_point *P, const unsigned char *buf, size_t ilen ); /** * \brief This function imports a point from a TLS ECPoint record. * * \note On function return, \p *buf is updated to point immediately * after the ECPoint record. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param pt The destination point. * \param buf The address of the pointer to the start of the input buffer. * \param len The length of the buffer. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_MPI_XXX error code on initialization * failure. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. */ int mbedtls_ecp_tls_read_point( const mbedtls_ecp_group *grp, mbedtls_ecp_point *pt, const unsigned char **buf, size_t len ); /** * \brief This function exports a point as a TLS ECPoint record * defined in RFC 4492, Section 5.4. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param pt The point to be exported. This must be initialized. * \param format The point format to use. This must be either * #MBEDTLS_ECP_PF_COMPRESSED or #MBEDTLS_ECP_PF_UNCOMPRESSED. * \param olen The address at which to store the length in Bytes * of the data written. * \param buf The target buffer. This must be a writable buffer of * length \p blen Bytes. * \param blen The length of the target buffer \p buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the input is invalid. * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the target buffer * is too small to hold the exported point. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_tls_write_point( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt, int format, size_t *olen, unsigned char *buf, size_t blen ); /** * \brief This function sets up an ECP group context * from a standardized set of domain parameters. * * \note The index should be a value of the NamedCurve enum, * as defined in <em>RFC-4492: Elliptic Curve Cryptography * (ECC) Cipher Suites for Transport Layer Security (TLS)</em>, * usually in the form of an \c MBEDTLS_ECP_DP_XXX macro. * * \param grp The group context to setup. This must be initialized. * \param id The identifier of the domain parameter set to load. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if \p id doesn't * correspond to a known group. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_group_load( mbedtls_ecp_group *grp, mbedtls_ecp_group_id id ); /** * \brief This function sets up an ECP group context from a TLS * ECParameters record as defined in RFC 4492, Section 5.4. * * \note The read pointer \p buf is updated to point right after * the ECParameters record on exit. * * \param grp The group context to setup. This must be initialized. * \param buf The address of the pointer to the start of the input buffer. * \param len The length of the input buffer \c *buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the group is not * recognized. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_tls_read_group( mbedtls_ecp_group *grp, const unsigned char **buf, size_t len ); /** * \brief This function extracts an elliptic curve group ID from a * TLS ECParameters record as defined in RFC 4492, Section 5.4. * * \note The read pointer \p buf is updated to point right after * the ECParameters record on exit. * * \param grp The address at which to store the group id. * This must not be \c NULL. * \param buf The address of the pointer to the start of the input buffer. * \param len The length of the input buffer \c *buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if input is invalid. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the group is not * recognized. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_tls_read_group_id( mbedtls_ecp_group_id *grp, const unsigned char **buf, size_t len ); /** * \brief This function exports an elliptic curve as a TLS * ECParameters record as defined in RFC 4492, Section 5.4. * * \param grp The ECP group to be exported. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param olen The address at which to store the number of Bytes written. * This must not be \c NULL. * \param buf The buffer to write to. This must be a writable buffer * of length \p blen Bytes. * \param blen The length of the output buffer \p buf in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the output * buffer is too small to hold the exported group. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_tls_write_group( const mbedtls_ecp_group *grp, size_t *olen, unsigned char *buf, size_t blen ); /** * \brief This function performs a scalar multiplication of a point * by an integer: \p R = \p m * \p P. * * It is not thread-safe to use same group in multiple threads. * * \note To prevent timing attacks, this function * executes the exact same sequence of base-field * operations for any valid \p m. It avoids any if-branch or * array index depending on the value of \p m. * * \note If \p f_rng is not NULL, it is used to randomize * intermediate results to prevent potential timing attacks * targeting these results. We recommend always providing * a non-NULL \p f_rng. The overhead is negligible. * Note: unless #MBEDTLS_ECP_NO_INTERNAL_RNG is defined, when * \p f_rng is NULL, an internal RNG (seeded from the value * of \p m) will be used instead. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param R The point in which to store the result of the calculation. * This must be initialized. * \param m The integer by which to multiply. This must be initialized. * \param P The point to multiply. This must be initialized. * \param f_rng The RNG function. This may be \c NULL if randomization * of intermediate results isn't desired (discouraged). * \param p_rng The RNG context to be passed to \p p_rng. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private * key, or \p P is not a valid public key. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_mul( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function performs multiplication of a point by * an integer: \p R = \p m * \p P in a restartable way. * * \see mbedtls_ecp_mul() * * \note This function does the same as \c mbedtls_ecp_mul(), but * it can return early and restart according to the limit set * with \c mbedtls_ecp_set_max_ops() to reduce blocking. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param R The point in which to store the result of the calculation. * This must be initialized. * \param m The integer by which to multiply. This must be initialized. * \param P The point to multiply. This must be initialized. * \param f_rng The RNG function. This may be \c NULL if randomization * of intermediate results isn't desired (discouraged). * \param p_rng The RNG context to be passed to \p p_rng. * \param rs_ctx The restart context (NULL disables restart). * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m is not a valid private * key, or \p P is not a valid public key. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_mul_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng, mbedtls_ecp_restart_ctx *rs_ctx ); #if defined(MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED) /** * \brief This function performs multiplication and addition of two * points by integers: \p R = \p m * \p P + \p n * \p Q * * It is not thread-safe to use same group in multiple threads. * * \note In contrast to mbedtls_ecp_mul(), this function does not * guarantee a constant execution flow and timing. * * \note This function is only defined for short Weierstrass curves. * It may not be included in builds without any short * Weierstrass curve. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param R The point in which to store the result of the calculation. * This must be initialized. * \param m The integer by which to multiply \p P. * This must be initialized. * \param P The point to multiply by \p m. This must be initialized. * \param n The integer by which to multiply \p Q. * This must be initialized. * \param Q The point to be multiplied by \p n. * This must be initialized. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not * valid private keys, or \p P or \p Q are not valid public * keys. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if \p grp does not * designate a short Weierstrass curve. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_muladd( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, const mbedtls_mpi *n, const mbedtls_ecp_point *Q ); /** * \brief This function performs multiplication and addition of two * points by integers: \p R = \p m * \p P + \p n * \p Q in a * restartable way. * * \see \c mbedtls_ecp_muladd() * * \note This function works the same as \c mbedtls_ecp_muladd(), * but it can return early and restart according to the limit * set with \c mbedtls_ecp_set_max_ops() to reduce blocking. * * \note This function is only defined for short Weierstrass curves. * It may not be included in builds without any short * Weierstrass curve. * * \param grp The ECP group to use. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param R The point in which to store the result of the calculation. * This must be initialized. * \param m The integer by which to multiply \p P. * This must be initialized. * \param P The point to multiply by \p m. This must be initialized. * \param n The integer by which to multiply \p Q. * This must be initialized. * \param Q The point to be multiplied by \p n. * This must be initialized. * \param rs_ctx The restart context (NULL disables restart). * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if \p m or \p n are not * valid private keys, or \p P or \p Q are not valid public * keys. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED on memory-allocation failure. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if \p grp does not * designate a short Weierstrass curve. * \return #MBEDTLS_ERR_ECP_IN_PROGRESS if maximum number of * operations was reached: see \c mbedtls_ecp_set_max_ops(). * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_muladd_restartable( mbedtls_ecp_group *grp, mbedtls_ecp_point *R, const mbedtls_mpi *m, const mbedtls_ecp_point *P, const mbedtls_mpi *n, const mbedtls_ecp_point *Q, mbedtls_ecp_restart_ctx *rs_ctx ); #endif /* MBEDTLS_ECP_SHORT_WEIERSTRASS_ENABLED */ /** * \brief This function checks that a point is a valid public key * on this curve. * * It only checks that the point is non-zero, has * valid coordinates and lies on the curve. It does not verify * that it is indeed a multiple of \p G. This additional * check is computationally more expensive, is not required * by standards, and should not be necessary if the group * used has a small cofactor. In particular, it is useless for * the NIST groups which all have a cofactor of 1. * * \note This function uses bare components rather than an * ::mbedtls_ecp_keypair structure, to ease use with other * structures, such as ::mbedtls_ecdh_context or * ::mbedtls_ecdsa_context. * * \param grp The ECP group the point should belong to. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param pt The point to check. This must be initialized. * * \return \c 0 if the point is a valid public key. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if the point is not * a valid public key for the given curve. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_check_pubkey( const mbedtls_ecp_group *grp, const mbedtls_ecp_point *pt ); /** * \brief This function checks that an \p mbedtls_mpi is a * valid private key for this curve. * * \note This function uses bare components rather than an * ::mbedtls_ecp_keypair structure to ease use with other * structures, such as ::mbedtls_ecdh_context or * ::mbedtls_ecdsa_context. * * \param grp The ECP group the private key should belong to. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param d The integer to check. This must be initialized. * * \return \c 0 if the point is a valid private key. * \return #MBEDTLS_ERR_ECP_INVALID_KEY if the point is not a valid * private key for the given curve. * \return Another negative error code on other kinds of failure. */ int mbedtls_ecp_check_privkey( const mbedtls_ecp_group *grp, const mbedtls_mpi *d ); /** * \brief This function generates a private key. * * \param grp The ECP group to generate a private key for. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param d The destination MPI (secret part). This must be initialized. * \param f_rng The RNG function. This must not be \c NULL. * \param p_rng The RNG parameter to be passed to \p f_rng. This may be * \c NULL if \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code * on failure. */ int mbedtls_ecp_gen_privkey( const mbedtls_ecp_group *grp, mbedtls_mpi *d, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function generates a keypair with a configurable base * point. * * \note This function uses bare components rather than an * ::mbedtls_ecp_keypair structure to ease use with other * structures, such as ::mbedtls_ecdh_context or * ::mbedtls_ecdsa_context. * * \param grp The ECP group to generate a key pair for. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param G The base point to use. This must be initialized * and belong to \p grp. It replaces the default base * point \c grp->G used by mbedtls_ecp_gen_keypair(). * \param d The destination MPI (secret part). * This must be initialized. * \param Q The destination point (public part). * This must be initialized. * \param f_rng The RNG function. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may * be \c NULL if \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code * on failure. */ int mbedtls_ecp_gen_keypair_base( mbedtls_ecp_group *grp, const mbedtls_ecp_point *G, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function generates an ECP keypair. * * \note This function uses bare components rather than an * ::mbedtls_ecp_keypair structure to ease use with other * structures, such as ::mbedtls_ecdh_context or * ::mbedtls_ecdsa_context. * * \param grp The ECP group to generate a key pair for. * This must be initialized and have group parameters * set, for example through mbedtls_ecp_group_load(). * \param d The destination MPI (secret part). * This must be initialized. * \param Q The destination point (public part). * This must be initialized. * \param f_rng The RNG function. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may * be \c NULL if \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code * on failure. */ int mbedtls_ecp_gen_keypair( mbedtls_ecp_group *grp, mbedtls_mpi *d, mbedtls_ecp_point *Q, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function generates an ECP key. * * \param grp_id The ECP group identifier. * \param key The destination key. This must be initialized. * \param f_rng The RNG function to use. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may * be \c NULL if \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_ECP_XXX or \c MBEDTLS_MPI_XXX error code * on failure. */ int mbedtls_ecp_gen_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function reads an elliptic curve private key. * * \param grp_id The ECP group identifier. * \param key The destination key. * \param buf The buffer containing the binary representation of the * key. (Big endian integer for Weierstrass curves, byte * string for Montgomery curves.) * \param buflen The length of the buffer in bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_INVALID_KEY error if the key is * invalid. * \return #MBEDTLS_ERR_MPI_ALLOC_FAILED if memory allocation failed. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the operation for * the group is not implemented. * \return Another negative error code on different kinds of failure. */ int mbedtls_ecp_read_key( mbedtls_ecp_group_id grp_id, mbedtls_ecp_keypair *key, const unsigned char *buf, size_t buflen ); /** * \brief This function exports an elliptic curve private key. * * \param key The private key. * \param buf The output buffer for containing the binary representation * of the key. (Big endian integer for Weierstrass curves, byte * string for Montgomery curves.) * \param buflen The total length of the buffer in bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL if the \p key representation is larger than the available space in \p buf. * \return #MBEDTLS_ERR_ECP_FEATURE_UNAVAILABLE if the operation for * the group is not implemented. * \return Another negative error code on different kinds of failure. */ int mbedtls_ecp_write_key( mbedtls_ecp_keypair *key, unsigned char *buf, size_t buflen ); /** * \brief This function checks that the keypair objects * \p pub and \p prv have the same group and the * same public point, and that the private key in * \p prv is consistent with the public key. * * \param pub The keypair structure holding the public key. This * must be initialized. If it contains a private key, that * part is ignored. * \param prv The keypair structure holding the full keypair. * This must be initialized. * * \return \c 0 on success, meaning that the keys are valid and match. * \return #MBEDTLS_ERR_ECP_BAD_INPUT_DATA if the keys are invalid or do not match. * \return An \c MBEDTLS_ERR_ECP_XXX or an \c MBEDTLS_ERR_MPI_XXX * error code on calculation failure. */ int mbedtls_ecp_check_pub_priv( const mbedtls_ecp_keypair *pub, const mbedtls_ecp_keypair *prv ); #if defined(MBEDTLS_SELF_TEST) /** * \brief The ECP checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_ecp_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* ecp.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/ssl_cookie.h
/** * \file ssl_cookie.h * * \brief DTLS cookie callbacks implementation */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_SSL_COOKIE_H #define MBEDTLS_SSL_COOKIE_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/ssl.h" #if defined(MBEDTLS_THREADING_C) #include "mbedtls/threading.h" #endif /** * \name SECTION: Module settings * * The configuration options you can set for this module are in this section. * Either change them in config.h or define them on the compiler command line. * \{ */ #ifndef MBEDTLS_SSL_COOKIE_TIMEOUT #define MBEDTLS_SSL_COOKIE_TIMEOUT 60 /**< Default expiration delay of DTLS cookies, in seconds if HAVE_TIME, or in number of cookies issued */ #endif /* \} name SECTION: Module settings */ #ifdef __cplusplus extern "C" { #endif /** * \brief Context for the default cookie functions. */ typedef struct mbedtls_ssl_cookie_ctx { mbedtls_md_context_t hmac_ctx; /*!< context for the HMAC portion */ #if !defined(MBEDTLS_HAVE_TIME) unsigned long serial; /*!< serial number for expiration */ #endif unsigned long timeout; /*!< timeout delay, in seconds if HAVE_TIME, or in number of tickets issued */ #if defined(MBEDTLS_THREADING_C) mbedtls_threading_mutex_t mutex; #endif } mbedtls_ssl_cookie_ctx; /** * \brief Initialize cookie context */ void mbedtls_ssl_cookie_init( mbedtls_ssl_cookie_ctx *ctx ); /** * \brief Setup cookie context (generate keys) */ int mbedtls_ssl_cookie_setup( mbedtls_ssl_cookie_ctx *ctx, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief Set expiration delay for cookies * (Default MBEDTLS_SSL_COOKIE_TIMEOUT) * * \param ctx Cookie contex * \param delay Delay, in seconds if HAVE_TIME, or in number of cookies * issued in the meantime. * 0 to disable expiration (NOT recommended) */ void mbedtls_ssl_cookie_set_timeout( mbedtls_ssl_cookie_ctx *ctx, unsigned long delay ); /** * \brief Free cookie context */ void mbedtls_ssl_cookie_free( mbedtls_ssl_cookie_ctx *ctx ); /** * \brief Generate cookie, see \c mbedtls_ssl_cookie_write_t */ mbedtls_ssl_cookie_write_t mbedtls_ssl_cookie_write; /** * \brief Verify cookie, see \c mbedtls_ssl_cookie_write_t */ mbedtls_ssl_cookie_check_t mbedtls_ssl_cookie_check; #ifdef __cplusplus } #endif #endif /* ssl_cookie.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/md.h
/** * \file md.h * * \brief This file contains the generic message-digest wrapper. * * \author Adriaan de Jong <[email protected]> */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_MD_H #define MBEDTLS_MD_H #include <stddef.h> #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #define MBEDTLS_ERR_MD_FEATURE_UNAVAILABLE -0x5080 /**< The selected feature is not available. */ #define MBEDTLS_ERR_MD_BAD_INPUT_DATA -0x5100 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_MD_ALLOC_FAILED -0x5180 /**< Failed to allocate memory. */ #define MBEDTLS_ERR_MD_FILE_IO_ERROR -0x5200 /**< Opening or reading of file failed. */ /* MBEDTLS_ERR_MD_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_MD_HW_ACCEL_FAILED -0x5280 /**< MD hardware accelerator failed. */ #ifdef __cplusplus extern "C" { #endif /** * \brief Supported message digests. * * \warning MD2, MD4, MD5 and SHA-1 are considered weak message digests and * their use constitutes a security risk. We recommend considering * stronger message digests instead. * */ typedef enum { MBEDTLS_MD_NONE=0, /**< None. */ MBEDTLS_MD_MD2, /**< The MD2 message digest. */ MBEDTLS_MD_MD4, /**< The MD4 message digest. */ MBEDTLS_MD_MD5, /**< The MD5 message digest. */ MBEDTLS_MD_SHA1, /**< The SHA-1 message digest. */ MBEDTLS_MD_SHA224, /**< The SHA-224 message digest. */ MBEDTLS_MD_SHA256, /**< The SHA-256 message digest. */ MBEDTLS_MD_SHA384, /**< The SHA-384 message digest. */ MBEDTLS_MD_SHA512, /**< The SHA-512 message digest. */ MBEDTLS_MD_RIPEMD160, /**< The RIPEMD-160 message digest. */ } mbedtls_md_type_t; #if defined(MBEDTLS_SHA512_C) #define MBEDTLS_MD_MAX_SIZE 64 /* longest known is SHA512 */ #else #define MBEDTLS_MD_MAX_SIZE 32 /* longest known is SHA256 or less */ #endif #if defined(MBEDTLS_SHA512_C) #define MBEDTLS_MD_MAX_BLOCK_SIZE 128 #else #define MBEDTLS_MD_MAX_BLOCK_SIZE 64 #endif /** * Opaque struct defined in md_internal.h. */ typedef struct mbedtls_md_info_t mbedtls_md_info_t; /** * The generic message-digest context. */ typedef struct mbedtls_md_context_t { /** Information about the associated message digest. */ const mbedtls_md_info_t *md_info; /** The digest-specific context. */ void *md_ctx; /** The HMAC part of the context. */ void *hmac_ctx; } mbedtls_md_context_t; /** * \brief This function returns the list of digests supported by the * generic digest module. * * \note The list starts with the strongest available hashes. * * \return A statically allocated array of digests. Each element * in the returned list is an integer belonging to the * message-digest enumeration #mbedtls_md_type_t. * The last entry is 0. */ const int *mbedtls_md_list( void ); /** * \brief This function returns the message-digest information * associated with the given digest name. * * \param md_name The name of the digest to search for. * * \return The message-digest information associated with \p md_name. * \return NULL if the associated message-digest information is not found. */ const mbedtls_md_info_t *mbedtls_md_info_from_string( const char *md_name ); /** * \brief This function returns the message-digest information * associated with the given digest type. * * \param md_type The type of digest to search for. * * \return The message-digest information associated with \p md_type. * \return NULL if the associated message-digest information is not found. */ const mbedtls_md_info_t *mbedtls_md_info_from_type( mbedtls_md_type_t md_type ); /** * \brief This function initializes a message-digest context without * binding it to a particular message-digest algorithm. * * This function should always be called first. It prepares the * context for mbedtls_md_setup() for binding it to a * message-digest algorithm. */ void mbedtls_md_init( mbedtls_md_context_t *ctx ); /** * \brief This function clears the internal structure of \p ctx and * frees any embedded internal structure, but does not free * \p ctx itself. * * If you have called mbedtls_md_setup() on \p ctx, you must * call mbedtls_md_free() when you are no longer using the * context. * Calling this function if you have previously * called mbedtls_md_init() and nothing else is optional. * You must not call this function if you have not called * mbedtls_md_init(). */ void mbedtls_md_free( mbedtls_md_context_t *ctx ); #if ! defined(MBEDTLS_DEPRECATED_REMOVED) #if defined(MBEDTLS_DEPRECATED_WARNING) #define MBEDTLS_DEPRECATED __attribute__((deprecated)) #else #define MBEDTLS_DEPRECATED #endif /** * \brief This function selects the message digest algorithm to use, * and allocates internal structures. * * It should be called after mbedtls_md_init() or mbedtls_md_free(). * Makes it necessary to call mbedtls_md_free() later. * * \deprecated Superseded by mbedtls_md_setup() in 2.0.0 * * \param ctx The context to set up. * \param md_info The information structure of the message-digest algorithm * to use. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. * \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_md_init_ctx( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info ) MBEDTLS_DEPRECATED; #undef MBEDTLS_DEPRECATED #endif /* MBEDTLS_DEPRECATED_REMOVED */ /** * \brief This function selects the message digest algorithm to use, * and allocates internal structures. * * It should be called after mbedtls_md_init() or * mbedtls_md_free(). Makes it necessary to call * mbedtls_md_free() later. * * \param ctx The context to set up. * \param md_info The information structure of the message-digest algorithm * to use. * \param hmac Defines if HMAC is used. 0: HMAC is not used (saves some memory), * or non-zero: HMAC is used with this context. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. * \return #MBEDTLS_ERR_MD_ALLOC_FAILED on memory-allocation failure. */ int mbedtls_md_setup( mbedtls_md_context_t *ctx, const mbedtls_md_info_t *md_info, int hmac ); /** * \brief This function clones the state of an message-digest * context. * * \note You must call mbedtls_md_setup() on \c dst before calling * this function. * * \note The two contexts must have the same type, * for example, both are SHA-256. * * \warning This function clones the message-digest state, not the * HMAC state. * * \param dst The destination context. * \param src The context to be cloned. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification failure. */ int mbedtls_md_clone( mbedtls_md_context_t *dst, const mbedtls_md_context_t *src ); /** * \brief This function extracts the message-digest size from the * message-digest information structure. * * \param md_info The information structure of the message-digest algorithm * to use. * * \return The size of the message-digest output in Bytes. */ unsigned char mbedtls_md_get_size( const mbedtls_md_info_t *md_info ); /** * \brief This function extracts the message-digest type from the * message-digest information structure. * * \param md_info The information structure of the message-digest algorithm * to use. * * \return The type of the message digest. */ mbedtls_md_type_t mbedtls_md_get_type( const mbedtls_md_info_t *md_info ); /** * \brief This function extracts the message-digest name from the * message-digest information structure. * * \param md_info The information structure of the message-digest algorithm * to use. * * \return The name of the message digest. */ const char *mbedtls_md_get_name( const mbedtls_md_info_t *md_info ); /** * \brief This function starts a message-digest computation. * * You must call this function after setting up the context * with mbedtls_md_setup(), and before passing data with * mbedtls_md_update(). * * \param ctx The generic message-digest context. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_starts( mbedtls_md_context_t *ctx ); /** * \brief This function feeds an input buffer into an ongoing * message-digest computation. * * You must call mbedtls_md_starts() before calling this * function. You may call this function multiple times. * Afterwards, call mbedtls_md_finish(). * * \param ctx The generic message-digest context. * \param input The buffer holding the input data. * \param ilen The length of the input data. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen ); /** * \brief This function finishes the digest operation, * and writes the result to the output buffer. * * Call this function after a call to mbedtls_md_starts(), * followed by any number of calls to mbedtls_md_update(). * Afterwards, you may either clear the context with * mbedtls_md_free(), or call mbedtls_md_starts() to reuse * the context for another digest operation with the same * algorithm. * * \param ctx The generic message-digest context. * \param output The buffer for the generic message-digest checksum result. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_finish( mbedtls_md_context_t *ctx, unsigned char *output ); /** * \brief This function calculates the message-digest of a buffer, * with respect to a configurable message-digest algorithm * in a single call. * * The result is calculated as * Output = message_digest(input buffer). * * \param md_info The information structure of the message-digest algorithm * to use. * \param input The buffer holding the data. * \param ilen The length of the input data. * \param output The generic message-digest checksum result. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md( const mbedtls_md_info_t *md_info, const unsigned char *input, size_t ilen, unsigned char *output ); #if defined(MBEDTLS_FS_IO) /** * \brief This function calculates the message-digest checksum * result of the contents of the provided file. * * The result is calculated as * Output = message_digest(file contents). * * \param md_info The information structure of the message-digest algorithm * to use. * \param path The input file name. * \param output The generic message-digest checksum result. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_FILE_IO_ERROR on an I/O error accessing * the file pointed by \p path. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info was NULL. */ int mbedtls_md_file( const mbedtls_md_info_t *md_info, const char *path, unsigned char *output ); #endif /* MBEDTLS_FS_IO */ /** * \brief This function sets the HMAC key and prepares to * authenticate a new message. * * Call this function after mbedtls_md_setup(), to use * the MD context for an HMAC calculation, then call * mbedtls_md_hmac_update() to provide the input data, and * mbedtls_md_hmac_finish() to get the HMAC value. * * \param ctx The message digest context containing an embedded HMAC * context. * \param key The HMAC secret key. * \param keylen The length of the HMAC key in Bytes. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_hmac_starts( mbedtls_md_context_t *ctx, const unsigned char *key, size_t keylen ); /** * \brief This function feeds an input buffer into an ongoing HMAC * computation. * * Call mbedtls_md_hmac_starts() or mbedtls_md_hmac_reset() * before calling this function. * You may call this function multiple times to pass the * input piecewise. * Afterwards, call mbedtls_md_hmac_finish(). * * \param ctx The message digest context containing an embedded HMAC * context. * \param input The buffer holding the input data. * \param ilen The length of the input data. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_hmac_update( mbedtls_md_context_t *ctx, const unsigned char *input, size_t ilen ); /** * \brief This function finishes the HMAC operation, and writes * the result to the output buffer. * * Call this function after mbedtls_md_hmac_starts() and * mbedtls_md_hmac_update() to get the HMAC value. Afterwards * you may either call mbedtls_md_free() to clear the context, * or call mbedtls_md_hmac_reset() to reuse the context with * the same HMAC key. * * \param ctx The message digest context containing an embedded HMAC * context. * \param output The generic HMAC checksum result. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_hmac_finish( mbedtls_md_context_t *ctx, unsigned char *output); /** * \brief This function prepares to authenticate a new message with * the same key as the previous HMAC operation. * * You may call this function after mbedtls_md_hmac_finish(). * Afterwards call mbedtls_md_hmac_update() to pass the new * input. * * \param ctx The message digest context containing an embedded HMAC * context. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_hmac_reset( mbedtls_md_context_t *ctx ); /** * \brief This function calculates the full generic HMAC * on the input buffer with the provided key. * * The function allocates the context, performs the * calculation, and frees the context. * * The HMAC result is calculated as * output = generic HMAC(hmac key, input buffer). * * \param md_info The information structure of the message-digest algorithm * to use. * \param key The HMAC secret key. * \param keylen The length of the HMAC secret key in Bytes. * \param input The buffer holding the input data. * \param ilen The length of the input data. * \param output The generic HMAC result. * * \return \c 0 on success. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA on parameter-verification * failure. */ int mbedtls_md_hmac( const mbedtls_md_info_t *md_info, const unsigned char *key, size_t keylen, const unsigned char *input, size_t ilen, unsigned char *output ); /* Internal use */ int mbedtls_md_process( mbedtls_md_context_t *ctx, const unsigned char *data ); #ifdef __cplusplus } #endif #endif /* MBEDTLS_MD_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/cipher_internal.h
/** * \file cipher_internal.h * * \brief Cipher wrappers. * * \author Adriaan de Jong <[email protected]> */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_CIPHER_WRAP_H #define MBEDTLS_CIPHER_WRAP_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/cipher.h" #if defined(MBEDTLS_USE_PSA_CRYPTO) #include "psa/crypto.h" #endif /* MBEDTLS_USE_PSA_CRYPTO */ #ifdef __cplusplus extern "C" { #endif /** * Base cipher information. The non-mode specific functions and values. */ struct mbedtls_cipher_base_t { /** Base Cipher type (e.g. MBEDTLS_CIPHER_ID_AES) */ mbedtls_cipher_id_t cipher; /** Encrypt using ECB */ int (*ecb_func)( void *ctx, mbedtls_operation_t mode, const unsigned char *input, unsigned char *output ); #if defined(MBEDTLS_CIPHER_MODE_CBC) /** Encrypt using CBC */ int (*cbc_func)( void *ctx, mbedtls_operation_t mode, size_t length, unsigned char *iv, const unsigned char *input, unsigned char *output ); #endif #if defined(MBEDTLS_CIPHER_MODE_CFB) /** Encrypt using CFB (Full length) */ int (*cfb_func)( void *ctx, mbedtls_operation_t mode, size_t length, size_t *iv_off, unsigned char *iv, const unsigned char *input, unsigned char *output ); #endif #if defined(MBEDTLS_CIPHER_MODE_OFB) /** Encrypt using OFB (Full length) */ int (*ofb_func)( void *ctx, size_t length, size_t *iv_off, unsigned char *iv, const unsigned char *input, unsigned char *output ); #endif #if defined(MBEDTLS_CIPHER_MODE_CTR) /** Encrypt using CTR */ int (*ctr_func)( void *ctx, size_t length, size_t *nc_off, unsigned char *nonce_counter, unsigned char *stream_block, const unsigned char *input, unsigned char *output ); #endif #if defined(MBEDTLS_CIPHER_MODE_XTS) /** Encrypt or decrypt using XTS. */ int (*xts_func)( void *ctx, mbedtls_operation_t mode, size_t length, const unsigned char data_unit[16], const unsigned char *input, unsigned char *output ); #endif #if defined(MBEDTLS_CIPHER_MODE_STREAM) /** Encrypt using STREAM */ int (*stream_func)( void *ctx, size_t length, const unsigned char *input, unsigned char *output ); #endif /** Set key for encryption purposes */ int (*setkey_enc_func)( void *ctx, const unsigned char *key, unsigned int key_bitlen ); /** Set key for decryption purposes */ int (*setkey_dec_func)( void *ctx, const unsigned char *key, unsigned int key_bitlen); /** Allocate a new context */ void * (*ctx_alloc_func)( void ); /** Free the given context */ void (*ctx_free_func)( void *ctx ); }; typedef struct { mbedtls_cipher_type_t type; const mbedtls_cipher_info_t *info; } mbedtls_cipher_definition_t; #if defined(MBEDTLS_USE_PSA_CRYPTO) typedef enum { MBEDTLS_CIPHER_PSA_KEY_UNSET = 0, MBEDTLS_CIPHER_PSA_KEY_OWNED, /* Used for PSA-based cipher contexts which */ /* use raw key material internally imported */ /* as a volatile key, and which hence need */ /* to destroy that key when the context is */ /* freed. */ MBEDTLS_CIPHER_PSA_KEY_NOT_OWNED, /* Used for PSA-based cipher contexts */ /* which use a key provided by the */ /* user, and which hence will not be */ /* destroyed when the context is freed. */ } mbedtls_cipher_psa_key_ownership; typedef struct { psa_algorithm_t alg; psa_key_id_t slot; mbedtls_cipher_psa_key_ownership slot_state; } mbedtls_cipher_context_psa; #endif /* MBEDTLS_USE_PSA_CRYPTO */ extern const mbedtls_cipher_definition_t mbedtls_cipher_definitions[]; extern int mbedtls_cipher_supported[]; #ifdef __cplusplus } #endif #endif /* MBEDTLS_CIPHER_WRAP_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/psa_util.h
/** * \file psa_util.h * * \brief Utility functions for the use of the PSA Crypto library. * * \warning This function is not part of the public API and may * change at any time. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_PSA_UTIL_H #define MBEDTLS_PSA_UTIL_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_USE_PSA_CRYPTO) #include "psa/crypto.h" #include "mbedtls/ecp.h" #include "mbedtls/md.h" #include "mbedtls/pk.h" #include "mbedtls/oid.h" #include <string.h> /* Translations for symmetric crypto. */ static inline psa_key_type_t mbedtls_psa_translate_cipher_type( mbedtls_cipher_type_t cipher ) { switch( cipher ) { case MBEDTLS_CIPHER_AES_128_CCM: case MBEDTLS_CIPHER_AES_192_CCM: case MBEDTLS_CIPHER_AES_256_CCM: case MBEDTLS_CIPHER_AES_128_GCM: case MBEDTLS_CIPHER_AES_192_GCM: case MBEDTLS_CIPHER_AES_256_GCM: case MBEDTLS_CIPHER_AES_128_CBC: case MBEDTLS_CIPHER_AES_192_CBC: case MBEDTLS_CIPHER_AES_256_CBC: return( PSA_KEY_TYPE_AES ); /* ARIA not yet supported in PSA. */ /* case MBEDTLS_CIPHER_ARIA_128_CCM: case MBEDTLS_CIPHER_ARIA_192_CCM: case MBEDTLS_CIPHER_ARIA_256_CCM: case MBEDTLS_CIPHER_ARIA_128_GCM: case MBEDTLS_CIPHER_ARIA_192_GCM: case MBEDTLS_CIPHER_ARIA_256_GCM: case MBEDTLS_CIPHER_ARIA_128_CBC: case MBEDTLS_CIPHER_ARIA_192_CBC: case MBEDTLS_CIPHER_ARIA_256_CBC: return( PSA_KEY_TYPE_ARIA ); */ default: return( 0 ); } } static inline psa_algorithm_t mbedtls_psa_translate_cipher_mode( mbedtls_cipher_mode_t mode, size_t taglen ) { switch( mode ) { case MBEDTLS_MODE_ECB: return( PSA_ALG_ECB_NO_PADDING ); case MBEDTLS_MODE_GCM: return( PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_GCM, taglen ) ); case MBEDTLS_MODE_CCM: return( PSA_ALG_AEAD_WITH_SHORTENED_TAG( PSA_ALG_CCM, taglen ) ); case MBEDTLS_MODE_CBC: if( taglen == 0 ) return( PSA_ALG_CBC_NO_PADDING ); else return( 0 ); default: return( 0 ); } } static inline psa_key_usage_t mbedtls_psa_translate_cipher_operation( mbedtls_operation_t op ) { switch( op ) { case MBEDTLS_ENCRYPT: return( PSA_KEY_USAGE_ENCRYPT ); case MBEDTLS_DECRYPT: return( PSA_KEY_USAGE_DECRYPT ); default: return( 0 ); } } /* Translations for hashing. */ static inline psa_algorithm_t mbedtls_psa_translate_md( mbedtls_md_type_t md_alg ) { switch( md_alg ) { #if defined(MBEDTLS_MD2_C) case MBEDTLS_MD_MD2: return( PSA_ALG_MD2 ); #endif #if defined(MBEDTLS_MD4_C) case MBEDTLS_MD_MD4: return( PSA_ALG_MD4 ); #endif #if defined(MBEDTLS_MD5_C) case MBEDTLS_MD_MD5: return( PSA_ALG_MD5 ); #endif #if defined(MBEDTLS_SHA1_C) case MBEDTLS_MD_SHA1: return( PSA_ALG_SHA_1 ); #endif #if defined(MBEDTLS_SHA256_C) case MBEDTLS_MD_SHA224: return( PSA_ALG_SHA_224 ); case MBEDTLS_MD_SHA256: return( PSA_ALG_SHA_256 ); #endif #if defined(MBEDTLS_SHA512_C) case MBEDTLS_MD_SHA384: return( PSA_ALG_SHA_384 ); case MBEDTLS_MD_SHA512: return( PSA_ALG_SHA_512 ); #endif #if defined(MBEDTLS_RIPEMD160_C) case MBEDTLS_MD_RIPEMD160: return( PSA_ALG_RIPEMD160 ); #endif case MBEDTLS_MD_NONE: return( 0 ); default: return( 0 ); } } /* Translations for ECC. */ static inline int mbedtls_psa_get_ecc_oid_from_id( psa_ecc_family_t curve, size_t bits, char const **oid, size_t *oid_len ) { switch( curve ) { case PSA_ECC_FAMILY_SECP_R1: switch( bits ) { #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) case 192: *oid = MBEDTLS_OID_EC_GRP_SECP192R1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP192R1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) case 224: *oid = MBEDTLS_OID_EC_GRP_SECP224R1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP224R1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) case 256: *oid = MBEDTLS_OID_EC_GRP_SECP256R1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP256R1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) case 384: *oid = MBEDTLS_OID_EC_GRP_SECP384R1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP384R1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) case 521: *oid = MBEDTLS_OID_EC_GRP_SECP521R1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP521R1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */ } break; case PSA_ECC_FAMILY_SECP_K1: switch( bits ) { #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) case 192: *oid = MBEDTLS_OID_EC_GRP_SECP192K1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP192K1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) case 224: *oid = MBEDTLS_OID_EC_GRP_SECP224K1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP224K1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) case 256: *oid = MBEDTLS_OID_EC_GRP_SECP256K1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_SECP256K1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */ } break; case PSA_ECC_FAMILY_BRAINPOOL_P_R1: switch( bits ) { #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) case 256: *oid = MBEDTLS_OID_EC_GRP_BP256R1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_BP256R1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) case 384: *oid = MBEDTLS_OID_EC_GRP_BP384R1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_BP384R1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) case 512: *oid = MBEDTLS_OID_EC_GRP_BP512R1; *oid_len = MBEDTLS_OID_SIZE( MBEDTLS_OID_EC_GRP_BP512R1 ); return( 0 ); #endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */ } break; } (void) oid; (void) oid_len; return( -1 ); } #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH 1 #if defined(MBEDTLS_ECP_DP_SECP192R1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 192 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 192 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_SECP192R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224R1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 224 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 224 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_SECP224R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256R1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 256 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 256 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_SECP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP384R1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 384 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 384 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_SECP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP521R1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 521 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 521 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_SECP521R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP192K1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 192 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 192 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_SECP192K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP224K1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 224 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 224 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_SECP224K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_SECP256K1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 256 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 256 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_SECP256K1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP256R1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 256 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 256 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_BP256R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP384R1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 384 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 384 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_BP384R1_ENABLED */ #if defined(MBEDTLS_ECP_DP_BP512R1_ENABLED) #if MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH < ( 2 * ( ( 512 + 7 ) / 8 ) + 1 ) #undef MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH #define MBEDTLS_PSA_MAX_EC_PUBKEY_LENGTH ( 2 * ( ( 512 + 7 ) / 8 ) + 1 ) #endif #endif /* MBEDTLS_ECP_DP_BP512R1_ENABLED */ /* Translations for PK layer */ static inline int mbedtls_psa_err_translate_pk( psa_status_t status ) { switch( status ) { case PSA_SUCCESS: return( 0 ); case PSA_ERROR_NOT_SUPPORTED: return( MBEDTLS_ERR_PK_FEATURE_UNAVAILABLE ); case PSA_ERROR_INSUFFICIENT_MEMORY: return( MBEDTLS_ERR_PK_ALLOC_FAILED ); case PSA_ERROR_INSUFFICIENT_ENTROPY: return( MBEDTLS_ERR_ECP_RANDOM_FAILED ); case PSA_ERROR_BAD_STATE: return( MBEDTLS_ERR_PK_BAD_INPUT_DATA ); /* All other failures */ case PSA_ERROR_COMMUNICATION_FAILURE: case PSA_ERROR_HARDWARE_FAILURE: case PSA_ERROR_CORRUPTION_DETECTED: return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED ); default: /* We return the same as for the 'other failures', * but list them separately nonetheless to indicate * which failure conditions we have considered. */ return( MBEDTLS_ERR_PK_HW_ACCEL_FAILED ); } } /* Translations for ECC */ /* This function transforms an ECC group identifier from * https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#tls-parameters-8 * into a PSA ECC group identifier. */ #if defined(MBEDTLS_ECP_C) static inline psa_key_type_t mbedtls_psa_parse_tls_ecc_group( uint16_t tls_ecc_grp_reg_id, size_t *bits ) { const mbedtls_ecp_curve_info *curve_info = mbedtls_ecp_curve_info_from_tls_id( tls_ecc_grp_reg_id ); if( curve_info == NULL ) return( 0 ); return( PSA_KEY_TYPE_ECC_KEY_PAIR( mbedtls_ecc_group_to_psa( curve_info->grp_id, bits ) ) ); } #endif /* MBEDTLS_ECP_C */ /* This function takes a buffer holding an EC public key * exported through psa_export_public_key(), and converts * it into an ECPoint structure to be put into a ClientKeyExchange * message in an ECDHE exchange. * * Both the present and the foreseeable future format of EC public keys * used by PSA have the ECPoint structure contained in the exported key * as a subbuffer, and the function merely selects this subbuffer instead * of making a copy. */ static inline int mbedtls_psa_tls_psa_ec_to_ecpoint( unsigned char *src, size_t srclen, unsigned char **dst, size_t *dstlen ) { *dst = src; *dstlen = srclen; return( 0 ); } /* This function takes a buffer holding an ECPoint structure * (as contained in a TLS ServerKeyExchange message for ECDHE * exchanges) and converts it into a format that the PSA key * agreement API understands. */ static inline int mbedtls_psa_tls_ecpoint_to_psa_ec( unsigned char const *src, size_t srclen, unsigned char *dst, size_t dstlen, size_t *olen ) { if( srclen > dstlen ) return( MBEDTLS_ERR_ECP_BUFFER_TOO_SMALL ); memcpy( dst, src, srclen ); *olen = srclen; return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ /* Expose whatever RNG the PSA subsystem uses to applications using the * mbedtls_xxx API. The declarations and definitions here need to be * consistent with the implementation in library/psa_crypto_random_impl.h. * See that file for implementation documentation. */ #if defined(MBEDTLS_PSA_CRYPTO_C) /* The type of a `f_rng` random generator function that many library functions * take. * * This type name is not part of the Mbed TLS stable API. It may be renamed * or moved without warning. */ typedef int mbedtls_f_rng_t( void *p_rng, unsigned char *output, size_t output_size ); #if defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) /** The random generator function for the PSA subsystem. * * This function is suitable as the `f_rng` random generator function * parameter of many `mbedtls_xxx` functions. Use #MBEDTLS_PSA_RANDOM_STATE * to obtain the \p p_rng parameter. * * The implementation of this function depends on the configuration of the * library. * * \note Depending on the configuration, this may be a function or * a pointer to a function. * * \note This function may only be used if the PSA crypto subsystem is active. * This means that you must call psa_crypto_init() before any call to * this function, and you must not call this function after calling * mbedtls_psa_crypto_free(). * * \param p_rng The random generator context. This must be * #MBEDTLS_PSA_RANDOM_STATE. No other state is * supported. * \param output The buffer to fill. It must have room for * \c output_size bytes. * \param output_size The number of bytes to write to \p output. * This function may fail if \p output_size is too * large. It is guaranteed to accept any output size * requested by Mbed TLS library functions. The * maximum request size depends on the library * configuration. * * \return \c 0 on success. * \return An `MBEDTLS_ERR_ENTROPY_xxx`, * `MBEDTLS_ERR_PLATFORM_xxx, * `MBEDTLS_ERR_CTR_DRBG_xxx` or * `MBEDTLS_ERR_HMAC_DRBG_xxx` on error. */ int mbedtls_psa_get_random( void *p_rng, unsigned char *output, size_t output_size ); /** The random generator state for the PSA subsystem. * * This macro expands to an expression which is suitable as the `p_rng` * random generator state parameter of many `mbedtls_xxx` functions. * It must be used in combination with the random generator function * mbedtls_psa_get_random(). * * The implementation of this macro depends on the configuration of the * library. Do not make any assumption on its nature. */ #define MBEDTLS_PSA_RANDOM_STATE NULL #else /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */ #if defined(MBEDTLS_CTR_DRBG_C) #include "mbedtls/ctr_drbg.h" typedef mbedtls_ctr_drbg_context mbedtls_psa_drbg_context_t; static mbedtls_f_rng_t *const mbedtls_psa_get_random = mbedtls_ctr_drbg_random; #elif defined(MBEDTLS_HMAC_DRBG_C) #include "mbedtls/hmac_drbg.h" typedef mbedtls_hmac_drbg_context mbedtls_psa_drbg_context_t; static mbedtls_f_rng_t *const mbedtls_psa_get_random = mbedtls_hmac_drbg_random; #endif extern mbedtls_psa_drbg_context_t *const mbedtls_psa_random_state; #define MBEDTLS_PSA_RANDOM_STATE mbedtls_psa_random_state #endif /* !defined(MBEDTLS_PSA_CRYPTO_EXTERNAL_RNG) */ #endif /* MBEDTLS_PSA_CRYPTO_C */ #endif /* MBEDTLS_PSA_UTIL_H */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/ripemd160.h
/** * \file ripemd160.h * * \brief RIPE MD-160 message digest */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_RIPEMD160_H #define MBEDTLS_RIPEMD160_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include <stddef.h> #include <stdint.h> /* MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_RIPEMD160_HW_ACCEL_FAILED -0x0031 /**< RIPEMD160 hardware accelerator failed */ #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_RIPEMD160_ALT) // Regular implementation // /** * \brief RIPEMD-160 context structure */ typedef struct mbedtls_ripemd160_context { uint32_t total[2]; /*!< number of bytes processed */ uint32_t state[5]; /*!< intermediate digest state */ unsigned char buffer[64]; /*!< data block being processed */ } mbedtls_ripemd160_context; #else /* MBEDTLS_RIPEMD160_ALT */ #include "ripemd160_alt.h" #endif /* MBEDTLS_RIPEMD160_ALT */ /** * \brief Initialize RIPEMD-160 context * * \param ctx RIPEMD-160 context to be initialized */ void mbedtls_ripemd160_init( mbedtls_ripemd160_context *ctx ); /** * \brief Clear RIPEMD-160 context * * \param ctx RIPEMD-160 context to be cleared */ void mbedtls_ripemd160_free( mbedtls_ripemd160_context *ctx ); /** * \brief Clone (the state of) an RIPEMD-160 context * * \param dst The destination context * \param src The context to be cloned */ void mbedtls_ripemd160_clone( mbedtls_ripemd160_context *dst, const mbedtls_ripemd160_context *src ); /** * \brief RIPEMD-160 context setup * * \param ctx context to be initialized * * \return 0 if successful */ int mbedtls_ripemd160_starts_ret( mbedtls_ripemd160_context *ctx ); /** * \brief RIPEMD-160 process buffer * * \param ctx RIPEMD-160 context * \param input buffer holding the data * \param ilen length of the input data * * \return 0 if successful */ int mbedtls_ripemd160_update_ret( mbedtls_ripemd160_context *ctx, const unsigned char *input, size_t ilen ); /** * \brief RIPEMD-160 final digest * * \param ctx RIPEMD-160 context * \param output RIPEMD-160 checksum result * * \return 0 if successful */ int mbedtls_ripemd160_finish_ret( mbedtls_ripemd160_context *ctx, unsigned char output[20] ); /** * \brief RIPEMD-160 process data block (internal use only) * * \param ctx RIPEMD-160 context * \param data buffer holding one block of data * * \return 0 if successful */ int mbedtls_internal_ripemd160_process( mbedtls_ripemd160_context *ctx, const unsigned char data[64] ); #if !defined(MBEDTLS_DEPRECATED_REMOVED) #if defined(MBEDTLS_DEPRECATED_WARNING) #define MBEDTLS_DEPRECATED __attribute__((deprecated)) #else #define MBEDTLS_DEPRECATED #endif /** * \brief RIPEMD-160 context setup * * \deprecated Superseded by mbedtls_ripemd160_starts_ret() in 2.7.0 * * \param ctx context to be initialized */ MBEDTLS_DEPRECATED void mbedtls_ripemd160_starts( mbedtls_ripemd160_context *ctx ); /** * \brief RIPEMD-160 process buffer * * \deprecated Superseded by mbedtls_ripemd160_update_ret() in 2.7.0 * * \param ctx RIPEMD-160 context * \param input buffer holding the data * \param ilen length of the input data */ MBEDTLS_DEPRECATED void mbedtls_ripemd160_update( mbedtls_ripemd160_context *ctx, const unsigned char *input, size_t ilen ); /** * \brief RIPEMD-160 final digest * * \deprecated Superseded by mbedtls_ripemd160_finish_ret() in 2.7.0 * * \param ctx RIPEMD-160 context * \param output RIPEMD-160 checksum result */ MBEDTLS_DEPRECATED void mbedtls_ripemd160_finish( mbedtls_ripemd160_context *ctx, unsigned char output[20] ); /** * \brief RIPEMD-160 process data block (internal use only) * * \deprecated Superseded by mbedtls_internal_ripemd160_process() in 2.7.0 * * \param ctx RIPEMD-160 context * \param data buffer holding one block of data */ MBEDTLS_DEPRECATED void mbedtls_ripemd160_process( mbedtls_ripemd160_context *ctx, const unsigned char data[64] ); #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ /** * \brief Output = RIPEMD-160( input buffer ) * * \param input buffer holding the data * \param ilen length of the input data * \param output RIPEMD-160 checksum result * * \return 0 if successful */ int mbedtls_ripemd160_ret( const unsigned char *input, size_t ilen, unsigned char output[20] ); #if !defined(MBEDTLS_DEPRECATED_REMOVED) #if defined(MBEDTLS_DEPRECATED_WARNING) #define MBEDTLS_DEPRECATED __attribute__((deprecated)) #else #define MBEDTLS_DEPRECATED #endif /** * \brief Output = RIPEMD-160( input buffer ) * * \deprecated Superseded by mbedtls_ripemd160_ret() in 2.7.0 * * \param input buffer holding the data * \param ilen length of the input data * \param output RIPEMD-160 checksum result */ MBEDTLS_DEPRECATED void mbedtls_ripemd160( const unsigned char *input, size_t ilen, unsigned char output[20] ); #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int mbedtls_ripemd160_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif #endif /* mbedtls_ripemd160.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/hmac_drbg.h
/** * \file hmac_drbg.h * * \brief The HMAC_DRBG pseudorandom generator. * * This module implements the HMAC_DRBG pseudorandom generator described * in <em>NIST SP 800-90A: Recommendation for Random Number Generation Using * Deterministic Random Bit Generators</em>. */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_HMAC_DRBG_H #define MBEDTLS_HMAC_DRBG_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/md.h" #if defined(MBEDTLS_THREADING_C) #include "mbedtls/threading.h" #endif /* * Error codes */ #define MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG -0x0003 /**< Too many random requested in single call. */ #define MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG -0x0005 /**< Input too large (Entropy + additional). */ #define MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR -0x0007 /**< Read/write error in file. */ #define MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED -0x0009 /**< The entropy source failed. */ /** * \name SECTION: Module settings * * The configuration options you can set for this module are in this section. * Either change them in config.h or define them on the compiler command line. * \{ */ #if !defined(MBEDTLS_HMAC_DRBG_RESEED_INTERVAL) #define MBEDTLS_HMAC_DRBG_RESEED_INTERVAL 10000 /**< Interval before reseed is performed by default */ #endif #if !defined(MBEDTLS_HMAC_DRBG_MAX_INPUT) #define MBEDTLS_HMAC_DRBG_MAX_INPUT 256 /**< Maximum number of additional input bytes */ #endif #if !defined(MBEDTLS_HMAC_DRBG_MAX_REQUEST) #define MBEDTLS_HMAC_DRBG_MAX_REQUEST 1024 /**< Maximum number of requested bytes per call */ #endif #if !defined(MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT) #define MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT 384 /**< Maximum size of (re)seed buffer */ #endif /* \} name SECTION: Module settings */ #define MBEDTLS_HMAC_DRBG_PR_OFF 0 /**< No prediction resistance */ #define MBEDTLS_HMAC_DRBG_PR_ON 1 /**< Prediction resistance enabled */ #ifdef __cplusplus extern "C" { #endif /** * HMAC_DRBG context. */ typedef struct mbedtls_hmac_drbg_context { /* Working state: the key K is not stored explicitly, * but is implied by the HMAC context */ mbedtls_md_context_t md_ctx; /*!< HMAC context (inc. K) */ unsigned char V[MBEDTLS_MD_MAX_SIZE]; /*!< V in the spec */ int reseed_counter; /*!< reseed counter */ /* Administrative state */ size_t entropy_len; /*!< entropy bytes grabbed on each (re)seed */ int prediction_resistance; /*!< enable prediction resistance (Automatic reseed before every random generation) */ int reseed_interval; /*!< reseed interval */ /* Callbacks */ int (*f_entropy)(void *, unsigned char *, size_t); /*!< entropy function */ void *p_entropy; /*!< context for the entropy function */ #if defined(MBEDTLS_THREADING_C) /* Invariant: the mutex is initialized if and only if * md_ctx->md_info != NULL. This means that the mutex is initialized * during the initial seeding in mbedtls_hmac_drbg_seed() or * mbedtls_hmac_drbg_seed_buf() and freed in mbedtls_ctr_drbg_free(). * * Note that this invariant may change without notice. Do not rely on it * and do not access the mutex directly in application code. */ mbedtls_threading_mutex_t mutex; #endif } mbedtls_hmac_drbg_context; /** * \brief HMAC_DRBG context initialization. * * This function makes the context ready for mbedtls_hmac_drbg_seed(), * mbedtls_hmac_drbg_seed_buf() or mbedtls_hmac_drbg_free(). * * \note The reseed interval is #MBEDTLS_HMAC_DRBG_RESEED_INTERVAL * by default. Override this value by calling * mbedtls_hmac_drbg_set_reseed_interval(). * * \param ctx HMAC_DRBG context to be initialized. */ void mbedtls_hmac_drbg_init( mbedtls_hmac_drbg_context *ctx ); /** * \brief HMAC_DRBG initial seeding. * * Set the initial seed and set up the entropy source for future reseeds. * * A typical choice for the \p f_entropy and \p p_entropy parameters is * to use the entropy module: * - \p f_entropy is mbedtls_entropy_func(); * - \p p_entropy is an instance of ::mbedtls_entropy_context initialized * with mbedtls_entropy_init() (which registers the platform's default * entropy sources). * * You can provide a personalization string in addition to the * entropy source, to make this instantiation as unique as possible. * * \note By default, the security strength as defined by NIST is: * - 128 bits if \p md_info is SHA-1; * - 192 bits if \p md_info is SHA-224; * - 256 bits if \p md_info is SHA-256, SHA-384 or SHA-512. * Note that SHA-256 is just as efficient as SHA-224. * The security strength can be reduced if a smaller * entropy length is set with * mbedtls_hmac_drbg_set_entropy_len(). * * \note The default entropy length is the security strength * (converted from bits to bytes). You can override * it by calling mbedtls_hmac_drbg_set_entropy_len(). * * \note During the initial seeding, this function calls * the entropy source to obtain a nonce * whose length is half the entropy length. */ #if defined(MBEDTLS_THREADING_C) /** * \note When Mbed TLS is built with threading support, * after this function returns successfully, * it is safe to call mbedtls_hmac_drbg_random() * from multiple threads. Other operations, including * reseeding, are not thread-safe. */ #endif /* MBEDTLS_THREADING_C */ /** * \param ctx HMAC_DRBG context to be seeded. * \param md_info MD algorithm to use for HMAC_DRBG. * \param f_entropy The entropy callback, taking as arguments the * \p p_entropy context, the buffer to fill, and the * length of the buffer. * \p f_entropy is always called with a length that is * less than or equal to the entropy length. * \param p_entropy The entropy context to pass to \p f_entropy. * \param custom The personalization string. * This can be \c NULL, in which case the personalization * string is empty regardless of the value of \p len. * \param len The length of the personalization string. * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT * and also at most * #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \p entropy_len * 3 / 2 * where \p entropy_len is the entropy length * described above. * * \return \c 0 if successful. * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is * invalid. * \return #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough * memory to allocate context data. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED * if the call to \p f_entropy failed. */ int mbedtls_hmac_drbg_seed( mbedtls_hmac_drbg_context *ctx, const mbedtls_md_info_t * md_info, int (*f_entropy)(void *, unsigned char *, size_t), void *p_entropy, const unsigned char *custom, size_t len ); /** * \brief Initilisation of simpified HMAC_DRBG (never reseeds). * * This function is meant for use in algorithms that need a pseudorandom * input such as deterministic ECDSA. */ #if defined(MBEDTLS_THREADING_C) /** * \note When Mbed TLS is built with threading support, * after this function returns successfully, * it is safe to call mbedtls_hmac_drbg_random() * from multiple threads. Other operations, including * reseeding, are not thread-safe. */ #endif /* MBEDTLS_THREADING_C */ /** * \param ctx HMAC_DRBG context to be initialised. * \param md_info MD algorithm to use for HMAC_DRBG. * \param data Concatenation of the initial entropy string and * the additional data. * \param data_len Length of \p data in bytes. * * \return \c 0 if successful. or * \return #MBEDTLS_ERR_MD_BAD_INPUT_DATA if \p md_info is * invalid. * \return #MBEDTLS_ERR_MD_ALLOC_FAILED if there was not enough * memory to allocate context data. */ int mbedtls_hmac_drbg_seed_buf( mbedtls_hmac_drbg_context *ctx, const mbedtls_md_info_t * md_info, const unsigned char *data, size_t data_len ); /** * \brief This function turns prediction resistance on or off. * The default value is off. * * \note If enabled, entropy is gathered at the beginning of * every call to mbedtls_hmac_drbg_random_with_add() * or mbedtls_hmac_drbg_random(). * Only use this if your entropy source has sufficient * throughput. * * \param ctx The HMAC_DRBG context. * \param resistance #MBEDTLS_HMAC_DRBG_PR_ON or #MBEDTLS_HMAC_DRBG_PR_OFF. */ void mbedtls_hmac_drbg_set_prediction_resistance( mbedtls_hmac_drbg_context *ctx, int resistance ); /** * \brief This function sets the amount of entropy grabbed on each * seed or reseed. * * See the documentation of mbedtls_hmac_drbg_seed() for the default value. * * \param ctx The HMAC_DRBG context. * \param len The amount of entropy to grab, in bytes. */ void mbedtls_hmac_drbg_set_entropy_len( mbedtls_hmac_drbg_context *ctx, size_t len ); /** * \brief Set the reseed interval. * * The reseed interval is the number of calls to mbedtls_hmac_drbg_random() * or mbedtls_hmac_drbg_random_with_add() after which the entropy function * is called again. * * The default value is #MBEDTLS_HMAC_DRBG_RESEED_INTERVAL. * * \param ctx The HMAC_DRBG context. * \param interval The reseed interval. */ void mbedtls_hmac_drbg_set_reseed_interval( mbedtls_hmac_drbg_context *ctx, int interval ); /** * \brief This function updates the state of the HMAC_DRBG context. * * \note This function is not thread-safe. It is not safe * to call this function if another thread might be * concurrently obtaining random numbers from the same * context or updating or reseeding the same context. * * \param ctx The HMAC_DRBG context. * \param additional The data to update the state with. * If this is \c NULL, there is no additional data. * \param add_len Length of \p additional in bytes. * Unused if \p additional is \c NULL. * * \return \c 0 on success, or an error from the underlying * hash calculation. */ int mbedtls_hmac_drbg_update_ret( mbedtls_hmac_drbg_context *ctx, const unsigned char *additional, size_t add_len ); /** * \brief This function reseeds the HMAC_DRBG context, that is * extracts data from the entropy source. * * \note This function is not thread-safe. It is not safe * to call this function if another thread might be * concurrently obtaining random numbers from the same * context or updating or reseeding the same context. * * \param ctx The HMAC_DRBG context. * \param additional Additional data to add to the state. * If this is \c NULL, there is no additional data * and \p len should be \c 0. * \param len The length of the additional data. * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT * and also at most * #MBEDTLS_HMAC_DRBG_MAX_SEED_INPUT - \p entropy_len * where \p entropy_len is the entropy length * (see mbedtls_hmac_drbg_set_entropy_len()). * * \return \c 0 if successful. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED * if a call to the entropy function failed. */ int mbedtls_hmac_drbg_reseed( mbedtls_hmac_drbg_context *ctx, const unsigned char *additional, size_t len ); /** * \brief This function updates an HMAC_DRBG instance with additional * data and uses it to generate random data. * * This function automatically reseeds if the reseed counter is exceeded * or prediction resistance is enabled. * * \note This function is not thread-safe. It is not safe * to call this function if another thread might be * concurrently obtaining random numbers from the same * context or updating or reseeding the same context. * * \param p_rng The HMAC_DRBG context. This must be a pointer to a * #mbedtls_hmac_drbg_context structure. * \param output The buffer to fill. * \param output_len The length of the buffer in bytes. * This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST. * \param additional Additional data to update with. * If this is \c NULL, there is no additional data * and \p add_len should be \c 0. * \param add_len The length of the additional data. * This must be at most #MBEDTLS_HMAC_DRBG_MAX_INPUT. * * \return \c 0 if successful. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED * if a call to the entropy source failed. * \return #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if * \p output_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST. * \return #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if * \p add_len > #MBEDTLS_HMAC_DRBG_MAX_INPUT. */ int mbedtls_hmac_drbg_random_with_add( void *p_rng, unsigned char *output, size_t output_len, const unsigned char *additional, size_t add_len ); /** * \brief This function uses HMAC_DRBG to generate random data. * * This function automatically reseeds if the reseed counter is exceeded * or prediction resistance is enabled. */ #if defined(MBEDTLS_THREADING_C) /** * \note When Mbed TLS is built with threading support, * it is safe to call mbedtls_ctr_drbg_random() * from multiple threads. Other operations, including * reseeding, are not thread-safe. */ #endif /* MBEDTLS_THREADING_C */ /** * \param p_rng The HMAC_DRBG context. This must be a pointer to a * #mbedtls_hmac_drbg_context structure. * \param output The buffer to fill. * \param out_len The length of the buffer in bytes. * This must be at most #MBEDTLS_HMAC_DRBG_MAX_REQUEST. * * \return \c 0 if successful. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED * if a call to the entropy source failed. * \return #MBEDTLS_ERR_HMAC_DRBG_REQUEST_TOO_BIG if * \p out_len > #MBEDTLS_HMAC_DRBG_MAX_REQUEST. */ int mbedtls_hmac_drbg_random( void *p_rng, unsigned char *output, size_t out_len ); /** * \brief This function resets HMAC_DRBG context to the state immediately * after initial call of mbedtls_hmac_drbg_init(). * * \param ctx The HMAC_DRBG context to free. */ void mbedtls_hmac_drbg_free( mbedtls_hmac_drbg_context *ctx ); #if ! defined(MBEDTLS_DEPRECATED_REMOVED) #if defined(MBEDTLS_DEPRECATED_WARNING) #define MBEDTLS_DEPRECATED __attribute__((deprecated)) #else #define MBEDTLS_DEPRECATED #endif /** * \brief This function updates the state of the HMAC_DRBG context. * * \deprecated Superseded by mbedtls_hmac_drbg_update_ret() * in 2.16.0. * * \param ctx The HMAC_DRBG context. * \param additional The data to update the state with. * If this is \c NULL, there is no additional data. * \param add_len Length of \p additional in bytes. * Unused if \p additional is \c NULL. */ MBEDTLS_DEPRECATED void mbedtls_hmac_drbg_update( mbedtls_hmac_drbg_context *ctx, const unsigned char *additional, size_t add_len ); #undef MBEDTLS_DEPRECATED #endif /* !MBEDTLS_DEPRECATED_REMOVED */ #if defined(MBEDTLS_FS_IO) /** * \brief This function writes a seed file. * * \param ctx The HMAC_DRBG context. * \param path The name of the file. * * \return \c 0 on success. * \return #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on reseed * failure. */ int mbedtls_hmac_drbg_write_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path ); /** * \brief This function reads and updates a seed file. The seed * is added to this instance. * * \param ctx The HMAC_DRBG context. * \param path The name of the file. * * \return \c 0 on success. * \return #MBEDTLS_ERR_HMAC_DRBG_FILE_IO_ERROR on file error. * \return #MBEDTLS_ERR_HMAC_DRBG_ENTROPY_SOURCE_FAILED on * reseed failure. * \return #MBEDTLS_ERR_HMAC_DRBG_INPUT_TOO_BIG if the existing * seed file is too large. */ int mbedtls_hmac_drbg_update_seed_file( mbedtls_hmac_drbg_context *ctx, const char *path ); #endif /* MBEDTLS_FS_IO */ #if defined(MBEDTLS_SELF_TEST) /** * \brief The HMAC_DRBG Checkup routine. * * \return \c 0 if successful. * \return \c 1 if the test failed. */ int mbedtls_hmac_drbg_self_test( int verbose ); #endif #ifdef __cplusplus } #endif #endif /* hmac_drbg.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/x509.h
/** * \file x509.h * * \brief X.509 generic defines and structures */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_X509_H #define MBEDTLS_X509_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/asn1.h" #include "mbedtls/pk.h" #if defined(MBEDTLS_RSA_C) #include "mbedtls/rsa.h" #endif /** * \addtogroup x509_module * \{ */ #if !defined(MBEDTLS_X509_MAX_INTERMEDIATE_CA) /** * Maximum number of intermediate CAs in a verification chain. * That is, maximum length of the chain, excluding the end-entity certificate * and the trusted root certificate. * * Set this to a low value to prevent an adversary from making you waste * resources verifying an overlong certificate chain. */ #define MBEDTLS_X509_MAX_INTERMEDIATE_CA 8 #endif /** * \name X509 Error codes * \{ */ #define MBEDTLS_ERR_X509_FEATURE_UNAVAILABLE -0x2080 /**< Unavailable feature, e.g. RSA hashing/encryption combination. */ #define MBEDTLS_ERR_X509_UNKNOWN_OID -0x2100 /**< Requested OID is unknown. */ #define MBEDTLS_ERR_X509_INVALID_FORMAT -0x2180 /**< The CRT/CRL/CSR format is invalid, e.g. different type expected. */ #define MBEDTLS_ERR_X509_INVALID_VERSION -0x2200 /**< The CRT/CRL/CSR version element is invalid. */ #define MBEDTLS_ERR_X509_INVALID_SERIAL -0x2280 /**< The serial tag or value is invalid. */ #define MBEDTLS_ERR_X509_INVALID_ALG -0x2300 /**< The algorithm tag or value is invalid. */ #define MBEDTLS_ERR_X509_INVALID_NAME -0x2380 /**< The name tag or value is invalid. */ #define MBEDTLS_ERR_X509_INVALID_DATE -0x2400 /**< The date tag or value is invalid. */ #define MBEDTLS_ERR_X509_INVALID_SIGNATURE -0x2480 /**< The signature tag or value invalid. */ #define MBEDTLS_ERR_X509_INVALID_EXTENSIONS -0x2500 /**< The extension tag or value is invalid. */ #define MBEDTLS_ERR_X509_UNKNOWN_VERSION -0x2580 /**< CRT/CRL/CSR has an unsupported version number. */ #define MBEDTLS_ERR_X509_UNKNOWN_SIG_ALG -0x2600 /**< Signature algorithm (oid) is unsupported. */ #define MBEDTLS_ERR_X509_SIG_MISMATCH -0x2680 /**< Signature algorithms do not match. (see \c ::mbedtls_x509_crt sig_oid) */ #define MBEDTLS_ERR_X509_CERT_VERIFY_FAILED -0x2700 /**< Certificate verification failed, e.g. CRL, CA or signature check failed. */ #define MBEDTLS_ERR_X509_CERT_UNKNOWN_FORMAT -0x2780 /**< Format not recognized as DER or PEM. */ #define MBEDTLS_ERR_X509_BAD_INPUT_DATA -0x2800 /**< Input invalid. */ #define MBEDTLS_ERR_X509_ALLOC_FAILED -0x2880 /**< Allocation of memory failed. */ #define MBEDTLS_ERR_X509_FILE_IO_ERROR -0x2900 /**< Read/write of file failed. */ #define MBEDTLS_ERR_X509_BUFFER_TOO_SMALL -0x2980 /**< Destination buffer is too small. */ #define MBEDTLS_ERR_X509_FATAL_ERROR -0x3000 /**< A fatal error occurred, eg the chain is too long or the vrfy callback failed. */ /* \} name */ /** * \name X509 Verify codes * \{ */ /* Reminder: update x509_crt_verify_strings[] in library/x509_crt.c */ #define MBEDTLS_X509_BADCERT_EXPIRED 0x01 /**< The certificate validity has expired. */ #define MBEDTLS_X509_BADCERT_REVOKED 0x02 /**< The certificate has been revoked (is on a CRL). */ #define MBEDTLS_X509_BADCERT_CN_MISMATCH 0x04 /**< The certificate Common Name (CN) does not match with the expected CN. */ #define MBEDTLS_X509_BADCERT_NOT_TRUSTED 0x08 /**< The certificate is not correctly signed by the trusted CA. */ #define MBEDTLS_X509_BADCRL_NOT_TRUSTED 0x10 /**< The CRL is not correctly signed by the trusted CA. */ #define MBEDTLS_X509_BADCRL_EXPIRED 0x20 /**< The CRL is expired. */ #define MBEDTLS_X509_BADCERT_MISSING 0x40 /**< Certificate was missing. */ #define MBEDTLS_X509_BADCERT_SKIP_VERIFY 0x80 /**< Certificate verification was skipped. */ #define MBEDTLS_X509_BADCERT_OTHER 0x0100 /**< Other reason (can be used by verify callback) */ #define MBEDTLS_X509_BADCERT_FUTURE 0x0200 /**< The certificate validity starts in the future. */ #define MBEDTLS_X509_BADCRL_FUTURE 0x0400 /**< The CRL is from the future */ #define MBEDTLS_X509_BADCERT_KEY_USAGE 0x0800 /**< Usage does not match the keyUsage extension. */ #define MBEDTLS_X509_BADCERT_EXT_KEY_USAGE 0x1000 /**< Usage does not match the extendedKeyUsage extension. */ #define MBEDTLS_X509_BADCERT_NS_CERT_TYPE 0x2000 /**< Usage does not match the nsCertType extension. */ #define MBEDTLS_X509_BADCERT_BAD_MD 0x4000 /**< The certificate is signed with an unacceptable hash. */ #define MBEDTLS_X509_BADCERT_BAD_PK 0x8000 /**< The certificate is signed with an unacceptable PK alg (eg RSA vs ECDSA). */ #define MBEDTLS_X509_BADCERT_BAD_KEY 0x010000 /**< The certificate is signed with an unacceptable key (eg bad curve, RSA too short). */ #define MBEDTLS_X509_BADCRL_BAD_MD 0x020000 /**< The CRL is signed with an unacceptable hash. */ #define MBEDTLS_X509_BADCRL_BAD_PK 0x040000 /**< The CRL is signed with an unacceptable PK alg (eg RSA vs ECDSA). */ #define MBEDTLS_X509_BADCRL_BAD_KEY 0x080000 /**< The CRL is signed with an unacceptable key (eg bad curve, RSA too short). */ /* \} name */ /* \} addtogroup x509_module */ /* * X.509 v3 Subject Alternative Name types. * otherName [0] OtherName, * rfc822Name [1] IA5String, * dNSName [2] IA5String, * x400Address [3] ORAddress, * directoryName [4] Name, * ediPartyName [5] EDIPartyName, * uniformResourceIdentifier [6] IA5String, * iPAddress [7] OCTET STRING, * registeredID [8] OBJECT IDENTIFIER */ #define MBEDTLS_X509_SAN_OTHER_NAME 0 #define MBEDTLS_X509_SAN_RFC822_NAME 1 #define MBEDTLS_X509_SAN_DNS_NAME 2 #define MBEDTLS_X509_SAN_X400_ADDRESS_NAME 3 #define MBEDTLS_X509_SAN_DIRECTORY_NAME 4 #define MBEDTLS_X509_SAN_EDI_PARTY_NAME 5 #define MBEDTLS_X509_SAN_UNIFORM_RESOURCE_IDENTIFIER 6 #define MBEDTLS_X509_SAN_IP_ADDRESS 7 #define MBEDTLS_X509_SAN_REGISTERED_ID 8 /* * X.509 v3 Key Usage Extension flags * Reminder: update x509_info_key_usage() when adding new flags. */ #define MBEDTLS_X509_KU_DIGITAL_SIGNATURE (0x80) /* bit 0 */ #define MBEDTLS_X509_KU_NON_REPUDIATION (0x40) /* bit 1 */ #define MBEDTLS_X509_KU_KEY_ENCIPHERMENT (0x20) /* bit 2 */ #define MBEDTLS_X509_KU_DATA_ENCIPHERMENT (0x10) /* bit 3 */ #define MBEDTLS_X509_KU_KEY_AGREEMENT (0x08) /* bit 4 */ #define MBEDTLS_X509_KU_KEY_CERT_SIGN (0x04) /* bit 5 */ #define MBEDTLS_X509_KU_CRL_SIGN (0x02) /* bit 6 */ #define MBEDTLS_X509_KU_ENCIPHER_ONLY (0x01) /* bit 7 */ #define MBEDTLS_X509_KU_DECIPHER_ONLY (0x8000) /* bit 8 */ /* * Netscape certificate types * (http://www.mozilla.org/projects/security/pki/nss/tech-notes/tn3.html) */ #define MBEDTLS_X509_NS_CERT_TYPE_SSL_CLIENT (0x80) /* bit 0 */ #define MBEDTLS_X509_NS_CERT_TYPE_SSL_SERVER (0x40) /* bit 1 */ #define MBEDTLS_X509_NS_CERT_TYPE_EMAIL (0x20) /* bit 2 */ #define MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING (0x10) /* bit 3 */ #define MBEDTLS_X509_NS_CERT_TYPE_RESERVED (0x08) /* bit 4 */ #define MBEDTLS_X509_NS_CERT_TYPE_SSL_CA (0x04) /* bit 5 */ #define MBEDTLS_X509_NS_CERT_TYPE_EMAIL_CA (0x02) /* bit 6 */ #define MBEDTLS_X509_NS_CERT_TYPE_OBJECT_SIGNING_CA (0x01) /* bit 7 */ /* * X.509 extension types * * Comments refer to the status for using certificates. Status can be * different for writing certificates or reading CRLs or CSRs. * * Those are defined in oid.h as oid.c needs them in a data structure. Since * these were previously defined here, let's have aliases for compatibility. */ #define MBEDTLS_X509_EXT_AUTHORITY_KEY_IDENTIFIER MBEDTLS_OID_X509_EXT_AUTHORITY_KEY_IDENTIFIER #define MBEDTLS_X509_EXT_SUBJECT_KEY_IDENTIFIER MBEDTLS_OID_X509_EXT_SUBJECT_KEY_IDENTIFIER #define MBEDTLS_X509_EXT_KEY_USAGE MBEDTLS_OID_X509_EXT_KEY_USAGE #define MBEDTLS_X509_EXT_CERTIFICATE_POLICIES MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES #define MBEDTLS_X509_EXT_POLICY_MAPPINGS MBEDTLS_OID_X509_EXT_POLICY_MAPPINGS #define MBEDTLS_X509_EXT_SUBJECT_ALT_NAME MBEDTLS_OID_X509_EXT_SUBJECT_ALT_NAME /* Supported (DNS) */ #define MBEDTLS_X509_EXT_ISSUER_ALT_NAME MBEDTLS_OID_X509_EXT_ISSUER_ALT_NAME #define MBEDTLS_X509_EXT_SUBJECT_DIRECTORY_ATTRS MBEDTLS_OID_X509_EXT_SUBJECT_DIRECTORY_ATTRS #define MBEDTLS_X509_EXT_BASIC_CONSTRAINTS MBEDTLS_OID_X509_EXT_BASIC_CONSTRAINTS /* Supported */ #define MBEDTLS_X509_EXT_NAME_CONSTRAINTS MBEDTLS_OID_X509_EXT_NAME_CONSTRAINTS #define MBEDTLS_X509_EXT_POLICY_CONSTRAINTS MBEDTLS_OID_X509_EXT_POLICY_CONSTRAINTS #define MBEDTLS_X509_EXT_EXTENDED_KEY_USAGE MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE #define MBEDTLS_X509_EXT_CRL_DISTRIBUTION_POINTS MBEDTLS_OID_X509_EXT_CRL_DISTRIBUTION_POINTS #define MBEDTLS_X509_EXT_INIHIBIT_ANYPOLICY MBEDTLS_OID_X509_EXT_INIHIBIT_ANYPOLICY #define MBEDTLS_X509_EXT_FRESHEST_CRL MBEDTLS_OID_X509_EXT_FRESHEST_CRL #define MBEDTLS_X509_EXT_NS_CERT_TYPE MBEDTLS_OID_X509_EXT_NS_CERT_TYPE /* * Storage format identifiers * Recognized formats: PEM and DER */ #define MBEDTLS_X509_FORMAT_DER 1 #define MBEDTLS_X509_FORMAT_PEM 2 #define MBEDTLS_X509_MAX_DN_NAME_SIZE 256 /**< Maximum value size of a DN entry */ #ifdef __cplusplus extern "C" { #endif /** * \addtogroup x509_module * \{ */ /** * \name Structures for parsing X.509 certificates, CRLs and CSRs * \{ */ /** * Type-length-value structure that allows for ASN1 using DER. */ typedef mbedtls_asn1_buf mbedtls_x509_buf; /** * Container for ASN1 bit strings. */ typedef mbedtls_asn1_bitstring mbedtls_x509_bitstring; /** * Container for ASN1 named information objects. * It allows for Relative Distinguished Names (e.g. cn=localhost,ou=code,etc.). */ typedef mbedtls_asn1_named_data mbedtls_x509_name; /** * Container for a sequence of ASN.1 items */ typedef mbedtls_asn1_sequence mbedtls_x509_sequence; /** Container for date and time (precision in seconds). */ typedef struct mbedtls_x509_time { int year, mon, day; /**< Date. */ int hour, min, sec; /**< Time. */ } mbedtls_x509_time; /** \} name Structures for parsing X.509 certificates, CRLs and CSRs */ /** \} addtogroup x509_module */ /** * \brief Store the certificate DN in printable form into buf; * no more than size characters will be written. * * \param buf Buffer to write to * \param size Maximum size of buffer * \param dn The X509 name to represent * * \return The length of the string written (not including the * terminated nul byte), or a negative error code. */ int mbedtls_x509_dn_gets( char *buf, size_t size, const mbedtls_x509_name *dn ); /** * \brief Store the certificate serial in printable form into buf; * no more than size characters will be written. * * \param buf Buffer to write to * \param size Maximum size of buffer * \param serial The X509 serial to represent * * \return The length of the string written (not including the * terminated nul byte), or a negative error code. */ int mbedtls_x509_serial_gets( char *buf, size_t size, const mbedtls_x509_buf *serial ); /** * \brief Check a given mbedtls_x509_time against the system time * and tell if it's in the past. * * \note Intended usage is "if( is_past( valid_to ) ) ERROR". * Hence the return value of 1 if on internal errors. * * \param to mbedtls_x509_time to check * * \return 1 if the given time is in the past or an error occurred, * 0 otherwise. */ int mbedtls_x509_time_is_past( const mbedtls_x509_time *to ); /** * \brief Check a given mbedtls_x509_time against the system time * and tell if it's in the future. * * \note Intended usage is "if( is_future( valid_from ) ) ERROR". * Hence the return value of 1 if on internal errors. * * \param from mbedtls_x509_time to check * * \return 1 if the given time is in the future or an error occurred, * 0 otherwise. */ int mbedtls_x509_time_is_future( const mbedtls_x509_time *from ); #if defined(MBEDTLS_SELF_TEST) /** * \brief Checkup routine * * \return 0 if successful, or 1 if the test failed */ int mbedtls_x509_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ /* * Internal module functions. You probably do not want to use these unless you * know you do. */ int mbedtls_x509_get_name( unsigned char **p, const unsigned char *end, mbedtls_x509_name *cur ); int mbedtls_x509_get_alg_null( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *alg ); int mbedtls_x509_get_alg( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *alg, mbedtls_x509_buf *params ); #if defined(MBEDTLS_X509_RSASSA_PSS_SUPPORT) int mbedtls_x509_get_rsassa_pss_params( const mbedtls_x509_buf *params, mbedtls_md_type_t *md_alg, mbedtls_md_type_t *mgf_md, int *salt_len ); #endif int mbedtls_x509_get_sig( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *sig ); int mbedtls_x509_get_sig_alg( const mbedtls_x509_buf *sig_oid, const mbedtls_x509_buf *sig_params, mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg, void **sig_opts ); int mbedtls_x509_get_time( unsigned char **p, const unsigned char *end, mbedtls_x509_time *t ); int mbedtls_x509_get_serial( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *serial ); int mbedtls_x509_get_ext( unsigned char **p, const unsigned char *end, mbedtls_x509_buf *ext, int tag ); int mbedtls_x509_sig_alg_gets( char *buf, size_t size, const mbedtls_x509_buf *sig_oid, mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg, const void *sig_opts ); int mbedtls_x509_key_size_helper( char *buf, size_t buf_size, const char *name ); int mbedtls_x509_string_to_names( mbedtls_asn1_named_data **head, const char *name ); int mbedtls_x509_set_extension( mbedtls_asn1_named_data **head, const char *oid, size_t oid_len, int critical, const unsigned char *val, size_t val_len ); int mbedtls_x509_write_extensions( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data *first ); int mbedtls_x509_write_names( unsigned char **p, unsigned char *start, mbedtls_asn1_named_data *first ); int mbedtls_x509_write_sig( unsigned char **p, unsigned char *start, const char *oid, size_t oid_len, unsigned char *sig, size_t size ); #define MBEDTLS_X509_SAFE_SNPRINTF \ do { \ if( ret < 0 || (size_t) ret >= n ) \ return( MBEDTLS_ERR_X509_BUFFER_TOO_SMALL ); \ \ n -= (size_t) ret; \ p += (size_t) ret; \ } while( 0 ) #ifdef __cplusplus } #endif #endif /* x509.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/oid.h
/** * \file oid.h * * \brief Object Identifier (OID) database */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_OID_H #define MBEDTLS_OID_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/asn1.h" #include "mbedtls/pk.h" #include <stddef.h> #if defined(MBEDTLS_CIPHER_C) #include "mbedtls/cipher.h" #endif #if defined(MBEDTLS_MD_C) #include "mbedtls/md.h" #endif #define MBEDTLS_ERR_OID_NOT_FOUND -0x002E /**< OID is not found. */ #define MBEDTLS_ERR_OID_BUF_TOO_SMALL -0x000B /**< output buffer is too small */ /* This is for the benefit of X.509, but defined here in order to avoid * having a "backwards" include of x.509.h here */ /* * X.509 extension types (internal, arbitrary values for bitsets) */ #define MBEDTLS_OID_X509_EXT_AUTHORITY_KEY_IDENTIFIER (1 << 0) #define MBEDTLS_OID_X509_EXT_SUBJECT_KEY_IDENTIFIER (1 << 1) #define MBEDTLS_OID_X509_EXT_KEY_USAGE (1 << 2) #define MBEDTLS_OID_X509_EXT_CERTIFICATE_POLICIES (1 << 3) #define MBEDTLS_OID_X509_EXT_POLICY_MAPPINGS (1 << 4) #define MBEDTLS_OID_X509_EXT_SUBJECT_ALT_NAME (1 << 5) #define MBEDTLS_OID_X509_EXT_ISSUER_ALT_NAME (1 << 6) #define MBEDTLS_OID_X509_EXT_SUBJECT_DIRECTORY_ATTRS (1 << 7) #define MBEDTLS_OID_X509_EXT_BASIC_CONSTRAINTS (1 << 8) #define MBEDTLS_OID_X509_EXT_NAME_CONSTRAINTS (1 << 9) #define MBEDTLS_OID_X509_EXT_POLICY_CONSTRAINTS (1 << 10) #define MBEDTLS_OID_X509_EXT_EXTENDED_KEY_USAGE (1 << 11) #define MBEDTLS_OID_X509_EXT_CRL_DISTRIBUTION_POINTS (1 << 12) #define MBEDTLS_OID_X509_EXT_INIHIBIT_ANYPOLICY (1 << 13) #define MBEDTLS_OID_X509_EXT_FRESHEST_CRL (1 << 14) #define MBEDTLS_OID_X509_EXT_NS_CERT_TYPE (1 << 16) /* * Top level OID tuples */ #define MBEDTLS_OID_ISO_MEMBER_BODIES "\x2a" /* {iso(1) member-body(2)} */ #define MBEDTLS_OID_ISO_IDENTIFIED_ORG "\x2b" /* {iso(1) identified-organization(3)} */ #define MBEDTLS_OID_ISO_CCITT_DS "\x55" /* {joint-iso-ccitt(2) ds(5)} */ #define MBEDTLS_OID_ISO_ITU_COUNTRY "\x60" /* {joint-iso-itu-t(2) country(16)} */ /* * ISO Member bodies OID parts */ #define MBEDTLS_OID_COUNTRY_US "\x86\x48" /* {us(840)} */ #define MBEDTLS_OID_ORG_RSA_DATA_SECURITY "\x86\xf7\x0d" /* {rsadsi(113549)} */ #define MBEDTLS_OID_RSA_COMPANY MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \ MBEDTLS_OID_ORG_RSA_DATA_SECURITY /* {iso(1) member-body(2) us(840) rsadsi(113549)} */ #define MBEDTLS_OID_ORG_ANSI_X9_62 "\xce\x3d" /* ansi-X9-62(10045) */ #define MBEDTLS_OID_ANSI_X9_62 MBEDTLS_OID_ISO_MEMBER_BODIES MBEDTLS_OID_COUNTRY_US \ MBEDTLS_OID_ORG_ANSI_X9_62 /* * ISO Identified organization OID parts */ #define MBEDTLS_OID_ORG_DOD "\x06" /* {dod(6)} */ #define MBEDTLS_OID_ORG_OIW "\x0e" #define MBEDTLS_OID_OIW_SECSIG MBEDTLS_OID_ORG_OIW "\x03" #define MBEDTLS_OID_OIW_SECSIG_ALG MBEDTLS_OID_OIW_SECSIG "\x02" #define MBEDTLS_OID_OIW_SECSIG_SHA1 MBEDTLS_OID_OIW_SECSIG_ALG "\x1a" #define MBEDTLS_OID_ORG_CERTICOM "\x81\x04" /* certicom(132) */ #define MBEDTLS_OID_CERTICOM MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_CERTICOM #define MBEDTLS_OID_ORG_TELETRUST "\x24" /* teletrust(36) */ #define MBEDTLS_OID_TELETRUST MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_TELETRUST /* * ISO ITU OID parts */ #define MBEDTLS_OID_ORGANIZATION "\x01" /* {organization(1)} */ #define MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ISO_ITU_COUNTRY MBEDTLS_OID_COUNTRY_US MBEDTLS_OID_ORGANIZATION /* {joint-iso-itu-t(2) country(16) us(840) organization(1)} */ #define MBEDTLS_OID_ORG_GOV "\x65" /* {gov(101)} */ #define MBEDTLS_OID_GOV MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_GOV /* {joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101)} */ #define MBEDTLS_OID_ORG_NETSCAPE "\x86\xF8\x42" /* {netscape(113730)} */ #define MBEDTLS_OID_NETSCAPE MBEDTLS_OID_ISO_ITU_US_ORG MBEDTLS_OID_ORG_NETSCAPE /* Netscape OID {joint-iso-itu-t(2) country(16) us(840) organization(1) netscape(113730)} */ /* ISO arc for standard certificate and CRL extensions */ #define MBEDTLS_OID_ID_CE MBEDTLS_OID_ISO_CCITT_DS "\x1D" /**< id-ce OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 29} */ #define MBEDTLS_OID_NIST_ALG MBEDTLS_OID_GOV "\x03\x04" /** { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) */ /** * Private Internet Extensions * { iso(1) identified-organization(3) dod(6) internet(1) * security(5) mechanisms(5) pkix(7) } */ #define MBEDTLS_OID_INTERNET MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_ORG_DOD "\x01" #define MBEDTLS_OID_PKIX MBEDTLS_OID_INTERNET "\x05\x05\x07" /* * Arc for standard naming attributes */ #define MBEDTLS_OID_AT MBEDTLS_OID_ISO_CCITT_DS "\x04" /**< id-at OBJECT IDENTIFIER ::= {joint-iso-ccitt(2) ds(5) 4} */ #define MBEDTLS_OID_AT_CN MBEDTLS_OID_AT "\x03" /**< id-at-commonName AttributeType:= {id-at 3} */ #define MBEDTLS_OID_AT_SUR_NAME MBEDTLS_OID_AT "\x04" /**< id-at-surName AttributeType:= {id-at 4} */ #define MBEDTLS_OID_AT_SERIAL_NUMBER MBEDTLS_OID_AT "\x05" /**< id-at-serialNumber AttributeType:= {id-at 5} */ #define MBEDTLS_OID_AT_COUNTRY MBEDTLS_OID_AT "\x06" /**< id-at-countryName AttributeType:= {id-at 6} */ #define MBEDTLS_OID_AT_LOCALITY MBEDTLS_OID_AT "\x07" /**< id-at-locality AttributeType:= {id-at 7} */ #define MBEDTLS_OID_AT_STATE MBEDTLS_OID_AT "\x08" /**< id-at-state AttributeType:= {id-at 8} */ #define MBEDTLS_OID_AT_ORGANIZATION MBEDTLS_OID_AT "\x0A" /**< id-at-organizationName AttributeType:= {id-at 10} */ #define MBEDTLS_OID_AT_ORG_UNIT MBEDTLS_OID_AT "\x0B" /**< id-at-organizationalUnitName AttributeType:= {id-at 11} */ #define MBEDTLS_OID_AT_TITLE MBEDTLS_OID_AT "\x0C" /**< id-at-title AttributeType:= {id-at 12} */ #define MBEDTLS_OID_AT_POSTAL_ADDRESS MBEDTLS_OID_AT "\x10" /**< id-at-postalAddress AttributeType:= {id-at 16} */ #define MBEDTLS_OID_AT_POSTAL_CODE MBEDTLS_OID_AT "\x11" /**< id-at-postalCode AttributeType:= {id-at 17} */ #define MBEDTLS_OID_AT_GIVEN_NAME MBEDTLS_OID_AT "\x2A" /**< id-at-givenName AttributeType:= {id-at 42} */ #define MBEDTLS_OID_AT_INITIALS MBEDTLS_OID_AT "\x2B" /**< id-at-initials AttributeType:= {id-at 43} */ #define MBEDTLS_OID_AT_GENERATION_QUALIFIER MBEDTLS_OID_AT "\x2C" /**< id-at-generationQualifier AttributeType:= {id-at 44} */ #define MBEDTLS_OID_AT_UNIQUE_IDENTIFIER MBEDTLS_OID_AT "\x2D" /**< id-at-uniqueIdentifier AttributType:= {id-at 45} */ #define MBEDTLS_OID_AT_DN_QUALIFIER MBEDTLS_OID_AT "\x2E" /**< id-at-dnQualifier AttributeType:= {id-at 46} */ #define MBEDTLS_OID_AT_PSEUDONYM MBEDTLS_OID_AT "\x41" /**< id-at-pseudonym AttributeType:= {id-at 65} */ #define MBEDTLS_OID_DOMAIN_COMPONENT "\x09\x92\x26\x89\x93\xF2\x2C\x64\x01\x19" /** id-domainComponent AttributeType:= {itu-t(0) data(9) pss(2342) ucl(19200300) pilot(100) pilotAttributeType(1) domainComponent(25)} */ /* * OIDs for standard certificate extensions */ #define MBEDTLS_OID_AUTHORITY_KEY_IDENTIFIER MBEDTLS_OID_ID_CE "\x23" /**< id-ce-authorityKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 35 } */ #define MBEDTLS_OID_SUBJECT_KEY_IDENTIFIER MBEDTLS_OID_ID_CE "\x0E" /**< id-ce-subjectKeyIdentifier OBJECT IDENTIFIER ::= { id-ce 14 } */ #define MBEDTLS_OID_KEY_USAGE MBEDTLS_OID_ID_CE "\x0F" /**< id-ce-keyUsage OBJECT IDENTIFIER ::= { id-ce 15 } */ #define MBEDTLS_OID_CERTIFICATE_POLICIES MBEDTLS_OID_ID_CE "\x20" /**< id-ce-certificatePolicies OBJECT IDENTIFIER ::= { id-ce 32 } */ #define MBEDTLS_OID_POLICY_MAPPINGS MBEDTLS_OID_ID_CE "\x21" /**< id-ce-policyMappings OBJECT IDENTIFIER ::= { id-ce 33 } */ #define MBEDTLS_OID_SUBJECT_ALT_NAME MBEDTLS_OID_ID_CE "\x11" /**< id-ce-subjectAltName OBJECT IDENTIFIER ::= { id-ce 17 } */ #define MBEDTLS_OID_ISSUER_ALT_NAME MBEDTLS_OID_ID_CE "\x12" /**< id-ce-issuerAltName OBJECT IDENTIFIER ::= { id-ce 18 } */ #define MBEDTLS_OID_SUBJECT_DIRECTORY_ATTRS MBEDTLS_OID_ID_CE "\x09" /**< id-ce-subjectDirectoryAttributes OBJECT IDENTIFIER ::= { id-ce 9 } */ #define MBEDTLS_OID_BASIC_CONSTRAINTS MBEDTLS_OID_ID_CE "\x13" /**< id-ce-basicConstraints OBJECT IDENTIFIER ::= { id-ce 19 } */ #define MBEDTLS_OID_NAME_CONSTRAINTS MBEDTLS_OID_ID_CE "\x1E" /**< id-ce-nameConstraints OBJECT IDENTIFIER ::= { id-ce 30 } */ #define MBEDTLS_OID_POLICY_CONSTRAINTS MBEDTLS_OID_ID_CE "\x24" /**< id-ce-policyConstraints OBJECT IDENTIFIER ::= { id-ce 36 } */ #define MBEDTLS_OID_EXTENDED_KEY_USAGE MBEDTLS_OID_ID_CE "\x25" /**< id-ce-extKeyUsage OBJECT IDENTIFIER ::= { id-ce 37 } */ #define MBEDTLS_OID_CRL_DISTRIBUTION_POINTS MBEDTLS_OID_ID_CE "\x1F" /**< id-ce-cRLDistributionPoints OBJECT IDENTIFIER ::= { id-ce 31 } */ #define MBEDTLS_OID_INIHIBIT_ANYPOLICY MBEDTLS_OID_ID_CE "\x36" /**< id-ce-inhibitAnyPolicy OBJECT IDENTIFIER ::= { id-ce 54 } */ #define MBEDTLS_OID_FRESHEST_CRL MBEDTLS_OID_ID_CE "\x2E" /**< id-ce-freshestCRL OBJECT IDENTIFIER ::= { id-ce 46 } */ /* * Certificate policies */ #define MBEDTLS_OID_ANY_POLICY MBEDTLS_OID_CERTIFICATE_POLICIES "\x00" /**< anyPolicy OBJECT IDENTIFIER ::= { id-ce-certificatePolicies 0 } */ /* * Netscape certificate extensions */ #define MBEDTLS_OID_NS_CERT MBEDTLS_OID_NETSCAPE "\x01" #define MBEDTLS_OID_NS_CERT_TYPE MBEDTLS_OID_NS_CERT "\x01" #define MBEDTLS_OID_NS_BASE_URL MBEDTLS_OID_NS_CERT "\x02" #define MBEDTLS_OID_NS_REVOCATION_URL MBEDTLS_OID_NS_CERT "\x03" #define MBEDTLS_OID_NS_CA_REVOCATION_URL MBEDTLS_OID_NS_CERT "\x04" #define MBEDTLS_OID_NS_RENEWAL_URL MBEDTLS_OID_NS_CERT "\x07" #define MBEDTLS_OID_NS_CA_POLICY_URL MBEDTLS_OID_NS_CERT "\x08" #define MBEDTLS_OID_NS_SSL_SERVER_NAME MBEDTLS_OID_NS_CERT "\x0C" #define MBEDTLS_OID_NS_COMMENT MBEDTLS_OID_NS_CERT "\x0D" #define MBEDTLS_OID_NS_DATA_TYPE MBEDTLS_OID_NETSCAPE "\x02" #define MBEDTLS_OID_NS_CERT_SEQUENCE MBEDTLS_OID_NS_DATA_TYPE "\x05" /* * OIDs for CRL extensions */ #define MBEDTLS_OID_PRIVATE_KEY_USAGE_PERIOD MBEDTLS_OID_ID_CE "\x10" #define MBEDTLS_OID_CRL_NUMBER MBEDTLS_OID_ID_CE "\x14" /**< id-ce-cRLNumber OBJECT IDENTIFIER ::= { id-ce 20 } */ /* * X.509 v3 Extended key usage OIDs */ #define MBEDTLS_OID_ANY_EXTENDED_KEY_USAGE MBEDTLS_OID_EXTENDED_KEY_USAGE "\x00" /**< anyExtendedKeyUsage OBJECT IDENTIFIER ::= { id-ce-extKeyUsage 0 } */ #define MBEDTLS_OID_KP MBEDTLS_OID_PKIX "\x03" /**< id-kp OBJECT IDENTIFIER ::= { id-pkix 3 } */ #define MBEDTLS_OID_SERVER_AUTH MBEDTLS_OID_KP "\x01" /**< id-kp-serverAuth OBJECT IDENTIFIER ::= { id-kp 1 } */ #define MBEDTLS_OID_CLIENT_AUTH MBEDTLS_OID_KP "\x02" /**< id-kp-clientAuth OBJECT IDENTIFIER ::= { id-kp 2 } */ #define MBEDTLS_OID_CODE_SIGNING MBEDTLS_OID_KP "\x03" /**< id-kp-codeSigning OBJECT IDENTIFIER ::= { id-kp 3 } */ #define MBEDTLS_OID_EMAIL_PROTECTION MBEDTLS_OID_KP "\x04" /**< id-kp-emailProtection OBJECT IDENTIFIER ::= { id-kp 4 } */ #define MBEDTLS_OID_TIME_STAMPING MBEDTLS_OID_KP "\x08" /**< id-kp-timeStamping OBJECT IDENTIFIER ::= { id-kp 8 } */ #define MBEDTLS_OID_OCSP_SIGNING MBEDTLS_OID_KP "\x09" /**< id-kp-OCSPSigning OBJECT IDENTIFIER ::= { id-kp 9 } */ /** * Wi-SUN Alliance Field Area Network * { iso(1) identified-organization(3) dod(6) internet(1) * private(4) enterprise(1) WiSUN(45605) FieldAreaNetwork(1) } */ #define MBEDTLS_OID_WISUN_FAN MBEDTLS_OID_INTERNET "\x04\x01\x82\xe4\x25\x01" #define MBEDTLS_OID_ON MBEDTLS_OID_PKIX "\x08" /**< id-on OBJECT IDENTIFIER ::= { id-pkix 8 } */ #define MBEDTLS_OID_ON_HW_MODULE_NAME MBEDTLS_OID_ON "\x04" /**< id-on-hardwareModuleName OBJECT IDENTIFIER ::= { id-on 4 } */ /* * PKCS definition OIDs */ #define MBEDTLS_OID_PKCS MBEDTLS_OID_RSA_COMPANY "\x01" /**< pkcs OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) 1 } */ #define MBEDTLS_OID_PKCS1 MBEDTLS_OID_PKCS "\x01" /**< pkcs-1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 1 } */ #define MBEDTLS_OID_PKCS5 MBEDTLS_OID_PKCS "\x05" /**< pkcs-5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 5 } */ #define MBEDTLS_OID_PKCS9 MBEDTLS_OID_PKCS "\x09" /**< pkcs-9 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 9 } */ #define MBEDTLS_OID_PKCS12 MBEDTLS_OID_PKCS "\x0c" /**< pkcs-12 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) pkcs(1) 12 } */ /* * PKCS#1 OIDs */ #define MBEDTLS_OID_PKCS1_RSA MBEDTLS_OID_PKCS1 "\x01" /**< rsaEncryption OBJECT IDENTIFIER ::= { pkcs-1 1 } */ #define MBEDTLS_OID_PKCS1_MD2 MBEDTLS_OID_PKCS1 "\x02" /**< md2WithRSAEncryption ::= { pkcs-1 2 } */ #define MBEDTLS_OID_PKCS1_MD4 MBEDTLS_OID_PKCS1 "\x03" /**< md4WithRSAEncryption ::= { pkcs-1 3 } */ #define MBEDTLS_OID_PKCS1_MD5 MBEDTLS_OID_PKCS1 "\x04" /**< md5WithRSAEncryption ::= { pkcs-1 4 } */ #define MBEDTLS_OID_PKCS1_SHA1 MBEDTLS_OID_PKCS1 "\x05" /**< sha1WithRSAEncryption ::= { pkcs-1 5 } */ #define MBEDTLS_OID_PKCS1_SHA224 MBEDTLS_OID_PKCS1 "\x0e" /**< sha224WithRSAEncryption ::= { pkcs-1 14 } */ #define MBEDTLS_OID_PKCS1_SHA256 MBEDTLS_OID_PKCS1 "\x0b" /**< sha256WithRSAEncryption ::= { pkcs-1 11 } */ #define MBEDTLS_OID_PKCS1_SHA384 MBEDTLS_OID_PKCS1 "\x0c" /**< sha384WithRSAEncryption ::= { pkcs-1 12 } */ #define MBEDTLS_OID_PKCS1_SHA512 MBEDTLS_OID_PKCS1 "\x0d" /**< sha512WithRSAEncryption ::= { pkcs-1 13 } */ #define MBEDTLS_OID_RSA_SHA_OBS "\x2B\x0E\x03\x02\x1D" #define MBEDTLS_OID_PKCS9_EMAIL MBEDTLS_OID_PKCS9 "\x01" /**< emailAddress AttributeType ::= { pkcs-9 1 } */ /* RFC 4055 */ #define MBEDTLS_OID_RSASSA_PSS MBEDTLS_OID_PKCS1 "\x0a" /**< id-RSASSA-PSS ::= { pkcs-1 10 } */ #define MBEDTLS_OID_MGF1 MBEDTLS_OID_PKCS1 "\x08" /**< id-mgf1 ::= { pkcs-1 8 } */ /* * Digest algorithms */ #define MBEDTLS_OID_DIGEST_ALG_MD2 MBEDTLS_OID_RSA_COMPANY "\x02\x02" /**< id-mbedtls_md2 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 2 } */ #define MBEDTLS_OID_DIGEST_ALG_MD4 MBEDTLS_OID_RSA_COMPANY "\x02\x04" /**< id-mbedtls_md4 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 4 } */ #define MBEDTLS_OID_DIGEST_ALG_MD5 MBEDTLS_OID_RSA_COMPANY "\x02\x05" /**< id-mbedtls_md5 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 5 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA1 MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_SHA1 /**< id-mbedtls_sha1 OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 26 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA224 MBEDTLS_OID_NIST_ALG "\x02\x04" /**< id-sha224 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 4 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA256 MBEDTLS_OID_NIST_ALG "\x02\x01" /**< id-mbedtls_sha256 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 1 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA384 MBEDTLS_OID_NIST_ALG "\x02\x02" /**< id-sha384 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 2 } */ #define MBEDTLS_OID_DIGEST_ALG_SHA512 MBEDTLS_OID_NIST_ALG "\x02\x03" /**< id-mbedtls_sha512 OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistalgorithm(4) hashalgs(2) 3 } */ #define MBEDTLS_OID_DIGEST_ALG_RIPEMD160 MBEDTLS_OID_TELETRUST "\x03\x02\x01" /**< id-ripemd160 OBJECT IDENTIFIER :: { iso(1) identified-organization(3) teletrust(36) algorithm(3) hashAlgorithm(2) ripemd160(1) } */ #define MBEDTLS_OID_HMAC_SHA1 MBEDTLS_OID_RSA_COMPANY "\x02\x07" /**< id-hmacWithSHA1 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 7 } */ #define MBEDTLS_OID_HMAC_SHA224 MBEDTLS_OID_RSA_COMPANY "\x02\x08" /**< id-hmacWithSHA224 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 8 } */ #define MBEDTLS_OID_HMAC_SHA256 MBEDTLS_OID_RSA_COMPANY "\x02\x09" /**< id-hmacWithSHA256 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 9 } */ #define MBEDTLS_OID_HMAC_SHA384 MBEDTLS_OID_RSA_COMPANY "\x02\x0A" /**< id-hmacWithSHA384 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 10 } */ #define MBEDTLS_OID_HMAC_SHA512 MBEDTLS_OID_RSA_COMPANY "\x02\x0B" /**< id-hmacWithSHA512 OBJECT IDENTIFIER ::= { iso(1) member-body(2) us(840) rsadsi(113549) digestAlgorithm(2) 11 } */ /* * Encryption algorithms */ #define MBEDTLS_OID_DES_CBC MBEDTLS_OID_ISO_IDENTIFIED_ORG MBEDTLS_OID_OIW_SECSIG_ALG "\x07" /**< desCBC OBJECT IDENTIFIER ::= { iso(1) identified-organization(3) oiw(14) secsig(3) algorithms(2) 7 } */ #define MBEDTLS_OID_DES_EDE3_CBC MBEDTLS_OID_RSA_COMPANY "\x03\x07" /**< des-ede3-cbc OBJECT IDENTIFIER ::= { iso(1) member-body(2) -- us(840) rsadsi(113549) encryptionAlgorithm(3) 7 } */ #define MBEDTLS_OID_AES MBEDTLS_OID_NIST_ALG "\x01" /** aes OBJECT IDENTIFIER ::= { joint-iso-itu-t(2) country(16) us(840) organization(1) gov(101) csor(3) nistAlgorithm(4) 1 } */ /* * Key Wrapping algorithms */ /* * RFC 5649 */ #define MBEDTLS_OID_AES128_KW MBEDTLS_OID_AES "\x05" /** id-aes128-wrap OBJECT IDENTIFIER ::= { aes 5 } */ #define MBEDTLS_OID_AES128_KWP MBEDTLS_OID_AES "\x08" /** id-aes128-wrap-pad OBJECT IDENTIFIER ::= { aes 8 } */ #define MBEDTLS_OID_AES192_KW MBEDTLS_OID_AES "\x19" /** id-aes192-wrap OBJECT IDENTIFIER ::= { aes 25 } */ #define MBEDTLS_OID_AES192_KWP MBEDTLS_OID_AES "\x1c" /** id-aes192-wrap-pad OBJECT IDENTIFIER ::= { aes 28 } */ #define MBEDTLS_OID_AES256_KW MBEDTLS_OID_AES "\x2d" /** id-aes256-wrap OBJECT IDENTIFIER ::= { aes 45 } */ #define MBEDTLS_OID_AES256_KWP MBEDTLS_OID_AES "\x30" /** id-aes256-wrap-pad OBJECT IDENTIFIER ::= { aes 48 } */ /* * PKCS#5 OIDs */ #define MBEDTLS_OID_PKCS5_PBKDF2 MBEDTLS_OID_PKCS5 "\x0c" /**< id-PBKDF2 OBJECT IDENTIFIER ::= {pkcs-5 12} */ #define MBEDTLS_OID_PKCS5_PBES2 MBEDTLS_OID_PKCS5 "\x0d" /**< id-PBES2 OBJECT IDENTIFIER ::= {pkcs-5 13} */ #define MBEDTLS_OID_PKCS5_PBMAC1 MBEDTLS_OID_PKCS5 "\x0e" /**< id-PBMAC1 OBJECT IDENTIFIER ::= {pkcs-5 14} */ /* * PKCS#5 PBES1 algorithms */ #define MBEDTLS_OID_PKCS5_PBE_MD2_DES_CBC MBEDTLS_OID_PKCS5 "\x01" /**< pbeWithMD2AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 1} */ #define MBEDTLS_OID_PKCS5_PBE_MD2_RC2_CBC MBEDTLS_OID_PKCS5 "\x04" /**< pbeWithMD2AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 4} */ #define MBEDTLS_OID_PKCS5_PBE_MD5_DES_CBC MBEDTLS_OID_PKCS5 "\x03" /**< pbeWithMD5AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 3} */ #define MBEDTLS_OID_PKCS5_PBE_MD5_RC2_CBC MBEDTLS_OID_PKCS5 "\x06" /**< pbeWithMD5AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 6} */ #define MBEDTLS_OID_PKCS5_PBE_SHA1_DES_CBC MBEDTLS_OID_PKCS5 "\x0a" /**< pbeWithSHA1AndDES-CBC OBJECT IDENTIFIER ::= {pkcs-5 10} */ #define MBEDTLS_OID_PKCS5_PBE_SHA1_RC2_CBC MBEDTLS_OID_PKCS5 "\x0b" /**< pbeWithSHA1AndRC2-CBC OBJECT IDENTIFIER ::= {pkcs-5 11} */ /* * PKCS#8 OIDs */ #define MBEDTLS_OID_PKCS9_CSR_EXT_REQ MBEDTLS_OID_PKCS9 "\x0e" /**< extensionRequest OBJECT IDENTIFIER ::= {pkcs-9 14} */ /* * PKCS#12 PBE OIDs */ #define MBEDTLS_OID_PKCS12_PBE MBEDTLS_OID_PKCS12 "\x01" /**< pkcs-12PbeIds OBJECT IDENTIFIER ::= {pkcs-12 1} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_128 MBEDTLS_OID_PKCS12_PBE "\x01" /**< pbeWithSHAAnd128BitRC4 OBJECT IDENTIFIER ::= {pkcs-12PbeIds 1} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_RC4_40 MBEDTLS_OID_PKCS12_PBE "\x02" /**< pbeWithSHAAnd40BitRC4 OBJECT IDENTIFIER ::= {pkcs-12PbeIds 2} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_DES3_EDE_CBC MBEDTLS_OID_PKCS12_PBE "\x03" /**< pbeWithSHAAnd3-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 3} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_DES2_EDE_CBC MBEDTLS_OID_PKCS12_PBE "\x04" /**< pbeWithSHAAnd2-KeyTripleDES-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 4} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_128_CBC MBEDTLS_OID_PKCS12_PBE "\x05" /**< pbeWithSHAAnd128BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 5} */ #define MBEDTLS_OID_PKCS12_PBE_SHA1_RC2_40_CBC MBEDTLS_OID_PKCS12_PBE "\x06" /**< pbeWithSHAAnd40BitRC2-CBC OBJECT IDENTIFIER ::= {pkcs-12PbeIds 6} */ /* * EC key algorithms from RFC 5480 */ /* id-ecPublicKey OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 } */ #define MBEDTLS_OID_EC_ALG_UNRESTRICTED MBEDTLS_OID_ANSI_X9_62 "\x02\01" /* id-ecDH OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) * schemes(1) ecdh(12) } */ #define MBEDTLS_OID_EC_ALG_ECDH MBEDTLS_OID_CERTICOM "\x01\x0c" /* * ECParameters namedCurve identifiers, from RFC 5480, RFC 5639, and SEC2 */ /* secp192r1 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 1 } */ #define MBEDTLS_OID_EC_GRP_SECP192R1 MBEDTLS_OID_ANSI_X9_62 "\x03\x01\x01" /* secp224r1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 33 } */ #define MBEDTLS_OID_EC_GRP_SECP224R1 MBEDTLS_OID_CERTICOM "\x00\x21" /* secp256r1 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) curves(3) prime(1) 7 } */ #define MBEDTLS_OID_EC_GRP_SECP256R1 MBEDTLS_OID_ANSI_X9_62 "\x03\x01\x07" /* secp384r1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 34 } */ #define MBEDTLS_OID_EC_GRP_SECP384R1 MBEDTLS_OID_CERTICOM "\x00\x22" /* secp521r1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 35 } */ #define MBEDTLS_OID_EC_GRP_SECP521R1 MBEDTLS_OID_CERTICOM "\x00\x23" /* secp192k1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 31 } */ #define MBEDTLS_OID_EC_GRP_SECP192K1 MBEDTLS_OID_CERTICOM "\x00\x1f" /* secp224k1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 32 } */ #define MBEDTLS_OID_EC_GRP_SECP224K1 MBEDTLS_OID_CERTICOM "\x00\x20" /* secp256k1 OBJECT IDENTIFIER ::= { * iso(1) identified-organization(3) certicom(132) curve(0) 10 } */ #define MBEDTLS_OID_EC_GRP_SECP256K1 MBEDTLS_OID_CERTICOM "\x00\x0a" /* RFC 5639 4.1 * ecStdCurvesAndGeneration OBJECT IDENTIFIER::= {iso(1) * identified-organization(3) teletrust(36) algorithm(3) signature- * algorithm(3) ecSign(2) 8} * ellipticCurve OBJECT IDENTIFIER ::= {ecStdCurvesAndGeneration 1} * versionOne OBJECT IDENTIFIER ::= {ellipticCurve 1} */ #define MBEDTLS_OID_EC_BRAINPOOL_V1 MBEDTLS_OID_TELETRUST "\x03\x03\x02\x08\x01\x01" /* brainpoolP256r1 OBJECT IDENTIFIER ::= {versionOne 7} */ #define MBEDTLS_OID_EC_GRP_BP256R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x07" /* brainpoolP384r1 OBJECT IDENTIFIER ::= {versionOne 11} */ #define MBEDTLS_OID_EC_GRP_BP384R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x0B" /* brainpoolP512r1 OBJECT IDENTIFIER ::= {versionOne 13} */ #define MBEDTLS_OID_EC_GRP_BP512R1 MBEDTLS_OID_EC_BRAINPOOL_V1 "\x0D" /* * SEC1 C.1 * * prime-field OBJECT IDENTIFIER ::= { id-fieldType 1 } * id-fieldType OBJECT IDENTIFIER ::= { ansi-X9-62 fieldType(1)} */ #define MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE MBEDTLS_OID_ANSI_X9_62 "\x01" #define MBEDTLS_OID_ANSI_X9_62_PRIME_FIELD MBEDTLS_OID_ANSI_X9_62_FIELD_TYPE "\x01" /* * ECDSA signature identifiers, from RFC 5480 */ #define MBEDTLS_OID_ANSI_X9_62_SIG MBEDTLS_OID_ANSI_X9_62 "\x04" /* signatures(4) */ #define MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 MBEDTLS_OID_ANSI_X9_62_SIG "\x03" /* ecdsa-with-SHA2(3) */ /* ecdsa-with-SHA1 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) 1 } */ #define MBEDTLS_OID_ECDSA_SHA1 MBEDTLS_OID_ANSI_X9_62_SIG "\x01" /* ecdsa-with-SHA224 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) * ecdsa-with-SHA2(3) 1 } */ #define MBEDTLS_OID_ECDSA_SHA224 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x01" /* ecdsa-with-SHA256 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) * ecdsa-with-SHA2(3) 2 } */ #define MBEDTLS_OID_ECDSA_SHA256 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x02" /* ecdsa-with-SHA384 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) * ecdsa-with-SHA2(3) 3 } */ #define MBEDTLS_OID_ECDSA_SHA384 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x03" /* ecdsa-with-SHA512 OBJECT IDENTIFIER ::= { * iso(1) member-body(2) us(840) ansi-X9-62(10045) signatures(4) * ecdsa-with-SHA2(3) 4 } */ #define MBEDTLS_OID_ECDSA_SHA512 MBEDTLS_OID_ANSI_X9_62_SIG_SHA2 "\x04" #ifdef __cplusplus extern "C" { #endif /** * \brief Base OID descriptor structure */ typedef struct mbedtls_oid_descriptor_t { const char *asn1; /*!< OID ASN.1 representation */ size_t asn1_len; /*!< length of asn1 */ const char *name; /*!< official name (e.g. from RFC) */ const char *description; /*!< human friendly description */ } mbedtls_oid_descriptor_t; /** * \brief Translate an ASN.1 OID into its numeric representation * (e.g. "\x2A\x86\x48\x86\xF7\x0D" into "1.2.840.113549") * * \param buf buffer to put representation in * \param size size of the buffer * \param oid OID to translate * * \return Length of the string written (excluding final NULL) or * MBEDTLS_ERR_OID_BUF_TOO_SMALL in case of error */ int mbedtls_oid_get_numeric_string( char *buf, size_t size, const mbedtls_asn1_buf *oid ); /** * \brief Translate an X.509 extension OID into local values * * \param oid OID to use * \param ext_type place to store the extension type * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_x509_ext_type( const mbedtls_asn1_buf *oid, int *ext_type ); /** * \brief Translate an X.509 attribute type OID into the short name * (e.g. the OID for an X520 Common Name into "CN") * * \param oid OID to use * \param short_name place to store the string pointer * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_attr_short_name( const mbedtls_asn1_buf *oid, const char **short_name ); /** * \brief Translate PublicKeyAlgorithm OID into pk_type * * \param oid OID to use * \param pk_alg place to store public key algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_pk_alg( const mbedtls_asn1_buf *oid, mbedtls_pk_type_t *pk_alg ); /** * \brief Translate pk_type into PublicKeyAlgorithm OID * * \param pk_alg Public key type to look for * \param oid place to store ASN.1 OID string pointer * \param olen length of the OID * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_oid_by_pk_alg( mbedtls_pk_type_t pk_alg, const char **oid, size_t *olen ); #if defined(MBEDTLS_ECP_C) /** * \brief Translate NamedCurve OID into an EC group identifier * * \param oid OID to use * \param grp_id place to store group id * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_ec_grp( const mbedtls_asn1_buf *oid, mbedtls_ecp_group_id *grp_id ); /** * \brief Translate EC group identifier into NamedCurve OID * * \param grp_id EC group identifier * \param oid place to store ASN.1 OID string pointer * \param olen length of the OID * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_oid_by_ec_grp( mbedtls_ecp_group_id grp_id, const char **oid, size_t *olen ); #endif /* MBEDTLS_ECP_C */ #if defined(MBEDTLS_MD_C) /** * \brief Translate SignatureAlgorithm OID into md_type and pk_type * * \param oid OID to use * \param md_alg place to store message digest algorithm * \param pk_alg place to store public key algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_sig_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg, mbedtls_pk_type_t *pk_alg ); /** * \brief Translate SignatureAlgorithm OID into description * * \param oid OID to use * \param desc place to store string pointer * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_sig_alg_desc( const mbedtls_asn1_buf *oid, const char **desc ); /** * \brief Translate md_type and pk_type into SignatureAlgorithm OID * * \param md_alg message digest algorithm * \param pk_alg public key algorithm * \param oid place to store ASN.1 OID string pointer * \param olen length of the OID * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_oid_by_sig_alg( mbedtls_pk_type_t pk_alg, mbedtls_md_type_t md_alg, const char **oid, size_t *olen ); /** * \brief Translate hash algorithm OID into md_type * * \param oid OID to use * \param md_alg place to store message digest algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_md_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg ); /** * \brief Translate hmac algorithm OID into md_type * * \param oid OID to use * \param md_hmac place to store message hmac algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_md_hmac( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_hmac ); #endif /* MBEDTLS_MD_C */ /** * \brief Translate Extended Key Usage OID into description * * \param oid OID to use * \param desc place to store string pointer * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_extended_key_usage( const mbedtls_asn1_buf *oid, const char **desc ); /** * \brief Translate certificate policies OID into description * * \param oid OID to use * \param desc place to store string pointer * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_certificate_policies( const mbedtls_asn1_buf *oid, const char **desc ); /** * \brief Translate md_type into hash algorithm OID * * \param md_alg message digest algorithm * \param oid place to store ASN.1 OID string pointer * \param olen length of the OID * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_oid_by_md( mbedtls_md_type_t md_alg, const char **oid, size_t *olen ); #if defined(MBEDTLS_CIPHER_C) /** * \brief Translate encryption algorithm OID into cipher_type * * \param oid OID to use * \param cipher_alg place to store cipher algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_cipher_alg( const mbedtls_asn1_buf *oid, mbedtls_cipher_type_t *cipher_alg ); #endif /* MBEDTLS_CIPHER_C */ #if defined(MBEDTLS_PKCS12_C) /** * \brief Translate PKCS#12 PBE algorithm OID into md_type and * cipher_type * * \param oid OID to use * \param md_alg place to store message digest algorithm * \param cipher_alg place to store cipher algorithm * * \return 0 if successful, or MBEDTLS_ERR_OID_NOT_FOUND */ int mbedtls_oid_get_pkcs12_pbe_alg( const mbedtls_asn1_buf *oid, mbedtls_md_type_t *md_alg, mbedtls_cipher_type_t *cipher_alg ); #endif /* MBEDTLS_PKCS12_C */ #ifdef __cplusplus } #endif #endif /* oid.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/pkcs12.h
/** * \file pkcs12.h * * \brief PKCS#12 Personal Information Exchange Syntax */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_PKCS12_H #define MBEDTLS_PKCS12_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/md.h" #include "mbedtls/cipher.h" #include "mbedtls/asn1.h" #include <stddef.h> #define MBEDTLS_ERR_PKCS12_BAD_INPUT_DATA -0x1F80 /**< Bad input parameters to function. */ #define MBEDTLS_ERR_PKCS12_FEATURE_UNAVAILABLE -0x1F00 /**< Feature not available, e.g. unsupported encryption scheme. */ #define MBEDTLS_ERR_PKCS12_PBE_INVALID_FORMAT -0x1E80 /**< PBE ASN.1 data not as expected. */ #define MBEDTLS_ERR_PKCS12_PASSWORD_MISMATCH -0x1E00 /**< Given private key password does not allow for correct decryption. */ #define MBEDTLS_PKCS12_DERIVE_KEY 1 /**< encryption/decryption key */ #define MBEDTLS_PKCS12_DERIVE_IV 2 /**< initialization vector */ #define MBEDTLS_PKCS12_DERIVE_MAC_KEY 3 /**< integrity / MAC key */ #define MBEDTLS_PKCS12_PBE_DECRYPT 0 #define MBEDTLS_PKCS12_PBE_ENCRYPT 1 #ifdef __cplusplus extern "C" { #endif #if defined(MBEDTLS_ASN1_PARSE_C) /** * \brief PKCS12 Password Based function (encryption / decryption) * for pbeWithSHAAnd128BitRC4 * * \param pbe_params an ASN1 buffer containing the pkcs-12PbeParams structure * \param mode either MBEDTLS_PKCS12_PBE_ENCRYPT or MBEDTLS_PKCS12_PBE_DECRYPT * \param pwd the password used (may be NULL if no password is used) * \param pwdlen length of the password (may be 0) * \param input the input data * \param len data length * \param output the output buffer * * \return 0 if successful, or a MBEDTLS_ERR_XXX code */ int mbedtls_pkcs12_pbe_sha1_rc4_128( mbedtls_asn1_buf *pbe_params, int mode, const unsigned char *pwd, size_t pwdlen, const unsigned char *input, size_t len, unsigned char *output ); /** * \brief PKCS12 Password Based function (encryption / decryption) * for cipher-based and mbedtls_md-based PBE's * * \param pbe_params an ASN1 buffer containing the pkcs-12PbeParams structure * \param mode either MBEDTLS_PKCS12_PBE_ENCRYPT or MBEDTLS_PKCS12_PBE_DECRYPT * \param cipher_type the cipher used * \param md_type the mbedtls_md used * \param pwd the password used (may be NULL if no password is used) * \param pwdlen length of the password (may be 0) * \param input the input data * \param len data length * \param output the output buffer * * \return 0 if successful, or a MBEDTLS_ERR_XXX code */ int mbedtls_pkcs12_pbe( mbedtls_asn1_buf *pbe_params, int mode, mbedtls_cipher_type_t cipher_type, mbedtls_md_type_t md_type, const unsigned char *pwd, size_t pwdlen, const unsigned char *input, size_t len, unsigned char *output ); #endif /* MBEDTLS_ASN1_PARSE_C */ /** * \brief The PKCS#12 derivation function uses a password and a salt * to produce pseudo-random bits for a particular "purpose". * * Depending on the given id, this function can produce an * encryption/decryption key, an nitialization vector or an * integrity key. * * \param data buffer to store the derived data in * \param datalen length to fill * \param pwd password to use (may be NULL if no password is used) * \param pwdlen length of the password (may be 0) * \param salt salt buffer to use * \param saltlen length of the salt * \param mbedtls_md mbedtls_md type to use during the derivation * \param id id that describes the purpose (can be MBEDTLS_PKCS12_DERIVE_KEY, * MBEDTLS_PKCS12_DERIVE_IV or MBEDTLS_PKCS12_DERIVE_MAC_KEY) * \param iterations number of iterations * * \return 0 if successful, or a MD, BIGNUM type error. */ int mbedtls_pkcs12_derivation( unsigned char *data, size_t datalen, const unsigned char *pwd, size_t pwdlen, const unsigned char *salt, size_t saltlen, mbedtls_md_type_t mbedtls_md, int id, int iterations ); #ifdef __cplusplus } #endif #endif /* pkcs12.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/net_sockets.h
/** * \file net_sockets.h * * \brief Network sockets abstraction layer to integrate Mbed TLS into a * BSD-style sockets API. * * The network sockets module provides an example integration of the * Mbed TLS library into a BSD sockets implementation. The module is * intended to be an example of how Mbed TLS can be integrated into a * networking stack, as well as to be Mbed TLS's network integration * for its supported platforms. * * The module is intended only to be used with the Mbed TLS library and * is not intended to be used by third party application software * directly. * * The supported platforms are as follows: * * Microsoft Windows and Windows CE * * POSIX/Unix platforms including Linux, OS X * */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_NET_SOCKETS_H #define MBEDTLS_NET_SOCKETS_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/ssl.h" #include <stddef.h> #include <stdint.h> #define MBEDTLS_ERR_NET_SOCKET_FAILED -0x0042 /**< Failed to open a socket. */ #define MBEDTLS_ERR_NET_CONNECT_FAILED -0x0044 /**< The connection to the given server / port failed. */ #define MBEDTLS_ERR_NET_BIND_FAILED -0x0046 /**< Binding of the socket failed. */ #define MBEDTLS_ERR_NET_LISTEN_FAILED -0x0048 /**< Could not listen on the socket. */ #define MBEDTLS_ERR_NET_ACCEPT_FAILED -0x004A /**< Could not accept the incoming connection. */ #define MBEDTLS_ERR_NET_RECV_FAILED -0x004C /**< Reading information from the socket failed. */ #define MBEDTLS_ERR_NET_SEND_FAILED -0x004E /**< Sending information through the socket failed. */ #define MBEDTLS_ERR_NET_CONN_RESET -0x0050 /**< Connection was reset by peer. */ #define MBEDTLS_ERR_NET_UNKNOWN_HOST -0x0052 /**< Failed to get an IP address for the given hostname. */ #define MBEDTLS_ERR_NET_BUFFER_TOO_SMALL -0x0043 /**< Buffer is too small to hold the data. */ #define MBEDTLS_ERR_NET_INVALID_CONTEXT -0x0045 /**< The context is invalid, eg because it was free()ed. */ #define MBEDTLS_ERR_NET_POLL_FAILED -0x0047 /**< Polling the net context failed. */ #define MBEDTLS_ERR_NET_BAD_INPUT_DATA -0x0049 /**< Input invalid. */ #define MBEDTLS_NET_LISTEN_BACKLOG 10 /**< The backlog that listen() should use. */ #define MBEDTLS_NET_PROTO_TCP 0 /**< The TCP transport protocol */ #define MBEDTLS_NET_PROTO_UDP 1 /**< The UDP transport protocol */ #define MBEDTLS_NET_POLL_READ 1 /**< Used in \c mbedtls_net_poll to check for pending data */ #define MBEDTLS_NET_POLL_WRITE 2 /**< Used in \c mbedtls_net_poll to check if write possible */ #ifdef __cplusplus extern "C" { #endif /** * Wrapper type for sockets. * * Currently backed by just a file descriptor, but might be more in the future * (eg two file descriptors for combined IPv4 + IPv6 support, or additional * structures for hand-made UDP demultiplexing). */ typedef struct mbedtls_net_context { int fd; /**< The underlying file descriptor */ } mbedtls_net_context; /** * \brief Initialize a context * Just makes the context ready to be used or freed safely. * * \param ctx Context to initialize */ void mbedtls_net_init( mbedtls_net_context *ctx ); /** * \brief Initiate a connection with host:port in the given protocol * * \param ctx Socket to use * \param host Host to connect to * \param port Port to connect to * \param proto Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP * * \return 0 if successful, or one of: * MBEDTLS_ERR_NET_SOCKET_FAILED, * MBEDTLS_ERR_NET_UNKNOWN_HOST, * MBEDTLS_ERR_NET_CONNECT_FAILED * * \note Sets the socket in connected mode even with UDP. */ int mbedtls_net_connect( mbedtls_net_context *ctx, const char *host, const char *port, int proto ); /** * \brief Create a receiving socket on bind_ip:port in the chosen * protocol. If bind_ip == NULL, all interfaces are bound. * * \param ctx Socket to use * \param bind_ip IP to bind to, can be NULL * \param port Port number to use * \param proto Protocol: MBEDTLS_NET_PROTO_TCP or MBEDTLS_NET_PROTO_UDP * * \return 0 if successful, or one of: * MBEDTLS_ERR_NET_SOCKET_FAILED, * MBEDTLS_ERR_NET_UNKNOWN_HOST, * MBEDTLS_ERR_NET_BIND_FAILED, * MBEDTLS_ERR_NET_LISTEN_FAILED * * \note Regardless of the protocol, opens the sockets and binds it. * In addition, make the socket listening if protocol is TCP. */ int mbedtls_net_bind( mbedtls_net_context *ctx, const char *bind_ip, const char *port, int proto ); /** * \brief Accept a connection from a remote client * * \param bind_ctx Relevant socket * \param client_ctx Will contain the connected client socket * \param client_ip Will contain the client IP address, can be NULL * \param buf_size Size of the client_ip buffer * \param ip_len Will receive the size of the client IP written, * can be NULL if client_ip is null * * \return 0 if successful, or * MBEDTLS_ERR_NET_SOCKET_FAILED, * MBEDTLS_ERR_NET_BIND_FAILED, * MBEDTLS_ERR_NET_ACCEPT_FAILED, or * MBEDTLS_ERR_NET_BUFFER_TOO_SMALL if buf_size is too small, * MBEDTLS_ERR_SSL_WANT_READ if bind_fd was set to * non-blocking and accept() would block. */ int mbedtls_net_accept( mbedtls_net_context *bind_ctx, mbedtls_net_context *client_ctx, void *client_ip, size_t buf_size, size_t *ip_len ); /** * \brief Check and wait for the context to be ready for read/write * * \note The current implementation of this function uses * select() and returns an error if the file descriptor * is \c FD_SETSIZE or greater. * * \param ctx Socket to check * \param rw Bitflag composed of MBEDTLS_NET_POLL_READ and * MBEDTLS_NET_POLL_WRITE specifying the events * to wait for: * - If MBEDTLS_NET_POLL_READ is set, the function * will return as soon as the net context is available * for reading. * - If MBEDTLS_NET_POLL_WRITE is set, the function * will return as soon as the net context is available * for writing. * \param timeout Maximal amount of time to wait before returning, * in milliseconds. If \c timeout is zero, the * function returns immediately. If \c timeout is * -1u, the function blocks potentially indefinitely. * * \return Bitmask composed of MBEDTLS_NET_POLL_READ/WRITE * on success or timeout, or a negative return code otherwise. */ int mbedtls_net_poll( mbedtls_net_context *ctx, uint32_t rw, uint32_t timeout ); /** * \brief Set the socket blocking * * \param ctx Socket to set * * \return 0 if successful, or a non-zero error code */ int mbedtls_net_set_block( mbedtls_net_context *ctx ); /** * \brief Set the socket non-blocking * * \param ctx Socket to set * * \return 0 if successful, or a non-zero error code */ int mbedtls_net_set_nonblock( mbedtls_net_context *ctx ); /** * \brief Portable usleep helper * * \param usec Amount of microseconds to sleep * * \note Real amount of time slept will not be less than * select()'s timeout granularity (typically, 10ms). */ void mbedtls_net_usleep( unsigned long usec ); /** * \brief Read at most 'len' characters. If no error occurs, * the actual amount read is returned. * * \param ctx Socket * \param buf The buffer to write to * \param len Maximum length of the buffer * * \return the number of bytes received, * or a non-zero error code; with a non-blocking socket, * MBEDTLS_ERR_SSL_WANT_READ indicates read() would block. */ int mbedtls_net_recv( void *ctx, unsigned char *buf, size_t len ); /** * \brief Write at most 'len' characters. If no error occurs, * the actual amount read is returned. * * \param ctx Socket * \param buf The buffer to read from * \param len The length of the buffer * * \return the number of bytes sent, * or a non-zero error code; with a non-blocking socket, * MBEDTLS_ERR_SSL_WANT_WRITE indicates write() would block. */ int mbedtls_net_send( void *ctx, const unsigned char *buf, size_t len ); /** * \brief Read at most 'len' characters, blocking for at most * 'timeout' seconds. If no error occurs, the actual amount * read is returned. * * \note The current implementation of this function uses * select() and returns an error if the file descriptor * is \c FD_SETSIZE or greater. * * \param ctx Socket * \param buf The buffer to write to * \param len Maximum length of the buffer * \param timeout Maximum number of milliseconds to wait for data * 0 means no timeout (wait forever) * * \return The number of bytes received if successful. * MBEDTLS_ERR_SSL_TIMEOUT if the operation timed out. * MBEDTLS_ERR_SSL_WANT_READ if interrupted by a signal. * Another negative error code (MBEDTLS_ERR_NET_xxx) * for other failures. * * \note This function will block (until data becomes available or * timeout is reached) even if the socket is set to * non-blocking. Handling timeouts with non-blocking reads * requires a different strategy. */ int mbedtls_net_recv_timeout( void *ctx, unsigned char *buf, size_t len, uint32_t timeout ); /** * \brief Closes down the connection and free associated data * * \param ctx The context to close */ void mbedtls_net_close( mbedtls_net_context *ctx ); /** * \brief Gracefully shutdown the connection and free associated data * * \param ctx The context to free */ void mbedtls_net_free( mbedtls_net_context *ctx ); #ifdef __cplusplus } #endif #endif /* net_sockets.h */
0
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include
repos/gyro/.gyro/zig-mbedtls-mattnite-github.com-a4f5357c/pkg/mbedtls/include/mbedtls/dhm.h
/** * \file dhm.h * * \brief This file contains Diffie-Hellman-Merkle (DHM) key exchange * definitions and functions. * * Diffie-Hellman-Merkle (DHM) key exchange is defined in * <em>RFC-2631: Diffie-Hellman Key Agreement Method</em> and * <em>Public-Key Cryptography Standards (PKCS) #3: Diffie * Hellman Key Agreement Standard</em>. * * <em>RFC-3526: More Modular Exponential (MODP) Diffie-Hellman groups for * Internet Key Exchange (IKE)</em> defines a number of standardized * Diffie-Hellman groups for IKE. * * <em>RFC-5114: Additional Diffie-Hellman Groups for Use with IETF * Standards</em> defines a number of standardized Diffie-Hellman * groups that can be used. * * \warning The security of the DHM key exchange relies on the proper choice * of prime modulus - optimally, it should be a safe prime. The usage * of non-safe primes both decreases the difficulty of the underlying * discrete logarithm problem and can lead to small subgroup attacks * leaking private exponent bits when invalid public keys are used * and not detected. This is especially relevant if the same DHM * parameters are reused for multiple key exchanges as in static DHM, * while the criticality of small-subgroup attacks is lower for * ephemeral DHM. * * \warning For performance reasons, the code does neither perform primality * nor safe primality tests, nor the expensive checks for invalid * subgroups. Moreover, even if these were performed, non-standardized * primes cannot be trusted because of the possibility of backdoors * that can't be effectively checked for. * * \warning Diffie-Hellman-Merkle is therefore a security risk when not using * standardized primes generated using a trustworthy ("nothing up * my sleeve") method, such as the RFC 3526 / 7919 primes. In the TLS * protocol, DH parameters need to be negotiated, so using the default * primes systematically is not always an option. If possible, use * Elliptic Curve Diffie-Hellman (ECDH), which has better performance, * and for which the TLS protocol mandates the use of standard * parameters. * */ /* * Copyright The Mbed TLS Contributors * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ #ifndef MBEDTLS_DHM_H #define MBEDTLS_DHM_H #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #include "mbedtls/bignum.h" /* * DHM Error codes */ #define MBEDTLS_ERR_DHM_BAD_INPUT_DATA -0x3080 /**< Bad input parameters. */ #define MBEDTLS_ERR_DHM_READ_PARAMS_FAILED -0x3100 /**< Reading of the DHM parameters failed. */ #define MBEDTLS_ERR_DHM_MAKE_PARAMS_FAILED -0x3180 /**< Making of the DHM parameters failed. */ #define MBEDTLS_ERR_DHM_READ_PUBLIC_FAILED -0x3200 /**< Reading of the public values failed. */ #define MBEDTLS_ERR_DHM_MAKE_PUBLIC_FAILED -0x3280 /**< Making of the public value failed. */ #define MBEDTLS_ERR_DHM_CALC_SECRET_FAILED -0x3300 /**< Calculation of the DHM secret failed. */ #define MBEDTLS_ERR_DHM_INVALID_FORMAT -0x3380 /**< The ASN.1 data is not formatted correctly. */ #define MBEDTLS_ERR_DHM_ALLOC_FAILED -0x3400 /**< Allocation of memory failed. */ #define MBEDTLS_ERR_DHM_FILE_IO_ERROR -0x3480 /**< Read or write of file failed. */ /* MBEDTLS_ERR_DHM_HW_ACCEL_FAILED is deprecated and should not be used. */ #define MBEDTLS_ERR_DHM_HW_ACCEL_FAILED -0x3500 /**< DHM hardware accelerator failed. */ #define MBEDTLS_ERR_DHM_SET_GROUP_FAILED -0x3580 /**< Setting the modulus and generator failed. */ #ifdef __cplusplus extern "C" { #endif #if !defined(MBEDTLS_DHM_ALT) /** * \brief The DHM context structure. */ typedef struct mbedtls_dhm_context { size_t len; /*!< The size of \p P in Bytes. */ mbedtls_mpi P; /*!< The prime modulus. */ mbedtls_mpi G; /*!< The generator. */ mbedtls_mpi X; /*!< Our secret value. */ mbedtls_mpi GX; /*!< Our public key = \c G^X mod \c P. */ mbedtls_mpi GY; /*!< The public key of the peer = \c G^Y mod \c P. */ mbedtls_mpi K; /*!< The shared secret = \c G^(XY) mod \c P. */ mbedtls_mpi RP; /*!< The cached value = \c R^2 mod \c P. */ mbedtls_mpi Vi; /*!< The blinding value. */ mbedtls_mpi Vf; /*!< The unblinding value. */ mbedtls_mpi pX; /*!< The previous \c X. */ } mbedtls_dhm_context; #else /* MBEDTLS_DHM_ALT */ #include "dhm_alt.h" #endif /* MBEDTLS_DHM_ALT */ /** * \brief This function initializes the DHM context. * * \param ctx The DHM context to initialize. */ void mbedtls_dhm_init( mbedtls_dhm_context *ctx ); /** * \brief This function parses the DHM parameters in a * TLS ServerKeyExchange handshake message * (DHM modulus, generator, and public key). * * \note In a TLS handshake, this is the how the client * sets up its DHM context from the server's public * DHM key material. * * \param ctx The DHM context to use. This must be initialized. * \param p On input, *p must be the start of the input buffer. * On output, *p is updated to point to the end of the data * that has been read. On success, this is the first byte * past the end of the ServerKeyExchange parameters. * On error, this is the point at which an error has been * detected, which is usually not useful except to debug * failures. * \param end The end of the input buffer. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_read_params( mbedtls_dhm_context *ctx, unsigned char **p, const unsigned char *end ); /** * \brief This function generates a DHM key pair and exports its * public part together with the DHM parameters in the format * used in a TLS ServerKeyExchange handshake message. * * \note This function assumes that the DHM parameters \c ctx->P * and \c ctx->G have already been properly set. For that, use * mbedtls_dhm_set_group() below in conjunction with * mbedtls_mpi_read_binary() and mbedtls_mpi_read_string(). * * \note In a TLS handshake, this is the how the server generates * and exports its DHM key material. * * \param ctx The DHM context to use. This must be initialized * and have the DHM parameters set. It may or may not * already have imported the peer's public key. * \param x_size The private key size in Bytes. * \param olen The address at which to store the number of Bytes * written on success. This must not be \c NULL. * \param output The destination buffer. This must be a writable buffer of * sufficient size to hold the reduced binary presentation of * the modulus, the generator and the public key, each wrapped * with a 2-byte length field. It is the responsibility of the * caller to ensure that enough space is available. Refer to * mbedtls_mpi_size() to computing the byte-size of an MPI. * \param f_rng The RNG function. Must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may be * \c NULL if \p f_rng doesn't need a context parameter. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_make_params( mbedtls_dhm_context *ctx, int x_size, unsigned char *output, size_t *olen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function sets the prime modulus and generator. * * \note This function can be used to set \c ctx->P, \c ctx->G * in preparation for mbedtls_dhm_make_params(). * * \param ctx The DHM context to configure. This must be initialized. * \param P The MPI holding the DHM prime modulus. This must be * an initialized MPI. * \param G The MPI holding the DHM generator. This must be an * initialized MPI. * * \return \c 0 if successful. * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_set_group( mbedtls_dhm_context *ctx, const mbedtls_mpi *P, const mbedtls_mpi *G ); /** * \brief This function imports the raw public value of the peer. * * \note In a TLS handshake, this is the how the server imports * the Client's public DHM key. * * \param ctx The DHM context to use. This must be initialized and have * its DHM parameters set, e.g. via mbedtls_dhm_set_group(). * It may or may not already have generated its own private key. * \param input The input buffer containing the \c G^Y value of the peer. * This must be a readable buffer of size \p ilen Bytes. * \param ilen The size of the input buffer \p input in Bytes. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_read_public( mbedtls_dhm_context *ctx, const unsigned char *input, size_t ilen ); /** * \brief This function creates a DHM key pair and exports * the raw public key in big-endian format. * * \note The destination buffer is always fully written * so as to contain a big-endian representation of G^X mod P. * If it is larger than \c ctx->len, it is padded accordingly * with zero-bytes at the beginning. * * \param ctx The DHM context to use. This must be initialized and * have the DHM parameters set. It may or may not already * have imported the peer's public key. * \param x_size The private key size in Bytes. * \param output The destination buffer. This must be a writable buffer of * size \p olen Bytes. * \param olen The length of the destination buffer. This must be at least * equal to `ctx->len` (the size of \c P). * \param f_rng The RNG function. This must not be \c NULL. * \param p_rng The RNG context to be passed to \p f_rng. This may be \c NULL * if \p f_rng doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_make_public( mbedtls_dhm_context *ctx, int x_size, unsigned char *output, size_t olen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function derives and exports the shared secret * \c (G^Y)^X mod \c P. * * \note If \p f_rng is not \c NULL, it is used to blind the input as * a countermeasure against timing attacks. Blinding is used * only if our private key \c X is re-used, and not used * otherwise. We recommend always passing a non-NULL * \p f_rng argument. * * \param ctx The DHM context to use. This must be initialized * and have its own private key generated and the peer's * public key imported. * \param output The buffer to write the generated shared key to. This * must be a writable buffer of size \p output_size Bytes. * \param output_size The size of the destination buffer. This must be at * least the size of \c ctx->len (the size of \c P). * \param olen On exit, holds the actual number of Bytes written. * \param f_rng The RNG function, for blinding purposes. This may * b \c NULL if blinding isn't needed. * \param p_rng The RNG context. This may be \c NULL if \p f_rng * doesn't need a context argument. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_DHM_XXX error code on failure. */ int mbedtls_dhm_calc_secret( mbedtls_dhm_context *ctx, unsigned char *output, size_t output_size, size_t *olen, int (*f_rng)(void *, unsigned char *, size_t), void *p_rng ); /** * \brief This function frees and clears the components * of a DHM context. * * \param ctx The DHM context to free and clear. This may be \c NULL, * in which case this function is a no-op. If it is not \c NULL, * it must point to an initialized DHM context. */ void mbedtls_dhm_free( mbedtls_dhm_context *ctx ); #if defined(MBEDTLS_ASN1_PARSE_C) /** * \brief This function parses DHM parameters in PEM or DER format. * * \param dhm The DHM context to import the DHM parameters into. * This must be initialized. * \param dhmin The input buffer. This must be a readable buffer of * length \p dhminlen Bytes. * \param dhminlen The size of the input buffer \p dhmin, including the * terminating \c NULL Byte for PEM data. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_DHM_XXX or \c MBEDTLS_ERR_PEM_XXX error * code on failure. */ int mbedtls_dhm_parse_dhm( mbedtls_dhm_context *dhm, const unsigned char *dhmin, size_t dhminlen ); #if defined(MBEDTLS_FS_IO) /** * \brief This function loads and parses DHM parameters from a file. * * \param dhm The DHM context to load the parameters to. * This must be initialized. * \param path The filename to read the DHM parameters from. * This must not be \c NULL. * * \return \c 0 on success. * \return An \c MBEDTLS_ERR_DHM_XXX or \c MBEDTLS_ERR_PEM_XXX * error code on failure. */ int mbedtls_dhm_parse_dhmfile( mbedtls_dhm_context *dhm, const char *path ); #endif /* MBEDTLS_FS_IO */ #endif /* MBEDTLS_ASN1_PARSE_C */ #if defined(MBEDTLS_SELF_TEST) /** * \brief The DMH checkup routine. * * \return \c 0 on success. * \return \c 1 on failure. */ int mbedtls_dhm_self_test( int verbose ); #endif /* MBEDTLS_SELF_TEST */ #ifdef __cplusplus } #endif /** * RFC 3526, RFC 5114 and RFC 7919 standardize a number of * Diffie-Hellman groups, some of which are included here * for use within the SSL/TLS module and the user's convenience * when configuring the Diffie-Hellman parameters by hand * through \c mbedtls_ssl_conf_dh_param. * * The following lists the source of the above groups in the standards: * - RFC 5114 section 2.2: 2048-bit MODP Group with 224-bit Prime Order Subgroup * - RFC 3526 section 3: 2048-bit MODP Group * - RFC 3526 section 4: 3072-bit MODP Group * - RFC 3526 section 5: 4096-bit MODP Group * - RFC 7919 section A.1: ffdhe2048 * - RFC 7919 section A.2: ffdhe3072 * - RFC 7919 section A.3: ffdhe4096 * - RFC 7919 section A.4: ffdhe6144 * - RFC 7919 section A.5: ffdhe8192 * * The constants with suffix "_p" denote the chosen prime moduli, while * the constants with suffix "_g" denote the chosen generator * of the associated prime field. * * The constants further suffixed with "_bin" are provided in binary format, * while all other constants represent null-terminated strings holding the * hexadecimal presentation of the respective numbers. * * The primes from RFC 3526 and RFC 7919 have been generating by the following * trust-worthy procedure: * - Fix N in { 2048, 3072, 4096, 6144, 8192 } and consider the N-bit number * the first and last 64 bits are all 1, and the remaining N - 128 bits of * which are 0x7ff...ff. * - Add the smallest multiple of the first N - 129 bits of the binary expansion * of pi (for RFC 5236) or e (for RFC 7919) to this intermediate bit-string * such that the resulting integer is a safe-prime. * - The result is the respective RFC 3526 / 7919 prime, and the corresponding * generator is always chosen to be 2 (which is a square for these prime, * hence the corresponding subgroup has order (p-1)/2 and avoids leaking a * bit in the private exponent). * */ #if !defined(MBEDTLS_DEPRECATED_REMOVED) /** * \warning The origin of the primes in RFC 5114 is not documented and * their use therefore constitutes a security risk! * * \deprecated The hex-encoded primes from RFC 5114 are deprecated and are * likely to be removed in a future version of the library without * replacement. */ /** * The hexadecimal presentation of the prime underlying the * 2048-bit MODP Group with 224-bit Prime Order Subgroup, as defined * in <em>RFC-5114: Additional Diffie-Hellman Groups for Use with * IETF Standards</em>. */ #define MBEDTLS_DHM_RFC5114_MODP_2048_P \ MBEDTLS_DEPRECATED_STRING_CONSTANT( \ "AD107E1E9123A9D0D660FAA79559C51FA20D64E5683B9FD1" \ "B54B1597B61D0A75E6FA141DF95A56DBAF9A3C407BA1DF15" \ "EB3D688A309C180E1DE6B85A1274A0A66D3F8152AD6AC212" \ "9037C9EDEFDA4DF8D91E8FEF55B7394B7AD5B7D0B6C12207" \ "C9F98D11ED34DBF6C6BA0B2C8BBC27BE6A00E0A0B9C49708" \ "B3BF8A317091883681286130BC8985DB1602E714415D9330" \ "278273C7DE31EFDC7310F7121FD5A07415987D9ADC0A486D" \ "CDF93ACC44328387315D75E198C641A480CD86A1B9E587E8" \ "BE60E69CC928B2B9C52172E413042E9B23F10B0E16E79763" \ "C9B53DCF4BA80A29E3FB73C16B8E75B97EF363E2FFA31F71" \ "CF9DE5384E71B81C0AC4DFFE0C10E64F" ) /** * The hexadecimal presentation of the chosen generator of the 2048-bit MODP * Group with 224-bit Prime Order Subgroup, as defined in <em>RFC-5114: * Additional Diffie-Hellman Groups for Use with IETF Standards</em>. */ #define MBEDTLS_DHM_RFC5114_MODP_2048_G \ MBEDTLS_DEPRECATED_STRING_CONSTANT( \ "AC4032EF4F2D9AE39DF30B5C8FFDAC506CDEBE7B89998CAF" \ "74866A08CFE4FFE3A6824A4E10B9A6F0DD921F01A70C4AFA" \ "AB739D7700C29F52C57DB17C620A8652BE5E9001A8D66AD7" \ "C17669101999024AF4D027275AC1348BB8A762D0521BC98A" \ "E247150422EA1ED409939D54DA7460CDB5F6C6B250717CBE" \ "F180EB34118E98D119529A45D6F834566E3025E316A330EF" \ "BB77A86F0C1AB15B051AE3D428C8F8ACB70A8137150B8EEB" \ "10E183EDD19963DDD9E263E4770589EF6AA21E7F5F2FF381" \ "B539CCE3409D13CD566AFBB48D6C019181E1BCFE94B30269" \ "EDFE72FE9B6AA4BD7B5A0F1C71CFFF4C19C418E1F6EC0179" \ "81BC087F2A7065B384B890D3191F2BFA" ) /** * The hexadecimal presentation of the prime underlying the 2048-bit MODP * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP) * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>. * * \deprecated The hex-encoded primes from RFC 3625 are deprecated and * superseded by the corresponding macros providing them as * binary constants. Their hex-encoded constants are likely * to be removed in a future version of the library. * */ #define MBEDTLS_DHM_RFC3526_MODP_2048_P \ MBEDTLS_DEPRECATED_STRING_CONSTANT( \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ "15728E5A8AACAA68FFFFFFFFFFFFFFFF" ) /** * The hexadecimal presentation of the chosen generator of the 2048-bit MODP * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP) * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>. */ #define MBEDTLS_DHM_RFC3526_MODP_2048_G \ MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" ) /** * The hexadecimal presentation of the prime underlying the 3072-bit MODP * Group, as defined in <em>RFC-3072: More Modular Exponential (MODP) * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>. */ #define MBEDTLS_DHM_RFC3526_MODP_3072_P \ MBEDTLS_DEPRECATED_STRING_CONSTANT( \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ "43DB5BFCE0FD108E4B82D120A93AD2CAFFFFFFFFFFFFFFFF" ) /** * The hexadecimal presentation of the chosen generator of the 3072-bit MODP * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP) * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>. */ #define MBEDTLS_DHM_RFC3526_MODP_3072_G \ MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" ) /** * The hexadecimal presentation of the prime underlying the 4096-bit MODP * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP) * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>. */ #define MBEDTLS_DHM_RFC3526_MODP_4096_P \ MBEDTLS_DEPRECATED_STRING_CONSTANT( \ "FFFFFFFFFFFFFFFFC90FDAA22168C234C4C6628B80DC1CD1" \ "29024E088A67CC74020BBEA63B139B22514A08798E3404DD" \ "EF9519B3CD3A431B302B0A6DF25F14374FE1356D6D51C245" \ "E485B576625E7EC6F44C42E9A637ED6B0BFF5CB6F406B7ED" \ "EE386BFB5A899FA5AE9F24117C4B1FE649286651ECE45B3D" \ "C2007CB8A163BF0598DA48361C55D39A69163FA8FD24CF5F" \ "83655D23DCA3AD961C62F356208552BB9ED529077096966D" \ "670C354E4ABC9804F1746C08CA18217C32905E462E36CE3B" \ "E39E772C180E86039B2783A2EC07A28FB5C55DF06F4C52C9" \ "DE2BCBF6955817183995497CEA956AE515D2261898FA0510" \ "15728E5A8AAAC42DAD33170D04507A33A85521ABDF1CBA64" \ "ECFB850458DBEF0A8AEA71575D060C7DB3970F85A6E1E4C7" \ "ABF5AE8CDB0933D71E8C94E04A25619DCEE3D2261AD2EE6B" \ "F12FFA06D98A0864D87602733EC86A64521F2B18177B200C" \ "BBE117577A615D6C770988C0BAD946E208E24FA074E5AB31" \ "43DB5BFCE0FD108E4B82D120A92108011A723C12A787E6D7" \ "88719A10BDBA5B2699C327186AF4E23C1A946834B6150BDA" \ "2583E9CA2AD44CE8DBBBC2DB04DE8EF92E8EFC141FBECAA6" \ "287C59474E6BC05D99B2964FA090C3A2233BA186515BE7ED" \ "1F612970CEE2D7AFB81BDD762170481CD0069127D5B05AA9" \ "93B4EA988D8FDDC186FFB7DC90A6C08F4DF435C934063199" \ "FFFFFFFFFFFFFFFF" ) /** * The hexadecimal presentation of the chosen generator of the 4096-bit MODP * Group, as defined in <em>RFC-3526: More Modular Exponential (MODP) * Diffie-Hellman groups for Internet Key Exchange (IKE)</em>. */ #define MBEDTLS_DHM_RFC3526_MODP_4096_G \ MBEDTLS_DEPRECATED_STRING_CONSTANT( "02" ) #endif /* MBEDTLS_DEPRECATED_REMOVED */ /* * Trustworthy DHM parameters in binary form */ #define MBEDTLS_DHM_RFC3526_MODP_2048_P_BIN { \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \ 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \ 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \ 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \ 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \ 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \ 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \ 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \ 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \ 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \ 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \ 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \ 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \ 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \ 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \ 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \ 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \ 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \ 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \ 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \ 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \ 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \ 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \ 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \ 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \ 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \ 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \ 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \ 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \ 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAC, 0xAA, 0x68, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } #define MBEDTLS_DHM_RFC3526_MODP_2048_G_BIN { 0x02 } #define MBEDTLS_DHM_RFC3526_MODP_3072_P_BIN { \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \ 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \ 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \ 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \ 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \ 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \ 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \ 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \ 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \ 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \ 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \ 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \ 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \ 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \ 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \ 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \ 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \ 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \ 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \ 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \ 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \ 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \ 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \ 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \ 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \ 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \ 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \ 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \ 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \ 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \ 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \ 0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \ 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \ 0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \ 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \ 0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \ 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \ 0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \ 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \ 0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \ 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \ 0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \ 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \ 0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \ 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \ 0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x3A, 0xD2, 0xCA, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } #define MBEDTLS_DHM_RFC3526_MODP_3072_G_BIN { 0x02 } #define MBEDTLS_DHM_RFC3526_MODP_4096_P_BIN { \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xC9, 0x0F, 0xDA, 0xA2, 0x21, 0x68, 0xC2, 0x34, \ 0xC4, 0xC6, 0x62, 0x8B, 0x80, 0xDC, 0x1C, 0xD1, \ 0x29, 0x02, 0x4E, 0x08, 0x8A, 0x67, 0xCC, 0x74, \ 0x02, 0x0B, 0xBE, 0xA6, 0x3B, 0x13, 0x9B, 0x22, \ 0x51, 0x4A, 0x08, 0x79, 0x8E, 0x34, 0x04, 0xDD, \ 0xEF, 0x95, 0x19, 0xB3, 0xCD, 0x3A, 0x43, 0x1B, \ 0x30, 0x2B, 0x0A, 0x6D, 0xF2, 0x5F, 0x14, 0x37, \ 0x4F, 0xE1, 0x35, 0x6D, 0x6D, 0x51, 0xC2, 0x45, \ 0xE4, 0x85, 0xB5, 0x76, 0x62, 0x5E, 0x7E, 0xC6, \ 0xF4, 0x4C, 0x42, 0xE9, 0xA6, 0x37, 0xED, 0x6B, \ 0x0B, 0xFF, 0x5C, 0xB6, 0xF4, 0x06, 0xB7, 0xED, \ 0xEE, 0x38, 0x6B, 0xFB, 0x5A, 0x89, 0x9F, 0xA5, \ 0xAE, 0x9F, 0x24, 0x11, 0x7C, 0x4B, 0x1F, 0xE6, \ 0x49, 0x28, 0x66, 0x51, 0xEC, 0xE4, 0x5B, 0x3D, \ 0xC2, 0x00, 0x7C, 0xB8, 0xA1, 0x63, 0xBF, 0x05, \ 0x98, 0xDA, 0x48, 0x36, 0x1C, 0x55, 0xD3, 0x9A, \ 0x69, 0x16, 0x3F, 0xA8, 0xFD, 0x24, 0xCF, 0x5F, \ 0x83, 0x65, 0x5D, 0x23, 0xDC, 0xA3, 0xAD, 0x96, \ 0x1C, 0x62, 0xF3, 0x56, 0x20, 0x85, 0x52, 0xBB, \ 0x9E, 0xD5, 0x29, 0x07, 0x70, 0x96, 0x96, 0x6D, \ 0x67, 0x0C, 0x35, 0x4E, 0x4A, 0xBC, 0x98, 0x04, \ 0xF1, 0x74, 0x6C, 0x08, 0xCA, 0x18, 0x21, 0x7C, \ 0x32, 0x90, 0x5E, 0x46, 0x2E, 0x36, 0xCE, 0x3B, \ 0xE3, 0x9E, 0x77, 0x2C, 0x18, 0x0E, 0x86, 0x03, \ 0x9B, 0x27, 0x83, 0xA2, 0xEC, 0x07, 0xA2, 0x8F, \ 0xB5, 0xC5, 0x5D, 0xF0, 0x6F, 0x4C, 0x52, 0xC9, \ 0xDE, 0x2B, 0xCB, 0xF6, 0x95, 0x58, 0x17, 0x18, \ 0x39, 0x95, 0x49, 0x7C, 0xEA, 0x95, 0x6A, 0xE5, \ 0x15, 0xD2, 0x26, 0x18, 0x98, 0xFA, 0x05, 0x10, \ 0x15, 0x72, 0x8E, 0x5A, 0x8A, 0xAA, 0xC4, 0x2D, \ 0xAD, 0x33, 0x17, 0x0D, 0x04, 0x50, 0x7A, 0x33, \ 0xA8, 0x55, 0x21, 0xAB, 0xDF, 0x1C, 0xBA, 0x64, \ 0xEC, 0xFB, 0x85, 0x04, 0x58, 0xDB, 0xEF, 0x0A, \ 0x8A, 0xEA, 0x71, 0x57, 0x5D, 0x06, 0x0C, 0x7D, \ 0xB3, 0x97, 0x0F, 0x85, 0xA6, 0xE1, 0xE4, 0xC7, \ 0xAB, 0xF5, 0xAE, 0x8C, 0xDB, 0x09, 0x33, 0xD7, \ 0x1E, 0x8C, 0x94, 0xE0, 0x4A, 0x25, 0x61, 0x9D, \ 0xCE, 0xE3, 0xD2, 0x26, 0x1A, 0xD2, 0xEE, 0x6B, \ 0xF1, 0x2F, 0xFA, 0x06, 0xD9, 0x8A, 0x08, 0x64, \ 0xD8, 0x76, 0x02, 0x73, 0x3E, 0xC8, 0x6A, 0x64, \ 0x52, 0x1F, 0x2B, 0x18, 0x17, 0x7B, 0x20, 0x0C, \ 0xBB, 0xE1, 0x17, 0x57, 0x7A, 0x61, 0x5D, 0x6C, \ 0x77, 0x09, 0x88, 0xC0, 0xBA, 0xD9, 0x46, 0xE2, \ 0x08, 0xE2, 0x4F, 0xA0, 0x74, 0xE5, 0xAB, 0x31, \ 0x43, 0xDB, 0x5B, 0xFC, 0xE0, 0xFD, 0x10, 0x8E, \ 0x4B, 0x82, 0xD1, 0x20, 0xA9, 0x21, 0x08, 0x01, \ 0x1A, 0x72, 0x3C, 0x12, 0xA7, 0x87, 0xE6, 0xD7, \ 0x88, 0x71, 0x9A, 0x10, 0xBD, 0xBA, 0x5B, 0x26, \ 0x99, 0xC3, 0x27, 0x18, 0x6A, 0xF4, 0xE2, 0x3C, \ 0x1A, 0x94, 0x68, 0x34, 0xB6, 0x15, 0x0B, 0xDA, \ 0x25, 0x83, 0xE9, 0xCA, 0x2A, 0xD4, 0x4C, 0xE8, \ 0xDB, 0xBB, 0xC2, 0xDB, 0x04, 0xDE, 0x8E, 0xF9, \ 0x2E, 0x8E, 0xFC, 0x14, 0x1F, 0xBE, 0xCA, 0xA6, \ 0x28, 0x7C, 0x59, 0x47, 0x4E, 0x6B, 0xC0, 0x5D, \ 0x99, 0xB2, 0x96, 0x4F, 0xA0, 0x90, 0xC3, 0xA2, \ 0x23, 0x3B, 0xA1, 0x86, 0x51, 0x5B, 0xE7, 0xED, \ 0x1F, 0x61, 0x29, 0x70, 0xCE, 0xE2, 0xD7, 0xAF, \ 0xB8, 0x1B, 0xDD, 0x76, 0x21, 0x70, 0x48, 0x1C, \ 0xD0, 0x06, 0x91, 0x27, 0xD5, 0xB0, 0x5A, 0xA9, \ 0x93, 0xB4, 0xEA, 0x98, 0x8D, 0x8F, 0xDD, 0xC1, \ 0x86, 0xFF, 0xB7, 0xDC, 0x90, 0xA6, 0xC0, 0x8F, \ 0x4D, 0xF4, 0x35, 0xC9, 0x34, 0x06, 0x31, 0x99, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } #define MBEDTLS_DHM_RFC3526_MODP_4096_G_BIN { 0x02 } #define MBEDTLS_DHM_RFC7919_FFDHE2048_P_BIN { \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x28, 0x5C, 0x97, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, } #define MBEDTLS_DHM_RFC7919_FFDHE2048_G_BIN { 0x02 } #define MBEDTLS_DHM_RFC7919_FFDHE3072_P_BIN { \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0xC6, 0x2E, 0x37, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } #define MBEDTLS_DHM_RFC7919_FFDHE3072_G_BIN { 0x02 } #define MBEDTLS_DHM_RFC7919_FFDHE4096_P_BIN { \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \ 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \ 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \ 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \ 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \ 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \ 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \ 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \ 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \ 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \ 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \ 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \ 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \ 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \ 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \ 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \ 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x65, 0x5F, 0x6A, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } #define MBEDTLS_DHM_RFC7919_FFDHE4096_G_BIN { 0x02 } #define MBEDTLS_DHM_RFC7919_FFDHE6144_P_BIN { \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \ 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \ 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \ 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \ 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \ 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \ 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \ 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \ 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \ 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \ 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \ 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \ 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \ 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \ 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \ 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \ 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \ 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \ 0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \ 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \ 0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \ 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \ 0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \ 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \ 0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \ 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \ 0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \ 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \ 0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \ 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \ 0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \ 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \ 0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \ 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \ 0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \ 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \ 0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \ 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \ 0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \ 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \ 0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \ 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \ 0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \ 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \ 0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \ 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \ 0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \ 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \ 0xA4, 0x0E, 0x32, 0x9C, 0xD0, 0xE4, 0x0E, 0x65, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } #define MBEDTLS_DHM_RFC7919_FFDHE6144_G_BIN { 0x02 } #define MBEDTLS_DHM_RFC7919_FFDHE8192_P_BIN { \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, \ 0xAD, 0xF8, 0x54, 0x58, 0xA2, 0xBB, 0x4A, 0x9A, \ 0xAF, 0xDC, 0x56, 0x20, 0x27, 0x3D, 0x3C, 0xF1, \ 0xD8, 0xB9, 0xC5, 0x83, 0xCE, 0x2D, 0x36, 0x95, \ 0xA9, 0xE1, 0x36, 0x41, 0x14, 0x64, 0x33, 0xFB, \ 0xCC, 0x93, 0x9D, 0xCE, 0x24, 0x9B, 0x3E, 0xF9, \ 0x7D, 0x2F, 0xE3, 0x63, 0x63, 0x0C, 0x75, 0xD8, \ 0xF6, 0x81, 0xB2, 0x02, 0xAE, 0xC4, 0x61, 0x7A, \ 0xD3, 0xDF, 0x1E, 0xD5, 0xD5, 0xFD, 0x65, 0x61, \ 0x24, 0x33, 0xF5, 0x1F, 0x5F, 0x06, 0x6E, 0xD0, \ 0x85, 0x63, 0x65, 0x55, 0x3D, 0xED, 0x1A, 0xF3, \ 0xB5, 0x57, 0x13, 0x5E, 0x7F, 0x57, 0xC9, 0x35, \ 0x98, 0x4F, 0x0C, 0x70, 0xE0, 0xE6, 0x8B, 0x77, \ 0xE2, 0xA6, 0x89, 0xDA, 0xF3, 0xEF, 0xE8, 0x72, \ 0x1D, 0xF1, 0x58, 0xA1, 0x36, 0xAD, 0xE7, 0x35, \ 0x30, 0xAC, 0xCA, 0x4F, 0x48, 0x3A, 0x79, 0x7A, \ 0xBC, 0x0A, 0xB1, 0x82, 0xB3, 0x24, 0xFB, 0x61, \ 0xD1, 0x08, 0xA9, 0x4B, 0xB2, 0xC8, 0xE3, 0xFB, \ 0xB9, 0x6A, 0xDA, 0xB7, 0x60, 0xD7, 0xF4, 0x68, \ 0x1D, 0x4F, 0x42, 0xA3, 0xDE, 0x39, 0x4D, 0xF4, \ 0xAE, 0x56, 0xED, 0xE7, 0x63, 0x72, 0xBB, 0x19, \ 0x0B, 0x07, 0xA7, 0xC8, 0xEE, 0x0A, 0x6D, 0x70, \ 0x9E, 0x02, 0xFC, 0xE1, 0xCD, 0xF7, 0xE2, 0xEC, \ 0xC0, 0x34, 0x04, 0xCD, 0x28, 0x34, 0x2F, 0x61, \ 0x91, 0x72, 0xFE, 0x9C, 0xE9, 0x85, 0x83, 0xFF, \ 0x8E, 0x4F, 0x12, 0x32, 0xEE, 0xF2, 0x81, 0x83, \ 0xC3, 0xFE, 0x3B, 0x1B, 0x4C, 0x6F, 0xAD, 0x73, \ 0x3B, 0xB5, 0xFC, 0xBC, 0x2E, 0xC2, 0x20, 0x05, \ 0xC5, 0x8E, 0xF1, 0x83, 0x7D, 0x16, 0x83, 0xB2, \ 0xC6, 0xF3, 0x4A, 0x26, 0xC1, 0xB2, 0xEF, 0xFA, \ 0x88, 0x6B, 0x42, 0x38, 0x61, 0x1F, 0xCF, 0xDC, \ 0xDE, 0x35, 0x5B, 0x3B, 0x65, 0x19, 0x03, 0x5B, \ 0xBC, 0x34, 0xF4, 0xDE, 0xF9, 0x9C, 0x02, 0x38, \ 0x61, 0xB4, 0x6F, 0xC9, 0xD6, 0xE6, 0xC9, 0x07, \ 0x7A, 0xD9, 0x1D, 0x26, 0x91, 0xF7, 0xF7, 0xEE, \ 0x59, 0x8C, 0xB0, 0xFA, 0xC1, 0x86, 0xD9, 0x1C, \ 0xAE, 0xFE, 0x13, 0x09, 0x85, 0x13, 0x92, 0x70, \ 0xB4, 0x13, 0x0C, 0x93, 0xBC, 0x43, 0x79, 0x44, \ 0xF4, 0xFD, 0x44, 0x52, 0xE2, 0xD7, 0x4D, 0xD3, \ 0x64, 0xF2, 0xE2, 0x1E, 0x71, 0xF5, 0x4B, 0xFF, \ 0x5C, 0xAE, 0x82, 0xAB, 0x9C, 0x9D, 0xF6, 0x9E, \ 0xE8, 0x6D, 0x2B, 0xC5, 0x22, 0x36, 0x3A, 0x0D, \ 0xAB, 0xC5, 0x21, 0x97, 0x9B, 0x0D, 0xEA, 0xDA, \ 0x1D, 0xBF, 0x9A, 0x42, 0xD5, 0xC4, 0x48, 0x4E, \ 0x0A, 0xBC, 0xD0, 0x6B, 0xFA, 0x53, 0xDD, 0xEF, \ 0x3C, 0x1B, 0x20, 0xEE, 0x3F, 0xD5, 0x9D, 0x7C, \ 0x25, 0xE4, 0x1D, 0x2B, 0x66, 0x9E, 0x1E, 0xF1, \ 0x6E, 0x6F, 0x52, 0xC3, 0x16, 0x4D, 0xF4, 0xFB, \ 0x79, 0x30, 0xE9, 0xE4, 0xE5, 0x88, 0x57, 0xB6, \ 0xAC, 0x7D, 0x5F, 0x42, 0xD6, 0x9F, 0x6D, 0x18, \ 0x77, 0x63, 0xCF, 0x1D, 0x55, 0x03, 0x40, 0x04, \ 0x87, 0xF5, 0x5B, 0xA5, 0x7E, 0x31, 0xCC, 0x7A, \ 0x71, 0x35, 0xC8, 0x86, 0xEF, 0xB4, 0x31, 0x8A, \ 0xED, 0x6A, 0x1E, 0x01, 0x2D, 0x9E, 0x68, 0x32, \ 0xA9, 0x07, 0x60, 0x0A, 0x91, 0x81, 0x30, 0xC4, \ 0x6D, 0xC7, 0x78, 0xF9, 0x71, 0xAD, 0x00, 0x38, \ 0x09, 0x29, 0x99, 0xA3, 0x33, 0xCB, 0x8B, 0x7A, \ 0x1A, 0x1D, 0xB9, 0x3D, 0x71, 0x40, 0x00, 0x3C, \ 0x2A, 0x4E, 0xCE, 0xA9, 0xF9, 0x8D, 0x0A, 0xCC, \ 0x0A, 0x82, 0x91, 0xCD, 0xCE, 0xC9, 0x7D, 0xCF, \ 0x8E, 0xC9, 0xB5, 0x5A, 0x7F, 0x88, 0xA4, 0x6B, \ 0x4D, 0xB5, 0xA8, 0x51, 0xF4, 0x41, 0x82, 0xE1, \ 0xC6, 0x8A, 0x00, 0x7E, 0x5E, 0x0D, 0xD9, 0x02, \ 0x0B, 0xFD, 0x64, 0xB6, 0x45, 0x03, 0x6C, 0x7A, \ 0x4E, 0x67, 0x7D, 0x2C, 0x38, 0x53, 0x2A, 0x3A, \ 0x23, 0xBA, 0x44, 0x42, 0xCA, 0xF5, 0x3E, 0xA6, \ 0x3B, 0xB4, 0x54, 0x32, 0x9B, 0x76, 0x24, 0xC8, \ 0x91, 0x7B, 0xDD, 0x64, 0xB1, 0xC0, 0xFD, 0x4C, \ 0xB3, 0x8E, 0x8C, 0x33, 0x4C, 0x70, 0x1C, 0x3A, \ 0xCD, 0xAD, 0x06, 0x57, 0xFC, 0xCF, 0xEC, 0x71, \ 0x9B, 0x1F, 0x5C, 0x3E, 0x4E, 0x46, 0x04, 0x1F, \ 0x38, 0x81, 0x47, 0xFB, 0x4C, 0xFD, 0xB4, 0x77, \ 0xA5, 0x24, 0x71, 0xF7, 0xA9, 0xA9, 0x69, 0x10, \ 0xB8, 0x55, 0x32, 0x2E, 0xDB, 0x63, 0x40, 0xD8, \ 0xA0, 0x0E, 0xF0, 0x92, 0x35, 0x05, 0x11, 0xE3, \ 0x0A, 0xBE, 0xC1, 0xFF, 0xF9, 0xE3, 0xA2, 0x6E, \ 0x7F, 0xB2, 0x9F, 0x8C, 0x18, 0x30, 0x23, 0xC3, \ 0x58, 0x7E, 0x38, 0xDA, 0x00, 0x77, 0xD9, 0xB4, \ 0x76, 0x3E, 0x4E, 0x4B, 0x94, 0xB2, 0xBB, 0xC1, \ 0x94, 0xC6, 0x65, 0x1E, 0x77, 0xCA, 0xF9, 0x92, \ 0xEE, 0xAA, 0xC0, 0x23, 0x2A, 0x28, 0x1B, 0xF6, \ 0xB3, 0xA7, 0x39, 0xC1, 0x22, 0x61, 0x16, 0x82, \ 0x0A, 0xE8, 0xDB, 0x58, 0x47, 0xA6, 0x7C, 0xBE, \ 0xF9, 0xC9, 0x09, 0x1B, 0x46, 0x2D, 0x53, 0x8C, \ 0xD7, 0x2B, 0x03, 0x74, 0x6A, 0xE7, 0x7F, 0x5E, \ 0x62, 0x29, 0x2C, 0x31, 0x15, 0x62, 0xA8, 0x46, \ 0x50, 0x5D, 0xC8, 0x2D, 0xB8, 0x54, 0x33, 0x8A, \ 0xE4, 0x9F, 0x52, 0x35, 0xC9, 0x5B, 0x91, 0x17, \ 0x8C, 0xCF, 0x2D, 0xD5, 0xCA, 0xCE, 0xF4, 0x03, \ 0xEC, 0x9D, 0x18, 0x10, 0xC6, 0x27, 0x2B, 0x04, \ 0x5B, 0x3B, 0x71, 0xF9, 0xDC, 0x6B, 0x80, 0xD6, \ 0x3F, 0xDD, 0x4A, 0x8E, 0x9A, 0xDB, 0x1E, 0x69, \ 0x62, 0xA6, 0x95, 0x26, 0xD4, 0x31, 0x61, 0xC1, \ 0xA4, 0x1D, 0x57, 0x0D, 0x79, 0x38, 0xDA, 0xD4, \ 0xA4, 0x0E, 0x32, 0x9C, 0xCF, 0xF4, 0x6A, 0xAA, \ 0x36, 0xAD, 0x00, 0x4C, 0xF6, 0x00, 0xC8, 0x38, \ 0x1E, 0x42, 0x5A, 0x31, 0xD9, 0x51, 0xAE, 0x64, \ 0xFD, 0xB2, 0x3F, 0xCE, 0xC9, 0x50, 0x9D, 0x43, \ 0x68, 0x7F, 0xEB, 0x69, 0xED, 0xD1, 0xCC, 0x5E, \ 0x0B, 0x8C, 0xC3, 0xBD, 0xF6, 0x4B, 0x10, 0xEF, \ 0x86, 0xB6, 0x31, 0x42, 0xA3, 0xAB, 0x88, 0x29, \ 0x55, 0x5B, 0x2F, 0x74, 0x7C, 0x93, 0x26, 0x65, \ 0xCB, 0x2C, 0x0F, 0x1C, 0xC0, 0x1B, 0xD7, 0x02, \ 0x29, 0x38, 0x88, 0x39, 0xD2, 0xAF, 0x05, 0xE4, \ 0x54, 0x50, 0x4A, 0xC7, 0x8B, 0x75, 0x82, 0x82, \ 0x28, 0x46, 0xC0, 0xBA, 0x35, 0xC3, 0x5F, 0x5C, \ 0x59, 0x16, 0x0C, 0xC0, 0x46, 0xFD, 0x82, 0x51, \ 0x54, 0x1F, 0xC6, 0x8C, 0x9C, 0x86, 0xB0, 0x22, \ 0xBB, 0x70, 0x99, 0x87, 0x6A, 0x46, 0x0E, 0x74, \ 0x51, 0xA8, 0xA9, 0x31, 0x09, 0x70, 0x3F, 0xEE, \ 0x1C, 0x21, 0x7E, 0x6C, 0x38, 0x26, 0xE5, 0x2C, \ 0x51, 0xAA, 0x69, 0x1E, 0x0E, 0x42, 0x3C, 0xFC, \ 0x99, 0xE9, 0xE3, 0x16, 0x50, 0xC1, 0x21, 0x7B, \ 0x62, 0x48, 0x16, 0xCD, 0xAD, 0x9A, 0x95, 0xF9, \ 0xD5, 0xB8, 0x01, 0x94, 0x88, 0xD9, 0xC0, 0xA0, \ 0xA1, 0xFE, 0x30, 0x75, 0xA5, 0x77, 0xE2, 0x31, \ 0x83, 0xF8, 0x1D, 0x4A, 0x3F, 0x2F, 0xA4, 0x57, \ 0x1E, 0xFC, 0x8C, 0xE0, 0xBA, 0x8A, 0x4F, 0xE8, \ 0xB6, 0x85, 0x5D, 0xFE, 0x72, 0xB0, 0xA6, 0x6E, \ 0xDE, 0xD2, 0xFB, 0xAB, 0xFB, 0xE5, 0x8A, 0x30, \ 0xFA, 0xFA, 0xBE, 0x1C, 0x5D, 0x71, 0xA8, 0x7E, \ 0x2F, 0x74, 0x1E, 0xF8, 0xC1, 0xFE, 0x86, 0xFE, \ 0xA6, 0xBB, 0xFD, 0xE5, 0x30, 0x67, 0x7F, 0x0D, \ 0x97, 0xD1, 0x1D, 0x49, 0xF7, 0xA8, 0x44, 0x3D, \ 0x08, 0x22, 0xE5, 0x06, 0xA9, 0xF4, 0x61, 0x4E, \ 0x01, 0x1E, 0x2A, 0x94, 0x83, 0x8F, 0xF8, 0x8C, \ 0xD6, 0x8C, 0x8B, 0xB7, 0xC5, 0xC6, 0x42, 0x4C, \ 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF, 0xFF } #define MBEDTLS_DHM_RFC7919_FFDHE8192_G_BIN { 0x02 } #endif /* dhm.h */