code
stringlengths
1
1.05M
repo_name
stringlengths
6
83
path
stringlengths
3
242
language
stringclasses
222 values
license
stringclasses
20 values
size
int64
1
1.05M
#!/usr/bin/env python # -*- coding: utf-8 -*- # This file is part of the openHiTLS project. # # openHiTLS is licensed under the Mulan PSL v2. # You can use this software according to the terms and conditions of the Mulan PSL v2. # You may obtain a copy of Mulan PSL v2 at: # # http://license.coscl.org.cn/MulanPSL2 # # THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, # EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, # MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. # See the Mulan PSL v2 for more details. """ Customize the openHiTLS build. Generate the modules.cmake file based on command line arguments and configuration files. Options usage and examples: 1 Enable the feature on demand and specify the implementation type of the feature, c or assembly. # Use 'enable' to specify the features to be constructed. # Compile C code if there is no other parameter. ./configure.py --enable all # Build all features of openHiTLS. ./configure.py --enable hitls_crypto # Build all features in the lib hitls_crypto. ./configure.py --enable md # Build all sub features of md. ./configure.py --enable sha2 sha3 hmac # Specifies to build certain features. # Use 'enable' to specify the features to be constructed. # Use 'asm_type' to specify the assembly type. # If there are features in enable list that supports assembly, compile its assembly implementation. ./configure.py --enable sm3 aes ... --asm_type armv8 # Use 'enable' to specify the features to be constructed. # Use 'asm_type' to specify the assembly type. # Use 'asm' to specify the assembly feature(s), which is(are) based on the enabled features. # Compile the assembly code of the features in the asm, and the C code of other features in the enable list. ./configure.py --enable sm3 aes ... --asm_type armv8 --asm sm3 2 Compile options: Add or delete compilation options based on the default compilation options (compile.json). ./configure.py --add_options "-O0 -g" --del_options "-O2 -D_FORTIFY_SOURCE=2" 3 Link options: Add or delete link options based on the default link options (compile.json). ./configure.py --add_link_flags "xxx xxx" --del_link_flags "xxx xxx" 4 Set the endian mode of the system. Set the endian mode of the system. The default value is little endian. ./configure.py --endian big 5 Specifies the system type. ./configure.py --system linux 6 Specifies the number of system bits. ./configure.py --bits 32 7 Generating modules.cmake ./configure.py -m 8 Specifies the directory where the compilation middleware is generated. The default directory is ./output. ./configure.py --build_dir build 9 Specifies the lib type. ./configure.py --lib_type static ./configure.py --lib_type static shared object 10 You can directly specify the compilation configuration files, omitting the above 1~9 command line parameters. For the file format, please refer to the compile_config.json and feature_config.json files generated after executing the above 1~9 commands. ./configure.py --feature_config path/to/xxx.json --compile_config path/to/xxx.json Note: Options for different functions can be combined. """ import sys sys.dont_write_bytecode = True import os import argparse import traceback import glob from script.methods import copy_file, save_json_file, trans2list from script.config_parser import (FeatureParser, CompileParser, FeatureConfigParser, CompileConfigParser, CompleteOptionParser) srcdir = os.path.dirname(os.path.realpath(sys.argv[0])) work_dir = os.path.abspath(os.getcwd()) def get_cfg_args(): parser = argparse.ArgumentParser(prog='openHiTLS', description='parser configure arguments') try: # Version/Release Build Configuration Parameters parser.add_argument('-m', '--module_cmake', action='store_true', help='generate moudules.cmake file') parser.add_argument('--build_dir', metavar='dir', type=str, default=os.path.join(srcdir, 'build'), help='compile temp directory') parser.add_argument('--output_dir', metavar='dir', type=str, default=os.path.join(srcdir, 'output'), help='compile output directory') parser.add_argument('--hkey', metavar='hkey', type=str, default="b8fc4931453af3285f0f", help='Key used by the HMAC.') # Configuration file parser.add_argument('--feature_config', metavar='file_path', type=str, default='', help='Configuration file of the compilation features.') parser.add_argument('--compile_config', metavar='file_path', type=str, default='', help='Configuration file of compilation parameters.') # Compilation Feature Configuration parser.add_argument('--enable', metavar='feature', nargs='+', default=[], help='enable some libs or features, such as --enable sha256 aes gcm_asm, default is "all"') parser.add_argument('--disable', metavar='feature', nargs='+', default=['uio_sctp'], help='disable some libs or features, such as --disable aes gcm_asm,\ default is disable "uio_sctp" ') parser.add_argument('--enable-sctp', action="store_true", help='enable sctp which is used in DTLS') parser.add_argument('--asm_type', type=str, help='Assembly Type, default is "no_asm".') parser.add_argument('--asm', metavar='feature', default=[], nargs='+', help='config asm, such as --asm sha2') # System Configuration parser.add_argument('--system', type=str, help='To enable feature "sal_xxx", should specify the system.') parser.add_argument('--endian', metavar='little|big', type=str, choices=['little', 'big'], help='Specify the platform endianness as little or big, default is "little".') parser.add_argument('--bits', metavar='32|64', type=int, choices=[32, 64], help='To enable feature "bn", should specify the number of OS bits, default is "64".') # Compiler Options, Link Options parser.add_argument('--lib_type', choices=['static', 'shared', 'object'], nargs='+', help='set lib type, such as --lib_type staic shared, default is "staic shared object"') parser.add_argument('--add_options', default='', type=str, help='add some compile options, such as --add_options="-O0 -g"') parser.add_argument('--del_options', default='', type=str, help='delete some compile options such as --del_options="-O2 -Werror"') parser.add_argument('--add_link_flags', default='', type=str, help='add some link flags such as --add_link_flags="-pie"') parser.add_argument('--del_link_flags', default='', type=str, help='delete some link flags such as --del_link_flags="-shared -Wl,-z,relro"') parser.add_argument('--no_config_check', action='store_true', help='disable the configuration check') parser.add_argument('--hitls_version', default='openHiTLS 0.2.0 15 May 2025', help='%(prog)s version str') parser.add_argument('--hitls_version_num', default=0x00200000, help='%(prog)s version num') parser.add_argument('--bundle_libs', action='store_true', help='Indicates that multiple libraries are bundled together. By default, it is not bound.\ It need to be used together with "-m"') # Compile the command apps. parser.add_argument('--executes', dest='executes', default=[], nargs='*', help='Enable hitls command apps') args = vars(parser.parse_args()) args['tmp_feature_config'] = os.path.join(args['build_dir'], 'feature_config.json') args['tmp_compile_config'] = os.path.join(args['build_dir'], 'compile_config.json') # disable uio_sctp by default if args['enable_sctp'] or args['module_cmake']: if 'uio_sctp' in args['disable']: args['disable'].remove('uio_sctp') except argparse.ArgumentError as e: parser.print_help() raise ValueError("Error: Failed to obtain parameters.") from e return argparse.Namespace(**args) class Configure: """Provides operations related to configuration and input parameter parsing: 1 Parse input parameters. 2 Read configuration files and input parameters. 3 Update the final configuration files in the build directory. """ config_json_file = 'config.json' feature_json_file = 'config/json/feature.json' complete_options_json_file = 'config/json/complete_options.json' default_compile_json_file = 'config/json/compile.json' def __init__(self, features: FeatureParser): self._features = features self._args = get_cfg_args() self._preprocess_args() @property def args(self): return self._args def _preprocess_args(self): if self._args.feature_config and not os.path.exists(self._args.feature_config): raise FileNotFoundError('File not found: %s' % self._args.feature_config) if self._args.compile_config and not os.path.exists(self._args.compile_config): raise FileNotFoundError('File not found: %s' % self._args.compile_config) if 'all' in self._args.enable: if len(self._args.enable) > 1: raise ValueError("Error: 'all' and other features cannot be set at the same time.") else: for fea in self._args.enable: if fea in self._features.libs or fea in self._features.feas_info: continue raise ValueError("unrecognized fea '%s'" % fea) if self._args.asm_type: if self._args.asm_type not in self._features.asm_types: raise ValueError("Unsupported asm_type: asm_type should be one of [%s]" % self._features.asm_types) else: if self._args.asm and not self._args.asm_type: raise ValueError("Error: 'asm_type' and 'asm' must be set at the same time.") # The value of 'asm' will be verified later. @staticmethod def _load_config(is_fea_cfg, src_file, dest_file): if os.path.exists(dest_file): if src_file != '': raise FileExistsError('{} already exists'.format(dest_file)) else: if src_file == '': # No custom configuration file is specified, create a default config file. cfg = FeatureConfigParser.default_cfg() if is_fea_cfg else CompileConfigParser.default_cfg() save_json_file(cfg, dest_file) else: copy_file(src_file, dest_file) def load_config_to_build(self): """Load the compilation feature and compilation option configuration files to the build directory: build/feature_config.json build/compile_config.json """ if not os.path.exists(self._args.build_dir): os.makedirs(self._args.build_dir) self._load_config(True, self._args.feature_config, self._args.tmp_feature_config) self._load_config(False, self._args.compile_config, self._args.tmp_compile_config) def update_feature_config(self, gen_cmake): """Update the feature configuration file in the build based on the input parameters.""" conf_custom_feature = FeatureConfigParser(self._features, self._args.tmp_feature_config) if self._args.executes: conf_custom_feature.enable_executes(self._args.executes) # If no feature is enabled before modules.cmake is generated, set enable to "all". if not conf_custom_feature.libs and not self._args.enable and gen_cmake: self._args.enable = ['all'] # Set parameters by referring to "FeatureConfigParser.key_value". conf_custom_feature.set_param('libType', self._args.lib_type) if self._args.bundle_libs: conf_custom_feature.set_param('bundleLibs', self._args.bundle_libs) conf_custom_feature.set_param('endian', self._args.endian) conf_custom_feature.set_param('system', self._args.system, False) conf_custom_feature.set_param('bits', self._args.bits, False) enable_feas, asm_feas = conf_custom_feature.get_enable_feas(self._args.enable, self._args.asm) asm_type = self._args.asm_type if self._args.asm_type else '' if not asm_type and conf_custom_feature.asm_type != 'no_asm': asm_type = conf_custom_feature.asm_type if asm_type: conf_custom_feature.set_asm_type(asm_type) conf_custom_feature.set_asm_features(enable_feas, asm_feas, asm_type) if enable_feas: conf_custom_feature.set_c_features(enable_feas) self._args.securec_lib = conf_custom_feature.securec_lib # update feature and resave file. conf_custom_feature.update_feature(self._args.enable, self._args.disable, gen_cmake) conf_custom_feature.save(self._args.tmp_feature_config) self._args.bundle_libs = conf_custom_feature.bundle_libs def update_compile_config(self, all_options: CompleteOptionParser): """Update the compilation configuration file in the build based on the input parameters.""" conf_custom_compile = CompileConfigParser(all_options, self._args.tmp_compile_config) if self._args.add_options: conf_custom_compile.change_options(self._args.add_options.strip().split(' '), True) if self._args.del_options: conf_custom_compile.change_options(self._args.del_options.strip().split(' '), False) if self._args.add_link_flags: conf_custom_compile.change_link_flags(self._args.add_link_flags.strip().split(' '), True) if self._args.del_link_flags: conf_custom_compile.change_link_flags(self._args.del_link_flags.strip().split(' '), False) conf_custom_compile.save(self._args.tmp_compile_config) class CMakeGenerator: """ Generating CMake Commands and Scripts Based on Configuration Files """ def __init__(self, args, features: FeatureParser, all_options: CompleteOptionParser): self._args = args self._cfg_feature = features self._cfg_compile = CompileParser(all_options, Configure.default_compile_json_file) self._cfg_custom_feature = FeatureConfigParser(features, args.tmp_feature_config) self._cfg_custom_feature.check_fea_opts() self._cfg_custom_compile = CompileConfigParser(all_options, args.tmp_compile_config) self._asm_type = self._cfg_custom_feature.asm_type self._platform = 'linux' self._approved_provider = False self._hmac = "sha256" @staticmethod def _add_if_exists(inc_dirs, path): if os.path.exists(path): inc_dirs.add(path) @staticmethod def _get_common_include(modules: list): """ modules: ['::','::']""" inc_dirs = set() top_modules = set(x.split('::')[0] for x in modules) top_modules.add('bsl/log') top_modules.add('bsl/err') for module in top_modules: CMakeGenerator._add_if_exists(inc_dirs, module + '/include') CMakeGenerator._add_if_exists(inc_dirs, 'include/' + module) CMakeGenerator._add_if_exists(inc_dirs, 'config/macro_config') CMakeGenerator._add_if_exists(inc_dirs, '../../../../Secure_C/include') CMakeGenerator._add_if_exists(inc_dirs, '../../../platform/Secure_C/include') return inc_dirs def _get_module_include(self, mod: str, dep_mods: list): inc_dirs = set() dep_mods.append(mod) for dep in dep_mods: top_dir, sub_dir = dep.split('::') path = "{}/{}/include".format(top_dir, sub_dir) if os.path.exists(path): inc_dirs.add(path) top_mod, sub_mod = dep.split('::') cfg_inc = self._cfg_feature.modules[top_mod][sub_mod].get('.include', []) for inc_dir in cfg_inc: if os.path.exists(inc_dir): inc_dirs.add(inc_dir) return inc_dirs @staticmethod def _expand_srcs(srcs): if not srcs: return [] ret = [] for x in srcs: ret += glob.glob(x, recursive=True) if len(ret) == 0: raise SystemError("The .c file does not exist in the {} directory.".format(srcs)) ret.sort() return ret @classmethod def _gen_cmd_cmake(cls, cmd: str, title, content_obj=None): if not content_obj: return '{}({})\n'.format(cmd, title) items = None if isinstance(content_obj, list) or isinstance(content_obj, set): items = content_obj elif isinstance(content_obj, dict): items = content_obj.values() elif isinstance(content_obj, str): items = [content_obj] else: raise ValueError('Unsupported type "%s"' % type(content_obj)) content = '' for item in items: content += ' {}\n'.format(item) if len(items) == 1: return '{}({} {})\n'.format(cmd, title, item) else: return '{}({}\n{})\n'.format(cmd, title, content) def _get_module_src_set(self, lib, top_mod, sub_mod, mod_obj): srcs = self._cfg_feature.get_mod_srcs(top_mod, sub_mod, mod_obj) return self._expand_srcs(srcs) def _gen_module_cmake(self, lib, mod, mod_obj, mods_cmake): top_mod, module_name = mod.split('::') inc_set = self._get_module_include(mod, mod_obj.get('deps', [])) src_list = self._get_module_src_set(lib, top_mod, module_name, mod_obj) tgt_name = module_name + '-objs' cmake = '\n# Add module {} \n'.format(module_name) cmake += self._gen_cmd_cmake('add_library', '{} OBJECT'.format(tgt_name)) cmake += self._gen_cmd_cmake('target_include_directories', '{} PRIVATE'.format(tgt_name), inc_set) cmake += self._gen_cmd_cmake('target_sources', '{} PRIVATE'.format(tgt_name), src_list) mods_cmake[tgt_name] = cmake def _gen_shared_lib_cmake(self, lib_name, tgt_obj_list, tgt_list, macros): tgt_name = lib_name + '-shared' properties = 'OUTPUT_NAME {}'.format(lib_name) cmake = '\n' cmake += self._gen_cmd_cmake('add_library', '{} SHARED'.format(tgt_name), tgt_obj_list) cmake += self._gen_cmd_cmake('target_link_options', '{} PRIVATE'.format(tgt_name), '${SHARED_LNK_FLAGS}') if os.path.exists('{}/platform/Secure_C/lib'.format(srcdir)): cmake += self._gen_cmd_cmake('target_link_directories', '{} PRIVATE'.format(tgt_name), '{}/platform/Secure_C/lib'.format(srcdir)) cmake += self._gen_cmd_cmake('set_target_properties', '{} PROPERTIES'.format(tgt_name), properties) cmake += 'install(TARGETS %s DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)\n' % tgt_name if (self._approved_provider): # Use the openssl command to generate an HMAC file. cmake += 'install(CODE "execute_process(COMMAND openssl dgst -hmac \\\"%s\\\" -%s -out lib%s.so.hmac lib%s.so)")\n' % (self._args.hkey, self._hmac, lib_name, lib_name) # Install the hmac file to the output directory. cmake += 'install(CODE "execute_process(COMMAND cp lib%s.so.hmac ${CMAKE_INSTALL_PREFIX}/lib/lib%s.so.hmac)")\n' % (lib_name, lib_name) if lib_name == 'hitls_bsl': for item in macros: if item == '-DHITLS_BSL_UIO' or item == '-DHITLS_BSL_UIO_SCTP': cmake += self._gen_cmd_cmake("target_link_directories", "hitls_bsl-shared PRIVATE " + "${CMAKE_SOURCE_DIR}/platform/Secure_C/lib") cmake += self._gen_cmd_cmake("target_link_libraries", "hitls_bsl-shared " + str(self._args.securec_lib)) if item == '-DHITLS_BSL_SAL_DL': cmake += self._gen_cmd_cmake("target_link_directories", "hitls_bsl-shared PRIVATE " + "${CMAKE_SOURCE_DIR}/platform/Secure_C/lib") cmake += self._gen_cmd_cmake("target_link_libraries", "hitls_bsl-shared dl " + str(self._args.securec_lib)) if lib_name == 'hitls_crypto': cmake += self._gen_cmd_cmake("target_link_directories", "hitls_crypto-shared PRIVATE " + "${CMAKE_SOURCE_DIR}/platform/Secure_C/lib") cmake += self._gen_cmd_cmake("target_link_libraries", "hitls_crypto-shared hitls_bsl-shared " + str(self._args.securec_lib)) if lib_name == 'hitls_tls': cmake += self._gen_cmd_cmake("target_link_directories", "hitls_tls-shared PRIVATE " + "${CMAKE_SOURCE_DIR}/platform/Secure_C/lib") cmake += self._gen_cmd_cmake("target_link_libraries", "hitls_tls-shared hitls_pki-shared hitls_crypto-shared hitls_bsl-shared " + str(self._args.securec_lib)) if lib_name == 'hitls_pki': cmake += self._gen_cmd_cmake("target_link_directories", "hitls_pki-shared PRIVATE " + "${CMAKE_SOURCE_DIR}/platform/Secure_C/lib") cmake += self._gen_cmd_cmake( "target_link_libraries", "hitls_pki-shared hitls_crypto-shared hitls_bsl-shared " + str(self._args.securec_lib)) if lib_name == 'hitls_auth': cmake += self._gen_cmd_cmake("target_link_directories", "hitls_auth-shared PRIVATE " + "${CMAKE_SOURCE_DIR}/platform/Secure_C/lib") cmake += self._gen_cmd_cmake( "target_link_libraries", "hitls_auth-shared hitls_crypto-shared hitls_bsl-shared " + str(self._args.securec_lib)) if self._approved_provider: cmake += self._gen_cmd_cmake("target_link_libraries", "hitls-shared m " + str(self._args.securec_lib)) tgt_list.append(tgt_name) return cmake def _gen_static_lib_cmake(self, lib_name, tgt_obj_list, tgt_list): tgt_name = lib_name + '-static' properties = 'OUTPUT_NAME {}'.format(lib_name) cmake = '\n' cmake += self._gen_cmd_cmake('add_library', '{} STATIC'.format(tgt_name), tgt_obj_list) cmake += self._gen_cmd_cmake('set_target_properties', '{} PROPERTIES'.format(tgt_name), properties) cmake += 'install(TARGETS %s DESTINATION ${CMAKE_INSTALL_PREFIX}/lib)\n' % tgt_name tgt_list.append(tgt_name) return cmake def _gen_obejct_lib_cmake(self, lib_name, tgt_obj_list, tgt_list): tgt_name = lib_name + '-object' properties = 'OUTPUT_NAME lib{}.o'.format(lib_name) cmake = '\n' cmake += self._gen_cmd_cmake('add_executable', tgt_name, tgt_obj_list) cmake += self._gen_cmd_cmake('target_link_options', '{} PRIVATE'.format(tgt_name), '${SHARED_LNK_FLAGS}') cmake += self._gen_cmd_cmake('set_target_properties', '{} PROPERTIES'.format(tgt_name), properties) cmake += 'install(TARGETS %s DESTINATION ${CMAKE_INSTALL_PREFIX}/obj)\n' % tgt_name tgt_list.append(tgt_name) return cmake def _get_definitions(self): ret = '"${CMAKE_C_FLAGS} -DOPENHITLS_VERSION_S=\'\\"%s\\"\' -DOPENHITLS_VERSION_I=%lu %s' % ( self._args.hitls_version, self._args.hitls_version_num, '-D__FILENAME__=\'\\"$(notdir $(subst .o,,$@))\\"\'') if self._approved_provider: icv_key = '-DCMVP_INTEGRITYKEY=\'\\"%s\\"\'' % self._args.hkey ret += ' %s' % icv_key ret += '"' return ret def _gen_lib_cmake(self, lib_name, inc_dirs, lib_obj, macros): lang = self._cfg_feature.libs[lib_name].get('lang', 'C') cmake = 'project({} {})\n\n'.format(lib_name, lang) cmake += self._gen_cmd_cmake('set', 'CMAKE_ASM_NASM_OBJECT_FORMAT elf64') cmake += self._gen_cmd_cmake('set', 'CMAKE_C_FLAGS', '${CC_ALL_OPTIONS}') cmake += self._gen_cmd_cmake('set', 'CMAKE_ASM_FLAGS', '${CC_ALL_OPTIONS}') cmake += self._gen_cmd_cmake('set', 'CMAKE_C_FLAGS', self._get_definitions()) cmake += self._gen_cmd_cmake('include_directories', '', inc_dirs) for _, mod_cmake in lib_obj['mods_cmake'].items(): cmake += mod_cmake tgt_obj_list = list('$<TARGET_OBJECTS:{}>'.format(x) for x in lib_obj['mods_cmake'].keys()) tgt_list = [] lib_type = self._cfg_custom_feature.lib_type if 'shared' in lib_type: cmake += self._gen_shared_lib_cmake(lib_name, tgt_obj_list, tgt_list, macros) if 'static' in lib_type: cmake += self._gen_static_lib_cmake(lib_name, tgt_obj_list, tgt_list) if 'object' in lib_type: cmake += self._gen_obejct_lib_cmake(lib_name, tgt_obj_list, tgt_list) lib_obj['cmake'] = cmake lib_obj['targets'] = tgt_list def _gen_exe_cmake(self, exe_name, inc_dirs, exe_obj): lang = self._cfg_feature.executes[exe_name].get('lang', 'C') definitions = '"${CMAKE_C_FLAGS} -DHITLS_VERSION=\'\\"%s\\"\' %s"' % ( self._args.hitls_version, '-D__FILENAME__=\'\\"$(notdir $(subst .o,,$@))\\"\'') cmake = 'project({} {})\n\n'.format(exe_name, lang) cmake += self._gen_cmd_cmake('set', 'CMAKE_C_FLAGS', '${CC_ALL_OPTIONS}') cmake += self._gen_cmd_cmake('set', 'CMAKE_C_FLAGS', definitions) cmake += self._gen_cmd_cmake('include_directories', '', inc_dirs) for _, mod_cmake in exe_obj['mods_cmake'].items(): cmake += mod_cmake tgt_obj_list = list('$<TARGET_OBJECTS:{}>'.format(x) for x in exe_obj['mods_cmake'].keys()) cmake += self._gen_cmd_cmake('add_executable', exe_name, tgt_obj_list) lib_type = self._cfg_custom_feature.lib_type if 'shared' in lib_type: cmake += self._gen_cmd_cmake('add_dependencies', exe_name, 'hitls_pki-shared hitls_crypto-shared hitls_bsl-shared') elif 'static' in lib_type: cmake += self._gen_cmd_cmake('add_dependencies', exe_name, 'hitls_pki-static hitls_crypto-static hitls_bsl-static') common_link_dir = [ '${CMAKE_CURRENT_LIST_DIR}', # libhitls_* '${CMAKE_SOURCE_DIR}/platform/Secure_C/lib', ] common_link_lib = [ 'hitls_pki', 'hitls_crypto', 'hitls_bsl', 'dl', 'pthread', 'm', str(self._args.securec_lib) ] cmake += self._gen_cmd_cmake('list', 'APPEND HITLS_APP_LINK_DIRS', common_link_dir) cmake += self._gen_cmd_cmake('list', 'APPEND HITLS_APP_LINK_LIBS', common_link_lib) cmake += self._gen_cmd_cmake('target_link_directories', '%s PRIVATE' % exe_name, '${HITLS_APP_LINK_DIRS}') cmake += self._gen_cmd_cmake('target_link_libraries', exe_name, '${HITLS_APP_LINK_LIBS}') cmake += self._gen_cmd_cmake('target_link_options', '{} PRIVATE'.format(exe_name), '${EXE_LNK_FLAGS}') cmake += 'install(TARGETS %s DESTINATION ${CMAKE_INSTALL_PREFIX})\n' % exe_name exe_obj['cmake'] = cmake exe_obj['targets'] = [exe_name] def _gen_bundled_lib_cmake(self, lib_name, inc_dirs, projects, macros): lang = 'C ASM' if 'mpa' in projects.keys(): lang += 'ASM_NASM' cmake = 'project({} {})\n\n'.format(lib_name, lang) cmake += self._gen_cmd_cmake('set', 'CMAKE_ASM_NASM_OBJECT_FORMAT elf64') cmake += self._gen_cmd_cmake('set', 'CMAKE_C_FLAGS', '${CC_ALL_OPTIONS}') cmake += self._gen_cmd_cmake('set', 'CMAKE_ASM_FLAGS', '${CC_ALL_OPTIONS}') cmake += self._gen_cmd_cmake('set', 'CMAKE_C_FLAGS', self._get_definitions()) cmake += self._gen_cmd_cmake('include_directories', '', inc_dirs) tgt_obj_list = [] for _, lib_obj in projects.items(): tgt_obj_list.extend(list('$<TARGET_OBJECTS:{}>'.format(x) for x in lib_obj['mods_cmake'].keys())) for _, mod_cmake in lib_obj['mods_cmake'].items(): cmake += mod_cmake tgt_list = [] lib_type = self._cfg_custom_feature.lib_type if 'shared' in lib_type: cmake += self._gen_shared_lib_cmake(lib_name, tgt_obj_list, tgt_list, macros) if 'static' in lib_type: cmake += self._gen_static_lib_cmake(lib_name, tgt_obj_list, tgt_list) if 'object' in lib_type: cmake += self._gen_obejct_lib_cmake(lib_name, tgt_obj_list, tgt_list) return {lib_name: {'cmake': cmake, 'targets': tgt_list}} def _gen_common_compile_c_flags(self): return self._gen_cmd_cmake('set', 'CMAKE_C_FLAGS', self._get_definitions()) def _gen_projects_cmake(self, macros): lib_enable_modules, exe_enable_modules = self._cfg_custom_feature.get_enable_modules() projects = {} all_inc_dirs = set() for lib, lib_obj in lib_enable_modules.items(): projects[lib] = {} projects[lib]['mods_cmake'] = {} inc_dirs = self._get_common_include(lib_obj.keys()) for mod, mod_obj in lib_obj.items(): self._gen_module_cmake(lib, mod, mod_obj, projects[lib]['mods_cmake']) if self._args.bundle_libs: all_inc_dirs = all_inc_dirs.union(inc_dirs) continue self._gen_lib_cmake(lib, inc_dirs, projects[lib], macros) if self._args.bundle_libs: # update projects projects = self._gen_bundled_lib_cmake('hitls', all_inc_dirs, projects, macros) for exe, exe_obj in exe_enable_modules.items(): projects[exe] = {} projects[exe]['mods_cmake'] = {} inc_dirs = self._get_common_include(exe_obj.keys()) for mod, mod_obj in exe_obj.items(): self._gen_module_cmake(exe, mod, mod_obj, projects[exe]['mods_cmake']) self._gen_exe_cmake(exe, inc_dirs, projects[exe]) return projects def _gen_target_cmake(self, lib_tgts): cmake = 'add_custom_target(openHiTLS)\n' cmake += self._gen_cmd_cmake('add_dependencies', 'openHiTLS', lib_tgts) return cmake def _gen_set_param_cmake(self, macro_file): compile_flags, link_flags = self._cfg_compile.union_options(self._cfg_custom_compile) macros = self._cfg_custom_feature.get_fea_macros() macros.sort() if self._args.no_config_check: macros.append('-DHITLS_NO_CONFIG_CHECK') if '-DHITLS_CRYPTO_CMVP_ISO19790' in compile_flags: self._approved_provider = True self._hmac = "sha256" elif '-DHITLS_CRYPTO_CMVP_SM' in compile_flags: self._approved_provider = True self._hmac = "sm3" compile_flags.extend(macros) hitls_macros = list(filter(lambda x: '-DHITLS' in x, compile_flags)) with open(macro_file, "w") as f: f.write(" ".join(hitls_macros)) f.close() self._cc_all_options = compile_flags compile_flags_str = '"{}"'.format(" ".join(compile_flags)) shared_link_flags = '{}'.format(" ".join(link_flags['SHARED']) + " " + " ".join(link_flags['PUBLIC'])) exe_link_flags = '{}'.format(" ".join(link_flags['EXE']) + " " + " ".join(link_flags['PUBLIC'])) cmake = self._gen_cmd_cmake('set', 'CC_ALL_OPTIONS', compile_flags_str) + "\n" cmake += self._gen_cmd_cmake('set', 'SHARED_LNK_FLAGS', shared_link_flags) + "\n" cmake += self._gen_cmd_cmake('set', 'EXE_LNK_FLAGS', exe_link_flags) + "\n" return cmake, macros def out_cmake(self, cmake_path, macro_file): self._cfg_custom_feature.check_bn_config() set_param_cmake, macros = self._gen_set_param_cmake(macro_file) set_param_cmake += self._gen_common_compile_c_flags() projects = self._gen_projects_cmake(macros) lib_tgts = list(tgt for lib_obj in projects.values() for tgt in lib_obj['targets']) bottom_cmake = self._gen_target_cmake(lib_tgts) with open(cmake_path, "w") as f: f.write(set_param_cmake) for lib_obj in projects.values(): f.write(lib_obj['cmake']) f.write('\n\n') f.write(bottom_cmake) def main(): os.chdir(srcdir) # The Python version cannot be earlier than 3.5. if sys.version_info < (3, 5): print("your python version %d.%d should not be lower than 3.5" % tuple(sys.version_info[:2])) raise Exception("your python version %d.%d should not be lower than 3.5" % tuple(sys.version_info[:2])) conf_feature = FeatureParser(Configure.feature_json_file) complete_options = CompleteOptionParser(Configure.complete_options_json_file) cfg = Configure(conf_feature) cfg.load_config_to_build() cfg.update_feature_config(cfg.args.module_cmake) cfg.update_compile_config(complete_options) if cfg.args.module_cmake: tmp_cmake = os.path.join(cfg.args.build_dir, 'modules.cmake') macro_file = os.path.join(cfg.args.build_dir, 'macro.txt') if (os.path.exists(macro_file)): os.remove(macro_file) CMakeGenerator(cfg.args, conf_feature, complete_options).out_cmake(tmp_cmake, macro_file) if __name__ == '__main__': try: main() except SystemExit: exit(0) except: traceback.print_exc() exit(2)
2302_82127028/openHiTLS-examples_1556
configure.py
Python
unknown
33,691
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_AES_H #define CRYPT_AES_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_AES #include <stdint.h> #ifdef __cplusplus extern "C" { #endif // __cplusplus #define CRYPT_AES_128 128 #define CRYPT_AES_192 192 #define CRYPT_AES_256 256 #define CRYPT_AES_MAX_ROUNDS 14 #define CRYPT_AES_MAX_KEYLEN (4 * (CRYPT_AES_MAX_ROUNDS + 1)) /** * @ingroup CRYPT_AES_Key * * aes key structure */ typedef struct { uint32_t key[CRYPT_AES_MAX_KEYLEN]; uint32_t rounds; } CRYPT_AES_Key; /** * @ingroup aes * @brief Set the AES encryption key. * * @param ctx [IN] AES handle * @param key [IN] Encryption key * @param len [IN] Key length. The value must be 16 bytes. */ int32_t CRYPT_AES_SetEncryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len); /** * @ingroup aes * @brief Set the AES encryption key. * * @param ctx [IN] AES handle * @param key [IN] Encryption key * @param len [IN] Key length. The value must be 24 bytes. */ int32_t CRYPT_AES_SetEncryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len); /** * @ingroup aes * @brief Set the AES encryption key. * * @param ctx [IN] AES handle * @param key [IN] Encryption key * @param len [IN] Key length. The value must be 32 bytes. */ int32_t CRYPT_AES_SetEncryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len); /** * @ingroup aes * @brief Set the AES decryption key. * * @param ctx [IN] AES handle * @param key [IN] Decryption key * @param len [IN] Key length. The value must be 16 bytes. */ int32_t CRYPT_AES_SetDecryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len); /** * @ingroup aes * @brief Set the AES decryption key. * * @param ctx [IN] AES handle * @param key [IN] Decryption key * @param len [IN] Key length. The value must be 24 bytes. */ int32_t CRYPT_AES_SetDecryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len); /** * @ingroup aes * @brief Set the AES decryption key. * * @param ctx [IN] AES handle * @param key [IN] Decryption key * @param len [IN] Key length. The value must be 32 bytes. */ int32_t CRYPT_AES_SetDecryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len); /** * @ingroup aes * @brief AES encryption * * @param ctx [IN] AES handle, storing keys * @param in [IN] Input plaintext data. The value must be 16 bytes. * @param out [OUT] Output ciphertext data. The length is 16 bytes. * @param len [IN] Block length. */ int32_t CRYPT_AES_Encrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len); /** * @ingroup aes * @brief AES decryption * * @param ctx [IN] AES handle, storing keys * @param in [IN] Input ciphertext data. The value must be 16 bytes. * @param out [OUT] Output plaintext data. The length is 16 bytes. * @param len [IN] Block length. The length is 16. */ int32_t CRYPT_AES_Decrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len); #ifdef HITLS_CRYPTO_CBC /** * @ingroup aes * @brief AES cbc encryption * * @param ctx [IN] AES handle, storing keys * @param in [IN] Input plaintext data, 16 bytes. * @param out [OUT] Output ciphertext data. The length is 16 bytes. * @param len [IN] Block length. * @param iv [IN] Initialization vector. */ int32_t CRYPT_AES_CBC_Encrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv); /** * @ingroup aes * @brief AES cbc decryption * * @param ctx [IN] AES handle, storing keys * @param in [IN] Input ciphertext data. The value is 16 bytes. * @param out [OUT] Output plaintext data. The length is 16 bytes. * @param len [IN] Block length. * @param iv [IN] Initialization vector. */ int32_t CRYPT_AES_CBC_Decrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv); #endif /* HITLS_CRYPTO_CBC */ #if defined(HITLS_CRYPTO_CTR) || defined(HITLS_CRYPTO_GCM) /** * @ingroup aes * @brief AES ctr encryption * * @param ctx [IN] AES handle, storing keys * @param in [IN] Input plaintext data, 16 bytes. * @param out [OUT] Output ciphertext data. The length is 16 bytes. * @param len [IN] Block length. * @param iv [IN] Initialization vector. */ int32_t CRYPT_AES_CTR_Encrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv); #endif #ifdef HITLS_CRYPTO_ECB /** * @ingroup aes * @brief AES ecb encryption * * @param ctx [IN] AES handle, storing keys * @param in [IN] Input plaintext data. The length is a multiple of 16 bytes. * @param out [OUT] Output ciphertext data. The length is a multiple of 16 bytes. * @param len [IN] Block length. */ int32_t CRYPT_AES_ECB_Encrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len); /** * @ingroup aes * @brief AES ecb decryption * * @param ctx [IN] AES handle, storing keys * @param in [IN] Input ciphertext data. The value is 16 bytes. * @param out [OUT] Output plaintext data. The length is 16 bytes. * @param len [IN] Block length. */ int32_t CRYPT_AES_ECB_Decrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len); #endif #ifdef HITLS_CRYPTO_CFB /** * @brief Decryption in CFB mode * * @param ctx [IN] Mode handle * @param in [IN] Data to be encrypted * @param out [OUT] Encrypted data * @param len [IN] Data length * @param iv [IN] Initial vector * @return Success response: CRYPT_SUCCESS * Returned upon failure: Other error codes. */ int32_t CRYPT_AES_CFB_Decrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len, uint8_t *iv); #endif #ifdef HITLS_CRYPTO_XTS /** * @ingroup aes * @brief AES xts encryption * * @param ctx [IN] AES key * @param in [IN] Input plaintext. * @param out [OUT] Output ciphertext. * @param len [IN] Input length. The length is guaraenteed to be greater than block-size. * @param tweak [IN/OUT] XTS tweak. */ int32_t CRYPT_AES_XTS_Encrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len, const uint8_t *tweak); /** * @ingroup aes * @brief AES xts decryption * * @param ctx [IN] AES handle, storing keys * @param in [IN] Input ciphertext data. The value is 16 bytes. * @param out [OUT] Output plaintext data. The length is 16 bytes. * @param len [IN] Block length. * @param t [IN/OUT] XTS tweak. */ int32_t CRYPT_AES_XTS_Decrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len, const uint8_t *t); #endif /** * @ingroup aes * @brief Delete the AES key information. * * @param ctx [IN] AES handle, storing keys * @return void */ void CRYPT_AES_Clean(CRYPT_AES_Key *ctx); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_AES #endif // CRYPT_AES_H
2302_82127028/openHiTLS-examples_1556
crypto/aes/include/crypt_aes.h
C
unknown
7,250
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_AES #include "crypt_arm.h" #include "crypt_aes_macro_armv8.s" .file "crypt_aes_armv8.S" .text .arch armv8-a+crypto KEY .req x0 IN .req x1 OUT .req x2 ROUNDS .req w6 RDK0 .req v17 RDK1 .req v18 .section .rodata .align 5 .g_cron: .long 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36 .align 5 /* * In Return-oriented programming (ROP) and Jump-oriented programming (JOP), we explored features * that Arm introduced to the Arm architecture to mitigate against JOP-style and ROP-style attacks. * ... * Whether the combined or NOP-compatible instructions are set depends on the architecture * version that the code is built for. When building for Armv8.3-A, or later, the compiler will use * the combined operations. When building for Armv8.2-A, or earlier, it will use the NOP compatible * instructions. * * The paciasp and autiasp instructions are used for function pointer authentication. * The pointer authentication feature is added in armv8.3 and is supported only by AArch64. * The addition of pointer authentication features is described in Section A2.6.1 of * DDI0487H_a_a-profile_architecture_reference_manual.pdf. */ /* * int32_t CRYPT_AES_Encrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, * uint8_t *out, * uint32_t len); */ .text .globl CRYPT_AES_Encrypt .type CRYPT_AES_Encrypt, %function .align 5 CRYPT_AES_Encrypt: .ecb_aesenc_start: AARCH64_PACIASP stp x29, x30, [sp, #-16]! add x29, sp, #0 ld1 {BLK0.16b}, [IN] AES_ENC_1_BLK KEY BLK0.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b}, [OUT] eor x0, x0, x0 eor RDK0.16b, RDK0.16b, RDK0.16b eor RDK1.16b, RDK1.16b, RDK1.16b ldp x29, x30, [sp], #16 AARCH64_AUTIASP ret .size CRYPT_AES_Encrypt, .-CRYPT_AES_Encrypt /* * int32_t CRYPT_AES_Decrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, * uint8_t *out, * uint32_t len); */ .globl CRYPT_AES_Decrypt .type CRYPT_AES_Decrypt, %function .align 5 CRYPT_AES_Decrypt: .ecb_aesdec_start: AARCH64_PACIASP stp x29, x30, [sp, #-16]! add x29, sp, #0 ld1 {BLK0.16b}, [IN] AES_DEC_1_BLK KEY BLK0.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b}, [OUT] eor x0, x0, x0 eor RDK0.16b, RDK0.16b, RDK0.16b eor RDK1.16b, RDK1.16b, RDK1.16b ldp x29, x30, [sp], #16 AARCH64_AUTIASP ret .size CRYPT_AES_Decrypt, .-CRYPT_AES_Decrypt /* * void SetEncryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key); * Generating extended keys. * x0 => CRYPT_AES_Key *ctx; x1 => const uint8_t *key */ .globl SetEncryptKey128 .type SetEncryptKey128, %function .align 5 SetEncryptKey128: .Lenc_key_128: AARCH64_PACIASP stp x29, x30, [sp, #-64]! add x29, sp, #0 stp x25, x26, [sp, #16] stp x23, x24, [sp, #32] stp x21, x22, [sp, #48] // Register push stack completed. adrp x23, .g_cron add x23, x23, :lo12:.g_cron // Round key start address. mov x24, x0 // Copy key string address. The address increases by 16 bytes. ld1 {v1.16b}, [x1] // Reads the 16-byte key of a user. mov w26, #10 // Number of encryption rounds, which is filled // with rounds in the structure. st1 {v1.4s}, [x0], #16 // Save the first key. eor v0.16b, v0.16b, v0.16b // Clear zeros in V0. mov w25, #10 // loop for 10 times. .Lenc_key_128_loop: ldr w21, [x23], #4 // Obtains the round constant. dup v1.4s, v1.s[3] // Repeated four times,The last word of v1 is changed to v1 (128 bits). ld1 {v2.4s}, [x24], #16 // Obtains the 4 words used for XOR. ext v1.16b, v1.16b, v1.16b, #1 // Byte loop. dup v3.4s, w21 // Repeat four times to change w21 to v3 (128 bits). aese v1.16b, v0.16b // Xor then shift then sbox (XOR operation with 0 is itself, // equivalent to omitting the XOR operation). subs w25, w25, #1 // Count of 10-round key extension. eor v1.16b, v1.16b, v3.16b // Round constant XOR. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (1). ext v2.16b, v0.16b, v2.16b, #12 // 4321->3210. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (2). ext v2.16b, v0.16b, v2.16b, #12 // 3210->2100. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (3). ext v2.16b, v0.16b, v2.16b, #12 // 2100->1000. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (4). st1 {v1.4s}, [x0], #16 // Stores the newly calculated 4-bytes key data into the key string. b.ne .Lenc_key_128_loop // Loop jump. str w26, [x0, #64] // Fill in the number of rounds. eor x24, x24, x24 // Clear sensitivity. eor x0, x0, x0 ldp x21, x22, [sp, #48] ldp x23, x24, [sp, #32] ldp x25, x26, [sp, #16] ldp x29, x30, [sp], #64 // Pop stack completed. AARCH64_AUTIASP ret .size SetEncryptKey128, .-SetEncryptKey128 /* * void SetDecryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key); * Set a decryption key string. * x0 => CRYPT_AES_Key *ctx; x1 => const uint8_t *key */ .globl SetDecryptKey128 .type SetDecryptKey128, %function .align 5 SetDecryptKey128: AARCH64_PACIASP stp x29, x30, [sp, #-0x40]! add x29, sp, #0 stp x25, x28, [sp, #0x10] // Register push stack completed. stp d8, d9, [sp, #0x20] stp d10, d11, [sp, #0x30] mov x28, x0 bl .Lenc_key_128 ld1 {v0.4s}, [x28], #16 SETDECKEY_LDR_9_BLOCK x28 ld1 {v10.4s}, [x28] mov x25, #-16 SETDECKEY_INVMIX_9_BLOCK st1 {v0.4s}, [x28], x25 SETDECKEY_STR_9_BLOCK x28, x25 st1 {v10.4s}, [x28] eor x28, x28, x28 eor x0, x0, x0 ldp d10, d11, [sp, #0x30] ldp d8, d9, [sp, #0x20] ldp x25, x28, [sp, #0x10] ldp x29, x30, [sp], #0x40 // Stacking completed. AARCH64_AUTIASP ret .size SetDecryptKey128, .-SetDecryptKey128 /* * void SetEncryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key); * Generating extended keys. * x0 => CRYPT_AES_Key *ctx; x1 => const uint8_t *key */ .globl SetEncryptKey192 .type SetEncryptKey192, %function .align 5 SetEncryptKey192: .Lenc_key_192: AARCH64_PACIASP stp x29, x30, [sp, #-64]! add x29, sp, #0 stp x25, x26, [sp, #16] stp x23, x24, [sp, #32] stp x21, x22, [sp, #48] // Register push stack completed. mov x24, x0 // Copy key string address. The address increases by 16 bytes. ld1 {v0.16b}, [x1], #16 // Obtain the first 128-bit key. mov w26, #12 // Number of encryption rounds. st1 {v0.4s}, [x0], #16 // Store the first 128-bit key. ld1 {v1.8b}, [x1] // Obtains the last 64-bit key. adrp x23, .g_cron add x23, x23, :lo12:.g_cron // Round key start address. st1 {v1.2s}, [x0], #8 // Store the last 64-bit key. eor v0.16b, v0.16b, v0.16b // Clear zeros in V0. mov w25, #8 // loop for 8 times. .Lenc_key_192_loop: dup v1.4s, v1.s[1] // Repeated four times,The last word of v1 is changed to v1 (128 bits). subs w25, w25, #1 // Count of 8-round key extensions. ext v1.16b, v1.16b, v1.16b, #1 // Byte cycle. ldr w22, [x23], #4 // Obtains the round constant. aese v1.16b, v0.16b // Shift and sbox (XOR operation with 0 is itself,equivalent to omitting the XOR operation). dup v2.4s, w22 // Repeat 4 times. W22 becomes v2(128bit). eor v1.16b, v1.16b, v2.16b // Round constant XOR. ld1 {v2.4s}, [x24], #16 // Obtains the 4 words used for XOR eor v1.16b, v1.16b, v2.16b // 4 XOR operation (1). ext v2.16b, v0.16b, v2.16b, #12 // 4321->3210. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (2). ext v2.16b, v0.16b, v2.16b, #12 // 3210->2100. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (3). ext v2.16b, v0.16b, v2.16b, #12 // 2100->1000. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (4). st1 {v1.4s}, [x0], #16 // Stores the newly calculated 4-word key data into the key string. ld1 {v2.2s}, [x24], #8 // Loads 6 words for the last 2 words of XOR. dup v1.2s, v1.s[3] // Repeated two times,The last word of v1 is changed to v1 (64bit). eor v1.8b, v1.8b, v2.8b // 2 XOR operation (1). ext v2.8b, v0.8b, v2.8b, #4 // 21->10. eor v1.8b, v1.8b, v2.8b // 2 XOR operation (2). st1 {v1.2s}, [x0], #8 // Stores the newly calculated 2-word key data into the key string. b.ne .Lenc_key_192_loop // Loop jump. str w26, [x0, #24] // Fill in the number of rounds. eor x24, x24, x24 // Clear sensitivity. eor x0, x0, x0 ldp x21, x22, [sp, #48] ldp x23, x24, [sp, #32] ldp x25, x26, [sp, #16] ldp x29, x30, [sp], #64 // Stacking completed. AARCH64_AUTIASP ret .size SetEncryptKey192, .-SetEncryptKey192 /* * void SetDecryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key); * Set a decryption key string. * x0 => CRYPT_AES_Key *ctx; x1 => const uint8_t *key */ .globl SetDecryptKey192 .type SetDecryptKey192, %function .align 5 SetDecryptKey192: AARCH64_PACIASP stp x29, x30, [sp, #-0x50]! add x29, sp, #0 stp x25, x28, [sp, #0x10] // Register is stacked. stp d8, d9, [sp, #0x20] // Register is stacked. stp d10, d11, [sp, #0x30] // Register is stacked. stp d12, d13, [sp, #0x40] // Register is stacked. mov x28, x0 bl .Lenc_key_192 mov x25, #-16 ld1 {v0.4s}, [x28], #16 SETDECKEY_LDR_9_BLOCK x28 ld1 {v10.4s}, [x28], #16 ld1 {v11.4s}, [x28], #16 ld1 {v12.4s}, [x28] SETDECKEY_INVMIX_9_BLOCK aesimc v10.16b, v10.16b aesimc v11.16b, v11.16b st1 {v0.4s}, [x28], x25 SETDECKEY_STR_9_BLOCK x28, x25 st1 {v10.4s}, [x28], x25 st1 {v11.4s}, [x28], x25 st1 {v12.4s}, [x28] eor x28, x28, x28 eor x0, x0, x0 ldp d12, d13, [sp, #0x40] ldp d10, d11, [sp, #0x30] ldp d8, d9, [sp, #0x20] ldp x25, x28, [sp, #0x10] ldp x29, x30, [sp], #0x50 // Stacking completed. AARCH64_AUTIASP ret .size SetDecryptKey192, .-SetDecryptKey192 /* * void SetEncryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key); * Generating extended keys. * x0 => CRYPT_AES_Key *ctx; x1 => const uint8_t *key */ .globl SetEncryptKey256 .type SetEncryptKey256, %function .align 5 SetEncryptKey256: .Lenc_key_256: AARCH64_PACIASP stp x29, x30, [sp, #-64]! add x29, sp, #0 stp x25, x26, [sp, #16] stp x23, x24, [sp, #32] stp x21, x22, [sp, #48] // Register is stacked. adrp x23, .g_cron add x23, x23, :lo12:.g_cron // Round key start address. ld1 {v0.16b}, [x1], #16 // Obtain the first 128-bit key. mov x24, x0 // Copy key string address. The address increases by 16 bytes. st1 {v0.4s}, [x0], #16 // Store the first 128-bit key. ld1 {v1.16b}, [x1] // Obtain the last 128-bit key. eor v0.16b, v0.16b, v0.16b // Clear zeros in V0. st1 {v1.4s}, [x0], #16 // Store the last 128-bit key. mov w26, #14 // Number of encryption rounds. mov w25, #6 // Loop for 7-1 times. .Lenc_key_256_loop: dup v1.4s, v1.s[3] // Repeated four times,The last word of v1 is changed to v1 (128 bits). ldr w22, [x23], #4 // Obtains the round constant. ext v1.16b, v1.16b, v1.16b, #1 // Byte cycle. aese v1.16b, v0.16b // XOR then shift then sbox (XOR operation with 0 is itself, // equivalent to omitting the XOR operation). dup v2.4s, w22 // Repeat 4 times. w22 becomes v2. eor v1.16b, v1.16b, v2.16b // Round constant XOR. ld1 {v2.4s}, [x24], #16 // Obtains the 4 words used for XOR. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (1). ext v2.16b, v0.16b, v2.16b, #12 // 4321->3210. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (2). ext v2.16b, v0.16b, v2.16b, #12 // 3210->2100. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (3). ext v2.16b, v0.16b, v2.16b, #12 // 2100->1000. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (4). st1 {v1.4s}, [x0], #16 // Stores the newly calculated 4-word key data into the key string. subs w25, w25, #1 // Count of 7-1-round key extensions. dup v1.4s, v1.s[3] // Repeated four times,The last word of v1 is changed to v1 (128 bits). ld1 {v2.4s}, [x24], #16 // Obtains the 4 words used for XOR. aese v1.16b, v0.16b // XOR then shift then sbox. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (1). ext v2.16b, v0.16b, v2.16b, #12 // 4321->3210. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (2). ext v2.16b, v0.16b, v2.16b, #12 // 3210->2100. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (3). ext v2.16b, v0.16b, v2.16b, #12 // 2100->1000. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (4). st1 {v1.4s}, [x0], #16 // Stores the newly calculated 4-word key data into the key string. b.ne .Lenc_key_256_loop // Loop jump. dup v1.4s, v1.s[3] // Repeated four times,The last word of v1 is changed to v1 (128 bits). ldr w22, [x23], #4 // Obtains the round constant. ext v1.16b, v1.16b, v1.16b, #1 // Byte cycle. aese v1.16b, v0.16b // XOR then shift then sbox. dup v2.4s, w22 // Repeat 4 times. w22 becomes v2(128bit). eor v1.16b, v1.16b, v2.16b // Round constant XOR. ld1 {v2.4s}, [x24], #16 // Obtains the 4 words used for XOR. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (1). ext v2.16b, v0.16b, v2.16b, #12 // 4321->3210. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (2). ext v2.16b, v0.16b, v2.16b, #12 // 3210->2100. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (3). ext v2.16b, v0.16b, v2.16b, #12 // 2100->1000. eor v1.16b, v1.16b, v2.16b // 4 XOR operation (4). st1 {v1.4s}, [x0], #16 // Stores the newly calculated 4-word key data into the key string. str w26, [x0] // Fill in the number of rounds. eor x24, x24, x24 // Clear sensitivity. eor x0, x0, x0 ldp x21, x22, [sp, #48] ldp x23, x24, [sp, #32] ldp x25, x26, [sp, #16] ldp x29, x30, [sp], #64 // Stacking completed. AARCH64_AUTIASP ret .size SetEncryptKey256, .-SetEncryptKey256 /* * void SetDecryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key); * Set a decryption key string. * x0 => CRYPT_AES_Key *ctx; x1 => const uint8_t *key */ .globl SetDecryptKey256 .type SetDecryptKey256, %function .align 5 SetDecryptKey256: AARCH64_PACIASP stp x29, x30, [sp, #-0x60]! add x29, sp, #0 stp x25, x28, [sp, #0x10] stp d8, d9, [sp, #0x20] stp d10, d11, [sp, #0x30] stp d12, d13, [sp, #0x40] stp d14, d15, [sp, #0x50] mov x28, x0 bl .Lenc_key_256 mov x25, #-16 ld1 {v0.4s}, [x28], #16 SETDECKEY_LDR_9_BLOCK x28 ld1 {v10.4s}, [x28], #16 ld1 {v11.4s}, [x28], #16 ld1 {v12.4s}, [x28], #16 ld1 {v13.4s}, [x28], #16 ld1 {v14.4s}, [x28] SETDECKEY_INVMIX_9_BLOCK aesimc v10.16b, v10.16b aesimc v11.16b, v11.16b aesimc v12.16b, v12.16b aesimc v13.16b, v13.16b st1 {v0.4s}, [x28], x25 SETDECKEY_STR_9_BLOCK x28, x25 st1 {v10.4s}, [x28], x25 st1 {v11.4s}, [x28], x25 st1 {v12.4s}, [x28], x25 st1 {v13.4s}, [x28], x25 st1 {v14.4s}, [x28] eor x28, x28, x28 eor x0, x0, x0 ldp d14, d15, [sp, #0x50] ldp d12, d13, [sp, #0x40] ldp d10, d11, [sp, #0x30] ldp d8, d9, [sp, #0x20] ldp x25, x28, [sp, #0x10] ldp x29, x30, [sp], #0x60 // Stack has been popped. AARCH64_AUTIASP ret .size SetDecryptKey256, .-SetDecryptKey256 #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_armv8.S
Unix Assembly
unknown
17,570
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_CBC) #include "crypt_arm.h" #include "crypt_aes_macro_armv8.s" .file "crypt_aes_cbc_armv8.S" .text .arch armv8-a+crypto KEY .req x0 IN .req x1 OUT .req x2 LEN .req x3 P_IV .req x4 KTMP .req x5 ROUNDS .req w6 BLK0 .req v0 BLK1 .req v1 BLK2 .req v2 BLK3 .req v3 BLK4 .req v4 BLK5 .req v5 BLK6 .req v6 BLK7 .req v7 KEY0_END .req v16 KEY0 .req v17 KEY1 .req v18 KEY2 .req v19 KEY3 .req v20 KEY4 .req v21 KEY5 .req v22 KEY6 .req v23 KEY7 .req v24 KEY8 .req v25 KEY9 .req v26 KEY10 .req v27 KEY11 .req v28 KEY12 .req v29 KEY13 .req v30 KEY14 .req v31 IVENC .req v1 IV0 .req v17 IV1 .req v18 IV2 .req v19 IV3 .req v20 IV4 .req v21 IV5 .req v22 IV6 .req v23 IV7 .req v24 IVT .req v25 RDK0 .req v26 RDK1 .req v27 RDK2 .req v28 /* * One round of encryption process. * block:input the plaintext. * key: One round key. */ .macro ROUND block, key aese \block, \key aesmc \block, \block .endm /* * Eight blocks of decryption. * block0_7:Input the ciphertext. * rdk0: Round key. * ktmp: Temporarily stores pointers to keys. */ .macro DEC8 rdk0s rdk0 blk0 blk1 blk2 blk3 blk4 blk5 blk6 blk7 ktmp aesd \blk0, \rdk0 aesimc \blk0, \blk0 aesd \blk5, \rdk0 aesimc \blk5, \blk5 aesd \blk1, \rdk0 aesimc \blk1, \blk1 aesd \blk6, \rdk0 aesimc \blk6, \blk6 aesd \blk2, \rdk0 aesimc \blk2, \blk2 aesd \blk3, \rdk0 aesimc \blk3, \blk3 aesd \blk4, \rdk0 aesimc \blk4, \blk4 aesd \blk7, \rdk0 aesimc \blk7, \blk7 ld1 {\rdk0s}, [\ktmp], #16 .endm /** * Function description: AES encrypted assembly acceleration API in CBC mode. * int32_t CRYPT_AES_CBC_Encrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, * uint8_t *out, * uint32_t len, * uint8_t *iv); * Input register: * x0:Pointer to the input key structure * x1:points to the input data address * x2:points to the output data address * x3:Length of the input data, which must be a multiple of 16 * x4:Points to the CBC mode mask address * Change register:x5, x6, v0-v31 * Output register:x0 * Function/Macro Call: None */ .globl CRYPT_AES_CBC_Encrypt .type CRYPT_AES_CBC_Encrypt, %function CRYPT_AES_CBC_Encrypt: AARCH64_PACIASP ld1 {IVENC.16b}, [P_IV] // load IV ldr w6, [KEY, #240] // load rounds ld1 {BLK0.16b}, [IN], #16 // load in ld1 {KEY0.4s, KEY1.4s}, [KEY], #32 // load keys cmp w6, #12 ld1 {KEY2.4s, KEY3.4s}, [KEY], #32 ld1 {KEY4.4s, KEY5.4s}, [KEY], #32 ld1 {KEY6.4s, KEY7.4s}, [KEY], #32 ld1 {KEY8.4s, KEY9.4s}, [KEY], #32 eor IVENC.16b, IVENC.16b, BLK0.16b // iv + in b.lt .Laes_cbc_128_start ld1 {KEY10.4s, KEY11.4s}, [KEY], #32 b.eq .Laes_cbc_192_start ld1 {KEY12.4s, KEY13.4s}, [KEY], #32 .Laes_cbc_256_start: ld1 {KEY14.4s}, [KEY] ROUND IVENC.16b, KEY0.16b eor KEY0_END.16b, KEY0.16b, KEY14.16b // key0 + keyEnd b .Laes_cbc_256_round_loop .Laes_cbc_256_loop: ROUND IVENC.16b, KEY0.16b st1 {BLK0.16b}, [OUT], #16 .Laes_cbc_256_round_loop: ROUND IVENC.16b, KEY1.16b ROUND IVENC.16b, KEY2.16b subs LEN, LEN, #16 ROUND IVENC.16b, KEY3.16b ROUND IVENC.16b, KEY4.16b ROUND IVENC.16b, KEY5.16b ld1 {KEY0.16b}, [IN], #16 // load IN ROUND IVENC.16b, KEY6.16b ROUND IVENC.16b, KEY7.16b ROUND IVENC.16b, KEY8.16b ROUND IVENC.16b, KEY9.16b ROUND IVENC.16b, KEY10.16b ROUND IVENC.16b, KEY11.16b ROUND IVENC.16b, KEY12.16b aese IVENC.16b, KEY13.16b eor KEY0.16b, KEY0.16b, KEY0_END.16b // IN + KEY0 + KEYEND eor BLK0.16b, IVENC.16b, KEY14.16b b.gt .Laes_cbc_256_loop b .Lescbcenc_finish .Laes_cbc_128_start: ld1 {KEY10.4s}, [KEY] ROUND IVENC.16b, KEY0.16b eor KEY0_END.16b, KEY0.16b, KEY10.16b // key0 + keyEnd b .Laes_cbc_128_round_loop .Laes_cbc_128_loop: ROUND IVENC.16b, KEY0.16b st1 {BLK0.16b}, [OUT], #16 .Laes_cbc_128_round_loop: ROUND IVENC.16b, KEY1.16b ROUND IVENC.16b, KEY2.16b subs LEN, LEN, #16 ROUND IVENC.16b, KEY3.16b ROUND IVENC.16b, KEY4.16b ROUND IVENC.16b, KEY5.16b ld1 {KEY0.16b}, [IN], #16 // load IN ROUND IVENC.16b, KEY6.16b ROUND IVENC.16b, KEY7.16b ROUND IVENC.16b, KEY8.16b aese IVENC.16b, KEY9.16b eor KEY0.16b, KEY0.16b, KEY0_END.16b // IN + KEY0 + KEYEND eor BLK0.16b, IVENC.16b, KEY10.16b // enc OK b.gt .Laes_cbc_128_loop b .Lescbcenc_finish .Laes_cbc_192_start: ld1 {KEY12.4s}, [KEY] ROUND IVENC.16b, KEY0.16b eor KEY0_END.16b, KEY0.16b, KEY12.16b // key0 + keyEnd b .Laes_cbc_192_round_loop .Laes_cbc_192_loop: ROUND IVENC.16b, KEY0.16b st1 {BLK0.16b}, [OUT], #16 .Laes_cbc_192_round_loop: ROUND IVENC.16b, KEY1.16b ROUND IVENC.16b, KEY2.16b subs LEN, LEN, #16 ROUND IVENC.16b, KEY3.16b ROUND IVENC.16b, KEY4.16b ROUND IVENC.16b, KEY5.16b ld1 {KEY0.16b}, [IN], #16 // load IN ROUND IVENC.16b, KEY6.16b ROUND IVENC.16b, KEY7.16b ROUND IVENC.16b, KEY8.16b ROUND IVENC.16b, KEY9.16b ROUND IVENC.16b, KEY10.16b aese IVENC.16b, KEY11.16b eor KEY0.16b, KEY0.16b, KEY0_END.16b // IN + KEY0 + KEYEND eor BLK0.16b, IVENC.16b, KEY12.16b b.gt .Laes_cbc_192_loop .Lescbcenc_finish: st1 {BLK0.16b}, [OUT], #16 st1 {BLK0.16b}, [P_IV] mov x0, #0 AARCH64_AUTIASP ret .size CRYPT_AES_CBC_Encrypt, .-CRYPT_AES_CBC_Encrypt /** * Function description: AES decryption and assembly acceleration API in CBC mode. * int32_t CRYPT_AES_CBC_Decrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, * uint8_t *out, * uint32_t len, * uint8_t *iv); * Input register: * x0:pointer to the input key structure * x1:points to the input data address * x2:points to the output data address * x3:Length of the input data, which must be a multiple of 16 * x4:Points to the CBC mode mask address * Change register:x5, x6, v0-v31 * Output register:x0 * Function/Macro Call: AES_DEC_8_BLKS, AES_DEC_1_BLK, AES_DEC_2_BLKS, AES_DEC_3_BLKS, * AES_DEC_4_BLKS, AES_DEC_5_BLKS, AES_DEC_6_BLKS, AES_DEC_7_BLKS */ .globl CRYPT_AES_CBC_Decrypt .type CRYPT_AES_CBC_Decrypt, %function CRYPT_AES_CBC_Decrypt: AARCH64_PACIASP ld1 {IV0.16b}, [P_IV] .Lcbc_aesdec_start: cmp LEN, #64 b.ge .Lcbc_dec_above_equal_4_blks cmp LEN, #32 b.ge .Lcbc_dec_above_equal_2_blks cmp LEN, #0 b.eq .Lcbc_aesdec_finish b .Lcbc_dec_proc_1_blk .Lcbc_dec_above_equal_2_blks: cmp LEN, #48 b.lt .Lcbc_dec_proc_2_blks b .Lcbc_dec_proc_3_blks .Lcbc_dec_above_equal_4_blks: cmp LEN, #96 b.ge .Lcbc_dec_above_equal_6_blks cmp LEN, #80 b.lt .Lcbc_dec_proc_4_blks b .Lcbc_dec_proc_5_blks .Lcbc_dec_above_equal_6_blks: cmp LEN, #112 b.lt .Lcbc_dec_proc_6_blks cmp LEN, #128 b.lt .Lcbc_dec_proc_7_blks .align 4 .Lcbc_aesdec_8_blks_loop: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 mov KTMP, KEY ldr ROUNDS, [KEY, #240] ld1 {BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b}, [IN], #64 mov IV1.16b, BLK0.16b mov IV2.16b, BLK1.16b mov IV3.16b, BLK2.16b ld1 {RDK0.4s, RDK1.4s}, [KTMP], #32 mov IV4.16b, BLK3.16b mov IV5.16b, BLK4.16b mov IV6.16b, BLK5.16b mov IV7.16b, BLK6.16b mov IVT.16b, BLK7.16b DEC8 RDK0.4s, RDK0.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP DEC8 RDK1.4s, RDK1.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP DEC8 RDK0.4s, RDK0.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP DEC8 RDK1.4s, RDK1.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP DEC8 RDK0.4s, RDK0.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP DEC8 RDK1.4s, RDK1.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP DEC8 RDK0.4s, RDK0.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP DEC8 RDK1.4s, RDK1.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP cmp ROUNDS, #12 b.lt .Ldec_8_blks_last DEC8 RDK0.4s, RDK0.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP DEC8 RDK1.4s, RDK1.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP b.eq .Ldec_8_blks_last DEC8 RDK0.4s, RDK0.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP DEC8 RDK1.4s, RDK1.16b, BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b, BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b, KTMP .Ldec_8_blks_last: ld1 {RDK2.4s}, [KTMP] aesd BLK0.16b, RDK0.16b aesimc BLK0.16b, BLK0.16b aesd BLK1.16b, RDK0.16b aesimc BLK1.16b, BLK1.16b aesd BLK2.16b, RDK0.16b aesimc BLK2.16b, BLK2.16b eor IV0.16b, IV0.16b, RDK2.16b aesd BLK3.16b, RDK0.16b aesimc BLK3.16b, BLK3.16b eor IV1.16b, IV1.16b, RDK2.16b aesd BLK4.16b, RDK0.16b aesimc BLK4.16b, BLK4.16b eor IV2.16b, IV2.16b, RDK2.16b aesd BLK5.16b, RDK0.16b aesimc BLK5.16b, BLK5.16b eor IV3.16b, IV3.16b, RDK2.16b aesd BLK6.16b, RDK0.16b aesimc BLK6.16b, BLK6.16b eor IV4.16b, IV4.16b, RDK2.16b aesd BLK7.16b, RDK0.16b aesimc BLK7.16b, BLK7.16b eor IV5.16b, IV5.16b, RDK2.16b aesd BLK0.16b, RDK1.16b aesd BLK1.16b, RDK1.16b eor IV6.16b, IV6.16b, RDK2.16b aesd BLK2.16b, RDK1.16b aesd BLK3.16b, RDK1.16b eor IV7.16b, IV7.16b, RDK2.16b aesd BLK4.16b, RDK1.16b aesd BLK5.16b, RDK1.16b aesd BLK6.16b, RDK1.16b aesd BLK7.16b, RDK1.16b sub LEN, LEN, #128 eor BLK0.16b, BLK0.16b, IV0.16b eor BLK1.16b, BLK1.16b, IV1.16b eor BLK2.16b, BLK2.16b, IV2.16b eor BLK3.16b, BLK3.16b, IV3.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 eor BLK4.16b, BLK4.16b, IV4.16b eor BLK5.16b, BLK5.16b, IV5.16b cmp LEN, #0 eor BLK6.16b, BLK6.16b, IV6.16b eor BLK7.16b, BLK7.16b, IV7.16b mov IV0.16b, IVT.16b st1 {BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b}, [OUT], #64 b.eq .Lcbc_aesdec_finish cmp LEN, #128 b.lt .Lcbc_aesdec_start b .Lcbc_aesdec_8_blks_loop .Lcbc_dec_proc_1_blk: ld1 {BLK0.16b}, [IN] AES_DEC_1_BLK KEY BLK0.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS eor BLK0.16b, BLK0.16b, IV0.16b ld1 {IV0.16b}, [IN] st1 {BLK0.16b}, [OUT] b .Lcbc_aesdec_finish .Lcbc_dec_proc_2_blks: ld1 {BLK0.16b, BLK1.16b}, [IN] ld1 {IV1.16b}, [IN], #16 AES_DEC_2_BLKS KEY BLK0.16b BLK1.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS eor BLK0.16b, BLK0.16b, IV0.16b eor BLK1.16b, BLK1.16b, IV1.16b ld1 {IV0.16b}, [IN] st1 {BLK0.16b, BLK1.16b}, [OUT] b .Lcbc_aesdec_finish .Lcbc_dec_proc_3_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b}, [IN] ld1 {IV1.16b, IV2.16b}, [IN], #32 AES_DEC_3_BLKS KEY BLK0.16b BLK1.16b BLK2.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS eor BLK0.16b, BLK0.16b, IV0.16b eor BLK1.16b, BLK1.16b, IV1.16b eor BLK2.16b, BLK2.16b, IV2.16b ld1 {IV0.16b}, [IN] st1 {BLK0.16b, BLK1.16b, BLK2.16b}, [OUT] b .Lcbc_aesdec_finish .Lcbc_dec_proc_4_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN] ld1 {IV1.16b, IV2.16b, IV3.16b}, [IN], #48 AES_DEC_4_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS eor BLK0.16b, BLK0.16b, IV0.16b eor BLK1.16b, BLK1.16b, IV1.16b eor BLK2.16b, BLK2.16b, IV2.16b eor BLK3.16b, BLK3.16b, IV3.16b ld1 {IV0.16b}, [IN] st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT] b .Lcbc_aesdec_finish .Lcbc_dec_proc_5_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN] ld1 {IV1.16b, IV2.16b, IV3.16b, IV4.16b}, [IN], #64 ld1 {BLK4.16b}, [IN] AES_DEC_5_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS eor BLK0.16b, BLK0.16b, IV0.16b eor BLK1.16b, BLK1.16b, IV1.16b eor BLK2.16b, BLK2.16b, IV2.16b eor BLK3.16b, BLK3.16b, IV3.16b eor BLK4.16b, BLK4.16b, IV4.16b ld1 {IV0.16b}, [IN] st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b}, [OUT] b .Lcbc_aesdec_finish .Lcbc_dec_proc_6_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN] ld1 {IV1.16b, IV2.16b, IV3.16b, IV4.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b}, [IN] ld1 {IV5.16b}, [IN], #16 AES_DEC_6_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b BLK5.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS eor BLK0.16b, BLK0.16b, IV0.16b eor BLK1.16b, BLK1.16b, IV1.16b eor BLK2.16b, BLK2.16b, IV2.16b eor BLK3.16b, BLK3.16b, IV3.16b eor BLK4.16b, BLK4.16b, IV4.16b eor BLK5.16b, BLK5.16b, IV5.16b ld1 {IV0.16b}, [IN] st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b}, [OUT] b .Lcbc_aesdec_finish .Lcbc_dec_proc_7_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN] ld1 {IV1.16b, IV2.16b, IV3.16b, IV4.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b, BLK6.16b}, [IN] ld1 {IV5.16b, IV6.16b}, [IN], #32 AES_DEC_7_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b BLK5.16b BLK6.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS eor BLK0.16b, BLK0.16b, IV0.16b eor BLK1.16b, BLK1.16b, IV1.16b eor BLK2.16b, BLK2.16b, IV2.16b eor BLK3.16b, BLK3.16b, IV3.16b eor BLK4.16b, BLK4.16b, IV4.16b eor BLK5.16b, BLK5.16b, IV5.16b eor BLK6.16b, BLK6.16b, IV6.16b ld1 {IV0.16b}, [IN] st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b, BLK6.16b}, [OUT] .Lcbc_aesdec_finish: st1 {IV0.16b}, [P_IV] mov x0, #0 eor RDK0.16b, RDK0.16b, RDK0.16b eor RDK1.16b, RDK1.16b, RDK1.16b eor RDK2.16b, RDK2.16b, RDK2.16b AARCH64_AUTIASP ret .size CRYPT_AES_CBC_Decrypt, .-CRYPT_AES_CBC_Decrypt #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_cbc_armv8.S
Unix Assembly
unknown
15,260
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_CBC) #include "crypt_aes_macro_x86_64.s" .file "crypt_aes_cbc_x86_64.S" .text .set ARG1, %rdi .set ARG2, %rsi .set ARG3, %rdx .set ARG4, %ecx .set ARG5, %r8 .set ARG6, %r9 .set RDK, %xmm3 .set KEY, %rdi .set KTMP, %r9 .set ROUNDS, %eax .set RET, %eax .set BLK0, %xmm1 .set BLK1, %xmm4 .set BLK2, %xmm5 .set BLK3, %xmm6 .set BLK4, %xmm10 .set BLK5, %xmm11 .set BLK6, %xmm12 .set BLK7, %xmm13 .set IV0, %xmm0 .set IV1, %xmm7 .set IV2, %xmm8 .set IV3, %xmm9 .set KEY1, %xmm4 .set KEY2, %xmm5 .set KEY3, %xmm6 .set KEY4, %xmm10 .set KEY5, %xmm11 .set KEY6, %xmm12 .set KEY7, %xmm13 .set KEY8, %xmm14 .set KEY9, %xmm15 .set KEY10, %xmm2 .set KEY11, %xmm7 .set KEY12, %xmm8 .set KEY13, %xmm9 .set KEYTEMP, %xmm3 /** * Function description:AES encrypted assembly acceleration API in CBC mode. * Function prototype:int32_t CRYPT_AES_CBC_Encrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, * uint8_t *out, * uint32_t len, * uint8_t *iv); * Input register: * rdi:pointer to the input key structure * rsi:points to the input data address * rdx:points to the output data address * rcx:Length of the input data, which must be a multiple of 16 * r8: Points to the CBC mode mask address * Change register:xmm0-xmm15 * Output register:eax * Function/Macro Call: None */ .globl CRYPT_AES_CBC_Encrypt .type CRYPT_AES_CBC_Encrypt, @function CRYPT_AES_CBC_Encrypt: .cfi_startproc .align 16 cmpl $16, ARG4 jb .Laescbcend_end movl 240(KEY), ROUNDS vmovdqu (ARG5), IV0 vmovdqu (KEY), KEY1 vmovdqu 16(KEY), KEY2 vmovdqu 32(KEY), KEY3 vmovdqu 48(KEY), KEY4 vmovdqu 64(KEY), KEY5 vmovdqu 80(KEY), KEY6 vmovdqu 96(KEY), KEY7 vmovdqu 112(KEY), KEY8 vmovdqu 128(KEY), KEY9 vmovdqu 144(KEY), KEY10 vmovdqu 160(KEY), KEY11 cmpl $12, ROUNDS jb .Laes_128_cbc_start je .Laes_192_cbc_start .align 16 .Laes_256_cbc_start: vmovdqu 176(KEY), KEY12 vmovdqu 192(KEY), KEY13 .Laes_256_cbc_loop: vpxor (ARG2), IV0, BLK0 vmovdqu 208(KEY), KEYTEMP vpxor BLK0, KEY1, BLK0 aesenc KEY2, BLK0 aesenc KEY3, BLK0 aesenc KEY4, BLK0 aesenc KEY5, BLK0 aesenc KEY6, BLK0 aesenc KEY7, BLK0 aesenc KEY8, BLK0 aesenc KEY9, BLK0 aesenc KEY10, BLK0 aesenc KEY11, BLK0 aesenc KEY12, BLK0 aesenc KEY13, BLK0 aesenc KEYTEMP, BLK0 vmovdqu 224(KEY), KEYTEMP aesenclast KEYTEMP, BLK0 leaq 16(ARG2), ARG2 vmovdqu BLK0, (ARG3) movdqa BLK0, IV0 leaq 16(ARG3), ARG3 subl $16, ARG4 cmpl $16, ARG4 jnb .Laes_256_cbc_loop // Special value processing vpxor KEY12, KEY12, KEY12 vpxor KEY13, KEY13, KEY13 vpxor KEYTEMP, KEYTEMP, KEYTEMP jmp .Laescbcenc_finish .align 16 .Laes_192_cbc_start: vmovdqu 176(KEY), KEY12 vmovdqu 192(KEY), KEY13 .Laes_192_cbc_loop: vpxor (ARG2), IV0, BLK0 vpxor BLK0, KEY1, BLK0 aesenc KEY2, BLK0 aesenc KEY3, BLK0 aesenc KEY4, BLK0 aesenc KEY5, BLK0 aesenc KEY6, BLK0 aesenc KEY7, BLK0 aesenc KEY8, BLK0 aesenc KEY9, BLK0 aesenc KEY10, BLK0 aesenc KEY11, BLK0 aesenc KEY12, BLK0 aesenclast KEY13, BLK0 leaq 16(ARG2), ARG2 vmovdqu BLK0, (ARG3) movdqa BLK0, IV0 leaq 16(ARG3), ARG3 subl $16 , ARG4 jnz .Laes_192_cbc_loop vpxor KEY12, KEY12, KEY12 vpxor KEY13, KEY13, KEY13 jmp .Laescbcenc_finish .align 16 .Laes_128_cbc_start: vpxor (ARG2), IV0, BLK0 vpxor BLK0, KEY1, BLK0 aesenc KEY2, BLK0 aesenc KEY3, BLK0 aesenc KEY4, BLK0 aesenc KEY5, BLK0 aesenc KEY6, BLK0 aesenc KEY7, BLK0 aesenc KEY8, BLK0 aesenc KEY9, BLK0 aesenc KEY10, BLK0 aesenclast KEY11, BLK0 leaq 16(ARG2), ARG2 vmovdqu BLK0, (ARG3) movdqa BLK0, IV0 leaq 16(ARG3), ARG3 subl $16, ARG4 jnz .Laes_128_cbc_start jmp .Laescbcenc_finish .Laescbcenc_finish: vmovdqu BLK0,(ARG5) vpxor KEY1, KEY1, KEY1 vpxor KEY2, KEY2, KEY2 vpxor KEY3, KEY3, KEY3 vpxor KEY4, KEY4, KEY4 vpxor KEY5, KEY5, KEY5 vpxor KEY6, KEY6, KEY6 vpxor KEY7, KEY7, KEY7 vpxor KEY8, KEY8, KEY8 vpxor KEY9, KEY9, KEY9 vpxor KEY10, KEY10, KEY10 vpxor KEY11, KEY11, KEY11 .Laescbcend_end: movl $0, RET ret .cfi_endproc .size CRYPT_AES_CBC_Encrypt, .-CRYPT_AES_CBC_Encrypt /** * Function description: Sets the AES decryption and assembly accelerated implementation interface in CBC mode * Function prototype:int32_t CRYPT_AES_CBC_Decrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, * uint8_t *out, * uint32_t len, * uint8_t *iv); * Input register: * rdi:pointer to the input key structure * rsi:points to the input data address. * rdx:points to the output data address. * rcx:Length of the input data, which must be a multiple of 16 * r8: Points to the CBC mode mask address * Change register:xmm0-xmm13 * Output register:eax * Function/Macro Call: None */ .globl CRYPT_AES_CBC_Decrypt .type CRYPT_AES_CBC_Decrypt, @function CRYPT_AES_CBC_Decrypt: .cfi_startproc .align 16 vmovdqu (ARG5), IV0 .Laes_cbc_dec_start: cmpl $64, ARG4 jae .Labove_equal_4_blks cmpl $32, ARG4 jae .Labove_equal_2_blks cmpl $0, ARG4 je .Laes_cbc_dec_finish jmp .Lproc_1_blk .Labove_equal_2_blks: cmpl $48, ARG4 jb .Lproc_2_blks jmp .Lproc_3_blks .Labove_equal_4_blks: cmpl $96, ARG4 jae .Labove_equal_6_blks cmpl $80, ARG4 jb .Lproc_4_blks jmp .Lproc_5_blks .Labove_equal_6_blks: cmpl $112, ARG4 jb .Lproc_6_blks cmpl $128, ARG4 jb .Lproc_7_blks .align 16 .Lproc_8_blks: .Laescbcdec_8_blks_loop: vmovdqu (ARG2), BLK0 vmovdqu 16(ARG2), BLK1 vmovdqu 32(ARG2), BLK2 movdqa BLK0, IV1 movdqa BLK1, IV2 movdqa BLK2, IV3 movq KEY, KTMP movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor BLK0, RDK, BLK0 vpxor BLK1, RDK, BLK1 vpxor BLK2, RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 vpxor 96(ARG2), RDK, BLK6 vpxor 112(ARG2), RDK, BLK7 decl ROUNDS AES_DEC_8_BLKS KTMP ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 BLK6 BLK7 vpxor BLK0, IV0, BLK0 vpxor BLK1, IV1, BLK1 vpxor BLK2, IV2, BLK2 vpxor BLK3, IV3, BLK3 vpxor 48(ARG2), BLK4, BLK4 vpxor 64(ARG2), BLK5, BLK5 vpxor 80(ARG2), BLK6, BLK6 vpxor 96(ARG2), BLK7, BLK7 vmovdqu 112(ARG2), IV0 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) vmovdqu BLK6, 96(ARG3) vmovdqu BLK7, 112(ARG3) subl $128, ARG4 leaq 128(ARG2), ARG2 leaq 128(ARG3), ARG3 cmpl $128, ARG4 jb .Laes_cbc_dec_start jmp .Laescbcdec_8_blks_loop .align 16 .Lproc_1_blk: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 decl ROUNDS AES_DEC_1_BLK KEY ROUNDS RDK BLK0 vpxor BLK0, IV0, BLK0 vmovdqu (ARG2), IV0 vmovdqu BLK0, (ARG3) jmp .Laes_cbc_dec_finish .align 16 .Lproc_2_blks: vmovdqu (ARG2), BLK0 movl 240(KEY), ROUNDS vmovdqu (KEY), RDK movdqa BLK0, IV1 vpxor BLK0, RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 decl ROUNDS AES_DEC_2_BLKS KEY ROUNDS RDK BLK0 BLK1 vpxor BLK0, IV0, BLK0 vpxor BLK1, IV1, BLK1 vmovdqu 16(ARG2), IV0 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) jmp .Laes_cbc_dec_finish .align 16 .Lproc_3_blks: vmovdqu (ARG2), BLK0 vmovdqu 16(ARG2), BLK1 movl 240(KEY), ROUNDS vmovdqu (KEY), RDK movdqa BLK0, IV1 movdqa BLK1, IV2 vpxor BLK0, RDK, BLK0 vpxor BLK1, RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 decl ROUNDS AES_DEC_3_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 vpxor BLK0, IV0, BLK0 vpxor BLK1, IV1, BLK1 vpxor BLK2, IV2, BLK2 vmovdqu 32(ARG2), IV0 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) jmp .Laes_cbc_dec_finish .align 16 .Lproc_4_blks: vmovdqu (ARG2), BLK0 vmovdqu 16(ARG2), BLK1 vmovdqu 32(ARG2), BLK2 movl 240(KEY), ROUNDS vmovdqu (KEY), RDK movdqa BLK0, IV1 movdqa BLK1, IV2 movdqa BLK2, IV3 vpxor BLK0, RDK, BLK0 vpxor BLK1, RDK, BLK1 vpxor BLK2, RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 decl ROUNDS AES_DEC_4_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 vpxor BLK0, IV0, BLK0 vpxor BLK1, IV1, BLK1 vpxor BLK2, IV2, BLK2 vpxor BLK3, IV3, BLK3 vmovdqu 48(ARG2), IV0 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) jmp .Laes_cbc_dec_finish .align 16 .Lproc_5_blks: vmovdqu (ARG2), BLK0 vmovdqu 16(ARG2), BLK1 vmovdqu 32(ARG2), BLK2 movl 240(KEY), ROUNDS vmovdqu (KEY), RDK movdqa BLK0, IV1 movdqa BLK1, IV2 movdqa BLK2, IV3 vpxor BLK0, RDK, BLK0 vpxor BLK1, RDK, BLK1 vpxor BLK2, RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 decl ROUNDS AES_DEC_5_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 vpxor BLK0, IV0, BLK0 vpxor BLK1, IV1, BLK1 vpxor BLK2, IV2, BLK2 vpxor BLK3, IV3, BLK3 vpxor 48(ARG2), BLK4, BLK4 vmovdqu 64(ARG2), IV0 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) jmp .Laes_cbc_dec_finish .align 16 .Lproc_6_blks: vmovdqu (ARG2), BLK0 vmovdqu 16(ARG2), BLK1 vmovdqu 32(ARG2), BLK2 movl 240(KEY), ROUNDS vmovdqu (KEY), RDK movdqa BLK0, IV1 movdqa BLK1, IV2 movdqa BLK2, IV3 vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 decl ROUNDS AES_DEC_6_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 vpxor BLK0, IV0, BLK0 vpxor BLK1, IV1, BLK1 vpxor BLK2, IV2, BLK2 vpxor BLK3, IV3, BLK3 vpxor 48(ARG2), BLK4, BLK4 vpxor 64(ARG2), BLK5, BLK5 vmovdqu 80(ARG2), IV0 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) jmp .Laes_cbc_dec_finish .align 16 .Lproc_7_blks: vmovdqu (ARG2), BLK0 vmovdqu 16(ARG2), BLK1 vmovdqu 32(ARG2), BLK2 movl 240(KEY), ROUNDS vmovdqu (KEY), RDK movdqa BLK0, IV1 movdqa BLK1, IV2 movdqa BLK2, IV3 vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 vpxor 96(ARG2), RDK, BLK6 decl ROUNDS AES_DEC_7_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 BLK6 vpxor BLK0, IV0, BLK0 vpxor BLK1, IV1, BLK1 vpxor BLK2, IV2, BLK2 vpxor BLK3, IV3, BLK3 vpxor 48(ARG2), BLK4, BLK4 vpxor 64(ARG2), BLK5, BLK5 vpxor 80(ARG2), BLK6, BLK6 vmovdqu 96(ARG2), IV0 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) vmovdqu BLK6, 96(ARG3) .align 16 .Laes_cbc_dec_finish: vmovdqu IV0, (ARG5) vpxor BLK0, BLK0, BLK0 vpxor BLK1, BLK1, BLK1 vpxor BLK2, BLK2, BLK2 vpxor BLK3, BLK3, BLK3 vpxor BLK4, BLK4, BLK4 vpxor BLK5, BLK5, BLK5 vpxor BLK6, BLK6, BLK6 vpxor BLK7, BLK7, BLK7 vpxor RDK, RDK, RDK movl $0, RET ret .cfi_endproc .size CRYPT_AES_CBC_Decrypt, .-CRYPT_AES_CBC_Decrypt #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_cbc_x86_64.S
Unix Assembly
unknown
12,757
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_CFB) #include "crypt_arm.h" #include "crypt_aes_macro_armv8.s" .file "crypt_aes_cfb_armv8.S" .text .arch armv8-a+crypto .align 5 KEY .req x0 IN .req x1 OUT .req x2 LEN .req x3 IV .req x4 LTMP .req x12 IVC .req v19 CT1 .req v20 CT2 .req v21 CT3 .req v22 CT4 .req v23 CT5 .req v24 CT6 .req v25 CT7 .req v26 CT8 .req v27 BLK0 .req v0 BLK1 .req v1 BLK2 .req v2 BLK3 .req v3 BLK4 .req v4 BLK5 .req v5 BLK6 .req v6 BLK7 .req v7 RDK0 .req v17 RDK1 .req v18 ROUNDS .req w6 /* * int32_t CRYPT_AES_CFB_Decrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, * uint8_t *out, * uint32_t len, * uint8_t *iv); */ .globl CRYPT_AES_CFB_Decrypt .type CRYPT_AES_CFB_Decrypt, %function CRYPT_AES_CFB_Decrypt: AARCH64_PACIASP ld1 {IVC.16b}, [IV] // Load the IV mov LTMP, LEN .Lcfb_aesdec_start: cmp LTMP, #64 b.ge .Lcfb_dec_above_equal_4_blks cmp LTMP, #32 b.ge .Lcfb_dec_above_equal_2_blks cmp LTMP, #0 b.eq .Lcfb_len_zero b .Lcfb_dec_proc_1_blk .Lcfb_dec_above_equal_2_blks: cmp LTMP, #48 b.lt .Lcfb_dec_proc_2_blks b .Lcfb_dec_proc_3_blks .Lcfb_dec_above_equal_4_blks: cmp LTMP, #96 b.ge .Lcfb_dec_above_equal_6_blks cmp LTMP, #80 b.lt .Lcfb_dec_proc_4_blks b .Lcfb_dec_proc_5_blks .Lcfb_dec_above_equal_6_blks: cmp LTMP, #112 b.lt .Lcfb_dec_proc_6_blks cmp LTMP, #128 b.lt .Lcfb_dec_proc_7_blks .Lcfb_dec_proc_8_blks: /* When the length is greater than or equal to 128, eight blocks loop is used */ .Lcfb_aesdec_8_blks_loop: /* Compute 8 CBF Decryption */ ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b}, [IN], #64 mov CT1.16b, IVC.16b // Prevent the IV or BLK from being changed mov CT2.16b, BLK0.16b mov CT3.16b, BLK1.16b mov CT4.16b, BLK2.16b mov CT5.16b, BLK3.16b mov CT6.16b, BLK4.16b mov CT7.16b, BLK5.16b mov CT8.16b, BLK6.16b mov x14, KEY // Prevent the key from being changed AES_ENC_8_BLKS x14 CT1.16b CT2.16b CT3.16b CT4.16b CT5.16b \ CT6.16b CT7.16b CT8.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS mov IVC.16b, BLK7.16b // Prepares for the next loop or update eor BLK0.16b, BLK0.16b, CT1.16b eor BLK1.16b, BLK1.16b, CT2.16b eor BLK2.16b, BLK2.16b, CT3.16b eor BLK3.16b, BLK3.16b, CT4.16b eor BLK4.16b, BLK4.16b, CT5.16b eor BLK5.16b, BLK5.16b, CT6.16b eor BLK6.16b, BLK6.16b, CT7.16b eor BLK7.16b, BLK7.16b, CT8.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b}, [OUT], #64 sub LTMP, LTMP, #128 cmp LTMP, #0 b.eq .Lcfb_aesdec_finish cmp LTMP, #128 b.lt .Lcfb_aesdec_start b .Lcfb_aesdec_8_blks_loop .Lcfb_dec_proc_1_blk: ld1 {BLK0.16b}, [IN] mov CT1.16b, IVC.16b AES_ENC_1_BLK KEY CT1.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS mov IVC.16b, BLK0.16b eor BLK0.16b, CT1.16b, BLK0.16b st1 {BLK0.16b}, [OUT] b .Lcfb_aesdec_finish .Lcfb_dec_proc_2_blks: ld1 {BLK0.16b, BLK1.16b}, [IN] mov CT1.16b, IVC.16b mov CT2.16b, BLK0.16b AES_ENC_2_BLKS KEY CT1.16b CT2.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS mov IVC.16b, BLK1.16b eor BLK0.16b, CT1.16b, BLK0.16b eor BLK1.16b, CT2.16b, BLK1.16b st1 {BLK0.16b, BLK1.16b}, [OUT] b .Lcfb_aesdec_finish .Lcfb_dec_proc_3_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b}, [IN] mov CT1.16b, IVC.16b mov CT2.16b, BLK0.16b mov CT3.16b, BLK1.16b AES_ENC_3_BLKS KEY CT1.16b CT2.16b CT3.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS mov IVC.16b, BLK2.16b eor BLK0.16b, BLK0.16b, CT1.16b eor BLK1.16b, BLK1.16b, CT2.16b eor BLK2.16b, BLK2.16b, CT3.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b}, [OUT] b .Lcfb_aesdec_finish .Lcfb_dec_proc_4_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN] mov CT1.16b, IVC.16b mov CT2.16b, BLK0.16b mov CT3.16b, BLK1.16b mov CT4.16b, BLK2.16b AES_ENC_4_BLKS KEY CT1.16b CT2.16b CT3.16b CT4.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS mov IVC.16b, BLK3.16b eor BLK0.16b, BLK0.16b, CT1.16b eor BLK1.16b, BLK1.16b, CT2.16b eor BLK2.16b, BLK2.16b, CT3.16b eor BLK3.16b, BLK3.16b, CT4.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT] b .Lcfb_aesdec_finish .Lcfb_dec_proc_5_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b}, [IN] mov CT1.16b, IVC.16b mov CT2.16b, BLK0.16b mov CT3.16b, BLK1.16b mov CT4.16b, BLK2.16b mov CT5.16b, BLK3.16b AES_ENC_5_BLKS KEY CT1.16b CT2.16b CT3.16b CT4.16b CT5.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS mov IVC.16b, BLK4.16b eor BLK0.16b, BLK0.16b, CT1.16b eor BLK1.16b, BLK1.16b, CT2.16b eor BLK2.16b, BLK2.16b, CT3.16b eor BLK3.16b, BLK3.16b, CT4.16b eor BLK4.16b, BLK4.16b, CT5.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b}, [OUT] b .Lcfb_aesdec_finish .Lcfb_dec_proc_6_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b}, [IN] mov CT1.16b, IVC.16b mov CT2.16b, BLK0.16b mov CT3.16b, BLK1.16b mov CT4.16b, BLK2.16b mov CT5.16b, BLK3.16b mov CT6.16b, BLK4.16b AES_ENC_6_BLKS KEY CT1.16b CT2.16b CT3.16b CT4.16b CT5.16b CT6.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS mov IVC.16b, BLK5.16b eor BLK0.16b, BLK0.16b, CT1.16b eor BLK1.16b, BLK1.16b, CT2.16b eor BLK2.16b, BLK2.16b, CT3.16b eor BLK3.16b, BLK3.16b, CT4.16b eor BLK4.16b, BLK4.16b, CT5.16b eor BLK5.16b, BLK5.16b, CT6.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b}, [OUT] b .Lcfb_aesdec_finish .Lcfb_dec_proc_7_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b, BLK6.16b}, [IN] mov CT1.16b, IVC.16b mov CT2.16b, BLK0.16b mov CT3.16b, BLK1.16b mov CT4.16b, BLK2.16b mov CT5.16b, BLK3.16b mov CT6.16b, BLK4.16b mov CT7.16b, BLK5.16b AES_ENC_7_BLKS KEY CT1.16b CT2.16b CT3.16b CT4.16b CT5.16b CT6.16b CT7.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS mov IVC.16b, BLK6.16b eor BLK0.16b, BLK0.16b, CT1.16b eor BLK1.16b, BLK1.16b, CT2.16b eor BLK2.16b, BLK2.16b, CT3.16b eor BLK3.16b, BLK3.16b, CT4.16b eor BLK4.16b, BLK4.16b, CT5.16b eor BLK5.16b, BLK5.16b, CT6.16b eor BLK6.16b, BLK6.16b, CT7.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b, BLK6.16b}, [OUT] .Lcfb_aesdec_finish: st1 {IVC.16b}, [IV] .Lcfb_len_zero: mov x0, #0 eor CT1.16b, CT1.16b, CT1.16b eor CT2.16b, CT2.16b, CT2.16b eor CT3.16b, CT3.16b, CT3.16b eor CT4.16b, CT4.16b, CT4.16b eor CT5.16b, CT5.16b, CT5.16b eor CT6.16b, CT6.16b, CT6.16b eor RDK0.16b, RDK0.16b, RDK0.16b eor RDK1.16b, RDK1.16b, RDK1.16b AARCH64_AUTIASP ret .size CRYPT_AES_CFB_Decrypt, .-CRYPT_AES_CFB_Decrypt #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_cfb_armv8.S
Unix Assembly
unknown
7,951
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_CTR) #include "crypt_arm.h" #include "crypt_aes_macro_armv8.s" .file "crypt_aes_ctr_armv8.S" .text .arch armv8-a+crypto .align 5 KEY .req x0 IN .req x1 OUT .req x2 LEN .req x3 IV .req x4 LTMP .req x12 CTMP .req v27 BLK0 .req v0 BLK1 .req v1 BLK2 .req v2 BLK3 .req v3 BLK4 .req v4 BLK5 .req v5 BLK6 .req v6 BLK7 .req v7 CTR0 .req v19 CTR1 .req v20 CTR2 .req v21 CTR3 .req v22 CTR4 .req v23 CTR5 .req v24 CTR6 .req v25 CTR7 .req v26 RDK0 .req v17 RDK1 .req v18 ROUNDS .req w6 /* ctr + 1 */ .macro ADDCTR ctr #ifndef HITLS_BIG_ENDIAN add w11, w11, #1 rev w9, w11 mov \ctr, w9 #else rev w11, w11 add w11, w11, #1 rev w11, w11 mov \ctr, w11 #endif .endm /* * Vn - V0 ~ V31 * 8bytes - Vn.8B Vn.4H Vn.2S Vn.1D * 16bytes - Vn.16B Vn.8H Vn.4S Vn.2D */ /* * int32_t CRYPT_AES_CTR_Encrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, * uint8_t *out, * uint32_t len, * uint8_t *iv); */ .globl CRYPT_AES_CTR_Encrypt .type CRYPT_AES_CTR_Encrypt, %function CRYPT_AES_CTR_Encrypt: AARCH64_PACIASP ld1 {CTR0.16b}, [IV] // Reads the IV. mov CTMP.16b, CTR0.16b mov w11, CTR0.s[3] #ifndef HITLS_BIG_ENDIAN rev w11, w11 #endif mov LTMP, LEN .Lctr_aesenc_start: cmp LTMP, #64 b.ge .Lctr_enc_above_equal_4_blks cmp LTMP, #32 b.ge .Lctr_enc_above_equal_2_blks cmp LTMP, #0 b.eq .Lctr_len_zero b .Lctr_enc_proc_1_blk .Lctr_enc_above_equal_2_blks: cmp LTMP, #48 b.lt .Lctr_enc_proc_2_blks b .Lctr_enc_proc_3_blks .Lctr_enc_above_equal_4_blks: cmp LTMP, #96 b.ge .Lctr_enc_above_equal_6_blks cmp LTMP, #80 b.lt .Lctr_enc_proc_4_blks b .Lctr_enc_proc_5_blks .Lctr_enc_above_equal_6_blks: cmp LTMP, #112 b.lt .Lctr_enc_proc_6_blks cmp LTMP, #128 b.lt .Lctr_enc_proc_7_blks .Lctr_enc_proc_8_blks: /* When the length is greater than or equal to 128, eight blocks loop is used. */ .Lctr_aesenc_8_blks_loop: /* Calculate eight CTRs. */ mov CTR1.16b, CTMP.16b mov CTR2.16b, CTMP.16b mov CTR3.16b, CTMP.16b mov CTR4.16b, CTMP.16b mov CTR5.16b, CTMP.16b mov CTR6.16b, CTMP.16b mov CTR7.16b, CTMP.16b ADDCTR CTR1.s[3] ADDCTR CTR2.s[3] ADDCTR CTR3.s[3] ADDCTR CTR4.s[3] ADDCTR CTR5.s[3] ADDCTR CTR6.s[3] ADDCTR CTR7.s[3] mov x14, KEY // Prevent the key from being changed. AES_ENC_8_BLKS x14 CTR0.16b CTR1.16b CTR2.16b CTR3.16b CTR4.16b \ CTR5.16b CTR6.16b CTR7.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b}, [IN], #64 eor BLK0.16b, BLK0.16b, CTR0.16b eor BLK1.16b, BLK1.16b, CTR1.16b eor BLK2.16b, BLK2.16b, CTR2.16b eor BLK3.16b, BLK3.16b, CTR3.16b eor BLK4.16b, BLK4.16b, CTR4.16b eor BLK5.16b, BLK5.16b, CTR5.16b eor BLK6.16b, BLK6.16b, CTR6.16b eor BLK7.16b, BLK7.16b, CTR7.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b}, [OUT], #64 sub LTMP, LTMP, #128 cmp LTMP, #0 b.eq .Lctr_aesenc_finish ADDCTR CTMP.s[3] mov CTR0.16b, CTMP.16b cmp LTMP, #128 b.lt .Lctr_aesenc_start b .Lctr_aesenc_8_blks_loop .Lctr_enc_proc_1_blk: AES_ENC_1_BLK KEY CTR0.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS ld1 {BLK0.16b}, [IN] eor BLK0.16b, CTR0.16b, BLK0.16b st1 {BLK0.16b}, [OUT] b .Lctr_aesenc_finish .Lctr_enc_proc_2_blks: mov CTR1.16b, CTMP.16b ADDCTR CTR1.s[3] AES_ENC_2_BLKS KEY CTR0.16b CTR1.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS ld1 {BLK0.16b, BLK1.16b}, [IN] eor BLK0.16b, CTR0.16b, BLK0.16b eor BLK1.16b, CTR1.16b, BLK1.16b st1 {BLK0.16b, BLK1.16b}, [OUT] b .Lctr_aesenc_finish .Lctr_enc_proc_3_blks: mov CTR1.16b, CTMP.16b mov CTR2.16b, CTMP.16b ADDCTR CTR1.s[3] ADDCTR CTR2.s[3] AES_ENC_3_BLKS KEY CTR0.16b CTR1.16b CTR2.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS ld1 {BLK0.16b, BLK1.16b, BLK2.16b}, [IN] eor BLK0.16b, BLK0.16b, CTR0.16b eor BLK1.16b, BLK1.16b, CTR1.16b eor BLK2.16b, BLK2.16b, CTR2.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b}, [OUT] b .Lctr_aesenc_finish .Lctr_enc_proc_4_blks: mov CTR1.16b, CTMP.16b mov CTR2.16b, CTMP.16b mov CTR3.16b, CTMP.16b ADDCTR CTR1.s[3] ADDCTR CTR2.s[3] ADDCTR CTR3.s[3] AES_ENC_4_BLKS KEY CTR0.16b CTR1.16b CTR2.16b CTR3.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN] eor BLK0.16b, BLK0.16b, CTR0.16b eor BLK1.16b, BLK1.16b, CTR1.16b eor BLK2.16b, BLK2.16b, CTR2.16b eor BLK3.16b, BLK3.16b, CTR3.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT] b .Lctr_aesenc_finish .Lctr_enc_proc_5_blks: mov CTR1.16b, CTMP.16b mov CTR2.16b, CTMP.16b mov CTR3.16b, CTMP.16b mov CTR4.16b, CTMP.16b ADDCTR CTR1.s[3] ADDCTR CTR2.s[3] ADDCTR CTR3.s[3] ADDCTR CTR4.s[3] AES_ENC_5_BLKS KEY CTR0.16b CTR1.16b CTR2.16b CTR3.16b CTR4.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b}, [IN] eor BLK0.16b, BLK0.16b, CTR0.16b eor BLK1.16b, BLK1.16b, CTR1.16b eor BLK2.16b, BLK2.16b, CTR2.16b eor BLK3.16b, BLK3.16b, CTR3.16b eor BLK4.16b, BLK4.16b, CTR4.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b}, [OUT] b .Lctr_aesenc_finish .Lctr_enc_proc_6_blks: mov CTR1.16b, CTMP.16b mov CTR2.16b, CTMP.16b mov CTR3.16b, CTMP.16b mov CTR4.16b, CTMP.16b mov CTR5.16b, CTMP.16b ADDCTR CTR1.s[3] ADDCTR CTR2.s[3] ADDCTR CTR3.s[3] ADDCTR CTR4.s[3] ADDCTR CTR5.s[3] AES_ENC_6_BLKS KEY CTR0.16b CTR1.16b CTR2.16b CTR3.16b CTR4.16b \ CTR5.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b}, [IN] eor BLK0.16b, BLK0.16b, CTR0.16b eor BLK1.16b, BLK1.16b, CTR1.16b eor BLK2.16b, BLK2.16b, CTR2.16b eor BLK3.16b, BLK3.16b, CTR3.16b eor BLK4.16b, BLK4.16b, CTR4.16b eor BLK5.16b, BLK5.16b, CTR5.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b}, [OUT] b .Lctr_aesenc_finish .Lctr_enc_proc_7_blks: mov CTR1.16b, CTMP.16b mov CTR2.16b, CTMP.16b mov CTR3.16b, CTMP.16b mov CTR4.16b, CTMP.16b mov CTR5.16b, CTMP.16b mov CTR6.16b, CTMP.16b ADDCTR CTR1.s[3] ADDCTR CTR2.s[3] ADDCTR CTR3.s[3] ADDCTR CTR4.s[3] ADDCTR CTR5.s[3] ADDCTR CTR6.s[3] AES_ENC_7_BLKS KEY CTR0.16b CTR1.16b CTR2.16b CTR3.16b CTR4.16b \ CTR5.16b CTR6.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b, BLK6.16b}, [IN] eor BLK0.16b, BLK0.16b, CTR0.16b eor BLK1.16b, BLK1.16b, CTR1.16b eor BLK2.16b, BLK2.16b, CTR2.16b eor BLK3.16b, BLK3.16b, CTR3.16b eor BLK4.16b, BLK4.16b, CTR4.16b eor BLK5.16b, BLK5.16b, CTR5.16b eor BLK6.16b, BLK6.16b, CTR6.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b, BLK6.16b}, [OUT] .Lctr_aesenc_finish: ADDCTR CTMP.s[3] // Fill CTR0 for the next round. st1 {CTMP.16b}, [IV] .Lctr_len_zero: mov x0, #0 eor CTR0.16b, CTR0.16b, CTR0.16b eor CTR1.16b, CTR1.16b, CTR1.16b eor CTR2.16b, CTR2.16b, CTR2.16b eor CTR3.16b, CTR3.16b, CTR3.16b eor CTR4.16b, CTR4.16b, CTR4.16b eor CTR5.16b, CTR5.16b, CTR5.16b eor CTR6.16b, CTR6.16b, CTR6.16b eor CTR7.16b, CTR7.16b, CTR7.16b eor RDK0.16b, RDK0.16b, RDK0.16b eor RDK1.16b, RDK1.16b, RDK1.16b AARCH64_AUTIASP ret .size CRYPT_AES_CTR_Encrypt, .-CRYPT_AES_CTR_Encrypt #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_ctr_armv8.S
Unix Assembly
unknown
9,199
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_CTR) .file "crypt_aes_ctr_x86_64.S" .text .set KEY, %rdi .set INPUT, %rsi .set OUTPUT, %rdx .set LEN, %ecx .set CTR_IV, %r8 .set RDK, %xmm0 .set RDK2, %xmm1 .set KTMP, %r13 .set ROUNDS, %eax .set RET, %eax .set IV0, %xmm2 .set IV1, %xmm3 .set IV2, %xmm4 .set IV3, %xmm5 .set IV4, %xmm6 .set IV5, %xmm7 .set IV6, %xmm8 .set IV7, %xmm9 .set BLK0, %xmm10 .set BLK1, %xmm11 .set BLK2, %xmm12 .set BLK3, %xmm13 .set BLK4, %xmm14 .set BLK5, %xmm15 /** * Macro description: Eight IVs are encrypted. * Input register: * Key: Round key. * block0-7: Encrypted IV. * Modify the register: block0-7. * Output register: * block0-7: IV after a round of encryption. */ .macro ONE_ENC key block0 block1 block2 block3 block4 block5 block6 block7 aesenc \key, \block0 aesenc \key, \block1 aesenc \key, \block2 aesenc \key, \block3 aesenc \key, \block4 aesenc \key, \block5 aesenc \key, \block6 aesenc \key, \block7 .endm /** * Macro description: Obtains a new ctr and XORs it with the round key. * input register: * ctr32:Initialization vector. * offset:Offset. * temp:32-bit CTR temporary register. * key32:32-bit round key. * addrOffset:push stack address offset. * addr:push stack address. * Modify the register: Temp. */ .macro XOR_KEY ctr32 offset temp key32 addrOffset addr leal \offset(\ctr32), \temp // XOR 32-bit ctr and key, push into the stack bswapl \temp xorl \key32, \temp movl \temp, \addrOffset+12(\addr) .endm /** * Macro description: Obtain the round key, encrypt the IV, obtain the next round of ctr, and XOR the round key. * Input register: * Key: pointer to the key. * Offset: round key offset. * Temp: Temporary register for the round key. * Ctr32: initialization vector. * Offset2: Ctr offset. * Temp2: 32-bit CTR temporary register. * Key32: 32-bit round key. * AddrOffset: Offest of entering the stack. * Addr: Address for entering the stack. * Modify register: Temp temp2 IV0-7. * Output register: * IV0-7: IV after a round of encryption. */ .macro ONE_ENC_XOR_KEY key offset temp ctr32 offset2 temp2 key32 addrOffset addr vmovdqu \offset(\key), \temp aesenc \temp, IV0 leal \offset2(\ctr32), \temp2 // XOR 32-bit ctr and key, push stack. aesenc \temp, IV1 bswapl \temp2 aesenc \temp, IV2 aesenc \temp, IV3 xorl \key32, \temp2 aesenc \temp, IV4 aesenc \temp, IV5 movl \temp2, \addrOffset+12(\addr) aesenc \temp, IV6 aesenc \temp, IV7 .endm /** * Macro description: Update the in and out pointer offsets and the remaining length of len. * Input register: * Input:pointer to the input memory. * Output:pointer to the output memory. * Len:remaining data length. * Offset:indicates the offset. * Modify the register: Input output len. * Output register: * Input output len */ .macro UPDATE_DATA input output len offset leaq \offset(\input), \input leaq \offset(\output), \output subl $\offset, \len .endm /** * Function description:Sets the AES encrypted assembly acceleration API, ctr mode. * Function prototype:int32_t CRYPT_AES_CTR_Encrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, * uint32_t len, uint8_t *iv); * Input register: * rdi:Pointer to the input key structure. * rsi:Points to the 128-bit input data. * rdx:Points to the 128-bit output data. * rcx:Length of the data block, that is, 16 bytes. * r8: 16-byte initialization vector. * Change register:xmm1, xmm3, xmm4, xmm5, xmm6, xmm10, xmm11, xmm12, xmm13. * Output register:rdx, r8. */ .globl CRYPT_AES_CTR_Encrypt .type CRYPT_AES_CTR_Encrypt, @function CRYPT_AES_CTR_Encrypt: .cfi_startproc pushq %r12 pushq %r13 pushq %r14 pushq %r15 mov %rsp, %r12 subq $128, %rsp // Declare for 128-byte stack space. andq $-16, %rsp vmovdqu (KEY), RDK vpxor (CTR_IV), RDK, IV0 vmovdqa IV0, 0(%rsp) vmovdqa IV0, 16(%rsp) vmovdqa IV0, 32(%rsp) vmovdqa IV0, 48(%rsp) vmovdqa IV0, 64(%rsp) vmovdqa IV0, 80(%rsp) vmovdqa IV0, 96(%rsp) vmovdqa IV0, 112(%rsp) movl 12(CTR_IV), %r11d // Read 32-bit ctr. movl 12(KEY), %r9d // Read 32-bit key. bswap %r11d mov LEN, %r14d shr $4, %r14d and $7, %r14d cmp $1, %r14d je .Lctr_enc_proc_1_blk cmp $2, %r14d je .Lctr_enc_proc_2_blk cmp $3, %r14d je .Lctr_enc_proc_3_blk cmp $4, %r14d je .Lctr_enc_proc_4_blk cmp $5, %r14d je .Lctr_enc_proc_5_blk cmp $6, %r14d je .Lctr_enc_proc_6_blk cmp $7, %r14d je .Lctr_enc_proc_7_blk .Lctr_enc_proc_8_blk: cmp $0, LEN je .Lctr_aesenc_finish leal 0(%r11d), %r15d leal 1(%r11d), %r10d bswapl %r15d bswapl %r10d xorl %r9d, %r15d xorl %r9d, %r10d leal 2(%r11d), %r14d movl %r15d, 12(%rsp) bswapl %r14d movl %r10d, 16+12(%rsp) xorl %r9d, %r14d leal 3(%r11d), %r15d leal 4(%r11d), %r10d bswapl %r15d bswapl %r10d movl %r14d, 32+12(%rsp) xorl %r9d, %r15d xorl %r9d, %r10d movl %r15d, 48+12(%rsp) leal 5(%r11d), %r14d bswapl %r14d movl %r10d, 64+12(%rsp) xorl %r9d, %r14d leal 6(%r11d), %r15d leal 7(%r11d), %r10d movl %r14d, 80+12(%rsp) bswapl %r15d bswapl %r10d xorl %r9d, %r15d xorl %r9d, %r10d movl %r15d, 96+12(%rsp) movl %r10d, 112+12(%rsp) vmovdqa (%rsp), IV0 vmovdqa 16(%rsp), IV1 vmovdqa 32(%rsp), IV2 vmovdqa 48(%rsp), IV3 vmovdqa 64(%rsp), IV4 vmovdqa 80(%rsp), IV5 vmovdqa 96(%rsp), IV6 vmovdqa 112(%rsp), IV7 .align 16 .Lctr_aesenc_8_blks_enc_loop: addl $8, %r11d // ctr+8 movl 240(KEY), ROUNDS ONE_ENC_XOR_KEY KEY, 16, RDK2, %r11d, 0, %r10d, %r9d, 0, %rsp // Round 1 encryption ONE_ENC_XOR_KEY KEY, 32, RDK2, %r11d, 1, %r10d, %r9d, 16, %rsp // Round 2 encryption ONE_ENC_XOR_KEY KEY, 48, RDK2, %r11d, 2, %r10d, %r9d, 32, %rsp // Round 3 encryption ONE_ENC_XOR_KEY KEY, 64, RDK2, %r11d, 3, %r10d, %r9d, 48, %rsp // Round 4 encryption ONE_ENC_XOR_KEY KEY, 80, RDK2, %r11d, 4, %r10d, %r9d, 64, %rsp // Round 5 encryption ONE_ENC_XOR_KEY KEY, 96, RDK2, %r11d, 5, %r10d, %r9d, 80, %rsp // Round 6 encryption ONE_ENC_XOR_KEY KEY, 112, RDK2, %r11d, 6, %r10d, %r9d, 96, %rsp // Round 7 encryption ONE_ENC_XOR_KEY KEY, 128, RDK2, %r11d, 7, %r10d, %r9d, 112, %rsp // Round 8 encryption vmovdqu 144(KEY), RDK // Round 9 key Load vmovdqu 160(KEY), RDK2 // Round 10 key Load cmp $12, ROUNDS jb .Lctr_aesenc_8_blks_enc_last ONE_ENC RDK, IV0, IV1, IV2, IV3, IV4, IV5, IV6, IV7 // Round 9 encryption vmovdqu 176(KEY), RDK // Round 11 key Load ONE_ENC RDK2, IV0, IV1, IV2, IV3, IV4, IV5, IV6, IV7 // Round 10 encryption vmovdqu 192(KEY), RDK2 // Round 12 key Load je .Lctr_aesenc_8_blks_enc_last ONE_ENC RDK, IV0, IV1, IV2, IV3, IV4, IV5, IV6, IV7 // Round 11 encryption vmovdqu 208(KEY), RDK // Round 13 key Load ONE_ENC RDK2, IV0, IV1, IV2, IV3, IV4, IV5, IV6, IV7 // Round 12 encryption vmovdqu 224(KEY), RDK2 // Round 14 key Load .align 16 .Lctr_aesenc_8_blks_enc_last: vpxor (INPUT), RDK2, BLK0 // Last round Key ^ Plaintext. vpxor 16(INPUT), RDK2, BLK1 vpxor 32(INPUT), RDK2, BLK2 vpxor 48(INPUT), RDK2, BLK3 ONE_ENC RDK, IV0, IV1, IV2, IV3, IV4, IV5, IV6, IV7 aesenclast BLK0, IV0 // Last round of encryption. aesenclast BLK1, IV1 aesenclast BLK2, IV2 aesenclast BLK3, IV3 aesenclast RDK2, IV4 aesenclast RDK2, IV5 aesenclast RDK2, IV6 aesenclast RDK2, IV7 vmovdqu IV0, (OUTPUT) // The first four ciphertexts are stored in out. vmovdqu IV1, 16(OUTPUT) vmovdqu IV2, 32(OUTPUT) vmovdqu IV3, 48(OUTPUT) vpxor 64(INPUT), IV4, BLK0 // Last Round Key ^ Plaintext. vpxor 80(INPUT), IV5, BLK1 vpxor 96(INPUT), IV6, BLK2 vpxor 112(INPUT), IV7, BLK3 vmovdqu BLK0, 64(OUTPUT) vmovdqu BLK1, 80(OUTPUT) vmovdqu BLK2, 96(OUTPUT) // The last four ciphertexts are stored in out. vmovdqu BLK3, 112(OUTPUT) vmovdqa (%rsp), IV0 // Reads the next round of ctr from the stack. vmovdqa 16(%rsp), IV1 vmovdqa 32(%rsp), IV2 vmovdqa 48(%rsp), IV3 vmovdqa 64(%rsp), IV4 vmovdqa 80(%rsp), IV5 vmovdqa 96(%rsp), IV6 vmovdqa 112(%rsp), IV7 UPDATE_DATA INPUT, OUTPUT, LEN, 128 cmpl $0, LEN jbe .Lctr_aesenc_finish jmp .Lctr_aesenc_8_blks_enc_loop .Lctr_enc_proc_1_blk: movl 240(KEY), ROUNDS movq KEY, KTMP decl ROUNDS .align 16 .Laesenc_loop: leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenc RDK, IV0 decl ROUNDS jnz .Laesenc_loop // Loop the loop until the ROUNDS is 0. leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenclast RDK, IV0 addl $1, %r11d // Update ctr32. vpxor (INPUT), IV0, BLK0 vmovdqu BLK0, (OUTPUT) // Ciphertext stored in out. UPDATE_DATA INPUT, OUTPUT, LEN, 16 jmp .Lctr_enc_proc_8_blk .Lctr_enc_proc_2_blk: movl 240(KEY), ROUNDS movq KEY, KTMP decl ROUNDS XOR_KEY %r11d, 1, %r10d, %r9d, 16, %rsp vmovdqa 16(%rsp), IV1 .align 16 .Laesenc_2_blks_loop: leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenc RDK, IV0 aesenc RDK, IV1 decl ROUNDS jnz .Laesenc_2_blks_loop leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenclast RDK, IV0 aesenclast RDK, IV1 vpxor (INPUT), IV0, BLK0 vpxor 16(INPUT), IV1, BLK1 vmovdqu BLK0, (OUTPUT) vmovdqu BLK1, 16(OUTPUT) addl $2, %r11d UPDATE_DATA INPUT, OUTPUT, LEN, 32 jmp .Lctr_enc_proc_8_blk .Lctr_enc_proc_3_blk: movl 240(KEY), ROUNDS movq KEY, KTMP decl ROUNDS XOR_KEY %r11d, 1, %r10d, %r9d, 16, %rsp XOR_KEY %r11d, 2, %r10d, %r9d, 32, %rsp vmovdqa 16(%rsp), IV1 vmovdqa 32(%rsp), IV2 .align 16 .Laesenc_3_blks_loop: leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenc RDK, IV0 aesenc RDK, IV1 aesenc RDK, IV2 decl ROUNDS jnz .Laesenc_3_blks_loop leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenclast RDK, IV0 aesenclast RDK, IV1 aesenclast RDK, IV2 vpxor (INPUT), IV0, BLK0 vpxor 16(INPUT), IV1, BLK1 vpxor 32(INPUT), IV2, BLK2 vmovdqu BLK0, (OUTPUT) vmovdqu BLK1, 16(OUTPUT) vmovdqu BLK2, 32(OUTPUT) addl $3, %r11d UPDATE_DATA INPUT, OUTPUT, LEN, 48 jmp .Lctr_enc_proc_8_blk .Lctr_enc_proc_4_blk: movl 240(KEY), ROUNDS movq KEY, KTMP decl ROUNDS XOR_KEY %r11d, 1, %r10d, %r9d, 16, %rsp XOR_KEY %r11d, 2, %r10d, %r9d, 32, %rsp XOR_KEY %r11d, 3, %r10d, %r9d, 48, %rsp vmovdqa 16(%rsp), IV1 vmovdqa 32(%rsp), IV2 vmovdqa 48(%rsp), IV3 .align 16 .Laesenc_4_blks_loop: leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenc RDK, IV0 aesenc RDK, IV1 aesenc RDK, IV2 aesenc RDK, IV3 decl ROUNDS jnz .Laesenc_4_blks_loop leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenclast RDK, IV0 aesenclast RDK, IV1 aesenclast RDK, IV2 aesenclast RDK, IV3 vpxor (INPUT), IV0, BLK0 vpxor 16(INPUT), IV1, BLK1 vpxor 32(INPUT), IV2, BLK2 vpxor 48(INPUT), IV3, BLK3 vmovdqu BLK0, (OUTPUT) vmovdqu BLK1, 16(OUTPUT) vmovdqu BLK2, 32(OUTPUT) vmovdqu BLK3, 48(OUTPUT) addl $4, %r11d UPDATE_DATA INPUT, OUTPUT, LEN, 64 jmp .Lctr_enc_proc_8_blk .Lctr_enc_proc_5_blk: movl 240(KEY), ROUNDS movq KEY, KTMP decl ROUNDS XOR_KEY %r11d, 1, %r10d, %r9d, 16, %rsp XOR_KEY %r11d, 2, %r10d, %r9d, 32, %rsp XOR_KEY %r11d, 3, %r10d, %r9d, 48, %rsp XOR_KEY %r11d, 4, %r10d, %r9d, 64, %rsp vmovdqa 16(%rsp), IV1 vmovdqa 32(%rsp), IV2 vmovdqa 48(%rsp), IV3 vmovdqa 64(%rsp), IV4 .align 16 .Laesenc_5_blks_loop: leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenc RDK, IV0 aesenc RDK, IV1 aesenc RDK, IV2 aesenc RDK, IV3 aesenc RDK, IV4 decl ROUNDS jnz .Laesenc_5_blks_loop leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenclast RDK, IV0 aesenclast RDK, IV1 aesenclast RDK, IV2 aesenclast RDK, IV3 aesenclast RDK, IV4 vpxor (INPUT), IV0, BLK0 vpxor 16(INPUT), IV1, BLK1 vpxor 32(INPUT), IV2, BLK2 vpxor 48(INPUT), IV3, BLK3 vpxor 64(INPUT), IV4, BLK4 vmovdqu BLK0, (OUTPUT) vmovdqu BLK1, 16(OUTPUT) vmovdqu BLK2, 32(OUTPUT) vmovdqu BLK3, 48(OUTPUT) vmovdqu BLK4, 64(OUTPUT) addl $5, %r11d UPDATE_DATA INPUT, OUTPUT, LEN, 80 jmp .Lctr_enc_proc_8_blk .Lctr_enc_proc_6_blk: movl 240(KEY), ROUNDS movq KEY, KTMP decl ROUNDS XOR_KEY %r11d, 1, %r10d, %r9d, 16, %rsp XOR_KEY %r11d, 2, %r10d, %r9d, 32, %rsp XOR_KEY %r11d, 3, %r10d, %r9d, 48, %rsp XOR_KEY %r11d, 4, %r10d, %r9d, 64, %rsp XOR_KEY %r11d, 5, %r10d, %r9d, 80, %rsp vmovdqa 16(%rsp), IV1 vmovdqa 32(%rsp), IV2 vmovdqa 48(%rsp), IV3 vmovdqa 64(%rsp), IV4 vmovdqa 80(%rsp), IV5 .align 16 .Laesenc_6_blks_loop: leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenc RDK, IV0 aesenc RDK, IV1 aesenc RDK, IV2 aesenc RDK, IV3 aesenc RDK, IV4 aesenc RDK, IV5 decl ROUNDS jnz .Laesenc_6_blks_loop leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenclast RDK, IV0 aesenclast RDK, IV1 aesenclast RDK, IV2 aesenclast RDK, IV3 aesenclast RDK, IV4 aesenclast RDK, IV5 vpxor (INPUT), IV0, BLK0 vpxor 16(INPUT), IV1, BLK1 vpxor 32(INPUT), IV2, BLK2 vpxor 48(INPUT), IV3, BLK3 vpxor 64(INPUT), IV4, BLK4 vpxor 80(INPUT), IV5, BLK5 vmovdqu BLK0, (OUTPUT) vmovdqu BLK1, 16(OUTPUT) vmovdqu BLK2, 32(OUTPUT) vmovdqu BLK3, 48(OUTPUT) vmovdqu BLK4, 64(OUTPUT) vmovdqu BLK5, 80(OUTPUT) addl $6, %r11d UPDATE_DATA INPUT, OUTPUT, LEN, 96 jmp .Lctr_enc_proc_8_blk .Lctr_enc_proc_7_blk: movl 240(KEY), ROUNDS movq KEY, KTMP decl ROUNDS XOR_KEY %r11d, 1, %r10d, %r9d, 16, %rsp XOR_KEY %r11d, 2, %r10d, %r9d, 32, %rsp XOR_KEY %r11d, 3, %r10d, %r9d, 48, %rsp XOR_KEY %r11d, 4, %r10d, %r9d, 64, %rsp XOR_KEY %r11d, 5, %r10d, %r9d, 80, %rsp XOR_KEY %r11d, 6, %r10d, %r9d, 96, %rsp vmovdqa 16(%rsp), IV1 vmovdqa 32(%rsp), IV2 vmovdqa 48(%rsp), IV3 vmovdqa 64(%rsp), IV4 vmovdqa 80(%rsp), IV5 vmovdqa 96(%rsp), IV6 .align 16 .Laesenc_7_blks_loop: leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenc RDK, IV0 aesenc RDK, IV1 aesenc RDK, IV2 aesenc RDK, IV3 aesenc RDK, IV4 aesenc RDK, IV5 aesenc RDK, IV6 decl ROUNDS jnz .Laesenc_7_blks_loop leaq 16(KTMP), KTMP vmovdqu (KTMP), RDK aesenclast RDK, IV0 aesenclast RDK, IV1 aesenclast RDK, IV2 aesenclast RDK, IV3 aesenclast RDK, IV4 aesenclast RDK, IV5 aesenclast RDK, IV6 vpxor (INPUT), IV0, BLK0 vpxor 16(INPUT), IV1, BLK1 vpxor 32(INPUT), IV2, BLK2 vpxor 48(INPUT), IV3, BLK3 vmovdqu BLK0, (OUTPUT) vmovdqu BLK1, 16(OUTPUT) vmovdqu BLK2, 32(OUTPUT) vmovdqu BLK3, 48(OUTPUT) vpxor 64(INPUT), IV4, BLK0 vpxor 80(INPUT), IV5, BLK1 vpxor 96(INPUT), IV6, BLK2 vmovdqu BLK0, 64(OUTPUT) vmovdqu BLK1, 80(OUTPUT) vmovdqu BLK2, 96(OUTPUT) addl $7, %r11d UPDATE_DATA INPUT, OUTPUT, LEN, 112 jmp .Lctr_enc_proc_8_blk .Lctr_aesenc_finish: bswap %r11d movl %r11d, 12(CTR_IV) vpxor IV0, IV0, IV0 vpxor IV1, IV1, IV1 vpxor IV2, IV2, IV2 vpxor IV3, IV3, IV3 vpxor IV4, IV4, IV4 vpxor IV5, IV5, IV5 vpxor IV6, IV6, IV6 vpxor IV7, IV7, IV7 vpxor RDK, RDK, RDK vmovdqa IV0, 0(%rsp) vmovdqa IV0, 16(%rsp) vmovdqa IV0, 32(%rsp) vmovdqa IV0, 48(%rsp) vmovdqa IV0, 64(%rsp) vmovdqa IV0, 80(%rsp) vmovdqa IV0, 96(%rsp) vmovdqa IV0, 112(%rsp) movq %r12, %rsp popq %r15 popq %r14 popq %r13 popq %r12 movl $0, RET ret .cfi_endproc .size CRYPT_AES_CTR_Encrypt, .-CRYPT_AES_CTR_Encrypt #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_ctr_x86_64.S
Unix Assembly
unknown
18,679
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_ECB) #include "crypt_arm.h" #include "crypt_aes_macro_armv8.s" .file "crypt_aes_ecb_armv8.S" .text .arch armv8-a+crypto KEY .req x0 IN .req x1 OUT .req x2 LEN .req x3 KTMP .req x4 LTMP .req x9 ROUNDS .req w6 BLK0 .req v0 BLK1 .req v1 BLK2 .req v2 BLK3 .req v3 BLK4 .req v4 BLK5 .req v5 BLK6 .req v6 BLK7 .req v7 RDK0 .req v17 RDK1 .req v18 /* * Vn - V0 ~ V31 * 8bytes - Vn.8B Vn.4H Vn.2S Vn.1D * 16bytes - Vn.16B Vn.8H Vn.4S Vn.2D * * In Return-oriented programming (ROP) and Jump-oriented programming (JOP), we explored features * that Arm introduced to the Arm architecture to mitigate against JOP-style and ROP-style attacks. * ... * Whether the combined or NOP-compatible instructions are generated depends on the architecture * version that the code is built for. When building for Armv8.3-A, or later, the compiler will use * the combined operations. When building for Armv8.2-A, or earlier, it will use the NOP compatible * instructions. * (https://developer.arm.com/documentation/102433/0100/Applying-these-techniques-to-real-code?lang=en) * * The paciasp and autiasp instructions are used for function pointer authentication. The pointer * authentication feature is added in armv8.3 and is supported only by AArch64. * The addition of pointer authentication features is described in Section A2.6.1 of * DDI0487H_a_a-profile_architecture_reference_manual.pdf. */ /** * Function description: Sets the AES encryption assembly acceleration interface in ECB mode. * int32_t CRYPT_AES_ECB_Encrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, * uint8_t *out, * uint32_t len); * Input register: * x0: Pointer to the input key structure. * x1: Points to the 128-bit input data. * x2: Points to the 128-bit output data. * x3: Indicates the length of a data block, that is, 16 bytes. * Change register: x4, x6, x9, v0-v7, v17, v18. * Output register: x0. * Function/Macro Call: AES_ENC_8_BLKS, AES_ENC_1_BLK, AES_ENC_2_BLKS, AES_ENC_4_BLKS, * AES_ENC_5_BLKS, AES_ENC_6_BLKS, AES_ENC_7_BLKS. */ .globl CRYPT_AES_ECB_Encrypt .type CRYPT_AES_ECB_Encrypt, %function CRYPT_AES_ECB_Encrypt: AARCH64_PACIASP mov LTMP, LEN .Lecb_aesenc_start: cmp LTMP, #64 b.ge .Lecb_enc_above_equal_4_blks cmp LTMP, #32 b.ge .Lecb_enc_above_equal_2_blks cmp LTMP, #0 b.eq .Lecb_aesenc_finish b .Lecb_enc_proc_1_blk .Lecb_enc_above_equal_2_blks: cmp LTMP, #48 b.lt .Lecb_enc_proc_2_blks b .Lecb_enc_proc_3_blks .Lecb_enc_above_equal_4_blks: cmp LTMP, #96 b.ge .Lecb_enc_above_equal_6_blks cmp LTMP, #80 b.lt .Lecb_enc_proc_4_blks b .Lecb_enc_proc_5_blks .Lecb_enc_above_equal_6_blks: cmp LTMP, #112 b.lt .Lecb_enc_proc_6_blks cmp LTMP, #128 b.lt .Lecb_enc_proc_7_blks .Lecb_enc_proc_8_blks: .Lecb_aesenc_8_blks_loop: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b}, [IN], #64 mov KTMP, KEY AES_ENC_8_BLKS KTMP BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b \ BLK5.16b BLK6.16b BLK7.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b}, [OUT], #64 sub LTMP, LTMP, #128 cmp LTMP, #128 b.lt .Lecb_aesenc_start b .Lecb_aesenc_8_blks_loop .Lecb_enc_proc_1_blk: ld1 {BLK0.16b}, [IN] AES_ENC_1_BLK KEY BLK0.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b}, [OUT] b .Lecb_aesenc_finish .Lecb_enc_proc_2_blks: ld1 {BLK0.16b, BLK1.16b}, [IN] AES_ENC_2_BLKS KEY BLK0.16b BLK1.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b}, [OUT] b .Lecb_aesenc_finish .Lecb_enc_proc_3_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b}, [IN] AES_ENC_3_BLKS KEY BLK0.16b BLK1.16b BLK2.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b}, [OUT] b .Lecb_aesenc_finish .Lecb_enc_proc_4_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN] AES_ENC_4_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT] b .Lecb_aesenc_finish .Lecb_enc_proc_5_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b}, [IN] AES_ENC_5_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b}, [OUT] b .Lecb_aesenc_finish .Lecb_enc_proc_6_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b}, [IN] AES_ENC_6_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b BLK5.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b}, [OUT] b .Lecb_aesenc_finish .Lecb_enc_proc_7_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b, BLK6.16b}, [IN] AES_ENC_7_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b BLK5.16b BLK6.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b, BLK6.16b}, [OUT] .Lecb_aesenc_finish: mov x0, #0 eor RDK0.16b, RDK0.16b, RDK0.16b eor RDK1.16b, RDK1.16b, RDK1.16b AARCH64_AUTIASP ret .size CRYPT_AES_ECB_Encrypt, .-CRYPT_AES_ECB_Encrypt /** * Function description: Sets the AES decryption and assembly acceleration API in ECB mode. * int32_t CRYPT_AES_ECB_Decrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, * uint8_t *out, * uint32_t len); * Input register: * x0: Pointer to the input key structure. * x1: Points to the 128-bit input data. * x2: Points to the 128-bit output data. * x3: Indicates the length of a data block, that is, 16 bytes. * Change register: x4, x6, x9, v0-v7, v17, v18 * Output register: x0 * Function/Macro Call: AES_DEC_8_BLKS, AES_DEC_1_BLK, AES_DEC_2_BLKS, AES_DEC_4_BLKS, * AES_DEC_5_BLKS, AES_DEC_6_BLKS, AES_DEC_7_BLKS. */ .globl CRYPT_AES_ECB_Decrypt .type CRYPT_AES_ECB_Decrypt, %function CRYPT_AES_ECB_Decrypt: AARCH64_PACIASP mov LTMP, LEN .Lecb_aesdec_start: cmp LTMP, #64 b.ge .Lecb_dec_above_equal_4_blks cmp LTMP, #32 b.ge .Lecb_dec_above_equal_2_blks cmp LTMP, #0 b.eq .Lecb_aesdec_finish b .Lecb_dec_proc_1_blk .Lecb_dec_above_equal_2_blks: cmp LTMP, #48 b.lt .Lecb_dec_proc_2_blks b .Lecb_dec_proc_3_blks .Lecb_dec_above_equal_4_blks: cmp LTMP, #96 b.ge .Lecb_dec_above_equal_6_blks cmp LTMP, #80 b.lt .Lecb_dec_proc_4_blks b .Lecb_dec_proc_5_blks .Lecb_dec_above_equal_6_blks: cmp LTMP, #112 b.lt .Lecb_dec_proc_6_blks cmp LTMP, #128 b.lt .Lecb_dec_proc_7_blks .Lecb_dec_proc_8_blks: .Lecb_aesdec_8_blks_loop: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b}, [IN], #64 mov KTMP, KEY AES_DEC_8_BLKS KTMP BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b \ BLK5.16b BLK6.16b BLK7.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b, BLK6.16b, BLK7.16b}, [OUT], #64 sub LTMP, LTMP, #128 cmp LTMP, #128 b.lt .Lecb_aesdec_start b .Lecb_aesdec_8_blks_loop .Lecb_dec_proc_1_blk: ld1 {BLK0.16b}, [IN] AES_DEC_1_BLK KEY BLK0.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b}, [OUT] b .Lecb_aesdec_finish .Lecb_dec_proc_2_blks: ld1 {BLK0.16b, BLK1.16b}, [IN] AES_DEC_2_BLKS KEY BLK0.16b BLK1.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b}, [OUT] b .Lecb_aesdec_finish .Lecb_dec_proc_3_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b}, [IN] AES_DEC_3_BLKS KEY BLK0.16b BLK1.16b BLK2.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b}, [OUT] b .Lecb_aesdec_finish .Lecb_dec_proc_4_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN] AES_DEC_4_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT] b .Lecb_aesdec_finish .Lecb_dec_proc_5_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b}, [IN] AES_DEC_5_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b}, [OUT] b .Lecb_aesdec_finish .Lecb_dec_proc_6_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b}, [IN] AES_DEC_6_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b BLK5.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b}, [OUT] b .Lecb_aesdec_finish .Lecb_dec_proc_7_blks: ld1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [IN], #64 ld1 {BLK4.16b, BLK5.16b, BLK6.16b}, [IN] AES_DEC_7_BLKS KEY BLK0.16b BLK1.16b BLK2.16b BLK3.16b BLK4.16b BLK5.16b BLK6.16b RDK0.4s RDK1.4s RDK0.16b RDK1.16b ROUNDS st1 {BLK0.16b, BLK1.16b, BLK2.16b, BLK3.16b}, [OUT], #64 st1 {BLK4.16b, BLK5.16b, BLK6.16b}, [OUT] .Lecb_aesdec_finish: mov x0, #0 eor RDK0.16b, RDK0.16b, RDK0.16b eor RDK1.16b, RDK1.16b, RDK1.16b AARCH64_AUTIASP ret .size CRYPT_AES_ECB_Decrypt, .-CRYPT_AES_ECB_Decrypt #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_ecb_armv8.S
Unix Assembly
unknown
10,519
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_ECB) #include "crypt_aes_macro_x86_64.s" .file "crypt_aes_ecb_x86_64.S" .text .set ARG1, %rdi .set ARG2, %rsi .set ARG3, %rdx .set ARG4, %ecx .set ARG5, %r8 .set ARG6, %r9 .set RDK, %xmm3 .set KEY, %rdi .set KTMP, %r9 .set ROUNDS, %eax .set RET, %eax .set BLK0, %xmm1 .set BLK1, %xmm4 .set BLK2, %xmm5 .set BLK3, %xmm6 .set BLK4, %xmm10 .set BLK5, %xmm11 .set BLK6, %xmm12 .set BLK7, %xmm13 .set BLK8, %xmm0 .set BLK9, %xmm2 .set BLK10, %xmm7 .set BLK11, %xmm8 .set BLK12, %xmm9 .set BLK13, %xmm14 /** * Function description: Sets the AES encryption assembly acceleration API in ECB mode. * Function prototype: int32_t CRYPT_AES_ECB_Encrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, uint8_t *out, uint32_t len); * Input register: * x0: Pointer to the input key structure. * x1: Points to the 128-bit input data. * x2: Points to the 128-bit output data. * x3: Indicates the length of a data block, that is, 16 bytes. * Change register: xmm1,xmm3,xmm4,xmm5,xmm6,xmm10,xmm11,xmm12,xmm13. * Output register: eax. * Function/Macro Call: None. */ .globl CRYPT_AES_ECB_Encrypt .type CRYPT_AES_ECB_Encrypt, @function CRYPT_AES_ECB_Encrypt: .cfi_startproc .align 16 .Lecb_aesenc_start: cmpl $64, ARG4 jae .Lecb_enc_above_equal_4_blks cmpl $32, ARG4 jae .Lecb_enc_above_equal_2_blks cmpl $0, ARG4 je .Lecb_aesdec_finish jmp .Lecb_enc_proc_1_blk .Lecb_enc_above_equal_2_blks: cmpl $48, ARG4 jb .Lecb_enc_proc_2_blks jmp .Lecb_enc_proc_3_blks .Lecb_enc_above_equal_4_blks: cmpl $96, ARG4 jae .Lecb_enc_above_equal_6_blks cmpl $80, ARG4 jb .Lecb_enc_proc_4_blks jmp .Lecb_enc_proc_5_blks .Lecb_enc_above_equal_6_blks: cmpl $112, ARG4 jb .Lecb_enc_proc_6_blks cmpl $128, ARG4 jb .Lecb_enc_proc_7_blks cmpl $256, ARG4 jbe .Lecb_enc_proc_8_blks .align 16 .ecb_enc_proc_14_blks: .Lecb_aesenc_14_blks_loop: movq KEY, KTMP vmovdqu (KEY), RDK movl 240(KEY), ROUNDS vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 vpxor 96(ARG2), RDK, BLK6 vpxor 112(ARG2), RDK, BLK7 vpxor 128(ARG2), RDK, BLK8 vpxor 144(ARG2), RDK, BLK9 vpxor 160(ARG2), RDK, BLK10 vpxor 176(ARG2), RDK, BLK11 vpxor 192(ARG2), RDK, BLK12 vpxor 208(ARG2), RDK, BLK13 decl ROUNDS AES_ENC_14_BLKS ARG2 KTMP ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 BLK6 BLK7 BLK8 BLK9 BLK10 BLK11 BLK12 BLK13 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) vmovdqu BLK6, 96(ARG3) vmovdqu BLK7, 112(ARG3) vmovdqu BLK8, 128(ARG3) vmovdqu BLK9, 144(ARG3) vmovdqu BLK10, 160(ARG3) vmovdqu BLK11, 176(ARG3) vmovdqu BLK12, 192(ARG3) vmovdqu BLK13, 208(ARG3) leaq 224(ARG2), ARG2 leaq 224(ARG3), ARG3 subl $224, ARG4 cmpl $224, ARG4 jb .Lecb_aesenc_start jmp .Lecb_aesenc_14_blks_loop .align 16 .Lecb_enc_proc_8_blks: .Lecb_aesenc_8_blks_loop: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK movq KEY, KTMP vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 vpxor 96(ARG2), RDK, BLK6 vpxor 112(ARG2), RDK, BLK7 decl ROUNDS AES_ENC_8_BLKS KTMP ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 BLK6 BLK7 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) vmovdqu BLK6, 96(ARG3) vmovdqu BLK7, 112(ARG3) leaq 128(ARG2), ARG2 leaq 128(ARG3), ARG3 subl $128, ARG4 cmpl $128, ARG4 jb .Lecb_aesenc_start jmp .Lecb_aesenc_8_blks_loop .align 16 .Lecb_enc_proc_1_blk: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 decl ROUNDS AES_ENC_1_BLK KEY ROUNDS RDK BLK0 vmovdqu BLK0, (ARG3) jmp .Lecb_aesenc_finish .align 16 .Lecb_enc_proc_2_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 decl ROUNDS AES_ENC_2_BLKS KEY ROUNDS RDK BLK0 BLK1 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) jmp .Lecb_aesenc_finish .align 16 .Lecb_enc_proc_3_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 decl ROUNDS AES_ENC_3_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) jmp .Lecb_aesenc_finish .align 16 .Lecb_enc_proc_4_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 decl ROUNDS AES_ENC_4_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) jmp .Lecb_aesenc_finish .align 16 .Lecb_enc_proc_5_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 decl ROUNDS AES_ENC_5_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) jmp .Lecb_aesenc_finish .align 16 .Lecb_enc_proc_6_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 decl ROUNDS AES_ENC_6_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) jmp .Lecb_aesenc_finish .align 16 .Lecb_enc_proc_7_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 vpxor 96(ARG2), RDK, BLK6 decl ROUNDS AES_ENC_7_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 BLK6 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) vmovdqu BLK6, 96(ARG3) .align 16 .Lecb_aesenc_finish: vpxor RDK, RDK, RDK movl $0, RET ret .cfi_endproc .size CRYPT_AES_ECB_Encrypt, .-CRYPT_AES_ECB_Encrypt /** * Function description: Sets the AES decryption and assembly acceleration API in ECB mode. * Function prototype: int32_t CRYPT_AES_ECB_Decrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, uint8_t *out, uint32_t len); * Input register: * x0: Pointer to the input key structure. * x1: Points to the 128-bit input data. * x2: Indicates the 128-bit output data. * x3: Indicates the length of a data block, that is, 16 bytes. * Change register: xmm1,xmm3,xmm4,xmm5,xmm6,xmm10,xmm11,xmm12,xmm13. * Output register: eax. * Function/Macro Call: None. */ .globl CRYPT_AES_ECB_Decrypt .type CRYPT_AES_ECB_Decrypt, @function CRYPT_AES_ECB_Decrypt: .cfi_startproc .align 16 .ecb_aesdec_start: cmpl $64, ARG4 jae .ecb_dec_above_equal_4_blks cmpl $32, ARG4 jae .ecb_dec_above_equal_2_blks cmpl $0, ARG4 je .Lecb_aesdec_finish jmp .ecb_dec_proc_1_blk .ecb_dec_above_equal_2_blks: cmpl $48, ARG4 jb .ecb_dec_proc_2_blks jmp .ecb_dec_proc_3_blks .ecb_dec_above_equal_4_blks: cmpl $96, ARG4 jae .ecb_dec_above_equal_6_blks cmpl $80, ARG4 jb .ecb_dec_proc_4_blks jmp .ecb_dec_proc_5_blks .ecb_dec_above_equal_6_blks: cmpl $112, ARG4 jb .ecb_dec_proc_6_blks cmpl $128, ARG4 jb .ecb_dec_proc_7_blks cmpl $256, ARG4 jbe .ecb_dec_proc_8_blks .align 16 .ecb_dec_proc_14_blks: .ecb_aesdec_14_blks_loop: movq KEY, KTMP movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 vpxor 96(ARG2), RDK, BLK6 vpxor 112(ARG2), RDK, BLK7 vpxor 128(ARG2), RDK, BLK8 vpxor 144(ARG2), RDK, BLK9 vpxor 160(ARG2), RDK, BLK10 vpxor 176(ARG2), RDK, BLK11 vpxor 192(ARG2), RDK, BLK12 vpxor 208(ARG2), RDK, BLK13 decl ROUNDS AES_DEC_14_BLKS KTMP ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 BLK6 BLK7 BLK8 BLK9 BLK10 BLK11 BLK12 BLK13 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) vmovdqu BLK6, 96(ARG3) vmovdqu BLK7, 112(ARG3) vmovdqu BLK8, 128(ARG3) vmovdqu BLK9, 144(ARG3) vmovdqu BLK10, 160(ARG3) vmovdqu BLK11, 176(ARG3) vmovdqu BLK12, 192(ARG3) vmovdqu BLK13, 208(ARG3) leaq 224(ARG2), ARG2 leaq 224(ARG3), ARG3 subl $224, ARG4 cmpl $224, ARG4 jb .ecb_aesdec_start jmp .ecb_aesdec_14_blks_loop .align 16 .ecb_dec_proc_8_blks: .aesecbdec_8_blks_loop: movq KEY, KTMP movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 vpxor 96(ARG2), RDK, BLK6 vpxor 112(ARG2), RDK, BLK7 decl ROUNDS AES_DEC_8_BLKS KTMP ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 BLK6 BLK7 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) vmovdqu BLK6, 96(ARG3) vmovdqu BLK7, 112(ARG3) leaq 128(ARG2), ARG2 leaq 128(ARG3), ARG3 subl $128, ARG4 cmpl $128, ARG4 jb .ecb_aesdec_start jmp .aesecbdec_8_blks_loop .align 16 .ecb_dec_proc_1_blk: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 decl ROUNDS AES_DEC_1_BLK KEY ROUNDS RDK BLK0 vmovdqu BLK0, (ARG3) jmp .Lecb_aesdec_finish .align 16 .ecb_dec_proc_2_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 decl ROUNDS AES_DEC_2_BLKS KEY ROUNDS RDK BLK0 BLK1 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) jmp .Lecb_aesdec_finish .align 16 .ecb_dec_proc_3_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 decl ROUNDS AES_DEC_3_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) jmp .Lecb_aesdec_finish .align 16 .ecb_dec_proc_4_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 decl ROUNDS AES_DEC_4_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) jmp .Lecb_aesdec_finish .align 16 .ecb_dec_proc_5_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 decl ROUNDS AES_DEC_5_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) jmp .Lecb_aesdec_finish .align 16 .ecb_dec_proc_6_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 decl ROUNDS AES_DEC_6_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) jmp .Lecb_aesdec_finish .align 16 .ecb_dec_proc_7_blks: movl 240(KEY), ROUNDS vmovdqu (KEY), RDK vpxor (ARG2), RDK, BLK0 vpxor 16(ARG2), RDK, BLK1 vpxor 32(ARG2), RDK, BLK2 vpxor 48(ARG2), RDK, BLK3 vpxor 64(ARG2), RDK, BLK4 vpxor 80(ARG2), RDK, BLK5 vpxor 96(ARG2), RDK, BLK6 decl ROUNDS AES_DEC_7_BLKS KEY ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 BLK5 BLK6 vmovdqu BLK0, (ARG3) vmovdqu BLK1, 16(ARG3) vmovdqu BLK2, 32(ARG3) vmovdqu BLK3, 48(ARG3) vmovdqu BLK4, 64(ARG3) vmovdqu BLK5, 80(ARG3) vmovdqu BLK6, 96(ARG3) .align 16 .Lecb_aesdec_finish: vpxor BLK0, BLK0, BLK0 vpxor BLK1, BLK1, BLK1 vpxor BLK2, BLK2, BLK2 vpxor BLK3, BLK3, BLK3 vpxor BLK4, BLK4, BLK4 vpxor BLK5, BLK5, BLK5 vpxor BLK6, BLK6, BLK6 vpxor BLK7, BLK7, BLK7 vpxor BLK8, BLK8, BLK8 vpxor BLK9, BLK9, BLK9 vpxor BLK10, BLK10, BLK10 vpxor BLK11, BLK11, BLK11 vpxor BLK12, BLK12, BLK12 vpxor BLK13, BLK13, BLK13 vpxor RDK, RDK, RDK movl $0, RET ret .cfi_endproc .size CRYPT_AES_ECB_Decrypt, .-CRYPT_AES_ECB_Decrypt #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_ecb_x86_64.S
Unix Assembly
unknown
14,681
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_AES .file "crypt_aes_macro_armv8.s" .text .arch armv8-a+crypto BLK0 .req v0 /* * AES_ENC_1_BLKS */ .macro AES_ENC_1_BLK key blk rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_enc: aese \blk,\rdk0 aesmc \blk,\blk subs \rounds,\rounds,#2 ld1 {\rdk0s},[\key],#16 aese \blk,\rdk1 aesmc \blk,\blk ld1 {\rdk1s},[\key],#16 b.gt .Loop_enc aese \blk,\rdk0 aesmc \blk,\blk ld1 {\rdk0s},[\key] aese \blk,\rdk1 eor \blk,\blk,\rdk0 .endm /* * AES_DEC_1_BLKS */ .macro AES_DEC_1_BLK key blk rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_dec: aesd \blk,\rdk0 aesimc \blk,\blk subs \rounds,\rounds,#2 ld1 {\rdk0s},[\key],#16 aesd \blk,\rdk1 aesimc \blk,\blk ld1 {\rdk1s},[\key],#16 b.gt .Loop_dec aesd \blk,\rdk0 aesimc \blk,\blk ld1 {\rdk0s},[\key] aesd \blk,\rdk1 eor \blk,\blk,\rdk0 .endm .macro SETDECKEY_LDR_9_BLOCK PTR ld1 {v1.4s}, [\PTR], #16 ld1 {v2.4s}, [\PTR], #16 ld1 {v3.4s}, [\PTR], #16 ld1 {v4.4s}, [\PTR], #16 ld1 {v5.4s}, [\PTR], #16 ld1 {v6.4s}, [\PTR], #16 ld1 {v7.4s}, [\PTR], #16 ld1 {v8.4s}, [\PTR], #16 ld1 {v9.4s}, [\PTR], #16 .endm .macro SETDECKEY_INVMIX_9_BLOCK aesimc v1.16b, v1.16b aesimc v2.16b, v2.16b aesimc v3.16b, v3.16b aesimc v4.16b, v4.16b aesimc v5.16b, v5.16b aesimc v6.16b, v6.16b aesimc v7.16b, v7.16b aesimc v8.16b, v8.16b aesimc v9.16b, v9.16b .endm .macro SETDECKEY_STR_9_BLOCK PTR OFFSETREG st1 {v1.4s}, [\PTR], \OFFSETREG st1 {v2.4s}, [\PTR], \OFFSETREG st1 {v3.4s}, [\PTR], \OFFSETREG st1 {v4.4s}, [\PTR], \OFFSETREG st1 {v5.4s}, [\PTR], \OFFSETREG st1 {v6.4s}, [\PTR], \OFFSETREG st1 {v7.4s}, [\PTR], \OFFSETREG st1 {v8.4s}, [\PTR], \OFFSETREG st1 {v9.4s}, [\PTR], \OFFSETREG .endm /* * AES_ENC_2_BLKS */ .macro AES_ENC_2_BLKS key blk0 blk1 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_enc_2_blks: aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk0,\rdk1 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk1,\rdk1 aesmc \blk1,\blk1 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_enc_2_blks aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 ld1 {\rdk0s},[\key] aese \blk0,\rdk1 aese \blk1,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 .endm /* * AES_ENC_3_BLKS */ .macro AES_ENC_3_BLKS key blk0 blk1 blk2 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .align 3 .Loop_enc_3_blks: aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk0,\rdk1 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk1,\rdk1 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk2,\rdk1 aesmc \blk2,\blk2 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_enc_3_blks aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 ld1 {\rdk0s},[\key] aese \blk0,\rdk1 aese \blk1,\rdk1 aese \blk2,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 .endm /* * AES_ENC_4_BLKS */ .macro AES_ENC_4_BLKS key blk0 blk1 blk2 blk3 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_enc_4_blks: aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk0,\rdk1 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk1,\rdk1 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk2,\rdk1 aesmc \blk2,\blk2 aese \blk3,\rdk0 aesmc \blk3,\blk3 aese \blk3,\rdk1 aesmc \blk3,\blk3 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_enc_4_blks aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk3,\rdk0 aesmc \blk3,\blk3 ld1 {\rdk0s},[\key] aese \blk0,\rdk1 aese \blk1,\rdk1 aese \blk2,\rdk1 aese \blk3,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 eor \blk3,\blk3,\rdk0 .endm /* * AES_ENC_5_BLKS */ .macro AES_ENC_5_BLKS key blk0 blk1 blk2 blk3 blk4 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_enc_5_blks: aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk3,\rdk0 aesmc \blk3,\blk3 aese \blk4,\rdk0 aesmc \blk4,\blk4 ld1 {\rdk0s},[\key],#16 subs \rounds,\rounds,#2 aese \blk0,\rdk1 aesmc \blk0,\blk0 aese \blk1,\rdk1 aesmc \blk1,\blk1 aese \blk2,\rdk1 aesmc \blk2,\blk2 aese \blk3,\rdk1 aesmc \blk3,\blk3 aese \blk4,\rdk1 aesmc \blk4,\blk4 ld1 {\rdk1s},[\key],#16 b.gt .Loop_enc_5_blks aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk3,\rdk0 aesmc \blk3,\blk3 aese \blk4,\rdk0 aesmc \blk4,\blk4 ld1 {\rdk0s},[\key] aese \blk0,\rdk1 aese \blk1,\rdk1 aese \blk2,\rdk1 aese \blk3,\rdk1 aese \blk4,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 eor \blk3,\blk3,\rdk0 eor \blk4,\blk4,\rdk0 .endm /* * AES_ENC_6_BLKS */ .macro AES_ENC_6_BLKS key blk0 blk1 blk2 blk3 blk4 blk5 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_enc_6_blks: aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk0,\rdk1 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk1,\rdk1 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk2,\rdk1 aesmc \blk2,\blk2 aese \blk3,\rdk0 aesmc \blk3,\blk3 aese \blk3,\rdk1 aesmc \blk3,\blk3 aese \blk4,\rdk0 aesmc \blk4,\blk4 aese \blk4,\rdk1 aesmc \blk4,\blk4 aese \blk5,\rdk0 aesmc \blk5,\blk5 aese \blk5,\rdk1 aesmc \blk5,\blk5 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_enc_6_blks aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk3,\rdk0 aesmc \blk3,\blk3 aese \blk4,\rdk0 aesmc \blk4,\blk4 aese \blk5,\rdk0 aesmc \blk5,\blk5 ld1 {\rdk0s},[\key] aese \blk0,\rdk1 aese \blk1,\rdk1 aese \blk2,\rdk1 aese \blk3,\rdk1 aese \blk4,\rdk1 aese \blk5,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 eor \blk3,\blk3,\rdk0 eor \blk4,\blk4,\rdk0 eor \blk5,\blk5,\rdk0 .endm /* * AES_ENC_7_BLKS */ .macro AES_ENC_7_BLKS key blk0 blk1 blk2 blk3 blk4 blk5 blk6 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_enc_7_blks: aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk0,\rdk1 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk1,\rdk1 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk2,\rdk1 aesmc \blk2,\blk2 aese \blk3,\rdk0 aesmc \blk3,\blk3 aese \blk3,\rdk1 aesmc \blk3,\blk3 aese \blk4,\rdk0 aesmc \blk4,\blk4 aese \blk4,\rdk1 aesmc \blk4,\blk4 aese \blk5,\rdk0 aesmc \blk5,\blk5 aese \blk5,\rdk1 aesmc \blk5,\blk5 aese \blk6,\rdk0 aesmc \blk6,\blk6 aese \blk6,\rdk1 aesmc \blk6,\blk6 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_enc_7_blks aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk3,\rdk0 aesmc \blk3,\blk3 aese \blk4,\rdk0 aesmc \blk4,\blk4 aese \blk5,\rdk0 aesmc \blk5,\blk5 aese \blk6,\rdk0 aesmc \blk6,\blk6 ld1 {\rdk0s},[\key] aese \blk0,\rdk1 aese \blk1,\rdk1 aese \blk2,\rdk1 aese \blk3,\rdk1 aese \blk4,\rdk1 aese \blk5,\rdk1 aese \blk6,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 eor \blk3,\blk3,\rdk0 eor \blk4,\blk4,\rdk0 eor \blk5,\blk5,\rdk0 eor \blk6,\blk6,\rdk0 .endm /* * AES_ENC_8_BLKS */ .macro AES_ENC_8_BLKS key blk0 blk1 blk2 blk3 blk4 blk5 blk6 blk7 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_enc_8_blks: aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk0,\rdk1 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk1,\rdk1 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk2,\rdk1 aesmc \blk2,\blk2 aese \blk3,\rdk0 aesmc \blk3,\blk3 aese \blk3,\rdk1 aesmc \blk3,\blk3 aese \blk4,\rdk0 aesmc \blk4,\blk4 aese \blk4,\rdk1 aesmc \blk4,\blk4 aese \blk5,\rdk0 aesmc \blk5,\blk5 aese \blk5,\rdk1 aesmc \blk5,\blk5 aese \blk6,\rdk0 aesmc \blk6,\blk6 aese \blk6,\rdk1 aesmc \blk6,\blk6 aese \blk7,\rdk0 aesmc \blk7,\blk7 aese \blk7,\rdk1 aesmc \blk7,\blk7 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_enc_8_blks aese \blk0,\rdk0 aesmc \blk0,\blk0 aese \blk1,\rdk0 aesmc \blk1,\blk1 aese \blk2,\rdk0 aesmc \blk2,\blk2 aese \blk3,\rdk0 aesmc \blk3,\blk3 aese \blk4,\rdk0 aesmc \blk4,\blk4 aese \blk5,\rdk0 aesmc \blk5,\blk5 aese \blk6,\rdk0 aesmc \blk6,\blk6 aese \blk7,\rdk0 aesmc \blk7,\blk7 ld1 {\rdk0s},[\key] aese \blk0,\rdk1 aese \blk1,\rdk1 aese \blk2,\rdk1 aese \blk3,\rdk1 aese \blk4,\rdk1 aese \blk5,\rdk1 aese \blk6,\rdk1 aese \blk7,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 eor \blk3,\blk3,\rdk0 eor \blk4,\blk4,\rdk0 eor \blk5,\blk5,\rdk0 eor \blk6,\blk6,\rdk0 eor \blk7,\blk7,\rdk0 .endm /* * AES_DEC_2_BLKS */ .macro AES_DEC_2_BLKS key blk0 blk1 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_dec_2_blks: aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk0,\rdk1 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk1,\rdk1 aesimc \blk1,\blk1 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_dec_2_blks aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 ld1 {\rdk0s},[\key] aesd \blk0,\rdk1 aesd \blk1,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 .endm /* * AES_DEC_3_BLKS */ .macro AES_DEC_3_BLKS key blk0 blk1 blk2 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .align 3 .Loop_dec_3_blks: aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk0,\rdk1 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk1,\rdk1 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk2,\rdk1 aesimc \blk2,\blk2 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_dec_3_blks aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 ld1 {\rdk0s},[\key] aesd \blk0,\rdk1 aesd \blk1,\rdk1 aesd \blk2,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 .endm /* * AES_DEC_4_BLKS */ .macro AES_DEC_4_BLKS key blk0 blk1 blk2 blk3 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_dec_4_blks: aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk0,\rdk1 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk1,\rdk1 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk2,\rdk1 aesimc \blk2,\blk2 aesd \blk3,\rdk0 aesimc \blk3,\blk3 aesd \blk3,\rdk1 aesimc \blk3,\blk3 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_dec_4_blks aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk3,\rdk0 aesimc \blk3,\blk3 ld1 {\rdk0s},[\key] aesd \blk0,\rdk1 aesd \blk1,\rdk1 aesd \blk2,\rdk1 aesd \blk3,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 eor \blk3,\blk3,\rdk0 .endm /* * AES_DEC_5_BLKS */ .macro AES_DEC_5_BLKS key blk0 blk1 blk2 blk3 blk4 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_dec_5_blks: aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk0,\rdk1 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk1,\rdk1 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk2,\rdk1 aesimc \blk2,\blk2 aesd \blk3,\rdk0 aesimc \blk3,\blk3 aesd \blk3,\rdk1 aesimc \blk3,\blk3 aesd \blk4,\rdk0 aesimc \blk4,\blk4 aesd \blk4,\rdk1 aesimc \blk4,\blk4 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_dec_5_blks aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk3,\rdk0 aesimc \blk3,\blk3 aesd \blk4,\rdk0 aesimc \blk4,\blk4 ld1 {\rdk0s},[\key] aesd \blk0,\rdk1 aesd \blk1,\rdk1 aesd \blk2,\rdk1 aesd \blk3,\rdk1 aesd \blk4,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 eor \blk3,\blk3,\rdk0 eor \blk4,\blk4,\rdk0 .endm /* * AES_DEC_6_BLKS */ .macro AES_DEC_6_BLKS key blk0 blk1 blk2 blk3 blk4 blk5 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_dec_6_blks: aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk0,\rdk1 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk1,\rdk1 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk2,\rdk1 aesimc \blk2,\blk2 aesd \blk3,\rdk0 aesimc \blk3,\blk3 aesd \blk3,\rdk1 aesimc \blk3,\blk3 aesd \blk4,\rdk0 aesimc \blk4,\blk4 aesd \blk4,\rdk1 aesimc \blk4,\blk4 aesd \blk5,\rdk0 aesimc \blk5,\blk5 aesd \blk5,\rdk1 aesimc \blk5,\blk5 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_dec_6_blks aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk3,\rdk0 aesimc \blk3,\blk3 aesd \blk4,\rdk0 aesimc \blk4,\blk4 aesd \blk5,\rdk0 aesimc \blk5,\blk5 ld1 {\rdk0s},[\key] aesd \blk0,\rdk1 aesd \blk1,\rdk1 aesd \blk2,\rdk1 aesd \blk3,\rdk1 aesd \blk4,\rdk1 aesd \blk5,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 eor \blk3,\blk3,\rdk0 eor \blk4,\blk4,\rdk0 eor \blk5,\blk5,\rdk0 .endm /* * AES_DEC_7_BLKS */ .macro AES_DEC_7_BLKS key blk0 blk1 blk2 blk3 blk4 blk5 blk6 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .Loop_dec_7_blks: aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk0,\rdk1 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk1,\rdk1 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk2,\rdk1 aesimc \blk2,\blk2 aesd \blk3,\rdk0 aesimc \blk3,\blk3 aesd \blk3,\rdk1 aesimc \blk3,\blk3 aesd \blk4,\rdk0 aesimc \blk4,\blk4 aesd \blk4,\rdk1 aesimc \blk4,\blk4 aesd \blk5,\rdk0 aesimc \blk5,\blk5 aesd \blk5,\rdk1 aesimc \blk5,\blk5 aesd \blk6,\rdk0 aesimc \blk6,\blk6 aesd \blk6,\rdk1 aesimc \blk6,\blk6 ld1 {\rdk0s,\rdk1s},[\key],#32 subs \rounds,\rounds,#2 b.gt .Loop_dec_7_blks aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk3,\rdk0 aesimc \blk3,\blk3 aesd \blk4,\rdk0 aesimc \blk4,\blk4 aesd \blk5,\rdk0 aesimc \blk5,\blk5 aesd \blk6,\rdk0 aesimc \blk6,\blk6 ld1 {\rdk0s},[\key] aesd \blk0,\rdk1 aesd \blk1,\rdk1 aesd \blk2,\rdk1 aesd \blk3,\rdk1 aesd \blk4,\rdk1 aesd \blk5,\rdk1 aesd \blk6,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 eor \blk3,\blk3,\rdk0 eor \blk4,\blk4,\rdk0 eor \blk5,\blk5,\rdk0 eor \blk6,\blk6,\rdk0 .endm /* * AES_DEC_8_BLKS */ .macro AES_DEC_8_BLKS key blk0 blk1 blk2 blk3 blk4 blk5 blk6 blk7 rdk0s rdk1s rdk0 rdk1 rounds ldr \rounds,[\key,#240] ld1 {\rdk0s,\rdk1s},[\key],#32 sub \rounds,\rounds,#2 .align 5 .Loop_dec_8_blks: aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk5,\rdk0 aesimc \blk5,\blk5 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk6,\rdk0 aesimc \blk6,\blk6 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk3,\rdk0 aesimc \blk3,\blk3 aesd \blk4,\rdk0 aesimc \blk4,\blk4 aesd \blk7,\rdk0 aesimc \blk7,\blk7 aesd \blk0,\rdk1 aesimc \blk0,\blk0 aesd \blk5,\rdk1 aesimc \blk5,\blk5 aesd \blk1,\rdk1 aesimc \blk1,\blk1 aesd \blk6,\rdk1 aesimc \blk6,\blk6 aesd \blk2,\rdk1 aesimc \blk2,\blk2 aesd \blk3,\rdk1 aesimc \blk3,\blk3 aesd \blk4,\rdk1 aesimc \blk4,\blk4 aesd \blk7,\rdk1 ld1 {\rdk0s, \rdk1s},[\key],#32 aesimc \blk7,\blk7 subs \rounds,\rounds,#2 b.gt .Loop_dec_8_blks aesd \blk0,\rdk0 aesimc \blk0,\blk0 aesd \blk1,\rdk0 aesimc \blk1,\blk1 aesd \blk2,\rdk0 aesimc \blk2,\blk2 aesd \blk3,\rdk0 aesimc \blk3,\blk3 aesd \blk4,\rdk0 aesimc \blk4,\blk4 aesd \blk5,\rdk0 aesimc \blk5,\blk5 aesd \blk6,\rdk0 aesimc \blk6,\blk6 aesd \blk7,\rdk0 ld1 {\rdk0s},[\key] aesimc \blk7,\blk7 aesd \blk0,\rdk1 aesd \blk1,\rdk1 aesd \blk2,\rdk1 aesd \blk3,\rdk1 aesd \blk4,\rdk1 aesd \blk5,\rdk1 aesd \blk6,\rdk1 aesd \blk7,\rdk1 eor \blk0,\blk0,\rdk0 eor \blk1,\blk1,\rdk0 eor \blk2,\blk2,\rdk0 eor \blk3,\blk3,\rdk0 eor \blk4,\blk4,\rdk0 eor \blk5,\blk5,\rdk0 eor \blk6,\blk6,\rdk0 eor \blk7,\blk7,\rdk0 .endm #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_macro_armv8.s
Unix Assembly
unknown
19,831
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_AES .file "crypt_aes_macro_x86_64.s" /* AES_ENC_1_BLK */ .macro AES_ENC_1_BLK key round rdk blk .align 16 .Laesenc_loop: leaq 16(\key), \key movdqu (\key), \rdk aesenc \rdk, \blk decl \round jnz .Laesenc_loop leaq 16(\key), \key movdqu (\key), \rdk aesenclast \rdk, \blk .endm /* AES_ENC_2_BLKS */ .macro AES_ENC_2_BLKS key round rdk blk0 blk1 .align 16 .Laesenc_2_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesenc \rdk, \blk0 aesenc \rdk, \blk1 decl \round jnz .Laesenc_2_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesenclast \rdk, \blk0 aesenclast \rdk, \blk1 .endm /* AES_ENC_3_BLKS */ .macro AES_ENC_3_BLKS key round rdk blk0 blk1 blk2 .align 16 .Laesenc_3_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesenc \rdk, \blk0 aesenc \rdk, \blk1 aesenc \rdk, \blk2 decl \round jnz .Laesenc_3_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesenclast \rdk, \blk0 aesenclast \rdk, \blk1 aesenclast \rdk, \blk2 .endm /* AES_ENC_4_BLKS */ .macro AES_ENC_4_BLKS key round rdk blk0 blk1 blk2 blk3 .align 16 .Laesenc_4_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesenc \rdk, \blk0 aesenc \rdk, \blk1 aesenc \rdk, \blk2 aesenc \rdk, \blk3 decl \round jnz .Laesenc_4_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesenclast \rdk, \blk0 aesenclast \rdk, \blk1 aesenclast \rdk, \blk2 aesenclast \rdk, \blk3 .endm /* AES_ENC_5_BLKS */ .macro AES_ENC_5_BLKS key round rdk blk0 blk1 blk2 blk3 blk4 .align 16 .Laesenc_5_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesenc \rdk, \blk0 aesenc \rdk, \blk1 aesenc \rdk, \blk2 aesenc \rdk, \blk3 aesenc \rdk, \blk4 decl \round jnz .Laesenc_5_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesenclast \rdk, \blk0 aesenclast \rdk, \blk1 aesenclast \rdk, \blk2 aesenclast \rdk, \blk3 aesenclast \rdk, \blk4 .endm /* AES_ENC_6_BLKS */ .macro AES_ENC_6_BLKS key round rdk blk0 blk1 blk2 blk3 blk4 blk5 .align 16 .Laesenc_6_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesenc \rdk, \blk0 aesenc \rdk, \blk1 aesenc \rdk, \blk2 aesenc \rdk, \blk3 aesenc \rdk, \blk4 aesenc \rdk, \blk5 decl \round jnz .Laesenc_6_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesenclast \rdk, \blk0 aesenclast \rdk, \blk1 aesenclast \rdk, \blk2 aesenclast \rdk, \blk3 aesenclast \rdk, \blk4 aesenclast \rdk, \blk5 .endm /* AES_ENC_7_BLKS */ .macro AES_ENC_7_BLKS key round rdk blk0 blk1 blk2 blk3 blk4 blk5 blk6 .align 16 .Laesenc_7_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesenc \rdk, \blk0 aesenc \rdk, \blk1 aesenc \rdk, \blk2 aesenc \rdk, \blk3 aesenc \rdk, \blk4 aesenc \rdk, \blk5 aesenc \rdk, \blk6 decl \round jnz .Laesenc_7_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesenclast \rdk, \blk0 aesenclast \rdk, \blk1 aesenclast \rdk, \blk2 aesenclast \rdk, \blk3 aesenclast \rdk, \blk4 aesenclast \rdk, \blk5 aesenclast \rdk, \blk6 .endm /* AES_ENC_8_BLKS */ .macro AES_ENC_8_BLKS key round rdk blk0 blk1 blk2 blk3 blk4 blk5 blk6 blk7 .align 16 .Laesenc_8_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesenc \rdk, \blk0 aesenc \rdk, \blk1 aesenc \rdk, \blk2 aesenc \rdk, \blk3 aesenc \rdk, \blk4 aesenc \rdk, \blk5 aesenc \rdk, \blk6 aesenc \rdk, \blk7 decl \round jnz .Laesenc_8_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesenclast \rdk, \blk0 aesenclast \rdk, \blk1 aesenclast \rdk, \blk2 aesenclast \rdk, \blk3 aesenclast \rdk, \blk4 aesenclast \rdk, \blk5 aesenclast \rdk, \blk6 aesenclast \rdk, \blk7 .endm /* AES_ENC_14_BLKS */ .macro AES_ENC_14_BLKS ARG2 key round rdk blk0 blk1 blk2 blk3 blk4 blk5 blk6 blk7 blk8 blk9 blk10 blk11 blk12 blk13 .align 16 .Laesenc_14_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesenc \rdk, \blk0 aesenc \rdk, \blk1 aesenc \rdk, \blk2 aesenc \rdk, \blk3 aesenc \rdk, \blk4 aesenc \rdk, \blk5 aesenc \rdk, \blk6 aesenc \rdk, \blk7 aesenc \rdk, \blk8 aesenc \rdk, \blk9 aesenc \rdk, \blk10 aesenc \rdk, \blk11 aesenc \rdk, \blk12 aesenc \rdk, \blk13 decl \round jnz .Laesenc_14_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesenclast \rdk, \blk0 aesenclast \rdk, \blk1 aesenclast \rdk, \blk2 aesenclast \rdk, \blk3 aesenclast \rdk, \blk4 aesenclast \rdk, \blk5 aesenclast \rdk, \blk6 aesenclast \rdk, \blk7 aesenclast \rdk, \blk8 aesenclast \rdk, \blk9 aesenclast \rdk, \blk10 aesenclast \rdk, \blk11 aesenclast \rdk, \blk12 aesenclast \rdk, \blk13 .endm /* AES_DEC_1_BLK */ .macro AES_DEC_1_BLK key round rdk blk .align 16 .Laesdec_loop: leaq 16(\key), \key movdqu (\key), \rdk aesdec \rdk, \blk decl \round jnz .Laesdec_loop leaq 16(\key), \key movdqu (\key), \rdk aesdeclast \rdk, \blk .endm /* AES_DEC_2_BLKS */ .macro AES_DEC_2_BLKS key round rdk blk0 blk1 .align 32 .Laesdec_2_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesdec \rdk, \blk0 aesdec \rdk, \blk1 decl \round jnz .Laesdec_2_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesdeclast \rdk, \blk0 aesdeclast \rdk, \blk1 .endm /* AES_DEC_3_BLKS */ .macro AES_DEC_3_BLKS key round rdk blk0 blk1 blk2 .align 16 .Laesdec_3_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesdec \rdk, \blk0 aesdec \rdk, \blk1 aesdec \rdk, \blk2 decl \round jnz .Laesdec_3_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesdeclast \rdk, \blk0 aesdeclast \rdk, \blk1 aesdeclast \rdk, \blk2 .endm /* AES_DEC_4_BLKS */ .macro AES_DEC_4_BLKS key round rdk blk0 blk1 blk2 blk3 .align 16 .Laesdec_4_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesdec \rdk, \blk0 aesdec \rdk, \blk1 aesdec \rdk, \blk2 aesdec \rdk, \blk3 decl \round jnz .Laesdec_4_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesdeclast \rdk, \blk0 aesdeclast \rdk, \blk1 aesdeclast \rdk, \blk2 aesdeclast \rdk, \blk3 .endm /* AES_DEC_5_BLKS */ .macro AES_DEC_5_BLKS key round rdk blk0 blk1 blk2 blk3 blk4 .align 16 .Laesdec_5_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesdec \rdk, \blk0 aesdec \rdk, \blk1 aesdec \rdk, \blk2 aesdec \rdk, \blk3 aesdec \rdk, \blk4 decl \round jnz .Laesdec_5_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesdeclast \rdk, \blk0 aesdeclast \rdk, \blk1 aesdeclast \rdk, \blk2 aesdeclast \rdk, \blk3 aesdeclast \rdk, \blk4 .endm /* AES_DEC_6_BLKS */ .macro AES_DEC_6_BLKS key round rdk blk0 blk1 blk2 blk3 blk4 blk5 .align 16 .Laesdec_6_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesdec \rdk, \blk0 aesdec \rdk, \blk1 aesdec \rdk, \blk2 aesdec \rdk, \blk3 aesdec \rdk, \blk4 aesdec \rdk, \blk5 decl \round jnz .Laesdec_6_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesdeclast \rdk, \blk0 aesdeclast \rdk, \blk1 aesdeclast \rdk, \blk2 aesdeclast \rdk, \blk3 aesdeclast \rdk, \blk4 aesdeclast \rdk, \blk5 .endm /* AES_DEC_7_BLKS */ .macro AES_DEC_7_BLKS key round rdk blk0 blk1 blk2 blk3 blk4 blk5 blk6 .align 16 .Laesdec_7_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesdec \rdk, \blk0 aesdec \rdk, \blk1 aesdec \rdk, \blk2 aesdec \rdk, \blk3 aesdec \rdk, \blk4 aesdec \rdk, \blk5 aesdec \rdk, \blk6 decl \round jnz .Laesdec_7_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesdeclast \rdk, \blk0 aesdeclast \rdk, \blk1 aesdeclast \rdk, \blk2 aesdeclast \rdk, \blk3 aesdeclast \rdk, \blk4 aesdeclast \rdk, \blk5 aesdeclast \rdk, \blk6 .endm /* AES_DEC_8_BLKS */ .macro AES_DEC_8_BLKS key round rdk blk0 blk1 blk2 blk3 blk4 blk5 blk6 blk7 .align 16 .Laesdec_8_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesdec \rdk, \blk0 aesdec \rdk, \blk1 aesdec \rdk, \blk2 aesdec \rdk, \blk3 aesdec \rdk, \blk4 aesdec \rdk, \blk5 aesdec \rdk, \blk6 aesdec \rdk, \blk7 decl \round jnz .Laesdec_8_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesdeclast \rdk, \blk0 aesdeclast \rdk, \blk1 aesdeclast \rdk, \blk2 aesdeclast \rdk, \blk3 aesdeclast \rdk, \blk4 aesdeclast \rdk, \blk5 aesdeclast \rdk, \blk6 aesdeclast \rdk, \blk7 .endm /* AES_DEC_14_BLKS */ .macro AES_DEC_14_BLKS key round rdk blk0 blk1 blk2 blk3 blk4 blk5 blk6 blk7 blk8 blk9 blk10 blk11 blk12 blk13 .align 16 .Laesdec_14_blks_loop: leaq 16(\key), \key movdqu (\key), \rdk aesdec \rdk, \blk0 aesdec \rdk, \blk1 aesdec \rdk, \blk2 aesdec \rdk, \blk3 aesdec \rdk, \blk4 aesdec \rdk, \blk5 aesdec \rdk, \blk6 aesdec \rdk, \blk7 aesdec \rdk, \blk8 aesdec \rdk, \blk9 aesdec \rdk, \blk10 aesdec \rdk, \blk11 aesdec \rdk, \blk12 aesdec \rdk, \blk13 decl \round jnz .Laesdec_14_blks_loop leaq 16(\key), \key movdqu (\key), \rdk aesdeclast \rdk, \blk0 aesdeclast \rdk, \blk1 aesdeclast \rdk, \blk2 aesdeclast \rdk, \blk3 aesdeclast \rdk, \blk4 aesdeclast \rdk, \blk5 aesdeclast \rdk, \blk6 aesdeclast \rdk, \blk7 aesdeclast \rdk, \blk8 aesdeclast \rdk, \blk9 aesdeclast \rdk, \blk10 aesdeclast \rdk, \blk11 aesdeclast \rdk, \blk12 aesdeclast \rdk, \blk13 .endm #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_macro_x86_64.s
Unix Assembly
unknown
10,609
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_AES #include "crypt_aes_macro_x86_64.s" .file "crypt_aes_x86_64.S" .text .set ARG1, %rdi .set ARG2, %rsi .set ARG3, %rdx .set ARG4, %rcx .set ARG5, %r8 .set ARG6, %r9 .set RET, %eax .set XM0, %xmm0 .set XM1, %xmm1 .set XM2, %xmm2 .set XM3, %xmm3 .set XM4, %xmm4 .set XM5, %xmm5 /** * aes128 macros for key extension processing. */ .macro KEY_EXPANSION_HELPER_128 xm0 xm1 xm2 vpermilps $0xff, \xm1, \xm1 vpslldq $4, \xm0, \xm2 vpxor \xm2, \xm0, \xm0 vpslldq $4, \xm2, \xm2 vpxor \xm2, \xm0, \xm0 vpslldq $4, \xm2, \xm2 vpxor \xm2, \xm0, \xm0 vpxor \xm1, \xm0, \xm0 .endm /** * aes192 macros for key extension processing. */ .macro KEY_EXPANSION_HELPER_192 xm1 xm3 vpslldq $4, \xm1, \xm3 vpxor \xm3, \xm1, \xm1 vpslldq $4, \xm3, \xm3 vpxor \xm3, \xm1, \xm1 vpslldq $4, \xm3, \xm3 vpxor \xm3, \xm1, \xm1 .endm /** * Function description: Sets the AES encryption key. Key length: 128 bits. * Function prototype: void SetEncryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key); * Input register: * x0:Pointer to the output key structure. * x1:Pointer to the input key. * Change register:xmm0-xmm2. * Output register:None. * Function/Macro Call: None. */ .globl SetEncryptKey128 .type SetEncryptKey128, @function SetEncryptKey128: .cfi_startproc movl $10, 240(%rdi) movdqu (ARG2), XM0 movdqu XM0, (ARG1) aeskeygenassist $0x01, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0, 16(ARG1) aeskeygenassist $0x02, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0, 32(ARG1) aeskeygenassist $0x04, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0, 48(ARG1) aeskeygenassist $0x08, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0, 64(ARG1) aeskeygenassist $0x10, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0, 80(ARG1) aeskeygenassist $0x20, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0, 96(ARG1) aeskeygenassist $0x40, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0, 112(ARG1) aeskeygenassist $0x80, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0, 128(ARG1) aeskeygenassist $0x1b, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0, 144(ARG1) aeskeygenassist $0x36, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0, 160(ARG1) vpxor XM0, XM0, XM0 vpxor XM1, XM1, XM1 vpxor XM2, XM2, XM2 ret .cfi_endproc .size SetEncryptKey128, .-SetEncryptKey128 /** * Function description: Sets the AES decryption key. Key length: 128 bits. * Function prototype: void SetDecryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key); * Input register: * x0:Pointer to the output key structure. * x1:Pointer to the input key. * Change register:xmm0-xmm3. * Output register: None. * Function/Macro Call: None. */ .globl SetDecryptKey128 .type SetDecryptKey128, @function SetDecryptKey128: .cfi_startproc movl $10, 240(%rdi) movdqu (ARG2), XM0 movdqu XM0, 160(ARG1) aeskeygenassist $0x01, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 aesimc XM0, XM3 movdqu XM3, 144(ARG1) aeskeygenassist $0x02, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 aesimc XM0, XM3 movdqu XM3, 128(ARG1) aeskeygenassist $0x04, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 aesimc XM0, XM3 movdqu XM3, 112(ARG1) aeskeygenassist $0x08, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 aesimc XM0, XM3 movdqu XM3, 96(ARG1) aeskeygenassist $0x10, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 aesimc XM0, XM3 movdqu XM3, 80(ARG1) aeskeygenassist $0x20, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 aesimc XM0, XM3 movdqu XM3, 64(ARG1) aeskeygenassist $0x40, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 aesimc XM0, XM3 movdqu XM3, 48(ARG1) aeskeygenassist $0x80, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 aesimc XM0, XM3 movdqu XM3, 32(ARG1) aeskeygenassist $0x1b, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 aesimc XM0, XM3 movdqu XM3, 16(ARG1) aeskeygenassist $0x36, XM0, XM1 KEY_EXPANSION_HELPER_128 XM0, XM1, XM2 movdqu XM0,(ARG1) vpxor XM0, XM0, XM0 vpxor XM1, XM1, XM1 vpxor XM2, XM2, XM2 vpxor XM3, XM3, XM3 ret .cfi_endproc .size SetDecryptKey128, .-SetDecryptKey128 /** * Function description: Sets the AES encryption key. Key length: 192 bits. * Function prototype: void SetEncryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key); * Input register: * x0:Pointer to the output key structure. * x1:Pointer to the input key. * Change register: xmm0-xmm4. * Output register: None. * Function/Macro Call: None. */ .globl SetEncryptKey192 .type SetEncryptKey192, @function SetEncryptKey192: .cfi_startproc movl $12, 240(ARG1) movdqu (ARG2), XM0 movdqu 8(ARG2), XM1 movdqu XM0,(ARG1) vpxor XM4, XM4, XM4 vshufps $0x40, XM0, XM4, XM2 aeskeygenassist $0x01, XM1, XM0 vshufps $0xf0, XM0, XM4, XM0 vpslldq $0x04, XM2, XM3 vpxor XM3, XM2, XM2 vpxor XM2, XM0, XM0 vshufps $0xee, XM0, XM1, XM0 movdqu XM0, 16(ARG1) movdqu XM1, XM2 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpermilps $0xff, XM0, XM3 vpxor XM3, XM2, XM2 movdqu XM2, 32(ARG1) vshufps $0x4e, XM2, XM0, XM1 aeskeygenassist $0x02, XM2, XM0 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM0, XM0 vpxor XM1, XM0, XM0 movdqu XM0, 48(ARG1) vshufps $0x4e, XM0, XM2, XM1 vpslldq $8, XM1, XM2 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpermilps $0xff, XM0, XM3 vpxor XM3, XM2, XM2 aeskeygenassist $0x04, XM2, XM3 vpermilps $0xff, XM3, XM3 vpsrldq $8, XM1, XM4 vpslldq $12, XM4, XM4 vpxor XM4, XM1, XM1 vpxor XM3, XM1, XM1 vshufps $0xee, XM1, XM2, XM2 movdqu XM2, 64(ARG1) vshufps $0x4e, XM2, XM0, XM1 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM2, XM0 vpxor XM1, XM0, XM0 movdqu XM0, 80(ARG1) vshufps $0x4e, XM0, XM2, XM1 aeskeygenassist $0x08, XM0, XM2 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM2, XM2 vpxor XM1, XM2, XM2 movdqu XM2, 96(ARG1) vshufps $0x4e, XM2, XM0, XM1 vpslldq $8, XM1, XM0 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpermilps $0xff, XM2, XM3 vpxor XM3, XM0, XM0 aeskeygenassist $0x10, XM0, XM3 vpermilps $0xff, XM3, XM3 vpsrldq $8, XM1, XM4 vpslldq $12, XM4, XM4 vpxor XM4, XM1, XM1 vpxor XM3, XM1, XM1 vshufps $0xee, XM1, XM0, XM0 movdqu XM0, 112(ARG1) vshufps $0x4e, XM0, XM2, XM1 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM0, XM2 vpxor XM1, XM2, XM2 movdqu XM2, 128(ARG1) vshufps $0x4e, XM2, XM0, XM1 aeskeygenassist $0x20, XM2, XM0 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM0, XM0 vpxor XM1, XM0, XM0 movdqu XM0, 144(ARG1) vshufps $0x4e, XM0, XM2, XM1 vpslldq $8, XM1, XM2 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpermilps $0xff, XM0, XM3 vpxor XM3, XM2, XM2 aeskeygenassist $0x40, XM2, XM3 vpermilps $0xff, XM3, XM3 vpsrldq $8, XM1, XM4 vpslldq $12, XM4, XM4 vpxor XM4, XM1, XM1 vpxor XM3, XM1, XM1 vshufps $0xee, XM1, XM2, XM2 movdqu XM2, 160(ARG1) vshufps $0x4e, XM2, XM0, XM1 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM2, XM0 vpxor XM1, XM0, XM0 movdqu XM0, 176(ARG1) vshufps $0x4e, XM0, XM2, XM1 aeskeygenassist $0x80, XM0, XM2 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM2, XM2 vpxor XM1, XM2, XM2 movdqu XM2, 192(ARG1) vpxor XM0, XM0, XM0 vpxor XM1, XM1, XM1 vpxor XM2, XM2, XM2 vpxor XM3, XM3, XM3 vpxor XM4, XM4, XM4 ret .cfi_endproc .size SetEncryptKey192, .-SetEncryptKey192 /** * Function description: Sets the AES decryption key. Key length: 192 bits. * Function prototype: void SetDecryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key); * Input register: * x0:Pointer to the output key structure. * x1:Pointer to the input key. * Change register: xmm0-xmm5 * Output register: None. * Function/Macro Call: None. */ .globl SetDecryptKey192 .type SetDecryptKey192, @function SetDecryptKey192: .cfi_startproc movl $12, 240(ARG1) movdqu (ARG2), XM0 movdqu 8(ARG2), XM1 movdqu XM0, 192(ARG1) vpxor XM4, XM4, XM4 vshufps $0x40, XM0, XM4, XM2 aeskeygenassist $0x01, XM1, XM0 vshufps $0xf0, XM0, XM4, XM0 vpslldq $0x04, XM2, XM3 vpxor XM3, XM2, XM2 vpxor XM2, XM0, XM0 vshufps $0xee, XM0, XM1, XM0 aesimc XM0, XM5 movdqu XM5, 176(ARG1) movdqu XM1, XM2 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpermilps $0xff, XM0, XM3 vpxor XM3, XM2, XM2 aesimc XM2, XM5 movdqu XM5, 160(ARG1) vshufps $0x4e, XM2, XM0, XM1 aeskeygenassist $0x02, XM2, XM0 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM0, XM0 vpxor XM1, XM0, XM0 aesimc XM0, XM5 movdqu XM5, 144(ARG1) vshufps $0x4e, XM0, XM2, XM1 vpslldq $8, XM1, XM2 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpermilps $0xff, XM0, XM3 vpxor XM3, XM2, XM2 aeskeygenassist $0x04, XM2, XM3 vpermilps $0xff, XM3, XM3 vpsrldq $8, XM1, XM4 vpslldq $12, XM4, XM4 vpxor XM4, XM1, XM1 vpxor XM3, XM1, XM1 vshufps $0xee, XM1, XM2, XM2 aesimc XM2, XM5 movdqu XM5, 128(ARG1) vshufps $0x4e, XM2, XM0, XM1 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM2, XM0 vpxor XM1, XM0, XM0 aesimc XM0, XM5 movdqu XM5,112(ARG1) vshufps $0x4e, XM0, XM2, XM1 aeskeygenassist $0x08, XM0, XM2 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM2, XM2 vpxor XM1, XM2, XM2 aesimc XM2, XM5 movdqu XM5, 96(ARG1) vshufps $0x4e, XM2, XM0, XM1 vpslldq $8, XM1, XM0 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpermilps $0xff, XM2, XM3 vpxor XM3, XM0, XM0 aeskeygenassist $0x10, XM0, XM3 vpermilps $0xff, XM3, XM3 vpsrldq $8, XM1, XM4 vpslldq $12, XM4, XM4 vpxor XM4, XM1, XM1 vpxor XM3, XM1, XM1 vshufps $0xee, XM1, XM0, XM0 aesimc XM0, XM5 movdqu XM5, 80(ARG1) vshufps $0x4e, XM0, XM2, XM1 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM0, XM2 vpxor XM1, XM2, XM2 aesimc XM2, XM5 movdqu XM5, 64(ARG1) vshufps $0x4e, XM2, XM0, XM1 aeskeygenassist $0x20, XM2, XM0 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM0, XM0 vpxor XM1, XM0, XM0 aesimc XM0, XM5 movdqu XM5, 48(ARG1) vshufps $0x4e, XM0, XM2, XM1 vpslldq $8, XM1, XM2 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpermilps $0xff, XM0, XM3 vpxor XM3, XM2, XM2 aeskeygenassist $0x40, XM2, XM3 vpermilps $0xff, XM3, XM3 vpsrldq $8, XM1, XM4 vpslldq $12, XM4, XM4 vpxor XM4, XM1, XM1 vpxor XM3, XM1, XM1 vshufps $0xee, XM1, XM2, XM2 aesimc XM2, XM5 movdqu XM5, 32(ARG1) vshufps $0x4e, XM2, XM0, XM1 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM2, XM0 vpxor XM1, XM0, XM0 aesimc XM0, XM5 movdqu XM5, 16(ARG1) vshufps $0x4e, XM0, XM2, XM1 aeskeygenassist $0x80, XM0, XM2 KEY_EXPANSION_HELPER_192 XM1, XM3 vpermilps $0xff, XM2, XM2 vpxor XM1, XM2, XM2 movdqu XM2,(ARG1) vpxor XM0, XM0, XM0 vpxor XM1, XM1, XM1 vpxor XM2, XM2, XM2 vpxor XM3, XM3, XM3 vpxor XM4, XM4, XM4 vpxor XM5, XM5, XM5 ret .cfi_endproc .size SetDecryptKey192, .-SetDecryptKey192 /** * Function description: Sets the AES encryption key. Key length: 192 bits. * Function prototype: void SetEncryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key); * Input register: * x0:Pointer to the output key structure. * x1:Pointer to the input key. * Change register: xmm0-xmm3. * Output register: None. * Function/Macro Call: None. */ .globl SetEncryptKey256 .type SetEncryptKey256, @function SetEncryptKey256: .cfi_startproc movl $14, 240(ARG1) movdqu (ARG2), XM0 movdqu 16(ARG2), XM1 movdqu XM0, (ARG1) movdqu XM1, 16(ARG1) aeskeygenassist $0x01, XM1, XM2 vpermilps $0xff, XM2, XM2 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpxor XM0, XM2, XM2 movdqu XM2, 32(ARG1) aeskeygenassist $0x01, XM2, XM0 vpermilps $0xAA, XM0, XM0 vpslldq $4, XM1, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpxor XM1, XM0, XM0 movdqu XM0, 48(ARG1) /*2*/ aeskeygenassist $0x02, XM0, XM1 vpermilps $0xff, XM1, XM1 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpxor XM2, XM1, XM1 movdqu XM1, 64(ARG1) aeskeygenassist $0x02, XM1, XM2 vpermilps $0xAA, XM2, XM2 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpxor XM0, XM2, XM2 movdqu XM2, 80(ARG1) /*3*/ aeskeygenassist $0x04, XM2, XM0 vpermilps $0xff, XM0, XM0 vpslldq $4, XM1, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpxor XM1, XM0, XM0 movdqu XM0, 96(ARG1) aeskeygenassist $0x04, XM0, XM1 vpermilps $0xAA, XM1, XM1 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpxor XM2, XM1, XM1 movdqu XM1, 112(ARG1) /*4*/ aeskeygenassist $0x08, XM1, XM2 vpermilps $0xff, XM2, XM2 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpxor XM0, XM2, XM2 movdqu XM2, 128(ARG1) aeskeygenassist $0x08, XM2, XM0 vpermilps $0xAA, XM0, XM0 vpslldq $4, XM1, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpxor XM1, XM0, XM0 movdqu XM0, 144(ARG1) /*5*/ aeskeygenassist $0x10, XM0, XM1 vpermilps $0xff, XM1, XM1 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpxor XM2, XM1, XM1 movdqu XM1, 160(ARG1) aeskeygenassist $0x10, XM1, XM2 vpermilps $0xAA, XM2, XM2 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpxor XM0, XM2, XM2 movdqu XM2, 176(ARG1) /*6*/ aeskeygenassist $0x20, XM2, XM0 vpermilps $0xff, XM0, XM0 vpslldq $4, XM1, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpxor XM1, XM0, XM0 movdqu XM0, 192(ARG1) aeskeygenassist $0x20, XM0, XM1 vpermilps $0xAA, XM1, XM1 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpxor XM2, XM1, XM1 movdqu XM1, 208(ARG1) /*7*/ aeskeygenassist $0x40, XM1, XM2 vpermilps $0xff, XM2, XM2 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpxor XM0, XM2, XM2 movdqu XM2, 224(ARG1) vpxor XM0, XM0, XM0 vpxor XM1, XM1, XM1 vpxor XM2, XM2, XM2 vpxor XM3, XM3, XM3 ret .cfi_endproc .size SetEncryptKey256, .-SetEncryptKey256 /** * Function description: Sets the AES encryption key. Key length: 192 bits. * Function prototype: void SetDecryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key); * Input register: * x0:Pointer to the output key structure. * x1:Pointer to the input key. * Change register: xmm0-xmm4. * Output register: None. * Function/Macro Call: None. */ .globl SetDecryptKey256 .type SetDecryptKey256, @function SetDecryptKey256: .cfi_startproc movl $14, 240(ARG1) movdqu (ARG2), XM0 movdqu 16(ARG2), XM1 movdqu XM0, 224(ARG1) aesimc XM1, XM4 movdqu XM4, 208(ARG1) aeskeygenassist $0x01, XM1, XM2 vpermilps $0xff, XM2, XM2 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpxor XM0, XM2, XM2 aesimc XM2, XM4 movdqu XM4, 192(ARG1) aeskeygenassist $0x01, XM2, XM0 vpermilps $0xAA, XM0, XM0 vpslldq $4, XM1, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpxor XM1, XM0, XM0 aesimc XM0, XM4 movdqu XM4, 176(ARG1) /*2*/ aeskeygenassist $0x02, XM0, XM1 vpermilps $0xff, XM1, XM1 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpxor XM2, XM1, XM1 aesimc XM1, XM4 movdqu XM4, 160(ARG1) aeskeygenassist $0x02, XM1, XM2 vpermilps $0xAA, XM2, XM2 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpxor XM0, XM2, XM2 aesimc XM2, XM4 movdqu XM4, 144(ARG1) /*3*/ aeskeygenassist $0x04, XM2, XM0 vpermilps $0xff, XM0, XM0 vpslldq $4, XM1, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpxor XM1, XM0, XM0 aesimc XM0, XM4 movdqu XM4, 128(ARG1) aeskeygenassist $0x04, XM0, XM1 vpermilps $0xAA, XM1, XM1 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpxor XM2, XM1, XM1 aesimc XM1, XM4 movdqu XM4, 112(ARG1) /*4*/ aeskeygenassist $0x08, XM1, XM2 vpermilps $0xff, XM2, XM2 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpxor XM0, XM2, XM2 aesimc XM2, XM4 movdqu XM4, 96(ARG1) aeskeygenassist $0x08, XM2, XM0 vpermilps $0xAA, XM0, XM0 vpslldq $4, XM1, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpxor XM1, XM0, XM0 aesimc XM0, XM4 movdqu XM4, 80(ARG1) /*5*/ aeskeygenassist $0x10, XM0, XM1 vpermilps $0xff, XM1, XM1 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpxor XM2, XM1, XM1 aesimc XM1, XM4 movdqu XM4, 64(ARG1) aeskeygenassist $0x10, XM1, XM2 vpermilps $0xAA, XM2, XM2 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpxor XM0, XM2, XM2 aesimc XM2, XM4 movdqu XM4, 48(ARG1) /*6*/ aeskeygenassist $0x20, XM2, XM0 vpermilps $0xff, XM0, XM0 vpslldq $4, XM1, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpslldq $4, XM3, XM3 vpxor XM3, XM1, XM1 vpxor XM1, XM0, XM0 aesimc XM0, XM4 movdqu XM4, 32(ARG1) aeskeygenassist $0x20, XM0, XM1 vpermilps $0xAA, XM1, XM1 vpslldq $4, XM2, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpslldq $4, XM3, XM3 vpxor XM3, XM2, XM2 vpxor XM2, XM1, XM1 aesimc XM1, XM4 movdqu XM4, 16(ARG1) /*7*/ aeskeygenassist $0x40, XM1, XM2 vpermilps $0xff, XM2, XM2 vpslldq $4, XM0, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpslldq $4, XM3, XM3 vpxor XM3, XM0, XM0 vpxor XM0, XM2, XM2 movdqu XM2, (ARG1) vpxor XM0, XM0, XM0 vpxor XM1, XM1, XM1 vpxor XM2, XM2, XM2 vpxor XM3, XM3, XM3 vpxor XM4, XM4, XM4 ret .cfi_endproc .size SetDecryptKey256, .-SetDecryptKey256 /** * Function description: This API is used to set the AES encryption assembly acceleration. * Function prototype: int32_t CRYPT_AES_Encrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len); * Input register: * x0:Pointer to the input key structure. * x1:Points to the 128-bit input data. * x2:Points to the 128-bit output data. * x3:Indicates the length of a data block, that is, 16 bytes. * Change register: xmm0-xmm1. * Output register: eax. * Function/Macro Call: None. */ .globl CRYPT_AES_Encrypt .type CRYPT_AES_Encrypt, @function CRYPT_AES_Encrypt: .cfi_startproc .set ROUNDS,%eax movdqu (ARG2), XM0 movl 240(ARG1),ROUNDS vpxor (ARG1), XM0, XM0 movdqu 16(ARG1), XM1 aesenc XM1, XM0 movdqu 32(ARG1), XM1 aesenc XM1, XM0 movdqu 48(ARG1), XM1 aesenc XM1, XM0 movdqu 64(ARG1), XM1 aesenc XM1, XM0 movdqu 80(ARG1), XM1 aesenc XM1, XM0 movdqu 96(ARG1), XM1 aesenc XM1, XM0 movdqu 112(ARG1), XM1 aesenc XM1, XM0 movdqu 128(ARG1), XM1 aesenc XM1, XM0 movdqu 144(ARG1), XM1 aesenc XM1, XM0 cmpl $10,ROUNDS je .Laesenc_128 movdqu 160(ARG1), XM1 aesenc XM1, XM0 movdqu 176(ARG1), XM1 aesenc XM1, XM0 cmpl $12,ROUNDS je .Laesenc_192 movdqu 192(ARG1), XM1 aesenc XM1, XM0 movdqu 208(ARG1), XM1 aesenc XM1, XM0 cmpl $14,ROUNDS je .Laesenc_256 .Laesenc_128: movdqu 160(ARG1), XM1 aesenclast XM1, XM0 jmp .Laesenc_end .Laesenc_192: movdqu 192(ARG1), XM1 aesenclast XM1, XM0 jmp .Laesenc_end .Laesenc_256: movdqu 224(ARG1), XM1 aesenclast XM1, XM0 .Laesenc_end: vpxor XM1, XM1, XM1 movdqu XM0,(ARG3) vpxor XM0, XM0, XM0 movl $0,RET ret .cfi_endproc .size CRYPT_AES_Encrypt, .-CRYPT_AES_Encrypt /** * Function description: AES decryption and assembly acceleration API. * Function prototype: int32_t CRYPT_AES_Decrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len); * Input register: * x0:Pointer to the input key structure. * x1:Points to the 128-bit input data. * x2:Points to the 128-bit output data. * x3:Indicates the length of a data block, that is, 16 bytes. * Change register: xmm0-xmm1. * Output register: eax. * Function/Macro Call: None. */ .globl CRYPT_AES_Decrypt .type CRYPT_AES_Decrypt, @function CRYPT_AES_Decrypt: .cfi_startproc .set ROUNDS,%eax movdqu (ARG2), XM0 movl 240(ARG1),ROUNDS vpxor (ARG1), XM0, XM0 movdqu 16(ARG1), XM1 aesdec XM1, XM0 movdqu 32(ARG1), XM1 aesdec XM1, XM0 movdqu 48(ARG1), XM1 aesdec XM1, XM0 movdqu 64(ARG1), XM1 aesdec XM1, XM0 movdqu 80(ARG1), XM1 aesdec XM1, XM0 movdqu 96(ARG1), XM1 aesdec XM1, XM0 movdqu 112(ARG1), XM1 aesdec XM1, XM0 movdqu 128(ARG1), XM1 aesdec XM1, XM0 movdqu 144(ARG1), XM1 aesdec XM1, XM0 cmpl $10,ROUNDS je .aesdec_128 movdqu 160(ARG1), XM1 aesdec XM1, XM0 movdqu 176(ARG1), XM1 aesdec XM1, XM0 cmpl $12,ROUNDS je .aesdec_192 movdqu 192(ARG1), XM1 aesdec XM1, XM0 movdqu 208(ARG1), XM1 aesdec XM1, XM0 cmpl $14,ROUNDS je .aesdec_256 .aesdec_128: movdqu 160(ARG1), XM1 aesdeclast XM1, XM0 jmp .aesdec_end .aesdec_192: movdqu 192(ARG1), XM1 aesdeclast XM1, XM0 jmp .aesdec_end .aesdec_256: movdqu 224(ARG1), XM1 aesdeclast XM1, XM0 .aesdec_end: vpxor XM1, XM1, XM1 movdqu XM0,(ARG3) vpxor XM0, XM0, XM0 movl $0,RET ret .cfi_endproc .size CRYPT_AES_Decrypt, .-CRYPT_AES_Decrypt #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_x86_64.S
Motorola 68K Assembly
unknown
25,400
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_XTS) #include "crypt_aes_macro_armv8.s" #include "crypt_arm.h" .file "crypt_aes_xts_armv8.S" .text .arch armv8-a+crypto KEY .req x0 IN .req x1 OUT .req x2 LEN .req x3 TWEAK .req x4 TMPOUT .req x17 WP .req w11 WC .req w12 KTMP .req x5 LTMP .req x6 TAILNUM .req x8 POS .req x16 ROUNDS .req w7 XROUNDS .req x7 TROUNDS .req w15 WTMP0 .req w9 WTMP1 .req w10 WTMP2 .req w11 WTMP3 .req w12 XTMP1 .req x10 XTMP2 .req x11 TWX0 .req x13 TWX1 .req x14 TWW1 .req w14 BLK0 .req v0 BLK1 .req v1 BLK2 .req v2 BLK3 .req v3 BLK4 .req v4 IN0 .req v5 IN1 .req v6 IN2 .req v7 IN3 .req v30 IN4 .req v31 TWK0 .req v8 TWK1 .req v9 TWK2 .req v10 TWK3 .req v11 TWK4 .req v12 TWKD00 .req d8 TWKD10 .req d9 TWKD20 .req d10 TWKD30 .req d11 TWKD40 .req d12 #define TWKD01 v8.d[1] #define TWKD11 v9.d[1] #define TWKD21 v10.d[1] #define TWKD31 v11.d[1] #define TWKD41 v12.d[1] RDK0 .req v16 RDK1 .req v17 RDK2 .req v18 RDK3 .req v19 RDK4 .req v20 RDK5 .req v21 RDK6 .req v22 RDK7 .req v23 RDK8 .req v24 TMP0 .req v25 TMP1 .req v26 TMP2 .req v27 TMP3 .req v28 TMP4 .req v29 #define MOV_REG_TO_VEC(SRC0, SRC1, DES0, DES1) \ fmov DES0,SRC0 ; \ fmov DES1,SRC1 ; \ .macro NextTweak twkl, twkh, twkd0, twkd1 asr XTMP2,\twkh,#63 extr \twkh,\twkh,\twkl,#63 and WTMP1,WTMP0,WTMP2 eor \twkl,XTMP1,\twkl,lsl#1 fmov \twkd0,\twkl // must set lower bits of 'q' register first.1 fmov \twkd1,\twkh // Set lower bits using 'd' register will clear higer bits. .endm .macro AesCrypt1x en, mc, d0, rk aes\en \d0\().16b, \rk\().16b aes\mc \d0\().16b, \d0\().16b .endm .macro AesEncrypt1x d0, rk AesCrypt1x e, mc, \d0, \rk .endm .macro AesDecrypt1x d0, rk AesCrypt1x d, imc, \d0, \rk .endm /** * int32_t CRYPT_AES_XTS_Encrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len, const uint8_t *tweak); */ .globl CRYPT_AES_XTS_Encrypt .type CRYPT_AES_XTS_Encrypt, %function .align 4 CRYPT_AES_XTS_Encrypt: AARCH64_PACIASP stp x29, x30, [sp,#-80]! add x29, sp, #0 stp d8, d9, [sp,#16] stp d10, d11, [sp,#32] stp d12, d13, [sp,#48] stp d14, d15, [sp,#64] ld1 {TWK0.16b}, [TWEAK] and TAILNUM, LEN, #0xF // get tail num, LEN % 16 and LTMP, LEN, #-16 mov WTMP0,0x87 ldr ROUNDS,[KEY,#240] fmov TWX0,TWKD00 fmov TWX1,TWKD01 sub ROUNDS,ROUNDS,#6 // perload last 7 rounds key add KTMP,KEY,XROUNDS,lsl#4 ld1 {RDK2.4s,RDK3.4s},[KTMP],#32 ld1 {RDK4.4s,RDK5.4s},[KTMP],#32 ld1 {RDK6.4s,RDK7.4s},[KTMP],#32 ld1 {RDK8.4s},[KTMP] .Lxts_aesenc_start: cmp LTMP, #80 b.ge .Lxts_enc_proc_5_blks cmp LTMP, #48 b.ge .Lxts_enc_proc_3_blks cmp LTMP, #32 b.eq .Lxts_enc_proc_2_blks cmp LTMP, #16 b.eq .Lxts_enc_proc_1blk .Lxtx_tail_blk: fmov TWX0,TWKD00 // reset already computed tweak fmov TWX1,TWKD01 cbz TAILNUM,.Lxts_aesenc_finish // prepare encrypt tail block sub TMPOUT,OUT,#16 .Lxtx_tail_blk_loop: subs TAILNUM,TAILNUM,1 ldrb WC,[TMPOUT,TAILNUM] ldrb WP,[IN,TAILNUM] strb WC,[OUT,TAILNUM] strb WP,[TMPOUT,TAILNUM] b.gt .Lxtx_tail_blk_loop ld1 {BLK0.16b}, [TMPOUT] mov LTMP,#16 mov OUT,TMPOUT b .Lxts_enc_proc_1blk_loaded cbz LTMP,.Lxts_aesenc_finish .Lxts_enc_proc_1blk: ld1 {BLK0.16b},[IN],#16 .Lxts_enc_proc_1blk_loaded: eor BLK0.16b,BLK0.16b,TWK0.16b mov KTMP, KEY ld1 {RDK0.4s,RDK1.4s},[KTMP],#32 sub TROUNDS,ROUNDS,#2 .Lxts_rounds_1blks: AesEncrypt1x BLK0,RDK0 ld1 {RDK0.4s},[KTMP],#16 subs TROUNDS,TROUNDS,#2 AesEncrypt1x BLK0,RDK1 ld1 {RDK1.4s},[KTMP],#16 b.gt .Lxts_rounds_1blks AesEncrypt1x BLK0,RDK0 AesEncrypt1x BLK0,RDK1 // last 7 rounds AesEncrypt1x BLK0,RDK2 AesEncrypt1x BLK0,RDK3 AesEncrypt1x BLK0,RDK4 AesEncrypt1x BLK0,RDK5 AesEncrypt1x BLK0,RDK6 aese BLK0.16b,RDK7.16b // final round eor BLK0.16b,BLK0.16b,RDK8.16b eor BLK0.16b,BLK0.16b,TWK0.16b st1 {BLK0.16b}, [OUT], #16 NextTweak TWX0,TWX1,TWKD00,TWKD01 subs LTMP,LTMP,#16 b.hs .Lxts_aesenc_start .Lxts_enc_proc_2_blks: ld1 {BLK0.16b, BLK1.16b}, [IN], #32 mov KTMP, KEY NextTweak TWX0,TWX1,TWKD10,TWKD11 ld1 {RDK0.4s,RDK1.4s},[KTMP],#32 sub TROUNDS,ROUNDS,#2 eor BLK0.16b, BLK0.16b, TWK0.16b eor BLK1.16b, BLK1.16b, TWK1.16b .Lxts_rounds_2blks: AesEncrypt1x BLK0,RDK0 AesEncrypt1x BLK1,RDK0 ld1 {RDK0.4s},[KTMP],#16 subs TROUNDS,TROUNDS,#2 AesEncrypt1x BLK0,RDK1 AesEncrypt1x BLK1,RDK1 ld1 {RDK1.4s},[KTMP],#16 b.gt .Lxts_rounds_2blks AesEncrypt1x BLK0,RDK0 AesEncrypt1x BLK1,RDK0 AesEncrypt1x BLK0,RDK1 AesEncrypt1x BLK1,RDK1 // last 7 rounds AesEncrypt1x BLK0,RDK2 AesEncrypt1x BLK1,RDK2 AesEncrypt1x BLK0,RDK3 AesEncrypt1x BLK1,RDK3 AesEncrypt1x BLK0,RDK4 AesEncrypt1x BLK1,RDK4 AesEncrypt1x BLK0,RDK5 AesEncrypt1x BLK1,RDK5 AesEncrypt1x BLK0,RDK6 AesEncrypt1x BLK1,RDK6 eor TWK0.16b,TWK0.16b,RDK8.16b eor TWK1.16b,TWK1.16b,RDK8.16b aese BLK0.16b,RDK7.16b // final round aese BLK1.16b,RDK7.16b eor BLK0.16b,BLK0.16b,TWK0.16b eor BLK1.16b,BLK1.16b,TWK1.16b st1 {BLK0.16b, BLK1.16b}, [OUT], #32 NextTweak TWX0,TWX1,TWKD00,TWKD01 subs LTMP,LTMP,#32 b.hs .Lxts_aesenc_start .Lxts_enc_proc_3_blks: ld1 {BLK0.16b}, [IN], #16 // first block NextTweak TWX0,TWX1,TWKD10,TWKD11 eor BLK0.16b,BLK0.16b,TWK0.16b ld1 {BLK1.16b}, [IN], #16 // second block NextTweak TWX0,TWX1,TWKD20,TWKD21 eor BLK1.16b,BLK1.16b,TWK1.16b ld1 {BLK2.16b}, [IN], #16 // third block eor BLK2.16b,BLK2.16b,TWK2.16b mov KTMP, KEY ld1 {RDK0.4s,RDK1.4s},[KTMP],#32 sub TROUNDS,ROUNDS,#2 .Lxts_rounds_3blks: AesEncrypt1x BLK0,RDK0 AesEncrypt1x BLK1,RDK0 AesEncrypt1x BLK2,RDK0 ld1 {RDK0.4s},[KTMP],#16 subs TROUNDS,TROUNDS,#2 AesEncrypt1x BLK0,RDK1 AesEncrypt1x BLK1,RDK1 AesEncrypt1x BLK2,RDK1 ld1 {RDK1.4s},[KTMP],#16 b.gt .Lxts_rounds_3blks AesEncrypt1x BLK0,RDK0 AesEncrypt1x BLK1,RDK0 AesEncrypt1x BLK2,RDK0 AesEncrypt1x BLK0,RDK1 AesEncrypt1x BLK1,RDK1 AesEncrypt1x BLK2,RDK1 // last 7 rounds AesEncrypt1x BLK0,RDK2 AesEncrypt1x BLK1,RDK2 AesEncrypt1x BLK2,RDK2 AesEncrypt1x BLK0,RDK3 AesEncrypt1x BLK1,RDK3 AesEncrypt1x BLK2,RDK3 AesEncrypt1x BLK0,RDK4 AesEncrypt1x BLK1,RDK4 AesEncrypt1x BLK2,RDK4 AesEncrypt1x BLK0,RDK5 AesEncrypt1x BLK1,RDK5 AesEncrypt1x BLK2,RDK5 AesEncrypt1x BLK0,RDK6 AesEncrypt1x BLK1,RDK6 AesEncrypt1x BLK2,RDK6 eor TWK0.16b,TWK0.16b,RDK8.16b eor TWK1.16b,TWK1.16b,RDK8.16b eor TWK2.16b,TWK2.16b,RDK8.16b aese BLK0.16b,RDK7.16b aese BLK1.16b,RDK7.16b aese BLK2.16b,RDK7.16b eor BLK0.16b,BLK0.16b,TWK0.16b eor BLK1.16b,BLK1.16b,TWK1.16b eor BLK2.16b,BLK2.16b,TWK2.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b}, [OUT], #48 NextTweak TWX0,TWX1,TWKD00,TWKD01 subs LTMP,LTMP,#48 b.hs .Lxts_aesenc_start .align 4 .Lxts_enc_proc_5_blks: ld1 {BLK0.16b}, [IN], #16 // first block NextTweak TWX0,TWX1,TWKD10,TWKD11 eor BLK0.16b,BLK0.16b,TWK0.16b ld1 {BLK1.16b}, [IN], #16 // second block NextTweak TWX0,TWX1,TWKD20,TWKD21 eor BLK1.16b,BLK1.16b,TWK1.16b sub LTMP,LTMP,#32 ld1 {BLK2.16b}, [IN], #16 // third block NextTweak TWX0,TWX1,TWKD30,TWKD31 eor BLK2.16b,BLK2.16b,TWK2.16b ld1 {BLK3.16b}, [IN], #16 // fourth block NextTweak TWX0,TWX1,TWKD40,TWKD41 eor BLK3.16b,BLK3.16b,TWK3.16b sub LTMP,LTMP,#32 ld1 {BLK4.16b}, [IN], #16 // fifth block eor BLK4.16b, BLK4.16b, TWK4.16b sub LTMP,LTMP,#16 mov KTMP, KEY ld1 {RDK0.4s,RDK1.4s},[KTMP],#32 sub TROUNDS,ROUNDS,#2 .align 4 .Lxts_rounds_5blks: AesEncrypt1x BLK0,RDK0 AesEncrypt1x BLK1,RDK0 AesEncrypt1x BLK2,RDK0 AesEncrypt1x BLK3,RDK0 AesEncrypt1x BLK4,RDK0 ld1 {RDK0.4s},[KTMP],#16 subs TROUNDS,TROUNDS,#2 AesEncrypt1x BLK0,RDK1 AesEncrypt1x BLK1,RDK1 AesEncrypt1x BLK2,RDK1 AesEncrypt1x BLK3,RDK1 AesEncrypt1x BLK4,RDK1 ld1 {RDK1.4s},[KTMP],#16 b.gt .Lxts_rounds_5blks AesEncrypt1x BLK0,RDK0 AesEncrypt1x BLK1,RDK0 AesEncrypt1x BLK2,RDK0 AesEncrypt1x BLK3,RDK0 AesEncrypt1x BLK4,RDK0 subs LTMP,LTMP,#80 AesEncrypt1x BLK0,RDK1 AesEncrypt1x BLK1,RDK1 AesEncrypt1x BLK2,RDK1 AesEncrypt1x BLK3,RDK1 AesEncrypt1x BLK4,RDK1 // last 7 rounds AesEncrypt1x BLK0,RDK2 AesEncrypt1x BLK1,RDK2 AesEncrypt1x BLK2,RDK2 AesEncrypt1x BLK3,RDK2 AesEncrypt1x BLK4,RDK2 csel POS,xzr,LTMP,gt // AesEncrypt1x BLK0,RDK3 AesEncrypt1x BLK1,RDK3 AesEncrypt1x BLK2,RDK3 AesEncrypt1x BLK3,RDK3 AesEncrypt1x BLK4,RDK3 add IN,IN,POS AesEncrypt1x BLK0,RDK4 AesEncrypt1x BLK1,RDK4 AesEncrypt1x BLK2,RDK4 AesEncrypt1x BLK3,RDK4 AesEncrypt1x BLK4,RDK4 AesEncrypt1x BLK0,RDK5 AesEncrypt1x BLK1,RDK5 AesEncrypt1x BLK2,RDK5 AesEncrypt1x BLK3,RDK5 AesEncrypt1x BLK4,RDK5 AesEncrypt1x BLK0,RDK6 AesEncrypt1x BLK1,RDK6 AesEncrypt1x BLK2,RDK6 AesEncrypt1x BLK3,RDK6 AesEncrypt1x BLK4,RDK6 eor TMP0.16b,TWK0.16b,RDK8.16b aese BLK0.16b,RDK7.16b // final round NextTweak TWX0,TWX1,TWKD00,TWKD01 // perform operations of next 5blks in advance eor TMP1.16b,TWK1.16b,RDK8.16b ld1 {IN0.16b}, [IN], #16 aese BLK1.16b,RDK7.16b NextTweak TWX0,TWX1,TWKD10,TWKD11 eor TMP2.16b,TWK2.16b,RDK8.16b ld1 {IN1.16b}, [IN], #16 aese BLK2.16b,RDK7.16b NextTweak TWX0,TWX1,TWKD20,TWKD21 eor TMP3.16b,TWK3.16b,RDK8.16b ld1 {IN2.16b}, [IN], #16 aese BLK3.16b,RDK7.16b NextTweak TWX0,TWX1,TWKD30,TWKD31 eor TMP4.16b,TWK4.16b,RDK8.16b ld1 {IN3.16b}, [IN], #16 aese BLK4.16b,RDK7.16b NextTweak TWX0,TWX1,TWKD40,TWKD41 ld1 {IN4.16b}, [IN], #16 mov KTMP, KEY ld1 {RDK0.4s,RDK1.4s},[KTMP],#32 eor TMP0.16b,TMP0.16b,BLK0.16b eor BLK0.16b,IN0.16b,TWK0.16b // blk0 = in0 ^ twk0 eor TMP1.16b,TMP1.16b,BLK1.16b eor BLK1.16b,IN1.16b,TWK1.16b st1 {TMP0.16b}, [OUT], #16 eor TMP2.16b,TMP2.16b,BLK2.16b eor BLK2.16b,IN2.16b,TWK2.16b eor TMP3.16b,TMP3.16b,BLK3.16b eor BLK3.16b,IN3.16b,TWK3.16b st1 {TMP1.16b}, [OUT], #16 eor TMP4.16b,TMP4.16b,BLK4.16b eor BLK4.16b,IN4.16b,TWK4.16b st1 {TMP2.16b}, [OUT], #16 sub TROUNDS,ROUNDS,#2 st1 {TMP3.16b,TMP4.16b}, [OUT], #32 b.hs .Lxts_rounds_5blks add LTMP,LTMP,#80 // add 5 blocks length back if LTMP < 0 cbz LTMP,.Lxtx_tail_blk cmp LTMP, #16 b.eq .Lxts_pre_last_1blks cmp LTMP,#32 b.eq .Lxts_pre_last_2blks cmp LTMP,#48 b.eq .Lxts_pre_last_3blks cmp LTMP,#64 b.eq .Lxts_pre_last_4blks .Lxts_pre_last_1blks: eor IN0.16b,IN0.16b,IN4.16b //in0 = in0 ^ in41 eor BLK0.16b,BLK0.16b,IN0.16b // blk0 = in0 ^ twk0 ^ in0 ^ in4 fmov TWX0,TWKD00 // reset already computed tweak fmov TWX1,TWKD01 b .Lxts_rounds_1blks .Lxts_pre_last_2blks: eor BLK0.16b,BLK0.16b,IN0.16b eor BLK1.16b,BLK1.16b,IN1.16b eor BLK0.16b,BLK0.16b,IN3.16b // in3 -> blk0 eor BLK1.16b,BLK1.16b,IN4.16b // in4 -> blk1 fmov TWX0,TWKD10 // reset already computed tweak fmov TWX1,TWKD11 b .Lxts_rounds_2blks .Lxts_pre_last_3blks: eor BLK0.16b,BLK0.16b,IN0.16b eor BLK1.16b,BLK1.16b,IN1.16b eor BLK2.16b,BLK2.16b,IN2.16b eor BLK0.16b,BLK0.16b,IN2.16b // in2 -> blk0 eor BLK1.16b,BLK1.16b,IN3.16b // in3 -> blk1 eor BLK2.16b,BLK2.16b,IN4.16b // in4 -> blk2 fmov TWX0,TWKD20 // reset already computed tweak fmov TWX1,TWKD21 b .Lxts_rounds_3blks .Lxts_pre_last_4blks: eor BLK0.16b,BLK0.16b,IN0.16b eor BLK1.16b,BLK1.16b,IN1.16b eor BLK2.16b,BLK2.16b,IN2.16b eor BLK3.16b,BLK3.16b,IN3.16b sub IN,IN,#16 // have loaded 4blks, using 3blks to process, so step back 1blk here eor BLK0.16b,BLK0.16b,IN1.16b // in1 -> blk0 eor BLK1.16b,BLK1.16b,IN2.16b // in2 -> blk1 eor BLK2.16b,BLK2.16b,IN3.16b // in3 -> blk2 eor BLK3.16b,BLK3.16b,IN4.16b // in4 -> blk3 fmov TWX0,TWKD20 // reset already computed tweak fmov TWX1,TWKD21 b .Lxts_rounds_3blks .Lxts_aesenc_finish: MOV_REG_TO_VEC(TWX0,TWX1,TWKD00,TWKD01) st1 {TWK0.16b}, [TWEAK] mov x0, #0 // return value ? no need ldp d14, d15, [sp,#64] ldp d12, d13, [sp, #48] ldp d10, d11, [sp, #32] ldp d8, d9, [sp, #16] ldp x29, x30, [sp], #80 AARCH64_AUTIASP ret .size CRYPT_AES_XTS_Encrypt, .-CRYPT_AES_XTS_Encrypt /** * int32_t CRYPT_AES_XTS_Decrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len, const uint8_t *t); */ .globl CRYPT_AES_XTS_Decrypt .type CRYPT_AES_XTS_Decrypt, %function .align 4 CRYPT_AES_XTS_Decrypt: AARCH64_PACIASP stp x29, x30, [sp,#-80]! add x29, sp, #0 stp d8, d9, [sp,#16] stp d10, d11, [sp,#32] stp d12, d13, [sp,#48] stp d14, d15, [sp,#64] ld1 {TWK0.16b}, [TWEAK] and LTMP, LEN, #-16 ands TAILNUM, LEN, #0xF // get tail num, LEN % 16 sub XTMP1,LTMP,#16 // preserve last and tail block csel LTMP,XTMP1,LTMP,ne // if tailnum != 0, len -= 16 mov WTMP0,0x87 ldr ROUNDS,[KEY,#240] fmov TWX0,TWKD00 fmov TWX1,TWKD01 sub ROUNDS,ROUNDS,#6 // perload last 7 rounds key add KTMP,KEY,XROUNDS,lsl#4 ld1 {RDK2.4s,RDK3.4s},[KTMP],#32 ld1 {RDK4.4s,RDK5.4s},[KTMP],#32 ld1 {RDK6.4s,RDK7.4s},[KTMP],#32 ld1 {RDK8.4s},[KTMP] .Lxts_aesdec_start: cmp LTMP, #80 b.ge .Lxts_dec_proc_5_blks cmp LTMP, #48 b.ge .Lxts_dec_proc_3_blks cmp LTMP, #32 b.eq .Lxts_dec_proc_2_blks cmp LTMP, #16 b.eq .Lxts_dec_proc_1blk cmp LTMP, #0 b.eq .Lxts_dec_last_secondblk .Lxtx_dec_tail_blk: fmov TWX0,TWKD00 // reset already computed tweak fmov TWX1,TWKD01 cbz TAILNUM,.Lxts_aesdec_finish // prepare encrypt tail block sub TMPOUT,OUT,#16 .Lxtx_dec_tail_blk_loop: subs TAILNUM,TAILNUM,1 ldrb WC,[TMPOUT,TAILNUM] ldrb WP,[IN,TAILNUM] strb WC,[OUT,TAILNUM] strb WP,[TMPOUT,TAILNUM] b.gt .Lxtx_dec_tail_blk_loop ld1 {BLK0.16b}, [TMPOUT] mov OUT,TMPOUT mov TWK0.16b,TWK2.16b // load pre-tweak back b .Lxts_dec_proc_1blk_loaded cbz LTMP,.Lxts_aesdec_finish .Lxts_dec_last_secondblk: cbz TAILNUM,.Lxts_aesdec_finish mov TWK2.16b,TWK0.16b // save last second tweak NextTweak TWX0,TWX1,TWKD00,TWKD01 .Lxts_dec_proc_1blk: ld1 {BLK0.16b}, [IN],#16 .Lxts_dec_proc_1blk_loaded: mov KTMP, KEY eor BLK0.16b,BLK0.16b,TWK0.16b ld1 {RDK0.4s},[KTMP],#16 sub TROUNDS,ROUNDS,#2 ld1 {RDK1.4s},[KTMP],#16 .Lxts_dec_rounds_1blks: AesDecrypt1x BLK0,RDK0 ld1 {RDK0.4s},[KTMP],#16 subs TROUNDS,TROUNDS,#2 AesDecrypt1x BLK0,RDK1 ld1 {RDK1.4s},[KTMP],#16 b.gt .Lxts_dec_rounds_1blks AesDecrypt1x BLK0,RDK0 AesDecrypt1x BLK0,RDK1 // last 7 rounds AesDecrypt1x BLK0,RDK2 AesDecrypt1x BLK0,RDK3 AesDecrypt1x BLK0,RDK4 AesDecrypt1x BLK0,RDK5 AesDecrypt1x BLK0,RDK6 aesd BLK0.16b,RDK7.16b // final round eor BLK0.16b,BLK0.16b,RDK8.16b eor BLK0.16b,BLK0.16b,TWK0.16b st1 {BLK0.16b}, [OUT], #16 NextTweak TWX0,TWX1,TWKD00,TWKD01 subs LTMP,LTMP,#16 b.lt .Lxtx_dec_tail_blk b.hs .Lxts_aesdec_start .Lxts_dec_proc_2_blks: ld1 {BLK0.16b, BLK1.16b}, [IN], #32 mov KTMP, KEY NextTweak TWX0,TWX1,TWKD10,TWKD11 ld1 {RDK0.4s,RDK1.4s},[KTMP],#32 sub TROUNDS,ROUNDS,#2 eor BLK0.16b, BLK0.16b, TWK0.16b eor BLK1.16b, BLK1.16b, TWK1.16b .Lxts_dec_rounds_2blks: AesDecrypt1x BLK0,RDK0 AesDecrypt1x BLK1,RDK0 ld1 {RDK0.4s},[KTMP],#16 subs TROUNDS,TROUNDS,#2 AesDecrypt1x BLK0,RDK1 AesDecrypt1x BLK1,RDK1 ld1 {RDK1.4s},[KTMP],#16 b.gt .Lxts_dec_rounds_2blks AesDecrypt1x BLK0,RDK0 AesDecrypt1x BLK1,RDK0 AesDecrypt1x BLK0,RDK1 AesDecrypt1x BLK1,RDK1 // last 7 rounds AesDecrypt1x BLK0,RDK2 AesDecrypt1x BLK1,RDK2 AesDecrypt1x BLK0,RDK3 AesDecrypt1x BLK1,RDK3 AesDecrypt1x BLK0,RDK4 AesDecrypt1x BLK1,RDK4 AesDecrypt1x BLK0,RDK5 AesDecrypt1x BLK1,RDK5 AesDecrypt1x BLK0,RDK6 AesDecrypt1x BLK1,RDK6 eor TWK0.16b,TWK0.16b,RDK8.16b eor TWK1.16b,TWK1.16b,RDK8.16b aesd BLK0.16b,RDK7.16b // final round aesd BLK1.16b,RDK7.16b eor BLK0.16b,BLK0.16b,TWK0.16b eor BLK1.16b,BLK1.16b,TWK1.16b st1 {BLK0.16b, BLK1.16b}, [OUT], #32 NextTweak TWX0,TWX1,TWKD00,TWKD01 subs LTMP,LTMP,#32 b.hs .Lxts_aesdec_start .Lxts_dec_proc_3_blks: ld1 {BLK0.16b}, [IN], #16 // first block NextTweak TWX0,TWX1,TWKD10,TWKD11 eor BLK0.16b,BLK0.16b,TWK0.16b ld1 {BLK1.16b}, [IN], #16 // second block NextTweak TWX0,TWX1,TWKD20,TWKD21 eor BLK1.16b,BLK1.16b,TWK1.16b ld1 {BLK2.16b}, [IN], #16 // third block eor BLK2.16b,BLK2.16b,TWK2.16b mov KTMP, KEY ld1 {RDK0.4s,RDK1.4s},[KTMP],#32 sub TROUNDS,ROUNDS,#2 .Lxts_dec_rounds_3blks: AesDecrypt1x BLK0,RDK0 AesDecrypt1x BLK1,RDK0 AesDecrypt1x BLK2,RDK0 ld1 {RDK0.4s},[KTMP],#16 subs TROUNDS,TROUNDS,#2 AesDecrypt1x BLK0,RDK1 AesDecrypt1x BLK1,RDK1 AesDecrypt1x BLK2,RDK1 ld1 {RDK1.4s},[KTMP],#16 b.gt .Lxts_dec_rounds_3blks AesDecrypt1x BLK0,RDK0 AesDecrypt1x BLK1,RDK0 AesDecrypt1x BLK2,RDK0 AesDecrypt1x BLK0,RDK1 AesDecrypt1x BLK1,RDK1 AesDecrypt1x BLK2,RDK1 // last 7 rounds AesDecrypt1x BLK0,RDK2 AesDecrypt1x BLK1,RDK2 AesDecrypt1x BLK2,RDK2 AesDecrypt1x BLK0,RDK3 AesDecrypt1x BLK1,RDK3 AesDecrypt1x BLK2,RDK3 AesDecrypt1x BLK0,RDK4 AesDecrypt1x BLK1,RDK4 AesDecrypt1x BLK2,RDK4 AesDecrypt1x BLK0,RDK5 AesDecrypt1x BLK1,RDK5 AesDecrypt1x BLK2,RDK5 AesDecrypt1x BLK0,RDK6 AesDecrypt1x BLK1,RDK6 AesDecrypt1x BLK2,RDK6 eor TWK0.16b,TWK0.16b,RDK8.16b eor TWK1.16b,TWK1.16b,RDK8.16b eor TWK2.16b,TWK2.16b,RDK8.16b aesd BLK0.16b,RDK7.16b aesd BLK1.16b,RDK7.16b aesd BLK2.16b,RDK7.16b eor BLK0.16b,BLK0.16b,TWK0.16b eor BLK1.16b,BLK1.16b,TWK1.16b eor BLK2.16b,BLK2.16b,TWK2.16b st1 {BLK0.16b, BLK1.16b, BLK2.16b}, [OUT], #48 NextTweak TWX0,TWX1,TWKD00,TWKD01 subs LTMP,LTMP,#48 b.hs .Lxts_aesdec_start .align 4 .Lxts_dec_proc_5_blks: ld1 {BLK0.16b}, [IN], #16 // first block NextTweak TWX0,TWX1,TWKD10,TWKD11 eor BLK0.16b,BLK0.16b,TWK0.16b ld1 {BLK1.16b}, [IN], #16 // second block NextTweak TWX0,TWX1,TWKD20,TWKD21 eor BLK1.16b,BLK1.16b,TWK1.16b sub LTMP,LTMP,#32 ld1 {BLK2.16b}, [IN], #16 // third block NextTweak TWX0,TWX1,TWKD30,TWKD31 eor BLK2.16b,BLK2.16b,TWK2.16b ld1 {BLK3.16b}, [IN], #16 // fourth block NextTweak TWX0,TWX1,TWKD40,TWKD41 eor BLK3.16b,BLK3.16b,TWK3.16b sub LTMP,LTMP,#32 ld1 {BLK4.16b}, [IN], #16 // fifth block eor BLK4.16b, BLK4.16b, TWK4.16b sub LTMP,LTMP,#16 mov KTMP, KEY ld1 {RDK0.4s,RDK1.4s},[KTMP],#32 sub TROUNDS,ROUNDS,#2 .align 4 .Lxts_dec_rounds_5blks: AesDecrypt1x BLK0,RDK0 AesDecrypt1x BLK1,RDK0 AesDecrypt1x BLK2,RDK0 AesDecrypt1x BLK3,RDK0 AesDecrypt1x BLK4,RDK0 ld1 {RDK0.4s},[KTMP],#16 subs TROUNDS,TROUNDS,#2 AesDecrypt1x BLK0,RDK1 AesDecrypt1x BLK1,RDK1 AesDecrypt1x BLK2,RDK1 AesDecrypt1x BLK3,RDK1 AesDecrypt1x BLK4,RDK1 ld1 {RDK1.4s},[KTMP],#16 b.gt .Lxts_dec_rounds_5blks AesDecrypt1x BLK0,RDK0 AesDecrypt1x BLK1,RDK0 AesDecrypt1x BLK2,RDK0 AesDecrypt1x BLK3,RDK0 AesDecrypt1x BLK4,RDK0 subs LTMP,LTMP,#80 AesDecrypt1x BLK0,RDK1 AesDecrypt1x BLK1,RDK1 AesDecrypt1x BLK2,RDK1 AesDecrypt1x BLK3,RDK1 AesDecrypt1x BLK4,RDK1 // last 7 rounds AesDecrypt1x BLK0,RDK2 AesDecrypt1x BLK1,RDK2 AesDecrypt1x BLK2,RDK2 AesDecrypt1x BLK3,RDK2 AesDecrypt1x BLK4,RDK2 csel POS,xzr,LTMP,gt // AesDecrypt1x BLK0,RDK3 AesDecrypt1x BLK1,RDK3 AesDecrypt1x BLK2,RDK3 AesDecrypt1x BLK3,RDK3 AesDecrypt1x BLK4,RDK3 add IN,IN,POS AesDecrypt1x BLK0,RDK4 AesDecrypt1x BLK1,RDK4 AesDecrypt1x BLK2,RDK4 AesDecrypt1x BLK3,RDK4 AesDecrypt1x BLK4,RDK4 AesDecrypt1x BLK0,RDK5 AesDecrypt1x BLK1,RDK5 AesDecrypt1x BLK2,RDK5 AesDecrypt1x BLK3,RDK5 AesDecrypt1x BLK4,RDK5 AesDecrypt1x BLK0,RDK6 AesDecrypt1x BLK1,RDK6 AesDecrypt1x BLK2,RDK6 AesDecrypt1x BLK3,RDK6 AesDecrypt1x BLK4,RDK6 eor TMP0.16b,TWK0.16b,RDK8.16b aesd BLK0.16b,RDK7.16b // final round NextTweak TWX0,TWX1,TWKD00,TWKD01 // perform operations of next 5blks in advance eor TMP1.16b,TWK1.16b,RDK8.16b ld1 {IN0.16b}, [IN], #16 aesd BLK1.16b,RDK7.16b NextTweak TWX0,TWX1,TWKD10,TWKD11 eor TMP2.16b,TWK2.16b,RDK8.16b ld1 {IN1.16b}, [IN], #16 aesd BLK2.16b,RDK7.16b NextTweak TWX0,TWX1,TWKD20,TWKD21 eor TMP3.16b,TWK3.16b,RDK8.16b ld1 {IN2.16b}, [IN], #16 aesd BLK3.16b,RDK7.16b NextTweak TWX0,TWX1,TWKD30,TWKD31 eor TMP4.16b,TWK4.16b,RDK8.16b ld1 {IN3.16b}, [IN], #16 aesd BLK4.16b,RDK7.16b NextTweak TWX0,TWX1,TWKD40,TWKD41 ld1 {IN4.16b}, [IN], #16 mov KTMP, KEY ld1 {RDK0.4s,RDK1.4s},[KTMP],#32 eor TMP0.16b,TMP0.16b,BLK0.16b eor BLK0.16b,IN0.16b,TWK0.16b // blk0 = in0 ^ twk0 eor TMP1.16b,TMP1.16b,BLK1.16b eor BLK1.16b,IN1.16b,TWK1.16b st1 {TMP0.16b}, [OUT], #16 eor TMP2.16b,TMP2.16b,BLK2.16b eor BLK2.16b,IN2.16b,TWK2.16b eor TMP3.16b,TMP3.16b,BLK3.16b eor BLK3.16b,IN3.16b,TWK3.16b st1 {TMP1.16b}, [OUT], #16 eor TMP4.16b,TMP4.16b,BLK4.16b eor BLK4.16b,IN4.16b,TWK4.16b st1 {TMP2.16b}, [OUT], #16 sub TROUNDS,ROUNDS,#2 st1 {TMP3.16b,TMP4.16b}, [OUT], #32 b.hs .Lxts_dec_rounds_5blks add LTMP,LTMP,#80 // add 5 blocks length back if LTMP < 0 cbz LTMP, .Lxts_dec_pre_last_secondblks cmp LTMP, #16 b.eq .Lxts_dec_pre_last_1blks cmp LTMP,#32 b.eq .Lxts_dec_pre_last_2blks cmp LTMP,#48 b.eq .Lxts_dec_pre_last_3blks cmp LTMP,#64 b.eq .Lxts_dec_pre_last_4blks .Lxts_dec_pre_last_secondblks: fmov TWX0,TWKD10 // reset already computed tweak fmov TWX1,TWKD11 mov TWK2.16b, TWK0.16b //save the last second tweak mov TWK0.16b, TWK1.16b // use the last tweak b .Lxts_dec_proc_1blk .Lxts_dec_pre_last_1blks: eor IN0.16b,IN0.16b,IN4.16b //in0 = in0 ^ in41 eor BLK0.16b,BLK0.16b,IN0.16b // blk0 = in0 ^ twk0 ^ in0 ^ in4 fmov TWX0,TWKD00 // reset already computed tweak fmov TWX1,TWKD01 b .Lxts_dec_rounds_1blks .Lxts_dec_pre_last_2blks: eor BLK0.16b,BLK0.16b,IN0.16b eor BLK1.16b,BLK1.16b,IN1.16b eor BLK0.16b,BLK0.16b,IN3.16b // in3 -> blk0 eor BLK1.16b,BLK1.16b,IN4.16b // in4 -> blk1 fmov TWX0,TWKD10 // reset already computed tweak fmov TWX1,TWKD11 b .Lxts_dec_rounds_2blks .Lxts_dec_pre_last_3blks: eor BLK0.16b,BLK0.16b,IN0.16b eor BLK1.16b,BLK1.16b,IN1.16b eor BLK2.16b,BLK2.16b,IN2.16b eor BLK0.16b,BLK0.16b,IN2.16b // in2 -> blk0 eor BLK1.16b,BLK1.16b,IN3.16b // in3 -> blk1 eor BLK2.16b,BLK2.16b,IN4.16b // in4 -> blk2 fmov TWX0,TWKD20 // reset already computed tweak fmov TWX1,TWKD21 b .Lxts_dec_rounds_3blks .Lxts_dec_pre_last_4blks: eor BLK0.16b,BLK0.16b,IN0.16b eor BLK1.16b,BLK1.16b,IN1.16b eor BLK2.16b,BLK2.16b,IN2.16b eor BLK3.16b,BLK3.16b,IN3.16b sub IN,IN,#16 // have loaded 4blks, using 3blks to process, so step back 1blk here eor BLK0.16b,BLK0.16b,IN1.16b // in1 -> blk0 eor BLK1.16b,BLK1.16b,IN2.16b // in2 -> blk1 eor BLK2.16b,BLK2.16b,IN3.16b // in3 -> blk2 eor BLK3.16b,BLK3.16b,IN4.16b // in4 -> blk3 fmov TWX0,TWKD20 // reset already computed tweak fmov TWX1,TWKD21 b .Lxts_dec_rounds_3blks .Lxts_aesdec_finish: MOV_REG_TO_VEC(TWX0,TWX1,TWKD00,TWKD01) st1 {TWK0.16b}, [TWEAK] mov x0, #0 ldp d14, d15, [sp,#64] ldp d12, d13, [sp, #48] ldp d10, d11, [sp, #32] ldp d8, d9, [sp, #16] ldp x29, x30, [sp], #80 AARCH64_AUTIASP ret .size CRYPT_AES_XTS_Decrypt, .-CRYPT_AES_XTS_Decrypt #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_xts_armv8.S
Unix Assembly
unknown
25,458
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_XTS) #include "crypt_aes_macro_x86_64.s" .file "crypt_aes_xts_x86_64.S" .set KEY, %rdi .set IN, %rsi .set OUT, %rdx .set LEN, %ecx .set TWEAK, %r8 .set KTMP, %r9 .set LTMP, %r15d .set TAILNUM,%r14d .set TMPOUT,%r13 .set TMPIN,%r9 .set ROUNDS, %eax .set RET, %eax .set TROUNDS, %r10 .set ROUNDSQ,%rax .set KEYEND,%r9 .set WTMP0, %ecx .set WTMP1, %r10d .set WTMP2, %r11d .set XTMP0, %rcx .set XTMP1, %r10 .set XTMP2, %r11 .set TWX0, %r13 .set TWX1, %r14 .set BLK0, %xmm8 .set BLK1, %xmm9 .set BLK2, %xmm10 .set BLK3, %xmm11 .set BLK4, %xmm12 .set BLK5, %xmm13 .set BLK6, %xmm14 .set TWEAK0, %xmm0 .set TWEAK1, %xmm1 .set TWEAK2, %xmm2 .set TWEAK3, %xmm3 .set TWEAK4, %xmm4 .set TWEAK5, %xmm5 .set TWEAK6, %xmm6 .set RDK, %xmm15 .set RDK1, %xmm7 .set TMPX, %xmm7 .set GFP, %xmm6 .set TWKTMP, %xmm14 .macro NextTweakCore gfp, twkin, twktmp, tmp vmovdqa \twktmp,\tmp vpaddd \twktmp,\twktmp,\twktmp // doubleword << 1 vpsrad $31,\tmp,\tmp // ASR doubleword vpaddq \twkin,\twkin,\twkin // quadword << 1 vpand \gfp,\tmp,\tmp // and 0x10000000000000087 vpxor \tmp,\twkin,\twkin .endm .macro NextTweak gfp, twkin, twkout, twktmp, tmp NextTweakCore \gfp,\twkin,\twktmp,\tmp vmovdqa \twkin,\twkout .endm .macro SAVE_STACK push %rbx push %rbp push %rsp push %r12 push %r13 push %r14 push %r15 .endm .macro LOAD_STACK pop %r15 pop %r14 pop %r13 pop %r12 pop %rsp pop %rbp pop %rbx .endm .data .align 64 // modulus of Galois Field x^128+x^7+x^2+x+1 => 0x87(0b10000111) .Lgfp128: .long 0x87,0,1,0 .text /** * Function description: Sets the AES encryption assembly acceleration API in XTS mode. * Function prototype: int32_t CRYPT_AES_XTS_Encrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, uint8_t *out, uint32_t len); * Input register: * x0: Pointer to the input key structure. * x1: Points to the 128-bit input data. * x2: Points to the 128-bit output data. * x3: Indicates the length of a data block, that is, 16 bytes. * Change register: xmm1,xmm3,xmm4,xmm5,xmm6,xmm10,xmm11,xmm12,xmm13. * Output register: eax. * Function/Macro Call: None. */ .align 32 .globl CRYPT_AES_XTS_Encrypt .type CRYPT_AES_XTS_Encrypt, @function CRYPT_AES_XTS_Encrypt: .cfi_startproc pushq %rbx pushq %rbp pushq %r12 pushq %r13 pushq %r14 pushq %r15 sub $96,%rsp mov %rsp,%rbp and $-16,%rsp // 16 bytes align movl LEN, LTMP movl LEN, TAILNUM andl $-16,LTMP andl $0xf,TAILNUM // LEN % 16 movl 240(KEY), ROUNDS vmovdqa .Lgfp128(%rip),GFP vmovdqu (TWEAK), TWEAK0 shl $4,ROUNDS // roundkey size: rounds*16, except for the last one lea 16(KEY, ROUNDSQ),KEYEND // step to the end of roundkeys .Lxts_aesenc_start: cmpl $64, LTMP jae .Lxts_enc_above_equal_4_blks cmpl $32, LTMP jae .Lxts_enc_above_equal_2_blks cmpl $0, LTMP je .Lxts_aesenc_finish jmp .Lxts_enc_proc_1_blk .Lxts_enc_above_equal_2_blks: cmpl $48, LTMP jb .Lxts_enc_proc_2_blks jmp .Lxts_enc_proc_3_blks .Lxts_enc_above_equal_4_blks: cmpl $96, LTMP jae .Lxts_enc_proc_6_blks_pre cmpl $80, LTMP jb .Lxts_enc_proc_4_blks jmp .Lxts_enc_proc_5_blks .align 16 .Lxts_enc_proc_1_blk: vmovdqu (IN),BLK0 .Lxts_enc_proc_1blk_loaded: mov KEY,KTMP vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK5 movl 240(KTMP), ROUNDS vmovdqu (KTMP), RDK vpxor RDK,BLK0,BLK0 decl ROUNDS vpxor TWEAK0, BLK0, BLK0 AES_ENC_1_BLK KTMP ROUNDS RDK BLK0 vpxor TWEAK0, BLK0, BLK0 vmovdqu BLK0, (OUT) NextTweak GFP, TWEAK5, TWEAK0, TWKTMP, TMPX lea 16(IN),IN subl $16,LTMP lea 16(OUT),OUT je .Lxts_aesenc_finish .align 16 .Lxts_enc_proc_2_blks: mov KEY,KTMP vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK5 movl 240(KTMP), ROUNDS vmovdqu (KTMP), RDK NextTweak GFP, TWEAK5, TWEAK1, TWKTMP, TMPX vpxor (IN), RDK, BLK0 vpxor 16(IN), RDK, BLK1 decl ROUNDS vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 AES_ENC_2_BLKS KTMP ROUNDS RDK BLK0 BLK1 vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vmovdqu BLK0, (OUT) vmovdqu BLK1, 16(OUT) NextTweak GFP, TWEAK5, TWEAK0, TWKTMP, TMPX lea 32(IN),IN subl $32,LTMP lea 32(OUT),OUT je .Lxts_aesenc_finish .align 16 .Lxts_enc_proc_3_blks: mov KEY,KTMP vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK5 movl 240(KTMP), ROUNDS vmovdqu (KTMP), RDK NextTweak GFP, TWEAK5, TWEAK1, TWKTMP, TMPX vpxor (IN), RDK, BLK0 vpxor 16(IN), RDK, BLK1 NextTweak GFP, TWEAK5, TWEAK2, TWKTMP, TMPX vpxor 32(IN), RDK, BLK2 decl ROUNDS vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 AES_ENC_3_BLKS KTMP ROUNDS RDK BLK0 BLK1 BLK2 vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 vmovdqu BLK0, (OUT) vmovdqu BLK1, 16(OUT) vmovdqu BLK2, 32(OUT) NextTweak GFP, TWEAK5, TWEAK0, TWKTMP, TMPX lea 48(IN),IN subl $48,LTMP lea 48(OUT),OUT je .Lxts_aesenc_finish .align 16 .Lxts_enc_proc_4_blks: mov KEY,KTMP vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK5 movl 240(KTMP), ROUNDS vmovdqu (KTMP), RDK NextTweak GFP, TWEAK5, TWEAK1, TWKTMP, TMPX vpxor (IN), RDK, BLK0 vpxor 16(IN), RDK, BLK1 NextTweak GFP, TWEAK5, TWEAK2, TWKTMP, TMPX vpxor 32(IN), RDK, BLK2 NextTweak GFP, TWEAK5, TWEAK3, TWKTMP, TMPX vpxor 48(IN), RDK, BLK3 decl ROUNDS vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 vpxor TWEAK3, BLK3, BLK3 AES_ENC_4_BLKS KTMP ROUNDS RDK BLK0 BLK1 BLK2 BLK3 vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 vpxor TWEAK3, BLK3, BLK3 vmovdqu BLK0, (OUT) vmovdqu BLK1, 16(OUT) vmovdqu BLK2, 32(OUT) vmovdqu BLK3, 48(OUT) NextTweak GFP, TWEAK5, TWEAK0, TWKTMP, TMPX lea 64(IN),IN subl $64,LTMP lea 64(OUT),OUT je .Lxts_aesenc_finish .align 16 .Lxts_enc_proc_5_blks: mov KEY,KTMP vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK5 movl 240(KTMP), ROUNDS vmovdqu (KTMP), RDK NextTweak GFP, TWEAK5, TWEAK1, TWKTMP, TMPX vpxor (IN), RDK, BLK0 vpxor 16(IN), RDK, BLK1 NextTweak GFP, TWEAK5, TWEAK2, TWKTMP, TMPX vpxor 32(IN), RDK, BLK2 NextTweak GFP, TWEAK5, TWEAK3, TWKTMP, TMPX vpxor 48(IN), RDK, BLK3 NextTweak GFP, TWEAK5, TWEAK4, TWKTMP, TMPX vpxor 64(IN), RDK, BLK4 decl ROUNDS vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 vpxor TWEAK3, BLK3, BLK3 vpxor TWEAK4, BLK4, BLK4 AES_ENC_5_BLKS KTMP ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 vpxor TWEAK3, BLK3, BLK3 vpxor TWEAK4, BLK4, BLK4 vmovdqu BLK0, (OUT) vmovdqu BLK1, 16(OUT) vmovdqu BLK2, 32(OUT) vmovdqu BLK3, 48(OUT) vmovdqu BLK4, 64(OUT) NextTweak GFP, TWEAK5, TWEAK0, TWKTMP, TMPX lea 80(IN),IN subl $80,LTMP lea 80(OUT),OUT je .Lxts_aesenc_finish .align 16 .Lxts_enc_proc_6_blks_pre: vpshufd $0x5f,TWEAK0,TWKTMP // save higher doubleword of tweak vmovdqa TWEAK0,TWEAK5 // copy first tweak NextTweak GFP, TWEAK5, TWEAK1, TWKTMP, TMPX NextTweak GFP, TWEAK5, TWEAK2, TWKTMP, TMPX NextTweak GFP, TWEAK5, TWEAK3, TWKTMP, TMPX NextTweak GFP, TWEAK5, TWEAK4, TWKTMP, TMPX NextTweakCore GFP, TWEAK5, TWKTMP, TMPX .Lxts_enc_proc_6_blks: vmovdqu (KEY), RDK vmovdqu (IN),BLK0 vpxor TWEAK0,BLK0,BLK0 // blk0 ^= tweak0 vpxor RDK,BLK0,BLK0 // blk0 = blk0 ^ tweak0 ^ rk0, prepared for the loop round vmovdqu -16(KEYEND),RDK1 // load last round key vmovdqu 16(IN),BLK1 vpxor RDK1,TWEAK0,TWEAK0 aesenc 16(KEY),BLK0 // first round: rk1 vmovdqa TWEAK0,(%rsp) vpxor TWEAK1,BLK1,BLK1 vpxor RDK,BLK1,BLK1 vmovdqu 32(IN),BLK2 vpxor RDK1,TWEAK1,TWEAK1 aesenc 16(KEY),BLK1 vmovdqa TWEAK1,16(%rsp) vpxor TWEAK2,BLK2,BLK2 vpxor RDK,BLK2,BLK2 vmovdqu 48(IN),BLK3 vpxor RDK1,TWEAK2,TWEAK2 aesenc 16(KEY),BLK2 vmovdqa TWEAK2,32(%rsp) vpxor TWEAK3,BLK3,BLK3 vpxor RDK,BLK3,BLK3 vmovdqu 64(IN),BLK4 vpxor RDK1,TWEAK3,TWEAK3 aesenc 16(KEY),BLK3 vmovdqa TWEAK3,48(%rsp) vpxor TWEAK4,BLK4,BLK4 vpxor RDK,BLK4,BLK4 vmovdqu 80(IN),BLK5 vpxor RDK1,TWEAK4,TWEAK4 aesenc 16(KEY),BLK4 vmovdqa TWEAK4,64(%rsp) vpxor TWEAK5,BLK5,BLK5 vpxor RDK,BLK5,BLK5 vpxor RDK1,TWEAK5,TWEAK5 aesenc 16(KEY),BLK5 vmovdqa TWEAK5,80(%rsp) mov $(7*16),TROUNDS // loop 7 rounds sub ROUNDSQ,TROUNDS .align 16 .Lxts_6_blks_loop: vmovdqu -96(KEYEND,TROUNDS),RDK // left 5+1 block to interval aesenc RDK, BLK0 aesenc RDK, BLK1 aesenc RDK, BLK2 add $16,TROUNDS aesenc RDK, BLK3 aesenc RDK, BLK4 aesenc RDK, BLK5 jnz .Lxts_6_blks_loop vpxor 80(%rsp),RDK1,TWEAK5 // tweak5 = tweak5^lastroundkey^lastroundkey vmovdqu -96(KEYEND,TROUNDS),RDK vpshufd $0x5f,TWEAK5,TWKTMP // use new tweak-tmp vmovdqa TWKTMP,TMPX // pre-calculate next round tweak0~tweak5 aesenc RDK, BLK0 vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesenc RDK, BLK1 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesenc RDK, BLK2 vpxor TMPX,TWEAK5,TWEAK5 add $16,TROUNDS aesenc RDK, BLK3 vmovdqa TWEAK5,TWEAK0 aesenc RDK, BLK4 aesenc RDK, BLK5 vmovdqu -96(KEYEND,TROUNDS),RDK vmovdqa TWKTMP,TMPX aesenc RDK, BLK0 vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesenc RDK, BLK1 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesenc RDK, BLK2 vpxor TMPX,TWEAK5,TWEAK5 add $16,TROUNDS aesenc RDK, BLK3 vmovdqa TWEAK5,TWEAK1 aesenc RDK, BLK4 aesenc RDK, BLK5 vmovdqu -96(KEYEND,TROUNDS),RDK vmovdqa TWKTMP,TMPX aesenc RDK, BLK0 vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesenc RDK, BLK1 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesenc RDK, BLK2 vpxor TMPX,TWEAK5,TWEAK5 add $16,TROUNDS aesenc RDK, BLK3 vmovdqa TWEAK5,TWEAK2 aesenc RDK, BLK4 aesenc RDK, BLK5 vmovdqu -96(KEYEND,TROUNDS),RDK vmovdqa TWKTMP,TMPX aesenc RDK, BLK0 vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesenc RDK, BLK1 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesenc RDK, BLK2 vpxor TMPX,TWEAK5,TWEAK5 add $16,TROUNDS aesenc RDK, BLK3 vmovdqa TWEAK5,TWEAK3 aesenc RDK, BLK4 aesenc RDK, BLK5 vmovdqu -96(KEYEND,TROUNDS),RDK vmovdqa TWKTMP,TMPX aesenc RDK, BLK0 vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesenc RDK, BLK1 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesenc RDK, BLK2 vpxor TMPX,TWEAK5,TWEAK5 aesenc RDK, BLK3 vmovdqa TWEAK5,TWEAK4 aesenc RDK, BLK4 aesenc RDK, BLK5 vmovdqa TWKTMP,TMPX aesenclast (%rsp), BLK0 aesenclast 16(%rsp), BLK1 // already do the tweak^lastround, so here just aesenclast vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesenclast 32(%rsp), BLK2 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesenclast 48(%rsp), BLK3 vpxor TMPX,TWEAK5,TWEAK5 aesenclast 64(%rsp), BLK4 aesenclast 80(%rsp), BLK5 vmovdqu BLK0, (OUT) vmovdqu BLK1, 16(OUT) vmovdqu BLK2, 32(OUT) vmovdqu BLK3, 48(OUT) vmovdqu BLK4, 64(OUT) vmovdqu BLK5, 80(OUT) leaq 96(IN), IN leaq 96(OUT), OUT sub $96, LTMP cmp $96, LTMP jb .Lxts_aesenc_start jmp .Lxts_enc_proc_6_blks .align 16 .Lxts_aesenc_finish: cmp $0,TAILNUM je .Lxts_ret .Lxts_tail_proc: mov OUT,TMPOUT mov IN,TMPIN .Lxts_tail_loop: sub $1,TAILNUM movzb -16(TMPOUT),%r10d movzb (TMPIN),%r11d mov %r10b,(TMPOUT) lea 1(TMPIN),TMPIN mov %r11b,-16(TMPOUT) lea 1(TMPOUT),TMPOUT ja .Lxts_tail_loop sub $16,OUT // step 1 block back to save the last stealing block encryption add $16,LTMP vmovdqu (OUT),BLK0 jmp .Lxts_enc_proc_1blk_loaded .Lxts_ret: vmovdqu TWEAK0, (TWEAK) vpxor BLK0, BLK0, BLK0 vpxor BLK1, BLK1, BLK1 vpxor BLK2, BLK2, BLK2 vpxor BLK3, BLK3, BLK3 vpxor BLK4, BLK4, BLK4 vpxor BLK5, BLK5, BLK5 vpxor BLK6, BLK6, BLK6 vpxor RDK, RDK, RDK movl $0, RET mov %rbp,%rsp add $96,%rsp popq %r15 popq %r14 popq %r13 popq %r12 popq %rbp popq %rbx ret .cfi_endproc .size CRYPT_AES_XTS_Encrypt, .-CRYPT_AES_XTS_Encrypt /** * Function description: Sets the AES decryption and assembly acceleration API in XTS mode. * Function prototype: int32_t CRYPT_AES_XTS_Decrypt(const CRYPT_AES_Key *ctx, * const uint8_t *in, uint8_t *out, uint32_t len); * Input register: * x0: Pointer to the input key structure. * x1: Points to the 128-bit input data. * x2: Indicates the 128-bit output data. * x3: Indicates the length of a data block, that is, 16 bytes. * Change register: xmm1,xmm3,xmm4,xmm5,xmm6,xmm10,xmm11,xmm12,xmm13. * Output register: eax. * Function/Macro Call: None. */ .align 32 .globl CRYPT_AES_XTS_Decrypt .type CRYPT_AES_XTS_Decrypt, @function CRYPT_AES_XTS_Decrypt: .cfi_startproc pushq %rbx pushq %rbp pushq %r12 pushq %r13 pushq %r14 pushq %r15 sub $96,%rsp mov %rsp,%rbp and $-16,%rsp // 16 bytes align movl LEN, LTMP movl LEN, TAILNUM andl $-16,LTMP movl LTMP,WTMP2 sub $16,WTMP2 // preserve last and tail block andl $0xf,TAILNUM // LEN % 16 cmovg WTMP2,LTMP movl 240(KEY), ROUNDS vmovdqa .Lgfp128(%rip),GFP vmovdqu (TWEAK), TWEAK0 shl $4,ROUNDS // roundkey size: rounds*16, except for the last one lea 16(KEY, ROUNDSQ),KEYEND // step to the end of roundkeys .Lxts_aesdec_start: cmpl $64, LTMP jae .Lxts_dec_above_equal_4_blks cmpl $32, LTMP jae .Lxts_dec_above_equal_2_blks cmpl $0, LTMP je .Lxts_dec_last_2blks jmp .Lxts_dec_proc_1_blk .Lxts_dec_above_equal_2_blks: cmpl $48, LTMP jb .Lxts_dec_proc_2_blks jmp .Lxts_dec_proc_3_blks .Lxts_dec_above_equal_4_blks: cmpl $96, LTMP jae .Lxts_dec_proc_6_blks_pre cmpl $80, LTMP jb .Lxts_dec_proc_4_blks jmp .Lxts_dec_proc_5_blks .align 16 .Lxts_dec_tail_proc: cmp $0,TAILNUM je .Lxts_aesdec_finish vmovdqa TWEAK1,TWEAK0 // restore back tweak0 mov OUT,TMPOUT mov IN,TMPIN .Lxts_dec_tail_loop: sub $1,TAILNUM movzb -16(TMPOUT),%r10d movzb (TMPIN),%r11d mov %r10b,(TMPOUT) lea 1(TMPIN),TMPIN mov %r11b,-16(TMPOUT) lea 1(TMPOUT),TMPOUT ja .Lxts_dec_tail_loop sub $16,OUT // step 1 block back to save the last stealing block encryption add $16,LTMP vmovdqu (OUT),BLK0 jmp .Lxts_dec_proc_1blk_loaded .align 16 .Lxts_dec_last_2blks: cmp $0,TAILNUM je .Lxts_aesdec_finish vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK1 // tail block use tweak0, last block use tweak1 NextTweakCore GFP, TWEAK0, TWKTMP, TMPX .Lxts_dec_proc_1_blk: vmovdqu (IN),BLK0 .Lxts_dec_proc_1blk_loaded: mov KEY,KTMP vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK5 movl 240(KTMP), ROUNDS vmovdqu (KTMP), RDK vpxor RDK,BLK0,BLK0 decl ROUNDS vpxor TWEAK0, BLK0, BLK0 AES_DEC_1_BLK KTMP ROUNDS RDK BLK0 vpxor TWEAK0, BLK0, BLK0 vmovdqu BLK0, (OUT) NextTweak GFP, TWEAK5, TWEAK0, TWKTMP, TMPX lea 16(IN),IN subl $16,LTMP lea 16(OUT),OUT jl .Lxts_dec_tail_proc jmp .Lxts_aesdec_start .align 16 .Lxts_dec_proc_2_blks: mov KEY,KTMP vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK5 movl 240(KTMP), ROUNDS vmovdqu (KTMP), RDK NextTweak GFP, TWEAK5, TWEAK1, TWKTMP, TMPX vpxor (IN), RDK, BLK0 vpxor 16(IN), RDK, BLK1 decl ROUNDS vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 AES_DEC_2_BLKS KTMP ROUNDS RDK BLK0 BLK1 vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vmovdqu BLK0, (OUT) vmovdqu BLK1, 16(OUT) NextTweak GFP, TWEAK5, TWEAK0, TWKTMP, TMPX lea 32(IN),IN subl $32,LTMP lea 32(OUT),OUT jge .Lxts_aesdec_start .align 16 .Lxts_dec_proc_3_blks: mov KEY,KTMP vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK5 movl 240(KTMP), ROUNDS vmovdqu (KTMP), RDK NextTweak GFP, TWEAK5, TWEAK1, TWKTMP, TMPX vpxor (IN), RDK, BLK0 vpxor 16(IN), RDK, BLK1 NextTweak GFP, TWEAK5, TWEAK2, TWKTMP, TMPX vpxor 32(IN), RDK, BLK2 decl ROUNDS vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 AES_DEC_3_BLKS KTMP ROUNDS RDK BLK0 BLK1 BLK2 vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 vmovdqu BLK0, (OUT) vmovdqu BLK1, 16(OUT) vmovdqu BLK2, 32(OUT) NextTweak GFP, TWEAK5, TWEAK0, TWKTMP, TMPX lea 48(IN),IN subl $48,LTMP lea 48(OUT),OUT jge .Lxts_aesdec_start .align 16 .Lxts_dec_proc_4_blks: mov KEY,KTMP vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK5 movl 240(KTMP), ROUNDS vmovdqu (KTMP), RDK NextTweak GFP, TWEAK5, TWEAK1, TWKTMP, TMPX vpxor (IN), RDK, BLK0 vpxor 16(IN), RDK, BLK1 NextTweak GFP, TWEAK5, TWEAK2, TWKTMP, TMPX vpxor 32(IN), RDK, BLK2 NextTweak GFP, TWEAK5, TWEAK3, TWKTMP, TMPX vpxor 48(IN), RDK, BLK3 decl ROUNDS vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 vpxor TWEAK3, BLK3, BLK3 AES_DEC_4_BLKS KTMP ROUNDS RDK BLK0 BLK1 BLK2 BLK3 vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 vpxor TWEAK3, BLK3, BLK3 vmovdqu BLK0, (OUT) vmovdqu BLK1, 16(OUT) vmovdqu BLK2, 32(OUT) vmovdqu BLK3, 48(OUT) NextTweak GFP, TWEAK5, TWEAK0, TWKTMP, TMPX lea 64(IN),IN subl $64,LTMP lea 64(OUT),OUT jge .Lxts_aesdec_start .align 16 .Lxts_dec_proc_5_blks: mov KEY,KTMP vpshufd $0x5f,TWEAK0,TWKTMP vmovdqa TWEAK0,TWEAK5 movl 240(KTMP), ROUNDS vmovdqu (KTMP), RDK NextTweak GFP, TWEAK5, TWEAK1, TWKTMP, TMPX vpxor (IN), RDK, BLK0 vpxor 16(IN), RDK, BLK1 NextTweak GFP, TWEAK5, TWEAK2, TWKTMP, TMPX vpxor 32(IN), RDK, BLK2 NextTweak GFP, TWEAK5, TWEAK3, TWKTMP, TMPX vpxor 48(IN), RDK, BLK3 NextTweak GFP, TWEAK5, TWEAK4, TWKTMP, TMPX vpxor 64(IN), RDK, BLK4 decl ROUNDS vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 vpxor TWEAK3, BLK3, BLK3 vpxor TWEAK4, BLK4, BLK4 AES_DEC_5_BLKS KTMP ROUNDS RDK BLK0 BLK1 BLK2 BLK3 BLK4 vpxor TWEAK0, BLK0, BLK0 vpxor TWEAK1, BLK1, BLK1 vpxor TWEAK2, BLK2, BLK2 vpxor TWEAK3, BLK3, BLK3 vpxor TWEAK4, BLK4, BLK4 vmovdqu BLK0, (OUT) vmovdqu BLK1, 16(OUT) vmovdqu BLK2, 32(OUT) vmovdqu BLK3, 48(OUT) vmovdqu BLK4, 64(OUT) NextTweak GFP, TWEAK5, TWEAK0, TWKTMP, TMPX lea 80(IN),IN subl $80,LTMP lea 80(OUT),OUT jge .Lxts_aesdec_start .align 32 .Lxts_dec_proc_6_blks_pre: vpshufd $0x5f,TWEAK0,TWKTMP // save higher doubleword of tweak vmovdqa TWEAK0,TWEAK5 // copy first tweak NextTweak GFP, TWEAK5, TWEAK1, TWKTMP, TMPX NextTweak GFP, TWEAK5, TWEAK2, TWKTMP, TMPX NextTweak GFP, TWEAK5, TWEAK3, TWKTMP, TMPX NextTweak GFP, TWEAK5, TWEAK4, TWKTMP, TMPX NextTweakCore GFP, TWEAK5, TWKTMP, TMPX .align 32 .Lxts_dec_proc_6_blks: vmovdqu (KEY), RDK vmovdqu (IN),BLK0 vpxor TWEAK0,BLK0,BLK0 // blk0 ^= tweak0 vpxor RDK,BLK0,BLK0 // blk0 = blk0 ^ tweak0 ^ rk0, prepared for the loop round vmovdqu -16(KEYEND),RDK1 // load last round key vmovdqu 16(IN),BLK1 vpxor RDK1,TWEAK0,TWEAK0 aesdec 16(KEY),BLK0 // first round: rk1 vmovdqa TWEAK0,(%rsp) vpxor TWEAK1,BLK1,BLK1 vpxor RDK,BLK1,BLK1 vmovdqu 32(IN),BLK2 vpxor RDK1,TWEAK1,TWEAK1 aesdec 16(KEY),BLK1 vmovdqa TWEAK1,16(%rsp) vpxor TWEAK2,BLK2,BLK2 vpxor RDK,BLK2,BLK2 vmovdqu 48(IN),BLK3 vpxor RDK1,TWEAK2,TWEAK2 aesdec 16(KEY),BLK2 vmovdqa TWEAK2,32(%rsp) vpxor TWEAK3,BLK3,BLK3 vpxor RDK,BLK3,BLK3 vmovdqu 64(IN),BLK4 vpxor RDK1,TWEAK3,TWEAK3 aesdec 16(KEY),BLK3 vmovdqa TWEAK3,48(%rsp) vpxor TWEAK4,BLK4,BLK4 vpxor RDK,BLK4,BLK4 vmovdqu 80(IN),BLK5 vpxor RDK1,TWEAK4,TWEAK4 aesdec 16(KEY),BLK4 vmovdqa TWEAK4,64(%rsp) vpxor TWEAK5,BLK5,BLK5 vpxor RDK,BLK5,BLK5 vpxor RDK1,TWEAK5,TWEAK5 aesdec 16(KEY),BLK5 vmovdqa TWEAK5,80(%rsp) mov $(7*16),TROUNDS // loop 7 rounds sub ROUNDSQ,TROUNDS .align 32 .Lxts_dec_6blks_loop: vmovdqu -96(KEYEND,TROUNDS),RDK // left 5+1 block to interval aesdec RDK, BLK0 aesdec RDK, BLK1 aesdec RDK, BLK2 add $16,TROUNDS aesdec RDK, BLK3 aesdec RDK, BLK4 aesdec RDK, BLK5 jnz .Lxts_dec_6blks_loop vpxor 80(%rsp),RDK1,TWEAK5 // tweak5 = tweak5^lastroundkey^lastroundkey vmovdqu -96(KEYEND,TROUNDS),RDK vpshufd $0x5f,TWEAK5,TWKTMP // use new tweak-tmp vmovdqa TWKTMP,TMPX // pre-calculate next round tweak0~tweak5 aesdec RDK, BLK0 vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesdec RDK, BLK1 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesdec RDK, BLK2 vpxor TMPX,TWEAK5,TWEAK5 add $16,TROUNDS aesdec RDK, BLK3 vmovdqa TWEAK5,TWEAK0 aesdec RDK, BLK4 aesdec RDK, BLK5 vmovdqu -96(KEYEND,TROUNDS),RDK vmovdqa TWKTMP,TMPX aesdec RDK, BLK0 vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesdec RDK, BLK1 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesdec RDK, BLK2 vpxor TMPX,TWEAK5,TWEAK5 add $16,TROUNDS aesdec RDK, BLK3 vmovdqa TWEAK5,TWEAK1 aesdec RDK, BLK4 aesdec RDK, BLK5 vmovdqu -96(KEYEND,TROUNDS),RDK vmovdqa TWKTMP,TMPX aesdec RDK, BLK0 vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesdec RDK, BLK1 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesdec RDK, BLK2 vpxor TMPX,TWEAK5,TWEAK5 add $16,TROUNDS aesdec RDK, BLK3 vmovdqa TWEAK5,TWEAK2 aesdec RDK, BLK4 aesdec RDK, BLK5 vmovdqu -96(KEYEND,TROUNDS),RDK vmovdqa TWKTMP,TMPX aesdec RDK, BLK0 vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesdec RDK, BLK1 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesdec RDK, BLK2 vpxor TMPX,TWEAK5,TWEAK5 add $16,TROUNDS aesdec RDK, BLK3 vmovdqa TWEAK5,TWEAK3 aesdec RDK, BLK4 aesdec RDK, BLK5 vmovdqu -96(KEYEND,TROUNDS),RDK vmovdqa TWKTMP,TMPX aesdec RDK, BLK0 vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesdec RDK, BLK1 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesdec RDK, BLK2 vpxor TMPX,TWEAK5,TWEAK5 aesdec RDK, BLK3 vmovdqa TWEAK5,TWEAK4 aesdec RDK, BLK4 aesdec RDK, BLK5 vmovdqa TWKTMP,TMPX aesdeclast (%rsp), BLK0 aesdeclast 16(%rsp), BLK1 // already do the tweak^lastround, so here just aesdeclast vpaddd TWKTMP,TWKTMP,TWKTMP vpsrad $31,TMPX,TMPX aesdeclast 32(%rsp), BLK2 vpaddq TWEAK5,TWEAK5,TWEAK5 vpand GFP,TMPX,TMPX aesdeclast 48(%rsp), BLK3 vpxor TMPX,TWEAK5,TWEAK5 aesdeclast 64(%rsp), BLK4 aesdeclast 80(%rsp), BLK5 vmovdqu BLK0, (OUT) vmovdqu BLK1, 16(OUT) vmovdqu BLK2, 32(OUT) vmovdqu BLK3, 48(OUT) vmovdqu BLK4, 64(OUT) vmovdqu BLK5, 80(OUT) leaq 96(IN), IN leaq 96(OUT), OUT sub $96, LTMP cmp $96, LTMP jb .Lxts_aesdec_start jmp .Lxts_dec_proc_6_blks .align 16 .Lxts_aesdec_finish: vmovdqu TWEAK0, (TWEAK) vpxor BLK0, BLK0, BLK0 vpxor BLK1, BLK1, BLK1 vpxor BLK2, BLK2, BLK2 vpxor BLK3, BLK3, BLK3 vpxor BLK4, BLK4, BLK4 vpxor BLK5, BLK5, BLK5 vpxor BLK6, BLK6, BLK6 vpxor RDK, RDK, RDK movl $0, RET mov %rbp,%rsp add $96,%rsp popq %r15 popq %r14 popq %r13 popq %r12 popq %rbp popq %rbx ret .cfi_endproc .size CRYPT_AES_XTS_Decrypt, .-CRYPT_AES_XTS_Decrypt #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/asm/crypt_aes_xts_x86_64.S
Unix Assembly
unknown
25,529
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_AES #include "securec.h" #include "bsl_err_internal.h" #include "crypt_utils.h" #include "crypt_errno.h" #include "bsl_sal.h" #ifdef HITLS_CRYPTO_AES_PRECALC_TABLES #include "crypt_aes_tbox.h" #else #include "crypt_aes_sbox.h" #endif #include "crypt_aes.h" void SetEncryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key) { ctx->rounds = 10; // 10 rounds #ifdef HITLS_CRYPTO_AES_PRECALC_TABLES SetAesKeyExpansionTbox(ctx, CRYPT_AES_128, key, true); #else SetAesKeyExpansionSbox(ctx, CRYPT_AES_128, key); #endif } void SetEncryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key) { ctx->rounds = 12; // 12 rounds #ifdef HITLS_CRYPTO_AES_PRECALC_TABLES SetAesKeyExpansionTbox(ctx, CRYPT_AES_192, key, true); #else SetAesKeyExpansionSbox(ctx, CRYPT_AES_192, key); #endif } void SetEncryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key) { ctx->rounds = 14; // 14 rounds #ifdef HITLS_CRYPTO_AES_PRECALC_TABLES SetAesKeyExpansionTbox(ctx, CRYPT_AES_256, key, true); #else SetAesKeyExpansionSbox(ctx, CRYPT_AES_256, key); #endif } void SetDecryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key) { ctx->rounds = 10; // 10 rounds #ifdef HITLS_CRYPTO_AES_PRECALC_TABLES SetAesKeyExpansionTbox(ctx, CRYPT_AES_128, key, false); #else SetAesKeyExpansionSbox(ctx, CRYPT_AES_128, key); #endif } void SetDecryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key) { ctx->rounds = 12; // 12 rounds #ifdef HITLS_CRYPTO_AES_PRECALC_TABLES SetAesKeyExpansionTbox(ctx, CRYPT_AES_192, key, false); #else SetAesKeyExpansionSbox(ctx, CRYPT_AES_192, key); #endif } void SetDecryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key) { ctx->rounds = 14; // 14 rounds #ifdef HITLS_CRYPTO_AES_PRECALC_TABLES SetAesKeyExpansionTbox(ctx, CRYPT_AES_256, key, false); #else SetAesKeyExpansionSbox(ctx, CRYPT_AES_256, key); #endif } int32_t CRYPT_AES_Encrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { #ifdef HITLS_CRYPTO_AES_PRECALC_TABLES CRYPT_AES_EncryptTbox(ctx, in, out, len); #else CRYPT_AES_EncryptSbox(ctx, in, out, len); #endif return CRYPT_SUCCESS; } int32_t CRYPT_AES_Decrypt(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { #ifdef HITLS_CRYPTO_AES_PRECALC_TABLES CRYPT_AES_DecryptTbox(ctx, in, out, len); #else CRYPT_AES_DecryptSbox(ctx, in, out, len); #endif return CRYPT_SUCCESS; } #endif /* HITLS_CRYPTO_AES */
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/crypt_aes.c
C
unknown
3,030
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_AES_LOCAL_H #define CRYPT_AES_LOCAL_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_AES #include "crypt_aes.h" void SetEncryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key); void SetEncryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key); void SetEncryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key); void SetDecryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key); void SetDecryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key); void SetDecryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key); #endif // HITLS_CRYPTO_AES #endif // CRYPT_AES_LOCAL_H
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/crypt_aes_local.h
C
unknown
1,111
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && !defined(HITLS_CRYPTO_AES_PRECALC_TABLES) #include "securec.h" #include "bsl_err_internal.h" #include "crypt_utils.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "crypt_aes.h" #include "crypt_aes_sbox.h" #define BYTE_BITS 8 static const uint8_t AES_S[256] = { 0x63U, 0x7cU, 0x77U, 0x7bU, 0xf2U, 0x6bU, 0x6fU, 0xc5U, 0x30U, 0x01U, 0x67U, 0x2bU, 0xfeU, 0xd7U, 0xabU, 0x76U, 0xcaU, 0x82U, 0xc9U, 0x7dU, 0xfaU, 0x59U, 0x47U, 0xf0U, 0xadU, 0xd4U, 0xa2U, 0xafU, 0x9cU, 0xa4U, 0x72U, 0xc0U, 0xb7U, 0xfdU, 0x93U, 0x26U, 0x36U, 0x3fU, 0xf7U, 0xccU, 0x34U, 0xa5U, 0xe5U, 0xf1U, 0x71U, 0xd8U, 0x31U, 0x15U, 0x04U, 0xc7U, 0x23U, 0xc3U, 0x18U, 0x96U, 0x05U, 0x9aU, 0x07U, 0x12U, 0x80U, 0xe2U, 0xebU, 0x27U, 0xb2U, 0x75U, 0x09U, 0x83U, 0x2cU, 0x1aU, 0x1bU, 0x6eU, 0x5aU, 0xa0U, 0x52U, 0x3bU, 0xd6U, 0xb3U, 0x29U, 0xe3U, 0x2fU, 0x84U, 0x53U, 0xd1U, 0x00U, 0xedU, 0x20U, 0xfcU, 0xb1U, 0x5bU, 0x6aU, 0xcbU, 0xbeU, 0x39U, 0x4aU, 0x4cU, 0x58U, 0xcfU, 0xd0U, 0xefU, 0xaaU, 0xfbU, 0x43U, 0x4dU, 0x33U, 0x85U, 0x45U, 0xf9U, 0x02U, 0x7fU, 0x50U, 0x3cU, 0x9fU, 0xa8U, 0x51U, 0xa3U, 0x40U, 0x8fU, 0x92U, 0x9dU, 0x38U, 0xf5U, 0xbcU, 0xb6U, 0xdaU, 0x21U, 0x10U, 0xffU, 0xf3U, 0xd2U, 0xcdU, 0x0cU, 0x13U, 0xecU, 0x5fU, 0x97U, 0x44U, 0x17U, 0xc4U, 0xa7U, 0x7eU, 0x3dU, 0x64U, 0x5dU, 0x19U, 0x73U, 0x60U, 0x81U, 0x4fU, 0xdcU, 0x22U, 0x2aU, 0x90U, 0x88U, 0x46U, 0xeeU, 0xb8U, 0x14U, 0xdeU, 0x5eU, 0x0bU, 0xdbU, 0xe0U, 0x32U, 0x3aU, 0x0aU, 0x49U, 0x06U, 0x24U, 0x5cU, 0xc2U, 0xd3U, 0xacU, 0x62U, 0x91U, 0x95U, 0xe4U, 0x79U, 0xe7U, 0xc8U, 0x37U, 0x6dU, 0x8dU, 0xd5U, 0x4eU, 0xa9U, 0x6cU, 0x56U, 0xf4U, 0xeaU, 0x65U, 0x7aU, 0xaeU, 0x08U, 0xbaU, 0x78U, 0x25U, 0x2eU, 0x1cU, 0xa6U, 0xb4U, 0xc6U, 0xe8U, 0xddU, 0x74U, 0x1fU, 0x4bU, 0xbdU, 0x8bU, 0x8aU, 0x70U, 0x3eU, 0xb5U, 0x66U, 0x48U, 0x03U, 0xf6U, 0x0eU, 0x61U, 0x35U, 0x57U, 0xb9U, 0x86U, 0xc1U, 0x1dU, 0x9eU, 0xe1U, 0xf8U, 0x98U, 0x11U, 0x69U, 0xd9U, 0x8eU, 0x94U, 0x9bU, 0x1eU, 0x87U, 0xe9U, 0xceU, 0x55U, 0x28U, 0xdfU, 0x8cU, 0xa1U, 0x89U, 0x0dU, 0xbfU, 0xe6U, 0x42U, 0x68U, 0x41U, 0x99U, 0x2dU, 0x0fU, 0xb0U, 0x54U, 0xbbU, 0x16U }; #define SEARCH_SBOX(t) \ ((AES_S[((t) >> 24)] << 24) | (AES_S[((t) >> 16) & 0xFF] << 16) | (AES_S[((t) >> 8) & 0xFF] << 8) | \ (AES_S[((t) >> 0) & 0xFF] << 0)) #define SEARCH_INVSBOX(t) \ ((InvSubSbox(((t) >> 24)) << 24) | (InvSubSbox(((t) >> 16) & 0xFF) << 16) | (InvSubSbox(((t) >> 8) & 0xFF) << 8) | \ (InvSubSbox(((t) >> 0) & 0xFF) << 0)) void SetAesKeyExpansionSbox(CRYPT_AES_Key *ctx, uint32_t keyLenBits, const uint8_t *key) { uint32_t *ekey = ctx->key; uint32_t keyLenByte = keyLenBits / (sizeof(uint32_t) * BYTE_BITS); uint32_t i = 0; for (i = 0; i < keyLenByte; ++i) { ekey[i] = GET_UINT32_BE(key, i * sizeof(uint32_t)); } for (; i < 4 * (ctx->rounds + 1); ++i) { if ((i % keyLenByte) == 0) { ekey[i] = ekey[i - keyLenByte] ^ SEARCH_SBOX(ROTL32(ekey[i - 1], BYTE_BITS)) ^ RoundConstArray(i / keyLenByte - 1); } else if (keyLenByte > 6 && (i % keyLenByte) == 4) { ekey[i] = ekey[i - keyLenByte] ^ SEARCH_SBOX(ekey[i - 1]); } else { ekey[i] = ekey[i - keyLenByte] ^ ekey[i - 1]; } } } static void AesAddRoundKey(uint32_t *state, const uint32_t *round, int nr) { for (int i = 0; i < 4; ++i) { state[i] ^= round[4 * nr + i]; } } static void AesSubBytes(uint32_t *state) { for (int i = 0; i < 4; ++i) { state[i] = SEARCH_SBOX(state[i]); } } static void AesShiftRows(uint32_t *state) { uint32_t s[4] = {0}; for (int32_t i = 0; i < 4; ++i) { s[i] = state[i]; } state[0] = (s[0] & 0xFF000000) | (s[1] & 0xFF0000) | (s[2] & 0xFF00) | (s[3] & 0xFF); state[1] = (s[1] & 0xFF000000) | (s[2] & 0xFF0000) | (s[3] & 0xFF00) | (s[0] & 0xFF); state[2] = (s[2] & 0xFF000000) | (s[3] & 0xFF0000) | (s[0] & 0xFF00) | (s[1] & 0xFF); state[3] = (s[3] & 0xFF000000) | (s[0] & 0xFF0000) | (s[1] & 0xFF00) | (s[2] & 0xFF); } static uint8_t AesXtime(uint8_t x) { return ((x << 1) ^ (((x >> 7) & 1) * 0x1b)); } static uint8_t AesXtimes(uint8_t x, int ts) { uint8_t tmpX = x; int tmpTs = ts; while (tmpTs-- > 0) { tmpX = AesXtime(tmpX); } return tmpX; } static uint8_t AesMul(uint8_t x, uint8_t y) { return ((((y >> 0) & 1) * AesXtimes(x, 0)) ^ (((y >> 1) & 1) * AesXtimes(x, 1)) ^ (((y >> 2) & 1) * AesXtimes(x, 2)) ^ (((y >> 3) & 1) * AesXtimes(x, 3)) ^ (((y >> 4) & 1) * AesXtimes(x, 4)) ^ (((y >> 5) & 1) * AesXtimes(x, 5)) ^ (((y >> 6) & 1) * AesXtimes(x, 6)) ^ (((y >> 7) & 1) * AesXtimes(x, 7))); } static void AesMixColumns(uint32_t *state, bool isMixColumns) { uint8_t ts[16] = {0}; for (int32_t i = 0; i < 4; ++i) { PUT_UINT32_BE(state[i], ts, 4 * i); } uint8_t aesY[16] = {2, 3, 1, 1, 1, 2, 3, 1, 1, 1, 2, 3, 3, 1, 1, 2}; uint8_t aesInvY[16] = {0x0e, 0x0b, 0x0d, 0x09, 0x09, 0x0e, 0x0b, 0x0d, 0x0d, 0x09, 0x0e, 0x0b, 0x0b, 0x0d, 0x09, 0x0e}; uint8_t s[4]; uint8_t *y = isMixColumns == true ? aesY : aesInvY; for (int i = 0; i < 4; ++i) { for (int r = 0; r < 4; ++r) { s[r] = 0; for (int j = 0; j < 4; ++j) { s[r] = s[r] ^ AesMul(ts[i * 4 + j], y[r * 4 + j]); } } for (int r = 0; r < 4; ++r) { ts[i * 4 + r] = s[r]; } } for (int32_t i = 0; i < 4; ++i) { state[i] = GET_UINT32_BE(ts, 4 * i); } } // addRound + 9/11/13 * (sub + shiftRow + mix + addRound) + (sub + shiftRow + addRound) void CRYPT_AES_EncryptSbox(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { (void)len; uint32_t s[4] = {0}; for (int32_t i = 0; i < 4; ++i) { s[i] = GET_UINT32_BE(in, 4 * i); } uint32_t nr = 0; AesAddRoundKey(s, ctx->key, nr); for (nr = 1; nr < ctx->rounds; ++nr) { AesSubBytes(s); AesShiftRows(s); AesMixColumns(s, true); AesAddRoundKey(s, ctx->key, nr); } AesSubBytes(s); AesShiftRows(s); AesAddRoundKey(s, ctx->key, nr); for (int32_t i = 0; i < 4; ++i) { PUT_UINT32_BE(s[i], out, 4 * i); } } static void InvShiftRows(uint32_t *state) { uint32_t s[4] = {0}; for (int32_t i = 0; i < 4; ++i) { s[i] = state[i]; } state[0] = (s[0] & 0xFF000000) | (s[3] & 0xFF0000) | (s[2] & 0xFF00) | (s[1] & 0xFF); state[1] = (s[1] & 0xFF000000) | (s[0] & 0xFF0000) | (s[3] & 0xFF00) | (s[2] & 0xFF); state[2] = (s[2] & 0xFF000000) | (s[1] & 0xFF0000) | (s[0] & 0xFF00) | (s[3] & 0xFF); state[3] = (s[3] & 0xFF000000) | (s[2] & 0xFF0000) | (s[1] & 0xFF00) | (s[0] & 0xFF); } static void InvSubBytes(uint32_t *state) { for (int i = 0; i < 4; ++i) { state[i] = SEARCH_INVSBOX(state[i]); } } // (addRound + InvShiftRow + InvSub) + 9/11/13 * (addRound + invMix + InvShiftRow + InvSub) + addRound void CRYPT_AES_DecryptSbox(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { (void)len; uint32_t s[4] = {0}; for (int32_t i = 0; i < 4; ++i) { s[i] = GET_UINT32_BE(in, 4 * i); } uint32_t nr = ctx->rounds; AesAddRoundKey(s, ctx->key, nr); InvShiftRows(s); InvSubBytes(s); for (nr = ctx->rounds - 1; nr > 0; --nr) { AesAddRoundKey(s, ctx->key, nr); AesMixColumns(s, false); InvShiftRows(s); InvSubBytes(s); } AesAddRoundKey(s, ctx->key, nr); for (int32_t i = 0; i < 4; ++i) { PUT_UINT32_BE(s[i], out, 4 * i); } BSL_SAL_CleanseData(&s, 4 * sizeof(uint32_t)); } #endif /* HITLS_CRYPTO_AES && !HITLS_CRYPTO_AES_PRECALC_TABLES */
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/crypt_aes_sbox.c
C
unknown
8,560
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_AES_SBOX_H #define CRYPT_AES_SBOX_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && !defined(HITLS_CRYPTO_AES_PRECALC_TABLES) #include "crypt_aes.h" uint32_t RoundConstArray(int val); uint8_t InvSubSbox(uint8_t val); void SetAesKeyExpansionSbox(CRYPT_AES_Key *ctx, uint32_t keyLenBits, const uint8_t *key); void CRYPT_AES_EncryptSbox(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len); void CRYPT_AES_DecryptSbox(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len); #endif /* HITLS_CRYPTO_AES && !HITLS_CRYPTO_AES_PRECALC_TABLES */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/crypt_aes_sbox.h
C
unknown
1,189
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_AES #include "securec.h" #include "bsl_err_internal.h" #include "crypt_utils.h" #include "crypt_errno.h" #include "crypt_aes_local.h" #include "bsl_sal.h" int32_t CRYPT_AES_SetEncryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len) { if (ctx == NULL || key == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (len != 16) { BSL_ERR_PUSH_ERROR(CRYPT_AES_ERR_KEYLEN); return CRYPT_AES_ERR_KEYLEN; } SetEncryptKey128(ctx, key); return CRYPT_SUCCESS; } int32_t CRYPT_AES_SetEncryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len) { if (ctx == NULL || key == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (len != 24) { BSL_ERR_PUSH_ERROR(CRYPT_AES_ERR_KEYLEN); return CRYPT_AES_ERR_KEYLEN; } SetEncryptKey192(ctx, key); return CRYPT_SUCCESS; } int32_t CRYPT_AES_SetEncryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len) { if (ctx == NULL || key == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (len != 32) { BSL_ERR_PUSH_ERROR(CRYPT_AES_ERR_KEYLEN); return CRYPT_AES_ERR_KEYLEN; } SetEncryptKey256(ctx, key); return CRYPT_SUCCESS; } int32_t CRYPT_AES_SetDecryptKey128(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len) { if (ctx == NULL || key == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (len != 16) { BSL_ERR_PUSH_ERROR(CRYPT_AES_ERR_KEYLEN); return CRYPT_AES_ERR_KEYLEN; } SetDecryptKey128(ctx, key); return CRYPT_SUCCESS; } int32_t CRYPT_AES_SetDecryptKey192(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len) { if (ctx == NULL || key == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (len != 24) { BSL_ERR_PUSH_ERROR(CRYPT_AES_ERR_KEYLEN); return CRYPT_AES_ERR_KEYLEN; } SetDecryptKey192(ctx, key); return CRYPT_SUCCESS; } int32_t CRYPT_AES_SetDecryptKey256(CRYPT_AES_Key *ctx, const uint8_t *key, uint32_t len) { if (ctx == NULL || key == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (len != 32) { BSL_ERR_PUSH_ERROR(CRYPT_AES_ERR_KEYLEN); return CRYPT_AES_ERR_KEYLEN; } SetDecryptKey256(ctx, key); return CRYPT_SUCCESS; } void CRYPT_AES_Clean(CRYPT_AES_Key *ctx) { if (ctx == NULL) { return; } BSL_SAL_CleanseData((void *)(ctx), sizeof(CRYPT_AES_Key)); } #endif /* HITLS_CRYPTO_AES */
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/crypt_aes_setkey.c
C
unknown
3,263
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_AES #include "securec.h" #include "bsl_err_internal.h" #include "crypt_utils.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "crypt_aes.h" #include "crypt_aes_tbox.h" static const uint8_t INV_S[256] = { 0x52U, 0x09U, 0x6aU, 0xd5U, 0x30U, 0x36U, 0xa5U, 0x38U, 0xbfU, 0x40U, 0xa3U, 0x9eU, 0x81U, 0xf3U, 0xd7U, 0xfbU, 0x7cU, 0xe3U, 0x39U, 0x82U, 0x9bU, 0x2fU, 0xffU, 0x87U, 0x34U, 0x8eU, 0x43U, 0x44U, 0xc4U, 0xdeU, 0xe9U, 0xcbU, 0x54U, 0x7bU, 0x94U, 0x32U, 0xa6U, 0xc2U, 0x23U, 0x3dU, 0xeeU, 0x4cU, 0x95U, 0x0bU, 0x42U, 0xfaU, 0xc3U, 0x4eU, 0x08U, 0x2eU, 0xa1U, 0x66U, 0x28U, 0xd9U, 0x24U, 0xb2U, 0x76U, 0x5bU, 0xa2U, 0x49U, 0x6dU, 0x8bU, 0xd1U, 0x25U, 0x72U, 0xf8U, 0xf6U, 0x64U, 0x86U, 0x68U, 0x98U, 0x16U, 0xd4U, 0xa4U, 0x5cU, 0xccU, 0x5dU, 0x65U, 0xb6U, 0x92U, 0x6cU, 0x70U, 0x48U, 0x50U, 0xfdU, 0xedU, 0xb9U, 0xdaU, 0x5eU, 0x15U, 0x46U, 0x57U, 0xa7U, 0x8dU, 0x9dU, 0x84U, 0x90U, 0xd8U, 0xabU, 0x00U, 0x8cU, 0xbcU, 0xd3U, 0x0aU, 0xf7U, 0xe4U, 0x58U, 0x05U, 0xb8U, 0xb3U, 0x45U, 0x06U, 0xd0U, 0x2cU, 0x1eU, 0x8fU, 0xcaU, 0x3fU, 0x0fU, 0x02U, 0xc1U, 0xafU, 0xbdU, 0x03U, 0x01U, 0x13U, 0x8aU, 0x6bU, 0x3aU, 0x91U, 0x11U, 0x41U, 0x4fU, 0x67U, 0xdcU, 0xeaU, 0x97U, 0xf2U, 0xcfU, 0xceU, 0xf0U, 0xb4U, 0xe6U, 0x73U, 0x96U, 0xacU, 0x74U, 0x22U, 0xe7U, 0xadU, 0x35U, 0x85U, 0xe2U, 0xf9U, 0x37U, 0xe8U, 0x1cU, 0x75U, 0xdfU, 0x6eU, 0x47U, 0xf1U, 0x1aU, 0x71U, 0x1dU, 0x29U, 0xc5U, 0x89U, 0x6fU, 0xb7U, 0x62U, 0x0eU, 0xaaU, 0x18U, 0xbeU, 0x1bU, 0xfcU, 0x56U, 0x3eU, 0x4bU, 0xc6U, 0xd2U, 0x79U, 0x20U, 0x9aU, 0xdbU, 0xc0U, 0xfeU, 0x78U, 0xcdU, 0x5aU, 0xf4U, 0x1fU, 0xddU, 0xa8U, 0x33U, 0x88U, 0x07U, 0xc7U, 0x31U, 0xb1U, 0x12U, 0x10U, 0x59U, 0x27U, 0x80U, 0xecU, 0x5fU, 0x60U, 0x51U, 0x7fU, 0xa9U, 0x19U, 0xb5U, 0x4aU, 0x0dU, 0x2dU, 0xe5U, 0x7aU, 0x9fU, 0x93U, 0xc9U, 0x9cU, 0xefU, 0xa0U, 0xe0U, 0x3bU, 0x4dU, 0xaeU, 0x2aU, 0xf5U, 0xb0U, 0xc8U, 0xebU, 0xbbU, 0x3cU, 0x83U, 0x53U, 0x99U, 0x61U, 0x17U, 0x2bU, 0x04U, 0x7eU, 0xbaU, 0x77U, 0xd6U, 0x26U, 0xe1U, 0x69U, 0x14U, 0x63U, 0x55U, 0x21U, 0x0cU, 0x7dU, }; static const uint32_t RCON[] = { 0x01000000, 0x02000000, 0x04000000, 0x08000000, 0x10000000, 0x20000000, 0x40000000, 0x80000000, 0x1B000000, 0x36000000, }; #ifndef HITLS_CRYPTO_AES_PRECALC_TABLES uint32_t RoundConstArray(uint8_t val) { return RCON[val]; } uint8_t InvSubSbox(uint8_t val) { return INV_S[val]; } #endif #ifdef HITLS_CRYPTO_AES_PRECALC_TABLES #define TESEARCH(t0, t1, t2, t3) \ (((uint32_t)TE2[((t0) >> 24)] & 0xff000000) ^ ((uint32_t)TE3[((t1) >> 16) & 0xff] & 0x00ff0000) ^ \ ((uint32_t)TE0[((t2) >> 8) & 0xff] & 0x0000ff00) ^ ((uint32_t)TE1[(t3) & 0xff] & 0x000000ff)) #define INVSSEARCH(t0, t1, t2, t3) \ (((uint32_t)INV_S[((t0) >> 24)] << 24) ^ ((uint32_t)INV_S[((t3) >> 16) & 0xff] << 16) ^ \ ((uint32_t)INV_S[((t2) >> 8) & 0xff] << 8) ^ ((uint32_t)INV_S[(t1) & 0xff])) static const uint32_t TE0[256] = { 0xc66363a5U, 0xf87c7c84U, 0xee777799U, 0xf67b7b8dU, 0xfff2f20dU, 0xd66b6bbdU, 0xde6f6fb1U, 0x91c5c554U, 0x60303050U, 0x02010103U, 0xce6767a9U, 0x562b2b7dU, 0xe7fefe19U, 0xb5d7d762U, 0x4dababe6U, 0xec76769aU, 0x8fcaca45U, 0x1f82829dU, 0x89c9c940U, 0xfa7d7d87U, 0xeffafa15U, 0xb25959ebU, 0x8e4747c9U, 0xfbf0f00bU, 0x41adadecU, 0xb3d4d467U, 0x5fa2a2fdU, 0x45afafeaU, 0x239c9cbfU, 0x53a4a4f7U, 0xe4727296U, 0x9bc0c05bU, 0x75b7b7c2U, 0xe1fdfd1cU, 0x3d9393aeU, 0x4c26266aU, 0x6c36365aU, 0x7e3f3f41U, 0xf5f7f702U, 0x83cccc4fU, 0x6834345cU, 0x51a5a5f4U, 0xd1e5e534U, 0xf9f1f108U, 0xe2717193U, 0xabd8d873U, 0x62313153U, 0x2a15153fU, 0x0804040cU, 0x95c7c752U, 0x46232365U, 0x9dc3c35eU, 0x30181828U, 0x379696a1U, 0x0a05050fU, 0x2f9a9ab5U, 0x0e070709U, 0x24121236U, 0x1b80809bU, 0xdfe2e23dU, 0xcdebeb26U, 0x4e272769U, 0x7fb2b2cdU, 0xea75759fU, 0x1209091bU, 0x1d83839eU, 0x582c2c74U, 0x341a1a2eU, 0x361b1b2dU, 0xdc6e6eb2U, 0xb45a5aeeU, 0x5ba0a0fbU, 0xa45252f6U, 0x763b3b4dU, 0xb7d6d661U, 0x7db3b3ceU, 0x5229297bU, 0xdde3e33eU, 0x5e2f2f71U, 0x13848497U, 0xa65353f5U, 0xb9d1d168U, 0x00000000U, 0xc1eded2cU, 0x40202060U, 0xe3fcfc1fU, 0x79b1b1c8U, 0xb65b5bedU, 0xd46a6abeU, 0x8dcbcb46U, 0x67bebed9U, 0x7239394bU, 0x944a4adeU, 0x984c4cd4U, 0xb05858e8U, 0x85cfcf4aU, 0xbbd0d06bU, 0xc5efef2aU, 0x4faaaae5U, 0xedfbfb16U, 0x864343c5U, 0x9a4d4dd7U, 0x66333355U, 0x11858594U, 0x8a4545cfU, 0xe9f9f910U, 0x04020206U, 0xfe7f7f81U, 0xa05050f0U, 0x783c3c44U, 0x259f9fbaU, 0x4ba8a8e3U, 0xa25151f3U, 0x5da3a3feU, 0x804040c0U, 0x058f8f8aU, 0x3f9292adU, 0x219d9dbcU, 0x70383848U, 0xf1f5f504U, 0x63bcbcdfU, 0x77b6b6c1U, 0xafdada75U, 0x42212163U, 0x20101030U, 0xe5ffff1aU, 0xfdf3f30eU, 0xbfd2d26dU, 0x81cdcd4cU, 0x180c0c14U, 0x26131335U, 0xc3ecec2fU, 0xbe5f5fe1U, 0x359797a2U, 0x884444ccU, 0x2e171739U, 0x93c4c457U, 0x55a7a7f2U, 0xfc7e7e82U, 0x7a3d3d47U, 0xc86464acU, 0xba5d5de7U, 0x3219192bU, 0xe6737395U, 0xc06060a0U, 0x19818198U, 0x9e4f4fd1U, 0xa3dcdc7fU, 0x44222266U, 0x542a2a7eU, 0x3b9090abU, 0x0b888883U, 0x8c4646caU, 0xc7eeee29U, 0x6bb8b8d3U, 0x2814143cU, 0xa7dede79U, 0xbc5e5ee2U, 0x160b0b1dU, 0xaddbdb76U, 0xdbe0e03bU, 0x64323256U, 0x743a3a4eU, 0x140a0a1eU, 0x924949dbU, 0x0c06060aU, 0x4824246cU, 0xb85c5ce4U, 0x9fc2c25dU, 0xbdd3d36eU, 0x43acacefU, 0xc46262a6U, 0x399191a8U, 0x319595a4U, 0xd3e4e437U, 0xf279798bU, 0xd5e7e732U, 0x8bc8c843U, 0x6e373759U, 0xda6d6db7U, 0x018d8d8cU, 0xb1d5d564U, 0x9c4e4ed2U, 0x49a9a9e0U, 0xd86c6cb4U, 0xac5656faU, 0xf3f4f407U, 0xcfeaea25U, 0xca6565afU, 0xf47a7a8eU, 0x47aeaee9U, 0x10080818U, 0x6fbabad5U, 0xf0787888U, 0x4a25256fU, 0x5c2e2e72U, 0x381c1c24U, 0x57a6a6f1U, 0x73b4b4c7U, 0x97c6c651U, 0xcbe8e823U, 0xa1dddd7cU, 0xe874749cU, 0x3e1f1f21U, 0x964b4bddU, 0x61bdbddcU, 0x0d8b8b86U, 0x0f8a8a85U, 0xe0707090U, 0x7c3e3e42U, 0x71b5b5c4U, 0xcc6666aaU, 0x904848d8U, 0x06030305U, 0xf7f6f601U, 0x1c0e0e12U, 0xc26161a3U, 0x6a35355fU, 0xae5757f9U, 0x69b9b9d0U, 0x17868691U, 0x99c1c158U, 0x3a1d1d27U, 0x279e9eb9U, 0xd9e1e138U, 0xebf8f813U, 0x2b9898b3U, 0x22111133U, 0xd26969bbU, 0xa9d9d970U, 0x078e8e89U, 0x339494a7U, 0x2d9b9bb6U, 0x3c1e1e22U, 0x15878792U, 0xc9e9e920U, 0x87cece49U, 0xaa5555ffU, 0x50282878U, 0xa5dfdf7aU, 0x038c8c8fU, 0x59a1a1f8U, 0x09898980U, 0x1a0d0d17U, 0x65bfbfdaU, 0xd7e6e631U, 0x844242c6U, 0xd06868b8U, 0x824141c3U, 0x299999b0U, 0x5a2d2d77U, 0x1e0f0f11U, 0x7bb0b0cbU, 0xa85454fcU, 0x6dbbbbd6U, 0x2c16163aU, }; static const uint32_t TE1[256] = { 0xa5c66363U, 0x84f87c7cU, 0x99ee7777U, 0x8df67b7bU, 0x0dfff2f2U, 0xbdd66b6bU, 0xb1de6f6fU, 0x5491c5c5U, 0x50603030U, 0x03020101U, 0xa9ce6767U, 0x7d562b2bU, 0x19e7fefeU, 0x62b5d7d7U, 0xe64dababU, 0x9aec7676U, 0x458fcacaU, 0x9d1f8282U, 0x4089c9c9U, 0x87fa7d7dU, 0x15effafaU, 0xebb25959U, 0xc98e4747U, 0x0bfbf0f0U, 0xec41adadU, 0x67b3d4d4U, 0xfd5fa2a2U, 0xea45afafU, 0xbf239c9cU, 0xf753a4a4U, 0x96e47272U, 0x5b9bc0c0U, 0xc275b7b7U, 0x1ce1fdfdU, 0xae3d9393U, 0x6a4c2626U, 0x5a6c3636U, 0x417e3f3fU, 0x02f5f7f7U, 0x4f83ccccU, 0x5c683434U, 0xf451a5a5U, 0x34d1e5e5U, 0x08f9f1f1U, 0x93e27171U, 0x73abd8d8U, 0x53623131U, 0x3f2a1515U, 0x0c080404U, 0x5295c7c7U, 0x65462323U, 0x5e9dc3c3U, 0x28301818U, 0xa1379696U, 0x0f0a0505U, 0xb52f9a9aU, 0x090e0707U, 0x36241212U, 0x9b1b8080U, 0x3ddfe2e2U, 0x26cdebebU, 0x694e2727U, 0xcd7fb2b2U, 0x9fea7575U, 0x1b120909U, 0x9e1d8383U, 0x74582c2cU, 0x2e341a1aU, 0x2d361b1bU, 0xb2dc6e6eU, 0xeeb45a5aU, 0xfb5ba0a0U, 0xf6a45252U, 0x4d763b3bU, 0x61b7d6d6U, 0xce7db3b3U, 0x7b522929U, 0x3edde3e3U, 0x715e2f2fU, 0x97138484U, 0xf5a65353U, 0x68b9d1d1U, 0x00000000U, 0x2cc1ededU, 0x60402020U, 0x1fe3fcfcU, 0xc879b1b1U, 0xedb65b5bU, 0xbed46a6aU, 0x468dcbcbU, 0xd967bebeU, 0x4b723939U, 0xde944a4aU, 0xd4984c4cU, 0xe8b05858U, 0x4a85cfcfU, 0x6bbbd0d0U, 0x2ac5efefU, 0xe54faaaaU, 0x16edfbfbU, 0xc5864343U, 0xd79a4d4dU, 0x55663333U, 0x94118585U, 0xcf8a4545U, 0x10e9f9f9U, 0x06040202U, 0x81fe7f7fU, 0xf0a05050U, 0x44783c3cU, 0xba259f9fU, 0xe34ba8a8U, 0xf3a25151U, 0xfe5da3a3U, 0xc0804040U, 0x8a058f8fU, 0xad3f9292U, 0xbc219d9dU, 0x48703838U, 0x04f1f5f5U, 0xdf63bcbcU, 0xc177b6b6U, 0x75afdadaU, 0x63422121U, 0x30201010U, 0x1ae5ffffU, 0x0efdf3f3U, 0x6dbfd2d2U, 0x4c81cdcdU, 0x14180c0cU, 0x35261313U, 0x2fc3ececU, 0xe1be5f5fU, 0xa2359797U, 0xcc884444U, 0x392e1717U, 0x5793c4c4U, 0xf255a7a7U, 0x82fc7e7eU, 0x477a3d3dU, 0xacc86464U, 0xe7ba5d5dU, 0x2b321919U, 0x95e67373U, 0xa0c06060U, 0x98198181U, 0xd19e4f4fU, 0x7fa3dcdcU, 0x66442222U, 0x7e542a2aU, 0xab3b9090U, 0x830b8888U, 0xca8c4646U, 0x29c7eeeeU, 0xd36bb8b8U, 0x3c281414U, 0x79a7dedeU, 0xe2bc5e5eU, 0x1d160b0bU, 0x76addbdbU, 0x3bdbe0e0U, 0x56643232U, 0x4e743a3aU, 0x1e140a0aU, 0xdb924949U, 0x0a0c0606U, 0x6c482424U, 0xe4b85c5cU, 0x5d9fc2c2U, 0x6ebdd3d3U, 0xef43acacU, 0xa6c46262U, 0xa8399191U, 0xa4319595U, 0x37d3e4e4U, 0x8bf27979U, 0x32d5e7e7U, 0x438bc8c8U, 0x596e3737U, 0xb7da6d6dU, 0x8c018d8dU, 0x64b1d5d5U, 0xd29c4e4eU, 0xe049a9a9U, 0xb4d86c6cU, 0xfaac5656U, 0x07f3f4f4U, 0x25cfeaeaU, 0xafca6565U, 0x8ef47a7aU, 0xe947aeaeU, 0x18100808U, 0xd56fbabaU, 0x88f07878U, 0x6f4a2525U, 0x725c2e2eU, 0x24381c1cU, 0xf157a6a6U, 0xc773b4b4U, 0x5197c6c6U, 0x23cbe8e8U, 0x7ca1ddddU, 0x9ce87474U, 0x213e1f1fU, 0xdd964b4bU, 0xdc61bdbdU, 0x860d8b8bU, 0x850f8a8aU, 0x90e07070U, 0x427c3e3eU, 0xc471b5b5U, 0xaacc6666U, 0xd8904848U, 0x05060303U, 0x01f7f6f6U, 0x121c0e0eU, 0xa3c26161U, 0x5f6a3535U, 0xf9ae5757U, 0xd069b9b9U, 0x91178686U, 0x5899c1c1U, 0x273a1d1dU, 0xb9279e9eU, 0x38d9e1e1U, 0x13ebf8f8U, 0xb32b9898U, 0x33221111U, 0xbbd26969U, 0x70a9d9d9U, 0x89078e8eU, 0xa7339494U, 0xb62d9b9bU, 0x223c1e1eU, 0x92158787U, 0x20c9e9e9U, 0x4987ceceU, 0xffaa5555U, 0x78502828U, 0x7aa5dfdfU, 0x8f038c8cU, 0xf859a1a1U, 0x80098989U, 0x171a0d0dU, 0xda65bfbfU, 0x31d7e6e6U, 0xc6844242U, 0xb8d06868U, 0xc3824141U, 0xb0299999U, 0x775a2d2dU, 0x111e0f0fU, 0xcb7bb0b0U, 0xfca85454U, 0xd66dbbbbU, 0x3a2c1616U, }; static const uint32_t TE2[256] = { 0x63a5c663U, 0x7c84f87cU, 0x7799ee77U, 0x7b8df67bU, 0xf20dfff2U, 0x6bbdd66bU, 0x6fb1de6fU, 0xc55491c5U, 0x30506030U, 0x01030201U, 0x67a9ce67U, 0x2b7d562bU, 0xfe19e7feU, 0xd762b5d7U, 0xabe64dabU, 0x769aec76U, 0xca458fcaU, 0x829d1f82U, 0xc94089c9U, 0x7d87fa7dU, 0xfa15effaU, 0x59ebb259U, 0x47c98e47U, 0xf00bfbf0U, 0xadec41adU, 0xd467b3d4U, 0xa2fd5fa2U, 0xafea45afU, 0x9cbf239cU, 0xa4f753a4U, 0x7296e472U, 0xc05b9bc0U, 0xb7c275b7U, 0xfd1ce1fdU, 0x93ae3d93U, 0x266a4c26U, 0x365a6c36U, 0x3f417e3fU, 0xf702f5f7U, 0xcc4f83ccU, 0x345c6834U, 0xa5f451a5U, 0xe534d1e5U, 0xf108f9f1U, 0x7193e271U, 0xd873abd8U, 0x31536231U, 0x153f2a15U, 0x040c0804U, 0xc75295c7U, 0x23654623U, 0xc35e9dc3U, 0x18283018U, 0x96a13796U, 0x050f0a05U, 0x9ab52f9aU, 0x07090e07U, 0x12362412U, 0x809b1b80U, 0xe23ddfe2U, 0xeb26cdebU, 0x27694e27U, 0xb2cd7fb2U, 0x759fea75U, 0x091b1209U, 0x839e1d83U, 0x2c74582cU, 0x1a2e341aU, 0x1b2d361bU, 0x6eb2dc6eU, 0x5aeeb45aU, 0xa0fb5ba0U, 0x52f6a452U, 0x3b4d763bU, 0xd661b7d6U, 0xb3ce7db3U, 0x297b5229U, 0xe33edde3U, 0x2f715e2fU, 0x84971384U, 0x53f5a653U, 0xd168b9d1U, 0x00000000U, 0xed2cc1edU, 0x20604020U, 0xfc1fe3fcU, 0xb1c879b1U, 0x5bedb65bU, 0x6abed46aU, 0xcb468dcbU, 0xbed967beU, 0x394b7239U, 0x4ade944aU, 0x4cd4984cU, 0x58e8b058U, 0xcf4a85cfU, 0xd06bbbd0U, 0xef2ac5efU, 0xaae54faaU, 0xfb16edfbU, 0x43c58643U, 0x4dd79a4dU, 0x33556633U, 0x85941185U, 0x45cf8a45U, 0xf910e9f9U, 0x02060402U, 0x7f81fe7fU, 0x50f0a050U, 0x3c44783cU, 0x9fba259fU, 0xa8e34ba8U, 0x51f3a251U, 0xa3fe5da3U, 0x40c08040U, 0x8f8a058fU, 0x92ad3f92U, 0x9dbc219dU, 0x38487038U, 0xf504f1f5U, 0xbcdf63bcU, 0xb6c177b6U, 0xda75afdaU, 0x21634221U, 0x10302010U, 0xff1ae5ffU, 0xf30efdf3U, 0xd26dbfd2U, 0xcd4c81cdU, 0x0c14180cU, 0x13352613U, 0xec2fc3ecU, 0x5fe1be5fU, 0x97a23597U, 0x44cc8844U, 0x17392e17U, 0xc45793c4U, 0xa7f255a7U, 0x7e82fc7eU, 0x3d477a3dU, 0x64acc864U, 0x5de7ba5dU, 0x192b3219U, 0x7395e673U, 0x60a0c060U, 0x81981981U, 0x4fd19e4fU, 0xdc7fa3dcU, 0x22664422U, 0x2a7e542aU, 0x90ab3b90U, 0x88830b88U, 0x46ca8c46U, 0xee29c7eeU, 0xb8d36bb8U, 0x143c2814U, 0xde79a7deU, 0x5ee2bc5eU, 0x0b1d160bU, 0xdb76addbU, 0xe03bdbe0U, 0x32566432U, 0x3a4e743aU, 0x0a1e140aU, 0x49db9249U, 0x060a0c06U, 0x246c4824U, 0x5ce4b85cU, 0xc25d9fc2U, 0xd36ebdd3U, 0xacef43acU, 0x62a6c462U, 0x91a83991U, 0x95a43195U, 0xe437d3e4U, 0x798bf279U, 0xe732d5e7U, 0xc8438bc8U, 0x37596e37U, 0x6db7da6dU, 0x8d8c018dU, 0xd564b1d5U, 0x4ed29c4eU, 0xa9e049a9U, 0x6cb4d86cU, 0x56faac56U, 0xf407f3f4U, 0xea25cfeaU, 0x65afca65U, 0x7a8ef47aU, 0xaee947aeU, 0x08181008U, 0xbad56fbaU, 0x7888f078U, 0x256f4a25U, 0x2e725c2eU, 0x1c24381cU, 0xa6f157a6U, 0xb4c773b4U, 0xc65197c6U, 0xe823cbe8U, 0xdd7ca1ddU, 0x749ce874U, 0x1f213e1fU, 0x4bdd964bU, 0xbddc61bdU, 0x8b860d8bU, 0x8a850f8aU, 0x7090e070U, 0x3e427c3eU, 0xb5c471b5U, 0x66aacc66U, 0x48d89048U, 0x03050603U, 0xf601f7f6U, 0x0e121c0eU, 0x61a3c261U, 0x355f6a35U, 0x57f9ae57U, 0xb9d069b9U, 0x86911786U, 0xc15899c1U, 0x1d273a1dU, 0x9eb9279eU, 0xe138d9e1U, 0xf813ebf8U, 0x98b32b98U, 0x11332211U, 0x69bbd269U, 0xd970a9d9U, 0x8e89078eU, 0x94a73394U, 0x9bb62d9bU, 0x1e223c1eU, 0x87921587U, 0xe920c9e9U, 0xce4987ceU, 0x55ffaa55U, 0x28785028U, 0xdf7aa5dfU, 0x8c8f038cU, 0xa1f859a1U, 0x89800989U, 0x0d171a0dU, 0xbfda65bfU, 0xe631d7e6U, 0x42c68442U, 0x68b8d068U, 0x41c38241U, 0x99b02999U, 0x2d775a2dU, 0x0f111e0fU, 0xb0cb7bb0U, 0x54fca854U, 0xbbd66dbbU, 0x163a2c16U, }; static const uint32_t TE3[256] = { 0x6363a5c6U, 0x7c7c84f8U, 0x777799eeU, 0x7b7b8df6U, 0xf2f20dffU, 0x6b6bbdd6U, 0x6f6fb1deU, 0xc5c55491U, 0x30305060U, 0x01010302U, 0x6767a9ceU, 0x2b2b7d56U, 0xfefe19e7U, 0xd7d762b5U, 0xababe64dU, 0x76769aecU, 0xcaca458fU, 0x82829d1fU, 0xc9c94089U, 0x7d7d87faU, 0xfafa15efU, 0x5959ebb2U, 0x4747c98eU, 0xf0f00bfbU, 0xadadec41U, 0xd4d467b3U, 0xa2a2fd5fU, 0xafafea45U, 0x9c9cbf23U, 0xa4a4f753U, 0x727296e4U, 0xc0c05b9bU, 0xb7b7c275U, 0xfdfd1ce1U, 0x9393ae3dU, 0x26266a4cU, 0x36365a6cU, 0x3f3f417eU, 0xf7f702f5U, 0xcccc4f83U, 0x34345c68U, 0xa5a5f451U, 0xe5e534d1U, 0xf1f108f9U, 0x717193e2U, 0xd8d873abU, 0x31315362U, 0x15153f2aU, 0x04040c08U, 0xc7c75295U, 0x23236546U, 0xc3c35e9dU, 0x18182830U, 0x9696a137U, 0x05050f0aU, 0x9a9ab52fU, 0x0707090eU, 0x12123624U, 0x80809b1bU, 0xe2e23ddfU, 0xebeb26cdU, 0x2727694eU, 0xb2b2cd7fU, 0x75759feaU, 0x09091b12U, 0x83839e1dU, 0x2c2c7458U, 0x1a1a2e34U, 0x1b1b2d36U, 0x6e6eb2dcU, 0x5a5aeeb4U, 0xa0a0fb5bU, 0x5252f6a4U, 0x3b3b4d76U, 0xd6d661b7U, 0xb3b3ce7dU, 0x29297b52U, 0xe3e33eddU, 0x2f2f715eU, 0x84849713U, 0x5353f5a6U, 0xd1d168b9U, 0x00000000U, 0xeded2cc1U, 0x20206040U, 0xfcfc1fe3U, 0xb1b1c879U, 0x5b5bedb6U, 0x6a6abed4U, 0xcbcb468dU, 0xbebed967U, 0x39394b72U, 0x4a4ade94U, 0x4c4cd498U, 0x5858e8b0U, 0xcfcf4a85U, 0xd0d06bbbU, 0xefef2ac5U, 0xaaaae54fU, 0xfbfb16edU, 0x4343c586U, 0x4d4dd79aU, 0x33335566U, 0x85859411U, 0x4545cf8aU, 0xf9f910e9U, 0x02020604U, 0x7f7f81feU, 0x5050f0a0U, 0x3c3c4478U, 0x9f9fba25U, 0xa8a8e34bU, 0x5151f3a2U, 0xa3a3fe5dU, 0x4040c080U, 0x8f8f8a05U, 0x9292ad3fU, 0x9d9dbc21U, 0x38384870U, 0xf5f504f1U, 0xbcbcdf63U, 0xb6b6c177U, 0xdada75afU, 0x21216342U, 0x10103020U, 0xffff1ae5U, 0xf3f30efdU, 0xd2d26dbfU, 0xcdcd4c81U, 0x0c0c1418U, 0x13133526U, 0xecec2fc3U, 0x5f5fe1beU, 0x9797a235U, 0x4444cc88U, 0x1717392eU, 0xc4c45793U, 0xa7a7f255U, 0x7e7e82fcU, 0x3d3d477aU, 0x6464acc8U, 0x5d5de7baU, 0x19192b32U, 0x737395e6U, 0x6060a0c0U, 0x81819819U, 0x4f4fd19eU, 0xdcdc7fa3U, 0x22226644U, 0x2a2a7e54U, 0x9090ab3bU, 0x8888830bU, 0x4646ca8cU, 0xeeee29c7U, 0xb8b8d36bU, 0x14143c28U, 0xdede79a7U, 0x5e5ee2bcU, 0x0b0b1d16U, 0xdbdb76adU, 0xe0e03bdbU, 0x32325664U, 0x3a3a4e74U, 0x0a0a1e14U, 0x4949db92U, 0x06060a0cU, 0x24246c48U, 0x5c5ce4b8U, 0xc2c25d9fU, 0xd3d36ebdU, 0xacacef43U, 0x6262a6c4U, 0x9191a839U, 0x9595a431U, 0xe4e437d3U, 0x79798bf2U, 0xe7e732d5U, 0xc8c8438bU, 0x3737596eU, 0x6d6db7daU, 0x8d8d8c01U, 0xd5d564b1U, 0x4e4ed29cU, 0xa9a9e049U, 0x6c6cb4d8U, 0x5656faacU, 0xf4f407f3U, 0xeaea25cfU, 0x6565afcaU, 0x7a7a8ef4U, 0xaeaee947U, 0x08081810U, 0xbabad56fU, 0x787888f0U, 0x25256f4aU, 0x2e2e725cU, 0x1c1c2438U, 0xa6a6f157U, 0xb4b4c773U, 0xc6c65197U, 0xe8e823cbU, 0xdddd7ca1U, 0x74749ce8U, 0x1f1f213eU, 0x4b4bdd96U, 0xbdbddc61U, 0x8b8b860dU, 0x8a8a850fU, 0x707090e0U, 0x3e3e427cU, 0xb5b5c471U, 0x6666aaccU, 0x4848d890U, 0x03030506U, 0xf6f601f7U, 0x0e0e121cU, 0x6161a3c2U, 0x35355f6aU, 0x5757f9aeU, 0xb9b9d069U, 0x86869117U, 0xc1c15899U, 0x1d1d273aU, 0x9e9eb927U, 0xe1e138d9U, 0xf8f813ebU, 0x9898b32bU, 0x11113322U, 0x6969bbd2U, 0xd9d970a9U, 0x8e8e8907U, 0x9494a733U, 0x9b9bb62dU, 0x1e1e223cU, 0x87879215U, 0xe9e920c9U, 0xcece4987U, 0x5555ffaaU, 0x28287850U, 0xdfdf7aa5U, 0x8c8c8f03U, 0xa1a1f859U, 0x89898009U, 0x0d0d171aU, 0xbfbfda65U, 0xe6e631d7U, 0x4242c684U, 0x6868b8d0U, 0x4141c382U, 0x9999b029U, 0x2d2d775aU, 0x0f0f111eU, 0xb0b0cb7bU, 0x5454fca8U, 0xbbbbd66dU, 0x16163a2cU, }; static const uint32_t TD0[256] = { 0x51f4a750U, 0x7e416553U, 0x1a17a4c3U, 0x3a275e96U, 0x3bab6bcbU, 0x1f9d45f1U, 0xacfa58abU, 0x4be30393U, 0x2030fa55U, 0xad766df6U, 0x88cc7691U, 0xf5024c25U, 0x4fe5d7fcU, 0xc52acbd7U, 0x26354480U, 0xb562a38fU, 0xdeb15a49U, 0x25ba1b67U, 0x45ea0e98U, 0x5dfec0e1U, 0xc32f7502U, 0x814cf012U, 0x8d4697a3U, 0x6bd3f9c6U, 0x038f5fe7U, 0x15929c95U, 0xbf6d7aebU, 0x955259daU, 0xd4be832dU, 0x587421d3U, 0x49e06929U, 0x8ec9c844U, 0x75c2896aU, 0xf48e7978U, 0x99583e6bU, 0x27b971ddU, 0xbee14fb6U, 0xf088ad17U, 0xc920ac66U, 0x7dce3ab4U, 0x63df4a18U, 0xe51a3182U, 0x97513360U, 0x62537f45U, 0xb16477e0U, 0xbb6bae84U, 0xfe81a01cU, 0xf9082b94U, 0x70486858U, 0x8f45fd19U, 0x94de6c87U, 0x527bf8b7U, 0xab73d323U, 0x724b02e2U, 0xe31f8f57U, 0x6655ab2aU, 0xb2eb2807U, 0x2fb5c203U, 0x86c57b9aU, 0xd33708a5U, 0x302887f2U, 0x23bfa5b2U, 0x02036abaU, 0xed16825cU, 0x8acf1c2bU, 0xa779b492U, 0xf307f2f0U, 0x4e69e2a1U, 0x65daf4cdU, 0x0605bed5U, 0xd134621fU, 0xc4a6fe8aU, 0x342e539dU, 0xa2f355a0U, 0x058ae132U, 0xa4f6eb75U, 0x0b83ec39U, 0x4060efaaU, 0x5e719f06U, 0xbd6e1051U, 0x3e218af9U, 0x96dd063dU, 0xdd3e05aeU, 0x4de6bd46U, 0x91548db5U, 0x71c45d05U, 0x0406d46fU, 0x605015ffU, 0x1998fb24U, 0xd6bde997U, 0x894043ccU, 0x67d99e77U, 0xb0e842bdU, 0x07898b88U, 0xe7195b38U, 0x79c8eedbU, 0xa17c0a47U, 0x7c420fe9U, 0xf8841ec9U, 0x00000000U, 0x09808683U, 0x322bed48U, 0x1e1170acU, 0x6c5a724eU, 0xfd0efffbU, 0x0f853856U, 0x3daed51eU, 0x362d3927U, 0x0a0fd964U, 0x685ca621U, 0x9b5b54d1U, 0x24362e3aU, 0x0c0a67b1U, 0x9357e70fU, 0xb4ee96d2U, 0x1b9b919eU, 0x80c0c54fU, 0x61dc20a2U, 0x5a774b69U, 0x1c121a16U, 0xe293ba0aU, 0xc0a02ae5U, 0x3c22e043U, 0x121b171dU, 0x0e090d0bU, 0xf28bc7adU, 0x2db6a8b9U, 0x141ea9c8U, 0x57f11985U, 0xaf75074cU, 0xee99ddbbU, 0xa37f60fdU, 0xf701269fU, 0x5c72f5bcU, 0x44663bc5U, 0x5bfb7e34U, 0x8b432976U, 0xcb23c6dcU, 0xb6edfc68U, 0xb8e4f163U, 0xd731dccaU, 0x42638510U, 0x13972240U, 0x84c61120U, 0x854a247dU, 0xd2bb3df8U, 0xaef93211U, 0xc729a16dU, 0x1d9e2f4bU, 0xdcb230f3U, 0x0d8652ecU, 0x77c1e3d0U, 0x2bb3166cU, 0xa970b999U, 0x119448faU, 0x47e96422U, 0xa8fc8cc4U, 0xa0f03f1aU, 0x567d2cd8U, 0x223390efU, 0x87494ec7U, 0xd938d1c1U, 0x8ccaa2feU, 0x98d40b36U, 0xa6f581cfU, 0xa57ade28U, 0xdab78e26U, 0x3fadbfa4U, 0x2c3a9de4U, 0x5078920dU, 0x6a5fcc9bU, 0x547e4662U, 0xf68d13c2U, 0x90d8b8e8U, 0x2e39f75eU, 0x82c3aff5U, 0x9f5d80beU, 0x69d0937cU, 0x6fd52da9U, 0xcf2512b3U, 0xc8ac993bU, 0x10187da7U, 0xe89c636eU, 0xdb3bbb7bU, 0xcd267809U, 0x6e5918f4U, 0xec9ab701U, 0x834f9aa8U, 0xe6956e65U, 0xaaffe67eU, 0x21bccf08U, 0xef15e8e6U, 0xbae79bd9U, 0x4a6f36ceU, 0xea9f09d4U, 0x29b07cd6U, 0x31a4b2afU, 0x2a3f2331U, 0xc6a59430U, 0x35a266c0U, 0x744ebc37U, 0xfc82caa6U, 0xe090d0b0U, 0x33a7d815U, 0xf104984aU, 0x41ecdaf7U, 0x7fcd500eU, 0x1791f62fU, 0x764dd68dU, 0x43efb04dU, 0xccaa4d54U, 0xe49604dfU, 0x9ed1b5e3U, 0x4c6a881bU, 0xc12c1fb8U, 0x4665517fU, 0x9d5eea04U, 0x018c355dU, 0xfa877473U, 0xfb0b412eU, 0xb3671d5aU, 0x92dbd252U, 0xe9105633U, 0x6dd64713U, 0x9ad7618cU, 0x37a10c7aU, 0x59f8148eU, 0xeb133c89U, 0xcea927eeU, 0xb761c935U, 0xe11ce5edU, 0x7a47b13cU, 0x9cd2df59U, 0x55f2733fU, 0x1814ce79U, 0x73c737bfU, 0x53f7cdeaU, 0x5ffdaa5bU, 0xdf3d6f14U, 0x7844db86U, 0xcaaff381U, 0xb968c43eU, 0x3824342cU, 0xc2a3405fU, 0x161dc372U, 0xbce2250cU, 0x283c498bU, 0xff0d9541U, 0x39a80171U, 0x080cb3deU, 0xd8b4e49cU, 0x6456c190U, 0x7bcb8461U, 0xd532b670U, 0x486c5c74U, 0xd0b85742U, }; static const uint32_t TD1[256] = { 0x5051f4a7U, 0x537e4165U, 0xc31a17a4U, 0x963a275eU, 0xcb3bab6bU, 0xf11f9d45U, 0xabacfa58U, 0x934be303U, 0x552030faU, 0xf6ad766dU, 0x9188cc76U, 0x25f5024cU, 0xfc4fe5d7U, 0xd7c52acbU, 0x80263544U, 0x8fb562a3U, 0x49deb15aU, 0x6725ba1bU, 0x9845ea0eU, 0xe15dfec0U, 0x02c32f75U, 0x12814cf0U, 0xa38d4697U, 0xc66bd3f9U, 0xe7038f5fU, 0x9515929cU, 0xebbf6d7aU, 0xda955259U, 0x2dd4be83U, 0xd3587421U, 0x2949e069U, 0x448ec9c8U, 0x6a75c289U, 0x78f48e79U, 0x6b99583eU, 0xdd27b971U, 0xb6bee14fU, 0x17f088adU, 0x66c920acU, 0xb47dce3aU, 0x1863df4aU, 0x82e51a31U, 0x60975133U, 0x4562537fU, 0xe0b16477U, 0x84bb6baeU, 0x1cfe81a0U, 0x94f9082bU, 0x58704868U, 0x198f45fdU, 0x8794de6cU, 0xb7527bf8U, 0x23ab73d3U, 0xe2724b02U, 0x57e31f8fU, 0x2a6655abU, 0x07b2eb28U, 0x032fb5c2U, 0x9a86c57bU, 0xa5d33708U, 0xf2302887U, 0xb223bfa5U, 0xba02036aU, 0x5ced1682U, 0x2b8acf1cU, 0x92a779b4U, 0xf0f307f2U, 0xa14e69e2U, 0xcd65daf4U, 0xd50605beU, 0x1fd13462U, 0x8ac4a6feU, 0x9d342e53U, 0xa0a2f355U, 0x32058ae1U, 0x75a4f6ebU, 0x390b83ecU, 0xaa4060efU, 0x065e719fU, 0x51bd6e10U, 0xf93e218aU, 0x3d96dd06U, 0xaedd3e05U, 0x464de6bdU, 0xb591548dU, 0x0571c45dU, 0x6f0406d4U, 0xff605015U, 0x241998fbU, 0x97d6bde9U, 0xcc894043U, 0x7767d99eU, 0xbdb0e842U, 0x8807898bU, 0x38e7195bU, 0xdb79c8eeU, 0x47a17c0aU, 0xe97c420fU, 0xc9f8841eU, 0x00000000U, 0x83098086U, 0x48322bedU, 0xac1e1170U, 0x4e6c5a72U, 0xfbfd0effU, 0x560f8538U, 0x1e3daed5U, 0x27362d39U, 0x640a0fd9U, 0x21685ca6U, 0xd19b5b54U, 0x3a24362eU, 0xb10c0a67U, 0x0f9357e7U, 0xd2b4ee96U, 0x9e1b9b91U, 0x4f80c0c5U, 0xa261dc20U, 0x695a774bU, 0x161c121aU, 0x0ae293baU, 0xe5c0a02aU, 0x433c22e0U, 0x1d121b17U, 0x0b0e090dU, 0xadf28bc7U, 0xb92db6a8U, 0xc8141ea9U, 0x8557f119U, 0x4caf7507U, 0xbbee99ddU, 0xfda37f60U, 0x9ff70126U, 0xbc5c72f5U, 0xc544663bU, 0x345bfb7eU, 0x768b4329U, 0xdccb23c6U, 0x68b6edfcU, 0x63b8e4f1U, 0xcad731dcU, 0x10426385U, 0x40139722U, 0x2084c611U, 0x7d854a24U, 0xf8d2bb3dU, 0x11aef932U, 0x6dc729a1U, 0x4b1d9e2fU, 0xf3dcb230U, 0xec0d8652U, 0xd077c1e3U, 0x6c2bb316U, 0x99a970b9U, 0xfa119448U, 0x2247e964U, 0xc4a8fc8cU, 0x1aa0f03fU, 0xd8567d2cU, 0xef223390U, 0xc787494eU, 0xc1d938d1U, 0xfe8ccaa2U, 0x3698d40bU, 0xcfa6f581U, 0x28a57adeU, 0x26dab78eU, 0xa43fadbfU, 0xe42c3a9dU, 0x0d507892U, 0x9b6a5fccU, 0x62547e46U, 0xc2f68d13U, 0xe890d8b8U, 0x5e2e39f7U, 0xf582c3afU, 0xbe9f5d80U, 0x7c69d093U, 0xa96fd52dU, 0xb3cf2512U, 0x3bc8ac99U, 0xa710187dU, 0x6ee89c63U, 0x7bdb3bbbU, 0x09cd2678U, 0xf46e5918U, 0x01ec9ab7U, 0xa8834f9aU, 0x65e6956eU, 0x7eaaffe6U, 0x0821bccfU, 0xe6ef15e8U, 0xd9bae79bU, 0xce4a6f36U, 0xd4ea9f09U, 0xd629b07cU, 0xaf31a4b2U, 0x312a3f23U, 0x30c6a594U, 0xc035a266U, 0x37744ebcU, 0xa6fc82caU, 0xb0e090d0U, 0x1533a7d8U, 0x4af10498U, 0xf741ecdaU, 0x0e7fcd50U, 0x2f1791f6U, 0x8d764dd6U, 0x4d43efb0U, 0x54ccaa4dU, 0xdfe49604U, 0xe39ed1b5U, 0x1b4c6a88U, 0xb8c12c1fU, 0x7f466551U, 0x049d5eeaU, 0x5d018c35U, 0x73fa8774U, 0x2efb0b41U, 0x5ab3671dU, 0x5292dbd2U, 0x33e91056U, 0x136dd647U, 0x8c9ad761U, 0x7a37a10cU, 0x8e59f814U, 0x89eb133cU, 0xeecea927U, 0x35b761c9U, 0xede11ce5U, 0x3c7a47b1U, 0x599cd2dfU, 0x3f55f273U, 0x791814ceU, 0xbf73c737U, 0xea53f7cdU, 0x5b5ffdaaU, 0x14df3d6fU, 0x867844dbU, 0x81caaff3U, 0x3eb968c4U, 0x2c382434U, 0x5fc2a340U, 0x72161dc3U, 0x0cbce225U, 0x8b283c49U, 0x41ff0d95U, 0x7139a801U, 0xde080cb3U, 0x9cd8b4e4U, 0x906456c1U, 0x617bcb84U, 0x70d532b6U, 0x74486c5cU, 0x42d0b857U, }; static const uint32_t TD2[256] = { 0xa75051f4U, 0x65537e41U, 0xa4c31a17U, 0x5e963a27U, 0x6bcb3babU, 0x45f11f9dU, 0x58abacfaU, 0x03934be3U, 0xfa552030U, 0x6df6ad76U, 0x769188ccU, 0x4c25f502U, 0xd7fc4fe5U, 0xcbd7c52aU, 0x44802635U, 0xa38fb562U, 0x5a49deb1U, 0x1b6725baU, 0x0e9845eaU, 0xc0e15dfeU, 0x7502c32fU, 0xf012814cU, 0x97a38d46U, 0xf9c66bd3U, 0x5fe7038fU, 0x9c951592U, 0x7aebbf6dU, 0x59da9552U, 0x832dd4beU, 0x21d35874U, 0x692949e0U, 0xc8448ec9U, 0x896a75c2U, 0x7978f48eU, 0x3e6b9958U, 0x71dd27b9U, 0x4fb6bee1U, 0xad17f088U, 0xac66c920U, 0x3ab47dceU, 0x4a1863dfU, 0x3182e51aU, 0x33609751U, 0x7f456253U, 0x77e0b164U, 0xae84bb6bU, 0xa01cfe81U, 0x2b94f908U, 0x68587048U, 0xfd198f45U, 0x6c8794deU, 0xf8b7527bU, 0xd323ab73U, 0x02e2724bU, 0x8f57e31fU, 0xab2a6655U, 0x2807b2ebU, 0xc2032fb5U, 0x7b9a86c5U, 0x08a5d337U, 0x87f23028U, 0xa5b223bfU, 0x6aba0203U, 0x825ced16U, 0x1c2b8acfU, 0xb492a779U, 0xf2f0f307U, 0xe2a14e69U, 0xf4cd65daU, 0xbed50605U, 0x621fd134U, 0xfe8ac4a6U, 0x539d342eU, 0x55a0a2f3U, 0xe132058aU, 0xeb75a4f6U, 0xec390b83U, 0xefaa4060U, 0x9f065e71U, 0x1051bd6eU, 0x8af93e21U, 0x063d96ddU, 0x05aedd3eU, 0xbd464de6U, 0x8db59154U, 0x5d0571c4U, 0xd46f0406U, 0x15ff6050U, 0xfb241998U, 0xe997d6bdU, 0x43cc8940U, 0x9e7767d9U, 0x42bdb0e8U, 0x8b880789U, 0x5b38e719U, 0xeedb79c8U, 0x0a47a17cU, 0x0fe97c42U, 0x1ec9f884U, 0x00000000U, 0x86830980U, 0xed48322bU, 0x70ac1e11U, 0x724e6c5aU, 0xfffbfd0eU, 0x38560f85U, 0xd51e3daeU, 0x3927362dU, 0xd9640a0fU, 0xa621685cU, 0x54d19b5bU, 0x2e3a2436U, 0x67b10c0aU, 0xe70f9357U, 0x96d2b4eeU, 0x919e1b9bU, 0xc54f80c0U, 0x20a261dcU, 0x4b695a77U, 0x1a161c12U, 0xba0ae293U, 0x2ae5c0a0U, 0xe0433c22U, 0x171d121bU, 0x0d0b0e09U, 0xc7adf28bU, 0xa8b92db6U, 0xa9c8141eU, 0x198557f1U, 0x074caf75U, 0xddbbee99U, 0x60fda37fU, 0x269ff701U, 0xf5bc5c72U, 0x3bc54466U, 0x7e345bfbU, 0x29768b43U, 0xc6dccb23U, 0xfc68b6edU, 0xf163b8e4U, 0xdccad731U, 0x85104263U, 0x22401397U, 0x112084c6U, 0x247d854aU, 0x3df8d2bbU, 0x3211aef9U, 0xa16dc729U, 0x2f4b1d9eU, 0x30f3dcb2U, 0x52ec0d86U, 0xe3d077c1U, 0x166c2bb3U, 0xb999a970U, 0x48fa1194U, 0x642247e9U, 0x8cc4a8fcU, 0x3f1aa0f0U, 0x2cd8567dU, 0x90ef2233U, 0x4ec78749U, 0xd1c1d938U, 0xa2fe8ccaU, 0x0b3698d4U, 0x81cfa6f5U, 0xde28a57aU, 0x8e26dab7U, 0xbfa43fadU, 0x9de42c3aU, 0x920d5078U, 0xcc9b6a5fU, 0x4662547eU, 0x13c2f68dU, 0xb8e890d8U, 0xf75e2e39U, 0xaff582c3U, 0x80be9f5dU, 0x937c69d0U, 0x2da96fd5U, 0x12b3cf25U, 0x993bc8acU, 0x7da71018U, 0x636ee89cU, 0xbb7bdb3bU, 0x7809cd26U, 0x18f46e59U, 0xb701ec9aU, 0x9aa8834fU, 0x6e65e695U, 0xe67eaaffU, 0xcf0821bcU, 0xe8e6ef15U, 0x9bd9bae7U, 0x36ce4a6fU, 0x09d4ea9fU, 0x7cd629b0U, 0xb2af31a4U, 0x23312a3fU, 0x9430c6a5U, 0x66c035a2U, 0xbc37744eU, 0xcaa6fc82U, 0xd0b0e090U, 0xd81533a7U, 0x984af104U, 0xdaf741ecU, 0x500e7fcdU, 0xf62f1791U, 0xd68d764dU, 0xb04d43efU, 0x4d54ccaaU, 0x04dfe496U, 0xb5e39ed1U, 0x881b4c6aU, 0x1fb8c12cU, 0x517f4665U, 0xea049d5eU, 0x355d018cU, 0x7473fa87U, 0x412efb0bU, 0x1d5ab367U, 0xd25292dbU, 0x5633e910U, 0x47136dd6U, 0x618c9ad7U, 0x0c7a37a1U, 0x148e59f8U, 0x3c89eb13U, 0x27eecea9U, 0xc935b761U, 0xe5ede11cU, 0xb13c7a47U, 0xdf599cd2U, 0x733f55f2U, 0xce791814U, 0x37bf73c7U, 0xcdea53f7U, 0xaa5b5ffdU, 0x6f14df3dU, 0xdb867844U, 0xf381caafU, 0xc43eb968U, 0x342c3824U, 0x405fc2a3U, 0xc372161dU, 0x250cbce2U, 0x498b283cU, 0x9541ff0dU, 0x017139a8U, 0xb3de080cU, 0xe49cd8b4U, 0xc1906456U, 0x84617bcbU, 0xb670d532U, 0x5c74486cU, 0x5742d0b8U, }; static const uint32_t TD3[256] = { 0xf4a75051U, 0x4165537eU, 0x17a4c31aU, 0x275e963aU, 0xab6bcb3bU, 0x9d45f11fU, 0xfa58abacU, 0xe303934bU, 0x30fa5520U, 0x766df6adU, 0xcc769188U, 0x024c25f5U, 0xe5d7fc4fU, 0x2acbd7c5U, 0x35448026U, 0x62a38fb5U, 0xb15a49deU, 0xba1b6725U, 0xea0e9845U, 0xfec0e15dU, 0x2f7502c3U, 0x4cf01281U, 0x4697a38dU, 0xd3f9c66bU, 0x8f5fe703U, 0x929c9515U, 0x6d7aebbfU, 0x5259da95U, 0xbe832dd4U, 0x7421d358U, 0xe0692949U, 0xc9c8448eU, 0xc2896a75U, 0x8e7978f4U, 0x583e6b99U, 0xb971dd27U, 0xe14fb6beU, 0x88ad17f0U, 0x20ac66c9U, 0xce3ab47dU, 0xdf4a1863U, 0x1a3182e5U, 0x51336097U, 0x537f4562U, 0x6477e0b1U, 0x6bae84bbU, 0x81a01cfeU, 0x082b94f9U, 0x48685870U, 0x45fd198fU, 0xde6c8794U, 0x7bf8b752U, 0x73d323abU, 0x4b02e272U, 0x1f8f57e3U, 0x55ab2a66U, 0xeb2807b2U, 0xb5c2032fU, 0xc57b9a86U, 0x3708a5d3U, 0x2887f230U, 0xbfa5b223U, 0x036aba02U, 0x16825cedU, 0xcf1c2b8aU, 0x79b492a7U, 0x07f2f0f3U, 0x69e2a14eU, 0xdaf4cd65U, 0x05bed506U, 0x34621fd1U, 0xa6fe8ac4U, 0x2e539d34U, 0xf355a0a2U, 0x8ae13205U, 0xf6eb75a4U, 0x83ec390bU, 0x60efaa40U, 0x719f065eU, 0x6e1051bdU, 0x218af93eU, 0xdd063d96U, 0x3e05aeddU, 0xe6bd464dU, 0x548db591U, 0xc45d0571U, 0x06d46f04U, 0x5015ff60U, 0x98fb2419U, 0xbde997d6U, 0x4043cc89U, 0xd99e7767U, 0xe842bdb0U, 0x898b8807U, 0x195b38e7U, 0xc8eedb79U, 0x7c0a47a1U, 0x420fe97cU, 0x841ec9f8U, 0x00000000U, 0x80868309U, 0x2bed4832U, 0x1170ac1eU, 0x5a724e6cU, 0x0efffbfdU, 0x8538560fU, 0xaed51e3dU, 0x2d392736U, 0x0fd9640aU, 0x5ca62168U, 0x5b54d19bU, 0x362e3a24U, 0x0a67b10cU, 0x57e70f93U, 0xee96d2b4U, 0x9b919e1bU, 0xc0c54f80U, 0xdc20a261U, 0x774b695aU, 0x121a161cU, 0x93ba0ae2U, 0xa02ae5c0U, 0x22e0433cU, 0x1b171d12U, 0x090d0b0eU, 0x8bc7adf2U, 0xb6a8b92dU, 0x1ea9c814U, 0xf1198557U, 0x75074cafU, 0x99ddbbeeU, 0x7f60fda3U, 0x01269ff7U, 0x72f5bc5cU, 0x663bc544U, 0xfb7e345bU, 0x4329768bU, 0x23c6dccbU, 0xedfc68b6U, 0xe4f163b8U, 0x31dccad7U, 0x63851042U, 0x97224013U, 0xc6112084U, 0x4a247d85U, 0xbb3df8d2U, 0xf93211aeU, 0x29a16dc7U, 0x9e2f4b1dU, 0xb230f3dcU, 0x8652ec0dU, 0xc1e3d077U, 0xb3166c2bU, 0x70b999a9U, 0x9448fa11U, 0xe9642247U, 0xfc8cc4a8U, 0xf03f1aa0U, 0x7d2cd856U, 0x3390ef22U, 0x494ec787U, 0x38d1c1d9U, 0xcaa2fe8cU, 0xd40b3698U, 0xf581cfa6U, 0x7ade28a5U, 0xb78e26daU, 0xadbfa43fU, 0x3a9de42cU, 0x78920d50U, 0x5fcc9b6aU, 0x7e466254U, 0x8d13c2f6U, 0xd8b8e890U, 0x39f75e2eU, 0xc3aff582U, 0x5d80be9fU, 0xd0937c69U, 0xd52da96fU, 0x2512b3cfU, 0xac993bc8U, 0x187da710U, 0x9c636ee8U, 0x3bbb7bdbU, 0x267809cdU, 0x5918f46eU, 0x9ab701ecU, 0x4f9aa883U, 0x956e65e6U, 0xffe67eaaU, 0xbccf0821U, 0x15e8e6efU, 0xe79bd9baU, 0x6f36ce4aU, 0x9f09d4eaU, 0xb07cd629U, 0xa4b2af31U, 0x3f23312aU, 0xa59430c6U, 0xa266c035U, 0x4ebc3774U, 0x82caa6fcU, 0x90d0b0e0U, 0xa7d81533U, 0x04984af1U, 0xecdaf741U, 0xcd500e7fU, 0x91f62f17U, 0x4dd68d76U, 0xefb04d43U, 0xaa4d54ccU, 0x9604dfe4U, 0xd1b5e39eU, 0x6a881b4cU, 0x2c1fb8c1U, 0x65517f46U, 0x5eea049dU, 0x8c355d01U, 0x877473faU, 0x0b412efbU, 0x671d5ab3U, 0xdbd25292U, 0x105633e9U, 0xd647136dU, 0xd7618c9aU, 0xa10c7a37U, 0xf8148e59U, 0x133c89ebU, 0xa927eeceU, 0x61c935b7U, 0x1ce5ede1U, 0x47b13c7aU, 0xd2df599cU, 0xf2733f55U, 0x14ce7918U, 0xc737bf73U, 0xf7cdea53U, 0xfdaa5b5fU, 0x3d6f14dfU, 0x44db8678U, 0xaff381caU, 0x68c43eb9U, 0x24342c38U, 0xa3405fc2U, 0x1dc37216U, 0xe2250cbcU, 0x3c498b28U, 0x0d9541ffU, 0xa8017139U, 0x0cb3de08U, 0xb4e49cd8U, 0x56c19064U, 0xcb84617bU, 0x32b670d5U, 0x6c5c7448U, 0xb85742d0U, }; static void SetDecryptKeyTbox(CRYPT_AES_Key *ctx) { uint32_t i, j; uint32_t *dkey = ctx->key; for (i = 1; i < ctx->rounds; i++) { dkey += 4; // 4: 16 bytes are calculated each time. for (j = 0; j < 4; j++) { // for 0 to 4 , operation for 16 / sizeof(uint32_t) cycles dkey[j] = TD0[TE1[(dkey[j] >> 24)] & 0xff] ^ // dkey j >> 24 TD1[TE1[(dkey[j] >> 16) & 0xff] & 0xff] ^ // dkey j >> 16 TD2[TE1[(dkey[j] >> 8) & 0xff] & 0xff] ^ // dkey j >> 8 TD3[TE1[(dkey[j] >> 0) & 0xff] & 0xff]; // dkey j >> 0 } } } static inline uint32_t AES_G(uint32_t w, uint32_t rcon) { uint32_t ret = 0; /* Query the table and perform shift. */ ret ^= (uint32_t)TE2[(w >> 16) & 0xff] & 0xff000000; // 16, row/column conversion relationship in the T table ret ^= (uint32_t)TE3[(w >> 8) & 0xff] & 0x00ff0000; // 8, row/column conversion relationship in the T table ret ^= (uint32_t)TE0[(w) & 0xff] & 0x0000ff00; // 0, row/column conversion relationship in the T table ret ^= (uint32_t)TE1[(w >> 24)] & 0x000000ff; // 24, row/column conversion relationship in the T table ret ^= rcon; return ret; } void SetEncryptKey128Tbox(CRYPT_AES_Key *ctx, const uint8_t *key) { uint32_t *ekey = ctx->key; ekey[0] = GET_UINT32_BE(key, 0); // ekey 0: Four bytes starting from index key 0 ekey[1] = GET_UINT32_BE(key, 4); // ekey 1: Four bytes starting from index key 4 ekey[2] = GET_UINT32_BE(key, 8); // ekey 2: Four bytes starting from index key 8 ekey[3] = GET_UINT32_BE(key, 12); // ekey 3: Four bytes starting from index key 12 // 128bit Key length required 11 * 4 = 44. Number of expansion rounds: 10 -> 10 * 4 + 4 = 44 uint32_t times; for (times = 0; times < 9; times++) { // 9 times ekey[4] = AES_G(ekey[3], RCON[times]) ^ ekey[0]; // ekey 4 = (ekey 3 xor rcon) ^ ekey 0 ekey[5] = ekey[4] ^ ekey[1]; // ekey 5 = ekey 4 ^ ekey 1 ekey[6] = ekey[5] ^ ekey[2]; // ekey 6 = ekey 5 ^ ekey 2 ekey[7] = ekey[6] ^ ekey[3]; // ekey 7 = ekey 6 ^ ekey 3 ekey += 4; // add 4 } // the last times ekey[4] = AES_G(ekey[3], RCON[times]) ^ ekey[0]; // ekey 4 = (ekey 3 xor rcon) ^ ekey 0 ekey[5] = ekey[4] ^ ekey[1]; // ekey 5 = ekey 4 ^ ekey 1 ekey[6] = ekey[5] ^ ekey[2]; // ekey 6 = ekey 5 ^ ekey 2 ekey[7] = ekey[6] ^ ekey[3]; // ekey 7 = ekey 6 ^ ekey 3 } void SetEncryptKey192Tbox(CRYPT_AES_Key *ctx, const uint8_t *key) { uint32_t *ekey = ctx->key; ekey[0] = GET_UINT32_BE(key, 0); // ekey 0: Four bytes starting from index key 0 ekey[1] = GET_UINT32_BE(key, 4); // ekey 1: Four bytes starting from index key 4 ekey[2] = GET_UINT32_BE(key, 8); // ekey 2: Four bytes starting from index key 8 ekey[3] = GET_UINT32_BE(key, 12); // ekey 3: Four bytes starting from index key 12 ekey[4] = GET_UINT32_BE(key, 16); // ekey 4: Four bytes starting from index key 16 ekey[5] = GET_UINT32_BE(key, 20); // ekey 5: Four bytes starting from index key 20 uint32_t times; for (times = 0; times < 7; times++) { // 7 times ekey[6] = AES_G(ekey[5], RCON[times]) ^ ekey[0]; // ekey 6 = AES_G(ekey 5 xor rcon) ^ ekey 0 ekey[7] = ekey[6] ^ ekey[1]; // ekey 7 = ekey 6 ^ ekey 1 ekey[8] = ekey[7] ^ ekey[2]; // ekey 8 = ekey 7 ^ ekey 2 ekey[9] = ekey[8] ^ ekey[3]; // ekey 9 = ekey 8 ^ ekey 3 ekey[10] = ekey[9] ^ ekey[4]; // ekey 10 = ekey 9 ^ ekey 4 ekey[11] = ekey[10] ^ ekey[5]; // ekey 11 = ekey 10 ^ ekey 5 ekey += 6; // add 6 } // the last times ekey[6] = AES_G(ekey[5], RCON[times]) ^ ekey[0]; // ekey 6 = AES_G(ekey 5 xor rcon) ^ ekey 0 ekey[7] = ekey[6] ^ ekey[1]; // ekey 7 = ekey 6 ^ ekey 1 ekey[8] = ekey[7] ^ ekey[2]; // ekey 8 = ekey 7 ^ ekey 2 ekey[9] = ekey[8] ^ ekey[3]; // ekey 9 = ekey 8 ^ ekey 3 } void SetEncryptKey256Tbox(CRYPT_AES_Key *ctx, const uint8_t *key) { uint32_t *ekey = ctx->key; ekey[0] = GET_UINT32_BE(key, 0); // ekey 0: Four bytes starting from index key 0 ekey[1] = GET_UINT32_BE(key, 4); // ekey 1: Four bytes starting from index key 4 ekey[2] = GET_UINT32_BE(key, 8); // ekey 2: Four bytes starting from index key 8 ekey[3] = GET_UINT32_BE(key, 12); // ekey 3: Four bytes starting from index key 12 ekey[4] = GET_UINT32_BE(key, 16); // ekey 4: Four bytes starting from index key 16 ekey[5] = GET_UINT32_BE(key, 20); // ekey 5: Four bytes starting from index key 20 ekey[6] = GET_UINT32_BE(key, 24); // ekey 6: Four bytes starting from index key 24 ekey[7] = GET_UINT32_BE(key, 28); // ekey 7: Four bytes starting from index key 28 /* The key length must be 15 * 4 = 60. The number of extension rounds is 7 -> 7 * 8 + 8 - 4 = 60 */ uint32_t times; uint32_t tmp; for (times = 0; times < 6; times++) { // 6 times ekey[8] = AES_G(ekey[7], RCON[times]) ^ ekey[0]; // ekey 8 = AES_G(ekey 7 xor rcon) ^ ekey 0 ekey[9] = ekey[8] ^ ekey[1]; // ekey 9 = ekey 8 ^ ekey 1 ekey[10] = ekey[9] ^ ekey[2]; // ekey 10 = ekey 9 ^ ekey 2 ekey[11] = ekey[10] ^ ekey[3]; // ekey 11 = ekey 10 ^ ekey 3 /* Shift operation to compensate for G operation */ tmp = (ekey[11] >> 8) | (ekey[11] << 24); // tmp is ekey 11 >> 8 | ekey 11 << 24 ekey[12] = AES_G(tmp, 0) ^ ekey[4]; // ekey 12 = AES_G(tme, 0) ^ ekey 4 ekey[13] = ekey[12] ^ ekey[5]; // ekey 13 = ekey 12 ^ ekey 5 ekey[14] = ekey[13] ^ ekey[6]; // ekey 14 = ekey 13 ^ ekey 6 ekey[15] = ekey[14] ^ ekey[7]; // ekey 15 = ekey 14 ^ ekey 7 ekey += 8; // add 8 } // the last times ekey[8] = AES_G(ekey[7], RCON[times]) ^ ekey[0]; // ekey 8 = AES_G(ekey 7 xor rcon) ^ ekey 0 ekey[9] = ekey[8] ^ ekey[1]; // ekey 9 = ekey 8 ^ ekey 1 ekey[10] = ekey[9] ^ ekey[2]; // ekey 10 = ekey 9 ^ ekey 2 ekey[11] = ekey[10] ^ ekey[3]; // ekey 11 = ekey 10 ^ ekey 3 } void SetAesKeyExpansionTbox(CRYPT_AES_Key *ctx, uint32_t keyLenBits, const uint8_t *key, bool isEncrypt) { switch (keyLenBits) { case CRYPT_AES_128: SetEncryptKey128Tbox(ctx, key); break; case CRYPT_AES_192: SetEncryptKey192Tbox(ctx, key); break; case CRYPT_AES_256: SetEncryptKey256Tbox(ctx, key); break; default: return; } if (!isEncrypt) { SetDecryptKeyTbox(ctx); } } #define AES_ROUND_INIT(in, r, enc) \ do { \ r##0 = GET_UINT32_BE(in, 0) ^ enc##key[0]; \ r##1 = GET_UINT32_BE(in, 4) ^ enc##key[1]; \ r##2 = GET_UINT32_BE(in, 8) ^ enc##key[2]; \ r##3 = GET_UINT32_BE(in, 12) ^ enc##key[3]; \ } while (0) #define AES_ENC_ROUND(in, r, i, ekey) \ do { \ r##0 = TE0[(in##0 >> 24)] ^ TE1[(in##1 >> 16) & 0xff] ^ TE2[(in##2 >> 8) & 0xff] ^ TE3[(in##3) & 0xff] \ ^ (ekey)[((i) << 2) + 0]; \ r##1 = TE0[(in##1 >> 24)] ^ TE1[(in##2 >> 16) & 0xff] ^ TE2[(in##3 >> 8) & 0xff] ^ TE3[(in##0) & 0xff] \ ^ (ekey)[((i) << 2) + 1]; \ r##2 = TE0[(in##2 >> 24)] ^ TE1[(in##3 >> 16) & 0xff] ^ TE2[(in##0 >> 8) & 0xff] ^ TE3[(in##1) & 0xff] \ ^ (ekey)[((i) << 2) + 2]; \ r##3 = TE0[(in##3 >> 24)] ^ TE1[(in##0 >> 16) & 0xff] ^ TE2[(in##1 >> 8) & 0xff] ^ TE3[(in##2) & 0xff] \ ^ (ekey)[((i) << 2) + 3]; \ } while (0) void CRYPT_AES_EncryptTbox(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { (void)len; const uint32_t *ekey = ctx->key; uint32_t c0, c1, c2, c3, t0, t1, t2, t3; AES_ROUND_INIT(in, c, e); AES_ENC_ROUND(c, t, 1, ekey); AES_ENC_ROUND(t, c, 2, ekey); AES_ENC_ROUND(c, t, 3, ekey); AES_ENC_ROUND(t, c, 4, ekey); AES_ENC_ROUND(c, t, 5, ekey); AES_ENC_ROUND(t, c, 6, ekey); AES_ENC_ROUND(c, t, 7, ekey); AES_ENC_ROUND(t, c, 8, ekey); AES_ENC_ROUND(c, t, 9, ekey); if (ctx->rounds > 10) { // AES192/AES256 Performs 10th and 11th rounds of calculation. AES_ENC_ROUND(t, c, 10, ekey); AES_ENC_ROUND(c, t, 11, ekey); } if (ctx->rounds > 12) { // AES256 Performs 12th and 13th rounds of calculation. AES_ENC_ROUND(t, c, 12, ekey); AES_ENC_ROUND(c, t, 13, ekey); } /* In the last round, the column confusion is not performed. Instead, the shift is performed and the s-box is searched. */ // Do the position of the last ekey calculation, which is the ekey that has been used 4*rounds. ekey += ctx->rounds * 4; c0 = TESEARCH(t0, t1, t2, t3) ^ ekey[0]; // operation ekey 0 c1 = TESEARCH(t1, t2, t3, t0) ^ ekey[1]; // operation ekey 1 c2 = TESEARCH(t2, t3, t0, t1) ^ ekey[2]; // operation ekey 2 c3 = TESEARCH(t3, t0, t1, t2) ^ ekey[3]; // operation ekey 3 PUT_UINT32_BE(c0, out, 0); // c0 is converted into four bytes which index is 0 in the out. PUT_UINT32_BE(c1, out, 4); // c1 is converted into four bytes which index is 4 in the out. PUT_UINT32_BE(c2, out, 8); // c2 is converted into four bytes which index is 8 in the out PUT_UINT32_BE(c3, out, 12); // c3 is converted into four bytes which index is 12 in the out } #define AES_DEC_ROUND(in, r, i, dkey) \ do { \ r##0 = TD0[(in##0 >> 24)] ^ TD1[(in##3 >> 16) & 0xff] ^ TD2[(in##2 >> 8) & 0xff] ^ TD3[(in##1) & 0xff] \ ^ (dkey)[((i) << 2) + 0]; \ r##1 = TD0[(in##1 >> 24)] ^ TD1[(in##0 >> 16) & 0xff] ^ TD2[(in##3 >> 8) & 0xff] ^ TD3[(in##2) & 0xff] \ ^ (dkey)[((i) << 2) + 1]; \ r##2 = TD0[(in##2 >> 24)] ^ TD1[(in##1 >> 16) & 0xff] ^ TD2[(in##0 >> 8) & 0xff] ^ TD3[(in##3) & 0xff] \ ^ (dkey)[((i) << 2) + 2]; \ r##3 = TD0[(in##3 >> 24)] ^ TD1[(in##2 >> 16) & 0xff] ^ TD2[(in##1 >> 8) & 0xff] ^ TD3[(in##0) & 0xff] \ ^ (dkey)[((i) << 2) + 3]; \ } while (0) void CRYPT_AES_DecryptTbox(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { (void)len; const uint32_t *dkey = ctx->key + ctx->rounds * 4; // 4 bytes uint32_t p0, p1, p2, p3, t0, t1, t2, t3; // Initialize p0. The dkey starts from the end of the key. AES_ROUND_INIT(in, p, d); dkey = ctx->key; if (ctx->rounds > 12) { // AES256 Performs 12th and 13th rounds of calculation. AES_DEC_ROUND(p, t, 13, dkey); AES_DEC_ROUND(t, p, 12, dkey); } if (ctx->rounds > 10) { // AES192 Performs 10th and 11th rounds of calculation. AES_DEC_ROUND(p, t, 11, dkey); AES_DEC_ROUND(t, p, 10, dkey); } AES_DEC_ROUND(p, t, 9, dkey); AES_DEC_ROUND(t, p, 8, dkey); AES_DEC_ROUND(p, t, 7, dkey); AES_DEC_ROUND(t, p, 6, dkey); AES_DEC_ROUND(p, t, 5, dkey); AES_DEC_ROUND(t, p, 4, dkey); AES_DEC_ROUND(p, t, 3, dkey); AES_DEC_ROUND(t, p, 2, dkey); AES_DEC_ROUND(p, t, 1, dkey); /* In the last round, the column confusion is not performed. Instead, the shift is directly performed and the inverse s-box is searched. */ p0 = INVSSEARCH(t0, t1, t2, t3) ^ dkey[0]; // dkey 0 p1 = INVSSEARCH(t1, t2, t3, t0) ^ dkey[1]; // dkey 1 p2 = INVSSEARCH(t2, t3, t0, t1) ^ dkey[2]; // dkey 2 p3 = INVSSEARCH(t3, t0, t1, t2) ^ dkey[3]; // dkey 3 PUT_UINT32_BE(p0, out, 0); // 4 bytes starting from the index 0 of the in PUT_UINT32_BE(p1, out, 4); // 4 bytes starting from the index 4 of the in PUT_UINT32_BE(p2, out, 8); // 4 bytes starting from the index 8 of the in PUT_UINT32_BE(p3, out, 12); // 4 bytes starting from the index 12 of the in BSL_SAL_CleanseData(&p0, sizeof(uint32_t)); BSL_SAL_CleanseData(&p1, sizeof(uint32_t)); BSL_SAL_CleanseData(&p2, sizeof(uint32_t)); BSL_SAL_CleanseData(&p3, sizeof(uint32_t)); } #endif /* HITLS_CRYPTO_AES_PRECALC_TABLES */ #endif /* HITLS_CRYPTO_AES */
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/crypt_aes_tbox.c
C
unknown
44,548
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_AES_TBOX_H #define CRYPT_AES_TBOX_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_AES) && defined(HITLS_CRYPTO_AES_PRECALC_TABLES) #include "crypt_aes.h" void SetAesKeyExpansionTbox(CRYPT_AES_Key *ctx, uint32_t keyLenBits, const uint8_t *key, bool isEncrypt); void CRYPT_AES_EncryptTbox(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len); void CRYPT_AES_DecryptTbox(const CRYPT_AES_Key *ctx, const uint8_t *in, uint8_t *out, uint32_t len); #endif /* HITLS_CRYPTO_AES_PRECALC_TABLES */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/aes/src/crypt_aes_tbox.h
C
unknown
1,107
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_BN_H #define CRYPT_BN_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include <stdlib.h> #include <stdbool.h> #ifdef __cplusplus extern "C" { #endif #if defined(HITLS_SIXTY_FOUR_BITS) #define BN_UINT uint64_t #define BN_MASK (0xffffffffffffffffL) #define BN_DEC_VAL (10000000000000000000ULL) #define BN_DEC_LEN 19 #define BN_UNIT_BITS 64 #elif defined(HITLS_THIRTY_TWO_BITS) #define BN_UINT uint32_t #define BN_MASK (0xffffffffL) #define BN_DEC_VAL (1000000000L) #define BN_DEC_LEN 9 #define BN_UNIT_BITS 32 #else #error BN_UINT MUST be defined first. #endif #define BN_MAX_BITS (1u << 29) /* @note: BN_BigNum bits limitation 2^29 bits */ #define BN_BITS_TO_BYTES(n) (((n) + 7) >> 3) /* @note: Calcute bytes form bits, bytes = (bits + 7) >> 3 */ #define BN_BYTES_TO_BITS(n) ((n) << 3) /* bits = bytes * 8 = bytes << 3 */ #define BN_UINT_BITS ((uint32_t)sizeof(BN_UINT) << 3) #define BITS_TO_BN_UNIT(bits) (((bits) + BN_UINT_BITS - 1) / BN_UINT_BITS) /* Flag of BigNum. If a new number is added, the value increases by 0x01 0x02 0x04... */ typedef enum { CRYPT_BN_FLAG_OPTIMIZER = 0x01, /**< Flag of BigNum, indicating the BigNum obtained from the optimizer */ CRYPT_BN_FLAG_STATIC = 0x02, /**< Flag of BigNum, indicating the BN memory management belongs to the user. */ CRYPT_BN_FLAG_CONSTTIME = 0x04, /**< Flag of BigNum, indicating the constant time execution. */ } CRYPT_BN_FLAG; typedef struct BigNum { bool sign; /* *< bignum sign: negtive(true) or not(false) */ uint32_t size; /* *< bignum size (count of BN_UINT) */ uint32_t room; /* *< bignum max size (count of BN_UINT) */ uint32_t flag; /* *< bignum flag */ BN_UINT *data; /* *< bignum data chunk(most significant limb at the largest) */ } BN_BigNum; typedef struct BnMont BN_Mont; typedef struct BnOptimizer BN_Optimizer; typedef struct BnCbCtx BN_CbCtx; typedef int32_t (*BN_CallBack)(BN_CbCtx *, int32_t, int32_t); /* If a is 0, all Fs are returned. If a is not 0, 0 is returned. */ static inline BN_UINT BN_IsZeroUintConsttime(BN_UINT a) { BN_UINT t = ~a & (a - 1); // The most significant bit of t is 1 only when a == 0. // Shifting 3 bits to the left is equivalent to multiplying 8, convert the number of bytes into the number of bits. return (BN_UINT)0 - (t >> (((uint32_t)sizeof(BN_UINT) << 3) - 1)); } #ifdef HITLS_CRYPTO_EAL_BN /* Check whether the BN entered externally is valid. */ bool BnVaild(const BN_BigNum *a); #endif /** * @ingroup bn * @brief BigNum creation * * @param bits [IN] Number of bits * * @retval not-NULL Success * @retval NULL fail */ BN_BigNum *BN_Create(uint32_t bits); /** * @ingroup bn * @brief BigNum Destruction * * @param a [IN] BigNum * * @retval none */ void BN_Destroy(BN_BigNum *a); /** * @ingroup bn * @brief BN initialization * @attention This interface is used to create the BN structure between modules. The BN does not manage the memory of the external BN structure and internal data space. the interface only the fixed attributes such as data, room, and flag. The size attribute is defined by the caller. * * @param bn [IN/OUT] BN, which is created by users and is not managed by the BN. * @param data [IN] BN data, the memory is allocated by the user and is not managed by the BN. * @param number [IN] number of BN that need to be initialized. * * @retval void */ void BN_Init(BN_BigNum *bn, BN_UINT *data, uint32_t room, int32_t number); #ifdef HITLS_CRYPTO_BN_CB /** * @ingroup bn * @brief BigNum callback creation * * @param none * * @retval not-NULL Success * @retval NULL fail */ BN_CbCtx *BN_CbCtxCreate(void); /** * @ingroup bn * @brief BigNum callback configuration * * @param gencb [out] Callback * @param callBack [in] Callback API * @param arg [in] Callback parameters * * @retval none */ void BN_CbCtxSet(BN_CbCtx *gencb, BN_CallBack callBack, void *arg); /** * @ingroup bn * @brief Invoke the callback. * * @param callBack [out] Callback * @param process [in] Parameter * @param target [in] Parameter * @retval CRYPT_SUCCESS succeeded * @retval other determined by the callback function */ int32_t BN_CbCtxCall(BN_CbCtx *callBack, int32_t process, int32_t target); /** * @ingroup bn * @brief Obtain the arg parameter in the callback. * * @param callBack [in] Callback * @retval void* NULL or callback parameter. */ void *BN_CbCtxGetArg(BN_CbCtx *callBack); /** * @ingroup bn * @brief Callback release * * @param cb [in] Callback * * @retval none */ void BN_CbCtxDestroy(BN_CbCtx *cb); #endif /** * @ingroup bn * @brief Set the symbol. * * @param a [IN] BigNum * @param sign [IN] symbol. The value true indicates a negative number and the value false indicates a positive number. * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_BN_NO_NEGATOR_ZERO 0 cannot be set to a negative sign. */ int32_t BN_SetSign(BN_BigNum *a, bool sign); /** * @ingroup bn * @brief Set the flag. * * @param a [IN] BigNum * @param flag [IN] flag, for example, BN_MARK_CONSTTIME indicates that the constant interface is used. * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_BN_FLAG_INVALID Invalid BigNum flag. */ int32_t BN_SetFlag(BN_BigNum *a, uint32_t flag); /** * @ingroup bn * @brief BigNum copy * * @param r [OUT] BigNum * @param a [IN] BigNum * * @retval CRYPT_SUCCESS succeeded. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_Copy(BN_BigNum *r, const BN_BigNum *a); /** * @ingroup bn * @brief Generate a BigNum with the same content. * * @param a [IN] BigNum * * @retval Not NULL Success * @retval NULL failure */ BN_BigNum *BN_Dup(const BN_BigNum *a); /** * @ingroup bn * @brief Check whether the value of a BigNum is 0. * * @attention The input parameter cannot be null. * @param a [IN] BigNum * * @retval true. The value of a BigNum is 0. * @retval false. The value of a BigNum is not 0. * @retval other: indicates that the input parameter is abnormal. * */ bool BN_IsZero(const BN_BigNum *a); /** * @ingroup bn * @brief Check whether the value of a BigNum is 1. * * @attention The input parameter cannot be null. * @param a [IN] BigNum * * @retval true. The value of a BigNum is 1. * @retval false. The value of a BigNum is not 1. * @retval other: indicates that the input parameter is abnormal. * */ bool BN_IsOne(const BN_BigNum *a); /** * @ingroup bn * @brief Check whether a BigNum is a negative number. * * @attention The input parameter cannot be null. * @param a [IN] BigNum * * @retval true. The value of a BigNum is a negative number. * @retval false. The value of a BigNum is not a negative number. * */ bool BN_IsNegative(const BN_BigNum *a); /** * @ingroup bn * @brief Check whether the value of a BigNum is an odd number. * * @attention The input parameter cannot be null. * @param a [IN] BigNum * * @retval true. The value of a BigNum is an odd number. * @retval false. The value of a BigNum is not an odd number. * @retval other: indicates that the input parameter is abnormal. * */ bool BN_IsOdd(const BN_BigNum *a); /** * @ingroup bn * @brief Check whether the flag of a BigNum meets the expected flag. * * @param a [IN] BigNum * @param flag [IN] Flag. For example, BN_MARK_CONSTTIME indicates that the constant interface is used. * * @retval true, invalid null pointer * @retval false, 0 cannot be set to a negative number. * @retval other: indicates that the input parameter is abnormal. */ bool BN_IsFlag(const BN_BigNum *a, uint32_t flag); /** * @ingroup bn * @brief Set the value of a BigNum to 0. * * @param a [IN] BigNum * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval other: indicates that the input parameter is abnormal. */ int32_t BN_Zeroize(BN_BigNum *a); /** * @ingroup bn * @brief Compare whether the value of BigNum a is the target limb w. * * @attention The input parameter cannot be null. * @param a [IN] BigNum * @param w [IN] Limb * * @retval true: equal * @retval false, not equal * @retval other: indicates that the input parameter is abnormal. */ bool BN_IsLimb(const BN_BigNum *a, const BN_UINT w); /** * @ingroup bn * @brief Set a limb to the BigNum. * * @param a [IN] BigNum * @param w [IN] Limb * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_SetLimb(BN_BigNum *r, BN_UINT w); /** * @ingroup bn * @brief Obtain the limb from the BigNum. * * @param a [IN] BigNum * * @retval 0 Get 0 * @retval BN_MASK Obtain the mask. * @retval others The limb is obtained successfully. */ BN_UINT BN_GetLimb(const BN_BigNum *a); /** * @ingroup bn * @brief Obtain the value of the bit corresponding to a BigNum. The value is 1 or 0. * * @attention The input parameter of a BigNum cannot be null. * @param a [IN] BigNum * @param n [IN] Number of bits * * @retval true. The corresponding bit is 1. * @retval false. The corresponding bit is 0. * */ bool BN_GetBit(const BN_BigNum *a, uint32_t n); /** * @ingroup bn * @brief Set the bit corresponding to the BigNum to 1. * * @param a [IN] BigNum * @param n [IN] Number of bits * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_BN_SPACE_NOT_ENOUGH The space is insufficient. */ int32_t BN_SetBit(BN_BigNum *a, uint32_t n); /** * @ingroup bn * @brief Clear the bit corresponding to the BigNum to 0. * * @param a [IN] BigNum * @param n [IN] Number of bits * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_BN_SPACE_NOT_ENOUGH The space is insufficient. */ int32_t BN_ClrBit(BN_BigNum *a, uint32_t n); /** * @ingroup bn * @brief Truncate a BigNum from the corresponding bit. * * @param a [IN] BigNum * @param n [IN] Number of bits * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_BN_SPACE_NOT_ENOUGH The space is insufficient. */ int32_t BN_MaskBit(BN_BigNum *a, uint32_t n); /** * @ingroup bn * @brief Obtain the valid bit length of a BigNum. * * @attention The input parameter of a BigNum cannot be null. * @param a [IN] BigNum * * @retval uint32_t, valid bit length */ uint32_t BN_Bits(const BN_BigNum *a); /** * @ingroup bn * @brief Obtain the valid byte length of a BigNum. * * @attention The large input parameter cannot be a null pointer. * @param a [IN] BigNum * * @retval uint32_t, valid byte length of a BigNum */ uint32_t BN_Bytes(const BN_BigNum *a); /** * @ingroup bn * @brief BigNum Calculate the greatest common divisor * @par Description: gcd(a, b) (a, b!=0) * * @param r [OUT] greatest common divisor * @param a [IN] BigNum * @param b [IN] BigNum * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_ERR_GCD_NO_ZERO The greatest common divisor cannot be 0. */ int32_t BN_Gcd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum modulo inverse * * @param r [OUT] Result * @param x [IN] BigNum * @param m [IN] mod * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_ERR_NO_INVERSE Cannot calculate the module inverse. */ int32_t BN_ModInv(BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *m, BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum comparison * * @attention The input parameter of a BigNum cannot be null. * @param a [IN] BigNum * @param b [IN] BigNum * * @retval 0,a == b * @retval 1,a > b * @retval -1,a < b */ int32_t BN_Cmp(const BN_BigNum *a, const BN_BigNum *b); /** * @ingroup bn * @brief BigNum Addition * * @param r [OUT] and * @param a [IN] Addendum * @param b [IN] Addendum * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_Add(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b); /** * @ingroup bn * @brief BigNum plus limb * * @param r [OUT] and * @param a [IN] Addendum * @param w [IN] Addendum * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_AddLimb(BN_BigNum *r, const BN_BigNum *a, BN_UINT w); /** * @ingroup bn * @brief subtraction of large numbers * * @param r [OUT] difference * @param a [IN] minuend * @param b [IN] subtrahend * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_Sub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b); /** * @ingroup bn * @brief BigNum minus limb * * @param r [OUT] difference * @param a [IN] minuend * @param w [IN] subtrahend * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_SubLimb(BN_BigNum *r, const BN_BigNum *a, BN_UINT w); /** * @ingroup bn * @brief BigNum Multiplication * * @param r [OUT] product * @param a [IN] multiplier * @param b [IN] multiplier * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. */ int32_t BN_Mul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt); /** * @ingroup bn * @brief Multiplication of BigNum by Limb * * @param r [OUT] product * @param a [IN] multiplicand * @param w [IN] multiplier (limb) * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_MulLimb(BN_BigNum *r, const BN_BigNum *a, const BN_UINT w); /** * @ingroup bn * @brief BigNum square. r must not be a. * * @param r [OUT] product * @param a [IN] multiplier * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. */ int32_t BN_Sqr(BN_BigNum *r, const BN_BigNum *a, BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum Division * * @param q [OUT] quotient * @param r [OUT] remainder * @param x [IN] dividend * @param y [IN] divisor * @param opt [IN] optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_INVALID_ARG The addresses of q, r are identical, or both of them are null. * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_ERR_DIVISOR_ZERO divisor cannot be 0. */ int32_t BN_Div(BN_BigNum *q, BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *y, BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum divided by limb * * @param q [OUT] quotient * @param r [OUT] remainder * @param x [IN] dividend * @param y [IN] Divisor (limb) * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_ERR_DIVISOR_ZERO divisor cannot be 0. */ int32_t BN_DivLimb(BN_BigNum *q, BN_UINT *r, const BN_BigNum *x, const BN_UINT y); /** * @ingroup bn * @brief BigNum Modular addition * @par Description: r = (a + b) mod (mod) * * @param r [OUT] Modulus result * @param a [IN] BigNum * @param b [IN] BigNum * @param mod [IN] mod * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0. */ int32_t BN_ModAdd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum Modular subtraction * @par Description: r = (a - b) mod (mod) * * @param r [OUT] Modulo result * @param a [IN] minuend * @param b [IN] subtrahend * @param mod [IN] mod * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0. */ int32_t BN_ModSub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum Modular multiplication * @par Description: r = (a * b) mod (mod) * * @param r [OUT] Modulus result * @param a [IN] BigNum * @param b [IN] BigNum * @param mod [IN] mod * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0. */ int32_t BN_ModMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum Modular squared * @par Description: r = (a ^ 2) mod (mod) * * @param r [OUT] Modulus result * @param a [IN] BigNum * @param mod [IN] mod * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0. */ int32_t BN_ModSqr( BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *mod, BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum Modular power * @par Description: r = (a ^ e) mod (mod) * * @param r [OUT] Modulus result * @param a [IN] BigNum * @param mod [IN] mod * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0. * @retval CRYPT_BN_ERR_EXP_NO_NEGATIVE exponent cannot be a negative number */ int32_t BN_ModExp(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, const BN_BigNum *m, BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum modulo * @par Description: r = a mod m * * @param r [OUT] Modulus result * @param a [IN] BigNum * @param m [IN] mod * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0. */ int32_t BN_Mod(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum modulo limb * @par Description: r = a mod m * * @param r [OUT] Modulus result * @param a [IN] BigNum * @param m [IN] Modulus (limb) * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_ERR_DIVISOR_ZERO module cannot be 0. */ int32_t BN_ModLimb(BN_UINT *r, const BN_BigNum *a, const BN_UINT m); #ifdef HITLS_CRYPTO_BN_PRIME /** * @ingroup bn * @brief generate BN prime * * @param r [OUT] Generate a prime number. * @param e [OUT] A helper prime to reduce the number of Miller-Rabin primes check. * @param bits [IN] Length of the generated prime number * @param half [IN] Whether to generate a prime number greater than the maximum value of this prime number by 1/2: * Yes: True, No: false * @param opt [IN] Optimizer * @param cb [IN] BigNum callback * @retval CRYPT_SUCCESS The prime number is successfully generated. * @retval CRYPT_NULL_INPUT Invalid null pointer. * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_STACK_FULL The optimizer stack is full. * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_NOR_GEN_PRIME Failed to generate prime numbers. * @retval CRYPT_NO_REGIST_RAND No random number is registered. * @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number. */ int32_t BN_GenPrime(BN_BigNum *r, BN_BigNum *e, uint32_t bits, bool half, BN_Optimizer *opt, BN_CbCtx *cb); /** * @ingroup bn * @brief check prime number * * @param bn [IN] Prime number to be checked * @param checkTimes [IN] the user can set the check times of miller-rabin testing. * if checkTimes == 0, it will use the default detection times of miller-rabin. * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS The check result is a prime number. * @retval CRYPT_BN_NOR_CHECK_PRIME The check result is a non-prime number. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_BN_OPTIMIZER_STACK_FULL The optimizer stack is full. * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_NO_REGIST_RAND No random number is registered. * @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number. */ int32_t BN_PrimeCheck(const BN_BigNum *bn, uint32_t checkTimes, BN_Optimizer *opt, BN_CbCtx *cb); #endif // HITLS_CRYPTO_BN_PRIME #ifdef HITLS_CRYPTO_BN_RAND #define BN_RAND_TOP_NOBIT 0 /* Not set bits */ #define BN_RAND_TOP_ONEBIT 1 /* Set the most significant bit to 1. */ #define BN_RAND_TOP_TWOBIT 2 /* Set the highest two bits to 1 */ #define BN_RAND_BOTTOM_NOBIT 0 /* Not set bits */ #define BN_RAND_BOTTOM_ONEBIT 1 /* Set the least significant bit to 1. */ #define BN_RAND_BOTTOM_TWOBIT 2 /* Set the least significant two bits to 1. */ /** * @ingroup bn * @brief generate random BigNum * * @param r [OUT] Generate a random number. * @param bits [IN] Length of the generated prime number * @param top [IN] Generating the flag indicating whether to set the most significant bit of a random number * @param bottom [IN] Generate the flag indicating whether to set the least significant bit of the random number. * * @retval CRYPT_SUCCESS A random number is generated successfully. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_ERR_RAND_TOP_BOTTOM The top or bottom is invalid during random number generation. * @retval CRYPT_NO_REGIST_RAND No random number is registered. * @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number. * @retval CRYPT_BN_ERR_RAND_BITS_NOT_ENOUGH The bit is too small during random number generation. */ int32_t BN_Rand(BN_BigNum *r, uint32_t bits, uint32_t top, uint32_t bottom); /** * @ingroup bn * @brief generate random BigNum * * @param libCtx [IN] provider libCtx * @param r [OUT] Generate a random number. * @param bits [IN] Length of the generated prime number * @param top [IN] Generating the flag indicating whether to set the most significant bit of a random number * @param bottom [IN] Generate the flag indicating whether to set the least significant bit of the random number. * * @retval CRYPT_SUCCESS A random number is generated successfully. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_ERR_RAND_TOP_BOTTOM The top or bottom is invalid during random number generation. * @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number. * @retval CRYPT_BN_ERR_RAND_BITS_NOT_ENOUGH The bit is too small during random number generation. */ int32_t BN_RandEx(void *libCtx, BN_BigNum *r, uint32_t bits, uint32_t top, uint32_t bottom); /** * @ingroup bn * @brief generate random BigNum * * @param r [OUT] Generate a random number. * @param p [IN] Compare data so that the generated r < p * * @retval CRYPT_SUCCESS A random number is successfully generated. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_NO_REGIST_RAND No random number is registered. * @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number. * @retval CRYPT_BN_ERR_RAND_ZERO Generate a random number smaller than 0. * @retval CRYPT_BN_ERR_RAND_NEGATE Generate a negative random number. */ int32_t BN_RandRange(BN_BigNum *r, const BN_BigNum *p); /** * @ingroup bn * @brief generate random BigNum * * @param libCtx [IN] provider libCtx * @param r [OUT] Generate a random number. * @param p [IN] Compare data so that the generated r < p * * @retval CRYPT_SUCCESS A random number is successfully generated. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_RAND_GEN_FAIL Failed to generate a random number. * @retval CRYPT_BN_ERR_RAND_ZERO Generate a random number smaller than 0. * @retval CRYPT_BN_ERR_RAND_NEGATE Generate a negative random number. */ int32_t BN_RandRangeEx(void *libCtx, BN_BigNum *r, const BN_BigNum *p); #endif /** * @ingroup bn * @brief Binary to BigNum * * @param r [OUT] BigNum * @param bin [IN] Data stream to be converted * @param binLen [IN] Data stream length * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_Bin2Bn(BN_BigNum *r, const uint8_t *bin, uint32_t binLen); /** * @ingroup bn * @brief Convert BigNum to a big-endian binary * * @param a [IN] BigNum * @param bin [IN/OUT] Data stream to be converted -- The input pointer cannot be null. * @param binLen [IN/OUT] Data stream length -- When input, binLen is also the length of the bin buffer. * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_SECUREC_FAIL An error occurred during the copy. */ int32_t BN_Bn2Bin(const BN_BigNum *a, uint8_t *bin, uint32_t *binLen); /** * @ingroup bn * @brief fix size of BigNum * * @param a [IN] BigNum * * @retval void */ void BN_FixSize(BN_BigNum *a); /** * @ingroup bn * @brief * * @param a [IN/OUT] BigNum * @param words [IN] the bn room that the caller wanted. * * @retval CRYPT_SUCCESS * @retval others, see crypt_errno.h */ int32_t BN_Extend(BN_BigNum *a, uint32_t words); /** * @ingroup bn * @brief Convert BigNum to binary to obtain big-endian data with the length of binLen. * The most significant bits are filled with 0. * * @param a [IN] BigNum * @param bin [OUT] Data stream to be converted -- The input pointer cannot be null. * @param binLen [IN] Data stream length -- When input, binLen is also the length of the bin buffer. * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_BN_BUFF_LEN_NOT_ENOUGH The space is insufficient. */ int32_t BN_Bn2BinFixZero(const BN_BigNum *a, uint8_t *bin, uint32_t binLen); #ifdef HITLS_CRYPTO_BN_STR_CONV /** * @ingroup bn * @brief Hexadecimal to a BigNum * * @param r [OUT] BigNum * @param r [IN] Data stream to be converted * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_CONVERT_INPUT_INVALID Invalid string */ int32_t BN_Hex2Bn(BN_BigNum **r, const char *str); /** * @ingroup bn * @brief Convert BigNum to hexadecimal number * * @param a [IN] BigNum * @param char [OUT] Converts a hexadecimal string. * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ char *BN_Bn2Hex(const BN_BigNum *a); /** * @ingroup bn * @brief Decimal to BigNum * * @param r [OUT] BigNum * @param str [IN] A decimal string to be converted * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_CONVERT_INPUT_INVALID Invalid string */ int32_t BN_Dec2Bn(BN_BigNum **r, const char *str); /** * @ingroup bn * @brief Convert BigNum to decimal number * * @param r [IN] BigNum * * @retval A decimal string after conversion or push error. */ char *BN_Bn2Dec(const BN_BigNum *a); #endif #if defined(HITLS_CRYPTO_CURVE_SM2_ASM) || \ ((defined(HITLS_CRYPTO_CURVE_NISTP521) || defined(HITLS_CRYPTO_CURVE_NISTP384_ASM)) && \ defined(HITLS_CRYPTO_NIST_USE_ACCEL)) /** * @ingroup bn * @brief Converting a 64-bit unsigned number array to a BigNum * * @param r [OUT] BigNum * @param array [IN] Array to be converted * @param len [IN] Number of elements in the array * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_U64Array2Bn(BN_BigNum *r, const uint64_t *array, uint32_t len); /** * @ingroup bn * @brief BigNum to 64-bit unsigned number array * * @param a [IN] BigNum * @param array [IN/OUT] Array for storing results -- The input pointer cannot be null. * @param len [IN/OUT] Length of the written array -- Number of writable elements when input * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_SECUREC_FAIL A copy error occurs. */ int32_t BN_Bn2U64Array(const BN_BigNum *a, uint64_t *array, uint32_t *len); #endif /** * @ingroup bn * @brief BigNum optimizer creation * * @param None * * @retval Not NULL Success * @retval NULL failure */ BN_Optimizer *BN_OptimizerCreate(void); /** * @ingroup bn * @brief Destroy the BigNum optimizer. * * @param opt [IN] BigNum optimizer * * @retval none */ void BN_OptimizerDestroy(BN_Optimizer *opt); /** * @ingroup bn * @brief set library context * * @param libCtx [IN] Library context * @param opt [OUT] BigNum optimizer * * @retval none */ void BN_OptimizerSetLibCtx(void *libCtx, BN_Optimizer *opt); /** * @ingroup bn * @brief get library context * * @param opt [In] BigNum optimizer * * @retval library context */ void *BN_OptimizerGetLibCtx(BN_Optimizer *opt); /** * @ingroup bn * @brief BigNum Montgomery context creation and setting * * @param m [IN] Modulus m, which must be positive and odd * * @retval Not NULL Success * @retval NULL failure */ BN_Mont *BN_MontCreate(const BN_BigNum *m); /** * @ingroup bn * @brief BigNum Montgomery modular exponentiation. * Whether to use the constant API depends on the property of the BigNum. * * @param r [OUT] Modular exponentiation result * @param a [IN] base * @param e [IN] Index * @param mont [IN] Montgomery context * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS calculated successfully. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_MONT_BASE_TOO_MAX Montgomery modulus exponentiation base is too large * @retval CRYPT_BN_OPTIMIZER_STACK_FULL The optimizer stack is full. * @retval CRYPT_BN_ERR_EXP_NO_NEGATE exponent cannot be a negative number */ int32_t BN_MontExp(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, BN_Mont *mont, BN_Optimizer *opt); /** * @ingroup bn * @brief Constant time BigNum Montgomery modular exponentiation * * @param r [OUT] Modular exponentiation result * @param a [IN] base * @param e [IN] exponent * @param mont [IN] Montgomery context * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS calculated successfully. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_BN_OPTIMIZER_GET_FAIL Failed to apply for space from the optimizer. * @retval CRYPT_BN_MONT_BASE_TOO_MAX Montgomery Modular exponentiation base is too large * @retval CRYPT_BN_OPTIMIZER_STACK_FULL The optimizer stack is full. * @retval CRYPT_BN_ERR_EXP_NO_NEGATE exponent cannot be a negative number */ int32_t BN_MontExpConsttime(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, BN_Mont *mont, BN_Optimizer *opt); /** * @ingroup mont * @brief BigNum Montgomery Context Destruction * * @param mont [IN] BigNum Montgomery context * * @retval none */ void BN_MontDestroy(BN_Mont *mont); /** * @ingroup bn * @brief shift a BigNum to the right * * @param r [OUT] Shift result * @param a [IN] Source data * @param n [IN] Shift bit num * * @retval CRYPT_SUCCESS succeeded. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_SECUREC_FAIL The security function returns an error. */ int32_t BN_Rshift(BN_BigNum *r, const BN_BigNum *a, uint32_t n); /** * @ingroup bn * @brief shift a BigNum to the left * * @param r [OUT] Shift result * @param a [IN] Source data * @param n [IN] Shift bit num * * @retval CRYPT_SUCCESS succeeded. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_Lshift(BN_BigNum *r, const BN_BigNum *a, uint32_t n); #ifdef HITLS_CRYPTO_DSA int32_t BN_MontExpMul(BN_BigNum *r, const BN_BigNum *a1, const BN_BigNum *e1, const BN_BigNum *a2, const BN_BigNum *e2, BN_Mont *mont, BN_Optimizer *opt); #endif #ifdef HITLS_CRYPTO_ECC /** * @ingroup bn * @brief Mould opening root * @par Description: r^2 = a mod p; p-1=q*2^s. * In the current implementation s=1 will take a special branch, and the calculation speed is faster. * The fast calculation branch with s=2 is not implemented currently. * Currently, the s corresponding to the mod p of the EC nist224, 256, 384, and 521 is 96, 1, 1, and 1 respectively * The branch with s=2 is not used. * The root number is provided for the EC. * @param r [OUT] Modular root result * @param a [IN] Source data, 0 <= a <= p-1 * @param p [IN] module, odd prime number * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS calculated successfully. * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_BN_ERR_SQRT_PARA The input parameter is incorrect. * @retval CRYPT_BN_ERR_LEGENDE_DATA: * Failed to find the specific number of the Legendre sign (z|p) of z to p equal to -1 when calculating the square root. * @retval CRYPT_BN_ERR_NO_SQUARE_ROOT The square root cannot be found. */ int32_t BN_ModSqrt(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *p, BN_Optimizer *opt); #endif #if defined(HITLS_CRYPTO_CURVE_SM2_ASM) || (defined(HITLS_CRYPTO_CURVE_NISTP256_ASM) && \ defined(HITLS_CRYPTO_NIST_USE_ACCEL)) /** * @ingroup bn * @brief BigNum to BN_UINT array * * @param src [IN] BigNum * @param dst [OUT] BN_UINT array for receiving the conversion result * @param size [IN] Length of the dst buffer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_SECUREC_FAIL The security function returns an error. */ int32_t BN_BN2Array(const BN_BigNum *src, BN_UINT *dst, uint32_t size); /** * @ingroup bn * @brief BN_UINT array to BigNum * * @param dst [OUT] BigNum * @param src [IN] BN_UINT array to be converted * @param size [IN] Length of the src buffer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer. * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_Array2BN(BN_BigNum *dst, const BN_UINT *src, const uint32_t size); #endif #ifdef HITLS_CRYPTO_ECC /** * @ingroup bn * @brief Copy with the mask. When the mask is set to (0), r = a; when the mask is set to (-1), r = b. * * @attention Data r, a, and b must have the same room. * * @param r [OUT] Output result * @param a [IN] Source data * @param b [IN] Source data * @param mask [IN] Mask data * * @retval CRYPT_SUCCESS succeeded. * @retval For details about other errors, see crypt_errno.h. */ int32_t BN_CopyWithMask(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_UINT mask); /** * @ingroup bn * @brief Calculate r = (a - b) % mod * * @attention This API is invoked in the area where ECC point computing is intensive and is performance-sensitive. * The user must ensure that a < mod, b < mod * In addition, a->room and b->room are not less than mod->size. * All data are non-negative * The mod information cannot be 0. * Otherwise, the interface may not be functional. * * @param r [OUT] Output result * @param a [IN] Source data * @param b [IN] Source data * @param mod [IN] Modular data * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS succeeded. * @retval For details about other errors, see crypt_errno.h. */ int32_t BN_ModSubQuick(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, const BN_Optimizer *opt); /** * @ingroup bn * @brief Calculate r = (a + b) % mod * * @attention This API is invoked in the area where ECC point computing is intensive and is performance-sensitive. * The user must ensure that a < mod, b < mod * In addition, a->room and b->room are not less than mod->size. * All data are non-negative * The mod information cannot be 0. * Otherwise, the interface may not be functional. * * @param r [OUT] Output result * @param a [IN] Source data * @param b [IN] Source data * @param mod [IN] Modular data * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS succeeded. * @retval For details about other errors, see crypt_errno.h. */ int32_t BN_ModAddQuick(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, const BN_Optimizer *opt); /** * @ingroup bn * @brief Calculate r = (a * b) % mod * * @attention This API is invoked in the area where ECC point computing is intensive and is performance sensitive. * The user must ensure that a < mod, b < mod * In addition, a->room and b->room are not less than mod->size. * All data are non-negative * The mod information can only be the parameter p of the curve of nistP224, nistP256, nistP384, and nistP521. * Otherwise, the interface may not be functional. * * @param r [OUT] Output result * @param a [IN] Source data * @param b [IN] Source data * @param mod [IN] Modular data * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS succeeded. * @retval For other errors, see crypt_errno.h. */ int32_t BN_ModNistEccMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *mod, BN_Optimizer *opt); /** * @ingroup bn * @brief Calculate r = (a ^ 2) % mod * * @attention This API is invoked in the area where ECC point computing is intensive and is performance sensitive. * The user must guarantee a < mod * In addition, a->room are not less than mod->size. * All data are non-negative * The mod information can only be the parameter p of the curve of nistP224, nistP256, nistP384, and nistP521. * Otherwise, the interface may not be functional. * * @param r [OUT] Output result * @param a [IN] Source data * @param mod [IN] Modular data * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS succeeded. * @retval For details about other errors, see crypt_errno.h. */ int32_t BN_ModNistEccSqr(BN_BigNum *r, const BN_BigNum *a, void *mod, BN_Optimizer *opt); #endif #ifdef HITLS_CRYPTO_CURVE_SM2 /** * @ingroup ecc * @brief sm2 curve: calculate r = (a*b)% mod * * @attention This API is invoked in the area where ECC point computing is intensive and is performance sensitive. * The user must guarantee a < mod、b < mod * In addition, a->room and b->room are not less than mod->size. * All data are non-negative * The mod information can only be the parameter p of the curve of sm2. * Otherwise, the interface may not be functional. * * @param r [OUT] Output result * @param a [IN] Source data * @param b [IN] Source data * @param mod [IN] Modular data * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS succeeded. * @retval For details about other errors, see crypt_errno.h. */ int32_t BN_ModSm2EccMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *data, BN_Optimizer *opt); /** * @ingroup ecc * @brief sm2 curve: calculate r = (a ^ 2) % mod * * @attention This API is invoked in the area where ECC point computing is intensive and is performance sensitive. * The user must guarantee a < mod * In addition, a->room are not less than mod->size. * All data are non-negative * The mod information can only be the parameter p of the curve of sm2. * Otherwise, the interface may not be functional. * * @param r [OUT] Output result * @param a [IN] Source data * @param mod [IN] Modular data * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS succeeded. * @retval For details about other errors, see crypt_errno.h. */ int32_t BN_ModSm2EccSqr(BN_BigNum *r, const BN_BigNum *a, void *data, BN_Optimizer *opt); #endif #ifdef HITLS_CRYPTO_BN_PRIME_RFC3526 /** * @ingroup bn * @brief Return the corresponding length of modulo exponent of the BigNum. * * @param r [OUT] Output result * @param len [IN] Length * * @retval Not NULL Success * @retval NULL failure */ BN_BigNum *BN_GetRfc3526Prime(BN_BigNum *r, uint32_t len); #endif /** * @ingroup bn * @brief Return the number of security bits provided by a specific algorithm and specific key size. * * @param [OUT] Output the result. * @param pubLen [IN] Size of the public key * @param prvLen [IN] Size of the private key. * * @retval Number of security bits */ int32_t BN_SecBits(int32_t pubLen, int32_t prvLen); #if defined(HITLS_CRYPTO_RSA) /** * @ingroup bn * @brief Montgomery modulus calculation process, need a < m, b < m, All is positive numbers, The large number optimizer must be enabled before this function is used. * * @param r [OUT] Output results * @param a [IN] Input data * @param b [IN] Input data * @param mont [IN] Montgomery context * @param opt [IN] Large number optimizer * * @retval CRYPT_SUCCESS * @retval For details about other errors, see crypt_errno.h. */ int32_t MontMulCore(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Mont *mont, BN_Optimizer *opt); #endif // HITLS_CRYPTO_RSA #if defined(HITLS_CRYPTO_BN_PRIME) /** * @ingroup bn * @brief Montgomery modulus calculation process, need a < m, unlimited symbols. * * @param r [OUT] Output results * @param a [IN] Input data * @param mont [IN] Montgomery context * @param opt [IN] Large number optimizer * * @retval CRYPT_SUCCESS * @retval For details about other errors, see crypt_errno.h. */ int32_t MontSqrCore(BN_BigNum *r, const BN_BigNum *a, BN_Mont *mont, BN_Optimizer *opt); #endif // HITLS_CRYPTO_BN_PRIME /** * @ingroup bn * @brief Enabling the big data optimizer * * @param opt [IN] Large number optimizer * * @retval CRYPT_SUCCESS * @retval For details about other errors, see crypt_errno.h. */ int32_t OptimizerStart(BN_Optimizer *opt); /** * @ingroup bn * @brief Disabling the Large Number Optimizer * * @param opt [IN] Large number optimizer * * @retval CRYPT_SUCCESS * @retval For details about other errors, see crypt_errno.h. */ void OptimizerEnd(BN_Optimizer *opt); /** * @ingroup bn * @brief Get Bn from the large number optimizer. * * @param opt [IN] Large number optimizer * @param room [IN] Length of the big number. * * @retval BN_BigNum if success * @retval NULL if failed */ BN_BigNum *OptimizerGetBn(BN_Optimizer *opt, uint32_t room); #if defined(HITLS_CRYPTO_PAILLIER) || defined(HITLS_CRYPTO_RSA_CHECK) /** * @ingroup bn * @brief BigNum Calculate the least common multiple * @par Description: lcm(a, b) (a, b!=0) * * @param r [OUT] least common multiple * @param a [IN] BigNum * @param b [IN] BigNum * @param opt [IN] Optimizer * * @retval CRYPT_SUCCESS * @retval CRYPT_NULL_INPUT Invalid null pointer * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure */ int32_t BN_Lcm(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt); #endif // HITLS_CRYPTO_PAILLIER || HITLS_CRYPTO_RSA_CHECK /** * @ingroup bn * @brief Enabling the big data optimizer * * @param opt [IN] Large number optimizer * * @retval CRYPT_SUCCESS * @retval For details about other errors, see crypt_errno.h. */ int32_t OptimizerStart(BN_Optimizer *opt); /** * @ingroup bn * @brief Disabling the Large Number Optimizer * * @param opt [IN] Large number optimizer * * @retval CRYPT_SUCCESS * @retval For details about other errors, see crypt_errno.h. */ void OptimizerEnd(BN_Optimizer *opt); /** * @ingroup bn * @brief Get Bn from the large number optimizer. * * @param opt [IN] Large number optimizer * @param room [IN] Length of the big number. * * @retval BN_BigNum if success * @retval NULL if failed */ BN_BigNum *OptimizerGetBn(BN_Optimizer *opt, uint32_t room); #ifdef HITLS_CRYPTO_CURVE_MONT /** * a, b is mont form. * r = a * b */ int32_t BN_EcPrimeMontMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *data, BN_Optimizer *opt); /** * a is mont form. * r = a ^ 2 */ int32_t BN_EcPrimeMontSqr(BN_BigNum *r, const BN_BigNum *a, void *mont, BN_Optimizer *opt); /** * r = Reduce(r * RR) */ int32_t BnMontEnc(BN_BigNum *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime); /** * r = Reduce(r) */ void BnMontDec(BN_BigNum *r, BN_Mont *mont); /** * This interface is a constant time. * if mask = BN_MASK. swap a and b. * if mask = 0, a and b remain as they are. */ int32_t BN_SwapWithMask(BN_BigNum *a, BN_BigNum *b, BN_UINT mask); #endif // HITLS_CRYPTO_CURVE_MONT #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_BN */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/include/crypt_bn.h
C
unknown
48,680
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include "bn_bincal.h" #ifndef HITLS_SIXTY_FOUR_BITS #error Bn binical x8664 optimizer must open BN-64. #endif // r = a + b, len = n, return carry BN_UINT BinAdd(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n) { if (n == 0) { return 0; } BN_UINT ret = 0; BN_UINT times = n >> 2; BN_UINT rem = n & 3; asm volatile( ".align 3 \n" " mov %0, #1 \n" " adcs %0, xzr, %0 \n" // clear C flags " mov %0, #0 \n" " cbz %1, 3f \n" "4: add x4, %3, %0 \n" " add x5, %4, %0 \n" " add x6, %5, %0 \n" " ldp x7, x8, [x5] \n" " ldp x9, x10, [x5,#16] \n" " ldp x11, x12, [x6] \n" " ldp x13, x14, [x6,#16] \n" " adcs x7, x7, x11 \n" " adcs x8, x8, x12 \n" " adcs x9, x9, x13 \n" " adcs x10, x10, x14 \n" " stp x7, x8, [x4] \n" " stp x9, x10, [x4, #16] \n" " sub %1, %1, #0x1 \n" " add %0, %0, #0x20 \n" " cbnz %1, 4b \n" "3: cbz %2, 2f \n" // times <= 0, jump to single cycle "1: ldr x7, [%4, %0] \n" " ldr x8, [%5, %0] \n" " adcs x7, x7, x8 \n" " str x7, [%3, %0] \n" " sub %2, %2, #0x1 \n" " add %0, %0, #0x8 \n" " cbnz %2, 1b \n" "2: mov %0, #0 \n" " adcs %0, xzr, %0 \n" :"+&r" (ret), "+r"(times), "+r"(rem) :"r"(r), "r"(a), "r"(b) :"x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "cc", "memory"); return ret & 1; } // r = a - b, len = n, return carry BN_UINT BinSub(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n) { if (n == 0) { return 0; } BN_UINT ret = 0; BN_UINT rem = n & 3; BN_UINT times = n >> 2; asm volatile( ".align 3 \n" " mov %0, #1 \n" " sbcs %0, %0, xzr \n" // clear C flags " mov %0, #0 \n" " cbz %1, 2f \n" "4: add x4, %3, %0 \n" " add x5, %4, %0 \n" " add x6, %5, %0 \n" " ldp x7, x8, [x5] \n" " ldp x9, x10, [x5,#16] \n" " ldp x11, x12, [x6] \n" " ldp x13, x14, [x6,#16] \n" " sbcs x7, x7, x11 \n" " sbcs x8, x8, x12 \n" " sbcs x9, x9, x13 \n" " sbcs x10, x10, x14 \n" " stp x7, x8, [x4] \n" " stp x9, x10, [x4, #16] \n" " sub %1, %1, #0x1 \n" " add %0, %0, #0x20 \n" " cbnz %1, 4b \n" "2: cbz %2, 3f \n" // times <= 0, jump to single cycle "1: ldr x7, [%4, %0] \n" " ldr x8, [%5, %0] \n" " sbcs x7, x7, x8 \n" " str x7, [%3, %0] \n" " sub %2, %2, #0x1 \n" " add %0, %0, #0x8 \n" " cbnz %2, 1b \n" "3: mov %0,#0 \n" " sbcs %0,xzr,%0 \n" :"+&r" (ret), "+r"(times), "+r"(rem) :"r"(r), "r"(a), "r"(b) :"x4", "x5", "x6", "x7", "x8", "x9", "x10", "x11", "x12", "x13", "x14", "cc", "memory"); return ret & 1; } // r = r - a * m, return the carry; BN_UINT BinSubMul(BN_UINT *r, const BN_UINT *a, BN_UINT aSize, BN_UINT m) { BN_UINT borrow = 0; BN_UINT i = 0; asm volatile( ".align 3 \n" "2: ldr x4, [%3, %1] \n" // x4 = r[i] " ldr x5, [%4, %1] \n" // x5 = r[i] " mul x7, x5, %5 \n" // x7 = al " umulh x6, x5, %5 \n" // x6 = ah " adds x7, %0, x7 \n" // x7 = borrow + al " adcs %0, x6, xzr \n" // borrow = ah + H(borrow + al) " cmp x7, x4 \n" // if r[i] > borrow + al, dont needs carry " beq 1f \n" " adc %0, %0, xzr \n" "1: sub x4, x4, x7 \n" " str x4, [%3, %1] \n" " sub %2, %2, #0x1 \n" " add %1, %1, #0x8 \n" " cbnz %2, 2b \n" :"+&r" (borrow), "+r"(i), "+r"(aSize) :"r"(r), "r"(a), "r"(m) :"x4", "x5", "x6", "x7", "cc", "memory"); return borrow; } /* Obtains the number of 0s in the first x most significant bits of data. */ uint32_t GetZeroBitsUint(BN_UINT x) { BN_UINT count; asm ("clz %0, %1" : "=r" (count) : "r" (x)); return (uint32_t)count; } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/armv8_bn_bincal.c
C
unknown
7,049
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* * Description: Big number Montgomery modular multiplication in armv8 implementation, MontMul_Asm * Ref: Montgomery Multiplication * Process: To cal A * B mod n, we can convert to mont form, and cal A*B*R^(-1). * Detail: * intput:A = (An-1,...,A1,A0)b, B = (Bn-1,...,B1,B0)b, n, n' * output:A*B*R^(-1) * tmp = (tn,tn-1,...,t1,t0)b, initialize to 0 * for i: 0 -> (n-1) * ui = (t0 + Ai*B0)m' mod b * t = (t + Ai*B + ui * m) / b * if t >= m * t -= m * return t; * * Deal process: * i. size % 8 == 0 & a == b --> Sqr8x --> complete multiplication * --> size == 8, goto single reduce step * --> size >= 8, goto loop reduce process * ii. size % 4 == 0 --> Mul4x * --> size == 4, goto single step * --> size >= 4, goto loop process * iii. Ordinary --> Mul1x * --> size == 2, goto single step * --> size >= 2, goto loop process * */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include "crypt_arm.h" .arch armv8-a+crypto .file "bn_mont_armv8.S" .text .global MontMul_Asm .type MontMul_Asm, %function .align 5 MontMul_Asm: AARCH64_PACIASP tst x5, #7 b.eq MontSqr8 tst x5, #3 b.eq MontMul4 stp x29, x30, [sp, #-64]! mov x29, sp stp x23, x24, [sp, #16] stp x21, x22, [sp, #32] stp x19, x20, [sp, #48] sub x21, x5 , #2 // j = size-2 cbnz x21,.LMul1xBegin // if size == 2, goto single step ldp x15, x16, [x1] // a[0], a[1] ldp x19, x20, [x2] // b[0], b[1] ldp x9, x10, [x3] // n[0], n[1] mul x23 , x15 , x19 // x23 = lo(a[0] * b[0]) umulh x24 , x15 , x19 // x24 = hi(a[0] * b[0]) mul x6, x16 , x19 // x6 = lo(a[1] * b[0]) umulh x7, x16 , x19 // x7 = hi(a[1] * b[0]) mul x11, x23 , x4 // x11 = lo(t[0] * k0) umulh x19, x9, x11 // x19 = hi(n[0] * t[0]*k0) mul x12, x10, x11 // x12 = lo(n[1] * t[0]*k0) umulh x13, x10, x11 // x13 = hi(n[1] * t[0]*k0) // we knowns a*b + n'n = 0 (mod R) // so lo(a[0] * b[0]) + lo(n[0] * t[0]*k0) = 0 (mod R) // if lo(a[0] * b[0]) > 0, then 'lo(a[0] * b[0]) + lo(n[0] * t[0]*k0)' would overflow, // else if lo(a[0] * b[0]) == 0, then lo(n[0] * t[0]*k0) == 0 cmp x23, #1 adc x19, x19, xzr adds x23 , x6, x24 // x23 = lo(a[1] * b[0]) + hi(a[0] * b[0]) adc x24 , x7, xzr // x24 = hi(a[1] * b[0]) + CF adds x8, x12, x19 // x8 = lo(n[1] * t[0]*k0) + hi(n[0] * t[0]*k0) adc x19, x13, xzr // x19 = hi(n[1] * t[0]*k0) + CF adds x21, x8, x23 // x21 = lo(n[1] * t[0]*k0) + hi(n[0] * t[0]*k0) adcs x22, x19, x24 adc x23, xzr, xzr // x23 = CF mul x14 , x15 , x20 // a[0] * b[1] umulh x15 , x15 , x20 mul x6, x16 , x20 // a[1] * b[1] umulh x7, x16 , x20 adds x14 , x14 , x21 adc x15 , x15 , xzr mul x11, x14 , x4 // t[0] * k0 umulh x20, x9, x11 mul x12, x10, x11 // n[1] * t[0]*k0 umulh x13, x10, x11 cmp x14 , #1 // Check whether the low location is carried. adc x20, x20, xzr adds x14 , x6, x15 adc x15 , x7, xzr adds x21, x12, x20 adcs x20, x13, x23 adc x23, xzr, xzr adds x14 , x14 , x22 adc x15 , x15 , xzr adds x21, x21, x14 adcs x20, x20, x15 adc x23, x23, xzr // x23 += CF subs x12 , x21, x9 sbcs x13, x20, x10 sbcs x23, x23, xzr // update CF csel x10, x21, x12, lo csel x11, x20, x13, lo stp x10, x11, [x0] b .LMul1xEnd .LMul1xBegin: mov x24, x5 // the outermost pointers of our loop lsl x5 , x5 , #3 sub x22, sp , x5 // The space size needs to be applied for. and x22, x22, #-16 // For 4-byte alignment mov sp , x22 // Apply for Space. mov x6, x5 mov x23, xzr .LMul1xInitstack: sub x6, x6, #8 str xzr, [x22], #8 cbnz x6, .LMul1xInitstack mov x22, sp .LMul1xLoopProces: sub x24, x24, #1 sub x21, x5 , #16 // j = size-2 // Begin mulx ldr x17, [x2], #8 // b[i] ldp x15, x16, [x1], #16 // a[0], a[1] ldp x9, x10, [x3], #16 // n[0], n[1] ldr x19, [x22] // The sp val is 0 during initialization. mul x14 , x15 , x17 // a[0] * b[i] umulh x15 , x15 , x17 mul x6, x16 , x17 // a[1] * b[i] umulh x7, x16 , x17 adds x14 , x14 , x19 adc x15 , x15 , xzr mul x11, x14 , x4 umulh x9, x9, x11 mul x12, x10, x11 // n[1] * t[0]*k0 cmp x14, #1 umulh x13, x10, x11 .LMul1xPrepare: sub x21, x21, #8 // index -= 1 ldr x16, [x1], #8 // a[i] ldr x10, [x3], #8 // n[i] ldr x19, [x22, #8] // t[j] adc x9, x9, xzr adds x14 , x6, x15 adc x15 , x7, xzr adds x8, x12, x9 adc x9, x13, xzr mul x6, x16, x17 // a[j] * b[i] adds x14, x14 , x19 umulh x7, x16 , x17 adc x15, x15 , xzr mul x12, x10, x11 // n[j] * t[0]*k0 adds x8, x8, x14 umulh x13, x10, x11 str x8, [x22], #8 // t[j-1] cbnz x21, .LMul1xPrepare .LMul1xReduce: ldr x19, [x22, #8] adc x9, x9, xzr adds x14 , x6, x15 adc x15 , x7, xzr adds x8, x12, x9 adcs x9, x13, x23 adc x23, xzr, xzr adds x14 , x14 , x19 adc x15 , x15 , xzr adds x8, x8, x14 adcs x9, x9, x15 adc x23, x23, xzr // x23 += CF, carry of the most significant bit. stp x8, x9, [x22], #8 mov x22, sp sub x1 , x1 , x5 subs x3 , x3 , x5 // x3 = &n[0] cbnz x24, .LMul1xLoopProces mov x1, x0 mov x21, x5 // get index .LMul1xSubMod: ldr x19, [x22], #8 ldr x10, [x3], #8 sub x21, x21, #8 // j-- sbcs x16, x19, x10 // t[j] - n[j] str x16, [x1], #8 // r[j] = t[j] - n[j] cbnz x21,.LMul1xSubMod sbcs x23, x23, xzr // x23 -= CF mov x22, sp .LMul1xCopy: ldr x19, [x22], #8 ldr x16, [x0] sub x5, x5, #8 // size-- csel x10, x19, x16, lo str x10, [x0], #8 cbnz x5 , .LMul1xCopy .LMul1xEnd: ldp x23, x24, [x29, #16] mov sp , x29 ldp x21, x22, [x29, #32] ldp x19, x20, [x29, #48] ldr x29, [sp], #64 AARCH64_AUTIASP ret .size MontMul_Asm, .-MontMul_Asm .type MontSqr8, %function MontSqr8: AARCH64_PACIASP cmp x1, x2 b.ne MontMul4 stp x29, x30, [sp, #-128]! // sp = sp - 128(Modify the SP and then save the SP.), [sp] = x29, [sp + 8] = x30, // !Indicates modification sp mov x29, sp // x29 = sp, The sp here has been reduced by 128. stp x27, x28, [sp, #16] stp x25, x26, [sp, #32] stp x23, x24, [sp, #48] stp x21, x22, [sp, #64] stp x19, x20, [sp, #80] stp x0 , x3 , [sp, #96] // offload r and n, Push the pointers of r and n into the stack. str x4 , [sp, #112] // store n0 lsl x5, x5, #3 // x5 = x5 * 8, Converts size to bytes. sub x2, sp, x5, lsl#1 // x2 = sp - 2*x5*8, x5 = size, x2 points to the start address of a 2*size memory. *8 is to convert to bytes mov sp, x2 // Alloca, Apply for Space. mov x19, x5 // The lowest eight data blocks do not need to be cleared. eor v0.16b,v0.16b,v0.16b eor v1.16b,v1.16b,v1.16b .LSqr8xStackInit: sub x19, x19, #8*8 // Offset 64, cyclic increment. st1 {v0.2d, v1.2d}, [x2], #32 st1 {v0.2d, v1.2d}, [x2], #32 st1 {v0.2d, v1.2d}, [x2], #32 st1 {v0.2d, v1.2d}, [x2], #32 cbnz x19, .LSqr8xStackInit // When x19 = 0, the loop exits. mov x2 , sp // After clear to zero, assign sp back to x2. ldp x27, x28, [x2] ldp x25, x26, [x2] ldp x23, x24, [x2] ldp x21, x22, [x2] add x3 , x1 , x5 // x3 = x1 + bytes(size * 8) ldp x14 , x15 , [x1], #16 // x14 = a[0], x15 = a[1] ldp x16 , x17 , [x1], #16 // x16 = a[2], x17 = a[3] ldp x6, x7, [x1], #16 // x6 = a[4], x7 = a[5] ldp x8, x9, [x1], #16 // x8 = a[6], x9 = a[7] .LSqr8xLoopMul: mul x10, x14, x15 // a[0] * a[1~4] mul x11, x14, x16 // keep cache hit ratio of x6 mul x12, x14, x17 mul x13, x14, x6 adds x28, x28, x10 // x27~x22 = t[0~7], x28 = t[1] = lo(a[0]*a[1]), adds is used to set CF to 0. adcs x25, x25, x11 // x10~x17 Used to save subsequent calculation results mul x10, x14 , x7 // lo(a[0] * a[5~7]), keep cache hit ratio of x14, the same below mul x11, x14 , x8 adcs x26, x26, x12 adcs x23, x23, x13 // t[4] = lo(a[0] * a[4]) adcs x24, x24, x10 // x24~x22 = t[5~7] mul x12, x14 , x9 // lo(a[0] * a[7]) stp x27, x28, [x2], #8*2 // t[0] = a[0]^2, Because the square term is not calculated temporarily, // so t[0] = 0, t[1] = a[0] * a[1] + carry adcs x21, x21, x11 adcs x22, x22, x12 // t[7] += lo(a[0] * a[7]), Carrying has to be given t[8] adc x27, xzr, xzr // x27 = CF ( Set by t[7] += lo(a[0] * a[7]) ), umulh x13, x14 , x15 // hi(a[0] * a[1~4]), Use x17 to keep the cache hit umulh x10, x14 , x16 umulh x11, x14 , x17 umulh x12, x14 , x6 // In the new round, the first calculation does not need to be carried, but the CF bit needs to be modified. adds x25, x25, x13 // t[2] += hi(a[0] * a[1]) adcs x26, x26, x10 adcs x23, x23, x11 adcs x24, x24, x12 // t[5] += hi(a[0] * a[4]) umulh x13, x14 , x7 // hi(a[0] * a[5~7]) umulh x10, x14 , x8 umulh x11, x14 , x9 //----- lo(a[1] * a[2~4]) ------ adcs x21, x21, x13 // t[6] += hi(a[0] * a[5]) adcs x22, x22, x10 // t[7] += hi(a[0] * a[6]) adc x27, x27, x11 // t[8] += hi(a[0] * a[7]) mul x12, x15, x16 // lo(a[1] * a[2]) mul x13, x15, x17 mul x10, x15, x6 //----- lo(a[1] * a[5~7]) ------ adds x26, x26, x12 // t[3] += lo(a[1] * a[2]), The first calculation of this round // does not take into account the previous carry, and the CF is not modified in line 118. adcs x23, x23, x13 // t[4] += lo(a[1] * a[3]) adcs x24, x24, x10 // t[5] += lo(a[1] * a[4]) mul x11, x15 , x7 mul x12, x15 , x8 mul x13, x15 , x9 //----- hi(a[1] * a[2~5]) ------ adcs x21, x21, x11 // t[6] += lo(a[1] * a[5]) adcs x22, x22, x12 // t[7] += lo(a[1] * a[6]) adcs x27, x27, x13 // t[8] += lo(a[1] * a[7]) umulh x10, x15, x16 // hi(a[1] * a[2]) umulh x11, x15, x17 umulh x12, x15, x6 umulh x13, x15, x7 stp x25, x26, [x2], #8*2 // t[2] and t[3] are calculated and stored in the memory. // x25 and x22 are used to store t[10] and t[11]. adc x28, xzr, xzr // t[9] = CF ( Set by t[8] += lo(a[1] * a[7]) ) //In the new round, the first calculation does not need to be carried, but the CF bit needs to be modified. //----- hi(a[1] * a[6~7]) ------ adds x23, x23, x10 // t[4] += hi(a[1] * a[2]) adcs x24, x24, x11 // t[5] += hi(a[1] * a[3]) adcs x21, x21, x12 // t[6] += hi(a[1] * a[4]) umulh x10, x15 , x8 // hi(a[1] * a[6]) umulh x11, x15 , x9 // hi(a[1] * a[7]) //----- lo(a[2] * a[3~7]) ------ adcs x22, x22, x13 // t[7] += hi(a[1] * a[5]) adcs x27, x27, x10 // t[8] += hi(a[1] * a[6]) adc x28, x28, x11 // t[9] += hi(a[1] * a[7]), Here, only the carry of the previous round mul x12, x16, x17 // lo(a[2] * a[3]) mul x13, x16, x6 mul x10, x16, x7 // of calculation is retained before x20 calculation. Add x15 to the carry. mul x11, x16 , x8 adds x24, x24, x12 // t[5] += lo(a[2] * a[3]), For the first calculation of this round, // the previous carry is not considered. mul x12, x16 , x9 adcs x21, x21, x13 // t[6] += lo(a[2] * a[4]) //----- hi(a[2] * a[3~7]) ------ adcs x22, x22, x10 // t[7] += lo(a[2] * a[5]) umulh x13, x16, x17 // hi(a[2] * a[3]) umulh x10, x16, x6 adcs x27, x27, x11 // t[8] += lo(a[2] * a[6]) adcs x28, x28, x12 // t[9] += lo(a[2] * a[7]) umulh x11, x16, x7 umulh x12, x16, x8 stp x23, x24, [x2], #8*2 // After t[4] and t[5] are calculated, they are stored in the memory. // x23 and x24 are used to store t[12] and t[13]. adc x25, xzr, xzr // t[10] = CF ( Set by t[9] += lo(a[2] * a[7]) ) // In the new round, the first calculation does not need to be carried, but the CF bit needs to be modified. adds x21, x21, x13 // t[6] += hi(a[2] * a[3]) adcs x22, x22, x10 // t[7] += hi(a[2] * a[4]) umulh x13, x16, x9 //----- lo(a[3] * a[4~7]) ------ adcs x27, x27, x11 // t[8] += hi(a[2] * a[5]) adcs x28, x28, x12 // t[9] += hi(a[2] * a[6]) adc x25, x25, x13 // t[10] += hi(a[2] * a[7]) mul x10, x17, x6 mul x11, x17, x7 mul x12, x17, x8 mul x13, x17, x9 //----- hi(a[3] * a[4~7]) ------ adds x22, x22, x10 // t[7] += lo(a[3] * a[4]) adcs x27, x27, x11 // t[8] += lo(a[3] * a[5]) adcs x28, x28, x12 // t[9] += lo(a[3] * a[6]) adcs x25, x25, x13 // t[10] += lo(a[3] * a[7]) umulh x10, x17, x6 umulh x11, x17, x7 umulh x12, x17, x8 umulh x13, x17, x9 stp x21, x22, [x2], #8*2 // t[6] and t[7] are calculated and stored in the memory. // x21 and x26 are used to store t[14] and t[15]. adc x26, xzr, xzr // t[11] = CF ( Set by t[10] += lo(a[3] * a[7]) ) // In the new round, the first calculation does not need to be carried, but the CF bit needs to be modified. adds x27, x27, x10 // t[8] += hi(a[3] * a[4]) //----- lo(a[4] * a[5~7]) ------ adcs x28, x28, x11 // t[9] += hi(a[3] * a[5]) adcs x25, x25, x12 // t[10] += hi(a[3] * a[6]) adc x26, x26, x13 // t[11] += hi(a[3] * a[7]) mul x10, x6, x7 mul x11, x6, x8 mul x12, x6, x9 //----- hi(a[4] * a[5~7]) ------ adds x28, x28, x10 // t[9] += lo(a[4] * a[5]) adcs x25, x25, x11 // t[10] += lo(a[4] * a[6]) adcs x26, x26, x12 // t[11] += lo(a[4] * a[7]) umulh x13, x6, x7 umulh x10, x6, x8 umulh x11, x6, x9 //----- lo(a[5] * a[6~7]) ------ mul x12, x7, x8 // This is actually a new round, but only t[0-7] can be calculated in each cycle, // and t[8-15] retains the intermediate calculation result. adc x23, xzr, xzr // t[12] = CF( Set by t[11] += lo(a[4] * a[7]) ) adds x25, x25, x13 // t[10] += hi(a[4] * a[5]) adcs x26, x26, x10 // t[11] += hi(a[4] * a[6]) mul x13, x7, x9 //----- hi(a[5] * a[6~7]) ------ adc x23, x23, x11 // t[12] += hi(a[4] * a[7]) umulh x10, x7, x8 umulh x11, x7, x9 adds x26, x26, x12 // t[11] += lo(a[5] * a[6]) //----- lo(a[6] * a[7]) ------ adcs x23, x23, x13 // t[12] += lo(a[5] * a[7]) mul x12, x8, x9 //----- hi(a[6] * a[7]) ------ adc x24, xzr, xzr // t[13] = CF ( Set by t[12] += lo(a[5] * a[7]) ), umulh x13, x8, x9 // This operation is required when a new umulh is added. adds x23, x23, x10 // t[12] += hi(a[5] * a[6]) adc x24, x24, x11 // t[13] += hi(a[5] * a[7]) sub x19, x3, x1 // x3 = &a[size], x1 = &a[8], x19 = (size - 8) * 8 adds x24, x24, x12 // t[13] += lo(a[6] * a[7]) adc x21, xzr, xzr // t[14] = CF ( set by t[13] += lo(a[6] * a[7]) ) add x21, x21, x13 // t[14] += hi(a[6] * a[7]), There must be no carry in the last step. cbz x19, .LSqr8xLoopMulEnd mov x0, x1 // x0 = &a[8] mov x22, xzr //######################################## //# a[0~7] * a[8~15] # //######################################## .LSqr8xHighMulBegian: mov x19, #-8*8 // Loop range. x0 can retrieve a[0–7] based on this offset. ldp x14 , x15 , [x2, #8*0] // x14 = t[8] , x15 = t[9] adds x27, x27, x14 // t[8](t[8] reserved in the previous round of calculation) + = t[8] // (t[8] taken from memory, initially 0) adcs x28, x28, x15 // t[9] += t[9], be the same as the above ldp x16 , x17 , [x2, #8*2] // x16 = t[10], x17 = t[11] ldp x14 , x15 , [x1], #16 // x14 = a[8], x15 = a[9] adcs x25, x25, x16 adcs x26, x26, x17 ldp x6, x7, [x2, #8*4] // x6 = t[12], x7 = t[13] ldp x16 , x17 , [x1], #16 // x16 = a[10], x17 = a[11] adcs x23, x23, x6 adcs x24, x24, x7 ldp x8, x9, [x2, #8*6] // x8 = t[14], x9 = t[15] ldp x6, x7, [x1], #16 // x6 = a[12], x7 = a[13] adcs x21, x21, x8 adcs x22, x22, x9 // t[15] = t[15] + CF, Because a[7]*a[7] is not calculated previously, t[15]=0 ldp x8, x9, [x1], #16 // x8 = a[14], x9 = a[15] .LSqr8xHighMulProces: ldr x4 , [x0, x19] // x4 = [x0 + x19] = [x0 - 56] = [&a[8] - 56] = a[8 - 7] = a[1] //-----lo(a[0] * a[8~11])----- adc x20, xzr, xzr // x20 += CF, Save the carry of t[15]. The same operation is performed below. add x19, x19, #8 // x19 += 8, Loop step size mul x10, x4 , x14 // x4 = a[0], x14 = a[8], x10 = lo(a[0] * a[8]) mul x11, x4 , x15 // x11 = lo(a[0] * a[9]) mul x12, x4 , x16 // x12 = lo(a[0] * a[10]) mul x13, x4 , x17 // x13 = lo(a[0] * a[11]) //-----lo(a[0] * a[12~15])----- adds x27, x27, x10 // CF does not need to be added for the first calculation, // t[8] += lo(a[0] * a[8]) adcs x28, x28, x11 // t[9] += lo(a[0] * a[9]) adcs x25, x25, x12 // t[10] += lo(a[0] * a[10]) adcs x26, x26, x13 // t[11] += lo(a[0] * a[11]) mul x10, x4 , x6 mul x11, x4 , x7 mul x12, x4 , x8 mul x13, x4 , x9 //-----hi(a[0] * a[8~11])----- adcs x23, x23, x10 // t[12] += lo(a[0] * a[12]) adcs x24, x24, x11 // t[13] += lo(a[0] * a[13]) adcs x21, x21, x12 // t[14] += lo(a[0] * a[14]) adcs x22, x22, x13 // t[15] += lo(a[0] * a[15]) umulh x10, x4 , x14 umulh x11, x4 , x15 umulh x12, x4 , x16 umulh x13, x4 , x17 adc x20, x20, xzr // x20 += CF, Save the carry of t[15] str x27, [x2], #8 // [x2] = t[8], x2 += 8, x27~x22 = t[9~16], // Update the mapping relationship to facilitate cycling. // x27~x26 always correspond to t[m~m+7], and x19 is always the LSB of the window //-----hi(a[0] * a[12~15])----- adds x27, x28, x10 // t[9] += hi(a[0] * a[8]), The last calculation was to calculate t[15], // so carry cannot be added to t[9], so adds is used adcs x28, x25, x11 // t[10] += hi(a[0] * a[9]) adcs x25, x26, x12 // t[11] += hi(a[0] * a[10]) adcs x26, x23, x13 // t[12] += hi(a[0] * a[11]) umulh x10, x4 , x6 umulh x11, x4 , x7 umulh x12, x4 , x8 umulh x13, x4 , x9 // x13 = hi(a[0] * a[15]) adcs x23, x24, x10 // t[13] += hi(a[0] * a[12]) adcs x24, x21, x11 // t[14] += hi(a[0] * a[13]) adcs x21, x22, x12 // t[15] += hi(a[0] * a[14]) adcs x22, x20, x13 // t[16] = hi(a[0] * a[15]) + CF cbnz x19, .LSqr8xHighMulProces // When exiting the loop, x0 = &a[8], x2 = &t[16] sub x16, x1, x3 // x3 = x1 + x5 * 8(Converted to bytes), When x1 = x3, the loop ends. cbnz x16, .LSqr8xHighMulBegian // x0 is the outer loop, x1 is the inner loop, and the inner loop ends. // In this case, x2 = &a[size], out-of-bounds position. mov x1, x0 // Outer Loop Increment, x1 = &a[16] ldp x14 , x15 , [x1], #16 // x14 = a[8] , x15 = a[9] ldp x16 , x17 , [x1], #16 // x16 = a[10], x17 = a[11] ldp x6, x7, [x1], #16 // x6 = a[12], x7 = a[13] ldp x8, x9, [x1], #16 // x8 = a[14], x9 = a[15] sub x10, x3 , x1 // Check whether the outer loop ends, x3 = &a[size], x10 = (size - 16)*8 cbz x10, .LSqr8xLoopMul sub x11, x2 , x10 // x2 = &t[24], x11 = &t[16] stp x27, x28, [x2 , #8*0] // t[24] = x27, t[25] = x28 ldp x27, x28, [x11, #8*0] // x27 = t[16], x28 = t[17] stp x25, x26, [x2 , #8*2] // t[26] = x25, t[27] = x26 ldp x25, x26, [x11, #8*2] // x25 = t[18], x26 = t[19] stp x23, x24, [x2 , #8*4] // t[28] = x23, t[29] = x24 ldp x23, x24, [x11, #8*4] // x23 = t[20], x24 = t[21] stp x21, x22, [x2 , #8*6] // t[30] = x21, t[31] = x22 ldp x21, x22, [x11, #8*6] // x21 = t[22], x22 = t[23] mov x2 , x11 // x2 = &t[16] b .LSqr8xLoopMul .align 4 .LSqr8xLoopMulEnd: //===== Calculate the squared term ===== //----- sp = &t[0] , x2 = &t[24]----- sub x10, x3, x5 // x10 = a[0] stp x27, x28, [x2, #8*0] // t[24] = x27, t[25] = x28 stp x25, x26, [x2, #8*2] // When this step is performed, the calculation results reserved for x27–x26 // are not pushed to the stack. stp x23, x24, [x2, #8*4] stp x21, x22, [x2, #8*6] ldp x11, x12, [sp, #8*1] // x11 = t[1], x12 = t[2] ldp x15, x17, [x10], #16 // x15 = a[0], x17 = a[1] ldp x7, x9, [x10], #16 // x7 = a[2], x9 = a[3] mov x1, x10 ldp x13, x10, [sp, #8*3] // x13 = t[3], x10 = t[4] mul x27, x15, x15 // x27 = lo(a[0] * a[0]) umulh x15, x15, x15 // x15 = hi(a[0] * a[0]) mov x2 , sp // x2 = sp = &t[0] mul x16, x17, x17 // x16 = lo(a[1] * a[1]) adds x28, x15, x11, lsl#1 // x28 = x15 + (x11 * 2) = hi(a[0] * a[0]) + 2 * t[1] umulh x17, x17, x17 // x17 = hi(a[1] * a[1]) extr x11, x12, x11, #63 // Lower 63 bits of x11 = x16 | most significant bit of x15 // Cyclic right shift by 63 bits to obtain the lower bit, // which is equivalent to cyclic left shift by 1 bit to obtain the upper bit. // The purpose is to *2. // x11 = 2*t[2](Ignore the overflowed part) + carry of (2*t[1]) mov x19, x5 // x19 = size*8 .LSqr8xDealSquare: adcs x25, x16 , x11 // x25 = lo(a[1] * a[1]) + 2*t[2] extr x12, x13, x12, #63 // x12 = 2*t[3](Ignore the overflowed part) + carry of (2*t[2]) adcs x26, x17 , x12 // x26 = hi(a[1] * a[1]) + 2*t[3] sub x19, x19, #8*4 // x19 = (size - 8)*8 stp x27, x28, [x2], #16 // t[0~3]Re-push stack stp x25, x26, [x2], #16 mul x6, x7, x7 // x6 = lo(a[2] * a[2]) umulh x7, x7, x7 // x7 = hi(a[2] * a[2]) mul x8, x9, x9 // x6 = lo(a[3] * a[3]) umulh x9, x9, x9 // x7 = hi(a[3] * a[3]) ldp x11, x12, [x2, #8] // x11 = t[5], x12 = t[6] extr x13, x10, x13, #63 // x13 = 2*t[4](Ignore the overflowed part) + carry of(2*t[3]) extr x10, x11, x10, #63 // x10 = 2*t[5](Ignore the overflowed part) + carry of(2*t[4]) adcs x23, x6, x13 // x23 = lo(a[2] * a[2]) + 2*t[4] adcs x24, x7, x10 // x24 = hi(a[2] * a[2]) + 2*t[5] cbz x19, .LSqr8xReduceStart ldp x13, x10, [x2, #24] // x13 = t[7], x10 = t[8] extr x11, x12, x11, #63 // x11 = 2*t[6](Ignore the overflowed part) + carry of(2*t[5]) extr x12, x13, x12, #63 // x12 = 2*t[7](Ignore the overflowed part) + carry of(2*t[6]) adcs x21, x8, x11 // x21 = lo(a[3] * a[3]) + 2*t[6] adcs x22, x9, x12 // x22 = hi(a[3] * a[3]) + 2*t[7] stp x23, x24, [x2], #16 // t[4~7]re-push stack stp x21, x22, [x2], #16 ldp x15, x17, [x1], #8*2 // x15 = a[4], x17 = a[5], x1 += 16 = &a[6] ldp x11, x12, [x2, #8] // x11 = t[9], x12 = t[10] mul x14 , x15 , x15 // x14 = lo(a[4] * a[4]) umulh x15 , x15 , x15 // x15 = hi(a[4] * a[4]) mul x16 , x17 , x17 // x16 = lo(a[5] * a[5]) umulh x17 , x17 , x17 // x17 = hi(a[5] * a[5]) extr x13, x10, x13, #63 // x13 = 2*t[8](Ignore the overflowed part) + carry of(2*t[7]) adcs x27, x14 , x13 // x27 = lo(a[4] * a[4]) + 2*t[8] extr x10, x11, x10, #63 // x10 = 2*t[9](Ignore the overflowed part) + carry of(2*t[8]) adcs x28, x15 , x10 // x28 = hi(a[4] * a[4]) + 2*t[9] extr x11, x12, x11, #63 // x11 = 2*t[10](Ignore the overflowed part) + carry of(2*t[9]) ldp x13, x10, [x2, #8*3] // Line 438 has obtained t[9] and t[10], x13 = &t[11], x10 = &t[12] ldp x7, x9, [x1], #8*2 // x7 = a[6], x9 = a[7], x1 += 16 = &a[8] b .LSqr8xDealSquare .LSqr8xReduceStart: extr x11, x12, x11, #63 // x11 = 2*t[2*size-2](Ignore the overflowed part) + carry of (2*t[2*size-3]) adcs x21, x8, x11 // x21 = lo(a[size-1] * a[size-1]) + 2*t[2*size-2] extr x12, xzr, x12, #63 // x12 = 2*t[2*size-1](Ignore the overflowed part) + carry of (2*t[2*size-2]) adc x22, x9, x12 // x22 = hi(a[size-1] * a[size-1]) + 2*t[2*size-1] ldp x1, x4, [x29, #104] // Pop n and k0 out of the stack, x1 = &n[0], x4 = k0 stp x23, x24, [x2] // t[2*size-4 ~ 2*size-1]re-push stack stp x21, x22, [x2,#8*2] cmp x5, #64 // if size == 8, we can goto Single step reduce b.ne .LSqr8xReduceLoop ldp x14 , x15 , [x1], #16 // x14~x9 = n[0~7] ldp x16 , x17 , [x1], #16 ldp x6, x7, [x1], #16 ldp x8, x9, [x1], #16 ldp x27, x28, [sp] // x14~x9 = t[0~7] ldp x25, x26, [sp,#8*2] ldp x23, x24, [sp,#8*4] ldp x21, x22, [sp,#8*6] mov x19, #8 mov x2 , sp // if size == 8, goto single reduce step .LSqr8xSingleReduce: mul x20, x4, x27 sub x19, x19, #1 //----- lo(n[1~7] * lo(t[0]*k0)) ----- mul x11, x15 , x20 mul x12, x16 , x20 mul x13, x17 , x20 mul x10, x6, x20 cmp x27, #1 adcs x27, x28, x11 adcs x28, x25, x12 adcs x25, x26, x13 adcs x26, x23, x10 mul x11, x7, x20 mul x12, x8, x20 mul x13, x9, x20 //----- hi(n[0~7] * lo(t[0]*k0)) ----- adcs x23, x24, x11 adcs x24, x21, x12 adcs x21, x22, x13 adc x22, xzr, xzr // x22 += CF umulh x10, x14 , x20 umulh x11, x15 , x20 umulh x12, x16 , x20 umulh x13, x17 , x20 adds x27, x27, x10 adcs x28, x28, x11 adcs x25, x25, x12 adcs x26, x26, x13 umulh x10, x6, x20 umulh x11, x7, x20 umulh x12, x8, x20 umulh x13, x9, x20 adcs x23, x23, x10 adcs x24, x24, x11 adcs x21, x21, x12 adc x22, x22, x13 cbnz x19, .LSqr8xSingleReduce // Need cycle 8 times ldp x10, x11, [x2, #64] // x10 = t[8], x11 = t[9] ldp x12, x13, [x2, #80] adds x27, x27, x10 adcs x28, x28, x11 ldp x10, x11, [x2, #96] adcs x25, x25, x12 adcs x26, x26, x13 adcs x23, x23, x10 ldp x12, x13, [x2, #112] adcs x24, x24, x11 adcs x21, x21, x12 adcs x22, x22, x13 adc x20, xzr, xzr ldr x0, [x29, #96] // r Pop-Stack // t - mod subs x14, x27, x14 sbcs x15, x28, x15 sbcs x16, x25, x16 sbcs x17, x26, x17 sbcs x6, x23, x6 sbcs x7, x24, x7 sbcs x8, x21, x8 sbcs x9, x22, x9 sbcs x20, x20, xzr // determine whether there is a borrowing // according to CF choose our result csel x14 , x27, x14 , lo csel x15 , x28, x15 , lo csel x16 , x25, x16 , lo csel x17 , x26, x17 , lo stp x14 , x15 , [x0, #8*0] csel x6, x23, x6, lo csel x7, x24, x7, lo stp x16 , x17 , [x0, #8*2] csel x8, x21, x8, lo csel x9, x22, x9, lo stp x6, x7, [x0, #8*4] stp x8, x9, [x0, #8*6] b .LMontSqr8xEnd .LSqr8xReduceLoop: add x3, x1, x5 // x3 = &n[size] mov x30, xzr ldp x14 , x15 , [x1], #16 // x14~x9 = n[0~7] ldp x16 , x17 , [x1], #16 ldp x6, x7, [x1], #16 ldp x8, x9, [x1], #16 ldp x27, x28, [sp] // x27 = t[0], x28 = t[1] ldp x25, x26, [sp,#8*2] // x25~x22 = t[2~7] ldp x23, x24, [sp,#8*4] ldp x21, x22, [sp,#8*6] mov x19, #8 mov x2 , sp .LSqr8xReduceProcess: mul x20, x4, x27 // x20 = lo(k0 * t[0]) sub x19, x19, #1 //----- lo(n[1~7] * lo(t[0]*k0)) ----- mul x11, x15, x20 // x11 = n[1] * lo(t[0]*k0) mul x12, x16, x20 // x12 = n[2] * lo(t[0]*k0) mul x13, x17, x20 // x13 = n[3] * lo(t[0]*k0) mul x10, x6, x20 // x10 = n[4] * lo(t[0]*k0) str x20, [x2], #8 // Push lo(t[0]*k0) on the stack., x2 += 8 cmp x27, #1 // Check whether the low location is carried. adcs x27, x28, x11 // x27 = t[1] + lo(n[1] * lo(t[0]*k0)) adcs x28, x25, x12 // x28 = t[2] + lo(n[2] * lo(t[0]*k0)) adcs x25, x26, x13 // x25 = t[3] + lo(n[3] * lo(t[0]*k0)) adcs x26, x23, x10 // x26 = t[4] + lo(n[4] * lo(t[0]*k0)) mul x11, x7, x20 mul x12, x8, x20 mul x13, x9, x20 //----- hi(n[0~7] * lo(t[0]*k0)) ----- adcs x23, x24, x11 // x23 = t[5] + lo(n[5] * lo(t[0]*k0)) adcs x24, x21, x12 // x24 = t[6] + lo(n[6] * lo(t[0]*k0)) adcs x21, x22, x13 // x21 = t[7] + lo(n[7] * lo(t[0]*k0)) adc x22, xzr, xzr // x22 += CF umulh x10, x14 , x20 umulh x11, x15 , x20 umulh x12, x16 , x20 umulh x13, x17 , x20 adds x27, x27, x10 // x27 += hi(n[0] * lo(t[0]*k0)) adcs x28, x28, x11 // x28 += hi(n[1] * lo(t[0]*k0)) adcs x25, x25, x12 // x25 += hi(n[2] * lo(t[0]*k0)) adcs x26, x26, x13 // x26 += hi(n[3] * lo(t[0]*k0)) umulh x10, x6, x20 umulh x11, x7, x20 umulh x12, x8, x20 umulh x13, x9, x20 adcs x23, x23, x10 // x23 += hi(n[4] * lo(t[0]*k0)) adcs x24, x24, x11 // x24 += hi(n[5] * lo(t[0]*k0)) adcs x21, x21, x12 // x21 += hi(n[6] * lo(t[0]*k0)) adc x22, x22, x13 // x22 += hi(n[7] * lo(t[0]*k0)) cbnz x19, .LSqr8xReduceProcess // Cycle 8 times, and at the end of the cycle, x2 += 8*8 ldp x10, x11, [x2, #8*0] // x10 = t[8], x11 = t[9] ldp x12, x13, [x2, #8*2] mov x0, x2 adds x27, x27, x10 adcs x28, x28, x11 ldp x10, x11, [x2,#8*4] adcs x25, x25, x12 adcs x26, x26, x13 ldp x12, x13, [x2,#8*6] adcs x23, x23, x10 adcs x24, x24, x11 adcs x21, x21, x12 adcs x22, x22, x13 ldr x4 , [x2, #-8*8] // x4 = t[0] ldp x14 , x15 , [x1], #16 // x14~x9 = &n[8]~&n[15] ldp x16 , x17 , [x1], #16 ldp x6, x7, [x1], #16 ldp x8, x9, [x1], #16 mov x19, #-8*8 .LSqr8xReduce: adc x20, xzr, xzr // x20 = CF add x19, x19, #8 mul x10, x14 , x4 mul x11, x15 , x4 mul x12, x16 , x4 mul x13, x17 , x4 adds x27, x27, x10 adcs x28, x28, x11 adcs x25, x25, x12 adcs x26, x26, x13 mul x10, x6, x4 mul x11, x7, x4 mul x12, x8, x4 mul x13, x9, x4 adcs x23, x23, x10 adcs x24, x24, x11 adcs x21, x21, x12 adcs x22, x22, x13 umulh x10, x14 , x4 umulh x11, x15 , x4 umulh x12, x16 , x4 umulh x13, x17 , x4 adc x20, x20, xzr str x27, [x2], #8 // x27 = t[8], x2 += 8 adds x27, x28, x10 // x27 = t[1] + lo(n[1] * lo(t[0]*k0)) adcs x28, x25, x11 // x28 = t[2] + lo(n[2] * lo(t[0]*k0)) adcs x25, x26, x12 // x25 = t[3] + lo(n[3] * lo(t[0]*k0)) adcs x26, x23, x13 // x26 = t[4] + lo(n[4] * lo(t[0]*k0)) umulh x10, x6, x4 umulh x11, x7, x4 umulh x12, x8, x4 umulh x13, x9, x4 // x0 = &t[8] ldr x4 , [x0, x19] adcs x23, x24, x10 adcs x24, x21, x11 adcs x21, x22, x12 adcs x22, x20, x13 cbnz x19, .LSqr8xReduce ldp x14 , x15 , [x2, #8*0] ldp x16 , x17 , [x2, #8*2] sub x19, x3, x1 // x19 = (size-16)*8 ldp x6, x7, [x2, #8*4] ldp x8, x9, [x2, #8*6] cbz x19, .LSqr8xReduceBreak ldr x4 , [x0, #-8*8] adds x27, x27, x14 adcs x28, x28, x15 adcs x25, x25, x16 adcs x26, x26, x17 adcs x23, x23, x6 adcs x24, x24, x7 adcs x21, x21, x8 adcs x22, x22, x9 ldp x14 , x15 , [x1], #16 ldp x16 , x17 , [x1], #16 ldp x6, x7, [x1], #16 ldp x8, x9, [x1], #16 mov x19, #-8*8 b .LSqr8xReduce .align 4 .LSqr8xReduceBreak: sub x12, x3, x5 // x12 = n, reassign to n ldr x4 , [x29, #112] // k0 pop-stack cmp x30, #1 // Check whether the low location is carried. adcs x10, x27, x14 adcs x11, x28, x15 stp x10, x11, [x2] , #16 ldp x27 ,x28, [x0 , #8*0] ldp x14 , x15, [x12], #16 // x12 = &n[0] (Line 638 assigns a value) adcs x25, x25, x16 adcs x26, x26, x17 adcs x23, x23, x6 adcs x24, x24, x7 adcs x21, x21, x8 adcs x22, x22, x9 adc x30, xzr, xzr ldp x16, x17, [x12], #16 ldp x6, x7, [x12], #16 ldp x8, x9, [x12], #16 stp x25, x26, [x2], #16 ldp x25, x26, [x0, #8*2] stp x23, x24, [x2], #16 ldp x23, x24, [x0, #8*4] stp x21, x22, [x2], #16 ldp x21, x22, [x0, #8*6] sub x20, x2, x29 // Check whether the loop ends mov x1, x12 mov x2, x0 // sliding window mov x19, #8 cbnz x20, .LSqr8xReduceProcess // Final step ldr x0 , [x29, #96] // r Pop-Stack add x2 , x2 , #8*8 subs x10, x27, x14 sbcs x11, x28, x15 sub x19, x5 , #8*8 mov x3 , x0 // backup x0 .LSqr8xSubMod: ldp x14 , x15, [x1], #16 sbcs x12, x25, x16 sbcs x13, x26, x17 ldp x16 , x17 , [x1], #16 stp x10, x11, [x0], #16 stp x12, x13, [x0], #16 sbcs x10, x23, x6 sbcs x11, x24, x7 ldp x6, x7, [x1], #16 sbcs x12, x21, x8 sbcs x13, x22, x9 ldp x8, x9, [x1], #16 stp x10, x11, [x0], #16 stp x12, x13, [x0], #16 ldp x27, x28, [x2], #16 ldp x25, x26, [x2], #16 ldp x23, x24, [x2], #16 ldp x21, x22, [x2], #16 sub x19, x19, #8*8 sbcs x10, x27, x14 sbcs x11, x28, x15 cbnz x19, .LSqr8xSubMod mov x2 , sp add x1 , sp , x5 sbcs x12, x25, x16 sbcs x13, x26, x17 stp x12, x13, [x0, #8*2] stp x10, x11, [x0, #8*0] sbcs x10, x23, x6 sbcs x11, x24, x7 stp x10, x11, [x0, #8*4] sbcs x12, x21, x8 sbcs x13, x22, x9 stp x12, x13, [x0, #8*6] sbcs xzr, x30, xzr // Determine whether there is a borrowing .LSqr8xCopy: ldp x14, x15, [x3, #8*0] ldp x16, x17, [x3, #8*2] ldp x6, x7, [x3, #8*4] ldp x8, x9, [x3, #8*6] ldp x27, x28, [x1], #16 ldp x25, x26, [x1], #16 ldp x23, x24, [x1], #16 ldp x21, x22, [x1], #16 sub x5, x5, #8*8 csel x10, x27, x14, lo // Condition selection instruction, lo = less than, // equivalent to x14 = (conf==lo) ? x27 : x14 csel x11, x28, x15, lo csel x12, x25, x16 , lo csel x13, x26, x17, lo csel x14, x23, x6, lo csel x15, x24, x7, lo csel x16, x21, x8, lo csel x17, x22, x9, lo stp x10, x11, [x3], #16 stp x12, x13, [x3], #16 stp x14, x15, [x3], #16 stp x16, x17, [x3], #16 cbnz x5, .LSqr8xCopy .LMontSqr8xEnd: ldr x30, [x29, #8] // Pop-Stack ldp x27, x28, [x29, #16] mov sp , x29 ldp x25, x26, [x29, #32] mov x0 , #1 ldp x23, x24, [x29, #48] ldp x21, x22, [x29, #64] ldp x19, x20, [x29, #80] // x19 = [x29 + 80], x20 = [x29 + 80 + 8], // ldp reads two 8-byte memory blocks at a time. ldr x29, [sp], #128 // x29 = [sp], sp = sp + 128,ldr reads only an 8-byte block of memory AARCH64_AUTIASP ret .size MontSqr8, .-MontSqr8 .type MontMul4, %function MontMul4: AARCH64_PACIASP stp x29, x30, [sp, #-128]! mov x29, sp stp x27, x28, [sp, #16] stp x25, x26, [sp, #32] stp x23, x24, [sp, #48] stp x21, x22, [sp, #64] stp x19, x20, [sp, #80] mov x27, xzr mov x28, xzr mov x25, xzr mov x26, xzr mov x30, xzr lsl x5 , x5 , #3 sub x22, sp , x5 sub sp , x22, #8*4 // The space of size + 4 is applied for mov x22, sp sub x6, x5, #32 cbnz x6, .LMul4xProcesStart ldp x14 , x15 , [x1, #8*0] ldp x16 , x17 , [x1, #8*2] // x14~x17 = a[0~3] ldp x10, x11, [x3] // x10~x13 = n[0~3] ldp x12, x13, [x3, #8*2] mov x1 , xzr mov x20, #4 // if size == 4, goto single step .LMul4xSingleStep: sub x20, x20, #0x1 ldr x24, [x2], #8 // b[i] //----- lo(a[0~3] * b[0]) ----- mul x6, x14 , x24 mul x7, x15 , x24 mul x8, x16 , x24 mul x9, x17 , x24 //----- hi(a[0~3] * b[0]) ----- adds x27, x27, x6 umulh x6, x14 , x24 adcs x28, x28, x7 umulh x7, x15 , x24 adcs x25, x25, x8 umulh x8, x16 , x24 adcs x26, x26, x9 umulh x9, x17 , x24 mul x21, x27, x4 adc x23, xzr, xzr //----- lo(n[0~3] * t[0]*k0) ----- adds x28, x28, x6 adcs x25, x25, x7 mul x7, x11, x21 adcs x26, x26, x8 mul x8, x12, x21 adc x23, x23, x9 mul x9, x13, x21 cmp x27, #1 adcs x27, x28, x7 //----- hi(n[0~3] *t[0]*k0) ----- umulh x6, x10, x21 umulh x7, x11, x21 adcs x28, x25, x8 umulh x8, x12, x21 adcs x25, x26, x9 umulh x9, x13, x21 adcs x26, x23, x1 adc x1 , xzr, xzr adds x27, x27, x6 adcs x28, x28, x7 adcs x25, x25, x8 adcs x26, x26, x9 adc x1 , x1 , xzr cbnz x20, .LMul4xSingleStep subs x14 , x27, x10 sbcs x15 , x28, x11 sbcs x16 , x25, x12 sbcs x17 , x26, x13 sbcs xzr, x1 , xzr // update CF, Determine whether to borrow csel x14 , x27, x14 , lo csel x15 , x28, x15 , lo csel x16 , x25, x16 , lo csel x17 , x26, x17 , lo stp x14 , x15 , [x0, #8*0] stp x16 , x17 , [x0, #8*2] b .LMontMul4xEnd .LMul4xProcesStart: add x6, x5, #32 eor v0.16b,v0.16b,v0.16b eor v1.16b,v1.16b,v1.16b .LMul4xInitstack: sub x6, x6, #32 st1 {v0.2d, v1.2d}, [x22], #32 cbnz x6, .LMul4xInitstack mov x22, sp add x6, x2 , x5 // x6 = &b[size] adds x19, x1 , x5 // x19 = &a[size] stp x0 , x6, [x29, #96] // r and b[size] push stack mov x0 , xzr mov x20, #0 .LMul4xLoopProces: ldr x24, [x2] // x24 = b[0] ldp x14 , x15 , [x1], #16 ldp x16 , x17 , [x1], #16 // x14~x17 = a[0~3] ldp x10 , x11 , [x3], #16 ldp x12 , x13 , [x3], #16 // x10~x13 = n[0~3] .LMul4xPrepare: //----- lo(a[0~3] * b[0]) ----- adc x0 , x0 , xzr // x0 += CF add x20, x20, #8 and x20, x20, #31 // x20 &= 0xff. The lower eight bits are used. // When x28 = 32, the instruction becomes 0. mul x6, x14 , x24 mul x7, x15 , x24 mul x8, x16 , x24 mul x9, x17 , x24 //----- hi(a[0~3] * b[0]) ----- adds x27, x27, x6 // t[0] += lo(a[0] * b[0]) adcs x28, x28, x7 // t[1] += lo(a[1] * b[0]) adcs x25, x25, x8 // t[2] += lo(a[2] * b[0]) adcs x26, x26, x9 // t[3] += lo(a[3] * b[0]) umulh x6, x14 , x24 // x6 = hi(a[0] * b[0]) umulh x7, x15 , x24 umulh x8, x16 , x24 umulh x9, x17 , x24 mul x21, x27, x4 // x21 = t[0] * k0, t[0]*k0 needs to be recalculated in each round. // t[0] is different in each round. adc x23, xzr, xzr // t[4] += CF(set by t[3] += lo(a[3] * b[0]) ) ldr x24, [x2, x20] // b[i] str x21, [x22], #8 // t[0] * k0 push stack, x22 += 8 //----- lo(n[0~3] * t[0]*k0) ----- adds x28, x28, x6 // t[1] += hi(a[0] * b[0]) adcs x25, x25, x7 // t[2] += hi(a[1] * b[0]) adcs x26, x26, x8 // t[3] += hi(a[2] * b[0]) adc x23, x23, x9 // t[4] += hi(a[3] * b[0]) mul x7, x11, x21 // x7 = lo(n[1] * t[0]*k0) mul x8, x12, x21 // x8 = lo(n[2] * t[0]*k0) mul x9, x13, x21 // x9 = lo(n[3] * t[0]*k0) cmp x27, #1 adcs x27, x28, x7 // (t[0]) = x27 = t[1] + lo(n[1] * t[0]*k0), // Perform S/R operations, r=2^64, shift right 64 bits. //----- hi(n[0~3] *t[0]*k0) ----- adcs x28, x25, x8 // x28 = t[2] + lo(n[2] * t[0]*k0) adcs x25, x26, x9 // x25 = t[3] + lo(n[3] * t[0]*k0) adcs x26, x23, x0 // x26 = t[4] + 0 + CF adc x0 , xzr, xzr // x0 = CF umulh x6, x10, x21 // x6 = hi(n[0] * t[0]*k0) umulh x7, x11, x21 // x7 = hi(n[1] * t[0]*k0) umulh x8, x12, x21 // x8 = hi(n[2] * t[0]*k0) umulh x9, x13, x21 // x9 = hi(n[3] * t[0]*k0) adds x27, x27, x6 // x27 = t[1] + hi(n[0] * t[0]*k0) adcs x28, x28, x7 // x28 = t[2] + hi(n[1] * t[0]*k0) adcs x25, x25, x8 // x25 = t[3] + hi(n[2] * t[0]*k0) adcs x26, x26, x9 // x26 = t[4] + hi(n[3] * t[0]*k0) cbnz x20, .LMul4xPrepare // Four t[0] * k0s are stacked in each loop. adc x0 , x0 , xzr ldp x6, x7, [x22, #8*4] // load A (cal before) ldp x8, x9, [x22, #8*6] adds x27, x27, x6 adcs x28, x28, x7 adcs x25, x25, x8 adcs x26, x26, x9 ldr x21, [sp] // x21 = t[0] * k0 .LMul4xReduceBegin: ldp x14 , x15 , [x1], #16 ldp x16 , x17 , [x1], #16 // x14~x17 = a[4~7] ldp x10 , x11 , [x3], #16 ldp x12 , x13 , [x3], #16 // n[4~7] .LMul4xReduceProces: adc x0 , x0 , xzr add x20, x20, #8 and x20, x20, #31 //----- lo(a[4~7] * b[i]) ----- mul x6, x14 , x24 mul x7, x15 , x24 mul x8, x16 , x24 mul x9, x17 , x24 //----- hi(a[4~7] * b[i]) ----- adds x27, x27, x6 // x27 += lo(a[4~7] * b[i]) adcs x28, x28, x7 adcs x25, x25, x8 adcs x26, x26, x9 adc x23, xzr, xzr umulh x6, x14 , x24 umulh x7, x15 , x24 umulh x8, x16 , x24 umulh x9, x17 , x24 ldr x24, [x2, x20] // b[i] //----- lo(n[4~7] * t[0]*k0) ----- adds x28, x28, x6 adcs x25, x25, x7 adcs x26, x26, x8 adc x23, x23, x9 mul x6, x10, x21 mul x7, x11, x21 mul x8, x12, x21 mul x9, x13, x21 //----- hi(n[4~7] * t[0]*k0) ----- adds x27, x27, x6 adcs x28, x28, x7 adcs x25, x25, x8 adcs x26, x26, x9 adcs x23, x23, x0 umulh x6, x10, x21 umulh x7, x11, x21 umulh x8, x12, x21 umulh x9, x13, x21 ldr x21, [sp, x20] // t[0]*k0 adc x0 , xzr, xzr // x0 = CF, record carry str x27, [x22], #8 // s[i] the calculation is complete, write the result, x22 += 8 adds x27, x28, x6 adcs x28, x25, x7 adcs x25, x26, x8 adcs x26, x23, x9 cbnz x20, .LMul4xReduceProces sub x6, x19, x1 // x6 = &a[size] - &a[i] // (The value of x1 increases cyclically.) Check whether the loop ends adc x0 , x0 , xzr cbz x6, .LMul4xLoopExitCheck ldp x6, x7, [x22, #8*4] // t[4~7] ldp x8, x9, [x22, #8*6] adds x27, x27, x6 adcs x28, x28, x7 adcs x25, x25, x8 adcs x26, x26, x9 b .LMul4xReduceBegin .LMul4xLoopExitCheck: ldr x9, [x29, #104] // b[size] Pop-Stack add x2 , x2 , #8*4 // b subscript is offset once by 4 each time, &b[4], &b[8]...... sub x9 , x9, x2 // Indicates whether the outer loop ends. adds x27, x27, x30 adcs x28, x28, xzr stp x27, x28, [x22, #8*0] // x27, x20 After the calculation is complete, Push-stack storage ldp x27, x28, [sp , #8*4] // t[0], t[1] adcs x25, x25, xzr adcs x26, x26, xzr stp x25, x26, [x22, #8*2] // x25, x22 After the calculation is complete, Push-stack storage ldp x25, x26, [sp , #8*6] // t[2], t[3] adc x30, x0 , xzr sub x3 , x3 , x5 // x1 = &n[0] cbz x9, .LMul4xEnd sub x1 , x1 , x5 // x1 = &a[0] mov x22, sp mov x0 , xzr b .LMul4xLoopProces .LMul4xEnd: ldp x10, x11, [x3], #16 ldp x12, x13, [x3], #16 ldr x0, [x29, #96] // r[0] Pop-Stack mov x19, x0 // backup, x19 = &r[0] subs x6, x27, x10 // t[0] - n[0], modify CF sbcs x7, x28, x11 // t[1] - n[1] - CF add x22, sp , #8*8 // x22 = &S[8] sub x20, x5 , #8*4 // x20 = (size - 4)*8 // t - n, x22 = &t[8], x3 = &n[0] .LMul4xSubMod: sbcs x8, x25, x12 sbcs x9, x26, x13 ldp x10, x11, [x3], #16 ldp x12, x13, [x3], #16 ldp x27, x28, [x22], #16 ldp x25, x26, [x22], #16 sub x20, x20, #8*4 stp x6, x7, [x0], 16 stp x8, x9, [x0], 16 sbcs x6, x27, x10 sbcs x7, x28, x11 cbnz x20, .LMul4xSubMod sbcs x8, x25, x12 sbcs x9, x26, x13 sbcs xzr, x30, xzr // CF = x30 - CF, x30 recorded the previous carry add x1 , sp , #8*4 // The size of the SP space is size + 4., x1 = sp + 4 stp x6, x7, [x0] stp x8, x9, [x0, #8*2] .LMul4xCopy: ldp x14 , x15 , [x19] // x14~x17 = r[0~3] ldp x16 , x17 , [x19, #8*2] ldp x27, x28, [x1], #16 // x27~22 = S[4~7] ldp x25, x26, [x1], #16 sub x5, x5, #8*4 csel x6, x27, x14, lo // x6 = (CF == 1) ? x27 : x14 csel x7, x28, x15, lo csel x8, x25, x16, lo csel x9, x26, x17, lo stp x6, x7, [x19], #16 stp x8, x9, [x19], #16 cbnz x5, .LMul4xCopy .LMontMul4xEnd: ldr x30, [x29, #8] // Value Pop-Stack in x30 (address of next instruction) ldp x27, x28, [x29, #16] ldp x25, x26, [x29, #32] ldp x23, x24, [x29, #48] ldp x21, x22, [x29, #64] ldp x19, x20, [x29, #80] mov sp , x29 ldr x29, [sp], #128 AARCH64_AUTIASP ret .size MontMul4, .-MontMul4 #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/asm/bn_mont_armv8.S
Unix Assembly
unknown
51,548
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN .file "bn_mont_x86_64.S" .text .macro ADD_CARRY a b addq \a,\b adcq $0,%rdx .endm .macro SAVE_REGISTERS pushq %r15 // Save non-volatile register. pushq %r14 pushq %r13 pushq %r12 pushq %rbp pushq %rbx .endm .macro RESTORE_REGISTERS popq %rbx // Restore non-volatile register. popq %rbp popq %r12 popq %r13 popq %r14 popq %r15 .endm /* * void MontMul_Asm(uint64_t *r, const uint64_t *a, const uint64_t *b, * const uint64_t *n, const uint64_t k0, uint32_t size); */ .globl MontMul_Asm .type MontMul_Asm,@function .align 16 MontMul_Asm: .cfi_startproc testl $3,%r9d jnz .LMontMul // If size is not divisible by 4, LMontMul. cmpl $8,%r9d jb .LMontMul // LMontMul cmpq %rsi,%rdx jne MontMul4 // if a != b, MontMul4 testl $7,%r9d jz MontSqr8 // If size is divisible by 8,enter MontSqr8. jmp MontMul4 .align 16 .LMontMul: SAVE_REGISTERS // Save non-volatile register. movq %rsp,%rax // rax stores the rsp movq %r9, %r15 negq %r15 // r15 = -size leaq -16(%rsp, %r15, 8), %r15 // r15 = rsp - size * 8 - 16 andq $-1024, %r15 // r15 The address is aligned down by 1 KB. movq %rsp, %r14 // r14 = rsp subq %r15,%r14 // __chkstk implemention, called when the stack size needs to exceed 4096. // (the size of a page) to allocate more pages. andq $-4096,%r14 // r14 4K down-align. leaq (%r15,%r14),%rsp // rsp = r15 + r14 cmpq %r15,%rsp // If you want to allocate more than one page, go to Lmul_page_walk. ja .LoopPage jmp .LMulBody .align 16 .LoopPage: leaq -4096(%rsp),%rsp // rsp - 4096 each time until rsp < r15. cmpq %r15,%rsp ja .LoopPage .LMulBody: movq %rax,8(%rsp,%r9,8) // Save the original rsp in the stack. movq %rdx,%r13 // r13 = b xorq %r11,%r11 // r11 = 0 xorq %r10,%r10 // r10 = 0 movq (%r13),%rbx // rbx = b[0] movq (%rsi),%rax // rax = a[0] mulq %rbx // (rdx, rax) = a[0] * b[0] movq %rax,%r15 // r15 = t[0] = lo(a[0] * b[0]) movq %rdx,%r14 // r14 = hi(a[0] * b[0]) movq %r8,%rbp // rbp = k0 imulq %r15,%rbp // rbp = t[0] * k0 movq (%rcx),%rax // rax = n[0] mulq %rbp // (rdx, rax) = t[0] * k0 * n[0] ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0]) + t[0] leaq 1(%r10),%r10 // j++ .Loop1st: movq (%rsi,%r10,8),%rax // rax = a[j] movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[0]) mulq %rbx // (rdx, rax) = a[j] * b[0] ADD_CARRY %rax,%r14 // r14 = hi(a[j - 1] * b[0]) + lo(a[j] * b[0]) movq %rdx,%r15 // r15 = hi(a[j] * b[0]) movq (%rcx,%r10,8),%rax // rax = n[j] mulq %rbp // (rdx, rax) = t[0] * k0 * n[j] leaq 1(%r10),%r10 // j++ cmpq %r9,%r10 // if j != size, loop L1st je .Loop1stSkip ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j]) + lo(t[0] * k0 * n[j]) ADD_CARRY %r14,%r12 // r12 += lo(a[j] * b[0]) + hi(a[j] * b[0]) movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13 movq %r15,%r14 // r14 = hi(a[j] * b[0]) jmp .Loop1st .Loop1stSkip: ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) + lo(t[0] * k0 * n[j]) ADD_CARRY %r14,%r12 // r12 += hi(a[j - 1] * b[0]) + lo(a[j] * b[0]) movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13 movq %r15,%r14 // r14 = hi(a[j] * b[0]) movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j]) xorq %rdx,%rdx // rdx = 0, Clearing the CF. ADD_CARRY %r14,%r12 // r12 = hi(t[0] * k0 * n[j]) + hi(a[j] * b[0]) movq %r12,-8(%rsp,%r9,8) // t[size - 1] = hi(t[0] * k0 * n[j]) + hi(a[j] * b[0]), save overflow bit. movq %rdx,(%rsp,%r9,8) leaq 1(%r11),%r11 // i++ .align 16 .LoopOuter: xorq %r10,%r10 // j = 0 movq (%rsi),%rax // rax = a[0] movq (%r13,%r11,8),%rbx // rbx = b[i] mulq %rbx // (rdx, rax) = a[0] * b[i] movq (%rsp),%r15 // r15 = lo(a[0] * b[i]) + t[0] ADD_CARRY %rax,%r15 movq %rdx,%r14 // r14 = hi(a[0] * b[i]) movq %r8,%rbp // rbp = t[0] * k0 imulq %r15,%rbp movq (%rcx),%rax // rax = n[0] mulq %rbp // (rdx, rax) = t[0] * k0 * n[0] ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0]) leaq 1(%r10),%r10 // j++ .align 16 .LoopInner: movq (%rsi,%r10,8),%rax // rax = a[j] movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j]) movq (%rsp,%r10,8),%r15 // r15 = t[j] mulq %rbx // (rdx, rax) = a[1] * b[i] ADD_CARRY %rax,%r14 // r14 = hi(a[0] * b[i]) + lo(a[1] * b[i]) movq (%rcx,%r10,8),%rax // rax = n[j] ADD_CARRY %r14,%r15 // r15 = a[j] * b[i] + t[j] movq %rdx,%r14 leaq 1(%r10),%r10 // j++ mulq %rbp // (rdx, rax) = t[0] * k0 * n[j] cmpq %r9,%r10 // if j != size, loop Linner je .LoopInnerSkip ADD_CARRY %rax,%r12 // r12 = t[0] * k0 * n[j] ADD_CARRY %r15,%r12 // r12 = a[j] * b[i] + t[j] + n[j] * t[0] * k0 movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13 jmp .LoopInner .LoopInnerSkip: ADD_CARRY %rax,%r12 // r12 = t[0] * k0 * n[j] ADD_CARRY %r15,%r12 // r12 = t[0] * k0 * n[j] + a[j] * b[i] + t[j] movq (%rsp,%r10,8),%r15 // r15 = t[j] movq %r12,-16(%rsp,%r10,8) // t[j - 2] movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j]) xorq %rdx,%rdx // rdx 0 ADD_CARRY %r14,%r12 // r12 = hi(a[1] * b[i]) + hi(t[0] * k0 * n[j]) ADD_CARRY %r15,%r12 // r12 += t[j] movq %r12,-8(%rsp,%r9,8) // t[size - 1] = r13 movq %rdx,(%rsp,%r9,8) // t[size] = CF leaq 1(%r11),%r11 // i++ cmpq %r9,%r11 // if size < i (unsigned) jne .LoopOuter xorq %r11,%r11 // r11 = 0, clear CF. movq (%rsp),%rax // rax = t[0] movq %r9,%r10 // r10 = size .align 16 .LoopSub: sbbq (%rcx,%r11,8),%rax // r[i] = t[i] - n[i] movq %rax,(%rdi,%r11,8) movq 8(%rsp,%r11,8),%rax // rax = t[i + 1] leaq 1(%r11),%r11 // i++ decq %r10 // j-- jnz .LoopSub // if j != 0 sbbq $0,%rax // rax -= CF movq $-1,%rbx xorq %rax,%rbx // rbx = !t[i + 1] xorq %r11,%r11 // r11 = 0 movq %r9,%r10 // r10 = size .LoopCopy: movq (%rdi,%r11,8),%rcx // rcx = r[i] & t[i] andq %rbx,%rcx movq (%rsp,%r11,8),%rdx // rdx = CF & t[i] andq %rax,%rdx orq %rcx,%rdx movq %rdx,(%rdi,%r11,8) // r[i] = t[i] movq %r9,(%rsp,%r11,8) // t[i] = size leaq 1(%r11),%r11 // i++ subq $1,%r10 // j-- jnz .LoopCopy // if j != 0 movq 8(%rsp,%r9,8),%rsi // rsi = pressed-stacked rsp. movq $1,%rax // rax = 1 leaq (%rsi),%rsp // restore rsp. RESTORE_REGISTERS // Restore non-volatile register. ret .cfi_endproc .size MontMul_Asm,.-MontMul_Asm .type MontMul4,@function .align 16 MontMul4: .cfi_startproc SAVE_REGISTERS movq %rsp,%rax // save rsp movq %r9,%r15 negq %r15 leaq -32(%rsp,%r15,8),%r15 // Allocate space: size * 8 + 32 bytes. andq $-1024,%r15 movq %rsp,%r14 subq %r15,%r14 // __chkstk implemention, called when the stack size needs to exceed 4096. andq $-4096,%r14 leaq (%r15,%r14),%rsp cmpq %r15,%rsp // If you want to allocate more than one page, go to LoopPage4x. ja .LoopPage4x jmp .LoopMul4x .LoopPage4x: leaq -4096(%rsp),%rsp // rsp - 4096each time until rsp >= r10. cmpq %r15,%rsp ja .LoopPage4x .LoopMul4x: xorq %r11,%r11 // i = 0 xorq %r10,%r10 // j = 0 movq %rax,8(%rsp,%r9,8) movq %rdi,16(%rsp,%r9,8) // t[size + 2] = r movq %rdx,%r13 // r13 = b movq (%rsi),%rax // rax = a[0] movq %r8,%rbp // rbp = k0 movq (%r13),%rbx // rbx = b[0] /* 计算a[i] * b[0] * k[0] * n[j] */ mulq %rbx // (rdx, rax) = a[0] * b[0] movq %rax,%r15 // r15 = t[0] = lo(b[0] * a[0]) movq (%rcx),%rax // rax = n[0] imulq %r15,%rbp // rbp = t[0] * k0 movq %rdx,%r14 // r14 = hi(a[0] * b[0]) mulq %rbp // (rdx, rax) = t[0] * k0 * n[0] ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0]) movq 8(%rsi),%rax // rax = a[1] movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[0]) mulq %rbx // (rdx, rax) = a[1] * b[0] ADD_CARRY %rax,%r14 // r14 = lo(a[1] * b[0]) + hi(a[0] * b[0]) movq 8(%rcx),%rax // rax = n[1] movq %rdx,%r15 // r15 = hi(a[1] * b[0]) mulq %rbp // (rdx, rax) = t[0] * k0 * n[1] ADD_CARRY %rax,%rdi // rdi = lo(t[0] * k0 * n[1]) + hi(t[0] * k0 * n[0]) movq 16(%rsi),%rax // rax = a[2] ADD_CARRY %r14,%rdi // rdi += hi(a[0] * b[0]) + lo(a[1] * b[0]) movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[1]) movq %rdi,(%rsp) // t[0] = rdi leaq 4(%r10),%r10 // j += 4 .align 16 .Loop1st4x: mulq %rbx // (rdx, rax) = a[2] * b[0] ADD_CARRY %rax,%r15 // r15 = hi(a[1] * b[0]) + lo(a[2] * b[0]) movq -16(%rcx,%r10,8),%rax // rax = n[j - 2] movq %rdx,%r14 // r14 = hi[a[2] * b[0]] mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 2] ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[1]) + lo(t[0] * k0 * n[j - 2]) movq -8(%rsi,%r10,8),%rax // rax = a[j - 1] ADD_CARRY %r15,%r12 // r12 += hi(a[1] * b[0]) + lo(a[2] * b[0]) movq %r12,-24(%rsp,%r10,8) // t[j - 3] = r13 movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) mulq %rbx // (rdx, rax) = a[j - 1] * b[0] ADD_CARRY %rax,%r14 // r14 = hi[a[2] * b[0]] + lo(a[j - 1] * b[0]) movq -8(%rcx,%r10,8),%rax // rax = n[j - 1] movq %rdx,%r15 // r15 = hi(a[j - 1] * b[0]) mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 1] ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) + lo(t[0] * k0 * n[j - 1] movq (%rsi,%r10,8),%rax // rax = a[j] ADD_CARRY %r14,%rdi // rdi += hi[a[2] * b[0]] + lo(a[j - 1] * b[0]) movq %rdi,-16(%rsp,%r10,8) // t[j - 2] = rdi movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) mulq %rbx // (rdx, rax) = a[j] * b[0] ADD_CARRY %rax,%r15 // r15 = hi(a[j - 1] * b[0]) + lo(a[j] * b[0]) movq (%rcx,%r10,8),%rax // rax = n[j] movq %rdx,%r14 // r14 = hi(a[j] * b[0]) mulq %rbp // (rdx, rax) = t[0] * k0 * n[j] ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) + lo(t[0] * k0 * n[j]) movq 8(%rsi,%r10,8),%rax // rax = a[j + 1] ADD_CARRY %r15,%r12 // r12 += hi(a[j - 1] * b[0]) + lo(a[j] * b[0]) movq %r12,-8(%rsp,%r10,8) // t[j - 1] = r13 movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j]) mulq %rbx // (rdx, rax) = a[j + 1] * b[0] ADD_CARRY %rax,%r14 // r14 = hi(a[j] * b[0]) + lo(a[j + 1] * b[0]) movq 8(%rcx,%r10,8),%rax // rax = n[j + 1] movq %rdx,%r15 // r15 = hi(a[j + 1] * b[0]) mulq %rbp // (rdx, rax) = t[0] * k0 * n[j + 1] ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j]) + lo(t[0] * k0 * n[j + 1]) movq 16(%rsi,%r10,8),%rax // rax = a[j + 2] ADD_CARRY %r14,%rdi // rdi += hi(a[j] * b[0]) + lo(a[j + 1] * b[0]) movq %rdi,(%rsp,%r10,8) // t[j - 4] = rdi movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j + 1]) leaq 4(%r10),%r10 // j += 4 cmpq %r9,%r10 // if size != j jb .Loop1st4x mulq %rbx // (rdx, rax) = a[j - 2] * b[0] ADD_CARRY %rax,%r15 // r15 = hi(a[j - 3] * b[0]) + lo(a[j - 2] * b[0]) movq -16(%rcx,%r10,8),%rax // rax = n[j - 2] movq %rdx,%r14 // r14 = hi(a[j - 2] * b[0]) mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 2] ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 3]) + lo(t[0] * k0 * n[j - 2]) movq -8(%rsi,%r10,8),%rax // rax = a[j - 1] ADD_CARRY %r15,%r12 // r12 += hi(a[j - 3] * b[0]) + lo(a[j - 2] * b[0]) movq %r12,-24(%rsp,%r10,8) // t[j - 3] = r13 movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) mulq %rbx // (rdx, rax) = a[j - 1] * b[0] ADD_CARRY %rax,%r14 // r14 = hi(a[j - 2] * b[0]) + lo(a[j- 1] * b[0]) movq -8(%rcx,%r10,8),%rax // rax = n[j - 1] movq %rdx,%r15 // r15 = hi(a[j - 1] * b[0]) mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 1] ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) + lo(t[0] * k0 * n[j - 1]) ADD_CARRY %r14,%rdi // rdi += hi(a[j - 2] * b[0]) + lo(a[j- 1] * b[0]) movq %rdi,-16(%rsp,%r10,8) // t[j - 2] = rdi movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) xorq %rdx,%rdx // rdx = 0 ADD_CARRY %r15,%r12 // r12 = hi(a[j - 1] * b[0]) + hi(t[0] * k0 * n[j - 1]) movq %r12,-8(%rsp,%r10,8) // t[j - 1] = r13 movq %rdx,(%rsp,%r10,8) // t[j] = CF leaq 1(%r11),%r11 // i++ .align 4 .LoopOuter4x: /* Calculate a[i] * b + q * N */ movq (%rsi),%rax // rax = a[0] movq (%r13,%r11,8),%rbx // rbx = b[i] xorq %r10,%r10 // j = 0 movq (%rsp),%r15 // r15 = t[0] movq %r8,%rbp // rbp = k0 mulq %rbx // (rdx, rax) = a[0] * b[i] ADD_CARRY %rax,%r15 // r15 = lo(a[0] * b[i]) + t[0] movq (%rcx),%rax // rax = n[0] imulq %r15,%rbp // rbp = t[0] * k0 movq %rdx,%r14 // r14 = hi[a[0] * b[i]] mulq %rbp // (rdx, rax) = t[0] * k0 * n[0] ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0]) movq 8(%rsi),%rax // rax = a[1] movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[0]) mulq %rbx // (rdx, rax) = a[1] * b[i] ADD_CARRY %rax,%r14 // r14 = hi[a[0] * b[i]] + lo(a[1] * b[i]) movq 8(%rcx),%rax // rax = n[1] ADD_CARRY 8(%rsp),%r14 // r14 = t[1] movq %rdx,%r15 // r15 = hi(a[1] * b[i]) mulq %rbp // (rdx, rax) = t[0] * k0 * n[1] ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[0]) + lo(t[0] * k0 * n[1]) movq 16(%rsi),%rax // rax = a[2] ADD_CARRY %r14,%rdi // rdi += t[1] leaq 4(%r10),%r10 // j += 4 movq %rdi,(%rsp) // t[0] = rdi movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[1]) .align 16 .Linner4x: mulq %rbx // (rdx, rax) = a[2] * b[i] ADD_CARRY %rax,%r15 // r15 = hi(a[1] * b[i]) + lo(a[2] * b[i]) addq -16(%rsp,%r10,8),%r15 // r15 = t[j - 2] adcq $0,%rdx movq -16(%rcx,%r10,8),%rax // rax = n[j - 2] movq %rdx,%r14 // r14 = hi(a[2] * b[i]) mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 2] ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 3]) * lo(t[0] * k0 * n[j - 2]) ADD_CARRY %r15,%r12 // r12 += t[j - 2] movq %r12,-24(%rsp,%r10,8) // t[j - 3] = r13 movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) movq -8(%rsi,%r10,8),%rax // rax = a[j - 1] mulq %rbx // (rdx, rax) = a[j - 1] * b[i] ADD_CARRY %rax,%r14 // r14 = lo(a[j - 1] * b[i]) addq -8(%rsp,%r10,8),%r14 // r14 += t[j - 1] adcq $0,%rdx movq %rdx,%r15 // r15 = hi(a[j - 1] * b[i]) movq -8(%rcx,%r10,8),%rax // rax = n[j - 1] mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 1] ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) + lo(t[0] * k0 * n[j - 1]) ADD_CARRY %r14,%rdi // rdi += t[j - 1] movq %rdi,-16(%rsp,%r10,8) // t[j - 2] = rdi movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) movq (%rsi,%r10,8),%rax // rax = a[j] mulq %rbx // (rdx, rax) = a[j] * b[i] ADD_CARRY %rax,%r15 // r15 = hi(a[j - 1] * b[i]) + lo(a[j] * b[i]) addq (%rsp,%r10,8),%r15 // r15 = t[j] adcq $0,%rdx movq %rdx,%r14 // r14 = hi(a[j] * b[i]) movq (%rcx,%r10,8),%rax // rax = n[j] mulq %rbp // (rdx, rax) = t[0] * k0 * n[j] ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) + lo(t[0] * k0 * n[j]) ADD_CARRY %r15,%r12 // r12 += t[j] movq %r12,-8(%rsp,%r10,8) // t[j - 1] = r13 movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j]) movq 8(%rsi,%r10,8),%rax // rax = a[j + 1] mulq %rbx // (rdx, rax) = a[j + 1] * b[i] ADD_CARRY %rax,%r14 // r14 = hi(a[j] * b[i]) + lo(a[j + 1] * b[i]) addq 8(%rsp,%r10,8),%r14 // r14 = t[j + 1] adcq $0,%rdx movq %rdx,%r15 // r15 = hi(a[j + 1] * b[i]) movq 8(%rcx,%r10,8),%rax // rax = n[j + 1] mulq %rbp // (rdx, rax) = t[0] * k0 * n[j + 1] ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j]) + lo(t[0] * k0 * n[j + 1]) ADD_CARRY %r14,%rdi // rdi += t[j + 1] movq %rdi,(%rsp,%r10,8) // t[j] = rdi movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j + 1]) movq 16(%rsi,%r10,8),%rax // rax = a[j + 2] leaq 4(%r10),%r10 // j += 4 cmpq %r9,%r10 // if j != size jb .Linner4x mulq %rbx // (rdx, rax) = a[j - 2] * b[i] ADD_CARRY %rax,%r15 // r15 = hi(a[j + 1] * b[i]) + lo(a[j - 2] * b[i]) addq -16(%rsp,%r10,8),%r15 // r15 = t[j - 2] adcq $0,%rdx movq %rdx,%r14 // r14 = hi(a[j - 2] * b[i]) movq -16(%rcx,%r10,8),%rax // rax = n[j - 2] mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 2] ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j + 1]) + lo(t[0] * k0 * n[j - 2]) ADD_CARRY %r15,%r12 // r12 += t[j - 2] movq %r12,-24(%rsp,%r10,8) // t[j - 3] = r13 movq %rdx,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) movq -8(%rsi,%r10,8),%rax // rax = a[j - 1] mulq %rbx // (rdx, rax) = a[j - 1] * b[i] ADD_CARRY %rax,%r14 // r14 = hi(a[j - 2] * b[i]) + lo(a[j - 1] * b[i]) addq -8(%rsp,%r10,8),%r14 // r14 = t[j - 1] adcq $0,%rdx leaq 1(%r11),%r11 // i++ movq %rdx,%r15 // r15 = hi(a[j - 1] * b[i]) movq -8(%rcx,%r10,8),%rax // rax = n[j - 1] mulq %rbp // (rdx, rax) = t[0] * k0 * n[j - 1] ADD_CARRY %rax,%rdi // rdi = hi(t[0] * k0 * n[j - 2]) + lo(t[0] * k0 * n[j - 1]) ADD_CARRY %r14,%rdi // rdi += t[j - 1] movq %rdi,-16(%rsp,%r10,8) // t[j - 2] = rdi movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) xorq %rdx,%rdx // rdi = 0 ADD_CARRY %r15,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) + r10 addq (%rsp,%r9,8),%r12 // r12 += t[size] adcq $0,%rdx movq %r12,-8(%rsp,%r10,8) // t[j - 1] = r13 movq %rdx,(%rsp,%r10,8) // t[j] = CF cmpq %r9,%r11 // if i != size jb .LoopOuter4x movq 16(%rsp,%r9,8),%rdi // rdi = t[size + 2] leaq -4(%r9),%r10 // j = size - 4 movq (%rsp),%rax // rax = t[0] movq 8(%rsp),%rdx // rdx = t[1] shrq $2,%r10 // r10 = (size - 4) / 4 leaq (%rsp),%rsi // rsi = t[0] xorq %r11,%r11 // i = 0 subq (%rcx),%rax // rax = t[0] - n[0] sbbq 8(%rcx),%rdx // rdx = t[1] - (n[1] + CF) movq 16(%rsi),%rbx // rbx = t[2] movq 24(%rsi),%rbp // rbp = t[3] /* 计算 S-N */ .LoopSub4x: movq %rax,(%rdi,%r11,8) // r[i] = n[0] movq %rdx,8(%rdi,%r11,8) // r[i + 1] = n[1] movq 32(%rsi,%r11,8),%rax // rax = t[i + 4] movq 40(%rsi,%r11,8),%rdx // rdx = t[i + 5] sbbq 16(%rcx,%r11,8),%rbx // rbx = t[2] - (n[i + 2] + CF) sbbq 24(%rcx,%r11,8),%rbp // rbp = t[3] - (n[i + 3] + CF) sbbq 32(%rcx,%r11,8),%rax // rax = t[i + 4] - (n[j + 4] + CF) sbbq 40(%rcx,%r11,8),%rdx // rdx = t[i + 5] - (n[i + 5] + CF) movq %rbx,16(%rdi,%r11,8) // r[i + 2] = rbx movq %rbp,24(%rdi,%r11,8) // r[i + 3] = rbp movq 48(%rsi,%r11,8),%rbx // rbx = t[i + 6] movq 56(%rsi,%r11,8),%rbp // rbp = t[i + 7] leaq 4(%r11),%r11 // i += 4 decq %r10 // j-- jnz .LoopSub4x // if j != 0 sbbq 16(%rcx,%r11,8),%rbx // rbx = rbx = t[i + 6] - (n[i + 2] + CF) sbbq 24(%rcx,%r11,8),%rbp // rbp = t[i + 7] - (n[i + 3] + CF) movq %rax,(%rdi,%r11,8) // r[i] = rax movq %rdx,8(%rdi,%r11,8) // r[i + 1] = rdx movq %rbx,16(%rdi,%r11,8) // r[i + 2] = rbx movq %rbp,24(%rdi,%r11,8) // r[i + 3] = rbp movq 32(%rsi,%r11,8),%rax // rax = t[i + 4] sbbq $0,%rax // rax -= CF pxor %xmm2,%xmm2 // xmm0 = 0 movq %rax, %xmm0 pcmpeqd %xmm1,%xmm1 // xmm5 = -1 pshufd $0,%xmm0,%xmm0 movq %r9,%r10 // j = size pxor %xmm0,%xmm1 shrq $2,%r10 // j = size / 4 xorl %eax,%eax // i = 0 .align 16 .LoopCopy4x: movdqa (%rsp,%rax),%xmm5 // Copy the result to r. movdqu (%rdi,%rax),%xmm3 pand %xmm0,%xmm5 pand %xmm1,%xmm3 movdqa 16(%rsp,%rax),%xmm4 movdqa %xmm2,(%rsp,%rax) por %xmm3,%xmm5 movdqu 16(%rdi,%rax),%xmm3 movdqu %xmm5,(%rdi,%rax) pand %xmm0,%xmm4 pand %xmm1,%xmm3 movdqa %xmm2,16(%rsp,%rax) por %xmm3,%xmm4 movdqu %xmm4,16(%rdi,%rax) leaq 32(%rax),%rax decq %r10 // j-- jnz .LoopCopy4x movq 8(%rsp,%r9,8),%rsi // rsi = pressed-stacked rsp. movq $1,%rax leaq (%rsi),%rsp // Restore srsp. RESTORE_REGISTERS ret .cfi_endproc .size MontMul4,.-MontMul4 .type MontSqr8,@function .align 32 MontSqr8: .cfi_startproc SAVE_REGISTERS movq %rsp,%rax movl %r9d,%r15d shll $3,%r9d // Calculate size * 8 bytes. shlq $5,%r15 // size * 8 * 4 negq %r9 leaq -64(%rsp,%r9,2),%r14 // r14 = rsp[size * 2 - 8] subq %rsi,%r14 andq $4095,%r14 movq %rsp,%rbp cmpq %r14,%r15 jae .Loop8xCheckstk leaq 4032(,%r9,2),%r15 // r15 = 4096 - frame - 2 * size subq %r15,%r14 movq $0,%r15 cmovcq %r15,%r14 .Loop8xCheckstk: subq %r14,%rbp leaq -64(%rbp,%r9,2),%rbp // Allocate a frame + 2 x size. andq $-64,%rbp // __checkstk implementation, // which is invoked when the stack size needs to exceed one page. movq %rsp,%r14 subq %rbp,%r14 andq $-4096,%r14 leaq (%r14,%rbp),%rsp cmpq %rbp,%rsp jbe .LoopMul8x .align 16 .LoopPage8x: leaq -4096(%rsp),%rsp // Change sp - 4096 each time until sp <= the space to be allocated cmpq %rbp,%rsp ja .LoopPage8x .LoopMul8x: movq %r9,%r15 // r15 = -size * 8 negq %r9 // Restoresize. movq %r8,32(%rsp) // Save the values of k0 and sp. movq %rax,40(%rsp) movq %rcx, %xmm1 // Pointer to saving n. pxor %xmm2,%xmm2 // xmm0 = 0 movq %rdi, %xmm0 // Pointer to saving r. movq %r15, %xmm5 // Save size. call MontSqr8Inner leaq (%rdi,%r9),%rbx // rbx = t[size] movq %r9,%rcx // rcx = -size movq %r9,%rdx // rdx = -size movq %xmm0, %rdi // rdi = r sarq $5,%rcx // rcx >>= 5 .align 32 /* T -= N */ .LoopSub8x: movq (%rbx),%r13 // r13 = t[i] movq 8(%rbx),%r12 // r12 = t[i + 1] movq 16(%rbx),%r11 // r11 = t[i + 2] movq 24(%rbx),%r10 // r10 = t[i + 3] sbbq (%rbp),%r13 // r13 = t[i] - (n[i] + CF) sbbq 8(%rbp),%r12 // r12 = t[i + 1] - (n[i + 1] + CF) sbbq 16(%rbp),%r11 // r11 = t[i + 2] - (n[i + 2] + CF) sbbq 24(%rbp),%r10 // r10 = t[i + 3] - (n[i + 3] + CF) movq %r13,0(%rdi) // Assigning value to r. movq %r12,8(%rdi) movq %r11,16(%rdi) movq %r10,24(%rdi) leaq 32(%rbp),%rbp // n += 4 leaq 32(%rdi),%rdi // r += 4 leaq 32(%rbx),%rbx // t += 4 incq %rcx jnz .LoopSub8x sbbq $0,%rax // rax -= CF leaq (%rbx,%r9),%rbx leaq (%rdi,%r9),%rdi movq %rax,%xmm0 pxor %xmm2,%xmm2 pshufd $0,%xmm0,%xmm0 movq 40(%rsp),%rsi // rsi = pressed-stacked rsp. .align 32 .LoopCopy8x: movdqa 0(%rbx),%xmm1 // Copy the result to r. movdqa 16(%rbx),%xmm5 leaq 32(%rbx),%rbx movdqu 0(%rdi),%xmm3 movdqu 16(%rdi),%xmm4 leaq 32(%rdi),%rdi movdqa %xmm2,-32(%rbx) movdqa %xmm2,-16(%rbx) movdqa %xmm2,-32(%rbx,%rdx) movdqa %xmm2,-16(%rbx,%rdx) pcmpeqd %xmm0,%xmm2 pand %xmm0,%xmm1 pand %xmm0,%xmm5 pand %xmm2,%xmm3 pand %xmm2,%xmm4 pxor %xmm2,%xmm2 por %xmm1,%xmm3 por %xmm5,%xmm4 movdqu %xmm3,-32(%rdi) movdqu %xmm4,-16(%rdi) addq $32,%r9 jnz .LoopCopy8x movq $1,%rax leaq (%rsi),%rsp // Restore rsp. RESTORE_REGISTERS // Restore non-volatile register. ret .cfi_endproc .size MontSqr8,.-MontSqr8 .type MontSqr8Inner,@function .align 32 MontSqr8Inner: .cfi_startproc leaq 32(%r15),%rbp // i = -size + 32 leaq (%rsi,%r9),%rsi // rsi = a[size] movq %r9,%rcx // j = size movq -32(%rsi,%rbp),%r11 // r11 = a[0] movq -24(%rsi,%rbp),%r10 // r10 = a[1] leaq 56(%rsp,%r9,2),%rdi // rdi = t[2 * size] leaq -16(%rsi,%rbp),%rbx // rbx = a[2] leaq -32(%rdi,%rbp),%rdi // rdi = t[2 * size - i] movq %r10,%rax // rax = a[1] mulq %r11 // (rdx, rax) = a[1] * a[0] movq %rax,%r15 // r15 = lo(a[1] * a[0]) movq %rdx,%r14 // r14 = hi(a[1] * a[0]) movq %r15,-24(%rdi,%rbp) // t[1] = lo(a[1] * a[0]) movq (%rbx),%rax // rax = a[2] mulq %r11 // (rdx, rax) = a[2] * a[0] ADD_CARRY %rax,%r14 // r14 = hi(a[1] * a[0]) + lo(a[2] * a[0]) movq %r14,-16(%rdi,%rbp) // t[2] = hi(a[1] * a[0]) + lo(a[2] * a[0]) movq %rdx,%r15 // r15 = hi(a[2] * a[0]) movq (%rbx),%rax // rax = a[2] mulq %r10 // (rdx, rax) = a[2] * a[1] movq %rax,%r13 // r13 = lo(a[2] * a[1]) movq %rdx,%r12 // r12 = hi(a[2] * a[1]) leaq 8(%rbx),%rbx // rbx = a[3] movq (%rbx),%rax // rax = a[3] mulq %r11 // (rdx, rax) = a[3] * a[0] ADD_CARRY %rax,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0]) ADD_CARRY %r13,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0]) + lo(a[2] * a[1]) movq %rdx,%r14 // r14 = hi(a[3] * a[0]) movq (%rbx),%rax // rax = a[3] leaq (%rbp),%rcx // j = i movq %r15,-8(%rdi,%rcx) // t[3] = hi(a[2] * a[0]) + lo(a[3] * a[0]) + lo(a[2] * a[1]) .align 32 .Loop1stSqr4x: leaq (%rsi,%rcx),%rbx // rbx = a[4] mulq %r10 // (rdx, rax) = a[3] * a[1] ADD_CARRY %rax,%r12 // r12 = hi(a[2] * a[1]) + lo(a[3] * a[1]) movq %rdx,%r13 // r13 = hi(a[3] * a[1]) movq (%rbx),%rax // rax = a[4] mulq %r11 // (rdx, rax) = a[4] * a[0] ADD_CARRY %rax,%r14 // r14 = hi(a[3] * a[0]) + lo(a[4] * a[0]) ADD_CARRY %r12,%r14 // r14 = hi(a[3] * a[0]) + lo(a[4] * a[0]) + lo(a[3] * a[1]) movq (%rbx),%rax // rax = a[4] movq %rdx,%r15 // r15 = hi(a[4] * a[0]) mulq %r10 // (rdx, rax) = a[4] * a[1] ADD_CARRY %rax,%r13 // r13 = hi(a[3] * a[1]) + lo(a[4] * a[1]) movq %r14,(%rdi,%rcx) // t[4] = hi(a[3] * a[0]) + lo(a[4] * a[0]) + lo(a[3] * a[1]) movq %rdx,%r12 // r12 = hi(a[4] * a[1]) leaq 8(%rbx),%rbx // rbx = a[5] movq (%rbx),%rax // rax = a[5] mulq %r11 // (rdx, rax) = a[5] * a[0] ADD_CARRY %rax,%r15 // r15 = hi(a[4] * a[0]) + lo(a[5] * a[0]) ADD_CARRY %r13,%r15 // r15 = hi(a[4] * a[0]) + lo(a[5] * a[0]) + hi(a[3] * a[1]) + lo(a[4] * a[1]) movq (%rbx),%rax // rax = a[5] movq %rdx,%r14 // r14 = hi(a[5] * a[0]) mulq %r10 // (rdx, rax) = a[5] * a[1] ADD_CARRY %rax,%r12 // r12 = hi(a[4] * a[1]) + lo(a[5] * a[1]) movq %r15,8(%rdi,%rcx) // t[5] = r10 movq %rdx,%r13 // r13 = hi(a[5] * a[1]) leaq 8(%rbx),%rbx // rbx = a[6] movq (%rbx),%rax // rax = a[6] mulq %r11 // (rdx, rax) = a[6] * a[0] ADD_CARRY %rax,%r14 // r14 = hi(a[5] * a[0]) + lo(a[6] * a[0]) ADD_CARRY %r12,%r14 // r14 = hi(a[5] * a[0]) + lo(a[6] * a[0]) + hi(a[4] * a[1]) + lo(a[5] * a[1]) movq (%rbx),%rax // rax = a[6] movq %rdx,%r15 // r15 = hi(a[6] * a[0]) mulq %r10 // (rdx, rax) = a[6] * a[1] ADD_CARRY %rax,%r13 // r13 = lo(a[6] * a[1]) movq %r14,16(%rdi,%rcx) // t[6] = r11 movq %rdx,%r12 // r12 = hi(a[6] * a[1]) leaq 8(%rbx),%rbx // rbx = a[7] movq (%rbx),%rax // rax = a[7] mulq %r11 // (rdx, rax) = a[7] * a[0] ADD_CARRY %rax,%r15 // r15 = hi(a[6] * a[0]) + lo(a[7] * a[0]) ADD_CARRY %r13,%r15 // r15 = hi(a[6] * a[0]) + lo(a[7] * a[0]) + lo(a[6] * a[1]) movq %r15,24(%rdi,%rcx) // t[7] = hi(a[6] * a[0]) + lo(a[7] * a[0]) + lo(a[6] * a[1]) movq %rdx,%r14 // r14 = hi(a[7] * a[0]) movq (%rbx),%rax // rax = a[7] leaq 32(%rcx),%rcx // j += 2 cmpq $0,%rcx // if j != 0 jne .Loop1stSqr4x mulq %r10 // (rdx, rax) = a[7] * a[1] ADD_CARRY %rax,%r12 // r12 = hi(a[6] * a[1]) + lo(a[7] * a[1]) leaq 16(%rbp),%rbp // i++ ADD_CARRY %r14,%r12 // r12 = hi(a[6] * a[1]) + hi(a[7] * a[0]) + lo(a[7] * a[1]) movq %r12,(%rdi) // t[8] = r13 movq %rdx,%r13 // r13 = hi(a[7] * a[1]) movq %rdx,8(%rdi) // t[9] = hi(a[7] * a[1]) .align 32 .LoopOuterSqr4x: movq -32(%rsi,%rbp),%r11 // r11 = a[0] movq -24(%rsi,%rbp),%r10 // r10 = a[1] leaq -16(%rsi,%rbp),%rbx // rbx = a[2] leaq 56(%rsp,%r9,2),%rdi // rdi = t[size * 2 - i] leaq -32(%rdi,%rbp),%rdi movq %r10,%rax // rax = a[1] mulq %r11 // (rdx, rax) = a[1] * a[0] movq -24(%rdi,%rbp),%r15 // r15 = t[1] ADD_CARRY %rax,%r15 // r15 = lo(a[1] * a[0]) + t[1] movq %r15,-24(%rdi,%rbp) // t[1] = r10 movq %rdx,%r14 // r14 = hi(a[1] * a[0]) movq (%rbx),%rax // rax = a[2] mulq %r11 // (rdx, rax) = a[2] * a[0] ADD_CARRY %rax,%r14 // r14 = hi(a[1] * a[0]) + lo(a[2] * a[0]) addq -16(%rdi,%rbp),%r14 // r14 = hi(a[1] * a[0]) + lo(a[2] * a[0]) + t[2] adcq $0,%rdx // r10 += CF movq %rdx,%r15 // r10 = hi(a[2] * a[0]) movq %r14,-16(%rdi,%rbp) // t[2] = r11 xorq %r13,%r13 // Clear CF. movq (%rbx),%rax // rax = a[2] mulq %r10 // (rdx, rax) = a[2] * a[1] ADD_CARRY %rax,%r13 // r13 = lo(a[2] * a[1]) addq -8(%rdi,%rbp),%r13 // r13 = lo(a[2] * a[1]) + t[3] adcq $0,%rdx movq %rdx,%r12 // r12 = hi(a[2] * a[1]) leaq 8(%rbx),%rbx // rbx = a[3] movq (%rbx),%rax // rax = a[3] mulq %r11 // (rdx, rax) = a[3] * a[0] ADD_CARRY %rax,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0]) ADD_CARRY %r13,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0]) + lo(a[2] * a[1]) + t[3] movq (%rbx),%rax // rax = a[3] leaq (%rbp),%rcx // j = i movq %r15,-8(%rdi,%rbp) // t[3] = r10 movq %rdx,%r14 // r14 = hi(a[3] * a[0]) .align 32 .LoopInnerSqr4x: leaq (%rsi,%rcx),%rbx // rbx = a[4] mulq %r10 // (rdx, rax) = a[3] * a[1] ADD_CARRY %rax,%r12 // r12 = hi(a[2] * a[1]) + lo(a[3] * a[1]) movq (%rbx),%rax // rax = a[4] movq %rdx,%r13 // r13 = hi(a[3] * a[1]) addq (%rdi,%rcx),%r12 // r12 = hi(a[2] * a[1]) + lo(a[3] * a[1]) + t[4] adcq $0,%rdx // r13 += CF movq %rdx,%r13 // r13 = hi(a[3] * a[1]) mulq %r11 // (rdx, rax) = a[4] * a[0] ADD_CARRY %rax,%r14 // r14 = hi(a[3] * a[0]) + lo(a[4] * a[0]) ADD_CARRY %r12,%r14 // r14 = hi(a[3] * a[0]) + lo(a[4] * a[0]) + hi(a[2] * a[1]) + lo(a[3] * a[1]) + t[4] movq %r14,(%rdi,%rcx) // t[4] = r11 movq %rdx,%r15 // r15 = hi(a[4] * a[0]) movq (%rbx),%rax // rax = a[4] mulq %r10 // (rdx, rax) = a[4] * a[1] ADD_CARRY %rax,%r13 // r13 = hi(a[3] * a[1]) + lo(a[4] * a[1]) addq 8(%rdi,%rcx),%r13 // r13 = hi(a[3] * a[1]) + lo(a[4] * a[1]) + t[5] adcq $0,%rdx // r12 += CF leaq 8(%rbx),%rbx // rbx = a[5] movq (%rbx),%rax // rax = a[5] movq %rdx,%r12 // r12 = hi(a[4] * a[1]) mulq %r11 // (rdx, rax) = a[5] * a[0] ADD_CARRY %rax,%r15 // r15 = hi(a[4] * a[0]) + lo(a[5] * a[0]) ADD_CARRY %r13,%r15 // r15 = hi(a[4] * a[0]) + lo(a[5] * a[0]) + hi(a[3] * a[1]) + lo(a[4] * a[1]) + t[5] movq %r15,8(%rdi,%rcx) // t[5] = r10 movq %rdx,%r14 // r14 = hi(a[5] * a[0]) movq (%rbx),%rax // rax = a[5] leaq 16(%rcx),%rcx // j++ cmpq $0,%rcx // if j != 0 jne .LoopInnerSqr4x mulq %r10 // (rdx, rax) = a[5] * a[1] ADD_CARRY %rax,%r12 // r12 = hi(a[4] * a[1]) + lo(a[5] * a[1]) ADD_CARRY %r14,%r12 // r12 = hi(a[4] * a[1]) + lo(a[5] * a[1]) + hi(a[5] * a[0]) movq %r12,(%rdi) // t[6] = r13 movq %rdx,%r13 // r13 = hi(a[5] * a[1]) movq %rdx,8(%rdi) // t[7] = hi(a[5] * a[1]) addq $16,%rbp // i++ jnz .LoopOuterSqr4x // if i != 0 movq -32(%rsi),%r11 // r11 = a[0] leaq 56(%rsp,%r9,2),%rdi // rdi = t[2 * size] movq -24(%rsi),%rax // rax = a[1] leaq -32(%rdi,%rbp),%rdi // rdi = t[2 * size - i] movq -16(%rsi),%rbx // rbx = a[2] movq %rax,%r10 // r10 = a[1] mulq %r11 // (rdx, rax) = a[1] * a[0] ADD_CARRY %rax,%r15 // r15 = lo(a[1] * a[0]) + t[1] movq %rbx,%rax // rax = a[2] movq %rdx,%r14 // r14 = hi(a[1] * a[0]) mulq %r11 // (rdx, rax) = a[2] * a[0] ADD_CARRY %rax,%r14 // r14 = hi(a[1] * a[0]) + lo(a[2] * a[0]) movq %r15,-24(%rdi) // t[1] = r10 ADD_CARRY %r12,%r14 // r14 = lo(a[2] * a[0]) + t[2] movq %rbx,%rax // rax = a[2] movq %rdx,%r15 // r15 = hi(a[2] * a[0]) mulq %r10 // (rdx, rax) = a[2] * a[1] ADD_CARRY %rax,%r13 // r13 = lo(a[2] * a[1]) + t[3] movq %r14,-16(%rdi) // t[2] = r11 movq %rdx,%r12 // r12 = hi(a[2] * a[1]) movq -8(%rsi),%rbx // rbx = a[3] movq %rbx,%rax // rax = a[3] mulq %r11 // (rdx, rax) = a[3] * a[0] ADD_CARRY %rax,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0]) ADD_CARRY %r13,%r15 // r15 = hi(a[2] * a[0]) + lo(a[3] * a[0]) + lo(a[2] * a[1]) + t[3] movq %rbx,%rax // rax = a[3] movq %r15,-8(%rdi) // t[3] = r10 movq %rdx,%r14 // r14 = hi(a[3] * a[0]) mulq %r10 // (rdx, rax) = a[3] * a[1] ADD_CARRY %rax,%r12 // r12 = hi(a[2] * a[1]) + lo(a[3] * a[1]) ADD_CARRY %r14,%r12 // r12 = hi(a[3] * a[0]) + hi(a[2] * a[1]) + lo(a[3] * a[1]) movq %r12,(%rdi) // t[4] = r13 movq %rdx,%r13 // r13 = hi(a[3] * a[1]) movq %rdx,8(%rdi) // t[5] = hi(a[3] * a[1]) movq -16(%rsi),%rax // rax = a[2] mulq %rbx // (rdx, rax) = a[3] * a[2] addq $16,%rbp xorq %r11,%r11 subq %r9,%rbp // i = 16 - size xorq %r10,%r10 ADD_CARRY %r13,%rax // rax = hi(a[3] * a[1]) + lo(a[3] * a[2]) movq %rax,8(%rdi) // t[5] = hi(a[3] * a[1]) + lo(a[3] * a[2]) movq %rdx,16(%rdi) // t[6] = hi(a[3] * a[2]) movq %r10,24(%rdi) // t[7] = 0 movq -16(%rsi,%rbp),%rax // rax = a[0] leaq 56(%rsp),%rdi // rdi = t[0] xorq %r15,%r15 movq 8(%rdi),%r14 // r14 = t[1] leaq (%r11,%r15,2),%r13 shrq $63,%r15 // Cyclically shifts 63 bits to the right to obtain the lower bits. leaq (%rcx,%r14,2),%r12 // r12 = t[1] * 2 shrq $63,%r14 // r14 = t[1] >> 63 orq %r15,%r12 // r12 = t[1] * 2 movq 16(%rdi),%r15 // r15 = t[2] movq %r14,%r11 // r11 = t[1] >> 63 mulq %rax // (rdx, rax) = a[0] * a[0] negq %r10 // If the value is not 0, CF is set to 1. adcq %rax,%r13 // r13 = lo(a[0] * a[0]) movq 24(%rdi),%r14 // r14 = t[3] movq %r13,(%rdi) // t[0] = 0 adcq %rdx,%r12 // r12 = t[1] * 2 + hi(a[0] * a[0]) leaq (%r11,%r15,2),%rbx // rbx = t[2] * 2 + t[1] >> 63 movq -8(%rsi,%rbp),%rax // rax = a[1] movq %r12,8(%rdi) // t[1] = t[1] * 2 + hi(a[0] * a[0]) sbbq %r10,%r10 // r10 = -CF clear CF shrq $63,%r15 // r15 = t[2] >> 63 leaq (%rcx,%r14,2),%r8 // r8 = t[3] * 2 shrq $63,%r14 // r14 = t[3] >> 63 orq %r15,%r8 // r8 = (t[3] * 2) + (t[2] >> 63) movq 32(%rdi),%r15 // r15 = t[4] movq %r14,%r11 // r11 = t[3] >> 63 mulq %rax // (rdx, rax) = a[1] * a[1] negq %r10 // If the value is not 0, CF is set to 1. movq 40(%rdi),%r14 // r14 = t[5] adcq %rax,%rbx // rbx = t[2] * 2 + t[1] >> 63 + lo(a[1] * a[1]) movq (%rsi,%rbp),%rax // rax = a[2] movq %rbx,16(%rdi) // t[2] = t[2] * 2 + t[1] >> 63 + lo(a[1] * a[1]) adcq %rdx,%r8 // r8 = t[3] * 2 + t[2] >> 63 + hi(a[1] * a[1]) leaq 16(%rbp),%rbp // i++ movq %r8,24(%rdi) // t[3] = r8 sbbq %r10,%r10 // r10 = -CF clear CF. leaq 64(%rdi),%rdi // t += 64 .align 32 .LoopShiftAddSqr4x: leaq (%r11,%r15,2),%r13 // r13 = t[4] * 2 + t[3] >> 63 shrq $63,%r15 // r15 = t[4] >> 63 leaq (%rcx,%r14,2),%r12 // r12 = t[5] * 2 shrq $63,%r14 // r14 = t[5] >> 63 orq %r15,%r12 // r12 = (t[5] * 2) + t[4] >> 63 movq -16(%rdi),%r15 // r15 = t[6] movq %r14,%r11 // r11 = t[5] >> 63 mulq %rax // (rdx, rax) = a[2] * a[2] negq %r10 // r10 = CF movq -8(%rdi),%r14 // r14 = t[7] adcq %rax,%r13 // r13 = t[4] * 2 + t[3] >> 63 + lo(a[2] * a[2]) movq %r13,-32(%rdi) // t[4] = r12 adcq %rdx,%r12 // r12 = (t[5] * 2) + t[4] >> 63 + hi(a[2] * a[2]) leaq (%r11,%r15,2),%rbx // rbx = t[6] * 2 + t[5] >> 63 movq -8(%rsi,%rbp),%rax // rax = a[3] movq %r12,-24(%rdi) // t[5] = hi(a[2] * a[2]) sbbq %r10,%r10 // r10 = -CF shrq $63,%r15 // r15 = t[6] >> 63 leaq (%rcx,%r14,2),%r8 // r8 = t[7] * 2 shrq $63,%r14 // r14 = t[7] >> 63 orq %r15,%r8 // r8 = t[7] * 2 + t[6] >> 63 movq 0(%rdi),%r15 // r15 = t[8] movq %r14,%r11 // r11 = t[7] >> 63 mulq %rax // (rdx, rax) = a[3] * a[3] negq %r10 // r10 = CF movq 8(%rdi),%r14 // r14 = t[9] adcq %rax,%rbx // rbx = t[6] * 2 + t[5] >> 63 + lo(a[3] * a[3]) movq %rbx,-16(%rdi) // t[6] = rbx adcq %rdx,%r8 // r8 = t[7] * 2 + t[6] >> 63 + hi(a[3] * a[3]) leaq (%r11,%r15,2),%r13 // r13 = t[8] * 2 + t[7] >> 63 movq %r8,-8(%rdi) // t[7] = hi(a[3] * a[3]) movq (%rsi,%rbp),%rax // rax = a[4] sbbq %r10,%r10 // r10 = -CF shrq $63,%r15 // r15 = t[8] >> 63 leaq (%rcx,%r14,2),%r12 // r12 = t[9] * 2 shrq $63,%r14 // r14 = t[9] >> 63 orq %r15,%r12 // r12 = t[9] * 2 + t[8] >> 63 movq 16(%rdi),%r15 // r15 = t[10] movq %r14,%r11 // r11 = t[9] >> 63 mulq %rax // (rdx, rax) = a[4] * a[4] negq %r10 // r10 = -CF movq 24(%rdi),%r14 // r14 = t[11] adcq %rax,%r13 // r13 = t[8] * 2 + t[7] >> 63 + lo(a[4] * a[4]) movq %r13,(%rdi) // t[8] = r12 adcq %rdx,%r12 // r12 = t[9] * 2 + t[8] >> 63 + hi(a[4] * a[4]) leaq (%r11,%r15,2),%rbx // rbx = t[10] * 2 + t[9] >> 63 movq 8(%rsi,%rbp),%rax // rax = a[5] movq %r12,8(%rdi) // t[9] = r13 sbbq %r10,%r10 // r10 = -CF shrq $63,%r15 // r15 = t[10] >> 63 leaq (%rcx,%r14,2),%r8 // r8 = t[11] * 2 shrq $63,%r14 // r14 = t[11] >> 63 orq %r15,%r8 // r8 = t[11] * 2 + t[10] >> 63 movq 32(%rdi),%r15 // r15 = t[12] movq %r14,%r11 // r11 = t[11] >> 63 mulq %rax // (rdx, rax) = a[5] * a[5] negq %r10 // r10 = CF movq 40(%rdi),%r14 // r14 = t[13] adcq %rax,%rbx // rbx = t[10] * 2 + t[9] >> 63 + lo(a[5] * a[5]) movq 16(%rsi,%rbp),%rax // rax = a[6] movq %rbx,16(%rdi) // t[10] = rbx adcq %rdx,%r8 // r8 = t[11] * 2 + t[10] >> 63 + hi(a[5] * a[5]) movq %r8,24(%rdi) // t[11] = r8 sbbq %r10,%r10 // r10 = -CF leaq 64(%rdi),%rdi // t += 64 addq $32,%rbp // i += 4 jnz .LoopShiftAddSqr4x // if i != 0 leaq (%r11,%r15,2),%r13 // r13 = t[12] * 2 + t[11] >> 63 shrq $63,%r15 // r15 = t[12] >> 63 leaq (%rcx,%r14,2),%r12 // r12 = t[13] * 2 shrq $63,%r14 // r14 = t[13] >> 63 orq %r15,%r12 // r12 = t[13] * 2 + t[12] >> 63 movq -16(%rdi),%r15 // r15 = t[14] movq %r14,%r11 // r11 = t[13] >> 63 mulq %rax // (rdx, rax) = a[6] * a[6] negq %r10 // r10 = CF movq -8(%rdi),%r14 // r14 = t[15] adcq %rax,%r13 // r13 = t[12] * 2 + t[11] >> 63 + lo(a[6] * a[6]) movq %r13,-32(%rdi) // t[12] = r12 adcq %rdx,%r12 // r12 = t[13] * 2 + t[12] >> 63 + hi(a[6] * a[6]) leaq (%r11,%r15,2),%rbx // rbx = t[14] * 2 + t[13] >> 63 movq -8(%rsi),%rax // rax = a[7] movq %r12,-24(%rdi) // t[13] = r13 sbbq %r10,%r10 // r10 = -CF shrq $63,%r15 // r15 = t[14] >> 63 leaq (%rcx,%r14,2),%r8 // r8 = t[15] * 2 shrq $63,%r14 // r14 = t[15] >> 63 orq %r15,%r8 // r8 = t[15] * 2 + t[14] >> 63 mulq %rax // (rdx, rax) = a[7] * a[7] negq %r10 // r10 = CF adcq %rax,%rbx // rbx = t[14] * 2 + t[13] >> 63 + lo(a[7] * a[7]) adcq %rdx,%r8 // r8 = t[15] * 2 + t[14] >> 63 + hi(a[7] * a[7]) movq %rbx,-16(%rdi) // t[14] = rbx movq %r8,-8(%rdi) // t[15] = r8 movq %xmm1,%rbp // rbp = n xorq %rax,%rax // rax = 0 leaq (%r9,%rbp),%rcx // rcx = n[size] leaq 56(%rsp,%r9,2),%rdx // rdx = t[size * 2] movq %rcx,8(%rsp) leaq 56(%rsp,%r9),%rdi movq %rdx,16(%rsp) negq %r9 .align 32 .LoopReduceSqr8x: leaq (%rdi,%r9),%rdi // rdi = t[] movq (%rdi),%rbx // rbx = t[0] movq 8(%rdi),%r9 // r9 = t[1] movq 16(%rdi),%r15 // r15 = t[2] movq 24(%rdi),%r14 // r14 = t[3] movq 32(%rdi),%r13 // r13 = t[4] movq 40(%rdi),%r12 // r12 = t[5] movq 48(%rdi),%r11 // r11 = t[6] movq 56(%rdi),%r10 // r10 = t[7] movq %rax,(%rdx) // Store the highest carry bit. leaq 64(%rdi),%rdi // rdi = t[8] movq %rbx,%r8 // r8 = t[0] imulq 40(%rsp),%rbx // rbx = k0 * t[0] movl $8,%ecx .align 32 .LoopReduce8x: movq (%rbp),%rax // rax = n[0] mulq %rbx // (rdx, rax) = t[0] * k0 * n[0] negq %r8 // r8 = -t[0], If t[0] is not 0, set CF to 1. movq %rdx,%r8 // r8 = hi(t[0] * k0 * n[0]) adcq $0,%r8 // r8 += CF movq 8(%rbp),%rax // rax = n[1] mulq %rbx // (rdx, rax) = t[0] * k0 * n[1] movq %rbx,48(%rsp,%rcx,8) ADD_CARRY %rax,%r9 // r9 = t[1] + lo(t[0] * k0 * n[1]) ADD_CARRY %r9,%r8 // r8 = hi(t[0] * k0 * n[0]) + lo(t[0] * k0 * n[1]) + t[1] movq 16(%rbp),%rax // rax = n[2] movq %rdx,%r9 // r9 = hi(t[0] * k0 * n[1]) mulq %rbx // (rdx, rax) = t[0] * k0 * n[2] ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[2]) + t[2] ADD_CARRY %r15,%r9 // r9 = hi(t[0] * k0 * n[1]) + lo(t[0] * k0 * n[2]) + t[2] movq 40(%rsp),%rsi // rsi = k0 movq %rdx,%r15 // r15 = hi(t[0] * k0 * n[2]) movq 24(%rbp),%rax // rax = n[3] mulq %rbx // (rdx, rax) = t[0] * k0 * n[3] ADD_CARRY %rax,%r14 // r14 = lo(t[0] * k0 * n[3]) imulq %r8,%rsi // rsi = k0 * r8 ADD_CARRY %r14,%r15 // r15 = hi(t[0] * k0 * n[2]) + lo(t[0] * k0 * n[3]) movq %rdx,%r14 // r14 = hi(t[0] * k0 * n[3]) movq 32(%rbp),%rax // rax = n[4] mulq %rbx // (rdx, rax) = t[0] * k0 * n[4] ADD_CARRY %rax,%r13 // r13 = lo(t[0] * k0 * n[4]) + t[4] ADD_CARRY %r13,%r14 // r14 = hi(t[0] * k0 * n[3]) + lo(t[0] * k0 * n[4]) + t[4]、 movq 40(%rbp),%rax // rax = n[5] movq %rdx,%r13 // r13 = hi(t[0] * k0 * n[4]) mulq %rbx // (rdx, rax) = t[0] * k0 * n[5] ADD_CARRY %rax,%r12 // r12 = lo(t[0] * k0 * n[5]) + t[5] ADD_CARRY %r12,%r13 // r13 = hi(t[0] * k0 * n[4]) + lo(t[0] * k0 * n[5]) + t[5] movq 48(%rbp),%rax // rax = n[6] movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[5]) mulq %rbx // (rdx, rax) = t[0] * k0 * n[6] ADD_CARRY %rax,%r11 // r11 = lo(t[0] * k0 * n[6]) + t[6] ADD_CARRY %r11,%r12 // r12 = hi(t[0] * k0 * n[5]) + lo(t[0] * k0 * n[6]) + t[6] movq 56(%rbp),%rax // rax = n[7] movq %rdx,%r11 // r11 = hi(t[0] * k0 * n[6]) mulq %rbx // (rdx, rax) = t[0] * k0 * n[7] movq %rsi,%rbx // rbx = k0 * r8 ADD_CARRY %rax,%r10 // r10 = lo(t[0] * k0 * n[7]) + t[7] ADD_CARRY %r10,%r11 // r11 = hi(t[0] * k0 * n[6]) + lo(t[0] * k0 * n[7]) + t[7] movq %rdx,%r10 // r10 = hi(t[0] * k0 * n[7]) decl %ecx // ecx-- jnz .LoopReduce8x // if ecx != 0 leaq 64(%rbp),%rbp // rbp += 64, n Pointer Offset. xorq %rax,%rax // rax = 0 movq 16(%rsp),%rdx // rdx = t[size * 2] cmpq 8(%rsp),%rbp // rbp = n[size] jae .LoopEndCondMul8x addq (%rdi),%r8 // r8 += t[0] adcq 8(%rdi),%r9 // r9 += t[1] adcq 16(%rdi),%r15 // r15 += t[2] adcq 24(%rdi),%r14 // r14 += t[3] adcq 32(%rdi),%r13 // r13 += t[4] adcq 40(%rdi),%r12 // r12 += t[5] adcq 48(%rdi),%r11 // r11 += t[6] adcq 56(%rdi),%r10 // r10 += t[7] sbbq %rsi,%rsi // rsi = -CF movq 112(%rsp),%rbx // rbx = t[0] * k0, 48 + 56 + 8 movl $8,%ecx .align 32 .LoopLastSqr8x: movq (%rbp),%rax // rax = n[0] mulq %rbx // (rdx, rax) = t[0] * k0 * n[0] ADD_CARRY %rax,%r8 // r8 += lo(t[0] * k0 * n[0]) movq %r8,(%rdi) // t[0] = r8 leaq 8(%rdi),%rdi // t++ movq %rdx,%r8 // r8 = hi(t[0] * k0 * n[0]) movq 8(%rbp),%rax // rax = n[1] mulq %rbx // (rdx, rax) = t[0] * k0 * n[1] ADD_CARRY %rax,%r9 // r9 += lo(t[0] * k0 * n[1]) ADD_CARRY %r9,%r8 // r8 = hi(t[0] * k0 * n[0]) + r9 movq 16(%rbp),%rax // rax = n[2] movq %rdx,%r9 // r9 = hi(t[0] * k0 * n[1]) mulq %rbx // (rdx, rax) = t[0] * k0 * n[2] ADD_CARRY %rax,%r15 // r15 += lo(t[0] * k0 * n[2]) ADD_CARRY %r15,%r9 // r9 = hi(t[0] * k0 * n[1]) + r10 movq 24(%rbp),%rax // rax = n[3] movq %rdx,%r15 // r15 = hi(t[0] * k0 * n[2]) mulq %rbx // (rdx, rax) = t[0] * k0 * n[3] ADD_CARRY %rax,%r14 // r14 += lo(t[0] * k0 * n[3]) ADD_CARRY %r14,%r15 // r15 = hi(t[0] * k0 * n[2]) + r11 movq 32(%rbp),%rax // rax = n[4] movq %rdx,%r14 // r14 = hi(t[0] * k0 * n[3]) mulq %rbx // (rdx, rax) = t[0] * k0 * n[4] ADD_CARRY %rax,%r13 // r13 += lo(t[0] * k0 * n[4]) ADD_CARRY %r13,%r14 // r14 = hi(t[0] * k0 * n[3]) + r12 movq 40(%rbp),%rax // rax = n[5] movq %rdx,%r13 // r13 = hi(t[0] * k0 * n[4]) mulq %rbx // (rdx, rax) = t[0] * k0 * n[5] ADD_CARRY %rax,%r12 // r12 += lo(t[0] * k0 * n[5]) ADD_CARRY %r12,%r13 // r13 = hi(t[0] * k0 * n[4]) + r13 movq 48(%rbp),%rax // rax = n[6] movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[5]) mulq %rbx // (rdx, rax) = t[0] * k0 * n[6] ADD_CARRY %rax,%r11 // r11 += lo(t[0] * k0 * n[6]) ADD_CARRY %r11,%r12 // r12 = hi(t[0] * k0 * n[5]) + r14 movq 56(%rbp),%rax // rax = n[7] movq %rdx,%r11 // r11 = hi(t[0] * k0 * n[6]) mulq %rbx // (rdx, rax) = t[0] * k0 * n[7] movq 40(%rsp,%rcx,8),%rbx // rbx = t[i] * k0 ADD_CARRY %rax,%r10 // r10 += lo(t[0] * k0 * n[7]) ADD_CARRY %r10,%r11 // r11 = hi(t[0] * k0 * n[6]) + r10 movq %rdx,%r10 // r10 = hi(t[0] * k0 * n[7]) decl %ecx // ecx-- jnz .LoopLastSqr8x // if ecx != 0 leaq 64(%rbp),%rbp // n += 8 movq 16(%rsp),%rdx // rdx = t[size * 2] cmpq 8(%rsp),%rbp // Check whether rbp is at the end of the n array. If yes, exit the loop. jae .LoopSqrBreak8x movq 112(%rsp),%rbx // rbx = t[0] * k0 negq %rsi // rsi = CF movq (%rbp),%rax // rax = = n[0] adcq (%rdi),%r8 // r8 = t[0] adcq 8(%rdi),%r9 // r9 = t[1] adcq 16(%rdi),%r15 // r15 = t[2] adcq 24(%rdi),%r14 // r14 = t[3] adcq 32(%rdi),%r13 // r13 = t[4] adcq 40(%rdi),%r12 // r12 = t[5] adcq 48(%rdi),%r11 // r11 = t[6] adcq 56(%rdi),%r10 // r10 = t[7] sbbq %rsi,%rsi // rsi = -CF movl $8,%ecx // ecx = 8 jmp .LoopLastSqr8x .align 32 .LoopSqrBreak8x: xorq %rax,%rax // rax = 0 addq (%rdx),%r8 // r8 += Highest carry bit. adcq $0,%r9 // r9 += CF adcq $0,%r15 // r15 += CF adcq $0,%r14 // r14 += CF adcq $0,%r13 // r13 += CF adcq $0,%r12 // r12 += CF adcq $0,%r11 // r11 += CF adcq $0,%r10 // r10 += CF adcq $0,%rax // rax += CF negq %rsi // rsi = CF .LoopEndCondMul8x: adcq (%rdi),%r8 // r8 += t[0] adcq 8(%rdi),%r9 // r9 += t[1] adcq 16(%rdi),%r15 // r15 += t[2] adcq 24(%rdi),%r14 // r14 += t[3] adcq 32(%rdi),%r13 // r13 += t[4] adcq 40(%rdi),%r12 // r12 += t[5] adcq 48(%rdi),%r11 // r11 += t[6] adcq 56(%rdi),%r10 // r10 += t[7] adcq $0,%rax // rax += CF movq -8(%rbp),%rcx // rcx = n[7] xorq %rsi,%rsi // rsi = 0 movq %xmm1,%rbp // rbp = n movq %r8,(%rdi) // Save the calculated result back to t[]. movq %r9,8(%rdi) movq %xmm5,%r9 movq %r15,16(%rdi) movq %r14,24(%rdi) movq %r13,32(%rdi) movq %r12,40(%rdi) movq %r11,48(%rdi) movq %r10,56(%rdi) leaq 64(%rdi),%rdi // t += 8 cmpq %rdx,%rdi // Cycle the entire t[]. jb .LoopReduceSqr8x ret .cfi_endproc .size MontSqr8Inner,.-MontSqr8Inner #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/asm/bn_mont_x86_64.S
Unix Assembly
unknown
61,353
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN .file "bn_mont_x86_64.S" .text .macro ADD_CARRY a b addq \a,\b adcq $0,%rdx .endm .macro SAVE_REGISTERS pushq %r15 // Save non-volatile register. pushq %r14 pushq %r13 pushq %r12 pushq %rbp pushq %rbx .endm .macro RESTORE_REGISTERS popq %rbx // Restore non-volatile register. popq %rbp popq %r12 popq %r13 popq %r14 popq %r15 .endm /* * void MontMulx_Asm(uint64_t *r, const uint64_t *a, const uint64_t *b, * const uint64_t *n, const uint64_t k0, uint32_t size); */ .globl MontMulx_Asm .type MontMulx_Asm,@function .align 16 MontMulx_Asm: .cfi_startproc testl $3,%r9d jnz .LMontMul // If size is not divisible by 4, LMontMul. cmpl $8,%r9d jb .LMontMul // LMontMul cmpq %rsi,%rdx jne MontMul4x // if a != b, MontMul4x testl $7,%r9d jz MontSqr8x // If size is divisible by 8,enter MontSqr8x. jmp MontMul4x .align 16 .LMontMul: SAVE_REGISTERS // Save non-volatile register. movq %rsp,%rax // rax stores the rsp movq %r9, %r15 negq %r15 // r15 = -size leaq -16(%rsp, %r15, 8), %r15 // r15 = rsp - size * 8 - 16 andq $-1024, %r15 // r15 The address is aligned down by 1 KB. movq %rsp, %r14 // r14 = rsp subq %r15,%r14 // __chkstk implemention, called when the stack size needs to exceed 4096. // (the size of a page) to allocate more pages. andq $-4096,%r14 // r14 4K down-align. leaq (%r15,%r14),%rsp // rsp = r15 + r14 cmpq %r15,%rsp // If you want to allocate more than one page, go to Lmul_page_walk. ja .LoopPage jmp .LMulBody .align 16 .LoopPage: leaq -4096(%rsp),%rsp // rsp - 4096 each time until rsp < r15. cmpq %r15,%rsp ja .LoopPage .LMulBody: movq %rax,8(%rsp,%r9,8) // Save the original rsp in the stack. movq %rdx,%r13 // r13 = b xorq %r11,%r11 // r11 = 0 xorq %r10,%r10 // r10 = 0 movq (%r13),%rbx // rbx = b[0] movq (%rsi),%rax // rax = a[0] mulq %rbx // (rdx, rax) = a[0] * b[0] movq %rax,%r15 // r15 = t[0] = lo(a[0] * b[0]) movq %rdx,%r14 // r14 = hi(a[0] * b[0]) movq %r8,%rbp // rbp = k0 imulq %r15,%rbp // rbp = t[0] * k0 movq (%rcx),%rax // rax = n[0] mulq %rbp // (rdx, rax) = t[0] * k0 * n[0] ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0]) + t[0] leaq 1(%r10),%r10 // j++ .Loop1st: movq (%rsi,%r10,8),%rax // rax = a[j] movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[0]) mulq %rbx // (rdx, rax) = a[j] * b[0] ADD_CARRY %rax,%r14 // r14 = hi(a[j - 1] * b[0]) + lo(a[j] * b[0]) movq %rdx,%r15 // r15 = hi(a[j] * b[0]) movq (%rcx,%r10,8),%rax // rax = n[j] mulq %rbp // (rdx, rax) = t[0] * k0 * n[j] leaq 1(%r10),%r10 // j++ cmpq %r9,%r10 // if j != size, loop L1st je .Loop1stSkip ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j]) + lo(t[0] * k0 * n[j]) ADD_CARRY %r14,%r12 // r12 += lo(a[j] * b[0]) + hi(a[j] * b[0]) movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13 movq %r15,%r14 // r14 = hi(a[j] * b[0]) jmp .Loop1st .Loop1stSkip: ADD_CARRY %rax,%r12 // r12 = hi(t[0] * k0 * n[j - 1]) + lo(t[0] * k0 * n[j]) ADD_CARRY %r14,%r12 // r12 += hi(a[j - 1] * b[0]) + lo(a[j] * b[0]) movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13 movq %r15,%r14 // r14 = hi(a[j] * b[0]) movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j]) xorq %rdx,%rdx // rdx = 0, Clearing the CF. ADD_CARRY %r14,%r12 // r12 = hi(t[0] * k0 * n[j]) + hi(a[j] * b[0]) movq %r12,-8(%rsp,%r9,8) // t[size - 1] = hi(t[0] * k0 * n[j]) + hi(a[j] * b[0]), save overflow bit. movq %rdx,(%rsp,%r9,8) leaq 1(%r11),%r11 // i++ .align 16 .LoopOuter: xorq %r10,%r10 // j = 0 movq (%rsi),%rax // rax = a[0] movq (%r13,%r11,8),%rbx // rbx = b[i] mulq %rbx // (rdx, rax) = a[0] * b[i] movq (%rsp),%r15 // r15 = lo(a[0] * b[i]) + t[0] ADD_CARRY %rax,%r15 movq %rdx,%r14 // r14 = hi(a[0] * b[i]) movq %r8,%rbp // rbp = t[0] * k0 imulq %r15,%rbp movq (%rcx),%rax // rax = n[0] mulq %rbp // (rdx, rax) = t[0] * k0 * n[0] ADD_CARRY %rax,%r15 // r15 = lo(t[0] * k0 * n[0]) leaq 1(%r10),%r10 // j++ .align 16 .LoopInner: movq (%rsi,%r10,8),%rax // rax = a[j] movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j]) movq (%rsp,%r10,8),%r15 // r15 = t[j] mulq %rbx // (rdx, rax) = a[1] * b[i] ADD_CARRY %rax,%r14 // r14 = hi(a[0] * b[i]) + lo(a[1] * b[i]) movq (%rcx,%r10,8),%rax // rax = n[j] ADD_CARRY %r14,%r15 // r15 = a[j] * b[i] + t[j] movq %rdx,%r14 leaq 1(%r10),%r10 // j++ mulq %rbp // (rdx, rax) = t[0] * k0 * n[j] cmpq %r9,%r10 // if j != size, loop Linner je .LoopInnerSkip ADD_CARRY %rax,%r12 // r12 = t[0] * k0 * n[j] ADD_CARRY %r15,%r12 // r12 = a[j] * b[i] + t[j] + n[j] * t[0] * k0 movq %r12,-16(%rsp,%r10,8) // t[j - 2] = r13 jmp .LoopInner .LoopInnerSkip: ADD_CARRY %rax,%r12 // r12 = t[0] * k0 * n[j] ADD_CARRY %r15,%r12 // r12 = t[0] * k0 * n[j] + a[j] * b[i] + t[j] movq (%rsp,%r10,8),%r15 // r15 = t[j] movq %r12,-16(%rsp,%r10,8) // t[j - 2] movq %rdx,%r12 // r12 = hi(t[0] * k0 * n[j]) xorq %rdx,%rdx // rdx 0 ADD_CARRY %r14,%r12 // r12 = hi(a[1] * b[i]) + hi(t[0] * k0 * n[j]) ADD_CARRY %r15,%r12 // r12 += t[j] movq %r12,-8(%rsp,%r9,8) // t[size - 1] = r13 movq %rdx,(%rsp,%r9,8) // t[size] = CF leaq 1(%r11),%r11 // i++ cmpq %r9,%r11 // if size < i (unsigned) jne .LoopOuter xorq %r11,%r11 // r11 = 0, clear CF. movq (%rsp),%rax // rax = t[0] movq %r9,%r10 // r10 = size .align 16 .LoopSub: sbbq (%rcx,%r11,8),%rax // r[i] = t[i] - n[i] movq %rax,(%rdi,%r11,8) movq 8(%rsp,%r11,8),%rax // rax = t[i + 1] leaq 1(%r11),%r11 // i++ decq %r10 // j-- jnz .LoopSub // if j != 0 sbbq $0,%rax // rax -= CF movq $-1,%rbx xorq %rax,%rbx // rbx = !t[i + 1] xorq %r11,%r11 // r11 = 0 movq %r9,%r10 // r10 = size .LoopCopy: movq (%rdi,%r11,8),%rcx // rcx = r[i] & t[i] andq %rbx,%rcx movq (%rsp,%r11,8),%rdx // rdx = CF & t[i] andq %rax,%rdx orq %rcx,%rdx movq %rdx,(%rdi,%r11,8) // r[i] = t[i] movq %r9,(%rsp,%r11,8) // t[i] = size leaq 1(%r11),%r11 // i++ subq $1,%r10 // j-- jnz .LoopCopy // if j != 0 movq 8(%rsp,%r9,8),%rsi // rsi = pressed-stacked rsp. movq $1,%rax // rax = 1 leaq (%rsi),%rsp // restore rsp. RESTORE_REGISTERS // Restore non-volatile register. ret .cfi_endproc .size MontMulx_Asm,.-MontMulx_Asm .type MontMul4x,@function .align 16 MontMul4x: .cfi_startproc SAVE_REGISTERS movq %rsp,%rax // save rsp movq %r9,%r15 negq %r15 leaq -48(%rsp,%r15,8),%r15 // Allocate space: size * 8 + 48 bytes. andq $-1024,%r15 movq %rsp,%r14 subq %r15,%r14 // __chkstk implemention, called when the stack size needs to exceed 4096. andq $-4096,%r14 leaq (%r15,%r14),%rsp cmpq %r15,%rsp // If you want to allocate more than one page, go to LoopPage4x. ja .LoopPage4x jmp .LoopMul4x .LoopPage4x: leaq -4096(%rsp),%rsp // rsp - 4096each time until rsp >= r10. cmpq %r15,%rsp ja .LoopPage4x .LoopMul4x: movq %rax, 0(%rsp) // save stack pointer movq %rdi, 8(%rsp) // save r movq %r8, 16(%rsp) // save k0 movq %r9, %r10 shrq $2, %r9 decq %r9 movq %r9, 24(%rsp) // save (size/4) - 1 shlq $3, %r10 movq %rdx, %r12 // r12 = b movq %r10, 32(%rsp) // save (size * 8) -> bytes addq %r10, %r12 // r12 = loc(b[size - 1]) leaq 80(%rsp),%rbp // rbp: start position of the tmp buffer movq %rdx,%r13 // r13 = b movq %r12, 40(%rsp) // save loc(b + size * 8) movq (%r13),%rdx // rbx = b[0] // cal a[0 ~ 3] * b[0] mulx (%rsi), %r12, %r14 // r14 = hi(a[0] * b[0]), r12 = lo(b[0] * a[0]) mulx 8(%rsi), %rax, %r15 // (r15, rax) = a[1] * b[0] addq %rax, %r14 // r14 = hi(a[0] * b[0]) + lo(a[1] * b[0]) mulx 16(%rsi), %rax, %r11 // (rax, r11) = a[2] * b[0] adcq %rax, %r15 // r15 = hi(a[1] * b[0]) + lo(a[2] * b[0]) adcq $0, %r11 // r11 = hi(a[2] * b[0]) + CF imulq %r12,%r8 // r8 = t[0] * k0, will change CF xorq %r10,%r10 // get r10 = 0 mulx 24(%rsi), %rax, %rbx // (rax, rbx) = a[3] * b[0] movq %r8, %rdx // rdx = t[0] * k0 = m' adcx %rax, %r11 // r11 = hi(a[2] * b[0]) + lo(a[3] * b[0]) adcx %r10, %rbx // rbx = hi(a[3] * b[0]) // cal n[0 ~ 3] * t[0] * k0 mulx (%rcx), %rax, %rdi // (rdi, rax) = n[0] * m' adcx %rax, %r12 // r12 = lo(b[0] * a[0]) + lo(n[0] * m') adox %r14, %rdi // r8 = hi(n[0] * m') + hi(a[0] * b[0]) + hi(n[0] * m') mulx 8(%rcx), %rax, %r14 // (r14, rax) = n[1] * m' adcx %rax, %rdi adox %r15, %r14 // r11 = hi(a[1] * b[0]) + lo(a[2] * b[0]) + hi(n[1] * m') movq %rdi, -32(%rbp) mulx 16(%rcx), %rax, %r15 // (r15, rax) = n[2] * m' adcx %rax, %r14 adox %r11, %r15 // r11 = hi(a[2] * b[0]) + lo(a[3] * b[0]) + hi(n[2] * m') movq %r14, -24(%rbp) mulx 24(%rcx), %rax, %r11 // (r11, rax) = n[3] * m' adcx %rax, %r15 adox %r10, %r11 // r11 = hi(n[3] * m') movq %r15, -16(%rbp) leaq 4*8(%rsi),%rsi // a offset 4 blocks leaq 4*8(%rcx),%rcx // n offset 4 blocks movq (%r13),%rdx // rdx = b[0] .align 16 .Loop1st4x: mulx (%rsi), %r12, %r14 // r14 = hi(a[4] * b[0]), r12 = lo(a[4] * b[0]) adcx %r10, %r11 // r11 += carry mulx 8(%rsi), %rax, %r15 // r15 = hi(a[5] * b[0]), rax = lo(a[5] * b[0]) adcx %rbx, %r12 // r12 = hi(a[3] * b[0]) + lo(a[4] * b[0]) adcx %rax, %r14 // r14 = hi(a[4] * b[0]) + lo(a[5] * a[0]) mulx 16(%rsi), %rax, %rdi // rax = hi(a[6] * b[0]), rax = lo(a[6] * b[0]) adcx %rax, %r15 // r15 = hi(a[5] * b[0]) + lo(a[6] * a[0]) mulx 24(%rsi), %rax, %rbx // rax = hi(a[7] * b[0]), rdi = lo(a[7] * b[0]) adcx %rax, %rdi // rbx = hi(a[6] * b[0]) + lo(a[7] * b[0]) adcx %r10, %rbx // rdi = hi(a[7] * b[0]) + CF movq %r8, %rdx adox %r11,%r12 // r12 = hi(a[3] * b[0]) + lo(b[4] * a[0]) + hi(n[3] * m') mulx (%rcx), %rax, %r11 // (rax, r8) = n[4] * m' leaq 4*8(%rsi), %rsi // a offset 4 blocks adcx %rax,%r12 // r12 = hi(a[3] * b[0]) + lo(b[4] * a[0]) // + hi(n[3] * m') + lo(n[4] * m') adox %r14, %r11 // r8 = hi(a[4] * b[0]) + lo(a[5] * b[0]) + hi(n[4] * m') mulx 8(%rcx), %rax, %r14 // (rax, r14) = n[5] * m' leaq 4*8(%rbp), %rbp // tmp offset 4 blocks adcx %rax, %r11 // r8 = hi(a[4] * b[0]) + lo(a[5] * b[0]) // + hi(n[4] * m') + lo(n[5] * m') adox %r15, %r14 // r14 = hi(a[5] * b[0]) + lo(a[6] * a[0]) // + ho(n[5] * m') mulx 16(%rcx), %rax, %r15 // (rax, r15) = n[6] * m' movq %r12, -5*8(%rbp) adcx %rax, %r14 // r14 = hi(a[5] * b[0]) + lo(a[6] * a[0]) // + hi(n[5] * m') + lo(n[6] * m') adox %rdi, %r15 // r15 = hi(a[6] * b[0]) + lo(a[7] * b[0]) // + hi(n[6] * m') movq %r11, -4*8(%rbp) mulx 24(%rcx), %rax, %r11 // (rax, r11) = n[7] * m' movq %r14, -3*8(%rbp) adcx %rax, %r15 // r15 = hi(a[6] * b[0]) + lo(a[7] * b[0]) // + hi(n[6] * m') + lo(n[7] * m') adox %r10, %r11 movq %r15, -2*8(%rbp) leaq 4*8(%rcx), %rcx // n offset 4 blocks movq (%r13),%rdx // recover rdx dec %r9 jnz .Loop1st4x movq 32(%rsp), %r15 // r15 = size * 8 leaq 8(%r13), %r13 // b offset 1 blocks adcx %r10, %r11 // hi(n[7] * m') + CF, here OX CF are carried. addq %r11, %rbx // hi(a[7] * b[0]) + hi(n[7] * m') sbbq %r11,%r11 // check r11 > 0 movq %rbx, -1*8(%rbp) .align 4 .LoopOuter4x: // cal a[0 ~ 3] * b[i] movq (%r13),%rdx // rdx = b[i] mov %r11, (%rbp) // keep the highest carry subq %r15, %rsi // get a[0] subq %r15, %rcx // get n[0] leaq 80(%rsp),%rbp // get tmp[0] // from here, a[0 ~ 3] * b[i] needs to add tmp mulx (%rsi), %r12, %r14 // r14 = hi(a[0] * b[i]), r12 = lo(b[i] * a[0]) xorq %r10,%r10 // get r10 = 0, and clear CF OF mulx 8(%rsi), %rax, %r15 // (r15, rax) = a[1] * b[i] adox -4*8(%rbp), %r12 // lo(a[1] * b[i]) + tmp[0] adcx %rax, %r14 // r14 = hi(a[0] * b[i]) + lo(a[1] * b[i]) mulx 16(%rsi), %rax, %r11 // (rax, r11) = a[2] * b[0] adox -3*8(%rbp),%r14 // r14 = hi(a[1] * b[i]) + lo(a[1] * b[i]) + tmp[1] adcx %rax, %r15 // r15 = hi(a[1] * b[i]) + lo(a[2] * b[i]) mulx 24(%rsi), %rax, %rbx // (rax, rbx) = a[3] * b[0] adox -2*8(%rbp),%r15 // r15 = hi(a[2] * b[i]) + lo(a[2] * b[i]) + tmp[2] adcx %rax, %r11 // r11 = hi(a[2] * b[0]) + lo(a[3] * b[0]) adox -1*8(%rbp),%r11 // r11 = hi(a[2] * b[i]) + lo(a[3] * b[i]) + tmp[3] adcx %r10,%rbx movq %r12, %rdx adox %r10,%rbx imulq 16(%rsp),%rdx // 16(%rsp) save k0, r8 = t[0] * k0 = m', imulq will change CF mulx (%rcx), %rax, %r8 // (rax, r8) = n[0] * m' xorq %r10, %r10 // clear CF adcx %rax, %r12 // r12 = lo(b[0] * a[0]) + lo(n[0] * m') adox %r14, %r8 // r8 = hi(n[0] * m') + hi(a[0] * b[0]) + hi(n[0] * m') mulx 8(%rcx), %rax, %rdi // (rdi, rax) = n[1] * m' leaq 4*8(%rsi),%rsi // a offsets 4 adcx %rax, %r8 adox %r15, %rdi // r11 = hi(a[1] * b[0]) + lo(a[2] * b[0]) + hi(n[1] * m') mulx 16(%rcx), %rax, %r15 // (rdi, rax) = n[2] * m' movq %r8, -32(%rbp) adcx %rax, %rdi adox %r11, %r15 // r11 = hi(a[2] * b[0]) + lo(a[3] * b[0]) + hi(n[2] * m') mulx 24(%rcx), %rax, %r11 // (rdi, rax) = n[3] * m' movq %rdi, -24(%rbp) adcx %rax, %r15 adox %r10, %r11 // r11 = hi(n[3] * m') movq %r15, -16(%rbp) leaq 4*8(%rcx),%rcx // n offsets 4 movq %rdx, %r8 // r8 = t[0] * k0 = m' movq (%r13), %rdx // rdx = b[i] movq 24(%rsp), %r9 .align 16 .Linner4x: mulx (%rsi), %r12, %r14 // r14 = hi(a[4] * b[i]), r12 = lo(a[4] * b[i]) adcx %r10, %r11 // carry of previous round adox %rbx, %r12 // r12 = hi(a[3] * b[i]) + lo(a[4] * b[i]) mulx 8(%rsi), %rax, %r15 // r15 = hi(a[5] * b[i]), rax = lo(a[5] * b[0]) adcx (%rbp), %r12 // r12 = hi(a[3] * b[i]) + lo(a[4] * b[i]) + tmp[4] --> 所以这里t不偏移 adox %rax, %r14 // r14 = hi(a[4] * b[i]) + lo(a[5] * b[0]) mulx 16(%rsi), %rax, %rdi // rax = hi(a[6] * b[i]), rax = lo(a[6] * b[i]) adcx 8(%rbp), %r14 // r12 = hi(a[3] * b[i]) + lo(a[4] * b[i]) + tmp[5] adox %rax, %r15 // r15 = hi(a[5] * b[i]) + lo(a[6] * b[i]) mulx 24(%rsi), %rax, %rbx // rax = hi(a[7] * b[i]), rdi = lo(a[7] * b[i]) adcx 16(%rbp), %r15 // r12 = hi(a[3] * b[i]) + lo(a[4] * b[i]) + tmp[6] adox %rax, %rdi // rbx = hi(a[6] * b[i]) + lo(a[7] * b[i]) adox %r10, %rbx // rbx += OF adcx 24(%rbp), %rdi // rdi = hi(a[6] * b[i]) + lo(a[7] * b[i]) + tmp[7] adcx %r10, %rbx // rbx += CF // update rdx, begin cal n[i] * k0 * m adox %r11,%r12 // r12 = hi(a[3] * b[i]) + lo(a[4] * b[i]) + hi(n[3] * m') movq %r8, %rdx mulx (%rcx), %rax, %r11 // (rax, r8) = n[4] * m' leaq 4*8(%rbp), %rbp // tmp offsets 4 adcx %rax,%r12 // r12 = hi(a[3] * b[i]) + lo(b[4] * a[i]) // + hi(n[3] * m') + lo(n[4] * m') adox %r14, %r11 // r8 = hi(a[4] * b[i]) + lo(a[5] * b[i]) + hi(n[4] * m') mulx 8(%rcx), %rax, %r14 // (rax, r14) = n[5] * m' leaq 4*8(%rsi), %rsi // a offsets 4 adcx %rax, %r11 // r8 = hi(a[4] * b[i]) + lo(a[5] * b[i]) // + hi(n[4] * m') + lo(n[5] * m') adox %r15, %r14 // r14 = hi(a[5] * b[i]) + lo(a[6] * a[i]) // + ho(n[5] * m') mulx 16(%rcx), %rax, %r15 // (rax, r15) = n[6] * m' movq %r12, -5*8(%rbp) adcx %rax, %r14 // r14 = hi(a[5] * b[i]) + lo(a[6] * b[i]) // + hi(n[5] * m') + lo(n[6] * m') movq %r11, -4*8(%rbp) adox %rdi, %r15 // r15 = hi(a[6] * b[i]) + lo(a[7] * b[i]) // + hi(n[6] * m') mulx 24(%rcx), %rax, %r11 // (rax, r11) = n[7] * m' movq %r14, -3*8(%rbp) adcx %rax, %r15 // r15 = hi(a[6] * b[0]) + lo(a[7] * b[0]) // + hi(n[6] * m') + lo(n[7] * m') adox %r10, %r11 movq %r15, -2*8(%rbp) leaq 4*8(%rcx), %rcx // n offsets 4 movq (%r13), %rdx dec %r9 jnz .Linner4x movq 32(%rsp), %r15 // r15 = size * 8 leaq 8(%r13), %r13 // b offsets 1. adcx %r10, %r11 // hi(n[7] * m') + OF + CF subq 0*8(%rbp), %r10 adcx %r11, %rbx // hi(a[7] * b[0]) + hi(n[7] * m') sbbq %r11,%r11 movq %rbx, -1*8(%rbp) cmp 40(%rsp), %r13 jne .LoopOuter4x leaq 48(%rsp),%rbp // rbp = tmp[0] subq %r15, %rcx // rcx= n[0] negq %r11 movq 24(%rsp), %rdx // rdx = size/4 movq 8(%rsp), %rdi // get r[0] // cal tmp - n movq 0(%rbp), %rax // rax = tmp[0] movq 8(%rbp), %rbx // rbx = tmp[1] movq 16(%rbp), %r10 // r10 = tmp[2] movq 24(%rbp), %r12 // r12 = tmp[3] leaq 32(%rbp), %rbp // tmp += 4 subq 0(%rcx), %rax // tmp[0] - n[0] sbbq 8(%rcx), %rbx // tmp[1] - n[1] sbbq 16(%rcx), %r10 // tmp[2] - n[2] sbbq 24(%rcx), %r12 // tmp[3] - n[3] leaq 32(%rcx), %rcx // n += 4 movq %rax, 0(%rdi) // r save the tmp - n movq %rbx, 8(%rdi) movq %r10, 16(%rdi) movq %r12, 24(%rdi) leaq 32(%rdi), %rdi // r += 4 .LoopSub4x: movq 0(%rbp), %rax // rax = tmp[0] movq 8(%rbp), %rbx // rbx = tmp[1] movq 16(%rbp), %r10 // r10 = tmp[2] movq 24(%rbp), %r12 // r12 = tmp[3] leaq 32(%rbp), %rbp sbbq 0(%rcx), %rax // tmp[0] - n[0] sbbq 8(%rcx), %rbx // tmp[1] - n[1] sbbq 16(%rcx), %r10 // tmp[2] - n[2] sbbq 24(%rcx), %r12 // tmp[3] - n[3] leaq 32(%rcx), %rcx movq %rax, 0(%rdi) movq %rbx, 8(%rdi) movq %r10, 16(%rdi) movq %r12, 24(%rdi) leaq 32(%rdi), %rdi decq %rdx // j-- jnz .LoopSub4x // if j != 0 sbbq $0,%r11 // cancellation of highest carry subq %r15, %rbp // rbp = tmp[0] subq %r15, %rdi // r = n[0] movq 24(%rsp), %r10 // r10 = size/4 - 1 pxor %xmm2,%xmm2 // xmm0 = 0 movq %r11, %xmm0 pcmpeqd %xmm1,%xmm1 // xmm5 = -1 pshufd $0,%xmm0,%xmm0 pxor %xmm0,%xmm1 xorq %rax,%rax movdqa (%rbp,%rax),%xmm5 // Copy the result to r. movdqu (%rdi,%rax),%xmm3 pand %xmm0,%xmm5 pand %xmm1,%xmm3 movdqa 16(%rbp,%rax),%xmm4 movdqu %xmm2,(%rbp,%rax) por %xmm3,%xmm5 movdqu 16(%rdi,%rax),%xmm3 movdqu %xmm5,(%rdi,%rax) pand %xmm0,%xmm4 pand %xmm1,%xmm3 movdqa %xmm2,16(%rbp,%rax) por %xmm3,%xmm4 movdqu %xmm4,16(%rdi,%rax) leaq 32(%rax),%rax .align 16 .LoopCopy4x: movdqa (%rbp,%rax),%xmm5 movdqu (%rdi,%rax),%xmm3 pand %xmm0,%xmm5 pand %xmm1,%xmm3 movdqa 16(%rbp,%rax),%xmm4 movdqu %xmm2,(%rbp,%rax) por %xmm3,%xmm5 movdqu 16(%rdi,%rax),%xmm3 movdqu %xmm5,(%rdi,%rax) pand %xmm0,%xmm4 pand %xmm1,%xmm3 movdqa %xmm2,16(%rbp,%rax) por %xmm3,%xmm4 movdqu %xmm4,16(%rdi,%rax) leaq 32(%rax),%rax decq %r10 // j-- jnz .LoopCopy4x movq 0(%rsp),%rsi // rsi = pressed-stacked rsp. movq $1,%rax leaq (%rsi),%rsp // Restore srsp. RESTORE_REGISTERS ret .cfi_endproc .size MontMul4x,.-MontMul4x .type MontSqr8x,@function .align 32 MontSqr8x: .cfi_startproc SAVE_REGISTERS movq %rsp,%rax movl %r9d,%r15d shll $3,%r9d // Calculate size * 8 bytes. shlq $5,%r15 // size * 8 * 4 negq %r9 leaq -64(%rsp,%r9,2),%r14 // r14 = rsp[size * 2 - 8] subq %rsi,%r14 andq $4095,%r14 movq %rsp,%rbp cmpq %r14,%r15 jae .Loop8xCheckstk leaq 4032(,%r9,2),%r15 // r15 = 4096 - frame - 2 * size subq %r15,%r14 movq $0,%r15 cmovcq %r15,%r14 .Loop8xCheckstk: subq %r14,%rbp leaq -96(%rbp,%r9,2),%rbp // Allocate a frame + 2 x size. andq $-64,%rbp // __checkstk implementation, // which is invoked when the stack size needs to exceed one page. movq %rsp,%r14 subq %rbp,%r14 andq $-4096,%r14 leaq (%r14,%rbp),%rsp cmpq %rbp,%rsp jbe .LoopMul8x .align 16 .LoopPage8x: leaq -4096(%rsp),%rsp // Change sp - 4096 each time until sp <= the space to be allocated cmpq %rbp,%rsp ja .LoopPage8x .LoopMul8x: movq %r9,%r15 // r15 = -size * 8 negq %r9 // Restoresize. movq %r8,32(%rsp) // Save the values of k0 and sp. movq %rax,40(%rsp) movq %rcx, %xmm1 // Pointer to saving n. pxor %xmm2,%xmm2 // xmm0 = 0 movq %rdi, %xmm0 // Pointer to saving r. movq %r15, %xmm5 // Save size. call MontSqr8Inner leaq (%rdi,%r9),%rbx // rbx = t[size] movq %r9,%rcx // rcx = -size movq %r9,%rdx // rdx = -size movq %xmm0, %rdi // rdi = r sarq $5,%rcx // rcx >>= 5 .align 32 /* T -= N */ .LoopSub8x: movq (%rbx),%r13 // r13 = t[i] movq 8(%rbx),%r12 // r12 = t[i + 1] movq 16(%rbx),%r11 // r11 = t[i + 2] movq 24(%rbx),%r10 // r10 = t[i + 3] sbbq (%rbp),%r13 // r13 = t[i] - (n[i] + CF) sbbq 8(%rbp),%r12 // r12 = t[i + 1] - (n[i + 1] + CF) sbbq 16(%rbp),%r11 // r11 = t[i + 2] - (n[i + 2] + CF) sbbq 24(%rbp),%r10 // r10 = t[i + 3] - (n[i + 3] + CF) movq %r13,0(%rdi) // Assigning value to r. movq %r12,8(%rdi) movq %r11,16(%rdi) movq %r10,24(%rdi) leaq 32(%rbp),%rbp // n += 4 leaq 32(%rdi),%rdi // r += 4 leaq 32(%rbx),%rbx // t += 4 incq %rcx jnz .LoopSub8x sbbq $0,%rax // rax -= CF leaq (%rbx,%r9),%rbx leaq (%rdi,%r9),%rdi movq %rax,%xmm0 pxor %xmm2,%xmm2 pshufd $0,%xmm0,%xmm0 movq 40(%rsp),%rsi // rsi = pressed-stacked rsp. .align 32 .LoopCopy8x: movdqa 0(%rbx),%xmm1 // Copy the result to r. movdqa 16(%rbx),%xmm5 leaq 32(%rbx),%rbx movdqu 0(%rdi),%xmm3 movdqu 16(%rdi),%xmm4 leaq 32(%rdi),%rdi movdqa %xmm2,-32(%rbx) movdqa %xmm2,-16(%rbx) movdqa %xmm2,-32(%rbx,%rdx) movdqa %xmm2,-16(%rbx,%rdx) pcmpeqd %xmm0,%xmm2 pand %xmm0,%xmm1 pand %xmm0,%xmm5 pand %xmm2,%xmm3 pand %xmm2,%xmm4 pxor %xmm2,%xmm2 por %xmm1,%xmm3 por %xmm5,%xmm4 movdqu %xmm3,-32(%rdi) movdqu %xmm4,-16(%rdi) addq $32,%r9 jnz .LoopCopy8x movq $1,%rax leaq (%rsi),%rsp // Restore rsp. RESTORE_REGISTERS // Restore non-volatile register. ret .cfi_endproc .size MontSqr8x,.-MontSqr8x .type MontSqr8Inner,@function .align 32 MontSqr8Inner: .cfi_startproc movq %rsi, %r8 addq %r9, %r8 movq %r8, 64(%rsp) // save a[size] movq %r9, 56(%rsp) // save size * 8 leaq 88(%rsp), %rbp // tmp的首地址 leaq 88(%rsp,%r9,2),%rbx movq %rbx,16(%rsp) // t[size * 2] leaq (%rcx,%r9),%rax movq %rax,8(%rsp) // n[size] jmp .MontSqr8xBegin .MontSqr8xInitStack: movdqa %xmm2,0*8(%rbp) movdqa %xmm2,2*8(%rbp) movdqa %xmm2,4*8(%rbp) movdqa %xmm2,6*8(%rbp) .MontSqr8xBegin: movdqa %xmm2,8*8(%rbp) movdqa %xmm2,10*8(%rbp) movdqa %xmm2,12*8(%rbp) movdqa %xmm2,14*8(%rbp) lea 128(%rbp), %rbp subq $64, %r9 jnz .MontSqr8xInitStack xorq %rbx, %rbx // clear CF OF movq $0, %r13 movq $0, %r12 movq $0, %r11 movq $0, %rdi movq $0, %r15 movq $0, %rcx leaq 88(%rsp), %rbp // set tmp[0] movq 0(%rsi), %rdx // rdx = a[0] movq $0, %r10 .LoopOuterSqr8x: // begin a[0] * a[1~7] mulx 8(%rsi), %rax, %r14 // rax = lo(a[1] * a[0]), r14 = hi(a[1] * a[0]) adcx %rbx, %rax movq %rax, 8(%rbp) adox %r13, %r14 mulx 16(%rsi), %rax, %r13 // (rax, r13) = a[2] * a[0] adcx %rax, %r14 // r14 = hi(a[1] * a[0]) + lo(a[2] * a[0]) adox %r12, %r13 mulx 24(%rsi), %rax, %r12 // (rax, r12) = a[3] * a[0] movq %r14, 16(%rbp) adcx %rax, %r13 // r13 = hi(a[2] * a[0]) + lo(a[3] * a[0]) adox %r11, %r12 mulx 32(%rsi), %rax, %r11 // (rax, r11) = a[4] * a[0] adcx %rax, %r12 // r12 = hi(a[3] * a[0]) + lo(a[4] * a[0]) adox %rdi, %r11 mulx 40(%rsi), %rax, %rdi // (rax, rdi) = a[5] * a[0] adcx %rax, %r11 // r11 = hi(a[4] * a[0]) + lo(a[5] * a[0]) adox %r15, %rdi mulx 48(%rsi), %rax, %r8 // (rax, r8) = a[6] * a[0] adcx %rax, %rdi // rdi = hi(a[5] * a[0]) + lo(a[6] * a[0]) adox %rcx, %r8 mulx 56(%rsi), %rax, %rbx // (rax, rbx) = a[7] * a[0] adcx %rax, %r8 // r8 = hi(a[6] * a[0]) + lo(a[7] * a[0]) adox %r10, %rbx // rbx += CF adcq 64(%rbp), %rbx // rbx += CF sbbq %r9, %r9 // get high CF xorq %r10, %r10 // clear CF OF // begin a[1] * a[2~7] movq 8(%rsi), %rdx // rdx = a[1] mulx 16(%rsi), %rax, %rcx // rax = lo(a[2] * a[1]), rcx = hi(a[2] * a[1]) adcx %rax, %r13 // r13 = hi(a[2] * a[0]) + lo(a[3] * a[0]) + lo(a[2] * a[1]) mulx 24(%rsi), %rax, %r14 // rax = lo(a[3] * a[1]), r14 = hi(a[3] * a[1]) movq %r13, 24(%rbp) adox %rax, %rcx // rcx = lo(a[3] * a[1]) + hi(a[2] * a[1]) mulx 32(%rsi), %rax, %r13 // (rax, r13) = a[4] * a[1] adcx %r12, %rcx // rcx = hi(a[3] * a[0]) + lo(a[4] * a[0]) + lo(a[3] * a[1]) + hi(a[2] * a[1]) adox %rax, %r14 // r14 = lo(a[4] * a[1]) + hi(a[3] * a[1]) mulx 40(%rsi), %rax, %r12 // (rax, r12) = a[5] * a[1] movq %rcx, 32(%rbp) adcx %r11, %r14 // r14 = lo(a[4] * a[1]) + hi(a[3] * a[1]) + hi(a[4] * a[0]) + lo(a[5] * a[0]) adox %rax, %r13 // r13 = lo(a[5] * a[1]) + hi(a[4] * a[1]) mulx 48(%rsi), %rax, %r11 // (rax, r11) = a[6] * a[1] adcx %rdi, %r13 // r13 = lo(a[5] * a[1]) + hi(a[4] * a[1]) + hi(a[5] * a[0]) + lo(a[6] * a[0]) adox %rax, %r12 // r12 = hi(a[5] * a[1]) + lo(a[6] * a[1]) mulx 56(%rsi), %rax, %rdi // (rax, rdi) = a[7] * a[1] adcx %r8, %r12 // r12 = hi(a[5] * a[1]) + lo(a[6] * a[1]) + hi(a[6] * a[0]) + lo(a[7] * a[0]) adox %rax, %r11 // r11 = hi(a[6] * a[1]) + lo(a[7] * a[1]) adcx %rbx, %r11 // r11 = hi(a[6] * a[1]) + lo(a[7] * a[1]) + hi(a[7] * a[0]) adcx %r10, %rdi // rdi += CF adox %r10, %rdi // rdi += OF movq 16(%rsi), %rdx // rdx = a[2] // begin a[2] * a[3~7] mulx 24(%rsi), %rax, %rbx // rax = lo(a[2] * a[3]), rbx = hi(a[2] * a[3]) adcx %rax, %r14 // r14 = lo(a[4] * a[1]) + hi(a[3] * a[1]) + hi(a[4] * a[0]) + lo(a[5] * a[0]) // + lo(a[2] * a[3]) mulx 32(%rsi), %rax, %rcx // rax = lo(a[2] * a[4]), rcx = hi(a[2] * a[4]) movq %r14, 40(%rbp) adox %rax, %rbx // r13 = lo(a[2] * a[4]) + hi(a[2] * a[3]) mulx 40(%rsi), %rax, %r8 // rax = lo(a[2] * a[5]), rcx = hi(a[2] * a[5]) adcx %r13, %rbx // rbx = lo(a[2] * a[4]) + hi(a[2] * a[3]) // + lo(a[5] * a[1]) + hi(a[4] * a[1]) + hi(a[5] * a[0]) + lo(a[6] * a[0]) adox %rax, %rcx // rcx = hi(a[2] * a[4]) + lo(a[2] * a[5]) movq %rbx, 48(%rbp) mulx 48(%rsi), %rax, %r13 // rax = lo(a[2] * a[6]), r13 = hi(a[2] * a[6]) adcx %r12, %rcx // rcx = hi(a[5] * a[1]) + lo(a[6] * a[1]) + hi(a[6] * a[0]) // + lo(a[7] * a[0]) + hi(a[2] * a[4]) + lo(a[2] * a[5]) adox %rax, %r8 // r8 = hi(a[2] * a[5]) + lo(a[2] * a[6]) mulx 56(%rsi), %rax, %r12 // rax = lo(a[2] * a[7]), r12 = hi(a[2] * a[7]) adcx %r11, %r8 // r8 = hi(a[2] * a[5]) + lo(a[2] * a[6]) // + hi(a[6] * a[1]) + lo(a[7] * a[1]) + hi(a[7] * a[0]) adox %rax, %r13 // r13 = hi(a[2] * a[6]) + lo(a[2] * a[7]) adcx %rdi, %r13 // r13 = hi(a[2] * a[6]) + lo(a[2] * a[7]) + hi(a[7] * a[1]) adcx %r10, %r12 // r12 += CF adox %r10, %r12 // r12 += OF movq 24(%rsi), %rdx // rdx = a[3] // begin a[3] * a[4~7] mulx 32(%rsi), %rax, %r14 // rax = lo(a[3] * a[4]), r14 = hi(a[3] * a[4]) adcx %rax, %rcx // rcx = hi(a[5] * a[1]) + lo(a[6] * a[1]) + hi(a[6] * a[0]) // + lo(a[7] * a[0]) + hi(a[2] * a[4]) + lo(a[2] * a[5]) + lo(a[3] * a[4]) mulx 40(%rsi), %rax, %rbx // rax = lo(a[3] * a[5]), rbx = hi(a[3] * a[5]) adox %rax, %r14 // r14 = hi(a[3] * a[4]) + lo(a[3] * a[5]) mulx 48(%rsi), %rax, %r11 // rax = lo(a[3] * a[6]), r11 = hi(a[3] * a[6]) adcx %r8, %r14 // r14 = hi(a[3] * a[4]) + lo(a[3] * a[5])+ hi(a[2] * a[5]) + lo(a[2] * a[6]) // + hi(a[6] * a[1]) + lo(a[7] * a[1]) + hi(a[7] * a[0]) adox %rax, %rbx // rbx = hi(a[3] * a[5]) + lo(a[3] * a[6]) mulx 56(%rsi), %rax, %rdi // rax = lo(a[3] * a[7]), rdi = hi(a[3] * a[7]) adcx %r13, %rbx // rbx = hi(a[3] * a[5]) + lo(a[3] * a[6]) // + hi(a[2] * a[6]) + lo(a[2] * a[7]) + hi(a[7] * a[1]) adox %rax, %r11 // r11 = hi(a[3] * a[6]) + lo(a[3] * a[7]) adcx %r12, %r11 // r11 = hi(a[2] * a[7]) + hi(a[3] * a[6]) + lo(a[3] * a[7]) adcx %r10, %rdi // rdi += CF adox %r10, %rdi // rdi += OF movq %rcx, 56(%rbp) movq %r14, 64(%rbp) movq 32(%rsi), %rdx // rdx = a[4] // begin a[4] * a[5~7] mulx 40(%rsi), %rax, %r13 // rax = lo(a[4] * a[5]), r13 = hi(a[4] * a[5]) adcx %rax, %rbx // rbx = hi(a[3] * a[5]) + lo(a[3] * a[6]) // + hi(a[2] * a[6]) + lo(a[2] * a[7]) + hi(a[7] * a[1]) + lo(a[4] * a[5]) mulx 48(%rsi), %rax, %r12 // rax = lo(a[4] * a[6]), r12 = hi(a[4] * a[6]) adox %rax, %r13 // r13 = lo(a[4] * a[6]) + hi(a[4] * a[5]) mulx 56(%rsi), %rax, %r14 // rax = lo(a[4] * a[7]), r14 = hi(a[4] * a[7]) adcx %r11, %r13 // r13 = hi(a[4] * a[5]) + hi(a[2] * a[7]) + hi(a[3] * a[6]) // + lo(a[3] * a[7]) adox %rax, %r12 // r12 = hi(a[4] * a[6]) + lo(a[4] * a[7]) adcx %rdi, %r12 // r12 = hi(a[4] * a[6]) + lo(a[4] * a[7]) + hi(a[3] * a[7]) adcx %r10, %r14 // r14 += CF adox %r10, %r14 // r14 += OF movq 40(%rsi), %rdx // rdx = a[5] // begin a[5] * a[6~7] mulx 48(%rsi), %rax, %r11 // rax = lo(a[5] * a[6]), r11 = hi(a[5] * a[6]) adcx %rax, %r12 // r14 = hi(a[4] * a[6]) + lo(a[4] * a[7]) + hi(a[3] * a[7]) + lo(a[5] * a[6]) mulx 56(%rsi), %rax, %rdi // rax = lo(a[5] * a[7]), rdi = hi(a[5] * a[7]) adox %rax, %r11 // r11 = hi(a[5] * a[6]) + lo(a[5] * a[7]) adcx %r14, %r11 // r11 = hi(a[5] * a[6]) + lo(a[5] * a[7]) + hi(a[4] * a[7]) adcx %r10, %rdi // rdi += CF adox %r10, %rdi // rdi += OF movq 48(%rsi), %rdx // rdx = a[6] mulx 56(%rsi), %rax, %r15 // rax = lo(a[7] * a[6]), r15 = hi(a[7] * a[6]) adcx %rax, %rdi // rdi = hi(a[5] * a[6]) + lo(a[7] * a[6]) adcx %r10, %r15 // r15 += CF leaq 64(%rsi), %rsi cmp 64(%rsp), %rsi // cmpared with a[size] je .Lsqrx8xEnd neg %r9 movq $0, %rcx movq 64(%rbp),%r14 adcx 9*8(%rbp),%rbx adcx 10*8(%rbp),%r13 adcx 11*8(%rbp),%r12 adcx 12*8(%rbp),%r11 adcx 13*8(%rbp),%rdi adcx 14*8(%rbp),%r15 adcx 15*8(%rbp),%rcx leaq (%rsi), %r10 // r10 = a[8] leaq 128(%rbp), %rbp sbbq %rax,%rax movq %rax, 72(%rsp) movq %rbp, 80(%rsp) xor %eax, %eax movq -64(%rsi), %rdx movq $-8, %r9 .align 32 .LoopSqr8x: movq %r14,%r8 // begin a[0] * a[8~11] mulx 0(%r10), %rax, %r14 // rax = lo(a[8] * a[0]), r14 = hi(a[8] * a[0]) adcx %rax, %r8 adox %rbx, %r14 mulx 8(%r10), %rax, %rbx // rax = lo(a[9] * a[0]), rbx = hi(a[8] * a[0]) adcx %rax, %r14 adox %r13, %rbx movq %r8,(%rbp,%r9,8) mulx 16(%r10), %rax, %r13 // rax = lo(a[10] * a[0]), r13 = hi(a[10] * a[0]) adcx %rax, %rbx adox %r12, %r13 mulx 24(%r10), %rax, %r12 // rax = lo(a[11] * a[0]), r12 = hi(a[11] * a[0]) adcx %rax, %r13 adox %r11, %r12 movq $0, %r8 mulx 32(%r10), %rax, %r11 // rax = lo(a[12] * a[0]), r11 = hi(a[12] * a[0]) adcx %rax, %r12 adox %rdi, %r11 mulx 40(%r10), %rax, %rdi // rax = lo(a[13] * a[0]), rdi = hi(a[13] * a[0]) adcx %rax, %r11 adox %r15, %rdi mulx 48(%r10), %rax, %r15 // rax = lo(a[14] * a[0]), r15 = hi(a[14] * a[0]) adcx %rax, %rdi adox %rcx, %r15 mulx 56(%r10), %rax, %rcx // rax = lo(a[15] * a[0]), rcx = hi(a[15] * a[0]) adcx %rax, %r15 adcx %r8, %rcx // here r8 = 0 adox %r8, %rcx movq 8(%rsi,%r9,8),%rdx inc %r9 jnz .LoopSqr8x leaq 64(%r10), %r10 movq $-8, %r9 cmp 64(%rsp), %r10 // cmpared with a[size] je .LoopSqr8xBreak subq 72(%rsp), %r8 // read the CF of the previous round. movq -64(%rsi), %rdx adcx 0*8(%rbp),%r14 adcx 1*8(%rbp),%rbx adcx 2*8(%rbp),%r13 adcx 3*8(%rbp),%r12 adcx 4*8(%rbp),%r11 adcx 5*8(%rbp),%rdi adcx 6*8(%rbp),%r15 adcx 7*8(%rbp),%rcx leaq 8*8(%rbp),%rbp sbbq %rax, %rax xorq %r8, %r8 movq %rax, 72(%rsp) jmp .LoopSqr8x .align 32 .LoopSqr8xBreak: xorq %r10, %r10 subq 72(%rsp),%r8 adcx %r10, %r14 movq 0(%rsi),%rdx movq %r14,0(%rbp) movq 80(%rsp), %r8 adcx %r10,%rbx adcx %r10,%r13 adcx %r10,%r12 adcx %r10,%r11 adcx %r10,%rdi adcx %r10,%r15 adcx %r10,%rcx cmp %r8, %rbp je .LoopOuterSqr8x // if tmp does not go to the end. The current value needs to be stored in tmp and updated. movq %rbx,1*8(%rbp) movq 1*8(%r8),%rbx movq %r13,2*8(%rbp) movq 2*8(%r8),%r13 movq %r12,3*8(%rbp) movq 3*8(%r8),%r12 movq %r11,4*8(%rbp) movq 4*8(%r8),%r11 movq %rdi,5*8(%rbp) movq 5*8(%r8),%rdi movq %r15,6*8(%rbp) movq 6*8(%r8),%r15 movq %rcx,7*8(%rbp) movq 7*8(%r8),%rcx movq %r8,%rbp jmp .LoopOuterSqr8x .align 32 .Lsqrx8xEnd: mov %rbx,9*8(%rbp) mov %r13,10*8(%rbp) mov %r12,11*8(%rbp) mov %r11,12*8(%rbp) mov %rdi,13*8(%rbp) mov %r15,14*8(%rbp) leaq 88(%rsp), %rbp // tmp[0] movq 56(%rsp), %rcx // rcx = size * 8 sbbq %rcx, %rsi // get a[0] xorq %r15, %r15 // clear CF OF, r15 = tmp[0] = 0 movq 8(%rbp), %r14 // r14 = tmp[1] movq 16(%rbp), %r13 // r13 = tmp[2] movq 24(%rbp), %r12 // r12 = tmp[3] adox %r14, %r14 // r14 = 2 * tmp[1] movq 0(%rsi), %rdx .align 32 .LoopShiftAddSqr4x: mulx %rdx, %rax, %rbx // (rbx, rax) = a[0] * a[0] adox %r13, %r13 // r13 = 2 * tmp[1] adox %r12, %r12 // r12 = 2 * tmp[3] adcx %rax, %r15 // r15 = 2 * tmp[0] + lo(a[0] * a[0]) adcx %rbx, %r14 // r14 = 2 * tmp[1] + hi(a[0] * a[0]) movq %r15, (%rbp) movq %r14, 8(%rbp) movq 8(%rsi), %rdx mulx %rdx, %rax, %rbx // (rbx, rax) = a[1] * a[1] adcx %rax, %r13 // r13 = 2 * tmp[2] + lo(a[1] * a[1]) adcx %rbx, %r12 // r12 = 2 * tmp[3] + hi(a[1] * a[1]) movq %r13, 16(%rbp) movq %r12, 24(%rbp) movq 32(%rbp), %r15 // r15 = tmp[4] movq 40(%rbp), %r14 // r14 = tmp[5] movq 48(%rbp), %r13 // r13 = tmp[6] movq 56(%rbp), %r12 // r12 = tmp[7] movq 16(%rsi), %rdx mulx %rdx, %rax, %rbx // (rbx, rax) = a[2] * a[2] adox %r15, %r15 // r15 = 2 * tmp[4] adcx %rax, %r15 // r15 = 2 * tmp[4] + lo(a[2] * a[2]) adox %r14, %r14 // r14 = 2 * tmp[4] adcx %rbx, %r14 // r14 = 2 * tmp[5] + hi(a[2] * a[2]) movq %r15, 32(%rbp) movq %r14, 40(%rbp) movq 24(%rsi), %rdx mulx %rdx, %rax, %rbx // (rbx, rax) = a[3] * a[3] adox %r13, %r13 // r13 = 2 * tmp[5] adcx %rax, %r13 // r13 = 2 * tmp[5] + lo(a[3] * a[3]) adox %r12, %r12 // r12 = 2 * tmp[5] adcx %rbx, %r12 // rbx = 2 * tmp[5] + hi(a[3] * a[3]) movq %r13, 48(%rbp) movq %r12, 56(%rbp) leaq 32(%rsi), %rsi // a[4] leaq -32(%rcx),%rcx jrcxz .LoopReduceSqr8xBegin // if i != 0 movq 64(%rbp), %r15 // r15 = tmp[8] movq 72(%rbp), %r14 // r14 = tmp[9] adox %r15, %r15 // r15 = 2 * tmp[8] adox %r14, %r14 // r14 = 2 * tmp[9] movq 80(%rbp), %r13 // r13 = tmp[8] movq 88(%rbp), %r12 // r12 = tmp[9] leaq 64(%rbp), %rbp movq 0(%rsi), %rdx jmp .LoopShiftAddSqr4x // if i != 0 .LoopReduceSqr8xBegin: xorq %rax,%rax // rax = 0 leaq 88(%rsp), %rdi // tmp[0] movq $0, %r9 // Save size. movq %xmm1, %rbp // get n[0] xorq %rsi, %rsi // rsi = 0 .align 32 .LoopReduceSqr8x: movq %rax,80(%rsp) // Store the highest carry bit. leaq (%rdi,%r9),%rdi // rdi = t[0] movq (%rdi),%rdx // rdx = t[0] movq 8(%rdi),%r9 // r9 = t[1] movq 16(%rdi),%r15 // r15 = t[2] movq 24(%rdi),%r14 // r14 = t[3] movq 32(%rdi),%r13 // r13 = t[4] movq 40(%rdi),%r12 // r12 = t[5] movq 48(%rdi),%r11 // r11 = t[6] movq 56(%rdi),%r10 // r10 = t[7] leaq 64(%rdi),%rdi // rdi = t[8] movq %rdx,%r8 // r8 = t[0] imulq 40(%rsp),%rdx // rbx = k0 * t[0] xorq %rbx,%rbx // clear CF OF movl $8,%ecx .align 32 .LoopReduce8x: movq %r8, %rbx movq %rdx, 80(%rsp,%rcx,8) mulx (%rbp), %rax, %r8 // (r8, rax) = m' * n[0] adcx %rbx, %rax adox %r9, %r8 // r9 = hi(m' * n[]) + t[1] mulx 8(%rbp), %rax, %r9 // (rdx, r9) = m' * n[0] adcx %rax,%r8 // r9 = t[1] + lo(m' * n[1]) adox %r9, %r15 // r15 = hi(m' * n[1]) + t[2] mulx 16(%rbp), %r9, %rax // (r9, rax) = m' * n[2] adcx %r15, %r9 // r9 = hi(m' * n[1]) + lo(m' * n[2]) + t[2] adox %rax, %r14 // rbx = hi(m' * n[2]) + t[3] mulx 24(%rbp), %r15, %rax // (r15, rax) = m' * n[3] adcx %r14,%r15 // r15 = hi(m' * n[2]) + lo(m' * n[3]) + t[3] adox %rax,%r13 // r13 = hi(m' * n[3]) + t[4] mulx 32(%rbp), %r14, %rax // (r14, rax) = m' * n[4] adcx %r13,%r14 // r14 = hi(m' * n[3]) + lo(m' * n[4]) + t[4] adox %rax,%r12 // r12 = hi(m' * n[4]) + t[5] mulx 40(%rbp), %r13, %rax // (r13, rax) = m' * n[5] adcx %r12,%r13 // r13 = hi(m' * n[4]) + lo(m' * n[5]) + t[5] adox %rax,%r11 // r12 = hi(m' * n[5]) + t[6] mulx 48(%rbp), %r12, %rax // (r12, rax) = m' * n[6] adcx %r11,%r12 // r13 = hi(m' * n[5]) + lo(m' * n[6]) + t[6] adox %r10,%rax // r12 = hi(m' * n[5]) + t[7] mulx 56(%rbp), %r11, %r10 // (r11, r10) = m' * n[7] adcx %rax,%r11 // r13 = hi(m' * n[6]) + lo(m' * n[7]) + t[7] adcx %rsi,%r10 // r12 = hi(m' * n[7]) + t[8] adox %rsi,%r10 // r12 = hi(m' * n[7]) + t[8] movq %r8, %rdx mulx 40(%rsp), %rdx, %rax // (rdx, rax) = m' * n[7] decl %ecx // ecx-- jnz .LoopReduce8x // if ecx != 0 leaq 64(%rbp),%rbp // rbp += 64, n Pointer Offset. xorq %rax,%rax // rax = 0 cmpq 8(%rsp),%rbp // rbp = n[size] jae .LoopEndCondMul8x addq (%rdi),%r8 // r8 += t[0] adcq 8(%rdi),%r9 // r9 += t[1] adcq 16(%rdi),%r15 // r15 += t[2] adcq 24(%rdi),%r14 // r14 += t[3] adcq 32(%rdi),%r13 // r13 += t[4] adcq 40(%rdi),%r12 // r12 += t[5] adcq 48(%rdi),%r11 // r11 += t[6] adcq 56(%rdi),%r10 // r10 += t[7] sbbq %rsi,%rsi // rsi = -CF movq 144(%rsp),%rdx // rbx = m', 80 + 64 movl $8,%ecx xor %eax,%eax .align 32 .LoopLastSqr8x: mulx (%rbp), %rax, %rbx // (rbx, rax) = m' * n[0] adcx %rax,%r8 // r8 = lo(m' * n[0]) + t[0] movq %r8,(%rdi) // t[0] = r8 leaq 8(%rdi),%rdi // t++ adox %rbx,%r9 // r9 = hi(m' * n[]) + t[2] mulx 8(%rbp), %r8, %rbx // (r8, rbx) = m' * n[0] adcx %r9,%r8 // r9 = t[1] + lo(m' * n[1]) adox %rbx, %r15 // r15 = hi(m' * n[1]) + t[2] mulx 16(%rbp), %r9, %rbx // (r9, rbx) = m' * n[2] adcx %r15, %r9 // r9 = hi(m' * n[1]) + lo(m' * n[2]) + t[2] adox %rbx, %r14 // r14 = hi(m' * n[2]) + t[3] mulx 24(%rbp), %r15, %rbx // (r15, rbx) = m' * n[3] adcx %r14,%r15 // r15 = hi(m' * n[2]) + lo(m' * n[3]) + t[3] adox %rbx,%r13 // r13 = hi(m' * n[3]) + t[4] mulx 32(%rbp), %r14, %rbx // (r14, rbx) = m' * n[4] adcx %r13,%r14 // r14 = hi(m' * n[3]) + lo(m' * n[4]) + t[4] adox %rbx,%r12 // r12 = hi(m' * n[4]) + t[5] mulx 40(%rbp), %r13, %rbx // (r13, rbx) = m' * n[5] adcx %r12,%r13 // r13 = hi(m' * n[4]) + lo(m' * n[5]) + t[5] adox %rbx,%r11 // r11 = hi(m' * n[5]) + t[6] mulx 48(%rbp), %r12, %rbx // (r12, rbx) = m' * n[6] adcx %r11,%r12 // r12 = hi(m' * n[5]) + lo(m' * n[6]) + t[6] adox %r10,%rbx // rbx = hi(m' * n[5]) + t[7] movq $0, %rax mulx 56(%rbp), %r11, %r10 // (r11, r10) = m' * n[7] adcx %rbx,%r11 // r11 = hi(m' * n[6]) + lo(m' * n[7]) + t[7] adcx %rax,%r10 // r10 = hi(m' * n[7]) + t[8] adox %rax,%r10 // r10 = hi(m' * n[7]) + t[8] movq 72(%rsp,%rcx,8),%rdx // rbx = t[i] * k0 decl %ecx // ecx-- jnz .LoopLastSqr8x // if ecx != 0 leaq 64(%rbp),%rbp // n += 8 cmpq 8(%rsp),%rbp // Check whether rbp is at the end of the n array. If yes, exit the loop. jae .LoopSqrBreak8x movq 144(%rsp),%rdx // rbx = m' negq %rsi // rsi = CF movq (%rbp),%rax // rax = = n[0] adcq (%rdi),%r8 // r8 = t[0] adcq 8(%rdi),%r9 // r9 = t[1] adcq 16(%rdi),%r15 // r15 = t[2] adcq 24(%rdi),%r14 // r14 = t[3] adcq 32(%rdi),%r13 // r13 = t[4] adcq 40(%rdi),%r12 // r12 = t[5] adcq 48(%rdi),%r11 // r11 = t[6] adcq 56(%rdi),%r10 // r10 = t[7] sbbq %rsi,%rsi // rsi = -CF movl $8,%ecx // ecx = 8 xorq %rax, %rax jmp .LoopLastSqr8x .align 32 .LoopSqrBreak8x: xorq %rax,%rax // rax = 0 addq 80(%rsp),%r8 // r8 += Highest carry bit. adcq $0,%r9 // r9 += CF adcq $0,%r15 // r15 += CF adcq $0,%r14 // r14 += CF adcq $0,%r13 // r13 += CF adcq $0,%r12 // r12 += CF adcq $0,%r11 // r11 += CF adcq $0,%r10 // r10 += CF adcq $0,%rax // rax += CF negq %rsi // rsi = CF .LoopEndCondMul8x: adcq (%rdi),%r8 // r8 += t[0] adcq 8(%rdi),%r9 // r9 += t[1] adcq 16(%rdi),%r15 // r15 += t[2] adcq 24(%rdi),%r14 // r14 += t[3] adcq 32(%rdi),%r13 // r13 += t[4] adcq 40(%rdi),%r12 // r12 += t[5] adcq 48(%rdi),%r11 // r11 += t[6] adcq 56(%rdi),%r10 // r10 += t[7] adcq $0,%rax // rax += CF movq -8(%rbp),%rcx // rcx = n[7] xorq %rsi,%rsi // rsi = 0 movq %xmm1,%rbp // rbp = n movq %r8,(%rdi) // Save the calculated result back to t[]. movq %r9,8(%rdi) movq %xmm5,%r9 movq %r15,16(%rdi) movq %r14,24(%rdi) movq %r13,32(%rdi) movq %r12,40(%rdi) movq %r11,48(%rdi) movq %r10,56(%rdi) leaq 64(%rdi),%rdi // t += 8 cmpq 16(%rsp),%rdi // Cycle the entire t[]. jb .LoopReduceSqr8x ret .cfi_endproc .size MontSqr8Inner,.-MontSqr8Inner #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/asm/bn_montx_x86_64.S
Unix Assembly
unknown
53,538
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include "crypt_errno.h" #include "bn_bincal.h" #include "bn_asm.h" #if defined(HITLS_CRYPTO_BN_X8664) && defined(__x86_64__) #include "crypt_utils.h" #endif int32_t MontSqrBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { if (mont->mSize > 1) { #if defined(HITLS_CRYPTO_BN_X8664) && defined(__x86_64__) if (IsSupportBMI2() && IsSupportADX()) { MontMulx_Asm(r, r, r, mont->mod, mont->k0, mont->mSize); return CRYPT_SUCCESS; } #endif MontMul_Asm(r, r, r, mont->mod, mont->k0, mont->mSize); return CRYPT_SUCCESS; } return MontSqrBinCore(r, mont, opt, consttime); } int32_t MontMulBin(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { if (mont->mSize > 1) { #if defined(HITLS_CRYPTO_BN_X8664) && defined(__x86_64__) if (IsSupportBMI2() && IsSupportADX()) { MontMulx_Asm(r, a, b, mont->mod, mont->k0, mont->mSize); return CRYPT_SUCCESS; } #endif MontMul_Asm(r, a, b, mont->mod, mont->k0, mont->mSize); return CRYPT_SUCCESS; } return MontMulBinCore(r, a, b, mont, opt, consttime); } int32_t MontEncBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { if (mont->mSize > 1) { #if defined(HITLS_CRYPTO_BN_X8664) && defined(__x86_64__) if (IsSupportBMI2() && IsSupportADX()) { MontMulx_Asm(r, r, mont->montRR, mont->mod, mont->k0, mont->mSize); return CRYPT_SUCCESS; } #endif MontMul_Asm(r, r, mont->montRR, mont->mod, mont->k0, mont->mSize); return CRYPT_SUCCESS; } return MontEncBinCore(r, mont, opt, consttime); } void Reduce(BN_UINT *r, BN_UINT *x, const BN_UINT *one, const BN_UINT *m, uint32_t mSize, BN_UINT m0) { if (mSize <= 1) { ReduceCore(r, x, m, mSize, m0); return; } #if defined(HITLS_CRYPTO_BN_X8664) && defined(__x86_64__) if (IsSupportBMI2() && IsSupportADX()) { MontMulx_Asm(r, x, one, m, m0, mSize); return; } #endif MontMul_Asm(r, x, one, m, m0, mSize); return; } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/asm_bn_mont.c
C
unknown
2,767
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BN_ASM_H #define BN_ASM_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include <stdlib.h> #include "crypt_bn.h" #ifdef __cplusplus extern "C" { #endif /** * Function description: r = reduce(a * b) mod n * Function prototype: void MontMul_Asm(uint64_t *r, const uint64_t *a, const uint64_t *b, * const uint64_t *n, const uint64_t k0, uint32_t size); * Input register: * x0: result array pointer r * x1: source data array pointer a * x2: source data array pointer b * x3: source data array pointer n * x4: k0 in the mont structure * x5: The size of the first four arrays is 'size'. * Modify registers: x0-x17, x19-x24 * Output register: None * Function/Macro Call: bn_mont_sqr8x, bn_mont_mul4x * Remarks: The four arrays must have the same length. * If these are different, expand the length to the length of the longest array. * In addition, the expanded part needs to be cleared to 0. */ void MontMul_Asm(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, const BN_UINT *n, const BN_UINT k0, size_t size); #if defined(HITLS_CRYPTO_BN_X8664) void MontMulx_Asm(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, const BN_UINT *n, const BN_UINT k0, size_t size); #endif #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_BN */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_asm.h
C
unknown
1,978
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "bn_bincal.h" #include "bn_basic.h" BN_BigNum *BN_Create(uint32_t bits) { if (bits > BN_MAX_BITS) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_INVALID); return NULL; } uint32_t room = BITS_TO_BN_UNIT(bits); BN_BigNum *r = (BN_BigNum *)BSL_SAL_Calloc(1u, sizeof(BN_BigNum)); if (r == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } if (room != 0) { r->room = room; r->data = (BN_UINT *)BSL_SAL_Calloc(1u, room * sizeof(BN_UINT)); if (r->data == NULL) { BSL_SAL_FREE(r); return NULL; } } return r; } void BN_Destroy(BN_BigNum *a) { if (a == NULL) { return; } // clear sensitive information BSL_SAL_CleanseData((void *)(a->data), a->size * sizeof(BN_UINT)); if (a->flag == CRYPT_BN_FLAG_STATIC) { return; } BSL_SAL_FREE(a->data); if (!BN_IsFlag(a, CRYPT_BN_FLAG_OPTIMIZER)) { BSL_SAL_FREE(a); } } inline void BN_Init(BN_BigNum *bn, BN_UINT *data, uint32_t room, int32_t number) { for (uint32_t i = 0; i < (uint32_t)number; i++) { bn[i].data = &data[room * i]; bn[i].room = room; bn[i].flag = CRYPT_BN_FLAG_STATIC; } } #ifdef HITLS_CRYPTO_EAL_BN bool BnVaild(const BN_BigNum *a) { if (a == NULL) { return false; } if (a->size == 0) { return !a->sign; } if (a->data == NULL || a->size > a->room) { return false; } if ((a->size <= a->room) && (a->data[a->size - 1] != 0)) { return true; } return false; } #endif #ifdef HITLS_CRYPTO_BN_CB BN_CbCtx *BN_CbCtxCreate(void) { BN_CbCtx *r = (BN_CbCtx *)BSL_SAL_Calloc(1u, sizeof(BN_CbCtx)); if (r == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } return r; } void BN_CbCtxSet(BN_CbCtx *gencb, BN_CallBack callBack, void *arg) { if (gencb == NULL) { return; } BN_CbCtx *tmpCb = gencb; tmpCb->arg = arg; tmpCb->cb = callBack; } void *BN_CbCtxGetArg(BN_CbCtx *callBack) { if (callBack == NULL) { return NULL; } return callBack->arg; } int32_t BN_CbCtxCall(BN_CbCtx *callBack, int32_t process, int32_t target) { if (callBack == NULL || callBack->cb == NULL) { return CRYPT_SUCCESS; } int32_t ret = callBack->cb(callBack, process, target); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } void BN_CbCtxDestroy(BN_CbCtx *cb) { if (cb == NULL) { return; } BSL_SAL_FREE(cb); } #endif int32_t BN_SetSign(BN_BigNum *a, bool sign) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } /* 0 must be a positive number symbol */ if (BN_IsZero(a) == true && sign == true) { BSL_ERR_PUSH_ERROR(CRYPT_BN_NO_NEGATIVE_ZERO); return CRYPT_BN_NO_NEGATIVE_ZERO; } a->sign = sign; return CRYPT_SUCCESS; } static bool IsLegalFlag(uint32_t flag) { switch (flag) { case CRYPT_BN_FLAG_CONSTTIME: case CRYPT_BN_FLAG_OPTIMIZER: case CRYPT_BN_FLAG_STATIC: return true; default: return false; } } int32_t BN_SetFlag(BN_BigNum *a, uint32_t flag) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (!IsLegalFlag(flag)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_FLAG_INVALID); return CRYPT_BN_FLAG_INVALID; } a->flag |= flag; return CRYPT_SUCCESS; } int32_t BN_Copy(BN_BigNum *r, const BN_BigNum *a) { if (r == NULL || a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (r != a) { int32_t ret = BnExtend(r, a->size); if (ret != CRYPT_SUCCESS) { return ret; } r->sign = a->sign; BN_COPY_BYTES(r->data, r->size, a->data, a->size); r->size = a->size; } return CRYPT_SUCCESS; } BN_BigNum *BN_Dup(const BN_BigNum *a) { if (a == NULL) { return NULL; } BN_BigNum *r = BN_Create(a->room * BN_UINT_BITS); if (r != NULL) { r->sign = a->sign; (void)memcpy_s(r->data, a->size * sizeof(BN_UINT), a->data, a->size * sizeof(BN_UINT)); r->size = a->size; } return r; } bool BN_IsZero(const BN_BigNum *a) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return true; } return (a->size == 0); } bool BN_IsOne(const BN_BigNum *a) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return false; } return (a->size == 1 && a->data[0] == 1 && a->sign == false); } bool BN_IsNegative(const BN_BigNum *a) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return false; } return a->sign; } bool BN_IsOdd(const BN_BigNum *a) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return false; } return (a->size > 0) && (a->data[0] & 1) != 0; } bool BN_IsFlag(const BN_BigNum *a, uint32_t flag) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return false; } return a->flag & flag; } int32_t BN_Zeroize(BN_BigNum *a) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } // clear sensitive information BSL_SAL_CleanseData(a->data, a->size * sizeof(BN_UINT)); a->sign = false; a->size = 0; return CRYPT_SUCCESS; } bool BN_IsLimb(const BN_BigNum *a, const BN_UINT w) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return (w == 0); } return !a->sign && (((a->size == 1) && (a->data[0] == w)) || ((w == 0) && (a->size == 0))); } int32_t BN_SetLimb(BN_BigNum *r, BN_UINT w) { if (r == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = BnExtend(r, 1); if (ret != CRYPT_SUCCESS) { return ret; } BN_Zeroize(r); if (w != 0) { r->data[r->size] = w; r->size++; } return CRYPT_SUCCESS; } BN_UINT BN_GetLimb(const BN_BigNum *a) { if (a == NULL) { return 0; } if (a->size > 1) { return BN_MASK; } else if (a->size == 1) { return a->data[0]; } return 0; } bool BN_GetBit(const BN_BigNum *a, uint32_t n) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return false; } uint32_t nw = n / BN_UINT_BITS; uint32_t nb = n % BN_UINT_BITS; if (nw >= a->size) { return false; } return (uint32_t)(((a->data[nw]) >> nb) & ((BN_UINT)1)); } int32_t BN_SetBit(BN_BigNum *a, uint32_t n) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint32_t nw = n / BN_UINT_BITS; uint32_t nb = n % BN_UINT_BITS; if (nw >= a->room) { BSL_ERR_PUSH_ERROR(CRYPT_BN_SPACE_NOT_ENOUGH); return CRYPT_BN_SPACE_NOT_ENOUGH; } a->data[nw] |= (((BN_UINT)1) << nb); if (a->size < nw + 1) { a->size = nw + 1; } return CRYPT_SUCCESS; } int32_t BN_ClrBit(BN_BigNum *a, uint32_t n) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint32_t nw = n / BN_UINT_BITS; uint32_t nb = n % BN_UINT_BITS; if (nw >= a->size) { BSL_ERR_PUSH_ERROR(CRYPT_BN_SPACE_NOT_ENOUGH); return CRYPT_BN_SPACE_NOT_ENOUGH; } a->data[nw] &= (~(((BN_UINT)1) << nb)); // check whether the size changes a->size = BinFixSize(a->data, a->size); if (a->size == 0) { a->sign = false; } return CRYPT_SUCCESS; } int32_t BN_MaskBit(BN_BigNum *a, uint32_t n) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint32_t nw = n / BN_UINT_BITS; uint32_t nb = n % BN_UINT_BITS; if (a->size <= nw) { BSL_ERR_PUSH_ERROR(CRYPT_BN_SPACE_NOT_ENOUGH); return CRYPT_BN_SPACE_NOT_ENOUGH; } if (nb == 0) { a->size = nw; } else { a->size = nw + 1; a->data[nw] &= ~(BN_MASK << nb); } a->size = BinFixSize(a->data, a->size); if (a->size == 0) { a->sign = false; } return CRYPT_SUCCESS; } uint32_t BN_Bits(const BN_BigNum *a) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } return BinBits(a->data, a->size); } uint32_t BN_Bytes(const BN_BigNum *a) { return BN_BITS_TO_BYTES(BN_Bits(a)); } int32_t BnExtend(BN_BigNum *a, uint32_t words) { if (a->room >= words) { return CRYPT_SUCCESS; } if (a->flag == CRYPT_BN_FLAG_STATIC) { BSL_ERR_PUSH_ERROR(CRYPT_BN_NOT_SUPPORT_EXTENSION); return CRYPT_BN_NOT_SUPPORT_EXTENSION; } if (words > BITS_TO_BN_UNIT(BN_MAX_BITS)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_TOO_MAX); return CRYPT_BN_BITS_TOO_MAX; } BN_UINT *tmp = (BN_UINT *)BSL_SAL_Calloc(1u, words * sizeof(BN_UINT)); if (tmp == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } if (a->size > 0) { (void)memcpy_s(tmp, a->size * sizeof(BN_UINT), a->data, a->size * sizeof(BN_UINT)); BSL_SAL_CleanseData(a->data, a->size * sizeof(BN_UINT)); } BSL_SAL_FREE(a->data); a->data = tmp; a->room = words; return CRYPT_SUCCESS; } // ref. NIST.SP.800-57 Section 5.6.1.1 int32_t BN_SecBits(int32_t pubLen, int32_t prvLen) { int32_t bits = 256; // the secure length is initialized to a maximum of 256 int32_t level[] = {1024, 2048, 3072, 7680, 15360, INT32_MAX}; int32_t secbits[] = {0, 80, 112, 128, 192, 256}; for (int32_t loc = 0; loc < (int32_t)(sizeof(level) / sizeof(level[0])); loc++) { if (pubLen < level[loc]) { bits = secbits[loc]; break; } } if (prvLen == -1) { // In IFC algorithm, the security length only needs to consider the modulus number. return bits; } bits = ((prvLen / 2) >= bits) ? bits : (prvLen / 2); // The security length of FFC algorithm is considering prvLen/2 // Encryption does not use the algorithm/key combination which security strength is less than 112 bits // such as less than 80 bits return (bits < 80) ? 0 : bits; } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_basic.c
C
unknown
11,141
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BN_BASIC_H #define BN_BASIC_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include "crypt_bn.h" #ifdef __cplusplus extern "C" { #endif struct BnMont { uint32_t mSize; /* *< size of mod in BN_UINT */ BN_UINT k0; /* *< low word of (1/(r - mod[0])) mod r */ BN_UINT *mod; /* *< mod */ BN_UINT *one; /* *< store one */ BN_UINT *montRR; /* *< mont_enc(1) */ BN_UINT *b; /* *< tmpb(1) */ BN_UINT *t; /* *< tmpt(1) ^ 2 */ }; struct BnCbCtx { void *arg; // callback parameter BN_CallBack cb; // callback function, which is defined by the user }; /* Find a pointer address aligned by 'alignment' bytes in the [ptr, ptr + alignment - 1] range. The input parameter alignment cannot be 0. */ static inline BN_UINT *AlignedPointer(const void *ptr, uintptr_t alignment) { uint8_t *p = (uint8_t *)(uintptr_t)ptr + alignment - 1; return (BN_UINT *)((uintptr_t)p - (uintptr_t)p % alignment); } int32_t BnExtend(BN_BigNum *a, uint32_t words); #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_BN */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_basic.h
C
unknown
1,642
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include "securec.h" #include "bn_bincal.h" /* r = a + w, the length of r and a array is 'size'. The return value is the carry. */ BN_UINT BinInc(BN_UINT *r, const BN_UINT *a, uint32_t size, BN_UINT w) { uint32_t i; BN_UINT carry = w; for (i = 0; i < size && carry != 0; i++) { ADD_AB(carry, r[i], a[i], carry); } if (r != a) { for (; i < size; i++) { r[i] = a[i]; } } return carry; } /* r = a - w, the length of r and a array is 'size'. The return value is the borrow-digit. */ BN_UINT BinDec(BN_UINT *r, const BN_UINT *a, uint32_t n, BN_UINT w) { uint32_t i; BN_UINT borrow = w; for (i = 0; (i < n) && (borrow > 0); i++) { SUB_AB(borrow, r[i], a[i], borrow); } if (r != a) { for (; i < n; i++) { r[i] = a[i]; } } return borrow; } /* r = a >> bits, the return value is the valid length of r after the shift. * The array length of a is n. The length of the r array must meet the requirements of the accepted calculation result, * which is guaranteed by the input parameter. */ uint32_t BinRshift(BN_UINT *r, const BN_UINT *a, uint32_t n, uint32_t bits) { uint32_t nw = bits / BN_UINT_BITS; /* shift words */ uint32_t nb = bits % BN_UINT_BITS; /* shift bits */ /** * unsigned shift operand cannot be greater than or equal to the data bit width * Otherwise, undefined behavior is triggered. */ uint32_t na = (BN_UINT_BITS - nb) % BN_UINT_BITS; uint32_t rsize = n - nw; uint32_t i; BN_UINT hi; BN_UINT lo = a[nw]; /* When nb == 0, discard the value of (hi << na) with the all-zero mask. */ BN_UINT mask = ~BN_IsZeroUintConsttime(nb); /* Assigns values from the lower bits. */ for (i = nw; i < n - 1; i++) { hi = a[i + 1]; r[i - nw] = (lo >> nb) | ((hi << na) & mask); lo = hi; } lo >>= nb; if (lo != 0) { r[rsize - 1] = lo; } else { rsize--; } return rsize; } /* r = a << bits. The return value is the valid length of r after the shift. * The array length of a is n. The length of the r array must meet the requirements of the accepted calculation result, * which is guaranteed by the input parameter. */ uint32_t BinLshift(BN_UINT *r, const BN_UINT *a, uint32_t n, uint32_t bits) { uint32_t nw = bits / BN_UINT_BITS; /* shift words */ uint32_t nb = bits % BN_UINT_BITS; /* shift bits */ /** * unsigned shift operand cannot be greater than or equal to the data bit width * Otherwise, undefined behavior is triggered. */ uint32_t na = (BN_UINT_BITS - nb) % BN_UINT_BITS; uint32_t rsize = n + nw; uint32_t i; BN_UINT hi = a[n - 1]; BN_UINT lo; /* When nb == 0, discard the value of (hi << na) with the all-zero mask. */ BN_UINT mask = ~BN_IsZeroUintConsttime(nb); lo = (hi >> na) & mask; /* Assign a value to the most significant bit. */ if (lo != 0) { r[rsize++] = lo; } /* Assign a value from the most significant bits. */ for (i = n - 1; i > 0; i--) { lo = a[i - 1]; r[i + nw] = (hi << nb) | ((lo >> na) & mask); hi = lo; } r[nw] = a[0] << nb; /* Clear the lower bits to 0. */ if (nw != 0) { (void)memset_s(r, nw * sizeof(BN_UINT), 0, nw * sizeof(BN_UINT)); } return rsize; } /* r = a * b + r. The return value is a carry. */ BN_UINT BinMulAcc(BN_UINT *r, const BN_UINT *a, uint32_t aSize, BN_UINT b) { BN_UINT c = 0; BN_UINT *rr = r; const BN_UINT *aa = a; uint32_t size = aSize; #ifndef HITLS_CRYPTO_BN_SMALL_MEM while (size >= 4) { /* a group of 4 */ MULADD_ABC(c, rr[0], aa[0], b); /* offset 0 */ MULADD_ABC(c, rr[1], aa[1], b); /* offset 1 */ MULADD_ABC(c, rr[2], aa[2], b); /* offset 2 */ MULADD_ABC(c, rr[3], aa[3], b); /* offset 3 */ aa += 4; /* a group of 4 */ rr += 4; /* a group of 4 */ size -= 4; /* a group of 4 */ } #endif while (size > 0) { MULADD_ABC(c, rr[0], aa[0], b); aa++; rr++; size--; } return c; } /* r = a * b rRoom >= aSize + bSize. The length is guaranteed by the input parameter. r != a, r != b. * The return value is the valid length of the result. */ uint32_t BinMul(BN_UINT *r, uint32_t rRoom, const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize) { BN_UINT carry = 0; (void)memset_s(r, rRoom * sizeof(BN_UINT), 0, rRoom * sizeof(BN_UINT)); /* Result combination of cyclic calculation data units. */ for (uint32_t i = 0; i < bSize; i++) { carry = 0; uint32_t j = 0; BN_UINT t = b[i]; for (; j < aSize; j++) { MULADC_AB(r[i + j], a[j], t, carry); } if (carry != 0) { r[i + j] = carry; } } return aSize + bSize - (carry == 0); } /* r = a * a rRoom >= aSize * 2. The length is guaranteed by the input parameter. r != a. * The return value is the valid length of the result. */ uint32_t BinSqr(BN_UINT *r, uint32_t rRoom, const BN_UINT *a, uint32_t aSize) { uint32_t i; BN_UINT carry; (void)memset_s(r, rRoom * sizeof(BN_UINT), 0, rRoom * sizeof(BN_UINT)); /* Calculate unequal data units, similar to trapezoid. */ for (i = 0; i < aSize - 1; i++) { BN_UINT t = a[i]; uint32_t j; for (j = i + 1, carry = 0; j < aSize; j++) { MULADC_AB(r[i + j], a[j], t, carry); } r[i + j] = carry; } /* In the square, the multiplier unit is symmetrical. r = r * 2 */ BinLshift(r, r, 2 * aSize - 1, 1); /* Calculate the direct squared data unit and add it to the result. */ for (i = 0, carry = 0; i < aSize; i++) { BN_UINT rh, rl; SQR_A(rh, rl, a[i]); ADD_ABC(carry, r[i << 1], r[i << 1], rl, carry); ADD_ABC(carry, r[(i << 1) + 1], r[(i << 1) + 1], rh, carry); } return aSize + aSize - (r[(aSize << 1) - 1] == 0); } /* refresh the size */ uint32_t BinFixSize(const BN_UINT *data, uint32_t size) { uint32_t fix = size; uint32_t i = size; for (; i > 0; i--) { if (data[i - 1] != 0) { return fix; }; fix--; } return fix; } /* compare BN array. Maybe aSize != bSize; * return 0, if a == b * return 1, if a > b * return -1, if a < b */ int32_t BinCmp(const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize) { if (aSize == bSize) { uint32_t len = aSize; while (len > 0) { len--; if (a[len] != b[len]) { return a[len] > b[len] ? 1 : -1; } } return 0; } return aSize > bSize ? 1 : -1; } /* obtain bits */ uint32_t BinBits(const BN_UINT *data, uint32_t size) { if (size == 0) { return 0; } return (size * BN_UINT_BITS - GetZeroBitsUint(data[size - 1])); } /** * Try to reduce the borrowing cost, guarantee h|l >= q * yl. If q is too large, reduce q. * Each time q decreases by 1, h increases by yh. y was previously offset, and the most significant bit of yh is 1. * Therefore (q * yl << BN_UINT_BITS) < (yh * 2), number of borrowing times ≤ 2. */ static BN_UINT TryDiv(BN_UINT q, BN_UINT h, BN_UINT l, BN_UINT yh, BN_UINT yl) { BN_UINT rh, rl; MUL_AB(rh, rl, q, yl); /* Compare h|l >= rh|rl. Otherwise, reduce q. */ if (rh < h || (rh == h && rl <= l)) { return q; } BN_UINT nq = q - 1; BN_UINT nh = h + yh; /* If carry occurs, no judgment is required. */ if (nh < yh) { return nq; } /* rh|rl - yl */ if (rl < yl) { rh--; } rl -= yl; /* Compare r|l >= rh|rl. Otherwise, reduce q. */ if (rh < nh || (rh == nh && rl <= l)) { return nq; } nq--; return nq; } /* Divide core operation */ static void BinDivCore(BN_UINT *q, uint32_t *qSize, BN_UINT *x, uint32_t xSize, const BN_UINT *y, uint32_t ySize) { BN_UINT yy = y[ySize - 1]; /* Obtain the most significant bit of the data. */ uint32_t i; for (i = xSize; i >= ySize; i--) { BN_UINT qq; if (x[i] == yy) { qq = (BN_UINT)-1; } else { BN_UINT rr; DIV_ND(qq, rr, x[i], x[i - 1], yy); if (ySize > 1) { /* If ySize is 1, do not need to try divide. */ /* Obtain the least significant bit data, that is, make subscript - 2. */ qq = TryDiv(qq, rr, x[i - 2], yy, y[ySize - 2]); } } if (qq > 0) { /* After the TryDiv is complete, perform the double subtraction. */ BN_UINT extend = BinSubMul(&x[i - ySize], y, ySize, qq); extend = (x[i] -= extend); if (extend > 0) { /* reverse, borrowing required */ extend = BinAdd(&x[i - ySize], &x[i - ySize], y, ySize); x[i] += extend; qq--; } if (q != NULL && qq != 0) { /* update quotient */ q[i - ySize] = qq; *qSize = (*qSize) > (i - ySize + 1) ? (*qSize) : (i - ySize + 1); } } } } // The L-shift of the divisor does not exceed the highest BN_UINT. static void BnLshiftSimple(BN_UINT *a, uint32_t aSize, uint32_t bits) { uint32_t rem = BN_UNIT_BITS - bits; BN_UINT nextBits = 0; for (uint32_t i = 0; i < aSize; i++) { BN_UINT n = a[i]; a[i] = (n << bits) | nextBits; nextBits = (n >> rem); } return; } /** * x / y = q...x, the return value is the updated xSize. * q and asize are both NULL or not NULL. Other input parameters must be valid. * q, x and y cannot be the same pointer, the data in q must be 0. * Ensure that x->room >= xSize + 2, and the extra two spaces need to be cleared. Extra space is used during try divide. * this interface does not ensure that the y is consistent after running. */ uint32_t BinDiv(BN_UINT *q, uint32_t *qSize, BN_UINT *x, uint32_t xSize, BN_UINT *y, uint32_t ySize) { uint32_t shifts = GetZeroBitsUint(y[ySize - 1]); uint32_t xNewSize = xSize; /* Left shift until the maximum displacement of the divisor is full. */ if (shifts != 0) { BnLshiftSimple(y, ySize, shifts); xNewSize = BinLshift(x, x, xSize, shifts); } BinDivCore(q, qSize, x, xSize, y, ySize); /* shift compensation */ if (shifts != 0) { xNewSize = BinRshift(x, x, xNewSize, shifts); } return BinFixSize(x, xNewSize); } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_bincal.c
C
unknown
11,223
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BN_BINCAL_H #define BN_BINCAL_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include "bn_basic.h" #if defined(HITLS_CRYPTO_BN_X8664) #include "bn_bincal_x8664.h" #elif defined(HITLS_CRYPTO_BN_ARMV8) #include "bn_bincal_armv8.h" #else #include "bn_bincal_noasm.h" #endif #ifdef __cplusplus extern "c" { #endif /* r = a + b, input 'carry' means carry */ #define ADD_AB(carry, r, a, b) \ do { \ BN_UINT macroTmpT = (a) + (b); \ (carry) = macroTmpT < (a) ? 1 : 0; \ (r) = macroTmpT; \ } while (0) /* r = a - b, input 'borrow' means borrow digit */ #define SUB_AB(borrow, r, a, b) \ do { \ BN_UINT macroTmpT = (a) - (b); \ (borrow) = ((a) < (b)) ? 1 : 0; \ (r) = macroTmpT; \ } while (0) /* r = a - b - c, input 'borrow' means borrow digit */ #define SUB_ABC(borrow, r, a, b, c) \ do { \ BN_UINT macroTmpS = (a) - (b); \ BN_UINT macroTmpB = ((a) < (b)) ? 1 : 0; \ macroTmpB += (macroTmpS < (c)) ? 1 : 0; \ (r) = macroTmpS - (c); \ borrow = macroTmpB; \ } while (0) #define BN_UINT_HALF_BITS (BN_UINT_BITS >> 1) /* carry value of the upper part */ #define BN_UINT_HC ((BN_UINT)1 << BN_UINT_HALF_BITS) /* Takes the low bit and assigns it to the high bit. */ #define BN_UINT_LO_TO_HI(t) ((t) << BN_UINT_HALF_BITS) /* Takes the high bit and assigns it to the high bit. */ #define BN_UINT_HI_TO_HI(t) ((t) & ((BN_UINT)0 - BN_UINT_HC)) /* Takes the low bit and assigns it to the low bit. */ #define BN_UINT_LO(t) ((t) & (BN_UINT_HC - 1)) /* Takes the high bit and assigns it to the low bit. */ #define BN_UINT_HI(t) ((t) >> BN_UINT_HALF_BITS) /* copy bytes, ensure that dstLen >= srcLen */ #define BN_COPY_BYTES(dst, dstlen, src, srclen) \ do { \ uint32_t macroTmpI; \ for (macroTmpI = 0; macroTmpI < (srclen); macroTmpI++) { (dst)[macroTmpI] = (src)[macroTmpI]; } \ for (; macroTmpI < (dstlen); macroTmpI++) { (dst)[macroTmpI] = 0; } \ } while (0) // Modular operation, satisfy d < (1 << BN_UINT_HALF_BITS) r = nh | nl % d #define MOD_HALF(r, nh, nl, d) \ do { \ BN_UINT macroTmpD = (d); \ (r) = (nh) % macroTmpD; \ (r) = ((r) << BN_UINT_HALF_BITS) | BN_UINT_HI((nl)); \ (r) = (r) % macroTmpD; \ (r) = ((r) << BN_UINT_HALF_BITS) | BN_UINT_LO((nl)); \ (r) = (r) % macroTmpD; \ } while (0) /* r = a * b + r + c, where c is refreshed as the new carry value */ #define MULADD_ABC(c, r, a, b) \ do { \ BN_UINT macroTmpAl = BN_UINT_LO(a); \ BN_UINT macroTmpAh = BN_UINT_HI(a); \ BN_UINT macroTmpBl = BN_UINT_LO(b); \ BN_UINT macroTmpBh = BN_UINT_HI(b); \ BN_UINT macroTmpX3 = macroTmpAh * macroTmpBh; \ BN_UINT macroTmpX2 = macroTmpAh * macroTmpBl; \ BN_UINT macroTmpX1 = macroTmpAl * macroTmpBh; \ BN_UINT macroTmpX0 = macroTmpAl * macroTmpBl; \ (r) += (c); \ (c) = ((r) < (c)) ? 1 : 0; \ macroTmpX1 += macroTmpX2; \ (c) += (macroTmpX1 < macroTmpX2) ? BN_UINT_HC : 0; \ macroTmpX2 = macroTmpX0; \ macroTmpX0 += macroTmpX1 << BN_UINT_HALF_BITS; \ (c) += (macroTmpX0 < macroTmpX2) ? 1 : 0; \ (c) += BN_UINT_HI(macroTmpX1); \ (c) += macroTmpX3; \ (r) += macroTmpX0; \ (c) += ((r) < macroTmpX0) ? 1 : 0; \ } while (0) /* r = a + b + c, input 'carry' means carry. Note that a and carry cannot be the same variable. */ #define ADD_ABC(carry, r, a, b, c) \ do { \ BN_UINT macroTmpS = (b) + (c); \ carry = (macroTmpS < (c)) ? 1 : 0; \ (r) = macroTmpS + (a); \ carry += ((r) < macroTmpS) ? 1 : 0; \ } while (0) BN_UINT BinAdd(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n); BN_UINT BinSub(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n); BN_UINT BinInc(BN_UINT *r, const BN_UINT *a, uint32_t size, BN_UINT w); BN_UINT BinDec(BN_UINT *r, const BN_UINT *a, uint32_t n, BN_UINT w); uint32_t BinRshift(BN_UINT *r, const BN_UINT *a, uint32_t n, uint32_t bits); BN_UINT BinSubMul(BN_UINT *r, const BN_UINT *a, BN_UINT aSize, BN_UINT m); uint32_t BinLshift(BN_UINT *r, const BN_UINT *a, uint32_t n, uint32_t bits); BN_UINT BinMulAcc(BN_UINT *r, const BN_UINT *a, uint32_t aSize, BN_UINT b); uint32_t BinMul(BN_UINT *r, uint32_t rRoom, const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize); uint32_t BinSqr(BN_UINT *r, uint32_t rRoom, const BN_UINT *a, uint32_t aSize); uint32_t GetZeroBitsUint(BN_UINT x); uint32_t BinFixSize(const BN_UINT *data, uint32_t size); int32_t BinCmp(const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize); uint32_t BinBits(const BN_UINT *data, uint32_t size); uint32_t BinDiv(BN_UINT *q, uint32_t *qSize, BN_UINT *x, uint32_t xSize, BN_UINT *y, uint32_t ySize); #ifdef HITLS_CRYPTO_BN_COMBA uint32_t SpaceSize(uint32_t size); // Perform a multiplication calculation of 4 blocks of data, r = a^2, // where the length of r is 8, and the length of a is 4. void MulComba4(BN_UINT *r, const BN_UINT *a, const BN_UINT *b); // Calculate the square of 4 blocks of data, r = a^2, where the length of r is 8, and the length of a is 4. void SqrComba4(BN_UINT *r, const BN_UINT *a); // Perform a multiplication calculation of 6 blocks of data, r = a*b, // where the length of r is 12, the length of a and b is 6. void MulComba6(BN_UINT *r, const BN_UINT *a, const BN_UINT *b); // Calculate the square of 6 blocks of data, r = a^2, where the length of r is 12, and the length of a is 6. void SqrComba6(BN_UINT *r, const BN_UINT *a); void MulConquer(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t size, BN_UINT *space, bool consttime); void SqrConquer(BN_UINT *r, const BN_UINT *a, uint32_t size, BN_UINT *space, bool consttime); #endif int32_t MontSqrBinCore(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime); int32_t MontMulBinCore(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, BN_Mont *mont, BN_Optimizer *opt, bool consttime); int32_t MontEncBinCore(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime); void ReduceCore(BN_UINT *r, BN_UINT *x, const BN_UINT *m, uint32_t mSize, BN_UINT m0); #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_BN */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_bincal.h
C
unknown
7,894
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BN_BINCAL_ARMV8_H #define BN_BINCAL_ARMV8_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include "bn_basic.h" #ifdef __cplusplus extern "c" { #endif // wh | wl = u * v #define MUL_AB(wh, wl, u, v) \ { \ __asm("mul %1, %2, %3 \n\t" \ "umulh %0, %2, %3 \n\t" \ : "=&r"(wh), "=&r"(wl) \ : "r"(u), "r"(v) \ : "cc"); \ } // wh | wl = u ^ 2 #define SQR_A(wh, wl, u) \ { \ __asm("mul %1, %2, %2 \n\t" \ "umulh %0, %2, %2 \n\t" \ : "=&r"(wh), "=&r"(wl) \ : "r"(u) \ : "cc"); \ } /* nh|nl / d = q...r */ #define DIV_ND(q, r, nh, nl, d) \ do { \ BN_UINT macroTmpD1, macroTmpD0, macroTmpQ1, macroTmpQ0, macroTmpR1, macroTmpR0, macroTmpM; \ \ macroTmpD1 = BN_UINT_HI(d); \ macroTmpD0 = BN_UINT_LO(d); \ \ macroTmpQ1 = (nh) / macroTmpD1; \ macroTmpR1 = (nh) - macroTmpQ1 * macroTmpD1; \ macroTmpM = macroTmpQ1 * macroTmpD0; \ macroTmpR1 = (macroTmpR1 << (BN_UINT_BITS >> 1)) | BN_UINT_HI(nl); \ if (macroTmpR1 < macroTmpM) { \ macroTmpQ1--, macroTmpR1 += (d); \ if (macroTmpR1 >= (d)) { \ if (macroTmpR1 < macroTmpM) { \ macroTmpQ1--; \ macroTmpR1 += (d); \ } \ } \ } \ macroTmpR1 -= macroTmpM; \ \ macroTmpQ0 = macroTmpR1 / macroTmpD1; \ macroTmpR0 = macroTmpR1 - macroTmpQ0 * macroTmpD1; \ macroTmpM = macroTmpQ0 * macroTmpD0; \ macroTmpR0 = (macroTmpR0 << (BN_UINT_BITS >> 1)) | BN_UINT_LO(nl); \ if (macroTmpR0 < macroTmpM) { \ macroTmpQ0--, macroTmpR0 += (d); \ if (macroTmpR0 >= (d)) { \ if (macroTmpR0 < macroTmpM) { \ macroTmpQ0--; \ macroTmpR0 += (d); \ } \ } \ } \ macroTmpR0 -= macroTmpM; \ \ (q) = (macroTmpQ1 << (BN_UINT_BITS >> 1)) | macroTmpQ0; \ (r) = macroTmpR0; \ } while (0) // (hi, lo) = a * b // r += lo + carry // carry = hi + c #define MULADC_AB(r, a, b, carry) \ do { \ BN_UINT hi, lo; \ __asm("mul %0, %2, %3 \n\t" \ "umulh %1, %2, %3 \n\t" \ : "=&r"(lo), "=&r"(hi) \ : "r"(a), "r"(b) \ : "cc"); \ __asm("adds %1, %1, %3 \n\t" \ "adc %2, %2, xzr \n\t " \ "adds %0, %0, %1 \n\t" \ "adc %2, %2, xzr \n\t " \ "mov %1, %2 \n\t" \ : "+&r"(r), "+&r"(carry), "+&r"(hi) \ : "r"(lo) \ : "cc"); \ } while (0) /* h|m|l = h|m|l + u * v. Ensure that the value of h is not too large to avoid carry. */ #define MULADD_AB(h, m, l, u, v) \ do { \ BN_UINT hi, lo; \ __asm("mul %0, %2, %3 \n\t" \ "umulh %1, %2, %3 \n\t" \ : "=&r"(lo), "=&r"(hi) \ : "r"(u), "r"(v) \ : "cc"); \ __asm("adds %0, %0, %3 \n\t " \ "adcs %1, %1, %4 \n\t " \ "adc %2, %2, xzr \n\t " \ : "+&r"(l), "+&r"(m), "+&r"(h) \ : "r"(lo), "r"(hi) \ : "cc"); \ } while (0) /* h|m|l = h|m|l + 2 * u * v. Ensure that the value of h is not too large to avoid carry. */ #define MULADD_AB2(h, m, l, u, v) \ do { \ BN_UINT hi, lo; \ __asm("mul %0, %2, %3 \n\t" \ "umulh %1, %2, %3 \n\t" \ : "=&r"(lo), "=&r"(hi) \ : "r"(u), "r"(v) \ : "cc"); \ __asm("adds %0, %0, %3 \n\t " \ "adcs %1, %1, %4 \n\t " \ "adc %2, %2, xzr \n\t " \ "adds %0, %0, %3 \n\t " \ "adcs %1, %1, %4 \n\t " \ "adc %2, %2, xzr \n\t " \ : "+&r"(l), "+&r"(m), "+&r"(h) \ : "r"(lo), "r"(hi) \ : "cc"); \ } while (0) /* h|m|l = h|m|l + u * u. Ensure that the value of h is not too large to avoid carry. */ #define SQRADD_A(h, m, l, u) MULADD_AB(h, m, l, u, u) #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_BN */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_bincal_armv8.h
C
unknown
7,144
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BN_BINCAL_NOASM_H #define BN_BINCAL_NOASM_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include "bn_basic.h" #ifdef __cplusplus extern "c" { #endif /* nh|nl / d = q...r */ #define DIV_ND(q, r, nh, nl, d) \ do { \ BN_UINT macroTmpD1, macroTmpD0, macroTmpQ1, macroTmpQ0, macroTmpR1, macroTmpR0, macroTmpM; \ \ macroTmpD1 = BN_UINT_HI(d); \ macroTmpD0 = BN_UINT_LO(d); \ \ macroTmpQ1 = (nh) / macroTmpD1; \ macroTmpR1 = (nh) - macroTmpQ1 * macroTmpD1; \ macroTmpM = macroTmpQ1 * macroTmpD0; \ macroTmpR1 = (macroTmpR1 << (BN_UINT_BITS >> 1)) | BN_UINT_HI(nl); \ if (macroTmpR1 < macroTmpM) { \ macroTmpQ1--, macroTmpR1 += (d); \ if (macroTmpR1 >= (d)) { \ if (macroTmpR1 < macroTmpM) { \ macroTmpQ1--; \ macroTmpR1 += (d); \ } \ } \ } \ macroTmpR1 -= macroTmpM; \ \ macroTmpQ0 = macroTmpR1 / macroTmpD1; \ macroTmpR0 = macroTmpR1 - macroTmpQ0 * macroTmpD1; \ macroTmpM = macroTmpQ0 * macroTmpD0; \ macroTmpR0 = (macroTmpR0 << (BN_UINT_BITS >> 1)) | BN_UINT_LO(nl); \ if (macroTmpR0 < macroTmpM) { \ macroTmpQ0--, macroTmpR0 += (d); \ if (macroTmpR0 >= (d)) { \ if (macroTmpR0 < macroTmpM) { \ macroTmpQ0--; \ macroTmpR0 += (d); \ } \ } \ } \ macroTmpR0 -= macroTmpM; \ \ (q) = (macroTmpQ1 << (BN_UINT_BITS >> 1)) | macroTmpQ0; \ (r) = macroTmpR0; \ } while (0) #define MUL_AB(wh, wl, u, v) \ do { \ BN_UINT macroTmpUl = BN_UINT_LO(u); \ BN_UINT macroTmpUh = BN_UINT_HI(u); \ BN_UINT macroTmpVl = BN_UINT_LO(v); \ BN_UINT macroTmpVh = BN_UINT_HI(v); \ \ BN_UINT macroTmpX0 = macroTmpUl * macroTmpVl; \ BN_UINT macroTmpX1 = macroTmpUl * macroTmpVh; \ BN_UINT macroTmpX2 = macroTmpUh * macroTmpVl; \ BN_UINT macroTmpX3 = macroTmpUh * macroTmpVh; \ \ macroTmpX1 += BN_UINT_HI(macroTmpX0); \ macroTmpX1 += macroTmpX2; \ if (macroTmpX1 < macroTmpX2) { macroTmpX3 += BN_UINT_HC; } \ \ (wh) = macroTmpX3 + BN_UINT_HI(macroTmpX1); \ (wl) = (macroTmpX1 << (BN_UINT_BITS >> 1)) | BN_UINT_LO(macroTmpX0); \ } while (0) #define SQR_A(wh, wl, u) \ do { \ BN_UINT macroTmpUl = BN_UINT_LO(u); \ BN_UINT macroTmpUh = BN_UINT_HI(u); \ \ BN_UINT macroTmpX0 = macroTmpUl * macroTmpUl; \ BN_UINT macroTmpX1 = macroTmpUl * macroTmpUh; \ BN_UINT macroTmpX2 = macroTmpUh * macroTmpUh; \ \ BN_UINT macroTmpT = macroTmpX1 << 1; \ macroTmpT += BN_UINT_HI(macroTmpX0); \ if (macroTmpT < macroTmpX1) { macroTmpX2 += BN_UINT_HC; } \ \ (wh) = macroTmpX2 + BN_UINT_HI(macroTmpT); \ (wl) = (macroTmpT << (BN_UINT_BITS >> 1)) | BN_UINT_LO(macroTmpX0); \ } while (0) /* r = a + b + c, input 'carry' means carry. Note that a and carry cannot be the same variable. */ #define ADD_ABC(carry, r, a, b, c) \ do { \ BN_UINT macroTmpS = (b) + (c); \ carry = (macroTmpS < (c)) ? 1 : 0; \ (r) = macroTmpS + (a); \ carry += ((r) < macroTmpS) ? 1 : 0; \ } while (0) // (hi, lo) = a * b // r += lo + carry // carry = hi + c #define MULADC_AB(r, a, b, carry) \ do { \ BN_UINT hi, lo; \ MUL_AB(hi, lo, a, b); \ ADD_ABC(carry, r, r, lo, carry); \ carry += hi; \ } while (0) /* h|m|l = h|m|l + u * v. Ensure that the value of h is not too large to avoid carry. */ #define MULADD_AB(h, m, l, u, v) \ do { \ BN_UINT macroTmpUl = BN_UINT_LO(u); \ BN_UINT macroTmpUh = BN_UINT_HI(u); \ BN_UINT macroTmpVl = BN_UINT_LO(v); \ BN_UINT macroTmpVh = BN_UINT_HI(v); \ \ BN_UINT macroTmpX3 = macroTmpUh * macroTmpVh; \ BN_UINT macroTmpX2 = macroTmpUh * macroTmpVl; \ BN_UINT macroTmpX1 = macroTmpUl * macroTmpVh; \ BN_UINT macroTmpX0 = macroTmpUl * macroTmpVl; \ macroTmpX1 += BN_UINT_HI(macroTmpX0); \ macroTmpX0 = (u) * (v); \ macroTmpX1 += macroTmpX2; \ macroTmpX3 = macroTmpX3 + BN_UINT_HI(macroTmpX1); \ \ (l) += macroTmpX0; \ \ if (macroTmpX1 < macroTmpX2) { macroTmpX3 += BN_UINT_HC; } \ macroTmpX3 += ((l) < macroTmpX0); \ (m) += macroTmpX3; \ (h) += ((m) < macroTmpX3); \ } while (0) /* h|m|l = h|m|l + 2 * u * v. Ensure that the value of h is not too large to avoid carry. */ #define MULADD_AB2(h, m, l, u, v) \ do { \ MULADD_AB((h), (m), (l), (u), (v)); \ MULADD_AB((h), (m), (l), (u), (v)); \ } while (0) /* h|m|l = h|m|l + v * v. Ensure that the value of h is not too large to avoid carry. */ #define SQRADD_A(h, m, l, v) \ do { \ BN_UINT macroTmpVl = BN_UINT_LO(v); \ BN_UINT macroTmpVh = BN_UINT_HI(v); \ \ BN_UINT macroTmpX3 = macroTmpVh * macroTmpVh; \ BN_UINT macroTmpX2 = macroTmpVh * macroTmpVl; \ BN_UINT macroTmpX1 = macroTmpX2; \ BN_UINT macroTmpX0 = macroTmpVl * macroTmpVl; \ macroTmpX1 += BN_UINT_HI(macroTmpX0); \ macroTmpX0 = (v) * (v); \ macroTmpX1 += macroTmpX2; \ macroTmpX3 = macroTmpX3 + BN_UINT_HI(macroTmpX1); \ \ (l) += macroTmpX0; \ \ if (macroTmpX1 < macroTmpX2) { macroTmpX3 += BN_UINT_HC; } \ if ((l) < macroTmpX0) { macroTmpX3 += 1; } \ (m) += macroTmpX3; \ if ((m) < macroTmpX3) { (h)++; } \ } while (0) #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_BN */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_bincal_noasm.h
C
unknown
9,332
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BN_BINCAL_X8664_H #define BN_BINCAL_X8664_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include "bn_basic.h" #ifdef __cplusplus extern "c" { #endif // wh | wl = u * v #define MUL_AB(wh, wl, u, v) \ { \ __asm("mulq %3" : "=d"(wh), "=a"(wl) : "a"(u), "r"(v) : "cc"); \ } // wh | wl = u ^ 2 #define SQR_A(wh, wl, u) \ { \ __asm("mulq %2 " : "=d"(wh), "=a"(wl) : "a"(u) : "cc"); \ } // nh | nl / d = q...r #define DIV_ND(q, r, nh, nl, d) \ { \ __asm("divq %4" : "=a"(q), "=d"(r) : "d"(nh), "a"(nl), "r"(d) : "cc"); \ } /* r += c * c = carry */ #define ADD_CARRY(carry, r) \ do { \ __asm("addq %1, %0 \n\t " \ "adcq %4, %1 \n\t " \ "adcq $0, %2 \n\t " \ : "+m"(l), "+r"(carry) \ : \ : "cc"); \ } while (0) /* h|m|l = h|m|l + u * v. Ensure that the value of h is not too large to avoid carry. */ #define MULXADD_AB(h, m, l, u, v) \ do { \ BN_UINT hi, lo; \ __asm("mulq %0, %1, %2" : "=a"(lo), "=d"(hi) : "a"(u), "m"(v) : "cc"); \ __asm("addq %3, %0 \n\t " \ "adcq %4, %1 \n\t " \ "adcq $0, %2 \n\t " \ : "+r"(l), "+r"(m), "+r"(h) \ : "r"(lo), "r"(hi) \ : "cc"); \ } while (0) // (hi, lo) = a * b // r += lo + carry // carry = hi + c #define MULADC_AB(r, a, b, carry) \ do { \ BN_UINT hi, lo; \ __asm("mulq %3" : "=a"(lo), "=d"(hi) : "a"(a), "g"(b) : "cc"); \ __asm("addq %3, %1 \n\t" \ "adcq $0, %2 \n\t" \ "addq %1, %0 \n\t" \ "adcq $0, %2 \n\t" \ "movq %2, %1 \n\t" \ : "+r"(r), "+r"(carry), "+r"(hi) \ : "r"(lo) \ : "cc"); \ } while (0) /* h|m|l = h|m|l + u * v. Ensure that the value of h is not too large to avoid carry. */ #define MULADD_AB(h, m, l, u, v) \ do { \ BN_UINT hi, lo; \ __asm("mulq %3" : "=a"(lo), "=d"(hi) : "a"(u), "m"(v) : "cc"); \ __asm("addq %3, %0 \n\t " \ "adcq %4, %1 \n\t " \ "adcq $0, %2 \n\t " \ : "+r"(l), "+r"(m), "+r"(h) \ : "r"(lo), "r"(hi) \ : "cc"); \ } while (0) /* h|m|l = h|m|l + 2 * u * v. Ensure that the value of h is not too large to avoid carry. */ #define MULADD_AB2(h, m, l, u, v) \ do { \ BN_UINT hi, lo; \ __asm("mulq %3" : "=a"(lo), "=d"(hi) : "a"(u), "m"(v) : "cc"); \ __asm("addq %3, %0 \n\t " \ "adcq %4, %1 \n\t " \ "adcq $0, %2 \n\t " \ "addq %3, %0 \n\t " \ "adcq %4, %1 \n\t " \ "adcq $0, %2 \n\t " \ : "+r"(l), "+r"(m), "+r"(h) \ : "r"(lo), "r"(hi) \ : "cc"); \ } while (0) /* h|m|l = h|m|l + u * u. Ensure that the value of h is not too large to avoid carry. */ #define SQRADD_A(h, m, l, u) MULADD_AB(h, m, l, u, u) #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_BN */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_bincal_x8664.h
C
unknown
5,705
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_BN) && defined(HITLS_CRYPTO_BN_COMBA) #include <stdint.h> #include "bn_bincal.h" #define SQR_COMBA_BEGIN_1(r, a, h, m, l) do { \ SQRADD_A((h), (m), (l), (a)[0]); \ (r)[0] = (l); \ (l) = 0; \ MULADD_AB2((l), (h), (m), (a)[0], (a)[1]); \ (r)[1] = (m); \ (m) = 0; \ MULADD_AB2((m), (l), (h), (a)[0], (a)[2]); /* 0 + 2 = 2 */ \ SQRADD_A((m), (l), (h), (a)[1]); /* 1 + 1 = 2 */ \ (r)[2] = (h); /* 2 */ \ (h) = 0; \ MULADD_AB2((h), (m), (l), (a)[1], (a)[2]); /* 1 + 2 = 3 */ \ MULADD_AB2((h), (m), (l), (a)[0], (a)[3]); /* 0 + 3 = 3 */ \ (r)[3] = (l); /* 3 */ \ (l) = 0; \ } while (0) #define SQR_COMBA_BEGIN_2(r, a, h, m, l) do { \ MULADD_AB2((l), (h), (m), (a)[0], (a)[4]); /* 0 + 4 = 4 */ \ MULADD_AB2((l), (h), (m), (a)[1], (a)[3]); /* 1 + 3 = 4 */ \ SQRADD_A((l), (h), (m), (a)[2]); /* 2 + 2 = 4 */ \ (r)[4] = (m); /* 4 */ \ (m) = 0; \ MULADD_AB2((m), (l), (h), (a)[2], (a)[3]); /* 2 + 3 = 5 */ \ MULADD_AB2((m), (l), (h), (a)[1], (a)[4]); /* 1 + 4 = 5 */ \ MULADD_AB2((m), (l), (h), (a)[0], (a)[5]); /* 0 + 5 = 5 */ \ (r)[5] = (h); /* 5 */ \ (h) = 0; \ } while (0) #define MUL_COMBA_BEGIN_1(r, a, b, h, m, l) do { \ MULADD_AB((h), (m), (l), (a)[0], (b)[0]); \ (r)[0] = (l); \ (l) = 0; \ MULADD_AB((l), (h), (m), (a)[0], (b)[1]); \ MULADD_AB((l), (h), (m), (a)[1], (b)[0]); \ (r)[1] = (m); \ (m) = 0; \ MULADD_AB((m), (l), (h), (a)[2], (b)[0]); /* 2 + 0 = 2 */ \ MULADD_AB((m), (l), (h), (a)[1], (b)[1]); /* 1 + 1 = 2 */ \ MULADD_AB((m), (l), (h), (a)[0], (b)[2]); /* 0 + 2 = 2 */ \ (r)[2] = (h); \ (h) = 0; \ MULADD_AB((h), (m), (l), (a)[0], (b)[3]); /* 0 + 3 = 3 */ \ MULADD_AB((h), (m), (l), (a)[1], (b)[2]); /* 1 + 2 = 3 */ \ MULADD_AB((h), (m), (l), (a)[2], (b)[1]); /* 2 + 1 = 3 */ \ MULADD_AB((h), (m), (l), (a)[3], (b)[0]); /* 3 + 9 = 3 */ \ (r)[3] = (l); /* 3 */ \ (l) = 0; \ } while (0) #define MUL_COMBA_BEGIN_2(r, a, b, h, m, l) do { \ MULADD_AB((l), (h), (m), (a)[4], (b)[0]); /* 4 + 0 = 4 */ \ MULADD_AB((l), (h), (m), (a)[3], (b)[1]); /* 3 + 1 = 4 */ \ MULADD_AB((l), (h), (m), (a)[2], (b)[2]); /* 2 + 2 = 4 */ \ MULADD_AB((l), (h), (m), (a)[1], (b)[3]); /* 1 + 3 = 4 */ \ MULADD_AB((l), (h), (m), (a)[0], (b)[4]); /* 0 + 4 = 4 */ \ (r)[4] = (m); /* 4 */ \ (m) = 0; \ MULADD_AB((m), (l), (h), (a)[0], (b)[5]); /* 0 + 5 = 5 */ \ MULADD_AB((m), (l), (h), (a)[1], (b)[4]); /* 1 + 4 = 5 */ \ MULADD_AB((m), (l), (h), (a)[2], (b)[3]); /* 2 + 3 = 5 */ \ MULADD_AB((m), (l), (h), (a)[3], (b)[2]); /* 3 + 2 = 5 */ \ MULADD_AB((m), (l), (h), (a)[4], (b)[1]); /* 4 + 1 = 5 */ \ MULADD_AB((m), (l), (h), (a)[5], (b)[0]); /* 5 + 0 = 5 */ \ (r)[5] = (h); /* 5 */ \ (h) = 0; \ } while (0) #define MUL_COMBA_BEGIN_3(r, a, b, h, m, l) do { \ MULADD_AB((h), (m), (l), (a)[6], (b)[0]); /* 6 + 0 = 6 */ \ MULADD_AB((h), (m), (l), (a)[5], (b)[1]); /* 5 + 1 = 6 */ \ MULADD_AB((h), (m), (l), (a)[4], (b)[2]); /* 4 + 2 = 6 */ \ MULADD_AB((h), (m), (l), (a)[3], (b)[3]); /* 3 + 3 = 6 */ \ MULADD_AB((h), (m), (l), (a)[2], (b)[4]); /* 2 + 4 = 6 */ \ MULADD_AB((h), (m), (l), (a)[1], (b)[5]); /* 1 + 5 = 6 */ \ MULADD_AB((h), (m), (l), (a)[0], (b)[6]); /* 0 + 6 = 6 */ \ (r)[6] = (l); /* 6 */ \ (l) = 0; \ MULADD_AB((l), (h), (m), (a)[0], (b)[7]); /* 0 + 7 = 7 */ \ MULADD_AB((l), (h), (m), (a)[1], (b)[6]); /* 1 + 6 = 7 */ \ MULADD_AB((l), (h), (m), (a)[2], (b)[5]); /* 2 + 5 = 7 */ \ MULADD_AB((l), (h), (m), (a)[3], (b)[4]); /* 3 + 4 = 7 */ \ MULADD_AB((l), (h), (m), (a)[4], (b)[3]); /* 4 + 3 = 7 */ \ MULADD_AB((l), (h), (m), (a)[5], (b)[2]); /* 5 + 2 = 7 */ \ MULADD_AB((l), (h), (m), (a)[6], (b)[1]); /* 6 + 1 = 7 */ \ MULADD_AB((l), (h), (m), (a)[7], (b)[0]); /* 7 + 0 = 7 */ \ (r)[7] = (m); /* 7 */ \ (m) = 0; \ MULADD_AB((m), (l), (h), (a)[7], (b)[1]); /* 7 + 1 = 8 */ \ MULADD_AB((m), (l), (h), (a)[6], (b)[2]); /* 6 + 2 = 8 */ \ MULADD_AB((m), (l), (h), (a)[5], (b)[3]); /* 5 + 3 = 8 */ \ MULADD_AB((m), (l), (h), (a)[4], (b)[4]); /* 4 + 4 = 8 */ \ MULADD_AB((m), (l), (h), (a)[3], (b)[5]); /* 3 + 5 = 8 */ \ MULADD_AB((m), (l), (h), (a)[2], (b)[6]); /* 2 + 6 = 8 */ \ MULADD_AB((m), (l), (h), (a)[1], (b)[7]); /* 1 + 7 = 8 */ \ (r)[8] = (h); /* 8 */ \ (h) = 0; \ } while (0) static void SqrComba8(BN_UINT *r, const BN_UINT *a) { BN_UINT h = 0; BN_UINT m = 0; BN_UINT l = 0; SQR_COMBA_BEGIN_1(r, a, h, m, l); SQR_COMBA_BEGIN_2(r, a, h, m, l); MULADD_AB2(h, m, l, a[0], a[6]); /* 0 + 6 = 6 */ MULADD_AB2(h, m, l, a[1], a[5]); /* 1 + 5 = 6 */ MULADD_AB2(h, m, l, a[2], a[4]); /* 2 + 4 = 6 */ SQRADD_A(h, m, l, a[3]); /* 3 + 3 = 6 */ r[6] = l; /* 6 */ l = 0; MULADD_AB2(l, h, m, a[3], a[4]); /* 3 + 4 = 7 */ MULADD_AB2(l, h, m, a[2], a[5]); /* 2 + 5 = 7 */ MULADD_AB2(l, h, m, a[1], a[6]); /* 1 + 6 = 7 */ MULADD_AB2(l, h, m, a[0], a[7]); /* 0 + 7 = 7 */ r[7] = m; /* 7 */ m = 0; MULADD_AB2(m, l, h, a[1], a[7]); /* 1 + 7 = 8 */ MULADD_AB2(m, l, h, a[2], a[6]); /* 2 + 6 = 8 */ MULADD_AB2(m, l, h, a[3], a[5]); /* 3 + 5 = 8 */ SQRADD_A(m, l, h, a[4]); /* 4 + 4 = 8 */ r[8] = h; /* 8 */ h = 0; MULADD_AB2(h, m, l, a[4], a[5]); /* 4 + 5 = 9 */ MULADD_AB2(h, m, l, a[3], a[6]); /* 3 + 6 = 9 */ MULADD_AB2(h, m, l, a[2], a[7]); /* 2 + 7 = 9 */ r[9] = l; /* 9 */ l = 0; MULADD_AB2(l, h, m, a[3], a[7]); /* 3 + 7 = 10 */ MULADD_AB2(l, h, m, a[4], a[6]); /* 4 + 6 = 10 */ SQRADD_A(l, h, m, a[5]); /* 5 + 5 = 10 */ r[10] = m; /* 10 */ m = 0; MULADD_AB2(m, l, h, a[5], a[6]); /* 5 + 6 = 11 */ MULADD_AB2(m, l, h, a[4], a[7]); /* 4 + 7 = 11 */ r[11] = h; /* 11 */ h = 0; MULADD_AB2(h, m, l, a[5], a[7]); /* 5 + 7 = 12 */ SQRADD_A(h, m, l, a[6]); /* 6 + 6 = 12 */ r[12] = l; /* 12 */ l = 0; MULADD_AB2(l, h, m, a[6], a[7]); /* 6 + 7 = 13 */ r[13] = m; /* 13 */ m = 0; SQRADD_A(m, l, h, a[7]); /* 7 + 7 = 14 */ r[14] = h; /* 14 */ r[15] = l; /* 15 */ } void SqrComba6(BN_UINT *r, const BN_UINT *a) { BN_UINT h = 0; BN_UINT m = 0; BN_UINT l = 0; SQR_COMBA_BEGIN_1(r, a, h, m, l); SQR_COMBA_BEGIN_2(r, a, h, m, l); MULADD_AB2(h, m, l, a[1], a[5]); /* 1 + 5 = 6 */ MULADD_AB2(h, m, l, a[2], a[4]); /* 2 + 4 = 6 */ SQRADD_A(h, m, l, a[3]); /* 3 + 3 = 6 */ r[6] = l; /* 6 */ l = 0; MULADD_AB2(l, h, m, a[3], a[4]); /* 3 + 4 = 7 */ MULADD_AB2(l, h, m, a[2], a[5]); /* 2 + 5 = 7 */ r[7] = m; /* 7 */ m = 0; MULADD_AB2(m, l, h, a[3], a[5]); /* 3 + 5 = 8 */ SQRADD_A(m, l, h, a[4]); /* 4 + 4 = 8 */ r[8] = h; /* 8 */ h = 0; MULADD_AB2(h, m, l, a[4], a[5]); /* 4 + 5 = 9 */ r[9] = l; /* 9 */ l = 0; SQRADD_A(l, h, m, a[5]); /* 5 + 5 = 10 */ r[10] = m; /* 10 */ r[11] = h; /* 11 */ } void SqrComba4(BN_UINT *r, const BN_UINT *a) { BN_UINT h = 0; BN_UINT m = 0; BN_UINT l = 0; SQR_COMBA_BEGIN_1(r, a, h, m, l); MULADD_AB2(l, h, m, a[1], a[3]); /* 1 + 3 = 4 */ SQRADD_A(l, h, m, a[2]); /* 2 + 2 = 4 */ r[4] = m; /* 4 */ m = 0; MULADD_AB2(m, l, h, a[2], a[3]); /* 2 + 3 = 5 */ r[5] = h; /* 5 */ h = 0; SQRADD_A(h, m, l, a[3]); /* 3 + 3 = 6 */ r[6] = l; /* 6 */ r[7] = m; /* 7 */ } static void SqrComba(BN_UINT *r, const BN_UINT *a, uint32_t size) { BN_UINT h = 0; BN_UINT m = 0; BN_UINT l = 0; if (size == 3) { /* 3 */ SQRADD_A(h, m, l, a[0]); r[0] = l; l = 0; MULADD_AB2(l, h, m, a[0], a[1]); r[1] = m; m = 0; MULADD_AB2(m, l, h, a[0], a[2]); /* 0 + 2 = 2 */ SQRADD_A(m, l, h, a[1]); /* 1 + 1 = 2 */ r[2] = h; /* 2 */ h = 0; MULADD_AB2(h, m, l, a[1], a[2]); /* 1 + 2 = 3 */ r[3] = l; /* 3 */ l = 0; SQRADD_A(l, h, m, a[2]); /* 2 + 2 = 4 */ r[4] = m; /* 4 */ r[5] = h; /* 5 */ return; } if (size == 2) { /* 2 */ SQRADD_A(h, m, l, a[0]); r[0] = l; l = 0; MULADD_AB2(l, h, m, a[0], a[1]); r[1] = m; m = 0; SQRADD_A(m, l, h, a[1]); /* 1 + 1 = 2 */ r[2] = h; /* 2 */ r[3] = l; /* 3 */ return; } SQR_A(r[1], r[0], a[0]); /* size == 1 */ } void MulComba8(BN_UINT *r, const BN_UINT *a, const BN_UINT *b) { BN_UINT h = 0; BN_UINT m = 0; BN_UINT l = 0; MUL_COMBA_BEGIN_1(r, a, b, h, m, l); MUL_COMBA_BEGIN_2(r, a, b, h, m, l); MUL_COMBA_BEGIN_3(r, a, b, h, m, l); MULADD_AB(h, m, l, a[2], b[7]); /* 2 + 7 = 9 */ MULADD_AB(h, m, l, a[3], b[6]); /* 3 + 6 = 9 */ MULADD_AB(h, m, l, a[4], b[5]); /* 4 + 5 = 9 */ MULADD_AB(h, m, l, a[5], b[4]); /* 5 + 4 = 9 */ MULADD_AB(h, m, l, a[6], b[3]); /* 6 + 3 = 9 */ MULADD_AB(h, m, l, a[7], b[2]); /* 7 + 2 = 9 */ r[9] = l; /* 9 */ l = 0; MULADD_AB(l, h, m, a[7], b[3]); /* 7 + 3 = 10 */ MULADD_AB(l, h, m, a[6], b[4]); /* 6 + 4 = 10 */ MULADD_AB(l, h, m, a[5], b[5]); /* 5 + 5 = 10 */ MULADD_AB(l, h, m, a[4], b[6]); /* 4 + 6 = 10 */ MULADD_AB(l, h, m, a[3], b[7]); /* 3 + 7 = 10 */ r[10] = m; /* 10 */ m = 0; MULADD_AB(m, l, h, a[4], b[7]); /* 4 + 7 = 11 */ MULADD_AB(m, l, h, a[5], b[6]); /* 5 + 6 = 11 */ MULADD_AB(m, l, h, a[6], b[5]); /* 6 + 5 = 11 */ MULADD_AB(m, l, h, a[7], b[4]); /* 7 + 4 = 11 */ r[11] = h; /* 11 */ h = 0; MULADD_AB(h, m, l, a[7], b[5]); /* 7 + 5 = 12 */ MULADD_AB(h, m, l, a[6], b[6]); /* 6 + 6 = 12 */ MULADD_AB(h, m, l, a[5], b[7]); /* 5 + 7 = 12 */ r[12] = l; /* 12 */ l = 0; MULADD_AB(l, h, m, a[6], b[7]); /* 6 + 7 = 13 */ MULADD_AB(l, h, m, a[7], b[6]); /* 7 + 6 = 13 */ r[13] = m; /* 13 */ m = 0; MULADD_AB(m, l, h, a[7], b[7]); /* 7 + 7 = 14 */ r[14] = h; /* 14 */ r[15] = l; /* 15 */ } void MulComba6(BN_UINT *r, const BN_UINT *a, const BN_UINT *b) { BN_UINT h = 0; BN_UINT m = 0; BN_UINT l = 0; MUL_COMBA_BEGIN_1(r, a, b, h, m, l); MUL_COMBA_BEGIN_2(r, a, b, h, m, l); MULADD_AB(h, m, l, a[5], b[1]); /* 5 + 1 = 6 */ MULADD_AB(h, m, l, a[4], b[2]); /* 4 + 2 = 6 */ MULADD_AB(h, m, l, a[3], b[3]); /* 3 + 3 = 6 */ MULADD_AB(h, m, l, a[2], b[4]); /* 2 + 4 = 6 */ MULADD_AB(h, m, l, a[1], b[5]); /* 1 + 5 = 6 */ r[6] = l; /* 6 */ l = 0; MULADD_AB(l, h, m, a[2], b[5]); /* 2 + 5 = 7 */ MULADD_AB(l, h, m, a[3], b[4]); /* 3 + 4 = 7 */ MULADD_AB(l, h, m, a[4], b[3]); /* 4 + 3 = 7 */ MULADD_AB(l, h, m, a[5], b[2]); /* 5 + 2 = 7 */ r[7] = m; /* 7 */ m = 0; MULADD_AB(m, l, h, a[5], b[3]); /* 5 + 3 = 8 */ MULADD_AB(m, l, h, a[4], b[4]); /* 4 + 4 = 8 */ MULADD_AB(m, l, h, a[3], b[5]); /* 3 + 5 = 8 */ r[8] = h; /* 8 */ h = 0; MULADD_AB(h, m, l, a[4], b[5]); /* 4 + 5 = 9 */ MULADD_AB(h, m, l, a[5], b[4]); /* 5 + 4 = 9 */ r[9] = l; /* 9 */ l = 0; MULADD_AB(l, h, m, a[5], b[5]); /* 5 + 5 = 10 */ r[10] = m; /* 10 */ r[11] = h; /* 11 */ } void MulComba4(BN_UINT *r, const BN_UINT *a, const BN_UINT *b) { BN_UINT h = 0; BN_UINT m = 0; BN_UINT l = 0; MUL_COMBA_BEGIN_1(r, a, b, h, m, l); MULADD_AB(l, h, m, a[3], b[1]); /* 3 + 1 = 4 */ MULADD_AB(l, h, m, a[2], b[2]); /* 2 + 2 = 4 */ MULADD_AB(l, h, m, a[1], b[3]); /* 1 + 3 = 4 */ r[4] = m; /* 4 */ m = 0; MULADD_AB(m, l, h, a[2], b[3]); /* 2 + 3 = 5 */ MULADD_AB(m, l, h, a[3], b[2]); /* 3 + 2 = 5 */ r[5] = h; /* 5 */ h = 0; MULADD_AB(h, m, l, a[3], b[3]); /* 3 + 3 = 6 */ r[6] = l; /* 6 */ r[7] = m; /* 7 */ } static void MulComba(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t size) { BN_UINT h = 0; BN_UINT m = 0; BN_UINT l = 0; if (size == 3) { /* 3 */ MULADD_AB(h, m, l, a[0], b[0]); r[0] = l; l = 0; MULADD_AB(l, h, m, a[0], b[1]); MULADD_AB(l, h, m, a[1], b[0]); r[1] = m; m = 0; MULADD_AB(m, l, h, a[2], b[0]); /* 2 + 0 = 2 */ MULADD_AB(m, l, h, a[1], b[1]); /* 1 + 1 = 2 */ MULADD_AB(m, l, h, a[0], b[2]); /* 0 + 2 = 2 */ r[2] = h; h = 0; MULADD_AB(h, m, l, a[1], b[2]); /* 1 + 2 = 3 */ MULADD_AB(h, m, l, a[2], b[1]); /* 2 + 1 = 3 */ r[3] = l; /* 3 */ l = 0; MULADD_AB(l, h, m, a[2], b[2]); /* 2 + 2 = 4 */ r[4] = m; /* 4 */ r[5] = h; /* 5 */ return; } if (size == 2) { /* 2 */ MULADD_AB(h, m, l, a[0], b[0]); r[0] = l; l = 0; MULADD_AB(l, h, m, a[0], b[1]); MULADD_AB(l, h, m, a[1], b[0]); r[1] = m; m = 0; MULADD_AB(m, l, h, a[1], b[1]); r[2] = h; /* 2 */ r[3] = l; /* 3 */ return; } MUL_AB(r[1], r[0], a[0], b[0]); /* size == 1 */ } uint32_t SpaceSize(uint32_t size) { uint32_t base = 8; /* Perform 8x batch processing */ while (size > base) { base <<= 1; } return base * 4; /* 2x expansion. Each layer requires 2 * size temporary space, 2 * 2 = 4 */ } /* compare BN array. * return 0, if a == b * return 1, if a > b * return -1, if a < b */ static int32_t BinCmpSame(const BN_UINT *a, const BN_UINT *b, uint32_t size) { int64_t idx = (int64_t)size; while (--idx >= 0) { if (a[idx] != b[idx]) { return a[idx] > b[idx] ? 1 : -1; } } return 0; } /* The caller promised that aSize >= bSize. * r = ABS(a - b). Need to ensure that aSize == bSize + (0 || 1). * return 0 if a > b * return 1 if a <= b */ static uint32_t ABS_Sub(BN_UINT *t, const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize) { int32_t ret; do { if (aSize > bSize) { t[bSize] = a[bSize]; /* bSize = aSize - 1 */ if (a[bSize] > 0) { ret = 1; break; } } ret = BinCmpSame(a, b, bSize); } while (0); if (ret > 0) { BN_UINT borrow = BinSub(t, a, b, bSize); if (aSize > bSize) { /* When the length difference exists and a > b exists, the borrowing is processed. */ t[bSize] -= borrow; } return 0; } else { BinSub(t, b, a, bSize); return 1; } return 0; } /** Only aSize == bSize is supported. This interface will recurse. The recursion depth is O(deep) = log2(size) * Ensure that space >= SpaceSize(size) * (ah|al * bh|bl) = (((ah*bh) << 2) + (((ah*bh) + (al*bl) - (ah - al)(bh - bl)) << 1) + (al*bl)) */ void MulConquer(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t size, BN_UINT *space, bool consttime) { if (!consttime) { if (size == 8) { /* Perform 8x batch processing */ MulComba8(r, a, b); return; } if (size == 6) { /* Perform 6x batch processing */ MulComba6(r, a, b); return; } if (size == 4) { /* Perform 4x batch processing */ MulComba4(r, a, b); return; } if (size < 4) { /* Less than 4, simple processing */ MulComba(r, a, b, size); return; } } else if (size <= 8) { /* Calculate if the block size is smaller than 8. */ BinMul(r, size << 1, a, size, b, size); return; } /* truncates the length of the low bits of the BigNum, that is the length of al bl. */ const uint32_t sizeLo = size >> 1; const uint32_t sizeLo2 = sizeLo << 1; const uint32_t shift1 = sizeLo; /* (((ah*bh) + (al*bl) - (ah - al)(bh - bl)) << 1) location */ const uint32_t shift2 = shift1 << 1; /* ((ah*bh) << 2) location */ /* truncates the length of the high bits of the BigNum, that is the length of ah bh. */ const uint32_t sizeHi = size - sizeLo; const uint32_t sizeHi2 = sizeHi << 1; /* Split the input 'space'. The current function uses tmp1 and tmp2, * and the remaining newspace is used by the lower layer. * space = tmp1_lo..tmp1_hi | tmp2_lo..tmp2_hi | newSpace, sizeof(tmp1_lo) == sizeHi. */ BN_UINT *tmp1 = space; BN_UINT *tmp2 = tmp1 + sizeHi2; BN_UINT *newSpace = tmp2 + sizeHi2; /* tmp2_lo = (ah-al) */ uint32_t sign = ABS_Sub(tmp2, a + shift1, sizeHi, a, sizeLo); /* tmp2_hi = (bh-bl) */ sign ^= ABS_Sub(tmp2 + sizeHi, b + shift1, sizeHi, b, sizeLo); MulConquer(r, a, b, sizeLo, newSpace, consttime); /* calculate (al*bl) */ MulConquer(r + shift2, a + shift1, b + shift1, sizeHi, newSpace, consttime); /* calculate (ah*bh) */ MulConquer(tmp1, tmp2, tmp2 + sizeHi, sizeHi, newSpace, consttime); /* calculate (ah-al)(bh-bl) */ /* At this time r has stored ((ah*bh) << 2) and (al*bl) */ /* carry should be added in (r + shift1)[sizeHi * 2] */ /* tmp2 is (ah*bh) + (al*bl), but the processing length here is sizeLo * 2 */ BN_UINT carry = BinAdd(tmp2, r, r + shift2, sizeLo2); if (sizeHi > sizeLo) { /* If there is a length difference, the length of (ah*bh) is sizeLo * 2 + 2, and the tail of (ah*bh) needs to be processed. */ /* point to (r + shift2)[sizeLo * 2], the unprocessed tail of (ah*bh) */ const uint32_t position = shift2 + (sizeLo2); tmp2[sizeLo2] = r[position] + carry; carry = (tmp2[sizeLo2] < carry) ? 1 : 0; /* continue the processing */ tmp2[(sizeLo2) + 1] = r[position + 1] + carry; carry = (tmp2[sizeLo2 + 1] < carry) ? 1 : 0; } /* tmp1 = (ah*bh) + (al*bl) - (ah-al)(bh-bl), tmp2 is (ah*bh) + (al*bl) */ if (sign == 1) { carry += BinAdd(tmp1, tmp2, tmp1, sizeHi2); } else { carry -= BinSub(tmp1, tmp2, tmp1, sizeHi2); } /* finally r adds tmp1, that is (ah*bh) + (al*bl) - (ah - al)(bh - bl) */ carry += BinAdd(r + shift1, r + shift1, tmp1, sizeHi2); for (uint32_t i = shift1 + sizeHi2; carry > 0 && i < (size << 1); i++) { ADD_AB(carry, r[i], r[i], carry); } } /** This interface will recurse. The recursion depth is O(deep) = log2(size) * Ensure that space >= SpaceSize(size) * (x|y)^2 = ((x^2 << 2) + ((x^2 + y^2 - (x - y)^2)) << 1) + y^2) */ void SqrConquer(BN_UINT *r, const BN_UINT *a, uint32_t size, BN_UINT *space, bool consttime) { if (!consttime) { if (size == 8) { /* Perform 8x batch processing */ SqrComba8(r, a); return; } if (size == 6) { /* Perform 6x batch processing */ SqrComba6(r, a); return; } if (size == 4) { /* Perform 4x batch processing */ SqrComba4(r, a); return; } if (size < 4) { /* Less than 4, simple processing */ SqrComba(r, a, size); return; } } else if (size <= 8) { /* Calculate if the block size is smaller than 8. */ BinSqr(r, size << 1, a, size); return; } /* truncates the length of the high bits of the BigNum, that is the length of x. */ const uint32_t sizeHi = (size + 1) >> 1; /* truncates the length of the low bits of the BigNum, that is the length of y. */ const uint32_t sizeLo = size >> 1; const uint32_t shift1 = sizeLo; /* ((x^2 + y^2 - (x - y)^2)) << 1) location */ const uint32_t shift2 = shift1 << 1; /* ((x^2 << 2) location */ /* Split the input 'space'. The current function uses tmp1 and tmp2, and the remaining newspace is used by the lower layer. */ BN_UINT *tmp1 = space; BN_UINT *tmp2 = tmp1 + (sizeHi << 1); BN_UINT *newSpace = tmp2 + (sizeHi << 1); /* tmp2 is the upper bits of num minus the lower bits of num, (x-y) */ (void)ABS_Sub(tmp2, a + shift1, sizeHi, a, sizeLo); SqrConquer(r, a, sizeLo, newSpace, consttime); /* calculate y^2 */ SqrConquer(r + shift2, a + shift1, sizeHi, newSpace, consttime); /* calculate x^2 */ SqrConquer(tmp1, tmp2, sizeHi, newSpace, consttime); /* calculate (x-y)^2 */ /* At this time r has stored (x^2 << 2) and y^2 */ /* carry should be added in (r + shift1)[sizeHi * 2] */ /* tmp2 = x^2 + y^2, but the processing length here is sizeLo * 2 */ BN_UINT carry = BinAdd(tmp2, r, r + shift2, sizeLo << 1); if (sizeHi > sizeLo) { /* If there is a length difference, the length of x^2 is sizeLo * 2 + 2, and the tail of x^2 needs to be processed. */ /* point to (r + shift2)[sizeLo * 2], the unprocessed tail of x^2 */ const uint32_t position = shift2 + (sizeLo << 1); tmp2[sizeLo << 1] = r[position] + carry; carry = (tmp2[sizeLo << 1] < carry) ? 1 : 0; /* continue the processing */ tmp2[(sizeLo << 1) + 1] = r[position + 1] + carry; carry = (tmp2[(sizeLo << 1) + 1] < carry) ? 1 : 0; } /* tmp1 = x^2 + y^2 - (x-y)^2, tmp2 is x^2 + y^2 */ carry -= BinSub(tmp1, tmp2, tmp1, sizeHi << 1); /* finally r adds x^2 + y^2 - (x-y)^2 */ carry += BinAdd(r + shift1, r + shift1, tmp1, sizeHi << 1); uint32_t i; for (i = shift1 + (sizeHi << 1); carry > 0 && i < (size << 1); i++) { ADD_AB(carry, r[i], r[i], carry); } } #endif /* HITLS_CRYPTO_BN_COMBA */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_comba.c
C
unknown
25,469
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN_PRIME_RFC3526 #include "crypt_errno.h" #include "bn_basic.h" #if defined(HITLS_SIXTY_FOUR_BITS) // RFC 3526: 2048-bit MODP GroupUL, this prime is: 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 } static const BN_UINT RFC3526_PRIME_2048[] = { 0xFFFFFFFFFFFFFFFFUL, 0x15728E5A8AACAA68UL, 0x15D2261898FA0510UL, 0x3995497CEA956AE5UL, 0xDE2BCBF695581718UL, 0xB5C55DF06F4C52C9UL, 0x9B2783A2EC07A28FUL, 0xE39E772C180E8603UL, 0x32905E462E36CE3BUL, 0xF1746C08CA18217CUL, 0x1C62F356208552BBUL, 0x83655D23DCA3AD96UL, 0x69163FA8FD24CF5FUL, 0x98DA48361C55D39AUL, 0xC2007CB8A163BF05UL, 0x49286651ECE45B3DUL, 0xAE9F24117C4B1FE6UL, 0xEE386BFB5A899FA5UL, 0x0BFF5CB6F406B7EDUL, 0xF44C42E9A637ED6BUL, 0xE485B576625E7EC6UL, 0x4FE1356D6D51C245UL, 0x302B0A6DF25F1437UL, 0xEF9519B3CD3A431BUL, 0x514A08798E3404DDUL, 0x020BBEA63B139B22UL, 0x29024E088A67CC74UL, 0xC4C6628B80DC1CD1UL, 0xC90FDAA22168C234UL, 0xFFFFFFFFFFFFFFFFUL }; // RFC 3526: 3072-bit MODP GroupUL, this prime is: 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 } static const BN_UINT RFC3526_PRIME_3072[] = { 0xFFFFFFFFFFFFFFFFUL, 0x4B82D120A93AD2CAUL, 0x43DB5BFCE0FD108EUL, 0x08E24FA074E5AB31UL, 0x770988C0BAD946E2UL, 0xBBE117577A615D6CUL, 0x521F2B18177B200CUL, 0xD87602733EC86A64UL, 0xF12FFA06D98A0864UL, 0xCEE3D2261AD2EE6BUL, 0x1E8C94E04A25619DUL, 0xABF5AE8CDB0933D7UL, 0xB3970F85A6E1E4C7UL, 0x8AEA71575D060C7DUL, 0xECFB850458DBEF0AUL, 0xA85521ABDF1CBA64UL, 0xAD33170D04507A33UL, 0x15728E5A8AAAC42DUL, 0x15D2261898FA0510UL, 0x3995497CEA956AE5UL, 0xDE2BCBF695581718UL, 0xB5C55DF06F4C52C9UL, 0x9B2783A2EC07A28FUL, 0xE39E772C180E8603UL, 0x32905E462E36CE3BUL, 0xF1746C08CA18217CUL, 0x670C354E4ABC9804UL, 0x9ED529077096966DUL, 0x1C62F356208552BBUL, 0x83655D23DCA3AD96UL, 0x69163FA8FD24CF5FUL, 0x98DA48361C55D39AUL, 0xC2007CB8A163BF05UL, 0x49286651ECE45B3DUL, 0xAE9F24117C4B1FE6UL, 0xEE386BFB5A899FA5UL, 0x0BFF5CB6F406B7EDUL, 0xF44C42E9A637ED6BUL, 0xE485B576625E7EC6UL, 0x4FE1356D6D51C245UL, 0x302B0A6DF25F1437UL, 0xEF9519B3CD3A431BUL, 0x514A08798E3404DDUL, 0x020BBEA63B139B22UL, 0x29024E088A67CC74UL, 0xC4C6628B80DC1CD1UL, 0xC90FDAA22168C234UL, 0xFFFFFFFFFFFFFFFFUL }; // RFC 3526: 4096-bit MODP GroupUL, this prime is: 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 } static const BN_UINT RFC3526_PRIME_4096[] = { 0xFFFFFFFFFFFFFFFFUL, 0x4DF435C934063199UL, 0x86FFB7DC90A6C08FUL, 0x93B4EA988D8FDDC1UL, 0xD0069127D5B05AA9UL, 0xB81BDD762170481CUL, 0x1F612970CEE2D7AFUL, 0x233BA186515BE7EDUL, 0x99B2964FA090C3A2UL, 0x287C59474E6BC05DUL, 0x2E8EFC141FBECAA6UL, 0xDBBBC2DB04DE8EF9UL, 0x2583E9CA2AD44CE8UL, 0x1A946834B6150BDAUL, 0x99C327186AF4E23CUL, 0x88719A10BDBA5B26UL, 0x1A723C12A787E6D7UL, 0x4B82D120A9210801UL, 0x43DB5BFCE0FD108EUL, 0x08E24FA074E5AB31UL, 0x770988C0BAD946E2UL, 0xBBE117577A615D6CUL, 0x521F2B18177B200CUL, 0xD87602733EC86A64UL, 0xF12FFA06D98A0864UL, 0xCEE3D2261AD2EE6BUL, 0x1E8C94E04A25619DUL, 0xABF5AE8CDB0933D7UL, 0xB3970F85A6E1E4C7UL, 0x8AEA71575D060C7DUL, 0xECFB850458DBEF0AUL, 0xA85521ABDF1CBA64UL, 0xAD33170D04507A33UL, 0x15728E5A8AAAC42DUL, 0x15D2261898FA0510UL, 0x3995497CEA956AE5UL, 0xDE2BCBF695581718UL, 0xB5C55DF06F4C52C9UL, 0x9B2783A2EC07A28FUL, 0xE39E772C180E8603UL, 0x32905E462E36CE3BUL, 0xF1746C08CA18217CUL, 0x670C354E4ABC9804UL, 0x9ED529077096966DUL, 0x1C62F356208552BBUL, 0x83655D23DCA3AD96UL, 0x69163FA8FD24CF5FUL, 0x98DA48361C55D39AUL, 0xC2007CB8A163BF05UL, 0x49286651ECE45B3DUL, 0xAE9F24117C4B1FE6UL, 0xEE386BFB5A899FA5UL, 0x0BFF5CB6F406B7EDUL, 0xF44C42E9A637ED6BUL, 0xE485B576625E7EC6UL, 0x4FE1356D6D51C245UL, 0x302B0A6DF25F1437UL, 0xEF9519B3CD3A431BUL, 0x514A08798E3404DDUL, 0x020BBEA63B139B22UL, 0x29024E088A67CC74UL, 0xC4C6628B80DC1CD1UL, 0xC90FDAA22168C234UL, 0xFFFFFFFFFFFFFFFFUL }; #elif defined(HITLS_THIRTY_TWO_BITS) // RFC 3526: 2048-bit MODP Group, this prime is: 2^2048 - 2^1984 - 1 + 2^64 * { [2^1918 pi] + 124476 } static const BN_UINT RFC3526_PRIME_2048[] = { 0xFFFFFFFF, 0xFFFFFFFF, 0x8AACAA68, 0x15728E5A, 0x98FA0510, 0x15D22618, 0xEA956AE5, 0x3995497C, 0x95581718, 0xDE2BCBF6, 0x6F4C52C9, 0xB5C55DF0, 0xEC07A28F, 0x9B2783A2, 0x180E8603, 0xE39E772C, 0x2E36CE3B, 0x32905E46, 0xCA18217C, 0xF1746C08, 0x4ABC9804, 0x670C354E, 0x7096966D, 0x9ED52907, 0x208552BB, 0x1C62F356, 0xDCA3AD96, 0x83655D23, 0xFD24CF5F, 0x69163FA8, 0x1C55D39A, 0x98DA4836, 0xA163BF05, 0xC2007CB8, 0xECE45B3D, 0x49286651, 0x7C4B1FE6, 0xAE9F2411, 0x5A899FA5, 0xEE386BFB, 0xF406B7ED, 0x0BFF5CB6, 0xA637ED6B, 0xF44C42E9, 0x625E7EC6, 0xE485B576, 0x6D51C245, 0x4FE1356D, 0xF25F1437, 0x302B0A6D, 0xCD3A431B, 0xEF9519B3, 0x8E3404DD, 0x514A0879, 0x3B139B22, 0x020BBEA6, 0x8A67CC74, 0x29024E08, 0x80DC1CD1, 0xC4C6628B, 0x2168C234, 0xC90FDAA2, 0xFFFFFFFF, 0xFFFFFFFF }; // RFC 3526: 3072-bit MODP Group, this prime is: 2^3072 - 2^3008 - 1 + 2^64 * { [2^2942 pi] + 1690314 } static const BN_UINT RFC3526_PRIME_3072[] = { 0xFFFFFFFF, 0xFFFFFFFF, 0xA93AD2CA, 0x4B82D120, 0xE0FD108E, 0x43DB5BFC, 0x74E5AB31, 0x08E24FA0, 0xBAD946E2, 0x770988C0, 0x7A615D6C, 0xBBE11757, 0x177B200C, 0x521F2B18, 0x3EC86A64, 0xD8760273, 0xD98A0864, 0xF12FFA06, 0x1AD2EE6B, 0xCEE3D226, 0x4A25619D, 0x1E8C94E0, 0xDB0933D7, 0xABF5AE8C, 0xA6E1E4C7, 0xB3970F85, 0x5D060C7D, 0x8AEA7157, 0x58DBEF0A, 0xECFB8504, 0xDF1CBA64, 0xA85521AB, 0x04507A33, 0xAD33170D, 0x8AAAC42D, 0x15728E5A, 0x98FA0510, 0x15D22618, 0xEA956AE5, 0x3995497C, 0x95581718, 0xDE2BCBF6, 0x6F4C52C9, 0xB5C55DF0, 0xEC07A28F, 0x9B2783A2, 0x180E8603, 0xE39E772C, 0x2E36CE3B, 0x32905E46, 0xCA18217C, 0xF1746C08, 0x4ABC9804, 0x670C354E, 0x7096966D, 0x9ED52907, 0x208552BB, 0x1C62F356, 0xDCA3AD96, 0x83655D23, 0xFD24CF5F, 0x69163FA8, 0x1C55D39A, 0x98DA4836, 0xA163BF05, 0xC2007CB8, 0xECE45B3D, 0x49286651, 0x7C4B1FE6, 0xAE9F2411, 0x5A899FA5, 0xEE386BFB, 0xF406B7ED, 0x0BFF5CB6, 0xA637ED6B, 0xF44C42E9, 0x625E7EC6, 0xE485B576, 0x6D51C245, 0x4FE1356D, 0xF25F1437, 0x302B0A6D, 0xCD3A431B, 0xEF9519B3, 0x8E3404DD, 0x514A0879, 0x3B139B22, 0x020BBEA6, 0x8A67CC74, 0x29024E08, 0x80DC1CD1, 0xC4C6628B, 0x2168C234, 0xC90FDAA2, 0xFFFFFFFF, 0xFFFFFFFF }; // RFC 3526: 4096-bit MODP Group, this prime is: 2^4096 - 2^4032 - 1 + 2^64 * { [2^3966 pi] + 240904 } static const BN_UINT RFC3526_PRIME_4096[] = { 0xFFFFFFFF, 0xFFFFFFFF, 0x34063199, 0x4DF435C9, 0x90A6C08F, 0x86FFB7DC, 0x8D8FDDC1, 0x93B4EA98, 0xD5B05AA9, 0xD0069127, 0x2170481C, 0xB81BDD76, 0xCEE2D7AF, 0x1F612970, 0x515BE7ED, 0x233BA186, 0xA090C3A2, 0x99B2964F, 0x4E6BC05D, 0x287C5947, 0x1FBECAA6, 0x2E8EFC14, 0x04DE8EF9, 0xDBBBC2DB, 0x2AD44CE8, 0x2583E9CA, 0xB6150BDA, 0x1A946834, 0x6AF4E23C, 0x99C32718, 0xBDBA5B26, 0x88719A10, 0xA787E6D7, 0x1A723C12, 0xA9210801, 0x4B82D120, 0xE0FD108E, 0x43DB5BFC, 0x74E5AB31, 0x08E24FA0, 0xBAD946E2, 0x770988C0, 0x7A615D6C, 0xBBE11757, 0x177B200C, 0x521F2B18, 0x3EC86A64, 0xD8760273, 0xD98A0864, 0xF12FFA06, 0x1AD2EE6B, 0xCEE3D226, 0x4A25619D, 0x1E8C94E0, 0xDB0933D7, 0xABF5AE8C, 0xA6E1E4C7, 0xB3970F85, 0x5D060C7D, 0x8AEA7157, 0x58DBEF0A, 0xECFB8504, 0xDF1CBA64, 0xA85521AB, 0x04507A33, 0xAD33170D, 0x8AAAC42D, 0x15728E5A, 0x98FA0510, 0x15D22618, 0xEA956AE5, 0x3995497C, 0x95581718, 0xDE2BCBF6, 0x6F4C52C9, 0xB5C55DF0, 0xEC07A28F, 0x9B2783A2, 0x180E8603, 0xE39E772C, 0x2E36CE3B, 0x32905E46, 0xCA18217C, 0xF1746C08, 0x4ABC9804, 0x670C354E, 0x7096966D, 0x9ED52907, 0x208552BB, 0x1C62F356, 0xDCA3AD96, 0x83655D23, 0xFD24CF5F, 0x69163FA8, 0x1C55D39A, 0x98DA4836, 0xA163BF05, 0xC2007CB8, 0xECE45B3D, 0x49286651, 0x7C4B1FE6, 0xAE9F2411, 0x5A899FA5, 0xEE386BFB, 0xF406B7ED, 0x0BFF5CB6, 0xA637ED6B, 0xF44C42E9, 0x625E7EC6, 0xE485B576, 0x6D51C245, 0x4FE1356D, 0xF25F1437, 0x302B0A6D, 0xCD3A431B, 0xEF9519B3, 0x8E3404DD, 0x514A0879, 0x3B139B22, 0x020BBEA6, 0x8A67CC74, 0x29024E08, 0x80DC1CD1, 0xC4C6628B, 0x2168C234, 0xC90FDAA2, 0xFFFFFFFF, 0xFFFFFFFF }; #endif static BN_BigNum g_bnRfc3526Prime2048 = { false, (uint32_t)sizeof(RFC3526_PRIME_2048) / sizeof(RFC3526_PRIME_2048[0]), (uint32_t)sizeof(RFC3526_PRIME_2048) / sizeof(RFC3526_PRIME_2048[0]), 0, (BN_UINT *)(uintptr_t)RFC3526_PRIME_2048 }; static BN_BigNum g_bnRfc3526Prime3072 = { false, (uint32_t)sizeof(RFC3526_PRIME_3072) / sizeof(RFC3526_PRIME_3072[0]), (uint32_t)sizeof(RFC3526_PRIME_3072) / sizeof(RFC3526_PRIME_3072[0]), 0, (BN_UINT *)(uintptr_t)RFC3526_PRIME_3072 }; static BN_BigNum g_bnRfc3526Prime4096 = { false, (uint32_t)sizeof(RFC3526_PRIME_4096) / sizeof(RFC3526_PRIME_4096[0]), (uint32_t)sizeof(RFC3526_PRIME_4096) / sizeof(RFC3526_PRIME_4096[0]), 0, (BN_UINT *)(uintptr_t)RFC3526_PRIME_4096 }; static BN_BigNum *GetBnConst(BN_BigNum *outConst, BN_BigNum *inConst) { if (outConst == NULL) { return BN_Dup(inConst); } else { if (BN_Copy(outConst, inConst) != CRYPT_SUCCESS) { return NULL; } return outConst; } } BN_BigNum *BN_GetRfc3526Prime(BN_BigNum *r, uint32_t len) { switch (len) { case 2048: // return 2048-bit MODP bn return GetBnConst(r, &g_bnRfc3526Prime2048); case 3072: // return 3072-bit MODP bn return GetBnConst(r, &g_bnRfc3526Prime3072); case 4096: // return 4096-bit MODP bn return GetBnConst(r, &g_bnRfc3526Prime4096); default: return NULL; } } #endif /* HITLS_CRYPTO_BN_PRIME_RFC3526 */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_const.c
C
unknown
10,049
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdbool.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "bn_basic.h" #include "bn_bincal.h" #include "bn_optimizer.h" /* Euclidean algorithm */ static int32_t BnGcdDiv(BN_BigNum *r, BN_BigNum *max, BN_BigNum *min, BN_Optimizer *opt) { int32_t ret = CRYPT_SUCCESS; BN_BigNum *tmp = NULL; BN_BigNum *big = max; BN_BigNum *small = min; do { ret = BN_Div(NULL, big, big, small, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (BN_IsOne(big)) { return BN_Copy(r, big); } if (BN_IsZero(big)) { return BN_Copy(r, small); } /* ensure that big > small in the next calculation of remainder */ tmp = big; big = small; small = tmp; } while (true); return CRYPT_SUCCESS; } int32_t BnGcdCheckInput(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_Optimizer *opt) { bool invalidInput = (a == NULL || b == NULL || r == NULL || opt == NULL); if (invalidInput) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } /* The GCD may be the minimum value between a and b. Ensure the r space before calculation. */ uint32_t needSize = (a->size < b->size) ? a->size : b->size; int32_t ret = BnExtend(r, needSize); if (ret != CRYPT_SUCCESS) { return ret; } // a and b cannot be 0 if (BN_IsZero(a) || BN_IsZero(b)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_GCD_NO_ZERO); return CRYPT_BN_ERR_GCD_NO_ZERO; } return CRYPT_SUCCESS; } int32_t BN_Gcd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt) { int32_t ret = BnGcdCheckInput(r, a, b, opt); if (ret != CRYPT_SUCCESS) { return ret; } ret = BinCmp(a->data, a->size, b->data, b->size); if (ret == 0) { // For example, a == b is the greatest common divisor of itself ret = BN_Copy(r, a); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } r->sign = false; // the greatest common divisor is a positive integer return CRYPT_SUCCESS; } const BN_BigNum *bigNum = (ret > 0) ? a : b; const BN_BigNum *smallNum = (ret > 0) ? b : a; ret = OptimizerStart(opt); // use the optimizer if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* Apply for temporary space of BN objects a and b. */ BN_BigNum *max = OptimizerGetBn(opt, bigNum->size); BN_BigNum *min = OptimizerGetBn(opt, smallNum->size); if (max == NULL || min == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } ret = BN_Copy(max, bigNum); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BN_Copy(min, smallNum); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(ret); return ret; } // obtain the GCD, ensure that input parameter max > min ret = BnGcdDiv(r, max, min, opt); if (ret == CRYPT_SUCCESS) { r->sign = false; // The GCD is a positive integer } OptimizerEnd(opt); // release occupation from the optimizer return ret; } static int32_t InverseReady(BN_BigNum *a, BN_BigNum *b, const BN_BigNum *x, const BN_BigNum *m, BN_Optimizer *opt) { int32_t ret = BN_Copy(a, m); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } a->sign = false; ret = BN_Mod(b, x, m, opt); // b must be a positive number and do not need to convert symbols. if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (BN_IsZero(b)) { // does not satisfy x and m interprime, so it cannot obtain the inverse module. BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_NO_INVERSE); return CRYPT_BN_ERR_NO_INVERSE; } return CRYPT_SUCCESS; } static int32_t InverseCore(BN_BigNum *r, BN_BigNum *x, BN_BigNum *y, uint32_t mSize, BN_Optimizer *opt) { BN_BigNum *a = x; BN_BigNum *b = y; BN_BigNum *c = OptimizerGetBn(opt, mSize); // One more bit is reserved for addition and subtraction. BN_BigNum *d = OptimizerGetBn(opt, mSize); BN_BigNum *e = OptimizerGetBn(opt, mSize * 2); // multiplication of c requires 2x space BN_BigNum *t = OptimizerGetBn(opt, mSize); if (c == NULL || d == NULL || e == NULL || t == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } (void)BN_SetBit(d, 0); // can ignore the return value do { int32_t ret = BN_Div(t, a, a, b, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (BN_IsZero(a)) { if (BN_IsOne(b)) { // b is 1 return BN_SetLimb(r, 1); // obtains the inverse modulus value 1 } break; // Failed to obtain the inverse modulus value. } t->sign = !t->sign; ret = BN_Mul(e, t, d, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BN_Add(c, c, e); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (BN_IsOne(a)) { return BN_Copy(r, c); // Obtain the module inverse. } // Switch a b BN_BigNum *tmp = a; a = b; b = tmp; // Switch c d tmp = c; c = d; d = tmp; } while (true); BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_NO_INVERSE); return CRYPT_BN_ERR_NO_INVERSE; } int32_t InverseInputCheck(BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *m, const BN_Optimizer *opt) { bool invalidInput = (r == NULL || x == NULL || m == NULL || opt == NULL); if (invalidInput) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } /* cannot be 0 */ if (BN_IsZero(x) || BN_IsZero(m)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO); return CRYPT_BN_ERR_DIVISOR_ZERO; } return BnExtend(r, m->size); } int32_t BN_ModInv(BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *m, BN_Optimizer *opt) { int32_t ret = InverseInputCheck(r, x, m, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = OptimizerStart(opt); // use the optimizer if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_BigNum *a = OptimizerGetBn(opt, m->size); BN_BigNum *b = OptimizerGetBn(opt, m->size); BN_BigNum *t = OptimizerGetBn(opt, m->size); bool invalidInput = (a == NULL || b == NULL || t == NULL); if (invalidInput) { BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); ret = CRYPT_BN_OPTIMIZER_GET_FAIL; goto ERR; } /* Take positive numbers a and b first. */ ret = InverseReady(a, b, x, m, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } /* Extended Euclidean algorithm */ ret = InverseCore(t, a, b, m->size, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } // Prevent the negative number. ret = BN_Mod(r, t, m, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ERR: OptimizerEnd(opt); // Release occupation from the optimizer. return ret; } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_gcd.c
C
unknown
8,304
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdbool.h> #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "bn_basic.h" #include "bn_bincal.h" #include "bn_optimizer.h" int32_t BN_Lcm(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt) { if (r == NULL || a == NULL || b == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BN_BigNum *gcd = BN_Create(BN_Bits(r)); if (gcd == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = BN_Gcd(gcd, a, b, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BN_Destroy(gcd); return ret; } if (BN_IsOne(gcd) == false) { ret = BN_Div(r, NULL, a, gcd, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BN_Destroy(gcd); return ret; } BN_Destroy(gcd); return BN_Mul(r, r, b, opt); } BN_Destroy(gcd); // a and b are coprime. return BN_Mul(r, a, b, opt); } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_lcm.c
C
unknown
1,728
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include <stdbool.h> #include "securec.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "bn_bincal.h" #include "bn_optimizer.h" #include "crypt_utils.h" #include "bn_montbin.h" // The mont contains 4 BN_UINT* fields and 2 common fields. #define MAX_MONT_SIZE ((BITS_TO_BN_UNIT(BN_MAX_BITS) * 4 + 2) * sizeof(BN_UINT)) static void CopyConsttime(BN_UINT *dst, const BN_UINT *a, const BN_UINT *b, uint32_t len, BN_UINT mask) { BN_UINT rmask = ~mask; for (uint32_t i = 0; i < len; i++) { dst[i] = (a[i] & mask) ^ (b[i] & rmask); } } /* reduce(r) */ static void MontDecBin(BN_UINT *r, BN_Mont *mont) { uint32_t mSize = mont->mSize; BN_UINT *x = mont->t; BN_COPY_BYTES(x, mSize << 1, r, mSize); Reduce(r, x, mont->one, mont->mod, mSize, mont->k0); } /* Return value is (r - m0)' mod r */ static BN_UINT Inverse(BN_UINT m0) { BN_UINT x = 2; /* 2^1 */ BN_UINT y = 1; BN_UINT mask = 1; /* Mask */ for (uint32_t i = 1; i < BN_UINT_BITS; i++, x <<= 1) { BN_UINT rH, rL; mask = (mask << 1) | 1; MUL_AB(rH, rL, m0, y); if (x < (rL & mask)) { y += x; } (void)rH; } return (BN_UINT)(0 - y); } /* Pre-computation */ static int32_t MontExpReady(BN_BigNum *table[], uint32_t num, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { BN_UINT *b = mont->b; uint32_t i; for (i = 1; i < num; i++) { /* Request num - 1 data blocks */ table[i] = OptimizerGetBn(opt, mont->mSize); if (table[i] == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } } table[0] = table[1]; (void)memcpy_s(table[1]->data, mont->mSize * sizeof(BN_UINT), b, mont->mSize * sizeof(BN_UINT)); for (i = 2; i < num; i++) { /* precompute num - 2 data blocks */ int32_t ret = MontMulBin(table[i]->data, table[0]->data, table[i - 1]->data, mont, opt, consttime); if (ret != CRYPT_SUCCESS) { return ret; } } return CRYPT_SUCCESS; } static uint32_t GetELimb(const BN_UINT *e, BN_UINT *eLimb, uint32_t base, uint32_t bits) { if (bits > base) { /* Required data */ (*eLimb) = e[0] & (((1u) << base) - 1); return base; } (*eLimb) = 0; for (uint32_t i = 0; i < bits; i++) { uint32_t bit = base - i - 1; uint32_t nw = bit / BN_UINT_BITS; /* shift words */ uint32_t nb = bit % BN_UINT_BITS; /* shift bits */ (*eLimb) <<= 1; (*eLimb) |= ((e[nw] >> nb) & 1); } return bits; } static uint32_t GetReadySize(uint32_t bits) { if (bits > 512) { /* If bits are greater than 512 */ return 6; /* The size is 6. */ } if (bits > 256) { /* If bits are greater than 256 */ return 5; /* The size is 5. */ } if (bits > 128) { /* If bits are greater than 128 */ return 4; /* The size is 4. */ } if (bits > 64) { /* If bits are greater than 64 */ return 3; /* The size is 3. */ } if (bits > 32) { /* If bits are greater than 32 */ return 2; /* The size is 2. */ } return 1; } /* r = r ^ e mod mont */ static int32_t MontExpBin(BN_UINT *r, const BN_UINT *e, uint32_t eSize, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { BN_BigNum *table[64] = { 0 }; /* 0 -- 2^6 that is 0 -- 64 */ int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { return ret; } (void)memcpy_s(mont->b, mont->mSize * sizeof(BN_UINT), r, mont->mSize * sizeof(BN_UINT)); uint32_t base = BinBits(e, eSize) - 1; uint32_t perSize = GetReadySize(base); const uint32_t readySize = 1 << perSize; ret = MontExpReady(table, readySize, mont, opt, consttime); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); return ret; } do { BN_UINT eLimb; uint32_t bit = GetELimb(e, &eLimb, base, perSize); for (uint32_t i = 0; i < bit; i++) { ret = MontSqrBin(r, mont, opt, consttime); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); return ret; } } if (consttime == true) { BN_UINT *x = mont->t; BN_UINT mask = ~BN_IsZeroUintConsttime(eLimb); ret = MontMulBin(x, r, table[eLimb]->data, mont, opt, consttime); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); return ret; } CopyConsttime(r, x, r, mont->mSize, mask); } else if (eLimb != 0) { ret = MontMulBin(r, r, table[eLimb]->data, mont, opt, consttime); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); return ret; } } base -= bit; } while (base != 0); OptimizerEnd(opt); return CRYPT_SUCCESS; } static int32_t MontParaCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, const BN_Mont *mont) { if (r == NULL || a == NULL || e == NULL || mont == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (e->sign) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_EXP_NO_NEGATIVE); return CRYPT_BN_ERR_EXP_NO_NEGATIVE; } return BnExtend(r, mont->mSize); } static const BN_BigNum *DealBaseNum(const BN_BigNum *a, BN_Mont *mont, BN_Optimizer *opt, int32_t *ret) { const BN_BigNum *aTmp = a; if (BinCmp(a->data, a->size, mont->mod, mont->mSize) >= 0) { BN_BigNum *tmpval = OptimizerGetBn(opt, a->size + 2); // BinDiv need a->room >= a->size + 2 BN_BigNum *tmpMod = OptimizerGetBn(opt, mont->mSize); // BinDiv need a->room >= a->size + 2 if (tmpval == NULL || tmpMod == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); *ret = CRYPT_BN_OPTIMIZER_GET_FAIL; return NULL; } *ret = BN_Copy(tmpval, a); if (*ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(*ret); return NULL; } (void)memcpy_s(tmpMod->data, mont->mSize * sizeof(BN_UINT), mont->mod, mont->mSize * sizeof(BN_UINT)); tmpval->size = BinDiv(NULL, NULL, tmpval->data, tmpval->size, tmpMod->data, mont->mSize); aTmp = tmpval; } return aTmp; } static const BN_UINT *TmpValueHandle(BN_BigNum *r, const BN_BigNum *e, const BN_BigNum *a, BN_Optimizer *opt) { const BN_UINT *te = e->data; uint32_t esize = e->size; if (e == r) { BN_BigNum *ee = OptimizerGetBn(opt, esize); if (ee == NULL) { return NULL; } (void)memcpy_s(ee->data, esize * sizeof(BN_UINT), e->data, esize * sizeof(BN_UINT)); te = ee->data; } BN_COPY_BYTES(r->data, r->room, a->data, a->size); return te; } /* must satisfy the absolute value x < mod */ static int32_t MontExpCore(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { if ((BinBits(e->data, e->size) == 0)) { if (mont->mSize != 1) { return BN_SetLimb(r, 1); } return (mont->mod[0] == 1) ? BN_Zeroize(r) : BN_SetLimb(r, 1); } if (a->size == 0) { return BN_Zeroize(r); } int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { return ret; } /* if a >= mod */ const BN_BigNum *aTmp = DealBaseNum(a, mont, opt, &ret); if (aTmp == NULL) { OptimizerEnd(opt); return ret; } const BN_UINT *te = TmpValueHandle(r, e, aTmp, opt); if (te == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } /* field conversion */ ret = MontEncBin(r->data, mont, opt, consttime); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); return ret; } /* modular exponentiation */ ret = MontExpBin(r->data, te, e->size, mont, opt, consttime); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); return ret; } /* field conversion */ MontDecBin(r->data, mont); /* negative number processing */ r->size = BinFixSize(r->data, mont->mSize); if (aTmp->sign && ((te[0] & 0x1) == 1) && r->size != 0) { BinSub(r->data, mont->mod, r->data, mont->mSize); r->size = BinFixSize(r->data, mont->mSize); } r->sign = false; OptimizerEnd(opt); return CRYPT_SUCCESS; } static int32_t MontExp(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { int32_t ret = MontParaCheck(r, a, e, mont); if (ret != CRYPT_SUCCESS) { return ret; } bool newOpt = (opt == NULL); if (newOpt) { opt = BN_OptimizerCreate(); if (opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } } ret = MontExpCore(r, a, e, mont, opt, consttime); if (newOpt) { BN_OptimizerDestroy(opt); } return ret; } int32_t BN_MontExp(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, BN_Mont *mont, BN_Optimizer *opt) { bool consttime = (BN_IsFlag(a, CRYPT_BN_FLAG_CONSTTIME) || BN_IsFlag(e, CRYPT_BN_FLAG_CONSTTIME)); return MontExp(r, a, e, mont, opt, consttime); } /* must satisfy the absolute value x < mod */ int32_t BN_MontExpConsttime(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, BN_Mont *mont, BN_Optimizer *opt) { return MontExp(r, a, e, mont, opt, true); } static uint32_t MontSize(uint32_t room) { uint32_t size = (uint32_t)(sizeof(BN_Mont) + sizeof(BN_UINT)); /* Requires 6 * room + 1 space. mod(1) + montRR(1) + b(1) + t(2) + one = 6. In addition, one more room is required when the modulus is set later. */ size += (room * 6 + 1) * ((uint32_t)sizeof(BN_UINT)); return size; } void BN_MontDestroy(BN_Mont *mont) { if (mont == NULL) { return; } (void)memset_s(mont, MontSize(mont->mSize), 0, MontSize(mont->mSize)); BSL_SAL_FREE(mont); } /* set the modulus */ static void SetMod(BN_Mont *mont, const BN_BigNum *mod) { uint32_t mSize = mod->size; (void)memcpy_s(mont->mod, mSize * sizeof(BN_UINT), mod->data, mSize * sizeof(BN_UINT)); (void)memset_s(mont->one, mSize * 3 * sizeof(BN_UINT), 0, mSize * 3 * sizeof(BN_UINT)); /* clear one and RR */ mont->one[0] = 1; /* set one */ mont->k0 = Inverse(mod->data[0]); mont->montRR[mSize * 2] = 1; /* 2^2n */ mont->montRR[mSize * 2 + 1] = 0; /* 2 more rooms are provided to ensure the division does not exceed the limit */ mont->montRR[mSize * 2 + 2] = 0; /* 2 more rooms are provided to ensure the division does not exceed the limit */ // The size of the space required for calculating the montRR is 2 * mSize + 1 (void)BinDiv(NULL, NULL, mont->montRR, 2 * mSize + 1, mont->mod, mSize); (void)memcpy_s(mont->mod, mSize * sizeof(BN_UINT), mod->data, mSize * sizeof(BN_UINT)); } /* create a Montgomery structure, where m is a modulo */ BN_Mont *BN_MontCreate(const BN_BigNum *m) { if (m == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return NULL; } if (!BN_GetBit(m, 0) || m->sign) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return NULL; } uint32_t mSize = m->size; uint32_t montSize = MontSize(mSize); if (montSize > MAX_MONT_SIZE) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_TOO_MAX); return NULL; } BN_Mont *mont = BSL_SAL_Malloc(montSize); if (mont == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } BN_UINT *base = AlignedPointer((uint8_t *)mont + sizeof(BN_Mont), sizeof(BN_UINT)); mont->mSize = mSize; mont->mod = base; /* mSize */ mont->one = (base += mSize); /* mSize */ mont->montRR = (base += mSize); /* mSize */ mont->b = (base += mSize); /* mSize */ mont->t = base + mSize; /* 2 * mSize */ SetMod(mont, m); return mont; } int32_t MontSqrBinCore(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { return ret; } uint32_t mSize = mont->mSize; BN_UINT *x = mont->t; #ifdef HITLS_CRYPTO_BN_COMBA BN_BigNum *bnSpace = OptimizerGetBn(opt, SpaceSize(mSize)); if (bnSpace == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } SqrConquer(x, r, mSize, bnSpace->data, consttime); #else (void)consttime; BinSqr(x, mSize << 1, r, mSize); #endif Reduce(r, x, mont->one, mont->mod, mSize, mont->k0); OptimizerEnd(opt); return CRYPT_SUCCESS; } /* reduce(a)= (a * R') mod N) */ void ReduceCore(BN_UINT *r, BN_UINT *x, const BN_UINT *m, uint32_t mSize, BN_UINT m0) { BN_UINT carry = 0; uint32_t n = 0; /* Cyclic shift, obtain r = (x / R) mod N */ do { BN_UINT q = x[n] * m0; /* q = (s[0] + x[i]) * m0 */ BN_UINT tmp = BinMulAcc(x + n, m, mSize, q); /* (s + qm) mod m == s. Refresh s[0] to x[0] */ /* Add carry to tmp and update carry flag. */ tmp = tmp + carry; carry = (tmp < carry) ? 1 : 0; /* Add tmp to x[mSize + n] and update the carry flag. */ x[mSize + n] += tmp; carry = (x[mSize + n] < tmp) ? 1 : carry; if (n + 1 == mSize) { break; } n++; } while (true); /* If x < 2m, the carry value is 0 or -1. */ carry -= BinSub(r, x + mSize, m, mSize); CopyConsttime(r, x + mSize, r, mSize, carry); } /* reduce(r * RR) */ int32_t MontEncBinCore(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { return ret; } uint32_t mSize = mont->mSize; BN_UINT *x = mont->t; #ifdef HITLS_CRYPTO_BN_COMBA BN_BigNum *bnSpace = OptimizerGetBn(opt, SpaceSize(mSize)); if (bnSpace == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } MulConquer(x, r, mont->montRR, mSize, bnSpace->data, consttime); #else (void)consttime; BinMul(x, mSize << 1, r, mSize, mont->montRR, mSize); #endif Reduce(r, x, mont->one, mont->mod, mSize, mont->k0); OptimizerEnd(opt); return CRYPT_SUCCESS; } /* reduce(r * b) */ int32_t MontMulBinCore(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { return ret; } uint32_t mSize = mont->mSize; BN_UINT *x = mont->t; #ifdef HITLS_CRYPTO_BN_COMBA uint32_t size = SpaceSize(mSize); BN_BigNum *bnSpace = OptimizerGetBn(opt, size); if (bnSpace == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } MulConquer(x, a, b, mSize, bnSpace->data, consttime); #else (void)consttime; BinMul(x, mSize << 1, a, mSize, b, mSize); #endif Reduce(r, x, mont->one, mont->mod, mSize, mont->k0); OptimizerEnd(opt); return CRYPT_SUCCESS; } #ifdef HITLS_CRYPTO_DSA static int32_t GetFirstData(BN_UINT *r, uint32_t base1, uint32_t base2, BN_BigNum *table1[], BN_BigNum *table2[], BN_Mont *mont, BN_Optimizer *opt) { bool consttime = false; if (base1 == base2) { return MontMulBin(r, table1[0]->data, table2[0]->data, mont, opt, consttime); } else if (base1 > base2) { (void)memcpy_s(r, mont->mSize * sizeof(BN_UINT), table1[0]->data, mont->mSize * sizeof(BN_UINT)); } else { (void)memcpy_s(r, mont->mSize * sizeof(BN_UINT), table2[0]->data, mont->mSize * sizeof(BN_UINT)); } return CRYPT_SUCCESS; } /* Precalculate odd multiples of data. The data in the table is b^1, b^3, b^5...b^(2*num - 1) */ static int32_t MontExpOddReady(BN_BigNum *table[], uint32_t num, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { BN_UINT *b = mont->b; uint32_t i; for (i = 0; i < num; i++) { /* Request num - 1 data blocks */ table[i] = OptimizerGetBn(opt, mont->mSize); if (table[i] == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } } (void)memcpy_s(table[0]->data, mont->mSize * sizeof(BN_UINT), b, mont->mSize * sizeof(BN_UINT)); if (num == 1) { // When num is 1, pre-computation is not need. return CRYPT_SUCCESS; } int32_t ret = MontSqrBin(table[0]->data, // b^2 mont, opt, consttime); if (ret != CRYPT_SUCCESS) { return ret; } ret = MontMulBin(table[1]->data, table[0]->data, mont->b, // b^3 mont, opt, consttime); if (ret != CRYPT_SUCCESS) { return ret; } for (i = 2; i < num; i++) { /* precompute num - 2 data blocks */ // b^(2*i + 1) ret = MontMulBin(table[i]->data, table[0]->data, table[i - 1]->data, mont, opt, consttime); if (ret != CRYPT_SUCCESS) { return ret; } } (void)memcpy_s(table[0]->data, mont->mSize * sizeof(BN_UINT), b, mont->mSize * sizeof(BN_UINT)); return CRYPT_SUCCESS; } // Obtain the data with the length of bits from the start position of the base to the eLimb, // ignore the high-order 0 data, and obtain an odd number or 0. uint32_t GetOddLimbBin(const BN_UINT *e, BN_UINT *eLimb, uint32_t base, uint32_t bits, uint32_t size) { (*eLimb) = 0; if (base == 0) { return 0; } uint32_t loc = base; uint32_t retBits = 0; // Offset from current. Check whether non-zero data exists. while (true) { loc--; uint32_t nw = loc / BN_UINT_BITS; /* shift words */ uint32_t nb = loc % BN_UINT_BITS; /* shift retBits */ if (nw < size && ((e[nw] >> nb) & 1) != 0) { // Exit the loop when the bit is 1. break; } retBits++; if (loc == 0) { // If no valid bit is encountered until the end, the subsequent bits are returned. return retBits; } } // Obtain valid data from the loc location. for (uint32_t i = 0; i < bits; i++) { uint32_t nw = loc / BN_UINT_BITS; /* shift words */ uint32_t nb = loc % BN_UINT_BITS; /* shift retBits */ (*eLimb) <<= 1; (*eLimb) |= ((e[nw] >> nb) & 1); retBits++; if (loc == 0) { // The remaining data is insufficient and the system exits early. break; } loc--; } // The data must be 0 or an odd number. while ((*eLimb) != 0 && ((*eLimb) & 1) == 0) { // If eLimb is not 0 and is an even number, shift the eLimb to right. (*eLimb) >>= 1; retBits--; } return retBits; } /* r = (a1 ^ e1) * (a2 ^ e2) mod mont */ static int32_t MontExpMul(BN_UINT *r, const BN_BigNum *a1, const BN_BigNum *e1, const BN_BigNum *a2, const BN_BigNum *e2, BN_Mont *mont, BN_Optimizer *opt) { bool consttime = false; BN_UINT eLimb1, eLimb2; uint32_t bit1 = 0; uint32_t bit2 = 0; // The window retains only the values whose exponent is an odd number, reduce storage in half. BN_BigNum *table1[32] = { 0 }; /* 0 -- (2^6 >> 1), that is 0 -- 32 */ BN_BigNum *table2[32] = { 0 }; /* 0 -- (2^6 >> 1), that is 0 -- 32 */ int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t base1 = BinBits(e1->data, e1->size); uint32_t base2 = BinBits(e2->data, e2->size); uint32_t base = (base1 > base2) ? base1 : base2; uint32_t perSize1 = GetReadySize(base1); uint32_t perSize2 = GetReadySize(base2); const uint32_t readySize1 = 1 << (perSize1 - 1); const uint32_t readySize2 = 1 << (perSize2 - 1); // Generate the pre-computation table. (void)memcpy_s(mont->b, mont->mSize * sizeof(BN_UINT), a1->data, mont->mSize * sizeof(BN_UINT)); GOTO_ERR_IF(MontExpOddReady(table1, readySize1, mont, opt, consttime), ret); (void)memcpy_s(mont->b, mont->mSize * sizeof(BN_UINT), a2->data, mont->mSize * sizeof(BN_UINT)); GOTO_ERR_IF(MontExpOddReady(table2, readySize2, mont, opt, consttime), ret); // Obtain the first data. GOTO_ERR_IF(GetFirstData(r, base1, base2, table1, table2, mont, opt), ret); base--; while (base != 0) { bit1 = (bit1 == 0) ? GetOddLimbBin(e1->data, &eLimb1, base, perSize1, e1->size) : bit1; bit2 = (bit2 == 0) ? GetOddLimbBin(e2->data, &eLimb2, base, perSize2, e2->size) : bit2; uint32_t bit = (bit1 < bit2) ? bit1 : bit2; for (uint32_t i = 0; i < bit; i++) { GOTO_ERR_IF(MontSqrBin(r, mont, opt, consttime), ret); } if (bit == bit1 && eLimb1 != 0) { GOTO_ERR_IF(MontMulBin(r, r, table1[(eLimb1 - 1) >> 1]->data, mont, opt, consttime), ret); } if (bit == bit2 && eLimb2 != 0) { GOTO_ERR_IF(MontMulBin(r, r, table2[(eLimb2 - 1) >> 1]->data, mont, opt, consttime), ret); } bit1 -= bit; bit2 -= bit; base -= bit; }; ERR: OptimizerEnd(opt); return ret; } static int32_t MontExpMulParaCheck(BN_BigNum *r, const BN_BigNum *a1, const BN_BigNum *e1, const BN_BigNum *a2, const BN_BigNum *e2, const BN_Mont *mont, const BN_Optimizer *opt) { if (r == NULL || a1 == NULL || e1 == NULL || a2 == NULL || e2 == NULL || mont == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (e1->sign || e2->sign) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_EXP_NO_NEGATIVE); return CRYPT_BN_ERR_EXP_NO_NEGATIVE; } return BnExtend(r, mont->mSize); } typedef struct { BN_BigNum *a1; BN_BigNum *a2; BN_BigNum *e1; BN_BigNum *e2; } MontsMulFactor; static int32_t MontsFactorGetByOptThenCopy(MontsMulFactor *dst, const MontsMulFactor *src, uint32_t mSize, BN_Optimizer *opt) { dst->a1 = OptimizerGetBn(opt, mSize); dst->a2 = OptimizerGetBn(opt, mSize); dst->e1 = OptimizerGetBn(opt, mSize); dst->e2 = OptimizerGetBn(opt, mSize); if (dst->a1 == NULL || dst->a2 == NULL || dst->e1 == NULL || dst->e2 == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } int32_t ret = BN_Copy(dst->a1, src->a1); if (ret != CRYPT_SUCCESS) { return ret; } ret = BN_Copy(dst->a2, src->a2); if (ret != CRYPT_SUCCESS) { return ret; } ret = BN_Copy(dst->e1, src->e1); if (ret != CRYPT_SUCCESS) { return ret; } return BN_Copy(dst->e2, src->e2); } /* r = (a1 ^ e1) * (a2 ^ e2) mod mont */ int32_t BN_MontExpMul(BN_BigNum *r, const BN_BigNum *a1, const BN_BigNum *e1, const BN_BigNum *a2, const BN_BigNum *e2, BN_Mont *mont, BN_Optimizer *opt) { int32_t ret = MontExpMulParaCheck(r, a1, e1, a2, e2, mont, opt); if (ret != CRYPT_SUCCESS) { return ret; } if (BinCmp(a2->data, a2->size, mont->mod, mont->mSize) >= 0 || BinCmp(a1->data, a1->size, mont->mod, mont->mSize) >= 0) { /* a1 >= mod || a2 >= mod */ BSL_ERR_PUSH_ERROR(CRYPT_BN_MONT_BASE_TOO_MAX); return CRYPT_BN_MONT_BASE_TOO_MAX; } if (BN_IsZero(a1) || BN_IsZero(a2)) { return BN_Zeroize(r); } if (BN_IsZero(e1)) { return MontExpCore(r, a2, e2, mont, opt, false); } if (BN_IsZero(e2)) { return MontExpCore(r, a1, e1, mont, opt, false); } ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } MontsMulFactor factor; const MontsMulFactor srcFactor = {(BN_BigNum *)(uintptr_t)a1, (BN_BigNum *)(uintptr_t)a2, (BN_BigNum *)(uintptr_t)e1, (BN_BigNum *)(uintptr_t)e2}; GOTO_ERR_IF_EX(MontsFactorGetByOptThenCopy(&factor, &srcFactor, mont->mSize, opt), ret); /* field conversion */ GOTO_ERR_IF(MontEncBin(factor.a1->data, mont, opt, false), ret); GOTO_ERR_IF(MontEncBin(factor.a2->data, mont, opt, false), ret); /* modular exponentiation */ GOTO_ERR_IF_EX(MontExpMul(r->data, factor.a1, factor.e1, factor.a2, factor.e2, mont, opt), ret); /* field conversion */ MontDecBin(r->data, mont); r->size = BinFixSize(r->data, mont->mSize); r->sign = false; ERR: OptimizerEnd(opt); return ret; } #endif #if defined(HITLS_CRYPTO_RSA) int32_t MontMulCore(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Mont *mont, BN_Optimizer *opt) { int32_t ret; BN_BigNum *t1 = OptimizerGetBn(opt, mont->mSize); if (t1 == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } BN_COPY_BYTES(t1->data, mont->mSize, a->data, a->size); BN_COPY_BYTES(r->data, mont->mSize, b->data, b->size); GOTO_ERR_IF(MontEncBin(t1->data, mont, opt, false), ret); GOTO_ERR_IF(MontEncBin(r->data, mont, opt, false), ret); GOTO_ERR_IF(MontMulBin(r->data, t1->data, r->data, mont, opt, false), ret); MontDecBin(r->data, mont); r->size = BinFixSize(r->data, mont->mSize); ERR: return ret; } #endif // HITLS_CRYPTO_RSA #if defined(HITLS_CRYPTO_BN_PRIME) int32_t MontSqrCore(BN_BigNum *r, const BN_BigNum *a, BN_Mont *mont, BN_Optimizer *opt) { int32_t ret; BN_COPY_BYTES(r->data, mont->mSize, a->data, a->size); GOTO_ERR_IF(MontEncBin(r->data, mont, opt, false), ret); GOTO_ERR_IF(MontSqrBin(r->data, mont, opt, false), ret); MontDecBin(r->data, mont); r->size = BinFixSize(r->data, mont->mSize); ERR: return ret; } #endif // HITLS_CRYPTO_BN_PRIME #ifdef HITLS_CRYPTO_CURVE_MONT int32_t BnMontEnc(BN_BigNum *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { int32_t ret; GOTO_ERR_IF(MontEncBin(r->data, mont, opt, consttime), ret); r->size = BinFixSize(r->data, mont->mSize); ERR: return ret; } void BnMontDec(BN_BigNum *r, BN_Mont *mont) { MontDecBin(r->data, mont); r->size = BinFixSize(r->data, mont->mSize); } int32_t BN_EcPrimeMontSqr(BN_BigNum *r, const BN_BigNum *a, void *data, BN_Optimizer *opt) { if (r == NULL || a == NULL || data == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR((CRYPT_NULL_INPUT)); return CRYPT_NULL_INPUT; } int32_t ret; BN_Mont *mont = (BN_Mont *)data; BN_COPY_BYTES(r->data, mont->mSize, a->data, a->size); GOTO_ERR_IF(MontSqrBin(r->data, mont, opt, false), ret); r->size = BinFixSize(r->data, mont->mSize); ERR: return ret; } int32_t BN_EcPrimeMontMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *data, BN_Optimizer *opt) { if (r == NULL || a == NULL || b == NULL || data == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR((CRYPT_NULL_INPUT)); return CRYPT_NULL_INPUT; } int32_t ret; BN_Mont *mont = (BN_Mont *)data; GOTO_ERR_IF(MontMulBin(r->data, a->data, b->data, mont, opt, false), ret); r->size = BinFixSize(r->data, mont->mSize); ERR: return ret; } #endif // HITLS_CRYPTO_CURVE_MONT #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_mont.c
C
unknown
27,907
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BN_MONTBIN_H #define BN_MONTBIN_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include "crypt_bn.h" #ifdef __cplusplus extern "c" { #endif /* r = reduce(r * r) mod mont */ int32_t MontSqrBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime); /* r = reduce(a * b) mod mont */ int32_t MontMulBin(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, BN_Mont *mont, BN_Optimizer *opt, bool consttime); /* r = reduce(r * montRR) mod mont */ int32_t MontEncBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime); /* r = reduce(x * 1) mod m = (x * R') mod m */ void Reduce(BN_UINT *r, BN_UINT *x, const BN_UINT *one, const BN_UINT *m, uint32_t mSize, BN_UINT m0); #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_BN */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_montbin.h
C
unknown
1,328
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_BN) && defined(HITLS_CRYPTO_ECC) #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "bn_bincal.h" // Refresh the valid length of the BigNum r. The maximum length is modSize. static void UpdateSize(BN_BigNum *r, uint32_t modSize) { uint32_t size = modSize; while (size > 0) { if (r->data[size - 1] != 0) { break; } size--; } if (r->size > modSize) { // Clear the high bits. uint32_t i = 0; for (i = modSize; i < r->size; i++) { r->data[i] = 0; } } r->size = size; r->sign = false; } #define P521SIZE SIZE_OF_BNUINT(521) #define SIZE_OF_BNUINT(bits) (((bits) + BN_UINT_BITS - 1) / BN_UINT_BITS) // 1byte = 8bit #if defined(HITLS_SIXTY_FOUR_BITS) #define P224SIZE SIZE_OF_BNUINT(224) #define P256SIZE SIZE_OF_BNUINT(256) #define P384SIZE SIZE_OF_BNUINT(384) BN_UINT g_modDataP224[][P224SIZE] = { { // 1p 0x0000000000000001UL, 0xffffffff00000000UL, 0xffffffffffffffffUL, 0x00000000ffffffffUL }, { // 2p 0x0000000000000002UL, 0xfffffffe00000000UL, 0xffffffffffffffffUL, 0x00000001ffffffffUL } }; BN_UINT g_modDataP256[][P256SIZE] = { { // p 0xffffffffffffffffUL, 0x00000000ffffffffUL, 0x0000000000000000UL, 0xffffffff00000001UL }, { // 2p 0xfffffffffffffffeUL, 0x00000001ffffffffUL, 0x0000000000000000UL, 0xfffffffe00000002UL }, { // 3p 0xfffffffffffffffdUL, 0x00000002ffffffffUL, 0x0000000000000000UL, 0xfffffffd00000003UL }, { // 4p 0xfffffffffffffffcUL, 0x00000003ffffffffUL, 0x0000000000000000UL, 0xfffffffc00000004UL }, { // 5p 0xfffffffffffffffbUL, 0x00000004ffffffffUL, 0x0000000000000000UL, 0xfffffffb00000005UL }, }; #ifdef HITLS_CRYPTO_CURVE_SM2 const BN_UINT MODDATASM2P256[][P256SIZE] = { { // p 0xffffffffffffffffUL, 0xffffffff00000000UL, 0xffffffffffffffffUL, 0xfffffffeffffffffUL }, { // 2p 0xfffffffffffffffeUL, 0xfffffffe00000001UL, 0xffffffffffffffffUL, 0xfffffffdffffffffUL }, { // 3p 0xfffffffffffffffdUL, 0xfffffffd00000002UL, 0xffffffffffffffffUL, 0xfffffffcffffffffUL }, { // 4p 0xfffffffffffffffcUL, 0xfffffffc00000003UL, 0xffffffffffffffffUL, 0xfffffffbffffffffUL }, { // 5p 0xfffffffffffffffbUL, 0xfffffffb00000004UL, 0xffffffffffffffffUL, 0xfffffffaffffffffUL }, { // 6p 0xfffffffffffffffaUL, 0xfffffffa00000005UL, 0xffffffffffffffffUL, 0xfffffff9ffffffffUL }, { // 7p 0xfffffffffffffff9UL, 0xfffffff900000006UL, 0xffffffffffffffffUL, 0xfffffff8ffffffffUL }, { // 8p 0xfffffffffffffff8UL, 0xfffffff800000007UL, 0xffffffffffffffffUL, 0xfffffff7ffffffffUL }, { // 9p 0xfffffffffffffff7UL, 0xfffffff700000008UL, 0xffffffffffffffffUL, 0xfffffff6ffffffffUL }, { // 10p 0xfffffffffffffff6UL, 0xfffffff600000009UL, 0xffffffffffffffffUL, 0xfffffff5ffffffffUL }, { // 11p 0xfffffffffffffff5UL, 0xfffffff50000000aUL, 0xffffffffffffffffUL, 0xfffffff4ffffffffUL }, { // 12p 0xfffffffffffffff4UL, 0xfffffff40000000bUL, 0xffffffffffffffffUL, 0xfffffff3ffffffffUL }, { // 13p 0xfffffffffffffff3UL, 0xfffffff30000000cUL, 0xffffffffffffffffUL, 0xfffffff2ffffffffUL }, }; #endif const BN_UINT MOD_DATA_P384[][P384SIZE] = { { 0x00000000ffffffffUL, 0xffffffff00000000UL, 0xfffffffffffffffeUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL }, { 0x00000001fffffffeUL, 0xfffffffe00000000UL, 0xfffffffffffffffdUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL }, { 0x00000002fffffffdUL, 0xfffffffd00000000UL, 0xfffffffffffffffcUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL }, { 0x00000003fffffffcUL, 0xfffffffc00000000UL, 0xfffffffffffffffbUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL }, { 0x00000004fffffffbUL, 0xfffffffb00000000UL, 0xfffffffffffffffaUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL }, }; const BN_UINT MOD_DATA_P521[P521SIZE] = { 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0xffffffffffffffffUL, 0x00000000000001ffUL }; static BN_UINT NistP384Add(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n) { (void)n; BN_UINT carry = 0; ADD_ABC(carry, r[0], a[0], b[0], carry); /* offset 0 */ ADD_ABC(carry, r[1], a[1], b[1], carry); /* offset 1 */ ADD_ABC(carry, r[2], a[2], b[2], carry); /* offset 2 */ ADD_ABC(carry, r[3], a[3], b[3], carry); /* offset 3 */ ADD_ABC(carry, r[4], a[4], b[4], carry); /* offset 4 */ ADD_ABC(carry, r[5], a[5], b[5], carry); /* offset 5 */ return carry; } static BN_UINT NistP384Sub(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n) { (void)n; BN_UINT borrow = 0; SUB_ABC(borrow, r[0], a[0], b[0], borrow); /* offset 0 */ SUB_ABC(borrow, r[1], a[1], b[1], borrow); /* offset 1 */ SUB_ABC(borrow, r[2], a[2], b[2], borrow); /* offset 2 */ SUB_ABC(borrow, r[3], a[3], b[3], borrow); /* offset 3 */ SUB_ABC(borrow, r[4], a[4], b[4], borrow); /* offset 4 */ SUB_ABC(borrow, r[5], a[5], b[5], borrow); /* offset 5 */ return borrow; } /** * Reduction item: 2^128 + 2^96 - 2^32+ 2^0 * * Reduction list 11 10 9 8 7 6 5 4 3 2 1 0 * a12 00, 00, 00, 00, 00, 00, 00, 01, 01, 00, -1, 01, * a13 00, 00, 00, 00, 00, 00, 01, 01, 00, -1, 01, 00, * a14 00, 00, 00, 00, 00, 01, 01, 00, -1, 01, 00, 00, * a15 00, 00, 00, 00, 01, 01, 00, -1, 01, 00, 00, 00, * a16 00, 00, 00, 01, 01, 00, -1, 01, 00, 00, 00, 00, * a17 00, 00, 01, 01, 00, -1, 01, 00, 00, 00, 00, 00, * a18 00, 01, 01, 00, -1, 01, 00, 00, 00, 00, 00, 00, * a19 01, 01, 00, -1, 01, 00, 00, 00, 00, 00, 00, 00, * a20 01, 00, -1, 01, 00, 00, 00, 01, 01, 00, -1, 01, * a21 00, -1, 01, 00, 00, 00, 01, 02, 01, -1, 00, 01, * a22 -1, 01, 00, 00, 00, 01, 02, 01, -1, 00, 01, 00, * a23 01, 00, 00, 00, 01, 02, 01, -2, -1, 01, 01, -1 * * Reduction chain * Coefficient 11 10 9 8 7 6 5 4 3 2 1 0 * 1 a23 a22 a21 a20 a19 a18 a17 a16 a15 a14 a13 a12 * 1 a20 a19 a18 a17 a16 a15 a14 a13 a12 a23 a22 a21 * 1 a19 a18 a17 a16 a15 a14 a13 a12 a20 a23 a20 * 1 a23 a22 a21 a20 a21 * 1 a23 a22 * 2 a23 a22 a21 * -1 a22 a21 a20 a19 a18 a17 a16 a15 a14 a13 a12 a23 * -1 a23 a22 a21 a20 * -1 a23 a23 */ int8_t ReduceNistP384(BN_UINT *r, const BN_UINT *a) { BN_UINT list[P384SIZE]; BN_UINT t[P384SIZE]; // 0 list[5] = a[11]; // offset 5 a23|a22 == ah[11]|al[11] list[4] = a[10]; // offset 4 a21|a20 == ah[10]|al[10] list[3] = a[9]; // offset 3 a19|a18 == ah[9]|al[9] list[2] = a[8]; // offset 2 a17|a16 == ah[8]|al[8] list[1] = a[7]; // offset 1 a15|a14 == ah[7]|al[7] list[0] = a[6]; // offset 0 a13|a12 == ah[6]|al[6] // 1 t[5] = BN_UINT_LO_TO_HI(a[10]) | BN_UINT_HI(a[9]); // offset 5 a20|a19 == al[10]|ah[9] t[4] = BN_UINT_LO_TO_HI(a[9]) | BN_UINT_HI(a[8]); // offset 4 a18|a17 == al[9]|ah[8] t[3] = BN_UINT_LO_TO_HI(a[8]) | BN_UINT_HI(a[7]); // offset 3 a16|a15 == al[8]|ah[7] t[2] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 2 a14|a13 == al[7]|ah[6] t[1] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[11]); // offset 1 a12|a23 == al[6]|ah[11] t[0] = BN_UINT_LO_TO_HI(a[11]) | BN_UINT_HI(a[10]); // offset 0 a22|a21 == al[11]|ah[10] int8_t carry = (int8_t)NistP384Add(t, list, t, P384SIZE); // 2 list[5] = a[9]; // offset 5 a19|a18 == ah[9]|al[9] list[4] = a[8]; // offset 4 a17|a16 == ah[8]|al[8] list[3] = a[7]; // offset 3 a15|a14 == ah[7]|al[7] list[2] = a[6]; // offset 2 a13|a12 == ah[6]|al[6] list[1] = BN_UINT_LO_TO_HI(a[10]); // offset 1 a20|0 == al[10]| 0 list[0] = BN_UINT_HI_TO_HI(a[11]) | BN_UINT_LO(a[10]); // offset 0 a23|a20 == ah[11]|al[10] carry += (int8_t)NistP384Add(t, list, t, P384SIZE); // 3 list[5] = 0; // offset 5 0 list[4] = 0; // offset 4 0 list[3] = a[11]; // offset 3 a23|a22 == ah[11]|al[11] list[2] = a[10]; // offset 2 a21|a20 == ah[10]|al[10] list[1] = BN_UINT_HI_TO_HI(a[10]); // offset 1 a21|0 == ah[10]|0 list[0] = 0; // offset 0 0 carry += (int8_t)NistP384Add(t, list, t, P384SIZE); // 4 list[5] = 0; // offset 5 0 list[4] = 0; // offset 4 0 list[3] = 0; // offset 3 0 list[2] = a[11]; // offset 2 a23|a22 == ah[11]|al[11] list[1] = 0; // offset 1 0 list[0] = 0; // offset 0 0 carry += (int8_t)NistP384Add(t, list, t, P384SIZE); // 5 list[5] = 0; // offset 5 0 list[4] = 0; // offset 4 0 list[3] = BN_UINT_HI(a[11]); // offset 3 0|a23 == 0|ah[11] list[2] = BN_UINT_LO_TO_HI(a[11]) | BN_UINT_HI(a[10]); // offset 2 a22|a21 == al[11]|ah[10] list[1] = 0; // offset 1 0 list[0] = 0; // offset 0 0 // double 5 // list[3] is left-shifted by 1 bit and the most significant bit of list[2] is added. list[3] = (list[2] >> (BN_UINT_BITS - 1)) | (list[3] << 1); list[2] = list[2] << 1; // list[2] left-shifted by 1bit carry += (int8_t)NistP384Add(t, list, t, P384SIZE); // 6 list[5] = BN_UINT_LO_TO_HI(a[11]) | BN_UINT_HI(a[10]); // offset 5 a22|a21 == al[11]|ah[10] list[4] = BN_UINT_LO_TO_HI(a[10]) | BN_UINT_HI(a[9]); // offset 4 a20|a19 == al[10]|ah[9] list[3] = BN_UINT_LO_TO_HI(a[9]) | BN_UINT_HI(a[8]); // offset 3 a18|a17 == al[9]|ah[8] list[2] = BN_UINT_LO_TO_HI(a[8]) | BN_UINT_HI(a[7]); // offset 2 a16|a15 == al[8]|ah[7] list[1] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 1 a14|a13 == al[7]|ah[6] list[0] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[11]); // offset 0 a12|a23 == al[6]|ah[11] carry -= (int8_t)NistP384Sub(t, t, list, P384SIZE); // 7 list[5] = 0; // offset 5 0 list[4] = 0; // offset 4 0 list[3] = 0; // offset 3 0 list[2] = BN_UINT_HI(a[11]); // offset 2 0|a23 == 0|ah[11] list[1] = BN_UINT_LO_TO_HI(a[11]) | BN_UINT_HI(a[10]); // offset 1 a22|a21 == al[11]|ah[10] list[0] = BN_UINT_LO_TO_HI(a[10]); // offset 0 a20|0 == al[10]|0 carry -= (int8_t)NistP384Sub(t, t, list, P384SIZE); // 8 list[5] = 0; // offset 5 0 list[4] = 0; // offset 4 0 list[3] = 0; // offset 3 0 list[2] = BN_UINT_HI(a[11]); // offset 2 0|a23 == 0|ah[11] list[1] = BN_UINT_HI_TO_HI(a[11]); // offset 1 a23|0 == ah[11]|0 list[0] = 0; // offset 0 carry -= (int8_t)NistP384Sub(t, t, list, P384SIZE); carry += (int8_t)NistP384Add(r, t, a, P384SIZE); return carry; } // The size of a is 2*P384SIZE, and the size of r is P384SIZE int32_t ModNistP384(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { (void)opt; (void)m; const BN_UINT *mod = MOD_DATA_P384[0]; int8_t carry = ReduceNistP384(r->data, a->data); if (carry > 0) { carry = (int8_t)1 - (int8_t)BinSub(r->data, r->data, MOD_DATA_P384[carry - 1], P384SIZE); } else if (carry < 0) { // For details could ref p256. carry = (int8_t)1 - (int8_t)BinAdd(r->data, r->data, MOD_DATA_P384[-carry - 1], P384SIZE); carry = -carry; } if (carry < 0) { BinAdd(r->data, r->data, mod, P384SIZE); } else if (carry > 0 || BinCmp(r->data, P384SIZE, mod, P384SIZE) >= 0) { BinSub(r->data, r->data, mod, P384SIZE); } UpdateSize(r, P384SIZE); return 0; } // Reduction item: 2^0 int8_t ReduceNistP521(BN_UINT *r, const BN_UINT *a) { #define P521LEFTBITS (521 % (sizeof(BN_UINT) * 8)) #define P521RIGHTBITS ((sizeof(BN_UINT) * 8) - P521LEFTBITS) BN_UINT t[P521SIZE]; uint32_t base = P521SIZE - 1; uint32_t i; for (i = 0; i < P521SIZE - 1; i++) { t[i] = (a[i + base] >> P521LEFTBITS) | (a[i + base + 1] << P521RIGHTBITS); r[i] = a[i]; } r[i] = a[i] & (((BN_UINT)1 << (P521LEFTBITS)) - 1); t[i] = (a[i + base] >> P521LEFTBITS); BinAdd(r, t, r, P521SIZE); return 0; } // The size of a is 2*P521SIZE-1, and the size of r is P521SIZE int32_t ModNistP521(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { (void)opt; (void)m; const BN_UINT *mod = MOD_DATA_P521; ReduceNistP521(r->data, a->data); if (BinCmp(r->data, P521SIZE, mod, P521SIZE) >= 0) { BinSub(r->data, r->data, mod, P521SIZE); } UpdateSize(r, P521SIZE); return 0; } static inline int8_t P256SUB(BN_UINT *rr, const BN_UINT *aa, const BN_UINT *bb) { BN_UINT borrow; SUB_AB(borrow, rr[0], aa[0], bb[0]); SUB_ABC(borrow, rr[1], aa[1], bb[1], borrow); /* offset 1 */ SUB_ABC(borrow, rr[2], aa[2], bb[2], borrow); /* offset 2 */ SUB_ABC(borrow, rr[3], aa[3], bb[3], borrow); /* offset 3 */ return (int8_t)borrow; } static inline int8_t P256ADD(BN_UINT *rr, const BN_UINT *aa, const BN_UINT *bb) { BN_UINT carry; ADD_AB(carry, rr[0], aa[0], bb[0]); /* offset 0 */ ADD_ABC(carry, rr[1], aa[1], bb[1], carry); /* offset 1 */ ADD_ABC(carry, rr[2], aa[2], bb[2], carry); /* offset 2 */ ADD_ABC(carry, rr[3], aa[3], bb[3], carry); /* offset 3 */ return (int8_t)carry; } /** * NIST_P256 curve reduction calculation for parameter P * Reduction item: 2^224 - 2^192 - 2^96 + 2^0 * ref. https://csrc.nist.gov/csrc/media/events/workshop-on-elliptic-curve-cryptography-standards/documents/papers/session6-adalier-mehmet.pdf * * Reduction list: * 7 6 5 4 3 2 1 0 * a8 01, -1, 00, 00, -1, 00, 00, 01, * a9 00, -1, 00, -1, -1, 00, 01, 01, * a10 -1, 00, -1, -1, 00, 01, 01, 00, * a11 -1, 00, -1, 00, 02, 01, 00, -1, * a12 -1, 00, 00, 02, 02, 00, -1, -1, * a13 -1, 01, 02, 02, 01, -1, -1, -1, * a14 00, 03, 02, 01, 00, -1, -1, -1, * a15 03, 02, 01, 00, -1, -1, -1, 00 * * Reduction chain * Compared with the reduce flow of the paper, we have made proper transformation, * which can reduce the splicing of upper 32 bits and lower 32 bits. * Coefficient 7 6 5 4 3 2 1 0 * 2 a15 a14 a13 a12 a12 0 0 0 * 2 a15 a14 a13 a11 * 1 a15 a14 a15 a14 a13 a11 a9 a8 * 1 a8 a13 a10 a10 a9 * -1 a13 a9 a11 a10 a15 a14 a15 a14 * -1 a12 a8 a10 a9 a8 a13 a14 a13 * -1 a11 a9 a15 a13 a12 * -1 a10 a12 a11 */ static int8_t ReduceNistP256(BN_UINT *r, const BN_UINT *a) { BN_UINT list[P256SIZE]; BN_UINT t[P256SIZE]; // Reduction chain 0 list[3] = a[7]; // offset 3 a15|a14 == ah[7]|al[7] list[2] = a[6]; // offset 2 a13|a12 == ah[6]|al[6] list[1] = BN_UINT_LO_TO_HI(a[6]); // offset 1 a12|0 == al[6]|0 list[0] = 0; // offset 0 0 // Reduction chain 1 t[3] = BN_UINT_HI(a[7]); // offset 3 0|a15 == 0|ah[7] t[2] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 2 a14|a13 == al[7]|ah[6] t[1] = BN_UINT_HI_TO_HI(a[5]); // offset 1 a11|0 == ah[5]|0 t[0] = 0; // offset 0 0 int8_t carry = P256ADD(t, t, list); // carry multiplied by 2 and padded with the most significant bit of t[3] carry = (carry * 2) + (int8_t)(t[3] >> (BN_UINT_BITS - 1)); t[3] = (t[3] << 1) | (t[2] >> (BN_UINT_BITS - 1)); // t[3] is shifted left by 1 bit and the MSB of t[2] is added. t[2] = (t[2] << 1) | (t[1] >> (BN_UINT_BITS - 1)); // t[2] is shifted left by 1 bit and the MSB of t[1] is added. t[1] = (t[1] << 1) | (t[0] >> (BN_UINT_BITS - 1)); // t[1] is shifted left by 1 bit and the MSB of t[0] is added. t[0] <<= 1; // 2 list[3] = a[7]; // offset 3 a15|a14 == ah[7]|al[7] list[2] = a[7]; // offset 2 a15|a14 == ah[7]|al[7] list[1] = BN_UINT_HI_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 1 a13|a11 == ah[6]|ah[5] list[0] = a[4]; // offset 0 a9|a8 == ah[4]|al[4] carry += (int8_t)P256ADD(t, t, list); // 3 list[3] = BN_UINT_LO_TO_HI(a[4]) | BN_UINT_HI(a[6]); // offset 3 a8|a13 == al[4]|ah[6] list[2] = 0; // offset 2 0 list[1] = BN_UINT_LO(a[5]); // offset 1 0|a10 == 0|al[5] list[0] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 0 a10|a9 == al[5]|ah[4] carry += (int8_t)P256ADD(t, t, list); // 4 list[3] = BN_UINT_HI_TO_HI(a[6]) | BN_UINT_HI(a[4]); // offset 3 a13|a9 == ah[6]|ah[4] list[2] = a[5]; // offset 2 a11|a10 == ah[5]|al[5] list[1] = a[7]; // offset 1 a15|a14 == ah[7]|al[7] list[0] = a[7]; // offset 0 a15|a14 == ah[7]|al[7] carry -= (int8_t)P256SUB(t, t, list); // 5 list[3] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_LO(a[4]); // offset 3 a12|a8 == al[6]|al[4] list[2] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 2 a10|a9 == al[5]|ah[4] list[1] = BN_UINT_LO_TO_HI(a[4]) | BN_UINT_HI(a[6]); // offset 1 a8|a13 == al[4]|ah[6] list[0] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 0 a14|a13 == al[7]|ah[6] carry -= (int8_t)P256SUB(t, t, list); // 6 list[3] = BN_UINT_HI_TO_HI(a[5]); // offset 3 a11|0 == ah[5]|0 list[2] = 0; // offset 2 0 list[1] = BN_UINT_HI_TO_HI(a[4]) | BN_UINT_HI(a[7]); // offset 1 a9|a15 == ah[4]|ah[7] list[0] = a[6]; // offset 0 a13|a12 == ah[6]|al[6] carry -= (int8_t)P256SUB(t, t, list); // 7 list[3] = BN_UINT_LO_TO_HI(a[5]); // offset 3 a10|0 == al[5]|0 list[2] = 0; // offset 2 0 list[1] = 0; // offset 1 0 list[0] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 0 a12|a11 == al[6]|ah[5] carry -= (int8_t)P256SUB(t, t, list); carry += (int8_t)P256ADD(r, t, a); return carry; } // For the NIST_P256 curve, perform modulo operation on parameter P. // The size of a is 2*P256SIZE, and the size of r is P256SIZE int32_t ModNistP256(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { (void)opt; (void)m; const BN_UINT *mod = g_modDataP256[0]; int8_t carry = ReduceNistP256(r->data, a->data); if (carry > 0) { carry = (int8_t)1 - (int8_t)P256SUB(r->data, r->data, g_modDataP256[carry - 1]); } else if (carry < 0) { /* * Here, we take carry < 0 as an example. * If carry = -3, it indicates that ReduceNistP256 needs to be borrowed three times. In this case, * we need to add 3 * p. It is worth noting that we have estimated 3 * p in g_modDataP256, * but the carry of 3 * p is not save, which is expressed by the following formula: * g_modDataP256[2] = 3 * p mod 2^256, we denoted as 2 + (3 * p)_remain. * Actually, we need to calculate the following formula: * -3 + r_data + 2 + (3 * p)_remain = -1 + r_data + (3 * p)_remain * Obviously, -1 is a mathematical borrowing, only r_data + (3 * p)_remain is calculated in actual P256ADD. * Therefore, we still need to consider the carry case of P256ADD. * 1. r_data + (3 * p)_remain has a carry. -1 has been eliminated. We only need to consider * whether r_data + (3 * p)_remain belongs to [0, p). * 2. r_data + (3*p)_remain does not carry. It indicates that –1 is not eliminated. We need to add another P * to eliminate –1. Considering the value of 3 * p in g_modDataP256, r_data + (3 * p)_remain + P must * generate a carry, and the final result value < P. */ carry = (int8_t)1 - (int8_t)P256ADD(r->data, r->data, g_modDataP256[-carry - 1]); carry = -carry; } if (carry < 0) { P256ADD(r->data, r->data, mod); } else if (carry > 0 || BinCmp(r->data, P256SIZE, mod, P256SIZE) >= 0) { P256SUB(r->data, r->data, mod); } UpdateSize(r, P256SIZE); return 0; } /** * NIST_P224 curve reduction calculation for parameter P * Reduction item: 2^96 - 2^0 * * Reduction list: * 6 5 4 3 2 1 0 * a7 00, 00, 00, 01, 00, 00, -1 * a8 00, 00, 01, 00, 00, -1, 00 * a9 00, 01, 00, 00, -1, 00, 00 * a10 01, 00, 00, -1, 00, 00, 00 * a11 00, 00, -1, 01, 00, 00, -1 * a12 00, -1, 01, 00, 00, -1, 00 * a13 -1, 01, 00, 00, -1, 00, 00 * * Reduction chain * Coefficient 6 5 4 3 2 1 0 * 1 a10 a9 a8 a7 * 1 a13 a12 a11 * -1 a13 a12 a11 a10 a9 a8 a7 * -1 a13 a12 a11 */ static int8_t ReduceNistP224(BN_UINT *r, const BN_UINT *a) { BN_UINT list[P224SIZE]; BN_UINT t[P224SIZE]; // 1 list[3] = BN_UINT_LO(a[5]); // offset 3 0|a10 == 0|al[5] list[2] = a[4]; // offset 2 a9|a8 == ah[4]|al[4] list[1] = BN_UINT_HI_TO_HI(a[3]); // offset 1 a7|0 == ah[3]|0 list[0] = 0; // offset 0 0 // 2 t[3] = 0; // offset 3 0 t[2] = a[6]; // offset 2 a13|a12 == ah[6]|al[6] t[1] = BN_UINT_HI_TO_HI(a[5]); // offset 1 a11|0 == ah[5]|0 t[0] = 0; // offset 0 0 P256ADD(t, t, list); // 3 list[3] = BN_UINT_HI(a[6]); // offset 3 0|a13 == 0|ah[6] list[2] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 2 a12|a11 == al[6]|ah[5] list[1] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 1 a10|a9 == al[5]|ah[4] list[0] = BN_UINT_LO_TO_HI(a[4]) | BN_UINT_HI(a[3]); // offset 0 a8|a7 == al[4]|ah[3] P256SUB(t, t, list); // 4 list[3] = 0; // offset 3 0 list[2] = 0; // offset 2 0 list[1] = BN_UINT_HI(a[6]); // offset 1 0|a13 == 0|ah[6] list[0] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 0 a12|a11 == al[6]|ah[5] P256SUB(t, t, list); r[3] = BN_UINT_LO(a[3]); // Take lower 32 bits of a[3] r[2] = a[2]; // Take a[2] r[1] = a[1]; r[0] = a[0]; P256ADD(r, r, t); return 0; } // NIST_P224 curve reduction calculation for parameter P. The size of a is 2*P224SIZE-1, and the size of r is P224SIZE int32_t ModNistP224( BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { (void)opt; (void)m; const BN_UINT *mod = g_modDataP224[0]; ReduceNistP224(r->data, a->data); // Obtain the high-order data of r[3] as carry information int8_t carry = (int8_t)((uint8_t)(BN_UINT_HI(r->data[3]) & 0xFF)); if (carry > 0) { (void)P256SUB(r->data, r->data, g_modDataP224[carry - 1]); } else if (carry < 0) { (void)P256ADD(r->data, r->data, g_modDataP224[-carry - 1]); } // Obtain the high-order data of r[3] as carry information carry = (int8_t)((uint8_t)(BN_UINT_HI(r->data[3]) & 0xFF)); if (carry < 0) { P256ADD(r->data, r->data, mod); } else if (carry > 0 || BinCmp(r->data, P256SIZE, mod, P256SIZE) >= 0) { P256SUB(r->data, r->data, mod); } UpdateSize(r, P224SIZE); return 0; } /** * Reduction item: 2^224 + 2^96 - 2^64 + 2^0 * 7 6 5 4 3 2 1 0 * a8 01, 00, 00, 00, 01, -1, 00, 01, * a9 01, 00, 00, 01, 00, -1, 01, 01, * a10 01, 00, 01, 00, 00, 00, 01, 01, * a11 01, 01, 00, 00, 01, 00, 01, 01, * a12 02, 00, 00, 01, 01, 00, 01, 01, * a13 02, 00, 01, 01, 02, -1, 01, 02, * a14 02, 01, 01, 02, 01, -1, 02, 02, * a15 03, 01, 02, 01, 01, 00, 02, 02, * Reduction chain * The last two reduction chain can be combined into the third to last chain for calculation. * Coefficient 7 6 5 4 3 2 1 0 * 2 a15 a14 a15 a14 a13 0 a15 a14 * 2 a14 0 0 0 0 0 a14 a13 * 2 a13 0 a13 a12 a11 0 a12 a11 * 2 a12 a11 a10 a9 0 0 a9 a8 * 1 a15 0 0 a15 a14 0 a13 a12 * 1 a11 0 0 0 a8 0 0 a15 * 1 a10 0 0 0 a15 0 a11 a10 * 1 a9 a10 a9 * 1 a8 a15 a14 a13 a12 a15 * -1 a14 a13 a12 a11 a13 a12 a11 * -1 a11 a10 a9 0 a14 a9 a8 * -1 a8 * -1 a9 */ #ifdef HITLS_CRYPTO_CURVE_SM2 static int8_t ReduceSm2P256(BN_UINT *r, const BN_UINT *a) { BN_UINT list[P256SIZE]; BN_UINT t[P256SIZE]; // Reduction chain 0, Coefficient 2 list[3] = a[7]; // offset 3 a15|a14 == ah[7]|al[7] list[2] = a[7]; // offset 2 a15|a14 == ah[7]|al[7] list[1] = BN_UINT_HI_TO_HI(a[6]); // offset 1 a13|0 == ah[6]|0 list[0] = a[7]; // offset 0 a15|a14 == ah[7]|al[7] // Reduction chain 1, Coefficient 2 t[3] = BN_UINT_LO_TO_HI(a[7]); // offset 3 a14|0 == al[7]|0 t[2] = 0; // offset 2 0 t[1] = 0; // offset 1 0 t[0] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 0 a14|a13 = al[7]|ah[6] int8_t carry = P256ADD(t, t, list); // Reduction chain 2, Coefficient 2 list[3] = BN_UINT_HI_TO_HI(a[6]); // offset 3 a13|0 == ah[6]|0 list[2] = a[6]; // offset 2 a13|a12 == ah[6]|al[6] list[1] = BN_UINT_HI_TO_HI(a[5]); // offset 1 a11|0 == ah[5]|0 list[0] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 0 a12|a11 == al[6]|ah[5] carry += (int8_t)P256ADD(t, t, list); // Reduction chain 3, Coefficient 2 list[3] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 3 a12|a11 == al[6]|ah[5] list[2] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 2 a10|a9 == al[5]|ah[4] list[1] = 0; // offset 1 0 list[0] = a[4]; // offset 0 a9|a8 == ah[4]|al[4] carry += (int8_t)P256ADD(t, t, list); // carry multiplied by 2 and padded with the most significant bit of t[3] carry = (carry * 2) + (int8_t)(t[3] >> (BN_UINT_BITS - 1)); t[3] = (t[3] << 1) | (t[2] >> (BN_UINT_BITS - 1)); // t[3] is shifted left by 1 bit and the MSB of t[2] is added. t[2] = (t[2] << 1) | (t[1] >> (BN_UINT_BITS - 1)); // t[2] is shifted left by 1 bit and the MSB of t[1] is added. t[1] = (t[1] << 1) | (t[0] >> (BN_UINT_BITS - 1)); // t[1] is shifted left by 1 bit and the MSB of t[0] is added. t[0] <<= 1; // Reduction chain 4, Coefficient 1 list[3] = BN_UINT_HI_TO_HI(a[7]); // offset 3 a15|0 == ah[7]|0 list[2] = BN_UINT_HI(a[7]); // offset 2 0|a15 == 0|ah[7] list[1] = BN_UINT_LO_TO_HI(a[7]); // offset 1 a14|0 == al[7]|0 list[0] = a[6]; // offset 0 a13|a12 == ah[6]|al[6] carry += (int8_t)P256ADD(t, t, list); // Reduction chain 5, Coefficient 1 list[3] = BN_UINT_HI_TO_HI(a[5]); // offset 3 a11|0 == ah[5]|0 list[2] = 0; // offset 2 0 list[1] = BN_UINT_LO_TO_HI(a[4]); // offset 1 a8|0 == al[4]|0 list[0] = BN_UINT_HI(a[7]); // offset 0 0|a15 == 0|ah[7] carry += (int8_t)P256ADD(t, t, list); // Reduction chain 6, Coefficient 1 list[3] = BN_UINT_LO_TO_HI(a[5]); // offset 3 a10|0 == al[5]|0 list[2] = 0; // offset 2 0 list[1] = BN_UINT_HI_TO_HI(a[7]); // offset 1 a15|0 == ah[7]|0 list[0] = a[5]; // offset 0 a11|a10 == ah[5]|al[5] carry += (int8_t)P256ADD(t, t, list); // Reduction chain 7, Coefficient 1 list[3] = BN_UINT_HI_TO_HI(a[4]); // offset 3 a9|0 == ah[4]|0 list[2] = 0; // offset 2 0 list[1] = 0; // offset 1 0 list[0] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 0 a10|a9 == al[5]|ah[4] carry += (int8_t)P256ADD(t, t, list); // Reduction chain 8, Coefficient 1 list[3] = BN_UINT_LO_TO_HI(a[4]) | BN_UINT_HI(a[7]); // offset 3 a8|a15 == al[4]|ah[7] list[2] = BN_UINT_LO_TO_HI(a[7]) | BN_UINT_HI(a[6]); // offset 2 a14|a13 = al[7]|ah[6] list[1] = BN_UINT_LO_TO_HI(a[6]); // offset 1 a12|0 == al[6]|0 list[0] = BN_UINT_HI(a[7]); // offset 0 0|a15 == 0|ah[7] carry += (int8_t)P256ADD(t, t, list); // Reduction chain 9, Coefficient -1 list[3] = BN_UINT_LO(a[7]); // offset 3 0|a14 == 0|al[7] list[2] = a[6]; // offset 2 a13|a12 == ah[6]|al[6] list[1] = BN_UINT_HI_TO_HI(a[5]) | BN_UINT_HI(a[6]); // offset 1 a11|a13 == ah[5]|ah[6] list[0] = BN_UINT_LO_TO_HI(a[6]) | BN_UINT_HI(a[5]); // offset 0 a12|a11 == al[6]|ah[5] carry -= (int8_t)P256SUB(t, t, list); // Reduction chain 10, Coefficient -1 list[3] = BN_UINT_HI(a[5]); // offset 3 0|a11 == 0|ah[5] list[2] = BN_UINT_LO_TO_HI(a[5]) | BN_UINT_HI(a[4]); // offset 2 a10|a9 == al[5]|ah[4] // offset 1 0|a14 == 0|al[7]. Add the values of the last two chains. list[1] = BN_UINT_LO(a[7]) + BN_UINT_HI(a[4]) + BN_UINT_LO(a[4]); list[0] = a[4]; // offset 0 a9|a8 == ah[4]|al[4] carry -= (int8_t)P256SUB(t, t, list); carry += (int8_t)P256ADD(r, t, a); return carry; } // SM2_P256 curve modulo parameter P. The size of a is 2*P256SIZE, and the size of r is P256SIZE int32_t ModSm2P256(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { (void)opt; (void)m; const BN_UINT *mod = MODDATASM2P256[0]; int8_t carry = ReduceSm2P256(r->data, a->data); if (carry < 0) { carry = (int8_t)1 - (int8_t)P256ADD(r->data, r->data, MODDATASM2P256[-carry - 1]); carry = -carry; } else if (carry > 0) { // For details could ref p256. carry = (int8_t)1 - (int8_t)P256SUB(r->data, r->data, MODDATASM2P256[carry - 1]); } if (carry < 0) { P256ADD(r->data, r->data, mod); } else if (carry > 0 || BinCmp(r->data, P256SIZE, mod, P256SIZE) >= 0) { P256SUB(r->data, r->data, mod); } UpdateSize(r, P256SIZE); return 0; } #endif #elif defined(HITLS_THIRTY_TWO_BITS) int32_t ModNistP224(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { return BN_Mod(r, a, m, opt); } int32_t ModNistP256(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { return BN_Mod(r, a, m, opt); } #ifdef HITLS_CRYPTO_CURVE_SM2 int32_t ModSm2P256(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { return BN_Mod(r, a, m, opt); } #endif int32_t ModNistP384(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { return BN_Mod(r, a, m, opt); } int32_t ModNistP521(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { return BN_Mod(r, a, m, opt); } #endif #if defined(HITLS_CRYPTO_BN_COMBA) && defined(HITLS_SIXTY_FOUR_BITS) static uint32_t MulNistP256P224(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize) { (void)rSize; (void)aSize; (void)bSize; MulComba4(r, a, b); uint32_t size = P224SIZE << 1; // in 64-bit environment, P224SIZE = P256SIZE while (size > 0) { if (r[size - 1] != 0) { break; } --size; } return size; } static uint32_t SqrNistP256P224(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize) { (void)rSize; (void)aSize; SqrComba4(r, a); uint32_t size = P224SIZE << 1; // in 64-bit environment, P224SIZE = P256SIZE while (size > 0) { if (r[size - 1] != 0) { break; } --size; } return size; } static uint32_t MulNistP384(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize) { (void)rSize; (void)aSize; (void)bSize; MulComba6(r, a, b); uint32_t size = P384SIZE << 1; while (size > 0) { if (r[size - 1] != 0) { break; } size--; } return size; } static uint32_t SqrNistP384(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize) { (void)rSize; (void)aSize; SqrComba6(r, a); uint32_t size = P384SIZE << 1; while (size > 0) { if (r[size - 1] != 0) { break; } size--; } return size; } #else static uint32_t MulNistP256P224(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize) { return BinMul(r, rSize, a, aSize, b, bSize); } static uint32_t SqrNistP256P224(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize) { return BinSqr(r, rSize, a, aSize); } static uint32_t MulNistP384(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize, const BN_UINT *b, uint32_t bSize) { return BinMul(r, rSize, a, aSize, b, bSize); } static uint32_t SqrNistP384(BN_UINT *r, uint32_t rSize, const BN_UINT *a, uint32_t aSize) { return BinSqr(r, rSize, a, aSize); } #endif static inline int32_t ModCalParaCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod) { if (r == NULL || a == NULL || b == NULL || mod == NULL) { return CRYPT_NULL_INPUT; } // 保证不越界访问 if ((mod->size > a->room) || (mod->size > b->room)) { return CRYPT_BN_SPACE_NOT_ENOUGH; } return BnExtend(r, mod->size); } // The user must ensure that a < m, and a->room & b->room are not less than mod->size. // All the data must be not negative number, otherwise the API may be not functional. int32_t BN_ModAddQuick(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, const BN_Optimizer *opt) { int32_t ret = ModCalParaCheck(r, a, b, mod); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } (void)opt; BN_UINT carry = BinAdd(r->data, a->data, b->data, mod->size); if (carry > 0 || BinCmp(r->data, mod->size, mod->data, mod->size) >= 0) { BinSub(r->data, r->data, mod->data, mod->size); } UpdateSize(r, mod->size); return CRYPT_SUCCESS; } // The user must ensure that a < m, and a->room & b->room are not less than mod->size. // All the data must be not negative number, otherwise the API may be not functional. int32_t BN_ModSubQuick(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, const BN_Optimizer *opt) { int32_t ret = ModCalParaCheck(r, a, b, mod); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } (void)opt; int32_t res = BinCmp(a->data, a->size, b->data, b->size); if (res < 0) { /* Apply for the temporary space of the BN object. */ BinSub(r->data, a->data, b->data, mod->size); BinAdd(r->data, r->data, mod->data, mod->size); } else { BinSub(r->data, a->data, b->data, mod->size); } UpdateSize(r, mod->size); return CRYPT_SUCCESS; } static inline int32_t ModEccMulParaCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt) { if (r == NULL || a == NULL || b == NULL || mod == NULL || opt == NULL) { return CRYPT_NULL_INPUT; } // Ensure that no out-of-bounds access occurs. if ((mod->size > b->room) || (mod->size > a->room)) { return CRYPT_BN_SPACE_NOT_ENOUGH; } return BnExtend(r, mod->size); } // The user must ensure that a < m, and a->room & b->room are not less than mod->size. // All the data must be not negative number, otherwise the API may be not functional. int32_t BN_ModNistEccMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *data, BN_Optimizer *opt) { BN_BigNum *mod = (BN_BigNum *)data; int32_t ret = ModEccMulParaCheck(r, a, b, mod, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (b->size == 0 || a->size == 0) { return BN_Zeroize(r); } BN_UINT tData[P521SIZE << 1] = { 0 }; BN_BigNum rMul = { .data = tData, .size = 0, .sign = false, .room = P521SIZE << 1 }; uint32_t size = mod->size << 1; uint32_t bits = BN_Bits(mod); if (bits == 224) { // 224bit rMul.size = MulNistP256P224(rMul.data, size, a->data, mod->size, b->data, mod->size); ModNistP224(r, &rMul, mod, opt); } else if (bits == 256) { // 256bit rMul.size = MulNistP256P224(rMul.data, size, a->data, mod->size, b->data, mod->size); ModNistP256(r, &rMul, mod, opt); } else if (bits == 384) { // 384bit rMul.size = MulNistP384(rMul.data, size, a->data, mod->size, b->data, mod->size); ModNistP384(r, &rMul, mod, opt); } else if (bits == 521) { // 521bit rMul.size = BinMul(rMul.data, size, a->data, mod->size, b->data, mod->size); ModNistP521(r, &rMul, mod, opt); } else { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_QUICK_MODDATA); return CRYPT_BN_ERR_QUICK_MODDATA; } return CRYPT_SUCCESS; } static int32_t ModEccSqrParaCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *mod, BN_Optimizer *opt) { if (r == NULL || a == NULL || mod == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } // Ensure that no out-of-bounds access occurs. if (mod->size > a->room) { BSL_ERR_PUSH_ERROR(CRYPT_BN_SPACE_NOT_ENOUGH); return CRYPT_BN_SPACE_NOT_ENOUGH; } return BnExtend(r, mod->size); } // The user must ensure that a < m, and a->room & b->room are not less than mod->size. // All the data must be not negative number, otherwise the API may be not functional. int32_t BN_ModNistEccSqr(BN_BigNum *r, const BN_BigNum *a, void *data, BN_Optimizer *opt) { BN_BigNum *mod = (BN_BigNum *)data; int32_t ret = ModEccSqrParaCheck(r, a, mod, opt); if (ret != CRYPT_SUCCESS) { return ret; } if (a->size == 0) { return BN_Zeroize(r); } BN_UINT tData[P521SIZE << 1] = { 0 }; BN_BigNum rSqr = { .data = tData, .size = 0, .sign = false, .room = P521SIZE << 1 }; uint32_t size = mod->size << 1; uint32_t bits = BN_Bits(mod); if (bits == 224) { // 224bit rSqr.size = SqrNistP256P224(rSqr.data, size, a->data, mod->size); ModNistP224(r, &rSqr, mod, opt); } else if (bits == 256) { // 256bit rSqr.size = SqrNistP256P224(rSqr.data, size, a->data, mod->size); ModNistP256(r, &rSqr, mod, opt); } else if (bits == 384) { // 384bit rSqr.size = SqrNistP384(rSqr.data, size, a->data, mod->size); ModNistP384(r, &rSqr, mod, opt); } else if (bits == 521) { // 521bit rSqr.size = BinSqr(rSqr.data, size, a->data, mod->size); ModNistP521(r, &rSqr, mod, opt); } else { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_QUICK_MODDATA); return CRYPT_BN_ERR_QUICK_MODDATA; } return CRYPT_SUCCESS; } #ifdef HITLS_CRYPTO_CURVE_SM2 #define SM2SIZE SIZE_OF_BNUINT(256) // The user must ensure that a < m, and a->room & b->room are not less than mod->size. // All the data must be not negative number, otherwise the API may be not functional. int32_t BN_ModSm2EccMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, void *data, BN_Optimizer *opt) { BN_BigNum *mod = (BN_BigNum *)data; int32_t ret = ModEccMulParaCheck(r, a, b, mod, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (a->size == 0 || b->size == 0) { return BN_Zeroize(r); } BN_UINT tData[SM2SIZE << 1] = { 0 }; BN_BigNum rMul = { .data = tData, .size = 0, .sign = false, .room = SM2SIZE << 1 }; uint32_t size = mod->size << 1; rMul.size = MulNistP256P224(rMul.data, size, a->data, mod->size, b->data, mod->size); ModSm2P256(r, &rMul, mod, opt); return CRYPT_SUCCESS; } // The user must ensure that a < m, and a->room & b->room are not less than mod->size. // All the data must be not negative number, otherwise the API may be not functional. int32_t BN_ModSm2EccSqr(BN_BigNum *r, const BN_BigNum *a, void *data, BN_Optimizer *opt) { BN_BigNum *mod = (BN_BigNum *)data; int32_t ret = ModEccSqrParaCheck(r, a, mod, opt); if (ret != CRYPT_SUCCESS) { return ret; } if (a->size == 0) { return BN_Zeroize(r); } BN_UINT tData[SM2SIZE << 1] = { 0 }; BN_BigNum rSqr = { .data = tData, .size = 0, .sign = false, .room = SM2SIZE << 1 }; uint32_t size = mod->size << 1; rSqr.size = SqrNistP256P224(rSqr.data, size, a->data, mod->size); ModSm2P256(r, &rSqr, mod, opt); return CRYPT_SUCCESS; } #endif #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_nistmod.c
C
unknown
45,086
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "bn_basic.h" #include "bn_bincal.h" #include "bn_ucal.h" #include "bn_optimizer.h" #define SMALL_CONQUER_SIZE 8 int32_t BN_Cmp(const BN_BigNum *a, const BN_BigNum *b) { if (a == NULL || b == NULL) { if (a != NULL) { return -1; } if (b != NULL) { return 1; } return 0; } if (a->sign != b->sign) { return a->sign == false ? 1 : -1; } if (a->sign == true) { return BinCmp(b->data, b->size, a->data, a->size); } return BinCmp(a->data, a->size, b->data, b->size); } int32_t BN_Add(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b) { if (r == NULL || a == NULL || b == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (a->sign == b->sign) { r->sign = a->sign; return UAdd(r, a, b); } // compare absolute value int32_t res = BinCmp(a->data, a->size, b->data, b->size); if (res > 0) { r->sign = a->sign; return USub(r, a, b); } else if (res < 0) { r->sign = b->sign; return USub(r, b, a); } return BN_Zeroize(r); } int32_t BN_AddLimb(BN_BigNum *r, const BN_BigNum *a, BN_UINT w) { if (r == NULL || a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (a->size == 0) { return BN_SetLimb(r, w); } int32_t ret; if (a->sign == false) { // a is positive ret = BnExtend(r, a->size + 1); if (ret != CRYPT_SUCCESS) { return ret; } BN_UINT carry = BinInc(r->data, a->data, a->size, w); if (carry != 0) { uint32_t size = a->size; r->size = size + 1; r->data[size] = carry; } else { r->size = a->size; } r->sign = false; return CRYPT_SUCCESS; } ret = BnExtend(r, a->size); if (ret != CRYPT_SUCCESS) { return ret; } if (a->size == 1) { if (a->data[0] > w) { r->sign = true; r->data[0] = a->data[0] - w; r->size = 1; } else if (a->data[0] == w) { r->sign = false; r->data[0] = 0; r->size = 0; } else { r->sign = false; r->data[0] = w - a->data[0]; r->size = 1; } return CRYPT_SUCCESS; } r->sign = true; UDec(r, a, w); return CRYPT_SUCCESS; } int32_t BN_Sub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b) { if (r == NULL || a == NULL || b == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (a->sign != b->sign) { r->sign = a->sign; return UAdd(r, a, b); } // compare absolute value int32_t res = BinCmp(a->data, a->size, b->data, b->size); if (res == 0) { return BN_Zeroize(r); } else if (res > 0) { r->sign = a->sign; return USub(r, a, b); } r->sign = !b->sign; return USub(r, b, a); } int32_t BN_SubLimb(BN_BigNum *r, const BN_BigNum *a, BN_UINT w) { if (r == NULL || a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret; if (a->size == 0) { if (BN_SetLimb(r, w) != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } r->sign = (w == 0) ? false : true; return CRYPT_SUCCESS; } if (a->sign == true) { ret = BnExtend(r, a->size + 1); if (ret != CRYPT_SUCCESS) { return ret; } BN_UINT carry = BinInc(r->data, a->data, a->size, w); if (carry != 0) { uint32_t size = a->size; r->data[size] = carry; r->size = size + 1; } else { r->size = a->size; } r->sign = true; return CRYPT_SUCCESS; } ret = BnExtend(r, a->size); if (ret != CRYPT_SUCCESS) { return ret; } if (a->size == 1) { if (a->data[0] >= w) { r->data[0] = a->data[0] - w; r->size = BinFixSize(r->data, 1); } else { r->sign = true; r->data[0] = w - a->data[0]; r->size = 1; } return CRYPT_SUCCESS; } r->sign = false; UDec(r, a, w); return CRYPT_SUCCESS; } #ifdef HITLS_CRYPTO_BN_COMBA static int32_t BnMulConquer(BN_BigNum *t, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt) { if (a->size <= SMALL_CONQUER_SIZE && a->size % 2 == 0) { // 2 is to check if a->size is even MulConquer(t->data, a->data, b->data, a->size, NULL, false); } else { BN_BigNum *tmpBn = OptimizerGetBn(opt, SpaceSize(a->size)); if (tmpBn == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } MulConquer(t->data, a->data, b->data, a->size, tmpBn->data, false); } t->size = a->size + b->size; return CRYPT_SUCCESS; } #endif int32_t BN_Mul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_Optimizer *opt) { if (r == NULL || a == NULL || b == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (a->size == 0 || b->size == 0) { return BN_Zeroize(r); } uint32_t size = a->size + b->size; int32_t ret = BnExtend(r, size); if (ret != CRYPT_SUCCESS) { return ret; } ret = OptimizerStart(opt); // using the Optimizer if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_BigNum *t = NULL; if (r == a || r == b) { t = OptimizerGetBn(opt, r->room); // apply for a BN object if (t == NULL) { OptimizerEnd(opt); // release occupation from the optimizer BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } } else { t = r; } t->sign = a->sign != b->sign; #ifdef HITLS_CRYPTO_BN_COMBA if (a->size == b->size) { ret = BnMulConquer(t, a, b, opt); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); return ret; } } else { #endif t->size = BinMul(t->data, t->room, a->data, a->size, b->data, b->size); #ifdef HITLS_CRYPTO_BN_COMBA } #endif if (r != t) { ret = BN_Copy(r, t); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); // release occupation from the optimizer BSL_ERR_PUSH_ERROR(ret); return ret; } } r->size = BinFixSize(r->data, size); OptimizerEnd(opt); return CRYPT_SUCCESS; } int32_t BN_MulLimb(BN_BigNum *r, const BN_BigNum *a, const BN_UINT w) { if (r == NULL || a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (BN_Bits(a) == 0 || w == 0) { return BN_Zeroize(r); } int32_t ret = BnExtend(r, a->size + 1); if (ret != CRYPT_SUCCESS) { return ret; } BN_UINT carry = 0; uint32_t loc; for (loc = 0; loc < a->size; loc++) { BN_UINT rh; BN_UINT rl; MUL_AB(rh, rl, a->data[loc], w); ADD_AB(carry, r->data[loc], rl, carry); carry += rh; } if (carry != 0) { r->data[loc++] = carry; // Input parameter checking ensures that no out-of-bounds } r->sign = a->sign; r->size = loc; return CRYPT_SUCCESS; } int32_t BN_Sqr(BN_BigNum *r, const BN_BigNum *a, BN_Optimizer *opt) { if (r == NULL || a == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (a->size == 0) { return BN_Zeroize(r); } int32_t ret = BnExtend(r, a->size * 2); // The maximum bit required for mul is 2x that of a. if (ret != CRYPT_SUCCESS) { return ret; } ret = OptimizerStart(opt); // using the Optimizer if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } #ifdef HITLS_CRYPTO_BN_COMBA if (a->size <= SMALL_CONQUER_SIZE && a->size % 2 == 0) { // 2 is to check if a->size is even. SqrConquer(r->data, a->data, a->size, NULL, false); } else { BN_BigNum *tmpBn = OptimizerGetBn(opt, SpaceSize(a->size)); if (tmpBn == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } SqrConquer(r->data, a->data, a->size, tmpBn->data, false); } #else BinSqr(r->data, a->size << 1, a->data, a->size); #endif r->size = BinFixSize(r->data, a->size * 2); // The r->data size is a->size * 2. r->sign = false; // The square must be positive. OptimizerEnd(opt); return CRYPT_SUCCESS; } int32_t DivInputCheck(const BN_BigNum *q, const BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *y, const BN_Optimizer *opt) { if (x == NULL || y == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (q == r) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } // The divisor cannot be 0. if (y->size == 0) { return CRYPT_BN_ERR_DIVISOR_ZERO; } return CRYPT_SUCCESS; } // If x <= y, perform special processing. int32_t DivSimple(BN_BigNum *q, BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *y, int32_t flag) { int32_t ret; if (flag < 0) { if (r != NULL) { ret = BN_Copy(r, x); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } if (q != NULL) { return BN_Zeroize(q); } } else { if (q != NULL) { bool sign = (x->sign != y->sign); ret = BN_SetLimb(q, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } q->sign = sign; } if (r != NULL) { return BN_Zeroize(r); } } return CRYPT_SUCCESS; } int32_t BN_Div(BN_BigNum *q, BN_BigNum *r, const BN_BigNum *x, const BN_BigNum *y, BN_Optimizer *opt) { int32_t ret = DivInputCheck(q, r, x, y, opt); if (ret != CRYPT_SUCCESS) { return ret; } ret = BinCmp(x->data, x->size, y->data, y->size); if (ret <= 0) { // simple processing when dividend <= divisor return DivSimple(q, r, x, y, ret); } ret = OptimizerStart(opt); // using the Optimizer if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* Apply for temporary space for the q and r of the BN. */ BN_BigNum *qTmp = OptimizerGetBn(opt, x->size + 2); // BinDiv:x->room >= xSize + 2 BN_BigNum *rTmp = OptimizerGetBn(opt, x->size + 2); // BinDiv:x->room >= xSize + 2 BN_BigNum *yTmp = OptimizerGetBn(opt, y->size); if (qTmp == NULL || rTmp == NULL || yTmp == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); ret = CRYPT_BN_OPTIMIZER_GET_FAIL; goto err; } (void)memcpy_s(yTmp->data, y->size * sizeof(BN_UINT), y->data, y->size * sizeof(BN_UINT)); (void)memcpy_s(rTmp->data, x->size * sizeof(BN_UINT), x->data, x->size * sizeof(BN_UINT)); rTmp->sign = x->sign; rTmp->size = BinDiv(qTmp->data, &(qTmp->size), rTmp->data, x->size, yTmp->data, y->size); if (q != NULL) { ret = BnExtend(q, qTmp->size); if (ret != CRYPT_SUCCESS) { goto err; } q->sign = (x->sign != y->sign); (void)memcpy_s(q->data, qTmp->size * sizeof(BN_UINT), qTmp->data, qTmp->size * sizeof(BN_UINT)); q->size = qTmp->size; } if (r != NULL) { ret = BnExtend(r, rTmp->size); if (ret != CRYPT_SUCCESS) { goto err; } r->sign = (rTmp->size == 0) ? false : rTmp->sign; // The symbol can only be positive when the value is 0. (void)memcpy_s(r->data, rTmp->size * sizeof(BN_UINT), rTmp->data, rTmp->size * sizeof(BN_UINT)); r->size = rTmp->size; } err: OptimizerEnd(opt); // release occupation from the optimizer return ret; } int32_t DivLimbInputCheck(const BN_BigNum *q, const BN_UINT *r, const BN_BigNum *x, const BN_UINT y) { if (x == NULL || (q == NULL && r == NULL)) { // q and r cannot be NULL at the same time BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (y == 0) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO); return CRYPT_BN_ERR_DIVISOR_ZERO; } return CRYPT_SUCCESS; } int32_t BN_DivLimb(BN_BigNum *q, BN_UINT *r, const BN_BigNum *x, const BN_UINT y) { int32_t ret = DivLimbInputCheck(q, r, x, y); if (ret != CRYPT_SUCCESS) { return ret; } // Apply for a copy of object x. BN_BigNum *xTmp = BN_Dup(x); if (xTmp == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } BN_UINT rem = 0; BN_UINT yTmp = y; uint32_t shifts; if (x->size == 0) { goto end; } shifts = GetZeroBitsUint(yTmp); if (shifts != 0) { yTmp <<= shifts; // Ensure that the most significant bit of the divisor is 1. ret = BN_Lshift(xTmp, xTmp, shifts); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BN_Destroy(xTmp); return ret; } } for (int32_t i = (int32_t)(xTmp->size - 1); i >= 0; i--) { BN_UINT quo; DIV_ND(quo, rem, rem, xTmp->data[i], yTmp); xTmp->data[i] = quo; } xTmp->size = BinFixSize(xTmp->data, xTmp->size); if (xTmp->size == 0) { xTmp->sign = 0; } rem >>= shifts; end: if (q != NULL) { ret = BN_Copy(q, xTmp); if (ret != CRYPT_SUCCESS) { BN_Destroy(xTmp); BSL_ERR_PUSH_ERROR(ret); return ret; } } if (r != NULL) { *r = rem; } BN_Destroy(xTmp); return ret; } int32_t BN_Mod(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *m, BN_Optimizer *opt) { // check input parameters if (r == NULL || a == NULL || m == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (m->size == 0) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO); return CRYPT_BN_ERR_DIVISOR_ZERO; } int32_t ret = BnExtend(r, m->size); if (ret != CRYPT_SUCCESS) { return ret; } ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_BigNum *t = OptimizerGetBn(opt, m->size); if (t == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } ret = BN_Div(NULL, t, a, m, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); OptimizerEnd(opt); return ret; } // t is a positive number if (t->sign == false) { ret = BN_Copy(r, t); OptimizerEnd(opt); return ret; } // When t is a negative number, the modulo operation result must be positive. if (m->sign == true) { // m is a negative number ret = BN_Sub(r, t, m); } else { // m is a positive number ret = BN_Add(r, t, m); } if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } OptimizerEnd(opt); return ret; } int32_t BN_ModLimb(BN_UINT *r, const BN_BigNum *a, const BN_UINT m) { if (r == NULL || a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (m == 0) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO); return CRYPT_BN_ERR_DIVISOR_ZERO; } if (a->size == 0) { *r = 0; return CRYPT_SUCCESS; } int32_t ret = BN_DivLimb(NULL, r, a, m); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (a->sign) { *r = m - *r; } return ret; } // Check the input parameters of basic operations such as modulo addition, subtraction, and multiplication. int32_t ModBaseInputCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, const BN_Optimizer *opt) { if (r == NULL || a == NULL || b == NULL || mod == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = BnExtend(r, mod->size); if (ret != CRYPT_SUCCESS) { return ret; } // mod cannot be 0 if (BN_IsZero(mod)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO); return CRYPT_BN_ERR_DIVISOR_ZERO; } return CRYPT_SUCCESS; } int32_t BN_ModSub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt) { int32_t ret; ret = ModBaseInputCheck(r, a, b, mod, opt); if (ret != CRYPT_SUCCESS) { return ret; } ret = OptimizerStart(opt); // using the Optimizer if (ret != CRYPT_SUCCESS) { return ret; } /* Difference: Apply for the temporary space of the BN object. */ uint32_t subTmpSize = (a->size > b ->size) ? a->size : b->size; BN_BigNum *t = OptimizerGetBn(opt, subTmpSize); if (t == NULL) { ret = CRYPT_BN_OPTIMIZER_GET_FAIL; BSL_ERR_PUSH_ERROR(ret); goto err; } ret = BN_Sub(t, a, b); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto err; } ret = BN_Mod(r, t, mod, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } err: OptimizerEnd(opt); // release occupation from the optimizer return ret; } int32_t BN_ModAdd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt) { int32_t ret; ret = ModBaseInputCheck(r, a, b, mod, opt); if (ret != CRYPT_SUCCESS) { return ret; } ret = OptimizerStart(opt); // using the Optimizer if (ret != CRYPT_SUCCESS) { return ret; } /* Difference: Apply for the temporary space of the BN object. */ uint32_t addTmpSize = (a->size > b ->size) ? a->size : b->size; BN_BigNum *t = OptimizerGetBn(opt, addTmpSize); if (t == NULL) { ret = CRYPT_BN_OPTIMIZER_GET_FAIL; BSL_ERR_PUSH_ERROR(ret); goto err; } ret = BN_Add(t, a, b); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto err; } ret = BN_Mod(r, t, mod, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } err: OptimizerEnd(opt); // release occupation from the optimizer return ret; } int32_t BN_ModMul(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, const BN_BigNum *mod, BN_Optimizer *opt) { int32_t ret; ret = ModBaseInputCheck(r, a, b, mod, opt); if (ret != CRYPT_SUCCESS) { return ret; } ret = OptimizerStart(opt); // using the Optimizer if (ret != CRYPT_SUCCESS) { return ret; } /* Apply for the temporary space of the BN object. */ BN_BigNum *t = OptimizerGetBn(opt, a->size + b->size + 1); if (t == NULL) { ret = CRYPT_BN_OPTIMIZER_GET_FAIL; BSL_ERR_PUSH_ERROR(ret); goto err; } ret = BN_Mul(t, a, b, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto err; } ret = BN_Mod(r, t, mod, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } err: OptimizerEnd(opt); // release occupation from the optimizer return ret; } int32_t BN_ModSqr(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *mod, BN_Optimizer *opt) { bool invalidInput = (r == NULL || a == NULL || mod == NULL || opt == NULL); if (invalidInput) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } // mod cannot be 0 if (BN_IsZero(mod)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO); return CRYPT_BN_ERR_DIVISOR_ZERO; } int32_t ret = BnExtend(r, mod->size); if (ret != CRYPT_SUCCESS) { return ret; } ret = OptimizerStart(opt); // using the Optimizer if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* Apply for the temporary space of the BN object. */ BN_BigNum *t = OptimizerGetBn(opt, (a->size << 1) + 1); if (t == NULL) { ret = CRYPT_BN_OPTIMIZER_GET_FAIL; BSL_ERR_PUSH_ERROR(ret); goto err; } ret = BN_Sqr(t, a, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto err; } ret = BN_Mod(r, t, mod, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } err: OptimizerEnd(opt); // release occupation from the optimizer return ret; } int32_t ModExpInputCheck(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, const BN_BigNum *m, const BN_Optimizer *opt) { bool invalidInput = (r == NULL || a == NULL || e == NULL || m == NULL || opt == NULL); if (invalidInput) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } // mod cannot be 0 if (BN_IsZero(m)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_DIVISOR_ZERO); return CRYPT_BN_ERR_DIVISOR_ZERO; } // the power cannot be negative if (e->sign == true) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_EXP_NO_NEGATIVE); return CRYPT_BN_ERR_EXP_NO_NEGATIVE; } return BnExtend(r, m->size); } int32_t ModExpCore(BN_BigNum *x, BN_BigNum *y, const BN_BigNum *e, const BN_BigNum *m, BN_Optimizer *opt) { int32_t ret; if (BN_GetBit(e, 0) == 1) { (void)BN_Copy(x, y); // ignores the returned value, we can ensure that no error occurs when applying memory } else { // set the value to 1 (void)BN_SetLimb(x, 1); // ignores the returned value, we can ensure that no error occurs when applying memory } uint32_t bits = BN_Bits(e); for (uint32_t i = 1; i < bits; i++) { ret = BN_ModSqr(y, y, m, opt); // y is a temporary variable, which is multiplied by x if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (BN_GetBit(e, i) == 1) { ret = BN_ModMul(x, x, y, m, opt); // x^1101 = x^1 * x^100 * x^1000 if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } } return CRYPT_SUCCESS; } static int32_t SwitchMont(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, const BN_BigNum *m, BN_Optimizer *opt) { BN_Mont *mont = BN_MontCreate(m); if (mont == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = BN_MontExp(r, a, e, mont, opt); BN_MontDestroy(mont); return ret; } int32_t BN_ModExp(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *e, const BN_BigNum *m, BN_Optimizer *opt) { int32_t ret = ModExpInputCheck(r, a, e, m, opt); if (ret != CRYPT_SUCCESS) { return ret; } // When m = 1 or -1 if (m->size == 1 && m->data[0] == 1) { return BN_Zeroize(r); } if (BN_IsOdd(m) && !BN_IsNegative(m)) { return SwitchMont(r, a, e, m, opt); } ret = OptimizerStart(opt); // using the Optimizer if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* Apply for the temporary space of the BN object. */ BN_BigNum *x = OptimizerGetBn(opt, m->size); BN_BigNum *y = OptimizerGetBn(opt, m->size); if (x == NULL || y == NULL) { OptimizerEnd(opt); // release occupation from the optimizer BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } // step 1: Obtain the modulus once, and then determine the power and remainder. ret = BN_Mod(y, a, m, opt); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(ret); return ret; } // step2: check the power. Any number to the power of 0 is 1. (0 to the power of 0 to the power of 0) if (BN_IsZero(e) || BN_IsOne(y)) { OptimizerEnd(opt); return BN_SetLimb(r, 1); } // step3: The remainder is 0 and the result must be 0. if (BN_IsZero(y)) { OptimizerEnd(opt); // release occupation from the optimizer return BN_Zeroize(r); } /* Power factorization: e binary x^1101 = x^1 * x^100 * x^1000 e Decimal x^13 = x^1 * x^4 * x^8 */ ret = ModExpCore(x, y, e, m, opt); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BN_Copy(r, x); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } OptimizerEnd(opt); // release occupation from the optimizer return ret; } int32_t BN_Rshift(BN_BigNum *r, const BN_BigNum *a, uint32_t n) { if (r == NULL || a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (BN_Bits(a) <= n) { return BN_Zeroize(r); } int32_t ret = BnExtend(r, BITS_TO_BN_UNIT(BN_Bits(a) - n)); if (ret != CRYPT_SUCCESS) { return ret; } r->sign = a->sign; uint32_t size = BinRshift(r->data, a->data, a->size, n); if (size < r->size) { if (memset_s(r->data + size, (r->room - size) * sizeof(BN_UINT), 0, (r->size - size) * sizeof(BN_UINT)) != EOK) { BSL_ERR_PUSH_ERROR(CRYPT_SECUREC_FAIL); return CRYPT_SECUREC_FAIL; } } r->size = size; return CRYPT_SUCCESS; } int32_t BN_Lshift(BN_BigNum *r, const BN_BigNum *a, uint32_t n) { if (r == NULL || a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint32_t incUnit = n % BN_UINT_BITS == 0 ? (n / BN_UINT_BITS) : ((n / BN_UINT_BITS) + 1); int32_t ret = BnExtend(r, a->size + incUnit); if (ret != CRYPT_SUCCESS) { return ret; } if (a->size != 0) { r->size = BinLshift(r->data, a->data, a->size, n); } else { (void)BN_Zeroize(r); } r->sign = a->sign; return CRYPT_SUCCESS; } #ifdef HITLS_CRYPTO_ECC // '~mask' is the mask of a and 'mask' is the mask of b. int32_t BN_CopyWithMask(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b, BN_UINT mask) { if (r == NULL || a == NULL || b == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((a->room != r->room) || (b->room != r->room)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_MASKCOPY_LEN); return CRYPT_BN_ERR_MASKCOPY_LEN; } BN_UINT rmask = ~mask; uint32_t len = r->room; BN_UINT *dst = r->data; BN_UINT *srcA = a->data; BN_UINT *srcB = b->data; for (uint32_t i = 0; i < len; i++) { dst[i] = (srcA[i] & rmask) ^ (srcB[i] & mask); } r->sign = (mask != 0) ? (a->sign) : (b->sign); r->size = (a->size & (uint32_t)rmask) ^ (b->size & (uint32_t)mask); return CRYPT_SUCCESS; } #endif #if defined(HITLS_CRYPTO_ECC) && defined(HITLS_CRYPTO_CURVE_MONT) /* Invoked by the ECC module and the sign can be ignored. * if mask = BN_MASK, a, b --> b, a * if mask = 0, a, b --> a, b */ int32_t BN_SwapWithMask(BN_BigNum *a, BN_BigNum *b, BN_UINT mask) { if (a == NULL || b == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (a->room != b->room) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_SWAP_LEN); return CRYPT_BN_ERR_SWAP_LEN; } BN_UINT rmask = ~mask; BN_UINT *srcA = a->data; BN_UINT *srcB = b->data; BN_UINT tmp1; BN_UINT tmp2; for (uint32_t i = 0; i < a->room; i++) { tmp1 = srcA[i]; tmp2 = srcB[i]; srcA[i] = (tmp1 & rmask) | (tmp2 & mask); srcB[i] = (tmp2 & rmask) | (tmp1 & mask); } tmp1 = a->size; tmp2 = b->size; a->size = (tmp1 & (uint32_t)rmask) | (tmp2 & (uint32_t)mask); b->size = (tmp2 & (uint32_t)rmask) | (tmp1 & (uint32_t)mask); return CRYPT_SUCCESS; } #endif // HITLS_CRYPTO_ECC and HITLS_CRYPTO_CURVE_MONT #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_operation.c
C
unknown
29,125
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include <string.h> #include "securec.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "bn_optimizer.h" BN_Optimizer *BN_OptimizerCreate(void) { BN_Optimizer *opt = BSL_SAL_Calloc(1u, sizeof(BN_Optimizer)); if (opt == NULL) { return NULL; } opt->curChunk = BSL_SAL_Calloc(1u, sizeof(Chunk)); if (opt->curChunk == NULL) { BSL_SAL_FREE(opt); return NULL; } return opt; } void BN_OptimizerSetLibCtx(void *libCtx, BN_Optimizer *opt) { opt->libCtx = libCtx; } void *BN_OptimizerGetLibCtx(BN_Optimizer *opt) { return opt->libCtx; } void BN_OptimizerDestroy(BN_Optimizer *opt) { if (opt == NULL) { return; } Chunk *curChunk = opt->curChunk; Chunk *nextChunk = curChunk->next; Chunk *prevChunk = curChunk->prev; while (nextChunk != NULL) { for (uint32_t i = 0; i < HITLS_CRYPT_OPTIMIZER_BN_NUM; i++) { BSL_SAL_CleanseData((void *)(nextChunk->bigNums[i].data), nextChunk->bigNums[i].size * sizeof(BN_UINT)); BSL_SAL_FREE(nextChunk->bigNums[i].data); } Chunk *tmp = nextChunk->next; BSL_SAL_Free(nextChunk); nextChunk = tmp; } while (prevChunk != NULL) { for (uint32_t i = 0; i < HITLS_CRYPT_OPTIMIZER_BN_NUM; i++) { BSL_SAL_CleanseData((void *)(prevChunk->bigNums[i].data), prevChunk->bigNums[i].size * sizeof(BN_UINT)); BSL_SAL_FREE(prevChunk->bigNums[i].data); } Chunk *tmp = prevChunk->prev; BSL_SAL_Free(prevChunk); prevChunk = tmp; } // curChunk != NULL for (uint32_t i = 0; i < HITLS_CRYPT_OPTIMIZER_BN_NUM; i++) { BSL_SAL_CleanseData((void *)(curChunk->bigNums[i].data), curChunk->bigNums[i].size * sizeof(BN_UINT)); BSL_SAL_FREE(curChunk->bigNums[i].data); } BSL_SAL_Free(curChunk); BSL_SAL_Free(opt); } int32_t OptimizerStart(BN_Optimizer *opt) { if (opt->deep != CRYPT_OPTIMIZER_MAXDEEP) { opt->deep++; return CRYPT_SUCCESS; } BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_STACK_FULL); return CRYPT_BN_OPTIMIZER_STACK_FULL; } /* create a new room that has not been initialized */ static BN_BigNum *GetPresetBn(BN_Optimizer *opt, Chunk *curChunk) { if (curChunk->occupied != HITLS_CRYPT_OPTIMIZER_BN_NUM) { curChunk->occupied++; return &curChunk->bigNums[curChunk->occupied - 1]; } if (curChunk->prev != NULL) { opt->curChunk = curChunk->prev; opt->curChunk->occupied++; // new chunk and occupied = 0; return &opt->curChunk->bigNums[opt->curChunk->occupied - 1]; } // We has used all chunks. Chunk *newChunk = BSL_SAL_Calloc(1u, sizeof(Chunk)); if (newChunk == NULL) { return NULL; } newChunk->next = curChunk; curChunk->prev = newChunk; opt->curChunk = newChunk; newChunk->occupied++; return &newChunk->bigNums[newChunk->occupied - 1]; } static int32_t BnMake(BN_BigNum *r, uint32_t room) { if (r->room < room) { if (room > BITS_TO_BN_UNIT(BN_MAX_BITS)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_TOO_MAX); return CRYPT_BN_BITS_TOO_MAX; } BN_UINT *tmp = (BN_UINT *)BSL_SAL_Calloc(1u, room * sizeof(BN_UINT)); if (tmp == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } if (r->size > 0) { BSL_SAL_CleanseData(r->data, r->size * sizeof(BN_UINT)); } BSL_SAL_FREE(r->data); r->data = tmp; r->room = room; } else { (void)memset_s(r->data, r->room * sizeof(BN_UINT), 0, r->room * sizeof(BN_UINT)); } r->size = 0; r->sign = false; r->flag |= CRYPT_BN_FLAG_OPTIMIZER; return CRYPT_SUCCESS; } /* create a BigNum and initialize to 0 */ BN_BigNum *OptimizerGetBn(BN_Optimizer *opt, uint32_t room) { if (opt->deep == 0) { return NULL; } if ((opt->used[opt->deep - 1] + 1) < opt->used[opt->deep - 1]) { // Avoid overflow return NULL; } BN_BigNum *tmp = GetPresetBn(opt, opt->curChunk); if (tmp == NULL) { return NULL; } if (BnMake(tmp, room) != CRYPT_SUCCESS) { return NULL; } opt->used[opt->deep - 1]++; return tmp; } void OptimizerEnd(BN_Optimizer *opt) { if (opt->deep == 0) { return; } opt->deep--; uint32_t usedNum = opt->used[opt->deep]; opt->used[opt->deep] = 0; Chunk *curChunk = opt->curChunk; if (usedNum <= curChunk->occupied) { curChunk->occupied -= usedNum; return; } usedNum -= curChunk->occupied; curChunk->occupied = 0; while (usedNum >= HITLS_CRYPT_OPTIMIZER_BN_NUM) { curChunk = curChunk->next; curChunk->occupied = 0; usedNum -= HITLS_CRYPT_OPTIMIZER_BN_NUM; } if (usedNum != 0) { curChunk = curChunk->next; curChunk->occupied = HITLS_CRYPT_OPTIMIZER_BN_NUM - usedNum; } opt->curChunk = curChunk; return; } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_optimizer.c
C
unknown
5,708
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BN_OPTIMIZER_H #define BN_OPTIMIZER_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include "bn_basic.h" #ifdef __cplusplus extern "c" { #endif #define CRYPT_OPTIMIZER_MAXDEEP 10 /* * Peak memory usage of the bn process during RSA key generation. BN_NUM stands for HITLS_CRYPT_OPTIMIZER_BN_NUM. * |----------------------------+--------+--------+--------+--------+--------| * | key bits\memory(Kb)\BN_NUM | 16 | 24 | 32 | 48 | 64 | * |----------------------------+--------+--------+--------+--------+--------| * | rsa1024 | 9.0 | 9.7 | 9.7 | 10.8 | 12.0 | * | rsa2048 | 20.4 | 21.0 | 21.1 | 22.6 | 22.6 | * | rsa3072 | 37.8 | 38.3 | 38.5 | 40.0 | 40.0 | * | rsa4096 | 73.5 | 73.5 | 74.2 | 75.7 | 75.7 | * |----------------------------+--------+--------+--------+--------+--------| * * The number of chunk during RSA key generation. BN_NUM stands for HITLS_CRYPT_OPTIMIZER_BN_NUM. * |----------------------------+--------+--------+--------+--------+--------| * |key bits\chunk number\BN_NUM| 16 | 24 | 32 | 48 | 64 | * |----------------------------+--------+--------+--------+--------+--------| * | rsa1024 | 352 | 352 | 193 | 193 | 193 | * | rsa2048 | 1325 | 1035 | 745 | 745 | 455 | * | rsa3072 | 1597 | 1227 | 857 | 857 | 487 | * | rsa4096 | 2522 | 1967 | 1412 | 1412 | 857 | * |----------------------------+--------+--------+--------+--------+--------| */ #ifndef HITLS_CRYPT_OPTIMIZER_BN_NUM #define HITLS_CRYPT_OPTIMIZER_BN_NUM 32 #endif typedef struct ChunkStruct { uint32_t occupied; /** < occupied of current chunk */ BN_BigNum bigNums[HITLS_CRYPT_OPTIMIZER_BN_NUM]; /** < preset BN_BigNums */ struct ChunkStruct *prev; /** < prev optimizer node */ struct ChunkStruct *next; /** < prev optimizer node */ } Chunk; struct BnOptimizer { uint32_t deep; /* depth of stack */ uint32_t used[CRYPT_OPTIMIZER_MAXDEEP]; /* size of the used stack */ Chunk *curChunk; /** < chunk, the last point*/ void *libCtx; }; #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_BN */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_optimizer.h
C
unknown
2,911
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN_PRIME #include <stdint.h> #include "securec.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "bn_bincal.h" #include "bn_optimizer.h" /* * Differential table of adjacent prime numbers, size = 1024 * The times of trial division will affect whether the number enters the Miller-rabin test. * We consider common prime lengths: 1024, 2048, 4096, 8192 bits. * 1024 bits: we choose 128 try times, ref the paper of 'A Performant, Misuse-Resistant API for Primality Testing'. * 2048 bits: 128 try times: 1 (performance baseline) * 384 try times: +0.15 * 512 try times: +0.03 * 1024 try times: +0.16 * 4096 bits: 1024 try times: 0.04 tps * 2048 try times: 0.02 tps * 8192 bits: 1024 try times: 0.02 tps * 2048 try times: 0.02 tps */ static const uint8_t PRIME_DIFF_TABLE[1024] = { 0, 1, 2, 2, 4, 2, 4, 2, 4, 6, 2, 6, 4, 2, 4, 6, 6, 2, 6, 4, 2, 6, 4, 6, 8, 4, 2, 4, 2, 4, 14, 4, 6, 2, 10, 2, 6, 6, 4, 6, 6, 2, 10, 2, 4, 2, 12, 12, 4, 2, 4, 6, 2, 10, 6, 6, 6, 2, 6, 4, 2, 10, 14, 4, 2, 4, 14, 6, 10, 2, 4, 6, 8, 6, 6, 4, 6, 8, 4, 8, 10, 2, 10, 2, 6, 4, 6, 8, 4, 2, 4, 12, 8, 4, 8, 4, 6, 12, 2, 18, 6, 10, 6, 6, 2, 6, 10, 6, 6, 2, 6, 6, 4, 2, 12, 10, 2, 4, 6, 6, 2, 12, 4, 6, 8, 10, 8, 10, 8, 6, 6, 4, 8, 6, 4, 8, 4, 14, 10, 12, 2, 10, 2, 4, 2, 10, 14, 4, 2, 4, 14, 4, 2, 4, 20, 4, 8, 10, 8, 4, 6, 6, 14, 4, 6, 6, 8, 6, 12, 4, 6, 2, 10, 2, 6, 10, 2, 10, 2, 6, 18, 4, 2, 4, 6, 6, 8, 6, 6, 22, 2, 10, 8, 10, 6, 6, 8, 12, 4, 6, 6, 2, 6, 12, 10, 18, 2, 4, 6, 2, 6, 4, 2, 4, 12, 2, 6, 34, 6, 6, 8, 18, 10, 14, 4, 2, 4, 6, 8, 4, 2, 6, 12, 10, 2, 4, 2, 4, 6, 12, 12, 8, 12, 6, 4, 6, 8, 4, 8, 4, 14, 4, 6, 2, 4, 6, 2, 6, 10, 20, 6, 4, 2, 24, 4, 2, 10, 12, 2, 10, 8, 6, 6, 6, 18, 6, 4, 2, 12, 10, 12, 8, 16, 14, 6, 4, 2, 4, 2, 10, 12, 6, 6, 18, 2, 16, 2, 22, 6, 8, 6, 4, 2, 4, 8, 6, 10, 2, 10, 14, 10, 6, 12, 2, 4, 2, 10, 12, 2, 16, 2, 6, 4, 2, 10, 8, 18, 24, 4, 6, 8, 16, 2, 4, 8, 16, 2, 4, 8, 6, 6, 4, 12, 2, 22, 6, 2, 6, 4, 6, 14, 6, 4, 2, 6, 4, 6, 12, 6, 6, 14, 4, 6, 12, 8, 6, 4, 26, 18, 10, 8, 4, 6, 2, 6, 22, 12, 2, 16, 8, 4, 12, 14, 10, 2, 4, 8, 6, 6, 4, 2, 4, 6, 8, 4, 2, 6, 10, 2, 10, 8, 4, 14, 10, 12, 2, 6, 4, 2, 16, 14, 4, 6, 8, 6, 4, 18, 8, 10, 6, 6, 8, 10, 12, 14, 4, 6, 6, 2, 28, 2, 10, 8, 4, 14, 4, 8, 12, 6, 12, 4, 6, 20, 10, 2, 16, 26, 4, 2, 12, 6, 4, 12, 6, 8, 4, 8, 22, 2, 4, 2, 12, 28, 2, 6, 6, 6, 4, 6, 2, 12, 4, 12, 2, 10, 2, 16, 2, 16, 6, 20, 16, 8, 4, 2, 4, 2, 22, 8, 12, 6, 10, 2, 4, 6, 2, 6, 10, 2, 12, 10, 2, 10, 14, 6, 4, 6, 8, 6, 6, 16, 12, 2, 4, 14, 6, 4, 8, 10, 8, 6, 6, 22, 6, 2, 10, 14, 4, 6, 18, 2, 10, 14, 4, 2, 10, 14, 4, 8, 18, 4, 6, 2, 4, 6, 2, 12, 4, 20, 22, 12, 2, 4, 6, 6, 2, 6, 22, 2, 6, 16, 6, 12, 2, 6, 12, 16, 2, 4, 6, 14, 4, 2, 18, 24, 10, 6, 2, 10, 2, 10, 2, 10, 6, 2, 10, 2, 10, 6, 8, 30, 10, 2, 10, 8, 6, 10, 18, 6, 12, 12, 2, 18, 6, 4, 6, 6, 18, 2, 10, 14, 6, 4, 2, 4, 24, 2, 12, 6, 16, 8, 6, 6, 18, 16, 2, 4, 6, 2, 6, 6, 10, 6, 12, 12, 18, 2, 6, 4, 18, 8, 24, 4, 2, 4, 6, 2, 12, 4, 14, 30, 10, 6, 12, 14, 6, 10, 12, 2, 4, 6, 8, 6, 10, 2, 4, 14, 6, 6, 4, 6, 2, 10, 2, 16, 12, 8, 18, 4, 6, 12, 2, 6, 6, 6, 28, 6, 14, 4, 8, 10, 8, 12, 18, 4, 2, 4, 24, 12, 6, 2, 16, 6, 6, 14, 10, 14, 4, 30, 6, 6, 6, 8, 6, 4, 2, 12, 6, 4, 2, 6, 22, 6, 2, 4, 18, 2, 4, 12, 2, 6, 4, 26, 6, 6, 4, 8, 10, 32, 16, 2, 6, 4, 2, 4, 2, 10, 14, 6, 4, 8, 10, 6, 20, 4, 2, 6, 30, 4, 8, 10, 6, 6, 8, 6, 12, 4, 6, 2, 6, 4, 6, 2, 10, 2, 16, 6, 20, 4, 12, 14, 28, 6, 20, 4, 18, 8, 6, 4, 6, 14, 6, 6, 10, 2, 10, 12, 8, 10, 2, 10, 8, 12, 10, 24, 2, 4, 8, 6, 4, 8, 18, 10, 6, 6, 2, 6, 10, 12, 2, 10, 6, 6, 6, 8, 6, 10, 6, 2, 6, 6, 6, 10, 8, 24, 6, 22, 2, 18, 4, 8, 10, 30, 8, 18, 4, 2, 10, 6, 2, 6, 4, 18, 8, 12, 18, 16, 6, 2, 12, 6, 10, 2, 10, 2, 6, 10, 14, 4, 24, 2, 16, 2, 10, 2, 10, 20, 4, 2, 4, 8, 16, 6, 6, 2, 12, 16, 8, 4, 6, 30, 2, 10, 2, 6, 4, 6, 6, 8, 6, 4, 12, 6, 8, 12, 4, 14, 12, 10, 24, 6, 12, 6, 2, 22, 8, 18, 10, 6, 14, 4, 2, 6, 10, 8, 6, 4, 6, 30, 14, 10, 2, 12, 10, 2, 16, 2, 18, 24, 18, 6, 16, 18, 6, 2, 18, 4, 6, 2, 10, 8, 10, 6, 6, 8, 4, 6, 2, 10, 2, 12, 4, 6, 6, 2, 12, 4, 14, 18, 4, 6, 20, 4, 8, 6, 4, 8, 4, 14, 6, 4, 14, 12, 4, 2, 30, 4, 24, 6, 6, 12, 12, 14, 6, 4, 2, 4, 18, 6, 12, 8, 6, 4, 12, 2, 12, 30, 16, 2, 6, 22, 14, 6, 10, 12, 6, 2, 4, 8, 10, 6, 6, 24, 14 }; /* Times of trial division. */ static uint32_t DivisorsCnt(uint32_t bits) { if (bits <= 1024) { /* 1024bit */ return 128; /* 128 times check */ } return 1024; /* 1024 times check */ } // Minimum times of checking for Miller-Rabin. // The probability of errors in a check is one quarter. After 64 rounds of check, the error rate is 2 ^ - 128. static uint32_t MinChecks(uint32_t bits) { if (bits >= 2048) { /* 2048bit */ return 128; /* 128 rounds of verification */ } return 64; /* 64 rounds of verification */ } /* A BigNum mod a limb, limb < (1 << (BN_UINT_BITS >> 1)) */ static BN_UINT ModLimbHalf(const BN_BigNum *a, BN_UINT w) { BN_UINT rem = 0; uint32_t i; for (i = a->size; i > 0; i--) { MOD_HALF(rem, rem, a->data[i - 1], w); } return rem; } static int32_t LimbCheck(const BN_BigNum *bn) { uint32_t bits = BN_Bits(bn); uint32_t cnt = DivisorsCnt(bits); int32_t ret = CRYPT_SUCCESS; BN_UINT littlePrime = 2; for (uint32_t i = 0; i < cnt; i++) { // Try division. Large prime numbers do not divide small prime numbers. littlePrime += PRIME_DIFF_TABLE[i]; BN_UINT mod = ModLimbHalf(bn, littlePrime); if (mod == 0) { if (BN_IsLimb(bn, littlePrime) == false) { // small prime judgement ret = CRYPT_BN_NOR_CHECK_PRIME; } break; } } return ret; } /* The random number increases by 2 each time, and added for n times, so that it is mutually primed to all data in the prime table. */ static int32_t FillUp(BN_BigNum *rnd, const BN_UINT *mods, uint32_t modsLen) { uint32_t i; uint32_t complete = 0; uint32_t bits = BN_Bits(rnd); uint32_t cnt = modsLen; BN_UINT inc = 0; while (complete == 0) { BN_UINT littlePrime = 2; // the minimum prime = 2 for (i = 1; i < cnt; i++) { /* check */ littlePrime += PRIME_DIFF_TABLE[i]; if ((mods[i] + inc) % littlePrime == 0) { inc += 2; // inc increases by 2 each time break; } if (i == cnt - 1) { // end and exit complete = 1; } } if (inc + 2 == 0) { // inc increases by 2 each time. Check whether the inc may overflow. BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME); return CRYPT_BN_NOR_CHECK_PRIME; } } int32_t ret = BN_AddLimb(rnd, rnd, inc); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // If the random number length of a prime number is incorrect, generate a new random number. if (BN_Bits(rnd) != bits) { BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME); return CRYPT_BN_NOR_CHECK_PRIME; } return CRYPT_SUCCESS; } /* Generate random numbers that can be mutually primed with the data in the small prime number table. */ static int32_t ProbablePrime(BN_BigNum *rnd, BN_BigNum *e, uint32_t bits, bool half, BN_Optimizer *opt) { const int32_t maxCnt = 100; /* try 100 times */ int32_t tryCnt = 0; uint32_t i; int32_t ret; uint32_t cnt = DivisorsCnt(bits); ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { return ret; } BN_BigNum *mods = OptimizerGetBn(opt, cnt); if (mods == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } uint32_t top = ((half == true) ? BN_RAND_TOP_TWOBIT : BN_RAND_TOP_ONEBIT); do { tryCnt++; if (tryCnt > maxCnt) { /* If it cannot be generated after loop 100 times, a failure message is returned. */ OptimizerEnd(opt); /* In this case, the random number may be incorrect. Keep the error information. */ BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_GEN_PRIME); return CRYPT_BN_NOR_GEN_PRIME; } // 'top' can control whether to set the most two significant bits to 1. // RSA key generation usually focuses on this parameter to ensure the length of p*q. ret = BN_RandEx(opt->libCtx, rnd, bits, top, BN_RAND_BOTTOM_ONEBIT); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); OptimizerEnd(opt); return ret; } BN_UINT littlePrime = 2; // the minimum prime = 2 // Random number rnd divided by the prime number in the table of small prime numbers, modulo mods. for (i = 1; i < cnt; i++) { littlePrime += PRIME_DIFF_TABLE[i]; mods->data[i] = ModLimbHalf(rnd, littlePrime); } // Check the mods and supplement the rnd. ret = FillUp(rnd, mods->data, cnt); if (ret != CRYPT_BN_NOR_CHECK_PRIME && ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); OptimizerEnd(opt); return ret; } if (ret != CRYPT_BN_NOR_CHECK_PRIME && e != NULL) { // check if rnd-1 and e are coprime // reference: https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-5.pdf A.1.3 BN_BigNum *rnd1 = OptimizerGetBn(opt, BITS_TO_BN_UNIT(bits)); BN_BigNum *inv = OptimizerGetBn(opt, e->size); if (rnd1 == NULL || inv == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } ret = BN_SubLimb(rnd1, rnd, 1); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BN_ModInv(inv, rnd1, e, opt); } } while (ret == CRYPT_BN_NOR_CHECK_PRIME); OptimizerEnd(opt); return ret; } static int32_t BnCheck(const BN_BigNum *bnSubOne, const BN_BigNum *bnSubThree, const BN_BigNum *divisor, const BN_BigNum *rnd, const BN_Mont *mont) { if (bnSubOne == NULL || bnSubThree == NULL || divisor == NULL || rnd == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } if (mont == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } return CRYPT_SUCCESS; } static int32_t GenRnd(void *libCtx, BN_BigNum *rnd, const BN_BigNum *bnSubThree) { int32_t ret = BN_RandRangeEx(libCtx, rnd, bnSubThree); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return BN_AddLimb(rnd, rnd, 2); /* bn - 3 + 2 = bn - 1 */ } static bool SumCorrect(BN_BigNum *sum, const BN_BigNum *bnSubOne) { if (BN_IsOne(sum) || BN_Cmp(sum, bnSubOne) == 0) { (void)BN_SetLimb(sum, 1); return true; } return false; } int32_t MillerRabinCheckCore(const BN_BigNum *bn, BN_Mont *mont, BN_BigNum *rnd, const BN_BigNum *divisor, const BN_BigNum *bnSubOne, const BN_BigNum *bnSubThree, uint32_t p, uint32_t checkTimes, BN_Optimizer *opt, BN_CbCtx *cb) { uint32_t i, j; int32_t ret = CRYPT_SUCCESS; uint32_t checks = (checkTimes == 0) ? MinChecks(BN_Bits(bn)) : checkTimes; BN_BigNum *sum = rnd; for (i = 0; i < checks; i++) { // 3.1 Generate a random number rnd, 2 < rnd < n-1 ret = GenRnd(opt->libCtx, rnd, bnSubThree); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // 3.2 Calculate base = rnd^divisor mod bn ret = BN_MontExp(sum, rnd, divisor, mont, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } for (j = 0; j < p; j++) { // If sum is equal to 1 or bn-1, the modulus square result must be 1. Exit directly. if (SumCorrect(sum, bnSubOne)) { break; } // sum < bn ret = MontSqrCore(sum, sum, mont, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // Inverse negation of Miller Rabin's theorem, if equal to 1, bn is not a prime number. if (BN_IsOne(sum)) { ret = CRYPT_BN_NOR_CHECK_PRIME; return ret; } } // 3.4 Fermat's little theorem inverse negation if sum = rnd^(bn -1) != 1 mod bn, bn is not a prime number. if (!BN_IsOne(sum)) { ret = CRYPT_BN_NOR_CHECK_PRIME; return ret; } #ifdef HITLS_CRYPTO_BN_CB ret = BN_CbCtxCall(cb, 0, 0); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } #else (void)cb; #endif } return ret; } static int32_t BnSubGet(BN_BigNum *bnSubOne, BN_BigNum *bnSubThree, const BN_BigNum *bn) { int32_t ret = BN_SubLimb(bnSubOne, bn, 1); /* bn - 1 */ if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return BN_SubLimb(bnSubThree, bn, 3); /* bn - 3 */ } static int32_t PrimeLimbCheck(const BN_BigNum *bn) { if (BN_IsLimb(bn, 2) || BN_IsLimb(bn, 3)) { /* 2 and 3 directly determine that the number is a prime number. */ return CRYPT_SUCCESS; } BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME); return CRYPT_BN_NOR_CHECK_PRIME; } static uint32_t GetP(const BN_BigNum *bn) { uint32_t p = 0; while (!BN_GetBit(bn, p)) { p++; } return p; } // CRYPT_SUCCESS is returned for a prime number, // and CRYPT_BN_NOR_CHECK_PRIME is returned for a non-prime number. Other error codes are returned. static int32_t MillerRabinPrimeVerify(const BN_BigNum *bn, uint32_t checkTimes, BN_Optimizer *opt, BN_CbCtx *cb) { int32_t ret = CRYPT_SUCCESS; uint32_t p; if (PrimeLimbCheck(bn) == CRYPT_SUCCESS) { /* 2 and 3 directly determine that the number is a prime number. */ return CRYPT_SUCCESS; } if (!BN_GetBit(bn, 0)) { // even BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME); return CRYPT_BN_NOR_CHECK_PRIME; } ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { return ret; } BN_BigNum *bnSubOne = OptimizerGetBn(opt, bn->size); // bnSubOne = bn - 1 BN_BigNum *bnSubThree = OptimizerGetBn(opt, bn->size); // bnSubThree = bn - 3 BN_BigNum *divisor = OptimizerGetBn(opt, bn->size); // divisor = bnSubOne / 2^p BN_BigNum *rnd = OptimizerGetBn(opt, bn->size); // rnd to verify bn BN_Mont *mont = BN_MontCreate(bn); ret = BnCheck(bnSubOne, bnSubThree, divisor, rnd, mont); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto err; } ret = BnSubGet(bnSubOne, bnSubThree, bn); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto err; } // 1. Extract the power p of factor 2 in bnSubOne. p = GetP(bnSubOne); // 2. Number after factor 2 is extracted by bnSubOne. divisor = (bn - 1) / 2^p ret = BN_Rshift(divisor, bnSubOne, p); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto err; } ret = MillerRabinCheckCore(bn, mont, rnd, divisor, bnSubOne, bnSubThree, p, checkTimes, opt, cb); err: BN_MontDestroy(mont); OptimizerEnd(opt); return ret; } // CRYPT_SUCCESS is returned for a prime number, // and CRYPT_BN_NOR_CHECK_PRIME is returned for a non-prime number. Other error codes are returned. int32_t BN_PrimeCheck(const BN_BigNum *bn, uint32_t checkTimes, BN_Optimizer *opt, BN_CbCtx *cb) { if (bn == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret; // Check whether the value is 0 or 1. if (BN_IsZero(bn) || BN_IsOne(bn)) { return CRYPT_BN_NOR_CHECK_PRIME; } // Check whether the number is negative. if (bn->sign == 1) { BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME); return CRYPT_BN_NOR_CHECK_PRIME; } ret = LimbCheck(bn); if (ret != CRYPT_SUCCESS) { return ret; } #ifdef HITLS_CRYPTO_BN_CB ret = BN_CbCtxCall(cb, 0, 0); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } #endif return MillerRabinPrimeVerify(bn, checkTimes, opt, cb); } static int32_t GenPrimeLimb(BN_BigNum *bn, uint32_t bits, bool half, BN_Optimizer *opt) { const BN_UINT baseAll[11] = {0, 2, 4, 6, 11, 18, 31, 54, 97, 172, 309}; const BN_UINT cntAll[11] = {2, 2, 2, 5, 7, 13, 23, 43, 75, 137, 255}; const BN_UINT baseHalf[11] = {1, 3, 5, 9, 15, 24, 43, 76, 135, 242, 439}; const BN_UINT cntHalf[11] = {1, 1, 1, 2, 3, 7, 11, 21, 37, 67, 125}; const BN_UINT *base = baseAll; const BN_UINT *cnt = cntAll; if (half == true) { base = baseHalf; cnt = cntHalf; } int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_BigNum *bnCnt = OptimizerGetBn(opt, BITS_TO_BN_UNIT(bits)); BN_BigNum *bnRnd = OptimizerGetBn(opt, BITS_TO_BN_UNIT(bits)); if (bnCnt == NULL || bnRnd == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } (void)BN_SetLimb(bnCnt, cnt[bits - 2]); /* offset, the minimum bit of the interface is 2. */ ret = BN_RandRangeEx(opt->libCtx, bnRnd, bnCnt); if (ret != CRYPT_SUCCESS) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(ret); return ret; } BN_UINT rnd = bnRnd->data[0] + base[bits - 2]; /* offset, the minimum bit of the interface is 2. */ OptimizerEnd(opt); BN_UINT littlePrime = 2; for (BN_UINT i = 1; i <= rnd; i++) { littlePrime += PRIME_DIFF_TABLE[i]; } return BN_SetLimb(bn, littlePrime); } static int32_t GenCheck(BN_BigNum *bn, uint32_t bits, const BN_Optimizer *opt) { if (bn == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (bits < 2) { // The number of bits less than 2 can only be 0 or 1. The prime number cannot be generated. BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_CHECK_PRIME); return CRYPT_BN_NOR_CHECK_PRIME; } return BnExtend(bn, BITS_TO_BN_UNIT(bits)); } // If the prime number r is generated successfully, CRYPT_SUCCESS is returned. // If the prime number r fails to be generated, CRYPT_BN_NOR_GEN_PRIME is returned. Other error codes are returned. // If half is 1, the prime number whose two most significant bits are 1 is generated. int32_t BN_GenPrime(BN_BigNum *r, BN_BigNum *e, uint32_t bits, bool half, BN_Optimizer *opt, BN_CbCtx *cb) { int32_t time = 0; #ifndef HITLS_CRYPTO_BN_CB (void)cb; const int32_t maxTime = 256; /* The maximum number of cycles is 256. If no prime number is generated after the * maximum number of cycles, the operation fails. */ #endif int32_t ret = GenCheck(r, bits, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (bits < 13) { // < 13 is limited by the small prime table of 1024 size. return GenPrimeLimb(r, bits, half, opt); } ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } /* To preventing insufficient space in addition operations when the rnd is constructed. */ BN_BigNum *rnd = OptimizerGetBn(opt, BITS_TO_BN_UNIT(bits) + 1); if (rnd == NULL) { OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_OPTIMIZER_GET_FAIL); return CRYPT_BN_OPTIMIZER_GET_FAIL; } do { #ifdef HITLS_CRYPTO_BN_CB if (BN_CbCtxCall(cb, time, 0) != CRYPT_SUCCESS) { #else if (time == maxTime) { #endif OptimizerEnd(opt); BSL_ERR_PUSH_ERROR(CRYPT_BN_NOR_GEN_PRIME); return CRYPT_BN_NOR_GEN_PRIME; } // Generate a random number bn that may be a prime. ret = ProbablePrime(rnd, e, bits, half, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); OptimizerEnd(opt); return ret; } ret = MillerRabinPrimeVerify(rnd, 0, opt, cb); time++; } while (ret != CRYPT_SUCCESS); OptimizerEnd(opt); return BN_Copy(r, rnd); } #endif /* HITLS_CRYPTO_BN_PRIME */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_prime.c
C
unknown
22,286
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN_RAND #include <stdint.h> #include "securec.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "bn_basic.h" #include "bn_bincal.h" #include "crypt_util_rand.h" static int32_t RandGenerate(void *libCtx, BN_BigNum *r, uint32_t bits) { int32_t ret; uint32_t room = BITS_TO_BN_UNIT(bits); BN_UINT mask; // Maxbits = (1 << 29) --> MaxBytes = (1 << 26), hence BN_BITS_TO_BYTES(bits) will not exceed the upper limit. uint32_t byteSize = BN_BITS_TO_BYTES(bits); uint8_t *buf = BSL_SAL_Malloc(byteSize); if (buf == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ret = CRYPT_RandEx(libCtx, buf, byteSize); if (ret == CRYPT_NO_REGIST_RAND) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(CRYPT_BN_RAND_GEN_FAIL); ret = CRYPT_BN_RAND_GEN_FAIL; goto ERR; } ret = BN_Bin2Bn(r, buf, byteSize); BSL_SAL_CleanseData(buf, byteSize); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } mask = (BN_UINT)(-1) >> ((BN_UINT_BITS - bits % BN_UINT_BITS) % BN_UINT_BITS); r->data[room - 1] &= mask; r->size = BinFixSize(r->data, room); ERR: BSL_SAL_FREE(buf); return ret; } static int32_t CheckTopAndBottom(uint32_t bits, uint32_t top, uint32_t bottom) { if (top > BN_RAND_TOP_TWOBIT) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_RAND_TOP_BOTTOM); return CRYPT_BN_ERR_RAND_TOP_BOTTOM; } if (bottom > BN_RAND_BOTTOM_TWOBIT) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_RAND_TOP_BOTTOM); return CRYPT_BN_ERR_RAND_TOP_BOTTOM; } if (top > bits || bottom > bits) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_RAND_BITS_NOT_ENOUGH); return CRYPT_BN_ERR_RAND_BITS_NOT_ENOUGH; } return CRYPT_SUCCESS; } int32_t BN_Rand(BN_BigNum *r, uint32_t bits, uint32_t top, uint32_t bottom) { return BN_RandEx(NULL, r, bits, top, bottom); } int32_t BN_RandEx(void *libCtx, BN_BigNum *r, uint32_t bits, uint32_t top, uint32_t bottom) { if (r == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = CheckTopAndBottom(bits, top, bottom); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (bits == 0) { return BN_Zeroize(r); } if (bits > BN_MAX_BITS) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_TOO_MAX); return CRYPT_BN_BITS_TOO_MAX; } ret = BnExtend(r, BITS_TO_BN_UNIT(bits)); if (ret != CRYPT_SUCCESS) { return ret; } ret = RandGenerate(libCtx, r, bits); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } r->data[0] |= (bottom == BN_RAND_BOTTOM_TWOBIT) ? 0x3 : (BN_UINT)bottom; // CheckTopAndBottom ensure that bottom>0 if (top == BN_RAND_TOP_ONEBIT) { (void)BN_SetBit(r, bits - 1); } else if (top == BN_RAND_TOP_TWOBIT) { (void)BN_SetBit(r, bits - 1); (void)BN_SetBit(r, bits - 2); /* the most significant 2 bits are 1 */ } r->size = BinFixSize(r->data, r->room); return ret; } static int32_t InputCheck(BN_BigNum *r, const BN_BigNum *p) { if (r == NULL || p == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (BN_IsZero(p)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_RAND_ZERO); return CRYPT_BN_ERR_RAND_ZERO; } if (p->sign == true) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_RAND_NEGATIVE); return CRYPT_BN_ERR_RAND_NEGATIVE; } return BnExtend(r, p->size); } int32_t BN_RandRange(BN_BigNum *r, const BN_BigNum *p) { return BN_RandRangeEx(NULL, r, p); } int32_t BN_RandRangeEx(void *libCtx, BN_BigNum *r, const BN_BigNum *p) { const int32_t maxCnt = 100; /* try 100 times */ int32_t tryCnt = 0; int32_t ret; ret = InputCheck(r, p); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BN_Zeroize(r); if (ret != CRYPT_SUCCESS) { return ret; } if (BN_IsOne(p)) { return CRYPT_SUCCESS; } uint32_t bits = BN_Bits(p); do { tryCnt++; if (tryCnt > maxCnt) { /* The success rate is more than 50%. */ /* Return a failure if failed to generated after try 100 times */ BSL_ERR_PUSH_ERROR(CRYPT_BN_RAND_GEN_FAIL); return CRYPT_BN_RAND_GEN_FAIL; } ret = RandGenerate(libCtx, r, bits); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } while (BinCmp(r->data, r->size, p->data, p->size) >= 0); return ret; } #endif /* HITLS_CRYPTO_BN_RAND */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_rand.c
C
unknown
5,406
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_ECC #include <stdint.h> #include <stdbool.h> #include "securec.h" #include "bsl_err_internal.h" #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "bn_optimizer.h" #include "crypt_bn.h" static uint32_t GetExp(const BN_BigNum *bn) { uint32_t s = 0; while (!BN_GetBit(bn, s)) { s++; } return s; } // p does not perform prime number check, but performs parity check. static int32_t CheckParam(const BN_BigNum *a, const BN_BigNum *p) { if (BN_IsZero(p) || BN_IsOne(p)) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_SQRT_PARA); return CRYPT_BN_ERR_SQRT_PARA; } if (!BN_GetBit(p, 0)) { // p must be odd prime BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_SQRT_PARA); return CRYPT_BN_ERR_SQRT_PARA; } if (p->sign || a->sign) { // p、a must be positive BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_SQRT_PARA); return CRYPT_BN_ERR_SQRT_PARA; } if (BN_Cmp(p, a) <= 0) { BSL_ERR_PUSH_ERROR(CRYPT_BN_ERR_SQRT_PARA); return CRYPT_BN_ERR_SQRT_PARA; } return CRYPT_SUCCESS; } // r = +- a^((p + 1)/4) static int32_t CalculationRoot(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *p, BN_Mont *mont, BN_Optimizer *opt) { int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_BigNum *temp = OptimizerGetBn(opt, p->size); if (temp == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ret = CRYPT_MEM_ALLOC_FAIL; goto ERR; } GOTO_ERR_IF_EX(BN_AddLimb(temp, p, 1), ret); // p + 1 GOTO_ERR_IF_EX(BN_Rshift(temp, temp, 2), ret); // (p + 1) / 4 = (p + 1) >> 2 GOTO_ERR_IF(BN_MontExp(r, a, temp, mont, opt), ret); ERR: OptimizerEnd(opt); return ret; } static int32_t LegendreFastTempDataCheck(const BN_BigNum *a, const BN_BigNum *pp) { if (a == NULL || pp == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } return CRYPT_SUCCESS; } int32_t LegendreFast(BN_BigNum *z, const BN_BigNum *p, int32_t *legendre, BN_Optimizer *opt) { int32_t l = 1; BN_BigNum *temp = NULL; int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_BigNum *a = OptimizerGetBn(opt, p->size); // The variable has been checked for NULL in BN_Copy. BN_BigNum *pp = OptimizerGetBn(opt, p->size); GOTO_ERR_IF(LegendreFastTempDataCheck(a, pp), ret); if (BN_IsOne(z)) { *legendre = 1; goto ERR; } if (BN_IsZero(z)) { *legendre = 0; goto ERR; } GOTO_ERR_IF_EX(BN_Copy(a, z), ret); GOTO_ERR_IF_EX(BN_Copy(pp, p), ret); while (true) { if (BN_IsZero(a)) { *legendre = BN_IsOne(pp) ? l : 0; break; } // Theorem: p is an odd prime number, a and b are numbers that are not divisible by p. (a|p)(b|p) = (ab|p) // a = aa * 2^exp // (a|pp) = (2|pp)^exp * (aa|pp) // If exp is an even number, (a|pp) = (aa|pp) uint32_t exp = GetExp(a); GOTO_ERR_IF_EX(BN_Rshift(a, a, exp), ret); if ((exp & 1) != 0) { // pp = +- 1 mod 8, 2 is its quadratic remainder. pp = +-3 mod 8, 2 is its non-quadric remainder. if ((pp->data[0] & 1) != 0) { // pp->data[0] % 8 = pp->data[0] & 7 // pp = +- 1 mod 8 = 7 or 1 mod l = ((pp->data[0] & 7) == 1 || (pp->data[0] & 7) == 7) ? l : -l; } else { l = 0; } } // pp->data[0] % 4 = pp->data[0] & 3 // K(a|pp) = K(pp|a) * (-1)^((a-1)*(pp-1)/4) // (a-1)*(pp-1)/4 is an even number only when at least one of A and P mod 4 = 1; // if both A and P mod 4 = 3, (a-1)*(pp-1)/4 is an odd number. if (((pp->data[0] & 3) == 3) && ((a->data[0] & 3) == 3)) { l = -l; } // K(pp|a) = K(pp%a|a), swap(a,pp) GOTO_ERR_IF_EX(BN_Div(NULL, pp, pp, a, opt), ret); temp = a; a = pp; pp = temp; } ret = CRYPT_SUCCESS; ERR: OptimizerEnd(opt); return ret; } // Find z so that legendre(z / p) = z^((p-1)/2) mod p != 1 static int32_t GetLegendreZ(BN_BigNum *z, const BN_BigNum *p, BN_Optimizer *opt) { uint32_t maxCnt = 50; // A random number can be generated cyclically for a maximum of 50 times. int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } int32_t legendre; BN_BigNum *exp = OptimizerGetBn(opt, p->size); // exp = (p - 1) / 2 if (exp == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ret = CRYPT_MEM_ALLOC_FAIL; goto ERR; } GOTO_ERR_IF_EX(BN_SubLimb(exp, p, 1), ret); GOTO_ERR_IF_EX(BN_Rshift(exp, exp, 1), ret); while (maxCnt > 0) { GOTO_ERR_IF_EX(BN_RandRangeEx(opt->libCtx, z, p), ret); maxCnt--; if (BN_IsZero(z)) { continue; } GOTO_ERR_IF_EX(LegendreFast(z, p, &legendre, opt), ret); if (legendre == -1) { ret = CRYPT_SUCCESS; goto ERR; } } ret = CRYPT_BN_ERR_LEGENDE_DATA; ERR: OptimizerEnd(opt); return ret; } static int32_t SetParaR(BN_BigNum *r, BN_BigNum *q, const BN_BigNum *a, BN_Mont *mont, BN_Optimizer *opt) { int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_BigNum *temp = OptimizerGetBn(opt, q->size); if (temp == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ret = CRYPT_MEM_ALLOC_FAIL; goto ERR; } GOTO_ERR_IF_EX(BN_AddLimb(temp, q, 1), ret); // q + 1 GOTO_ERR_IF_EX(BN_Rshift(temp, temp, 1), ret); // (p + 1) / 2 GOTO_ERR_IF(BN_MontExp(r, a, temp, mont, opt), ret); // r = a^((q+1)/2) mod p ERR: OptimizerEnd(opt); return ret; } static int32_t TonelliShanksCalculation(BN_BigNum *r, BN_BigNum *c, BN_BigNum *t, uint32_t s, const BN_BigNum *p, BN_Optimizer *opt) { uint32_t m = s; uint32_t i, j; int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_BigNum *b = OptimizerGetBn(opt, p->size); BN_BigNum *tempT = OptimizerGetBn(opt, p->size); if (b == NULL || tempT == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ret = CRYPT_MEM_ALLOC_FAIL; goto ERR; } while (!BN_IsOne(t)) { // Find an i (0 < i < s) so that t^(2^i) = 1 i = 1; // repeat modulus square GOTO_ERR_IF_EX(BN_ModSqr(tempT, t, p, opt), ret); while (!BN_IsOne(tempT)) { i++; if (i >= m) { ret = CRYPT_BN_ERR_NO_SQUARE_ROOT; BSL_ERR_PUSH_ERROR(ret); goto ERR; } GOTO_ERR_IF_EX(BN_ModSqr(tempT, tempT, p, opt), ret); } // b = c^(2^(m-i-1)), if m-i-1 == 0, b = c GOTO_ERR_IF_EX(BN_Copy(b, c), ret); for (j = m - i - 1; j > 0; j--) { GOTO_ERR_IF_EX(BN_ModSqr(b, b, p, opt), ret); } GOTO_ERR_IF_EX(BN_ModMul(r, r, b, p, opt), ret); // r = r * b GOTO_ERR_IF_EX(BN_ModSqr(c, b, p, opt), ret); // c = b*b GOTO_ERR_IF_EX(BN_ModMul(t, t, c, p, opt), ret); // t = t * b * b = t * c m = i; } ret = CRYPT_SUCCESS; ERR: OptimizerEnd(opt); return ret; } static int32_t SqrtVerify( BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *p, BN_Optimizer *opt) { int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_BigNum *square = OptimizerGetBn(opt, p->size); if (square == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); ret = CRYPT_MEM_ALLOC_FAIL; goto ERR; } GOTO_ERR_IF_EX(BN_ModSqr(square, r, p, opt), ret); if (BN_Cmp(square, a) != 0) { ret = CRYPT_BN_ERR_NO_SQUARE_ROOT; BSL_ERR_PUSH_ERROR(ret); goto ERR; } ERR: OptimizerEnd(opt); return ret; } static int32_t BN_ModSqrtTempDataCheck(const BN_BigNum *pSubOne, const BN_BigNum *q, const BN_BigNum *z, const BN_BigNum *c, const BN_BigNum *t) { if (pSubOne == NULL || q == NULL || z == NULL || c == NULL || t == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } return CRYPT_SUCCESS; } /* 1. Input parameters a and p. p is an odd prime number, and a is an integer (0 <= a <= p-1) 2. For P-1 processing, let p-1 = q * 2^s 3. If s=1,r = a^((p + 1)/4) 4. Randomly select z (1<= z <= p-1) so that the Legendre symbol of z to p equals -1. (z, p) = 1, (z/p) = a^((p-1)/2) 5. Setting c = z^q, r = a^((q+1)/2), t = a^q, m = s 6. Circulation 1) If t = 1, return r. 2) Find an i (0 < i < m) so that t^(2^i) = 1. 3) b = c^(2^(m-i-1)), r = r * b, t = t*b*b, c = b*b, m = i 7. Verification */ int32_t BN_ModSqrt(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *p, BN_Optimizer *opt) { if (r == NULL || a == NULL || p == NULL || opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = OptimizerStart(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t s = 0; BN_Mont *mont = NULL; BN_BigNum *pSubOne = OptimizerGetBn(opt, p->size); BN_BigNum *q = OptimizerGetBn(opt, p->size); BN_BigNum *z = OptimizerGetBn(opt, p->size); BN_BigNum *c = OptimizerGetBn(opt, p->size); BN_BigNum *t = OptimizerGetBn(opt, p->size); GOTO_ERR_IF(BN_ModSqrtTempDataCheck(pSubOne, q, z, c, t), ret); GOTO_ERR_IF_EX(CheckParam(a, p), ret); if (BN_IsZero(a) || BN_IsOne(a)) { GOTO_ERR_IF_EX(BN_Copy(r, a), ret); goto VERIFY; } mont = BN_MontCreate(p); if (mont == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); goto ERR; } GOTO_ERR_IF_EX(BN_SubLimb(pSubOne, p, 1), ret); s = GetExp(pSubOne); // Obtains the power s of factor 2 in p-1. GOTO_ERR_IF_EX(BN_Rshift(q, pSubOne, s), ret); // p - 1 = q * 2^s if (s == 1) { // s==1,r = +- n^((p + 1)/4) GOTO_ERR_IF_EX(CalculationRoot(r, a, p, mont, opt), ret); goto VERIFY; } // Randomly select z(1<= z <= p-1), so that the Legendre symbol of z to p equals -1. (z, p) = 1, (z/p) = a^((p-1)/2) GOTO_ERR_IF(GetLegendreZ(z, p, opt), ret); GOTO_ERR_IF(BN_MontExp(c, z, q, mont, opt), ret); // c = z^q mod p GOTO_ERR_IF(BN_MontExp(t, a, q, mont, opt), ret); // t = a^q mod p GOTO_ERR_IF_EX(SetParaR(r, q, a, mont, opt), ret); // r = a^((q+1)/2) mod p // Circulation // 1) If t = 1, return r. // 2) Find an i (0 < i < m) so that t^(2^i) = 1 // 3) b = c^(2^(m-i-1)), r = r * b, t = t*b*b, c = b*b, m = i GOTO_ERR_IF_EX(TonelliShanksCalculation(r, c, t, s, p, opt), ret); VERIFY: GOTO_ERR_IF_EX(SqrtVerify(r, a, p, opt), ret); ERR: OptimizerEnd(opt); BN_MontDestroy(mont); return ret; } #endif /* HITLS_CRYPTO_ECC */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_sqrt.c
C
unknown
11,863
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include "securec.h" #include "bn_bincal.h" #include "crypt_errno.h" #include "bsl_err_internal.h" /* the user should guaranteed a.size >= b.size */ int32_t USub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b) { uint32_t maxSize = a->size; uint32_t minSize = b->size; // Ensure that r is sufficient. int32_t ret = BnExtend(r, maxSize); if (ret != CRYPT_SUCCESS) { return ret; } BN_UINT *rr = r->data; const BN_UINT *aa = a->data; const BN_UINT *bb = b->data; BN_UINT borrow = BinSub(rr, aa, bb, minSize); rr += minSize; aa += minSize; uint32_t diff = maxSize - minSize; while (diff > 0) { BN_UINT t = *aa; aa++; *rr = t - borrow; rr++; borrow = t < borrow; diff--; } while (maxSize != 0) { rr--; if (*rr != 0) { break; } maxSize--; } r->size = maxSize; return CRYPT_SUCCESS; } void UDec(BN_BigNum *r, const BN_BigNum *a, BN_UINT w) { uint32_t size = a->size; // the user should guaranteed size > 1, the return value must be 0 thus the return value is ignored (void)BinDec(r->data, a->data, size, w); r->size = BinFixSize(r->data, size); } int32_t UAdd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b) { const BN_BigNum *max = (a->size < b->size) ? b : a; const BN_BigNum *min = (a->size < b->size) ? a : b; uint32_t maxSize = max->size; uint32_t minSize = min->size; // Ensure that r is sufficient to carry the sum. int32_t ret = BnExtend(r, maxSize + 1); if (ret != CRYPT_SUCCESS) { return ret; } r->size = maxSize; BN_UINT *rr = r->data; const BN_UINT *aa = max->data; const BN_UINT *bb = min->data; BN_UINT carry = BinAdd(rr, aa, bb, minSize); rr += minSize; aa += minSize; uint32_t diff = maxSize - minSize; while (diff > 0) { ADD_AB(carry, *rr, *aa, carry); aa++, rr++, diff--; } if (carry != 0) { *rr = carry; r->size += 1; } return CRYPT_SUCCESS; } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_ucal.c
C
unknown
2,714
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef BN_UCAL_H #define BN_UCAL_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include "bn_basic.h" #ifdef __cplusplus extern "C" { #endif /* unsigned BigNum subtraction, caution: The input parameter validity must be ensured during external invoking. */ int32_t USub(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b); /* unsigned BigNum add fraction, caution: The input parameter validity must be ensured during external invoking. */ void UDec(BN_BigNum *r, const BN_BigNum *a, BN_UINT w); /* unsigned BigNum addition, caution: The input parameter validity must be ensured during external invoking. */ int32_t UAdd(BN_BigNum *r, const BN_BigNum *a, const BN_BigNum *b); #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_BN */ #endif
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_ucal.h
C
unknown
1,296
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include "securec.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "bn_basic.h" #include "bn_bincal.h" #include "bsl_sal.h" int32_t BN_Bin2Bn(BN_BigNum *r, const uint8_t *bin, uint32_t binLen) { if (r == NULL || bin == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } (void)BN_Zeroize(r); uint32_t zeroNum = 0; for (; zeroNum < binLen; zeroNum++) { if (bin[zeroNum] != 0) { break; } } if (zeroNum == binLen) { // All data is 0. return CRYPT_SUCCESS; } const uint8_t *base = bin + zeroNum; uint32_t left = binLen - zeroNum; uint32_t needRooms = (left % sizeof(BN_UINT) == 0) ? left / sizeof(BN_UINT) : (left / sizeof(BN_UINT)) + 1; int32_t ret = BnExtend(r, needRooms); if (ret != CRYPT_SUCCESS) { return ret; } uint32_t offset = 0; while (left > 0) { BN_UINT num = 0; // single number uint32_t m = (left >= sizeof(BN_UINT)) ? sizeof(BN_UINT) : left; uint32_t i; for (i = m; i > 0; i--) { // big-endian num = (num << 8) | base[left - i]; // 8: indicates the number of bits in a byte. } r->data[offset++] = num; left -= m; } r->size = BinFixSize(r->data, offset); return CRYPT_SUCCESS; } /* convert BN_UINT to bin */ static inline void Limb2Bin(uint8_t *bin, BN_UINT num) { // convert BN_UINT to bin: buff[0] is the most significant bit. uint32_t i; for (i = 0; i < sizeof(BN_UINT); i++) { // big-endian bin[sizeof(BN_UINT) - i - 1] = (uint8_t)(num >> (8 * i)); // 8: indicates the number of bits in a byte. } } int32_t BN_Bn2Bin(const BN_BigNum *a, uint8_t *bin, uint32_t *binLen) { if (a == NULL || bin == NULL || binLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint32_t bytes = BN_Bytes(a); bytes = (bytes == 0) ? 1 : bytes; // If bytes is 0, 1 byte 0 data needs to be output. if (*binLen < bytes) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BUFF_LEN_NOT_ENOUGH); return CRYPT_BN_BUFF_LEN_NOT_ENOUGH; } int32_t ret = BN_Bn2BinFixZero(a, bin, bytes); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *binLen = bytes; return ret; } void BN_FixSize(BN_BigNum *a) { if (a == NULL) { return; } a->size = BinFixSize(a->data, a->size); } int32_t BN_Extend(BN_BigNum *a, uint32_t words) { return BnExtend(a, words); } // Padded 0s before bin to obtain the output data whose length is binLen. int32_t BN_Bn2BinFixZero(const BN_BigNum *a, uint8_t *bin, uint32_t binLen) { if (a == NULL || bin == NULL || binLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint32_t bytes = BN_Bytes(a); if (binLen < bytes) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BUFF_LEN_NOT_ENOUGH); return CRYPT_BN_BUFF_LEN_NOT_ENOUGH; } uint32_t fixLen = binLen - bytes; uint8_t *base = bin + fixLen; (void)memset_s(bin, binLen, 0, fixLen); if (bytes == 0) { return CRYPT_SUCCESS; } uint32_t index = a->size - 1; uint32_t left = bytes % sizeof(BN_UINT); // High-order non-integrated data uint32_t offset = 0; while (left != 0) { base[offset] = (uint8_t)((a->data[index] >> (8 * (left - 1))) & 0xFF); // 1byte = 8bit left--; offset++; } if (offset != 0) { index--; } uint32_t num = bytes / sizeof(BN_UINT); // High-order non-integrated data // Cyclically parse the entire data block. for (uint32_t i = 0; i < num; i++) { Limb2Bin(base + offset, a->data[index]); index--; offset += sizeof(BN_UINT); } return CRYPT_SUCCESS; } #if defined(HITLS_CRYPTO_CURVE_SM2_ASM) || \ ((defined(HITLS_CRYPTO_CURVE_NISTP521) || defined(HITLS_CRYPTO_CURVE_NISTP384_ASM)) && \ defined(HITLS_CRYPTO_NIST_USE_ACCEL)) /* Convert BigNum to a 64-bit array in little-endian order. */ int32_t BN_Bn2U64Array(const BN_BigNum *a, uint64_t *array, uint32_t *len) { // Number of BN_UINTs that can be accommodated const uint64_t capacity = ((uint64_t)(*len)) * (sizeof(uint64_t) / sizeof(BN_UINT)); if (a->size > capacity || *len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_BN_SPACE_NOT_ENOUGH); return CRYPT_BN_SPACE_NOT_ENOUGH; } if (BN_IsZero(a)) { *len = 1; array[0] = 0; return CRYPT_SUCCESS; } // BN_UINT is 64-bit or 32-bit. Select one during compilation. if (sizeof(BN_UINT) == sizeof(uint64_t)) { uint32_t i = 0; for (; i < a->size; i++) { array[i] = a->data[i]; } *len = i; } if (sizeof(BN_UINT) == sizeof(uint32_t)) { uint32_t i = 0; uint32_t j = 0; for (; i < a->size - 1; i += 2) { // processes 2 BN_UINT each time. Here, a->size >= 1 array[j] = a->data[i]; array[j] |= ((uint64_t)a->data[i + 1]) << 32; // in the upper 32 bits j++; } // When a->size is an odd number, process the tail. if (i < a->size) { array[j++] = a->data[i]; } *len = j; } return CRYPT_SUCCESS; } /* Convert a 64-bit array in little-endian order to a BigNum. */ int32_t BN_U64Array2Bn(BN_BigNum *r, const uint64_t *array, uint32_t len) { const uint64_t needRoom = ((uint64_t)len) * sizeof(uint64_t) / sizeof(BN_UINT); if (r == NULL || array == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (needRoom > UINT32_MAX) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BITS_TOO_MAX); return CRYPT_BN_BITS_TOO_MAX; } int32_t ret = BnExtend(r, (uint32_t)needRoom); if (ret != CRYPT_SUCCESS) { return ret; } (void)BN_Zeroize(r); // BN_UINT is 64-bit or 32-bit. Select one during compilation. if (sizeof(BN_UINT) == sizeof(uint64_t)) { for (uint32_t i = 0; i < needRoom; i++) { r->data[i] = array[i]; } } if (sizeof(BN_UINT) == sizeof(uint32_t)) { for (uint64_t i = 0; i < len; i++) { r->data[i * 2] = (BN_UINT)array[i]; // uint64_t is twice the width of uint32_t. // obtain the upper 32 bits, uint64_t is twice the width of uint32_t. r->data[i * 2 + 1] = (BN_UINT)(array[i] >> 32); } } // can be forcibly converted to 32 bits because needRoom <= r->room r->size = BinFixSize(r->data, (uint32_t)needRoom); return CRYPT_SUCCESS; } #endif #if defined(HITLS_CRYPTO_CURVE_SM2_ASM) || (defined(HITLS_CRYPTO_CURVE_NISTP256_ASM) && \ defined(HITLS_CRYPTO_NIST_USE_ACCEL)) int32_t BN_BN2Array(const BN_BigNum *src, BN_UINT *dst, uint32_t size) { if (size < src->size) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BUFF_LEN_NOT_ENOUGH); return CRYPT_BN_BUFF_LEN_NOT_ENOUGH; } (void)memset_s(dst, size * sizeof(BN_UINT), 0, size * sizeof(BN_UINT)); for (uint32_t i = 0; i < src->size; i++) { dst[i] = src->data[i]; } return CRYPT_SUCCESS; } int32_t BN_Array2BN(BN_BigNum *dst, const BN_UINT *src, const uint32_t size) { int32_t ret = BnExtend(dst, size); if (ret != CRYPT_SUCCESS) { return ret; } // No error code is returned because the src has been checked NULL. (void)BN_Zeroize(dst); for (uint32_t i = 0; i < size; i++) { dst->data[i] = src[i]; } dst->size = BinFixSize(dst->data, size); return CRYPT_SUCCESS; } #endif #ifdef HITLS_CRYPTO_BN_STR_CONV static const char HEX_MAP[] = "0123456789ABCDEF"; // Hexadecimal value corresponding to 0-15 #define BITS_OF_NUM 4 #define BITS_OF_BYTE 8 static bool IsXdigit(const char str, bool isHex) { if ((str >= '0') && (str <= '9')) { return true; } if (isHex) { if ((str >= 'A') && (str <= 'F')) { return true; } if ((str >= 'a') && (str <= 'f')) { return true; } } return false; } static unsigned char StrToHex(char str) { if ((str >= '0') && (str <= '9')) { return (unsigned char)(str - '0'); } if ((str >= 'A') && (str <= 'F')) { return (unsigned char)(str - 'A' + 10); // Hexadecimal. A~F offset 10 } if ((str >= 'a') && (str <= 'f')) { return (unsigned char)(str - 'a' + 10); // Hexadecimal. a~f offset 10 } return 0x00; // Unexpected character string, which is processed as 0. } static int32_t CheckInputStr(int32_t *outLen, const char *str, int32_t *negtive, bool isHex) { int32_t len = 0; int32_t strMax = BN_MAX_BITS / BITS_OF_NUM; // BigNum storage limit: 2^29 bits const char *inputStr = str; if (str[0] == '\0') { BSL_ERR_PUSH_ERROR(CRYPT_BN_CONVERT_INPUT_INVALID); return CRYPT_BN_CONVERT_INPUT_INVALID; } if (str[0] == '-') { *negtive = 1; inputStr++; } int32_t initStrLen = strlen(inputStr); if (initStrLen == 0 || initStrLen > strMax) { BSL_ERR_PUSH_ERROR(CRYPT_BN_CONVERT_INPUT_INVALID); return CRYPT_BN_CONVERT_INPUT_INVALID; } while (len < initStrLen) { if (!IsXdigit(inputStr[len++], isHex)) { // requires that the entire content of a character string must be valid BSL_ERR_PUSH_ERROR(CRYPT_BN_CONVERT_INPUT_INVALID); return CRYPT_BN_CONVERT_INPUT_INVALID; } } *outLen = len; return CRYPT_SUCCESS; } static int32_t OutputCheck(BN_BigNum **r, int32_t num) { uint32_t needBits = (uint32_t)num * BITS_OF_NUM; if (*r == NULL) { *r = BN_Create(needBits); if (*r == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } } else { int32_t ret = BnExtend(*r, BITS_TO_BN_UNIT(needBits)); if (ret != CRYPT_SUCCESS) { return ret; } (void)BN_Zeroize(*r); } return CRYPT_SUCCESS; } int32_t BN_Hex2Bn(BN_BigNum **r, const char *str) { int32_t ret; int32_t len; int32_t negtive = 0; if (r == NULL || str == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const char *inputStr = str; ret = CheckInputStr(&len, inputStr, &negtive, true); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = OutputCheck(r, len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_UINT *p = (*r)->data; if (negtive != 0) { inputStr++; } int32_t unitBytes; uint32_t tmpval = 0; uint32_t size = 0; // Record the size that r will use. int32_t bytes = sizeof(BN_UINT); BN_UINT unitValue; while (len > 0) { unitBytes = (bytes * 2 <= len) ? bytes * 2 : len; // Prevents the number of char left being less than bytes *2 unitValue = 0; for (; unitBytes > 0; unitBytes--) { // interface ensures that all characters are valid at the begining tmpval = StrToHex(inputStr[len - unitBytes]); unitValue = (unitValue << 4) | tmpval; // The upper bits are shifted rightwards by 4 bits each time. } p[size++] = unitValue; len -= bytes * 2; // Length of the character stream processed each time = Number of bytes x 2 } (*r)->size = BinFixSize(p, size); if (!BN_IsZero(*r)) { (*r)->sign = negtive; } return CRYPT_SUCCESS; } char *BN_Bn2Hex(const BN_BigNum *a) { uint32_t bytes = sizeof(BN_UINT); if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return NULL; } // output character stream = Number of bytes x 2 + minus sign + terminator char *ret = (char *)BSL_SAL_Malloc(a->size * bytes * 2 + 2); if (ret == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } char *p = ret; if (BN_IsZero(a)) { *p++ = '0'; *p++ = '\0'; return ret; } if (a->sign) { *p++ = '-'; } bool leadingZeros = true; for (int32_t i = a->size - 1; i >= 0; i--) { // processes data in a group of 8 bits for (int32_t j = (int32_t)(bytes * BITS_OF_BYTE - BITS_OF_BYTE); j >= 0; j -= 8) { uint32_t chars = (uint32_t)((a->data[i] >> (uint32_t)j) & 0xFF); // Take the last eight bits. if (leadingZeros && (chars == 0)) { continue; } *p++ = HEX_MAP[chars >> 4]; // Higher 4 bits *p++ = HEX_MAP[chars & 0x0F]; // Lower 4 bits leadingZeros = false; } } *p = '\0'; return ret; } static int32_t CalBnData(BN_BigNum **r, int32_t num, const char *inputStr) { int32_t ret = CRYPT_INVALID_ARG; int32_t optTimes; int32_t len = num; const char *p = inputStr; BN_UINT unitValue = 0; /* * Processes decimal strings in groups of BN_DEC_LEN. * If the length of a string is not a multiple of BN_DEC_LEN, then in the first round of string processing, handle according to the actual length of less than BN_DEC_LEN */ optTimes = (len % BN_DEC_LEN == 0) ? 0 : (BN_DEC_LEN - len % BN_DEC_LEN); while (len > 0) { // keep the upper limit of each round of traversal as BN_DEC_LEN for (; optTimes < BN_DEC_LEN; optTimes++, len--) { unitValue *= 10; // A decimal number is multiplied by 10 and then added. unitValue += *p - '0'; p++; } ret = BN_MulLimb(*r, *r, BN_DEC_VAL); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ret = BN_AddLimb(*r, *r, unitValue); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } unitValue = 0; optTimes = 0; } ERR: return ret; } int32_t BN_Dec2Bn(BN_BigNum **r, const char *str) { int32_t ret; int32_t num; int32_t negtive = 0; if (r == NULL || str == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const char *inputStr = str; ret = CheckInputStr(&num, inputStr, &negtive, false); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = OutputCheck(r, num); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (negtive != 0) { inputStr++; } ret = CalBnData(r, num, inputStr); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (!BN_IsZero(*r)) { (*r)->sign = negtive; } return ret; } static int32_t CalDecStr(const BN_BigNum *a, BN_UINT *bnInit, uint32_t unitNum, uint32_t *step) { int32_t ret = CRYPT_INVALID_ARG; BN_UINT *valNow = bnInit; uint32_t index = 0; BN_BigNum *bnDup = BN_Dup(a); if (bnDup == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; goto ERR; } while (!BN_IsZero(bnDup)) { BN_UINT rem; // index records the amount of BN_UINT offset, cannot exceed the maximum value unitNum if (index == unitNum) { ret = CRYPT_SECUREC_FAIL; goto ERR; } ret = BN_DivLimb(bnDup, &rem, bnDup, BN_DEC_VAL); if (ret != CRYPT_SUCCESS) { goto ERR; } valNow[index++] = rem; } (*step) = index - 1; ERR: BN_Destroy(bnDup); return ret; } static int32_t NumToStr(char *output, uint32_t *restLen, BN_UINT valNow, bool isNeedPad, uint32_t *printNum) { BN_UINT num = valNow; char *target = output; uint32_t len = 0; do { if (*restLen < len + 1) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BUFF_LEN_NOT_ENOUGH); return CRYPT_BN_BUFF_LEN_NOT_ENOUGH; } // The ASCII code of 0 to 9 is [48, 57] target[len++] = num % 10 + 48; // Take last num by mod 10, and convet to 'char'. num /= 10; // for taken the last digit by dividing 10 } while (num != 0); if (isNeedPad) { if (*restLen < BN_DEC_LEN) { BSL_ERR_PUSH_ERROR(CRYPT_BN_BUFF_LEN_NOT_ENOUGH); return CRYPT_BN_BUFF_LEN_NOT_ENOUGH; } while (len < BN_DEC_LEN) { target[len++] = '0'; } } // Symmetrically swapped values at both ends, needs len / 2 times. for (uint32_t j = 0; j < len / 2; j++) { char t = target[j]; target[j] = target[len - 1 - j]; target[len - 1 - j] = t; } *restLen -= len; *printNum = len; return CRYPT_SUCCESS; } static int32_t FmtDecOutput(char *output, uint32_t outLen, const BN_UINT *bnInit, uint32_t steps) { uint32_t cpyNum = 0; char *outputPtr = output; uint32_t index = steps; uint32_t restLen = outLen - 1; // Reserve the position of the terminator. int32_t ret = NumToStr(outputPtr, &restLen, *(bnInit + index), false, &cpyNum); if (ret != CRYPT_SUCCESS) { return ret; } outputPtr += cpyNum; while (index-- != 0) { ret = NumToStr(outputPtr, &restLen, *(bnInit + index), true, &cpyNum); if (ret != CRYPT_SUCCESS) { return ret; } outputPtr += cpyNum; } *outputPtr = '\0'; return CRYPT_SUCCESS; } char *BN_Bn2Dec(const BN_BigNum *a) { if (a == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return NULL; } int32_t ret; char *p = NULL; uint32_t steps = 0; /* * Estimate the maximum length of a decimal BigNum * x <= 10 ^ y < 2 ^ (bit + 1) * y < lg_(2) ( 2 ^ (bit + 1)) * y < (bit + 1) * lg2 -- (lg_2 = 0.30102999566...) * y < (bit + 1) * 0.303 * y < 3 * bit * 0.001 + 3 * bit * 0.100 + 1 */ uint32_t numLen = (BN_Bits(a) * 3) / 10 + (BN_Bits(a) * 3) / 1000 + 1; uint32_t outLen = numLen + 3; // Add the sign, end symbol, and buffer space. uint32_t unitNum = (numLen / BN_DEC_LEN) + 1; char *result = BSL_SAL_Malloc(outLen); BN_UINT *bnInit = (BN_UINT *)BSL_SAL_Malloc(unitNum * sizeof(BN_UINT)); if (result == NULL || bnInit == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); goto ERR; } p = result; if (BN_IsZero(a)) { *p++ = '0'; *p++ = '\0'; ret = CRYPT_SUCCESS; goto ERR; } if (a->sign) { *p++ = '-'; outLen--; } ret = CalDecStr(a, bnInit, unitNum, &steps); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ret = FmtDecOutput(p, outLen, bnInit, steps); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ERR: BSL_SAL_FREE(bnInit); if (ret == CRYPT_SUCCESS) { return result; } BSL_SAL_FREE(result); return NULL; } #endif /* HITLS_CRYPTO_BN_STR_CONV */ #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/bn_utils.c
C
unknown
19,706
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include "bn_bincal.h" /* r = a + b, the length of r, a and b array is n. The return value is the carry. */ BN_UINT BinAdd(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n) { BN_UINT carry = 0; uint32_t nn = n; const BN_UINT *aa = a; const BN_UINT *bb = b; BN_UINT *rr = r; #ifndef HITLS_CRYPTO_BN_SMALL_MEM while (nn >= 4) { /* Process 4 groups in batches. */ ADD_ABC(carry, rr[0], aa[0], bb[0], carry); /* offset 0 */ ADD_ABC(carry, rr[1], aa[1], bb[1], carry); /* offset 1 */ ADD_ABC(carry, rr[2], aa[2], bb[2], carry); /* offset 2 */ ADD_ABC(carry, rr[3], aa[3], bb[3], carry); /* offset 3 */ rr += 4; /* a group of 4 */ aa += 4; /* a group of 4 */ bb += 4; /* a group of 4 */ nn -= 4; /* a group of 4 */ } #endif uint32_t i = 0; for (; i < nn; i++) { ADD_ABC(carry, rr[i], aa[i], bb[i], carry); } return carry; } /* r = a - b, the length of r, a and b array is n. The return value is the borrow-digit. */ BN_UINT BinSub(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n) { BN_UINT borrow = 0; uint32_t nn = n; const BN_UINT *aa = a; const BN_UINT *bb = b; BN_UINT *rr = r; #ifndef HITLS_CRYPTO_BN_SMALL_MEM while (nn >= 4) { /* Process 4 groups in batches. */ SUB_ABC(borrow, rr[0], aa[0], bb[0], borrow); /* offset 0 */ SUB_ABC(borrow, rr[1], aa[1], bb[1], borrow); /* offset 1 */ SUB_ABC(borrow, rr[2], aa[2], bb[2], borrow); /* offset 2 */ SUB_ABC(borrow, rr[3], aa[3], bb[3], borrow); /* offset 3 */ rr += 4; /* a group of 4 */ aa += 4; /* a group of 4 */ bb += 4; /* a group of 4 */ nn -= 4; /* a group of 4 */ } #endif uint32_t i = 0; for (; i < nn; i++) { SUB_ABC(borrow, rr[i], aa[i], bb[i], borrow); } return borrow; } /* Obtains the number of 0s in the first x most significant bits of data. */ uint32_t GetZeroBitsUint(BN_UINT x) { BN_UINT iter; BN_UINT tmp = x; uint32_t bits = BN_UNIT_BITS; uint32_t base = BN_UNIT_BITS >> 1; do { iter = tmp >> base; if (iter != 0) { tmp = iter; bits -= base; } base = base >> 1; } while (base != 0); return (uint32_t)(bits - tmp); } /* Multiply and then subtract. The return value is borrow digit. */ BN_UINT BinSubMul(BN_UINT *r, const BN_UINT *a, BN_UINT aSize, BN_UINT m) { BN_UINT borrow = 0; uint32_t i; for (i = 0; i < aSize; i++) { BN_UINT ah, al; MUL_AB(ah, al, a[i], m); SUB_ABC(borrow, r[i], r[i], al, borrow); borrow += ah; } return borrow; } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/noasm_bn_bincal.c
C
unknown
3,341
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include <stdbool.h> #include "bn_bincal.h" /* reduce(r * r) */ int32_t MontSqrBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { return MontSqrBinCore(r, mont, opt, consttime); } int32_t MontMulBin(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { return MontMulBinCore(r, a, b, mont, opt, consttime); } int32_t MontEncBin(BN_UINT *r, BN_Mont *mont, BN_Optimizer *opt, bool consttime) { return MontEncBinCore(r, mont, opt, consttime); } void Reduce(BN_UINT *r, BN_UINT *x, const BN_UINT *one, const BN_UINT *m, uint32_t mSize, BN_UINT m0) { (void)one; ReduceCore(r, x, m, mSize, m0); } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/noasm_bn_mont.c
C
unknown
1,325
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_BN #include <stdint.h> #include "bn_bincal.h" #ifndef HITLS_SIXTY_FOUR_BITS #error Bn binical x8664 optimizer must open BN-64. #endif // r = a + b, len = n, return carry BN_UINT BinAdd(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n) { if (n == 0) { return 0; } BN_UINT ret = n; asm volatile ( ".p2align 4 \n" " mov %0, %%rcx \n" " and $3, %%rcx \n" // will clear CF " shr $2, %0 \n" " clc \n" " jz aone \n" // n / 4 > = 0 , goto step 4 "4: movq 0(%2), %%r8 \n" " movq 8(%2), %%r9 \n" " movq 16(%2), %%r10 \n" " movq 24(%2), %%r11 \n" " adcq 0(%3), %%r8 \n" " adcq 8(%3), %%r9 \n" " adcq 16(%3), %%r10 \n" " adcq 24(%3), %%r11 \n" " movq %%r8, 0(%1) \n" " movq %%r9, 8(%1) \n" " movq %%r10, 16(%1) \n" " movq %%r11, 24(%1) \n" " lea 32(%1), %1 \n" " lea 32(%2), %2 \n" " lea 32(%3), %3 \n" " dec %0 \n" " jnz 4b \n" "aone: jrcxz eadd \n" // n % 4 == 0, goto end "1: movq (%2,%0,8), %%r8 \n" " adcq (%3,%0,8), %%r8 \n" " movq %%r8, (%1,%0,8) \n" " inc %0 \n" " dec %%rcx \n" " jnz 1b \n" "eadd: sbbq %0, %0 \n" :"+&r" (ret) :"r"(r), "r"(a), "r"(b) :"r8", "r9", "r10", "r11", "rcx", "cc", "memory"); return ret & 1; } // r = a - b, len = n, return carry BN_UINT BinSub(BN_UINT *r, const BN_UINT *a, const BN_UINT *b, uint32_t n) { if (n == 0) { return 0; } BN_UINT res = n; asm volatile ( ".p2align 4 \n" " mov %0, %%rcx \n" " and $3, %%rcx \n" " shr $2, %0 \n" " clc \n" " jz sone \n" // n / 4 > = 0 , goto step 4 "4: movq 0(%2), %%r8 \n" " movq 8(%2), %%r9 \n" " movq 16(%2), %%r10 \n" " movq 24(%2), %%r11 \n" " sbbq 0(%3), %%r8 \n" " sbbq 8(%3), %%r9 \n" " sbbq 16(%3), %%r10 \n" " sbbq 24(%3), %%r11 \n" " movq %%r8, 0(%1) \n" " movq %%r9, 8(%1) \n" " movq %%r10, 16(%1) \n" " movq %%r11, 24(%1) \n" " lea 32(%1), %1 \n" " lea 32(%2), %2 \n" " lea 32(%3), %3 \n" " dec %0 \n" " jnz 4b \n" "sone: jrcxz esub \n" // n % 4 == 0, goto end "1: movq (%2,%0,8), %%r8 \n" " sbbq (%3,%0,8), %%r8 \n" " movq %%r8, (%1,%0,8) \n" " inc %0 \n" " dec %%rcx \n" " jnz 1b \n" "esub: sbbq %0, %0 \n" :"+&r" (res) :"r"(r), "r"(a), "r"(b) :"r8", "r9", "r10", "r11", "rcx", "cc", "memory"); return res & 1; } // r = r - a * m, return the carry; BN_UINT BinSubMul(BN_UINT *r, const BN_UINT *a, BN_UINT aSize, BN_UINT m) { BN_UINT borrow = 0; BN_UINT i = 0; asm volatile ( ".p2align 4 \n" "endy: movq %5, %%rax \n" // rax = m " mulq (%4,%1,8) \n" // rax -> al, rdx -> ah " addq %0, %%rax \n" // rax = al + borrow " adcq $0, %%rdx \n" // if has carry, rdx++ " subq %%rax, (%3,%1,8) \n" // r[i] = r[i] - (al + borrow) " adcq $0, %%rdx \n" // if has carry, borrow++ " movq %%rdx, %0 \n" " inc %1 \n" " dec %2 \n" " jnz endy \n" :"+&r" (borrow), "+r"(i), "+r"(aSize) :"r"(r), "r"(a), "r"(m) :"rax", "rdx", "cc", "memory"); return borrow; } /* Obtains the number of 0s in the first x most significant bits of data. */ uint32_t GetZeroBitsUint(BN_UINT x) { BN_UINT iter; BN_UINT tmp = x; uint32_t bits = BN_UNIT_BITS; uint32_t base = BN_UNIT_BITS >> 1; do { iter = tmp >> base; if (iter != 0) { tmp = iter; bits -= base; } base = base >> 1; } while (base != 0); return bits - tmp; } #endif /* HITLS_CRYPTO_BN */
2302_82127028/openHiTLS-examples_1556
crypto/bn/src/x8664_bn_bincal.c
C
unknown
6,809
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_CHACHA20_H #define CRYPT_CHACHA20_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 #include <stdint.h> #include "crypt_types.h" #ifdef __cplusplus extern "C" { #endif // __cplusplus #define CHACHA20_STATESIZE 16 #define CHACHA20_STATEBYTES (CHACHA20_STATESIZE * sizeof(uint32_t)) #define CHACHA20_KEYLEN 32 #define CHACHA20_NONCELEN 12 typedef struct { uint32_t state[CHACHA20_STATESIZE]; // state RFC 7539 union { uint32_t c[CHACHA20_STATESIZE]; uint8_t u[CHACHA20_STATEBYTES]; } last; // save the last data uint32_t lastLen; // remaining length of the last data in bytes uint8_t set; // indicates whether the key and nonce are set } CRYPT_CHACHA20_Ctx; int32_t CRYPT_CHACHA20_SetKey(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *key, uint32_t keyLen); int32_t CRYPT_CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len); int32_t CRYPT_CHACHA20_Ctrl(CRYPT_CHACHA20_Ctx *ctx, int32_t opt, void *val, uint32_t len); void CRYPT_CHACHA20_Clean(CRYPT_CHACHA20_Ctx *ctx); #ifdef __cplusplus } #endif // __cplusplus #endif // HITLS_CRYPTO_CHACHA20 #endif // CRYPT_CHACHA20_H
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/include/crypt_chacha20.h
C
unknown
1,710
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 .text .macro CHA256_SET_VDATA mov VREG01.16b, VSIGMA.16b mov VREG11.16b, VSIGMA.16b mov VREG21.16b, VSIGMA.16b mov VREG02.16b, VKEY01.16b mov VREG12.16b, VKEY01.16b mov VREG22.16b, VKEY01.16b mov VREG03.16b, VKEY02.16b mov VREG13.16b, VKEY02.16b mov VREG23.16b, VKEY02.16b mov VREG04.16b, VREG52.16b // 1 mov VREG14.16b, VREG53.16b // 2 mov VREG24.16b, VREG54.16b // 3 .endm .macro CHA256_ROUND_A add WINPUT0, WINPUT0, WINPUT4 // A+B add VREG01.4s, VREG01.4s, VREG02.4s add WINPUT1, WINPUT1, WINPUT5 // A+B add VREG11.4s, VREG11.4s, VREG12.4s add WINPUT2, WINPUT2, WINPUT6 // A+B add VREG21.4s, VREG21.4s, VREG22.4s add WINPUT3, WINPUT3, WINPUT7 // A+B eor VREG04.16b, VREG04.16b, VREG01.16b eor WINPUT12, WINPUT12, WINPUT0 // D^A eor VREG14.16b, VREG14.16b, VREG11.16b eor WINPUT13, WINPUT13, WINPUT1 // D^A eor VREG24.16b, VREG24.16b, VREG21.16b eor WINPUT14, WINPUT14, WINPUT2 // D^A rev32 VREG04.8h, VREG04.8h eor WINPUT15, WINPUT15, WINPUT3 // D^A rev32 VREG14.8h, VREG14.8h ror WINPUT12, WINPUT12, #16 // D>>>16 rev32 VREG24.8h, VREG24.8h ror WINPUT13, WINPUT13, #16 // D>>>16 add VREG03.4s, VREG03.4s, VREG04.4s ror WINPUT14, WINPUT14, #16 // D>>>16 add VREG13.4s, VREG13.4s, VREG14.4s ror WINPUT15, WINPUT15, #16 // D>>>16 add VREG23.4s, VREG23.4s, VREG24.4s add WINPUT8, WINPUT8, WINPUT12 // C+D eor VREG41.16b, VREG03.16b, VREG02.16b add WINPUT9, WINPUT9, WINPUT13 // C+D eor VREG42.16b, VREG13.16b, VREG12.16b add WINPUT10, WINPUT10, WINPUT14 // C+D eor VREG43.16b, VREG23.16b, VREG22.16b add WINPUT11, WINPUT11, WINPUT15 // C+D ushr VREG02.4s, VREG41.4s, #20 eor WINPUT4, WINPUT4, WINPUT8 // B^C ushr VREG12.4s, VREG42.4s, #20 eor WINPUT5, WINPUT5, WINPUT9 // B^C ushr VREG22.4s, VREG43.4s, #20 eor WINPUT6, WINPUT6, WINPUT10 // B^C sli VREG02.4s, VREG41.4s, #12 eor WINPUT7, WINPUT7, WINPUT11 // B^C sli VREG12.4s, VREG42.4s, #12 ror WINPUT4, WINPUT4, #20 // B>>>20 sli VREG22.4s, VREG43.4s, #12 ror WINPUT5, WINPUT5, #20 // B>>>20 add VREG01.4s, VREG01.4s, VREG02.4s ror WINPUT6, WINPUT6, #20 // B>>>20 add VREG11.4s, VREG11.4s, VREG12.4s ror WINPUT7, WINPUT7, #20 // B>>>20 add VREG21.4s, VREG21.4s, VREG22.4s add WINPUT0, WINPUT0, WINPUT4 // A+B eor VREG41.16b, VREG04.16b, VREG01.16b add WINPUT1, WINPUT1, WINPUT5 // A+B eor VREG42.16b, VREG14.16b, VREG11.16b add WINPUT2, WINPUT2, WINPUT6 // A+B eor VREG43.16b, VREG24.16b, VREG21.16b add WINPUT3, WINPUT3, WINPUT7 // A+B ushr VREG04.4s, VREG41.4s, #24 eor WINPUT12, WINPUT12, WINPUT0 // D^A ushr VREG14.4s, VREG42.4s, #24 eor WINPUT13, WINPUT13, WINPUT1 // D^A ushr VREG24.4s, VREG43.4s, #24 eor WINPUT14, WINPUT14, WINPUT2 // D^A sli VREG04.4s, VREG41.4s, #8 eor WINPUT15, WINPUT15, WINPUT3 // D^A sli VREG14.4s, VREG42.4s, #8 ror WINPUT12, WINPUT12, #24 // D>>>24 sli VREG24.4s, VREG43.4s, #8 ror WINPUT13, WINPUT13, #24 // D>>>24 add VREG03.4s, VREG03.4s, VREG04.4s ror WINPUT14, WINPUT14, #24 // D>>>24 add VREG13.4s, VREG13.4s, VREG14.4s ror WINPUT15, WINPUT15, #24 // D>>>24 add VREG23.4s, VREG23.4s, VREG24.4s add WINPUT8, WINPUT8, WINPUT12 // C+D eor VREG41.16b, VREG03.16b, VREG02.16b add WINPUT9, WINPUT9, WINPUT13 // C+D eor VREG42.16b, VREG13.16b, VREG12.16b add WINPUT10, WINPUT10, WINPUT14 // C+D eor VREG43.16b, VREG23.16b, VREG22.16b add WINPUT11, WINPUT11, WINPUT15 // C+D ushr VREG02.4s, VREG41.4s, #25 eor WINPUT4, WINPUT4, WINPUT8 // B^C ushr VREG12.4s, VREG42.4s, #25 eor WINPUT5, WINPUT5, WINPUT9 // B^C ushr VREG22.4s, VREG43.4s, #25 eor WINPUT6, WINPUT6, WINPUT10 // B^C sli VREG02.4s, VREG41.4s, #7 eor WINPUT7, WINPUT7, WINPUT11 // B^C sli VREG12.4s, VREG42.4s, #7 ror WINPUT4, WINPUT4, #25 // B>>>25 sli VREG22.4s, VREG43.4s, #7 ror WINPUT5, WINPUT5, #25 // B>>>25 ext VREG03.16b, VREG03.16b, VREG03.16b, #8 ror WINPUT6, WINPUT6, #25 // B>>>25 ext VREG13.16b, VREG13.16b, VREG13.16b, #8 ror WINPUT7, WINPUT7, #25 // B>>>25 ext VREG23.16b, VREG23.16b, VREG23.16b, #8 .endm .macro CHA256_ROUND_B add WINPUT0, WINPUT0, WINPUT5 // A+B add VREG01.4s, VREG01.4s, VREG02.4s add WINPUT1, WINPUT1, WINPUT6 // A+B add VREG11.4s, VREG11.4s, VREG12.4s add WINPUT2, WINPUT2, WINPUT7 // A+B add VREG21.4s, VREG21.4s, VREG22.4s add WINPUT3, WINPUT3, WINPUT4 // A+B eor VREG04.16b, VREG04.16b, VREG01.16b eor WINPUT15, WINPUT15, WINPUT0 // D^A eor VREG14.16b, VREG14.16b, VREG11.16b eor WINPUT12, WINPUT12, WINPUT1 // D^A eor VREG24.16b, VREG24.16b, VREG21.16b eor WINPUT13, WINPUT13, WINPUT2 // D^A rev32 VREG04.8h, VREG04.8h eor WINPUT14, WINPUT14, WINPUT3 // D^A rev32 VREG14.8h, VREG14.8h ror WINPUT12, WINPUT12, #16 // D>>>16 rev32 VREG24.8h, VREG24.8h ror WINPUT13, WINPUT13, #16 // D>>>16 add VREG03.4s, VREG03.4s, VREG04.4s ror WINPUT14, WINPUT14, #16 // D>>>16 add VREG13.4s, VREG13.4s, VREG14.4s ror WINPUT15, WINPUT15, #16 // D>>>16 add VREG23.4s, VREG23.4s, VREG24.4s add WINPUT10, WINPUT10, WINPUT15 // C+D eor VREG41.16b, VREG03.16b, VREG02.16b add WINPUT11, WINPUT11, WINPUT12 // C+D eor VREG42.16b, VREG13.16b, VREG12.16b add WINPUT8, WINPUT8, WINPUT13 // C+D eor VREG43.16b, VREG23.16b, VREG22.16b add WINPUT9, WINPUT9, WINPUT14 // C+D ushr VREG02.4s, VREG41.4s, #20 eor WINPUT5, WINPUT5, WINPUT10 // B^C ushr VREG12.4s, VREG42.4s, #20 eor WINPUT6, WINPUT6, WINPUT11 // B^C ushr VREG22.4s, VREG43.4s, #20 eor WINPUT7, WINPUT7, WINPUT8 // B^C sli VREG02.4s, VREG41.4s, #12 eor WINPUT4, WINPUT4, WINPUT9 // B^C sli VREG12.4s, VREG42.4s, #12 ror WINPUT4, WINPUT4, #20 // B>>>20 sli VREG22.4s, VREG43.4s, #12 ror WINPUT5, WINPUT5, #20 // B>>>20 add VREG01.4s, VREG01.4s, VREG02.4s ror WINPUT6, WINPUT6, #20 // B>>>20 add VREG11.4s, VREG11.4s, VREG12.4s ror WINPUT7, WINPUT7, #20 // B>>>20 add VREG21.4s, VREG21.4s, VREG22.4s add WINPUT0, WINPUT0, WINPUT5 // A+B eor VREG41.16b, VREG04.16b, VREG01.16b add WINPUT1, WINPUT1, WINPUT6 // A+B eor VREG42.16b, VREG14.16b, VREG11.16b add WINPUT2, WINPUT2, WINPUT7 // A+B eor VREG43.16b, VREG24.16b, VREG21.16b add WINPUT3, WINPUT3, WINPUT4 // A+B ushr VREG04.4s, VREG41.4s, #24 eor WINPUT15, WINPUT15, WINPUT0 // D^A ushr VREG14.4s, VREG42.4s, #24 eor WINPUT12, WINPUT12, WINPUT1 // D^A ushr VREG24.4s, VREG43.4s, #24 eor WINPUT13, WINPUT13, WINPUT2 // D^A sli VREG04.4s, VREG41.4s, #8 eor WINPUT14, WINPUT14, WINPUT3 // D^A sli VREG14.4s, VREG42.4s, #8 ror WINPUT12, WINPUT12, #24 // D>>>24 sli VREG24.4s, VREG43.4s, #8 ror WINPUT13, WINPUT13, #24 add VREG03.4s, VREG03.4s, VREG04.4s ror WINPUT14, WINPUT14, #24 add VREG13.4s, VREG13.4s, VREG14.4s ror WINPUT15, WINPUT15, #24 add VREG23.4s, VREG23.4s, VREG24.4s add WINPUT10, WINPUT10, WINPUT15 // C+D eor VREG41.16b, VREG03.16b, VREG02.16b add WINPUT11, WINPUT11, WINPUT12 // C+D eor VREG42.16b, VREG13.16b, VREG12.16b add WINPUT8, WINPUT8, WINPUT13 // C+D eor VREG43.16b, VREG23.16b, VREG22.16b add WINPUT9, WINPUT9, WINPUT14 // C+D ushr VREG02.4s, VREG41.4s, #25 eor WINPUT5, WINPUT5, WINPUT10 // B^C ushr VREG12.4s, VREG42.4s, #25 eor WINPUT6, WINPUT6, WINPUT11 ushr VREG22.4s, VREG43.4s, #25 eor WINPUT7, WINPUT7, WINPUT8 sli VREG02.4s, VREG41.4s, #7 eor WINPUT4, WINPUT4, WINPUT9 sli VREG12.4s, VREG42.4s, #7 ror WINPUT4, WINPUT4, #25 // B>>>25 sli VREG22.4s, VREG43.4s, #7 ror WINPUT5, WINPUT5, #25 ext VREG03.16b, VREG03.16b, VREG03.16b, #8 ror WINPUT6, WINPUT6, #25 ext VREG13.16b, VREG13.16b, VREG13.16b, #8 ror WINPUT7, WINPUT7, #25 ext VREG23.16b, VREG23.16b, VREG23.16b, #8 .endm .macro CHA256_ROUND_END add VREG01.4s, VREG01.4s, VSIGMA.4s // After the cycle is complete, add input. add VREG11.4s, VREG11.4s, VSIGMA.4s add VREG21.4s, VREG21.4s, VSIGMA.4s add VREG02.4s, VREG02.4s, VKEY01.4s // After the cycle is complete, add input. add VREG12.4s, VREG12.4s, VKEY01.4s add VREG22.4s, VREG22.4s, VKEY01.4s add VREG03.4s, VREG03.4s, VKEY02.4s // After the cycle is complete, add input. add VREG13.4s, VREG13.4s, VKEY02.4s add VREG23.4s, VREG23.4s, VKEY02.4s add VREG04.4s, VREG04.4s, VREG52.4s // 0 add VREG14.4s, VREG14.4s, VREG53.4s // 1 add VREG24.4s, VREG24.4s, VREG54.4s // 2 .endm .macro CHA256_WRITE_BACK ld1 {VREG41.16b, VREG42.16b, VREG43.16b, VREG44.16b}, [REGINC], #64 // Load 64 bytes. eor XINPUT0, XINPUT0, XINPUT1 eor XINPUT2, XINPUT2, XINPUT3 eor XINPUT4, XINPUT4, XINPUT5 eor XINPUT6, XINPUT6, XINPUT7 eor XINPUT8, XINPUT8, XINPUT9 stp XINPUT0, XINPUT2, [REGOUT], #16 // Write data. eor VREG01.16b, VREG01.16b, VREG41.16b stp XINPUT4, XINPUT6, [REGOUT], #16 eor XINPUT10, XINPUT10, XINPUT11 eor VREG02.16b, VREG02.16b, VREG42.16b eor XINPUT12, XINPUT12, XINPUT13 eor VREG03.16b, VREG03.16b, VREG43.16b eor XINPUT14, XINPUT14, XINPUT15 stp XINPUT8, XINPUT10, [REGOUT], #16 eor VREG04.16b, VREG04.16b, VREG44.16b ld1 {VREG41.16b, VREG42.16b, VREG43.16b, VREG44.16b}, [REGINC], #64 // Load 64 bytes. stp XINPUT12, XINPUT14, [REGOUT], #16 eor VREG11.16b, VREG11.16b, VREG41.16b eor VREG12.16b, VREG12.16b, VREG42.16b st1 {VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b}, [REGOUT], #64 // Write 64 bytes. eor VREG13.16b, VREG13.16b, VREG43.16b eor VREG14.16b, VREG14.16b, VREG44.16b ld1 {VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b}, [REGINC], #64 // Load 64 bytes. st1 {VREG11.16b, VREG12.16b, VREG13.16b, VREG14.16b}, [REGOUT], #64 // Write 64 bytes. eor VREG21.16b, VREG21.16b, VREG01.16b eor VREG22.16b, VREG22.16b, VREG02.16b eor VREG23.16b, VREG23.16b, VREG03.16b eor VREG24.16b, VREG24.16b, VREG04.16b st1 {VREG21.16b, VREG22.16b, VREG23.16b, VREG24.16b}, [REGOUT], #64 // Write 64 bytes. .endm .macro CHA256_WRITE_BACKB src1, src2, src3, src4 ld1 {VREG41.16b, VREG42.16b, VREG43.16b, VREG44.16b}, [REGINC], #64 // Load 64 bytes. eor \src1, \src1, VREG41.16b eor \src2, \src2, VREG42.16b eor \src3, \src3, VREG43.16b eor \src4, \src4, VREG44.16b st1 {\src1, \src2, \src3, \src4}, [REGOUT], #64 // Write 64 bytes. .endm #endif
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/asm/chacha20_256block_aarch64.S
Unix Assembly
unknown
12,601
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 .text .macro CHA512_EXTA VEXT2 VREG04.16b, VREG14.16b, #12 VEXT2 VREG24.16b, VREG34.16b, #12 VEXT2 VREG44.16b, VREG54.16b, #12 VEXT2 VREG02.16b, VREG12.16b, #4 VEXT2 VREG22.16b, VREG32.16b, #4 VEXT2 VREG42.16b, VREG52.16b, #4 .endm .macro CHA512_EXTB VEXT2 VREG04.16b, VREG14.16b, #4 VEXT2 VREG24.16b, VREG34.16b, #4 VEXT2 VREG44.16b, VREG54.16b, #4 VEXT2 VREG02.16b, VREG12.16b, #12 VEXT2 VREG22.16b, VREG32.16b, #12 VEXT2 VREG42.16b, VREG52.16b, #12 .endm .macro CHA512_SET_VDATA mov VREG01.16b, VSIGMA.16b mov VREG11.16b, VSIGMA.16b mov VREG21.16b, VSIGMA.16b mov VREG31.16b, VSIGMA.16b mov VREG41.16b, VSIGMA.16b mov VREG51.16b, VSIGMA.16b mov VREG02.16b, VKEY01.16b mov VREG12.16b, VKEY01.16b mov VREG22.16b, VKEY01.16b mov VREG32.16b, VKEY01.16b mov VREG42.16b, VKEY01.16b mov VREG52.16b, VKEY01.16b mov VREG03.16b, VKEY02.16b mov VREG13.16b, VKEY02.16b mov VREG23.16b, VKEY02.16b mov VREG33.16b, VKEY02.16b mov VREG43.16b, VKEY02.16b mov VREG53.16b, VKEY02.16b mov VREG04.16b, VCUR01.16b // Counter + 2 mov VREG14.16b, VCUR02.16b // Counter + 3 mov VREG24.16b, VCUR03.16b // Counter + 4 mov VREG34.16b, VCUR04.16b // Counter + 5 add VREG44.4s, VREG04.4s, VADDER.4s // Counter + 6 = 4 + 2 add VREG54.4s, VREG14.4s, VADDER.4s // Counter + 7 = 4 + 3 .endm .macro CHA512_ROUND_END add VREG01.4s, VREG01.4s, VSIGMA.4s // After the loop is complete, add input. add VREG11.4s, VREG11.4s, VSIGMA.4s add VREG21.4s, VREG21.4s, VSIGMA.4s add VREG31.4s, VREG31.4s, VSIGMA.4s add VREG41.4s, VREG41.4s, VSIGMA.4s add VREG51.4s, VREG51.4s, VSIGMA.4s add VREG02.4s, VREG02.4s, VKEY01.4s // After the loop is complete, add input. add VREG12.4s, VREG12.4s, VKEY01.4s add VREG22.4s, VREG22.4s, VKEY01.4s add VREG32.4s, VREG32.4s, VKEY01.4s add VREG42.4s, VREG42.4s, VKEY01.4s add VREG52.4s, VREG52.4s, VKEY01.4s add VREG03.4s, VREG03.4s, VKEY02.4s // After the loop is complete, add input. add VREG13.4s, VREG13.4s, VKEY02.4s add VREG23.4s, VREG23.4s, VKEY02.4s add VREG33.4s, VREG33.4s, VKEY02.4s add VREG43.4s, VREG43.4s, VKEY02.4s add VREG53.4s, VREG53.4s, VKEY02.4s add VREG44.4s, VREG44.4s, VCUR01.4s // 2 add VREG54.4s, VREG54.4s, VCUR02.4s // 3 add VREG04.4s, VREG04.4s, VCUR01.4s // 2 add VREG14.4s, VREG14.4s, VCUR02.4s // 3 add VREG24.4s, VREG24.4s, VCUR03.4s // 4 add VREG34.4s, VREG34.4s, VCUR04.4s // 5 add VREG44.4s, VREG44.4s, VADDER.4s // 4 + 2 add VREG54.4s, VREG54.4s, VADDER.4s // 4 + 3 .endm .macro CHA512_WRITE_BACK ld1 {VCUR01.16b, VCUR02.16b, VCUR03.16b, VCUR04.16b}, [REGINC], #64 // Load 64 bytes. eor VREG01.16b, VREG01.16b, VCUR01.16b eor VREG02.16b, VREG02.16b, VCUR02.16b eor VREG03.16b, VREG03.16b, VCUR03.16b eor VREG04.16b, VREG04.16b, VCUR04.16b ld1 {VCUR01.16b, VCUR02.16b, VCUR03.16b, VCUR04.16b}, [REGINC], #64 // Load 64 bytes. st1 {VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b}, [REGOUT], #64 // Write 64 bytes. eor VREG11.16b, VREG11.16b, VCUR01.16b eor VREG12.16b, VREG12.16b, VCUR02.16b eor VREG13.16b, VREG13.16b, VCUR03.16b eor VREG14.16b, VREG14.16b, VCUR04.16b ld1 {VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b}, [REGINC], #64 // Load 64 bytes. st1 {VREG11.16b, VREG12.16b, VREG13.16b, VREG14.16b}, [REGOUT], #64 // Write 64 bytes. eor VREG21.16b, VREG21.16b, VREG01.16b eor VREG22.16b, VREG22.16b, VREG02.16b eor VREG23.16b, VREG23.16b, VREG03.16b eor VREG24.16b, VREG24.16b, VREG04.16b ld1 {VREG11.16b, VREG12.16b, VREG13.16b, VREG14.16b}, [REGINC], #64 // Load 64 bytes. st1 {VREG21.16b, VREG22.16b, VREG23.16b, VREG24.16b}, [REGOUT], #64 // Write 64 bytes. eor VREG31.16b, VREG31.16b, VREG11.16b eor VREG32.16b, VREG32.16b, VREG12.16b eor VREG33.16b, VREG33.16b, VREG13.16b eor VREG34.16b, VREG34.16b, VREG14.16b ld1 {VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b}, [REGINC], #64 // Load 64 bytes. st1 {VREG31.16b, VREG32.16b, VREG33.16b, VREG34.16b}, [REGOUT], #64 // Write 64 bytes. shl VREG21.4s, VADDER.4s, #1 // 4 -> 8 eor VREG41.16b, VREG41.16b, VREG01.16b eor VREG42.16b, VREG42.16b, VREG02.16b eor VREG43.16b, VREG43.16b, VREG03.16b eor VREG44.16b, VREG44.16b, VREG04.16b ld1 {VREG11.16b, VREG12.16b, VREG13.16b, VREG14.16b}, [REGINC], #64 // Load 64 bytes. st1 {VREG41.16b, VREG42.16b, VREG43.16b, VREG44.16b}, [REGOUT], #64 // Write 64 bytes. ldp QCUR01, QCUR02, [sp, #32] // restore counter 0 1 2 4 ldp QCUR03, QCUR04, [sp, #64] eor VREG51.16b, VREG51.16b, VREG11.16b eor VREG52.16b, VREG52.16b, VREG12.16b eor VREG53.16b, VREG53.16b, VREG13.16b eor VREG54.16b, VREG54.16b, VREG14.16b st1 {VREG51.16b, VREG52.16b, VREG53.16b, VREG54.16b}, [REGOUT], #64 // Write 64 bytes. add VCUR01.4s, VCUR01.4s, VREG21.4s add VCUR02.4s, VCUR02.4s, VREG21.4s add VCUR03.4s, VCUR03.4s, VREG21.4s add VCUR04.4s, VCUR04.4s, VREG21.4s .endm .macro CHA512_ROUND WCHA_ADD_A_B // a += b VADD2 VREG02.4s, VREG01.4s, VREG12.4s, VREG11.4s // a[0,1,2,3] += b[4,5,6,7] VADD2 VREG22.4s, VREG21.4s, VREG32.4s, VREG31.4s WCHA_EOR_D_A // d ^= a VADD2 VREG42.4s, VREG41.4s, VREG52.4s, VREG51.4s VEOR2 VREG01.16b, VREG04.16b, VREG11.16b, VREG14.16b // d[12,13,14,15] ^= a[0,1,2,3] WCHA_ROR_D #16 // d <<<= 16 ror Cyclic shift right by 16 bits. VEOR2 VREG21.16b, VREG24.16b, VREG31.16b, VREG34.16b VEOR2 VREG41.16b, VREG44.16b, VREG51.16b, VREG54.16b WCHA_ADD_C_D // c += d VREV322 VREG04.8h, VREG14.8h // d[12,13,14,15] (#16 inverse). VREV322 VREG24.8h, VREG34.8h WCHA_EOR_B_C VREV322 VREG44.8h, VREG54.8h VADD2 VREG04.4s, VREG03.4s, VREG14.4s, VREG13.4s // c[8,9,10,11] += d[12,13,14,15] WCHA_ROR_B #20 VADD2 VREG24.4s, VREG23.4s, VREG34.4s, VREG33.4s VADD2 VREG44.4s, VREG43.4s, VREG54.4s, VREG53.4s WCHA_ADD_A_B // a += b VEORX VREG03.16b, VREG02.16b, VCUR01.16b, VREG13.16b, VREG12.16b, VCUR02.16b // m = b[4,5,6,7] ^ c[8,9,10,11] VEORX VREG23.16b, VREG22.16b, VCUR03.16b, VREG33.16b, VREG32.16b, VCUR04.16b WCHA_EOR_D_A VEORX VREG43.16b, VREG42.16b, VCUR05.16b, VREG53.16b, VREG52.16b, VCUR06.16b VUSHR2 VCUR01.4s, VREG02.4s, VCUR02.4s, VREG12.4s, #20 // b[4,5,6,7] = m << 20 WCHA_ROR_D #24 VUSHR2 VCUR03.4s, VREG22.4s, VCUR04.4s, VREG32.4s, #20 VUSHR2 VCUR05.4s, VREG42.4s, VCUR06.4s, VREG52.4s, #20 WCHA_ADD_C_D // c += d VSLI2 VCUR01.4s, VREG02.4s, VCUR02.4s, VREG12.4s, #12 // b[4,5,6,7] = m >> 12 VSLI2 VCUR03.4s, VREG22.4s, VCUR04.4s, VREG32.4s, #12 WCHA_EOR_B_C VSLI2 VCUR05.4s, VREG42.4s, VCUR06.4s, VREG52.4s, #12 VADD2 VREG02.4s, VREG01.4s, VREG12.4s, VREG11.4s // a[0,1,2,3] += b[4,5,6,7] WCHA_ROR_B #25 VADD2 VREG22.4s, VREG21.4s, VREG32.4s, VREG31.4s VADD2 VREG42.4s, VREG41.4s, VREG52.4s, VREG51.4s WCHA_ADD2_A_B VEORX VREG04.16b, VREG01.16b, VCUR01.16b, VREG14.16b, VREG11.16b, VCUR02.16b // m = d[12,13,14,15] ^ a[0,1,2,3] VEORX VREG24.16b, VREG21.16b, VCUR03.16b, VREG34.16b, VREG31.16b, VCUR04.16b WCHA_EOR2_D_A VEORX VREG44.16b, VREG41.16b, VCUR05.16b, VREG54.16b, VREG51.16b, VCUR06.16b VUSHR2 VCUR01.4s, VREG04.4s, VCUR02.4s, VREG14.4s, #24 // d[12,13,14,15] = m << 24 WCHA_ROR_D #16 VUSHR2 VCUR03.4s, VREG24.4s, VCUR04.4s, VREG34.4s, #24 VUSHR2 VCUR05.4s, VREG44.4s, VCUR06.4s, VREG54.4s, #24 WCHA_ADD2_C_D VSLI2 VCUR01.4s, VREG04.4s, VCUR02.4s, VREG14.4s, #8 // d[12,13,14,15] = m >> 8 VSLI2 VCUR03.4s, VREG24.4s, VCUR04.4s, VREG34.4s, #8 WCHA_EOR2_B_C VSLI2 VCUR05.4s, VREG44.4s, VCUR06.4s, VREG54.4s, #8 VADD2 VREG04.4s, VREG03.4s, VREG14.4s, VREG13.4s // c[8,9,10,11] += d[12,13,14,15] WCHA_ROR_B #20 VADD2 VREG24.4s, VREG23.4s, VREG34.4s, VREG33.4s VADD2 VREG44.4s, VREG43.4s, VREG54.4s, VREG53.4s WCHA_ADD2_A_B VEORX VREG03.16b, VREG02.16b, VCUR01.16b, VREG13.16b, VREG12.16b, VCUR02.16b // m = b[4,5,6,7] ^ c[8,9,10,11] VEORX VREG23.16b, VREG22.16b, VCUR03.16b, VREG33.16b, VREG32.16b, VCUR04.16b WCHA_EOR2_D_A VEORX VREG43.16b, VREG42.16b, VCUR05.16b, VREG53.16b, VREG52.16b, VCUR06.16b VUSHR2 VCUR01.4s, VREG02.4s, VCUR02.4s, VREG12.4s, #25 // b[4,5,6,7] = m << 25 WCHA_ROR_D #24 VUSHR2 VCUR03.4s, VREG22.4s, VCUR04.4s, VREG32.4s, #25 VUSHR2 VCUR05.4s, VREG42.4s, VCUR06.4s, VREG52.4s, #25 WCHA_ADD2_C_D VSLI2 VCUR01.4s, VREG02.4s, VCUR02.4s, VREG12.4s, #7 // b[4,5,6,7] = m >> 7 VSLI2 VCUR03.4s, VREG22.4s, VCUR04.4s, VREG32.4s, #7 WCHA_EOR2_B_C VSLI2 VCUR05.4s, VREG42.4s, VCUR06.4s, VREG52.4s, #7 VEXT2 VREG03.16b, VREG13.16b, #8 WCHA_ROR_B #25 VEXT2 VREG23.16b, VREG33.16b, #8 VEXT2 VREG43.16b, VREG53.16b, #8 .endm #endif
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/asm/chacha20_512block_aarch64.S
Unix Assembly
unknown
10,013
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 .text .macro CHA64_SET_WDATA mov WINPUT0, WSIG01 lsr XINPUT1, XSIG01, #32 mov WINPUT2, WSIG02 lsr XINPUT3, XSIG02, #32 mov WINPUT4, WKEY01 lsr XINPUT5, XKEY01, #32 mov WINPUT6, WKEY02 lsr XINPUT7, XKEY02, #32 mov WINPUT8, WKEY03 lsr XINPUT9, XKEY03, #32 mov WINPUT10, WKEY04 lsr XINPUT11, XKEY04, #32 mov WINPUT12, WCOUN1 lsr XINPUT13, XCOUN1, #32 // 0 mov WINPUT14, WCOUN2 lsr XINPUT15, XCOUN2, #32 .endm .macro CHA64_ROUND_END add WINPUT0, WINPUT0, WSIG01 // Sum of the upper 32 bits and lower 32 bits. add XINPUT1, XINPUT1, XSIG01, lsr#32 add WINPUT2, WINPUT2, WSIG02 add XINPUT3, XINPUT3, XSIG02, lsr#32 add WINPUT4, WINPUT4, WKEY01 add XINPUT5, XINPUT5, XKEY01, lsr#32 add WINPUT6, WINPUT6, WKEY02 add XINPUT7, XINPUT7, XKEY02, lsr#32 add WINPUT8, WINPUT8, WKEY03 add XINPUT9, XINPUT9, XKEY03, lsr#32 add WINPUT10, WINPUT10, WKEY04 add XINPUT11, XINPUT11, XKEY04, lsr#32 add WINPUT12, WINPUT12, WCOUN1 add XINPUT13, XINPUT13, XCOUN1, lsr#32 add WINPUT14, WINPUT14, WCOUN2 add XINPUT15, XINPUT15, XCOUN2, lsr#32 add XINPUT0, XINPUT0, XINPUT1, lsl#32 // Combination of upper 32 bits and lower 32 bits. add XINPUT2, XINPUT2, XINPUT3, lsl#32 // Combination of upper 32 bits and lower 32 bits. ldp XINPUT1, XINPUT3, [REGINC], #16 // Load input. add XINPUT4, XINPUT4, XINPUT5, lsl#32 // Combination of upper 32 bits and lower 32 bits. add XINPUT6, XINPUT6, XINPUT7, lsl#32 // Combination of upper 32 bits and lower 32 bits. ldp XINPUT5, XINPUT7, [REGINC], #16 // Load input. add XINPUT8, XINPUT8, XINPUT9, lsl#32 // Combination of upper 32 bits and lower 32 bits. add XINPUT10, XINPUT10, XINPUT11, lsl#32 // Combination of upper 32 bits and lower 32 bits. ldp XINPUT9, XINPUT11, [REGINC], #16 // Load input. add XINPUT12, XINPUT12, XINPUT13, lsl#32 // Combination of upper 32 bits and lower 32 bits. add XINPUT14, XINPUT14, XINPUT15, lsl#32 // Combination of upper 32 bits and lower 32 bits. ldp XINPUT13, XINPUT15, [REGINC], #16 // Load input. #ifdef HITLS_BIG_ENDIAN // Special processing is required in big-endian mode. rev XINPUT0, XINPUT0 rev XINPUT2, XINPUT2 rev XINPUT4, XINPUT4 rev XINPUT6, XINPUT6 rev XINPUT8, XINPUT8 rev XINPUT10, XINPUT10 rev XINPUT12, XINPUT12 rev XINPUT14, XINPUT14 #endif .endm .macro CHA64_WRITE_BACK eor XINPUT0, XINPUT0, XINPUT1 eor XINPUT2, XINPUT2, XINPUT3 eor XINPUT4, XINPUT4, XINPUT5 eor XINPUT6, XINPUT6, XINPUT7 eor XINPUT8, XINPUT8, XINPUT9 stp XINPUT0, XINPUT2, [REGOUT], #16 // Write data. eor XINPUT10, XINPUT10, XINPUT11 stp XINPUT4, XINPUT6, [REGOUT], #16 eor XINPUT12, XINPUT12, XINPUT13 eor XINPUT14, XINPUT14, XINPUT15 stp XINPUT8, XINPUT10, [REGOUT], #16 stp XINPUT12, XINPUT14, [REGOUT], #16 .endm #endif
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/asm/chacha20_64block_aarch64.S
Unix Assembly
unknown
3,649
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 #include "crypt_arm.h" #include "chacha20_common_aarch64.S" #include "chacha20_64block_aarch64.S" #include "chacha20_256block_aarch64.S" #include "chacha20_512block_aarch64.S" .section .rodata .ADD_LONG: .long 1,0,0,0 /** * @Interconnection with the C interface:void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len); * @brief Chacha20 algorithm * @param ctx [IN] Algorithm context, which is set by the C interface and transferred. * @param in [IN] Data to be encrypted * @param out [OUT] Data after encryption * @param len [IN] Encrypted length */ .text .globl CHACHA20_Update .type CHACHA20_Update,%function .align 4 CHACHA20_Update: AARCH64_PACIASP lsr REGLEN, REGLEN, #6 // Divided by 64 to calculate how many blocks. stp x29, x30, [sp, #-96]! // x29 x30 store sp -96 address sp -=96. add x29, sp, #0 // x29 = sp stp x19, x20, [sp, #80] // x19 x20 store sp, sp +=16. stp x21, x22, [sp, #64] cmp REGLEN, #1 // 1 stp x23, x24, [sp, #48] stp x25, x26, [sp, #32] stp x27, x28, [sp, #16] sub sp, sp, #128+64 // sp -= 192 b.lo .Lchacha_end // Less than 1 block. b.eq .Lchacha64 // Equals 1 block. adrp x5, .ADD_LONG add x5, x5, :lo12:.ADD_LONG // load(1, 0, 0, 0) cmp REGLEN, #8 // >= 512(64*8) #ifdef HITLS_BIG_ENDIAN ldp XSIG01, XSIG02, [x0] ld1 {VSIGMA.4s}, [x0], #16 // {sima0, sima1, key0, key1, key3, key4, counter1, counter2} ldp XKEY01, XKEY02, [x0] ldp XKEY03, XKEY04, [x0, #16] ld1 {VKEY01.4s, VKEY02.4s}, [x0], #32 ldp XCOUN1, XCOUN2, [x0] ld1 {VCOUN0.4s}, [x0] // Processing when the big-endian machine is loaded. ror XCOUN1, XCOUN1, #32 ror XCOUN2, XCOUN2, #32 ror XSIG01, XSIG01, #32 ror XSIG02, XSIG02, #32 add WINPUT2, WCOUN1, w3 ror XKEY01, XKEY01, #32 ror XKEY02, XKEY02, #32 ror XKEY03, XKEY03, #32 ror XKEY04, XKEY04, #32 str WINPUT2, [x0] #else ldp XSIG01, XSIG02, [x0] ld1 {VSIGMA.4s}, [x0], #16 // {sima0, sima1, key0, key1, key3, key4, counter1, counter2} ldp XKEY01, XKEY02, [x0] ldp XKEY03, XKEY04, [x0, #16] ld1 {VKEY01.4s, VKEY02.4s}, [x0], #32 ldp XCOUN1, XCOUN2, [x0] ld1 {VCOUN0.4s}, [x0] add x6, XCOUN1, REGLEN str x6, [x0] // Write back the counter. #endif b.lo .Lchacha256 // < 512 stp QCUR05, QCUR06, [sp, #0] // Write sigma key1 to SP. ld1 {VADDER.4s}, [x5] // Load ADDR. add VCUR01.4s, VCOUN0.4s, VADDER.4s // 0 add VCUR01.4s, VCUR01.4s, VADDER.4s // +2 add VCUR02.4s, VCUR01.4s, VADDER.4s // +3 add VCUR03.4s, VCUR02.4s, VADDER.4s // +4 add VCUR04.4s, VCUR03.4s, VADDER.4s // +5 shl VADDER.4s, VADDER.4s, #2 // 4 stp d8, d9,[sp,#128+0] // Meet ABI requirements. stp d10, d11,[sp,#128+16] stp d12, d13,[sp,#128+32] stp d14, d15,[sp,#128+48] // 8 block .Loop_512_start: cmp REGLEN, #8 b.lo .L512ToChacha256 // Less than 512. CHA64_SET_WDATA // General-purpose register 1 x 64 bytes. CHA512_SET_VDATA // Wide register 6 x 64 bytes. stp QCUR01, QCUR02, [sp, #32] // Write counter 0, 1, 2 3 to sp. stp QCUR03, QCUR04, [sp, #64] mov x4, #5 sub REGLEN, REGLEN, #8 // Process 512 at a time. .Loop_512_a_run: sub x4, x4, #1 CHA512_ROUND CHA512_EXTA CHA512_ROUND CHA512_EXTB cbnz x4, .Loop_512_a_run CHA64_ROUND_END // Add to input after the loop is complete. CHA64_WRITE_BACK // 512 Write 64 bytes in the first half round. add XCOUN1, XCOUN1, #1 // +1 CHA64_SET_WDATA // Resetting. mov x4, #5 .Loop_512_b_run: sub x4, x4, #1 CHA512_ROUND CHA512_EXTA CHA512_ROUND CHA512_EXTB cbnz x4, .Loop_512_b_run CHA64_ROUND_END // Add to input after the loop is complete. CHA64_WRITE_BACK // 512 Write 64 bytes in the first half round. add XCOUN1, XCOUN1, #7 // +7 ldp QCUR05, QCUR06, [sp, #0] // Restore sigma and key1. ldp QCUR01, QCUR02, [sp, #32] // Restore counter 0 1 2 4. ldp QCUR03, QCUR04, [sp, #64] CHA512_ROUND_END // Add to input after the loop is complete. CHA512_WRITE_BACK // Write back data. b .Loop_512_start // return start. // 1 block .Lchacha64: #ifdef HITLS_BIG_ENDIAN ldp XCOUN1, XCOUN2, [x0, #48] ldp XSIG01, XSIG02, [x0] ldp XKEY01, XKEY02, [x0, #16] // Processing when the big-endian machine is loaded ror XCOUN1, XCOUN1, #32 ror XCOUN2, XCOUN2, #32 ror XSIG01, XSIG01, #32 ror XSIG02, XSIG02, #32 ldp XKEY03, XKEY04, [x0, #32] add WINPUT0, WCOUN1, w3 ror XKEY01, XKEY01, #32 ror XKEY02, XKEY02, #32 ror XKEY03, XKEY03, #32 ror XKEY04, XKEY04, #32 str WINPUT0, [x0, #48] #else ldp XCOUN1, XCOUN2, [x0, #48] ldp XSIG01, XSIG02, [x0] ldp XKEY01, XKEY02, [x0, #16] add XINPUT0, XCOUN1, REGLEN ldp XKEY03, XKEY04, [x0, #32] str XINPUT0, [x0, #48] // Write data. #endif .Loop_64_start: CHA64_SET_WDATA // General-purpose register, 1x64byte. mov x4, #10 .Loop_64_run: sub x4, x4, #1 WCHA_ADD_A_B // a += b WCHA_EOR_D_A // d ^= a WCHA_ROR_D #16 // d <<<= 16 ror Cyclic shift right by 16 bits. WCHA_ADD_C_D // c += d WCHA_EOR_B_C WCHA_ROR_B #20 WCHA_ADD_A_B // a += b WCHA_EOR_D_A WCHA_ROR_D #24 WCHA_ADD_C_D // c += d WCHA_EOR_B_C WCHA_ROR_B #25 WCHA_ADD2_A_B WCHA_EOR2_D_A WCHA_ROR_D #16 WCHA_ADD2_C_D WCHA_EOR2_B_C WCHA_ROR_B #20 WCHA_ADD2_A_B WCHA_EOR2_D_A WCHA_ROR_D #24 WCHA_ADD2_C_D WCHA_EOR2_B_C WCHA_ROR_B #25 cbnz x4, .Loop_64_run CHA64_ROUND_END // Add to input after the loop is complete. subs REGLEN, REGLEN, #1 CHA64_WRITE_BACK // Write 64 bytes. add XCOUN1, XCOUN1, #1 b.le .Lchacha_end b .Loop_64_start .L512ToChacha256: ldp d8,d9,[sp,#128+0] // Meet ABI requirements. ldp d10,d11,[sp,#128+16] ldp d12,d13,[sp,#128+32] ldp d14,d15,[sp,#128+48] cbz REGLEN, .Lchacha_end // The length is 0. ushr VADDER.4s, VADDER.4s, #2 // 4->1 sub VREG52.4s, VCUR01.4s, VADDER.4s // 10-1 = 9 8 sub VREG53.4s, VCUR02.4s, VADDER.4s // 11-1 = 10 sub VREG54.4s, VCUR03.4s, VADDER.4s // 12-1 = 11 shl VCUR01.4s, VADDER.4s, #2 // 2 -> 4 b .Loop_256_start // 4 block .Lchacha256: ld1 {VADDER.4s}, [x5] // Load ADDR. mov VREG51.16b, VCOUN0.16b // 0 add VREG52.4s, VCOUN0.4s, VADDER.4s // 1 add VREG53.4s, VREG52.4s, VADDER.4s // 2 add VREG54.4s, VREG53.4s, VADDER.4s // 3 shl VCUR01.4s, VADDER.4s, #2 // 4 .Loop_256_start: CHA64_SET_WDATA // General-purpose register 16 byte. CHA256_SET_VDATA // Neon register 3 * 48 byte. mov x4, #10 .Loop_256_run: sub x4, x4, #1 CHA256_ROUND_A VEXT2 VREG04.16b, VREG14.16b, #12 VEXT2 VREG24.16b, VREG34.16b, #12 VEXT2 VREG02.16b, VREG12.16b, #4 VEXT2 VREG22.16b, VREG32.16b, #4 CHA256_ROUND_B VEXT2 VREG04.16b, VREG14.16b, #4 VEXT2 VREG24.16b, VREG34.16b, #4 VEXT2 VREG02.16b, VREG12.16b, #12 VEXT2 VREG22.16b, VREG32.16b, #12 cbnz x4, .Loop_256_run subs REGLEN, REGLEN, #4 // One-time processing 256. CHA256_ROUND_END b.lo .Lchacha_less_than_256 // < 0 CHA64_ROUND_END CHA256_WRITE_BACK // Write back data. b.le .Lchacha_end // = 0 add XCOUN1, XCOUN1, #4 // Counter+4. add VREG52.4s, VREG52.4s, VCUR01.4s // Counter+4. add VREG53.4s, VREG53.4s, VCUR01.4s add VREG54.4s, VREG54.4s, VCUR01.4s b .Loop_256_start .Lchacha_less_than_256: add REGLEN, REGLEN, #4 cmp REGLEN, #1 b.lo .Lchacha_end // <= 64 byte. CHA64_ROUND_END CHA64_WRITE_BACK sub REGLEN, REGLEN, #1 cmp REGLEN, #1 b.lo .Lchacha_end CHA256_WRITE_BACKB VREG01.16b, VREG02.16b, VREG03.16b, VREG04.16b sub REGLEN, REGLEN, #1 cmp REGLEN, #1 b.lo .Lchacha_end CHA256_WRITE_BACKB VREG11.16b, VREG12.16b, VREG13.16b, VREG14.16b .Lchacha_end: eor XKEY01, XKEY01, XKEY01 eor XKEY02, XKEY02, XKEY02 eor XKEY03, XKEY03, XKEY03 eor XKEY04, XKEY04, XKEY04 eor XKEY04, XKEY04, XKEY04 eor XCOUN2, XCOUN2, XCOUN2 eor VKEY01.16b, VKEY01.16b, VKEY01.16b eor VKEY02.16b, VKEY02.16b, VKEY02.16b eor VCUR01.16b, VCUR01.16b, VCUR01.16b ldp x19, x20, [x29, #80] add sp, sp, #128+64 ldp x21, x22, [x29, #64] ldp x23, x24, [x29, #48] ldp x25, x26, [x29, #32] ldp x27, x28, [x29, #16] ldp x29, x30, [sp], #96 .Labort: AARCH64_AUTIASP ret .size CHACHA20_Update,.-CHACHA20_Update #endif
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/asm/chacha20_aarch64.S
Unix Assembly
unknown
10,460
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 .text // Input ctx、in、out、len. REGCTX .req x0 REGINC .req x1 REGOUT .req x2 REGLEN .req x3 // 64-byte input, temporarily loaded register(0 ~ 15). WINPUT0 .req w5 XINPUT0 .req x5 WINPUT1 .req w6 XINPUT1 .req x6 WINPUT2 .req w7 XINPUT2 .req x7 WINPUT3 .req w8 XINPUT3 .req x8 WINPUT4 .req w9 XINPUT4 .req x9 WINPUT5 .req w10 XINPUT5 .req x10 WINPUT6 .req w11 XINPUT6 .req x11 WINPUT7 .req w12 XINPUT7 .req x12 WINPUT8 .req w13 XINPUT8 .req x13 WINPUT9 .req w14 XINPUT9 .req x14 WINPUT10 .req w15 XINPUT10 .req x15 WINPUT11 .req w16 XINPUT11 .req x16 WINPUT12 .req w17 XINPUT12 .req x17 WINPUT13 .req w19 XINPUT13 .req x19 WINPUT14 .req w20 XINPUT14 .req x20 WINPUT15 .req w21 XINPUT15 .req x21 // 8 blocks in parallel, 6 blocks of 64-byte data in 8 blocks of 512 bytes. VREG01 .req v0 VREG02 .req v1 VREG03 .req v2 VREG04 .req v3 VREG11 .req v4 VREG12 .req v5 VREG13 .req v6 VREG14 .req v7 VREG21 .req v8 VREG22 .req v9 VREG23 .req v10 VREG24 .req v11 VREG31 .req v12 VREG32 .req v13 VREG33 .req v14 VREG34 .req v15 VREG41 .req v16 VREG42 .req v17 VREG43 .req v18 VREG44 .req v19 VREG51 .req v20 VREG52 .req v21 VREG53 .req v22 VREG54 .req v23 // Public register, used for temporary calculation. VCUR01 .req v24 QCUR01 .req q24 VCUR02 .req v25 QCUR02 .req q25 VCUR03 .req v26 QCUR03 .req q26 VCUR04 .req v27 QCUR04 .req q27 VCUR05 .req v28 QCUR05 .req q28 VCUR06 .req v29 QCUR06 .req q29 // Counter、sigma、key、adder register. VCOUN0 .req v27 VSIGMA .req v28 VKEY01 .req v29 VKEY02 .req v30 VADDER .req v31 // Counter、sigma、key、adder register. WSIG01 .req w22 XSIG01 .req x22 WSIG02 .req w23 XSIG02 .req x23 WKEY01 .req w24 XKEY01 .req x24 WKEY02 .req w25 XKEY02 .req x25 WKEY03 .req w26 XKEY03 .req x26 WKEY04 .req w27 XKEY04 .req x27 WCOUN1 .req w28 XCOUN1 .req x28 WCOUN2 .req w30 XCOUN2 .req x30 .macro VADD2 src, dest, src2, dest2 add \dest, \dest, \src add \dest2, \dest2, \src2 .endm .macro VEOR2 src, dest, src2, dest2 eor \dest, \dest, \src eor \dest2, \dest2, \src2 .endm .macro VEORX srca, srcb, dest, srca2, srcb2, dest2 eor \dest, \srcb, \srca eor \dest2, \srcb2, \srca2 .endm .macro VREV322 dest, dest2 rev32 \dest, \dest rev32 \dest2, \dest2 .endm .macro VUSHR2 src, dest, src2, dest2, count ushr \dest, \src, \count ushr \dest2, \src2, \count .endm .macro VSLI2 src, dest, src2, dest2, count sli \dest, \src, \count sli \dest2, \src2, \count .endm .macro VEXT2 src, src2, count ext \src, \src, \src, \count ext \src2, \src2, \src2, \count .endm .macro WCHA_ADD_A_B add WINPUT0, WINPUT0, WINPUT4 add WINPUT1, WINPUT1, WINPUT5 add WINPUT2, WINPUT2, WINPUT6 add WINPUT3, WINPUT3, WINPUT7 .endm .macro WCHA_EOR_D_A eor WINPUT12, WINPUT12, WINPUT0 eor WINPUT13, WINPUT13, WINPUT1 eor WINPUT14, WINPUT14, WINPUT2 eor WINPUT15, WINPUT15, WINPUT3 .endm .macro WCHA_ROR_D count ror WINPUT12, WINPUT12, \count ror WINPUT13, WINPUT13, \count ror WINPUT14, WINPUT14, \count ror WINPUT15, WINPUT15, \count .endm .macro WCHA_ADD_C_D add WINPUT8, WINPUT8, WINPUT12 add WINPUT9, WINPUT9, WINPUT13 add WINPUT10, WINPUT10, WINPUT14 add WINPUT11, WINPUT11, WINPUT15 .endm .macro WCHA_EOR_B_C eor WINPUT4, WINPUT4, WINPUT8 eor WINPUT5, WINPUT5, WINPUT9 eor WINPUT6, WINPUT6, WINPUT10 eor WINPUT7, WINPUT7, WINPUT11 .endm .macro WCHA_ROR_B count ror WINPUT4, WINPUT4, \count ror WINPUT5, WINPUT5, \count ror WINPUT6, WINPUT6, \count ror WINPUT7, WINPUT7, \count .endm .macro WCHA_ADD2_A_B add WINPUT0, WINPUT0, WINPUT5 add WINPUT1, WINPUT1, WINPUT6 add WINPUT2, WINPUT2, WINPUT7 add WINPUT3, WINPUT3, WINPUT4 .endm .macro WCHA_EOR2_D_A eor WINPUT15, WINPUT15, WINPUT0 eor WINPUT12, WINPUT12, WINPUT1 eor WINPUT13, WINPUT13, WINPUT2 eor WINPUT14, WINPUT14, WINPUT3 .endm .macro WCHA_ADD2_C_D add WINPUT10, WINPUT10, WINPUT15 add WINPUT11, WINPUT11, WINPUT12 add WINPUT8, WINPUT8, WINPUT13 add WINPUT9, WINPUT9, WINPUT14 .endm .macro WCHA_EOR2_B_C eor WINPUT5, WINPUT5, WINPUT10 eor WINPUT6, WINPUT6, WINPUT11 eor WINPUT7, WINPUT7, WINPUT8 eor WINPUT4, WINPUT4, WINPUT9 .endm #endif
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/asm/chacha20_common_aarch64.S
Motorola 68K Assembly
unknown
4,831
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 /* --------------AVX2 Overall design----------------- * 64->%xmm0-%xmm7 No need to use stack memory * 128->%xmm0-%xmm11 No need to use stack memory * 256->%xmm0-%xmm15 Use 256 + 64 bytes of stack memory * 512->%ymm0-%ymm15 Use 512 + 128 bytes of stack memory * --------------AVX512 Overall design----------------- * 64->%xmm0-%xmm7 No need to use stack memory * 128->%xmm0-%xmm11 No need to use stack memory * 256->%xmm0-%xmm31 Use 64-byte stack memory * 512->%ymm0-%ymm31 Use 128-byte stack memory * 1024->%zmm0-%zmm31 Use 256-byte stack memory */ /************************************************************************************* * AVX2/AVX512 Generic Instruction Set Using Macros *************************************************************************************/ /* %xmm0-15 load STATE Macro. */ .macro LOAD_STATE s0 s1 s2 s3 adr vmovdqu (\adr), \s0 // state[0-3] vmovdqu 16(\adr), \s1 // state[4-7] vmovdqu 32(\adr), \s2 // state[8-11] vmovdqu 48(\adr), \s3 // state[12-15] .endm /* %ymm0-15 load STATE Macro. */ .macro LOAD_512_STATE s0 s1 s2 s3 adr vbroadcasti128 (\adr), \s0 // state[0-3] vbroadcasti128 16(\adr), \s1 // state[4-7] vbroadcasti128 32(\adr), \s2 // state[8-11] vbroadcasti128 48(\adr), \s3 // state[12-15] .endm /* * %xmm0-15, %ymm0-15 MATRIX TO STATE * IN: s0 s1 s2 s3 cur1 cur2 * OUT: s0 s3 cur1 cur2 * xmm: * {A0 B0 C0 D0} => {A0 A1 A2 A3} * {A1 B1 C1 D1} {B0 B1 B2 B3} * {A2 B2 C2 D2} {C0 C1 C2 C3} * {A3 B3 C3 D3} {D0 D1 D2 D3} * ymm: * {A0 B0 C0 D0 E0 F0 G0 H0} => {A0 A1 A2 A3 E0 E1 E2 E3} * {A1 B1 C1 D1 E1 F1 G1 H1} {B0 B1 B2 B3 F0 F1 F2 F3} * {A2 B2 C2 D2 E2 F2 G2 H2} {C0 C1 C2 C3 G0 G1 G2 G3} * {A3 B3 C3 D3 E3 F3 G3 H3} {D0 D1 D2 D3 H0 H1 H2 H3} * zmm: * {A0 B0 C0 D0 E0 F0 G0 H0 I0 J0 K0 L0 M0 N0 O0 P0} => {A0 A1 A2 A3 E0 E1 E2 E3 I0 I1 I2 I3 M0 M1 M2 M3} * {A1 B1 C1 D1 E1 F1 G1 H1 I1 J1 K1 L1 M1 N1 O1 P1} {B0 B1 B2 B3 F0 F1 F2 F3 J0 J1 J2 J3 N0 N1 N2 N3} * {A2 B2 C2 D2 E2 F2 G2 H2 I2 J2 K2 L2 M2 N2 O2 P2} {C0 C1 C2 C3 G0 G1 G2 G3 K0 K1 K2 K3 O0 O1 O2 O3} * {A3 B3 C3 D3 E3 F3 G3 H3 I3 J3 K3 L3 M3 N3 O3 P3} {D0 D1 D2 D3 H0 H1 H2 H3 L0 L1 L2 L3 P0 P1 P2 P3} */ .macro MATRIX_TO_STATE s0 s1 s2 s3 cur1 cur2 vpunpckldq \s1, \s0, \cur1 vpunpckldq \s3, \s2, \cur2 vpunpckhdq \s1, \s0, \s1 vpunpckhdq \s3, \s2, \s2 vpunpcklqdq \cur2, \cur1, \s0 vpunpckhqdq \cur2, \cur1, \s3 vpunpcklqdq \s2, \s1, \cur1 vpunpckhqdq \s2, \s1, \cur2 .endm /************************************************************************************* * AVX2 instruction set use macros *************************************************************************************/ .macro WRITEBACK_64_AVX2 inpos outpos s0 s1 s2 s3 vpxor (\inpos), \s0, \s0 vpxor 16(\inpos), \s1, \s1 vpxor 32(\inpos), \s2, \s2 vpxor 48(\inpos), \s3, \s3 vmovdqu \s0, (\outpos) // write back output vmovdqu \s1, 16(\outpos) vmovdqu \s2, 32(\outpos) vmovdqu \s3, 48(\outpos) add $64, \inpos add $64, \outpos .endm /* * Converts a state into a matrix. * %xmm0-15 %ymm0-15 STATE TO MATRIX * s0-s15:Corresponding to 16 wide-bit registers,adr:counter Settings; base:address of the data storage stack; * per:Register bit width,Byte representation(16、32) */ .macro STATE_TO_MATRIX s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 base per adr vpshufd $0b00000000, \s3, \s12 vpshufd $0b01010101, \s3, \s13 vpaddd \adr, \s12, \s12 // 0, 1, 2, 3, 4, 5, 6 ,7 vmovdqa \s12, \base+12*\per(%rsp) vpshufd $0b10101010, \s3, \s14 vmovdqa \s13, \base+13*\per(%rsp) vpshufd $0b11111111, \s3, \s15 vmovdqa \s14, \base+14*\per(%rsp) vpshufd $0b00000000, \s2, \s8 vmovdqa \s15, \base+15*\per(%rsp) vpshufd $0b01010101, \s2, \s9 vmovdqa \s8, \base+8*\per(%rsp) vpshufd $0b10101010, \s2, \s10 vmovdqa \s9, \base+9*\per(%rsp) vpshufd $0b11111111, \s2, \s11 vmovdqa \s10, \base+10*\per(%rsp) vpshufd $0b00000000, \s1, \s4 vmovdqa \s11, \base+11*\per(%rsp) vpshufd $0b01010101, \s1, \s5 vmovdqa \s4, \base+4*\per(%rsp) vpshufd $0b10101010, \s1, \s6 vmovdqa \s5, \base+5*\per(%rsp) vpshufd $0b11111111, \s1, \s7 vmovdqa \s6, \base+6*\per(%rsp) vpshufd $0b11111111, \s0, \s3 vmovdqa \s7, \base+7*\per(%rsp) vpshufd $0b10101010, \s0, \s2 vmovdqa \s3, \base+3*\per(%rsp) vpshufd $0b01010101, \s0, \s1 vmovdqa \s2, \base+2*\per(%rsp) vpshufd $0b00000000, \s0, \s0 vmovdqa \s1, \base+1*\per(%rsp) vmovdqa \s0, \base(%rsp) .endm /* * %xmm0-15 %ymm0-15 LOAD MATRIX */ .macro LOAD_MATRIX s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 base per adr vmovdqa \base(%rsp), \s0 vmovdqa \base+1*\per(%rsp), \s1 vmovdqa \base+2*\per(%rsp), \s2 vmovdqa \base+3*\per(%rsp), \s3 vmovdqa \base+4*\per(%rsp), \s4 vmovdqa \base+5*\per(%rsp), \s5 vmovdqa \base+6*\per(%rsp), \s6 vmovdqa \base+7*\per(%rsp), \s7 vmovdqa \base+8*\per(%rsp), \s8 vmovdqa \base+9*\per(%rsp), \s9 vmovdqa \base+10*\per(%rsp), \s10 vmovdqa \base+11*\per(%rsp), \s11 vmovdqa \base+12*\per(%rsp), \s12 vmovdqa \base+13*\per(%rsp), \s13 vpaddd \adr, \s12, \s12 // add 8, 8, 8, 8, 8, 8, 8, 8 or 4, 4, 4, 4 vmovdqa \base+14*\per(%rsp), \s14 vmovdqa \base+15*\per(%rsp), \s15 vmovdqa \s12, \base+12*\per(%rsp) .endm /* * %xmm0-15(256) %ymm0-15(512) Loop */ .macro CHACHA20_LOOP s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 s12 s13 s14 s15 base per A8 ror16 ror8 /* 0 = 0 + 4, 12 = (12 ^ 0) >>> 16 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 12 | * 0 = 0 + 4, 12 = (12 ^ 0) >>> 8 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 7 * 1 = 1 + 5, 13 = (13 ^ 1) >>> 16 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 12 | * 1 = 1 + 5, 13 = (13 ^ 1) >>> 8 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 7 */ COLUM_QUARTER_AVX_0 \s0 \s4 \s12 \s1 \s5 \s13 (\ror16) COLUM_QUARTER_AVX_1 \s8 \s12 \s4 \s9 \s13 \s5 \s10 \s11 $20 $12 COLUM_QUARTER_AVX_0 \s0 \s4 \s12 \s1 \s5 \s13 (\ror8) COLUM_QUARTER_AVX_1 \s8 \s12 \s4 \s9 \s13 \s5 \s10 \s11 $25 $7 vmovdqa \s8, \base(\A8) vmovdqa \s9, \base+\per(\A8) vmovdqa \base+2*\per(\A8), \s10 vmovdqa \base+3*\per(\A8), \s11 /* 2 = 2 + 6, 14 = (14 ^ 2) >>> 16 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 12 | * 2 = 2 + 6, 14 = (14 ^ 2) >>> 8 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 7 * 3 = 3 + 7, 15 = (15 ^ 3) >>> 16 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 12 | * 3 = 3 + 7, 15 = (15 ^ 3) >>> 8 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 7 */ COLUM_QUARTER_AVX_0 \s2 \s6 \s14 \s3 \s7 \s15 (\ror16) COLUM_QUARTER_AVX_1 \s10 \s14 \s6 \s11 \s15 \s7 \s8 \s9 $20 $12 COLUM_QUARTER_AVX_0 \s2 \s6 \s14 \s3 \s7 \s15 (\ror8) COLUM_QUARTER_AVX_1 \s10 \s14 \s6 \s11 \s15 \s7 \s8 \s9 $25 $7 /* 0 = 0 + 5, 15 = (15 ^ 0) >>> 16 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 12 | * 0 = 0 + 5, 15 = (15 ^ 0) >>> 8 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 7 * 1 = 1 + 6, 12 = (12 ^ 1) >>> 16 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 12 | * 1 = 1 + 6, 12 = (12 ^ 1) >>> 8 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 7 */ COLUM_QUARTER_AVX_0 \s0 \s5 \s15 \s1 \s6 \s12 (\ror16) COLUM_QUARTER_AVX_1 \s10 \s15 \s5 \s11 \s12 \s6 \s8 \s9 $20 $12 COLUM_QUARTER_AVX_0 \s0 \s5 \s15 \s1 \s6 \s12 (\ror8) COLUM_QUARTER_AVX_1 \s10 \s15 \s5 \s11 \s12 \s6 \s8 \s9 $25 $7 vmovdqa \s10, \base+2*\per(\A8) vmovdqa \s11, \base+3*\per(\A8) vmovdqa \base(\A8), \s8 vmovdqa \base+\per(\A8), \s9 /* 2 = 2 + 7, 13 = (13 ^ 2) >>> 16 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 12 | * 2 = 2 + 7, 13 = (13 ^ 2) >>> 8 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 7 * 3 = 3 + 4, 14 = (14 ^ 3) >>> 16 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 12 | * 3 = 3 + 4, 14 = (14 ^ 3) >>> 8 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 7 */ COLUM_QUARTER_AVX_0 \s2 \s7 \s13 \s3 \s4 \s14 (\ror16) COLUM_QUARTER_AVX_1 \s8 \s13 \s7 \s9 \s14 \s4 \s10 \s11 $20 $12 COLUM_QUARTER_AVX_0 \s2 \s7 \s13 \s3 \s4 \s14 (\ror8) COLUM_QUARTER_AVX_1 \s8 \s13 \s7 \s9 \s14 \s4 \s10 \s11 $25 $7 .endm /* * %xmm0-15 %ymm0-15 QUARTER macro(used when cyclically moving right by 16 or 8) */ .macro COLUM_QUARTER_AVX_0 a0 a1 a2 b0 b1 b2 ror vpaddd \a1, \a0, \a0 vpaddd \b1, \b0, \b0 vpxor \a0, \a2, \a2 vpxor \b0, \b2, \b2 vpshufb \ror, \a2, \a2 vpshufb \ror, \b2, \b2 .endm /* * %xmm0-15 %ymm0-15 QUARTER macro(used when cyclically moving right by 12 or 7) */ .macro COLUM_QUARTER_AVX_1 a0 a1 a2 b0 b1 b2 cur1 cur2 psr psl vpaddd \a1, \a0, \a0 vpaddd \b1, \b0, \b0 vpxor \a0, \a2, \a2 vpxor \b0, \b2, \b2 vpsrld \psr, \a2, \cur1 vpsrld \psr, \b2, \cur2 vpslld \psl, \a2, \a2 vpslld \psl, \b2, \b2 vpor \cur1, \a2, \a2 vpor \cur2, \b2, \b2 .endm /************************************************************************************* * AVX512 generic instruction set using macros. *************************************************************************************/ /* %zmm0-15 LOAD STATE MACRO. */ .macro LOAD_1024_STATE s0 s1 s2 s3 adr vbroadcasti32x4 (\adr), \s0 // state[0-3] vbroadcasti32x4 16(\adr), \s1 // state[4-7] vbroadcasti32x4 32(\adr), \s2 // state[8-11] vbroadcasti32x4 48(\adr), \s3 // state[12-15] .endm .macro WRITEBACK_64_AVX512 inpos outpos s0 s1 s2 s3 vpxord (\inpos), \s0, \s0 vpxord 16(\inpos), \s1, \s1 vpxord 32(\inpos), \s2, \s2 vpxord 48(\inpos), \s3, \s3 vmovdqu32 \s0, (\outpos) // Write back output. vmovdqu32 \s1, 16(\outpos) vmovdqu32 \s2, 32(\outpos) vmovdqu32 \s3, 48(\outpos) add $64, \inpos add $64, \outpos .endm /* * %zmm0-15 STATE TO MATRIX */ .macro STATE_TO_MATRIX_Z_AVX512 in out0 out1 out2 out3 // {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0} .... {15,15,15,15,15,15,15,15,15,15,15,15,15,15,15,15} vpshufd $0b00000000, \in, \out0 vpshufd $0b01010101, \in, \out1 vpshufd $0b10101010, \in, \out2 vpshufd $0b11111111, \in, \out3 .endm /* AVX512 instruction set * %zmm0-31(1024) QUARTER */ .macro COLUM_QUARTER_AVX512_4 s0 s1 s2 s3 s4 s5 s6 s7 s8 s9 s10 s11 ror vpaddd \s4, \s0, \s0 vpaddd \s5, \s1, \s1 vpaddd \s6, \s2, \s2 vpaddd \s7, \s3, \s3 vpxord \s0, \s8, \s8 vpxord \s1, \s9, \s9 vpxord \s2, \s10, \s10 vpxord \s3, \s11, \s11 vprold \ror, \s8, \s8 vprold \ror, \s9, \s9 vprold \ror, \s10, \s10 vprold \ror, \s11, \s11 .endm /* AVX512 instruction set * %xmm0-15(256) %ymm0-15(512) %zmm0-31(1024) Loop */ .macro CHACHA20_LOOP_AVX512 s00 s01 s02 s03 s04 s05 s06 s07 s08 s09 s10 s11 s12 s13 s14 s15 /* 0 = 0 + 4, 12 = (12 ^ 0) >>> 16 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 12 | * 0 = 0 + 4, 12 = (12 ^ 0) >>> 8 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 7 * 1 = 1 + 5, 13 = (13 ^ 1) >>> 16 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 12 | * 1 = 1 + 5, 13 = (13 ^ 1) >>> 8 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 7 * 2 = 2 + 6, 14 = (14 ^ 2) >>> 16 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 12 | * 2 = 2 + 6, 14 = (14 ^ 2) >>> 8 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 7 * 3 = 3 + 7, 15 = (15 ^ 3) >>> 16 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 12 | * 3 = 3 + 7, 15 = (15 ^ 3) >>> 8 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 7 */ COLUM_QUARTER_AVX512_4 \s00 \s01 \s02 \s03 \s04 \s05 \s06 \s07 \s12 \s13 \s14 \s15 $16 COLUM_QUARTER_AVX512_4 \s08 \s09 \s10 \s11 \s12 \s13 \s14 \s15 \s04 \s05 \s06 \s07 $12 COLUM_QUARTER_AVX512_4 \s00 \s01 \s02 \s03 \s04 \s05 \s06 \s07 \s12 \s13 \s14 \s15 $8 COLUM_QUARTER_AVX512_4 \s08 \s09 \s10 \s11 \s12 \s13 \s14 \s15 \s04 \s05 \s06 \s07 $7 /* 0 = 0 + 5, 15 = (15 ^ 0) >>> 16 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 12 | * 0 = 0 + 5, 15 = (15 ^ 0) >>> 8 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 7 * 1 = 1 + 6, 12 = (12 ^ 1) >>> 16 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 12 | * 1 = 1 + 6, 12 = (12 ^ 1) >>> 8 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 7 * 2 = 2 + 7, 13 = (13 ^ 2) >>> 16 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 12 | * 2 = 2 + 7, 13 = (13 ^ 2) >>> 8 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 7 * 3 = 3 + 4, 14 = (14 ^ 3) >>> 16 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 12 | * 3 = 3 + 4, 14 = (14 ^ 3) >>> 8 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 7 */ COLUM_QUARTER_AVX512_4 \s00 \s01 \s02 \s03 \s05 \s06 \s07 \s04 \s15 \s12 \s13 \s14 $16 COLUM_QUARTER_AVX512_4 \s10 \s11 \s08 \s09 \s15 \s12 \s13 \s14 \s05 \s06 \s07 \s04 $12 COLUM_QUARTER_AVX512_4 \s00 \s01 \s02 \s03 \s05 \s06 \s07 \s04 \s15 \s12 \s13 \s14 $8 COLUM_QUARTER_AVX512_4 \s10 \s11 \s08 \s09 \s15 \s12 \s13 \s14 \s05 \s06 \s07 \s04 $7 .endm #endif
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/asm/chacha20_x8664_common.S
Unix Assembly
unknown
13,328
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 #include "chacha20_x8664_common.S" .text .align 64 g_ror16_128: .byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd, \ 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd .size g_ror16_128, .-g_ror16_128 .align 64 g_ror8_128: .byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe, \ 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe .size g_ror8_128, .-g_ror8_128 .align 64 g_ror16: .byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd .size g_ror16, .-g_ror16 .align 64 g_ror8: .byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe .size g_ror8, .-g_ror8 .align 64 g_ror16_512: .byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd, \ 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd .size g_ror16_512, .-g_ror16_512 .align 64 g_ror8_512: .byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe, \ 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe .size g_ror8_512, .-g_ror8_512 .align 64 g_add4block: .long 0, 1, 2, 3 .size g_add4block, .-g_add4block .align 64 g_addsecond4block: .long 4, 4, 4, 4 .size g_addsecond4block, .-g_addsecond4block .align 64 g_add8block: .long 0, 1, 2, 3, 4, 5, 6, 7 .size g_add8block, .-g_add8block .align 64 g_addsecond8block: .long 8, 8, 8, 8, 8, 8, 8, 8 .size g_addsecond8block, .-g_addsecond8block .align 64 g_addOne: .long 0, 0, 0, 0, 1, 0, 0, 0 .size g_addOne, .-g_addOne .set IN, %rsi .set OUT, %rdx /* QUARTERROUND for one state */ .macro CHACHA20_ROUND s0 s1 s2 s3 cur ror16 ror8 vpaddd \s1, \s0, \s0 vpxor \s0, \s3, \s3 vpshufb (\ror16), \s3, \s3 vpaddd \s3, \s2, \s2 vpxor \s2, \s1, \s1 vmovdqa \s1, \cur vpsrld $20, \s1, \s1 vpslld $12, \cur, \cur vpor \cur, \s1, \s1 vpaddd \s1, \s0, \s0 vpxor \s0, \s3, \s3 vpshufb (\ror8), \s3, \s3 vpaddd \s3, \s2, \s2 vpxor \s2, \s1, \s1 vmovdqa \s1, \cur vpsrld $25, \s1, \s1 vpslld $7, \cur, \cur vpor \cur, \s1, \s1 .endm /* QUARTERROUND for two states */ .macro CHACHA20_2_ROUND s0 s1 s2 s3 cur s4 s5 s6 s7 cur1 ror16 ror8 vpaddd \s1, \s0, \s0 vpxor \s0, \s3, \s3 vpshufb (\ror16), \s3, \s3 vpaddd \s3, \s2, \s2 vpxor \s2, \s1, \s1 vmovdqa \s1, \cur vpsrld $20, \s1, \s1 vpslld $12, \cur, \cur vpor \cur, \s1, \s1 vpaddd \s1, \s0, \s0 vpxor \s0, \s3, \s3 vpshufb (\ror8), \s3, \s3 vpaddd \s3, \s2, \s2 vpxor \s2, \s1, \s1 vmovdqa \s1, \cur vpsrld $25, \s1, \s1 vpslld $7, \cur, \cur vpor \cur, \s1, \s1 vpaddd \s5, \s4, \s4 vpxor \s4, \s7, \s7 vpshufb (\ror16), \s7, \s7 vpaddd \s7, \s6, \s6 vpxor \s6, \s5, \s5 vmovdqa \s5, \cur1 vpsrld $20, \s5, \s5 vpslld $12, \cur1, \cur1 vpor \cur1, \s5, \s5 vpaddd \s5, \s4, \s4 vpxor \s4, \s7, \s7 vpshufb (\ror8), \s7, \s7 vpaddd \s7, \s6, \s6 vpxor \s6, \s5, \s5 vmovdqa \s5, \cur1 vpsrld $25, \s5, \s5 vpslld $7, \cur1, \cur1 vpor \cur1, \s5, \s5 .endm /* current matrix add original matrix */ .macro LASTADD_MATRIX S0 S1 S2 S3 S4 S5 S6 S7 S8 S9 S10 S11 S12 S13 S14 S15 PER vpaddd (%rsp), \S0, \S0 vpaddd 1*\PER(%rsp), \S1, \S1 vpaddd 2*\PER(%rsp), \S2, \S2 vpaddd 3*\PER(%rsp), \S3, \S3 vpaddd 4*\PER(%rsp), \S4, \S4 vpaddd 5*\PER(%rsp), \S5, \S5 vpaddd 6*\PER(%rsp), \S6, \S6 vpaddd 7*\PER(%rsp), \S7, \S7 vpaddd 8*\PER(%rsp), \S8, \S8 vpaddd 9*\PER(%rsp), \S9, \S9 vpaddd 10*\PER(%rsp), \S10, \S10 vpaddd 11*\PER(%rsp), \S11, \S11 vpaddd 12*\PER(%rsp), \S12, \S12 vpaddd 13*\PER(%rsp), \S13, \S13 vpaddd 14*\PER(%rsp), \S14, \S14 vpaddd 15*\PER(%rsp), \S15, \S15 .endm /* write output for left part of 512 bytes (ymm) */ .macro WRITE_BACK_512_L inpos outpos s0 s1 s2 s3 s4 s5 s6 s7 out0 out1 out2 out3 /* {A0 B0 C0 D0 E0 F0 G0 H0} {A1 B1 C1 D1 E1 F1 G1 H1} => {A0 B0 C0 D0 A1 B1 C1 D1} */ vperm2i128 $0x20, \s1, \s0, \out0 vpxor (\inpos), \out0, \out0 vmovdqu \out0, (\outpos) // write back output vperm2i128 $0x20, \s3, \s2, \out1 vpxor 32(\inpos), \out1, \out1 vmovdqu \out1, 32(\outpos) vperm2i128 $0x20, \s5, \s4, \out2 vpxor 64(\inpos), \out2, \out2 // write back output vmovdqu \out2, 64(\outpos) vperm2i128 $0x20, \s7, \s6, \out3 vpxor 96(\inpos), \out3, \out3 vmovdqu \out3, 96(\outpos) .endm /* write output for right part of 512 bytes (ymm) */ .macro WRITE_BACK_512_R inpos outpos s0 s1 s2 s3 s4 s5 s6 s7 /* {A0 B0 C0 D0 E0 F0 G0 H0} {A1 B1 C1 D1 E1 F1 G1 H1} => {E0 F0 G0 H0 E1 F1 G1 H1} */ vperm2i128 $0x31, \s1, \s0, \s1 vpxor (\inpos), \s1, \s1 vmovdqu \s1, (\outpos) // write back output vperm2i128 $0x31, \s3, \s2, \s3 vpxor 32(\inpos), \s3, \s3 vmovdqu \s3, 32(\outpos) vperm2i128 $0x31, \s5, \s4, \s5 vpxor 64(\inpos), \s5, \s5 vmovdqu \s5, 64(\outpos) // write back output vperm2i128 $0x31, \s7, \s6, \s7 vpxor 96(\inpos), \s7, \s7 vmovdqu \s7, 96(\outpos) .endm /* * Processing 64 bytes: 4 xmm registers * xmm0 ~ xmm3: * xmm0 {0, 1, 2, 3} * xmm1 {4, 5, 6, 7} * xmm2 {8, 9, 10, 11} * xmm3 {12, 13, 14, 15} * * Processing 128 bytes: 8 xmm registers * xmm0 ~ xmm8: * xmm0 {0, 1, 2, 3} xmm5 {0, 1, 2, 3} * xmm1 {4, 5, 6, 7} xmm6 {4, 5, 6, 7} * xmm2 {8, 9, 10, 11} xmm7 {8, 9, 10, 11} * xmm3 {12, 13, 14, 15} xmm8 {12, 13, 14, 15} * * Processing 256 bytes: 16 xmm registers * xmm0 ~ xmm15: * xmm0 {0, 0, 0, 0} * xmm1 {1, 2, 2, 2} * xmm2 {3, 3, 3, 3} * xmm3 {4, 4, 4, 4} * ... * xmm15 {15, 15, 15, 15} * * Processing 512 bytes: 16 xmm registers * ymm0 ~ ymm15: * ymm0 {0, 0, 0, 0} * ymm1 {1, 2, 2, 2} * ymm2 {3, 3, 3, 3} * ymm3 {4, 4, 4, 4} * ... * ymm15 {15, 15, 15, 15} * */ /* * @Interconnection with the C interface:void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len); * @brief chacha20 algorithm * @param ctx [IN] Algorithm context, which is set by the C interface and transferred. * @param in [IN] Data to be encrypted * @param out [OUT] Data after encryption * @param len [IN] Encrypted length * esp cannot use 15 available ctx in out len * 16 registers are needed in one cycle, then * {0, 1, 4, 5, 8, 9, 12, 13} * {2, 3, 6, 7, 10, 11, 14, 15} */ .globl CHACHA20_Update .type CHACHA20_Update,%function .align 64 CHACHA20_Update: .cfi_startproc mov 48(%rdi), %r11d mov %rsp, %rax subq $1024,%rsp andq $-512,%rsp .Lchacha20_start: cmp $512, %rcx jae .Lchacha20_512_start cmp $256, %rcx jae .Lchacha20_256_start cmp $128, %rcx jae .Lchacha20_128_start cmp $64, %rcx jae .Lchacha20_64_start jmp .Lchacha20_end .Lchacha20_64_start: LOAD_STATE %xmm0, %xmm1, %xmm2, %xmm3, %rdi vmovdqa %xmm0, %xmm10 vmovdqa %xmm1, %xmm11 vmovdqa %xmm2, %xmm12 vmovdqa %xmm3, %xmm13 leaq g_ror16(%rip), %r9 leaq g_ror8(%rip), %r10 mov $10, %r8 .Lchacha20_64_loop: /* 0 = 0 + 4, 12 = (12 ^ 0) >>> 16 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 12 | * 0 = 0 + 4, 12 = (12 ^ 0) >>> 8 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 7 * 1 = 1 + 5, 13 = (13 ^ 1) >>> 16 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 12 | * 1 = 1 + 5, 13 = (13 ^ 1) >>> 8 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 7 * 2 = 2 + 6, 14 = (14 ^ 2) >>> 16 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 12 | * 2 = 2 + 6, 14 = (14 ^ 2) >>> 8 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 7 * 3 = 3 + 7, 15 = (15 ^ 3) >>> 16 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 12 | * 3 = 3 + 7 ,15 = (15 ^ 3) >>> 8 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 7 */ CHACHA20_ROUND %xmm0, %xmm1, %xmm2, %xmm3, %xmm4, %r9, %r10 vpshufd $78, %xmm2, %xmm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 vpshufd $57, %xmm1, %xmm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 vpshufd $147, %xmm3, %xmm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 /* 0 = 0 + 5 , 15 = (15 ^ 0) >>> 16 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 12 | * 0 = 0 + 5, 15 = (15 ^ 0) >>> 8 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 7 * 1 = 1 + 6 , 12 = (12 ^ 1) >>> 16 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 12 | * 1 = 1 + 6, 12 = (12 ^ 1) >>> 8 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 7 * 2 = 2 + 7 , 13 = (13 ^ 2) >>> 16 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 12 | * 2 = 2 + 7, 13 = (13 ^ 2) >>> 8 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 7 * 3 = 3 + 4 , 14 = (14 ^ 3) >>> 16 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 12 | * 3 = 3 + 4, 14 = (14 ^ 3) >>> 8 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 7 */ CHACHA20_ROUND %xmm0, %xmm1, %xmm2, %xmm3, %xmm4, %r9, %r10 vpshufd $78, %xmm2, %xmm2 // {10 11 8 9} ==> {8 9 10 11} 01 00 11 10 vpshufd $147, %xmm1, %xmm1 // {5 6 7 4} ==> {4 5 6 7} 00 11 10 01 vpshufd $57, %xmm3, %xmm3 // {15 12 13 14} ==> {12 13 14 15} 10 01 00 11 decq %r8 jnz .Lchacha20_64_loop vpaddd %xmm10, %xmm0, %xmm0 vpaddd %xmm11, %xmm1, %xmm1 vpaddd %xmm12, %xmm2, %xmm2 vpaddd %xmm13, %xmm3, %xmm3 add $1, %r11d vpxor 0(IN), %xmm0, %xmm4 vpxor 16(IN), %xmm1, %xmm5 vpxor 32(IN), %xmm2, %xmm6 vpxor 48(IN), %xmm3, %xmm7 vmovdqu %xmm4, 0(OUT) vmovdqu %xmm5, 16(OUT) vmovdqu %xmm6, 32(OUT) vmovdqu %xmm7, 48(OUT) add $64, IN add $64, OUT mov %r11d, 48(%rdi) jmp .Lchacha20_end .Lchacha20_128_start: vbroadcasti128 (%rdi), %ymm0 // {0 1 2 3 0 1 2 3} vbroadcasti128 16(%rdi), %ymm1 // {4 5 6 7 4 5 6 7} vbroadcasti128 32(%rdi), %ymm2 // {8 9 10 11 8 9 10 11} vbroadcasti128 48(%rdi), %ymm3 // {12 13 14 15 12 13 14 15} vpaddd g_addOne(%rip), %ymm3, %ymm3 vmovdqa %ymm0, %ymm12 vmovdqa %ymm1, %ymm13 vmovdqa %ymm2, %ymm14 vmovdqa %ymm3, %ymm15 leaq g_ror16_128(%rip), %r9 leaq g_ror8_128(%rip), %r10 mov $10, %r8 .Lchacha20_128_loop: CHACHA20_ROUND %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %r9, %r10 vpshufd $78, %ymm2, %ymm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 vpshufd $57, %ymm1, %ymm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 vpshufd $147, %ymm3, %ymm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 CHACHA20_ROUND %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %r9, %r10 vpshufd $78, %ymm2, %ymm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 vpshufd $147, %ymm1, %ymm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 vpshufd $57, %ymm3, %ymm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 decq %r8 jnz .Lchacha20_128_loop vpaddd %ymm12, %ymm0, %ymm0 vpaddd %ymm13, %ymm1, %ymm1 vpaddd %ymm14, %ymm2, %ymm2 vpaddd %ymm15, %ymm3, %ymm3 vextracti128 $1, %ymm0, %xmm4 // ymm0 => {xmm0 xmm5} vextracti128 $1, %ymm1, %xmm5 // ymm1 => {xmm1 xmm6} vextracti128 $1, %ymm2, %xmm6 // ymm2 => {xmm2 xmm7} vextracti128 $1, %ymm3, %xmm7 // ymm3 => {xmm3 xmm8} WRITEBACK_64_AVX2 IN, OUT, %xmm0, %xmm1, %xmm2, %xmm3 add $2, %r11d WRITEBACK_64_AVX2 IN, OUT, %xmm4, %xmm5, %xmm6, %xmm7 mov %r11d, 48(%rdi) sub $128, %rcx jz .Lchacha20_end jmp .Lchacha20_start .Lchacha20_256_start: LOAD_STATE %xmm0, %xmm1, %xmm2, %xmm3, %rdi STATE_TO_MATRIX %xmm0, %xmm1, %xmm2, %xmm3, %xmm4, %xmm5, %xmm6, %xmm7, %xmm8, %xmm9, %xmm10, \ %xmm11, %xmm12, %xmm13, %xmm14, %xmm15, 0, 16, g_add4block(%rip) /* move xmm8~11 into stack for CHACHA20_LOOP encryption */ vmovdqa %xmm8, 256(%rsp) vmovdqa %xmm9, 256+16(%rsp) vmovdqa %xmm10, 256+32(%rsp) vmovdqa %xmm11, 256+48(%rsp) leaq g_ror16(%rip), %r9 leaq g_ror8(%rip), %r10 mov $10, %r8 .Lchacha20_256_loop: CHACHA20_LOOP %xmm0, %xmm1, %xmm2, %xmm3, %xmm4, %xmm5, %xmm6, %xmm7, %xmm8, %xmm9, %xmm10 \ %xmm11, %xmm12, %xmm13, %xmm14, %xmm15, 256, 16, %rsp, %r9, %r10 decq %r8 jnz .Lchacha20_256_loop /* xmm0~15: encrypt matrix 0 ~ 15*/ vmovdqa 256+32(%rsp), %xmm10 // rsp32: encrypt matrix xmm10 vmovdqa 256+48(%rsp), %xmm11 LASTADD_MATRIX %xmm0, %xmm1, %xmm2, %xmm3, %xmm4, %xmm5, %xmm6, %xmm7, %xmm8, %xmm9, %xmm10 \ %xmm11, %xmm12, %xmm13, %xmm14, %xmm15, 16 /* store xmm9, 10, 13, 14 in stack */ vmovdqa %xmm9, 256(%rsp) // rsp 0: encrypt matrix xmm9 vmovdqa %xmm10, 256+32(%rsp) // rsp32: encrypt matrix xmm9 vmovdqa %xmm13, 256+16(%rsp) // rsp16: encrypt matrix xmm13 vmovdqa %xmm14, 256+48(%rsp) // rsp48: encrypt matrix xmm14 MATRIX_TO_STATE %xmm0, %xmm1, %xmm2, %xmm3, %xmm9, %xmm10 // set state 0, 3, 9, 10 MATRIX_TO_STATE %xmm4, %xmm5, %xmm6, %xmm7, %xmm13, %xmm14 // set state 4, 7, 13, 14 vmovdqa 256(%rsp), %xmm5 vmovdqa 256+32(%rsp), %xmm6 vmovdqa %xmm9, 256(%rsp) vmovdqa %xmm10, 256+32(%rsp) MATRIX_TO_STATE %xmm8, %xmm5, %xmm6, %xmm11, %xmm1, %xmm2 // set state 8, 11, 1, 2 vmovdqa 256+16(%rsp), %xmm9 vmovdqa 256+48(%rsp), %xmm10 vmovdqa %xmm13, 256+16(%rsp) vmovdqa %xmm14, 256+48(%rsp) MATRIX_TO_STATE %xmm12, %xmm9, %xmm10, %xmm15, %xmm5, %xmm6 // set state 12, 15, 5, 6 vmovdqa 256(%rsp), %xmm9 // rsp 0: state 9 vmovdqa 256+32(%rsp), %xmm10 // rsp32: state 10 vmovdqa 256+16(%rsp), %xmm13 // rsp16: state 13 vmovdqa 256+48(%rsp), %xmm14 // rsp48: state 14 /* finish state calculation, now write result to output */ WRITEBACK_64_AVX2 IN, OUT, %xmm0, %xmm4, %xmm8, %xmm12 WRITEBACK_64_AVX2 IN, OUT, %xmm3, %xmm7, %xmm11, %xmm15 WRITEBACK_64_AVX2 IN, OUT, %xmm9, %xmm13, %xmm1, %xmm5 WRITEBACK_64_AVX2 IN, OUT, %xmm10, %xmm14, %xmm2, %xmm6 add $4, %r11d sub $256, %rcx mov %r11d, 48(%rdi) cmp $256, %rcx jz .Lchacha20_end jmp .Lchacha20_start .Lchacha20_512_start: LOAD_512_STATE %ymm0 %ymm1 %ymm2 %ymm3 %rdi STATE_TO_MATRIX %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %ymm5, %ymm6, %ymm7, %ymm8, %ymm9, \ %ymm10, %ymm11, %ymm12, %ymm13, %ymm14, %ymm15, 0, 32, g_add8block(%rip) jmp .Lchacha20_512_run .Lchacha20_512_start_cont: LOAD_MATRIX %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %ymm5, %ymm6, %ymm7, %ymm8, %ymm9, \ %ymm10, %ymm11, %ymm12, %ymm13, %ymm14, %ymm15, 0, 32, g_addsecond8block(%rip) .Lchacha20_512_run: /* move ymm8~11 into stack for CHACHA20_LOOP encryption */ vmovdqa %ymm8, 512(%rsp) vmovdqa %ymm9, 512+32(%rsp) vmovdqa %ymm10, 512+64(%rsp) vmovdqa %ymm11, 512+96(%rsp) leaq g_ror16_512(%rip), %r9 leaq g_ror8_512(%rip), %r10 mov $10, %r8 .align 32 .Lchacha20_512_loop: CHACHA20_LOOP %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %ymm5, %ymm6, %ymm7, %ymm8, %ymm9, %ymm10 \ %ymm11, %ymm12, %ymm13, %ymm14, %ymm15, 512, 32, %rsp, %r9, %r10 decq %r8 jnz .Lchacha20_512_loop /* ymm0~15: encrypt matrix 0 ~ 15*/ vmovdqa 512+64(%rsp), %ymm10 // rsp64: encrypt matrix ymm10 vmovdqu 512+96(%rsp), %ymm11 LASTADD_MATRIX %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %ymm5, %ymm6, %ymm7, %ymm8, %ymm9, %ymm10 \ %ymm11, %ymm12, %ymm13, %ymm14, %ymm15, 32 /* store matrix ymm9, 10, 13, 14 in stack */ vmovdqa %ymm9, 512(%rsp) // rsp 0: encrypt matrix ymm9 vmovdqu %ymm10, 512+32(%rsp) // rsp32: encrypt matrix ymm10 vmovdqa %ymm13, 512+64(%rsp) // rsp64: encrypt matrix ymm13 vmovdqu %ymm14, 512+96(%rsp) // rsp96: encrypt matrix ymm14 MATRIX_TO_STATE %ymm0, %ymm1, %ymm2, %ymm3, %ymm9, %ymm10 // set state 0, 3, 9, 10 MATRIX_TO_STATE %ymm4, %ymm5, %ymm6, %ymm7, %ymm13, %ymm14 // set state 4, 7, 13, 14 vmovdqu 512(%rsp), %ymm5 vmovdqa 512+32(%rsp), %ymm6 vmovdqu %ymm9, 512(%rsp) vmovdqa %ymm10, 512+32(%rsp) MATRIX_TO_STATE %ymm8, %ymm5, %ymm6, %ymm11, %ymm1, %ymm2 // set state 8, 11, 1, 2 vmovdqa 512+64(%rsp), %ymm9 vmovdqu 512+96(%rsp), %ymm10 vmovdqa %ymm13, 512+64(%rsp) vmovdqu %ymm14, 512+96(%rsp) MATRIX_TO_STATE %ymm12, %ymm9, %ymm10, %ymm15, %ymm5, %ymm6 // set state 12, 15, 5, 6 /* * {A0 A1 A2 A3 E0 E1 E2 E3} * {B0 B1 B2 B3 F0 F1 F2 F3} * {C0 C1 C2 C3 G0 G1 G2 G3} * {D0 D1 D2 D3 H0 H1 H2 H3} * ... * => * {A0 A1 A2 A3 B0 B1 B2 B3} * {C0 C1 C2 C3 D0 D1 D2 D3} * .... */ /* left half of ymm registers */ WRITE_BACK_512_L IN, OUT, %ymm0, %ymm4, %ymm8, %ymm12, %ymm3, %ymm7, %ymm11, %ymm15, %ymm9, %ymm10, %ymm13, %ymm14 add $256, IN add $256, OUT /* right half of ymm registers */ WRITE_BACK_512_R IN, OUT, %ymm0, %ymm4, %ymm8, %ymm12, %ymm3, %ymm7, %ymm11, %ymm15 sub $128, IN sub $128, OUT vmovdqa 512(%rsp), %ymm9 vmovdqu 512+32(%rsp), %ymm10 vmovdqa 512+64(%rsp), %ymm13 vmovdqu 512+96(%rsp), %ymm14 /* second left half of ymm registers */ WRITE_BACK_512_L IN, OUT, %ymm9, %ymm13, %ymm1, %ymm5, %ymm10, %ymm14, %ymm2, %ymm6, %ymm0, %ymm4, %ymm8, %ymm12 add $256, IN add $256, OUT /* second right half of ymm registers */ WRITE_BACK_512_R IN, OUT, %ymm9, %ymm13, %ymm1, %ymm5, %ymm10, %ymm14, %ymm2, %ymm6 add $128, IN add $128, OUT add $8, %r11d sub $512, %rcx mov %r11d, 48(%rdi) jz .Lchacha20_end cmp $512, %rcx jae .Lchacha20_512_start_cont jmp .Lchacha20_start .Lchacha20_end: /* clear sensitive info in stack */ vpxor %ymm0, %ymm0, %ymm0 xor %r11d, %r11d vmovdqa %ymm0, (%rsp) vmovdqa %ymm0, 32(%rsp) vmovdqa %ymm0, 64(%rsp) vmovdqa %ymm0, 96(%rsp) vmovdqa %ymm0, 128(%rsp) vmovdqa %ymm0, 160(%rsp) vmovdqa %ymm0, 192(%rsp) vmovdqa %ymm0, 224(%rsp) vmovdqa %ymm0, 256(%rsp) vmovdqa %ymm0, 288(%rsp) vmovdqa %ymm0, 320(%rsp) vmovdqa %ymm0, 352(%rsp) vmovdqa %ymm0, 384(%rsp) vmovdqa %ymm0, 416(%rsp) vmovdqa %ymm0, 448(%rsp) vmovdqa %ymm0, 480(%rsp) vmovdqa %ymm0, 512(%rsp) vmovdqa %ymm0, 512+32(%rsp) vmovdqa %ymm0, 512+64(%rsp) vmovdqa %ymm0, 512+96(%rsp) mov %rax, %rsp .cfi_endproc ret .size CHACHA20_Update,.-CHACHA20_Update #endif
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/asm/chacha20block_x8664_avx2.S
Unix Assembly
unknown
20,876
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 #include "chacha20_x8664_common.S" .text .align 64 g_ror16: .byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd .size g_ror16, .-g_ror16 .align 64 g_ror8: .byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe .size g_ror8, .-g_ror8 .align 64 g_ror16_128: .byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd, \ 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd .size g_ror16_128, .-g_ror16_128 .align 64 g_ror8_128: .byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe, \ 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe .size g_ror8_128, .-g_ror8_128 .align 64 g_addOne: .long 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0 .size g_addOne, .-g_addOne .align 64 g_add4block: .long 0, 1, 2, 3 .size g_add4block, .-g_add4block .align 64 g_addsecond4block: .long 4, 4, 4, 4 .size g_addsecond4block, .-g_addsecond4block .align 64 g_add8block: .long 0, 1, 2, 3, 4, 5, 6, 7 .size g_add8block, .-g_add8block .align 64 g_addsecond8block: .long 8, 8, 8, 8, 8, 8, 8, 8 .size g_addsecond8block, .-g_addsecond8block .align 64 g_add16block: .long 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 .size g_add16block, .-g_add16block .align 64 g_addsecond16block: .long 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, 16 .size g_addsecond16block, .-g_addsecond16block .set IN, %rsi .set OUT, %rdx /* * Processing 64 bytes: 4 x registers, number of instructions in a single loop: 21*2 = 42 * xmm0 ~ xmm3: * xmm0 {0, 1, 2, 3} * xmm1 {4, 5, 6, 7} * xmm2 {8, 9, 10, 11} * xmm3 {12, 13, 14, 15} * * Processing 128-256 bytes: 4 x registers, number of instructions in a single loop:30 * ymm0 ~ ymm3: * ymm0 {0, 1, 2, 3, 0, 1, 2, 3 } * ymm1 {4, 5, 6, 7, 4, 5, 6, 7 } * ymm2 {8, 9, 10, 11, 8, 9, 10, 11} * ymm3 {12, 13, 14, 15, 12, 13, 14, 15} * * Processing 512 bytes: y registers 0-15, 128 stack space and y registers 16-31,number of instructions *in a single loop:12*8 = 96 * Processing 1024 bytes: z registers 0-15, 256 stack space and z registers 16-31, number of instructions * in a single loop:12*8 = 96 * ymm0 ~ ymm15: * ymm0 {0, 0, 0, 0, 0, 0, 0, 0} * ymm1 {1, 1, 1, 1, 1, 1, 1, 1} * ymm2 {2, 2, 2, 2, 2, 2, 2, 2} * ymm3 {3, 3, 3, 3, 3, 3, 3, 3} * ...... * ymm15 {15, 15, 15, 15, 15, 15, 15, 15} * * zmm0 ~ zmm31: * zmm0 {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0} * zmm1 {1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1} * zmm2 {2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2} * zmm3 {3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3} * ... * zmm15 {15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15, 15} */ .macro CHACHA20_ROUND s0 s1 s2 s3 vpaddd \s1, \s0, \s0 vpxord \s0, \s3, \s3 vprold $16, \s3, \s3 vpaddd \s3, \s2, \s2 vpxord \s2, \s1, \s1 vprold $12, \s1, \s1 vpaddd \s1, \s0, \s0 vpxord \s0, \s3, \s3 vprold $8, \s3, \s3 vpaddd \s3, \s2, \s2 vpxord \s2, \s1, \s1 vprold $7, \s1, \s1 .endm /* convert y registers and write back */ .macro CONVERT_Y s0 s1 pos inpos outpos /* ymm16 => {xmm16, xmm17} */ vextracti32x4 \pos, \s0, %xmm16 vextracti32x4 \pos, \s1, %xmm17 vinserti32x4 $1, %xmm17, %ymm16, %ymm16 vpxord (IN), %ymm16, %ymm16 vmovdqu64 %ymm16, (OUT) add $32, \inpos add $32, \outpos .endm /* convert z registers and write back */ .macro CONVERT_Z s0 s1 s2 s3 pos inpos outpos /* zmm16 => {xmm16, xmm17, xmm18, xmm19} */ vextracti64x2 \pos, \s0, %xmm16 vextracti64x2 \pos, \s1, %xmm17 vextracti64x2 \pos, \s2, %xmm18 vextracti64x2 \pos, \s3, %xmm19 vinserti64x2 $1, %xmm17, %zmm16, %zmm16 vinserti64x2 $2, %xmm18, %zmm16, %zmm16 vinserti64x2 $3, %xmm19, %zmm16, %zmm16 vpxord (IN), %zmm16, %zmm16 vmovdqu64 %zmm16, (OUT) add $64, \inpos add $64, \outpos .endm /** * @Interconnection with the C interface:void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len); * @brief chacha20 algorithm * @param ctx [IN] Algorithm context, which is set by the C interface and transferred. * @param in [IN] Data to be encrypted * @param out [OUT] Data after encryption * @param len [IN] Encrypted length * esp cannot use 15 available ctx in out len * 16 registers are needed in one cycle, then * {0, 1, 4, 5, 8, 9, 12, 13} * {2, 3, 6, 7, 10, 11, 14, 15} **/ .globl CHACHA20_Update .type CHACHA20_Update,%function .align 64 CHACHA20_Update: .cfi_startproc mov 48(%rdi), %r11d mov %rsp, %r9 subq $2048,%rsp andq $-1024,%rsp .Lchacha20_start: cmp $1024, %rcx jae .Lchacha20_1024_start cmp $512, %rcx jae .Lchacha20_512_start cmp $256, %rcx jae .Lchacha20_256_start cmp $128, %rcx jae .Lchacha20_128_start cmp $64, %rcx jae .Lchacha20_64_start jmp .Lchacha20_end .Lchacha20_64_start: LOAD_STATE %xmm0, %xmm1, %xmm2, %xmm3, %rdi vmovdqa %xmm0, %xmm10 vmovdqa %xmm1, %xmm11 vmovdqa %xmm2, %xmm12 vmovdqa %xmm3, %xmm13 mov $10, %r8 .Lchacha20_64_loop: /* 0 = 0 + 4, 12 = (12 ^ 0) >>> 16 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 12 | * 0 = 0 + 4, 12 = (12 ^ 0) >>> 8 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 7 * 1 = 1 + 5, 13 = (13 ^ 1) >>> 16 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 12 | * 1 = 1 + 5, 13 = (13 ^ 1) >>> 8 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 7 * 2 = 2 + 6, 14 = (14 ^ 2) >>> 16 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 12 | * 2 = 2 + 6, 14 = (14 ^ 2) >>> 8 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 7 * 3 = 3 + 7, 15 = (15 ^ 3) >>> 16 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 12 | * 3 = 3 + 7 ,15 = (15 ^ 3) >>> 8 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 7 */ CHACHA20_ROUND %xmm0, %xmm1, %xmm2, %xmm3 vpshufd $78, %xmm2, %xmm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 vpshufd $57, %xmm1, %xmm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 vpshufd $147, %xmm3, %xmm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 /* 0 = 0 + 5 , 15 = (15 ^ 0) >>> 16 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 12 | * 0 = 0 + 5, 15 = (15 ^ 0) >>> 8 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 7 * 1 = 1 + 6 , 12 = (12 ^ 1) >>> 16 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 12 | * 1 = 1 + 6, 12 = (12 ^ 1) >>> 8 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 7 * 2 = 2 + 7 , 13 = (13 ^ 2) >>> 16 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 12 | * 2 = 2 + 7, 13 = (13 ^ 2) >>> 8 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 7 * 3 = 3 + 4 , 14 = (14 ^ 3) >>> 16 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 12 | * 3 = 3 + 4, 14 = (14 ^ 3) >>> 8 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 7 */ CHACHA20_ROUND %xmm0, %xmm1, %xmm2, %xmm3 vpshufd $78, %xmm2, %xmm2 // {10 11 8 9} ==> {8 9 10 11} 01 00 11 10 vpshufd $147, %xmm1, %xmm1 // {5 6 7 4} ==> {4 5 6 7} 00 11 10 01 vpshufd $57, %xmm3, %xmm3 // {15 12 13 14} ==> {12 13 14 15} 10 01 00 11 decq %r8 jnz .Lchacha20_64_loop vpaddd %xmm10, %xmm0, %xmm0 vpaddd %xmm11, %xmm1, %xmm1 vpaddd %xmm12, %xmm2, %xmm2 vpaddd %xmm13, %xmm3, %xmm3 add $1, %r11d WRITEBACK_64_AVX512 IN, OUT, %xmm0, %xmm1, %xmm2, %xmm3 mov %r11d, 48(%rdi) jmp .Lchacha20_end .Lchacha20_128_start: vbroadcasti128 (%rdi), %ymm0 // {0 1 2 3 0 1 2 3} vbroadcasti128 16(%rdi), %ymm1 // {4 5 6 7 4 5 6 7} vbroadcasti128 32(%rdi), %ymm2 // {8 9 10 11 8 9 10 11} vbroadcasti128 48(%rdi), %ymm3 // {12 13 14 15 12 13 14 15} vpaddd g_addOne(%rip), %ymm3, %ymm3 vmovdqa32 %ymm0, %ymm16 vmovdqa32 %ymm1, %ymm17 vmovdqa32 %ymm2, %ymm18 vmovdqa32 %ymm3, %ymm19 mov $10, %r8 .Lchacha20_128_loop: CHACHA20_ROUND %ymm0, %ymm1, %ymm2, %ymm3 vpshufd $78, %ymm2, %ymm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 vpshufd $57, %ymm1, %ymm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 vpshufd $147, %ymm3, %ymm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 CHACHA20_ROUND %ymm0, %ymm1, %ymm2, %ymm3 vpshufd $78, %ymm2, %ymm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 vpshufd $147, %ymm1, %ymm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 vpshufd $57, %ymm3, %ymm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 decq %r8 jnz .Lchacha20_128_loop vpaddd %ymm16, %ymm0, %ymm0 vpaddd %ymm17, %ymm1, %ymm1 vpaddd %ymm18, %ymm2, %ymm2 vpaddd %ymm19, %ymm3, %ymm3 vextracti32x4 $1, %ymm0, %xmm5 // ymm0 => {xmm0 xmm5} vextracti32x4 $1, %ymm1, %xmm6 // ymm1 => {xmm1 xmm6} vextracti32x4 $1, %ymm2, %xmm7 // ymm2 => {xmm2 xmm7} vextracti32x4 $1, %ymm3, %xmm8 // ymm3 => {xmm3 xmm8} WRITEBACK_64_AVX512 IN, OUT, %xmm0, %xmm1, %xmm2, %xmm3 WRITEBACK_64_AVX512 IN, OUT, %xmm5, %xmm6, %xmm7, %xmm8 add $2, %r11d sub $128, %rcx mov %r11d, 48(%rdi) jz .Lchacha20_end jmp .Lchacha20_start .Lchacha20_256_start: LOAD_1024_STATE %zmm0 %zmm1 %zmm2 %zmm3 %rdi vpaddd g_addOne(%rip), %zmm3, %zmm3 vmovdqa64 %zmm0, %zmm16 vmovdqa64 %zmm1, %zmm17 vmovdqa64 %zmm2, %zmm18 vmovdqa64 %zmm3, %zmm19 mov $10, %r8 .Lchacha20_256_loop: CHACHA20_ROUND %zmm0, %zmm1, %zmm2, %zmm3 vpshufd $78, %zmm2, %zmm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 vpshufd $57, %zmm1, %zmm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 vpshufd $147, %zmm3, %zmm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 CHACHA20_ROUND %zmm0, %zmm1, %zmm2, %zmm3 vpshufd $78, %zmm2, %zmm2 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 vpshufd $147, %zmm1, %zmm1 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 vpshufd $57, %zmm3, %zmm3 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 decq %r8 jnz .Lchacha20_256_loop vpaddd %zmm16, %zmm0, %zmm0 vpaddd %zmm17, %zmm1, %zmm1 vpaddd %zmm18, %zmm2, %zmm2 vpaddd %zmm19, %zmm3, %zmm3 vextracti64x2 $1, %zmm0, %xmm4 vextracti64x2 $1, %zmm1, %xmm5 vextracti64x2 $1, %zmm2, %xmm6 vextracti64x2 $1, %zmm3, %xmm7 vextracti64x2 $2, %zmm0, %xmm8 vextracti64x2 $2, %zmm1, %xmm9 vextracti64x2 $2, %zmm2, %xmm10 vextracti64x2 $2, %zmm3, %xmm11 vextracti64x2 $3, %zmm0, %xmm12 vextracti64x2 $3, %zmm1, %xmm13 vextracti64x2 $3, %zmm2, %xmm14 vextracti64x2 $3, %zmm3, %xmm15 WRITEBACK_64_AVX512 IN, OUT, %xmm0, %xmm1, %xmm2, %xmm3 WRITEBACK_64_AVX512 IN, OUT, %xmm4, %xmm5, %xmm6, %xmm7 WRITEBACK_64_AVX512 IN, OUT, %xmm8, %xmm9, %xmm10, %xmm11 WRITEBACK_64_AVX512 IN, OUT, %xmm12, %xmm13, %xmm14, %xmm15 add $4, %r11d sub $256, %rcx mov %r11d, 48(%rdi) jz .Lchacha20_end jmp .Lchacha20_start .Lchacha20_512_start: LOAD_512_STATE %ymm0, %ymm1, %ymm2, %ymm3, %rdi vpshufd $0b00000000, %ymm3, %ymm12 vpshufd $0b01010101, %ymm3, %ymm13 vpaddd g_add8block(%rip), %ymm12, %ymm12 // 0, 1, 2, 3, 4, 5, 6 ,7 vmovdqa32 %ymm12, %ymm28 vpshufd $0b10101010, %ymm3, %ymm14 vmovdqa32 %ymm13, %ymm29 vpshufd $0b11111111, %ymm3, %ymm15 vmovdqa32 %ymm14, %ymm30 vpshufd $0b00000000, %ymm2, %ymm8 vmovdqa32 %ymm15, %ymm31 vpshufd $0b01010101, %ymm2, %ymm9 vmovdqa32 %ymm8, %ymm24 vpshufd $0b10101010, %ymm2, %ymm10 vmovdqa32 %ymm9, %ymm25 vpshufd $0b11111111, %ymm2, %ymm11 vmovdqa32 %ymm10, %ymm26 vpshufd $0b00000000, %ymm1, %ymm4 vmovdqa32 %ymm11, %ymm27 vpshufd $0b01010101, %ymm1, %ymm5 vmovdqa32 %ymm4, %ymm20 vpshufd $0b10101010, %ymm1, %ymm6 vmovdqa32 %ymm5, %ymm21 vpshufd $0b11111111, %ymm1, %ymm7 vmovdqa32 %ymm6, %ymm22 vpshufd $0b11111111, %ymm0, %ymm3 vmovdqa32 %ymm7, %ymm23 vpshufd $0b10101010, %ymm0, %ymm2 vmovdqa32 %ymm3, %ymm19 vpshufd $0b01010101, %ymm0, %ymm1 vmovdqa32 %ymm2, %ymm18 vpshufd $0b00000000, %ymm0, %ymm0 vmovdqa32 %ymm1, %ymm17 vmovdqa32 %ymm0, %ymm16 mov $10, %r8 .Lchacha20_512_loop: CHACHA20_LOOP_AVX512 %ymm0, %ymm1, %ymm2, %ymm3, %ymm4, %ymm5, %ymm6, %ymm7, %ymm8, %ymm9, \ %ymm10, %ymm11, %ymm12, %ymm13, %ymm14, %ymm15 decq %r8 jnz .Lchacha20_512_loop /* ymm16~31: original matrix */ vpaddd %ymm16, %ymm0, %ymm0 vpaddd %ymm17, %ymm1, %ymm1 vpaddd %ymm18, %ymm2, %ymm2 vpaddd %ymm19, %ymm3, %ymm3 vpaddd %ymm20, %ymm4, %ymm4 vpaddd %ymm21, %ymm5, %ymm5 vpaddd %ymm22, %ymm6, %ymm6 vpaddd %ymm23, %ymm7, %ymm7 vpaddd %ymm24, %ymm8, %ymm8 vpaddd %ymm25, %ymm9, %ymm9 vpaddd %ymm26, %ymm10, %ymm10 vpaddd %ymm27, %ymm11, %ymm11 vpaddd %ymm28, %ymm12, %ymm12 vpaddd %ymm29, %ymm13, %ymm13 vpaddd %ymm30, %ymm14, %ymm14 vpaddd %ymm31, %ymm15, %ymm15 MATRIX_TO_STATE %ymm0, %ymm1, %ymm2, %ymm3, %ymm20, %ymm21 // set state 0, 3, 9, 10 MATRIX_TO_STATE %ymm4, %ymm5, %ymm6, %ymm7, %ymm22, %ymm23 // set state 4, 7, 13, 14 MATRIX_TO_STATE %ymm8, %ymm9, %ymm10, %ymm11, %ymm1, %ymm2 // set state 8, 11, 1, 2 MATRIX_TO_STATE %ymm12, %ymm13, %ymm14, %ymm15, %ymm5, %ymm6 // set state 12, 15, 5, 6 /* * {A0 A1 A2 A3 E0 E1 E2 E3} * {B0 B1 B2 B3 F0 F1 F2 F3} * {C0 C1 C2 C3 G0 G1 G2 G3} * {D0 D1 D2 D3 H0 H1 H2 H3} * ... * => * {A0 A1 A2 A3 B0 B1 B2 B3} * {C0 C1 C2 C3 D0 D1 D2 D3} * .... */ CONVERT_Y %ymm0, %ymm4, $0 IN OUT CONVERT_Y %ymm8, %ymm12, $0 IN OUT CONVERT_Y %ymm3, %ymm7, $0 IN OUT CONVERT_Y %ymm11, %ymm15, $0 IN OUT CONVERT_Y %ymm20, %ymm22, $0 IN OUT CONVERT_Y %ymm1, %ymm5, $0 IN OUT CONVERT_Y %ymm21, %ymm23, $0 IN OUT CONVERT_Y %ymm2, %ymm6, $0 IN OUT CONVERT_Y %ymm0, %ymm4, $1 IN OUT CONVERT_Y %ymm8, %ymm12, $1 IN OUT CONVERT_Y %ymm3, %ymm7, $1 IN OUT CONVERT_Y %ymm11, %ymm15, $1 IN OUT CONVERT_Y %ymm20, %ymm22, $1 IN OUT CONVERT_Y %ymm1, %ymm5, $1 IN OUT CONVERT_Y %ymm21, %ymm23, $1 IN OUT CONVERT_Y %ymm2, %ymm6, $1 IN OUT add $8, %r11d sub $512, %rcx mov %r11d, 48(%rdi) jz .Lchacha20_end jmp .Lchacha20_start .Lchacha20_1024_start: LOAD_1024_STATE %zmm0 %zmm1 %zmm2 %zmm3 %rdi STATE_TO_MATRIX_Z_AVX512 %zmm0, %zmm16, %zmm17, %zmm18, %zmm19 STATE_TO_MATRIX_Z_AVX512 %zmm1, %zmm20, %zmm21, %zmm22, %zmm23 STATE_TO_MATRIX_Z_AVX512 %zmm2, %zmm24, %zmm25, %zmm26, %zmm27 STATE_TO_MATRIX_Z_AVX512 %zmm3, %zmm28, %zmm29, %zmm30, %zmm31 vpaddd g_add16block(%rip), %zmm28, %zmm28 vmovdqa64 %zmm16, %zmm0 vmovdqa64 %zmm17, %zmm1 vmovdqa64 %zmm18, %zmm2 vmovdqa64 %zmm19, %zmm3 vmovdqa64 %zmm20, %zmm4 vmovdqa64 %zmm21, %zmm5 vmovdqa64 %zmm22, %zmm6 vmovdqa64 %zmm23, %zmm7 vmovdqa64 %zmm24, %zmm8 vmovdqa64 %zmm25, %zmm9 vmovdqa64 %zmm26, %zmm10 vmovdqa64 %zmm27, %zmm11 vmovdqa64 %zmm28, %zmm12 vmovdqa64 %zmm29, %zmm13 vmovdqa64 %zmm30, %zmm14 vmovdqa64 %zmm31, %zmm15 mov $10, %r8 jmp .Lchacha20_1024_loop .Lchacha20_1024_start_cont: vmovdqa32 %zmm16, %zmm0 vmovdqa32 %zmm17, %zmm1 vmovdqa32 %zmm18, %zmm2 vmovdqa32 %zmm19, %zmm3 vmovdqa32 %zmm20, %zmm4 vmovdqa32 %zmm21, %zmm5 vmovdqa32 %zmm22, %zmm6 vmovdqa32 %zmm23, %zmm7 vmovdqa32 %zmm24, %zmm8 vmovdqa32 %zmm25, %zmm9 vmovdqa32 %zmm26, %zmm10 vmovdqa32 %zmm27, %zmm11 vmovdqa32 %zmm28, %zmm12 vmovdqa32 %zmm29, %zmm13 vpaddd g_addsecond16block(%rip), %zmm12, %zmm12 // add 8, 8, 8, 8, 8, 8, 8, 8 or 4, 4, 4, 4 vmovdqa32 %zmm30, %zmm14 vmovdqa32 %zmm31, %zmm15 vmovdqa32 %zmm12, %zmm28 mov $10, %r8 .Lchacha20_1024_loop: CHACHA20_LOOP_AVX512 %zmm0, %zmm1, %zmm2, %zmm3, %zmm4, %zmm5, %zmm6, %zmm7, %zmm8, %zmm9, \ %zmm10, %zmm11, %zmm12, %zmm13, %zmm14, %zmm15 decq %r8 jnz .Lchacha20_1024_loop vpaddd %zmm16, %zmm0, %zmm0 vpaddd %zmm17, %zmm1, %zmm1 vpaddd %zmm18, %zmm2, %zmm2 vpaddd %zmm19, %zmm3, %zmm3 vpaddd %zmm20, %zmm4, %zmm4 vpaddd %zmm21, %zmm5, %zmm5 vpaddd %zmm22, %zmm6, %zmm6 vpaddd %zmm23, %zmm7, %zmm7 vpaddd %zmm24, %zmm8, %zmm8 vpaddd %zmm25, %zmm9, %zmm9 vpaddd %zmm26, %zmm10, %zmm10 vpaddd %zmm27, %zmm11, %zmm11 vpaddd %zmm28, %zmm12, %zmm12 vpaddd %zmm29, %zmm13, %zmm13 vpaddd %zmm30, %zmm14, %zmm14 vpaddd %zmm31, %zmm15, %zmm15 /* store matrix 16, 17, 18, 19 in stack */ vmovdqa64 %zmm16, (%rsp) vmovdqa64 %zmm17, 64(%rsp) vmovdqa64 %zmm18, 128(%rsp) vmovdqa64 %zmm19, 192(%rsp) /* store matrix 9, 10, 13, 14 in zmm16, 17, 18, 19 */ vmovdqa64 %zmm9, %zmm16 // zmm16: encrypt matrix zmm9 vmovdqa64 %zmm10, %zmm17 // zmm17: encrypt matrix zmm10 vmovdqa64 %zmm13, %zmm18 // zmm18: encrypt matrix zmm13 vmovdqa64 %zmm14, %zmm19 // zmm19: encrypt matrix zmm14 /* zmm0~15: encrypt matrix 0 ~ 15*/ MATRIX_TO_STATE %zmm0, %zmm1, %zmm2, %zmm3, %zmm9, %zmm10 // set state 0, 3, 9, 10 MATRIX_TO_STATE %zmm4, %zmm5, %zmm6, %zmm7, %zmm13, %zmm14 // set state 4, 7, 13, 14 MATRIX_TO_STATE %zmm8, %zmm16, %zmm17, %zmm11, %zmm1, %zmm2 // set state 8, 11, 1, 2 MATRIX_TO_STATE %zmm12, %zmm18, %zmm19, %zmm15, %zmm5, %zmm6 // set state 12, 15, 5, 6 /* * {A0 A1 A2 A3 E0 E1 E2 E3 I0 I1 I2 I3 M0 M1 M2 M3} * {B0 B1 B2 B3 F0 F1 F2 F3 J0 J1 J2 J3 N0 N1 N2 N3} * {C0 C1 C2 C3 G0 G1 G2 G3 K0 K1 K2 K3 O0 O1 O2 O3} * {D0 D1 D2 D3 H0 H1 H2 H3 L0 L1 L2 L3 P0 P1 P2 P3} * ... * => * {A0 A1 A2 A3 B0 B1 B2 B3 C0 C1 C2 C3 D0 D1 D2 D3} * {E0 E1 E2 E3 F0 F1 F2 F3 G0 G1 G2 G3 H0 H1 H2 H3} * {I0 I1 I2 I3 J0 J1 J2 J3 K0 K1 K2 K3 L0 L1 L2 L3} * .... */ CONVERT_Z %zmm0, %zmm4, %zmm8, %zmm12, $0 IN OUT CONVERT_Z %zmm3, %zmm7, %zmm11, %zmm15, $0 IN OUT CONVERT_Z %zmm9, %zmm13, %zmm1, %zmm5, $0 IN OUT CONVERT_Z %zmm10, %zmm14, %zmm2, %zmm6, $0 IN OUT CONVERT_Z %zmm0, %zmm4, %zmm8, %zmm12, $1 IN OUT CONVERT_Z %zmm3, %zmm7, %zmm11, %zmm15, $1 IN OUT CONVERT_Z %zmm9, %zmm13, %zmm1, %zmm5, $1 IN OUT CONVERT_Z %zmm10, %zmm14, %zmm2, %zmm6, $1 IN OUT CONVERT_Z %zmm0, %zmm4, %zmm8, %zmm12, $2 IN OUT CONVERT_Z %zmm3, %zmm7, %zmm11, %zmm15, $2 IN OUT CONVERT_Z %zmm9, %zmm13, %zmm1, %zmm5, $2 IN OUT CONVERT_Z %zmm10, %zmm14, %zmm2, %zmm6, $2 IN OUT CONVERT_Z %zmm0, %zmm4, %zmm8, %zmm12, $3 IN OUT CONVERT_Z %zmm3, %zmm7, %zmm11, %zmm15, $3 IN OUT CONVERT_Z %zmm9, %zmm13, %zmm1, %zmm5, $3 IN OUT CONVERT_Z %zmm10, %zmm14, %zmm2, %zmm6, $3 IN OUT /* store zmm16~19 in stack */ vmovdqa64 (%rsp), %zmm16 vmovdqa64 64(%rsp), %zmm17 vmovdqa64 128(%rsp), %zmm18 vmovdqa64 192(%rsp), %zmm19 add $16, %r11d sub $1024, %rcx mov %r11d, 48(%rdi) jz .Lchacha20_clear cmp $1024, %rcx jae .Lchacha20_1024_start_cont jmp .Lchacha20_start .Lchacha20_clear: /* clear sensitive info in stack */ vpxord %zmm0, %zmm0, %zmm0 vmovdqa64 %zmm0, (%rsp) vmovdqa64 %zmm0, 64(%rsp) vmovdqa64 %zmm0, 128(%rsp) vmovdqa64 %zmm0, 192(%rsp) .Lchacha20_end: xor %r11d, %r11d mov %r9, %rsp .cfi_endproc ret .size CHACHA20_Update,.-CHACHA20_Update #endif
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/asm/chacha20block_x8664_avx512.S
Unix Assembly
unknown
21,249
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 .text .LAndBlock: .long 1, 0, 0, 0 .LRor16: .byte 0x2,0x3,0x0,0x1, 0x6,0x7,0x4,0x5, 0xa,0xb,0x8,0x9, 0xe,0xf,0xc,0xd .LRor8: .byte 0x3,0x0,0x1,0x2, 0x7,0x4,0x5,0x6, 0xb,0x8,0x9,0xa, 0xf,0xc,0xd,0xe .set IN, %r9 .set OUT, %r10 /* Original State */ .set O00, %xmm12 .set O01, %xmm13 .set O02, %xmm14 .set O03, %xmm15 /* State 0 */ .set S00, %xmm0 // LINE 0 STATE 0 .set S01, %xmm1 // LINE 1 STATE 0 .set S02, %xmm2 // LINE 2 STATE 0 .set S03, %xmm3 // LINE 3 STATE 0 /* State 1 */ .set S10, %xmm5 // LINE 0 STATE 1 .set S11, %xmm6 // LINE 1 STATE 1 .set S12, %xmm7 // LINE 2 STATE 1 .set S13, %xmm8 // LINE 3 STATE 1 .macro CHACHA20_ROUND S0 S1 S2 S3 CUR paddd \S1, \S0 pxor \S0, \S3 pshufb .LRor16(%rip), \S3 paddd \S3, \S2 pxor \S2, \S1 movdqa \S1, \CUR psrld $20, \S1 pslld $12, \CUR por \CUR, \S1 paddd \S1, \S0 pxor \S0, \S3 pshufb .LRor8(%rip), \S3 paddd \S3, \S2 pxor \S2, \S1 movdqa \S1, \CUR psrld $25, \S1 pslld $7, \CUR por \CUR, \S1 .endm /* QUARTERROUND for two states */ .macro CHACHA20_2_ROUND S0 S1 S2 S3 CUR S4 S5 S6 S7 CUR1 paddd \S1, \S0 pxor \S0, \S3 pshufb .LRor16(%rip), \S3 paddd \S3, \S2 pxor \S2, \S1 movdqa \S1, \CUR psrld $20, \S1 pslld $12, \CUR por \CUR, \S1 paddd \S1, \S0 pxor \S0, \S3 pshufb .LRor8(%rip), \S3 paddd \S3, \S2 pxor \S2, \S1 movdqa \S1, \CUR psrld $25, \S1 pslld $7, \CUR por \CUR, \S1 paddd \S5, \S4 pxor \S4, \S7 pshufb .LRor16(%rip), \S7 paddd \S7, \S6 pxor \S6, \S5 movdqa \S5, \CUR1 psrld $20, \S5 pslld $12, \CUR1 por \CUR1, \S5 paddd \S5, \S4 pxor \S4, \S7 pshufb .LRor8(%rip), \S7 paddd \S7, \S6 pxor \S6, \S5 movdqa \S5, \CUR1 psrld $25, \S5 pslld $7, \CUR1 por \CUR1, \S5 .endm /* final add & xor for 64 bytes */ .macro WRITE_BACK_64 IN_POS OUT_POS paddd O00, S00 paddd O01, S01 paddd O02, S02 paddd O03, S03 movdqu (\IN_POS), %xmm4 // get input movdqu 16(\IN_POS), %xmm9 movdqu 32(\IN_POS), %xmm10 movdqu 48(\IN_POS), %xmm11 pxor %xmm4, S00 pxor %xmm9, S01 pxor %xmm10, S02 pxor %xmm11, S03 movdqu S00, (\OUT_POS) // write back output movdqu S01, 16(\OUT_POS) movdqu S02, 32(\OUT_POS) movdqu S03, 48(\OUT_POS) .endm /* final add & xor for 128 bytes */ .macro WRITE_BACK_128 IN_POS OUT_POS paddd O00, S00 // state 0 + origin state 0 paddd O01, S01 paddd O02, S02 paddd O03, S03 pinsrd $0, %r11d, O03 // change Original state 0 to Original state 1 paddd O00, S10 // state 1 + origin state 1 paddd O01, S11 paddd O02, S12 paddd O03, S13 movdqu (\IN_POS), %xmm4 // get input 0 movdqu 16(\IN_POS), %xmm9 movdqu 32(\IN_POS), %xmm10 movdqu 48(\IN_POS), %xmm11 pxor %xmm4, S00 // input 0 ^ state 0 pxor %xmm9, S01 pxor %xmm10, S02 pxor %xmm11, S03 movdqu S00, (\OUT_POS) // write back to output 0 movdqu S01, 16(\OUT_POS) movdqu S02, 32(\OUT_POS) movdqu S03, 48(\OUT_POS) movdqu 64(\IN_POS), %xmm4 // get input 1 movdqu 80(\IN_POS), %xmm9 movdqu 96(\IN_POS), %xmm10 movdqu 112(\IN_POS), %xmm11 pxor %xmm4, S10 // input 1 ^ state 1 pxor %xmm9, S11 pxor %xmm10, S12 pxor %xmm11, S13 movdqu S10, 64(\OUT_POS) // write back to output 1 movdqu S11, 80(\OUT_POS) movdqu S12, 96(\OUT_POS) movdqu S13, 112(\OUT_POS) .endm .macro GENERATE_1_STATE add $1, %r11d pinsrd $0, %r11d, O03 movdqu O00, S00 // set state 0 movdqu O01, S01 movdqu O02, S02 movdqu O03, S03 .endm .macro GENERATE_2_STATE add $1, %r11d pinsrd $0, %r11d, O03 movdqu O00, S00 // set state 0 movdqu O01, S01 movdqu O02, S02 movdqu O03, S03 movdqu O00, S10 // set state 1 movdqu O01, S11 movdqu O02, S12 movdqu O03, S13 add $1, %r11d pinsrd $0, %r11d, S13 .endm /* * Processing 64 bytes: 4 xmm registers * xmm0 ~ xmm3: * xmm0 {0, 1, 2, 3} * xmm1 {4, 5, 6, 7} * xmm2 {8, 9, 10, 11} * xmm3 {12, 13, 14, 15} * * Processing 128 bytes: 8 xmm registers * xmm0 ~ xmm8: * xmm0 {0, 1, 2, 3} xmm5 {0, 1, 2, 3} * xmm1 {4, 5, 6, 7} xmm6 {4, 5, 6, 7} * xmm2 {8, 9, 10, 11} xmm7 {8, 9, 10, 11} * xmm3 {12, 13, 14, 15} xmm8 {12, 13, 14, 15} * * Processing 256 bytes: 16 xmm registers * xmm0 ~ xmm15: * xmm0 {0, 0, 0, 0} * xmm1 {1, 2, 2, 2} * xmm2 {3, 3, 3, 3} * xmm3 {4, 4, 4, 4} * ... * xmm15 {15, 15, 15, 15} * * Processing 512 bytes: 16 xmm registers * ymm0 ~ ymm15: * ymm0 {0, 0, 0, 0} * ymm1 {1, 2, 2, 2} * ymm2 {3, 3, 3, 3} * ymm3 {4, 4, 4, 4} * ... * ymm15 {15, 15, 15, 15} * */ /** * @Interconnection with the C interface:void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len); * @brief chacha20 algorithm * @param ctx [IN] Algorithm context, which is set by the C interface and transferred. * @param in [IN] Data to be encrypted * @param out [OUT] Data after encryption * @param len [IN] Encrypted length * esp cannot use 15 available ctx in out len * 16 registers are needed in one cycle, then * {0, 1, 4, 5, 8, 9, 12, 13} * {2, 3, 6, 7, 10, 11, 14, 15} **/ .globl CHACHA20_Update .type CHACHA20_Update,%function .align 64 CHACHA20_Update: .cfi_startproc push %r12 mov %rcx, %r12 mov 48(%rdi), %r11d mov %rsi, IN mov %rdx, OUT movdqu (%rdi), O00 // state[0-3] movdqu 16(%rdi), O01 // state[4-7] movdqu 32(%rdi), O02 // state[8-11] movdqu 48(%rdi), O03 // state[12-15] sub $1, %r11d .LChaCha20_start: cmp $128, %r12 jae .LChaCha20_128_start cmp $64, %r12 jae .LChaCha20_64_start jmp .LChaCha20_end .LChaCha20_64_start: GENERATE_1_STATE mov $10, %r8 .LChaCha20_64_loop: sub $1, %r8 /* 0 = 0 + 4, 12 = (12 ^ 0) >>> 16 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 12 | 0 = 0 + 4, 12 = (12 ^ 0) >>> 8 | 8 = 8 + 12, 4 = (4 ^ 8) >>> 7 */ /* 1 = 1 + 5, 13 = (13 ^ 1) >>> 16 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 12 | 1 = 1 + 5, 13 = (13 ^ 1) >>> 8 | 9 = 9 + 13, 5 = (5 ^ 9) >>> 7 */ /* 2 = 2 + 6, 14 = (14 ^ 2) >>> 16 | 10 = 10 + 14, 6 = (6 ^ 10)>>> 12 | 2 = 2 + 6, 14 = (14 ^ 2) >>> 8 | 10 =10+ 14, 6 = (6 ^ 10)>>> 7 */ /* 3 = 3 + 7, 15 = (15 ^ 3) >>> 16 | 11 = 11 + 15, 7 = (7 ^ 11)>>> 12 | 3 = 3 + 7 ,15 = (15 ^ 3) >>> 8 | 11 =11+ 15, 7 = (7 ^ 11)>>> 7 */ CHACHA20_ROUND S00 S01 S02 S03 %xmm4 pshufd $78, S02, S02 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 pshufd $57, S01, S01 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 pshufd $147, S03, S03 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 /* 0 = 0 + 5 , 15 = (15 ^ 0) >>> 16 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 12 | 0 = 0 + 5, 15 = (15 ^ 0) >>> 8 | 10 = 10 + 15, 5 = (5 ^ 10) >>> 7 */ /* 1 = 1 + 6 , 12 = (12 ^ 1) >>> 16 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 12 | 1 = 1 + 6, 12 = (12 ^ 1) >>> 8 | 11 = 11 + 12, 6 = (6 ^ 11) >>> 7 */ /* 2 = 2 + 7 , 13 = (13 ^ 2) >>> 16 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 12 | 2 = 2 + 7, 13 = (13 ^ 2) >>> 8 | 8 = 8 + 13, 7 = (7 ^ 8)>>> 7 */ /* 3 = 3 + 4 , 14 = (14 ^ 3) >>> 16 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 12 | 3 = 3 + 4, 14 = (14 ^ 3) >>> 8 | 9 = 9 + 14, 4 = (4 ^ 9)>>> 7 */ CHACHA20_ROUND S00 S01 S02 S03 %xmm4 pshufd $78, S02, S02 // {10 11 8 9} ==> {8 9 10 11} 01 00 11 10 pshufd $147, S01, S01 // {5 6 7 4} ==> {4 5 6 7} 00 11 10 01 pshufd $57, S03, S03 // {15 12 13 14} ==> {12 13 14 15} 10 01 00 11 jnz .LChaCha20_64_loop WRITE_BACK_64 IN OUT add $64, IN add $64, OUT sub $64, %r12 jmp .LChaCha20_start .LChaCha20_128_start: GENERATE_2_STATE mov $10, %r8 .LChaCha20_128_loop: CHACHA20_2_ROUND S00 S01 S02 S03 %xmm4 S10 S11 S12 S13 %xmm9 pshufd $78, S02, S02 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 pshufd $57, S01, S01 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 pshufd $147, S03, S03 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 pshufd $78, S12, S12 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 pshufd $57, S11, S11 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 pshufd $147, S13, S13 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 CHACHA20_2_ROUND S00 S01 S02 S03 %xmm4 S10 S11 S12 S13 %xmm9 pshufd $78, S02, S02 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 pshufd $147, S01, S01 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 pshufd $57, S03, S03 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 pshufd $78, S12, S12 // {8 9 10 11} ==> {10 11 8 9} 01 00 11 10 pshufd $147, S11, S11 // {4 5 6 7} ==> {5 6 7 4} 00 11 10 01 pshufd $57, S13, S13 // {12 13 14 15} ==> {15 12 13 14} 10 01 00 11 sub $1, %r8 jnz .LChaCha20_128_loop WRITE_BACK_128 IN OUT add $128, IN add $128, OUT sub $128, %r12 jmp .LChaCha20_start .LChaCha20_end: add $1, %r11d mov %r11d, 48(%rdi) pop %r12 ret .cfi_endproc .size CHACHA20_Update,.-CHACHA20_Update #endif
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/asm/chachablock_x86_AVX2.S
Unix Assembly
unknown
10,613
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 #include "securec.h" #include "bsl_err_internal.h" #include "crypt_utils.h" #include "crypt_errno.h" #include "crypt_chacha20.h" #include "chacha20_local.h" #define KEYSET 0x01 #define NONCESET 0x02 // RFC7539-2.1 #define QUARTER(a, b, c, d) \ do { \ (a) += (b); (d) ^= (a); (d) = ROTL32((d), 16); \ (c) += (d); (b) ^= (c); (b) = ROTL32((b), 12); \ (a) += (b); (d) ^= (a); (d) = ROTL32((d), 8); \ (c) += (d); (b) ^= (c); (b) = ROTL32((b), 7); \ } while (0) #define QUARTERROUND(state, a, b, c, d) QUARTER((state)[(a)], (state)[(b)], (state)[(c)], (state)[(d)]) int32_t CRYPT_CHACHA20_SetKey(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *key, uint32_t keyLen) { if (ctx == NULL || key == NULL || keyLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (keyLen != CHACHA20_KEYLEN) { BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_KEYLEN_ERROR); return CRYPT_CHACHA20_KEYLEN_ERROR; } /** * RFC7539-2.3 * cccccccc cccccccc cccccccc cccccccc * kkkkkkkk kkkkkkkk kkkkkkkk kkkkkkkk * kkkkkkkk kkkkkkkk kkkkkkkk kkkkkkkk * bbbbbbbb nnnnnnnn nnnnnnnn nnnnnnnn */ // The first four words (0-3) are constants: 0x61707865, 0x3320646e, 0x79622d32, 0x6b206574 ctx->state[0] = 0x61707865; ctx->state[1] = 0x3320646e; ctx->state[2] = 0x79622d32; ctx->state[3] = 0x6b206574; /** * The next eight words (4-11) are taken from the 256-bit key by * reading the bytes in little-endian order, in 4-byte chunks. */ ctx->state[4] = GET_UINT32_LE(key, 0); ctx->state[5] = GET_UINT32_LE(key, 4); ctx->state[6] = GET_UINT32_LE(key, 8); ctx->state[7] = GET_UINT32_LE(key, 12); ctx->state[8] = GET_UINT32_LE(key, 16); ctx->state[9] = GET_UINT32_LE(key, 20); ctx->state[10] = GET_UINT32_LE(key, 24); ctx->state[11] = GET_UINT32_LE(key, 28); // Word 12 is a block counter // RFC7539-2.4: It makes sense to use one if we use the zero block ctx->state[12] = 1; ctx->set |= KEYSET; ctx->lastLen = 0; return CRYPT_SUCCESS; } static int32_t CRYPT_CHACHA20_SetNonce(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *nonce, uint32_t nonceLen) { // RFC7539-2.3 if (ctx == NULL || nonce == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (nonceLen != CHACHA20_NONCELEN) { BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_NONCELEN_ERROR); return CRYPT_CHACHA20_NONCELEN_ERROR; } /** * Words 13-15 are a nonce, which should not be repeated for the same * key. The 13th word is the first 32 bits of the input nonce taken * as a little-endian integer, while the 15th word is the last 32 * bits. */ ctx->state[13] = GET_UINT32_LE(nonce, 0); ctx->state[14] = GET_UINT32_LE(nonce, 4); ctx->state[15] = GET_UINT32_LE(nonce, 8); ctx->set |= NONCESET; ctx->lastLen = 0; return CRYPT_SUCCESS; } // Little-endian data input static int32_t CRYPT_CHACHA20_SetCount(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *cnt, uint32_t cntLen) { if (ctx == NULL || cnt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (cntLen != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_COUNTLEN_ERROR); return CRYPT_CHACHA20_COUNTLEN_ERROR; } /** * RFC7539-2.4 * This can be set to any number, but will * usually be zero or one. It makes sense to use one if we use the * zero block for something else, such as generating a one-time * authenticator key as part of an AEAD algorithm */ ctx->state[12] = GET_UINT32_LE((uintptr_t)cnt, 0); ctx->lastLen = 0; return CRYPT_SUCCESS; } void CHACHA20_Block(CRYPT_CHACHA20_Ctx *ctx) { uint32_t i; // The length defined by ctx->last.c is the same as that defined by ctx->state. // Therefore, the returned value is not out of range. (void)memcpy_s(ctx->last.c, CHACHA20_STATEBYTES, ctx->state, sizeof(ctx->state)); /* RFC7539-2.3 These are 20 round in this function */ for (i = 0; i < 10; i++) { /* column round */ QUARTERROUND(ctx->last.c, 0, 4, 8, 12); QUARTERROUND(ctx->last.c, 1, 5, 9, 13); QUARTERROUND(ctx->last.c, 2, 6, 10, 14); QUARTERROUND(ctx->last.c, 3, 7, 11, 15); /* diagonal round */ QUARTERROUND(ctx->last.c, 0, 5, 10, 15); QUARTERROUND(ctx->last.c, 1, 6, 11, 12); QUARTERROUND(ctx->last.c, 2, 7, 8, 13); QUARTERROUND(ctx->last.c, 3, 4, 9, 14); } /* Reference from rfc 7539, At the end of 20 rounds (or 10 iterations of the above list), * we add the original input words to the output words */ for (i = 0; i < CHACHA20_STATESIZE; i++) { ctx->last.c[i] += ctx->state[i]; ctx->last.c[i] = CRYPT_HTOLE32(ctx->last.c[i]); } ctx->state[12]++; } int32_t CRYPT_CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { if (ctx == NULL || out == NULL || in == NULL || len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((ctx->set & KEYSET) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_NO_KEYINFO); return CRYPT_CHACHA20_NO_KEYINFO; } if ((ctx->set & NONCESET) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_NO_NONCEINFO); return CRYPT_CHACHA20_NO_NONCEINFO; } uint32_t i; const uint8_t *offIn = in; uint8_t *offOut = out; uint32_t tLen = len; if (ctx->lastLen != 0) { // has remaining data during the last processing uint32_t num = (tLen < ctx->lastLen) ? tLen : ctx->lastLen; uint8_t *tLast = ctx->last.u + CHACHA20_STATEBYTES - ctx->lastLen; // offset for (i = 0; i < num; i++) { offOut[i] = tLast[i] ^ offIn[i]; } offIn += num; offOut += num; tLen -= num; ctx->lastLen -= num; } if (tLen >= CHACHA20_STATEBYTES) { // which is greater than or equal to an integer multiple of 64 bytes CHACHA20_Update(ctx, offIn, offOut, tLen); // processes data that is an integer multiple of 64 bytes uint32_t vLen = tLen - (tLen & 0x3f); // 0x3f = %CHACHA20_STATEBYTES offIn += vLen; offOut += vLen; tLen -= vLen; } // Process the remaining data if (tLen > 0) { CHACHA20_Block(ctx); uint32_t t = tLen & 0xf8; // processing length is a multiple of 8 if (t != 0) { DATA64_XOR(ctx->last.u, offIn, offOut, t); } for (i = t; i < tLen; i++) { offOut[i] = ctx->last.u[i] ^ offIn[i]; } ctx->lastLen = CHACHA20_STATEBYTES - tLen; } return CRYPT_SUCCESS; } int32_t CRYPT_CHACHA20_Ctrl(CRYPT_CHACHA20_Ctx *ctx, int32_t opt, void *val, uint32_t len) { switch (opt) { case CRYPT_CTRL_SET_IV: // in chacha20_poly1305 mode, the configured IV is the nonce of chacha20. /** * RFC_7539-2.8.1 * chacha20_aead_encrypt(aad, key, iv, constant, plaintext): * nonce = constant | iv */ return CRYPT_CHACHA20_SetNonce(ctx, val, len); case CRYPT_CTRL_SET_COUNT: return CRYPT_CHACHA20_SetCount(ctx, val, len); default: BSL_ERR_PUSH_ERROR(CRYPT_CHACHA20_CTRLTYPE_ERROR); return CRYPT_CHACHA20_CTRLTYPE_ERROR; } } void CRYPT_CHACHA20_Clean(CRYPT_CHACHA20_Ctx *ctx) { if (ctx == NULL) { return; } (void)memset_s(ctx, sizeof(CRYPT_CHACHA20_Ctx), 0, sizeof(CRYPT_CHACHA20_Ctx)); } #endif // HITLS_CRYPTO_CHACHA20
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/chacha20.c
C
unknown
8,292
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CHACHA20_LOCAL_H #define CHACHA20_LOCAL_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 #include "crypt_chacha20.h" void CHACHA20_Block(CRYPT_CHACHA20_Ctx *ctx); void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len); #endif // HITLS_CRYPTO_CHACHA20 #endif // CHACHA20_LOCAL_H
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/chacha20_local.h
C
unknown
885
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CHACHA20 #include "crypt_utils.h" #include "chacha20_local.h" void CHACHA20_Update(CRYPT_CHACHA20_Ctx *ctx, const uint8_t *in, uint8_t *out, uint32_t len) { const uint8_t *offIn = in; uint8_t *offOut = out; uint32_t tLen = len; // one block is processed each time while (tLen >= CHACHA20_STATEBYTES) { CHACHA20_Block(ctx); // Process 64 bits at a time DATA64_XOR(ctx->last.u, offIn, offOut, CHACHA20_STATEBYTES); offIn += CHACHA20_STATEBYTES; offOut += CHACHA20_STATEBYTES; tLen -= CHACHA20_STATEBYTES; } } #endif // HITLS_CRYPTO_CHACHA20
2302_82127028/openHiTLS-examples_1556
crypto/chacha20/src/chacha20block.c
C
unknown
1,206
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_CBC_MAC_H #define CRYPT_CBC_MAC_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CBC_MAC #include <stdint.h> #include "crypt_types.h" #include "crypt_cmac.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ typedef struct CBC_MAC_Ctx CRYPT_CBC_MAC_Ctx; #define CRYPT_CBC_MAC_SetParam NULL /** * @brief Create a new CBC_MAC context. * @param id [IN] CBC_MAC algorithm ID * @return Pointer to the CBC_MAC context */ CRYPT_CBC_MAC_Ctx *CRYPT_CBC_MAC_NewCtx(CRYPT_MAC_AlgId id); /** * @brief Create a new CBC_MAC context with external library context. * @param libCtx [in] External library context * @param id [in] CBC_MAC algorithm ID * @return Pointer to the CBC_MAC context */ CRYPT_CBC_MAC_Ctx *CRYPT_CBC_MAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id); /** * @brief Use the key passed by the user to initialize the algorithm context. * @param ctx [IN] CBC_MAC context * @param key [in] symmetric algorithm key * @param len [in] Key length * @param param [in] param * @retval #CRYPT_SUCCESS Succeeded. * @retval #CRYPT_NULL_INPUT The input parameter is NULL. * For other error codes, see crypt_errno.h. */ int32_t CRYPT_CBC_MAC_Init(CRYPT_CBC_MAC_Ctx *ctx, const uint8_t *key, uint32_t len, void *param); /** * @brief Enter the data to be calculated and update the context. * @param ctx [IN] CBC_MAC context * @param *in [in] Pointer to the data to be calculated * @param len [in] Length of the data to be calculated * @retval #CRYPT_SUCCESS Succeeded. * @retval #CRYPT_NULL_INPUT The input parameter is NULL. * For other error codes, see crypt_errno.h. */ int32_t CRYPT_CBC_MAC_Update(CRYPT_CBC_MAC_Ctx *ctx, const uint8_t *in, uint32_t len); /** * @brief Output the cmac calculation result. * @param ctx [IN] CBC_MAC context * @param out [OUT] Output data. Sufficient memory must be allocated to store CBC_MAC results and cannot be null. * @param len [IN/OUT] Output data length * @retval #CRYPT_SUCCESS Succeeded. * @retval #CRYPT_NULL_INPUT The input parameter is NULL. * @retval #CRYPT_EAL_BUFF_LEN_NOT_ENOUGH The length of the output buffer is insufficient. * For other error codes, see crypt_errno.h. */ int32_t CRYPT_CBC_MAC_Final(CRYPT_CBC_MAC_Ctx *ctx, uint8_t *out, uint32_t *len); /** * @brief Re-initialize using the information retained in the ctx. Do not need to invoke the init again. * This function is equivalent to the combination of deinit and init interfaces. * @param ctx [IN] CBC_MAC context */ int32_t CRYPT_CBC_MAC_Reinit(CRYPT_CBC_MAC_Ctx *ctx); /** * @brief Deinitialization function. * If calculation is required after this function is invoked, it needs to be initialized again. * @param ctx [IN] CBC_MAC context */ int32_t CRYPT_CBC_MAC_Deinit(CRYPT_CBC_MAC_Ctx *ctx); /** * @brief CBC_MAC control function to set some information * @param ctx [IN] CBC_MAC context * @param opt [IN] option * @param val [IN] value * @param len [IN] the length of value * @return See crypt_errno.h. */ int32_t CRYPT_CBC_MAC_Ctrl(CRYPT_CBC_MAC_Ctx *ctx, uint32_t opt, void *val, uint32_t len); /** * @brief Free the CBC_MAC context. * @param ctx [IN] CBC_MAC context */ void CRYPT_CBC_MAC_FreeCtx(CRYPT_CBC_MAC_Ctx *ctx); #ifdef __cplusplus } #endif /* __cpluscplus */ #endif #endif
2302_82127028/openHiTLS-examples_1556
crypto/cmac/include/crypt_cbc_mac.h
C
unknown
4,037
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_CMAC_H #define CRYPT_CMAC_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CMAC #include <stdint.h> #include "crypt_types.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ typedef struct Cipher_MAC_Ctx CRYPT_CMAC_Ctx; #define CRYPT_CMAC_SetParam NULL /** * @brief Create a new CMAC context. * @param id [in] Symmetric encryption and decryption algorithm ID * @return CMAC context */ CRYPT_CMAC_Ctx *CRYPT_CMAC_NewCtx(CRYPT_MAC_AlgId id); /** * @brief Create a new CMAC context with external library context. * @param libCtx [in] External library context * @param id [in] Symmetric encryption and decryption algorithm ID * @return CMAC context */ CRYPT_CMAC_Ctx *CRYPT_CMAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id); /** * @brief Use the key passed by the user to initialize the algorithm context. * @param ctx [IN] CMAC context * @param key [in] symmetric algorithm key * @param len [in] Key length * @param param [in] param * @retval #CRYPT_SUCCESS Succeeded. * @retval #CRYPT_NULL_INPUT The input parameter is NULL. * For other error codes, see crypt_errno.h. */ int32_t CRYPT_CMAC_Init(CRYPT_CMAC_Ctx *ctx, const uint8_t *key, uint32_t len, void *param); /** * @brief Enter the data to be calculated and update the context. * @param ctx [IN] CMAC context * @param *in [in] Pointer to the data to be calculated * @param len [in] Length of the data to be calculated * @retval #CRYPT_SUCCESS Succeeded. * @retval #CRYPT_NULL_INPUT The input parameter is NULL. * For other error codes, see crypt_errno.h. */ int32_t CRYPT_CMAC_Update(CRYPT_CMAC_Ctx *ctx, const uint8_t *in, uint32_t len); /** * @brief Output the cmac calculation result. * @param ctx [IN] CMAC context * @param out [OUT] Output data. Sufficient memory must be allocated to store CMAC results and cannot be null. * @param len [IN/OUT] Output data length * @retval #CRYPT_SUCCESS Succeeded. * @retval #CRYPT_NULL_INPUT The input parameter is NULL. * @retval #CRYPT_EAL_BUFF_LEN_NOT_ENOUGH The length of the output buffer is insufficient. * For other error codes, see crypt_errno.h. */ int32_t CRYPT_CMAC_Final(CRYPT_CMAC_Ctx *ctx, uint8_t *out, uint32_t *len); /** * @brief Re-initialize using the information retained in the ctx. Do not need to invoke the init again. * This function is equivalent to the combination of deinit and init interfaces. * @param ctx [IN] CMAC context * @retval #CRYPT_SUCCESS Succeeded. * @retval #CRYPT_NULL_INPUT The input parameter is NULL. * For other error codes, see crypt_errno.h. */ int32_t CRYPT_CMAC_Reinit(CRYPT_CMAC_Ctx *ctx); /** * @brief Deinitialization function. * If calculation is required after this function is invoked, it needs to be initialized again. * @param ctx [IN] CMAC context * @retval #CRYPT_SUCCESS Succeeded. * @retval #CRYPT_NULL_INPUT The input parameter is NULL. * For other error codes, see crypt_errno.h. */ int32_t CRYPT_CMAC_Deinit(CRYPT_CMAC_Ctx *ctx); /** * @brief Control function for CMAC. * @param ctx [IN] CMAC context * @param opt [IN] Control option * @param val [IN]/[OUT] Control value * @param len [IN] Control value length * @retval #CRYPT_SUCCESS Succeeded. * @retval #CRYPT_NULL_INPUT The input parameter is NULL. * For other error codes, see crypt_errno.h. */ int32_t CRYPT_CMAC_Ctrl(CRYPT_CMAC_Ctx *ctx, uint32_t opt, void *val, uint32_t len); /** * @brief Free the CMAC context. * @param ctx [IN] CMAC context */ void CRYPT_CMAC_FreeCtx(CRYPT_CMAC_Ctx *ctx); #ifdef __cplusplus } #endif /* __cpluscplus */ #endif #endif
2302_82127028/openHiTLS-examples_1556
crypto/cmac/include/crypt_cmac.h
C
unknown
4,258
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CBC_MAC #include <stdint.h> #include "bsl_sal.h" #include "crypt_types.h" #include "crypt_utils.h" #include "bsl_err_internal.h" #include "cipher_mac_common.h" #include "crypt_errno.h" #include "crypt_cbc_mac.h" #include "eal_mac_local.h" CRYPT_CBC_MAC_Ctx *CRYPT_CBC_MAC_NewCtx(CRYPT_MAC_AlgId id) { int32_t ret; EAL_MacDepMethod method = {0}; ret = EAL_MacFindDepMethod(id, NULL, NULL, &method, NULL, false); if (ret != CRYPT_SUCCESS) { return NULL; } CRYPT_CBC_MAC_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_CBC_MAC_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ret = CipherMacInitCtx(&ctx->common, method.method.sym); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(ctx); return NULL; } ctx->paddingType = CRYPT_PADDING_MAX_COUNT; return ctx; } CRYPT_CBC_MAC_Ctx *CRYPT_CBC_MAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id) { (void)libCtx; return CRYPT_CBC_MAC_NewCtx(id); } int32_t CRYPT_CBC_MAC_Init(CRYPT_CBC_MAC_Ctx *ctx, const uint8_t *key, uint32_t len, void *param) { (void)param; if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return CipherMacInit(&ctx->common, key, len); } int32_t CRYPT_CBC_MAC_Update(CRYPT_CBC_MAC_Ctx *ctx, const uint8_t *in, uint32_t len) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->paddingType == CRYPT_PADDING_MAX_COUNT) { BSL_ERR_PUSH_ERROR(CRYPT_CBC_MAC_PADDING_NOT_SET); return CRYPT_CBC_MAC_PADDING_NOT_SET; } return CipherMacUpdate(&ctx->common, in, len); } static int32_t CbcMacPadding(CRYPT_CBC_MAC_Ctx *ctx) { const EAL_SymMethod *method = ctx->common.method; uint32_t length = ctx->common.len; uint32_t padLen = method->blockSize - length; switch (ctx->paddingType) { case CRYPT_PADDING_ZEROS: for (uint32_t i = 0; i < padLen; i++) { ctx->common.left[length++] = 0; } ctx->common.len = length; return CRYPT_SUCCESS; default: BSL_ERR_PUSH_ERROR(CRYPT_CBC_MAC_PADDING_NOT_SUPPORT); return CRYPT_CBC_MAC_PADDING_NOT_SUPPORT; } } int32_t CRYPT_CBC_MAC_Final(CRYPT_CBC_MAC_Ctx *ctx, uint8_t *out, uint32_t *len) { if (ctx == NULL || ctx->common.method == NULL || len == NULL || out == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const EAL_SymMethod *method = ctx->common.method; uint32_t blockSize = method->blockSize; if (*len < blockSize) { BSL_ERR_PUSH_ERROR(CRYPT_CBC_MAC_OUT_BUFF_LEN_NOT_ENOUGH); return CRYPT_CBC_MAC_OUT_BUFF_LEN_NOT_ENOUGH; } int32_t ret = CbcMacPadding(ctx); if (ret != CRYPT_SUCCESS) { return ret; } DATA_XOR(ctx->common.left, ctx->common.data, ctx->common.left, blockSize); ret = method->encryptBlock(ctx->common.key, ctx->common.left, out, blockSize); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *len = blockSize; return CRYPT_SUCCESS; } int32_t CRYPT_CBC_MAC_Reinit(CRYPT_CBC_MAC_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return CipherMacReinit(&ctx->common); } int32_t CRYPT_CBC_MAC_Deinit(CRYPT_CBC_MAC_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } return CipherMacDeinit(&ctx->common); } int32_t CRYPT_CBC_MAC_Ctrl(CRYPT_CBC_MAC_Ctx *ctx, uint32_t opt, void *val, uint32_t len) { if (ctx == NULL || val == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } switch (opt) { case CRYPT_CTRL_SET_CBC_MAC_PADDING: if (len != sizeof(CRYPT_PaddingType)) { BSL_ERR_PUSH_ERROR(CRYPT_CBC_MAC_ERR_CTRL_LEN); return CRYPT_CBC_MAC_ERR_CTRL_LEN; } ctx->paddingType = *(CRYPT_PaddingType*)val; return CRYPT_SUCCESS; case CRYPT_CTRL_GET_MACLEN: return CipherMacGetMacLen(&ctx->common, val, len); default: BSL_ERR_PUSH_ERROR(CRYPT_CBC_MAC_ERR_UNSUPPORTED_CTRL_OPTION); return CRYPT_CBC_MAC_ERR_UNSUPPORTED_CTRL_OPTION; } } void CRYPT_CBC_MAC_FreeCtx(CRYPT_CBC_MAC_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return; } CipherMacDeinitCtx(&ctx->common); BSL_SAL_Free(ctx); } #endif
2302_82127028/openHiTLS-examples_1556
crypto/cmac/src/cbc_mac.c
C
unknown
5,409
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_CBC_MAC) || defined(HITLS_CRYPTO_CMAC) #include <stdlib.h> #include "securec.h" #include "bsl_sal.h" #include "crypt_utils.h" #include "crypt_errno.h" #include "bsl_err_internal.h" #include "crypt_local_types.h" #include "cipher_mac_common.h" int32_t CipherMacInitCtx(Cipher_MAC_Common_Ctx *ctx, const EAL_SymMethod *method) { if (ctx == NULL || method == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } void *key = (void *)BSL_SAL_Calloc(1u, method->ctxSize); if (key == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } // set key and set method ctx->key = key; ctx->method = method; return CRYPT_SUCCESS; } void CipherMacDeinitCtx(Cipher_MAC_Common_Ctx *ctx) { if (ctx == NULL || ctx->method == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return; } const EAL_SymMethod *method = ctx->method; BSL_SAL_CleanseData((void *)(ctx->key), method->ctxSize); BSL_SAL_FREE(ctx->key); } int32_t CipherMacInit(Cipher_MAC_Common_Ctx *ctx, const uint8_t *key, uint32_t len) { if (ctx == NULL || ctx->method == NULL || (key == NULL && len != 0)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = ctx->method->setEncryptKey(ctx->key, key, len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } (void)memset_s(ctx->data, CIPHER_MAC_MAXBLOCKSIZE, 0, CIPHER_MAC_MAXBLOCKSIZE); ctx->len = 0; return CRYPT_SUCCESS; } int32_t CipherMacUpdate(Cipher_MAC_Common_Ctx *ctx, const uint8_t *in, uint32_t len) { if (ctx == NULL || ctx->method == NULL || (in == NULL && len != 0)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const EAL_SymMethod *method = ctx->method; int32_t ret; uint32_t blockSize = method->blockSize; const uint8_t *inTmp = in; uint32_t lenTmp = len; if (ctx->len > 0) { if (ctx->len > (UINT32_MAX - lenTmp)) { BSL_ERR_PUSH_ERROR(CRYPT_CMAC_INPUT_OVERFLOW); return CRYPT_CMAC_INPUT_OVERFLOW; } uint32_t end = (ctx->len + lenTmp) > (blockSize) ? (blockSize) : (ctx->len + lenTmp); for (uint32_t i = ctx->len; i < end; i++) { ctx->left[i] = (*inTmp); inTmp++; } lenTmp -= (end - ctx->len); if (lenTmp == 0) { ctx->len = end; return CRYPT_SUCCESS; } DATA_XOR(ctx->left, ctx->data, ctx->left, blockSize); ret = method->encryptBlock(ctx->key, ctx->left, ctx->data, blockSize); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } while (lenTmp > blockSize) { DATA_XOR(inTmp, ctx->data, ctx->left, blockSize); ret = method->encryptBlock(ctx->key, ctx->left, ctx->data, blockSize); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } lenTmp -= blockSize; inTmp += blockSize; } for (uint32_t i = 0; i < lenTmp; i++) { ctx->left[i] = inTmp[i]; } ctx->len = lenTmp; return CRYPT_SUCCESS; } int32_t CipherMacReinit(Cipher_MAC_Common_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } (void)memset_s(ctx->data, CIPHER_MAC_MAXBLOCKSIZE, 0, CIPHER_MAC_MAXBLOCKSIZE); ctx->len = 0; return CRYPT_SUCCESS; } int32_t CipherMacDeinit(Cipher_MAC_Common_Ctx *ctx) { if (ctx == NULL || ctx->method == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const uint32_t ctxSize = ctx->method->ctxSize; BSL_SAL_CleanseData(ctx->key, ctxSize); (void)memset_s(ctx->data, CIPHER_MAC_MAXBLOCKSIZE, 0, CIPHER_MAC_MAXBLOCKSIZE); (void)memset_s(ctx->left, CIPHER_MAC_MAXBLOCKSIZE, 0, CIPHER_MAC_MAXBLOCKSIZE); ctx->len = 0; return CRYPT_SUCCESS; } int32_t CipherMacGetMacLen(const Cipher_MAC_Common_Ctx *ctx, void *val, uint32_t len) { if (ctx == NULL || ctx->method == NULL || val == NULL || len != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } *(uint32_t *)val = ctx->method->blockSize; return CRYPT_SUCCESS; } #endif // #if defined(HITLS_CRYPTO_CBC_MAC) || defined(HITLS_CRYPTO_CMAC)
2302_82127028/openHiTLS-examples_1556
crypto/cmac/src/cipher_mac_common.c
C
unknown
5,210
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CIPHER_MAC_COMMON_H #define CIPHER_MAC_COMMON_H #include "hitls_build.h" #if defined(HITLS_CRYPTO_CBC_MAC) || defined(HITLS_CRYPTO_CMAC) #include <stdint.h> #include "crypt_local_types.h" #include "crypt_cmac.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ #define CIPHER_MAC_MAXBLOCKSIZE 16 struct Cipher_MAC_Ctx { const EAL_SymMethod *method; void *key; /* Stores the intermediate process data of CBC_MAC. The length is the block size. */ uint8_t data[CIPHER_MAC_MAXBLOCKSIZE]; uint8_t left[CIPHER_MAC_MAXBLOCKSIZE]; uint32_t len; /* Length of a non-integral data block */ }; typedef struct Cipher_MAC_Ctx Cipher_MAC_Common_Ctx; #ifdef HITLS_CRYPTO_CBC_MAC struct CBC_MAC_Ctx { Cipher_MAC_Common_Ctx common; CRYPT_PaddingType paddingType; }; #endif int32_t CipherMacInitCtx(Cipher_MAC_Common_Ctx *ctx, const EAL_SymMethod *method); void CipherMacDeinitCtx(Cipher_MAC_Common_Ctx *ctx); int32_t CipherMacInit(Cipher_MAC_Common_Ctx *ctx, const uint8_t *key, uint32_t len); int32_t CipherMacUpdate(Cipher_MAC_Common_Ctx *ctx, const uint8_t *in, uint32_t len); int32_t CipherMacReinit(Cipher_MAC_Common_Ctx *ctx); int32_t CipherMacDeinit(Cipher_MAC_Common_Ctx *ctx); int32_t CipherMacGetMacLen(const Cipher_MAC_Common_Ctx *ctx, void *val, uint32_t len); #ifdef __cplusplus } #endif /* __cpluscplus */ #endif // #if defined(HITLS_CRYPTO_CBC_MAC) || defined(HITLS_CRYPTO_CMAC) #endif // CIPHER_MAC_COMMON_H
2302_82127028/openHiTLS-examples_1556
crypto/cmac/src/cipher_mac_common.h
C
unknown
2,084
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CMAC #include <stdlib.h> #include "bsl_sal.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "bsl_err_internal.h" #include "cipher_mac_common.h" #include "crypt_cmac.h" #include "eal_mac_local.h" CRYPT_CMAC_Ctx *CRYPT_CMAC_NewCtx(CRYPT_MAC_AlgId id) { int32_t ret; EAL_MacDepMethod method = {0}; ret = EAL_MacFindDepMethod(id, NULL, NULL, &method, NULL, false); if (ret != CRYPT_SUCCESS) { return NULL; } CRYPT_CMAC_Ctx *ctx = BSL_SAL_Calloc(1, sizeof(CRYPT_CMAC_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ret = CipherMacInitCtx(ctx, method.method.sym); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(ctx); return NULL; } return ctx; } CRYPT_CMAC_Ctx *CRYPT_CMAC_NewCtxEx(void *libCtx, CRYPT_MAC_AlgId id) { (void)libCtx; return CRYPT_CMAC_NewCtx(id); } int32_t CRYPT_CMAC_Init(CRYPT_CMAC_Ctx *ctx, const uint8_t *key, uint32_t len, void *param) { (void)param; return CipherMacInit((Cipher_MAC_Common_Ctx *)ctx, key, len); } int32_t CRYPT_CMAC_Update(CRYPT_CMAC_Ctx *ctx, const uint8_t *in, uint32_t len) { return CipherMacUpdate((Cipher_MAC_Common_Ctx *)ctx, in, len); } static inline void LeftShiftOneBit(const uint8_t *in, uint32_t len, uint8_t *out) { uint32_t i = len - 1; out[i] = (in[i] << 1) | 0; do { i--; out[i] = (in[i] << 1) | (in[i + 1] >> 7); // 7 is used to obtain the most significant bit of the 8-bit data. } while (i != 0); } static void CMAC_Final(CRYPT_CMAC_Ctx *ctx) { const uint8_t z[CIPHER_MAC_MAXBLOCKSIZE] = {0}; uint8_t rb; uint8_t l[CIPHER_MAC_MAXBLOCKSIZE]; uint8_t k1[CIPHER_MAC_MAXBLOCKSIZE]; const EAL_SymMethod *method = ctx->method; uint32_t blockSize = method->blockSize; int32_t ret; ret = method->encryptBlock(ctx->key, z, l, blockSize); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return; } LeftShiftOneBit(l, blockSize, k1); if (blockSize == CIPHER_MAC_MAXBLOCKSIZE) { rb = 0x87; /* When the AES algorithm is used and the blocksize is 128 bits, rb uses 0x87. */ } else { rb = 0x1B; /* When the DES and TDES algorithms are used and blocksize is 64 bits, rb uses 0x1B. */ } if ((l[0] & 0x80) != 0) { k1[blockSize - 1] ^= rb; } uint32_t length = ctx->len; if (length == blockSize) { // When the message length is an integer multiple of blockSize, use K1 DATA_XOR(ctx->left, k1, ctx->left, blockSize); } else { // The message length is not an integer multiple of blockSize. Use K2 after padding. /* padding */ ctx->left[length++] = 0x80; // 0x80 indicates that the first bit of the data is added with 1. while (length < blockSize) { ctx->left[length++] = 0; } uint8_t k2[CIPHER_MAC_MAXBLOCKSIZE]; LeftShiftOneBit(k1, blockSize, k2); if ((k1[0] & 0x80) != 0) { k2[blockSize - 1] ^= rb; } DATA_XOR(ctx->left, k2, ctx->left, blockSize); ctx->len = blockSize; } } int32_t CRYPT_CMAC_Final(CRYPT_CMAC_Ctx *ctx, uint8_t *out, uint32_t *len) { if (ctx == NULL || ctx->method == NULL || len == NULL || out == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const EAL_SymMethod *method = ctx->method; uint32_t blockSize = method->blockSize; if (*len < blockSize) { BSL_ERR_PUSH_ERROR(CRYPT_CMAC_OUT_BUFF_LEN_NOT_ENOUGH); return CRYPT_CMAC_OUT_BUFF_LEN_NOT_ENOUGH; } CMAC_Final(ctx); DATA_XOR(ctx->left, ctx->data, ctx->left, blockSize); int32_t ret = method->encryptBlock(ctx->key, ctx->left, out, blockSize); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *len = blockSize; return CRYPT_SUCCESS; } int32_t CRYPT_CMAC_Reinit(CRYPT_CMAC_Ctx *ctx) { return CipherMacReinit((Cipher_MAC_Common_Ctx *)ctx); } int32_t CRYPT_CMAC_Deinit(CRYPT_CMAC_Ctx *ctx) { return CipherMacDeinit((Cipher_MAC_Common_Ctx *)ctx); } int32_t CRYPT_CMAC_Ctrl(CRYPT_CMAC_Ctx *ctx, uint32_t opt, void *val, uint32_t len) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } switch (opt) { case CRYPT_CTRL_GET_MACLEN: return CipherMacGetMacLen(ctx, val, len); default: break; } BSL_ERR_PUSH_ERROR(CRYPT_CMAC_ERR_UNSUPPORTED_CTRL_OPTION); return CRYPT_CMAC_ERR_UNSUPPORTED_CTRL_OPTION; } void CRYPT_CMAC_FreeCtx(CRYPT_CMAC_Ctx *ctx) { CipherMacDeinitCtx(ctx); BSL_SAL_Free(ctx); } #endif /* HITLS_CRYPTO_CMAC */
2302_82127028/openHiTLS-examples_1556
crypto/cmac/src/cmac.c
C
unknown
5,318
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_DECODE_KEY_IMPL_H #define CRYPT_DECODE_KEY_IMPL_H #ifdef __cplusplus extern "C" { #endif #include "hitls_build.h" #ifdef HITLS_CRYPTO_CODECSKEY #include <stdint.h> #include "bsl_params.h" typedef struct { const char *outFormat; const char *outType; } DECODER_CommonCtx; int32_t DECODER_CommonGetParam(const DECODER_CommonCtx *commonCtx, BSL_Param *param); void *DECODER_EPKI2PKI_NewCtx(void *provCtx); int32_t DECODER_EPKI2PKI_GetParam(void *ctx, BSL_Param *param); int32_t DECODER_EPKI2PKI_SetParam(void *ctx, const BSL_Param *param); int32_t DECODER_EPKI2PKI_Decode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); void DECODER_EPKI2PKI_FreeOutData(void *ctx, BSL_Param *outParam); void DECODER_EPKI2PKI_FreeCtx(void *ctx); int32_t DECODER_DER2KEY_GetParam(void *ctx, BSL_Param *param); int32_t DECODER_DER2KEY_SetParam(void *ctx, const BSL_Param *param); void DECODER_DER2KEY_FreeOutData(void *ctx, BSL_Param *outParam); void DECODER_DER2KEY_FreeCtx(void *ctx); #ifdef HITLS_CRYPTO_RSA void *DECODER_RsaDer2KeyNewCtx(void *provCtx); int32_t DECODER_RsaPrvKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_RsaPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_RsaSubPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_RsaSubPubKeyWithOutSeqDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_RsaPkcs8Der2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); #endif #ifdef HITLS_CRYPTO_ECDSA void *DECODER_EcdsaDer2KeyNewCtx(void *provCtx); int32_t DECODER_EcdsaPrvKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_EcdsaSubPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_EcdsaSubPubKeyWithOutSeqDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_EcdsaPkcs8Der2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); #endif #ifdef HITLS_CRYPTO_SM2 void *DECODER_Sm2Der2KeyNewCtx(void *provCtx); int32_t DECODER_Sm2PrvKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_Sm2SubPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_Sm2SubPubKeyWithOutSeqDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_Sm2Pkcs8Der2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); #endif #ifdef HITLS_CRYPTO_ED25519 void *DECODER_Ed25519Der2KeyNewCtx(void *provCtx); int32_t DECODER_Ed25519SubPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_Ed25519SubPubKeyWithOutSeqDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); int32_t DECODER_Ed25519Pkcs8Der2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); #endif #ifdef HITLS_BSL_PEM void *DECODER_Pem2DerNewCtx(void *provCtx); int32_t DECODER_Pem2DerGetParam(void *ctx, BSL_Param *param); int32_t DECODER_Pem2DerSetParam(void *ctx, const BSL_Param *param); int32_t DECODER_Pem2DerDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); void DECODER_Pem2DerFreeOutData(void *ctx, BSL_Param *outParam); void DECODER_Pem2DerFreeCtx(void *ctx); #endif void *DECODER_LowKeyObject2PkeyObjectNewCtx(void *provCtx); int32_t DECODER_LowKeyObject2PkeyObjectSetParam(void *ctx, const BSL_Param *param); int32_t DECODER_LowKeyObject2PkeyObjectGetParam(void *ctx, BSL_Param *param); int32_t DECODER_LowKeyObject2PkeyObjectDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam); void DECODER_LowKeyObject2PkeyObjectFreeOutData(void *ctx, BSL_Param *outParam); void DECODER_LowKeyObject2PkeyObjectFreeCtx(void *ctx); #endif /* HITLS_CRYPTO_CODECSKEY */ #ifdef __cplusplus } #endif #endif /* CRYPT_DECODE_KEY_IMPL_H */
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/include/crypt_decode_key_impl.h
C
unknown
4,509
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_ENCODE_DECODE_KEY_H #define CRYPT_ENCODE_DECODE_KEY_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CODECSKEY #include "bsl_types.h" #include "bsl_asn1_internal.h" #include "crypt_eal_pkey.h" #ifdef HITLS_CRYPTO_KEY_INFO #include "bsl_uio.h" #endif #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ typedef struct { int32_t version; BslCid keyType; BSL_ASN1_Buffer keyParam; uint8_t *pkeyRawKey; uint32_t pkeyRawKeyLen; void *attrs; // HITLS_X509_Attrs * } CRYPT_ENCODE_DECODE_Pk8PrikeyInfo; #ifdef HITLS_CRYPTO_KEY_DECODE typedef struct { BslCid keyType; BSL_ASN1_Buffer keyParam; BSL_ASN1_BitString pubKey; } CRYPT_DECODE_SubPubkeyInfo; int32_t CRYPT_DECODE_SubPubkey(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb, CRYPT_DECODE_SubPubkeyInfo *subPubkeyInfo, bool isComplete); int32_t CRYPT_DECODE_Pkcs8Info(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb, CRYPT_ENCODE_DECODE_Pk8PrikeyInfo *pk8PrikeyInfo); int32_t CRYPT_EAL_ParseRsaPssAlgParam(BSL_ASN1_Buffer *param, CRYPT_RSA_PssPara *para); int32_t CRYPT_EAL_PriKeyParseFile(BSL_ParseFormat format, int32_t type, const char *path, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey); #endif // HITLS_CRYPTO_KEY_DECODE #ifdef HITLS_CRYPTO_KEY_ENCODE int32_t CRYPT_ENCODE_Pkcs8Info(CRYPT_ENCODE_DECODE_Pk8PrikeyInfo *pk8PrikeyInfo, BSL_Buffer *asn1); int32_t CRYPT_EAL_EncodePubKeyBuffInternal(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ParseFormat format, int32_t type, bool isComplete, BSL_Buffer *encode); #ifdef HITLS_CRYPTO_RSA int32_t CRYPT_EAL_EncodeRsaPssAlgParam(const CRYPT_RSA_PssPara *rsaPssParam, uint8_t **buf, uint32_t *bufLen); #endif #endif // HITLS_CRYPTO_KEY_ENCODE #if defined(HITLS_CRYPTO_RSA) && (defined(HITLS_CRYPTO_KEY_ENCODE) || defined(HITLS_CRYPTO_KEY_INFO)) int32_t CRYPT_EAL_InitRsaPrv(const CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_PKEY_AlgId cid, CRYPT_EAL_PkeyPrv *rsaPrv); void CRYPT_EAL_DeinitRsaPrv(CRYPT_EAL_PkeyPrv *rsaPrv); int32_t CRYPT_EAL_GetRsaPssPara(CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_RSA_PssPara *rsaPssParam); #endif #ifdef HITLS_PKI_PKCS12_PARSE // parse PKCS7-EncryptData:only support PBES2 + PBKDF2. int32_t CRYPT_EAL_ParseAsn1PKCS7EncryptedData(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *encode, const uint8_t *pwd, uint32_t pwdlen, BSL_Buffer *output); #endif #ifdef HITLS_PKI_PKCS12_GEN // encode PKCS7-EncryptData:only support PBES2 + PBKDF2. int32_t CRYPT_EAL_EncodePKCS7EncryptDataBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *data, const void *encodeParam, BSL_Buffer *encode); #endif #ifdef HITLS_CRYPTO_KEY_INFO int32_t CRYPT_EAL_PrintPubkey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio); int32_t CRYPT_EAL_PrintPrikey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio); #ifdef HITLS_CRYPTO_RSA int32_t CRYPT_EAL_PrintRsaPssPara(uint32_t layer, CRYPT_RSA_PssPara *para, BSL_UIO *uio); #endif #endif // HITLS_CRYPTO_KEY_INFO int32_t CRYPT_EAL_GetEncodeFormat(const char *format); int32_t CRYPT_EAL_GetEncodeType(const char *type); #ifdef __cplusplus } #endif #endif // HITLS_CRYPTO_CODECSKEY #endif // CRYPT_ENCODE_DECODE_KEY_H
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/include/crypt_encode_decode_key.h
C
unknown
3,777
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_CODECSKEY) && defined(HITLS_CRYPTO_PROVIDER) #include <string.h> #include <stdbool.h> #include "crypt_eal_implprovider.h" #include "crypt_eal_pkey.h" #include "crypt_default_provderimpl.h" #include "crypt_algid.h" #ifdef HITLS_CRYPTO_RSA #include "crypt_rsa.h" #endif #ifdef HITLS_CRYPTO_ECDSA #include "crypt_ecdsa.h" #endif #ifdef HITLS_CRYPTO_SM2 #include "crypt_sm2.h" #endif #ifdef HITLS_CRYPTO_ED25519 #include "crypt_curve25519.h" #endif #include "eal_pkey.h" #include "crypt_provider_local.h" #include "crypt_errno.h" #include "bsl_sal.h" #include "bsl_obj.h" #include "bsl_err_internal.h" #include "crypt_encode_decode_local.h" #include "crypt_decode_key_impl.h" #define PKEY_MAX_PARAM_NUM 20 #if defined(HITLS_CRYPTO_RSA) || defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) || \ defined(HITLS_CRYPTO_ED25519) typedef struct { CRYPT_EAL_ProvMgrCtx *provMgrCtx; EAL_PkeyUnitaryMethod *method; int32_t keyAlgId; const char *outFormat; const char *outType; } DECODER_Der2KeyCtx; DECODER_Der2KeyCtx *DECODER_DER2KEY_NewCtx(void *provCtx) { (void)provCtx; DECODER_Der2KeyCtx *ctx = (DECODER_Der2KeyCtx *)BSL_SAL_Calloc(1, sizeof(DECODER_Der2KeyCtx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ctx->outFormat = "OBJECT"; ctx->outType = "LOW_KEY"; return ctx; } #define DECODER_DEFINE_DER2KEY_NEW_CTX(keyType, keyId, keyMethod, asyCipherMethod, exchMethod, signMethod, kemMethod) \ void *DECODER_##keyType##Der2KeyNewCtx(void *provCtx) \ { \ DECODER_Der2KeyCtx *ctx = DECODER_DER2KEY_NewCtx(provCtx); \ if (ctx == NULL) { \ return NULL; \ } \ int32_t ret = CRYPT_EAL_SetPkeyMethod(&ctx->method, keyMethod, asyCipherMethod, exchMethod, signMethod, \ kemMethod); \ if (ret != CRYPT_SUCCESS) { \ BSL_SAL_Free(ctx); \ return NULL; \ } \ ctx->keyAlgId = keyId; \ return ctx; \ } int32_t DECODER_CommonGetParam(const DECODER_CommonCtx *commonCtx, BSL_Param *param) { if (commonCtx == NULL || param == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_Param *param1 = BSL_PARAM_FindParam(param, CRYPT_PARAM_DECODE_OUTPUT_TYPE); if (param1 != NULL) { if (param1->valueType != BSL_PARAM_TYPE_OCTETS_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } param1->value = (void *)(uintptr_t)commonCtx->outType; } BSL_Param *param2 = BSL_PARAM_FindParam(param, CRYPT_PARAM_DECODE_OUTPUT_FORMAT); if (param2 != NULL) { if (param2->valueType != BSL_PARAM_TYPE_OCTETS_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } param2->value = (void *)(uintptr_t)commonCtx->outFormat; } return CRYPT_SUCCESS; } int32_t DECODER_DER2KEY_GetParam(void *ctx, BSL_Param *param) { DECODER_Der2KeyCtx *decoderCtx = (DECODER_Der2KeyCtx *)ctx; if (decoderCtx == NULL || param == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } DECODER_CommonCtx commonCtx = { .outFormat = decoderCtx->outFormat, .outType = decoderCtx->outType }; return DECODER_CommonGetParam(&commonCtx, param); } int32_t DECODER_DER2KEY_SetParam(void *ctx, const BSL_Param *param) { DECODER_Der2KeyCtx *decoderCtx = (DECODER_Der2KeyCtx *)ctx; if (decoderCtx == NULL || param == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const BSL_Param *input = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_DECODE_PROVIDER_CTX); if (input != NULL) { if (input->valueType != BSL_PARAM_TYPE_CTX_PTR || input->value == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } decoderCtx->provMgrCtx = (CRYPT_EAL_ProvMgrCtx *)(uintptr_t)input->value; } return CRYPT_SUCCESS; } static int32_t CheckParams(DECODER_Der2KeyCtx *decoderCtx, const BSL_Param *inParam, BSL_Param **outParam, BSL_Buffer *asn1Encode) { if (decoderCtx == NULL || inParam == NULL || outParam == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const BSL_Param *input = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_BUFFER_DATA); if (input == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (input->value == NULL || input->valueLen == 0 || input->valueType != BSL_PARAM_TYPE_OCTETS) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } asn1Encode->data = (uint8_t *)(uintptr_t)input->value; asn1Encode->dataLen = input->valueLen; return CRYPT_SUCCESS; } #define DECODER_CHECK_PARAMS(ctx, inParam, outParam) \ void *key = NULL; \ BSL_Buffer asn1Encode = {0}; \ DECODER_Der2KeyCtx *decoderCtx = (DECODER_Der2KeyCtx *)ctx; \ int32_t ret = CheckParams(decoderCtx, inParam, outParam, &asn1Encode); \ if (ret != CRYPT_SUCCESS) { \ BSL_ERR_PUSH_ERROR(ret); \ return ret; \ } static int32_t ConstructOutputParams(DECODER_Der2KeyCtx *decoderCtx, void *key, BSL_Param **outParam) { BSL_Param *result = BSL_SAL_Calloc(7, sizeof(BSL_Param)); if (result == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = BSL_PARAM_InitValue(&result[0], CRYPT_PARAM_DECODE_OBJECT_DATA, BSL_PARAM_TYPE_CTX_PTR, key, 0); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BSL_PARAM_InitValue(&result[1], CRYPT_PARAM_DECODE_OBJECT_TYPE, BSL_PARAM_TYPE_INT32, &decoderCtx->keyAlgId, sizeof(int32_t)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BSL_PARAM_InitValue(&result[2], CRYPT_PARAM_DECODE_PKEY_EXPORT_METHOD_FUNC, BSL_PARAM_TYPE_FUNC_PTR, decoderCtx->method->export, 0); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BSL_PARAM_InitValue(&result[3], CRYPT_PARAM_DECODE_PKEY_FREE_METHOD_FUNC, BSL_PARAM_TYPE_FUNC_PTR, decoderCtx->method->freeCtx, 0); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BSL_PARAM_InitValue(&result[4], CRYPT_PARAM_DECODE_PKEY_DUP_METHOD_FUNC, BSL_PARAM_TYPE_FUNC_PTR, decoderCtx->method->dupCtx, 0); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BSL_PARAM_InitValue(&result[5], CRYPT_PARAM_DECODE_PROVIDER_CTX, BSL_PARAM_TYPE_CTX_PTR, decoderCtx->provMgrCtx, 0); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } *outParam = result; return CRYPT_SUCCESS; EXIT: if (decoderCtx->method != NULL && decoderCtx->method->freeCtx != NULL) { decoderCtx->method->freeCtx(key); } BSL_SAL_Free(result); return ret; } #define DECODER_DEFINE_PRVKEY_DER2KEY_DECODE(keyType, keyStructName, parseFunc) \ int32_t DECODER_##keyType##PrvKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) \ { \ DECODER_CHECK_PARAMS(ctx, inParam, outParam); \ ret = parseFunc(decoderCtx->provMgrCtx->libCtx, asn1Encode.data, asn1Encode.dataLen, NULL, \ (keyStructName **)&key); \ if (ret != CRYPT_SUCCESS) { \ BSL_ERR_PUSH_ERROR(ret); \ return ret; \ } \ return ConstructOutputParams(decoderCtx, key, outParam); \ } #define DECODER_DEFINE_PUBKEY_DER2KEY_DECODE(keyType, keyStructName, parseFunc) \ int32_t DECODER_##keyType##PubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) \ { \ DECODER_CHECK_PARAMS(ctx, inParam, outParam); \ ret = parseFunc(decoderCtx->provMgrCtx->libCtx, asn1Encode.data, asn1Encode.dataLen, NULL, \ (keyStructName **)&key, BSL_CID_UNKNOWN); \ if (ret != CRYPT_SUCCESS) { \ BSL_ERR_PUSH_ERROR(ret); \ return ret; \ } \ return ConstructOutputParams(decoderCtx, key, outParam); \ } #define DECODER_DEFINE_SUBPUBKEY_DER2KEY_DECODE(keyType, keyStructName, parseFunc) \ int32_t DECODER_##keyType##SubPubKeyDer2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) \ { \ DECODER_CHECK_PARAMS(ctx, inParam, outParam) \ ret = parseFunc(decoderCtx->provMgrCtx->libCtx, asn1Encode.data, asn1Encode.dataLen, \ (keyStructName **)&key, true); \ if (ret != CRYPT_SUCCESS) { \ BSL_ERR_PUSH_ERROR(ret); \ return ret; \ } \ return ConstructOutputParams(decoderCtx, key, outParam); \ } #define DECODER_DEFINE_SUBPUBKEY_WITHOUT_SEQ_DER2KEY_DECODE(keyType, keyStructName, parseFunc) \ int32_t DECODER_##keyType##SubPubKeyWithOutSeqDer2KeyDecode(void *ctx, const BSL_Param *inParam, \ BSL_Param **outParam) \ { \ DECODER_CHECK_PARAMS(ctx, inParam, outParam) \ ret = parseFunc(decoderCtx->provMgrCtx->libCtx, asn1Encode.data, asn1Encode.dataLen, (keyStructName **)&key, \ false); \ if (ret != CRYPT_SUCCESS) { \ BSL_ERR_PUSH_ERROR(ret); \ return ret; \ } \ return ConstructOutputParams(decoderCtx, key, outParam); \ } #define DECODER_DEFINE_PKCS8_DECODE(keyType, keyStructName, parseFunc) \ int32_t DECODER_##keyType##Pkcs8Der2KeyDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) \ { \ DECODER_CHECK_PARAMS(ctx, inParam, outParam) \ ret = parseFunc(decoderCtx->provMgrCtx->libCtx, asn1Encode.data, asn1Encode.dataLen, (keyStructName **)&key); \ if (ret != CRYPT_SUCCESS) { \ BSL_ERR_PUSH_ERROR(ret); \ return ret; \ } \ return ConstructOutputParams(decoderCtx, key, outParam); \ } void DECODER_DER2KEY_FreeOutData(void *ctx, BSL_Param *outParam) { DECODER_Der2KeyCtx *decoderCtx = ctx; if (decoderCtx == NULL || outParam == NULL) { return; } if (decoderCtx->method == NULL || decoderCtx->method->freeCtx == NULL) { return; } BSL_Param *outKey = BSL_PARAM_FindParam(outParam, CRYPT_PARAM_DECODE_OBJECT_DATA); if (outKey == NULL) { return; } decoderCtx->method->freeCtx(outKey->value); BSL_SAL_Free(outParam); } void DECODER_DER2KEY_FreeCtx(void *ctx) { if (ctx == NULL) { return; } DECODER_Der2KeyCtx *decoderCtx = (DECODER_Der2KeyCtx *)ctx; if (decoderCtx->method != NULL) { BSL_SAL_Free(decoderCtx->method); } BSL_SAL_Free(decoderCtx); } #endif #ifdef HITLS_CRYPTO_RSA DECODER_DEFINE_DER2KEY_NEW_CTX(Rsa, CRYPT_PKEY_RSA, g_defEalKeyMgmtRsa, g_defEalAsymCipherRsa, NULL, \ g_defEalSignRsa, NULL) #endif #ifdef HITLS_CRYPTO_ECDSA DECODER_DEFINE_DER2KEY_NEW_CTX(Ecdsa, CRYPT_PKEY_ECDSA, g_defEalKeyMgmtEcdsa, NULL, NULL, \ g_defEalSignEcdsa, NULL) #endif #ifdef HITLS_CRYPTO_SM2 DECODER_DEFINE_DER2KEY_NEW_CTX(Sm2, CRYPT_PKEY_SM2, g_defEalKeyMgmtSm2, g_defEalAsymCipherSm2, g_defEalExchSm2, \ g_defEalSignSm2, NULL) #endif #ifdef HITLS_CRYPTO_ED25519 DECODER_DEFINE_DER2KEY_NEW_CTX(Ed25519, CRYPT_PKEY_ED25519, g_defEalKeyMgmtEd25519, NULL, NULL, \ g_defEalSignEd25519, NULL) #endif #ifdef HITLS_CRYPTO_RSA DECODER_DEFINE_PRVKEY_DER2KEY_DECODE(Rsa, CRYPT_RSA_Ctx, CRYPT_RSA_ParsePrikeyAsn1Buff) DECODER_DEFINE_PUBKEY_DER2KEY_DECODE(Rsa, CRYPT_RSA_Ctx, CRYPT_RSA_ParsePubkeyAsn1Buff) DECODER_DEFINE_SUBPUBKEY_DER2KEY_DECODE(Rsa, CRYPT_RSA_Ctx, CRYPT_RSA_ParseSubPubkeyAsn1Buff) DECODER_DEFINE_SUBPUBKEY_WITHOUT_SEQ_DER2KEY_DECODE(Rsa, CRYPT_RSA_Ctx, CRYPT_RSA_ParseSubPubkeyAsn1Buff) DECODER_DEFINE_PKCS8_DECODE(Rsa, CRYPT_RSA_Ctx, CRYPT_RSA_ParsePkcs8Key) #endif #ifdef HITLS_CRYPTO_ECDSA DECODER_DEFINE_PRVKEY_DER2KEY_DECODE(Ecdsa, void, CRYPT_ECC_ParsePrikeyAsn1Buff) DECODER_DEFINE_SUBPUBKEY_DER2KEY_DECODE(Ecdsa, void, CRYPT_ECC_ParseSubPubkeyAsn1Buff) DECODER_DEFINE_SUBPUBKEY_WITHOUT_SEQ_DER2KEY_DECODE(Ecdsa, void, CRYPT_ECC_ParseSubPubkeyAsn1Buff) DECODER_DEFINE_PKCS8_DECODE(Ecdsa, void, CRYPT_ECC_ParsePkcs8Key) #endif #ifdef HITLS_CRYPTO_SM2 DECODER_DEFINE_PRVKEY_DER2KEY_DECODE(Sm2, CRYPT_SM2_Ctx, CRYPT_SM2_ParsePrikeyAsn1Buff) DECODER_DEFINE_SUBPUBKEY_DER2KEY_DECODE(Sm2, CRYPT_SM2_Ctx, CRYPT_SM2_ParseSubPubkeyAsn1Buff) DECODER_DEFINE_SUBPUBKEY_WITHOUT_SEQ_DER2KEY_DECODE(Sm2, CRYPT_SM2_Ctx,CRYPT_SM2_ParseSubPubkeyAsn1Buff) DECODER_DEFINE_PKCS8_DECODE(Sm2, CRYPT_SM2_Ctx, CRYPT_SM2_ParsePkcs8Key) #endif #ifdef HITLS_CRYPTO_ED25519 DECODER_DEFINE_SUBPUBKEY_DER2KEY_DECODE(Ed25519, CRYPT_CURVE25519_Ctx, CRYPT_ED25519_ParseSubPubkeyAsn1Buff) DECODER_DEFINE_SUBPUBKEY_WITHOUT_SEQ_DER2KEY_DECODE(Ed25519, CRYPT_CURVE25519_Ctx, CRYPT_ED25519_ParseSubPubkeyAsn1Buff) DECODER_DEFINE_PKCS8_DECODE(Ed25519, CRYPT_CURVE25519_Ctx, CRYPT_ED25519_ParsePkcs8Key) #endif #endif /* HITLS_CRYPTO_CODECSKEY && defined(HITLS_CRYPTO_PROVIDER) */
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_decode_der2key.c
C
unknown
13,506
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_KEY_DECODE #include "crypt_ecc.h" #ifdef HITLS_CRYPTO_ECDSA #include "crypt_ecdsa.h" #endif #ifdef HITLS_CRYPTO_SM2 #include "crypt_sm2.h" #endif #ifdef HITLS_CRYPTO_ED25519 #include "crypt_curve25519.h" #endif #include "crypt_params_key.h" #include "bsl_asn1_internal.h" #include "bsl_params.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_encode_decode_local.h" #include "crypt_encode_decode_key.h" #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) typedef struct { int32_t version; BSL_ASN1_Buffer param; BSL_ASN1_Buffer prikey; BSL_ASN1_Buffer pubkey; } CRYPT_DECODE_EccPrikeyInfo; static int32_t GetParaId(uint8_t *octs, uint32_t octsLen) { BslOidString oidStr = {octsLen, (char *)octs, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID); return CRYPT_PKEY_PARAID_MAX; } return (int32_t)cid; } static int32_t ParsePrikeyAsn1Info(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pk8AlgoParam, CRYPT_DECODE_EccPrikeyInfo *eccPrvInfo) { BSL_ASN1_Buffer asn1[CRYPT_ECPRIKEY_PUBKEY_IDX + 1] = {0}; int32_t ret = CRYPT_DECODE_PrikeyAsn1Buff(buff, buffLen, asn1, CRYPT_ECPRIKEY_PUBKEY_IDX + 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } int32_t version; BSL_ASN1_Buffer *prikey = &asn1[CRYPT_ECPRIKEY_PRIKEY_IDX]; // the ECC OID BSL_ASN1_Buffer *ecParamOid = &asn1[CRYPT_ECPRIKEY_PARAM_IDX]; // the parameters OID BSL_ASN1_Buffer *pubkey = &asn1[CRYPT_ECPRIKEY_PUBKEY_IDX]; // the ECC OID BSL_ASN1_Buffer *param = pk8AlgoParam; if (ecParamOid->len != 0) { // has a valid Algorithm param param = ecParamOid; } else { if (param == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (param->len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM); return CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM; } } if (pubkey->len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ASN1_BUFF_FAILED); return CRYPT_DECODE_ASN1_BUFF_FAILED; } ret = BSL_ASN1_DecodePrimitiveItem(&asn1[CRYPT_ECPRIKEY_VERSION_IDX], &version); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } eccPrvInfo->version = version; eccPrvInfo->param = *param; eccPrvInfo->prikey = *prikey; eccPrvInfo->pubkey = *pubkey; return CRYPT_SUCCESS; } #endif // HITLS_CRYPTO_ECDSA || HITLS_CRYPTO_SM2 #ifdef HITLS_CRYPTO_ECDSA // ecdh is not considered, and it will be improved in the future static int32_t EccKeyNew(void *libCtx, BSL_ASN1_Buffer *ecParamOid, void **ecKey) { int32_t paraId = GetParaId(ecParamOid->buff, ecParamOid->len); if (!IsEcdsaEcParaId(paraId)) { return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH; } CRYPT_ECDSA_Ctx *key = CRYPT_ECDSA_NewCtxEx(libCtx); if (key == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = ECC_SetPara(key, ECC_NewPara(paraId)); if (ret != CRYPT_SUCCESS) { ECC_FreeCtx(key); BSL_ERR_PUSH_ERROR(ret); return ret; } *ecKey = (void *)key; return CRYPT_SUCCESS; } int32_t CRYPT_ECC_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, void **pubKey, bool isComplete) { if (buff == NULL || buffLen == 0 || pubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DECODE_SubPubkeyInfo subPubkeyInfo = {0}; void *pctx = NULL; int32_t ret = CRYPT_DECODE_SubPubkey(buff, buffLen, NULL, &subPubkeyInfo, isComplete); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (subPubkeyInfo.keyType != BSL_CID_EC_PUBLICKEY) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH); return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH; } ret = EccKeyNew(libCtx, &subPubkeyInfo.keyParam, &pctx); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Param pubParam[2] = { {CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, subPubkeyInfo.pubKey.buff, subPubkeyInfo.pubKey.len, 0}, BSL_PARAM_END }; ret = ECC_PkeySetPubKeyEx(pctx, pubParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); ECC_FreeCtx(pctx); return ret; } *pubKey = (void *)pctx; return ret; } int32_t CRYPT_ECC_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *pk8AlgoParam, void **ecPriKey) { if (buffer == NULL || bufferLen == 0 || ecPriKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DECODE_EccPrikeyInfo eccPrvInfo = {0}; int32_t ret = ParsePrikeyAsn1Info(buffer, bufferLen, pk8AlgoParam, &eccPrvInfo); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } void *pctx = NULL; ret = EccKeyNew(libCtx, &eccPrvInfo.param, &pctx); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Param pubParam[2] = { {CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, (eccPrvInfo.pubkey.buff + 1), eccPrvInfo.pubkey.len - 1, 0}, BSL_PARAM_END }; ret = ECC_PkeySetPubKeyEx(pctx, pubParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } BSL_Param prvParam[2] = { {CRYPT_PARAM_EC_PRVKEY, BSL_PARAM_TYPE_OCTETS, eccPrvInfo.prikey.buff, eccPrvInfo.prikey.len, 0}, BSL_PARAM_END }; ret = ECC_PkeySetPrvKeyEx(pctx, prvParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } *ecPriKey = pctx; return ret; ERR: ECC_FreeCtx(pctx); return ret; } int32_t CRYPT_ECC_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, void **ecdsaPriKey) { CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0}; int32_t ret = CRYPT_DECODE_Pkcs8Info(buff, buffLen, NULL, &pk8PrikeyInfo); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (pk8PrikeyInfo.keyType != BSL_CID_EC_PUBLICKEY) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH); return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH; } ret = CRYPT_ECC_ParsePrikeyAsn1Buff(libCtx, pk8PrikeyInfo.pkeyRawKey, pk8PrikeyInfo.pkeyRawKeyLen, &pk8PrikeyInfo.keyParam, ecdsaPriKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_CRYPTO_ECDSA #ifdef HITLS_CRYPTO_SM2 static int32_t Sm2KeyNew(void *libCtx, BSL_ASN1_Buffer *ecParamOid, CRYPT_SM2_Ctx **ecKey) { CRYPT_SM2_Ctx *key = NULL; int32_t paraId = GetParaId(ecParamOid->buff, ecParamOid->len); if (paraId != CRYPT_ECC_SM2) { return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH; } key = CRYPT_SM2_NewCtxEx(libCtx); if (key == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } *ecKey = key; return CRYPT_SUCCESS; } int32_t CRYPT_SM2_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_SM2_Ctx **pubKey, bool isComplete) { if (buff == NULL || buffLen == 0 || pubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DECODE_SubPubkeyInfo subPubkeyInfo = {0}; CRYPT_SM2_Ctx *pctx = NULL; int32_t ret = CRYPT_DECODE_SubPubkey(buff, buffLen, NULL, &subPubkeyInfo, isComplete); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (subPubkeyInfo.keyType != BSL_CID_EC_PUBLICKEY && subPubkeyInfo.keyType != BSL_CID_SM2PRIME256) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH); return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH; } ret = Sm2KeyNew(libCtx, &subPubkeyInfo.keyParam, &pctx); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Param pubParam[2] = { {CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, subPubkeyInfo.pubKey.buff, subPubkeyInfo.pubKey.len, 0}, BSL_PARAM_END }; ret = CRYPT_SM2_SetPubKeyEx(pctx, pubParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); CRYPT_SM2_FreeCtx(pctx); return ret; } *pubKey = pctx; return ret; } int32_t CRYPT_SM2_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *pk8AlgoParam, CRYPT_SM2_Ctx **sm2PriKey) { CRYPT_DECODE_EccPrikeyInfo eccPrvInfo = {0}; int32_t ret = ParsePrikeyAsn1Info(buffer, bufferLen, pk8AlgoParam, &eccPrvInfo); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_SM2_Ctx *pctx = NULL; ret = Sm2KeyNew(libCtx, &eccPrvInfo.param, &pctx); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Param pubParam[2] = { {CRYPT_PARAM_EC_PUBKEY, BSL_PARAM_TYPE_OCTETS, eccPrvInfo.pubkey.buff + 1, eccPrvInfo.pubkey.len - 1, 0}, BSL_PARAM_END }; ret = CRYPT_SM2_SetPubKeyEx(pctx, pubParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } BSL_Param prvParam[2] = { {CRYPT_PARAM_EC_PRVKEY, BSL_PARAM_TYPE_OCTETS, eccPrvInfo.prikey.buff, eccPrvInfo.prikey.len, 0}, BSL_PARAM_END }; ret = CRYPT_SM2_SetPrvKeyEx(pctx, prvParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } *sm2PriKey = pctx; return ret; ERR: CRYPT_SM2_FreeCtx(pctx); return ret; } int32_t CRYPT_SM2_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_SM2_Ctx **sm2PriKey) { CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0}; int32_t ret = CRYPT_DECODE_Pkcs8Info(buff, buffLen, NULL, &pk8PrikeyInfo); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (pk8PrikeyInfo.keyType != BSL_CID_EC_PUBLICKEY) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH); return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH; } ret = CRYPT_SM2_ParsePrikeyAsn1Buff(libCtx, pk8PrikeyInfo.pkeyRawKey, pk8PrikeyInfo.pkeyRawKeyLen, &pk8PrikeyInfo.keyParam, sm2PriKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_CRYPTO_SM2 #ifdef HITLS_CRYPTO_ED25519 static int32_t ParseEd25519PrikeyAsn1Buff(void *libCtx, uint8_t *buffer, uint32_t bufferLen, CRYPT_CURVE25519_Ctx **ed25519PriKey) { uint8_t *tmpBuff = buffer; uint32_t tmpBuffLen = bufferLen; int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_OCTETSTRING, &tmpBuff, &tmpBuffLen, &tmpBuffLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_CURVE25519_Ctx *pctx = CRYPT_ED25519_NewCtxEx(libCtx); if (pctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } BSL_Param prvParam[2] = { {CRYPT_PARAM_CURVE25519_PRVKEY, BSL_PARAM_TYPE_OCTETS, tmpBuff, tmpBuffLen, 0}, BSL_PARAM_END }; ret = CRYPT_CURVE25519_SetPrvKeyEx(pctx, prvParam); if (ret != CRYPT_SUCCESS) { CRYPT_CURVE25519_FreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } *ed25519PriKey = pctx; return CRYPT_SUCCESS; } int32_t CRYPT_ED25519_ParsePkcs8Key(void *libCtx, uint8_t *buffer, uint32_t bufferLen, CRYPT_CURVE25519_Ctx **ed25519PriKey) { CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0}; int32_t ret = CRYPT_DECODE_Pkcs8Info(buffer, bufferLen, NULL, &pk8PrikeyInfo); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (pk8PrikeyInfo.keyType != BSL_CID_ED25519) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH); return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH; } return ParseEd25519PrikeyAsn1Buff(libCtx, pk8PrikeyInfo.pkeyRawKey, pk8PrikeyInfo.pkeyRawKeyLen, ed25519PriKey); } int32_t CRYPT_ED25519_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_CURVE25519_Ctx **pubKey, bool isComplete) { if (buff == NULL || buffLen == 0 || pubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DECODE_SubPubkeyInfo subPubkeyInfo = {0}; int32_t ret = CRYPT_DECODE_SubPubkey(buff, buffLen, NULL, &subPubkeyInfo, isComplete); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (subPubkeyInfo.keyType != BSL_CID_ED25519) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH); return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH; } CRYPT_CURVE25519_Ctx *pctx = CRYPT_ED25519_NewCtxEx(libCtx); if (pctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } BSL_Param pubParam[2] = { {CRYPT_PARAM_CURVE25519_PUBKEY, BSL_PARAM_TYPE_OCTETS, subPubkeyInfo.pubKey.buff, subPubkeyInfo.pubKey.len, 0}, BSL_PARAM_END }; ret = CRYPT_CURVE25519_SetPubKeyEx(pctx, pubParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); CRYPT_CURVE25519_FreeCtx(pctx); return ret; } *pubKey = pctx; return ret; } #endif // HITLS_CRYPTO_ED25519 #endif // HITLS_CRYPTO_KEY_DECODE
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_decode_ecc.c
C
unknown
14,282
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_CODECSKEY) && defined(HITLS_CRYPTO_KEY_EPKI) && defined(HITLS_CRYPTO_PROVIDER) #include <string.h> #include "crypt_eal_implprovider.h" #include "crypt_params_key.h" #include "crypt_errno.h" #include "bsl_types.h" #include "bsl_params.h" #include "bsl_err_internal.h" #include "crypt_encode_decode_local.h" #include "crypt_decode_key_impl.h" typedef struct DECODER_EPki2PkiCtx { CRYPT_EAL_LibCtx *libCtx; const char *attrName; const char *outFormat; const char *outType; } DECODER_EPki2PkiCtx; void *DECODER_EPKI2PKI_NewCtx(void *provCtx) { (void)provCtx; DECODER_EPki2PkiCtx *ctx = (DECODER_EPki2PkiCtx *)BSL_SAL_Calloc(1, sizeof(DECODER_EPki2PkiCtx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ctx->outFormat = "ASN1"; ctx->outType = "PRIKEY_PKCS8_UNENCRYPT"; return ctx; } int32_t DECODER_EPKI2PKI_GetParam(void *ctx, BSL_Param *param) { DECODER_EPki2PkiCtx *decoderCtx = (DECODER_EPki2PkiCtx *)ctx; if (decoderCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } DECODER_CommonCtx commonCtx = { .outFormat = decoderCtx->outFormat, .outType = decoderCtx->outType }; return DECODER_CommonGetParam(&commonCtx, param); } int32_t DECODER_EPKI2PKI_SetParam(void *ctx, const BSL_Param *param) { DECODER_EPki2PkiCtx *decoderCtx = (DECODER_EPki2PkiCtx *)ctx; if (decoderCtx == NULL || param == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const BSL_Param *attrNameParam = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_DECODE_TARGET_ATTR_NAME); if (attrNameParam != NULL) { if (attrNameParam->valueType != BSL_PARAM_TYPE_OCTETS_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } decoderCtx->attrName = (const char *)attrNameParam->value; } const BSL_Param *libCtxParam = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_DECODE_LIB_CTX); if (libCtxParam != NULL) { if (libCtxParam->valueType != BSL_PARAM_TYPE_CTX_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } decoderCtx->libCtx = (CRYPT_EAL_LibCtx *)(uintptr_t)libCtxParam->value; } return CRYPT_SUCCESS; } int32_t DECODER_EPKI2PKI_Decode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) { DECODER_EPki2PkiCtx *decoderCtx = (DECODER_EPki2PkiCtx *)ctx; if (decoderCtx == NULL || inParam == NULL || outParam == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const BSL_Param *inputParam = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_BUFFER_DATA); if (inputParam == NULL || inputParam->value == NULL || inputParam->valueType != BSL_PARAM_TYPE_OCTETS) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } const BSL_Param *passParam = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_PASSWORD); if (passParam == NULL || passParam->valueType != BSL_PARAM_TYPE_OCTETS) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } BSL_Buffer input = {(uint8_t *)(uintptr_t)inputParam->value, inputParam->valueLen}; BSL_Buffer pwdBuff = {(uint8_t *)(uintptr_t)passParam->value, passParam->valueLen}; BSL_Buffer decode = {NULL, 0}; int32_t ret = CRYPT_DECODE_Pkcs8PrvDecrypt(decoderCtx->libCtx, decoderCtx->attrName, &input, &pwdBuff, NULL, &decode); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return CRYPT_DECODE_ConstructBufferOutParam(outParam, decode.data, decode.dataLen); } void DECODER_EPKI2PKI_FreeCtx(void *ctx) { if (ctx == NULL) { return; } BSL_SAL_Free(ctx); } void DECODER_EPKI2PKI_FreeOutData(void *ctx, BSL_Param *outParam) { (void)ctx; if (outParam == NULL) { return; } BSL_Param *dataParam = BSL_PARAM_FindParam(outParam, CRYPT_PARAM_DECODE_BUFFER_DATA); if (dataParam == NULL) { return; } BSL_SAL_ClearFree(dataParam->value, dataParam->valueLen); BSL_SAL_Free(outParam); } #endif /* HITLS_CRYPTO_CODECSKEY && HITLS_CRYPTO_EPKI2PKI && HITLS_CRYPTO_PROVIDER */
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_decode_epki2pki.c
C
unknown
4,914
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_CODECSKEY) && defined(HITLS_CRYPTO_PROVIDER) #include "crypt_eal_implprovider.h" #include "crypt_eal_pkey.h" #include "crypt_provider.h" #include "crypt_params_key.h" #include "crypt_types.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "eal_pkey.h" #include "crypt_decode_key_impl.h" #include "bsl_err_internal.h" typedef struct { CRYPT_EAL_LibCtx *libCtx; const char *targetAttrName; const char *outFormat; const char *outType; } DECODER_Lowkey2PkeyCtx; void *DECODER_LowKeyObject2PkeyObjectNewCtx(void *provCtx) { (void)provCtx; DECODER_Lowkey2PkeyCtx *ctx = (DECODER_Lowkey2PkeyCtx *)BSL_SAL_Calloc(1, sizeof(DECODER_Lowkey2PkeyCtx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ctx->outFormat = "OBJECT"; ctx->outType = "HIGH_KEY"; return (void *)ctx; } int32_t DECODER_LowKeyObject2PkeyObjectSetParam(void *ctx, const BSL_Param *param) { DECODER_Lowkey2PkeyCtx *decoderCtx = (DECODER_Lowkey2PkeyCtx *)ctx; if (decoderCtx == NULL || param == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } const BSL_Param *libCtxParam = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_DECODE_LIB_CTX); if (libCtxParam != NULL) { if (libCtxParam->valueType != BSL_PARAM_TYPE_CTX_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } decoderCtx->libCtx = (CRYPT_EAL_LibCtx *)(uintptr_t)libCtxParam->value; } const BSL_Param *targetAttrNameParam = BSL_PARAM_FindConstParam(param, CRYPT_PARAM_DECODE_TARGET_ATTR_NAME); if (targetAttrNameParam != NULL) { if (targetAttrNameParam->valueType != BSL_PARAM_TYPE_OCTETS_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } decoderCtx->targetAttrName = (const char *)(uintptr_t)targetAttrNameParam->value; } return CRYPT_SUCCESS; } int32_t DECODER_LowKeyObject2PkeyObjectGetParam(void *ctx, BSL_Param *param) { DECODER_Lowkey2PkeyCtx *decoderCtx = (DECODER_Lowkey2PkeyCtx *)ctx; if (decoderCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } DECODER_CommonCtx commonCtx = { .outFormat = decoderCtx->outFormat, .outType = decoderCtx->outType }; return DECODER_CommonGetParam(&commonCtx, param); } typedef struct LowKeyObjectMethodInfo { CRYPT_EAL_ImplPkeyMgmtExport export; CRYPT_EAL_ImplPkeyMgmtDupCtx dupCtx; CRYPT_EAL_ImplPkeyMgmtFreeCtx freeCtx; } LowKeyObjectMethodInfo; static int32_t GetLowKeyObjectInfo(const BSL_Param *inParam, void **object, int32_t *objectType, LowKeyObjectMethodInfo *method) { const BSL_Param *lowObjectRef = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_OBJECT_DATA); if (lowObjectRef == NULL || lowObjectRef->valueType != BSL_PARAM_TYPE_CTX_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } const BSL_Param *lowObjectRefType = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_OBJECT_TYPE); if (lowObjectRefType == NULL || lowObjectRefType->valueType != BSL_PARAM_TYPE_INT32) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } const BSL_Param *exportFunc = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_PKEY_EXPORT_METHOD_FUNC); if (exportFunc == NULL || exportFunc->valueType != BSL_PARAM_TYPE_FUNC_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } const BSL_Param *dupFunc = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_PKEY_DUP_METHOD_FUNC); if (dupFunc == NULL || dupFunc->valueType != BSL_PARAM_TYPE_FUNC_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } const BSL_Param *freeFunc = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_PKEY_FREE_METHOD_FUNC); if (freeFunc == NULL || freeFunc->valueType != BSL_PARAM_TYPE_FUNC_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (lowObjectRef->value == NULL || lowObjectRefType->value == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } *object = (void *)(uintptr_t)lowObjectRef->value; *objectType = *((int32_t *)(uintptr_t)lowObjectRefType->value); method->export = (CRYPT_EAL_ImplPkeyMgmtExport)(uintptr_t)exportFunc->value; method->dupCtx = (CRYPT_EAL_ImplPkeyMgmtDupCtx)(uintptr_t)dupFunc->value; method->freeCtx = (CRYPT_EAL_ImplPkeyMgmtFreeCtx)(uintptr_t)freeFunc->value; return CRYPT_SUCCESS; } static int32_t GetProviderInfo(const BSL_Param *inParam, CRYPT_EAL_ProvMgrCtx **lastDecoderProviderCtx) { const BSL_Param *lastDecoderProvCtxParam = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_PROVIDER_CTX); if (lastDecoderProvCtxParam != NULL) { if (lastDecoderProvCtxParam->valueType != BSL_PARAM_TYPE_CTX_PTR) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } *lastDecoderProviderCtx = (CRYPT_EAL_ProvMgrCtx *)(uintptr_t)lastDecoderProvCtxParam->value; } return CRYPT_SUCCESS; } typedef struct { CRYPT_EAL_PkeyMgmtInfo *pkeyAlgInfo; void *targetKeyRef; } ImportTargetPkeyArgs; static int32_t ImportTargetPkey(const BSL_Param *param, void *args) { if (param == NULL || args == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } ImportTargetPkeyArgs *importTargetPkeyArgs = (ImportTargetPkeyArgs *)args; void *provCtx = NULL; CRYPT_EAL_PkeyMgmtInfo *pkeyAlgInfo = importTargetPkeyArgs->pkeyAlgInfo; if (pkeyAlgInfo == NULL || pkeyAlgInfo->keyMgmtMethod->provNewCtx == NULL || pkeyAlgInfo->keyMgmtMethod->import == NULL || pkeyAlgInfo->keyMgmtMethod->freeCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = CRYPT_EAL_ProviderCtrl(pkeyAlgInfo->mgrCtx, CRYPT_PROVIDER_GET_USER_CTX, &provCtx, sizeof(provCtx)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } void *keyRef = pkeyAlgInfo->keyMgmtMethod->provNewCtx(provCtx, pkeyAlgInfo->algId); if (keyRef == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ret = pkeyAlgInfo->keyMgmtMethod->import(keyRef, param); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); pkeyAlgInfo->keyMgmtMethod->freeCtx(keyRef); return ret; } importTargetPkeyArgs->targetKeyRef = keyRef; return CRYPT_SUCCESS; } static int32_t TransLowKeyToTargetLowKey(CRYPT_EAL_PkeyMgmtInfo *pkeyAlgInfo, const LowKeyObjectMethodInfo *method, void *lowObjectRef, void **targetKeyRef) { ImportTargetPkeyArgs importTargetPkeyArgs = {0}; importTargetPkeyArgs.pkeyAlgInfo = pkeyAlgInfo; if (method->export == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_Param param[3] = { {CRYPT_PARAM_PKEY_PROCESS_FUNC, BSL_PARAM_TYPE_FUNC_PTR, ImportTargetPkey, 0, 0}, {CRYPT_PARAM_PKEY_PROCESS_ARGS, BSL_PARAM_TYPE_CTX_PTR, &importTargetPkeyArgs, 0, 0}, BSL_PARAM_END }; int32_t ret = method->export(lowObjectRef, param); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *targetKeyRef = importTargetPkeyArgs.targetKeyRef; return CRYPT_SUCCESS; } static int32_t DupLowKey(const LowKeyObjectMethodInfo *method, void *lowObjectRef, void **targetKeyRef) { if (method->dupCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } *targetKeyRef = method->dupCtx(lowObjectRef); if (*targetKeyRef == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } return CRYPT_SUCCESS; } static int32_t ConstructOutObjectParam(BSL_Param **outParam, void *object) { BSL_Param *result = BSL_SAL_Calloc(2, sizeof(BSL_Param)); if (result == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = BSL_PARAM_InitValue(&result[0], CRYPT_PARAM_DECODE_OBJECT_DATA, BSL_PARAM_TYPE_CTX_PTR, object, 0); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(result); BSL_ERR_PUSH_ERROR(ret); } *outParam = result; return ret; } /* input is pem format buffer, output is der format buffer */ int32_t DECODER_LowKeyObject2PkeyObjectDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) { if (ctx == NULL || inParam == NULL || outParam == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } DECODER_Lowkey2PkeyCtx *decoderCtx = (DECODER_Lowkey2PkeyCtx *)ctx; void *lowObjectRef = NULL; int32_t lowObjectRefType = 0; CRYPT_EAL_ProvMgrCtx *lastDecoderProviderCtx = NULL; LowKeyObjectMethodInfo method = {0}; void *targetKeyRef = NULL; CRYPT_EAL_PkeyMgmtInfo pkeyAlgInfo = {0}; int32_t ret = 0; RETURN_RET_IF_ERR(GetLowKeyObjectInfo(inParam, &lowObjectRef, &lowObjectRefType, &method), ret); if (method.freeCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } RETURN_RET_IF_ERR(GetProviderInfo(inParam, &lastDecoderProviderCtx), ret); RETURN_RET_IF_ERR(CRYPT_EAL_GetPkeyAlgInfo(decoderCtx->libCtx, lowObjectRefType, decoderCtx->targetAttrName, &pkeyAlgInfo), ret); if (pkeyAlgInfo.mgrCtx != lastDecoderProviderCtx) { ret = TransLowKeyToTargetLowKey(&pkeyAlgInfo, &method, lowObjectRef, &targetKeyRef); } else { ret = DupLowKey(&method, lowObjectRef, &targetKeyRef); } if (ret != CRYPT_SUCCESS) { goto EXIT; } CRYPT_EAL_PkeyCtx *ealPKey = CRYPT_EAL_MakeKeyByPkeyAlgInfo(&pkeyAlgInfo, targetKeyRef, sizeof(void *)); if (ealPKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); goto EXIT; } ret = ConstructOutObjectParam(outParam, ealPKey); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(ealPKey); BSL_ERR_PUSH_ERROR(ret); } return ret; EXIT: BSL_SAL_Free(pkeyAlgInfo.keyMgmtMethod); if (targetKeyRef != NULL) { method.freeCtx(targetKeyRef); } return ret; } void DECODER_LowKeyObject2PkeyObjectFreeOutData(void *ctx, BSL_Param *outParam) { DECODER_Lowkey2PkeyCtx *decoderCtx = (DECODER_Lowkey2PkeyCtx *)ctx; if (outParam == NULL || decoderCtx == NULL) { return; } BSL_Param *objectDataParam = BSL_PARAM_FindParam(outParam, CRYPT_PARAM_DECODE_OBJECT_DATA); if (objectDataParam == NULL || objectDataParam->valueType != BSL_PARAM_TYPE_CTX_PTR || objectDataParam->value == NULL) { return; } CRYPT_EAL_PkeyCtx *ealPKey = (CRYPT_EAL_PkeyCtx *)objectDataParam->value; CRYPT_EAL_PkeyFreeCtx(ealPKey); BSL_SAL_Free(outParam); } void DECODER_LowKeyObject2PkeyObjectFreeCtx(void *ctx) { if (ctx == NULL) { return; } BSL_SAL_Free(ctx); } #endif
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_decode_lowkey2pkey.c
C
unknown
11,815
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_CODECSKEY) && defined(HITLS_BSL_PEM) && defined(HITLS_CRYPTO_PROVIDER) #include <stdint.h> #include <string.h> #include "crypt_eal_implprovider.h" #include "crypt_errno.h" #include "crypt_params_key.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "bsl_pem_internal.h" #include "crypt_encode_decode_local.h" #include "crypt_decode_key_impl.h" typedef struct { void *provCtx; const char *outFormat; const char *outType; } DECODER_Pem2DerCtx; void *DECODER_Pem2DerNewCtx(void *provCtx) { (void)provCtx; DECODER_Pem2DerCtx *ctx = (DECODER_Pem2DerCtx *)BSL_SAL_Calloc(1, sizeof(DECODER_Pem2DerCtx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ctx->provCtx = provCtx; ctx->outFormat = "ASN1"; ctx->outType = NULL; return ctx; } int32_t DECODER_Pem2DerGetParam(void *ctx, BSL_Param *param) { DECODER_Pem2DerCtx *decoderCtx = (DECODER_Pem2DerCtx *)ctx; if (decoderCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } DECODER_CommonCtx commonCtx = { .outFormat = decoderCtx->outFormat, .outType = decoderCtx->outType }; return DECODER_CommonGetParam(&commonCtx, param); } int32_t DECODER_Pem2DerSetParam(void *ctx, const BSL_Param *param) { (void)ctx; (void)param; return CRYPT_SUCCESS; } /* input is pem format buffer, output is der format buffer */ int32_t DECODER_Pem2DerDecode(void *ctx, const BSL_Param *inParam, BSL_Param **outParam) { if (ctx == NULL || inParam == NULL || outParam == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_PEM_Symbol symbol = {0}; char *dataType = NULL; DECODER_Pem2DerCtx *decoderCtx = (DECODER_Pem2DerCtx *)ctx; const BSL_Param *input = BSL_PARAM_FindConstParam(inParam, CRYPT_PARAM_DECODE_BUFFER_DATA); if (input == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (input->value == NULL || input->valueLen == 0 || input->valueType != BSL_PARAM_TYPE_OCTETS) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } BSL_Buffer encode = {(uint8_t *)(uintptr_t)input->value, input->valueLen}; uint8_t *asn1Encode = NULL; uint32_t asn1Len = 0; int32_t ret = BSL_PEM_GetSymbolAndType((char *)encode.data, encode.dataLen, &symbol, &dataType); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_PEM_DecodePemToAsn1((char **)&encode.data, &encode.dataLen, &symbol, &asn1Encode, &asn1Len); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(asn1Encode); BSL_ERR_PUSH_ERROR(ret); return ret; } decoderCtx->outType = dataType; return CRYPT_DECODE_ConstructBufferOutParam(outParam, asn1Encode, asn1Len); } void DECODER_Pem2DerFreeOutData(void *ctx, BSL_Param *outParam) { (void)ctx; if (outParam == NULL) { return; } BSL_Param *asn1DataParam = BSL_PARAM_FindParam(outParam, CRYPT_PARAM_DECODE_BUFFER_DATA); if (asn1DataParam == NULL) { return; } BSL_SAL_Free(asn1DataParam->value); asn1DataParam->value = NULL; asn1DataParam->valueLen = 0; BSL_SAL_Free(outParam); } void DECODER_Pem2DerFreeCtx(void *ctx) { if (ctx == NULL) { return; } BSL_SAL_Free(ctx); } #endif /* HITLS_CRYPTO_CODECSKEY && HITLS_BSL_PEM && HITLS_CRYPTO_PROVIDER */
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_decode_pem2der.c
C
unknown
4,088
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_CODECSKEY) #include "securec.h" #include "bsl_sal.h" #include "bsl_list.h" #include "sal_file.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_eal_provider.h" #include "crypt_eal_implprovider.h" #include "crypt_eal_codecs.h" #include "crypt_provider.h" #include "crypt_eal_pkey.h" #include "bsl_types.h" #include "crypt_types.h" #include "crypt_utils.h" #include "eal_pkey.h" #include "crypt_encode_decode_local.h" #include "crypt_encode_decode_key.h" #if defined(HITLS_CRYPTO_PROVIDER) static int32_t SetDecodePoolParamForKey(CRYPT_DECODER_PoolCtx *poolCtx, char *targetType, char *targetFormat) { int32_t ret = CRYPT_DECODE_PoolCtrl(poolCtx, CRYPT_DECODE_POOL_CMD_SET_TARGET_FORMAT, targetFormat, (int32_t)strlen(targetFormat)); if (ret != CRYPT_SUCCESS) { return ret; } ret = CRYPT_DECODE_PoolCtrl(poolCtx, CRYPT_DECODE_POOL_CMD_SET_TARGET_TYPE, targetType, (int32_t)strlen(targetType)); if (ret != CRYPT_SUCCESS) { return ret; } return ret; } static int32_t GetObjectFromOutData(BSL_Param *outData, void **object) { if (outData == NULL || object == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_Param *param = BSL_PARAM_FindParam(outData, CRYPT_PARAM_DECODE_OBJECT_DATA); if (param == NULL || param->valueType != BSL_PARAM_TYPE_CTX_PTR || param->value == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } *object = param->value; return CRYPT_SUCCESS; } int32_t CRYPT_EAL_ProviderDecodeBuffKeyInner(CRYPT_EAL_LibCtx *libCtx, const char *attrName, int32_t keyType, const char *format, const char *type, BSL_Buffer *encode, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPKey) { char *targetType = "HIGH_KEY"; char *targetFormat = "OBJECT"; uint32_t index = 0; BSL_Param *outParam = NULL; bool isFreeOutData = false; BSL_Param input[3] = {{0}, {0}, BSL_PARAM_END}; CRYPT_EAL_PkeyCtx *tmpPKey = NULL; if (encode == NULL || encode->data == NULL || encode->dataLen == 0 || ealPKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DECODER_PoolCtx *poolCtx = CRYPT_DECODE_PoolNewCtx(libCtx, attrName, keyType, format, type); if (poolCtx == NULL) { return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = SetDecodePoolParamForKey(poolCtx, targetType, targetFormat); if (ret != CRYPT_SUCCESS) { goto EXIT; } (void)BSL_PARAM_InitValue(&input[index++], CRYPT_PARAM_DECODE_BUFFER_DATA, BSL_PARAM_TYPE_OCTETS, encode->data, encode->dataLen); if (pwd != NULL) { (void)BSL_PARAM_InitValue(&input[index++], CRYPT_PARAM_DECODE_PASSWORD, BSL_PARAM_TYPE_OCTETS, pwd->data, pwd->dataLen); } ret = CRYPT_DECODE_PoolDecode(poolCtx, input, &outParam); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = GetObjectFromOutData(outParam, (void **)(&tmpPKey)); if (ret != CRYPT_SUCCESS) { goto EXIT; } int32_t algId = CRYPT_EAL_PkeyGetId(tmpPKey); if (keyType != BSL_CID_UNKNOWN && algId != keyType) { ret = CRYPT_EAL_ERR_ALGID; BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID); goto EXIT; } ret = CRYPT_DECODE_PoolCtrl(poolCtx, CRYPT_DECODE_POOL_CMD_SET_FLAG_FREE_OUT_DATA, &isFreeOutData, sizeof(bool)); if (ret != CRYPT_SUCCESS) { goto EXIT; } *ealPKey = tmpPKey; BSL_SAL_Free(outParam); EXIT: CRYPT_DECODE_PoolFreeCtx(poolCtx); return ret; } #endif /* HITLS_CRYPTO_PROVIDER */ int32_t CRYPT_EAL_ProviderDecodeBuffKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, int32_t keyType, const char *format, const char *type, BSL_Buffer *encode, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPKey) { #ifdef HITLS_CRYPTO_PROVIDER return CRYPT_EAL_ProviderDecodeBuffKeyInner(libCtx, attrName, keyType, format, type, encode, pwd, ealPKey); #else (void)libCtx; (void)attrName; (void)keyType; int32_t encodeType = CRYPT_EAL_GetEncodeType(type); int32_t encodeFormat = CRYPT_EAL_GetEncodeFormat(format); if (pwd == NULL) { return CRYPT_EAL_DecodeBuffKey(encodeFormat, encodeType, encode, NULL, 0, ealPKey); } else { return CRYPT_EAL_DecodeBuffKey(encodeFormat, encodeType, encode, pwd->data, pwd->dataLen, ealPKey); } #endif } #ifdef HITLS_BSL_SAL_FILE int32_t CRYPT_EAL_ProviderDecodeFileKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, int32_t keyType, const char *format, const char *type, const char *path, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPKey) { if (path == NULL || strlen(path) > PATH_MAX_LEN) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer encode = {data, dataLen}; ret = CRYPT_EAL_ProviderDecodeBuffKey(libCtx, attrName, keyType, format, type, &encode, pwd, ealPKey); BSL_SAL_Free(data); return ret; } #endif /* HITLS_BSL_SAL_FILE */ #endif /* HITLS_CRYPTO_CODECSKEY */
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_decode_pkey.c
C
unknown
5,857
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #if defined(HITLS_CRYPTO_KEY_DECODE) && defined(HITLS_CRYPTO_RSA) #include "crypt_rsa.h" #include "bsl_asn1_internal.h" #include "bsl_params.h" #include "bsl_errno.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_params_key.h" #include "crypt_encode_decode_local.h" #include "crypt_encode_decode_key.h" static int32_t ProcRsaPubKey(const BSL_ASN1_Buffer *asn1, CRYPT_RSA_Ctx *rsaKey) { const BSL_Param param[3] = { {CRYPT_PARAM_RSA_E, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_E_IDX].buff, asn1[CRYPT_RSA_PRV_E_IDX].len, 0}, {CRYPT_PARAM_RSA_N, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_N_IDX].buff, asn1[CRYPT_RSA_PRV_N_IDX].len, 0}, BSL_PARAM_END }; return CRYPT_RSA_SetPubKeyEx(rsaKey, param); } static int32_t ProcRsaPrivKey(const BSL_ASN1_Buffer *asn1, CRYPT_RSA_Ctx *rsaKey) { const BSL_Param param[10] = { {CRYPT_PARAM_RSA_D, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_D_IDX].buff, asn1[CRYPT_RSA_PRV_D_IDX].len, 0}, {CRYPT_PARAM_RSA_N, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_N_IDX].buff, asn1[CRYPT_RSA_PRV_N_IDX].len, 0}, {CRYPT_PARAM_RSA_E, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_E_IDX].buff, asn1[CRYPT_RSA_PRV_E_IDX].len, 0}, {CRYPT_PARAM_RSA_P, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_P_IDX].buff, asn1[CRYPT_RSA_PRV_P_IDX].len, 0}, {CRYPT_PARAM_RSA_Q, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_Q_IDX].buff, asn1[CRYPT_RSA_PRV_Q_IDX].len, 0}, {CRYPT_PARAM_RSA_DP, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_DP_IDX].buff, asn1[CRYPT_RSA_PRV_DP_IDX].len, 0}, {CRYPT_PARAM_RSA_DQ, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_DQ_IDX].buff, asn1[CRYPT_RSA_PRV_DQ_IDX].len, 0}, {CRYPT_PARAM_RSA_QINV, BSL_PARAM_TYPE_OCTETS, asn1[CRYPT_RSA_PRV_QINV_IDX].buff, asn1[CRYPT_RSA_PRV_QINV_IDX].len, 0}, BSL_PARAM_END }; return CRYPT_RSA_SetPrvKeyEx(rsaKey, param); } static int32_t ProcRsaKeyPair(uint8_t *buff, uint32_t buffLen, CRYPT_RSA_Ctx *rsaKey) { // decode n and e BSL_ASN1_Buffer asn1[CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1] = {0}; int32_t ret = CRYPT_DECODE_RsaPrikeyAsn1Buff(buff, buffLen, asn1, CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = ProcRsaPrivKey(asn1, rsaKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return ProcRsaPubKey(asn1, rsaKey); } static int32_t ProcRsaPssParam(BSL_ASN1_Buffer *rsaPssParam, CRYPT_RSA_Ctx *rsaPriKey) { CRYPT_RsaPadType padType = CRYPT_EMSA_PSS; int32_t ret = CRYPT_RSA_Ctrl(rsaPriKey, CRYPT_CTRL_SET_RSA_PADDING, &padType, sizeof(CRYPT_RsaPadType)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (rsaPssParam == NULL || rsaPssParam->buff == NULL) { return CRYPT_SUCCESS; } CRYPT_RSA_PssPara para = {0}; ret = CRYPT_EAL_ParseRsaPssAlgParam(rsaPssParam, &para); if (ret != CRYPT_SUCCESS) { return ret; } BSL_Param param[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &para.mdId, sizeof(para.mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &para.mgfId, sizeof(para.mgfId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &para.saltLen, sizeof(para.saltLen), 0}, BSL_PARAM_END}; return CRYPT_RSA_Ctrl(rsaPriKey, CRYPT_CTRL_SET_RSA_EMSA_PSS, param, 0); } static int32_t DecodeRsaPrikeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *rsaPssParam, BslCid cid, CRYPT_RSA_Ctx **rsaPriKey) { CRYPT_RSA_Ctx *pctx = CRYPT_RSA_NewCtxEx(libCtx); if (pctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = ProcRsaKeyPair(buff, buffLen, pctx); if (ret != CRYPT_SUCCESS) { CRYPT_RSA_FreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } if (cid != BSL_CID_RSASSAPSS) { *rsaPriKey = pctx; return CRYPT_SUCCESS; } ret = ProcRsaPssParam(rsaPssParam, pctx); if (ret != CRYPT_SUCCESS) { CRYPT_RSA_FreeCtx(pctx); return ret; } *rsaPriKey = pctx; return ret; } int32_t CRYPT_RSA_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *rsaPssParam, CRYPT_RSA_Ctx **rsaPriKey) { return DecodeRsaPrikeyAsn1Buff(libCtx, buff, buffLen, rsaPssParam, BSL_CID_UNKNOWN, rsaPriKey); } int32_t CRYPT_RSA_ParsePubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *param, CRYPT_RSA_Ctx **rsaPubKey, BslCid cid) { // decode n and e BSL_ASN1_Buffer pubAsn1[CRYPT_RSA_PUB_E_IDX + 1] = {0}; int32_t ret = CRYPT_DECODE_RsaPubkeyAsn1Buff(buff, buffLen, pubAsn1, CRYPT_RSA_PUB_E_IDX + 1); if (ret != CRYPT_SUCCESS) { return ret; } CRYPT_RSA_Ctx *pctx = CRYPT_RSA_NewCtxEx(libCtx); if (pctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } BSL_Param pubParam[3] = { {CRYPT_PARAM_RSA_E, BSL_PARAM_TYPE_OCTETS, pubAsn1[CRYPT_RSA_PUB_E_IDX].buff, pubAsn1[CRYPT_RSA_PUB_E_IDX].len, 0}, {CRYPT_PARAM_RSA_N, BSL_PARAM_TYPE_OCTETS, pubAsn1[CRYPT_RSA_PUB_N_IDX].buff, pubAsn1[CRYPT_RSA_PUB_N_IDX].len, 0}, BSL_PARAM_END }; ret = CRYPT_RSA_SetPubKeyEx(pctx, pubParam); if (cid != BSL_CID_RSASSAPSS) { *rsaPubKey = pctx; return CRYPT_SUCCESS; } ret = ProcRsaPssParam(param, pctx); if (ret != CRYPT_SUCCESS) { CRYPT_RSA_FreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } *rsaPubKey = pctx; return ret; } int32_t CRYPT_RSA_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_RSA_Ctx **pubKey, bool isComplete) { if (pubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DECODE_SubPubkeyInfo subPubkeyInfo = {0}; CRYPT_RSA_Ctx *pctx = NULL; int32_t ret = CRYPT_DECODE_SubPubkey(buff, buffLen, NULL, &subPubkeyInfo, isComplete); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (subPubkeyInfo.keyType != BSL_CID_RSASSAPSS && subPubkeyInfo.keyType != BSL_CID_RSA) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH); return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH; } ret = CRYPT_RSA_ParsePubkeyAsn1Buff(libCtx, subPubkeyInfo.pubKey.buff, subPubkeyInfo.pubKey.len, &subPubkeyInfo.keyParam, &pctx, subPubkeyInfo.keyType); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } *pubKey = pctx; return ret; } int32_t CRYPT_RSA_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_RSA_Ctx **rsaPriKey) { CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0}; int32_t ret = CRYPT_DECODE_Pkcs8Info(buff, buffLen, NULL, &pk8PrikeyInfo); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (pk8PrikeyInfo.keyType != BSL_CID_RSASSAPSS && pk8PrikeyInfo.keyType != BSL_CID_RSA) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH); return CRYPT_DECODE_ERR_KEY_TYPE_NOT_MATCH; } ret = DecodeRsaPrikeyAsn1Buff(libCtx, pk8PrikeyInfo.pkeyRawKey, pk8PrikeyInfo.pkeyRawKeyLen, &pk8PrikeyInfo.keyParam, pk8PrikeyInfo.keyType, rsaPriKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_CRYPTO_KEY_DECODE && HITLS_CRYPTO_RSA
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_decode_rsa.c
C
unknown
8,338
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CODECSKEY #include <stdint.h> #include <string.h> #ifdef HITLS_BSL_SAL_FILE #include "sal_file.h" #endif #include "bsl_types.h" #include "bsl_asn1_internal.h" #ifdef HITLS_BSL_PEM #include "bsl_pem_internal.h" #endif // HITLS_BSL_PEM #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_types.h" #include "crypt_eal_pkey.h" #include "crypt_eal_codecs.h" #include "crypt_encode_decode_local.h" #include "crypt_encode_decode_key.h" int32_t CRYPT_EAL_GetEncodeFormat(const char *format) { if (format == NULL) { return BSL_FORMAT_UNKNOWN; } static const struct { const char *formatStr; int32_t formatInt; } FORMAT_MAP[] = { {"ASN1", BSL_FORMAT_ASN1}, {"PEM", BSL_FORMAT_PEM}, {"PFX_COM", BSL_FORMAT_PFX_COM}, {"PKCS12", BSL_FORMAT_PKCS12}, {"OBJECT", BSL_FORMAT_OBJECT} }; for (size_t i = 0; i < sizeof(FORMAT_MAP) / sizeof(FORMAT_MAP[0]); i++) { if (strcmp(format, FORMAT_MAP[i].formatStr) == 0) { return FORMAT_MAP[i].formatInt; } } return BSL_FORMAT_UNKNOWN; } #ifdef HITLS_BSL_PEM static int32_t EAL_GetPemPubKeySymbol(int32_t type, BSL_PEM_Symbol *symbol) { switch (type) { case CRYPT_PUBKEY_SUBKEY: symbol->head = BSL_PEM_PUB_KEY_BEGIN_STR; symbol->tail = BSL_PEM_PUB_KEY_END_STR; return CRYPT_SUCCESS; #ifdef HITLS_CRYPTO_RSA case CRYPT_PUBKEY_RSA: symbol->head = BSL_PEM_RSA_PUB_KEY_BEGIN_STR; symbol->tail = BSL_PEM_RSA_PUB_KEY_END_STR; return CRYPT_SUCCESS; #endif default: BSL_ERR_PUSH_ERROR(CRYPT_DECODE_NO_SUPPORT_TYPE); return CRYPT_DECODE_NO_SUPPORT_TYPE; } } static int32_t EAL_GetPemPriKeySymbol(int32_t type, BSL_PEM_Symbol *symbol) { switch (type) { #ifdef HITLS_CRYPTO_ECDSA case CRYPT_PRIKEY_ECC: symbol->head = BSL_PEM_EC_PRI_KEY_BEGIN_STR; symbol->tail = BSL_PEM_EC_PRI_KEY_END_STR; return CRYPT_SUCCESS; #endif #ifdef HITLS_CRYPTO_RSA case CRYPT_PRIKEY_RSA: symbol->head = BSL_PEM_RSA_PRI_KEY_BEGIN_STR; symbol->tail = BSL_PEM_RSA_PRI_KEY_END_STR; return CRYPT_SUCCESS; #endif case CRYPT_PRIKEY_PKCS8_UNENCRYPT: symbol->head = BSL_PEM_PRI_KEY_BEGIN_STR; symbol->tail = BSL_PEM_PRI_KEY_END_STR; return CRYPT_SUCCESS; case CRYPT_PRIKEY_PKCS8_ENCRYPT: symbol->head = BSL_PEM_P8_PRI_KEY_BEGIN_STR; symbol->tail = BSL_PEM_P8_PRI_KEY_END_STR; return CRYPT_SUCCESS; default: BSL_ERR_PUSH_ERROR(CRYPT_DECODE_NO_SUPPORT_TYPE); return CRYPT_DECODE_NO_SUPPORT_TYPE; } } #endif // HITLS_BSL_PEM #ifdef HITLS_CRYPTO_KEY_DECODE int32_t CRYPT_EAL_ParseAsn1PriKey(int32_t type, BSL_Buffer *encode, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey) { (void)pwd; switch (type) { #ifdef HITLS_CRYPTO_ECDSA case CRYPT_PRIKEY_ECC: return ParseEccPrikeyAsn1Buff(encode->data, encode->dataLen, NULL, ealPriKey); #endif #ifdef HITLS_CRYPTO_RSA case CRYPT_PRIKEY_RSA: return ParseRsaPrikeyAsn1Buff(encode->data, encode->dataLen, NULL, BSL_CID_UNKNOWN, ealPriKey); #endif case CRYPT_PRIKEY_PKCS8_UNENCRYPT: return ParsePk8PriKeyBuff(encode, ealPriKey); #ifdef HITLS_CRYPTO_KEY_EPKI case CRYPT_PRIKEY_PKCS8_ENCRYPT: return ParsePk8EncPriKeyBuff(encode, pwd, ealPriKey); #endif default: BSL_ERR_PUSH_ERROR(CRYPT_DECODE_NO_SUPPORT_TYPE); return CRYPT_DECODE_NO_SUPPORT_TYPE; } } #ifdef HITLS_BSL_PEM int32_t CRYPT_EAL_ParsePemPriKey(int32_t type, BSL_Buffer *encode, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey) { BSL_PEM_Symbol symbol = {0}; uint8_t *buff = encode->data; uint32_t buffLen = encode->dataLen; int32_t ret = EAL_GetPemPriKeySymbol(type, &symbol); if (ret != CRYPT_SUCCESS) { return ret; } BSL_Buffer asn1 = {0}; ret = BSL_PEM_DecodePemToAsn1((char **)&buff, &buffLen, &symbol, &(asn1.data), &(asn1.dataLen)); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_ParseAsn1PriKey(type, &asn1, pwd, ealPriKey); BSL_SAL_Free(asn1.data); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_BSL_PEM int32_t CRYPT_EAL_ParseUnknownPriKey(int32_t type, BSL_Buffer *encode, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey) { #ifdef HITLS_BSL_PEM bool isPem = BSL_PEM_IsPemFormat((char *)(encode->data), encode->dataLen); if (isPem) { return CRYPT_EAL_ParsePemPriKey(type, encode, pwd, ealPriKey); } #endif return CRYPT_EAL_ParseAsn1PriKey(type, encode, pwd, ealPriKey); } int32_t CRYPT_EAL_PriKeyParseBuff(BSL_ParseFormat format, int32_t type, BSL_Buffer *encode, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey) { if (encode == NULL || encode->data == NULL || encode->dataLen == 0 || ealPriKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } switch (format) { case BSL_FORMAT_ASN1: return CRYPT_EAL_ParseAsn1PriKey(type, encode, pwd, ealPriKey); #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: return CRYPT_EAL_ParsePemPriKey(type, encode, pwd, ealPriKey); #endif // HITLS_BSL_PEM case BSL_FORMAT_UNKNOWN: return CRYPT_EAL_ParseUnknownPriKey(type, encode, pwd, ealPriKey); default: return CRYPT_DECODE_NO_SUPPORT_FORMAT; } } int32_t CRYPT_EAL_ParseAsn1PubKey(int32_t type, BSL_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey) { switch (type) { case CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ: return CRYPT_EAL_ParseAsn1SubPubkey(encode->data, encode->dataLen, (void **)ealPubKey, false); case CRYPT_PUBKEY_SUBKEY: return CRYPT_EAL_ParseAsn1SubPubkey(encode->data, encode->dataLen, (void **)ealPubKey, true); default: #ifdef HITLS_CRYPTO_RSA return ParseRsaPubkeyAsn1Buff(encode->data, encode->dataLen, NULL, ealPubKey, BSL_CID_UNKNOWN); #else return CRYPT_DECODE_NO_SUPPORT_TYPE; #endif } } #ifdef HITLS_BSL_PEM int32_t CRYPT_EAL_ParsePemPubKey(int32_t type, BSL_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey) { BSL_PEM_Symbol symbol = {0}; int32_t ret = EAL_GetPemPubKeySymbol(type, &symbol); if (ret != CRYPT_SUCCESS) { return ret; } BSL_Buffer asn1 = {0}; ret = BSL_PEM_DecodePemToAsn1((char **)&(encode->data), &(encode->dataLen), &symbol, &(asn1.data), &(asn1.dataLen)); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_ParseAsn1PubKey(type, &asn1, ealPubKey); BSL_SAL_Free(asn1.data); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_BSL_PEM int32_t CRYPT_EAL_ParseUnknownPubKey(int32_t type, BSL_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey) { #ifdef HITLS_BSL_PEM bool isPem = BSL_PEM_IsPemFormat((char *)(encode->data), encode->dataLen); if (isPem) { return CRYPT_EAL_ParsePemPubKey(type, encode, ealPubKey); } #endif return CRYPT_EAL_ParseAsn1PubKey(type, encode, ealPubKey); } int32_t CRYPT_EAL_PubKeyParseBuff(BSL_ParseFormat format, int32_t type, BSL_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey) { if (encode == NULL || encode->data == NULL || encode->dataLen == 0 || ealPubKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } switch (format) { case BSL_FORMAT_ASN1: return CRYPT_EAL_ParseAsn1PubKey(type, encode, ealPubKey); #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: return CRYPT_EAL_ParsePemPubKey(type, encode, ealPubKey); #endif // HITLS_BSL_PEM case BSL_FORMAT_UNKNOWN: return CRYPT_EAL_ParseUnknownPubKey(type, encode, ealPubKey); default: return CRYPT_DECODE_NO_SUPPORT_FORMAT; } } int32_t CRYPT_EAL_UnKnownKeyParseBuff(BSL_ParseFormat format, const BSL_Buffer *pwd, BSL_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPKey) { int32_t ret; for (int32_t type = CRYPT_PRIKEY_PKCS8_UNENCRYPT; type <= CRYPT_PRIKEY_ECC; type++) { ret = CRYPT_EAL_PriKeyParseBuff(format, type, encode, pwd, ealPKey); if (ret == CRYPT_SUCCESS) { return ret; } } for (int32_t type = CRYPT_PUBKEY_SUBKEY; type <= CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ; type++) { ret = CRYPT_EAL_PubKeyParseBuff(format, type, encode, ealPKey); if (ret == CRYPT_SUCCESS) { return ret; } } return CRYPT_DECODE_NO_SUPPORT_TYPE; } int32_t CRYPT_EAL_DecodeBuffKey(int32_t format, int32_t type, BSL_Buffer *encode, const uint8_t *pwd, uint32_t pwdlen, CRYPT_EAL_PkeyCtx **ealPKey) { BSL_Buffer pwdBuffer = {(uint8_t *)(uintptr_t)pwd, pwdlen}; switch (type) { case CRYPT_PRIKEY_PKCS8_UNENCRYPT: case CRYPT_PRIKEY_PKCS8_ENCRYPT: #ifdef HITLS_CRYPTO_ECDSA case CRYPT_PRIKEY_ECC: #endif #ifdef HITLS_CRYPTO_RSA case CRYPT_PRIKEY_RSA: #endif return CRYPT_EAL_PriKeyParseBuff(format, type, encode, &pwdBuffer, ealPKey); case CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ: case CRYPT_PUBKEY_SUBKEY: #ifdef HITLS_CRYPTO_RSA case CRYPT_PUBKEY_RSA: #endif return CRYPT_EAL_PubKeyParseBuff(format, type, encode, ealPKey); case CRYPT_ENCDEC_UNKNOW: return CRYPT_EAL_UnKnownKeyParseBuff(format, &pwdBuffer, encode, ealPKey); default: BSL_ERR_PUSH_ERROR(CRYPT_DECODE_NO_SUPPORT_TYPE); return CRYPT_DECODE_NO_SUPPORT_TYPE; } } #ifdef HITLS_BSL_SAL_FILE int32_t CRYPT_EAL_PriKeyParseFile(BSL_ParseFormat format, int32_t type, const char *path, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey) { uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer encode = {data, dataLen}; ret = CRYPT_EAL_PriKeyParseBuff(format, type, &encode, pwd, ealPriKey); BSL_SAL_Free(data); return ret; } int32_t CRYPT_EAL_PubKeyParseFile(BSL_ParseFormat format, int32_t type, const char *path, CRYPT_EAL_PkeyCtx **ealPubKey) { uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer encode = {data, dataLen}; ret = CRYPT_EAL_PubKeyParseBuff(format, type, &encode, ealPubKey); BSL_SAL_Free(data); return ret; } int32_t CRYPT_EAL_UnKnownKeyParseFile(BSL_ParseFormat format, const char *path, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealKey) { uint8_t *data = NULL; uint32_t dataLen = 0; int32_t ret = BSL_SAL_ReadFile(path, &data, &dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_Buffer encode = {data, dataLen}; ret = CRYPT_EAL_UnKnownKeyParseBuff(format, pwd, &encode, ealKey); BSL_SAL_Free(data); return ret; } int32_t CRYPT_EAL_DecodeFileKey(int32_t format, int32_t type, const char *path, uint8_t *pwd, uint32_t pwdlen, CRYPT_EAL_PkeyCtx **ealPKey) { BSL_Buffer pwdBuffer = {(uint8_t *)pwd, pwdlen}; if (path == NULL || strlen(path) > PATH_MAX_LEN) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } switch (type) { case CRYPT_PRIKEY_PKCS8_UNENCRYPT: case CRYPT_PRIKEY_PKCS8_ENCRYPT: #ifdef HITLS_CRYPTO_RSA case CRYPT_PRIKEY_RSA: #endif #ifdef HITLS_CRYPTO_ECDSA case CRYPT_PRIKEY_ECC: #endif return CRYPT_EAL_PriKeyParseFile(format, type, path, &pwdBuffer, ealPKey); case CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ: case CRYPT_PUBKEY_SUBKEY: #ifdef HITLS_CRYPTO_RSA case CRYPT_PUBKEY_RSA: return CRYPT_EAL_PubKeyParseFile(format, type, path, ealPKey); #endif case CRYPT_ENCDEC_UNKNOW: return CRYPT_EAL_UnKnownKeyParseFile(format, path, &pwdBuffer, ealPKey); default: BSL_ERR_PUSH_ERROR(CRYPT_DECODE_NO_SUPPORT_TYPE); return CRYPT_DECODE_NO_SUPPORT_TYPE; } } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_CRYPTO_KEY_DECODE int32_t CRYPT_EAL_GetEncodeType(const char *type) { if (type == NULL) { return CRYPT_ENCDEC_UNKNOW; } static const struct { const char *typeStr; int32_t typeInt; } TYPE_MAP[] = { {"PRIKEY_PKCS8_UNENCRYPT", CRYPT_PRIKEY_PKCS8_UNENCRYPT}, {"PRIKEY_PKCS8_ENCRYPT", CRYPT_PRIKEY_PKCS8_ENCRYPT}, {"PRIKEY_RSA", CRYPT_PRIKEY_RSA}, {"PRIKEY_ECC", CRYPT_PRIKEY_ECC}, {"PUBKEY_SUBKEY", CRYPT_PUBKEY_SUBKEY}, {"PUBKEY_RSA", CRYPT_PUBKEY_RSA}, {"PUBKEY_SUBKEY_WITHOUT_SEQ", CRYPT_PUBKEY_SUBKEY_WITHOUT_SEQ} }; for (size_t i = 0; i < sizeof(TYPE_MAP) / sizeof(TYPE_MAP[0]); i++) { if (strcmp(type, TYPE_MAP[i].typeStr) == 0) { return TYPE_MAP[i].typeInt; } } return CRYPT_ENCDEC_UNKNOW; } #ifdef HITLS_CRYPTO_KEY_ENCODE int32_t CRYPT_EAL_EncodeAsn1PriKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey, const CRYPT_EncodeParam *encodeParam, int32_t type, BSL_Buffer *encode) { #ifndef HITLS_CRYPTO_KEY_EPKI (void)libCtx; (void)attrName; (void)encodeParam; #endif switch (type) { #ifdef HITLS_CRYPTO_ECDSA case CRYPT_PRIKEY_ECC: return EncodeEccPrikeyAsn1Buff(ealPriKey, NULL, encode); #endif #ifdef HITLS_CRYPTO_RSA case CRYPT_PRIKEY_RSA: return EncodeRsaPrikeyAsn1Buff(ealPriKey, CRYPT_PKEY_RSA, encode); #endif case CRYPT_PRIKEY_PKCS8_UNENCRYPT: return EncodePk8PriKeyBuff(ealPriKey, encode); #ifdef HITLS_CRYPTO_KEY_EPKI case CRYPT_PRIKEY_PKCS8_ENCRYPT: return EncodePk8EncPriKeyBuff(libCtx, attrName, ealPriKey, encodeParam, encode); #endif default: BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_FORMAT); return CRYPT_ENCODE_NO_SUPPORT_FORMAT; } } #ifdef HITLS_BSL_PEM int32_t CRYPT_EAL_EncodePemPriKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey, const CRYPT_EncodeParam *encodeParam, int32_t type, BSL_Buffer *encode) { BSL_Buffer asn1 = {0}; int32_t ret = CRYPT_EAL_EncodeAsn1PriKey(libCtx, attrName, ealPriKey, encodeParam, type, &asn1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_PEM_Symbol symbol = {0}; ret = EAL_GetPemPriKeySymbol(type, &symbol); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(asn1.data); return ret; } ret = BSL_PEM_EncodeAsn1ToPem(asn1.data, asn1.dataLen, &symbol, (char **)&encode->data, &encode->dataLen); BSL_SAL_Free(asn1.data); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_BSL_PEM int32_t CRYPT_EAL_PriKeyEncodeBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey, const CRYPT_EncodeParam *encodeParam, BSL_ParseFormat format, int32_t type, BSL_Buffer *encode) { if (ealPriKey == NULL || encode == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } switch (format) { case BSL_FORMAT_ASN1: return CRYPT_EAL_EncodeAsn1PriKey(libCtx, attrName, ealPriKey, encodeParam, type, encode); #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: return CRYPT_EAL_EncodePemPriKey(libCtx, attrName, ealPriKey, encodeParam, type, encode); #endif // HITLS_BSL_PEM default: BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_FORMAT); return CRYPT_ENCODE_NO_SUPPORT_FORMAT; } } int32_t CRYPT_EAL_PubKeyEncodeBuff(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ParseFormat format, int32_t type, BSL_Buffer *encode) { return CRYPT_EAL_EncodePubKeyBuffInternal(ealPubKey, format, type, true, encode); } static int32_t ProviderEncodeBuffKeyInternal(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPKey, const CRYPT_EncodeParam *encodeParam, int32_t format, int32_t type, BSL_Buffer *encode) { switch (type) { case CRYPT_PRIKEY_PKCS8_UNENCRYPT: case CRYPT_PRIKEY_PKCS8_ENCRYPT: #ifdef HITLS_CRYPTO_RSA case CRYPT_PRIKEY_RSA: #endif #ifdef HITLS_CRYPTO_ECDSA case CRYPT_PRIKEY_ECC: #endif return CRYPT_EAL_PriKeyEncodeBuff(libCtx, attrName, ealPKey, encodeParam, format, type, encode); case CRYPT_PUBKEY_SUBKEY: #ifdef HITLS_CRYPTO_RSA case CRYPT_PUBKEY_RSA: #endif return CRYPT_EAL_PubKeyEncodeBuff(ealPKey, format, type, encode); default: BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_TYPE); return CRYPT_ENCODE_NO_SUPPORT_TYPE; } } int32_t CRYPT_EAL_ProviderEncodeBuffKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPKey, const CRYPT_EncodeParam *encodeParam, const char *format, const char *type, BSL_Buffer *encode) { int32_t encodeType = CRYPT_EAL_GetEncodeType(type); int32_t encodeFormat = CRYPT_EAL_GetEncodeFormat(format); return ProviderEncodeBuffKeyInternal(libCtx, attrName, ealPKey, encodeParam, encodeFormat, encodeType, encode); } int32_t CRYPT_EAL_EncodeBuffKey(CRYPT_EAL_PkeyCtx *ealPKey, const CRYPT_EncodeParam *encodeParam, int32_t format, int32_t type, BSL_Buffer *encode) { return ProviderEncodeBuffKeyInternal(NULL, NULL, ealPKey, encodeParam, format, type, encode); } static int32_t CRYPT_EAL_EncodeAsn1PubKey(CRYPT_EAL_PkeyCtx *ealPubKey, int32_t type, bool isComplete, BSL_Buffer *encode) { switch (type) { case CRYPT_PUBKEY_SUBKEY: return CRYPT_EAL_EncodeAsn1SubPubkey(ealPubKey, isComplete, encode); #ifdef HITLS_CRYPTO_RSA case CRYPT_PUBKEY_RSA: return EncodeRsaPubkeyAsn1Buff(ealPubKey, NULL, encode); #endif default: BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_TYPE); return CRYPT_ENCODE_NO_SUPPORT_TYPE; } } #ifdef HITLS_BSL_PEM static int32_t CRYPT_EAL_EncodePemPubKey(CRYPT_EAL_PkeyCtx *ealPubKey, int32_t type, bool isComplete, BSL_Buffer *encode) { BSL_Buffer asn1 = {0}; int32_t ret = CRYPT_EAL_EncodeAsn1PubKey(ealPubKey, type, isComplete, &asn1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_PEM_Symbol symbol = {0}; ret = EAL_GetPemPubKeySymbol(type, &symbol); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(asn1.data); return ret; } ret = BSL_PEM_EncodeAsn1ToPem(asn1.data, asn1.dataLen, &symbol, (char **)&encode->data, &encode->dataLen); BSL_SAL_Free(asn1.data); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_BSL_PEM int32_t CRYPT_EAL_EncodePubKeyBuffInternal(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ParseFormat format, int32_t type, bool isComplete, BSL_Buffer *encode) { if (ealPubKey == NULL || encode == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } switch (format) { case BSL_FORMAT_ASN1: return CRYPT_EAL_EncodeAsn1PubKey(ealPubKey, type, isComplete, encode); #ifdef HITLS_BSL_PEM case BSL_FORMAT_PEM: return CRYPT_EAL_EncodePemPubKey(ealPubKey, type, isComplete, encode); #endif // HITLS_BSL_PEM default: BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_FORMAT); return CRYPT_ENCODE_NO_SUPPORT_FORMAT; } } #ifdef HITLS_BSL_SAL_FILE int32_t CRYPT_EAL_PriKeyEncodeFile(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey, const CRYPT_EncodeParam *encodeParam, BSL_ParseFormat format, int32_t type, const char *path) { BSL_Buffer encode = {0}; int32_t ret = CRYPT_EAL_PriKeyEncodeBuff(libCtx, attrName, ealPriKey, encodeParam, format, type, &encode); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_SAL_WriteFile(path, encode.data, encode.dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } BSL_SAL_Free(encode.data); return ret; } int32_t CRYPT_EAL_PubKeyEncodeFile(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ParseFormat format, int32_t type, const char *path) { BSL_Buffer encode = {0}; int32_t ret = CRYPT_EAL_PubKeyEncodeBuff(ealPubKey, format, type, &encode); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_SAL_WriteFile(path, encode.data, encode.dataLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } BSL_SAL_FREE(encode.data); return ret; } static int32_t ProviderEncodeFileKeyInternal(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPKey, const CRYPT_EncodeParam *encodeParam, int32_t format, int32_t type, const char *path) { if (path == NULL || strlen(path) > PATH_MAX_LEN) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } switch (type) { case CRYPT_PRIKEY_PKCS8_UNENCRYPT: case CRYPT_PRIKEY_PKCS8_ENCRYPT: #ifdef HITLS_CRYPTO_RSA case CRYPT_PRIKEY_RSA: #endif #ifdef HITLS_CRYPTO_ECDSA case CRYPT_PRIKEY_ECC: #endif return CRYPT_EAL_PriKeyEncodeFile(libCtx, attrName, ealPKey, encodeParam, format, type, path); case CRYPT_PUBKEY_SUBKEY: #ifdef HITLS_CRYPTO_RSA case CRYPT_PUBKEY_RSA: #endif return CRYPT_EAL_PubKeyEncodeFile(ealPKey, format, type, path); default: BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_TYPE); return CRYPT_ENCODE_NO_SUPPORT_TYPE; } } int32_t CRYPT_EAL_ProviderEncodeFileKey(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPKey, const CRYPT_EncodeParam *encodeParam, const char *format, const char *type, const char *path) { int32_t encodeType = CRYPT_EAL_GetEncodeType(type); int32_t encodeFormat = CRYPT_EAL_GetEncodeFormat(format); return ProviderEncodeFileKeyInternal(libCtx, attrName, ealPKey, encodeParam, encodeFormat, encodeType, path); } int32_t CRYPT_EAL_EncodeFileKey(CRYPT_EAL_PkeyCtx *ealPKey, const CRYPT_EncodeParam *encodeParam, int32_t format, int32_t type, const char *path) { return ProviderEncodeFileKeyInternal(NULL, NULL, ealPKey, encodeParam, format, type, path); } #endif // HITLS_BSL_SAL_FILE #endif // HITLS_CRYPTO_KEY_ENCODE #endif // HITLS_CRYPTO_CODECSKEY
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_encode_decode.c
C
unknown
23,492
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CODECSKEY #include "securec.h" #include "bsl_asn1_internal.h" #include "bsl_params.h" #include "bsl_err_internal.h" #include "bsl_obj_internal.h" #include "crypt_errno.h" #include "crypt_algid.h" #include "crypt_eal_kdf.h" #include "crypt_eal_rand.h" #include "crypt_eal_cipher.h" #include "crypt_params_key.h" #include "crypt_encode_decode_key.h" #include "crypt_encode_decode_local.h" #if defined(HITLS_CRYPTO_KEY_EPKI) && defined(HITLS_CRYPTO_KEY_ENCODE) /** * EncryptedPrivateKeyInfo ::= SEQUENCE { * encryptionAlgorithm EncryptionAlgorithmIdentifier, * encryptedData EncryptedData } * * https://datatracker.ietf.org/doc/html/rfc5208#autoid-6 */ static BSL_ASN1_TemplateItem g_pk8EncPriKeyTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, // EncryptionAlgorithmIdentifier {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 3}, // derivation param {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 3}, // enc scheme {BSL_ASN1_TAG_OBJECT_ID, 0, 4}, // alg {BSL_ASN1_TAG_OCTETSTRING, 0, 4}, // iv {BSL_ASN1_TAG_OCTETSTRING, 0, 1}, // EncryptedData }; #endif // HITLS_CRYPTO_KEY_EPKI && HITLS_CRYPTO_KEY_ENCODE #if defined(HITLS_CRYPTO_RSA) && (defined(HITLS_CRYPTO_KEY_ENCODE) || defined(HITLS_CRYPTO_KEY_INFO)) int32_t CRYPT_EAL_GetRsaPssPara(CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_RSA_PssPara *rsaPssParam) { int32_t ret; ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_GET_RSA_SALTLEN, &rsaPssParam->saltLen, sizeof(rsaPssParam->saltLen)); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_GET_RSA_MD, &rsaPssParam->mdId, sizeof(rsaPssParam->mdId)); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_GET_RSA_MGF, &rsaPssParam->mgfId, sizeof(rsaPssParam->mgfId)); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #ifdef HITLS_CRYPTO_KEY_ENCODE int32_t CRYPT_EAL_InitRsaPrv(const CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_PKEY_AlgId cid, CRYPT_EAL_PkeyPrv *rsaPrv) { uint32_t bnLen = CRYPT_EAL_PkeyGetKeyLen(ealPriKey); if (bnLen == 0) { return CRYPT_EAL_ALG_NOT_SUPPORT; } uint8_t *pri = (uint8_t *)BSL_SAL_Malloc(bnLen * 8); // 8 items if (pri == NULL) { return CRYPT_MEM_ALLOC_FAIL; } rsaPrv->id = cid; rsaPrv->key.rsaPrv.d = pri; rsaPrv->key.rsaPrv.n = pri + bnLen; rsaPrv->key.rsaPrv.p = pri + bnLen * 2; // 2nd buffer rsaPrv->key.rsaPrv.q = pri + bnLen * 3; // 3rd buffer rsaPrv->key.rsaPrv.dP = pri + bnLen * 4; // 4th buffer rsaPrv->key.rsaPrv.dQ = pri + bnLen * 5; // 5th buffer rsaPrv->key.rsaPrv.qInv = pri + bnLen * 6; // 6th buffer rsaPrv->key.rsaPrv.e = pri + bnLen * 7; // 7th buffer rsaPrv->key.rsaPrv.dLen = bnLen; rsaPrv->key.rsaPrv.nLen = bnLen; rsaPrv->key.rsaPrv.pLen = bnLen; rsaPrv->key.rsaPrv.qLen = bnLen; rsaPrv->key.rsaPrv.dPLen = bnLen; rsaPrv->key.rsaPrv.dQLen = bnLen; rsaPrv->key.rsaPrv.qInvLen = bnLen; rsaPrv->key.rsaPrv.eLen = bnLen; return CRYPT_SUCCESS; } void CRYPT_EAL_DeinitRsaPrv(CRYPT_EAL_PkeyPrv *rsaPrv) { BSL_SAL_ClearFree(rsaPrv->key.rsaPrv.d, rsaPrv->key.rsaPrv.dLen * 8); // 8 items } #endif // HITLS_CRYPTO_KEY_ENCODE #endif // HITLS_CRYPTO_RSA #ifdef HITLS_CRYPTO_KEY_DECODE #ifdef HITLS_CRYPTO_RSA static int32_t ProcRsaPssParam(BSL_ASN1_Buffer *rsaPssParam, CRYPT_EAL_PkeyCtx *ealPriKey) { CRYPT_RsaPadType padType = CRYPT_EMSA_PSS; int32_t ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_SET_RSA_PADDING, &padType, sizeof(CRYPT_RsaPadType)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (rsaPssParam == NULL || rsaPssParam->buff == NULL) { return CRYPT_SUCCESS; } CRYPT_RSA_PssPara para = {0}; ret = CRYPT_EAL_ParseRsaPssAlgParam(rsaPssParam, &para); if (ret != CRYPT_SUCCESS) { return ret; } BSL_Param param[4] = { {CRYPT_PARAM_RSA_MD_ID, BSL_PARAM_TYPE_INT32, &para.mdId, sizeof(para.mdId), 0}, {CRYPT_PARAM_RSA_MGF1_ID, BSL_PARAM_TYPE_INT32, &para.mgfId, sizeof(para.mgfId), 0}, {CRYPT_PARAM_RSA_SALTLEN, BSL_PARAM_TYPE_INT32, &para.saltLen, sizeof(para.saltLen), 0}, BSL_PARAM_END}; return CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_SET_RSA_EMSA_PSS, param, 0); } static int32_t SetRsaPubKey(const BSL_ASN1_Buffer *n, const BSL_ASN1_Buffer *e, CRYPT_EAL_PkeyCtx *ealPkey) { CRYPT_EAL_PkeyPub rsaPub = { .id = CRYPT_PKEY_RSA, .key.rsaPub = {.n = n->buff, .nLen = n->len, .e = e->buff, .eLen = e->len}}; return CRYPT_EAL_PkeySetPub(ealPkey, &rsaPub); } int32_t ParseRsaPubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *param, CRYPT_EAL_PkeyCtx **ealPubKey, BslCid cid) { // decode n and e BSL_ASN1_Buffer pubAsn1[CRYPT_RSA_PUB_E_IDX + 1] = {0}; int32_t ret = CRYPT_DECODE_RsaPubkeyAsn1Buff(buff, buffLen, pubAsn1, CRYPT_RSA_PUB_E_IDX + 1); if (ret != CRYPT_SUCCESS) { return ret; } CRYPT_EAL_PkeyCtx *pctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); if (pctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ret = SetRsaPubKey(pubAsn1 + CRYPT_RSA_PUB_N_IDX, pubAsn1 + CRYPT_RSA_PUB_E_IDX, pctx); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } if (cid != BSL_CID_RSASSAPSS) { *ealPubKey = pctx; return CRYPT_SUCCESS; } ret = ProcRsaPssParam(param, pctx); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } *ealPubKey = pctx; return ret; } static int32_t ProcEalRsaPrivKey(const BSL_ASN1_Buffer *asn1, CRYPT_EAL_PkeyCtx *ealPkey) { CRYPT_EAL_PkeyPrv rsaPrv = {0}; rsaPrv.id = CRYPT_PKEY_RSA; rsaPrv.key.rsaPrv.d = asn1[CRYPT_RSA_PRV_D_IDX].buff; rsaPrv.key.rsaPrv.dLen = asn1[CRYPT_RSA_PRV_D_IDX].len; rsaPrv.key.rsaPrv.n = asn1[CRYPT_RSA_PRV_N_IDX].buff; rsaPrv.key.rsaPrv.nLen = asn1[CRYPT_RSA_PRV_N_IDX].len; rsaPrv.key.rsaPrv.e = asn1[CRYPT_RSA_PRV_E_IDX].buff; rsaPrv.key.rsaPrv.eLen = asn1[CRYPT_RSA_PRV_E_IDX].len; rsaPrv.key.rsaPrv.p = asn1[CRYPT_RSA_PRV_P_IDX].buff; rsaPrv.key.rsaPrv.pLen = asn1[CRYPT_RSA_PRV_P_IDX].len; rsaPrv.key.rsaPrv.q = asn1[CRYPT_RSA_PRV_Q_IDX].buff; rsaPrv.key.rsaPrv.qLen = asn1[CRYPT_RSA_PRV_Q_IDX].len; rsaPrv.key.rsaPrv.dP = asn1[CRYPT_RSA_PRV_DP_IDX].buff; rsaPrv.key.rsaPrv.dPLen = asn1[CRYPT_RSA_PRV_DP_IDX].len; rsaPrv.key.rsaPrv.dQ = asn1[CRYPT_RSA_PRV_DQ_IDX].buff; rsaPrv.key.rsaPrv.dQLen = asn1[CRYPT_RSA_PRV_DQ_IDX].len; rsaPrv.key.rsaPrv.qInv = asn1[CRYPT_RSA_PRV_QINV_IDX].buff; rsaPrv.key.rsaPrv.qInvLen = asn1[CRYPT_RSA_PRV_QINV_IDX].len; return CRYPT_EAL_PkeySetPrv(ealPkey, &rsaPrv); } static int32_t ProcEalRsaKeyPair(uint8_t *buff, uint32_t buffLen, CRYPT_EAL_PkeyCtx *ealPkey) { // decode n and e BSL_ASN1_Buffer asn1[CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1] = {0}; int32_t ret = CRYPT_DECODE_RsaPrikeyAsn1Buff(buff, buffLen, asn1, CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = ProcEalRsaPrivKey(asn1, ealPkey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return SetRsaPubKey(asn1 + CRYPT_RSA_PRV_N_IDX, asn1 + CRYPT_RSA_PRV_E_IDX, ealPkey); } int32_t ParseRsaPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *rsaPssParam, BslCid cid, CRYPT_EAL_PkeyCtx **ealPriKey) { CRYPT_EAL_PkeyCtx *pctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_RSA); if (pctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = ProcEalRsaKeyPair(buff, buffLen, pctx); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } if (cid != BSL_CID_RSASSAPSS) { *ealPriKey = pctx; return CRYPT_SUCCESS; } ret = ProcRsaPssParam(rsaPssParam, pctx); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pctx); return ret; } *ealPriKey = pctx; return ret; } #endif #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) static int32_t EccEalKeyNew(BSL_ASN1_Buffer *ecParamOid, int32_t *alg, CRYPT_EAL_PkeyCtx **ealKey) { int32_t algId; BslOidString oidStr = {ecParamOid->len, (char *)ecParamOid->buff, 0}; CRYPT_PKEY_ParaId paraId = (CRYPT_PKEY_ParaId)BSL_OBJ_GetCID(&oidStr); if (paraId == CRYPT_ECC_SM2) { algId = CRYPT_PKEY_SM2; } else if (IsEcdsaEcParaId(paraId)) { algId = CRYPT_PKEY_ECDSA; } else { // scenario ecdh is not considered, and it will be improved in the future return CRYPT_DECODE_UNKNOWN_OID; } CRYPT_EAL_PkeyCtx *key = CRYPT_EAL_PkeyNewCtx(algId); if (key == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } #ifdef HITLS_CRYPTO_ECDSA if (paraId != CRYPT_ECC_SM2) { int32_t ret = CRYPT_EAL_PkeySetParaById(key, paraId); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(key); BSL_ERR_PUSH_ERROR(ret); return ret; } } #endif *ealKey = key; *alg = algId; return CRYPT_SUCCESS; } static int32_t ParseEccPubkeyAsn1Buff(BSL_ASN1_BitString *bitPubkey, BSL_ASN1_Buffer *ecParamOid, CRYPT_EAL_PkeyCtx **ealPubKey) { int32_t algId; CRYPT_EAL_PkeyCtx *pctx = NULL; int32_t ret = EccEalKeyNew(ecParamOid, &algId, &pctx); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_EAL_PkeyPub pub = {.id = algId, .key.eccPub = {.data = bitPubkey->buff, .len = bitPubkey->len}}; ret = CRYPT_EAL_PkeySetPub(pctx, &pub); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } *ealPubKey = pctx; return ret; } static int32_t ParseEccPrikeyAsn1(BSL_ASN1_Buffer *encode, BSL_ASN1_Buffer *pk8AlgoParam, CRYPT_EAL_PkeyCtx **ealPriKey) { BSL_ASN1_Buffer *prikey = &encode[CRYPT_ECPRIKEY_PRIKEY_IDX]; // the ECC OID BSL_ASN1_Buffer *ecParamOid = &encode[CRYPT_ECPRIKEY_PARAM_IDX]; // the parameters OID BSL_ASN1_Buffer *pubkey = &encode[CRYPT_ECPRIKEY_PUBKEY_IDX]; // the ECC OID BSL_ASN1_Buffer *param = pk8AlgoParam; if (ecParamOid->len != 0) { // has a valid Algorithm param param = ecParamOid; } else { if (param == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (param->len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM); return CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM; } } if (pubkey->len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ASN1_BUFF_FAILED); return CRYPT_DECODE_ASN1_BUFF_FAILED; } int32_t algId; CRYPT_EAL_PkeyCtx *pctx = NULL; int32_t ret = EccEalKeyNew(param, &algId, &pctx); // Changed ecParamOid to param if (ret != CRYPT_SUCCESS) { return ret; } CRYPT_EAL_PkeyPrv prv = {.id = algId, .key.eccPrv = {.data = prikey->buff, .len = prikey->len}}; ret = CRYPT_EAL_PkeySetPrv(pctx, &prv); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } // the tag of public key is BSL_ASN1_TAG_BITSTRING, 1 denote unusedBits CRYPT_EAL_PkeyPub pub = {.id = algId, .key.eccPub = {.data = pubkey->buff + 1, .len = pubkey->len - 1}}; ret = CRYPT_EAL_PkeySetPub(pctx, &pub); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } *ealPriKey = pctx; return ret; } int32_t ParseEccPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pk8AlgoParam, CRYPT_EAL_PkeyCtx **ealPriKey) { BSL_ASN1_Buffer asn1[CRYPT_ECPRIKEY_PUBKEY_IDX + 1] = {0}; int32_t ret = CRYPT_DECODE_PrikeyAsn1Buff(buff, buffLen, asn1, CRYPT_ECPRIKEY_PUBKEY_IDX + 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return ParseEccPrikeyAsn1(asn1, pk8AlgoParam, ealPriKey); } #endif // HITLS_CRYPTO_ECDSA || HITLS_CRYPTO_SM2 #ifdef HITLS_CRYPTO_ED25519 static int32_t ParseEd25519PrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, CRYPT_EAL_PkeyCtx **ealPriKey) { uint8_t *tmpBuff = buff; uint32_t tmpBuffLen = buffLen; int32_t ret = BSL_ASN1_DecodeTagLen(BSL_ASN1_TAG_OCTETSTRING, &tmpBuff, &tmpBuffLen, &tmpBuffLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_EAL_PkeyCtx *pctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ED25519); if (pctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } CRYPT_EAL_PkeyPrv prv = {.id = CRYPT_PKEY_ED25519, .key.curve25519Prv = {.data = tmpBuff, .len = tmpBuffLen}}; ret = CRYPT_EAL_PkeySetPrv(pctx, &prv); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } *ealPriKey = pctx; return CRYPT_SUCCESS; } static int32_t ParseEd25519PubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, CRYPT_EAL_PkeyCtx **ealPubKey) { CRYPT_EAL_PkeyCtx *pctx = CRYPT_EAL_PkeyNewCtx(CRYPT_PKEY_ED25519); if (pctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } CRYPT_EAL_PkeyPub pub = {.id = CRYPT_PKEY_ED25519, .key.curve25519Pub = {.data = buff, .len = buffLen}}; int32_t ret = CRYPT_EAL_PkeySetPub(pctx, &pub); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_PkeyFreeCtx(pctx); BSL_ERR_PUSH_ERROR(ret); return ret; } *ealPubKey = pctx; return ret; } #endif // HITLS_CRYPTO_ED25519 static int32_t ParsePk8PrikeyAsn1(CRYPT_ENCODE_DECODE_Pk8PrikeyInfo *pk8PrikeyInfo, CRYPT_EAL_PkeyCtx **ealPriKey) { #ifdef HITLS_CRYPTO_RSA if (pk8PrikeyInfo->keyType == BSL_CID_RSA || pk8PrikeyInfo->keyType == BSL_CID_RSASSAPSS) { return ParseRsaPrikeyAsn1Buff(pk8PrikeyInfo->pkeyRawKey, pk8PrikeyInfo->pkeyRawKeyLen, &pk8PrikeyInfo->keyParam, pk8PrikeyInfo->keyType, ealPriKey); } #endif #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) if (pk8PrikeyInfo->keyType == BSL_CID_EC_PUBLICKEY) { return ParseEccPrikeyAsn1Buff(pk8PrikeyInfo->pkeyRawKey, pk8PrikeyInfo->pkeyRawKeyLen, &pk8PrikeyInfo->keyParam, ealPriKey); } #endif #ifdef HITLS_CRYPTO_ED25519 if (pk8PrikeyInfo->keyType == BSL_CID_ED25519) { return ParseEd25519PrikeyAsn1Buff(pk8PrikeyInfo->pkeyRawKey, pk8PrikeyInfo->pkeyRawKeyLen, ealPriKey); } #endif return CRYPT_DECODE_UNSUPPORTED_PKCS8_TYPE; } int32_t ParseSubPubkeyAsn1(BSL_ASN1_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey) { uint8_t *algoBuff = encode->buff; // AlgorithmIdentifier Tag and Len, 2 bytes. uint32_t algoBuffLen = encode->len; BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {0}; int32_t ret = CRYPT_DECODE_AlgoIdAsn1Buff(algoBuff, algoBuffLen, NULL, algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1); if (ret != CRYPT_SUCCESS) { return ret; } BSL_ASN1_Buffer *oid = algoId; // OID BSL_ASN1_Buffer *algParam = algoId + 1; // the parameters BSL_ASN1_Buffer *pubkey = &encode[CRYPT_SUBKEYINFO_BITSTRING_IDX]; // the last BSL_ASN1_Buffer, the pubkey BSL_ASN1_BitString bitPubkey = {0}; ret = BSL_ASN1_DecodePrimitiveItem(pubkey, &bitPubkey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString oidStr = {oid->len, (char *)oid->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) if (cid == BSL_CID_EC_PUBLICKEY || cid == BSL_CID_SM2PRIME256) { return ParseEccPubkeyAsn1Buff(&bitPubkey, algParam, ealPubKey); } #endif #ifdef HITLS_CRYPTO_RSA if (cid == BSL_CID_RSA || cid == BSL_CID_RSASSAPSS) { return ParseRsaPubkeyAsn1Buff(bitPubkey.buff, bitPubkey.len, algParam, ealPubKey, cid); } #endif #ifdef HITLS_CRYPTO_ED25519 (void)algParam; if (cid == BSL_CID_ED25519) { return ParseEd25519PubkeyAsn1Buff(bitPubkey.buff, bitPubkey.len, ealPubKey); } #endif BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID); return CRYPT_DECODE_UNKNOWN_OID; } int32_t ParsePk8PriKeyBuff(BSL_Buffer *buff, CRYPT_EAL_PkeyCtx **ealPriKey) { uint8_t *tmpBuff = buff->data; uint32_t tmpBuffLen = buff->dataLen; CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0}; int32_t ret = CRYPT_DECODE_Pkcs8Info(tmpBuff, tmpBuffLen, NULL, &pk8PrikeyInfo); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return ParsePk8PrikeyAsn1(&pk8PrikeyInfo, ealPriKey); } #ifdef HITLS_CRYPTO_KEY_EPKI int32_t ParsePk8EncPriKeyBuff(BSL_Buffer *buff, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey) { BSL_Buffer decode = {0}; int32_t ret = CRYPT_DECODE_Pkcs8PrvDecrypt(NULL, NULL, buff, pwd, NULL, &decode); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = ParsePk8PriKeyBuff(&decode, ealPriKey); BSL_SAL_ClearFree(decode.data, decode.dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif int32_t CRYPT_EAL_ParseAsn1SubPubkey(uint8_t *buff, uint32_t buffLen, void **ealPubKey, bool isComplete) { // decode sub pubkey info BSL_ASN1_Buffer pubAsn1[CRYPT_SUBKEYINFO_BITSTRING_IDX + 1] = {0}; int32_t ret = CRYPT_DECODE_ParseSubKeyInfo(buff, buffLen, pubAsn1, isComplete); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return ParseSubPubkeyAsn1(pubAsn1, (CRYPT_EAL_PkeyCtx **)ealPubKey); } #endif // HITLS_CRYPTO_KEY_DECODE #ifdef HITLS_CRYPTO_KEY_ENCODE #ifdef HITLS_CRYPTO_RSA static int32_t EncodePssParam(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ASN1_Buffer *pssParam) { if (pssParam == NULL) { return CRYPT_SUCCESS; } int32_t padType = 0; int32_t ret = CRYPT_EAL_PkeyCtrl(ealPubKey, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(padType)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (padType != CRYPT_EMSA_PSS) { pssParam->tag = BSL_ASN1_TAG_NULL; return CRYPT_SUCCESS; } CRYPT_RSA_PssPara rsaPssParam = {0}; ret = CRYPT_EAL_GetRsaPssPara(ealPubKey, &rsaPssParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } pssParam->tag = BSL_ASN1_TAG_SEQUENCE | BSL_ASN1_TAG_CONSTRUCTED; return CRYPT_EAL_EncodeRsaPssAlgParam(&rsaPssParam, &pssParam->buff, &pssParam->len); } int32_t EncodeRsaPubkeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ASN1_Buffer *pssParam, BSL_Buffer *encodePub) { uint32_t bnLen = CRYPT_EAL_PkeyGetKeyLen(ealPubKey); if (bnLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT); return CRYPT_EAL_ALG_NOT_SUPPORT; } CRYPT_EAL_PkeyPub pub = {0}; pub.id = CRYPT_PKEY_RSA; pub.key.rsaPub.n = (uint8_t *)BSL_SAL_Malloc(bnLen); if (pub.key.rsaPub.n == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } pub.key.rsaPub.e = (uint8_t *)BSL_SAL_Malloc(bnLen); if (pub.key.rsaPub.e == NULL) { BSL_SAL_FREE(pub.key.rsaPub.n); BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } pub.key.rsaPub.nLen = bnLen; pub.key.rsaPub.eLen = bnLen; int32_t ret = CRYPT_EAL_PkeyGetPub(ealPubKey, &pub); if (ret != CRYPT_SUCCESS) { BSL_SAL_FREE(pub.key.rsaPub.n); BSL_SAL_FREE(pub.key.rsaPub.e); BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Buffer pubAsn1[CRYPT_RSA_PUB_E_IDX + 1] = { {BSL_ASN1_TAG_INTEGER, pub.key.rsaPub.nLen, pub.key.rsaPub.n}, {BSL_ASN1_TAG_INTEGER, pub.key.rsaPub.eLen, pub.key.rsaPub.e}, }; ret = CRYPT_ENCODE_RsaPubkeyAsn1Buff(pubAsn1, encodePub); BSL_SAL_FREE(pub.key.rsaPub.n); BSL_SAL_FREE(pub.key.rsaPub.e); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = EncodePssParam(ealPubKey, pssParam); if (ret != CRYPT_SUCCESS) { BSL_SAL_FREE(encodePub->data); BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t EncodeRsaPrvKey(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_ASN1_Buffer *pk8AlgoParam, BSL_Buffer *bitStr, CRYPT_PKEY_AlgId *cid) { CRYPT_RsaPadType pad = CRYPT_RSA_PADDINGMAX; int32_t ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_GET_RSA_PADDING, &pad, sizeof(pad)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_RSA_PssPara rsaPssParam = {0}; BSL_Buffer tmp = {0}; switch (pad) { case CRYPT_EMSA_PSS: ret = CRYPT_EAL_GetRsaPssPara(ealPriKey, &rsaPssParam); if (ret != BSL_SUCCESS) { return ret; } ret = EncodeRsaPrikeyAsn1Buff(ealPriKey, CRYPT_PKEY_RSA, &tmp); if (ret != BSL_SUCCESS) { return ret; } ret = CRYPT_EAL_EncodeRsaPssAlgParam(&rsaPssParam, &pk8AlgoParam->buff, &pk8AlgoParam->len); if (ret != BSL_SUCCESS) { BSL_SAL_ClearFree(tmp.data, tmp.dataLen); BSL_ERR_PUSH_ERROR(ret); return ret; } pk8AlgoParam->tag = BSL_ASN1_TAG_SEQUENCE | BSL_ASN1_TAG_CONSTRUCTED; *cid = (CRYPT_PKEY_AlgId)BSL_CID_RSASSAPSS; break; default: ret = EncodeRsaPrikeyAsn1Buff(ealPriKey, CRYPT_PKEY_RSA, &tmp); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } pk8AlgoParam->tag = BSL_ASN1_TAG_NULL; break; } bitStr->data = tmp.data; bitStr->dataLen = tmp.dataLen; return CRYPT_SUCCESS; } static void SetRsaPrv2Arr(const CRYPT_EAL_PkeyPrv *rsaPrv, BSL_ASN1_Buffer *asn1) { asn1[CRYPT_RSA_PRV_D_IDX].buff = rsaPrv->key.rsaPrv.d; asn1[CRYPT_RSA_PRV_D_IDX].len = rsaPrv->key.rsaPrv.dLen; asn1[CRYPT_RSA_PRV_N_IDX].buff = rsaPrv->key.rsaPrv.n; asn1[CRYPT_RSA_PRV_N_IDX].len = rsaPrv->key.rsaPrv.nLen; asn1[CRYPT_RSA_PRV_E_IDX].buff = rsaPrv->key.rsaPrv.e; asn1[CRYPT_RSA_PRV_E_IDX].len = rsaPrv->key.rsaPrv.eLen; asn1[CRYPT_RSA_PRV_P_IDX].buff = rsaPrv->key.rsaPrv.p; asn1[CRYPT_RSA_PRV_P_IDX].len = rsaPrv->key.rsaPrv.pLen; asn1[CRYPT_RSA_PRV_Q_IDX].buff = rsaPrv->key.rsaPrv.q; asn1[CRYPT_RSA_PRV_Q_IDX].len = rsaPrv->key.rsaPrv.qLen; asn1[CRYPT_RSA_PRV_DP_IDX].buff = rsaPrv->key.rsaPrv.dP; asn1[CRYPT_RSA_PRV_DP_IDX].len = rsaPrv->key.rsaPrv.dPLen; asn1[CRYPT_RSA_PRV_DQ_IDX].buff = rsaPrv->key.rsaPrv.dQ; asn1[CRYPT_RSA_PRV_DQ_IDX].len = rsaPrv->key.rsaPrv.dQLen; asn1[CRYPT_RSA_PRV_QINV_IDX].buff = rsaPrv->key.rsaPrv.qInv; asn1[CRYPT_RSA_PRV_QINV_IDX].len = rsaPrv->key.rsaPrv.qInvLen; asn1[CRYPT_RSA_PRV_D_IDX].tag = BSL_ASN1_TAG_INTEGER; asn1[CRYPT_RSA_PRV_N_IDX].tag = BSL_ASN1_TAG_INTEGER; asn1[CRYPT_RSA_PRV_E_IDX].tag = BSL_ASN1_TAG_INTEGER; asn1[CRYPT_RSA_PRV_P_IDX].tag = BSL_ASN1_TAG_INTEGER; asn1[CRYPT_RSA_PRV_Q_IDX].tag = BSL_ASN1_TAG_INTEGER; asn1[CRYPT_RSA_PRV_DP_IDX].tag = BSL_ASN1_TAG_INTEGER; asn1[CRYPT_RSA_PRV_DQ_IDX].tag = BSL_ASN1_TAG_INTEGER; asn1[CRYPT_RSA_PRV_QINV_IDX].tag = BSL_ASN1_TAG_INTEGER; } int32_t EncodeRsaPrikeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_PKEY_AlgId cid, BSL_Buffer *encode) { int32_t ret; BSL_ASN1_Buffer asn1[CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1] = {0}; CRYPT_EAL_PkeyPrv rsaPrv = {0}; ret = CRYPT_EAL_InitRsaPrv(ealPriKey, cid, &rsaPrv); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_EAL_PkeyGetPrv(ealPriKey, &rsaPrv); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_DeinitRsaPrv(&rsaPrv); BSL_ERR_PUSH_ERROR(ret); return ret; } SetRsaPrv2Arr(&rsaPrv, asn1); uint8_t version = 0; asn1[CRYPT_RSA_PRV_VERSION_IDX].buff = (uint8_t *)&version; asn1[CRYPT_RSA_PRV_VERSION_IDX].len = sizeof(version); asn1[CRYPT_RSA_PRV_VERSION_IDX].tag = BSL_ASN1_TAG_INTEGER; ret = CRYPT_ENCODE_RsaPrikeyAsn1Buff(asn1, CRYPT_RSA_PRV_OTHER_PRIME_IDX + 1, encode); CRYPT_EAL_DeinitRsaPrv(&rsaPrv); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) static inline void SetAsn1Buffer(BSL_ASN1_Buffer *asn, uint8_t tag, uint32_t len, uint8_t *buff) { asn->tag = tag; asn->len = len; asn->buff = buff; } static int32_t EncodeEccKeyPair(CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_PKEY_AlgId cid, BSL_ASN1_Buffer *asn1, BSL_Buffer *encode) { int32_t ret; uint32_t keyLen = CRYPT_EAL_PkeyGetKeyLen(ealPriKey); if (keyLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT); return CRYPT_EAL_ALG_NOT_SUPPORT; } uint8_t *pri = (uint8_t *)BSL_SAL_Malloc(keyLen); if (pri == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } CRYPT_EAL_PkeyPrv prv = {.id = cid, .key.eccPrv = {.data = pri, .len = keyLen}}; uint8_t *pub = NULL; do { ret = CRYPT_EAL_PkeyGetPrv(ealPriKey, &prv); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); break; } SetAsn1Buffer(asn1 + CRYPT_ECPRIKEY_PRIKEY_IDX, BSL_ASN1_TAG_OCTETSTRING, prv.key.eccPrv.len, prv.key.eccPrv.data); pub = (uint8_t *)BSL_SAL_Malloc(keyLen); if (pub == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); break; } CRYPT_EAL_PkeyPub pubKey = {.id = cid, .key.eccPub = {.data = pub, .len = keyLen}}; ret = CRYPT_EAL_PkeyCtrl(ealPriKey, CRYPT_CTRL_GEN_ECC_PUBLICKEY, NULL, 0); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); break; } ret = CRYPT_EAL_PkeyGetPub(ealPriKey, &pubKey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); break; } BSL_ASN1_BitString bitStr = {pubKey.key.eccPub.data, pubKey.key.eccPub.len, 0}; SetAsn1Buffer(asn1 + CRYPT_ECPRIKEY_PUBKEY_IDX, BSL_ASN1_TAG_BITSTRING, sizeof(BSL_ASN1_BitString), (uint8_t *)&bitStr); ret = CRYPT_ENCODE_EccPrikeyAsn1Buff(asn1, CRYPT_ECPRIKEY_PUBKEY_IDX + 1, encode); } while (0); BSL_SAL_ClearFree(pri, keyLen); BSL_SAL_FREE(pub); return ret; } int32_t EncodeEccPrikeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_ASN1_Buffer *pk8AlgoParam, BSL_Buffer *encode) { uint8_t version = 1; BSL_ASN1_Buffer asn1[CRYPT_ECPRIKEY_PUBKEY_IDX + 1] = { {BSL_ASN1_TAG_INTEGER, sizeof(version), &version}, {0}, {0}, {0}}; CRYPT_PKEY_AlgId cid = CRYPT_EAL_PkeyGetId(ealPriKey); BslOidString *oid = cid == CRYPT_PKEY_SM2 ? BSL_OBJ_GetOID((BslCid)CRYPT_ECC_SM2) : BSL_OBJ_GetOID((BslCid)CRYPT_EAL_PkeyGetParaId(ealPriKey)); if (oid == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); return CRYPT_ERR_ALGID; } if (pk8AlgoParam != NULL) { // pkcs8 pk8AlgoParam->buff = (uint8_t *)oid->octs; pk8AlgoParam->len = oid->octetLen; pk8AlgoParam->tag = BSL_ASN1_TAG_OBJECT_ID; } else { // pkcs1 asn1[CRYPT_ECPRIKEY_PARAM_IDX].buff = (uint8_t *)oid->octs; asn1[CRYPT_ECPRIKEY_PARAM_IDX].len = oid->octetLen; asn1[CRYPT_ECPRIKEY_PARAM_IDX].tag = BSL_ASN1_TAG_OBJECT_ID; } return EncodeEccKeyPair(ealPriKey, cid, asn1, encode); } static int32_t EncodeEccPubkeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ASN1_Buffer *ecParamOid, BSL_Buffer *encodePub) { int32_t ret; CRYPT_PKEY_ParaId paraId = CRYPT_EAL_PkeyGetParaId(ealPubKey); BslOidString *oid = BSL_OBJ_GetOID((BslCid)paraId); if (CRYPT_EAL_PkeyGetId(ealPubKey) == CRYPT_PKEY_SM2) { oid = BSL_OBJ_GetOID((BslCid)CRYPT_ECC_SM2); } if (oid == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); return CRYPT_ERR_ALGID; } ecParamOid->buff = (uint8_t *)oid->octs; ecParamOid->len = oid->octetLen; ecParamOid->tag = BSL_ASN1_TAG_OBJECT_ID; uint32_t pubLen = CRYPT_EAL_PkeyGetKeyLen(ealPubKey); if (pubLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT); return CRYPT_EAL_ALG_NOT_SUPPORT; } uint8_t *pub = (uint8_t *)BSL_SAL_Malloc(pubLen); if (pub == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } CRYPT_EAL_PkeyPub pubKey = {.id = CRYPT_EAL_PkeyGetId(ealPubKey), .key.eccPub = {.data = pub, .len = pubLen}}; ret = CRYPT_EAL_PkeyGetPub(ealPubKey, &pubKey); if (ret != CRYPT_SUCCESS) { BSL_SAL_FREE(pub); BSL_ERR_PUSH_ERROR(ret); return ret; } encodePub->data = pubKey.key.eccPub.data; encodePub->dataLen = pubKey.key.eccPub.len; return ret; } #endif // HITLS_CRYPTO_ECDSA || HITLS_CRYPTO_SM2 #ifdef HITLS_CRYPTO_ED25519 static int32_t EncodeEd25519PubkeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_Buffer *bitStr) { uint32_t pubLen = CRYPT_EAL_PkeyGetKeyLen(ealPubKey); if (pubLen == 0) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ALG_NOT_SUPPORT); return CRYPT_EAL_ALG_NOT_SUPPORT; } uint8_t *pub = (uint8_t *)BSL_SAL_Malloc(pubLen); if (pub == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } CRYPT_EAL_PkeyPub pubKey = {.id = CRYPT_PKEY_ED25519, .key.curve25519Pub = {.data = pub, .len = pubLen}}; int32_t ret = CRYPT_EAL_PkeyGetPub(ealPubKey, &pubKey); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(pub); BSL_ERR_PUSH_ERROR(ret); return ret; } bitStr->data = pubKey.key.curve25519Pub.data; bitStr->dataLen = pubKey.key.curve25519Pub.len; return CRYPT_SUCCESS; } static int32_t EncodeEd25519PrikeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_Buffer *bitStr) { uint8_t keyBuff[32] = {0}; // The length of the ed25519 private key is 32 CRYPT_EAL_PkeyPrv prv = {.id = CRYPT_PKEY_ED25519, .key.curve25519Prv = {.data = keyBuff, .len = sizeof(keyBuff)}}; int32_t ret = CRYPT_EAL_PkeyGetPrv(ealPriKey, &prv); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_TemplateItem octStr[] = {{BSL_ASN1_TAG_OCTETSTRING, 0, 0}}; BSL_ASN1_Template templ = {octStr, 1}; BSL_ASN1_Buffer prvAsn1 = {BSL_ASN1_TAG_OCTETSTRING, prv.key.curve25519Prv.len, prv.key.curve25519Prv.data}; return BSL_ASN1_EncodeTemplate(&templ, &prvAsn1, 1, &bitStr->data, &bitStr->dataLen); } #endif // HITLS_CRYPTO_ED25519 static int32_t EncodePk8AlgidAny(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_Buffer *bitStr, BSL_ASN1_Buffer *keyParam, BslCid *cidOut) { (void)keyParam; int32_t ret = CRYPT_DECODE_NO_SUPPORT_TYPE; BSL_Buffer tmp = {0}; CRYPT_PKEY_AlgId cid = CRYPT_EAL_PkeyGetId(ealPriKey); switch (cid) { #ifdef HITLS_CRYPTO_RSA case CRYPT_PKEY_RSA: ret = EncodeRsaPrvKey(ealPriKey, keyParam, &tmp, &cid); break; #endif #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) case CRYPT_PKEY_ECDSA: case CRYPT_PKEY_SM2: cid = (CRYPT_PKEY_AlgId)BSL_CID_EC_PUBLICKEY; ret = EncodeEccPrikeyAsn1Buff(ealPriKey, keyParam, &tmp); break; #endif #ifdef HITLS_CRYPTO_ED25519 case CRYPT_PKEY_ED25519: ret = EncodeEd25519PrikeyAsn1Buff(ealPriKey, &tmp); break; #endif default: ret = CRYPT_DECODE_NO_SUPPORT_TYPE; break; } if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } bitStr->data = tmp.data; bitStr->dataLen = tmp.dataLen; *cidOut = (BslCid)cid; return ret; } int32_t EncodePk8PriKeyBuff(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_Buffer *asn1) { int32_t ret; BSL_Buffer bitStr = {0}; CRYPT_ENCODE_DECODE_Pk8PrikeyInfo pk8PrikeyInfo = {0}; do { ret = EncodePk8AlgidAny(ealPriKey, &bitStr, &pk8PrikeyInfo.keyParam, &pk8PrikeyInfo.keyType); if (ret != CRYPT_SUCCESS) { break; } pk8PrikeyInfo.pkeyRawKey = bitStr.data; pk8PrikeyInfo.pkeyRawKeyLen = bitStr.dataLen; ret = CRYPT_ENCODE_Pkcs8Info(&pk8PrikeyInfo, asn1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); break; } } while (0); // rsa-pss mode release buffer if (pk8PrikeyInfo.keyParam.tag == (BSL_ASN1_TAG_SEQUENCE | BSL_ASN1_TAG_CONSTRUCTED)) { BSL_SAL_FREE(pk8PrikeyInfo.keyParam.buff); } BSL_SAL_ClearFree(bitStr.data, bitStr.dataLen); return ret; } #ifdef HITLS_CRYPTO_KEY_EPKI static int32_t CheckEncodeParam(const CRYPT_EncodeParam *encodeParam) { if (encodeParam == NULL || encodeParam->param == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (encodeParam->deriveMode != CRYPT_DERIVE_PBKDF2) { BSL_ERR_PUSH_ERROR(CRYPT_ENCODE_NO_SUPPORT_TYPE); return CRYPT_ENCODE_NO_SUPPORT_TYPE; } CRYPT_Pbkdf2Param *pkcsParam = (CRYPT_Pbkdf2Param *)encodeParam->param; if (pkcsParam->pwdLen > PWD_MAX_LEN || (pkcsParam->pwd == NULL && pkcsParam->pwdLen != 0)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } if (pkcsParam->pbesId != BSL_CID_PBES2 || pkcsParam->pbkdfId != BSL_CID_PBKDF2) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); return CRYPT_ERR_ALGID; } return CRYPT_SUCCESS; } int32_t EncodePk8EncPriKeyBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey, const CRYPT_EncodeParam *encodeParam, BSL_Buffer *encode) { /* EncAlgid */ int32_t ret = CheckEncodeParam(encodeParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_Pbkdf2Param *pkcs8Param = (CRYPT_Pbkdf2Param *)encodeParam->param; BSL_Buffer unEncrypted = {0}; ret = EncodePk8PriKeyBuff(ealPriKey, &unEncrypted); if (ret != CRYPT_SUCCESS) { return ret; } BSL_ASN1_Buffer asn1[CRYPT_PKCS_ENCPRIKEY_MAX] = {0}; ret = CRYPT_ENCODE_PkcsEncryptedBuff(libCtx, attrName, pkcs8Param, &unEncrypted, asn1); if (ret != CRYPT_SUCCESS) { BSL_SAL_ClearFree(unEncrypted.data, unEncrypted.dataLen); return ret; } BSL_ASN1_Template templ = {g_pk8EncPriKeyTempl, sizeof(g_pk8EncPriKeyTempl) / sizeof(g_pk8EncPriKeyTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asn1, CRYPT_PKCS_ENCPRIKEY_MAX, &encode->data, &encode->dataLen); BSL_SAL_ClearFree(unEncrypted.data, unEncrypted.dataLen); BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len); BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len); BSL_SAL_FREE(asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].buff); return ret; } #endif // HITLS_CRYPTO_KEY_EPKI static int32_t CRYPT_EAL_SubPubkeyGetInfo(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ASN1_Buffer *algo, BSL_Buffer *bitStr) { int32_t ret = CRYPT_ERR_ALGID; CRYPT_PKEY_AlgId cid = CRYPT_EAL_PkeyGetId(ealPubKey); BSL_Buffer bitTmp = {0}; BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {0}; #ifdef HITLS_CRYPTO_RSA if (cid == CRYPT_PKEY_RSA) { ret = EncodeRsaPubkeyAsn1Buff(ealPubKey, &algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX], &bitTmp); if (algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX].tag == (BSL_ASN1_TAG_SEQUENCE | BSL_ASN1_TAG_CONSTRUCTED)) { cid = (CRYPT_PKEY_AlgId)BSL_CID_RSASSAPSS; } } #endif #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) if (cid == CRYPT_PKEY_ECDSA || cid == CRYPT_PKEY_SM2) { cid = (CRYPT_PKEY_AlgId)BSL_CID_EC_PUBLICKEY; ret = EncodeEccPubkeyAsn1Buff(ealPubKey, &algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX], &bitTmp); } #endif #ifdef HITLS_CRYPTO_ED25519 if (cid == CRYPT_PKEY_ED25519) { ret = EncodeEd25519PubkeyAsn1Buff(ealPubKey, &bitTmp); } #endif if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString *oidStr = BSL_OBJ_GetOID((BslCid)cid); if (oidStr == NULL) { BSL_SAL_FREE(bitTmp.data); ret = CRYPT_ERR_ALGID; BSL_ERR_PUSH_ERROR(ret); goto EXIT; } algoId[BSL_ASN1_TAG_ALGOID_IDX].buff = (uint8_t *)oidStr->octs; algoId[BSL_ASN1_TAG_ALGOID_IDX].len = oidStr->octetLen; algoId[BSL_ASN1_TAG_ALGOID_IDX].tag = BSL_ASN1_TAG_OBJECT_ID; ret = CRYPT_ENCODE_AlgoIdAsn1Buff(algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1, &algo->buff, &algo->len); if (ret != CRYPT_SUCCESS) { BSL_SAL_FREE(bitTmp.data); BSL_ERR_PUSH_ERROR(ret); goto EXIT; } bitStr->data = bitTmp.data; bitStr->dataLen = bitTmp.dataLen; EXIT: #ifdef HITLS_CRYPTO_RSA if (cid == (CRYPT_PKEY_AlgId)BSL_CID_RSASSAPSS) { BSL_SAL_FREE(algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX].buff); } #endif return ret; } int32_t CRYPT_EAL_EncodeAsn1SubPubkey(CRYPT_EAL_PkeyCtx *ealPubKey, bool isComplete, BSL_Buffer *encodeH) { BSL_ASN1_Buffer algo = {0}; BSL_Buffer bitStr = {0}; int32_t ret = CRYPT_EAL_SubPubkeyGetInfo(ealPubKey, &algo, &bitStr); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_ENCODE_SubPubkeyByInfo(&algo, &bitStr, encodeH, isComplete); BSL_SAL_FREE(bitStr.data); BSL_SAL_FREE(algo.buff); return ret; } #ifdef HITLS_CRYPTO_RSA int32_t EncodeHashAlg(CRYPT_MD_AlgId mdId, BSL_ASN1_Buffer *asn) { if (mdId == CRYPT_MD_SHA1) { asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_HASH; asn->buff = NULL; asn->len = 0; return CRYPT_SUCCESS; } BslOidString *oidStr = BSL_OBJ_GetOID((BslCid)mdId); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); return CRYPT_ERR_ALGID; } BSL_ASN1_TemplateItem hashTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_OBJECT_ID, 0, 1}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 1}, }; BSL_ASN1_Template templ = {hashTempl, sizeof(hashTempl) / sizeof(hashTempl[0])}; BSL_ASN1_Buffer asnArr[2] = { {BSL_ASN1_TAG_OBJECT_ID, oidStr->octetLen, (uint8_t *)oidStr->octs}, {BSL_ASN1_TAG_NULL, 0, NULL}, }; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, 2, &(asn->buff), &(asn->len)); // 2: oid and null if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_HASH; return CRYPT_SUCCESS; } static int32_t EncodeMgfAlg(CRYPT_MD_AlgId mgfId, BSL_ASN1_Buffer *asn) { if (mgfId == CRYPT_MD_SHA1) { asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_MASKGEN; asn->buff = NULL; asn->len = 0; return CRYPT_SUCCESS; } BslOidString *mgfStr = BSL_OBJ_GetOID(BSL_CID_MGF1); if (mgfStr == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); return CRYPT_ERR_ALGID; } BslOidString *oidStr = BSL_OBJ_GetOID((BslCid)mgfId); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); return CRYPT_ERR_ALGID; } BSL_ASN1_TemplateItem mgfTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_OBJECT_ID, 0, 1}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 2}, }; BSL_ASN1_Template templ = {mgfTempl, sizeof(mgfTempl) / sizeof(mgfTempl[0])}; BSL_ASN1_Buffer asnArr[3] = { {BSL_ASN1_TAG_OBJECT_ID, mgfStr->octetLen, (uint8_t *)mgfStr->octs}, {BSL_ASN1_TAG_OBJECT_ID, oidStr->octetLen, (uint8_t *)oidStr->octs}, {BSL_ASN1_TAG_NULL, 0, NULL}, // param }; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, 3, &(asn->buff), &(asn->len)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_MASKGEN; return CRYPT_SUCCESS; } static int32_t EncodeSaltLen(int32_t saltLen, BSL_ASN1_Buffer *asn) { if (saltLen == 20) { // 20 : default saltLen asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_SALTLEN; asn->buff = NULL; asn->len = 0; return CRYPT_SUCCESS; } BSL_ASN1_Buffer saltAsn = {0}; int32_t ret = BSL_ASN1_EncodeLimb(BSL_ASN1_TAG_INTEGER, (uint64_t)saltLen, &saltAsn); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_TemplateItem saltTempl = {BSL_ASN1_TAG_INTEGER, 0, 0}; BSL_ASN1_Template templ = {&saltTempl, 1}; ret = BSL_ASN1_EncodeTemplate(&templ, &saltAsn, 1, &(asn->buff), &(asn->len)); BSL_SAL_Free(saltAsn.buff); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } asn->tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_SALTLEN; return CRYPT_SUCCESS; } #define X509_RSAPSS_ELEM_NUMBER 4 int32_t CRYPT_EAL_EncodeRsaPssAlgParam(const CRYPT_RSA_PssPara *rsaPssParam, uint8_t **buf, uint32_t *bufLen) { BSL_ASN1_Buffer asnArr[X509_RSAPSS_ELEM_NUMBER] = {0}; int32_t ret = EncodeHashAlg(rsaPssParam->mdId, &asnArr[0]); if (ret != CRYPT_SUCCESS) { return ret; } ret = EncodeMgfAlg(rsaPssParam->mgfId, &asnArr[1]); if (ret != CRYPT_SUCCESS) { goto EXIT; } ret = EncodeSaltLen(rsaPssParam->saltLen, &asnArr[2]); // 2: saltLength if (ret != CRYPT_SUCCESS) { goto EXIT; } if (asnArr[0].len + asnArr[1].len + asnArr[2].len == 0) { // [0]:hash + [1]:mgf + [2]:salt all default return ret; } // 3 : trailed asnArr[3].tag = BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_TRAILED; BSL_ASN1_TemplateItem rsapssTempl[] = { {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_HASH, BSL_ASN1_FLAG_DEFAULT, 0}, {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_MASKGEN, BSL_ASN1_FLAG_DEFAULT, 0}, {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_SALTLEN, BSL_ASN1_FLAG_DEFAULT, 0}, {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_TRAILED, BSL_ASN1_FLAG_DEFAULT, 0}, }; BSL_ASN1_Template templ = {rsapssTempl, sizeof(rsapssTempl) / sizeof(rsapssTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, asnArr, X509_RSAPSS_ELEM_NUMBER, buf, bufLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: for (uint32_t i = 0; i < X509_RSAPSS_ELEM_NUMBER; i++) { BSL_SAL_Free(asnArr[i].buff); } return ret; } #endif // HITLS_CRYPTO_RSA #endif // HITLS_CRYPTO_KEY_ENCODE #ifdef HITLS_PKI_PKCS12 #define HITLS_P7_SPECIFIC_ENCONTENTINFO_EXTENSION 0 /** * EncryptedContentInfo ::= SEQUENCE { * contentType ContentType, * contentEncryptionAlgorithm ContentEncryptionAlgorithmIdentifier, * encryptedContent [0] IMPLICIT EncryptedContent OPTIONAL * } * * https://datatracker.ietf.org/doc/html/rfc5652#section-6.1 */ static BSL_ASN1_TemplateItem g_enContentInfoTempl[] = { /* ContentType */ {BSL_ASN1_TAG_OBJECT_ID, 0, 0}, /* ContentEncryptionAlgorithmIdentifier */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, // ContentEncryptionAlgorithmIdentifier {BSL_ASN1_TAG_OBJECT_ID, 0, 1}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 2}, // derivation param {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, // enc scheme {BSL_ASN1_TAG_OBJECT_ID, 0, 3}, // alg {BSL_ASN1_TAG_OCTETSTRING, 0, 3}, // iv /* encryptedContent */ {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_P7_SPECIFIC_ENCONTENTINFO_EXTENSION, BSL_ASN1_FLAG_OPTIONAL, 0}, }; typedef enum { HITLS_P7_ENC_CONTINFO_TYPE_IDX, HITLS_P7_ENC_CONTINFO_ENCALG_IDX, HITLS_P7_ENC_CONTINFO_DERIVE_PARAM_IDX, HITLS_P7_ENC_CONTINFO_SYMALG_IDX, HITLS_P7_ENC_CONTINFO_SYMIV_IDX, HITLS_P7_ENC_CONTINFO_ENCONTENT_IDX, HITLS_P7_ENC_CONTINFO_MAX_IDX, } HITLS_P7_ENC_CONTINFO_IDX; #define HITLS_P7_SPECIFIC_UNPROTECTEDATTRS_EXTENSION 1 /** * EncryptedData ::= SEQUENCE { * version CMSVersion, * encryptedContentInfo EncryptedContentInfo, * unprotectedAttrs [1] IMPLICIT UnprotectedAttributes OPTIONAL * } * * https://datatracker.ietf.org/doc/html/rfc5652#page-29 */ static BSL_ASN1_TemplateItem g_encryptedDataTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* version */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* EncryptedContentInfo */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1}, /* unprotectedAttrs */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SET | HITLS_P7_SPECIFIC_UNPROTECTEDATTRS_EXTENSION, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY, 1}, }; typedef enum { HITLS_P7_ENCRYPTDATA_VERSION_IDX, HITLS_P7_ENCRYPTDATA_ENCRYPTINFO_IDX, HITLS_P7_ENCRYPTDATA_UNPROTECTEDATTRS_IDX, HITLS_P7_ENCRYPTDATA_MAX_IDX, } HITLS_P7_ENCRYPTDATA_IDX; #ifdef HITLS_PKI_PKCS12_PARSE static int32_t ParsePKCS7EncryptedContentInfo(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *encode, const uint8_t *pwd, uint32_t pwdlen, BSL_Buffer *output) { uint8_t *temp = encode->data; uint32_t tempLen = encode->dataLen; BSL_ASN1_Buffer asn1[HITLS_P7_ENC_CONTINFO_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_enContentInfoTempl, sizeof(g_enContentInfoTempl) / sizeof(g_enContentInfoTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asn1, HITLS_P7_ENC_CONTINFO_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString typeOidStr = {asn1[HITLS_P7_ENC_CONTINFO_TYPE_IDX].len, (char *)asn1[HITLS_P7_ENC_CONTINFO_TYPE_IDX].buff, 0}; BslCid cid = BSL_OBJ_GetCID(&typeOidStr); if (cid != BSL_CID_PKCS7_SIMPLEDATA) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNSUPPORTED_PKCS7_TYPE); return CRYPT_DECODE_UNSUPPORTED_PKCS7_TYPE; } BslOidString encOidStr = {asn1[HITLS_P7_ENC_CONTINFO_ENCALG_IDX].len, (char *)asn1[HITLS_P7_ENC_CONTINFO_ENCALG_IDX].buff, 0}; cid = BSL_OBJ_GetCID(&encOidStr); if (cid != BSL_CID_PBES2) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNSUPPORTED_ENCRYPT_TYPE); return CRYPT_DECODE_UNSUPPORTED_ENCRYPT_TYPE; } // parse sym alg id BslOidString symOidStr = {asn1[HITLS_P7_ENC_CONTINFO_SYMALG_IDX].len, (char *)asn1[HITLS_P7_ENC_CONTINFO_SYMALG_IDX].buff, 0}; BslCid symId = BSL_OBJ_GetCID(&symOidStr); if (symId == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID); return CRYPT_DECODE_UNKNOWN_OID; } BSL_Buffer derivekeyData = {asn1[HITLS_P7_ENC_CONTINFO_DERIVE_PARAM_IDX].buff, asn1[HITLS_P7_ENC_CONTINFO_DERIVE_PARAM_IDX].len}; BSL_Buffer ivData = {asn1[HITLS_P7_ENC_CONTINFO_SYMIV_IDX].buff, asn1[HITLS_P7_ENC_CONTINFO_SYMIV_IDX].len}; BSL_Buffer enData = {asn1[HITLS_P7_ENC_CONTINFO_ENCONTENT_IDX].buff, asn1[HITLS_P7_ENC_CONTINFO_ENCONTENT_IDX].len}; EncryptPara encPara = {.derivekeyData = &derivekeyData, .ivData = &ivData, .enData = &enData}; BSL_Buffer pwdBuffer = {(uint8_t *)(uintptr_t)pwd, pwdlen}; ret = CRYPT_DECODE_ParseEncDataAsn1(libCtx, attrName, symId, &encPara, &pwdBuffer, NULL, output); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t CRYPT_EAL_ParseAsn1PKCS7EncryptedData(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *encode, const uint8_t *pwd, uint32_t pwdlen, BSL_Buffer *output) { if (encode == NULL || pwd == NULL || output == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (pwdlen > PWD_MAX_LEN) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } uint8_t *temp = encode->data; uint32_t tempLen = encode->dataLen; BSL_ASN1_Buffer asn1[HITLS_P7_ENCRYPTDATA_MAX_IDX] = {0}; BSL_ASN1_Template templ = {g_encryptedDataTempl, sizeof(g_encryptedDataTempl) / sizeof(g_encryptedDataTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &temp, &tempLen, asn1, HITLS_P7_ENCRYPTDATA_MAX_IDX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t version = 0; ret = BSL_ASN1_DecodePrimitiveItem(&asn1[HITLS_P7_ENCRYPTDATA_VERSION_IDX], &version); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (version == 0 && asn1[HITLS_P7_ENCRYPTDATA_UNPROTECTEDATTRS_IDX].buff != NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS7_INVALIDE_ENCRYPTDATA_TYPE); return CRYPT_DECODE_PKCS7_INVALIDE_ENCRYPTDATA_TYPE; } // In RFC5652, if the encapsulated content type is other than id-data, then the value of version MUST be 2. if (version == 2 && asn1[HITLS_P7_ENCRYPTDATA_UNPROTECTEDATTRS_IDX].buff == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS7_INVALIDE_ENCRYPTDATA_TYPE); return CRYPT_DECODE_PKCS7_INVALIDE_ENCRYPTDATA_TYPE; } BSL_Buffer encryptInfo = {asn1[HITLS_P7_ENCRYPTDATA_ENCRYPTINFO_IDX].buff, asn1[HITLS_P7_ENCRYPTDATA_ENCRYPTINFO_IDX].len}; ret = ParsePKCS7EncryptedContentInfo(libCtx, attrName, &encryptInfo, pwd, pwdlen, output); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_PKI_PKCS12_PARSE #ifdef HITLS_PKI_PKCS12_GEN /* Encode PKCS7-EncryptData:only support PBES2 + PBKDF2, the param check ref CheckEncodeParam. */ static int32_t EncodePKCS7EncryptedContentInfo(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *data, const CRYPT_EncodeParam *encodeParam, BSL_Buffer *encode) { /* EncAlgid */ int32_t ret = CheckEncodeParam(encodeParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_Pbkdf2Param *pkcs7Param = (CRYPT_Pbkdf2Param *)encodeParam->param; BSL_ASN1_Buffer asn1[CRYPT_PKCS_ENCPRIKEY_MAX] = {0}; ret = CRYPT_ENCODE_PkcsEncryptedBuff(libCtx, attrName, pkcs7Param, data, asn1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } do { BslOidString *oidStr = BSL_OBJ_GetOID(BSL_CID_PKCS7_SIMPLEDATA); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); ret = CRYPT_ERR_ALGID; break; } BSL_ASN1_Buffer p7asn[HITLS_P7_ENC_CONTINFO_MAX_IDX] = { {BSL_ASN1_TAG_OBJECT_ID, oidStr->octetLen, (uint8_t *)oidStr->octs}, {asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].tag, asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].len, asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].buff}, {asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].tag, asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len, asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff}, {asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].tag, asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].len, asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].buff}, {asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].tag, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff}, {BSL_ASN1_CLASS_CTX_SPECIFIC | HITLS_P7_SPECIFIC_ENCONTENTINFO_EXTENSION, asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].len, asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].buff}, }; BSL_ASN1_Template templ = {g_enContentInfoTempl, sizeof(g_enContentInfoTempl) / sizeof(g_enContentInfoTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&templ, p7asn, HITLS_P7_ENC_CONTINFO_MAX_IDX, &encode->data, &encode->dataLen); } while (0); BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len); BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len); BSL_SAL_FREE(asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].buff); return ret; } int32_t CRYPT_EAL_EncodePKCS7EncryptDataBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, BSL_Buffer *data, const void *encodeParam, BSL_Buffer *encode) { if (data == NULL || encodeParam == NULL || encode == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_Buffer contentInfo = {0}; int32_t ret = EncodePKCS7EncryptedContentInfo(libCtx, attrName, data, encodeParam, &contentInfo); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint8_t version = 0; BSL_ASN1_Buffer asn1[HITLS_P7_ENCRYPTDATA_MAX_IDX] = { {BSL_ASN1_TAG_INTEGER, sizeof(version), &version}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, contentInfo.dataLen, contentInfo.data}, {0, 0, 0}, }; BSL_ASN1_Template templ = {g_encryptedDataTempl, sizeof(g_encryptedDataTempl) / sizeof(g_encryptedDataTempl[0])}; BSL_Buffer tmp = {0}; ret = BSL_ASN1_EncodeTemplate(&templ, asn1, HITLS_P7_ENCRYPTDATA_MAX_IDX, &tmp.data, &tmp.dataLen); BSL_SAL_FREE(contentInfo.data); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } encode->data = tmp.data; encode->dataLen = tmp.dataLen; return ret; } #endif // HITLS_PKI_PKCS12_GEN #endif // HITLS_PKI_PKCS12 #endif // HITLS_CRYPTO_CODECSKEY
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_encode_decode_local.c
C
unknown
56,034
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_ENCODE_DECODE_KEY_LOCAL_H #define CRYPT_ENCODE_DECODE_KEY_LOCAL_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CODECSKEY #include "bsl_types.h" #include "bsl_asn1_internal.h" #include "crypt_types.h" #include "crypt_eal_pkey.h" #ifdef HITLS_CRYPTO_RSA #include "crypt_rsa.h" #endif #ifdef HITLS_CRYPTO_SM2 #include "crypt_sm2.h" #endif #ifdef HITLS_CRYPTO_ED25519 #include "crypt_curve25519.h" #endif #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ typedef struct { BSL_Buffer *derivekeyData; BSL_Buffer *ivData; BSL_Buffer *enData; } EncryptPara; typedef enum { CRYPT_RSA_PUB_N_IDX = 0, CRYPT_RSA_PUB_E_IDX = 1, } CRYPT_RSA_PUB_TEMPL_IDX; typedef enum { BSL_ASN1_TAG_ALGOID_IDX = 0, BSL_ASN1_TAG_ALGOID_ANY_IDX = 1, } ALGOID_TEMPL_IDX; typedef enum { CRYPT_SUBKEYINFO_ALGOID_IDX = 0, CRYPT_SUBKEYINFO_BITSTRING_IDX = 1, } CRYPT_SUBKEYINFO_TEMPL_IDX; typedef enum { CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX, CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX, CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX, CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX, CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX, CRYPT_PKCS_ENCPRIKEY_MAX } CRYPT_PKCS_ENCPRIKEY_TEMPL_IDX; typedef enum { CRYPT_ECPRIKEY_VERSION_IDX = 0, CRYPT_ECPRIKEY_PRIKEY_IDX = 1, CRYPT_ECPRIKEY_PARAM_IDX = 2, CRYPT_ECPRIKEY_PUBKEY_IDX = 3, } CRYPT_ECPRIKEY_TEMPL_IDX; typedef enum { CRYPT_RSA_PRV_VERSION_IDX = 0, CRYPT_RSA_PRV_N_IDX = 1, CRYPT_RSA_PRV_E_IDX = 2, CRYPT_RSA_PRV_D_IDX = 3, CRYPT_RSA_PRV_P_IDX = 4, CRYPT_RSA_PRV_Q_IDX = 5, CRYPT_RSA_PRV_DP_IDX = 6, CRYPT_RSA_PRV_DQ_IDX = 7, CRYPT_RSA_PRV_QINV_IDX = 8, CRYPT_RSA_PRV_OTHER_PRIME_IDX = 9 } CRYPT_RSA_PRV_TEMPL_IDX; #define CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_HASH 0 #define CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_MASKGEN 1 #define CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_SALTLEN 2 #define CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_TRAILED 3 #define PATH_MAX_LEN 4096 #define PWD_MAX_LEN 4096 #ifdef HITLS_CRYPTO_KEY_DECODE int32_t ParseSubPubkeyAsn1(BSL_ASN1_Buffer *encode, CRYPT_EAL_PkeyCtx **ealPubKey); int32_t ParseRsaPubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *param, CRYPT_EAL_PkeyCtx **ealPubKey, BslCid cid); int32_t ParseRsaPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *rsaPssParam, BslCid cid, CRYPT_EAL_PkeyCtx **ealPriKey); int32_t ParseEccPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pk8AlgoParam, CRYPT_EAL_PkeyCtx **ealPriKey); int32_t ParsePk8PriKeyBuff(BSL_Buffer *buff, CRYPT_EAL_PkeyCtx **ealPriKey); #ifdef HITLS_CRYPTO_KEY_EPKI int32_t ParsePk8EncPriKeyBuff(BSL_Buffer *buff, const BSL_Buffer *pwd, CRYPT_EAL_PkeyCtx **ealPriKey); int32_t CRYPT_DECODE_Pkcs8PrvDecrypt(CRYPT_EAL_LibCtx *libctx, const char *attrName, BSL_Buffer *buff, const BSL_Buffer *pwd, BSL_ASN1_DecTemplCallBack keyInfoCb, BSL_Buffer *decode); int32_t CRYPT_DECODE_ParseEncDataAsn1(CRYPT_EAL_LibCtx *libctx, const char *attrName, BslCid symAlg, EncryptPara *encPara, const BSL_Buffer *pwd, BSL_ASN1_DecTemplCallBack keyInfoCb, BSL_Buffer *decode); #endif int32_t CRYPT_EAL_ParseAsn1SubPubkey(uint8_t *buff, uint32_t buffLen, void **ealPubKey, bool isComplete); int32_t CRYPT_DECODE_AlgoIdAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb, BSL_ASN1_Buffer *algoId, uint32_t algoIdNum); int32_t CRYPT_DECODE_ConstructBufferOutParam(BSL_Param **outParam, uint8_t *buffer, uint32_t bufferLen); int32_t CRYPT_DECODE_ParseSubKeyInfo(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pubAsn1, bool isComplete); int32_t CRYPT_DECODE_PrikeyAsn1Buff(uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *asn1, uint32_t arrNum); #ifdef HITLS_CRYPTO_RSA int32_t CRYPT_DECODE_RsaPubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pubAsn1, uint32_t arrNum); int32_t CRYPT_DECODE_RsaPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *asn1, uint32_t asn1Num); int32_t CRYPT_RSA_ParsePubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *param, CRYPT_RSA_Ctx **rsaPubKey, BslCid cid); int32_t CRYPT_RSA_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_RSA_Ctx **rsaPriKey); int32_t CRYPT_RSA_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_RSA_Ctx **pubKey, bool isComplete); int32_t CRYPT_RSA_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *rsaPssParam, CRYPT_RSA_Ctx **rsaPriKey); #endif #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_ECDH) int32_t CRYPT_ECC_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, void **pubKey, bool isComplete); int32_t CRYPT_ECC_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, void **ecdsaPriKey); int32_t CRYPT_ECC_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *pk8AlgoParam, void **ecPriKey); #endif #ifdef HITLS_CRYPTO_SM2 int32_t CRYPT_SM2_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_SM2_Ctx **pubKey, bool isComplete); int32_t CRYPT_SM2_ParsePrikeyAsn1Buff(void *libCtx, uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *pk8AlgoParam, CRYPT_SM2_Ctx **sm2PriKey); int32_t CRYPT_SM2_ParsePkcs8Key(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_SM2_Ctx **sm2PriKey); #endif #ifdef HITLS_CRYPTO_ED25519 int32_t CRYPT_ED25519_ParsePkcs8Key(void *libCtx, uint8_t *buffer, uint32_t bufferLen, CRYPT_CURVE25519_Ctx **ed25519PriKey); int32_t CRYPT_ED25519_ParseSubPubkeyAsn1Buff(void *libCtx, uint8_t *buff, uint32_t buffLen, CRYPT_CURVE25519_Ctx **pubKey, bool isComplete); #endif #endif #ifdef HITLS_CRYPTO_KEY_ENCODE int32_t EncodeRsaPubkeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPubKey, BSL_ASN1_Buffer *pssParam, BSL_Buffer *encodePub); int32_t EncodeRsaPrikeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPriKey, CRYPT_PKEY_AlgId cid, BSL_Buffer *encode); int32_t EncodeEccPrikeyAsn1Buff(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_ASN1_Buffer *pk8AlgoParam, BSL_Buffer *encode); int32_t EncodePk8PriKeyBuff(CRYPT_EAL_PkeyCtx *ealPriKey, BSL_Buffer *asn1); int32_t CRYPT_ENCODE_SubPubkeyByInfo(BSL_ASN1_Buffer *algo, BSL_Buffer *bitStr, BSL_Buffer *encodeH, bool isComplete); int32_t CRYPT_ENCODE_AlgoIdAsn1Buff(BSL_ASN1_Buffer *algoId, uint32_t algoIdNum, uint8_t **buff, uint32_t *buffLen); int32_t CRYPT_ENCODE_PkcsEncryptedBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_Pbkdf2Param *pkcsParam, BSL_Buffer *unEncrypted, BSL_ASN1_Buffer *asn1); int32_t CRYPT_ENCODE_EccPrikeyAsn1Buff(BSL_ASN1_Buffer *asn1, uint32_t asn1Num, BSL_Buffer *encode); #ifdef HITLS_CRYPTO_KEY_EPKI int32_t EncodePk8EncPriKeyBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_EAL_PkeyCtx *ealPriKey, const CRYPT_EncodeParam *encodeParam, BSL_Buffer *encode); #endif int32_t CRYPT_EAL_EncodeAsn1SubPubkey(CRYPT_EAL_PkeyCtx *ealPubKey, bool isComplete, BSL_Buffer *encodeH); #ifdef HITLS_CRYPTO_RSA int32_t CRYPT_ENCODE_RsaPrikeyAsn1Buff(BSL_ASN1_Buffer *asn1, uint32_t asn1Num, BSL_Buffer *encode); int32_t CRYPT_ENCODE_RsaPubkeyAsn1Buff(BSL_ASN1_Buffer *pubAsn1, BSL_Buffer *encodePub); #endif #endif static inline bool IsEcdsaEcParaId(int32_t paraId) { return paraId == CRYPT_ECC_NISTP224 || paraId == CRYPT_ECC_NISTP256 || paraId == CRYPT_ECC_NISTP384 || paraId == CRYPT_ECC_NISTP521 || paraId == CRYPT_ECC_BRAINPOOLP256R1 || paraId == CRYPT_ECC_BRAINPOOLP384R1 || paraId == CRYPT_ECC_BRAINPOOLP512R1; } #ifdef __cplusplus } #endif #endif // HITLS_CRYPTO_CODECSKEY #endif // CRYPT_ENCODE_DECODE_KEY_LOCAL_H
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_encode_decode_local.h
C
unknown
8,212
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CODECSKEY #include <stdint.h> #include "securec.h" #include "bsl_types.h" #include "bsl_asn1_internal.h" #include "bsl_obj_internal.h" #include "bsl_err_internal.h" #include "crypt_params_key.h" #include "crypt_errno.h" #include "crypt_encode_decode_key.h" #include "crypt_encode_decode_local.h" #include "crypt_eal_kdf.h" #include "crypt_eal_cipher.h" #include "crypt_eal_rand.h" #ifdef HITLS_CRYPTO_RSA /** * RSAPrivateKey ::= SEQUENCE { * version Version, * 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 * otherPrimeInfos OtherPrimeInfos OPTIONAL * } * * https://datatracker.ietf.org/doc/html/rfc3447#autoid-39 */ static BSL_ASN1_TemplateItem g_rsaPrvTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* ignore seq header */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* version */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* n */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* e */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* d */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* p */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* q */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* d mod (p-1) */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* d mod (q-1) */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* q^-1 mod p */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_OPTIONAL | BSL_ASN1_FLAG_HEADERONLY | BSL_ASN1_FLAG_SAME, 1}, /* OtherPrimeInfos OPTIONAL */ {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, /* OtherPrimeInfo */ {BSL_ASN1_TAG_INTEGER, 0, 3}, /* ri */ {BSL_ASN1_TAG_INTEGER, 0, 3}, /* di */ {BSL_ASN1_TAG_INTEGER, 0, 3} /* ti */ }; /** * RSAPublicKey ::= SEQUENCE { * modulus INTEGER, -- n * publicExponent INTEGER } -- e * * https://datatracker.ietf.org/doc/html/rfc4055#autoid-3 */ static BSL_ASN1_TemplateItem g_rsaPubTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, /* ignore seq */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* n */ {BSL_ASN1_TAG_INTEGER, 0, 1}, /* e */ }; #ifdef HITLS_CRYPTO_KEY_DECODE /** * ref: rfc4055 * RSASSA-PSS-params ::= SEQUENCE { * hashAlgorithm [0] HashAlgorithm DEFAULT sha1Identifier, * maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier, * saltLength [2] INTEGER DEFAULT 20, * trailerField [3] INTEGER DEFAULT 1 * } * HashAlgorithm ::= AlgorithmIdentifier * MaskGenAlgorithm ::= AlgorithmIdentifier */ static BSL_ASN1_TemplateItem g_rsaPssTempl[] = { {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_HASH, BSL_ASN1_FLAG_DEFAULT, 0}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 2}, {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_MASKGEN, BSL_ASN1_FLAG_DEFAULT, 0}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, {BSL_ASN1_TAG_OBJECT_ID, 0, 3}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 3}, {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_SALTLEN, BSL_ASN1_FLAG_DEFAULT, 0}, {BSL_ASN1_TAG_INTEGER, 0, 1}, {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | CRYPT_ASN1_CTX_SPECIFIC_TAG_RSAPSS_TRAILED, BSL_ASN1_FLAG_DEFAULT, 0}, {BSL_ASN1_TAG_INTEGER, 0, 1} }; typedef enum { CRYPT_RSAPSS_HASH_IDX, CRYPT_RSAPSS_HASHANY_IDX, CRYPT_RSAPSS_MGF1_IDX, CRYPT_RSAPSS_MGF1PARAM_IDX, CRYPT_RSAPSS_MGF1PARAMANY_IDX, CRYPT_RSAPSS_SALTLEN_IDX, CRYPT_RSAPSS_TRAILED_IDX, CRYPT_RSAPSS_MAX } CRYPT_RSAPSS_IDX; #endif // HITLS_CRYPTO_KEY_DECODE #endif #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) /** * ECPrivateKey ::= SEQUENCE { * version INTEGER { ecPrivkeyVer1(1) } (ecPrivkeyVer1), * privateKey OCTET STRING, * parameters [0] ECParameters {{ NamedCurve }} OPTIONAL, * publicKey [1] BIT STRING OPTIONAL * } * * https://datatracker.ietf.org/doc/html/rfc5915#autoid-3 */ #define BSL_ASN1_TAG_EC_PRIKEY_PARAM 0 #define BSL_ASN1_TAG_EC_PRIKEY_PUBKEY 1 static BSL_ASN1_TemplateItem g_ecPriKeyTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, // ignore seq header {BSL_ASN1_TAG_INTEGER, 0, 1}, /* version */ {BSL_ASN1_TAG_OCTETSTRING, 0, 1}, /* private key */ {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_EC_PRIKEY_PARAM, BSL_ASN1_FLAG_OPTIONAL, 1}, {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_CLASS_CTX_SPECIFIC | BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_EC_PRIKEY_PUBKEY, BSL_ASN1_FLAG_OPTIONAL, 1}, {BSL_ASN1_TAG_BITSTRING, 0, 2}, }; #endif /** * PrivateKeyInfo ::= SEQUENCE { * version INTEGER, * privateKeyAlgorithm AlgorithmIdentifier, * privateKey OCTET STRING, * attributes [0] IMPLICIT Attributes OPTIONAL } * * https://datatracker.ietf.org/doc/html/rfc5208#autoid-5 */ static BSL_ASN1_TemplateItem g_pk8PriKeyTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, // ignore seq header {BSL_ASN1_TAG_INTEGER, 0, 1}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1}, {BSL_ASN1_TAG_OCTETSTRING, 0, 1}, }; typedef enum { CRYPT_PK8_PRIKEY_VERSION_IDX = 0, CRYPT_PK8_PRIKEY_ALGID_IDX = 1, CRYPT_PK8_PRIKEY_PRIKEY_IDX = 2, } CRYPT_PK8_PRIKEY_TEMPL_IDX; #ifdef HITLS_CRYPTO_KEY_EPKI #ifdef HITLS_CRYPTO_KEY_DECODE /** * EncryptedPrivateKeyInfo ::= SEQUENCE { * encryptionAlgorithm EncryptionAlgorithmIdentifier, * encryptedData EncryptedData } * * https://datatracker.ietf.org/doc/html/rfc5208#autoid-6 */ static BSL_ASN1_TemplateItem g_pk8EncPriKeyTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 1}, // EncryptionAlgorithmIdentifier {BSL_ASN1_TAG_OBJECT_ID, 0, 2}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 2}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 3}, // derivation param {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 3}, // enc scheme {BSL_ASN1_TAG_OBJECT_ID, 0, 4}, // alg {BSL_ASN1_TAG_OCTETSTRING, 0, 4}, // iv {BSL_ASN1_TAG_OCTETSTRING, 0, 1}, // EncryptedData }; #endif static BSL_ASN1_TemplateItem g_pbkdf2DerParamTempl[] = { {BSL_ASN1_TAG_OBJECT_ID, 0, 0}, // derive alg {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_OCTETSTRING, 0, 1}, // salt {BSL_ASN1_TAG_INTEGER, 0, 1}, // iteration {BSL_ASN1_TAG_INTEGER, BSL_ASN1_FLAG_OPTIONAL, 1}, // keyLen {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_DEFAULT | BSL_ASN1_FLAG_HEADERONLY, 1}, // prf }; #endif // HITLS_CRYPTO_KEY_EPKI /** * SubjectPublicKeyInfo ::= SEQUENCE { * algorithm AlgorithmIdentifier, * subjectPublicKey BIT STRING * } * * https://datatracker.ietf.org/doc/html/rfc5480#autoid-3 */ static BSL_ASN1_TemplateItem g_subKeyInfoTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, 0, 0}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 1}, {BSL_ASN1_TAG_BITSTRING, 0, 1}, }; static BSL_ASN1_TemplateItem g_subKeyInfoInnerTempl[] = { {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, BSL_ASN1_FLAG_HEADERONLY, 0}, {BSL_ASN1_TAG_BITSTRING, 0, 0}, }; /** * AlgorithmIdentifier ::= SEQUENCE { * algorithm OBJECT IDENTIFIER, * parameters ANY DEFINED BY algorithm OPTIONAL } * * https://datatracker.ietf.org/doc/html/rfc5280#section-4.1.1.2 */ static BSL_ASN1_TemplateItem g_algoIdTempl[] = { {BSL_ASN1_TAG_OBJECT_ID, 0, 0}, {BSL_ASN1_TAG_ANY, BSL_ASN1_FLAG_OPTIONAL, 0}, }; #ifdef HITLS_CRYPTO_KEY_EPKI typedef enum { CRYPT_PKCS_ENC_DERALG_IDX, CRYPT_PKCS_ENC_DERSALT_IDX, CRYPT_PKCS_ENC_DERITER_IDX, CRYPT_PKCS_ENC_DERKEYLEN_IDX, CRYPT_PKCS_ENC_DERPRF_IDX, CRYPT_PKCS_ENC_DERPARAM_MAX } CRYPT_PKCS_ENC_DERIVEPARAM_IDX; static int32_t CRYPT_ENCODE_DECODE_DecryptEncData(CRYPT_EAL_LibCtx *libctx, const char *attrName, BSL_Buffer *ivData, BSL_Buffer *enData, int32_t alg, bool isEnc, BSL_Buffer *key, uint8_t *output, uint32_t *dataLen) { uint32_t buffLen = *dataLen; CRYPT_EAL_CipherCtx *ctx = CRYPT_EAL_ProviderCipherNewCtx(libctx, alg, attrName); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } int32_t ret = CRYPT_EAL_CipherInit(ctx, key->data, key->dataLen, ivData->data, ivData->dataLen, isEnc); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } uint32_t blockSize; ret = CRYPT_EAL_CipherCtrl(ctx, CRYPT_CTRL_GET_BLOCKSIZE, &blockSize, sizeof(blockSize)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } if (blockSize != 1) { ret = CRYPT_EAL_CipherSetPadding(ctx, CRYPT_PADDING_PKCS7); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } } ret = CRYPT_EAL_CipherUpdate(ctx, enData->data, enData->dataLen, output, dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } buffLen -= *dataLen; ret = CRYPT_EAL_CipherFinal(ctx, output + *dataLen, &buffLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } *dataLen += buffLen; EXIT: CRYPT_EAL_CipherFreeCtx(ctx); return ret; } static int32_t PbkdfDeriveKey(CRYPT_EAL_LibCtx *libctx, const char *attrName, uint32_t iter, int32_t prfId, BSL_Buffer *salt, const uint8_t *pwd, uint32_t pwdLen, BSL_Buffer *key) { CRYPT_EAL_KdfCTX *kdfCtx = CRYPT_EAL_ProviderKdfNewCtx(libctx, CRYPT_KDF_PBKDF2, attrName); if (kdfCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_PBKDF2_NOT_SUPPORTED); return CRYPT_PBKDF2_NOT_SUPPORTED; } BSL_Param params[5] = {{0}, {0}, {0}, {0}, BSL_PARAM_END}; (void)BSL_PARAM_InitValue(&params[0], CRYPT_PARAM_KDF_MAC_ID, BSL_PARAM_TYPE_UINT32, &prfId, sizeof(prfId)); (void)BSL_PARAM_InitValue(&params[1], CRYPT_PARAM_KDF_PASSWORD, BSL_PARAM_TYPE_OCTETS, (uint8_t *)(uintptr_t)pwd, pwdLen); // Fixed pwd parameter (void)BSL_PARAM_InitValue(&params[2], CRYPT_PARAM_KDF_SALT, BSL_PARAM_TYPE_OCTETS, salt->data, salt->dataLen); (void)BSL_PARAM_InitValue(&params[3], CRYPT_PARAM_KDF_ITER, BSL_PARAM_TYPE_UINT32, &iter, sizeof(iter)); int32_t ret = CRYPT_EAL_KdfSetParam(kdfCtx, params); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = CRYPT_EAL_KdfDerive(kdfCtx, key->data, key->dataLen); EXIT: CRYPT_EAL_KdfFreeCtx(kdfCtx); return ret; } #endif // HITLS_CRYPTO_EPKI #ifdef HITLS_CRYPTO_KEY_DECODE #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) int32_t CRYPT_DECODE_PrikeyAsn1Buff(uint8_t *buffer, uint32_t bufferLen, BSL_ASN1_Buffer *asn1, uint32_t arrNum) { uint8_t *tmpBuff = buffer; uint32_t tmpBuffLen = bufferLen; BSL_ASN1_Template templ = {g_ecPriKeyTempl, sizeof(g_ecPriKeyTempl) / sizeof(g_ecPriKeyTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &tmpBuff, &tmpBuffLen, asn1, arrNum); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif #ifdef HITLS_CRYPTO_RSA int32_t CRYPT_DECODE_RsaPubkeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pubAsn1, uint32_t arrNum) { if (buff == NULL || pubAsn1 == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint8_t *tmpBuff = buff; uint32_t tmpBuffLen = buffLen; BSL_ASN1_Template pubTempl = {g_rsaPubTempl, sizeof(g_rsaPubTempl) / sizeof(g_rsaPubTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&pubTempl, NULL, &tmpBuff, &tmpBuffLen, pubAsn1, arrNum); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t CRYPT_DECODE_RsaPrikeyAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *asn1, uint32_t asn1Num) { uint8_t *tmpBuff = buff; uint32_t tmpBuffLen = buffLen; BSL_ASN1_Template templ = {g_rsaPrvTempl, sizeof(g_rsaPrvTempl) / sizeof(g_rsaPrvTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &tmpBuff, &tmpBuffLen, asn1, asn1Num); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t RsaPssTagGetOrCheck(int32_t type, uint32_t idx, void *data, void *expVal) { (void) idx; (void) data; if (type == BSL_ASN1_TYPE_GET_ANY_TAG) { *(uint8_t *) expVal = BSL_ASN1_TAG_NULL; // is null return CRYPT_SUCCESS; } BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_RSSPSS_GET_ANY_TAG); return CRYPT_DECODE_ERR_RSSPSS_GET_ANY_TAG; } int32_t CRYPT_EAL_ParseRsaPssAlgParam(BSL_ASN1_Buffer *param, CRYPT_RSA_PssPara *para) { para->mdId = (CRYPT_MD_AlgId)BSL_CID_SHA1; // hashAlgorithm [0] HashAlgorithm DEFAULT sha1Identifier, para->mgfId = (CRYPT_MD_AlgId)BSL_CID_SHA1; // maskGenAlgorithm [1] MaskGenAlgorithm DEFAULT mgf1SHA1Identifier, para->saltLen = 20; // saltLength [2] INTEGER DEFAULT 20 uint8_t *temp = param->buff; uint32_t tempLen = param->len; BSL_ASN1_Buffer asns[CRYPT_RSAPSS_MAX] = {0}; BSL_ASN1_Template templ = {g_rsaPssTempl, sizeof(g_rsaPssTempl) / sizeof(g_rsaPssTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, RsaPssTagGetOrCheck, &temp, &tempLen, asns, CRYPT_RSAPSS_MAX); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_RSSPSS); return CRYPT_DECODE_ERR_RSSPSS; } if (asns[CRYPT_RSAPSS_HASH_IDX].tag != 0) { BslOidString hashOid = {asns[CRYPT_RSAPSS_HASH_IDX].len, (char *)asns[CRYPT_RSAPSS_HASH_IDX].buff, 0}; para->mdId = (CRYPT_MD_AlgId)BSL_OBJ_GetCID(&hashOid); if (para->mdId == (CRYPT_MD_AlgId)BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_RSSPSS_MD); return CRYPT_DECODE_ERR_RSSPSS_MD; } } if (asns[CRYPT_RSAPSS_MGF1PARAM_IDX].tag != 0) { BslOidString mgf1 = {asns[CRYPT_RSAPSS_MGF1PARAM_IDX].len, (char *)asns[CRYPT_RSAPSS_MGF1PARAM_IDX].buff, 0}; para->mgfId = (CRYPT_MD_AlgId)BSL_OBJ_GetCID(&mgf1); if (para->mgfId == (CRYPT_MD_AlgId)BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_RSSPSS_MGF1MD); return CRYPT_DECODE_ERR_RSSPSS_MGF1MD; } } if (asns[CRYPT_RSAPSS_SALTLEN_IDX].tag != 0) { ret = BSL_ASN1_DecodePrimitiveItem(&asns[CRYPT_RSAPSS_SALTLEN_IDX], &para->saltLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } if (asns[CRYPT_RSAPSS_TRAILED_IDX].tag != 0) { // trailerField ret = BSL_ASN1_DecodePrimitiveItem(&asns[CRYPT_RSAPSS_TRAILED_IDX], &tempLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (tempLen != 1) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ERR_RSSPSS_TRAILER); return CRYPT_DECODE_ERR_RSSPSS_TRAILER; } } return ret; } #endif static int32_t DecSubKeyInfoCb(int32_t type, uint32_t idx, void *data, void *expVal) { (void)idx; BSL_ASN1_Buffer *param = (BSL_ASN1_Buffer *)data; switch (type) { case BSL_ASN1_TYPE_GET_ANY_TAG: { BslOidString oidStr = {param->len, (char *)param->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_EC_PUBLICKEY || cid == BSL_CID_SM2PRIME256) { // note: any It can be encoded empty or it can be null *(uint8_t *)expVal = BSL_ASN1_TAG_OBJECT_ID; } else if (cid == BSL_CID_RSASSAPSS) { *(uint8_t *)expVal = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; } else if (cid == BSL_CID_ED25519) { /* RFC8410: Ed25519 has no algorithm parameters */ *(uint8_t *)expVal = BSL_ASN1_TAG_EMPTY; // is empty } else { *(uint8_t *)expVal = BSL_ASN1_TAG_NULL; // is null } return CRYPT_SUCCESS; } default: break; } BSL_ERR_PUSH_ERROR(CRYPT_DECODE_ASN1_BUFF_FAILED); return CRYPT_DECODE_ASN1_BUFF_FAILED; } int32_t CRYPT_DECODE_ParseSubKeyInfo(uint8_t *buff, uint32_t buffLen, BSL_ASN1_Buffer *pubAsn1, bool isComplete) { uint8_t *tmpBuff = buff; uint32_t tmpBuffLen = buffLen; // decode sub pubkey info BSL_ASN1_Template pubTempl; if (isComplete) { pubTempl.templItems = g_subKeyInfoTempl; pubTempl.templNum = sizeof(g_subKeyInfoTempl) / sizeof(g_subKeyInfoTempl[0]); } else { pubTempl.templItems = g_subKeyInfoInnerTempl; pubTempl.templNum = sizeof(g_subKeyInfoInnerTempl) / sizeof(g_subKeyInfoInnerTempl[0]); } int32_t ret = BSL_ASN1_DecodeTemplate(&pubTempl, DecSubKeyInfoCb, &tmpBuff, &tmpBuffLen, pubAsn1, CRYPT_SUBKEYINFO_BITSTRING_IDX + 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t CRYPT_DECODE_AlgoIdAsn1Buff(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb, BSL_ASN1_Buffer *algoId, uint32_t algoIdNum) { uint8_t *tmpBuff = buff; uint32_t tmpBuffLen = buffLen; BSL_ASN1_DecTemplCallBack cb = keyInfoCb == NULL ? DecSubKeyInfoCb : keyInfoCb; BSL_ASN1_Template templ = {g_algoIdTempl, sizeof(g_algoIdTempl) / sizeof(g_algoIdTempl[0])}; return BSL_ASN1_DecodeTemplate(&templ, cb, &tmpBuff, &tmpBuffLen, algoId, algoIdNum); } int32_t CRYPT_DECODE_SubPubkey(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb, CRYPT_DECODE_SubPubkeyInfo *subPubkeyInfo, bool isComplete) { if (buff == NULL || subPubkeyInfo == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } BSL_ASN1_Buffer pubAsn1[CRYPT_SUBKEYINFO_BITSTRING_IDX + 1] = {0}; BSL_ASN1_BitString bitPubkey = {0}; BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {0}; int32_t ret = CRYPT_DECODE_ParseSubKeyInfo(buff, buffLen, pubAsn1, isComplete); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_DECODE_AlgoIdAsn1Buff(pubAsn1->buff, pubAsn1->len, keyInfoCb, algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Buffer *oid = algoId; BSL_ASN1_Buffer *pubkey = &pubAsn1[CRYPT_SUBKEYINFO_BITSTRING_IDX]; ret = BSL_ASN1_DecodePrimitiveItem(pubkey, &bitPubkey); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString oidStr = {oid->len, (char *)oid->buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID); return CRYPT_DECODE_UNKNOWN_OID; } subPubkeyInfo->keyType = cid; subPubkeyInfo->keyParam = *(algoId + 1); subPubkeyInfo->pubKey = bitPubkey; return CRYPT_SUCCESS; } static int32_t ParsePk8PriParamAsn1(BSL_ASN1_Buffer *encode, BSL_ASN1_DecTemplCallBack keyInfoCb, BslCid *keyType, BSL_ASN1_Buffer *keyParam) { BSL_ASN1_Buffer *algo = &encode[CRYPT_PK8_PRIKEY_ALGID_IDX]; // AlgorithmIdentifier BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {0}; int32_t ret = CRYPT_DECODE_AlgoIdAsn1Buff(algo->buff, algo->len, keyInfoCb, algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1); if (ret != CRYPT_SUCCESS) { return ret; } BslOidString oidStr = {algoId[0].len, (char *)algoId[0].buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID); return CRYPT_DECODE_UNKNOWN_OID; } *keyType = cid; *keyParam = *(algoId + 1); return CRYPT_SUCCESS; } int32_t CRYPT_DECODE_Pkcs8Info(uint8_t *buff, uint32_t buffLen, BSL_ASN1_DecTemplCallBack keyInfoCb, CRYPT_ENCODE_DECODE_Pk8PrikeyInfo *pk8PrikeyInfo) { if (buff == NULL || buffLen == 0 || pk8PrikeyInfo == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint8_t *tmpBuff = buff; uint32_t tmpBuffLen = buffLen; int32_t version = 0; BslCid keyType = BSL_CID_UNKNOWN; BSL_ASN1_Buffer keyParam = {0}; BSL_ASN1_Buffer asn1[CRYPT_PK8_PRIKEY_PRIKEY_IDX + 1] = {0}; BSL_ASN1_Template templ = {g_pk8PriKeyTempl, sizeof(g_pk8PriKeyTempl) / sizeof(g_pk8PriKeyTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &tmpBuff, &tmpBuffLen, asn1, CRYPT_PK8_PRIKEY_PRIKEY_IDX + 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = BSL_ASN1_DecodePrimitiveItem(&asn1[CRYPT_PK8_PRIKEY_VERSION_IDX], &version); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Buffer octPriKey = asn1[CRYPT_PK8_PRIKEY_PRIKEY_IDX]; ret = ParsePk8PriParamAsn1(asn1, keyInfoCb, &keyType, &keyParam); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } pk8PrikeyInfo->version = version; pk8PrikeyInfo->keyType = keyType; pk8PrikeyInfo->pkeyRawKey = octPriKey.buff; pk8PrikeyInfo->pkeyRawKeyLen = octPriKey.len; pk8PrikeyInfo->keyParam = keyParam; pk8PrikeyInfo->attrs = NULL; return CRYPT_SUCCESS; } #ifdef HITLS_CRYPTO_KEY_EPKI static int32_t ParseDeriveKeyPrfAlgId(BSL_ASN1_Buffer *asn, int32_t *prfId, BSL_ASN1_DecTemplCallBack keyInfoCb) { if (asn->len != 0) { BSL_ASN1_Buffer algoId[2] = {0}; int32_t ret = CRYPT_DECODE_AlgoIdAsn1Buff(asn->buff, asn->len, keyInfoCb, algoId, 2); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString oidStr = {algoId[BSL_ASN1_TAG_ALGOID_IDX].len, (char *)algoId[BSL_ASN1_TAG_ALGOID_IDX].buff, 0}; *prfId = BSL_OBJ_GetCID(&oidStr); if (*prfId == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM); return CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM; } } else { *prfId = BSL_CID_HMAC_SHA1; } return CRYPT_SUCCESS; } static int32_t ParseDeriveKeyParam(BSL_Buffer *derivekeyData, uint32_t *iter, uint32_t *keyLen, BSL_Buffer *salt, int32_t *prfId, BSL_ASN1_DecTemplCallBack keyInfoCb) { uint8_t *tmpBuff = derivekeyData->data; uint32_t tmpBuffLen = derivekeyData->dataLen; BSL_ASN1_Buffer derParam[CRYPT_PKCS_ENC_DERPARAM_MAX] = {0}; BSL_ASN1_Template templ = {g_pbkdf2DerParamTempl, sizeof(g_pbkdf2DerParamTempl) / sizeof(g_pbkdf2DerParamTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &tmpBuff, &tmpBuffLen, derParam, CRYPT_PKCS_ENC_DERPARAM_MAX); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString oidStr = {derParam[CRYPT_PKCS_ENC_DERALG_IDX].len, (char *)derParam[CRYPT_PKCS_ENC_DERALG_IDX].buff, 0}; BslCid cid = BSL_OBJ_GetCID(&oidStr); if (cid != BSL_CID_PBKDF2) { // only pbkdf2 is supported BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM); return CRYPT_DECODE_PKCS8_INVALID_ALGO_PARAM; } ret = BSL_ASN1_DecodePrimitiveItem(&derParam[CRYPT_PKCS_ENC_DERITER_IDX], iter); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_ITER); return CRYPT_DECODE_PKCS8_INVALID_ITER; } if (derParam[CRYPT_PKCS_ENC_DERKEYLEN_IDX].len != 0) { ret = BSL_ASN1_DecodePrimitiveItem(&derParam[CRYPT_PKCS_ENC_DERKEYLEN_IDX], keyLen); if (ret != BSL_SUCCESS) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_KEYLEN); return CRYPT_DECODE_PKCS8_INVALID_KEYLEN; } } salt->data = derParam[CRYPT_PKCS_ENC_DERSALT_IDX].buff; salt->dataLen = derParam[CRYPT_PKCS_ENC_DERSALT_IDX].len; return ParseDeriveKeyPrfAlgId(&derParam[CRYPT_PKCS_ENC_DERPRF_IDX], prfId, keyInfoCb); } int32_t CRYPT_DECODE_ParseEncDataAsn1(CRYPT_EAL_LibCtx *libctx, const char *attrName, BslCid symAlg, EncryptPara *encPara, const BSL_Buffer *pwd, BSL_ASN1_DecTemplCallBack keyInfoCb, BSL_Buffer *decode) { uint32_t iter; int32_t prfId; uint32_t keylen = 0; uint8_t key[512] = {0}; // The maximum length of the symmetry algorithm BSL_Buffer salt = {0}; int32_t ret = ParseDeriveKeyParam(encPara->derivekeyData, &iter, &keylen, &salt, &prfId, keyInfoCb); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } uint32_t symKeyLen; ret = CRYPT_EAL_CipherGetInfo((CRYPT_CIPHER_AlgId)symAlg, CRYPT_INFO_KEY_LEN, &symKeyLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (keylen != 0 && symKeyLen != keylen) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PKCS8_INVALID_KEYLEN); return CRYPT_DECODE_PKCS8_INVALID_KEYLEN; } BSL_Buffer keyBuff = {key, symKeyLen}; ret = PbkdfDeriveKey(libctx, attrName, iter, prfId, &salt, pwd->data, pwd->dataLen, &keyBuff); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (encPara->enData->dataLen != 0) { uint8_t *output = BSL_SAL_Malloc(encPara->enData->dataLen); if (output == NULL) { (void)memset_s(key, sizeof(key), 0, sizeof(key)); BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } uint32_t dataLen = encPara->enData->dataLen; ret = CRYPT_ENCODE_DECODE_DecryptEncData(libctx, attrName, encPara->ivData, encPara->enData, symAlg, false, &keyBuff, output, &dataLen); if (ret != CRYPT_SUCCESS) { (void)memset_s(key, sizeof(key), 0, sizeof(key)); BSL_SAL_Free(output); BSL_ERR_PUSH_ERROR(ret); return ret; } decode->data = output; decode->dataLen = dataLen; } (void)memset_s(key, sizeof(key), 0, sizeof(key)); return CRYPT_SUCCESS; } int32_t CRYPT_DECODE_Pkcs8PrvDecrypt(CRYPT_EAL_LibCtx *libctx, const char *attrName, BSL_Buffer *buff, const BSL_Buffer *pwd, BSL_ASN1_DecTemplCallBack keyInfoCb, BSL_Buffer *decode) { if (buff == NULL || buff->dataLen == 0 || pwd == NULL || decode == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (pwd->dataLen > PWD_MAX_LEN || (pwd->data == NULL && pwd->dataLen != 0)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } uint8_t *tmpBuff = buff->data; uint32_t tmpBuffLen = buff->dataLen; BSL_ASN1_Buffer asn1[CRYPT_PKCS_ENCPRIKEY_MAX] = {0}; BSL_ASN1_Template templ = {g_pk8EncPriKeyTempl, sizeof(g_pk8EncPriKeyTempl) / sizeof(g_pk8EncPriKeyTempl[0])}; int32_t ret = BSL_ASN1_DecodeTemplate(&templ, NULL, &tmpBuff, &tmpBuffLen, asn1, CRYPT_PKCS_ENCPRIKEY_MAX); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BslOidString encOidStr = {asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].len, (char *)asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].buff, 0}; BslCid cid = BSL_OBJ_GetCID(&encOidStr); if (cid != BSL_CID_PBES2) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID); return CRYPT_DECODE_UNKNOWN_OID; } // parse sym alg id BslOidString symOidStr = {asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].len, (char *)asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].buff, 0}; BslCid symId = BSL_OBJ_GetCID(&symOidStr); if (symId == BSL_CID_UNKNOWN) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_UNKNOWN_OID); return CRYPT_DECODE_UNKNOWN_OID; } BSL_Buffer derivekeyData = {asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len}; BSL_Buffer ivData = {asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len}; BSL_Buffer enData = {asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].len}; EncryptPara encPara = { .derivekeyData = &derivekeyData, .ivData = &ivData, .enData = &enData, }; ret = CRYPT_DECODE_ParseEncDataAsn1(libctx, attrName, symId, &encPara, pwd, keyInfoCb, decode); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif /* HITLS_CRYPTO_KEY_EPKI */ int32_t CRYPT_DECODE_ConstructBufferOutParam(BSL_Param **outParam, uint8_t *buffer, uint32_t bufferLen) { BSL_Param *result = BSL_SAL_Calloc(2, sizeof(BSL_Param)); if (result == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = BSL_PARAM_InitValue(&result[0], CRYPT_PARAM_DECODE_BUFFER_DATA, BSL_PARAM_TYPE_OCTETS, buffer, bufferLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(result); BSL_ERR_PUSH_ERROR(ret); return ret; } *outParam = result; return ret; } #endif /* HITLS_CRYPTO_KEY_DECODE */ #ifdef HITLS_CRYPTO_KEY_ENCODE #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) int32_t CRYPT_ENCODE_EccPrikeyAsn1Buff(BSL_ASN1_Buffer *asn1, uint32_t asn1Num, BSL_Buffer *encode) { BSL_ASN1_Template templ = {g_ecPriKeyTempl, sizeof(g_ecPriKeyTempl) / sizeof(g_ecPriKeyTempl[0])}; return BSL_ASN1_EncodeTemplate(&templ, asn1, asn1Num, &encode->data, &encode->dataLen); } #endif /* HITLS_CRYPTO_ECDSA || HITLS_CRYPTO_SM2 */ #ifdef HITLS_CRYPTO_RSA int32_t CRYPT_ENCODE_RsaPubkeyAsn1Buff(BSL_ASN1_Buffer *pubAsn1, BSL_Buffer *encodePub) { BSL_ASN1_Template pubTempl = {g_rsaPubTempl, sizeof(g_rsaPubTempl) / sizeof(g_rsaPubTempl[0])}; int32_t ret = BSL_ASN1_EncodeTemplate(&pubTempl, pubAsn1, CRYPT_RSA_PUB_E_IDX + 1, &encodePub->data, &encodePub->dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return CRYPT_SUCCESS; } int32_t CRYPT_ENCODE_RsaPrikeyAsn1Buff(BSL_ASN1_Buffer *asn1, uint32_t asn1Num, BSL_Buffer *encode) { BSL_ASN1_Template templ = {g_rsaPrvTempl, sizeof(g_rsaPrvTempl) / sizeof(g_rsaPrvTempl[0])}; int32_t ret = BSL_ASN1_EncodeTemplate(&templ, asn1, asn1Num, &encode->data, &encode->dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif int32_t CRYPT_ENCODE_SubPubkeyByInfo(BSL_ASN1_Buffer *algo, BSL_Buffer *bitStr, BSL_Buffer *encodeH, bool isComplete) { BSL_ASN1_Buffer encode[CRYPT_SUBKEYINFO_BITSTRING_IDX + 1] = {0}; encode[CRYPT_SUBKEYINFO_ALGOID_IDX].buff = algo->buff; encode[CRYPT_SUBKEYINFO_ALGOID_IDX].len = algo->len; encode[CRYPT_SUBKEYINFO_ALGOID_IDX].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; BSL_ASN1_BitString bitPubkey = {bitStr->data, bitStr->dataLen, 0}; encode[CRYPT_SUBKEYINFO_BITSTRING_IDX].buff = (uint8_t *)&bitPubkey; encode[CRYPT_SUBKEYINFO_BITSTRING_IDX].len = sizeof(BSL_ASN1_BitString); encode[CRYPT_SUBKEYINFO_BITSTRING_IDX].tag = BSL_ASN1_TAG_BITSTRING; BSL_ASN1_Template pubTempl; if (isComplete) { pubTempl.templItems = g_subKeyInfoTempl; pubTempl.templNum = sizeof(g_subKeyInfoTempl) / sizeof(g_subKeyInfoTempl[0]); } else { pubTempl.templItems = g_subKeyInfoInnerTempl; pubTempl.templNum = sizeof(g_subKeyInfoInnerTempl) / sizeof(g_subKeyInfoInnerTempl[0]); } int32_t ret = BSL_ASN1_EncodeTemplate(&pubTempl, encode, CRYPT_SUBKEYINFO_BITSTRING_IDX + 1, &encodeH->data, &encodeH->dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t CRYPT_ENCODE_AlgoIdAsn1Buff(BSL_ASN1_Buffer *algoId, uint32_t algoIdNum, uint8_t **buff, uint32_t *buffLen) { BSL_ASN1_Template templ = {g_algoIdTempl, sizeof(g_algoIdTempl) / sizeof(g_algoIdTempl[0])}; return BSL_ASN1_EncodeTemplate(&templ, algoId, algoIdNum, buff, buffLen); } #ifdef HITLS_CRYPTO_KEY_EPKI static int32_t EncodeDeriveKeyParam(CRYPT_EAL_LibCtx *libCtx, CRYPT_Pbkdf2Param *param, BSL_Buffer *encode, BSL_Buffer *salt) { BSL_ASN1_Buffer derParam[CRYPT_PKCS_ENC_DERPRF_IDX + 1] = {0}; /* deralg */ BslOidString *oidPbkdf = BSL_OBJ_GetOID((BslCid)param->pbkdfId); if (oidPbkdf == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); return CRYPT_ERR_ALGID; } derParam[CRYPT_PKCS_ENC_DERALG_IDX].buff = (uint8_t *)oidPbkdf->octs; derParam[CRYPT_PKCS_ENC_DERALG_IDX].len = oidPbkdf->octetLen; derParam[CRYPT_PKCS_ENC_DERALG_IDX].tag = BSL_ASN1_TAG_OBJECT_ID; /* salt */ int32_t ret = CRYPT_EAL_RandbytesEx(libCtx, salt->data, salt->dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } derParam[CRYPT_PKCS_ENC_DERSALT_IDX].buff = salt->data; derParam[CRYPT_PKCS_ENC_DERSALT_IDX].len = salt->dataLen; derParam[CRYPT_PKCS_ENC_DERSALT_IDX].tag = BSL_ASN1_TAG_OCTETSTRING; /* iter */ ret = BSL_ASN1_EncodeLimb(BSL_ASN1_TAG_INTEGER, param->itCnt, &derParam[CRYPT_PKCS_ENC_DERITER_IDX]); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BSL_ASN1_Template templ = {g_pbkdf2DerParamTempl, sizeof(g_pbkdf2DerParamTempl) / sizeof(g_pbkdf2DerParamTempl[0])}; if (param->hmacId == CRYPT_MAC_HMAC_SHA1) { ret = BSL_ASN1_EncodeTemplate(&templ, derParam, CRYPT_PKCS_ENC_DERPRF_IDX + 1, &encode->data, &encode->dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } BSL_SAL_FREE(derParam[CRYPT_PKCS_ENC_DERITER_IDX].buff); return ret; } BslOidString *oidHmac = BSL_OBJ_GetOID((BslCid)param->hmacId); if (oidHmac == NULL) { BSL_SAL_FREE(derParam[CRYPT_PKCS_ENC_DERITER_IDX].buff); BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); return CRYPT_ERR_ALGID; } BSL_Buffer algo = {0}; BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = { {BSL_ASN1_TAG_OBJECT_ID, oidHmac->octetLen, (uint8_t *)oidHmac->octs}, {BSL_ASN1_TAG_NULL, 0, NULL}, }; ret = CRYPT_ENCODE_AlgoIdAsn1Buff(algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1, &algo.data, &algo.dataLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_FREE(derParam[CRYPT_PKCS_ENC_DERITER_IDX].buff); BSL_ERR_PUSH_ERROR(ret); return ret; } derParam[CRYPT_PKCS_ENC_DERPRF_IDX].buff = algo.data; derParam[CRYPT_PKCS_ENC_DERPRF_IDX].len = algo.dataLen; derParam[CRYPT_PKCS_ENC_DERPRF_IDX].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; ret = BSL_ASN1_EncodeTemplate(&templ, derParam, CRYPT_PKCS_ENC_DERPRF_IDX + 1, &encode->data, &encode->dataLen); BSL_SAL_FREE(algo.data); BSL_SAL_FREE(derParam[CRYPT_PKCS_ENC_DERITER_IDX].buff); return ret; } static int32_t EncodeEncryptedData(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_Pbkdf2Param *pkcsParam, BSL_Buffer *unEncrypted, BSL_Buffer *salt, BSL_ASN1_Buffer *asn1) { int32_t ret; uint8_t *output = NULL; BSL_Buffer keyBuff = {0}; do { ret = CRYPT_EAL_CipherGetInfo(pkcsParam->symId, CRYPT_INFO_KEY_LEN, &keyBuff.dataLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); break; } keyBuff.data = (uint8_t *)BSL_SAL_Malloc(keyBuff.dataLen); if (keyBuff.data == NULL) { ret = BSL_MALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); break; } ret = PbkdfDeriveKey(libCtx, attrName, pkcsParam->itCnt, (int32_t)pkcsParam->hmacId, salt, pkcsParam->pwd, pkcsParam->pwdLen, &keyBuff); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); break; } uint32_t pkcsDataLen = unEncrypted->dataLen + 16; // extras 16 for padding. output = (uint8_t *)BSL_SAL_Malloc(pkcsDataLen); if (output == NULL) { ret = BSL_MALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); break; } BSL_Buffer enData = {unEncrypted->data, unEncrypted->dataLen}; BSL_Buffer ivData = {asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len}; ret = CRYPT_ENCODE_DECODE_DecryptEncData(libCtx, attrName, &ivData, &enData, (int32_t)pkcsParam->symId, true, &keyBuff, output, &pkcsDataLen); if (ret != CRYPT_SUCCESS) { break; } asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].buff = output; asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].len = pkcsDataLen; asn1[CRYPT_PKCS_ENCPRIKEY_ENCDATA_IDX].tag = BSL_ASN1_TAG_OCTETSTRING; BSL_SAL_ClearFree(keyBuff.data, keyBuff.dataLen); return ret; } while (0); BSL_SAL_ClearFree(keyBuff.data, keyBuff.dataLen); BSL_SAL_FREE(output); return ret; } static int32_t GenRandIv(CRYPT_EAL_LibCtx *libCtx, CRYPT_Pbkdf2Param *pkcsParam, BSL_ASN1_Buffer *asn1) { int32_t ret; BslOidString *oidSym = BSL_OBJ_GetOID((BslCid)pkcsParam->symId); if (oidSym == NULL) { return CRYPT_ERR_ALGID; } asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].buff = (uint8_t *)oidSym->octs; asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].len = oidSym->octetLen; asn1[CRYPT_PKCS_ENCPRIKEY_SYMALG_IDX].tag = BSL_ASN1_TAG_OBJECT_ID; uint32_t ivLen; ret = CRYPT_EAL_CipherGetInfo(pkcsParam->symId, CRYPT_INFO_IV_LEN, &ivLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (ivLen == 0) { asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].tag = BSL_ASN1_TAG_OCTETSTRING; return CRYPT_SUCCESS; } uint8_t *iv = (uint8_t *)BSL_SAL_Malloc(ivLen); if (iv == NULL) { BSL_ERR_PUSH_ERROR(BSL_MALLOC_FAIL); return BSL_MALLOC_FAIL; } ret = CRYPT_EAL_RandbytesEx(libCtx, iv, ivLen); if (ret != CRYPT_SUCCESS) { BSL_SAL_FREE(iv); BSL_ERR_PUSH_ERROR(ret); return ret; } asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff = iv; asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len = ivLen; asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].tag = BSL_ASN1_TAG_OCTETSTRING; return ret; } int32_t CRYPT_ENCODE_PkcsEncryptedBuff(CRYPT_EAL_LibCtx *libCtx, const char *attrName, CRYPT_Pbkdf2Param *pkcsParam, BSL_Buffer *unEncrypted, BSL_ASN1_Buffer *asn1) { int32_t ret; BslOidString *oidPbes = BSL_OBJ_GetOID((BslCid)pkcsParam->pbesId); if (oidPbes == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); return CRYPT_ERR_ALGID; } /* derivation param */ BSL_Buffer derParam = {0}; uint8_t *saltData = (uint8_t *)BSL_SAL_Malloc(pkcsParam->saltLen); if (saltData == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } do { BSL_Buffer salt = {saltData, pkcsParam->saltLen}; ret = EncodeDeriveKeyParam(libCtx, pkcsParam, &derParam, &salt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); break; } asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff = derParam.data; asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len = derParam.dataLen; asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].tag = BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE; /* iv */ ret = GenRandIv(libCtx, pkcsParam, asn1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); break; } /* encryptedData */ ret = EncodeEncryptedData(libCtx, attrName, pkcsParam, unEncrypted, &salt, asn1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); break; } BSL_SAL_ClearFree(saltData, pkcsParam->saltLen); asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].buff = (uint8_t *)oidPbes->octs; asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].len = oidPbes->octetLen; asn1[CRYPT_PKCS_ENCPRIKEY_ENCALG_IDX].tag = BSL_ASN1_TAG_OBJECT_ID; return CRYPT_SUCCESS; } while (0); BSL_SAL_ClearFree(saltData, pkcsParam->saltLen); BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_DERPARAM_IDX].len); BSL_SAL_ClearFree(asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].buff, asn1[CRYPT_PKCS_ENCPRIKEY_SYMIV_IDX].len); return ret; } #endif // HITLS_CRYPTO_KEY_EPKI int32_t CRYPT_ENCODE_Pkcs8Info(CRYPT_ENCODE_DECODE_Pk8PrikeyInfo *pk8PrikeyInfo, BSL_Buffer *asn1) { if (pk8PrikeyInfo == NULL || asn1 == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } int32_t ret; BSL_ASN1_Buffer algo = {0}; BSL_ASN1_Buffer algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX + 1] = {0}; do { BslOidString *oidStr = BSL_OBJ_GetOID((BslCid)pk8PrikeyInfo->keyType); if (oidStr == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_ERR_ALGID); ret = CRYPT_ERR_ALGID; break; } algoId[BSL_ASN1_TAG_ALGOID_IDX].buff = (uint8_t *)oidStr->octs; algoId[BSL_ASN1_TAG_ALGOID_IDX].len = oidStr->octetLen; algoId[BSL_ASN1_TAG_ALGOID_IDX].tag = BSL_ASN1_TAG_OBJECT_ID; algoId[BSL_ASN1_TAG_ALGOID_ANY_IDX] = pk8PrikeyInfo->keyParam; ret = CRYPT_ENCODE_AlgoIdAsn1Buff(algoId, BSL_ASN1_TAG_ALGOID_ANY_IDX + 1, &algo.buff, &algo.len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); break; } BSL_ASN1_Buffer encode[CRYPT_PK8_PRIKEY_PRIKEY_IDX + 1] = { {BSL_ASN1_TAG_INTEGER, sizeof(pk8PrikeyInfo->version), (uint8_t *)&pk8PrikeyInfo->version}, {BSL_ASN1_TAG_CONSTRUCTED | BSL_ASN1_TAG_SEQUENCE, algo.len, algo.buff}, {BSL_ASN1_TAG_OCTETSTRING, pk8PrikeyInfo->pkeyRawKeyLen, pk8PrikeyInfo->pkeyRawKey} }; BSL_ASN1_Template pubTempl = {g_pk8PriKeyTempl, sizeof(g_pk8PriKeyTempl) / sizeof(g_pk8PriKeyTempl[0])}; ret = BSL_ASN1_EncodeTemplate(&pubTempl, encode, CRYPT_PK8_PRIKEY_PRIKEY_IDX + 1, &asn1->data, &asn1->dataLen); } while (0); BSL_SAL_ClearFree(algo.buff, algo.len); return ret; } #endif /* HITLS_CRYPTO_KEY_ENCODE */ #endif /* HITLS_CRYPTO_CODECSKEY */
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_encode_decode_utils.c
C
unknown
43,490
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_KEY_INFO #include <stdint.h> #include <string.h> #include "bsl_err_internal.h" #include "bsl_obj_internal.h" #include "bsl_print.h" #include "crypt_utils.h" #include "crypt_eal_pkey.h" #include "crypt_errno.h" #include "crypt_encode_decode_key.h" #define CRYPT_UNKOWN_STRING "Unknown\n" #define CRYPT_UNSUPPORT_ALG "Unsupported alg\n" static inline int32_t PrintPubkeyBits(bool isEcc, uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio) { if (!isEcc) { return BSL_PRINT_Fmt(layer, uio, "Public-Key: (%d bit)\n", CRYPT_EAL_PkeyGetKeyBits(pkey)); } uint32_t bits = 0; int32_t ret = CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_ECC_ORDER_BITS, &bits, sizeof(uint32_t)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return BSL_PRINT_Fmt(layer, uio, "Public-Key: (%d bit)\n", bits); } #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) static int32_t GetEccPub(const CRYPT_EAL_PkeyCtx *pkey, CRYPT_EAL_PkeyPub *pub) { uint32_t keyLen = CRYPT_EAL_PkeyGetKeyLen(pkey); if (keyLen == 0) { return CRYPT_DECODE_PRINT_NO_KEY; } uint8_t *buff = (uint8_t *)BSL_SAL_Malloc(keyLen); if (buff == NULL) { return CRYPT_MEM_ALLOC_FAIL; } pub->id = CRYPT_EAL_PkeyGetId(pkey); pub->key.eccPub.data = buff; pub->key.eccPub.len = keyLen; int32_t ret = CRYPT_EAL_PkeyGetPub(pkey, pub); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_SAL_Free(buff); pub->key.eccPub.data = NULL; } return ret; } static int32_t PrintEccPubkey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio) { RETURN_RET_IF(PrintPubkeyBits(true, layer, pkey, uio) != 0, CRYPT_DECODE_PRINT_KEYBITS); /* pub key */ CRYPT_EAL_PkeyPub pub = {0}; int32_t ret = GetEccPub(pkey, &pub); if (ret != CRYPT_SUCCESS) { return ret; } if (BSL_PRINT_Fmt(layer, uio, "Pub:\n") != 0 || BSL_PRINT_Hex(layer + 1, false, pub.key.eccPub.data, pub.key.eccPub.len, uio) != 0) { BSL_SAL_Free(pub.key.eccPub.data); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_ECC_PUB); return CRYPT_DECODE_PRINT_ECC_PUB; } BSL_SAL_Free(pub.key.eccPub.data); /* ASN1 OID */ CRYPT_PKEY_ParaId paraId = CRYPT_EAL_PkeyGetId(pkey) == CRYPT_PKEY_SM2 ? CRYPT_ECC_SM2 : CRYPT_EAL_PkeyGetParaId(pkey); const char *name = BSL_OBJ_GetOidNameFromCID((BslCid)paraId); if (BSL_PRINT_Fmt(layer, uio, "ANS1 OID: %s\n", name == NULL ? CRYPT_UNKOWN_STRING : name) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_ECC_OID); return CRYPT_DECODE_PRINT_ECC_OID; } return CRYPT_SUCCESS; } #endif // HITLS_CRYPTO_ECDSA || HITLS_CRYPTO_SM2 #ifdef HITLS_CRYPTO_RSA static int32_t GetRsaPub(const CRYPT_EAL_PkeyCtx *pkey, CRYPT_EAL_PkeyPub *pub) { uint32_t keyLen = CRYPT_EAL_PkeyGetKeyLen(pkey); if (keyLen == 0) { return CRYPT_DECODE_PRINT_NO_KEY; } uint8_t *buff = (uint8_t *)BSL_SAL_Malloc(keyLen * 2); // 2: n + e if (buff == NULL) { return CRYPT_MEM_ALLOC_FAIL; } pub->id = CRYPT_PKEY_RSA; pub->key.rsaPub.n = buff; pub->key.rsaPub.e = buff + keyLen; pub->key.rsaPub.nLen = keyLen; pub->key.rsaPub.eLen = keyLen; int32_t ret = CRYPT_EAL_PkeyGetPub(pkey, pub); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); BSL_SAL_Free(buff); pub->key.rsaPub.n = NULL; pub->key.rsaPub.e = NULL; } return ret; } int32_t CRYPT_EAL_PrintRsaPssPara(uint32_t layer, CRYPT_RSA_PssPara *para, BSL_UIO *uio) { if (para == NULL || uio == NULL) { return CRYPT_INVALID_ARG; } /* hash */ const char *mdIdName = BSL_OBJ_GetOidNameFromCID((BslCid)para->mdId); RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Hash Algorithm: %s%s\n", mdIdName == NULL ? CRYPT_UNKOWN_STRING : mdIdName, para->mdId == CRYPT_MD_SHA1 ? " (default)" : "") != BSL_SUCCESS, CRYPT_DECODE_PRINT_RSAPSS_PARA); /* mgf */ const char *mgfIdName = BSL_OBJ_GetOidNameFromCID((BslCid)para->mgfId); RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Mask Algorithm: %s%s\n", mgfIdName == NULL ? CRYPT_UNKOWN_STRING : mgfIdName, para->mgfId == CRYPT_MD_SHA1 ? " (default)" : "") != BSL_SUCCESS, CRYPT_DECODE_PRINT_RSAPSS_PARA); /* saltLen */ RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "Salt Length: 0x%x%s\n", para->saltLen, para->saltLen == 20 ? " (default)" : "") != 0, CRYPT_DECODE_PRINT_RSAPSS_PARA); /* trailer is not supported */ return CRYPT_SUCCESS; } static int32_t PrintRsaPssPara(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio) { CRYPT_RsaPadType padType = 0; int32_t ret = CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_RSA_PADDING, &padType, sizeof(CRYPT_RsaPadType)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (padType != CRYPT_EMSA_PSS) { return CRYPT_SUCCESS; } CRYPT_RSA_PssPara para = {0}; ret = CRYPT_EAL_GetRsaPssPara(pkey, &para); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (para.saltLen <= 0 && para.mdId == 0 && para.mgfId == 0) { return BSL_PRINT_Fmt(layer, uio, "No PSS parameter restrictions\n"); } RETURN_RET_IF(BSL_PRINT_Fmt(layer, uio, "PSS parameter restrictions:\n") != 0, CRYPT_DECODE_PRINT_RSAPSS_PARA); return CRYPT_EAL_PrintRsaPssPara(layer + 1, &para, uio); } static int32_t PrintRsaPubkey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio) { RETURN_RET_IF(PrintPubkeyBits(false, layer, pkey, uio) != 0, CRYPT_DECODE_PRINT_KEYBITS); /* pub key */ CRYPT_EAL_PkeyPub pub = {0}; int32_t ret = GetRsaPub(pkey, &pub); if (ret != CRYPT_SUCCESS) { return ret; } if (BSL_PRINT_Fmt(layer, uio, "Modulus:\n") != 0 || BSL_PRINT_Hex(layer + 1, false, pub.key.rsaPub.n, pub.key.rsaPub.nLen, uio) != 0) { BSL_SAL_Free(pub.key.rsaPub.n); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS); return CRYPT_DECODE_PRINT_MODULUS; } if (BSL_PRINT_Number(layer, "Exponent", pub.key.rsaPub.e, pub.key.rsaPub.eLen, uio) != 0) { BSL_SAL_Free(pub.key.rsaPub.n); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_EXPONENT); return CRYPT_DECODE_PRINT_EXPONENT; } BSL_SAL_Free(pub.key.rsaPub.n); return PrintRsaPssPara(layer, pkey, uio); } #endif // HITLS_CRYPTO_RSA int32_t CRYPT_EAL_PrintPubkey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio) { if (uio == NULL) { return CRYPT_INVALID_ARG; } CRYPT_PKEY_AlgId algId = CRYPT_EAL_PkeyGetId(pkey); switch (algId) { #ifdef HITLS_CRYPTO_RSA case CRYPT_PKEY_RSA: return PrintRsaPubkey(layer, pkey, uio); #endif #if defined(HITLS_CRYPTO_ECDSA) || defined(HITLS_CRYPTO_SM2) case CRYPT_PKEY_ECDSA: case CRYPT_PKEY_SM2: return PrintEccPubkey(layer, pkey, uio); #endif default: return CRYPT_DECODE_PRINT_UNSUPPORT_ALG; } } #ifdef HITLS_CRYPTO_RSA static inline int32_t PrintPrikeyBits(bool isEcc, uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio) { if (!isEcc) { return BSL_PRINT_Fmt(layer, uio, "Private-Key: (%d bit)\n", CRYPT_EAL_PkeyGetKeyBits(pkey)); } uint32_t bits = 0; int32_t ret = CRYPT_EAL_PkeyCtrl(pkey, CRYPT_CTRL_GET_ECC_ORDER_BITS, &bits, sizeof(uint32_t)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } return BSL_PRINT_Fmt(layer, uio, "Private-Key: (%d bit)\n", bits); } static int32_t PrintRsaPrikey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio) { RETURN_RET_IF(PrintPrikeyBits(false, layer, pkey, uio) != 0, CRYPT_DECODE_PRINT_KEYBITS); int32_t ret; /* pri key */ CRYPT_EAL_PkeyPrv pri = {0}; ret = CRYPT_EAL_InitRsaPrv(pkey, CRYPT_PKEY_RSA, &pri); if (ret != CRYPT_SUCCESS) { return ret; } ret = CRYPT_EAL_PkeyGetPrv(pkey, &pri); if (ret != CRYPT_SUCCESS) { CRYPT_EAL_DeinitRsaPrv(&pri); return ret; } if (BSL_PRINT_Fmt(layer, uio, "Modulus:\n") != 0 || BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.n, pri.key.rsaPrv.nLen, uio) != 0) { CRYPT_EAL_DeinitRsaPrv(&pri); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS); return CRYPT_DECODE_PRINT_MODULUS; } if (BSL_PRINT_Number(layer, "PublicExponent", pri.key.rsaPrv.e, pri.key.rsaPrv.eLen, uio) != 0) { CRYPT_EAL_DeinitRsaPrv(&pri); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_EXPONENT); return CRYPT_DECODE_PRINT_EXPONENT; } if (BSL_PRINT_Fmt(layer, uio, "PrivateExponent:\n") != 0 || BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.d, pri.key.rsaPrv.dLen, uio) != 0) { CRYPT_EAL_DeinitRsaPrv(&pri); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS); return CRYPT_DECODE_PRINT_MODULUS; } if (BSL_PRINT_Fmt(layer, uio, "Prime1:\n") != 0 || BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.p, pri.key.rsaPrv.pLen, uio) != 0) { CRYPT_EAL_DeinitRsaPrv(&pri); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS); return CRYPT_DECODE_PRINT_MODULUS; } if (BSL_PRINT_Fmt(layer, uio, "Prime2:\n") != 0 || BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.q, pri.key.rsaPrv.qLen, uio) != 0) { CRYPT_EAL_DeinitRsaPrv(&pri); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS); return CRYPT_DECODE_PRINT_MODULUS; } if (BSL_PRINT_Fmt(layer, uio, "Exponent1:\n") != 0 || BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.dP, pri.key.rsaPrv.dPLen, uio) != 0) { CRYPT_EAL_DeinitRsaPrv(&pri); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS); return CRYPT_DECODE_PRINT_MODULUS; } if (BSL_PRINT_Fmt(layer, uio, "Exponent2:\n") != 0 || BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.dQ, pri.key.rsaPrv.dQLen, uio) != 0) { CRYPT_EAL_DeinitRsaPrv(&pri); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS); return CRYPT_DECODE_PRINT_MODULUS; } if (BSL_PRINT_Fmt(layer, uio, "Coefficient:\n") != 0 || BSL_PRINT_Hex(layer + 1, false, pri.key.rsaPrv.qInv, pri.key.rsaPrv.qInvLen, uio) != 0) { CRYPT_EAL_DeinitRsaPrv(&pri); BSL_ERR_PUSH_ERROR(CRYPT_DECODE_PRINT_MODULUS); return CRYPT_DECODE_PRINT_MODULUS; } CRYPT_EAL_DeinitRsaPrv(&pri); return CRYPT_SUCCESS; } #endif int32_t CRYPT_EAL_PrintPrikey(uint32_t layer, CRYPT_EAL_PkeyCtx *pkey, BSL_UIO *uio) { if (uio == NULL) { return CRYPT_INVALID_ARG; } CRYPT_PKEY_AlgId algId = CRYPT_EAL_PkeyGetId(pkey); switch (algId) { #ifdef HITLS_CRYPTO_RSA case CRYPT_PKEY_RSA: return PrintRsaPrikey(layer, pkey, uio); #endif default: return CRYPT_DECODE_PRINT_UNSUPPORT_ALG; } } #endif // HITLS_CRYPTO_KEY_INFO
2302_82127028/openHiTLS-examples_1556
crypto/codecskey/src/crypt_encode_print.c
C
unknown
11,557
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_CURVE25519_H #define CRYPT_CURVE25519_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CURVE25519 #include <stdint.h> #include "crypt_local_types.h" #include "bsl_params.h" #ifdef __cplusplus extern "C" { #endif #define CRYPT_CURVE25519_KEYLEN 32 #define CRYPT_CURVE25519_SIGNLEN 64 typedef struct CryptCurve25519Ctx CRYPT_CURVE25519_Ctx; #ifdef HITLS_CRYPTO_X25519 /** * @ingroup curve25519 * @brief curve25519 Create a key pair structure and allocate memory space. * * @retval (CRYPT_CURVE25519_Ctx *) Pointer to the key pair structure * @retval NULL Invalid null pointer */ CRYPT_CURVE25519_Ctx *CRYPT_X25519_NewCtx(void); /** * @ingroup curve25519 * @brief curve25519 Create a key pair structure and allocate memory space. * * @param libCtx [IN] Library context * * @retval (CRYPT_CURVE25519_Ctx *) Pointer to the key pair structure * @retval NULL Invalid null pointer */ CRYPT_CURVE25519_Ctx *CRYPT_X25519_NewCtxEx(void *libCtx); #endif #ifdef HITLS_CRYPTO_ED25519 /** * @ingroup ed25519 * @brief curve25519 Create a key pair structure for ED25519 algorithm and allocate memory space. * * @retval (CRYPT_CURVE25519_Ctx *) Pointer to the key pair structure * @retval NULL Invalid null pointer */ CRYPT_CURVE25519_Ctx *CRYPT_ED25519_NewCtx(void); /** * @ingroup ed25519 * @brief curve25519 Create a key pair structure for ED25519 algorithm and allocate memory space. * * @param libCtx [IN] Library context * * @retval (CRYPT_CURVE25519_Ctx *) Pointer to the key pair structure * @retval NULL Invalid null pointer */ CRYPT_CURVE25519_Ctx *CRYPT_ED25519_NewCtxEx(void *libCtx); #endif /** * @ingroup curve25519 * @brief Copy the curve25519 context. The memory management of the return value is handed over to the caller. * * @param ctx [IN] Source curve25519 context. The CTX is set NULL by the invoker. * * @return CRYPT_CURVE25519_Ctx curve25519 Context pointer * If the operation fails, null is returned. */ CRYPT_CURVE25519_Ctx *CRYPT_CURVE25519_DupCtx(CRYPT_CURVE25519_Ctx *ctx); /** * @ingroup curve25519 * @brief Clear the curve25519 key pair data and releases memory. * * @param pkey [IN] curve25519 Key pair structure. The pkey is set NULL by the invoker. */ void CRYPT_CURVE25519_FreeCtx(CRYPT_CURVE25519_Ctx *pkey); /** * @ingroup curve25519 * @brief curve25519 Control interface * * @param pkey [IN/OUT] curve25519 Key pair structure * @param val [IN] Hash method, which must be SHA512. * @param opt [IN] Operation mode * @param len [IN] val length * * @retval CRYPT_SUCCESS set successfully. * @retval CRYPT_NULL_INPUT If any input parameter is empty * @retval CRYPT_CURVE25519_UNSUPPORTED_CTRL_OPTION The opt mode is not supported. * @retval CRYPT_CURVE25519_HASH_METH_ERROR The hash method is not SHA512 */ int32_t CRYPT_CURVE25519_Ctrl(CRYPT_CURVE25519_Ctx *pkey, int32_t opt, void *val, uint32_t len); /** * @ingroup curve25519 * @brief curve25519 Set the public key. * * @param pkey [IN] curve25519 Key pair structure * @param pub [IN] Public key * * @retval CRYPT_SUCCESS set successfully. * @retval CRYPT_NULL_INPUT If any input parameter is empty * @retval CRYPT_CURVE25519_KEYLEN_ERROR pubKeyLen is not equal to curve25519 public key length */ int32_t CRYPT_CURVE25519_SetPubKey(CRYPT_CURVE25519_Ctx *pkey, const CRYPT_Curve25519Pub *pub); /** * @ingroup curve25519 * @brief curve25519 Obtain the public key. * * @param pkey [IN] curve25519 Key pair structure * @param pub [OUT] Public key * * @retval CRYPT_SUCCESS set successfully. * @retval CRYPT_NULL_INPUT If any input parameter is empty * @retval CRYPT_CURVE25519_NO_PUBKEY The key pair has no public key. * @retval CRYPT_CURVE25519_KEYLEN_ERROR pubKeyLen is less than curve25519 public key length. */ int32_t CRYPT_CURVE25519_GetPubKey(const CRYPT_CURVE25519_Ctx *pkey, CRYPT_Curve25519Pub *pub); /** * @ingroup curve25519 * @brief curve25519 Set the private key. * * @param pkey [IN] curve25519 Key pair structure * @param prv [IN] Private key * * @retval CRYPT_SUCCESS set successfully. * @retval CRYPT_NULL_INPUT If any input parameter is empty * @retval CRYPT_CURVE25519_KEYLEN_ERROR prvKeyLen is not equal to curve25519 private key length */ int32_t CRYPT_CURVE25519_SetPrvKey(CRYPT_CURVE25519_Ctx *pkey, const CRYPT_Curve25519Prv *prv); /** * @ingroup curve25519 * @brief curve25519 Obtain the private key. * * @param pkey [IN] curve25519 Key pair structure * @param prv [OUT] private key * * @retval CRYPT_SUCCESS successfully set. * @retval CRYPT_NULL_INPUT Any input parameter is empty. * @retval CRYPT_CURVE25519_NO_PRVKEY The key pair has no private key. * @retval CRYPT_CURVE25519_KEYLEN_ERROR prvKeyLen is less than the private key length of curve25519. */ int32_t CRYPT_CURVE25519_GetPrvKey(const CRYPT_CURVE25519_Ctx *pkey, CRYPT_Curve25519Prv *prv); #ifdef HITLS_BSL_PARAMS /** * @ingroup curve25519 * @brief curve25519 Set the public key. * * @param pkey [IN] curve25519 Key pair structure * @param para [IN] Public key * * @retval CRYPT_SUCCESS set successfully. * @retval CRYPT_NULL_INPUT If any input parameter is empty * @retval CRYPT_CURVE25519_KEYLEN_ERROR pubKeyLen is not equal to curve25519 public key length */ int32_t CRYPT_CURVE25519_SetPubKeyEx(CRYPT_CURVE25519_Ctx *pkey, const BSL_Param *para); /** * @ingroup curve25519 * @brief curve25519 Set the private key. * * @param pkey [IN] curve25519 Key pair structure * @param para [IN] Private key * * @retval CRYPT_SUCCESS set successfully. * @retval CRYPT_NULL_INPUT If any input parameter is empty * @retval CRYPT_CURVE25519_KEYLEN_ERROR prvKeyLen is not equal to curve25519 private key length */ int32_t CRYPT_CURVE25519_SetPrvKeyEx(CRYPT_CURVE25519_Ctx *pkey, const BSL_Param *para); /** * @ingroup curve25519 * @brief curve25519 Obtain the public key. * * @param pkey [IN] curve25519 Key pair structure * @param para [OUT] Public key * * @retval CRYPT_SUCCESS set successfully. * @retval CRYPT_NULL_INPUT If any input parameter is empty * @retval CRYPT_CURVE25519_NO_PUBKEY The key pair has no public key. * @retval CRYPT_CURVE25519_KEYLEN_ERROR pubKeyLen is less than curve25519 public key length. */ int32_t CRYPT_CURVE25519_GetPubKeyEx(const CRYPT_CURVE25519_Ctx *pkey, BSL_Param *para); /** * @ingroup curve25519 * @brief curve25519 Obtain the private key. * * @param pkey [IN] curve25519 Key pair structure * @param para [OUT] private key * * @retval CRYPT_SUCCESS successfully set. * @retval CRYPT_NULL_INPUT Any input parameter is empty. * @retval CRYPT_CURVE25519_NO_PRVKEY The key pair has no private key. * @retval CRYPT_CURVE25519_KEYLEN_ERROR prvKeyLen is less than the private key length of curve25519. */ int32_t CRYPT_CURVE25519_GetPrvKeyEx(const CRYPT_CURVE25519_Ctx *pkey, BSL_Param *para); #endif /** * @ingroup curve25519 * @brief curve25519 Obtain the key length, in bits. * * @param pkey [IN] curve25519 Key pair structure * * @retval Key length */ int32_t CRYPT_CURVE25519_GetBits(const CRYPT_CURVE25519_Ctx *pkey); #ifdef HITLS_CRYPTO_ED25519 /** * @ingroup curve25519 * @brief curve25519 Sign * * @param pkey [IN/OUT] curve25519 Key pair structure. A private key is required for signature. * After signature, a public key is generated. * @param algid [IN] md algid * @param msg [IN] Data to be signed * @param msgLen [IN] Data length: 0 <= msgLen <= (2^125 - 64) bytes * @param hashMethod [IN] SHA512 method * @param sign [OUT] Signature * @param signLen [IN/OUT] Length of the signature buffer (must be greater than 64 bytes)/Length of the signature * * @retval CRYPT_SUCCESS generated successfully. * @retval CRYPT_CURVE25519_NO_PRVKEY The key pair has no private key. * @retval CRYPT_NULL_INPUT If any input parameter is empty * @retval Error code of the hash module. An error occurs in the sha512 operation. * @retval CRYPT_CURVE25519_NO_HASH_METHOD No hash method is set. * @retval CRYPT_CURVE25519_SIGNLEN_ERROR signLen is less than the signature length of curve25519. */ int32_t CRYPT_CURVE25519_Sign(CRYPT_CURVE25519_Ctx *pkey, int32_t algId, const uint8_t *msg, uint32_t msgLen, uint8_t *sign, uint32_t *signLen); /** * @ingroup curve25519 * @brief curve25519 Obtain the signature length, in bytes. * * @param pkey [IN] curve25519 Key pair structure * * @retval Signature length */ int32_t CRYPT_CURVE25519_GetSignLen(const CRYPT_CURVE25519_Ctx *pkey); /** * @ingroup curve25519 * @brief curve25519 Verification * * @param pkey [IN] curve25519 Key pair structure. A public key is required for signature verification. * @param algid [IN] md algid * @param msg [IN] Data * @param msgLen [IN] Data length: 0 <= msgLen <= (2^125 - 64) bytes * @param sign [IN] Signature * @param signLen [IN] Signature length, which must be 64 bytes * * @retval CRYPT_SUCCESS The signature verification is successful. * @retval CRYPT_CURVE25519_NO_PUBKEY The key pair has no public key. * @retval CRYPT_NULL_INPUT If any input parameter is empty * @retval Error code of the hash module. An error occurs in the sha512 operation. * @retval CRYPT_CURVE25519_VERIFY_FAIL Failed to verify the signature. * @retval CRYPT_CURVE25519_INVALID_PUBKEY Invalid public key. * @retval CRYPT_CURVE25519_SIGNLEN_ERROR signLen is not equal to curve25519 signature length * @retval CRYPT_CURVE25519_NO_HASH_METHOD No hash method is set. */ int32_t CRYPT_CURVE25519_Verify(const CRYPT_CURVE25519_Ctx *pkey, int32_t algId, const uint8_t *msg, uint32_t msgLen, const uint8_t *sign, uint32_t signLen); /** * @ingroup curve25519 * @brief ed25519 Generate a key pair (public and private keys). * * @param pkey [IN/OUT] curve25519 Key pair structure/Key pair structure containing public and private keys * * @retval CRYPT_SUCCESS generated successfully. * @retval CRYPT_NO_REGIST_RAND Unregistered random number * @retval Error code of the hash module. An error occurs during the SHA512 operation. * @retval Error code of the registered random number module. Failed to obtain the random number. * @retval CRYPT_CURVE25519_NO_HASH_METHOD No hash method is set. * @retval CRYPT_NULL_INPUT The input parameter is empty. */ int32_t CRYPT_ED25519_GenKey(CRYPT_CURVE25519_Ctx *pkey); #endif /* HITLS_CRYPTO_ED25519 */ #ifdef HITLS_CRYPTO_X25519 /** * @ingroup curve25519 * @brief x25519 Calculate the shared key based on the private key of the local end and the public key of the peer end. * * @param prvKey [IN] curve25519 Key pair structure, local private key * @param pubKey [IN] curve25519 Key pair structure, peer public key * @param sharedKey [OUT] Shared key * @param shareKeyLen [IN/OUT] Shared key length * * @retval CRYPT_SUCCESS generated successfully. * @retval CRYPT_CURVE25519_KEY_COMPUTE_FAILED Failed to generate the shared key. */ int32_t CRYPT_CURVE25519_ComputeSharedKey(CRYPT_CURVE25519_Ctx *prvKey, CRYPT_CURVE25519_Ctx *pubKey, uint8_t *sharedKey, uint32_t *shareKeyLen); /** * @ingroup curve25519 * @brief x25519 Generate a key pair (public and private keys). * * @param pkey [IN/OUT] curve25519 Key pair structure/Key pair structure containing public and private keys * * @retval CRYPT_SUCCESS generated successfully. * @retval CRYPT_NO_REGIST_RAND Unregistered random number callback * @retval Error code of the registered random number module. Failed to obtain the random number. * @retval CRYPT_NULL_INPUT The input parameter is empty. */ int32_t CRYPT_X25519_GenKey(CRYPT_CURVE25519_Ctx *pkey); #endif /* HITLS_CRYPTO_X25519 */ /** * @ingroup curve25519 * @brief curve25519 Public key comparison * * @param a [IN] curve25519 Context structure * @param b [IN] curve25519 Context structure * * @retval CRYPT_SUCCESS is the same * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_CURVE25519_PUBKEY_NOT_EQUAL Public Keys are not equal */ int32_t CRYPT_CURVE25519_Cmp(const CRYPT_CURVE25519_Ctx *a, const CRYPT_CURVE25519_Ctx *b); /** * @ingroup curve25519 * @brief curve25519 get security bits * * @param ctx [IN] curve25519 Context structure * * @retval security bits */ int32_t CRYPT_CURVE25519_GetSecBits(const CRYPT_CURVE25519_Ctx *ctx); #ifdef HITLS_CRYPTO_PROVIDER /** * @ingroup curve25519 * @brief curve25519 import key * * @param ctx [IN/OUT] curve25519 context structure * @param params [IN] parameters */ int32_t CRYPT_CURVE25519_Import(CRYPT_CURVE25519_Ctx *ctx, const BSL_Param *params); /** * @ingroup curve25519 * @brief curve25519 export key * * @param ctx [IN] curve25519 context structure * @param params [IN/OUT] key parameters */ int32_t CRYPT_CURVE25519_Export(const CRYPT_CURVE25519_Ctx *ctx, BSL_Param *params); #endif // HITLS_CRYPTO_PROVIDER #ifdef HITLS_CRYPTO_ED25519_CHECK /** * @ingroup ed25519 * @brief ed25519 check key pair * * @param checkType [IN] check type * @param pkey1 [IN] ed25519 context structure * @param pkey2 [IN] ed25519 context structure * * @retval CRYPT_SUCCESS successfully. * @retval other error. */ int32_t CRYPT_ED25519_Check(uint32_t checkType, const CRYPT_CURVE25519_Ctx *pkey1, const CRYPT_CURVE25519_Ctx *pkey2); #endif // HITLS_CRYPTO_ED25519_CHECK #ifdef HITLS_CRYPTO_X25519_CHECK /** * @ingroup x25519 * @brief x25519 check key pair * * @param checkType [IN] check type * @param pkey1 [IN] x25519 context structure * @param pkey2 [IN] x25519 context structure * * @retval CRYPT_SUCCESS successfully. * @retval other error. */ int32_t CRYPT_X25519_Check(uint32_t checkType, const CRYPT_CURVE25519_Ctx *pkey1, const CRYPT_CURVE25519_Ctx *pkey2); #endif // HITLS_CRYPTO_X25519_CHECK #ifdef __cplusplus } #endif #endif // HITLS_CRYPTO_CURVE25519 #endif // CRYPT_CURVE25519_H
2302_82127028/openHiTLS-examples_1556
crypto/curve25519/include/crypt_curve25519.h
C
unknown
15,400
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_X25519 #include "crypt_arm.h" .file "x25519_armv8.S" .text .macro push_stack /* save register. */ stp x19, x20, [sp, #-16]! stp x21, x22, [sp, #-16]! sub sp, sp, #32 .endm .macro pop_stack add sp, sp, #32 /* pop register */ ldp x21, x22, [sp], #16 ldp x19, x20, [sp], #16 .endm .macro u64mul oper1, oper2 mul x19, \oper1, \oper2 umulh x2, \oper1, \oper2 .endm .macro u51mul cur, low, high u64mul x3, \cur adds \low, \low, x19 adc \high, \high, x2 .endm .macro reduce /* retain the last 51 bits */ mov x8, #0x7ffffffffffff /* 计算 h2' */ mov x3, x9 lsr x9, x9, #51 // carry(h2-low) lsl x10, x10, #13 // (h2-high) << 13 /* 计算 h0' */ mov x1, x4 lsr x4, x4, #51 // carry(h1-low) lsl x5, x5, #13 // (h1-high) << 13 /* 计算 h2' */ and x3, x3, x8 // h2' = rax = h2 & (2^51 - 1) = r12 & (2^51 - 1) orr x10, x10, x9 // r13 = (h2 >> 51) adds x11, x11, x10 // h3 += (h2 >> 51) adc x12, x12, XZR // h3-high carry /* 计算 h0' */ and x1, x1, x8 // h0' = rsi = h0 & (2^51 - 1) = r8 & (2^51 - 1) orr x5, x5, x4 // r9 = (h0 >> 51) adds x6, x6, x5 // h1 += (h0 >> 51) adc x7, x7, XZR // h1-high carry /* 计算 h3' */ mov x4, x11 // h3-low -> x4 lsr x11, x11, #51 // h3->low >> 51 lsl x12, x12, #13 // h3-high << 13 and x4, x4, x8 // h3' = r8 = h3 & (2^51 - 1) = r14 & (2^51 - 1) orr x12, x12, x11 // r15 = (h3 >> 51) adds x13, x13, x12 // h4 += (h3 >> 51) adc x14, x14, XZR // h4-high carry /* 计算 h1' */ mov x2, x6 // h1-low -> x2 lsr x6, x6, #51 // h1->low >> 51 lsl x7, x7, #13 // h1-high << 13 and x2, x2, x8 // h1' = rdx = h1 & (2^51 - 1) = r10 & (2^51 - 1) orr x7, x7, x6 // r11 = (h1 >> 51) adds x3, x3, x7 // h2 += (h1 >> 51) /* 计算 h4' */ mov x5, x13 // h4-low -> x5 lsr x13, x13, #51 // h4->low >> 51 lsl x14, x14, #13 // h4-high << 13 and x5, x5, x8 // h4' = r9 = h4 & (2^51 - 1) = rbx & (2^51 - 1) orr x14, x14, x13 // rcx = (h4 >> 51) /* out[0] = out[0] + 19 * carry */ lsl x6, x14, #3 adds x6, x6, x14 // h4-high * 8 + h4-high -> x6 (9 * h4-high) adds x14, x14, x6, lsl #1 // x6 *2 + x14 => x6 --- h4-high * 9 * 2 + h4-high adds x1, x1, x14 // h4-high * 19 +->h0-low /* h2 剩余 */ mov x6, x3 // h2-low -> x6 and x3, x8, x3 // h2 &= (2^51 - 1) lsr x6, x6, #51 // h2-low << 51 adds x4, x4, x6 // h2-low << 51 -> h3-low /* out[1] += out[0] >> 51 */ mov x6, x1 // h0-low -> x6 /* out[0] &= (2^51 - 1) */ and x1, x1, x8 // clear the upper 13 bits of h0-low lsr x6, x6, #51 // h0-low << 51 adds x2, x2, x6 // h0-low << 51 -> h1-low /* 存储结果 */ str x1, [x0] // h0' str x2, [x0, #8] // h1' str x3, [x0, #16] // h2' str x4, [x0, #24] // h3' str x5, [x0, #32] // h4' .endm ############################################################# # void Fp51Mul (Fp51 *out, const Fp51 *f, const Fp51 *g); ############################################################# .globl Fp51Mul .type Fp51Mul, @function .align 6 Fp51Mul: AARCH64_PACIASP /* save register */ push_stack /* * x0: out; x1: f; x2: g; fp51: array[u64; 5] */ ldr x3, [x1] // f0 ldr x13, [x2] // g0 ldp x11, x12, [x2, #8] // g1, g2 ldp x15, x14, [x2, #24] // g3, g4 str x0, [sp, #24] /* * x13, x11, and x12 will be overwritten in subsequent calculation, and g0 to g2 will be stored. */ mov x8, #19 /* h0 = f0g0 + 19f1g4 + 19f2g3 + 19f3g2 + 19f4g1; save in x4(low), x5(high) */ mul x4, x3, x13 // (x4, x5) = f0 * g0 umulh x5, x3, x13 str x13, [sp, #16] // g0 /* h1 = f0g1 + f1g0 + 19f2g4 + 19f3g3 + 19f4g2; save in x6, x7 */ mul x6, x3, x11 // (x6, x7) = f0 * g1 umulh x7, x3, x11 lsl x13, x14, #3 add x13, x13, x14 // g4 * 8 + g4 = g4 * 9 str x11, [sp, #8] // g1 /* h2 = f0g2 + f1g1 + f2g0 + 19f3g4 + 19f4g3; save in x9, x10 */ mul x9, x3, x12 // (x9, x10) = f0 * g2 umulh x10, x3, x12 lsl x0, x13, #1 add x0, x0, x14 // rdi = 2 * (9 * g4) + g4 str x12, [sp] // g2 /* h3 = f0g3 + f1g2 + f2g1 + f3g0 + 19f4g4; save in x11, x12 */ mul x11, x3, x15 // (x11, x12) = f0 * g3 umulh x12, x3, x15 /* h4 = f0g4 + f1g3 + f2g2 + f3g1 + f4g0; save in x13, x14 */ mul x13, x3, x14 // (x13, x14) = f0 * g4 umulh x14, x3, x14 ldr x3, [x1, #8] // f1 /* compute 19 * g4 */ u51mul x0, x4, x5 // (x4, x5) = 19 * f1 * g4; load f2 ldr x3, [x1, #16] u51mul x0, x6, x7 // (x6, x7) = 19 * f2 * g4; load f3 ldr x3, [x1, #24] u51mul x0, x9, x10 // (x9, x10) = 19 * f3 * g4; load f4 ldr x3, [x1, #32] u51mul x0, x11, x12 // (x11, x12) = 19 * f3 * g4; load f4 ldr x3, [x1, #8] mul x0, x15, x8 // 19 * g3 /* compute g3 */ u64mul x3, x15 // (x13, x14) = f1 * g3 ldr x15, [sp] // g2 adds x13, x13, x19 ldr x3, [x1, #16] // f2 adc x14, x14, x2 u51mul x0, x4, x5 // (x4, x5) = 19 * f2 * g3; load f3 ldr x3, [x1, #24] u51mul x0, x6, x7 // (x6, x7) = 19 * f3 * g3; load f4 ldr x3, [x1, #32] u64mul x3, x0 // (rax, rdx) = 19 * f4 * g3 mul x0, x15, x8 // 19 * g2 adds x9, x9, x19 ldr x3, [x1, #8] // f1 adc x10, x10, x2 /* compute g2 */ u51mul x15, x11, x12 // (x11, x12) = f1 * g2; load f2 ldr x3, [x1, #16] u64mul x3, x15 // (rax, rdx) = f2 * g2 ldr x15, [sp, #8] // g1 adds x13, x13, x19 ldr x3, [x1, #24] // f3 adc x14, x14, x2 u51mul x0, x4, x5 // (x4, x5) = 19 * f3 * g2; load f4 ldr x3, [x1, #32] u51mul x0, x6, x7 // (x6, x7) = 19 * f4 * g2; load f2 ldr x3, [x1, #8] /* compute g1 */ u64mul x3, x15 // (x19, x2) = f1 * g1 mul x0, x15, x8 // 19 * g1 adds x9, x9, x19 ldr x3, [x1, #16] // f2 adc x10, x10, x2 u51mul x15, x11, x12 // (x11, x12) += f2 * g1; load f3 ldr x3, [x1, #24] u64mul x3, x15 // (x19, x2) = f3 * g1 ldr x15, [sp, #16] // g0 adds x13, x13, x19 ldr x3, [x1, #32] // f4 adc x14, x14, x2 u51mul x0, x4, x5 // (x4, x5) += 19 * f4 * g1; load f1 ldr x3, [x1, #8] /* compute g0 */ u51mul x15, x6, x7 // (x6, x7) += f1 * g0; load f2 ldr x3, [x1, #16] u51mul x15, x9, x10 // (x9, x10) += f2 * g0; load f3 ldr x3, [x1, #24] u51mul x15, x11, x12 // (x11, x12) = f3 * g0; load f4 ldr x3, [x1, #32] u64mul x3, x15 // (x13, x14) += f4 * g0 adds x13, x13, x19 adc x14, x14, x2 /* pop stack register */ ldr x0, [sp, #24] reduce pop_stack AARCH64_AUTIASP ret .size Fp51Mul,.-Fp51Mul ############################################################# # void Fp51Square(Fp51 *out, const Fp51 *f); ############################################################# .globl Fp51Square .type Fp51Square, @function .align 6 Fp51Square: AARCH64_PACIASP push_stack /* * x0: out; x1: f; fp51 : array [u64; 5] */ ldr x3, [x1] // f0 ldr x12, [x1, #16] // f2 ldr x14, [x1, #32] // f4 mov x8, #19 lsl x2, x3, #1 // 2 * f0 str x0, [sp, #24] /* h0 = f0^2 + 38f1f4 + 38f2f3; save in x4, x5 */ mul x4, x3, x3 // (x4, x5) = f0^2 umulh x5, x3, x3 ldr x3, [x1, #8] // f1 /* h1 = 19f3^2 + 2f0f1 + 38f2g4; save in x6, x7 */ mul x6, x3, x2 // (x6, x7) = 2f0 * f1 umulh x7, x3, x2 str x12, [sp, #16] // save f2 /* h2 = f1^2 + 2f0f2 + 38f3g4; save in x9, x10 */ mul x9, x12, x2 // (x9, x10) = 2f0 * f2 umulh x10, x12, x2 ldr x3, [x1, #24] // f3 mul x0, x14, x8 // 19 * f4 /* h3 = 19f4^2 + 2f0f3 + 2f1f2; save in r14, r15 */ mul x11, x3, x2 // (x11, x12) = 2f0 * f3 umulh x12, x3, x2 mov x3, x14 // f4 /* h4 = f2^2 + 2f0f4 + 2f1f3; save in x13, x14 */ mul x13, x3, x2 // (x13, x14) = 2f0 * f4 umulh x14, x3, x2 /* * h3: compute 19 * f4 */ u51mul x0, x11, x12 // (x11, x12) += 19 * f4^2; load f1 ldr x3, [x1, #8] /* * h2 : compute f1 */ lsl x15, x3, #1 // 2 * f1 u51mul x3, x9, x10 // (x9, x10) += f1^2; load f2 ldr x3, [sp, #16] /* h3 */ u51mul x15, x11, x12 // (x11, x12) += 2 * f1 * f2; load f3 ldr x3, [x1, #24] /* h4 */ u51mul x15, x13, x14 // (x13, x14) = 2 * f1 * f3; load 2 * f1 mov x3, x15 ldr x1, [x1, #24] // f3 mul x15, x1, x8 // 19 * f3 /* h0 */ u64mul x3, x0 lsl x3, x1, #1 // 2 * f3 adds x4, x4, x19 // (x4, x5) += 2 * f1 * 19 * f4 adc x5, x5, x2 /* * h2: compute f3 */ u51mul x0, x9, x10 // (x9, x10) += f3 * 2 * 19 * f4; load f3 mov x3, x1 /* h1 */ u51mul x15, x6, x7 // (x6, x7) += 19 * f3 * f3; load f2 ldr x3, [sp, #16] /* * h4: compute f2 */ lsl x1, x3, #1 // 2 * f2 u51mul x3, x13, x14 // (x13, x14) += f2 * f2; load 19 * f3 mov x3, x15 /* h0 */ u51mul x1, x4, x5 // (x4, x5) = 2 * f2 * 19 * f3; load 2 * f2 mov x3, x1 /* h1 */ u64mul x3, x0 // (x6, x7) += 2 * f2 * 19 * f4 adds x6, x19, x6 adc x7, x2, x7 ldr x0, [sp, #24] reduce pop_stack AARCH64_AUTIASP ret .size Fp51Square,.-Fp51Square ############################################################# # void Fp51MulScalar(Fp51 *out, const Fp51 *in); ############################################################# .globl Fp51MulScalar .type Fp51MulScalar, @function .align 6 Fp51MulScalar: AARCH64_PACIASP /* * x0: out; x1: in; fp51 array [u64; 5] */ /* mov 121666 */ mov x3, #0xDB42 movk x3, #0x1, lsl #16 /* ldr f0, f1 */ ldp x2, x8, [x1] /* h0 */ mul x4, x2, x3 // f0 * 121666 umulh x5, x2, x3 /* h1 */ mul x6, x8, x3 // f1 * 121666 umulh x7, x8, x3 /* ldr f2, f3 */ ldp x2, x8, [x1, #16] /* h2 */ mul x9, x2, x3 // f2 * 121666 umulh x10, x2, x3 /* h3 */ mul x11, x8, x3 // f3 * 121666 umulh x12, x8, x3 /* ldr f4 */ ldr x8, [x1, #32] /* h4 */ mul x13, x3, x8 // f4 * 121666 umulh x14, x3, x8 reduce AARCH64_AUTIASP ret .size Fp51MulScalar,.-Fp51MulScalar #endif
2302_82127028/openHiTLS-examples_1556
crypto/curve25519/src/asm/x25519_armv8.S
Unix Assembly
unknown
13,608
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_X25519 .file "x25519_x86_64.S" .text .macro push_stack /* Save register. The following registers need to be saved by the caller and restored when the function exits. */ pushq %rbx pushq %rbp pushq %r12 pushq %r13 pushq %r14 pushq %r15 /* Allocate stack space and store the following necessary content: */ leaq -32(%rsp), %rsp .endm .macro pop_stack /* Recovery register */ movq 32(%rsp),%r15 movq 40(%rsp),%r14 movq 48(%rsp),%r13 movq 56(%rsp),%r12 movq 64(%rsp),%rbp movq 72(%rsp),%rbx /* Restore stack pointer. The stack is opened with 32 bytes and 6 registers are restored. The total number is 80 bytes. */ leaq 80(%rsp), %rsp .endm .macro u51mul cur, low, high, next mulq \cur addq %rax, \low movq \next, %rax adcq %rdx, \high .endm .macro reduce /* Retain the last 51 digits. */ movq $0x7ffffffffffff, %rbp /* Calculate h2' */ movq %r12, %rax shrq $51, %r12 shlq $13, %r13 /* Calculate h0' */ movq %r8, %rsi shrq $51, %r8 shlq $13, %r9 /* Calculate h2' */ andq %rbp, %rax // h2' = rax = h2 & (2^51 - 1) = r12 & (2^51 - 1) orq %r12, %r13 // r13 = (h2 >> 51) addq %r13, %r14 // h3 += (h2 >> 51) adcq $0, %r15 /* Calculate h0' */ andq %rbp, %rsi // h0' = rsi = h0 & (2^51 - 1) = r8 & (2^51 - 1) orq %r8, %r9 // r9 = (h0 >> 51) addq %r9, %r10 // h1 += (h0 >> 51) adcq $0, %r11 /* Calculate h3' */ movq %r14, %r8 shrq $51, %r14 shlq $13, %r15 andq %rbp, %r8 // h3' = r8 = h3 & (2^51 - 1) = r14 & (2^51 - 1) orq %r14, %r15 // r15 = (h3 >> 51) addq %r15, %rbx // h4 += (h3 >> 51) adcq $0, %rcx /* Calculate h1' */ movq %r10, %rdx shrq $51, %r10 shlq $13, %r11 andq %rbp, %rdx // h1' = rdx = h1 & (2^51 - 1) = r10 & (2^51 - 1) orq %r10, %r11 // r11 = (h1 >> 51) addq %r11, %rax // h2 += (h1 >> 51) /* Calculate h4' */ movq %rbx, %r9 shrq $51, %rbx shlq $13, %rcx andq %rbp, %r9 // h4' = r9 = h4 & (2^51 - 1) = rbx & (2^51 - 1) orq %rbx, %rcx // rcx = (h4 >> 51) /* out[0] = out[0] + 19 * carry */ leaq (%rcx, %rcx, 8), %r10 // r10 = 8 * rcx leaq (%rcx, %r10, 2), %rcx // rcx = 2 * (8 * rcx) + rcx = 19 * rcx addq %rcx, %rsi /* h2 remaining */ movq %rax, %r10 andq %rbp, %rax // h2 &= (2^51 - 1) shrq $51, %r10 addq %r10, %r8 /* out[1] += out[0] >> 51 */ movq %rsi, %r10 /* out[0] &= (2^51 - 1) */ andq %rbp, %rsi shrq $51, %r10 addq %r10, %rdx /* Storing Results */ movq %rsi, (%rdi) // h0' movq %rdx, 8(%rdi) // h1' movq %rax, 16(%rdi) // h2' movq %r8, 24(%rdi) // h3' movq %r9, 32(%rdi) // h4' .endm ############################################################# # void Fp51Mul (Fp51 *out, const Fp51 *f, const Fp51 *g); ############################################################# .globl Fp51Mul .type Fp51Mul, @function .align 32 Fp51Mul: .cfi_startproc /* Save Register */ push_stack /* The input and output parameters are transferred by registers rdi, rsi, and rdx. * rdi: out; rsi: f; rdx: g; fp51 is an array of [u64; 5] * rdx will be overwritten in subsequent calculation. * Therefore, you need to load the data in the rdx variable in advance. */ movq (%rsi), %rax // f0 movq (%rdx), %rbx // g0 movq 8(%rdx), %r14 // g1 movq 16(%rdx), %r15 // g2 movq 24(%rdx), %rbp // g3, Store g0-g3, store g3 in unaffected registers movq 32(%rdx), %rcx // g4 /* Stores the out pointer and frees the rdi so that the rdi can be used in subsequent calculations. Stores 19 * g4. */ movq %rdi, 24(%rsp) movq %rax, %rdi // f0 /* r14, r15, rbx, and rcx will be overwritten in subsequent calculations. g0 to g2 will be stored. * Storage actions will be scattered in the calculation code for performance purposes. */ /* h0 = f0g0 + 19f1g4 + 19f2g3 + 19f3g2 + 19f4g1; Stored in r8, r9 */ mulq %rbx // (rax, rdx) = f0 * g0, in le movq %rax, %r8 movq %rdi, %rax // f0 movq %rbx, 16(%rsp) // g0 movq %rdx, %r9 /* h1 = f0g1 + f1g0 + 19f2g4 + 19f3g3 + 19f4g2; Stored in r10, r11 */ mulq %r14 // (rax, rdx) = f0 * g1 movq %rax, %r10 movq %rdi, %rax // f0 leaq (%rcx, %rcx, 8), %rbx // g4 * 8 + g4 = g4 * 9 movq %r14, 8(%rsp) // g1 movq %rdx, %r11 /* h2 = f0g2 + f1g1 + f2g0 + 19f3g4 + 19f4g3; Stored in r12, r13 */ mulq %r15 // (rax, rdx) = f0 * g2 movq %rax, %r12 movq %rdi, %rax // f0 leaq (%rcx, %rbx, 2), %rdi // rdi = 2 * (9 * g4) + g4, Store 19 * g4 to rdi before rcx is overwritten movq %r15, (%rsp) // g2 movq %rdx, %r13 /* h3 = f0g3 + f1g2 + f2g1 + f3g0 + 19f4g4; Stored in r14, r15 */ mulq %rbp // (rax, rdx) = f0 * g3 movq %rax, %r14 movq (%rsi), %rax // f0 movq %rdx, %r15 /* h4 = f0g4 + f1g3 + f2g2 + f3g1 + f4g0; Stored in rbx, rcx */ mulq %rcx // (rax, rdx) = f0 * g4 movq %rax, %rbx movq 8(%rsi), %rax // f1 movq %rdx, %rcx /* Calculate 19 * g4 related */ u51mul %rdi, %r8, %r9, 16(%rsi) // (rax, rdx) = 19 * f1 * g4; load f2 u51mul %rdi, %r10, %r11, 24(%rsi) // (rax, rdx) = 19 * f2 * g4; load f3 u51mul %rdi, %r12, %r13, 32(%rsi) // (rax, rdx) = 19 * f3 * g4; load f4 mulq %rdi // (rax, rdx) = 19 * f4 * g4 imulq $19, %rbp, %rdi // 19 * g3 addq %rax, %r14 movq 8(%rsi), %rax // f1 adcq %rdx, %r15 /* Calculate g3 related */ mulq %rbp // (rax, rdx) = f1 * g3 movq (%rsp), %rbp // g2 addq %rax, %rbx movq 16(%rsi), %rax // f2 adcq %rdx, %rcx u51mul %rdi, %r8, %r9, 24(%rsi) // (rax, rdx) = 19 * f2 * g3; load f3 u51mul %rdi, %r10, %r11, 32(%rsi) // (rax, rdx) = 19 * f3 * g3; load f4 mulq %rdi // (rax, rdx) = 19 * f4 * g3 imulq $19, %rbp, %rdi // 19 * g2 addq %rax, %r12 movq 8(%rsi), %rax // f1 adcq %rdx, %r13 /* Calculate g2 related */ u51mul %rbp, %r14, %r15, 16(%rsi) // (rax, rdx) = f1 * g2; load f2 mulq %rbp // (rax, rdx) = f2 * g2 movq 8(%rsp), %rbp // g1 addq %rax, %rbx movq 24(%rsi), %rax // f3 adcq %rdx, %rcx u51mul %rdi, %r8, %r9, 32(%rsi) // (rax, rdx) = 19 * f3 * g2; load f4 u51mul %rdi, %r10, %r11, 8(%rsi) // (rax, rdx) = 19 * f4 * g2; load f2 /* Calculate g1 related */ mulq %rbp // (rax, rdx) = f1 * g1 imulq $19, %rbp, %rdi // 19 * g1 addq %rax, %r12 movq 16(%rsi), %rax // f2 adcq %rdx, %r13 u51mul %rbp, %r14, %r15, 24(%rsi) // (rax, rdx) = f2 * g1; load f3 mulq %rbp // (rax, rdx) = f3 * g1 movq 16(%rsp), %rbp // g0 addq %rax, %rbx movq 32(%rsi), %rax // f4 adcq %rdx, %rcx u51mul %rdi, %r8, %r9, 8(%rsi) // (rax, rdx) = 19 * f4 * g1; load f1 /* Calculate g0 related */ u51mul %rbp, %r10, %r11, 16(%rsi) // (rax, rdx) = f1 * g0; load f2 u51mul %rbp, %r12, %r13, 24(%rsi) // (rax, rdx) = f2 * g0; load f3 u51mul %rbp, %r14, %r15, 32(%rsi) // (rax, rdx) = f3 * g0; load f4 mulq %rbp // (rax, rdx) = f4 * g0 addq %rax, %rbx adcq %rdx, %rcx /* Restore the stack pointer. */ movq 24(%rsp), %rdi reduce /* Recovery register */ pop_stack ret .cfi_endproc .size Fp51Mul,.-Fp51Mul ############################################################# # void Fp51Square(Fp51 *out, const Fp51 *f); ############################################################# .globl Fp51Square .type Fp51Square, @function .align 32 Fp51Square: .cfi_startproc /* Save Register */ push_stack /* The input and output parameters are transferred by registers rdi and rsi. * rdi: out; rsi: f; fp51 is an array of [u64; 5] * Loads only non-adjacent data, vacating registers for storage calculations */ movq (%rsi), %rax // f0 movq 16(%rsi), %r15 // f2 movq 32(%rsi), %rcx // f4 /* Open the stack and store the following necessary content, which is consistent with the Fp51Mul. * Stores the out pointer, frees the rdi, * so that the rdi can be used in subsequent calculations, and stores 19 * f4. */ leaq (%rax, %rax, 1), %rbp // 2 * f0 movq %rdi, 24(%rsp) /* h0 = f0^2 + 38f1f4 + 38f2f3; Stored in r8, r9 */ mulq %rax // (rax, rdx) = f0^2 movq %rax, %r8 movq 8(%rsi), %rax // f1 movq %rdx, %r9 /* h1 = 19f3^2 + 2f0f1 + 38f2g4; Stored in r10, r11 */ mulq %rbp // (rax, rdx) = 2f0 * f1 movq %rax, %r10 movq %r15, %rax // f2 movq %r15, 16(%rsp) // Store f2 for later use of rsi movq %rdx, %r11 /* h2 = f1^2 + 2f0f2 + 38f3g4; Stored in r12, r13 */ mulq %rbp // (rax, rdx) = 2f0 * f2 movq %rax, %r12 movq 24(%rsi), %rax // f3 movq %rdx, %r13 imulq $19, %rcx, %rdi // Store 19 * f4 to rdi before rcx is overwritten /* h3 = 19f4^2 + 2f0f3 + 2f1f2; Stored in r14, r15 */ mulq %rbp // (rax, rdx) = 2f0 * f3 movq %rax, %r14 movq %rcx, %rax // f4 movq %rdx, %r15 /* h4 = f2^2 + 2f0f4 + 2f1f3; Stored in rbx, rcx */ mulq %rbp // (rax, rdx) = 2f0 * f4 movq %rax, %rbx movq %rcx, %rax // f4 movq %rdx, %rcx /* Calculate 19 * f4 related * h3 */ u51mul %rdi, %r14, %r15, 8(%rsi) // (rax, rdx) = 19 * f4^2; load f1 movq 24(%rsi), %rsi // f3 /* Calculate f1 related * h2 */ leaq (%rax, %rax, 1), %rbp // 2 * f1 u51mul %rax, %r12, %r13, 16(%rsp) // (rax, rdx) = f1^2; load f2 /* h3 */ u51mul %rbp, %r14, %r15, %rsi // (rax, rdx) = 2 * f1 * f2; load f3 /* h4 */ u51mul %rbp, %rbx, %rcx, %rbp // (rax, rdx) = 2 * f1 * f3; load 2 * f1 imulq $19, %rsi, %rbp // 19 * f3 /* h0 */ mulq %rdi // (rax, rdx) = 2 * f1 * 19 * f4 addq %rax, %r8 leaq (%rsi, %rsi, 1), %rax // 2 * f3 adcq %rdx, %r9 /* Calculate f3 related * h2 */ u51mul %rdi, %r12, %r13, %rsi // (rax, rdx) = f3 * 2 * 19 * f4; load f3 /* h1 */ u51mul %rbp, %r10, %r11, 16(%rsp) // (rax, rdx) = 19 * f3^2; load f2 /* Calculate f2 related * h4 */ leaq (%rax, %rax, 1), %rsi // 2 * f2 u51mul %rax, %rbx, %rcx, %rbp // (rax, rdx) = f2^2; load 19 * f3 /* h0 */ u51mul %rsi, %r8, %r9, %rsi // (rax, rdx) = 2 * f2 * 19 * f3; load 2 * f2 /* h1 */ mulq %rdi // (rax, rdx) = 2 * f2 * 19 * f4 addq %rax, %r10 adcq %rdx, %r11 /* Recovery register */ movq 24(%rsp), %rdi reduce /* Recovery register */ pop_stack ret .cfi_endproc .size Fp51Square,.-Fp51Square ############################################################# # void Fp51MulScalar(Fp51 *out, const Fp51 *in); ############################################################# .globl Fp51MulScalar .type Fp51MulScalar, @function .align 32 Fp51MulScalar: .cfi_startproc /* Save Register */ push_stack /*The input and output parameters are transferred by registers rdi, rsi, and rdx. * rdi: out; rsi: in; rdx: scalar; fp51 Is an array of [u64; 5] * Open stack, consistent with Fp51Mul */ /* h0 */ movl $121666, %eax mulq (%rsi) // f0 * 121666 movq %rax, %r8 movl $121666, %eax // Modify the rax immediately after the rax is vacated. movq %rdx, %r9 /* h1 */ mulq 8(%rsi) // f1 * 121666 movq %rax, %r10 movl $121666, %eax movq %rdx, %r11 /* h2 */ mulq 16(%rsi) // f2 * 121666 movq %rax, %r12 movl $121666, %eax movq %rdx, %r13 /* h3 */ mulq 24(%rsi) // f3 * 121666 movq %rax, %r14 movl $121666, %eax movq %rdx, %r15 /* h4 */ mulq 32(%rsi) // f4 * 121666 movq %rax, %rbx movq %rdx, %rcx reduce /* Recovery register */ pop_stack ret .cfi_endproc .size Fp51MulScalar,.-Fp51MulScalar /** * Fp64 reduce: * +------+-----+-----+-----+------+ * | | r15 | r14 | r13 | r12 | * | | | | | 38 | * +-------------------------------+ * | | | | r12'| r12' | * | | | r13'| r13'| | * | | r14'| r14'| | | * | r15' | r15'| | | | * +-------------------------------+ * | | r11'| r10'| r9' | r8' | * | | | | |19r15'| * +-------------------------------+ * | | r11 | r10 | r9 | r8 | * +------+-----+-----+-----+------+ */ .macro Fp64Reduce xorq %rsi, %rsi movq $38, %rdx mulx %r12, %rax, %rbx adcx %rax, %r8 adox %rbx, %r9 mulx %r13, %rax, %rbx adcx %rax, %r9 adox %rbx, %r10 mulx %r14, %rax, %rbx adcx %rax, %r10 adox %rbx, %r11 mulx %r15, %rax, %r12 adcx %rax, %r11 adcx %rsi, %r12 adox %rsi, %r12 shld $1, %r11, %r12 movq $0x7FFFFFFFFFFFFFFF, %rbp andq %rbp, %r11 imulq $19, %r12, %r12 addq %r12, %r8 adcx %rsi, %r9 adcx %rsi, %r10 adcx %rsi, %r11 movq 0(%rsp), %rdi movq %r9, 8(%rdi) movq %r10, 16(%rdi) movq %r11, 24(%rdi) movq %r8, 0(%rdi) .endm .globl Fp64Mul .type Fp64Mul,@function .align 32 Fp64Mul: .cfi_startproc pushq %rbp pushq %rbx pushq %r12 pushq %r13 pushq %r14 pushq %r15 pushq %rdi /** * (f3, f2, f1, f0) * (g3, g2, g1, g0) : * + + + + + + + + + * | | | | | A3 | A2 | A1 | A0 | * | | | | | B3 | B2 | B1 | B0 | * +------------------------------------------+ * | | | | | | |A0B0|A0B0| * | | | | | |A1B0|A1B0| | * | | | | |A2B0|A2B0| | | * | | | |A3B0|A3B0| | | | * | | | | | |A0B1|A0B1| | * | | | | |A1B1|A1B1| | | * | | | |A2B1|A2B1| | | | * | | |A3B1|A3B1| | | | | * | | | | |A2B0|A2B0| | | * | | | |A2B1|A2B1| | | | * | | |A2B2|A2B2| | | | | * | |A2B3|A2B3| | | | | | * | | | |A3B0|A3B0| | | | * | | |A3B1|A3B1| | | | | * | |A3B2|A3B2| | | | | | * |A3B3|A3B3| | | | | | | * +------------------------------------------+ * |r15 |r14 |r13 |r12 |r11 |r10 |r9 |r8 | * + + + + + + + + + */ movq 0(%rdx), %rcx movq 8(%rdx), %rbp movq 16(%rdx), %rdi movq 24(%rdx), %r15 movq 0(%rsi), %rdx xorq %r14, %r14 // (f3, f2, f1, f0) * g0 mulx %rcx, %r8, %rax mulx %rbp, %r9, %rbx adcx %rax, %r9 mulx %rdi, %r10, %rax adcx %rbx, %r10 mulx %r15, %r11, %r12 movq 8(%rsi), %rdx adcx %rax, %r11 adcx %r14, %r12 // (f3, f2, f1, f0) * g1 mulx %rcx, %rax, %rbx adcx %rax, %r9 adox %rbx, %r10 mulx %rbp, %rax, %rbx adcx %rax, %r10 adox %rbx, %r11 mulx %rdi, %rax, %rbx adcx %rax, %r11 adox %rbx, %r12 mulx %r15, %rax, %r13 movq 16(%rsi), %rdx adcx %rax, %r12 adox %r14, %r13 adcx %r14, %r13 // (f3, f2, f1, f0) * g2 mulx %rcx, %rax, %rbx adcx %rax, %r10 adox %rbx, %r11 mulx %rbp, %rax, %rbx adcx %rax, %r11 adox %rbx, %r12 mulx %rdi, %rax, %rbx adcx %rax, %r12 adox %rbx, %r13 mulx %r15, %rax, %r14 movq 24(%rsi), %rdx adcx %rax, %r13 movq $0, %rsi adox %rsi, %r14 adcx %rsi, %r14 // (f3, f2, f1, f0) * g3 mulx %rcx, %rax, %rbx adcx %rax, %r11 adox %rbx, %r12 mulx %rbp, %rax, %rbx adcx %rax, %r12 adox %rbx, %r13 mulx %rdi, %rax, %rbx adcx %rax, %r13 adox %rbx, %r14 mulx %r15, %rax, %r15 adcx %rax, %r14 adox %rsi, %r15 adcx %rsi, %r15 // reduce Fp64Reduce movq 8(%rsp), %r15 movq 16(%rsp), %r14 movq 24(%rsp), %r13 movq 32(%rsp), %r12 movq 40(%rsp), %rbx movq 48(%rsp), %rbp leaq 56(%rsp), %rsp ret .cfi_endproc .size Fp64Mul,.-Fp64Mul .globl Fp64Sqr .type Fp64Sqr,@function .align 32 Fp64Sqr: .cfi_startproc pushq %rbp pushq %rbx pushq %r12 pushq %r13 pushq %r14 pushq %r15 pushq %rdi /** * (f3, f2, f1, f0) ^ 2 : * +----+----+----+----+----+----+----+----+----+ * | | | | | | A3 | A2 | A1 | A0 | * | * | | | | | A3 | A2 | A1 | A0 | * +--------------------------------------------+ * | | | | | | |A0A1|A0A1| | * | | | | | |A0A2|A0A2| | | * | + | | | |A0A3|A0A3| | | | * | | | | |A1A2|A1A2| | | | * | | | |A1A3|A1A3| | | | | * | | |A2A3|A2A3| | | | | | * +--------------------------------------------+ * | *2 | |r14`|r13`|r12`|r11`|r10`|r9` | | * +--------------------------------------------+ * | |r15'|r14'|r13'|r12'|r11'|r10'|r9' | | * +--------------------------------------------+ * | | | | | | | |A0A0|A0A0| * | | | | | |A1A1|A1A1| | | * | + | | |A2A2|A2A2| | | | | * | |A3A3|A3A3| | | | | | | * +--------------------------------------------+ * | |r15 |r14 |r13 |r12 |r11 |r10 |r9 |r8 | * +--------------------------------------------+ */ movq 0(%rsi), %rbx // a0 movq 8(%rsi), %rcx // a1 movq 16(%rsi), %rbp // a2 movq 24(%rsi), %rdi // a3 xorq %r15, %r15 // (a1, a2, a3) * a0 movq %rbx, %rdx mulx %rcx, %r9, %rsi mulx %rbp, %r10, %rax adcx %rsi, %r10 mulx %rdi, %r11, %r12 movq %rcx, %rdx adcx %rax, %r11 adcx %r15, %r12 // (a2, a3) * a1 mulx %rbp, %rsi, %rax adcx %rsi, %r11 adox %rax, %r12 mulx %rdi, %rsi, %r13 movq %rbp, %rdx adcx %rsi, %r12 adcx %r15, %r13 adox %r15, %r13 // a3 * a2 mulx %rdi, %rsi, %r14 movq %rbx, %rdx adcx %rsi, %r13 adcx %r15, %r14 // (r9 --- r14) *2 shld $1, %r14, %r15 shld $1, %r13, %r14 shld $1, %r12, %r13 shld $1, %r11, %r12 shld $1, %r10, %r11 shld $1, %r9, %r10 shlq $1, %r9 xorq %r8, %r8 // clear cf flag // a0 * a0 mulx %rdx, %r8, %rax movq %rcx, %rdx adcx %rax, %r9 // a1 * a1 mulx %rdx, %rsi, %rax movq %rbp, %rdx adcx %rsi, %r10 adcx %rax, %r11 // a2 * a2 mulx %rdx, %rsi, %rax movq %rdi, %rdx adcx %rsi, %r12 adcx %rax, %r13 // a3 * a3 mulx %rdx, %rsi, %rax adcx %rsi, %r14 adcx %rax, %r15 // reduce Fp64Reduce movq 8(%rsp), %r15 movq 16(%rsp), %r14 movq 24(%rsp), %r13 movq 32(%rsp), %r12 movq 40(%rsp), %rbx movq 48(%rsp), %rbp leaq 56(%rsp), %rsp ret .cfi_endproc .size Fp64Sqr, .-Fp64Sqr .globl Fp64MulScalar .type Fp64MulScalar, @function .align 32 Fp64MulScalar: .cfi_startproc movl $121666, %edx mulx 0(%rsi), %r8, %rax mulx 8(%rsi), %r9, %rcx addq %rax, %r9 mulx 16(%rsi), %r10, %rax adcx %rcx, %r10 mulx 24(%rsi), %r11, %rcx adcx %rax, %r11 movl $0, %edx adcx %rdx, %rcx movq $0x7FFFFFFFFFFFFFFF, %rax shld $1, %r11, %rcx andq %rax, %r11 imulq $19, %rcx, %rcx addq %rcx, %r8 adcx %rdx, %r9 movq %r8, 0(%rdi) adcx %rdx, %r10 movq %r9, 8(%rdi) adcx %rdx, %r11 movq %r10, 16(%rdi) movq %r11, 24(%rdi) ret .cfi_endproc .size Fp64MulScalar, .-Fp64MulScalar .globl Fp64Add .type Fp64Add, @function .align 32 Fp64Add: .cfi_startproc movq 0(%rsi),%r8 movq 8(%rsi),%r9 addq 0(%rdx),%r8 adcx 8(%rdx),%r9 movq 16(%rsi),%r10 movq 24(%rsi),%r11 adcx 16(%rdx),%r10 adcx 24(%rdx),%r11 movq $0, %rax movq $38, %rcx cmovae %rax, %rcx addq %rcx, %r8 adcx %rax, %r9 adcx %rax, %r10 movq %r9, 8(%rdi) adcx %rax, %r11 movq %r10, 16(%rdi) movq %r11, 24(%rdi) cmovc %rcx, %rax addq %rax, %r8 movq %r8, 0(%rdi) ret .cfi_endproc .size Fp64Add, .-Fp64Add .globl Fp64Sub .type Fp64Sub,@function .align 32 Fp64Sub: .cfi_startproc movq 0(%rsi),%r8 movq 8(%rsi),%r9 subq 0(%rdx),%r8 sbbq 8(%rdx),%r9 movq 16(%rsi),%r10 movq 24(%rsi),%r11 sbbq 16(%rdx),%r10 sbbq 24(%rdx),%r11 movq $0, %rax movq $38, %rcx cmovae %rax, %rcx subq %rcx, %r8 sbbq %rax, %r9 sbbq %rax, %r10 movq %r9,8(%rdi) sbbq %rax, %r11 movq %r10,16(%rdi) cmovc %rcx, %rax movq %r11,24(%rdi) subq %rax, %r8 movq %r8,0(%rdi) ret .cfi_endproc .size Fp64Sub,.-Fp64Sub .globl Fp64PolyToData .type Fp64PolyToData,@function .align 32 Fp64PolyToData: .cfi_startproc movq 24(%rsi), %r11 movq 16(%rsi), %r10 xorq %rax, %rax leaq (%r11, %r11, 1), %rcx sarq $63, %r11 shrq $1, %rcx andq $19, %r11 addq $19, %r11 movq 0(%rsi), %r8 movq 8(%rsi), %r9 addq %r11, %r8 adcx %rax, %r9 adcx %rax, %r10 adcx %rax, %rcx leaq (%rcx, %rcx, 1), %r11 sarq $63, %rcx shrq $1, %r11 notq %rcx andq $19, %rcx subq %rcx, %r8 sbbq $0, %r9 movq %r8, 0(%rdi) movq %r9, 8(%rdi) sbbq $0, %r10 sbbq $0, %r11 movq %r10, 16(%rdi) movq %r11, 24(%rdi) ret .cfi_endproc .size Fp64PolyToData,.-Fp64PolyToData #endif
2302_82127028/openHiTLS-examples_1556
crypto/curve25519/src/asm/x25519_x86_64.S
Unix Assembly
unknown
25,769
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_X25519 #include "x25519_asm.h" #include "securec.h" #include "curve25519_local.h" #ifdef HITLS_CRYPTO_X25519_X8664 #include "crypt_utils.h" #endif // X25519 alternative implementation, faster but require asm #define CURVE25519_51BITS_MASK 0x7ffffffffffff #define CURVE25519_51BITS 51 static void Fp51DataToPoly(Fp51 *out, const uint8_t in[32]) { uint64_t h[5]; CURVE25519_BYTES7_LOAD(h, in); // load 7 bytes CURVE25519_BYTES6_LOAD(h + 1, in + 7); // load 6 bytes from in7 to h1 h[1] <<= 5; // shift 5 to fit 51 bits CURVE25519_BYTES7_LOAD(h + 2, in + 13); // load 7 bytes from in13 to h2 h[2] <<= 2; // shift 2 to fit 51 bits CURVE25519_BYTES6_LOAD(h + 3, in + 20); // load 6 bytes from in20 to h3 h[3] <<= 7; // shift 7 to fit 51 bits CURVE25519_BYTES6_LOAD(h + 4, in + 26); // load 6 bytes from in26 to h4 h[4] &= 0x7fffffffffff; // 41 bits mask = 0x7fffffffffff h[4] <<= 4; // shift 4 to fit 51 bits h[1] |= h[0] >> CURVE25519_51BITS; // carry h[0] -> h[1] h[0] &= CURVE25519_51BITS_MASK; // clear h[0] h[2] |= h[1] >> CURVE25519_51BITS; // carry h[1] -> h[2] h[1] &= CURVE25519_51BITS_MASK; // clear h[1] h[3] |= h[2] >> CURVE25519_51BITS; // carry h[2] -> h[3] h[2] &= CURVE25519_51BITS_MASK; // clear h[2] h[4] |= h[3] >> CURVE25519_51BITS; // carry h[3] -> h[4] h[3] &= CURVE25519_51BITS_MASK; // clear h[3] out->data[0] = h[0]; // 0 out->data[1] = h[1]; // 1 out->data[2] = h[2]; // 2 out->data[3] = h[3]; // 3 out->data[4] = h[4]; // 4 } static void Fp51UnloadTo8Bits(uint8_t out[32], uint64_t h[5]) { // load from uint64 to uint8, load 8 bits at a time out[0] = (uint8_t)h[0]; out[1] = (uint8_t)(h[0] >> 8); // load from position 8 to out[1] out[2] = (uint8_t)(h[0] >> 16); // load from position 16 to out[2] out[3] = (uint8_t)(h[0] >> 24); // load from position 24 to out[3] out[4] = (uint8_t)(h[0] >> 32); // load from position 32 to out[4] out[5] = (uint8_t)(h[0] >> 40); // load from position 40 to out[5] // load from position 48 from h[1] and (8-5)=3 bits from h[1] to out[6] out[6] = (uint8_t)((h[0] >> 48) | (uint8_t)(h[1] << 3)); out[7] = (uint8_t)(h[1] >> 5); // load h[1] from position 5 to out[7] out[8] = (uint8_t)(h[1] >> 13); // load h[1] from position 13 to out[8] out[9] = (uint8_t)(h[1] >> 21); // load h[1] from position 21 to out[9] out[10] = (uint8_t)(h[1] >> 29); // load h[1] from position 29 to out[10] out[11] = (uint8_t)(h[1] >> 37); // load h[1] from position 37 to out[11] // load from position 45 from h[1] and (8-2)=6 bits from h[2] to out[12] out[12] = (uint8_t)((h[1] >> 45) | (uint8_t)(h[2] << 6)); out[13] = (uint8_t)(h[2] >> 2); // load h[2] from position 2 to out[13] out[14] = (uint8_t)(h[2] >> 10); // load h[2] from position 10 to out[14] out[15] = (uint8_t)(h[2] >> 18); // load h[2] from position 18 to out[15] out[16] = (uint8_t)(h[2] >> 26); // load h[2] from position 26 to out[16] out[17] = (uint8_t)(h[2] >> 34); // load h[2] from position 34 to out[17] out[18] = (uint8_t)(h[2] >> 42); // load h[2] from position 42 to out[18] // load from position 50 from h[2] and (8-1)=7 bits from h[3] to out[19] out[19] = (uint8_t)((h[2] >> 50) | (uint8_t)(h[3] << 1)); out[20] = (uint8_t)(h[3] >> 7); // load h[3] from position 7 to out[20] out[21] = (uint8_t)(h[3] >> 15); // load h[3] from position 15 to out[21] out[22] = (uint8_t)(h[3] >> 23); // load h[3] from position 23 to out[22] out[23] = (uint8_t)(h[3] >> 31); // load h[3] from position 31 to out[23] out[24] = (uint8_t)(h[3] >> 39); // load h[3] from position 39 to out[24] // load from position 47 from h[3] and (4-4)=4 bits from h[4] to out[25] out[25] = (uint8_t)((h[3] >> 47) | (uint8_t)(h[4] << 4)); out[26] = (uint8_t)(h[4] >> 4); // load h[4] from position 4 to out[26] out[27] = (uint8_t)(h[4] >> 12); // load h[4] from position 12 to out[27] out[28] = (uint8_t)(h[4] >> 20); // load h[4] from position 20 to out[28] out[29] = (uint8_t)(h[4] >> 28); // load h[4] from position 28 to out[29] out[30] = (uint8_t)(h[4] >> 36); // load h[4] from position 36 to out[30] out[31] = (uint8_t)(h[4] >> 44); // load h[4] from position 44 to out[31] } static void Fp51PolyToData(const Fp51 *in, uint8_t out[32]) { uint64_t h[5]; h[0] = in->data[0]; // 0 h[1] = in->data[1]; // 1 h[2] = in->data[2]; // 2 h[3] = in->data[3]; // 3 h[4] = in->data[4]; // 4 uint64_t carry; carry = (h[0] + 19) >> CURVE25519_51BITS; // plus 19 then calculate carry carry = (h[1] + carry) >> CURVE25519_51BITS; // carry of h[1] carry = (h[2] + carry) >> CURVE25519_51BITS; // carry of h[2] carry = (h[3] + carry) >> CURVE25519_51BITS; // carry of h[3] carry = (h[4] + carry) >> CURVE25519_51BITS; // carry of h[4] h[0] += 19 * carry; // process carry h[4] -> h[0], h[0] += 19 * carry h[1] += h[0] >> CURVE25519_51BITS; // process carry h[0] -> h[1] h[0] &= CURVE25519_51BITS_MASK; // clear h[0] h[2] += h[1] >> CURVE25519_51BITS; // process carry h[1] -> h[2] h[1] &= CURVE25519_51BITS_MASK; // clear h[1] h[3] += h[2] >> CURVE25519_51BITS; // process carry h[2] -> h[3] h[2] &= CURVE25519_51BITS_MASK; // clear h[2] h[4] += h[3] >> CURVE25519_51BITS; // process carry h[3] -> h[4] h[3] &= CURVE25519_51BITS_MASK; // clear h[3] h[4] &= CURVE25519_51BITS_MASK; // clear h[4] Fp51UnloadTo8Bits(out, h); } /* out = in1 ^ (4 * 2 ^ (2 * times)) * in2 */ static inline void Fp51MultiSquare(Fp51 *in1, Fp51 *in2, Fp51 *out, int32_t times) { int32_t i; Fp51 temp1, temp2; Fp51Square(&temp1, in1); Fp51Square(&temp2, &temp1); for (i = 0; i < times; i++) { Fp51Square(&temp1, &temp2); Fp51Square(&temp2, &temp1); } Fp51Mul(out, in2, &temp2); } /* out = a ^ -1 */ static void Fp51Invert(Fp51 *out, const Fp51 *a) { Fp51 a0; /* save a^1 */ Fp51 a1; /* save a^2 */ Fp51 a2; /* save a^11 */ Fp51 a3; /* save a^(2^5-1) */ Fp51 a4; /* save a^(2^10-1) */ Fp51 a5; /* save a^(2^20-1) */ Fp51 a6; /* save a^(2^40-1) */ Fp51 a7; /* save a^(2^50-1) */ Fp51 a8; /* save a^(2^100-1) */ Fp51 a9; /* save a^(2^200-1) */ Fp51 a10; /* save a^(2^250-1) */ Fp51 temp1, temp2; /* We know a×b=1(mod p), then a and b are inverses of mod p, i.e. a=b^(-1), b=a^(-1); * According to Fermat's little theorem a^(p-1)=1(mod p), so a*a^(p-2)=1(mod p); * So the inverse element of a is a^(-1) = a^(p-2)(mod p) * Here it is, p=2^255-19, thus we need to compute a^(2^255-21)(mod(2^255-19)) */ /* a^1 */ CURVE25519_FP51_COPY(a0.data, a->data); /* a^2 */ Fp51Square(&a1, &a0); /* a^4 */ Fp51Square(&temp1, &a1); /* a^8 */ Fp51Square(&temp2, &temp1); /* a^9 */ Fp51Mul(&temp1, &a0, &temp2); /* a^11 */ Fp51Mul(&a2, &a1, &temp1); /* a^22 */ Fp51Square(&temp2, &a2); /* a^(2^5-1) = a^(9+22) */ Fp51Mul(&a3, &temp1, &temp2); /* a^(2^10-1) = a^(2^10-2^5) * a^(2^5-1) */ Fp51Square(&temp1, &a3); Fp51Square(&temp2, &temp1); Fp51Square(&temp1, &temp2); Fp51Square(&temp2, &temp1); Fp51Square(&temp1, &temp2); Fp51Mul(&a4, &a3, &temp1); /* a^(2^20-1) = a^(2^20-2^10) * a^(2^10-1) */ Fp51MultiSquare(&a4, &a4, &a5, 4); // (2 * 2) ^ 4 /* a^(2^40-1) = a^(2^40-2^20) * a^(2^20-1) */ Fp51MultiSquare(&a5, &a5, &a6, 9); // (2 * 2) ^ 9 /* a^(2^50-1) = a^(2^50-2^10) * a^(2^10-1) */ Fp51MultiSquare(&a6, &a4, &a7, 4); // (2 * 2) ^ 4 /* a^(2^100-1) = a^(2^100-2^50) * a^(2^50-1) */ Fp51MultiSquare(&a7, &a7, &a8, 24); // (2 * 2) ^ 24 /* a^(2^200-1) = a^(2^200-2^100) * a^(2^100-1) */ Fp51MultiSquare(&a8, &a8, &a9, 49); // (2 * 2) ^ 49 /* a^(2^250-1) = a^(2^250-2^50) * a^(2^50-1) */ Fp51MultiSquare(&a9, &a7, &a10, 24); // (2 * 2) ^ 24 /* a^(2^5*(2^250-1)) = (a^(2^250-1))^5 */ Fp51Square(&temp1, &a10); Fp51Square(&temp2, &temp1); Fp51Square(&temp1, &temp2); Fp51Square(&temp2, &temp1); Fp51Square(&temp1, &temp2); /* The output:a^(2^255-21) = a(2^5*(2^250-1)+11) = a^(2^5*(2^250-1)) * a^11 */ Fp51Mul(out, &a2, &temp1); } void Fp51ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32]) { uint8_t k[32]; const uint8_t *u = point; int32_t t; uint32_t swap; uint32_t kTemp; Fp51 x1, x2, x3; Fp51 z2, z3; Fp51 t1, t2; /* Decord the scalar into k */ CURVE25519_DECODE_LITTLE_ENDIAN(k, scalar); /* Reference RFC 7748 section 5:The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 */ Fp51DataToPoly(&x1, u); CURVE25519_FP51_SET(x2.data, 1); CURVE25519_FP51_SET(z2.data, 0); CURVE25519_FP51_COPY(x3.data, x1.data); CURVE25519_FP51_SET(z3.data, 1); swap = 0; /* "bits" parameter set to 255 for x25519 */ /* For t = bits-1(254) down to 0: */ for (t = 254; t >= 0; t--) { /* t >> 3: calculation the index of bit; t & 7: Obtains the corresponding bit in the byte */ kTemp = (k[(uint32_t)t >> 3] >> ((uint32_t)t & 7)) & 1; /* kTemp = (k >> t) & 1 */ swap ^= kTemp; /* swap ^= kTemp */ CURVE25519_FP51_CSWAP(swap, x2.data, x3.data); /* (x_2, x_3) = cswap(swap, x_2, x_3) */ CURVE25519_FP51_CSWAP(swap, z2.data, z3.data); /* (z_2, z_3) = cswap(swap, z_2, z_3) */ swap = kTemp; /* swap = kTemp */ CURVE25519_FP51_SUB(t1.data, x3.data, z3.data); /* x3 = D */ CURVE25519_FP51_SUB(t2.data, x2.data, z2.data); /* t2 = B */ CURVE25519_FP51_ADD(x2.data, x2.data, z2.data); /* t1 = A */ CURVE25519_FP51_ADD(z2.data, x3.data, z3.data); /* x2 = C */ Fp51Mul(&z3, &t1, &x2); Fp51Mul(&z2, &z2, &t2); Fp51Square(&t1, &t2); Fp51Square(&t2, &x2); CURVE25519_FP51_ADD(x3.data, z3.data, z2.data); CURVE25519_FP51_SUB(z2.data, z3.data, z2.data); Fp51Mul(&x2, &t2, &t1); CURVE25519_FP51_SUB(t2.data, t2.data, t1.data); Fp51Square(&z2, &z2); Fp51MulScalar(&z3, &t2); // z2 *= 121665 + 1 = 121666 Fp51Square(&x3, &x3); CURVE25519_FP51_ADD(t1.data, t1.data, z3.data); Fp51Mul(&z3, &x1, &z2); Fp51Mul(&z2, &t2, &t1); } CURVE25519_FP51_CSWAP(swap, x2.data, x3.data); CURVE25519_FP51_CSWAP(swap, z2.data, z3.data); /* Return x2 * (z2 ^ (p - 2)) */ Fp51Invert(&t1, &z2); Fp51Mul(&t2, &x2, &t1); Fp51PolyToData(&t2, out); (void)memset_s(k, sizeof(k), 0, sizeof(k)); } #ifdef HITLS_CRYPTO_X25519_X8664 #define CURVE25519_63BITS_MASK 0x7fffffffffffffff #define CURVE25519_FP64_SET(dst, value) \ do { \ (dst)[0] = (value); \ (dst)[1] = 0; \ (dst)[2] = 0; \ (dst)[3] = 0; \ } while (0) #define CURVE25519_FP64_COPY(dst, src) \ do { \ (dst)[0] = (src)[0]; \ (dst)[1] = (src)[1]; \ (dst)[2] = (src)[2]; \ (dst)[3] = (src)[3]; \ } while (0) #define CURVE25519_BYTES8_LOAD(dst, src) \ do { \ dst = (uint64_t)(src)[0]; \ dst |= ((uint64_t)(src)[1]) << 8; \ dst |= ((uint64_t)(src)[2]) << 16; \ dst |= ((uint64_t)(src)[3]) << 24; \ dst |= ((uint64_t)(src)[4]) << 32; \ dst |= ((uint64_t)(src)[5]) << 40; \ dst |= ((uint64_t)(src)[6]) << 48; \ dst |= ((uint64_t)(src)[7]) << 56; \ } while (0) #define CURVE25519_FP64_CSWAP(s, a, b) \ do { \ uint64_t tt; \ const uint64_t tsMacro = 0 - (uint64_t)(s); \ for (uint32_t ii = 0; ii < 4; ii++) { \ tt = tsMacro & ((a)[ii] ^ (b)[ii]); \ (a)[ii] = (a)[ii] ^ tt; \ (b)[ii] = (b)[ii] ^ tt; \ } \ } while (0) static void Fp64DataToPoly(Fp64 h, const uint8_t *point) { uint8_t *tmp = (uint8_t *)(uintptr_t)point; CURVE25519_BYTES8_LOAD(h[0], tmp); tmp += 8; // the second 8 bytes CURVE25519_BYTES8_LOAD(h[1], tmp); tmp += 8; // the third 8 bytes CURVE25519_BYTES8_LOAD(h[2], tmp); tmp += 8; // the forth 8 bytes CURVE25519_BYTES8_LOAD(h[3], tmp); h[3] &= CURVE25519_63BITS_MASK; return; } /* out = in1 ^ (4 * 2 ^ (2 * times)) * in2 */ static inline void Fp64MultiSqr(Fp64 in1, Fp64 in2, Fp64 out, int32_t times) { int32_t i; Fp64 temp1, temp2; Fp64Sqr(temp1, in1); Fp64Sqr(temp2, temp1); for (i = 0; i < times; i++) { Fp64Sqr(temp1, temp2); Fp64Sqr(temp2, temp1); } Fp64Mul(out, in2, temp2); } static void Fe64Invert(Fp64 out, const Fp64 z) { Fp64 t0; Fp64 t1; Fp64 t2; Fp64 t3; Fp64 t4; Fp64Sqr(t0, z); /* t^2 */ Fp64Sqr(t1, t0); /* t^4 */ Fp64Sqr(t1, t1); /* t^8 */ Fp64Mul(t1, z, t1); /* t^9 */ Fp64Mul(t0, t0, t1); /* t^11 */ Fp64Sqr(t2, t0); /* t^22 */ Fp64Mul(t1, t1, t2); /* t^(2^5-1) = t^(9+22) */ /* t^(2^10-1) = t^(2^10-2^5) * t^(2^5-1) */ Fp64Sqr(t2, t1); Fp64Sqr(t4, t2); Fp64Sqr(t2, t4); Fp64Sqr(t4, t2); Fp64Sqr(t2, t4); Fp64Mul(t1, t2, t1); /* t^(2^20-1) = t^(2^20-2^10) * t^(2^10-1) */ Fp64MultiSqr(t1, t1, t2, 4); /* t^(2^40-1) = t^(2^40-2^20) * t^(2^20-1) */ Fp64MultiSqr(t2, t2, t4, 9); // (2 * 2) ^ 9 /* t^(2^50-1) = t^(2^50-2^10) * t^(2^10-1) */ Fp64MultiSqr(t4, t1, t2, 4); // (2 * 2) ^ 4 /* t^(2^100-1) = t^(2^100-2^50) * t^(2^50-1) */ Fp64MultiSqr(t2, t2, t1, 24); // (2 * 2) ^ 24 /* t^(2^200-1) = t^(2^200-2^100) * t^(2^100-1) */ Fp64MultiSqr(t1, t1, t4, 49); // (2 * 2) ^ 49 /* t^(2^250-1) = t^(2^250-2^50) * t^(2^50-1) */ Fp64MultiSqr(t4, t2, t3, 24); // (2 * 2) ^ 24 /* t^(2^5*(2^250-1)) = (t^(2^250-1))^5 */ Fp64Sqr(t1, t3); Fp64Sqr(t2, t1); Fp64Sqr(t1, t2); Fp64Sqr(t2, t1); Fp64Sqr(t1, t2); /* The output:t^(2^255-21) = t(2^5*(2^250-1)+11) = t^(2^5*(2^250-1)) * t^11 */ Fp64Mul(out, t0, t1); } void Fp64ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32]) { uint8_t e[32]; uint32_t swap = 0; int32_t t; Fp64 x1, x2, x3; Fp64 z2, z3; Fp64 t1, t2; CURVE25519_DECODE_LITTLE_ENDIAN(e, scalar); Fp64DataToPoly(x1, point); CURVE25519_FP64_SET(x2, 1); CURVE25519_FP64_SET(z2, 0); CURVE25519_FP64_COPY(x3, x1); CURVE25519_FP64_SET(z3, 1); for (t = 254; t >= 0; --t) { /* For t = bits-1(254) down to 0: */ /* t >> 3: calculation the index of bit; t & 7: Obtains the corresponding bit in the byte */ uint32_t kTemp = (e[(uint32_t)t >> 3] >> ((uint32_t)t & 7)) & 1; swap ^= kTemp; CURVE25519_FP64_CSWAP(swap, x2, x3); CURVE25519_FP64_CSWAP(swap, z2, z3); swap = kTemp; Fp64Sub(t1, x3, z3); Fp64Sub(t2, x2, z2); Fp64Add(x2, x2, z2); Fp64Add(z2, x3, z3); Fp64Mul(z3, x2, t1); Fp64Mul(z2, z2, t2); Fp64Sqr(t1, t2); Fp64Sqr(t2, x2); Fp64Add(x3, z3, z2); Fp64Sub(z2, z3, z2); Fp64Mul(x2, t2, t1); Fp64Sub(t2, t2, t1); Fp64Sqr(z2, z2); Fp64MulScalar(z3, t2); Fp64Sqr(x3, x3); Fp64Add(t1, t1, z3); Fp64Mul(z3, x1, z2); Fp64Mul(z2, t2, t1); } Fe64Invert(z2, z2); Fp64Mul(x2, x2, z2); Fp64PolyToData(out, x2); (void)memset_s(e, sizeof(e), 0, sizeof(e)); } #endif void ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32]) { #if defined (__x86_64__) && defined (HITLS_CRYPTO_X25519_X8664) if (IsSupportBMI2() && IsSupportADX()) { Fp64ScalarMultiPoint(out, scalar, point); return; } #endif Fp51ScalarMultiPoint(out, scalar, point); return; } #endif /* HITLS_CRYPTO_X25519 */
2302_82127028/openHiTLS-examples_1556
crypto/curve25519/src/asm_curve25519_ops.c
C
unknown
17,901
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CURVE25519 #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_errno.h" #include "crypt_utils.h" #include "curve25519_local.h" #include "crypt_util_rand.h" #include "crypt_types.h" #include "eal_md_local.h" #ifdef HITLS_BSL_PARAMS #include "bsl_params.h" #include "crypt_params_key.h" #endif #ifdef HITLS_CRYPTO_X25519 CRYPT_CURVE25519_Ctx *CRYPT_X25519_NewCtx(void) { CRYPT_CURVE25519_Ctx *ctx = NULL; ctx = (CRYPT_CURVE25519_Ctx *)BSL_SAL_Malloc(sizeof(CRYPT_CURVE25519_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(ctx, sizeof(CRYPT_CURVE25519_Ctx), 0, sizeof(CRYPT_CURVE25519_Ctx)); ctx->keyType = CURVE25519_NOKEY; ctx->hashMethod = NULL; BSL_SAL_ReferencesInit(&(ctx->references)); return ctx; } CRYPT_CURVE25519_Ctx *CRYPT_X25519_NewCtxEx(void *libCtx) { CRYPT_CURVE25519_Ctx *ctx = CRYPT_X25519_NewCtx(); if (ctx == NULL) { return NULL; } ctx->libCtx = libCtx; return ctx; } #endif #ifdef HITLS_CRYPTO_ED25519 CRYPT_CURVE25519_Ctx *CRYPT_ED25519_NewCtx(void) { CRYPT_CURVE25519_Ctx *ctx = NULL; ctx = (CRYPT_CURVE25519_Ctx *)BSL_SAL_Malloc(sizeof(CRYPT_CURVE25519_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(ctx, sizeof(CRYPT_CURVE25519_Ctx), 0, sizeof(CRYPT_CURVE25519_Ctx)); ctx->hashMethod = EAL_MdFindDefaultMethod(CRYPT_MD_SHA512); if (ctx->hashMethod == NULL) { BSL_SAL_Free(ctx); BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID); return NULL; } ctx->keyType = CURVE25519_NOKEY; BSL_SAL_ReferencesInit(&(ctx->references)); return ctx; } CRYPT_CURVE25519_Ctx *CRYPT_ED25519_NewCtxEx(void *libCtx) { CRYPT_CURVE25519_Ctx *ctx = CRYPT_ED25519_NewCtx(); if (ctx == NULL) { return NULL; } ctx->libCtx = libCtx; return ctx; } #endif CRYPT_CURVE25519_Ctx *CRYPT_CURVE25519_DupCtx(CRYPT_CURVE25519_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return NULL; } CRYPT_CURVE25519_Ctx *newCtx = (CRYPT_CURVE25519_Ctx *)BSL_SAL_Malloc(sizeof(CRYPT_CURVE25519_Ctx)); if (newCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memcpy_s(newCtx, sizeof(CRYPT_CURVE25519_Ctx), ctx, sizeof(CRYPT_CURVE25519_Ctx)); BSL_SAL_ReferencesInit(&(newCtx->references)); return newCtx; } static int32_t CRYPT_CURVE25519_GetLen(CRYPT_CURVE25519_Ctx *ctx, GetLenFunc func, void *val, uint32_t len) { if (val == NULL || len != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } *(int32_t *)val = func(ctx); return CRYPT_SUCCESS; } static int32_t CRYPT_CURVE25519_GetKeyLen(const CRYPT_CURVE25519_Ctx *pkey) { (void)pkey; return CRYPT_CURVE25519_KEYLEN; } int32_t CRYPT_CURVE25519_Ctrl(CRYPT_CURVE25519_Ctx *pkey, int32_t opt, void *val, uint32_t len) { if (pkey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } switch (opt) { case CRYPT_CTRL_GET_BITS: return CRYPT_CURVE25519_GetLen(pkey, (GetLenFunc)CRYPT_CURVE25519_GetBits, val, len); #ifdef HITLS_CRYPTO_ED25519 case CRYPT_CTRL_GET_SIGNLEN: return CRYPT_CURVE25519_GetLen(pkey, (GetLenFunc)CRYPT_CURVE25519_GetSignLen, val, len); #endif case CRYPT_CTRL_GET_SECBITS: return CRYPT_CURVE25519_GetLen(pkey, (GetLenFunc)CRYPT_CURVE25519_GetSecBits, val, len); case CRYPT_CTRL_GET_PUBKEY_LEN: case CRYPT_CTRL_GET_PRVKEY_LEN: case CRYPT_CTRL_GET_SHARED_KEY_LEN: return GetUintCtrl(pkey, val, len, (GetUintCallBack)CRYPT_CURVE25519_GetKeyLen); case CRYPT_CTRL_UP_REFERENCES: if (val == NULL || len != (uint32_t)sizeof(int)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } return BSL_SAL_AtomicUpReferences(&(pkey->references), (int *)val); #ifdef HITLS_CRYPTO_X25519 case CRYPT_CTRL_GEN_X25519_PUBLICKEY: if ((pkey->keyType & CURVE25519_PUBKEY) != 0) { return CRYPT_SUCCESS; } if ((pkey->keyType & CURVE25519_PRVKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY); return CRYPT_CURVE25519_NO_PRVKEY; } CRYPT_X25519_PublicFromPrivate(pkey->prvKey, pkey->pubKey); pkey->keyType |= CURVE25519_PUBKEY; return CRYPT_SUCCESS; #endif default: break; } BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_UNSUPPORTED_CTRL_OPTION); return CRYPT_CURVE25519_UNSUPPORTED_CTRL_OPTION; } void CRYPT_CURVE25519_FreeCtx(CRYPT_CURVE25519_Ctx *pkey) { if (pkey == NULL) { return; } int ret = 0; BSL_SAL_AtomicDownReferences(&(pkey->references), &ret); if (ret > 0) { return; } BSL_SAL_ReferencesFree(&(pkey->references)); BSL_SAL_CleanseData((void *)(pkey), sizeof(CRYPT_CURVE25519_Ctx)); BSL_SAL_FREE(pkey); } #ifdef HITLS_BSL_PARAMS int32_t CRYPT_CURVE25519_SetPubKeyEx(CRYPT_CURVE25519_Ctx *pkey, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_Curve25519Pub pub = {0}; if (GetConstParamValue(para, CRYPT_PARAM_CURVE25519_PUBKEY, &pub.data, &pub.len) == NULL) { (void)GetConstParamValue(para, CRYPT_PARAM_PKEY_ENCODE_PUBKEY, (uint8_t **)&pub.data, &pub.len); } return CRYPT_CURVE25519_SetPubKey(pkey, &pub); } int32_t CRYPT_CURVE25519_SetPrvKeyEx(CRYPT_CURVE25519_Ctx *pkey, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_Curve25519Prv prv = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_CURVE25519_PRVKEY, &prv.data, &prv.len); return CRYPT_CURVE25519_SetPrvKey(pkey, &prv); } int32_t CRYPT_CURVE25519_GetPubKeyEx(const CRYPT_CURVE25519_Ctx *pkey, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_Curve25519Pub pub = {0}; BSL_Param *paramPub = GetParamValue(para, CRYPT_PARAM_CURVE25519_PUBKEY, &pub.data, &(pub.len)); if (paramPub == NULL) { paramPub = GetParamValue(para, CRYPT_PARAM_PKEY_ENCODE_PUBKEY, &pub.data, &(pub.len)); } int32_t ret = CRYPT_CURVE25519_GetPubKey(pkey, &pub); if (ret != CRYPT_SUCCESS) { return ret; } paramPub->useLen = pub.len; return CRYPT_SUCCESS; } int32_t CRYPT_CURVE25519_GetPrvKeyEx(const CRYPT_CURVE25519_Ctx *pkey, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_Curve25519Prv prv = {0}; BSL_Param *paramPrv = GetParamValue(para, CRYPT_PARAM_CURVE25519_PRVKEY, &prv.data, &(prv.len)); int32_t ret = CRYPT_CURVE25519_GetPrvKey(pkey, &prv); if (ret != CRYPT_SUCCESS) { return ret; } paramPrv->useLen = prv.len; return CRYPT_SUCCESS; } #endif int32_t CRYPT_CURVE25519_SetPubKey(CRYPT_CURVE25519_Ctx *pkey, const CRYPT_Curve25519Pub *pub) { if (pkey == NULL || pub == NULL || pub->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (pub->len != CRYPT_CURVE25519_KEYLEN) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEYLEN_ERROR); return CRYPT_CURVE25519_KEYLEN_ERROR; } /* The keyLen has been checked and does not have the overlong problem. The pkey memory is dynamically allocated and does not overlap with the pubkey memory. */ /* There is no failure case for memcpy_s. */ (void)memcpy_s(pkey->pubKey, CRYPT_CURVE25519_KEYLEN, pub->data, pub->len); pkey->keyType |= CURVE25519_PUBKEY; return CRYPT_SUCCESS; } int32_t CRYPT_CURVE25519_SetPrvKey(CRYPT_CURVE25519_Ctx *pkey, const CRYPT_Curve25519Prv *prv) { if (pkey == NULL || prv == NULL || prv->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (prv->len != CRYPT_CURVE25519_KEYLEN) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEYLEN_ERROR); return CRYPT_CURVE25519_KEYLEN_ERROR; } /* The keyLen has been checked and does not have the overlong problem. The pkey memory is dynamically allocated and does not overlap with the pubkey memory. */ /* There is no failure case for memcpy_s. */ (void)memcpy_s(pkey->prvKey, CRYPT_CURVE25519_KEYLEN, prv->data, prv->len); pkey->keyType |= CURVE25519_PRVKEY; return CRYPT_SUCCESS; } int32_t CRYPT_CURVE25519_GetPubKey(const CRYPT_CURVE25519_Ctx *pkey, CRYPT_Curve25519Pub *pub) { if (pkey == NULL || pub == NULL || pub->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (pub->len < CRYPT_CURVE25519_KEYLEN) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEYLEN_ERROR); return CRYPT_CURVE25519_KEYLEN_ERROR; } if ((pkey->keyType & CURVE25519_PUBKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PUBKEY); return CRYPT_CURVE25519_NO_PUBKEY; } /* The keyLen has been checked and does not have the overlong problem. The pkey memory is dynamically allocated and does not overlap with the pubkey memory. */ /* There is no failure case for memcpy_s. */ (void)memcpy_s(pub->data, pub->len, pkey->pubKey, CRYPT_CURVE25519_KEYLEN); pub->len = CRYPT_CURVE25519_KEYLEN; return CRYPT_SUCCESS; } int32_t CRYPT_CURVE25519_GetPrvKey(const CRYPT_CURVE25519_Ctx *pkey, CRYPT_Curve25519Prv *prv) { if (pkey == NULL || prv == NULL || prv->data == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (prv->len < CRYPT_CURVE25519_KEYLEN) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEYLEN_ERROR); return CRYPT_CURVE25519_KEYLEN_ERROR; } if ((pkey->keyType & CURVE25519_PRVKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY); return CRYPT_CURVE25519_NO_PRVKEY; } /* The keyLen has been checked and does not have the overlong problem. The pkey memory is dynamically allocated and does not overlap with the pubkey memory. */ /* There is no failure case for memcpy_s. */ (void)memcpy_s(prv->data, prv->len, pkey->prvKey, CRYPT_CURVE25519_KEYLEN); prv->len = CRYPT_CURVE25519_KEYLEN; return CRYPT_SUCCESS; } int32_t CRYPT_CURVE25519_GetBits(const CRYPT_CURVE25519_Ctx *pkey) { (void)pkey; return CRYPT_CURVE25519_KEYLEN * 8; // bits = 8 * bytes } #ifdef HITLS_CRYPTO_ED25519 static int32_t PrvKeyHash(const uint8_t *prvKey, uint32_t prvKeyLen, uint8_t *prvKeyHash, uint32_t prvHashLen, const EAL_MdMethod *hashMethod) { void *mdCtx = NULL; int32_t ret; uint32_t hashLen = prvHashLen; mdCtx = hashMethod->newCtx(NULL, hashMethod->id); if (mdCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ret = hashMethod->init(mdCtx, NULL); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = hashMethod->update(mdCtx, prvKey, prvKeyLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = hashMethod->final(mdCtx, prvKeyHash, &hashLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: hashMethod->freeCtx(mdCtx); return ret; } static int32_t GetRHash(uint8_t r[CRYPT_CURVE25519_SIGNLEN], const uint8_t prefix[CRYPT_CURVE25519_KEYLEN], const uint8_t *msg, uint32_t msgLen, const EAL_MdMethod *hashMethod) { void *mdCtx = NULL; int32_t ret; uint32_t hashLen = CRYPT_CURVE25519_SIGNLEN; mdCtx = hashMethod->newCtx(NULL, hashMethod->id); if (mdCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } ret = hashMethod->init(mdCtx, NULL); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = hashMethod->update(mdCtx, prefix, CRYPT_CURVE25519_KEYLEN); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = hashMethod->update(mdCtx, msg, msgLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = hashMethod->final(mdCtx, r, &hashLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: hashMethod->freeCtx(mdCtx); return ret; } static int32_t GetKHash(uint8_t k[CRYPT_CURVE25519_SIGNLEN], const uint8_t r[CRYPT_CURVE25519_KEYLEN], const uint8_t pubKey[CRYPT_CURVE25519_KEYLEN], const uint8_t *msg, uint32_t msgLen, const EAL_MdMethod *hashMethod) { void *mdCtx = NULL; uint32_t hashLen = CRYPT_CURVE25519_SIGNLEN; mdCtx = hashMethod->newCtx(NULL, hashMethod->id); if (mdCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = hashMethod->init(mdCtx, NULL); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = hashMethod->update(mdCtx, r, CRYPT_CURVE25519_KEYLEN); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = hashMethod->update(mdCtx, pubKey, CRYPT_CURVE25519_KEYLEN); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = hashMethod->update(mdCtx, msg, msgLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = hashMethod->final(mdCtx, k, &hashLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } EXIT: hashMethod->freeCtx(mdCtx); return ret; } static int32_t SignInputCheck(const CRYPT_CURVE25519_Ctx *pkey, const uint8_t *msg, uint32_t msgLen, const uint8_t *sign, const uint32_t *signLen) { if (pkey == NULL || (msg == NULL && msgLen != 0) || sign == NULL || signLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((pkey->keyType & CURVE25519_PRVKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY); return CRYPT_CURVE25519_NO_PRVKEY; } if (*signLen < CRYPT_CURVE25519_SIGNLEN) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_SIGNLEN_ERROR); return CRYPT_CURVE25519_SIGNLEN_ERROR; } if (pkey->hashMethod == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_HASH_METHOD); return CRYPT_CURVE25519_NO_HASH_METHOD; } return CRYPT_SUCCESS; } int32_t CRYPT_CURVE25519_Sign(CRYPT_CURVE25519_Ctx *pkey, int32_t algId, const uint8_t *msg, uint32_t msgLen, uint8_t *sign, uint32_t *signLen) { (void)algId; uint8_t prvKeyHash[CRYPT_CURVE25519_SIGNLEN]; uint8_t r[CRYPT_CURVE25519_SIGNLEN]; uint8_t k[CRYPT_CURVE25519_SIGNLEN]; uint8_t outSign[CRYPT_CURVE25519_SIGNLEN]; GeE geTmp; int32_t ret = SignInputCheck(pkey, msg, msgLen, sign, signLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = PrvKeyHash(pkey->prvKey, CRYPT_CURVE25519_KEYLEN, prvKeyHash, CRYPT_CURVE25519_SIGNLEN, pkey->hashMethod); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } prvKeyHash[0] &= 0xf8; // on block 31, clear the highest bit prvKeyHash[31] &= 0x7f; // on block 31, set second highest bit to 1 prvKeyHash[31] |= 0x40; // if ctx has no public key, generate public key and store it in ctx if ((pkey->keyType & CURVE25519_PUBKEY) == 0) { ScalarMultiBase(&geTmp, prvKeyHash); PointEncoding(&geTmp, pkey->pubKey, CRYPT_CURVE25519_KEYLEN); pkey->keyType |= CURVE25519_PUBKEY; } ret = GetRHash(r, prvKeyHash + CRYPT_CURVE25519_KEYLEN, msg, msgLen, pkey->hashMethod); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ModuloL(r); ScalarMultiBase(&geTmp, r); PointEncoding(&geTmp, outSign, CRYPT_CURVE25519_SIGNLEN); ret = GetKHash(k, outSign, pkey->pubKey, msg, msgLen, pkey->hashMethod); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ModuloL(k); ScalarMulAdd(outSign + CRYPT_CURVE25519_KEYLEN, k, prvKeyHash, r); // The value of *signLen has been checked in SignInputCheck to ensure that // the value is greater than or equal to CRYPT_CURVE25519_SIGNLEN. // The sign memory is input from outside the function. The outSign memory is allocated within the function. // Memory overlap does not exist. There is no failure case for memcpy_s. (void)memcpy_s(sign, *signLen, outSign, CRYPT_CURVE25519_SIGNLEN); *signLen = CRYPT_CURVE25519_SIGNLEN; EXIT: BSL_SAL_CleanseData(prvKeyHash, sizeof(prvKeyHash)); BSL_SAL_CleanseData(r, sizeof(r)); BSL_SAL_CleanseData(k, sizeof(k)); return ret; } int32_t CRYPT_CURVE25519_GetSignLen(const CRYPT_CURVE25519_Ctx *pkey) { (void)pkey; return CRYPT_CURVE25519_SIGNLEN; } static int32_t VerifyInputCheck(const CRYPT_CURVE25519_Ctx *pkey, const uint8_t *msg, uint32_t msgLen, const uint8_t *sign, uint32_t signLen) { if (pkey == NULL || (msg == NULL && msgLen != 0) || sign == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((pkey->keyType & CURVE25519_PUBKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PUBKEY); return CRYPT_CURVE25519_NO_PUBKEY; } if (signLen != CRYPT_CURVE25519_SIGNLEN) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_SIGNLEN_ERROR); return CRYPT_CURVE25519_SIGNLEN_ERROR; } if (pkey->hashMethod == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_HASH_METHOD); return CRYPT_CURVE25519_NO_HASH_METHOD; } return CRYPT_SUCCESS; } /* check 0 <= s < l, l = 2^252 + 27742317777372353535851937790883648493 */ static bool VerifyCheckSValid(const uint8_t s[CRYPT_CURVE25519_KEYLEN]) { const uint8_t l[CRYPT_CURVE25519_KEYLEN] = { 0xED, 0xD3, 0xF5, 0x5C, 0x1A, 0x63, 0x12, 0x58, 0xD6, 0x9C, 0xF7, 0xA2, 0xDE, 0xF9, 0xDE, 0x14, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x10 }; int32_t i; // start from highest block 31 for (i = 31; i >= 0; i--) { if (s[i] > l[i]) { return false; } else if (s[i] < l[i]) { return true; } } // s = l is invalid return false; } int32_t CRYPT_CURVE25519_Verify(const CRYPT_CURVE25519_Ctx *pkey, int32_t algId, const uint8_t *msg, uint32_t msgLen, const uint8_t *sign, uint32_t signLen) { if (algId != CRYPT_MD_SHA512) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_ALGID); return CRYPT_EAL_ERR_ALGID; } GeE geA, sG; uint8_t kHash[CRYPT_CURVE25519_SIGNLEN]; uint8_t localR[CRYPT_CURVE25519_KEYLEN]; const uint8_t *r = NULL; const uint8_t *s = NULL; int32_t ret = VerifyInputCheck(pkey, msg, msgLen, sign, signLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // r is first half of sign, length 32 r = sign; // s is second half of the sign, length 32 s = sign + 32; if (!VerifyCheckSValid(s)) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_VERIFY_FAIL); ret = CRYPT_CURVE25519_VERIFY_FAIL; return ret; } if (PointDecoding(&geA, pkey->pubKey) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_VERIFY_FAIL); ret = CRYPT_CURVE25519_INVALID_PUBKEY; return ret; } ret = GetKHash(kHash, r, pkey->pubKey, msg, msgLen, pkey->hashMethod); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } CURVE25519_FP_NEGATE(geA.x, geA.x); CURVE25519_FP_NEGATE(geA.t, geA.t); ModuloL(kHash); KAMulPlusMulBase(&sG, kHash, &geA, s); PointEncoding(&sG, localR, CRYPT_CURVE25519_KEYLEN); if (memcmp(localR, r, CRYPT_CURVE25519_KEYLEN) != 0) { ret = CRYPT_CURVE25519_VERIFY_FAIL; BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t CRYPT_ED25519_PublicFromPrivate(const uint8_t prvKey[CRYPT_CURVE25519_KEYLEN], uint8_t pubKey[CRYPT_CURVE25519_KEYLEN], const EAL_MdMethod *hashMethod) { GeE tmp; uint8_t prvKeyHash[CRYPT_CURVE25519_SIGNLEN]; int32_t ret = PrvKeyHash(prvKey, CRYPT_CURVE25519_KEYLEN, prvKeyHash, CRYPT_CURVE25519_SIGNLEN, hashMethod); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } prvKeyHash[0] &= 0xf8; // on block 31, clear the highest bit prvKeyHash[31] &= 0x7f; // on block 31, set second highest bit to 1 prvKeyHash[31] |= 0x40; ScalarMultiBase(&tmp, prvKeyHash); PointEncoding(&tmp, pubKey, CRYPT_CURVE25519_KEYLEN); BSL_SAL_CleanseData(prvKeyHash, sizeof(prvKeyHash)); return CRYPT_SUCCESS; } int32_t CRYPT_ED25519_GenKey(CRYPT_CURVE25519_Ctx *pkey) { if (pkey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } // SHA512 digest size is 64, no other hash has 64 md size if (pkey->hashMethod == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_HASH_METHOD); return CRYPT_CURVE25519_NO_HASH_METHOD; } int32_t ret; uint8_t prvKey[CRYPT_CURVE25519_KEYLEN]; ret = CRYPT_RandEx(pkey->libCtx, prvKey, sizeof(prvKey)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } ret = CRYPT_ED25519_PublicFromPrivate(prvKey, pkey->pubKey, pkey->hashMethod); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } // The pkey is not empty. The length of the prvKey is CRYPT_CURVE25519_KEYLEN, // which is the same as the length of local prvKey. // The pkey->prvKey memory is input outside the function. The local prvKey memory is allocated within the function. // Memory overlap does not exist. No failure case exists for memcpy_s. (void)memcpy_s(pkey->prvKey, CRYPT_CURVE25519_KEYLEN, prvKey, CRYPT_CURVE25519_KEYLEN); pkey->keyType = CURVE25519_PRVKEY | CURVE25519_PUBKEY; EXIT: BSL_SAL_CleanseData(prvKey, sizeof(prvKey)); return ret; } #endif /* HITLS_CRYPTO_ED25519 */ #ifdef HITLS_CRYPTO_X25519 /* Calculate the shared key based on the local private key and peer public key * Shared12 = prv1 * Pub2 = prv1 * (prv2 * G) = prv1 * prv2 * G */ int32_t CRYPT_CURVE25519_ComputeSharedKey(CRYPT_CURVE25519_Ctx *prvKey, CRYPT_CURVE25519_Ctx *pubKey, uint8_t *sharedKey, uint32_t *shareKeyLen) { if (prvKey == NULL || pubKey == NULL || sharedKey == NULL || shareKeyLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (*shareKeyLen < CRYPT_CURVE25519_KEYLEN) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEYLEN_ERROR); return CRYPT_CURVE25519_KEYLEN_ERROR; } if ((prvKey->keyType & CURVE25519_PRVKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY); return CRYPT_CURVE25519_NO_PRVKEY; } if ((pubKey->keyType & CURVE25519_PUBKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PUBKEY); return CRYPT_CURVE25519_NO_PUBKEY; } uint32_t tmpLen = *shareKeyLen; ScalarMultiPoint(sharedKey, prvKey->prvKey, pubKey->pubKey); int32_t i; uint8_t checkValid = 0; for (i = 0; i < CRYPT_CURVE25519_KEYLEN; i++) { checkValid |= sharedKey[i]; } if (checkValid == 0) { *shareKeyLen = tmpLen; BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_KEY_COMPUTE_FAILED); return CRYPT_CURVE25519_KEY_COMPUTE_FAILED; } else { *shareKeyLen = CRYPT_CURVE25519_KEYLEN; return CRYPT_SUCCESS; } } /** * @brief x25519 Calculate the public key based on the private key. * * @param privateKey [IN] Private key * @param publicKey [OUT] Public key * */ void CRYPT_X25519_PublicFromPrivate(const uint8_t privateKey[CRYPT_CURVE25519_KEYLEN], uint8_t publicKey[CRYPT_CURVE25519_KEYLEN]) { uint8_t privateCopy[CRYPT_CURVE25519_KEYLEN]; GeE out; Fp25 zPlusY, zMinusY, zMinusYInvert; (void)memcpy_s(privateCopy, sizeof(privateCopy), privateKey, sizeof(privateCopy)); privateCopy[0] &= 0xf8; /* decodeScalar25519(k): k_list[0] &= 0xf8 */ privateCopy[31] &= 0x7f; /* decodeScalar25519(k): k_list[31] &= 0x7f */ privateCopy[31] |= 0x40; /* decodeScalar25519(k): k_list[31] |= 0x40 */ ScalarMultiBase(&out, privateCopy); CURVE25519_FP_ADD(zPlusY, out.z, out.y); CURVE25519_FP_SUB(zMinusY, out.z, out.y); FpInvert(zMinusYInvert, zMinusY); FpMul(zPlusY, zPlusY, zMinusYInvert); PolynomialToData(publicKey, zPlusY); /* cleanup tmp private key */ BSL_SAL_CleanseData(privateCopy, sizeof(privateCopy)); } int32_t CRYPT_X25519_GenKey(CRYPT_CURVE25519_Ctx *pkey) { if (pkey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = CRYPT_RandEx(pkey->libCtx, pkey->prvKey, sizeof(pkey->prvKey)); if (ret != CRYPT_SUCCESS) { pkey->keyType = 0; BSL_ERR_PUSH_ERROR(ret); return ret; } CRYPT_X25519_PublicFromPrivate(pkey->prvKey, pkey->pubKey); pkey->keyType = CURVE25519_PRVKEY | CURVE25519_PUBKEY; return CRYPT_SUCCESS; } #endif /* HITLS_CRYPTO_X25519 */ int32_t CRYPT_CURVE25519_Cmp(const CRYPT_CURVE25519_Ctx *a, const CRYPT_CURVE25519_Ctx *b) { RETURN_RET_IF(a == NULL || b == NULL, CRYPT_NULL_INPUT); RETURN_RET_IF((a->keyType & CURVE25519_PUBKEY) == 0 || (b->keyType & CURVE25519_PUBKEY) == 0, CRYPT_CURVE25519_NO_PUBKEY); RETURN_RET_IF(memcmp(a->pubKey, b->pubKey, CRYPT_CURVE25519_KEYLEN) != 0, CRYPT_CURVE25519_PUBKEY_NOT_EQUAL); return CRYPT_SUCCESS; } int32_t CRYPT_CURVE25519_GetSecBits(const CRYPT_CURVE25519_Ctx *ctx) { (void) ctx; return 128; } #ifdef HITLS_CRYPTO_PROVIDER int32_t CRYPT_CURVE25519_Import(CRYPT_CURVE25519_Ctx *ctx, const BSL_Param *params) { if (ctx == NULL || params == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = CRYPT_SUCCESS; const BSL_Param *prv = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_CURVE25519_PRVKEY); const BSL_Param *pub = BSL_PARAM_FindConstParam(params, CRYPT_PARAM_CURVE25519_PUBKEY); if (prv != NULL) { ret = CRYPT_CURVE25519_SetPrvKeyEx(ctx, params); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } if (pub != NULL) { ret = CRYPT_CURVE25519_SetPubKeyEx(ctx, params); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } return ret; } int32_t CRYPT_CURVE25519_Export(const CRYPT_CURVE25519_Ctx *ctx, BSL_Param *params) { if (ctx == NULL || params == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } uint32_t index = 0; uint32_t keyBytes = CRYPT_CURVE25519_KEYLEN; CRYPT_EAL_ProcessFuncCb processCb = NULL; void *args = NULL; BSL_Param ed25519Params[3] = {0}; // 3: pub key + priv key + end marker int32_t ret = CRYPT_GetPkeyProcessParams(params, &processCb, &args); if (ret != CRYPT_SUCCESS) { return ret; } uint8_t *buffer = BSL_SAL_Calloc(1, keyBytes * 2); // For public + private key if (buffer == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } if ((ctx->keyType & CURVE25519_PUBKEY) != 0) { (void)BSL_PARAM_InitValue(&ed25519Params[index], CRYPT_PARAM_CURVE25519_PUBKEY, BSL_PARAM_TYPE_OCTETS, buffer, keyBytes); ret = CRYPT_CURVE25519_GetPubKeyEx(ctx, ed25519Params); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(buffer); return ret; } ed25519Params[index].valueLen = ed25519Params[index].useLen; index++; } if ((ctx->keyType & CURVE25519_PRVKEY) != 0) { (void)BSL_PARAM_InitValue(&ed25519Params[index], CRYPT_PARAM_CURVE25519_PRVKEY, BSL_PARAM_TYPE_OCTETS, buffer + keyBytes, keyBytes); ret = CRYPT_CURVE25519_GetPrvKeyEx(ctx, ed25519Params); if (ret != CRYPT_SUCCESS) { BSL_SAL_Free(buffer); return ret; } ed25519Params[index].valueLen = ed25519Params[index].useLen; index++; } ret = processCb(ed25519Params, args); BSL_SAL_Free(buffer); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } #endif // HITLS_CRYPTO_PROVIDER #if defined(HITLS_CRYPTO_X25519_CHECK) || defined(HITLS_CRYPTO_ED25519_CHECK) static int32_t Curve25519PrvKeyCheck(const CRYPT_CURVE25519_Ctx *prvKey) { if (prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((prvKey->keyType & CURVE25519_PRVKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY); return CRYPT_CURVE25519_NO_PRVKEY; } uint8_t tmp[CRYPT_CURVE25519_KEYLEN] = {0}; // prv key is not all 0. if (memcmp(tmp, prvKey->prvKey, CRYPT_CURVE25519_KEYLEN) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_INVALID_PRVKEY); return CRYPT_CURVE25519_INVALID_PRVKEY; } return CRYPT_SUCCESS; } #endif // HITLS_CRYPTO_X25519_CHECK || HITLS_CRYPTO_ED25519_CHECK #ifdef HITLS_CRYPTO_ED25519_CHECK static int32_t ED25519KeyPairCheck(const CRYPT_CURVE25519_Ctx *pubKey, const CRYPT_CURVE25519_Ctx *prvKey) { if (pubKey == NULL || prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((prvKey->keyType & CURVE25519_PRVKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY); return CRYPT_CURVE25519_NO_PRVKEY; } if ((pubKey->keyType & CURVE25519_PUBKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PUBKEY); return CRYPT_CURVE25519_NO_PUBKEY; } uint8_t res[CRYPT_CURVE25519_KEYLEN]; int32_t ret = CRYPT_ED25519_PublicFromPrivate(prvKey->prvKey, res, prvKey->hashMethod); if (ret != CRYPT_SUCCESS) { return ret; } if (memcmp(res, pubKey->pubKey, CRYPT_CURVE25519_KEYLEN) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_PAIRWISE_CHECK_FAIL); return CRYPT_CURVE25519_PAIRWISE_CHECK_FAIL; } return CRYPT_SUCCESS; } int32_t CRYPT_ED25519_Check(uint32_t checkType, const CRYPT_CURVE25519_Ctx *pkey1, const CRYPT_CURVE25519_Ctx *pkey2) { switch (checkType) { case CRYPT_PKEY_CHECK_KEYPAIR: return ED25519KeyPairCheck(pkey1, pkey2); case CRYPT_PKEY_CHECK_PRVKEY: return Curve25519PrvKeyCheck(pkey1); default: BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } } #endif // HITLS_CRYPTO_ED25519_CHECK #ifdef HITLS_CRYPTO_X25519_CHECK static int32_t X25519KeyPairCheck(const CRYPT_CURVE25519_Ctx *pubKey, const CRYPT_CURVE25519_Ctx *prvKey) { if (pubKey == NULL || prvKey == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if ((prvKey->keyType & CURVE25519_PRVKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PRVKEY); return CRYPT_CURVE25519_NO_PRVKEY; } if ((pubKey->keyType & CURVE25519_PUBKEY) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_NO_PUBKEY); return CRYPT_CURVE25519_NO_PUBKEY; } uint8_t res[CRYPT_CURVE25519_KEYLEN]; CRYPT_X25519_PublicFromPrivate(prvKey->prvKey, res); if (memcmp(res, pubKey->pubKey, CRYPT_CURVE25519_KEYLEN) != 0) { BSL_ERR_PUSH_ERROR(CRYPT_CURVE25519_PAIRWISE_CHECK_FAIL); return CRYPT_CURVE25519_PAIRWISE_CHECK_FAIL; } return CRYPT_SUCCESS; } int32_t CRYPT_X25519_Check(uint32_t checkType, const CRYPT_CURVE25519_Ctx *pkey1, const CRYPT_CURVE25519_Ctx *pkey2) { switch (checkType) { case CRYPT_PKEY_CHECK_KEYPAIR: return X25519KeyPairCheck(pkey1, pkey2); case CRYPT_PKEY_CHECK_PRVKEY: return Curve25519PrvKeyCheck(pkey1); default: BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } } #endif // HITLS_CRYPTO_X25519_CHECK #endif /* HITLS_CRYPTO_CURVE25519 */
2302_82127028/openHiTLS-examples_1556
crypto/curve25519/src/curve25519.c
C
unknown
33,267
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CURVE25519_LOCAL_H #define CURVE25519_LOCAL_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_CURVE25519 #include "crypt_curve25519.h" #include "sal_atomic.h" #ifdef __cplusplus extern "C" { #endif #define CURVE25519_NOKEY 0 #define CURVE25519_PRVKEY 0x1 #define CURVE25519_PUBKEY 0x10 #define UINT8_32_21BITS_BLOCKNUM 12 #define UINT8_64_21BITS_BLOCKNUM 24 struct CryptCurve25519Ctx { uint8_t keyType; /* specify the key type */ const EAL_MdMethod *hashMethod; uint8_t pubKey[CRYPT_CURVE25519_KEYLEN]; uint8_t prvKey[CRYPT_CURVE25519_KEYLEN]; BSL_SAL_RefCount references; void *libCtx; }; typedef int32_t Fp25[10]; typedef struct Fp51 { uint64_t data[5]; } Fp51; typedef struct H19 { int64_t data[19]; } H19; // group element in Projective Coordinate, x = X / Z, y = Y / Z typedef struct GeP { Fp25 x; Fp25 y; Fp25 z; } GeP; // group element in Extended Coordinate, x = X / Z, y = Y / Z, T = XY / Z which leads to XY = ZT typedef struct GeE { Fp25 x; Fp25 y; Fp25 t; Fp25 z; } GeE; // group element in Completed Coordinate, x = X / Z, y = Y / T typedef struct GeC { Fp25 x; Fp25 y; Fp25 t; Fp25 z; } GeC; typedef struct GePre { Fp25 yplusx; Fp25 yminusx; Fp25 xy2d; } GePre; typedef struct GeEPre { Fp25 yplusx; Fp25 yminusx; Fp25 t2z; Fp25 z; } GeEPre; /* Get High x bits for 64bits block */ #define MASK_HIGH64(x) (0xFFFFFFFFFFFFFFFFLL << (64 - (x))) /* Get low x bits for 32bits block */ #define MASK_LOW32(x) (0xFFFFFFFF >> (32 - (x))) /* Get high x bits for 32bits block */ #define MASK_HIGH32(x) (0xFFFFFFFF << (32 - (x))) /* low 21 bits for 64bits block */ #define MASK_64_LOW21 0x1fffffLL #define CURVE25519_MASK_HIGH_38 0xfffffffffc000000LL #define CURVE25519_MASK_HIGH_39 0xfffffffffe000000LL /* process carry from h0_ to h1_, h0_ boundary restrictions is bits */ #define PROCESS_CARRY(h0_, h1_, signMask_, over_, bits) \ do { \ (over_) = (h0_) + (1 << (bits)); \ (signMask_) = MASK_HIGH64((bits) + 1) & (-((over_) >> 63)); \ (h1_) += ((over_) >> ((bits) + 1)) | (signMask_); \ (h0_) -= MASK_HIGH64(64 - ((bits) + 1)) & (over_); \ } while (0) /* process carry from h0_ to h1_ ignoring sign, h0_ boundary restrictions is bits */ #define PROCESS_CARRY_UNSIGN(h0_, h1_, signMask_, over_, bits) \ do { \ (signMask_) = MASK_HIGH64((bits)) & (-((h0_) >> 63)); \ (over_) = ((h0_) >> (bits)) | (signMask_); \ (h1_) += (over_); \ (h0_) -= (over_) * (1 << (bits)); \ } while (0) /* l = 2^252 + 27742317777372353535851937790883648493, let l0 = 27742317777372353535851937790883648493 */ /* -l0 = 666643 * 2^0 + 470296 * 2^21 + 654183 * 2^(2*21) - 997805 * 2^(3*21) + 136657 * 2^(4*21) - 683901 * 2^(5*21) */ #define CURVE25519_MULTI_BY_L0(src, pos) \ do { \ (src)[0 + (pos)] += (src)[12 + (pos)] * 666643; \ (src)[1 + (pos)] += (src)[12 + (pos)] * 470296; \ (src)[2 + (pos)] += (src)[12 + (pos)] * 654183; \ (src)[3 + (pos)] -= (src)[12 + (pos)] * 997805; \ (src)[4 + (pos)] += (src)[12 + (pos)] * 136657; \ (src)[5 + (pos)] -= (src)[12 + (pos)] * 683901; \ (src)[12 + (pos)] = 0; \ } while (0) /* Compute multiplications by 19 */ #define CURVE25519_MULTI_BY_19(dst, src, t1_, t2_, t16_) \ do { \ (t1_) = (uint64_t)(src); \ (t2_) = (t1_) << 1; \ (t16_) = (t1_) << 4; \ (dst) += (int64_t)((t1_) + (t2_) + (t16_)); \ } while (0) /* Set this parameter to value, */ #define CURVE25519_FP_SET(dst, value) \ do { \ (dst)[0] = (value); \ (dst)[1] = 0; \ (dst)[2] = 0; \ (dst)[3] = 0; \ (dst)[4] = 0; \ (dst)[5] = 0; \ (dst)[6] = 0; \ (dst)[7] = 0; \ (dst)[8] = 0; \ (dst)[9] = 0; \ } while (0) #define CURVE25519_FP51_SET(dst, value) \ do { \ (dst)[0] = (value); \ (dst)[1] = 0; \ (dst)[2] = 0; \ (dst)[3] = 0; \ (dst)[4] = 0; \ } while (0) /* Copy */ #define CURVE25519_FP_COPY(dst, src) \ do { \ (dst)[0] = (src)[0]; \ (dst)[1] = (src)[1]; \ (dst)[2] = (src)[2]; \ (dst)[3] = (src)[3]; \ (dst)[4] = (src)[4]; \ (dst)[5] = (src)[5]; \ (dst)[6] = (src)[6]; \ (dst)[7] = (src)[7]; \ (dst)[8] = (src)[8]; \ (dst)[9] = (src)[9]; \ } while (0) #define CURVE25519_FP51_COPY(dst, src) \ do { \ (dst)[0] = (src)[0]; \ (dst)[1] = (src)[1]; \ (dst)[2] = (src)[2]; \ (dst)[3] = (src)[3]; \ (dst)[4] = (src)[4]; \ } while (0) /* Negate */ #define CURVE25519_FP_NEGATE(dst, src) \ do { \ (dst)[0] = -(src)[0]; \ (dst)[1] = -(src)[1]; \ (dst)[2] = -(src)[2]; \ (dst)[3] = -(src)[3]; \ (dst)[4] = -(src)[4]; \ (dst)[5] = -(src)[5]; \ (dst)[6] = -(src)[6]; \ (dst)[7] = -(src)[7]; \ (dst)[8] = -(src)[8]; \ (dst)[9] = -(src)[9]; \ } while (0) /* Basic operation */ #define CURVE25519_FP_OP(dst, src1, src2, op) \ do { \ (dst)[0] = (src1)[0] op (src2)[0]; \ (dst)[1] = (src1)[1] op (src2)[1]; \ (dst)[2] = (src1)[2] op (src2)[2]; \ (dst)[3] = (src1)[3] op (src2)[3]; \ (dst)[4] = (src1)[4] op (src2)[4]; \ (dst)[5] = (src1)[5] op (src2)[5]; \ (dst)[6] = (src1)[6] op (src2)[6]; \ (dst)[7] = (src1)[7] op (src2)[7]; \ (dst)[8] = (src1)[8] op (src2)[8]; \ (dst)[9] = (src1)[9] op (src2)[9]; \ } while (0) /* Basic operation */ #define CURVE25519_FP51_ADD(dst, src1, src2) \ do { \ (dst)[0] = (src1)[0] + (src2)[0]; \ (dst)[1] = (src1)[1] + (src2)[1]; \ (dst)[2] = (src1)[2] + (src2)[2]; \ (dst)[3] = (src1)[3] + (src2)[3]; \ (dst)[4] = (src1)[4] + (src2)[4]; \ } while (0) #define CURVE25519_FP51_SUB(dst, src1, src2) \ do { \ (dst)[0] = ((src1)[0] + 0xfffffffffffda) - (src2)[0]; \ (dst)[1] = ((src1)[1] + 0xffffffffffffe) - (src2)[1]; \ (dst)[2] = ((src1)[2] + 0xffffffffffffe) - (src2)[2]; \ (dst)[3] = ((src1)[3] + 0xffffffffffffe) - (src2)[3]; \ (dst)[4] = ((src1)[4] + 0xffffffffffffe) - (src2)[4]; \ } while (0) #define CURVE25519_GE_COPY(dst, src) \ do { \ CURVE25519_FP_COPY((dst).x, (src).x); \ CURVE25519_FP_COPY((dst).y, (src).y); \ CURVE25519_FP_COPY((dst).z, (src).z); \ CURVE25519_FP_COPY((dst).t, (src).t); \ } while (0) /* Add */ #define CURVE25519_FP_ADD(dst, src1, src2) CURVE25519_FP_OP(dst, src1, src2, +) /* Subtract */ #define CURVE25519_FP_SUB(dst, src1, src2) CURVE25519_FP_OP(dst, src1, src2, -) /* dst = dst * bit, bit = 0 or 1 */ #define CURVE25519_FP_MUL_BIT(dst, bit) \ do { \ int ii; \ for (ii = 0; ii < 10; ii++) { \ (dst)[ii] = (dst)[ii] * (bit); \ } \ } while (0) /* dst[i] = src[i] * scalar */ #define CURVE25519_FP_MUL_SCALAR(dst, src, scalar) \ do { \ uint32_t ii; \ for (ii = 0; ii < 10; ii++) { \ (dst)[ii] = (uint64_t)((src)[ii] * (scalar)); \ } \ } while (0) #define CURVE25519_BYTES3_LOAD_PADDING(dst, bits, src) \ do { \ uint64_t valMacro = ((uint64_t)*((src) + 0)) << 0; \ valMacro |= ((uint64_t)*((src) + 1)) << 8; \ valMacro |= ((uint64_t)*((src) + 2)) << 16; \ *(dst) = (uint64_t)(valMacro<< (bits)); \ } while (0) #define CURVE25519_BYTES3_LOAD(dst, src) \ do { \ *(dst) = ((uint64_t)*((src) + 0)) << 0; \ *(dst) |= ((uint64_t)*((src) + 1)) << 8; \ *(dst) |= ((uint64_t)*((src) + 2)) << 16; \ } while (0) #define CURVE25519_BYTES4_LOAD(dst, src) \ do { \ *(dst) = ((uint64_t)*((src) + 0)) << 0; \ *(dst) |= ((uint64_t)*((src) + 1)) << 8; \ *(dst) |= ((uint64_t)*((src) + 2)) << 16; \ *(dst) |= ((uint64_t)*((src) + 3)) << 24; \ } while (0) #define CURVE25519_BYTES6_LOAD(dst, src) \ do { \ *(dst) = (uint64_t)*(src); \ *(dst) |= ((uint64_t)*((src) + 1)) << 8; \ *(dst) |= ((uint64_t)*((src) + 2)) << 16; \ *(dst) |= ((uint64_t)*((src) + 3)) << 24; \ *(dst) |= ((uint64_t)*((src) + 4)) << 32; \ *(dst) |= ((uint64_t)*((src) + 5)) << 40; \ } while (0) #define CURVE25519_BYTES7_LOAD(dst, src) \ do { \ *(dst) = (uint64_t)*(src); \ *(dst) |= ((uint64_t)*((src) + 1)) << 8; \ *(dst) |= ((uint64_t)*((src) + 2)) << 16; \ *(dst) |= ((uint64_t)*((src) + 3)) << 24; \ *(dst) |= ((uint64_t)*((src) + 4)) << 32; \ *(dst) |= ((uint64_t)*((src) + 5)) << 40; \ *(dst) |= ((uint64_t)*((src) + 6)) << 48; \ } while (0) #define CURVE25519_BYTES3_PADDING_UNLOAD(dst, bits1, bits2, src) \ do { \ const uint32_t posMacro = 8 - (bits1); \ uint32_t valMacro = (uint32_t)(*(src)); \ uint32_t signMaskMacro= -(valMacro >> 31); \ uint32_t expand =( (uint32_t)(*((src) + 1))) << (bits2); \ *((dst) + 0) = (uint8_t)(valMacro >> (0 + posMacro) | (signMaskMacro>> (0 + posMacro))); \ *((dst) + 1) = (uint8_t)(valMacro >> (8 + posMacro) | (signMaskMacro>> (8 + posMacro))); \ *((dst) + 2) = (uint8_t)(expand | ((valMacro >> (16 + posMacro)) | (signMaskMacro>> (16 + posMacro)))); \ } while (0) #define CURVE25519_BYTES3_UNLOAD(dst, bits, src) \ do { \ const uint32_t posMacro = 8 - (bits); \ uint32_t valMacro = (uint32_t)(*(src)); \ uint32_t signMaskMacro= -(valMacro >> 31); \ *((dst) + 0) = (uint8_t)((valMacro >> (0 + posMacro)) | (signMaskMacro>> (0 + posMacro))); \ *((dst) + 1) = (uint8_t)((valMacro >> (8 + posMacro)) | (signMaskMacro>> (8 + posMacro))); \ *((dst) + 2) = (uint8_t)((valMacro >> (16 + posMacro)) | (signMaskMacro>> (16 + posMacro))); \ } while (0) #define CURVE25519_BYTES4_PADDING_UNLOAD(dst, bits, src) \ do { \ uint32_t valMacro = (uint32_t)(*(src)); \ uint32_t signMaskMacro= -(valMacro >> 31); \ uint32_t expand = ((uint32_t)(*((src) + 1))) << (bits); \ *((dst) + 0) = (uint8_t)((valMacro >> 0) | (signMaskMacro>> 0)); \ *((dst) + 1) = (uint8_t)((valMacro >> 8) | (signMaskMacro>> 8)); \ *((dst) + 2) = (uint8_t)((valMacro >> 16) | (signMaskMacro>> 16)); \ *((dst) + 3) = (uint8_t)(expand | ((valMacro >> 24) | (signMaskMacro>> 24))); \ } while (0) /** * Reference RFC 7748 section 5: For X25519, in order to decode 32 random bytes as an integer scalar, * set the three least significant bits of the first byte and the most significant bit of the last to zero, * set the second most significant bit of the last byte to 1 and, finally, decode as little-endian. */ #define CURVE25519_DECODE_LITTLE_ENDIAN(dst, src) \ do { \ uint32_t ii; \ for (ii = 0; ii < 32; ii++) { \ (dst)[ii] = (src)[ii]; \ } \ (dst)[0] &= 248; \ (dst)[31] &= 127; \ (dst)[31] |= 64; \ } while (0) #define CURVE25519_FP_CSWAP(s, a, b) \ do { \ uint32_t tt; \ const uint32_t tsMacro = 0 - (s); \ for (uint32_t ii = 0; ii < 10; ii++) { \ tt = tsMacro & (((uint32_t)(a)[ii]) ^ ((uint32_t)(b)[ii])); \ (a)[ii] = (int32_t)((uint32_t)(a)[ii] ^ tt); \ (b)[ii] = (int32_t)((uint32_t)(b)[ii] ^ tt); \ } \ } while (0) #define CURVE25519_FP51_CSWAP(s, a, b) \ do { \ uint64_t tt; \ const uint64_t tsMacro = 0 - (uint64_t)(s); \ for (uint32_t ii = 0; ii < 5; ii++) { \ tt = tsMacro & ((a)[ii] ^ (b)[ii]); \ (a)[ii] = (a)[ii] ^ tt; \ (b)[ii] = (b)[ii] ^ tt; \ } \ } while (0) void TableLookup(GePre *preCompute, int32_t pos, int8_t e); void ConditionalMove(GePre *preCompute, const GePre *tableElement, uint32_t indicator); void ScalarMultiBase(GeE *out, const uint8_t in[CRYPT_CURVE25519_KEYLEN]); #ifdef HITLS_CRYPTO_ED25519 void PointEncoding(const GeE *point, uint8_t *output, uint32_t outputLen); int32_t PointDecoding(GeE *point, const uint8_t in[CRYPT_CURVE25519_KEYLEN]); void ScalarMulAdd(uint8_t s[CRYPT_CURVE25519_KEYLEN], const uint8_t a[CRYPT_CURVE25519_KEYLEN], const uint8_t b[CRYPT_CURVE25519_KEYLEN], const uint8_t c[CRYPT_CURVE25519_KEYLEN]); void ModuloL(uint8_t s[CRYPT_CURVE25519_SIGNLEN]); void KAMulPlusMulBase(GeE *out, const uint8_t hash[CRYPT_CURVE25519_KEYLEN], const GeE *p, const uint8_t s[CRYPT_CURVE25519_KEYLEN]); #endif #ifdef HITLS_CRYPTO_X25519 void ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32]); #endif void FpInvert(Fp25 out, const Fp25 a); void FpMul(Fp25 out, const Fp25 f, const Fp25 g); void FpSquareDoubleCore(Fp25 out, const Fp25 in, bool doDouble); void PolynomialToData(uint8_t out[32], const Fp25 polynomial); void DataToPolynomial(Fp25 out, const uint8_t data[32]); #ifdef HITLS_CRYPTO_X25519 void CRYPT_X25519_PublicFromPrivate(const uint8_t privateKey[CRYPT_CURVE25519_KEYLEN], uint8_t publicKey[CRYPT_CURVE25519_KEYLEN]); #endif #ifdef __cplusplus } #endif #endif // HITLS_CRYPTO_CURVE25519 #endif // CURVE25519_LOCAL_H
2302_82127028/openHiTLS-examples_1556
crypto/curve25519/src/curve25519_local.h
C
unknown
18,563
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* Some of these codes are adapted from https://ed25519.cr.yp.to/software.html */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CURVE25519 #include <stdbool.h> #include "securec.h" #include "curve25519_local.h" #include "bsl_sal.h" #ifdef HITLS_CRYPTO_ED25519 #define CRYPT_CURVE25519_OPTLEN 32 #endif #define CONDITION_COPY(dst, src, indicate) \ (int32_t)((uint32_t)(dst) ^ (((uint32_t)(dst) ^ (uint32_t)(src)) & (indicate))) // process Fp multiplication carry #define FP_PROCESS_CARRY(h) \ do { \ int64_t carry0, carry1, carry2, carry3, carry4, carry5, carry6, carry7, carry8, carry9; \ carry0 = h##0 + (1 << 25); h##1 += carry0 >> 26; h##0 -= carry0 & CURVE25519_MASK_HIGH_38; \ carry4 = h##4 + (1 << 25); h##5 += carry4 >> 26; h##4 -= carry4 & CURVE25519_MASK_HIGH_38; \ carry1 = h##1 + (1 << 24); h##2 += carry1 >> 25; h##1 -= carry1 & CURVE25519_MASK_HIGH_39; \ carry5 = h##5 + (1 << 24); h##6 += carry5 >> 25; h##5 -= carry5 & CURVE25519_MASK_HIGH_39; \ carry2 = h##2 + (1 << 25); h##3 += carry2 >> 26; h##2 -= carry2 & CURVE25519_MASK_HIGH_38; \ carry6 = h##6 + (1 << 25); h##7 += carry6 >> 26; h##6 -= carry6 & CURVE25519_MASK_HIGH_38; \ carry3 = h##3 + (1 << 24); h##4 += carry3 >> 25; h##3 -= carry3 & CURVE25519_MASK_HIGH_39; \ carry7 = h##7 + (1 << 24); h##8 += carry7 >> 25; h##7 -= carry7 & CURVE25519_MASK_HIGH_39; \ carry4 = h##4 + (1 << 25); h##5 += carry4 >> 26; h##4 -= carry4 & CURVE25519_MASK_HIGH_38; \ carry8 = h##8 + (1 << 25); h##9 += carry8 >> 26; h##8 -= carry8 & CURVE25519_MASK_HIGH_38; \ carry9 = h##9 + (1 << 24); h##0 += (carry9 >> 25) * 19; h##9 -= carry9 & CURVE25519_MASK_HIGH_39; \ carry0 = h##0 + (1 << 25); h##1 += carry0 >> 26; h##0 -= carry0 & CURVE25519_MASK_HIGH_38; \ } while (0) // h0...h9 to Fp25 #define INT64_2_FP25(h, out) \ do { \ (out)[0] = (int32_t)h##0; \ (out)[1] = (int32_t)h##1; \ (out)[2] = (int32_t)h##2; \ (out)[3] = (int32_t)h##3; \ (out)[4] = (int32_t)h##4; \ (out)[5] = (int32_t)h##5; \ (out)[6] = (int32_t)h##6; \ (out)[7] = (int32_t)h##7; \ (out)[8] = (int32_t)h##8; \ (out)[9] = (int32_t)h##9; \ } while (0) #define FP25_2_INT32(in, out) \ do { \ out##0 = (in)[0]; \ out##1 = (in)[1]; \ out##2 = (in)[2]; \ out##3 = (in)[3]; \ out##4 = (in)[4]; \ out##5 = (in)[5]; \ out##6 = (in)[6]; \ out##7 = (in)[7]; \ out##8 = (in)[8]; \ out##9 = (in)[9]; \ } while (0) /* out = f * g */ void FpMul(Fp25 out, const Fp25 f, const Fp25 g) { int32_t f0, f1, f2, f3, f4, f5, f6, f7, f8, f9; int32_t g0, g1, g2, g3, g4, g5, g6, g7, g8, g9; int64_t h0, h1, h2, h3, h4, h5, h6, h7, h8, h9; FP25_2_INT32(f, f); FP25_2_INT32(g, g); int32_t f1_2 = f1 * 2; int32_t f3_2 = f3 * 2; int32_t f5_2 = f5 * 2; int32_t f7_2 = f7 * 2; int32_t f9_2 = f9 * 2; int32_t g1_19 = g1 * 19; int32_t g2_19 = g2 * 19; int32_t g3_19 = g3 * 19; int32_t g4_19 = g4 * 19; int32_t g5_19 = g5 * 19; int32_t g6_19 = g6 * 19; int32_t g7_19 = g7 * 19; int32_t g8_19 = g8 * 19; int32_t g9_19 = g9 * 19; /* h0 = f0g0 + 38f1g9 + 19f2g8 + 38f3g7 + 19f4g6 + 38f5g5 + 19f6g4 + 38f7g3 + 19f8g2 + 38f9g1 h1 = f0g1 + f1g0 + 19f2g9 + 19f3g8 + 19f4g7 + 19f5g6 + 19f6g5 + 19f7g4 + 19f8g3 + 19f9g2 h2 = f0g2 + 2f1g1 + f2g0 + 38f3g9 + 19f4g8 + 38f5g7 + 19f6g6 + 38f7g5 + 19f8g4 + 38f9g2 h3 = f0g3 + f1g2 + f2g1 + f3g0 + 19f4g9 + 19f5g8 + 19f6g7 + 19f7g6 + 19f8g5 + 19f9g4 h4 = f0g4 + 2f1g3 + f2g2 + 2f3g1 + f4g0 + 38f5g9 + 19f6g8 + 38f7g7 + 19f8g6 + 38f9g5 h5 = f0g5 + f1g4 + f2g3 + f3g2 + f4g1 + f5g0 + 19f6g9 + 19f7g8 + 19f8g7 + 19f9g6 h6 = f0g6 + 2f1g5 + f2g4 + 2f3g3 + f4g2 + 2f5g1 + f6g0 + 38f7g9 + 19f8g8 + 38f9g7 h7 = f0g7 + f1g6 + f2g5 + f3g4 + f4g3 + f5g2 + f6g1 + f7g0 + 19f8g9 + 19f9g8 h8 = f0g8 + 2f1g7 + f2g6 + 2f3g5 + f4g4 + 2f5g3 + f6g2 + 2f7g1 + f8g0 + 38f9g9 h9 = f0g9 + f1g8 + f2g7 + f3g6 + f4g5 + f5g4 + f6g3 + f7g2 + f8g1 + f9g0 The calculation is performed by column. */ h0 = (int64_t)f0 * g0; h1 = (int64_t)f0 * g1; h2 = (int64_t)f0 * g2; h3 = (int64_t)f0 * g3; h4 = (int64_t)f0 * g4; h5 = (int64_t)f0 * g5; h6 = (int64_t)f0 * g6; h7 = (int64_t)f0 * g7; h8 = (int64_t)f0 * g8; h9 = (int64_t)f0 * g9; h0 += (int64_t)f1_2 * g9_19; h1 += (int64_t)f1 * g0; h2 += (int64_t)f1_2 * g1; h3 += (int64_t)f1 * g2; h4 += (int64_t)f1_2 * g3; h5 += (int64_t)f1 * g4; h6 += (int64_t)f1_2 * g5; h7 += (int64_t)f1 * g6; h8 += (int64_t)f1_2 * g7; h9 += (int64_t)f1 * g8; h0 += (int64_t)f2 * g8_19; h1 += (int64_t)f2 * g9_19; h2 += (int64_t)f2 * g0; h3 += (int64_t)f2 * g1; h4 += (int64_t)f2 * g2; h5 += (int64_t)f2 * g3; h6 += (int64_t)f2 * g4; h7 += (int64_t)f2 * g5; h8 += (int64_t)f2 * g6; h9 += (int64_t)f2 * g7; h0 += (int64_t)f3_2 * g7_19; h1 += (int64_t)f3 * g8_19; h2 += (int64_t)f3_2 * g9_19; h3 += (int64_t)f3 * g0; h4 += (int64_t)f3_2 * g1; h5 += (int64_t)f3 * g2; h6 += (int64_t)f3_2 * g3; h7 += (int64_t)f3 * g4; h8 += (int64_t)f3_2 * g5; h9 += (int64_t)f3 * g6; h0 += (int64_t)f4 * g6_19; h1 += (int64_t)f4 * g7_19; h2 += (int64_t)f4 * g8_19; h3 += (int64_t)f4 * g9_19; h4 += (int64_t)f4 * g0; h5 += (int64_t)f4 * g1; h6 += (int64_t)f4 * g2; h7 += (int64_t)f4 * g3; h8 += (int64_t)f4 * g4; h9 += (int64_t)f4 * g5; h0 += (int64_t)f5_2 * g5_19; h1 += (int64_t)f5 * g6_19; h2 += (int64_t)f5_2 * g7_19; h3 += (int64_t)f5 * g8_19; h4 += (int64_t)f5_2 * g9_19; h5 += (int64_t)f5 * g0; h6 += (int64_t)f5_2 * g1; h7 += (int64_t)f5 * g2; h8 += (int64_t)f5_2 * g3; h9 += (int64_t)f5 * g4; h0 += (int64_t)f6 * g4_19; h1 += (int64_t)f6 * g5_19; h2 += (int64_t)f6 * g6_19; h3 += (int64_t)f6 * g7_19; h4 += (int64_t)f6 * g8_19; h5 += (int64_t)f6 * g9_19; h6 += (int64_t)f6 * g0; h7 += (int64_t)f6 * g1; h8 += (int64_t)f6 * g2; h9 += (int64_t)f6 * g3; h0 += (int64_t)f7_2 * g3_19; h1 += (int64_t)f7 * g4_19; h2 += (int64_t)f7_2 * g5_19; h3 += (int64_t)f7 * g6_19; h4 += (int64_t)f7_2 * g7_19; h5 += (int64_t)f7 * g8_19; h6 += (int64_t)f7_2 * g9_19; h7 += (int64_t)f7 * g0; h8 += (int64_t)f7_2 * g1; h9 += (int64_t)f7 * g2; h0 += (int64_t)f8 * g2_19; h1 += (int64_t)f8 * g3_19; h2 += (int64_t)f8 * g4_19; h3 += (int64_t)f8 * g5_19; h4 += (int64_t)f8 * g6_19; h5 += (int64_t)f8 * g7_19; h6 += (int64_t)f8 * g8_19; h7 += (int64_t)f8 * g9_19; h8 += (int64_t)f8 * g0; h9 += (int64_t)f8 * g1; h0 += (int64_t)f9_2 * g1_19; h1 += (int64_t)f9 * g2_19; h2 += (int64_t)f9_2 * g3_19; h3 += (int64_t)f9 * g4_19; h4 += (int64_t)f9_2 * g5_19; h5 += (int64_t)f9 * g6_19; h6 += (int64_t)f9_2 * g7_19; h7 += (int64_t)f9 * g8_19; h8 += (int64_t)f9_2 * g9_19; h9 += (int64_t)f9 * g0; FP_PROCESS_CARRY(h); INT64_2_FP25(h, out); } void FpSquareDoubleCore(Fp25 out, const Fp25 in, bool doDouble) { int64_t h0, h1, h2, h3, h4, h5, h6, h7, h8, h9; int32_t f0, f1, f2, f3, f4, f5, f6, f7, f8, f9; FP25_2_INT32(in, f); int32_t f0_2 = f0 * 2; int32_t f1_2 = f1 * 2; int32_t f2_2 = f2 * 2; int32_t f3_2 = f3 * 2; int32_t f4_2 = f4 * 2; int32_t f5_2 = f5 * 2; int32_t f6_2 = f6 * 2; int32_t f7_2 = f7 * 2; int32_t f9_38 = f9 * 38; int32_t f8_19 = f8 * 19; int32_t f7_38 = f7 * 38; int32_t f6_19 = f6 * 19; int32_t f5_19 = f5 * 19; h0 = (int64_t)f0 * f0; h1 = (int64_t)f0_2 * f1; h2 = (int64_t)f0_2 * f2; h3 = (int64_t)f0_2 * f3; h4 = (int64_t)f0_2 * f4; h5 = (int64_t)f0_2 * f5; h6 = (int64_t)f0_2 * f6; h7 = (int64_t)f0_2 * f7; h8 = (int64_t)f0_2 * f8; h9 = (int64_t)f0_2 * f9; h0 += (int64_t)f1_2 * f9_38; h1 += (int64_t)f2 * f9_38; h2 += (int64_t)f1_2 * f1; h3 += (int64_t)f1_2 * f2; h4 += (int64_t)f1_2 * f3_2; h5 += (int64_t)f1_2 * f4; h6 += (int64_t)f1_2 * f5_2; h7 += (int64_t)f1_2 * f6; h8 += (int64_t)f1_2 * f7_2; h9 += (int64_t)f1_2 * f8; h0 += (int64_t)f2_2 * f8_19; h1 += (int64_t)f3_2 * f8_19; h2 += (int64_t)f3_2 * f9_38; h3 += (int64_t)f4 * f9_38; h4 += (int64_t)f2 * f2; h5 += (int64_t)f2_2 * f3; h6 += (int64_t)f2_2 * f4; h7 += (int64_t)f2_2 * f5; h8 += (int64_t)f2_2 * f6; h9 += (int64_t)f2_2 * f7; h0 += (int64_t)f3_2 * f7_38; h1 += (int64_t)f4 * f7_38; h2 += (int64_t)f4_2 * f8_19; h3 += (int64_t)f5_2 * f8_19; h4 += (int64_t)f5_2 * f9_38; h5 += (int64_t)f6 * f9_38; h6 += (int64_t)f3_2 * f3; h7 += (int64_t)f3_2 * f4; h8 += (int64_t)f3_2 * f5_2; h9 += (int64_t)f3_2 * f6; h0 += (int64_t)f4_2 * f6_19; h1 += (int64_t)f5_2 * f6_19; h2 += (int64_t)f5_2 * f7_38; h3 += (int64_t)f6 * f7_38; h4 += (int64_t)f6_2 * f8_19; h5 += (int64_t)f7_2 * f8_19; h6 += (int64_t)f7_2 * f9_38; h7 += (int64_t)f8 * f9_38; h8 += (int64_t)f4 * f4; h9 += (int64_t)f4_2 * f5; h0 += (int64_t)f5_2 * f5_19; h2 += (int64_t)f6 * f6_19; h4 += (int64_t)f7 * f7_38; h6 += (int64_t)f8 * f8_19; h8 += (int64_t)f9 * f9_38; if (doDouble) { h0 *= 2; h1 *= 2; h2 *= 2; h3 *= 2; h4 *= 2; h5 *= 2; h6 *= 2; h7 *= 2; h8 *= 2; h9 *= 2; } FP_PROCESS_CARRY(h); INT64_2_FP25(h, out); } /* out = in1 ^ (4 * 2 ^ (2 * times)) * in2 */ static void FpMultiSquare(Fp25 in1, Fp25 in2, Fp25 out, int32_t times) { int32_t i; Fp25 temp1, temp2; FpSquareDoubleCore(temp1, in1, false); FpSquareDoubleCore(temp2, temp1, false); for (i = 0; i < times; i++) { FpSquareDoubleCore(temp1, temp2, false); FpSquareDoubleCore(temp2, temp1, false); } FpMul(out, in2, temp2); } /* out = a ^ -1 */ void FpInvert(Fp25 out, const Fp25 a) { int32_t i; Fp25 a0; /* save a^1 */ Fp25 a1; /* save a^2 */ Fp25 a2; /* save a^11 */ Fp25 a3; /* save a^(2^5-1) */ Fp25 a4; /* save a^(2^10-1) */ Fp25 a5; /* save a^(2^20-1) */ Fp25 a6; /* save a^(2^40-1) */ Fp25 a7; /* save a^(2^50-1) */ Fp25 a8; /* save a^(2^100-1) */ Fp25 a9; /* save a^(2^200-1) */ Fp25 a10; /* save a^(2^250-1) */ Fp25 temp1, temp2; /* We know a×b=1(mod p), then a and b are inverses of mod p, i.e. a=b^(-1), b=a^(-1); * According to Fermat's little theorem a^(p-1)=1(mod p), so a*a^(p-2)=1(mod p); * So the inverse element of a is a^(-1) = a^(p-2)(mod p) * Here it is, p=2^255-19, thus we need to compute a^(2^255-21)(mod(2^255-19)) */ /* a^1 */ CURVE25519_FP_COPY(a0, a); /* a^2 */ FpSquareDoubleCore(a1, a0, false); /* a^4 */ FpSquareDoubleCore(temp1, a1, false); /* a^8 */ FpSquareDoubleCore(temp2, temp1, false); /* a^9 */ FpMul(temp1, a0, temp2); /* a^11 */ FpMul(a2, a1, temp1); /* a^22 */ FpSquareDoubleCore(temp2, a2, false); /* a^(2^5-1) = a^(9+22) */ FpMul(a3, temp1, temp2); /* a^(2^10-1) = a^(2^10-2^5) * a^(2^5-1) */ FpSquareDoubleCore(temp1, a3, false); for (i = 0; i < 2; i++) { // (2 * 2)^2 FpSquareDoubleCore(temp2, temp1, false); FpSquareDoubleCore(temp1, temp2, false); } FpMul(a4, a3, temp1); /* a^(2^20-1) = a^(2^20-2^10) * a^(2^10-1) */ FpMultiSquare(a4, a4, a5, 4); // (2 * 2) ^ 4 /* a^(2^40-1) = a^(2^40-2^20) * a^(2^20-1) */ FpMultiSquare(a5, a5, a6, 9); // (2 * 2) ^ 9 /* a^(2^50-1) = a^(2^50-2^10) * a^(2^10-1) */ FpMultiSquare(a6, a4, a7, 4); // (2 * 2) ^ 4 /* a^(2^100-1) = a^(2^100-2^50) * a^(2^50-1) */ FpMultiSquare(a7, a7, a8, 24); // (2 * 2) ^ 24 /* a^(2^200-1) = a^(2^200-2^100) * a^(2^100-1) */ FpMultiSquare(a8, a8, a9, 49); // (2 * 2) ^ 49 /* a^(2^250-1) = a^(2^250-2^50) * a^(2^50-1) */ FpMultiSquare(a9, a7, a10, 24); // (2 * 2) ^ 24 /* a^(2^5*(2^250-1)) = (a^(2^250-1))^5 */ FpSquareDoubleCore(temp1, a10, false); FpSquareDoubleCore(temp2, temp1, false); FpSquareDoubleCore(temp1, temp2, false); FpSquareDoubleCore(temp2, temp1, false); FpSquareDoubleCore(temp1, temp2, false); /* The output:a^(2^255-21) = a(2^5*(2^250-1)+11) = a^(2^5*(2^250-1)) * a^11 */ FpMul(out, a2, temp1); } #ifdef HITLS_CRYPTO_ED25519 /* out = in ^ ((q - 5) / 8) */ static void FpPowq58(Fp25 out, Fp25 in) { Fp25 a, b, c; int32_t i; FpSquareDoubleCore(a, in, false); FpSquareDoubleCore(b, a, false); FpSquareDoubleCore(b, b, false); FpMul(b, in, b); FpMul(a, a, b); FpSquareDoubleCore(a, a, false); FpMul(a, b, a); FpSquareDoubleCore(b, a, false); // b = a ^ (2^5) for (i = 1; i < 5; i++) { FpSquareDoubleCore(b, b, false); } FpMul(a, b, a); FpSquareDoubleCore(b, a, false); // b = a ^ (2^10) for (i = 1; i < 10; i++) { FpSquareDoubleCore(b, b, false); } FpMul(b, b, a); FpSquareDoubleCore(c, b, false); // c = b ^ (2^20) for (i = 1; i < 20; i++) { FpSquareDoubleCore(c, c, false); } FpMul(b, c, b); // b = b ^ (2^10) for (i = 0; i < 10; i++) { FpSquareDoubleCore(b, b, false); } FpMul(a, b, a); FpSquareDoubleCore(b, a, false); // b = a ^ (2^50) for (i = 1; i < 50; i++) { FpSquareDoubleCore(b, b, false); } FpMul(b, b, a); FpSquareDoubleCore(c, b, false); // c = b ^ (2 ^ 100) for (i = 1; i < 100; i++) { FpSquareDoubleCore(c, c, false); } FpMul(b, c, b); // b = b ^ (2^50) for (i = 0; i < 50; i++) { FpSquareDoubleCore(b, b, false); } FpMul(a, b, a); FpSquareDoubleCore(a, a, false); FpSquareDoubleCore(a, a, false); FpMul(out, a, in); } #endif static void PaddingUnload(uint8_t out[32], Fp25 pFp25) { int32_t *p = (int32_t *)pFp25; /* Take a polynomial form number into a 32-byte array */ CURVE25519_BYTES4_PADDING_UNLOAD(out, 2, p); /* p0 unload 4 bytes on out[0] expand 2 */ CURVE25519_BYTES3_PADDING_UNLOAD(out + 4, 2, 3, p + 1); /* p1 unload 3 bytes on out[4] shift 2 expand 3 */ CURVE25519_BYTES3_PADDING_UNLOAD(out + 7, 3, 5, p + 2); /* p2 unload 3 bytes on out[7] shift 3 expand 5 */ CURVE25519_BYTES3_PADDING_UNLOAD(out + 10, 5, 6, p + 3); /* p3 unload 3 bytes on out[10] shift 5 expand 6 */ CURVE25519_BYTES3_UNLOAD(out + 13, 6, p + 4); /* p4 unload 3 bytes on out[13] shift 6 */ CURVE25519_BYTES4_PADDING_UNLOAD(out + 16, 1, p + 5); /* p5 unload 4 bytes on out[16] expand 1 */ CURVE25519_BYTES3_PADDING_UNLOAD(out + 20, 1, 3, p + 6); /* p6 unload 3 bytes on out[20] shift 1 expand 3 */ CURVE25519_BYTES3_PADDING_UNLOAD(out + 23, 3, 4, p + 7); /* p7 unload 3 bytes on out[23] shift 3 expand 4 */ CURVE25519_BYTES3_PADDING_UNLOAD(out + 26, 4, 6, p + 8); /* p8 unload 3 bytes on out[26] shift 4 expand 6 */ CURVE25519_BYTES3_UNLOAD(out + 29, 6, p + 9); /* p9 unload 3 bytes on out[29] shift 6 */ } void PolynomialToData(uint8_t out[32], const Fp25 polynomial) { Fp25 pFp25; uint32_t pos; uint32_t over; uint32_t mul19; uint32_t signMask; CURVE25519_FP_COPY(pFp25, polynomial); /* First process, all the carry transport to pFp25[0] */ mul19 = (uint32_t)pFp25[9] * 19; // mul 19 for mod over = mul19 + (1 << 24); // plus 1 << 24 for carry // restricted to 25 bits, shift 31 for sign signMask = (-(over >> 31)) & MASK_HIGH32(25); over = (over >> 25) | signMask; // 25 bits pos = 0; do { over = (uint32_t)pFp25[pos] + over; // first carry is restricted to 25 bits, shift 31 for sign signMask = (-(over >> 31)) & MASK_HIGH32(25); over = (over >> 25) | signMask; // 25 bits pos++; over = (uint32_t)pFp25[pos] + over; // second carry is restricted to 26 bits, shift 31 for sign signMask = (-(over >> 31)) & MASK_HIGH32(26); over = (over >> 26) | signMask; // 26 bits pos++; } while (pos < 10); // process from 0 to 9, pos < 10 mul19 = over * 19; // mul 19 for mod pFp25[0] += (int32_t)mul19; /* We subtracted 2^255-19 and get the result * all polynomial[i] is restricted to 25 bits or 26 bits */ pos = 0; do { // first polynomial is restricted to 26 bits, shift 31 for sign signMask = (-((uint32_t)pFp25[pos] >> 31)) & MASK_HIGH32(26); over = ((uint32_t)pFp25[pos] >> 26) | signMask; // 26 bits pFp25[pos] = (int32_t)((uint32_t)pFp25[pos] & MASK_LOW32(26)); // 26 bits pos++; pFp25[pos] += (int32_t)over; // second polynomial is restricted to 25 bits, shift 31 for sign signMask = (-((uint32_t)pFp25[pos] >> 31)) & MASK_HIGH32(25); over = ((uint32_t)pFp25[pos] >> 25) | signMask; // 25 bits pFp25[pos] = (int32_t)((uint32_t)pFp25[pos] & MASK_LOW32(25)); pos++; pFp25[pos] += (int32_t)over; } while (pos < 8); // process form 0 to 7, pos < 8 // process pFp25[8], restricted to 26 bits, shift 31 for sign signMask = (-((uint32_t)pFp25[pos] >> 31)) & MASK_HIGH32(26); over = ((uint32_t)pFp25[pos] >> 26) | signMask; // 26 bits pFp25[pos] = (int32_t)((uint32_t)pFp25[pos] & MASK_LOW32(26)); // 26 bits pos++; // process pFp25[9] pFp25[pos] += (int32_t)over; pFp25[pos] = (int32_t)((uint32_t)pFp25[pos] & MASK_LOW32(25)); // pFp25[9] is restricted to 25 bits PaddingUnload(out, pFp25); } /* unified addition in Extended twist Edwards Coordinate */ /* out = out + tableElement */ static void GeAdd(GeE *out, const GePre *tableElement) { Fp25 a; Fp25 b; Fp25 c; Fp25 d; Fp25 e; Fp25 f; Fp25 g; Fp25 h; /* a = (Y1 − X1) * (Y2 − X2), b = (Y1 + X1) * (Y2 + X2) * c = 2 * d * T1 * X2 * Y2, d = 2 * Z1 * e = b − a, f = d − c, g = d + c, h = b + a * X3 = e * f, Y3 = g * h, T3 = e * h, Z3 = f * g */ CURVE25519_FP_ADD(e, out->y, out->x); CURVE25519_FP_SUB(f, out->y, out->x); FpMul(b, e, tableElement->yplusx); FpMul(a, f, tableElement->yminusx); FpMul(c, out->t, tableElement->xy2d); CURVE25519_FP_ADD(d, out->z, out->z); CURVE25519_FP_SUB(e, b, a); CURVE25519_FP_SUB(f, d, c); CURVE25519_FP_ADD(g, d, c); CURVE25519_FP_ADD(h, b, a); FpMul(out->x, e, f); FpMul(out->y, h, g); FpMul(out->z, g, f); FpMul(out->t, e, h); } #ifdef HITLS_CRYPTO_ED25519 /* out = out - tableElement */ static void GeSub(GeE *out, const GePre *tableElement) { Fp25 a; Fp25 b; Fp25 c; Fp25 d; Fp25 e; Fp25 f; Fp25 g; Fp25 h; CURVE25519_FP_ADD(e, out->y, out->x); CURVE25519_FP_SUB(f, out->y, out->x); FpMul(b, e, tableElement->yminusx); FpMul(a, f, tableElement->yplusx); FpMul(c, out->t, tableElement->xy2d); CURVE25519_FP_ADD(d, out->z, out->z); CURVE25519_FP_SUB(e, b, a); CURVE25519_FP_ADD(f, d, c); CURVE25519_FP_SUB(g, d, c); CURVE25519_FP_ADD(h, b, a); FpMul(out->x, e, f); FpMul(out->y, h, g); FpMul(out->z, g, f); FpMul(out->t, e, h); } #endif /* double in Projective twist Edwards Coordinate */ static void ProjectiveDouble(GeC *complete, const GeP *projective) { Fp25 tmp; FpSquareDoubleCore((complete->x), (projective->x), false); FpSquareDoubleCore((complete->z), (projective->y), false); // T = 2 * Z^2 FpSquareDoubleCore(complete->t, projective->z, true); CURVE25519_FP_ADD(complete->y, projective->x, projective->y); FpSquareDoubleCore(tmp, complete->y, false); // tmp = (X1 + Y1) ^ 2, T = 2 * Z^2, X = X1 ^ 2, Y = Z1 ^ 2, Z = Y1 ^ 2 CURVE25519_FP_ADD(complete->y, complete->z, complete->x); CURVE25519_FP_SUB(complete->z, complete->z, complete->x); CURVE25519_FP_SUB(complete->x, tmp, complete->y); CURVE25519_FP_SUB(complete->t, complete->t, complete->z); } /* Convert complete coordinate to projective coordinate */ static void GeCompleteToProjective(GeP *out, const GeC *complete) { FpMul(out->x, complete->t, complete->x); FpMul(out->y, complete->z, complete->y); FpMul(out->z, complete->t, complete->z); } /* p1 = 16 * p1 */ static void P1DoubleFourTimes(GeE *p1) { GeP p; GeC c; // From extended coordinate to projective coordinate, just ignore T CURVE25519_FP_COPY(p.x, p1->x); CURVE25519_FP_COPY(p.y, p1->y); CURVE25519_FP_COPY(p.z, p1->z); // double 4 times to get 16p1 ProjectiveDouble(&c, &p); GeCompleteToProjective(&p, &c); ProjectiveDouble(&c, &p); GeCompleteToProjective(&p, &c); ProjectiveDouble(&c, &p); GeCompleteToProjective(&p, &c); ProjectiveDouble(&c, &p); FpMul(p1->x, c.x, c.t); FpMul(p1->y, c.y, c.z); FpMul(p1->z, c.z, c.t); FpMul(p1->t, c.x, c.y); } static void SetExtendedBasePoint(GeE *out) { CURVE25519_FP_SET(out->x, 0); CURVE25519_FP_SET(out->y, 1); CURVE25519_FP_SET(out->t, 0); CURVE25519_FP_SET(out->z, 1); } /* Multiple with Base point, see paper: High-speed high-security signatures */ void ScalarMultiBase(GeE *out, const uint8_t in[CRYPT_CURVE25519_KEYLEN]) { uint8_t carry; // inLen is always 32, buffer needs 32 * 2 = 64 uint8_t privateKey[64]; int32_t i; GePre preCompute; // split 32 8bits input into 64 4bits-based number for (i = 0; i < 32; i++) { privateKey[i * 2] = in[i] & 15; // and 15 to get low 4 bits, stored in 2i privateKey[i * 2 + 1] = (in[i] >> 4) & 15; // shift 4 then and 15 to get upper 4 bits, stored in 2i+1 } carry = 0; /** * change from 0 - 15 to -8 - 7, if privateKey[i] >= 8, carry = 1, privateKey[i] -= 16 * if privateKey[i] < 8, privateKey[i] = privateKey[i] */ for (i = 0; i < 63; i++) { // 0 to 63 privateKey[i] += carry; carry = (privateKey[i] + 8) >> 4; // plus 8 then shit 4 to get carry privateKey[i] -= carry << 4; // left shift 4 } // never overflow since we set first bit to 0 of private key privateKey[63] += carry; // last one is 63 // set base point X:Y:T:Z -> 0:1:0:1 SetExtendedBasePoint(out); for (i = 1; i < 64; i += 2) { // form 1 to 63, process all odd element, increment by 2, i < 64 TableLookup(&preCompute, i / 2, (int8_t)privateKey[i]); // position goes from 0 to 31, i / 2 = pos // Fit with paper: Twisted Edwards Curves Revisited GeAdd(out, &preCompute); } // now we have P1, double it four times we have 16P1, P1 is in Extended now, we do double in projective coordinate P1DoubleFourTimes(out); // Add P0 with precomute for (i = 0; i < 64; i += 2) { // form 0 to 62, process all even element, increment by 2, i < 64 TableLookup(&preCompute, i / 2, (int8_t)privateKey[i]); // position goes from 0 to 31, i / 2 = pos GeAdd(out, &preCompute); } // clean up private key information BSL_SAL_CleanseData(privateKey, sizeof(privateKey)); } #ifdef HITLS_CRYPTO_ED25519 void PointEncoding(const GeE *point, uint8_t *output, uint32_t outputLen) { Fp25 zInvert; Fp25 x; Fp25 y; uint8_t xData[CRYPT_CURVE25519_KEYLEN]; /* x = X / Z, y = Y / Z */ (void)outputLen; FpInvert(zInvert, point->z); FpMul(x, point->x, zInvert); FpMul(y, point->y, zInvert); PolynomialToData(output, y); PolynomialToData(xData, x); // PointEcoding writes only 32 bytes data, therefore output[31] is the last one output[31] ^= (xData[0] & 0x1) << 7; // last one is output[31], get only last bit then shift 7 } #endif static void FeCmove(Fp25 dst, const Fp25 src, const uint32_t indicator) { // if indicator = 1, now it will be 111111111111b.... const uint32_t indicate = 0 - indicator; /* des become source if dst->data[i] ^ src->data[i] is in 1111....b, or it does not change if (dst->data[i] ^ src->data[i]) & indicate is all 0 */ dst[0] = CONDITION_COPY(dst[0], src[0], indicate); // 0 dst[1] = CONDITION_COPY(dst[1], src[1], indicate); // 1 dst[2] = CONDITION_COPY(dst[2], src[2], indicate); // 2 dst[3] = CONDITION_COPY(dst[3], src[3], indicate); // 3 dst[4] = CONDITION_COPY(dst[4], src[4], indicate); // 4 dst[5] = CONDITION_COPY(dst[5], src[5], indicate); // 5 dst[6] = CONDITION_COPY(dst[6], src[6], indicate); // 6 dst[7] = CONDITION_COPY(dst[7], src[7], indicate); // 7 dst[8] = CONDITION_COPY(dst[8], src[8], indicate); // 8 dst[9] = CONDITION_COPY(dst[9], src[9], indicate); // 9 } void ConditionalMove(GePre *preCompute, const GePre *tableElement, uint32_t indicator) { FeCmove(preCompute->yplusx, tableElement->yplusx, indicator); FeCmove(preCompute->yminusx, tableElement->yminusx, indicator); FeCmove(preCompute->xy2d, tableElement->xy2d, indicator); } void DataToPolynomial(Fp25 out, const uint8_t data[32]) { const uint8_t *t = data; uint64_t p[10]; uint64_t over; int32_t i; uint64_t signMask; /* f0, load 32 bits */ CURVE25519_BYTES4_LOAD(p, t); /* f1, load 24 bits from t4, shift bits: 26 - 24 - (8 - x) = 0 -> x = 6 */ CURVE25519_BYTES3_LOAD_PADDING(p + 1, 6, t + 4); /* f2, load 24 bits from t7, shift bits: 51 - 48 - (8 - x) = 0 -> x = 5 */ CURVE25519_BYTES3_LOAD_PADDING(p + 2, 5, t + 7); /* f3, load 24 bits from t10, shift bits: 77 - 72 - (8 - x) = 0 -> x = 3 */ CURVE25519_BYTES3_LOAD_PADDING(p + 3, 3, t + 10); /* f4, load 24 bits from t13, shift bits: 102 - 96 - (8 - x) = 0 -> x = 2 */ CURVE25519_BYTES3_LOAD_PADDING(p + 4, 2, t + 13); /* f5, load 32 bits from t16 */ CURVE25519_BYTES4_LOAD(p + 5, t + 16); /* f6, load 24 bits from t20, shift bits: 153 - 152 - (8 - x) = 0 -> x = 7 */ CURVE25519_BYTES3_LOAD_PADDING(p + 6, 7, t + 20); /* f7, load 24 bits from t23, shift bits: 179 - 176 - (8 - x) = 0 -> x = 5 */ CURVE25519_BYTES3_LOAD_PADDING(p + 7, 5, t + 23); /* f8, load 24 bits from t26, shift bits: 204 - 200 - (8 - x) = 0 -> x = 4 */ CURVE25519_BYTES3_LOAD_PADDING(p + 8, 4, t + 26); /* f9, load 24 bits from t29, shift bits: 230 - 224 - (8 - x) = 0 -> x = 2 */ CURVE25519_BYTES3_LOAD(p + 9, t + 29); p[9] = (p[9] & 0x7fffff) << 2; /* p9 is 25 bits, left shift 2 */ /* Limiting the number of bits, exchange 2^1 to 2^25.5, turn into polynomial representation */ /* f9->f0, shift 24 for carry */ over = p[9] + (1 << 24); signMask = MASK_HIGH64(25) & (-((over) >> 63)); // shift 63 bits for sign, mask 25 bits p[0] += ((over >> 25) | signMask) * 19; // 24 bits plus sign is 25, mul 19 for mod p[9] -= MASK_HIGH64(39) & over; // 64 - 25 = 39 bits mask /* f1->f2, restricted to 24 bits */ PROCESS_CARRY(p[1], p[2], signMask, over, 24); /* f3->f4, restricted to 24 bits */ PROCESS_CARRY(p[3], p[4], signMask, over, 24); /* f5->f6, restricted to 24 bits */ PROCESS_CARRY(p[5], p[6], signMask, over, 24); /* f7->f8, restricted to 24 bits */ PROCESS_CARRY(p[7], p[8], signMask, over, 24); /* f0->f1, restricted to 25 bits */ PROCESS_CARRY(p[0], p[1], signMask, over, 25); /* f2->f3, restricted to 25 bits */ PROCESS_CARRY(p[2], p[3], signMask, over, 25); /* f4->f5, restricted to 25 bits */ PROCESS_CARRY(p[4], p[5], signMask, over, 25); /* f6->f7, restricted to 25 bits */ PROCESS_CARRY(p[6], p[7], signMask, over, 25); /* f8->f9, restricted to 25 bits */ PROCESS_CARRY(p[8], p[9], signMask, over, 25); /* After process carry, polynomial every term would not exceed 32 bits, convert form 0 to 9, i < 10 */ for (i = 0; i < 10; i++) { out[i] = (int32_t)p[i]; } } #ifdef HITLS_CRYPTO_ED25519 static bool CheckZero(Fp25 x) { uint8_t tmp[32]; const uint8_t zero[32] = {0}; PolynomialToData(tmp, x); if (memcmp(tmp, zero, sizeof(zero)) == 0) { return true; } else { return false; } } static uint8_t GetXBit(Fp25 in) { uint8_t tmp[32]; PolynomialToData(tmp, in); return tmp[0] & 0x1; } static const Fp25 SQRTM1 = {-32595792, -7943725, 9377950, 3500415, 12389472, -272473, -25146209, -2005654, 326686, 11406482}; static const Fp25 D = {-10913610, 13857413, -15372611, 6949391, 114729, -8787816, -6275908, -3247719, -18696448, -12055116}; int32_t PointDecoding(GeE *point, const uint8_t in[CRYPT_CURVE25519_KEYLEN]) { Fp25 u, v, v3, x2, result; // get the last block (31), shift 7 for first bit uint8_t x0 = in[31] >> 7; DataToPolynomial(point->y, in); CURVE25519_FP_SET(point->z, 1); FpSquareDoubleCore(u, point->y, false); FpMul(v, u, D); CURVE25519_FP_SUB(u, u, point->z); CURVE25519_FP_ADD(v, v, point->z); FpSquareDoubleCore(v3, v, false); FpMul(v3, v3, v); FpSquareDoubleCore(point->x, v3, false); FpMul(point->x, point->x, v); FpMul(point->x, point->x, u); /* x = x ^ ((q - 5) / 8) */ FpPowq58(point->x, point->x); FpMul(point->x, point->x, v3); FpMul(point->x, point->x, u); FpSquareDoubleCore(x2, point->x, false); FpMul(x2, x2, v); CURVE25519_FP_SUB(result, x2, u); if (CheckZero(result) == false) { CURVE25519_FP_ADD(result, x2, u); if (CheckZero(result) == false) { return 1; } FpMul(point->x, point->x, SQRTM1); } uint8_t bit = GetXBit(point->x); if (bit != x0) { CURVE25519_FP_NEGATE(point->x, point->x); } FpMul(point->t, point->x, point->y); return 0; } static void ScalarMulAddPreLoad(const uint8_t in[CRYPT_CURVE25519_KEYLEN], uint64_t out[UINT8_32_21BITS_BLOCKNUM]) { CURVE25519_BYTES3_LOAD(&out[0], in); out[0] = out[0] & MASK_64_LOW21; CURVE25519_BYTES4_LOAD(&out[1], in + 2); // 1: load 4 bytes form position 2 out[1] = MASK_64_LOW21 & (out[1] >> 5); // 1: 8 - ((3 * 8) mod 21) mod 8 = 5 CURVE25519_BYTES3_LOAD(&out[2], in + 5); // 2: load 3 bytes form position 5 out[2] = MASK_64_LOW21 & (out[2] >> 2); // 2: 8 - ((6 * 8) mod 21) mod 8 = 2 CURVE25519_BYTES4_LOAD(&out[3], in + 7); // 3: load 4 bytes form position 7 out[3] = MASK_64_LOW21 & (out[3] >> 7); // 3: 8 - ((8 * 8) mod 21) mod 8 = 7 CURVE25519_BYTES4_LOAD(&out[4], in + 10); // 4: load 4 bytes form position 10 out[4] = MASK_64_LOW21 & (out[4] >> 4); // 4: 8 - ((11 * 8) mod 21) mod 8 = 4 CURVE25519_BYTES3_LOAD(&out[5], in + 13); // 5: load 3 bytes form position 13 out[5] = MASK_64_LOW21 & (out[5] >> 1); // 5: 8 - ((14 * 8) mod 21) mod 8 = 1 CURVE25519_BYTES4_LOAD(&out[6], in + 15); // 6: load 4 bytes form position 15 out[6] = MASK_64_LOW21 & (out[6] >> 6); // 6: 8 - ((16 * 8) mod 21) mod 8 = 6 CURVE25519_BYTES3_LOAD(&out[7], in + 18); // 7: load 3 bytes form position 18 out[7] = MASK_64_LOW21 & (out[7] >> 3); // 7: 8 - ((19 * 8) mod 21) mod 8 = 3 CURVE25519_BYTES3_LOAD(&out[8], in + 21); // 8: load 3 bytes form position 21 out[8] = MASK_64_LOW21 & out[8]; // 8: ((22 * 8) mod 21) mod 8 = 0 CURVE25519_BYTES4_LOAD(&out[9], in + 23); // 9: load 4 bytes form position 23 out[9] = MASK_64_LOW21 & (out[9] >> 5); // 9: 8 - ((24 * 8) mod 21) mod 8 = 5 CURVE25519_BYTES3_LOAD(&out[10], in + 26); // 10: load 3 bytes form position 26 out[10] = MASK_64_LOW21 & (out[10] >> 2); // 10: 8 - ((27 * 8) mod 21) mod 8 = 2 CURVE25519_BYTES4_LOAD(&out[11], in + 28); // 11: load 4 bytes form position 28 out[11] = (out[11] >> 7); // 11: 8 - ((29 * 8) mod 21) mod 8 = 7 } static void ModuloLPreLoad(const uint8_t s[CRYPT_CURVE25519_SIGNLEN], uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM]) { CURVE25519_BYTES3_LOAD(&s21Bits[0], s); s21Bits[0] = s21Bits[0] & MASK_64_LOW21; CURVE25519_BYTES4_LOAD(&s21Bits[1], s + 2); // 1: load 4 bytes form position 2 s21Bits[1] = MASK_64_LOW21 & (s21Bits[1] >> 5); // 1: 8 - ((3 * 8) mod 21) mod 8 = 5 CURVE25519_BYTES3_LOAD(&s21Bits[2], s + 5); // 2: load 3 bytes form position 5 s21Bits[2] = MASK_64_LOW21 & (s21Bits[2] >> 2); // 2: 8 - ((6 * 8) mod 21) mod 8 = 2 CURVE25519_BYTES4_LOAD(&s21Bits[3], s + 7); // 3: load 4 bytes form position 7 s21Bits[3] = MASK_64_LOW21 & (s21Bits[3] >> 7); // 3: 8 - ((8 * 8) mod 21) mod 8 = 7 CURVE25519_BYTES4_LOAD(&s21Bits[4], s + 10); // 4: load 4 bytes form position 10 s21Bits[4] = MASK_64_LOW21 & (s21Bits[4] >> 4); // 4: 8 - ((11 * 8) mod 21) mod 8 = 4 CURVE25519_BYTES3_LOAD(&s21Bits[5], s + 13); // 5: load 3 bytes form position 13 s21Bits[5] = MASK_64_LOW21 & (s21Bits[5] >> 1); // 5: 8 - ((14 * 8) mod 21) mod 8 = 1 CURVE25519_BYTES4_LOAD(&s21Bits[6], s + 15); // 6: load 4 bytes form position 15 s21Bits[6] = MASK_64_LOW21 & (s21Bits[6] >> 6); // 6: 8 - ((16 * 8) mod 21) mod 8 = 6 CURVE25519_BYTES3_LOAD(&s21Bits[7], s + 18); // 7: load 3 bytes form position 18 s21Bits[7] = MASK_64_LOW21 & (s21Bits[7] >> 3); // 7: 8 - ((19 * 8) mod 21) mod 8 = 3 CURVE25519_BYTES3_LOAD(&s21Bits[8], s + 21); // 8: load 3 bytes form position 21 s21Bits[8] = MASK_64_LOW21 & s21Bits[8]; // 8: ((22 * 8) mod 21) mod 8 = 0 CURVE25519_BYTES4_LOAD(&s21Bits[9], s + 23); // 9: load 4 bytes form position 23 s21Bits[9] = MASK_64_LOW21 & (s21Bits[9] >> 5); // 9: 8 - ((24 * 8) mod 21) mod 8 = 5 CURVE25519_BYTES3_LOAD(&s21Bits[10], s + 26); // 10: load 3 bytes form position 26 s21Bits[10] = MASK_64_LOW21 & (s21Bits[10] >> 2); // 10: 8 - ((27 * 8) mod 21) mod 8 = 2 CURVE25519_BYTES4_LOAD(&s21Bits[11], s + 28); // 11: load 4 bytes form position 28 s21Bits[11] = MASK_64_LOW21 & (s21Bits[11] >> 7); // 11: 8 - ((29 * 8) mod 21) mod 8 = 7 CURVE25519_BYTES4_LOAD(&s21Bits[12], s + 31); // 12: load 4 bytes form position 31 s21Bits[12] = MASK_64_LOW21 & (s21Bits[12] >> 4); // 12: 8 - ((32 * 8) mod 21) mod 8 = 4 CURVE25519_BYTES3_LOAD(&s21Bits[13], s + 34); // 13: load 3 bytes form position 34 s21Bits[13] = MASK_64_LOW21 & (s21Bits[13] >> 1); // 13: 8 - ((35 * 8) mod 21) mod 8 = 1 CURVE25519_BYTES4_LOAD(&s21Bits[14], s + 36); // 14: load 4 bytes form position 36 s21Bits[14] = MASK_64_LOW21 & (s21Bits[14] >> 6); // 14: 8 - ((37 * 8) mod 21) mod 8 = 6 CURVE25519_BYTES3_LOAD(&s21Bits[15], s + 39); // 15: load 3 bytes form position 39 s21Bits[15] = MASK_64_LOW21 & (s21Bits[15] >> 3); // 15: 8 - ((40 * 8) mod 21) mod 8 = 3 CURVE25519_BYTES3_LOAD(&s21Bits[16], s + 42); // 16: load 3 bytes form position 42 s21Bits[16] = MASK_64_LOW21 & s21Bits[16]; // 16: ((43 * 8) mod 21) mod 8 = 0 CURVE25519_BYTES4_LOAD(&s21Bits[17], s + 44); // 17: load 4 bytes form position 44 s21Bits[17] = MASK_64_LOW21 & (s21Bits[17] >> 5); // 17: 8 - ((45 * 8) mod 21) mod 8 = 5 CURVE25519_BYTES3_LOAD(&s21Bits[18], s + 47); // 18: load 3 bytes form position 47 s21Bits[18] = MASK_64_LOW21 & (s21Bits[18] >> 2); // 18: 8 - ((48 * 8) mod 21) mod 8 = 2 CURVE25519_BYTES4_LOAD(&s21Bits[19], s + 49); // 19: load 4 bytes form position 49 s21Bits[19] = MASK_64_LOW21 & (s21Bits[19] >> 7); // 19: 8 - ((50 * 8) mod 21) mod 8 = 7 CURVE25519_BYTES4_LOAD(&s21Bits[20], s + 52); // 20: load 4 bytes form position 52 s21Bits[20] = MASK_64_LOW21 & (s21Bits[20] >> 4); // 20: 8 - ((53 * 8) mod 21) mod 8 = 4 CURVE25519_BYTES3_LOAD(&s21Bits[21], s + 55); // 21: load 3 bytes form position 55 s21Bits[21] = MASK_64_LOW21 & (s21Bits[21] >> 1); // 21: 8 - ((56 * 8) mod 21) mod 8 = 1 CURVE25519_BYTES4_LOAD(&s21Bits[22], s + 57); // 22: load 4 bytes form position 57 s21Bits[22] = MASK_64_LOW21 & (s21Bits[22] >> 6); // 22: 8 - ((58 * 8) mod 21) mod 8 = 6 CURVE25519_BYTES4_LOAD(&s21Bits[23], s + 60); // 23: load 4 bytes form position 60 s21Bits[23] = s21Bits[23] >> 3; // 23: 8 - ((61 * 8) mod 21) mod 8 = 3 } static void UnloadTo8Bits(uint8_t s8Bits[CRYPT_CURVE25519_OPTLEN], uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM]) { s8Bits[0] = (uint8_t)s21Bits[0]; // 1: load from 8 on block 0 s8Bits[1] = (uint8_t)(s21Bits[0] >> 8); // 2: load from (16 + 1) to 21 on block 0 and 1 to 3 on block 1, 8 - 3 = 5 s8Bits[2] = (uint8_t)((s21Bits[0] >> 16) | (s21Bits[1] << 5)); // 3: load from (3 + 1) on block 1 s8Bits[3] = (uint8_t)(s21Bits[1] >> 3); // 4: load from (11 + 1) on block 1 s8Bits[4] = (uint8_t)(s21Bits[1] >> 11); // 5: load from (19 + 1) to 21 on block 1 and 1 to 6 on block 2, 8 - 6 = 2 s8Bits[5] = (uint8_t)((s21Bits[1] >> 19) | (s21Bits[2] << 2)); // 6: load from (6 + 1) on block 2 s8Bits[6] = (uint8_t)(s21Bits[2] >> 6); // 7: load from (14 + 1) to 21 on block 2 and 1 on block 3, 8 - 7 = 1 s8Bits[7] = (uint8_t)((s21Bits[2] >> 14) | (s21Bits[3] << 7)); // 8: load from (1 + 1) on block 3 s8Bits[8] = (uint8_t)(s21Bits[3] >> 1); // 9: load from (9 + 1) on block 3 s8Bits[9] = (uint8_t)(s21Bits[3] >> 9); // 10: load from (17 + 1) to 21 on block 3 and 1 to 4 on block 4, 8 - 4 = 4 s8Bits[10] = (uint8_t)((s21Bits[3] >> 17) | (s21Bits[4] << 4)); // 11: load from (4 + 1) on block 4 s8Bits[11] = (uint8_t)(s21Bits[4] >> 4); // 12: load from (12 + 1) on block 4 s8Bits[12] = (uint8_t)(s21Bits[4] >> 12); // 13: load from (20 + 1) on block 4 and 1 to 7 on block 5, 8 - 7 = 1 s8Bits[13] = (uint8_t)((s21Bits[4] >> 20) | (s21Bits[5] << 1)); // 14: load from (7 + 1) on block 5 s8Bits[14] = (uint8_t)(s21Bits[5] >> 7); // 15: load from (15 + 1) to 21 on block 5 and 1 to 2 on block 6, 8 - 2 = 6 s8Bits[15] = (uint8_t)((s21Bits[5] >> 15) | (s21Bits[6] << 6)); // 16: load from (2 + 1) on block 6 s8Bits[16] = (uint8_t)(s21Bits[6] >> 2); // 17: load from (10 + 1) on block 6 s8Bits[17] = (uint8_t)(s21Bits[6] >> 10); // 18: load from (18 + 1) to 21 on block 6 and 1 to 5 on block 7, 8 - 5 = 3 s8Bits[18] = (uint8_t)((s21Bits[6] >> 18) | (s21Bits[7] << 3)); // 19: load from (5 + 1) on block 7 s8Bits[19] = (uint8_t)(s21Bits[7] >> 5); // 20: load from (13 + 1) on block 7 s8Bits[20] = (uint8_t)(s21Bits[7] >> 13); // 21: load 8bits on block 8 s8Bits[21] = (uint8_t)s21Bits[8]; // 22: load from (8 + 1) on block 8 s8Bits[22] = (uint8_t)(s21Bits[8] >> 8); // 23: load from (16 + 1) to 21 on block 8 and 1 to 3 on block 9, 8 - 3 = 5 s8Bits[23] = (uint8_t)((s21Bits[8] >> 16) | (s21Bits[9] << 5)); // 24: load from (3 + 1) on block 9 s8Bits[24] = (uint8_t)(s21Bits[9] >> 3); // 25: load from (11 + 1) on block 9 s8Bits[25] = (uint8_t)(s21Bits[9] >> 11); // 26: load from (19 + 1) to 21 on block 9 and 1 to 6 on block 10, 8 - 6 = 2 s8Bits[26] = (uint8_t)((s21Bits[9] >> 19) | (s21Bits[10] << 2)); // 27: load from (6 + 1) on block 10 s8Bits[27] = (uint8_t)(s21Bits[10] >> 6); // 28: load from (14 + 1) to 21 on block 10 and 1 on block 11, 8 - 7 = 1 s8Bits[28] = (uint8_t)((s21Bits[10] >> 14) | (s21Bits[11] << 7)); // 29: load from (1 + 1) on block 11 s8Bits[29] = (uint8_t)(s21Bits[11] >> 1); // 30: load from (9 + 1) on block 11 s8Bits[30] = (uint8_t)(s21Bits[11] >> 9); // 31: load from (17 + 1) on block 11 s8Bits[31] = (uint8_t)(s21Bits[11] >> 17); } static void ModuloLCore(uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM]) { int32_t i; uint64_t signMask1, signMask2; uint64_t carry1, carry2; // multiply by l0, start with {11, 12, 13, 14, 15, 16} to {6, 7, 8, 9, 10, 11, 12} CURVE25519_MULTI_BY_L0(s21Bits, 11); CURVE25519_MULTI_BY_L0(s21Bits, 10); CURVE25519_MULTI_BY_L0(s21Bits, 9); CURVE25519_MULTI_BY_L0(s21Bits, 8); CURVE25519_MULTI_BY_L0(s21Bits, 7); CURVE25519_MULTI_BY_L0(s21Bits, 6); // need to process carry to prevent overflow, process carry from 6->7, 8->9 ... 16->17, increment by 2 for (i = 6; i <= 16; i += 2) { // 21 bits minus sign is 20 bits PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask1, carry1, 20); } // process carry from 7->8, 9->10 ... 15->16, increment by 2 for (i = 7; i <= 15; i += 2) { // 21 bits minus sign bit is 20 bits PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask2, carry2, 20); } // {5, 6, 7, 8, 9, 10} to {0, 1, 2, 3, 4, 5, 6} CURVE25519_MULTI_BY_L0(s21Bits, 5); CURVE25519_MULTI_BY_L0(s21Bits, 4); CURVE25519_MULTI_BY_L0(s21Bits, 3); CURVE25519_MULTI_BY_L0(s21Bits, 2); CURVE25519_MULTI_BY_L0(s21Bits, 1); CURVE25519_MULTI_BY_L0(s21Bits, 0); // process carry again, from 0->1, 2->3 ... 10->11, increment by 2 for (i = 0; i <= 10; i += 2) { // 21 bits minus sign bit is 20 bits PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask1, carry1, 20); } // from 1->2, 3->4 ... 11->12, increment by 2 for (i = 1; i <= 11; i += 2) { // 21 bits minus sign is 20 bits PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask2, carry2, 20); } CURVE25519_MULTI_BY_L0(s21Bits, 0); // process carry from 0 to 11 for (i = 0; i <= 11; i++) { PROCESS_CARRY_UNSIGN(s21Bits[i], s21Bits[i + 1], signMask1, carry1, 21); // s21Bits is 21 bits } CURVE25519_MULTI_BY_L0(s21Bits, 0); // from 0 to 10 for (i = 0; i <= 10; i++) { PROCESS_CARRY_UNSIGN(s21Bits[i], s21Bits[i + 1], signMask1, carry1, 21); // s21Bits is 21 bits } } void ModuloL(uint8_t s[CRYPT_CURVE25519_SIGNLEN]) { // 24 of 21 bits block uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM] = {0}; ModuloLPreLoad(s, s21Bits); ModuloLCore(s21Bits); UnloadTo8Bits(s, s21Bits); } static void MulAdd(uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM], const uint64_t a21Bits[UINT8_32_21BITS_BLOCKNUM], const uint64_t b21Bits[UINT8_32_21BITS_BLOCKNUM], const uint64_t c21Bits[UINT8_32_21BITS_BLOCKNUM]) { // s0 = c0 + a0b0 s21Bits[0] = c21Bits[0] + a21Bits[0] * b21Bits[0]; // s1 = c1 + a0b1 + a1b0 s21Bits[1] = c21Bits[1] + a21Bits[0] * b21Bits[1] + a21Bits[1] * b21Bits[0]; // s2 = c2 + a0b2 + b1a1 + a2b0 s21Bits[2] = c21Bits[2] + a21Bits[0] * b21Bits[2] + a21Bits[1] * b21Bits[1] + a21Bits[2] * b21Bits[0]; // s3 = c3 + a0b3 + a1b2 + a2b1 + a3b0 s21Bits[3] = c21Bits[3] + a21Bits[0] * b21Bits[3] + a21Bits[1] * b21Bits[2] + a21Bits[2] * b21Bits[1] + a21Bits[3] * b21Bits[0]; // a2b1 + a3b0 // s4 = c4 + a0b4 +a1b3 + a2b2 + a3b1 + a4b0 s21Bits[4] = c21Bits[4] + a21Bits[0] * b21Bits[4] + a21Bits[1] * b21Bits[3] + a21Bits[2] * b21Bits[2] + a21Bits[3] * b21Bits[1] + a21Bits[4] * b21Bits[0]; // a2b2 + a3b1 + a4b0 // s5 = c5 + a0b5 + a1b4 + a2b3 + a3b2 + a4b1 + a5b0 s21Bits[5] = c21Bits[5] + a21Bits[0] * b21Bits[5] + a21Bits[1] * b21Bits[4] + a21Bits[2] * b21Bits[3] + a21Bits[3] * b21Bits[2] + a21Bits[4] * b21Bits[1] + a21Bits[5] * b21Bits[0]; // a3b2 + a4b1 + a5b0 // s6 = c6 + a0b6 + a1b5 + a2b4 + a3b3 + a2b4 + a5b1 + a6b0 s21Bits[6] = c21Bits[6] + a21Bits[0] * b21Bits[6] + a21Bits[1] * b21Bits[5] + a21Bits[2] * b21Bits[4] + a21Bits[3] * b21Bits[3] + a21Bits[4] * b21Bits[2] + a21Bits[5] * b21Bits[1] + // a3b3 + a2b4 + a5b1 a21Bits[6] * b21Bits[0]; // a6b0 // s7 = c7 + a0b7 + a1b6 + a2b5 + a3b4 + a4b3 + a5b2 + a6b1 + a7b0 s21Bits[7] = c21Bits[7] + a21Bits[0] * b21Bits[7] + a21Bits[1] * b21Bits[6] + a21Bits[2] * b21Bits[5] + a21Bits[3] * b21Bits[4] + a21Bits[4] * b21Bits[3] + a21Bits[5] * b21Bits[2] + // a3b4 + a4b3 + a5b2 a21Bits[6] * b21Bits[1] + a21Bits[7] * b21Bits[0]; // a6b1 + a7b0 // s8 = c8 + a0b8 + a1b7 + a2b6 + a3b5 + a4b4 + a5b3 + a6b2 + a7b1 + a8b0 s21Bits[8] = c21Bits[8] + a21Bits[0] * b21Bits[8] + a21Bits[1] * b21Bits[7] + a21Bits[2] * b21Bits[6] + a21Bits[3] * b21Bits[5] + a21Bits[4] * b21Bits[4] + a21Bits[5] * b21Bits[3] + // a3b5 + a4b4 + a5b3 a21Bits[6] * b21Bits[2] + a21Bits[7] * b21Bits[1] + a21Bits[8] * b21Bits[0]; // a6b2 + a7b1 + a8b0 // s9 = c9 + a0b9 + a1b8 + a2b7 + a3b6 + a4b5 + a5b4 + a6b3 + a7b2 + a8b1 + a9b0 s21Bits[9] = c21Bits[9] + a21Bits[0] * b21Bits[9] + a21Bits[1] * b21Bits[8] + a21Bits[2] * b21Bits[7] + a21Bits[3] * b21Bits[6] + a21Bits[4] * b21Bits[5] + a21Bits[5] * b21Bits[4] + // a3b6 + a4b5 + a5b4 a21Bits[6] * b21Bits[3] + a21Bits[7] * b21Bits[2] + a21Bits[8] * b21Bits[1] + // a6b3 + a7b2 + a8b1 a21Bits[9] * b21Bits[0]; // a9b0 // s10 = c10 + a0b10 + a1b9 + a2b8 + a3b7 + a4b6 + a5b5 + a6b4 + a7b3 + a8b2 + a9b1 + a10b0 s21Bits[10] = c21Bits[10] + a21Bits[0] * b21Bits[10] + a21Bits[1] * b21Bits[9] + a21Bits[2] * b21Bits[8] + a21Bits[3] * b21Bits[7] + a21Bits[4] * b21Bits[6] + a21Bits[5] * b21Bits[5] + // a3b7 + a4b6 + a5b5 a21Bits[6] * b21Bits[4] + a21Bits[7] * b21Bits[3] + a21Bits[8] * b21Bits[2] + // a6b4 + a7b3 + a8b2 a21Bits[9] * b21Bits[1] + a21Bits[10] * b21Bits[0]; // a9b1 + a10b0 // s11 = c11 + a0b11 + a1b10 + a2b9 + a3b8 + a4b7 + a5b6 + a6b5 + a7b4 + a8b3 + a9b2 + a10b1 + a11b0 s21Bits[11] = c21Bits[11] + a21Bits[0] * b21Bits[11] + a21Bits[1] * b21Bits[10] + a21Bits[2] * b21Bits[9] + a21Bits[3] * b21Bits[8] + a21Bits[4] * b21Bits[7] + a21Bits[5] * b21Bits[6] + // a3b8 + a4b7 + a5b6 a21Bits[6] * b21Bits[5] + a21Bits[7] * b21Bits[4] + a21Bits[8] * b21Bits[3] + // a6b5 + a7b4 + a8b3 a21Bits[9] * b21Bits[2] + a21Bits[10] * b21Bits[1] + a21Bits[11] * b21Bits[0]; // a9b2 + a10b1 + a11b0 // s12 = a1b11 + a2b10 + a3b9 + a4b8 + a5b7 + a6b6 + a7b5 + a8b4 + a9b3 + a10b2 + a11b1 s21Bits[12] = a21Bits[1] * b21Bits[11] + a21Bits[2] * b21Bits[10] + a21Bits[3] * b21Bits[9] + a21Bits[4] * b21Bits[8] + a21Bits[5] * b21Bits[7] + a21Bits[6] * b21Bits[6] + // a4b8 + a5b7 + a6b6 a21Bits[7] * b21Bits[5] + a21Bits[8] * b21Bits[4] + a21Bits[9] * b21Bits[3] + // a7b5 + a8b4 + a9b3 a21Bits[10] * b21Bits[2] + a21Bits[11] * b21Bits[1]; // a10b2 + a11b1 // s13 = a2b11 + a3b10 + a4b9 + a5b8 + a6b7 + a7b6 + a8b5 + a9b4 + a10b3 + a11b2 s21Bits[13] = a21Bits[2] * b21Bits[11] + a21Bits[3] * b21Bits[10] + a21Bits[4] * b21Bits[9] + a21Bits[5] * b21Bits[8] + a21Bits[6] * b21Bits[7] + a21Bits[7] * b21Bits[6] + // a5b8 + a6b7 + a7b6 a21Bits[8] * b21Bits[5] + a21Bits[9] * b21Bits[4] + a21Bits[10] * b21Bits[3] + // a8b5 + a9b4 + a10b3 a21Bits[11] * b21Bits[2]; // a11b2 // s14 = a3b11 + a4b10 + a5b9 + a6b8 + a7b7 + a8b6 + a9b5 + a10b4 + a11b3 s21Bits[14] = a21Bits[3] * b21Bits[11] + a21Bits[4] * b21Bits[10] + a21Bits[5] * b21Bits[9] + a21Bits[6] * b21Bits[8] + a21Bits[7] * b21Bits[7] + a21Bits[8] * b21Bits[6] + // a6b8 + a7b7 + a8b6 a21Bits[9] * b21Bits[5] + a21Bits[10] * b21Bits[4] + a21Bits[11] * b21Bits[3]; // a9b5 + a10b4 + a11b3 // s15 = a4b11 + a5b10 + a6b9 + a7b8 + a8b7 + a9b6 + a10b5 + a11b4 s21Bits[15] = a21Bits[4] * b21Bits[11] + a21Bits[5] * b21Bits[10] + a21Bits[6] * b21Bits[9] + a21Bits[7] * b21Bits[8] + a21Bits[8] * b21Bits[7] + a21Bits[9] * b21Bits[6] + // a7b8 + a8b7 + a9b6 a21Bits[10] * b21Bits[5] + a21Bits[11] * b21Bits[4]; // a10b5 + a11b4 // s16 = a5b11 + a6b10 + a7b9 + a8b8 + a9b7 + a10b6 + a11b5 s21Bits[16] = a21Bits[5] * b21Bits[11] + a21Bits[6] * b21Bits[10] + a21Bits[7] * b21Bits[9] + a21Bits[8] * b21Bits[8] + a21Bits[9] * b21Bits[7] + a21Bits[10] * b21Bits[6] + // a8b8 + a9b7 + a10b6 a21Bits[11] * b21Bits[5]; // a11b5 // s17 = a6b11 + a7b10 + a8b9 + a9b8 + a10b7 + a11b6 s21Bits[17] = a21Bits[6] * b21Bits[11] + a21Bits[7] * b21Bits[10] + a21Bits[8] * b21Bits[9] + a21Bits[9] * b21Bits[8] + a21Bits[10] * b21Bits[7] + a21Bits[11] * b21Bits[6]; // a9b8 + a10b7 + a11b6 // s18 = a7b11 + a8b10 + a9b9 + a10b8 + a11b7 s21Bits[18] = a21Bits[7] * b21Bits[11] + a21Bits[8] * b21Bits[10] + a21Bits[9] * b21Bits[9] + a21Bits[10] * b21Bits[8] + a21Bits[11] * b21Bits[7]; // a10b8 + a11b7 // s19 = a8b11 + a9b10 + a10b9 + a11b8 s21Bits[19] = a21Bits[8] * b21Bits[11] + a21Bits[9] * b21Bits[10] + a21Bits[10] * b21Bits[9] + a21Bits[11] * b21Bits[8]; // a11b8 // s20 = a9b11 + a10b10 + a11b9 s21Bits[20] = a21Bits[9] * b21Bits[11] + a21Bits[10] * b21Bits[10] + a21Bits[11] * b21Bits[9]; // s21 = a10b11 + a11b10 s21Bits[21] = a21Bits[10] * b21Bits[11] + a21Bits[11] * b21Bits[10]; // s22 = a11b11 s21Bits[22] = a21Bits[11] * b21Bits[11]; // s23 = 0 s21Bits[23] = 0; } void ScalarMulAdd(uint8_t s[CRYPT_CURVE25519_KEYLEN], const uint8_t a[CRYPT_CURVE25519_KEYLEN], const uint8_t b[CRYPT_CURVE25519_KEYLEN], const uint8_t c[CRYPT_CURVE25519_KEYLEN]) { uint64_t a21Bits[UINT8_32_21BITS_BLOCKNUM]; uint64_t b21Bits[UINT8_32_21BITS_BLOCKNUM]; uint64_t c21Bits[UINT8_32_21BITS_BLOCKNUM]; ScalarMulAddPreLoad(a, a21Bits); ScalarMulAddPreLoad(b, b21Bits); ScalarMulAddPreLoad(c, c21Bits); uint64_t s21Bits[UINT8_64_21BITS_BLOCKNUM]; MulAdd(s21Bits, a21Bits, b21Bits, c21Bits); int32_t i; uint64_t signMask1, signMask2; uint64_t carryA, carryB; // process carry 0->1, 2->3 ... 22->23 for (i = 0; i <= 22; i += 2) { // 21 bits minus sign bit is 20 bits PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask1, carryA, 20); } // process carry 1->2, 3->4 ... 21->22 for (i = 1; i <= 21; i += 2) { // 21 bits minus sign bit is 20 bits PROCESS_CARRY(s21Bits[i], s21Bits[i + 1], signMask2, carryB, 20); } ModuloLCore(s21Bits); UnloadTo8Bits(s, s21Bits); } /* RFC8032, out = a + b */ static void PointAdd(GeE *out, GeE *greA, GeE *greB) { const Fp25 d2 = {-21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199}; Fp25 a, b, c, d, e, f, g, h; CURVE25519_FP_SUB(e, greA->y, greA->x); CURVE25519_FP_SUB(f, greB->y, greB->x); CURVE25519_FP_ADD(g, greA->y, greA->x); CURVE25519_FP_ADD(h, greB->y, greB->x); FpMul(a, e, f); FpMul(b, g, h); FpMul(c, greA->t, greB->t); FpMul(c, c, d2); FpMul(d, greA->z, greB->z); CURVE25519_FP_ADD(d, d, d); CURVE25519_FP_SUB(e, b, a); CURVE25519_FP_SUB(f, d, c); CURVE25519_FP_ADD(g, d, c); CURVE25519_FP_ADD(h, b, a); FpMul(out->x, e, f); FpMul(out->y, g, h); FpMul(out->z, f, g); FpMul(out->t, e, h); } static void PointAddPrecompute(GeE *out, GeE *greA, GeEPre *greB) { Fp25 a, b, c, d, e, f, g, h; CURVE25519_FP_SUB(e, greA->y, greA->x); CURVE25519_FP_ADD(g, greA->y, greA->x); FpMul(a, e, greB->yminusx); FpMul(b, g, greB->yplusx); FpMul(c, greA->t, greB->t2z); FpMul(d, greA->z, greB->z); CURVE25519_FP_ADD(d, d, d); CURVE25519_FP_SUB(e, b, a); CURVE25519_FP_SUB(f, d, c); CURVE25519_FP_ADD(g, d, c); CURVE25519_FP_ADD(h, b, a); FpMul(out->x, e, f); FpMul(out->y, g, h); FpMul(out->z, f, g); FpMul(out->t, e, h); } static void PointSubPrecompute(GeE *out, GeE *greA, GeEPre *greB) { Fp25 a, b, c, d, e, f, g, h; CURVE25519_FP_SUB(e, greA->y, greA->x); CURVE25519_FP_ADD(g, greA->y, greA->x); FpMul(a, e, greB->yplusx); FpMul(b, g, greB->yminusx); FpMul(c, greA->t, greB->t2z); FpMul(d, greA->z, greB->z); CURVE25519_FP_ADD(d, d, d); CURVE25519_FP_SUB(e, b, a); CURVE25519_FP_ADD(f, d, c); CURVE25519_FP_SUB(g, d, c); CURVE25519_FP_ADD(h, b, a); FpMul(out->x, e, f); FpMul(out->y, g, h); FpMul(out->z, f, g); FpMul(out->t, e, h); } static void P1DoubleN(GeE *p1, int32_t n) { GeP p; GeC c; int32_t i; // From extended coordinate to projective coordinate, just ignore T CURVE25519_FP_COPY(p.x, p1->x); CURVE25519_FP_COPY(p.y, p1->y); CURVE25519_FP_COPY(p.z, p1->z); ProjectiveDouble(&c, &p); for (i = 1; i < n; i++) { GeCompleteToProjective(&p, &c); ProjectiveDouble(&c, &p); } FpMul(p1->x, c.t, c.x); FpMul(p1->y, c.z, c.y); FpMul(p1->z, c.t, c.z); FpMul(p1->t, c.y, c.x); } static void PointToPrecompute(GeEPre *out, GeE *in) { const Fp25 d2 = {-21827239, -5839606, -30745221, 13898782, 229458, 15978800, -12551817, -6495438, 29715968, 9444199}; CURVE25519_FP_ADD(out->yplusx, in->y, in->x); CURVE25519_FP_SUB(out->yminusx, in->y, in->x); CURVE25519_FP_COPY(out->z, in->z); FpMul(out->t2z, in->t, d2); } static void FlipK(int8_t slide[256], uint32_t start) { uint32_t k; for (k = start; k < 256; k++) { if (slide[k] == 0) { slide[k] = 1; break; } else { slide[k] = 0; } } } static void SlideReduce(int8_t *out, uint32_t outLen, const uint8_t *in, uint32_t inLen) { uint32_t i, j; int8_t tmp; (void)outLen; (void)inLen; // 32 * 8 = 256 for (i = 0; i < 256; i++) { // turn 32 8bits to 256 1bit, block: in[i >> 3], bit: (i & 7) out[i] = (int8_t)((in[i >> 3] >> (i & 7)) & 1); } // 32 * 8 = 256 for (i = 0; i < 256; i++) { if (out[i] == 0) { continue; } for (j = 1; j <= 6 && (i + j) < 256; j++) { // check next 6 since 2^6 - 2^5 = 16 > 15, 256 is array length if (out[i + j] == 0) { continue; } // range 15 to -15 tmp = (int8_t)((uint8_t)(out[i + j]) << j); if (out[i] + tmp <= 15) { // max 15, 0x1, 0x1, 0x1, 0x1 , 0 -> 0x1111, 0, 0, 0, 0 out[i] += tmp; out[i + j] = 0; } else if (out[i] - tmp >= -15) { // min -15, 0x1111, 0, 0, 0, 1, 1 -> -1, 0, 0, 0, 0, 1 out[i] -= tmp; FlipK(out, i + j); } else { break; } } } } // Base on article "High-speed high-security signatures" // stores B, 3B, 5B, 7B, 9B, 11B, 13B, 15B, with B as ed25519 base point static const GePre g_precomputedB[8] = { { {25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, {-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378}, {-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546}, }, { {15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024}, {16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574}, {30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357}, }, { {10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380}, {4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306}, {19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942}, }, { {5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766}, {-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701}, {28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300}, }, { {-22518993, -6692182, 14201702, -8745502, -23510406, 8844726, 18474211, -1361450, -13062696, 13821877}, {-6455177, -7839871, 3374702, -4740862, -27098617, -10571707, 31655028, -7212327, 18853322, -14220951}, {4566830, -12963868, -28974889, -12240689, -7602672, -2830569, -8514358, -10431137, 2207753, -3209784}, }, { {-25154831, -4185821, 29681144, 7868801, -6854661, -9423865, -12437364, -663000, -31111463, -16132436}, {25576264, -2703214, 7349804, -11814844, 16472782, 9300885, 3844789, 15725684, 171356, 6466918}, {23103977, 13316479, 9739013, -16149481, 817875, -15038942, 8965339, -14088058, -30714912, 16193877}, }, { {-33521811, 3180713, -2394130, 14003687, -16903474, -16270840, 17238398, 4729455, -18074513, 9256800}, {-25182317, -4174131, 32336398, 5036987, -21236817, 11360617, 22616405, 9761698, -19827198, 630305}, {-13720693, 2639453, -24237460, -7406481, 9494427, -5774029, -6554551, -15960994, -2449256, -14291300}, }, { {-3151181, -5046075, 9282714, 6866145, -31907062, -863023, -18940575, 15033784, 25105118, -7894876}, {-24326370, 15950226, -31801215, -14592823, -11662737, -5090925, 1573892, -2625887, 2198790, -15804619}, {-3099351, 10324967, -2241613, 7453183, -5446979, -2735503, -13812022, -16236442, -32461234, -12290683}, }, }; /* out = hash * p + s * B */ void KAMulPlusMulBase(GeE *out, const uint8_t hash[CRYPT_CURVE25519_KEYLEN], const GeE *p, const uint8_t s[CRYPT_CURVE25519_KEYLEN]) { SetExtendedBasePoint(out); GeE tmpP[8]; // stores p, 3p, 5p, 7p, 9p, 11p, 13p, 15p GeE doubleP; GeEPre preComputedP[8]; // stores p, 3p, 5p, 7p, 9p, 11p, 13p, 15p int8_t slideP[256]; int8_t slideS[256]; int32_t i; SlideReduce(slideP, 256, hash, CRYPT_CURVE25519_KEYLEN); SlideReduce(slideS, 256, s, CRYPT_CURVE25519_KEYLEN); CURVE25519_GE_COPY(tmpP[0], *p); CURVE25519_GE_COPY(doubleP, *p); PointToPrecompute(&preComputedP[0], &tmpP[0]); P1DoubleN(&doubleP, 1); for (i = 1; i < 8; i += 1) { // p, 3p, ....., 13p, 15p, total 8 PointAdd(&tmpP[i], &tmpP[i - 1], &doubleP); PointToPrecompute(&preComputedP[i], &tmpP[i]); } int32_t zeroCount = 0; i = 255; // 255 to 0 while (i >= 0 && slideP[i] == 0 && slideS[i] == 0) { i--; } for (; i >= 0; i--) { while (i >= 0 && slideP[i] == 0 && slideS[i] == 0) { zeroCount++; i--; } if (i < 0) { P1DoubleN(out, zeroCount); break; } else { P1DoubleN(out, zeroCount + 1); } zeroCount = 0; if (slideP[i] > 0) { PointAddPrecompute(out, out, &preComputedP[slideP[i] / 2]); // preComputedP[i] = (i * 2 + 1)P } else if (slideP[i] < 0) { PointSubPrecompute(out, out, &preComputedP[(-slideP[i]) / 2]); // preComputedP[i] = (i * 2 + 1)P } if (slideS[i] > 0) { GeAdd(out, &g_precomputedB[slideS[i] / 2]); // g_precomputedB[i] = (i * 2 + 1)P } else if (slideS[i] < 0) { GeSub(out, &g_precomputedB[(-slideS[i]) / 2]); // g_precomputedB[i] = (i * 2 + 1)P } } } #endif /* HITLS_CRYPTO_ED25519 */ #endif /* HITLS_CRYPTO_CURVE25519 */
2302_82127028/openHiTLS-examples_1556
crypto/curve25519/src/curve25519_op.c
C
unknown
60,542
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ /* Some of these codes are adapted from https://ed25519.cr.yp.to/software.html */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_CURVE25519 #include "curve25519_local.h" /* lookup table that computing y-x, y+x and 2dxy, with 512 ^ n B, n starts from 0 */ /* table is generated base on article "High-speed high-security signatures" */ static const GePre CURVE25519PRE_COMPUTE[32][8] = { { { {25967493, -14356035, 29566456, 3660896, -12694345, 4014787, 27544626, -11754271, -6079156, 2047605}, {-12545711, 934262, -2722910, 3049990, -727428, 9406986, 12720692, 5043384, 19500929, -15469378}, {-8738181, 4489570, 9688441, -14785194, 10184609, -12363380, 29287919, 11864899, -24514362, -4438546}, }, { {-12815894, -12976347, -21581243, 11784320, -25355658, -2750717, -11717903, -3814571, -358445, -10211303}, {-21703237, 6903825, 27185491, 6451973, -29577724, -9554005, -15616551, 11189268, -26829678, -5319081}, {26966642, 11152617, 32442495, 15396054, 14353839, -12752335, -3128826, -9541118, -15472047, -4166697}, }, { {15636291, -9688557, 24204773, -7912398, 616977, -16685262, 27787600, -14772189, 28944400, -1550024}, {16568933, 4717097, -11556148, -1102322, 15682896, -11807043, 16354577, -11775962, 7689662, 11199574}, {30464156, -5976125, -11779434, -15670865, 23220365, 15915852, 7512774, 10017326, -17749093, -9920357}, }, { {-17036878, 13921892, 10945806, -6033431, 27105052, -16084379, -28926210, 15006023, 3284568, -6276540}, {23599295, -8306047, -11193664, -7687416, 13236774, 10506355, 7464579, 9656445, 13059162, 10374397}, {7798556, 16710257, 3033922, 2874086, 28997861, 2835604, 32406664, -3839045, -641708, -101325}, }, { {10861363, 11473154, 27284546, 1981175, -30064349, 12577861, 32867885, 14515107, -15438304, 10819380}, {4708026, 6336745, 20377586, 9066809, -11272109, 6594696, -25653668, 12483688, -12668491, 5581306}, {19563160, 16186464, -29386857, 4097519, 10237984, -4348115, 28542350, 13850243, -23678021, -15815942}, }, { {-15371964, -12862754, 32573250, 4720197, -26436522, 5875511, -19188627, -15224819, -9818940, -12085777}, {-8549212, 109983, 15149363, 2178705, 22900618, 4543417, 3044240, -15689887, 1762328, 14866737}, {-18199695, -15951423, -10473290, 1707278, -17185920, 3916101, -28236412, 3959421, 27914454, 4383652}, }, { {5153746, 9909285, 1723747, -2777874, 30523605, 5516873, 19480852, 5230134, -23952439, -15175766}, {-30269007, -3463509, 7665486, 10083793, 28475525, 1649722, 20654025, 16520125, 30598449, 7715701}, {28881845, 14381568, 9657904, 3680757, -20181635, 7843316, -31400660, 1370708, 29794553, -1409300}, }, { {14499471, -2729599, -33191113, -4254652, 28494862, 14271267, 30290735, 10876454, -33154098, 2381726}, {-7195431, -2655363, -14730155, 462251, -27724326, 3941372, -6236617, 3696005, -32300832, 15351955}, {27431194, 8222322, 16448760, -3907995, -18707002, 11938355, -32961401, -2970515, 29551813, 10109425}, }, }, { { {-13657040, -13155431, -31283750, 11777098, 21447386, 6519384, -2378284, -1627556, 10092783, -4764171}, {27939166, 14210322, 4677035, 16277044, -22964462, -12398139, -32508754, 12005538, -17810127, 12803510}, {17228999, -15661624, -1233527, 300140, -1224870, -11714777, 30364213, -9038194, 18016357, 4397660}, }, { {-10958843, -7690207, 4776341, -14954238, 27850028, -15602212, -26619106, 14544525, -17477504, 982639}, {29253598, 15796703, -2863982, -9908884, 10057023, 3163536, 7332899, -4120128, -21047696, 9934963}, {5793303, 16271923, -24131614, -10116404, 29188560, 1206517, -14747930, 4559895, -30123922, -10897950}, }, { {-27643952, -11493006, 16282657, -11036493, 28414021, -15012264, 24191034, 4541697, -13338309, 5500568}, {12650548, -1497113, 9052871, 11355358, -17680037, -8400164, -17430592, 12264343, 10874051, 13524335}, {25556948, -3045990, 714651, 2510400, 23394682, -10415330, 33119038, 5080568, -22528059, 5376628}, }, { {-26088264, -4011052, -17013699, -3537628, -6726793, 1920897, -22321305, -9447443, 4535768, 1569007}, {-2255422, 14606630, -21692440, -8039818, 28430649, 8775819, -30494562, 3044290, 31848280, 12543772}, {-22028579, 2943893, -31857513, 6777306, 13784462, -4292203, -27377195, -2062731, 7718482, 14474653}, }, { {2385315, 2454213, -22631320, 46603, -4437935, -15680415, 656965, -7236665, 24316168, -5253567}, {13741529, 10911568, -33233417, -8603737, -20177830, -1033297, 33040651, -13424532, -20729456, 8321686}, {21060490, -2212744, 15712757, -4336099, 1639040, 10656336, 23845965, -11874838, -9984458, 608372}, }, { {-13672732, -15087586, -10889693, -7557059, -6036909, 11305547, 1123968, -6780577, 27229399, 23887}, {-23244140, -294205, -11744728, 14712571, -29465699, -2029617, 12797024, -6440308, -1633405, 16678954}, {-29500620, 4770662, -16054387, 14001338, 7830047, 9564805, -1508144, -4795045, -17169265, 4904953}, }, { {24059557, 14617003, 19037157, -15039908, 19766093, -14906429, 5169211, 16191880, 2128236, -4326833}, {-16981152, 4124966, -8540610, -10653797, 30336522, -14105247, -29806336, 916033, -6882542, -2986532}, {-22630907, 12419372, -7134229, -7473371, -16478904, 16739175, 285431, 2763829, 15736322, 4143876}, }, { {2379352, 11839345, -4110402, -5988665, 11274298, 794957, 212801, -14594663, 23527084, -16458268}, {33431127, -11130478, -17838966, -15626900, 8909499, 8376530, -32625340, 4087881, -15188911, -14416214}, {1767683, 7197987, -13205226, -2022635, -13091350, 448826, 5799055, 4357868, -4774191, -16323038}, }, }, { { {6721966, 13833823, -23523388, -1551314, 26354293, -11863321, 23365147, -3949732, 7390890, 2759800}, {4409041, 2052381, 23373853, 10530217, 7676779, -12885954, 21302353, -4264057, 1244380, -12919645}, {-4421239, 7169619, 4982368, -2957590, 30256825, -2777540, 14086413, 9208236, 15886429, 16489664}, }, { {1996075, 10375649, 14346367, 13311202, -6874135, -16438411, -13693198, 398369, -30606455, -712933}, {-25307465, 9795880, -2777414, 14878809, -33531835, 14780363, 13348553, 12076947, -30836462, 5113182}, {-17770784, 11797796, 31950843, 13929123, -25888302, 12288344, -30341101, -7336386, 13847711, 5387222}, }, { {-18582163, -3416217, 17824843, -2340966, 22744343, -10442611, 8763061, 3617786, -19600662, 10370991}, {20246567, -14369378, 22358229, -543712, 18507283, -10413996, 14554437, -8746092, 32232924, 16763880}, {9648505, 10094563, 26416693, 14745928, -30374318, -6472621, 11094161, 15689506, 3140038, -16510092}, }, { {-16160072, 5472695, 31895588, 4744994, 8823515, 10365685, -27224800, 9448613, -28774454, 366295}, {19153450, 11523972, -11096490, -6503142, -24647631, 5420647, 28344573, 8041113, 719605, 11671788}, {8678025, 2694440, -6808014, 2517372, 4964326, 11152271, -15432916, -15266516, 27000813, -10195553}, }, { {-15157904, 7134312, 8639287, -2814877, -7235688, 10421742, 564065, 5336097, 6750977, -14521026}, {11836410, -3979488, 26297894, 16080799, 23455045, 15735944, 1695823, -8819122, 8169720, 16220347}, {-18115838, 8653647, 17578566, -6092619, -8025777, -16012763, -11144307, -2627664, -5990708, -14166033}, }, { {-23308498, -10968312, 15213228, -10081214, -30853605, -11050004, 27884329, 2847284, 2655861, 1738395}, {-27537433, -14253021, -25336301, -8002780, -9370762, 8129821, 21651608, -3239336, -19087449, -11005278}, {1533110, 3437855, 23735889, 459276, 29970501, 11335377, 26030092, 5821408, 10478196, 8544890}, }, { {32173121, -16129311, 24896207, 3921497, 22579056, -3410854, 19270449, 12217473, 17789017, -3395995}, {-30552961, -2228401, -15578829, -10147201, 13243889, 517024, 15479401, -3853233, 30460520, 1052596}, {-11614875, 13323618, 32618793, 8175907, -15230173, 12596687, 27491595, -4612359, 3179268, -9478891}, }, { {31947069, -14366651, -4640583, -15339921, -15125977, -6039709, -14756777, -16411740, 19072640, -9511060}, {11685058, 11822410, 3158003, -13952594, 33402194, -4165066, 5977896, -5215017, 473099, 5040608}, {-20290863, 8198642, -27410132, 11602123, 1290375, -2799760, 28326862, 1721092, -19558642, -3131606}, }, }, { { {7881532, 10687937, 7578723, 7738378, -18951012, -2553952, 21820786, 8076149, -27868496, 11538389}, {-19935666, 3899861, 18283497, -6801568, -15728660, -11249211, 8754525, 7446702, -5676054, 5797016}, {-11295600, -3793569, -15782110, -7964573, 12708869, -8456199, 2014099, -9050574, -2369172, -5877341}, }, { {-22472376, -11568741, -27682020, 1146375, 18956691, 16640559, 1192730, -3714199, 15123619, 10811505}, {14352098, -3419715, -18942044, 10822655, 32750596, 4699007, -70363, 15776356, -28886779, -11974553}, {-28241164, -8072475, -4978962, -5315317, 29416931, 1847569, -20654173, -16484855, 4714547, -9600655}, }, { {15200332, 8368572, 19679101, 15970074, -31872674, 1959451, 24611599, -4543832, -11745876, 12340220}, {12876937, -10480056, 33134381, 6590940, -6307776, 14872440, 9613953, 8241152, 15370987, 9608631}, {-4143277, -12014408, 8446281, -391603, 4407738, 13629032, -7724868, 15866074, -28210621, -8814099}, }, { {26660628, -15677655, 8393734, 358047, -7401291, 992988, -23904233, 858697, 20571223, 8420556}, {14620715, 13067227, -15447274, 8264467, 14106269, 15080814, 33531827, 12516406, -21574435, -12476749}, {236881, 10476226, 57258, -14677024, 6472998, 2466984, 17258519, 7256740, 8791136, 15069930}, }, { {1276410, -9371918, 22949635, -16322807, -23493039, -5702186, 14711875, 4874229, -30663140, -2331391}, {5855666, 4990204, -13711848, 7294284, -7804282, 1924647, -1423175, -7912378, -33069337, 9234253}, {20590503, -9018988, 31529744, -7352666, -2706834, 10650548, 31559055, -11609587, 18979186, 13396066}, }, { {24474287, 4968103, 22267082, 4407354, 24063882, -8325180, -18816887, 13594782, 33514650, 7021958}, {-11566906, -6565505, -21365085, 15928892, -26158305, 4315421, -25948728, -3916677, -21480480, 12868082}, {-28635013, 13504661, 19988037, -2132761, 21078225, 6443208, -21446107, 2244500, -12455797, -8089383}, }, { {-30595528, 13793479, -5852820, 319136, -25723172, -6263899, 33086546, 8957937, -15233648, 5540521}, {-11630176, -11503902, -8119500, -7643073, 2620056, 1022908, -23710744, -1568984, -16128528, -14962807}, {23152971, 775386, 27395463, 14006635, -9701118, 4649512, 1689819, 892185, -11513277, -15205948}, }, { {9770129, 9586738, 26496094, 4324120, 1556511, -3550024, 27453819, 4763127, -19179614, 5867134}, {-32765025, 1927590, 31726409, -4753295, 23962434, -16019500, 27846559, 5931263, -29749703, -16108455}, {27461885, -2977536, 22380810, 1815854, -23033753, -3031938, 7283490, -15148073, -19526700, 7734629}, }, }, { { {-8010264, -9590817, -11120403, 6196038, 29344158, -13430885, 7585295, -3176626, 18549497, 15302069}, {-32658337, -6171222, -7672793, -11051681, 6258878, 13504381, 10458790, -6418461, -8872242, 8424746}, {24687205, 8613276, -30667046, -3233545, 1863892, -1830544, 19206234, 7134917, -11284482, -828919}, }, { {11334899, -9218022, 8025293, 12707519, 17523892, -10476071, 10243738, -14685461, -5066034, 16498837}, {8911542, 6887158, -9584260, -6958590, 11145641, -9543680, 17303925, -14124238, 6536641, 10543906}, {-28946384, 15479763, -17466835, 568876, -1497683, 11223454, -2669190, -16625574, -27235709, 8876771}, }, { {-25742899, -12566864, -15649966, -846607, -33026686, -796288, -33481822, 15824474, -604426, -9039817}, {10330056, 70051, 7957388, -9002667, 9764902, 15609756, 27698697, -4890037, 1657394, 3084098}, {10477963, -7470260, 12119566, -13250805, 29016247, -5365589, 31280319, 14396151, -30233575, 15272409}, }, { {-12288309, 3169463, 28813183, 16658753, 25116432, -5630466, -25173957, -12636138, -25014757, 1950504}, {-26180358, 9489187, 11053416, -14746161, -31053720, 5825630, -8384306, -8767532, 15341279, 8373727}, {28685821, 7759505, -14378516, -12002860, -31971820, 4079242, 298136, -10232602, -2878207, 15190420}, }, { {-32932876, 13806336, -14337485, -15794431, -24004620, 10940928, 8669718, 2742393, -26033313, -6875003}, {-1580388, -11729417, -25979658, -11445023, -17411874, -10912854, 9291594, -16247779, -12154742, 6048605}, {-30305315, 14843444, 1539301, 11864366, 20201677, 1900163, 13934231, 5128323, 11213262, 9168384}, }, { {-26280513, 11007847, 19408960, -940758, -18592965, -4328580, -5088060, -11105150, 20470157, -16398701}, {-23136053, 9282192, 14855179, -15390078, -7362815, -14408560, -22783952, 14461608, 14042978, 5230683}, {29969567, -2741594, -16711867, -8552442, 9175486, -2468974, 21556951, 3506042, -5933891, -12449708}, }, { {-3144746, 8744661, 19704003, 4581278, -20430686, 6830683, -21284170, 8971513, -28539189, 15326563}, {-19464629, 10110288, -17262528, -3503892, -23500387, 1355669, -15523050, 15300988, -20514118, 9168260}, {-5353335, 4488613, -23803248, 16314347, 7780487, -15638939, -28948358, 9601605, 33087103, -9011387}, }, { {-19443170, -15512900, -20797467, -12445323, -29824447, 10229461, -27444329, -15000531, -5996870, 15664672}, {23294591, -16632613, -22650781, -8470978, 27844204, 11461195, 13099750, -2460356, 18151676, 13417686}, {-24722913, -4176517, -31150679, 5988919, -26858785, 6685065, 1661597, -12551441, 15271676, -15452665}, }, }, { { {11433042, -13228665, 8239631, -5279517, -1985436, -725718, -18698764, 2167544, -6921301, -13440182}, {-31436171, 15575146, 30436815, 12192228, -22463353, 9395379, -9917708, -8638997, 12215110, 12028277}, {14098400, 6555944, 23007258, 5757252, -15427832, -12950502, 30123440, 4617780, -16900089, -655628}, }, { {-4026201, -15240835, 11893168, 13718664, -14809462, 1847385, -15819999, 10154009, 23973261, -12684474}, {-26531820, -3695990, -1908898, 2534301, -31870557, -16550355, 18341390, -11419951, 32013174, -10103539}, {-25479301, 10876443, -11771086, -14625140, -12369567, 1838104, 21911214, 6354752, 4425632, -837822}, }, { {-10433389, -14612966, 22229858, -3091047, -13191166, 776729, -17415375, -12020462, 4725005, 14044970}, {19268650, -7304421, 1555349, 8692754, -21474059, -9910664, 6347390, -1411784, -19522291, -16109756}, {-24864089, 12986008, -10898878, -5558584, -11312371, -148526, 19541418, 8180106, 9282262, 10282508}, }, { {-26205082, 4428547, -8661196, -13194263, 4098402, -14165257, 15522535, 8372215, 5542595, -10702683}, {-10562541, 14895633, 26814552, -16673850, -17480754, -2489360, -2781891, 6993761, -18093885, 10114655}, {-20107055, -929418, 31422704, 10427861, -7110749, 6150669, -29091755, -11529146, 25953725, -106158}, }, { {-4234397, -8039292, -9119125, 3046000, 2101609, -12607294, 19390020, 6094296, -3315279, 12831125}, {-15998678, 7578152, 5310217, 14408357, -33548620, -224739, 31575954, 6326196, 7381791, -2421839}, {-20902779, 3296811, 24736065, -16328389, 18374254, 7318640, 6295303, 8082724, -15362489, 12339664}, }, { {27724736, 2291157, 6088201, -14184798, 1792727, 5857634, 13848414, 15768922, 25091167, 14856294}, {-18866652, 8331043, 24373479, 8541013, -701998, -9269457, 12927300, -12695493, -22182473, -9012899}, {-11423429, -5421590, 11632845, 3405020, 30536730, -11674039, -27260765, 13866390, 30146206, 9142070}, }, { {3924129, -15307516, -13817122, -10054960, 12291820, -668366, -27702774, 9326384, -8237858, 4171294}, {-15921940, 16037937, 6713787, 16606682, -21612135, 2790944, 26396185, 3731949, 345228, -5462949}, {-21327538, 13448259, 25284571, 1143661, 20614966, -8849387, 2031539, -12391231, -16253183, -13582083}, }, { {31016211, -16722429, 26371392, -14451233, -5027349, 14854137, 17477601, 3842657, 28012650, -16405420}, {-5075835, 9368966, -8562079, -4600902, -15249953, 6970560, -9189873, 16292057, -8867157, 3507940}, {29439664, 3537914, 23333589, 6997794, -17555561, -11018068, -15209202, -15051267, -9164929, 6580396}, }, }, { { {-12185861, -7679788, 16438269, 10826160, -8696817, -6235611, 17860444, -9273846, -2095802, 9304567}, {20714564, -4336911, 29088195, 7406487, 11426967, -5095705, 14792667, -14608617, 5289421, -477127}, {-16665533, -10650790, -6160345, -13305760, 9192020, -1802462, 17271490, 12349094, 26939669, -3752294}, }, { {-12889898, 9373458, 31595848, 16374215, 21471720, 13221525, -27283495, -12348559, -3698806, 117887}, {22263325, -6560050, 3984570, -11174646, -15114008, -566785, 28311253, 5358056, -23319780, 541964}, {16259219, 3261970, 2309254, -15534474, -16885711, -4581916, 24134070, -16705829, -13337066, -13552195}, }, { {9378160, -13140186, -22845982, -12745264, 28198281, -7244098, -2399684, -717351, 690426, 14876244}, {24977353, -314384, -8223969, -13465086, 28432343, -1176353, -13068804, -12297348, -22380984, 6618999}, {-1538174, 11685646, 12944378, 13682314, -24389511, -14413193, 8044829, -13817328, 32239829, -5652762}, }, { {-18603066, 4762990, -926250, 8885304, -28412480, -3187315, 9781647, -10350059, 32779359, 5095274}, {-33008130, -5214506, -32264887, -3685216, 9460461, -9327423, -24601656, 14506724, 21639561, -2630236}, {-16400943, -13112215, 25239338, 15531969, 3987758, -4499318, -1289502, -6863535, 17874574, 558605}, }, { {-13600129, 10240081, 9171883, 16131053, -20869254, 9599700, 33499487, 5080151, 2085892, 5119761}, {-22205145, -2519528, -16381601, 414691, -25019550, 2170430, 30634760, -8363614, -31999993, -5759884}, {-6845704, 15791202, 8550074, -1312654, 29928809, -12092256, 27534430, -7192145, -22351378, 12961482}, }, { {-24492060, -9570771, 10368194, 11582341, -23397293, -2245287, 16533930, 8206996, -30194652, -5159638}, {-11121496, -3382234, 2307366, 6362031, -135455, 8868177, -16835630, 7031275, 7589640, 8945490}, {-32152748, 8917967, 6661220, -11677616, -1192060, -15793393, 7251489, -11182180, 24099109, -14456170}, }, { {5019558, -7907470, 4244127, -14714356, -26933272, 6453165, -19118182, -13289025, -6231896, -10280736}, {10853594, 10721687, 26480089, 5861829, -22995819, 1972175, -1866647, -10557898, -3363451, -6441124}, {-17002408, 5906790, 221599, -6563147, 7828208, -13248918, 24362661, -2008168, -13866408, 7421392}, }, { {8139927, -6546497, 32257646, -5890546, 30375719, 1886181, -21175108, 15441252, 28826358, -4123029}, {6267086, 9695052, 7709135, -16603597, -32869068, -1886135, 14795160, -7840124, 13746021, -1742048}, {28584902, 7787108, -6732942, -15050729, 22846041, -7571236, -3181936, -363524, 4771362, -8419958}, }, }, { { {24949256, 6376279, -27466481, -8174608, -18646154, -9930606, 33543569, -12141695, 3569627, 11342593}, {26514989, 4740088, 27912651, 3697550, 19331575, -11472339, 6809886, 4608608, 7325975, -14801071}, {-11618399, -14554430, -24321212, 7655128, -1369274, 5214312, -27400540, 10258390, -17646694, -8186692}, }, { {11431204, 15823007, 26570245, 14329124, 18029990, 4796082, -31446179, 15580664, 9280358, -3973687}, {-160783, -10326257, -22855316, -4304997, -20861367, -13621002, -32810901, -11181622, -15545091, 4387441}, {-20799378, 12194512, 3937617, -5805892, -27154820, 9340370, -24513992, 8548137, 20617071, -7482001}, }, { {-938825, -3930586, -8714311, 16124718, 24603125, -6225393, -13775352, -11875822, 24345683, 10325460}, {-19855277, -1568885, -22202708, 8714034, 14007766, 6928528, 16318175, -1010689, 4766743, 3552007}, {-21751364, -16730916, 1351763, -803421, -4009670, 3950935, 3217514, 14481909, 10988822, -3994762}, }, { {15564307, -14311570, 3101243, 5684148, 30446780, -8051356, 12677127, -6505343, -8295852, 13296005}, {-9442290, 6624296, -30298964, -11913677, -4670981, -2057379, 31521204, 9614054, -30000824, 12074674}, {4771191, -135239, 14290749, -13089852, 27992298, 14998318, -1413936, -1556716, 29832613, -16391035}, }, { {7064884, -7541174, -19161962, -5067537, -18891269, -2912736, 25825242, 5293297, -27122660, 13101590}, {-2298563, 2439670, -7466610, 1719965, -27267541, -16328445, 32512469, -5317593, -30356070, -4190957}, {-30006540, 10162316, -33180176, 3981723, -16482138, -13070044, 14413974, 9515896, 19568978, 9628812}, }, { {33053803, 199357, 15894591, 1583059, 27380243, -4580435, -17838894, -6106839, -6291786, 3437740}, {-18978877, 3884493, 19469877, 12726490, 15913552, 13614290, -22961733, 70104, 7463304, 4176122}, {-27124001, 10659917, 11482427, -16070381, 12771467, -6635117, -32719404, -5322751, 24216882, 5944158}, }, { {8894125, 7450974, -2664149, -9765752, -28080517, -12389115, 19345746, 14680796, 11632993, 5847885}, {26942781, -2315317, 9129564, -4906607, 26024105, 11769399, -11518837, 6367194, -9727230, 4782140}, {19916461, -4828410, -22910704, -11414391, 25606324, -5972441, 33253853, 8220911, 6358847, -1873857}, }, { {801428, -2081702, 16569428, 11065167, 29875704, 96627, 7908388, -4480480, -13538503, 1387155}, {19646058, 5720633, -11416706, 12814209, 11607948, 12749789, 14147075, 15156355, -21866831, 11835260}, {19299512, 1155910, 28703737, 14890794, 2925026, 7269399, 26121523, 15467869, -26560550, 5052483}, }, }, { { {-3017432, 10058206, 1980837, 3964243, 22160966, 12322533, -6431123, -12618185, 12228557, -7003677}, {32944382, 14922211, -22844894, 5188528, 21913450, -8719943, 4001465, 13238564, -6114803, 8653815}, {22865569, -4652735, 27603668, -12545395, 14348958, 8234005, 24808405, 5719875, 28483275, 2841751}, }, { {-16420968, -1113305, -327719, -12107856, 21886282, -15552774, -1887966, -315658, 19932058, -12739203}, {-11656086, 10087521, -8864888, -5536143, -19278573, -3055912, 3999228, 13239134, -4777469, -13910208}, {1382174, -11694719, 17266790, 9194690, -13324356, 9720081, 20403944, 11284705, -14013818, 3093230}, }, { {16650921, -11037932, -1064178, 1570629, -8329746, 7352753, -302424, 16271225, -24049421, -6691850}, {-21911077, -5927941, -4611316, -5560156, -31744103, -10785293, 24123614, 15193618, -21652117, -16739389}, {-9935934, -4289447, -25279823, 4372842, 2087473, 10399484, 31870908, 14690798, 17361620, 11864968}, }, { {-11307610, 6210372, 13206574, 5806320, -29017692, -13967200, -12331205, -7486601, -25578460, -16240689}, {14668462, -12270235, 26039039, 15305210, 25515617, 4542480, 10453892, 6577524, 9145645, -6443880}, {5974874, 3053895, -9433049, -10385191, -31865124, 3225009, -7972642, 3936128, -5652273, -3050304}, }, { {30625386, -4729400, -25555961, -12792866, -20484575, 7695099, 17097188, -16303496, -27999779, 1803632}, {-3553091, 9865099, -5228566, 4272701, -5673832, -16689700, 14911344, 12196514, -21405489, 7047412}, {20093277, 9920966, -11138194, -5343857, 13161587, 12044805, -32856851, 4124601, -32343828, -10257566}, }, { {-20788824, 14084654, -13531713, 7842147, 19119038, -13822605, 4752377, -8714640, -21679658, 2288038}, {-26819236, -3283715, 29965059, 3039786, -14473765, 2540457, 29457502, 14625692, -24819617, 12570232}, {-1063558, -11551823, 16920318, 12494842, 1278292, -5869109, -21159943, -3498680, -11974704, 4724943}, }, { {17960970, -11775534, -4140968, -9702530, -8876562, -1410617, -12907383, -8659932, -29576300, 1903856}, {23134274, -14279132, -10681997, -1611936, 20684485, 15770816, -12989750, 3190296, 26955097, 14109738}, {15308788, 5320727, -30113809, -14318877, 22902008, 7767164, 29425325, -11277562, 31960942, 11934971}, }, { {-27395711, 8435796, 4109644, 12222639, -24627868, 14818669, 20638173, 4875028, 10491392, 1379718}, {-13159415, 9197841, 3875503, -8936108, -1383712, -5879801, 33518459, 16176658, 21432314, 12180697}, {-11787308, 11500838, 13787581, -13832590, -22430679, 10140205, 1465425, 12689540, -10301319, -13872883}, }, }, { { {5414091, -15386041, -21007664, 9643570, 12834970, 1186149, -2622916, -1342231, 26128231, 6032912}, {-26337395, -13766162, 32496025, -13653919, 17847801, -12669156, 3604025, 8316894, -25875034, -10437358}, {3296484, 6223048, 24680646, -12246460, -23052020, 5903205, -8862297, -4639164, 12376617, 3188849}, }, { {29190488, -14659046, 27549113, -1183516, 3520066, -10697301, 32049515, -7309113, -16109234, -9852307}, {-14744486, -9309156, 735818, -598978, -20407687, -5057904, 25246078, -15795669, 18640741, -960977}, {-6928835, -16430795, 10361374, 5642961, 4910474, 12345252, -31638386, -494430, 10530747, 1053335}, }, { {-29265967, -14186805, -13538216, -12117373, -19457059, -10655384, -31462369, -2948985, 24018831, 15026644}, {-22592535, -3145277, -2289276, 5953843, -13440189, 9425631, 25310643, 13003497, -2314791, -15145616}, {-27419985, -603321, -8043984, -1669117, -26092265, 13987819, -27297622, 187899, -23166419, -2531735}, }, { {-21744398, -13810475, 1844840, 5021428, -10434399, -15911473, 9716667, 16266922, -5070217, 726099}, {29370922, -6053998, 7334071, -15342259, 9385287, 2247707, -13661962, -4839461, 30007388, -15823341}, {-936379, 16086691, 23751945, -543318, -1167538, -5189036, 9137109, 730663, 9835848, 4555336}, }, { {-23376435, 1410446, -22253753, -12899614, 30867635, 15826977, 17693930, 544696, -11985298, 12422646}, {31117226, -12215734, -13502838, 6561947, -9876867, -12757670, -5118685, -4096706, 29120153, 13924425}, {-17400879, -14233209, 19675799, -2734756, -11006962, -5858820, -9383939, -11317700, 7240931, -237388}, }, { {-31361739, -11346780, -15007447, -5856218, -22453340, -12152771, 1222336, 4389483, 3293637, -15551743}, {-16684801, -14444245, 11038544, 11054958, -13801175, -3338533, -24319580, 7733547, 12796905, -6335822}, {-8759414, -10817836, -25418864, 10783769, -30615557, -9746811, -28253339, 3647836, 3222231, -11160462}, }, { {18606113, 1693100, -25448386, -15170272, 4112353, 10045021, 23603893, -2048234, -7550776, 2484985}, {9255317, -3131197, -12156162, -1004256, 13098013, -9214866, 16377220, -2102812, -19802075, -3034702}, {-22729289, 7496160, -5742199, 11329249, 19991973, -3347502, -31718148, 9936966, -30097688, -10618797}, }, { {21878590, -5001297, 4338336, 13643897, -3036865, 13160960, 19708896, 5415497, -7360503, -4109293}, {27736861, 10103576, 12500508, 8502413, -3413016, -9633558, 10436918, -1550276, -23659143, -8132100}, {19492550, -12104365, -29681976, -852630, -3208171, 12403437, 30066266, 8367329, 13243957, 8709688}, }, }, { { {12015105, 2801261, 28198131, 10151021, 24818120, -4743133, -11194191, -5645734, 5150968, 7274186}, {2831366, -12492146, 1478975, 6122054, 23825128, -12733586, 31097299, 6083058, 31021603, -9793610}, {-2529932, -2229646, 445613, 10720828, -13849527, -11505937, -23507731, 16354465, 15067285, -14147707}, }, { {7840942, 14037873, -33364863, 15934016, -728213, -3642706, 21403988, 1057586, -19379462, -12403220}, {915865, -16469274, 15608285, -8789130, -24357026, 6060030, -17371319, 8410997, -7220461, 16527025}, {32922597, -556987, 20336074, -16184568, 10903705, -5384487, 16957574, 52992, 23834301, 6588044}, }, { {32752030, 11232950, 3381995, -8714866, 22652988, -10744103, 17159699, 16689107, -20314580, -1305992}, {-4689649, 9166776, -25710296, -10847306, 11576752, 12733943, 7924251, -2752281, 1976123, -7249027}, {21251222, 16309901, -2983015, -6783122, 30810597, 12967303, 156041, -3371252, 12331345, -8237197}, }, { {8651614, -4477032, -16085636, -4996994, 13002507, 2950805, 29054427, -5106970, 10008136, -4667901}, {31486080, 15114593, -14261250, 12951354, 14369431, -7387845, 16347321, -13662089, 8684155, -10532952}, {19443825, 11385320, 24468943, -9659068, -23919258, 2187569, -26263207, -6086921, 31316348, 14219878}, }, { {-28594490, 1193785, 32245219, 11392485, 31092169, 15722801, 27146014, 6992409, 29126555, 9207390}, {32382935, 1110093, 18477781, 11028262, -27411763, -7548111, -4980517, 10843782, -7957600, -14435730}, {2814918, 7836403, 27519878, -7868156, -20894015, -11553689, -21494559, 8550130, 28346258, 1994730}, }, { {-19578299, 8085545, -14000519, -3948622, 2785838, -16231307, -19516951, 7174894, 22628102, 8115180}, {-30405132, 955511, -11133838, -15078069, -32447087, -13278079, -25651578, 3317160, -9943017, 930272}, {-15303681, -6833769, 28856490, 1357446, 23421993, 1057177, 24091212, -1388970, -22765376, -10650715}, }, { {-22751231, -5303997, -12907607, -12768866, -15811511, -7797053, -14839018, -16554220, -1867018, 8398970}, {-31969310, 2106403, -4736360, 1362501, 12813763, 16200670, 22981545, -6291273, 18009408, -15772772}, {-17220923, -9545221, -27784654, 14166835, 29815394, 7444469, 29551787, -3727419, 19288549, 1325865}, }, { {15100157, -15835752, -23923978, -1005098, -26450192, 15509408, 12376730, -3479146, 33166107, -8042750}, {20909231, 13023121, -9209752, 16251778, -5778415, -8094914, 12412151, 10018715, 2213263, -13878373}, {32529814, -11074689, 30361439, -16689753, -9135940, 1513226, 22922121, 6382134, -5766928, 8371348}, }, }, { { {9923462, 11271500, 12616794, 3544722, -29998368, -1721626, 12891687, -8193132, -26442943, 10486144}, {-22597207, -7012665, 8587003, -8257861, 4084309, -12970062, 361726, 2610596, -23921530, -11455195}, {5408411, -1136691, -4969122, 10561668, 24145918, 14240566, 31319731, -4235541, 19985175, -3436086}, }, { {-13994457, 16616821, 14549246, 3341099, 32155958, 13648976, -17577068, 8849297, 65030, 8370684}, {-8320926, -12049626, 31204563, 5839400, -20627288, -1057277, -19442942, 6922164, 12743482, -9800518}, {-2361371, 12678785, 28815050, 4759974, -23893047, 4884717, 23783145, 11038569, 18800704, 255233}, }, { {-5269658, -1773886, 13957886, 7990715, 23132995, 728773, 13393847, 9066957, 19258688, -14753793}, {-2936654, -10827535, -10432089, 14516793, -3640786, 4372541, -31934921, 2209390, -1524053, 2055794}, {580882, 16705327, 5468415, -2683018, -30926419, -14696000, -7203346, -8994389, -30021019, 7394435}, }, { {23838809, 1822728, -15738443, 15242727, 8318092, -3733104, -21672180, -3492205, -4821741, 14799921}, {13345610, 9759151, 3371034, -16137791, 16353039, 8577942, 31129804, 13496856, -9056018, 7402518}, {2286874, -4435931, -20042458, -2008336, -13696227, 5038122, 11006906, -15760352, 8205061, 1607563}, }, { {14414086, -8002132, 3331830, -3208217, 22249151, -5594188, 18364661, -2906958, 30019587, -9029278}, {-27688051, 1585953, -10775053, 931069, -29120221, -11002319, -14410829, 12029093, 9944378, 8024}, {4368715, -3709630, 29874200, -15022983, -20230386, -11410704, -16114594, -999085, -8142388, 5640030}, }, { {10299610, 13746483, 11661824, 16234854, 7630238, 5998374, 9809887, -16694564, 15219798, -14327783}, {27425505, -5719081, 3055006, 10660664, 23458024, 595578, -15398605, -1173195, -18342183, 9742717}, {6744077, 2427284, 26042789, 2720740, -847906, 1118974, 32324614, 7406442, 12420155, 1994844}, }, { {14012521, -5024720, -18384453, -9578469, -26485342, -3936439, -13033478, -10909803, 24319929, -6446333}, {16412690, -4507367, 10772641, 15929391, -17068788, -4658621, 10555945, -10484049, -30102368, -4739048}, {22397382, -7767684, -9293161, -12792868, 17166287, -9755136, -27333065, 6199366, 21880021, -12250760}, }, { {-4283307, 5368523, -31117018, 8163389, -30323063, 3209128, 16557151, 8890729, 8840445, 4957760}, {-15447727, 709327, -6919446, -10870178, -29777922, 6522332, -21720181, 12130072, -14796503, 5005757}, {-2114751, -14308128, 23019042, 15765735, -25269683, 6002752, 10183197, -13239326, -16395286, -2176112}, }, }, { { {-19025756, 1632005, 13466291, -7995100, -23640451, 16573537, -32013908, -3057104, 22208662, 2000468}, {3065073, -1412761, -25598674, -361432, -17683065, -5703415, -8164212, 11248527, -3691214, -7414184}, {10379208, -6045554, 8877319, 1473647, -29291284, -12507580, 16690915, 2553332, -3132688, 16400289}, }, { {15716668, 1254266, -18472690, 7446274, -8448918, 6344164, -22097271, -7285580, 26894937, 9132066}, {24158887, 12938817, 11085297, -8177598, -28063478, -4457083, -30576463, 64452, -6817084, -2692882}, {13488534, 7794716, 22236231, 5989356, 25426474, -12578208, 2350710, -3418511, -4688006, 2364226}, }, { {16335052, 9132434, 25640582, 6678888, 1725628, 8517937, -11807024, -11697457, 15445875, -7798101}, {29004207, -7867081, 28661402, -640412, -12794003, -7943086, 31863255, -4135540, -278050, -15759279}, {-6122061, -14866665, -28614905, 14569919, -10857999, -3591829, 10343412, -6976290, -29828287, -10815811}, }, { {27081650, 3463984, 14099042, -4517604, 1616303, -6205604, 29542636, 15372179, 17293797, 960709}, {20263915, 11434237, -5765435, 11236810, 13505955, -10857102, -16111345, 6493122, -19384511, 7639714}, {-2830798, -14839232, 25403038, -8215196, -8317012, -16173699, 18006287, -16043750, 29994677, -15808121}, }, { {9769828, 5202651, -24157398, -13631392, -28051003, -11561624, -24613141, -13860782, -31184575, 709464}, {12286395, 13076066, -21775189, -1176622, -25003198, 4057652, -32018128, -8890874, 16102007, 13205847}, {13733362, 5599946, 10557076, 3195751, -5557991, 8536970, -25540170, 8525972, 10151379, 10394400}, }, { {4024660, -16137551, 22436262, 12276534, -9099015, -2686099, 19698229, 11743039, -33302334, 8934414}, {-15879800, -4525240, -8580747, -2934061, 14634845, -698278, -9449077, 3137094, -11536886, 11721158}, {17555939, -5013938, 8268606, 2331751, -22738815, 9761013, 9319229, 8835153, -9205489, -1280045}, }, { {-461409, -7830014, 20614118, 16688288, -7514766, -4807119, 22300304, 505429, 6108462, -6183415}, {-5070281, 12367917, -30663534, 3234473, 32617080, -8422642, 29880583, -13483331, -26898490, -7867459}, {-31975283, 5726539, 26934134, 10237677, -3173717, -605053, 24199304, 3795095, 7592688, -14992079}, }, { {21594432, -14964228, 17466408, -4077222, 32537084, 2739898, 6407723, 12018833, -28256052, 4298412}, {-20650503, -11961496, -27236275, 570498, 3767144, -1717540, 13891942, -1569194, 13717174, 10805743}, {-14676630, -15644296, 15287174, 11927123, 24177847, -8175568, -796431, 14860609, -26938930, -5863836}, }, }, { { {12962541, 5311799, -10060768, 11658280, 18855286, -7954201, 13286263, -12808704, -4381056, 9882022}, {18512079, 11319350, -20123124, 15090309, 18818594, 5271736, -22727904, 3666879, -23967430, -3299429}, {-6789020, -3146043, 16192429, 13241070, 15898607, -14206114, -10084880, -6661110, -2403099, 5276065}, }, { {30169808, -5317648, 26306206, -11750859, 27814964, 7069267, 7152851, 3684982, 1449224, 13082861}, {10342826, 3098505, 2119311, 193222, 25702612, 12233820, 23697382, 15056736, -21016438, -8202000}, {-33150110, 3261608, 22745853, 7948688, 19370557, -15177665, -26171976, 6482814, -10300080, -11060101}, }, { {32869458, -5408545, 25609743, 15678670, -10687769, -15471071, 26112421, 2521008, -22664288, 6904815}, {29506923, 4457497, 3377935, -9796444, -30510046, 12935080, 1561737, 3841096, -29003639, -6657642}, {10340844, -6630377, -18656632, -2278430, 12621151, -13339055, 30878497, -11824370, -25584551, 5181966}, }, { {25940115, -12658025, 17324188, -10307374, -8671468, 15029094, 24396252, -16450922, -2322852, -12388574}, {-21765684, 9916823, -1300409, 4079498, -1028346, 11909559, 1782390, 12641087, 20603771, -6561742}, {-18882287, -11673380, 24849422, 11501709, 13161720, -4768874, 1925523, 11914390, 4662781, 7820689}, }, { {12241050, -425982, 8132691, 9393934, 32846760, -1599620, 29749456, 12172924, 16136752, 15264020}, {-10349955, -14680563, -8211979, 2330220, -17662549, -14545780, 10658213, 6671822, 19012087, 3772772}, {3753511, -3421066, 10617074, 2028709, 14841030, -6721664, 28718732, -15762884, 20527771, 12988982}, }, { {-14822485, -5797269, -3707987, 12689773, -898983, -10914866, -24183046, -10564943, 3299665, -12424953}, {-16777703, -15253301, -9642417, 4978983, 3308785, 8755439, 6943197, 6461331, -25583147, 8991218}, {-17226263, 1816362, -1673288, -6086439, 31783888, -8175991, -32948145, 7417950, -30242287, 1507265}, }, { {29692663, 6829891, -10498800, 4334896, 20945975, -11906496, -28887608, 8209391, 14606362, -10647073}, {-3481570, 8707081, 32188102, 5672294, 22096700, 1711240, -33020695, 9761487, 4170404, -2085325}, {-11587470, 14855945, -4127778, -1531857, -26649089, 15084046, 22186522, 16002000, -14276837, -8400798}, }, { {-4811456, 13761029, -31703877, -2483919, -3312471, 7869047, -7113572, -9620092, 13240845, 10965870}, {-7742563, -8256762, -14768334, -13656260, -23232383, 12387166, 4498947, 14147411, 29514390, 4302863}, {-13413405, -12407859, 20757302, -13801832, 14785143, 8976368, -5061276, -2144373, 17846988, -13971927}, }, }, { { {-2244452, -754728, -4597030, -1066309, -6247172, 1455299, -21647728, -9214789, -5222701, 12650267}, {-9906797, -16070310, 21134160, 12198166, -27064575, 708126, 387813, 13770293, -19134326, 10958663}, {22470984, 12369526, 23446014, -5441109, -21520802, -9698723, -11772496, -11574455, -25083830, 4271862}, }, { {-25169565, -10053642, -19909332, 15361595, -5984358, 2159192, 75375, -4278529, -32526221, 8469673}, {15854970, 4148314, -8893890, 7259002, 11666551, 13824734, -30531198, 2697372, 24154791, -9460943}, {15446137, -15806644, 29759747, 14019369, 30811221, -9610191, -31582008, 12840104, 24913809, 9815020}, }, { {-4709286, -5614269, -31841498, -12288893, -14443537, 10799414, -9103676, 13438769, 18735128, 9466238}, {11933045, 9281483, 5081055, -5183824, -2628162, -4905629, -7727821, -10896103, -22728655, 16199064}, {14576810, 379472, -26786533, -8317236, -29426508, -10812974, -102766, 1876699, 30801119, 2164795}, }, { {15995086, 3199873, 13672555, 13712240, -19378835, -4647646, -13081610, -15496269, -13492807, 1268052}, {-10290614, -3659039, -3286592, 10948818, 23037027, 3794475, -3470338, -12600221, -17055369, 3565904}, {29210088, -9419337, -5919792, -4952785, 10834811, -13327726, -16512102, -10820713, -27162222, -14030531}, }, { {-13161890, 15508588, 16663704, -8156150, -28349942, 9019123, -29183421, -3769423, 2244111, -14001979}, {-5152875, -3800936, -9306475, -6071583, 16243069, 14684434, -25673088, -16180800, 13491506, 4641841}, {10813417, 643330, -19188515, -728916, 30292062, -16600078, 27548447, -7721242, 14476989, -12767431}, }, { {10292079, 9984945, 6481436, 8279905, -7251514, 7032743, 27282937, -1644259, -27912810, 12651324}, {-31185513, -813383, 22271204, 11835308, 10201545, 15351028, 17099662, 3988035, 21721536, -3148940}, {10202177, -6545839, -31373232, -9574638, -32150642, -8119683, -12906320, 3852694, 13216206, 14842320}, }, { {-15815640, -10601066, -6538952, -7258995, -6984659, -6581778, -31500847, 13765824, -27434397, 9900184}, {14465505, -13833331, -32133984, -14738873, -27443187, 12990492, 33046193, 15796406, -7051866, -8040114}, {30924417, -8279620, 6359016, -12816335, 16508377, 9071735, -25488601, 15413635, 9524356, -7018878}, }, { {12274201, -13175547, 32627641, -1785326, 6736625, 13267305, 5237659, -5109483, 15663516, 4035784}, {-2951309, 8903985, 17349946, 601635, -16432815, -4612556, -13732739, -15889334, -22258478, 4659091}, {-16916263, -4952973, -30393711, -15158821, 20774812, 15897498, 5736189, 15026997, -2178256, -13455585}, }, }, { { {-8858980, -2219056, 28571666, -10155518, -474467, -10105698, -3801496, 278095, 23440562, -290208}, {10226241, -5928702, 15139956, 120818, -14867693, 5218603, 32937275, 11551483, -16571960, -7442864}, {17932739, -12437276, -24039557, 10749060, 11316803, 7535897, 22503767, 5561594, -3646624, 3898661}, }, { {7749907, -969567, -16339731, -16464, -25018111, 15122143, -1573531, 7152530, 21831162, 1245233}, {26958459, -14658026, 4314586, 8346991, -5677764, 11960072, -32589295, -620035, -30402091, -16716212}, {-12165896, 9166947, 33491384, 13673479, 29787085, 13096535, 6280834, 14587357, -22338025, 13987525}, }, { {-24349909, 7778775, 21116000, 15572597, -4833266, -5357778, -4300898, -5124639, -7469781, -2858068}, {9681908, -6737123, -31951644, 13591838, -6883821, 386950, 31622781, 6439245, -14581012, 4091397}, {-8426427, 1470727, -28109679, -1596990, 3978627, -5123623, -19622683, 12092163, 29077877, -14741988}, }, { {5269168, -6859726, -13230211, -8020715, 25932563, 1763552, -5606110, -5505881, -20017847, 2357889}, {32264008, -15407652, -5387735, -1160093, -2091322, -3946900, 23104804, -12869908, 5727338, 189038}, {14609123, -8954470, -6000566, -16622781, -14577387, -7743898, -26745169, 10942115, -25888931, -14884697}, }, { {20513500, 5557931, -15604613, 7829531, 26413943, -2019404, -21378968, 7471781, 13913677, -5137875}, {-25574376, 11967826, 29233242, 12948236, -6754465, 4713227, -8940970, 14059180, 12878652, 8511905}, {-25656801, 3393631, -2955415, -7075526, -2250709, 9366908, -30223418, 6812974, 5568676, -3127656}, }, { {11630004, 12144454, 2116339, 13606037, 27378885, 15676917, -17408753, -13504373, -14395196, 8070818}, {27117696, -10007378, -31282771, -5570088, 1127282, 12772488, -29845906, 10483306, -11552749, -1028714}, {10637467, -5688064, 5674781, 1072708, -26343588, -6982302, -1683975, 9177853, -27493162, 15431203}, }, { {20525145, 10892566, -12742472, 12779443, -29493034, 16150075, -28240519, 14943142, -15056790, -7935931}, {-30024462, 5626926, -551567, -9981087, 753598, 11981191, 25244767, -3239766, -3356550, 9594024}, {-23752644, 2636870, -5163910, -10103818, 585134, 7877383, 11345683, -6492290, 13352335, -10977084}, }, { {-1931799, -5407458, 3304649, -12884869, 17015806, -4877091, -29783850, -7752482, -13215537, -319204}, {20239939, 6607058, 6203985, 3483793, -18386976, -779229, -20723742, 15077870, -22750759, 14523817}, {27406042, -6041657, 27423596, -4497394, 4996214, 10002360, -28842031, -4545494, -30172742, -4805667}, }, }, { { {11374242, 12660715, 17861383, -12540833, 10935568, 1099227, -13886076, -9091740, -27727044, 11358504}, {-12730809, 10311867, 1510375, 10778093, -2119455, -9145702, 32676003, 11149336, -26123651, 4985768}, {-19096303, 341147, -6197485, -239033, 15756973, -8796662, -983043, 13794114, -19414307, -15621255}, }, { {6490081, 11940286, 25495923, -7726360, 8668373, -8751316, 3367603, 6970005, -1691065, -9004790}, {1656497, 13457317, 15370807, 6364910, 13605745, 8362338, -19174622, -5475723, -16796596, -5031438}, {-22273315, -13524424, -64685, -4334223, -18605636, -10921968, -20571065, -7007978, -99853, -10237333}, }, { {17747465, 10039260, 19368299, -4050591, -20630635, -16041286, 31992683, -15857976, -29260363, -5511971}, {31932027, -4986141, -19612382, 16366580, 22023614, 88450, 11371999, -3744247, 4882242, -10626905}, {29796507, 37186, 19818052, 10115756, -11829032, 3352736, 18551198, 3272828, -5190932, -4162409}, }, { {12501286, 4044383, -8612957, -13392385, -32430052, 5136599, -19230378, -3529697, 330070, -3659409}, {6384877, 2899513, 17807477, 7663917, -2358888, 12363165, 25366522, -8573892, -271295, 12071499}, {-8365515, -4042521, 25133448, -4517355, -6211027, 2265927, -32769618, 1936675, -5159697, 3829363}, }, { {28425966, -5835433, -577090, -4697198, -14217555, 6870930, 7921550, -6567787, 26333140, 14267664}, {-11067219, 11871231, 27385719, -10559544, -4585914, -11189312, 10004786, -8709488, -21761224, 8930324}, {-21197785, -16396035, 25654216, -1725397, 12282012, 11008919, 1541940, 4757911, -26491501, -16408940}, }, { {13537262, -7759490, -20604840, 10961927, -5922820, -13218065, -13156584, 6217254, -15943699, 13814990}, {-17422573, 15157790, 18705543, 29619, 24409717, -260476, 27361681, 9257833, -1956526, -1776914}, {-25045300, -10191966, 15366585, 15166509, -13105086, 8423556, -29171540, 12361135, -18685978, 4578290}, }, { {24579768, 3711570, 1342322, -11180126, -27005135, 14124956, -22544529, 14074919, 21964432, 8235257}, {-6528613, -2411497, 9442966, -5925588, 12025640, -1487420, -2981514, -1669206, 13006806, 2355433}, {-16304899, -13605259, -6632427, -5142349, 16974359, -10911083, 27202044, 1719366, 1141648, -12796236}, }, { {-12863944, -13219986, -8318266, -11018091, -6810145, -4843894, 13475066, -3133972, 32674895, 13715045}, {11423335, -5468059, 32344216, 8962751, 24989809, 9241752, -13265253, 16086212, -28740881, -15642093}, {-1409668, 12530728, -6368726, 10847387, 19531186, -14132160, -11709148, 7791794, -27245943, 4383347}, }, }, { { {-28970898, 5271447, -1266009, -9736989, -12455236, 16732599, -4862407, -4906449, 27193557, 6245191}, {-15193956, 5362278, -1783893, 2695834, 4960227, 12840725, 23061898, 3260492, 22510453, 8577507}, {-12632451, 11257346, -32692994, 13548177, -721004, 10879011, 31168030, 13952092, -29571492, -3635906}, }, { {3877321, -9572739, 32416692, 5405324, -11004407, -13656635, 3759769, 11935320, 5611860, 8164018}, {-16275802, 14667797, 15906460, 12155291, -22111149, -9039718, 32003002, -8832289, 5773085, -8422109}, {-23788118, -8254300, 1950875, 8937633, 18686727, 16459170, -905725, 12376320, 31632953, 190926}, }, { {-24593607, -16138885, -8423991, 13378746, 14162407, 6901328, -8288749, 4508564, -25341555, -3627528}, {8884438, -5884009, 6023974, 10104341, -6881569, -4941533, 18722941, -14786005, -1672488, 827625}, {-32720583, -16289296, -32503547, 7101210, 13354605, 2659080, -1800575, -14108036, -24878478, 1541286}, }, { {2901347, -1117687, 3880376, -10059388, -17620940, -3612781, -21802117, -3567481, 20456845, -1885033}, {27019610, 12299467, -13658288, -1603234, -12861660, -4861471, -19540150, -5016058, 29439641, 15138866}, {21536104, -6626420, -32447818, -10690208, -22408077, 5175814, -5420040, -16361163, 7779328, 109896}, }, { {30279744, 14648750, -8044871, 6425558, 13639621, -743509, 28698390, 12180118, 23177719, -554075}, {26572847, 3405927, -31701700, 12890905, -19265668, 5335866, -6493768, 2378492, 4439158, -13279347}, {-22716706, 3489070, -9225266, -332753, 18875722, -1140095, 14819434, -12731527, -17717757, -5461437}, }, { {-5056483, 16566551, 15953661, 3767752, -10436499, 15627060, -820954, 2177225, 8550082, -15114165}, {-18473302, 16596775, -381660, 15663611, 22860960, 15585581, -27844109, -3582739, -23260460, -8428588}, {-32480551, 15707275, -8205912, -5652081, 29464558, 2713815, -22725137, 15860482, -21902570, 1494193}, }, { {-19562091, -14087393, -25583872, -9299552, 13127842, 759709, 21923482, 16529112, 8742704, 12967017}, {-28464899, 1553205, 32536856, -10473729, -24691605, -406174, -8914625, -2933896, -29903758, 15553883}, {21877909, 3230008, 9881174, 10539357, -4797115, 2841332, 11543572, 14513274, 19375923, -12647961}, }, { {8832269, -14495485, 13253511, 5137575, 5037871, 4078777, 24880818, -6222716, 2862653, 9455043}, {29306751, 5123106, 20245049, -14149889, 9592566, 8447059, -2077124, -2990080, 15511449, 4789663}, {-20679756, 7004547, 8824831, -9434977, -4045704, -3750736, -5754762, 108893, 23513200, 16652362}, }, }, { { {-33256173, 4144782, -4476029, -6579123, 10770039, -7155542, -6650416, -12936300, -18319198, 10212860}, {2756081, 8598110, 7383731, -6859892, 22312759, -1105012, 21179801, 2600940, -9988298, -12506466}, {-24645692, 13317462, -30449259, -15653928, 21365574, -10869657, 11344424, 864440, -2499677, -16710063}, }, { {-26432803, 6148329, -17184412, -14474154, 18782929, -275997, -22561534, 211300, 2719757, 4940997}, {-1323882, 3911313, -6948744, 14759765, -30027150, 7851207, 21690126, 8518463, 26699843, 5276295}, {-13149873, -6429067, 9396249, 365013, 24703301, -10488939, 1321586, 149635, -15452774, 7159369}, }, { {9987780, -3404759, 17507962, 9505530, 9731535, -2165514, 22356009, 8312176, 22477218, -8403385}, {18155857, -16504990, 19744716, 9006923, 15154154, -10538976, 24256460, -4864995, -22548173, 9334109}, {2986088, -4911893, 10776628, -3473844, 10620590, -7083203, -21413845, 14253545, -22587149, 536906}, }, { {4377756, 8115836, 24567078, 15495314, 11625074, 13064599, 7390551, 10589625, 10838060, -15420424}, {-19342404, 867880, 9277171, -3218459, -14431572, -1986443, 19295826, -15796950, 6378260, 699185}, {7895026, 4057113, -7081772, -13077756, -17886831, -323126, -716039, 15693155, -5045064, -13373962}, }, { {-7737563, -5869402, -14566319, -7406919, 11385654, 13201616, 31730678, -10962840, -3918636, -9669325}, {10188286, -15770834, -7336361, 13427543, 22223443, 14896287, 30743455, 7116568, -21786507, 5427593}, {696102, 13206899, 27047647, -10632082, 15285305, -9853179, 10798490, -4578720, 19236243, 12477404}, }, { {-11229439, 11243796, -17054270, -8040865, -788228, -8167967, -3897669, 11180504, -23169516, 7733644}, {17800790, -14036179, -27000429, -11766671, 23887827, 3149671, 23466177, -10538171, 10322027, 15313801}, {26246234, 11968874, 32263343, -5468728, 6830755, -13323031, -15794704, -101982, -24449242, 10890804}, }, { {-31365647, 10271363, -12660625, -6267268, 16690207, -13062544, -14982212, 16484931, 25180797, -5334884}, {-586574, 10376444, -32586414, -11286356, 19801893, 10997610, 2276632, 9482883, 316878, 13820577}, {-9882808, -4510367, -2115506, 16457136, -11100081, 11674996, 30756178, -7515054, 30696930, -3712849}, }, { {32988917, -9603412, 12499366, 7910787, -10617257, -11931514, -7342816, -9985397, -32349517, 7392473}, {-8855661, 15927861, 9866406, -3649411, -2396914, -16655781, -30409476, -9134995, 25112947, -2926644}, {-2504044, -436966, 25621774, -5678772, 15085042, -5479877, -24884878, -13526194, 5537438, -13914319}, }, }, { { {-11225584, 2320285, -9584280, 10149187, -33444663, 5808648, -14876251, -1729667, 31234590, 6090599}, {-9633316, 116426, 26083934, 2897444, -6364437, -2688086, 609721, 15878753, -6970405, -9034768}, {-27757857, 247744, -15194774, -9002551, 23288161, -10011936, -23869595, 6503646, 20650474, 1804084}, }, { {-27589786, 15456424, 8972517, 8469608, 15640622, 4439847, 3121995, -10329713, 27842616, -202328}, {-15306973, 2839644, 22530074, 10026331, 4602058, 5048462, 28248656, 5031932, -11375082, 12714369}, {20807691, -7270825, 29286141, 11421711, -27876523, -13868230, -21227475, 1035546, -19733229, 12796920}, }, { {12076899, -14301286, -8785001, -11848922, -25012791, 16400684, -17591495, -12899438, 3480665, -15182815}, {-32361549, 5457597, 28548107, 7833186, 7303070, -11953545, -24363064, -15921875, -33374054, 2771025}, {-21389266, 421932, 26597266, 6860826, 22486084, -6737172, -17137485, -4210226, -24552282, 15673397}, }, { {-20184622, 2338216, 19788685, -9620956, -4001265, -8740893, -20271184, 4733254, 3727144, -12934448}, {6120119, 814863, -11794402, -622716, 6812205, -15747771, 2019594, 7975683, 31123697, -10958981}, {30069250, -11435332, 30434654, 2958439, 18399564, -976289, 12296869, 9204260, -16432438, 9648165}, }, { {32705432, -1550977, 30705658, 7451065, -11805606, 9631813, 3305266, 5248604, -26008332, -11377501}, {17219865, 2375039, -31570947, -5575615, -19459679, 9219903, 294711, 15298639, 2662509, -16297073}, {-1172927, -7558695, -4366770, -4287744, -21346413, -8434326, 32087529, -1222777, 32247248, -14389861}, }, { {14312628, 1221556, 17395390, -8700143, -4945741, -8684635, -28197744, -9637817, -16027623, -13378845}, {-1428825, -9678990, -9235681, 6549687, -7383069, -468664, 23046502, 9803137, 17597934, 2346211}, {18510800, 15337574, 26171504, 981392, -22241552, 7827556, -23491134, -11323352, 3059833, -11782870}, }, { {10141598, 6082907, 17829293, -1947643, 9830092, 13613136, -25556636, -5544586, -33502212, 3592096}, {33114168, -15889352, -26525686, -13343397, 33076705, 8716171, 1151462, 1521897, -982665, -6837803}, {-32939165, -4255815, 23947181, -324178, -33072974, -12305637, -16637686, 3891704, 26353178, 693168}, }, { {30374239, 1595580, -16884039, 13186931, 4600344, 406904, 9585294, -400668, 31375464, 14369965}, {-14370654, -7772529, 1510301, 6434173, -18784789, -6262728, 32732230, -13108839, 17901441, 16011505}, {18171223, -11934626, -12500402, 15197122, -11038147, -15230035, -19172240, -16046376, 8764035, 12309598}, }, }, { { {5975908, -5243188, -19459362, -9681747, -11541277, 14015782, -23665757, 1228319, 17544096, -10593782}, {5811932, -1715293, 3442887, -2269310, -18367348, -8359541, -18044043, -15410127, -5565381, 12348900}, {-31399660, 11407555, 25755363, 6891399, -3256938, 14872274, -24849353, 8141295, -10632534, -585479}, }, { {-12675304, 694026, -5076145, 13300344, 14015258, -14451394, -9698672, -11329050, 30944593, 1130208}, {8247766, -6710942, -26562381, -7709309, -14401939, -14648910, 4652152, 2488540, 23550156, -271232}, {17294316, -3788438, 7026748, 15626851, 22990044, 113481, 2267737, -5908146, -408818, -137719}, }, { {16091085, -16253926, 18599252, 7340678, 2137637, -1221657, -3364161, 14550936, 3260525, -7166271}, {-4910104, -13332887, 18550887, 10864893, -16459325, -7291596, -23028869, -13204905, -12748722, 2701326}, {-8574695, 16099415, 4629974, -16340524, -20786213, -6005432, -10018363, 9276971, 11329923, 1862132}, }, { {14763076, -15903608, -30918270, 3689867, 3511892, 10313526, -21951088, 12219231, -9037963, -940300}, {8894987, -3446094, 6150753, 3013931, 301220, 15693451, -31981216, -2909717, -15438168, 11595570}, {15214962, 3537601, -26238722, -14058872, 4418657, -15230761, 13947276, 10730794, -13489462, -4363670}, }, { {-2538306, 7682793, 32759013, 263109, -29984731, -7955452, -22332124, -10188635, 977108, 699994}, {-12466472, 4195084, -9211532, 550904, -15565337, 12917920, 19118110, -439841, -30534533, -14337913}, {31788461, -14507657, 4799989, 7372237, 8808585, -14747943, 9408237, -10051775, 12493932, -5409317}, }, { {-25680606, 5260744, -19235809, -6284470, -3695942, 16566087, 27218280, 2607121, 29375955, 6024730}, {842132, -2794693, -4763381, -8722815, 26332018, -12405641, 11831880, 6985184, -9940361, 2854096}, {-4847262, -7969331, 2516242, -5847713, 9695691, -7221186, 16512645, 960770, 12121869, 16648078}, }, { {-15218652, 14667096, -13336229, 2013717, 30598287, -464137, -31504922, -7882064, 20237806, 2838411}, {-19288047, 4453152, 15298546, -16178388, 22115043, -15972604, 12544294, -13470457, 1068881, -12499905}, {-9558883, -16518835, 33238498, 13506958, 30505848, -1114596, -8486907, -2630053, 12521378, 4845654}, }, { {-28198521, 10744108, -2958380, 10199664, 7759311, -13088600, 3409348, -873400, -6482306, -12885870}, {-23561822, 6230156, -20382013, 10655314, -24040585, -11621172, 10477734, -1240216, -3113227, 13974498}, {12966261, 15550616, -32038948, -1615346, 21025980, -629444, 5642325, 7188737, 18895762, 12629579}, }, }, { { {14741879, -14946887, 22177208, -11721237, 1279741, 8058600, 11758140, 789443, 32195181, 3895677}, {10758205, 15755439, -4509950, 9243698, -4879422, 6879879, -2204575, -3566119, -8982069, 4429647}, {-2453894, 15725973, -20436342, -10410672, -5803908, -11040220, -7135870, -11642895, 18047436, -15281743}, }, { {-25173001, -11307165, 29759956, 11776784, -22262383, -15820455, 10993114, -12850837, -17620701, -9408468}, {21987233, 700364, -24505048, 14972008, -7774265, -5718395, 32155026, 2581431, -29958985, 8773375}, {-25568350, 454463, -13211935, 16126715, 25240068, 8594567, 20656846, 12017935, -7874389, -13920155}, }, { {6028182, 6263078, -31011806, -11301710, -818919, 2461772, -31841174, -5468042, -1721788, -2776725}, {-12278994, 16624277, 987579, -5922598, 32908203, 1248608, 7719845, -4166698, 28408820, 6816612}, {-10358094, -8237829, 19549651, -12169222, 22082623, 16147817, 20613181, 13982702, -10339570, 5067943}, }, { {-30505967, -3821767, 12074681, 13582412, -19877972, 2443951, -19719286, 12746132, 5331210, -10105944}, {30528811, 3601899, -1957090, 4619785, -27361822, -15436388, 24180793, -12570394, 27679908, -1648928}, {9402404, -13957065, 32834043, 10838634, -26580150, -13237195, 26653274, -8685565, 22611444, -12715406}, }, { {22190590, 1118029, 22736441, 15130463, -30460692, -5991321, 19189625, -4648942, 4854859, 6622139}, {-8310738, -2953450, -8262579, -3388049, -10401731, -271929, 13424426, -3567227, 26404409, 13001963}, {-31241838, -15415700, -2994250, 8939346, 11562230, -12840670, -26064365, -11621720, -15405155, 11020693}, }, { {1866042, -7949489, -7898649, -10301010, 12483315, 13477547, 3175636, -12424163, 28761762, 1406734}, {-448555, -1777666, 13018551, 3194501, -9580420, -11161737, 24760585, -4347088, 25577411, -13378680}, {-24290378, 4759345, -690653, -1852816, 2066747, 10693769, -29595790, 9884936, -9368926, 4745410}, }, { {-9141284, 6049714, -19531061, -4341411, -31260798, 9944276, -15462008, -11311852, 10931924, -11931931}, {-16561513, 14112680, -8012645, 4817318, -8040464, -11414606, -22853429, 10856641, -20470770, 13434654}, {22759489, -10073434, -16766264, -1871422, 13637442, -10168091, 1765144, -12654326, 28445307, -5364710}, }, { {29875063, 12493613, 2795536, -3786330, 1710620, 15181182, -10195717, -8788675, 9074234, 1167180}, {-26205683, 11014233, -9842651, -2635485, -26908120, 7532294, -18716888, -9535498, 3843903, 9367684}, {-10969595, -6403711, 9591134, 9582310, 11349256, 108879, 16235123, 8601684, -139197, 4242895}, }, }, { { {22092954, -13191123, -2042793, -11968512, 32186753, -11517388, -6574341, 2470660, -27417366, 16625501}, {-11057722, 3042016, 13770083, -9257922, 584236, -544855, -7770857, 2602725, -27351616, 14247413}, {6314175, -10264892, -32772502, 15957557, -10157730, 168750, -8618807, 14290061, 27108877, -1180880}, }, { {-8586597, -7170966, 13241782, 10960156, -32991015, -13794596, 33547976, -11058889, -27148451, 981874}, {22833440, 9293594, -32649448, -13618667, -9136966, 14756819, -22928859, -13970780, -10479804, -16197962}, {-7768587, 3326786, -28111797, 10783824, 19178761, 14905060, 22680049, 13906969, -15933690, 3797899}, }, { {21721356, -4212746, -12206123, 9310182, -3882239, -13653110, 23740224, -2709232, 20491983, -8042152}, {9209270, -15135055, -13256557, -6167798, -731016, 15289673, 25947805, 15286587, 30997318, -6703063}, {7392032, 16618386, 23946583, -8039892, -13265164, -1533858, -14197445, -2321576, 17649998, -250080}, }, { {-9301088, -14193827, 30609526, -3049543, -25175069, -1283752, -15241566, -9525724, -2233253, 7662146}, {-17558673, 1763594, -33114336, 15908610, -30040870, -12174295, 7335080, -8472199, -3174674, 3440183}, {-19889700, -5977008, -24111293, -9688870, 10799743, -16571957, 40450, -4431835, 4862400, 1133}, }, { {-32856209, -7873957, -5422389, 14860950, -16319031, 7956142, 7258061, 311861, -30594991, -7379421}, {-3773428, -1565936, 28985340, 7499440, 24445838, 9325937, 29727763, 16527196, 18278453, 15405622}, {-4381906, 8508652, -19898366, -3674424, -5984453, 15149970, -13313598, 843523, -21875062, 13626197}, }, { {2281448, -13487055, -10915418, -2609910, 1879358, 16164207, -10783882, 3953792, 13340839, 15928663}, {31727126, -7179855, -18437503, -8283652, 2875793, -16390330, -25269894, -7014826, -23452306, 5964753}, {4100420, -5959452, -17179337, 6017714, -18705837, 12227141, -26684835, 11344144, 2538215, -7570755}, }, { {-9433605, 6123113, 11159803, -2156608, 30016280, 14966241, -20474983, 1485421, -629256, -15958862}, {-26804558, 4260919, 11851389, 9658551, -32017107, 16367492, -20205425, -13191288, 11659922, -11115118}, {26180396, 10015009, -30844224, -8581293, 5418197, 9480663, 2231568, -10170080, 33100372, -1306171}, }, { {15121113, -5201871, -10389905, 15427821, -27509937, -15992507, 21670947, 4486675, -5931810, -14466380}, {16166486, -9483733, -11104130, 6023908, -31926798, -1364923, 2340060, -16254968, -10735770, -10039824}, {28042865, -3557089, -12126526, 12259706, -3717498, -6945899, 6766453, -8689599, 18036436, 5803270}, }, }, { { {-817581, 6763912, 11803561, 1585585, 10958447, -2671165, 23855391, 4598332, -6159431, -14117438}, {-31031306, -14256194, 17332029, -2383520, 31312682, -5967183, 696309, 50292, -20095739, 11763584}, {-594563, -2514283, -32234153, 12643980, 12650761, 14811489, 665117, -12613632, -19773211, -10713562}, }, { {30464590, -11262872, -4127476, -12734478, 19835327, -7105613, -24396175, 2075773, -17020157, 992471}, {18357185, -6994433, 7766382, 16342475, -29324918, 411174, 14578841, 8080033, -11574335, -10601610}, {19598397, 10334610, 12555054, 2555664, 18821899, -10339780, 21873263, 16014234, 26224780, 16452269}, }, { {-30223925, 5145196, 5944548, 16385966, 3976735, 2009897, -11377804, -7618186, -20533829, 3698650}, {14187449, 3448569, -10636236, -10810935, -22663880, -3433596, 7268410, -10890444, 27394301, 12015369}, {19695761, 16087646, 28032085, 12999827, 6817792, 11427614, 20244189, -1312777, -13259127, -3402461}, }, { {30860103, 12735208, -1888245, -4699734, -16974906, 2256940, -8166013, 12298312, -8550524, -10393462}, {-5719826, -11245325, -1910649, 15569035, 26642876, -7587760, -5789354, -15118654, -4976164, 12651793}, {-2848395, 9953421, 11531313, -5282879, 26895123, -12697089, -13118820, -16517902, 9768698, -2533218}, }, { {-24719459, 1894651, -287698, -4704085, 15348719, -8156530, 32767513, 12765450, 4940095, 10678226}, {18860224, 15980149, -18987240, -1562570, -26233012, -11071856, -7843882, 13944024, -24372348, 16582019}, {-15504260, 4970268, -29893044, 4175593, -20993212, -2199756, -11704054, 15444560, -11003761, 7989037}, }, { {31490452, 5568061, -2412803, 2182383, -32336847, 4531686, -32078269, 6200206, -19686113, -14800171}, {-17308668, -15879940, -31522777, -2831, -32887382, 16375549, 8680158, -16371713, 28550068, -6857132}, {-28126887, -5688091, 16837845, -1820458, -6850681, 12700016, -30039981, 4364038, 1155602, 5988841}, }, { {21890435, -13272907, -12624011, 12154349, -7831873, 15300496, 23148983, -4470481, 24618407, 8283181}, {-33136107, -10512751, 9975416, 6841041, -31559793, 16356536, 3070187, -7025928, 1466169, 10740210}, {-1509399, -15488185, -13503385, -10655916, 32799044, 909394, -13938903, -5779719, -32164649, -15327040}, }, { {3960823, -14267803, -28026090, -15918051, -19404858, 13146868, 15567327, 951507, -3260321, -573935}, {24740841, 5052253, -30094131, 8961361, 25877428, 6165135, -24368180, 14397372, -7380369, -6144105}, {-28888365, 3510803, -28103278, -1158478, -11238128, -10631454, -15441463, -14453128, -1625486, -6494814}, }, }, { { {793299, -9230478, 8836302, -6235707, -27360908, -2369593, 33152843, -4885251, -9906200, -621852}, {5666233, 525582, 20782575, -8038419, -24538499, 14657740, 16099374, 1468826, -6171428, -15186581}, {-4859255, -3779343, -2917758, -6748019, 7778750, 11688288, -30404353, -9871238, -1558923, -9863646}, }, { {10896332, -7719704, 824275, 472601, -19460308, 3009587, 25248958, 14783338, -30581476, -15757844}, {10566929, 12612572, -31944212, 11118703, -12633376, 12362879, 21752402, 8822496, 24003793, 14264025}, {27713862, -7355973, -11008240, 9227530, 27050101, 2504721, 23886875, -13117525, 13958495, -5732453}, }, { {-23481610, 4867226, -27247128, 3900521, 29838369, -8212291, -31889399, -10041781, 7340521, -15410068}, {4646514, -8011124, -22766023, -11532654, 23184553, 8566613, 31366726, -1381061, -15066784, -10375192}, {-17270517, 12723032, -16993061, 14878794, 21619651, -6197576, 27584817, 3093888, -8843694, 3849921}, }, { {-9064912, 2103172, 25561640, -15125738, -5239824, 9582958, 32477045, -9017955, 5002294, -15550259}, {-12057553, -11177906, 21115585, -13365155, 8808712, -12030708, 16489530, 13378448, -25845716, 12741426}, {-5946367, 10645103, -30911586, 15390284, -3286982, -7118677, 24306472, 15852464, 28834118, -7646072}, }, { {-17335748, -9107057, -24531279, 9434953, -8472084, -583362, -13090771, 455841, 20461858, 5491305}, {13669248, -16095482, -12481974, -10203039, -14569770, -11893198, -24995986, 11293807, -28588204, -9421832}, {28497928, 6272777, -33022994, 14470570, 8906179, -1225630, 18504674, -14165166, 29867745, -8795943}, }, { {-16207023, 13517196, -27799630, -13697798, 24009064, -6373891, -6367600, -13175392, 22853429, -4012011}, {24191378, 16712145, -13931797, 15217831, 14542237, 1646131, 18603514, -11037887, 12876623, -2112447}, {17902668, 4518229, -411702, -2829247, 26878217, 5258055, -12860753, 608397, 16031844, 3723494}, }, { {-28632773, 12763728, -20446446, 7577504, 33001348, -13017745, 17558842, -7872890, 23896954, -4314245}, {-20005381, -12011952, 31520464, 605201, 2543521, 5991821, -2945064, 7229064, -9919646, -8826859}, {28816045, 298879, -28165016, -15920938, 19000928, -1665890, -12680833, -2949325, -18051778, -2082915}, }, { {16000882, -344896, 3493092, -11447198, -29504595, -13159789, 12577740, 16041268, -19715240, 7847707}, {10151868, 10572098, 27312476, 7922682, 14825339, 4723128, -32855931, -6519018, -10020567, 3852848}, {-11430470, 15697596, -21121557, -4420647, 5386314, 15063598, 16514493, -15932110, 29330899, -15076224}, }, }, { { {-25499735, -4378794, -15222908, -6901211, 16615731, 2051784, 3303702, 15490, -27548796, 12314391}, {15683520, -6003043, 18109120, -9980648, 15337968, -5997823, -16717435, 15921866, 16103996, -3731215}, {-23169824, -10781249, 13588192, -1628807, -3798557, -1074929, -19273607, 5402699, -29815713, -9841101}, }, { {23190676, 2384583, -32714340, 3462154, -29903655, -1529132, -11266856, 8911517, -25205859, 2739713}, {21374101, -3554250, -33524649, 9874411, 15377179, 11831242, -33529904, 6134907, 4931255, 11987849}, {-7732, -2978858, -16223486, 7277597, 105524, -322051, -31480539, 13861388, -30076310, 10117930}, }, { {-29501170, -10744872, -26163768, 13051539, -25625564, 5089643, -6325503, 6704079, 12890019, 15728940}, {-21972360, -11771379, -951059, -4418840, 14704840, 2695116, 903376, -10428139, 12885167, 8311031}, {-17516482, 5352194, 10384213, -13811658, 7506451, 13453191, 26423267, 4384730, 1888765, -5435404}, }, { {-25817338, -3107312, -13494599, -3182506, 30896459, -13921729, -32251644, -12707869, -19464434, -3340243}, {-23607977, -2665774, -526091, 4651136, 5765089, 4618330, 6092245, 14845197, 17151279, -9854116}, {-24830458, -12733720, -15165978, 10367250, -29530908, -265356, 22825805, -7087279, -16866484, 16176525}, }, { {-23583256, 6564961, 20063689, 3798228, -4740178, 7359225, 2006182, -10363426, -28746253, -10197509}, {-10626600, -4486402, -13320562, -5125317, 3432136, -6393229, 23632037, -1940610, 32808310, 1099883}, {15030977, 5768825, -27451236, -2887299, -6427378, -15361371, -15277896, -6809350, 2051441, -15225865}, }, { {-3362323, -7239372, 7517890, 9824992, 23555850, 295369, 5148398, -14154188, -22686354, 16633660}, {4577086, -16752288, 13249841, -15304328, 19958763, -14537274, 18559670, -10759549, 8402478, -9864273}, {-28406330, -1051581, -26790155, -907698, -17212414, -11030789, 9453451, -14980072, 17983010, 9967138}, }, { {-25762494, 6524722, 26585488, 9969270, 24709298, 1220360, -1677990, 7806337, 17507396, 3651560}, {-10420457, -4118111, 14584639, 15971087, -15768321, 8861010, 26556809, -5574557, -18553322, -11357135}, {2839101, 14284142, 4029895, 3472686, 14402957, 12689363, -26642121, 8459447, -5605463, -7621941}, }, { {-4839289, -3535444, 9744961, 2871048, 25113978, 3187018, -25110813, -849066, 17258084, -7977739}, {18164541, -10595176, -17154882, -1542417, 19237078, -9745295, 23357533, -15217008, 26908270, 12150756}, {-30264870, -7647865, 5112249, -7036672, -1499807, -6974257, 43168, -5537701, -32302074, 16215819}, }, }, { { {-6898905, 9824394, -12304779, -4401089, -31397141, -6276835, 32574489, 12532905, -7503072, -8675347}, {-27343522, -16515468, -27151524, -10722951, 946346, 16291093, 254968, 7168080, 21676107, -1943028}, {21260961, -8424752, -16831886, -11920822, -23677961, 3968121, -3651949, -6215466, -3556191, -7913075}, }, { {16544754, 13250366, -16804428, 15546242, -4583003, 12757258, -2462308, -8680336, -18907032, -9662799}, {-2415239, -15577728, 18312303, 4964443, -15272530, -12653564, 26820651, 16690659, 25459437, -4564609}, {-25144690, 11425020, 28423002, -11020557, -6144921, -15826224, 9142795, -2391602, -6432418, -1644817}, }, { {-23104652, 6253476, 16964147, -3768872, -25113972, -12296437, -27457225, -16344658, 6335692, 7249989}, {-30333227, 13979675, 7503222, -12368314, -11956721, -4621693, -30272269, 2682242, 25993170, -12478523}, {4364628, 5930691, 32304656, -10044554, -8054781, 15091131, 22857016, -10598955, 31820368, 15075278}, }, { {31879134, -8918693, 17258761, 90626, -8041836, -4917709, 24162788, -9650886, -17970238, 12833045}, {19073683, 14851414, -24403169, -11860168, 7625278, 11091125, -19619190, 2074449, -9413939, 14905377}, {24483667, -11935567, -2518866, -11547418, -1553130, 15355506, -25282080, 9253129, 27628530, -7555480}, }, { {17597607, 8340603, 19355617, 552187, 26198470, -3176583, 4593324, -9157582, -14110875, 15297016}, {510886, 14337390, -31785257, 16638632, 6328095, 2713355, -20217417, -11864220, 8683221, 2921426}, {18606791, 11874196, 27155355, -5281482, -24031742, 6265446, -25178240, -1278924, 4674690, 13890525}, }, { {13609624, 13069022, -27372361, -13055908, 24360586, 9592974, 14977157, 9835105, 4389687, 288396}, {9922506, -519394, 13613107, 5883594, -18758345, -434263, -12304062, 8317628, 23388070, 16052080}, {12720016, 11937594, -31970060, -5028689, 26900120, 8561328, -20155687, -11632979, -14754271, -10812892}, }, { {15961858, 14150409, 26716931, -665832, -22794328, 13603569, 11829573, 7467844, -28822128, 929275}, {11038231, -11582396, -27310482, -7316562, -10498527, -16307831, -23479533, -9371869, -21393143, 2465074}, {20017163, -4323226, 27915242, 1529148, 12396362, 15675764, 13817261, -9658066, 2463391, -4622140}, }, { {-16358878, -12663911, -12065183, 4996454, -1256422, 1073572, 9583558, 12851107, 4003896, 12673717}, {-1731589, -15155870, -3262930, 16143082, 19294135, 13385325, 14741514, -9103726, 7903886, 2348101}, {24536016, -16515207, 12715592, -3862155, 1511293, 10047386, -3842346, -7129159, -28377538, 10048127}, }, }, { { {-12622226, -6204820, 30718825, 2591312, -10617028, 12192840, 18873298, -7297090, -32297756, 15221632}, {-26478122, -11103864, 11546244, -1852483, 9180880, 7656409, -21343950, 2095755, 29769758, 6593415}, {-31994208, -2907461, 4176912, 3264766, 12538965, -868111, 26312345, -6118678, 30958054, 8292160}, }, { {31429822, -13959116, 29173532, 15632448, 12174511, -2760094, 32808831, 3977186, 26143136, -3148876}, {22648901, 1402143, -22799984, 13746059, 7936347, 365344, -8668633, -1674433, -3758243, -2304625}, {-15491917, 8012313, -2514730, -12702462, -23965846, -10254029, -1612713, -1535569, -16664475, 8194478}, }, { {27338066, -7507420, -7414224, 10140405, -19026427, -6589889, 27277191, 8855376, 28572286, 3005164}, {26287124, 4821776, 25476601, -4145903, -3764513, -15788984, -18008582, 1182479, -26094821, -13079595}, {-7171154, 3178080, 23970071, 6201893, -17195577, -4489192, -21876275, -13982627, 32208683, -1198248}, }, { {-16657702, 2817643, -10286362, 14811298, 6024667, 13349505, -27315504, -10497842, -27672585, -11539858}, {15941029, -9405932, -21367050, 8062055, 31876073, -238629, -15278393, -1444429, 15397331, -4130193}, {8934485, -13485467, -23286397, -13423241, -32446090, 14047986, 31170398, -1441021, -27505566, 15087184}, }, { {-18357243, -2156491, 24524913, -16677868, 15520427, -6360776, -15502406, 11461896, 16788528, -5868942}, {-1947386, 16013773, 21750665, 3714552, -17401782, -16055433, -3770287, -10323320, 31322514, -11615635}, {21426655, -5650218, -13648287, -5347537, -28812189, -4920970, -18275391, -14621414, 13040862, -12112948}, }, { {11293895, 12478086, -27136401, 15083750, -29307421, 14748872, 14555558, -13417103, 1613711, 4896935}, {-25894883, 15323294, -8489791, -8057900, 25967126, -13425460, 2825960, -4897045, -23971776, -11267415}, {-15924766, -5229880, -17443532, 6410664, 3622847, 10243618, 20615400, 12405433, -23753030, -8436416}, }, { {-7091295, 12556208, -20191352, 9025187, -17072479, 4333801, 4378436, 2432030, 23097949, -566018}, {4565804, -16025654, 20084412, -7842817, 1724999, 189254, 24767264, 10103221, -18512313, 2424778}, {366633, -11976806, 8173090, -6890119, 30788634, 5745705, -7168678, 1344109, -3642553, 12412659}, }, { {-24001791, 7690286, 14929416, -168257, -32210835, -13412986, 24162697, -15326504, -3141501, 11179385}, {18289522, -14724954, 8056945, 16430056, -21729724, 7842514, -6001441, -1486897, -18684645, -11443503}, {476239, 6601091, -6152790, -9723375, 17503545, -4863900, 27672959, 13403813, 11052904, 5219329}, }, }, { { {20678546, -8375738, -32671898, 8849123, -5009758, 14574752, 31186971, -3973730, 9014762, -8579056}, {-13644050, -10350239, -15962508, 5075808, -1514661, -11534600, -33102500, 9160280, 8473550, -3256838}, {24900749, 14435722, 17209120, -15292541, -22592275, 9878983, -7689309, -16335821, -24568481, 11788948}, }, { {-3118155, -11395194, -13802089, 14797441, 9652448, -6845904, -20037437, 10410733, -24568470, -1458691}, {-15659161, 16736706, -22467150, 10215878, -9097177, 7563911, 11871841, -12505194, -18513325, 8464118}, {-23400612, 8348507, -14585951, -861714, -3950205, -6373419, 14325289, 8628612, 33313881, -8370517}, }, { {-20186973, -4967935, 22367356, 5271547, -1097117, -4788838, -24805667, -10236854, -8940735, -5818269}, {-6948785, -1795212, -32625683, -16021179, 32635414, -7374245, 15989197, -12838188, 28358192, -4253904}, {-23561781, -2799059, -32351682, -1661963, -9147719, 10429267, -16637684, 4072016, -5351664, 5596589}, }, { {-28236598, -3390048, 12312896, 6213178, 3117142, 16078565, 29266239, 2557221, 1768301, 15373193}, {-7243358, -3246960, -4593467, -7553353, -127927, -912245, -1090902, -4504991, -24660491, 3442910}, {-30210571, 5124043, 14181784, 8197961, 18964734, -11939093, 22597931, 7176455, -18585478, 13365930}, }, { {-7877390, -1499958, 8324673, 4690079, 6261860, 890446, 24538107, -8570186, -9689599, -3031667}, {25008904, -10771599, -4305031, -9638010, 16265036, 15721635, 683793, -11823784, 15723479, -15163481}, {-9660625, 12374379, -27006999, -7026148, -7724114, -12314514, 11879682, 5400171, 519526, -1235876}, }, { {22258397, -16332233, -7869817, 14613016, -22520255, -2950923, -20353881, 7315967, 16648397, 7605640}, {-8081308, -8464597, -8223311, 9719710, 19259459, -15348212, 23994942, -5281555, -9468848, 4763278}, {-21699244, 9220969, -15730624, 1084137, -25476107, -2852390, 31088447, -7764523, -11356529, 728112}, }, { {26047220, -11751471, -6900323, -16521798, 24092068, 9158119, -4273545, -12555558, -29365436, -5498272}, {17510331, -322857, 5854289, 8403524, 17133918, -3112612, -28111007, 12327945, 10750447, 10014012}, {-10312768, 3936952, 9156313, -8897683, 16498692, -994647, -27481051, -666732, 3424691, 7540221}, }, { {30322361, -6964110, 11361005, -4143317, 7433304, 4989748, -7071422, -16317219, -9244265, 15258046}, {13054562, -2779497, 19155474, 469045, -12482797, 4566042, 5631406, 2711395, 1062915, -5136345}, {-19240248, -11254599, -29509029, -7499965, -5835763, 13005411, -6066489, 12194497, 32960380, 1459310}, }, }, { { {19852034, 7027924, 23669353, 10020366, 8586503, -6657907, 394197, -6101885, 18638003, -11174937}, {31395534, 15098109, 26581030, 8030562, -16527914, -5007134, 9012486, -7584354, -6643087, -5442636}, {-9192165, -2347377, -1997099, 4529534, 25766844, 607986, -13222, 9677543, -32294889, -6456008}, }, { {-2444496, -149937, 29348902, 8186665, 1873760, 12489863, -30934579, -7839692, -7852844, -8138429}, {-15236356, -15433509, 7766470, 746860, 26346930, -10221762, -27333451, 10754588, -9431476, 5203576}, {31834314, 14135496, -770007, 5159118, 20917671, -16768096, -7467973, -7337524, 31809243, 7347066}, }, { {-9606723, -11874240, 20414459, 13033986, 13716524, -11691881, 19797970, -12211255, 15192876, -2087490}, {-12663563, -2181719, 1168162, -3804809, 26747877, -14138091, 10609330, 12694420, 33473243, -13382104}, {33184999, 11180355, 15832085, -11385430, -1633671, 225884, 15089336, -11023903, -6135662, 14480053}, }, { {31308717, -5619998, 31030840, -1897099, 15674547, -6582883, 5496208, 13685227, 27595050, 8737275}, {-20318852, -15150239, 10933843, -16178022, 8335352, -7546022, -31008351, -12610604, 26498114, 66511}, {22644454, -8761729, -16671776, 4884562, -3105614, -13559366, 30540766, -4286747, -13327787, -7515095}, }, { {-28017847, 9834845, 18617207, -2681312, -3401956, -13307506, 8205540, 13585437, -17127465, 15115439}, {23711543, -672915, 31206561, -8362711, 6164647, -9709987, -33535882, -1426096, 8236921, 16492939}, {-23910559, -13515526, -26299483, -4503841, 25005590, -7687270, 19574902, 10071562, 6708380, -6222424}, }, { {2101391, -4930054, 19702731, 2367575, -15427167, 1047675, 5301017, 9328700, 29955601, -11678310}, {3096359, 9271816, -21620864, -15521844, -14847996, -7592937, -25892142, -12635595, -9917575, 6216608}, {-32615849, 338663, -25195611, 2510422, -29213566, -13820213, 24822830, -6146567, -26767480, 7525079}, }, { {-23066649, -13985623, 16133487, -7896178, -3389565, 778788, -910336, -2782495, -19386633, 11994101}, {21691500, -13624626, -641331, -14367021, 3285881, -3483596, -25064666, 9718258, -7477437, 13381418}, {18445390, -4202236, 14979846, 11622458, -1727110, -3582980, 23111648, -6375247, 28535282, 15779576}, }, { {30098053, 3089662, -9234387, 16662135, -21306940, 11308411, -14068454, 12021730, 9955285, -16303356}, {9734894, -14576830, -7473633, -9138735, 2060392, 11313496, -18426029, 9924399, 20194861, 13380996}, {-26378102, -7965207, -22167821, 15789297, -18055342, -6168792, -1984914, 15707771, 26342023, 10146099}, }, }, { { {-26016874, -219943, 21339191, -41388, 19745256, -2878700, -29637280, 2227040, 21612326, -545728}, {-13077387, 1184228, 23562814, -5970442, -20351244, -6348714, 25764461, 12243797, -20856566, 11649658}, {-10031494, 11262626, 27384172, 2271902, 26947504, -15997771, 39944, 6114064, 33514190, 2333242}, }, { {-21433588, -12421821, 8119782, 7219913, -21830522, -9016134, -6679750, -12670638, 24350578, -13450001}, {-4116307, -11271533, -23886186, 4843615, -30088339, 690623, -31536088, -10406836, 8317860, 12352766}, {18200138, -14475911, -33087759, -2696619, -23702521, -9102511, -23552096, -2287550, 20712163, 6719373}, }, { {26656208, 6075253, -7858556, 1886072, -28344043, 4262326, 11117530, -3763210, 26224235, -3297458}, {-17168938, -14854097, -3395676, -16369877, -19954045, 14050420, 21728352, 9493610, 18620611, -16428628}, {-13323321, 13325349, 11432106, 5964811, 18609221, 6062965, -5269471, -9725556, -30701573, -16479657}, }, { {-23860538, -11233159, 26961357, 1640861, -32413112, -16737940, 12248509, -5240639, 13735342, 1934062}, {25089769, 6742589, 17081145, -13406266, 21909293, -16067981, -15136294, -3765346, -21277997, 5473616}, {31883677, -7961101, 1083432, -11572403, 22828471, 13290673, -7125085, 12469656, 29111212, -5451014}, }, { {24244947, -15050407, -26262976, 2791540, -14997599, 16666678, 24367466, 6388839, -10295587, 452383}, {-25640782, -3417841, 5217916, 16224624, 19987036, -4082269, -24236251, -5915248, 15766062, 8407814}, {-20406999, 13990231, 15495425, 16395525, 5377168, 15166495, -8917023, -4388953, -8067909, 2276718}, }, { {30157918, 12924066, -17712050, 9245753, 19895028, 3368142, -23827587, 5096219, 22740376, -7303417}, {2041139, -14256350, 7783687, 13876377, -25946985, -13352459, 24051124, 13742383, -15637599, 13295222}, {33338237, -8505733, 12532113, 7977527, 9106186, -1715251, -17720195, -4612972, -4451357, -14669444}, }, { {-20045281, 5454097, -14346548, 6447146, 28862071, 1883651, -2469266, -4141880, 7770569, 9620597}, {23208068, 7979712, 33071466, 8149229, 1758231, -10834995, 30945528, -1694323, -33502340, -14767970}, {1439958, -16270480, -1079989, -793782, 4625402, 10647766, -5043801, 1220118, 30494170, -11440799}, }, { {-5037580, -13028295, -2970559, -3061767, 15640974, -6701666, -26739026, 926050, -1684339, -13333647}, {13908495, -3549272, 30919928, -6273825, -21521863, 7989039, 9021034, 9078865, 3353509, 4033511}, {-29663431, -15113610, 32259991, -344482, 24295849, -12912123, 23161163, 8839127, 27485041, 7356032}, }, }, { { {9661027, 705443, 11980065, -5370154, -1628543, 14661173, -6346142, 2625015, 28431036, -16771834}, {-23839233, -8311415, -25945511, 7480958, -17681669, -8354183, -22545972, 14150565, 15970762, 4099461}, {29262576, 16756590, 26350592, -8793563, 8529671, -11208050, 13617293, -9937143, 11465739, 8317062}, }, { {-25493081, -6962928, 32500200, -9419051, -23038724, -2302222, 14898637, 3848455, 20969334, -5157516}, {-20384450, -14347713, -18336405, 13884722, -33039454, 2842114, -21610826, -3649888, 11177095, 14989547}, {-24496721, -11716016, 16959896, 2278463, 12066309, 10137771, 13515641, 2581286, -28487508, 9930240}, }, { {-17751622, -2097826, 16544300, -13009300, -15914807, -14949081, 18345767, -13403753, 16291481, -5314038}, {-33229194, 2553288, 32678213, 9875984, 8534129, 6889387, -9676774, 6957617, 4368891, 9788741}, {16660756, 7281060, -10830758, 12911820, 20108584, -8101676, -21722536, -8613148, 16250552, -11111103}, }, { {-19765507, 2390526, -16551031, 14161980, 1905286, 6414907, 4689584, 10604807, -30190403, 4782747}, {-1354539, 14736941, -7367442, -13292886, 7710542, -14155590, -9981571, 4383045, 22546403, 437323}, {31665577, -12180464, -16186830, 1491339, -18368625, 3294682, 27343084, 2786261, -30633590, -14097016}, }, { {-14467279, -683715, -33374107, 7448552, 19294360, 14334329, -19690631, 2355319, -19284671, -6114373}, {15121312, -15796162, 6377020, -6031361, -10798111, -12957845, 18952177, 15496498, -29380133, 11754228}, {-2637277, -13483075, 8488727, -14303896, 12728761, -1622493, 7141596, 11724556, 22761615, -10134141}, }, { {16918416, 11729663, -18083579, 3022987, -31015732, -13339659, -28741185, -12227393, 32851222, 11717399}, {11166634, 7338049, -6722523, 4531520, -29468672, -7302055, 31474879, 3483633, -1193175, -4030831}, {-185635, 9921305, 31456609, -13536438, -12013818, 13348923, 33142652, 6546660, -19985279, -3948376}, }, { {-32460596, 11266712, -11197107, -7899103, 31703694, 3855903, -8537131, -12833048, -30772034, -15486313}, {-18006477, 12709068, 3991746, -6479188, -21491523, -10550425, -31135347, -16049879, 10928917, 3011958}, {-6957757, -15594337, 31696059, 334240, 29576716, 14796075, -30831056, -12805180, 18008031, 10258577}, }, { {-22448644, 15655569, 7018479, -4410003, -30314266, -1201591, -1853465, 1367120, 25127874, 6671743}, {29701166, -14373934, -10878120, 9279288, -17568, 13127210, 21382910, 11042292, 25838796, 4642684}, {-20430234, 14955537, -24126347, 8124619, -5369288, -5990470, 30468147, -13900640, 18423289, 4177476}, }, }, }; void TableLookup(GePre *preCompute, int32_t pos, int8_t e) { GePre negate; // Prevent side-channel attack: Do not use conditional statements to ensure that the execution time is constant. // -negative = 11111111 if e is negative, or 0 if e is not // (-negative & e) << 1 = 2e if e is negative, or 0 if e is positive // absolute value = e - 2e (e negative) or e (e positive) uint8_t negative = (uint8_t)e >> 7; // shift 7 to check negative // range of e is -7 to 8, left shift won't cause sign change uint8_t abs = (uint8_t)(e - ((uint8_t)(-negative & (uint8_t)e) << 1)); // set base result CURVE25519_FP_SET(preCompute->yplusx, 1); CURVE25519_FP_SET(preCompute->yminusx, 1); CURVE25519_FP_SET(preCompute->xy2d, 0); // only copy the corrsponding position ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][0], abs == 1); // 1 of 8 ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][1], abs == 2); // 2 of 8 ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][2], abs == 3); // 3 of 8 ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][3], abs == 4); // 4 of 8 ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][4], abs == 5); // 5 of 8 ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][5], abs == 6); // 6 of 8 ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][6], abs == 7); // 7 of 8 ConditionalMove(preCompute, &CURVE25519PRE_COMPUTE[pos][7], abs == 8); // 8 of 8 CURVE25519_FP_COPY(negate.yminusx, preCompute->yplusx); CURVE25519_FP_COPY(negate.yplusx, preCompute->yminusx); CURVE25519_FP_NEGATE(negate.xy2d, preCompute->xy2d); ConditionalMove(preCompute, &negate, negative); } #endif /* HITLS_CRYPTO_CURVE25519 */
2302_82127028/openHiTLS-examples_1556
crypto/curve25519/src/curve25519_table.c
C
unknown
96,121
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_X25519 #include "securec.h" #include "curve25519_local.h" // X25519 alternative implementation, faster but require int128 #if (defined(__SIZEOF_INT128__) && (__SIZEOF_INT128__ == 16)) #define CURVE25519_51BITS_MASK 0x7ffffffffffff #define CURVE25519_51BITS 51 static void Fp51DataToPoly(Fp51 *out, const uint8_t in[32]) { uint64_t h[5]; CURVE25519_BYTES7_LOAD(h, in); CURVE25519_BYTES6_LOAD(h + 1, in + 7); h[1] <<= 5; CURVE25519_BYTES7_LOAD(h + 2, in + 13); h[2] <<= 2; CURVE25519_BYTES6_LOAD(h + 3, in + 20); h[3] <<= 7; CURVE25519_BYTES6_LOAD(h + 4, in + 26); h[4] &= 0x7fffffffffff; // 41 bits mask = 0x7fffffffffff h[4] <<= 4; h[1] |= h[0] >> CURVE25519_51BITS; h[0] &= CURVE25519_51BITS_MASK; h[2] |= h[1] >> CURVE25519_51BITS; h[1] &= CURVE25519_51BITS_MASK; h[3] |= h[2] >> CURVE25519_51BITS; h[2] &= CURVE25519_51BITS_MASK; h[4] |= h[3] >> CURVE25519_51BITS; h[3] &= CURVE25519_51BITS_MASK; out->data[0] = h[0]; out->data[1] = h[1]; out->data[2] = h[2]; out->data[3] = h[3]; out->data[4] = h[4]; } static void Fp51UnloadTo8Bits(uint8_t out[32], uint64_t h[5]) { // load from uint64 to uint8, load 8 bits at a time out[0] = (uint8_t)h[0]; out[1] = (uint8_t)(h[0] >> 8); out[2] = (uint8_t)(h[0] >> 16); out[3] = (uint8_t)(h[0] >> 24); out[4] = (uint8_t)(h[0] >> 32); out[5] = (uint8_t)(h[0] >> 40); // load from position 48 from h[1] and (8-5)=3 bits from h[1] to out[6] out[6] = (uint8_t)((h[0] >> 48) | (uint8_t)(h[1] << 3)); out[7] = (uint8_t)(h[1] >> 5); out[8] = (uint8_t)(h[1] >> 13); out[9] = (uint8_t)(h[1] >> 21); out[10] = (uint8_t)(h[1] >> 29); out[11] = (uint8_t)(h[1] >> 37); // load from position 45 from h[1] and (8-2)=6 bits from h[2] to out[12] out[12] = (uint8_t)((h[1] >> 45) | (uint8_t)(h[2] << 6)); out[13] = (uint8_t)(h[2] >> 2); out[14] = (uint8_t)(h[2] >> 10); out[15] = (uint8_t)(h[2] >> 18); out[16] = (uint8_t)(h[2] >> 26); out[17] = (uint8_t)(h[2] >> 34); out[18] = (uint8_t)(h[2] >> 42); // load from position 50 from h[2] and (8-1)=7 bits from h[3] to out[19] out[19] = (uint8_t)((h[2] >> 50) | (uint8_t)(h[3] << 1)); out[20] = (uint8_t)(h[3] >> 7); out[21] = (uint8_t)(h[3] >> 15); out[22] = (uint8_t)(h[3] >> 23); out[23] = (uint8_t)(h[3] >> 31); out[24] = (uint8_t)(h[3] >> 39); // load from position 47 from h[3] and (4-4)=4 bits from h[4] to out[25] out[25] = (uint8_t)((h[3] >> 47) | (uint8_t)(h[4] << 4)); out[26] = (uint8_t)(h[4] >> 4); out[27] = (uint8_t)(h[4] >> 12); out[28] = (uint8_t)(h[4] >> 20); out[29] = (uint8_t)(h[4] >> 28); out[30] = (uint8_t)(h[4] >> 36); out[31] = (uint8_t)(h[4] >> 44); } static void Fp51PolyToData(const Fp51 *in, uint8_t out[32]) { uint64_t h[5]; h[0] = in->data[0]; h[1] = in->data[1]; h[2] = in->data[2]; h[3] = in->data[3]; h[4] = in->data[4]; uint64_t carry; carry = (h[0] + 19) >> CURVE25519_51BITS; // plus 19 then calculate carry carry = (h[1] + carry) >> CURVE25519_51BITS; carry = (h[2] + carry) >> CURVE25519_51BITS; carry = (h[3] + carry) >> CURVE25519_51BITS; carry = (h[4] + carry) >> CURVE25519_51BITS; h[0] += 19 * carry; // process carry h[4] -> h[0], h[0] += 19 * carry h[1] += h[0] >> CURVE25519_51BITS; h[0] &= CURVE25519_51BITS_MASK; h[2] += h[1] >> CURVE25519_51BITS; h[1] &= CURVE25519_51BITS_MASK; h[3] += h[2] >> CURVE25519_51BITS; h[2] &= CURVE25519_51BITS_MASK; h[4] += h[3] >> CURVE25519_51BITS; h[3] &= CURVE25519_51BITS_MASK; h[4] &= CURVE25519_51BITS_MASK; Fp51UnloadTo8Bits(out, h); } void Fp51ProcessCarry(__uint128_t in[5]) { in[1] += (uint64_t)(in[0] >> CURVE25519_51BITS); in[0] = (uint64_t)in[0] & CURVE25519_51BITS_MASK; in[2] += (uint64_t)(in[1] >> CURVE25519_51BITS); in[1] = (uint64_t)in[1] & CURVE25519_51BITS_MASK; in[3] += (uint64_t)(in[2] >> CURVE25519_51BITS); in[2] = (uint64_t)in[2] & CURVE25519_51BITS_MASK; in[4] += (uint64_t)(in[3] >> CURVE25519_51BITS); in[3] = (uint64_t)in[3] & CURVE25519_51BITS_MASK; in[0] += (uint64_t)(in[4] >> CURVE25519_51BITS) * 19; in[4] = (uint64_t)in[4] & CURVE25519_51BITS_MASK; in[1] += in[0] >> CURVE25519_51BITS; in[0] &= CURVE25519_51BITS_MASK; } void Fp51Mul(Fp51 *out, const Fp51 *f, const Fp51 *g) { __uint128_t h[5]; // h[0] = f0g0 + 19*f1g4 + 19*f2g3 + 19*f3g2 + 19*f4g1 h[0] = (__uint128_t)f->data[0] * g->data[0] + (__uint128_t)f->data[1] * g->data[4] * 19 + (__uint128_t)f->data[2] * g->data[3] * 19 + (__uint128_t)f->data[3] * g->data[2] * 19 + // 19*f2g3 + 19*f3g2 (__uint128_t)f->data[4] * g->data[1] * 19; // 19*f4g1 // h[1] = f0g1 + f1g0 + 19*f2g4 + 19*f3g3 + 19*f4g2 h[1] = (__uint128_t)f->data[0] * g->data[1] + (__uint128_t)f->data[1] * g->data[0] + (__uint128_t)f->data[2] * g->data[4] * 19 + (__uint128_t)f->data[3] * g->data[3] * 19 + // 19*f2g4 + 19*f3g3 (__uint128_t)f->data[4] * g->data[2] * 19; // 19*f4g2 // h[2] = f0g2 + f1g1 + f2g0 + 19*f3g4 + 19*f4g3 h[2] = (__uint128_t)f->data[0] * g->data[2] + (__uint128_t)f->data[1] * g->data[1] + (__uint128_t)f->data[2] * g->data[0] + (__uint128_t)f->data[3] * g->data[4] * 19 + // f2g0 + 19*f3g4 (__uint128_t)f->data[4] * g->data[3] * 19; // 19*f4g3 // h[3] = f0g3 + f1g2 + f2g1 + f3g0 + 19*f4g4 h[3] = (__uint128_t)f->data[0] * g->data[3] + (__uint128_t)f->data[1] * g->data[2] + (__uint128_t)f->data[2] * g->data[1] + (__uint128_t)f->data[3] * g->data[0] + // f2g1 + f3g0 (__uint128_t)f->data[4] * g->data[4] * 19; // 19*f4g4 // h[4] = f0g4 + f1g3 + f2g2 + f3g1 + f4g0 h[4] = (__uint128_t)f->data[0] * g->data[4] + (__uint128_t)f->data[1] * g->data[3] + (__uint128_t)f->data[2] * g->data[2] + (__uint128_t)f->data[3] * g->data[1] + // f2g2 + f3g1 (__uint128_t)f->data[4] * g->data[0]; // f4g0 Fp51ProcessCarry(h); out->data[0] = (uint64_t)h[0]; out->data[1] = (uint64_t)h[1]; out->data[2] = (uint64_t)h[2]; out->data[3] = (uint64_t)h[3]; out->data[4] = (uint64_t)h[4]; } void Fp51Square(Fp51 *out, const Fp51 *in) { __uint128_t h[5]; uint64_t in0mul2 = in->data[0] * 2; uint64_t in1mul2 = in->data[1] * 2; uint64_t in2mul2 = in->data[2] * 2; uint64_t in3mul19 = in->data[3] * 19; uint64_t in4mul19 = in->data[4] * 19; // h0 = in0^2 + 38 * in1 * in4 + 38 * in2 * in3 h[0] = (__uint128_t)in->data[0] * in->data[0] + (__uint128_t)in1mul2 * in4mul19 + (__uint128_t)in2mul2 * in3mul19; // h1 = 2 * in0 * in1 + 19 * in3^2 + 38 * in2 * in4 h[1] = (__uint128_t)in0mul2 * in->data[1] + (__uint128_t)in->data[3] * in3mul19 + (__uint128_t)in2mul2 * in4mul19; // h2 = 2 * in0 * in2 + in1^2 + 38 * in3 * in4 h[2] = (__uint128_t)in0mul2 * in->data[2] + (__uint128_t)in->data[1] * in->data[1] + (__uint128_t)(in->data[3] * 2) * in4mul19; // 2 * 19 * in3 * in4 // h3 = 2 * in0 * in3 + 19 * in4^2 + 2 * in1 * in2 h[3] = (__uint128_t)in0mul2 * in->data[3] + (__uint128_t)in->data[4] * in4mul19 + (__uint128_t)in1mul2 * in->data[2]; // 2 * in1 * in2 // h4 = 2 * in0 * in4 + 2 * in1 * in3 + in2^2 h[4] = (__uint128_t)in0mul2 * in->data[4] + (__uint128_t)in1mul2 * in->data[3] + (__uint128_t)in->data[2] * in->data[2]; // in2^2 Fp51ProcessCarry(h); out->data[0] = (uint64_t)h[0]; out->data[1] = (uint64_t)h[1]; out->data[2] = (uint64_t)h[2]; out->data[3] = (uint64_t)h[3]; out->data[4] = (uint64_t)h[4]; } void Fp51MulScalar(Fp51 *out, const Fp51 *in, const uint32_t scalar) { __uint128_t h[5]; h[0] = in->data[0] * (__uint128_t)scalar; h[1] = in->data[1] * (__uint128_t)scalar; h[2] = in->data[2] * (__uint128_t)scalar; h[3] = in->data[3] * (__uint128_t)scalar; h[4] = in->data[4] * (__uint128_t)scalar; Fp51ProcessCarry(h); out->data[0] = (uint64_t)h[0]; out->data[1] = (uint64_t)h[1]; out->data[2] = (uint64_t)h[2]; out->data[3] = (uint64_t)h[3]; out->data[4] = (uint64_t)h[4]; } /* out = in1 ^ (4 * 2 ^ (2 * times)) * in2 */ static inline void Fp51MultiSquare(Fp51 *in1, Fp51 *in2, Fp51 *out, int32_t times) { int32_t i; Fp51 temp1, temp2; Fp51Square(&temp1, in1); Fp51Square(&temp2, &temp1); for (i = 0; i < times; i++) { Fp51Square(&temp1, &temp2); Fp51Square(&temp2, &temp1); } Fp51Mul(out, in2, &temp2); } /* out = a ^ -1 */ static void Fp51Invert(Fp51 *out, const Fp51 *a) { Fp51 a0; /* save a^1 */ Fp51 a1; /* save a^2 */ Fp51 a2; /* save a^11 */ Fp51 a3; /* save a^(2^5-1) */ Fp51 a4; /* save a^(2^10-1) */ Fp51 a5; /* save a^(2^20-1) */ Fp51 a6; /* save a^(2^40-1) */ Fp51 a7; /* save a^(2^50-1) */ Fp51 a8; /* save a^(2^100-1) */ Fp51 a9; /* save a^(2^200-1) */ Fp51 a10; /* save a^(2^250-1) */ Fp51 temp1, temp2; /* We know a×b=1(mod p), then a and b are inverses of mod p, i.e. a=b^(-1), b=a^(-1); * According to Fermat's little theorem a^(p-1)=1(mod p), so a*a^(p-2)=1(mod p); * So the inverse element of a is a^(-1) = a^(p-2)(mod p) * Here it is, p=2^255-19, thus we need to compute a^(2^255-21)(mod(2^255-19)) */ /* a^1 */ CURVE25519_FP51_COPY(a0.data, a->data); /* a^2 */ Fp51Square(&a1, &a0); /* a^4 */ Fp51Square(&temp1, &a1); /* a^8 */ Fp51Square(&temp2, &temp1); /* a^9 */ Fp51Mul(&temp1, &a0, &temp2); /* a^11 */ Fp51Mul(&a2, &a1, &temp1); /* a^22 */ Fp51Square(&temp2, &a2); /* a^(2^5-1) = a^(9+22) */ Fp51Mul(&a3, &temp1, &temp2); /* a^(2^10-1) = a^(2^10-2^5) * a^(2^5-1) */ Fp51Square(&temp1, &a3); Fp51Square(&temp2, &temp1); Fp51Square(&temp1, &temp2); Fp51Square(&temp2, &temp1); Fp51Square(&temp1, &temp2); Fp51Mul(&a4, &a3, &temp1); /* a^(2^20-1) = a^(2^20-2^10) * a^(2^10-1) */ Fp51MultiSquare(&a4, &a4, &a5, 4); // (2 * 2) ^ 4 /* a^(2^40-1) = a^(2^40-2^20) * a^(2^20-1) */ Fp51MultiSquare(&a5, &a5, &a6, 9); // (2 * 2) ^ 9 /* a^(2^50-1) = a^(2^50-2^10) * a^(2^10-1) */ Fp51MultiSquare(&a6, &a4, &a7, 4); // (2 * 2) ^ 4 /* a^(2^100-1) = a^(2^100-2^50) * a^(2^50-1) */ Fp51MultiSquare(&a7, &a7, &a8, 24); // (2 * 2) ^ 24 /* a^(2^200-1) = a^(2^200-2^100) * a^(2^100-1) */ Fp51MultiSquare(&a8, &a8, &a9, 49); // (2 * 2) ^ 49 /* a^(2^250-1) = a^(2^250-2^50) * a^(2^50-1) */ Fp51MultiSquare(&a9, &a7, &a10, 24); // (2 * 2) ^ 24 /* a^(2^5*(2^250-1)) = (a^(2^250-1))^5 */ Fp51Square(&temp1, &a10); Fp51Square(&temp2, &temp1); Fp51Square(&temp1, &temp2); Fp51Square(&temp2, &temp1); Fp51Square(&temp1, &temp2); /* The output: a^(2^255-21) = a(2^5*(2^250-1)+11) = a^(2^5*(2^250-1)) * a^11 */ Fp51Mul(out, &a2, &temp1); } void ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32]) { uint8_t k[32]; const uint8_t *u = point; int32_t t; uint32_t swap; uint32_t kTemp; Fp51 x1, x2, x3; Fp51 z2, z3; Fp51 t1, t2; /* Decord the scalar into k */ CURVE25519_DECODE_LITTLE_ENDIAN(k, scalar); /* Reference RFC 7748 section 5: The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 */ Fp51DataToPoly(&x1, u); CURVE25519_FP51_SET(x2.data, 1); CURVE25519_FP51_SET(z2.data, 0); CURVE25519_FP51_COPY(x3.data, x1.data); CURVE25519_FP51_SET(z3.data, 1); swap = 0; /* "bits" parameter set to 255 for x25519 */ /* For t = bits-1(254) down to 0: */ for (t = 254; t >= 0; t--) { /* t >> 3: calculation the index of bit; t & 7: Obtains the corresponding bit in the byte */ kTemp = (k[(uint32_t)t >> 3] >> ((uint32_t)t & 7)) & 1; /* kTemp = (k >> t) & 1 */ swap ^= kTemp; /* swap ^= kTemp */ CURVE25519_FP51_CSWAP(swap, x2.data, x3.data); /* (x_2, x_3) = cswap(swap, x_2, x_3) */ CURVE25519_FP51_CSWAP(swap, z2.data, z3.data); /* (z_2, z_3) = cswap(swap, z_2, z_3) */ swap = kTemp; /* swap = kTemp */ CURVE25519_FP51_SUB(t1.data, x3.data, z3.data); /* x3 = D */ CURVE25519_FP51_SUB(t2.data, x2.data, z2.data); /* t2 = B */ CURVE25519_FP51_ADD(x2.data, x2.data, z2.data); /* t1 = A */ CURVE25519_FP51_ADD(z2.data, x3.data, z3.data); /* x2 = C */ Fp51Mul(&z3, &t1, &x2); Fp51Mul(&z2, &z2, &t2); Fp51Square(&t1, &t2); Fp51Square(&t2, &x2); CURVE25519_FP51_ADD(x3.data, z3.data, z2.data); CURVE25519_FP51_SUB(z2.data, z3.data, z2.data); Fp51Mul(&x2, &t2, &t1); CURVE25519_FP51_SUB(t2.data, t2.data, t1.data); Fp51Square(&z2, &z2); Fp51MulScalar(&z3, &t2, 121666); // z2 *= 121665 + 1 = 121666 Fp51Square(&x3, &x3); CURVE25519_FP51_ADD(t1.data, t1.data, z3.data); Fp51Mul(&z3, &x1, &z2); Fp51Mul(&z2, &t2, &t1); } CURVE25519_FP51_CSWAP(swap, x2.data, x3.data); CURVE25519_FP51_CSWAP(swap, z2.data, z3.data); /* Return x2 * (z2 ^ (p - 2)) */ Fp51Invert(&t1, &z2); Fp51Mul(&t2, &x2, &t1); Fp51PolyToData(&t2, out); BSL_SAL_CleanseData(k, sizeof(k)); } #else void FpMulScalar(Fp25 out, const Fp25 p, const int32_t scalar) { int64_t s = (int64_t)scalar; uint64_t over; uint64_t result[10]; uint64_t mul19; uint64_t t1; uint64_t signMask1; uint64_t signMask2; /* Could be more than 32 bits but not be more than 64 bits */ CURVE25519_FP_MUL_SCALAR(result, p, s); /* Process Carry */ /* the radix 2^25.5 representation: * f0+2^26*f1+2^51*f2+2^77*f3+2^102*f4+2^128*f5+2^153*f6+2^179*f7+2^204*f8+2^230*f9 */ over = result[9] + (1 << 24); /* carry chain: index 9->0; 2^25 progressiv, left shift by 24 bits */ signMask1 = MASK_HIGH64(25) & (-((over) >> 63)); /* 2^25 progressiv, shift 63 for sign */ t1 = (over >> 25) | signMask1; mul19 = (t1 + (t1 << 1) + (t1 << 4)); /* 19 = 1 + 2^1 + 2^4 */ result[0] += mul19; /* carry chain: index 9->0 */ result[9] -= CURVE25519_MASK_HIGH_39 & over; /* carry chain: index 1->2; 2^25 progressiv(26->51) */ /* carry chain: index 1->2; 2^25 progressiv, left shift by 24 bits */ PROCESS_CARRY(result[1], result[2], signMask1, over, 24); /* carry chain: index 3->4; 2^25 progressiv(77->102) */ /* carry chain: index 3->4; 2^25 progressiv, left shift by 24 bits */ PROCESS_CARRY(result[3], result[4], signMask1, over, 24); /* carry chain: index 5->6; 2^25 progressiv(128->153) */ /* carry chain: index 5->6; 2^25 progressiv, left shift by 24 bits */ PROCESS_CARRY(result[5], result[6], signMask1, over, 24); /* carry chain: index 7->8; 2^25 progressiv(179->204) */ /* carry chain: index 7->8; 2^25 progressiv, left shift by 24 bits */ PROCESS_CARRY(result[7], result[8], signMask1, over, 24); /* carry chain: index 0->1; 2^26 progressiv(0->26) */ /* carry chain: index 0->1; 2^26 progressiv, left shift by 25 bits */ PROCESS_CARRY(result[0], result[1], signMask2, over, 25); /* carry chain: index 2->3; 2^26 progressiv(51->77) */ /* carry chain: index 2->3; 2^26 progressiv, left shift by 25 bits */ PROCESS_CARRY(result[2], result[3], signMask2, over, 25); /* carry chain: index 4->5; 2^26 progressiv(102->128) */ /* carry chain: index 4->5; 2^26 progressiv, left shift by 25 bits */ PROCESS_CARRY(result[4], result[5], signMask2, over, 25); /* carry chain: index 6->7; 2^26 progressiv(153->179) */ /* carry chain: index 6->7; 2^26 progressiv, left shift by 25 bits */ PROCESS_CARRY(result[6], result[7], signMask2, over, 25); /* carry chain: index 8->9; 2^26 progressiv(204->230) */ /* carry chain: index 8->9; 2^26 progressiv, left shift by 25 bits */ PROCESS_CARRY(result[8], result[9], signMask2, over, 25); /* The result would not be more than 32 bits */ out[0] = (int32_t)result[0]; // 0 out[1] = (int32_t)result[1]; // 1 out[2] = (int32_t)result[2]; // 2 out[3] = (int32_t)result[3]; // 3 out[4] = (int32_t)result[4]; // 4 out[5] = (int32_t)result[5]; // 5 out[6] = (int32_t)result[6]; // 6 out[7] = (int32_t)result[7]; // 7 out[8] = (int32_t)result[8]; // 8 out[9] = (int32_t)result[9]; // 9 (void)memset_s(result, sizeof(result), 0, sizeof(result)); } void ScalarMultiPoint(uint8_t out[32], const uint8_t scalar[32], const uint8_t point[32]) { uint8_t k[32]; const uint8_t *u = point; int32_t t; uint32_t swap; uint32_t kTemp; Fp25 x1, x2, x3, z2, z3, t1, t2, t3; /* Decord the scalar into k */ CURVE25519_DECODE_LITTLE_ENDIAN(k, scalar); /* Reference RFC 7748 section 5:The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 */ DataToPolynomial(x1, u); CURVE25519_FP_SET(x2, 1); CURVE25519_FP_SET(z2, 0); CURVE25519_FP_COPY(x3, x1); CURVE25519_FP_SET(z3, 1); swap = 0; /* "bits" parameter set to 255 for x25519 */ /* For t = bits-1(254) down to 0: */ for (t = 254; t >= 0; t--) { /* t >> 3: calculation the index of bit; t & 7: Obtains the corresponding bit in the byte */ kTemp = (k[(uint32_t)t >> 3] >> ((uint32_t)t & 7)) & 1; /* kTemp = (k >> t) & 1 */ swap ^= kTemp; /* swap ^= kTemp */ CURVE25519_FP_CSWAP(swap, x2, x3); /* (x_2, x_3) = cswap(swap, x_2, x_3) */ CURVE25519_FP_CSWAP(swap, z2, z3); /* (z_2, z_3) = cswap(swap, z_2, z_3) */ swap = kTemp; /* swap = kTemp */ CURVE25519_FP_ADD(t1, x2, z2); /* t1 = A */ CURVE25519_FP_SUB(t2, x2, z2); /* t2 = B */ CURVE25519_FP_ADD(x2, x3, z3); /* x2 = C */ CURVE25519_FP_SUB(x3, x3, z3); /* x3 = D */ FpMul(z2, x3, t1); /* z2 = DA */ FpMul(z3, x2, t2); /* z3 = CB */ FpSquareDoubleCore(t1, t1, false); /* t1 = AA */ FpSquareDoubleCore(t2, t2, false); /* t2 = BB */ CURVE25519_FP_SUB(t3, t1, t2); /* t3 = E = AA - BB */ CURVE25519_FP_ADD(x3, z2, z3); /* x3 = DA + CB */ FpSquareDoubleCore(x3, x3, false); /* x3 = (DA + CB)^2 */ CURVE25519_FP_SUB(z3, z2, z3); /* z3 = DA - CB */ FpSquareDoubleCore(z3, z3, false); /* z3 = (DA - CB)^2 */ FpMul(z3, x1, z3); /* z3 = x1 * (DA - CB)^2 */ FpMul(x2, t1, t2); /* x2 = AA * BB */ FpMul(t1, t3, t1); /* t1 = E * AA */ FpSquareDoubleCore(z2, t3, false); /* z2 = E^2 */ /* Reference RFC 7748 section 5:The constant a24 is (486662 - 2) / 4 = 121665 for curve25519/X25519 */ FpMulScalar(z2, z2, 121665); /* z2 = a24 * E^2 */ CURVE25519_FP_ADD(z2, t1, z2); /* z2 = E * (AA + a24 * E) */ } CURVE25519_FP_CSWAP(swap, x2, x3); CURVE25519_FP_CSWAP(swap, z2, z3); /* Return x2 * (z2 ^ (p - 2)) */ FpInvert(t1, z2); FpMul(t2, x2, t1); PolynomialToData(out, t2); } #endif // uint128 #endif /* HITLS_CRYPTO_X25519 */
2302_82127028/openHiTLS-examples_1556
crypto/curve25519/src/noasm_curve25519_fp51_ops.c
C
unknown
20,251
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef X25519_ASM_H #define X25519_ASM_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_X25519 #include "curve25519_local.h" #ifdef __cplusplus extern "C" { #endif /** * Function description: out = f * g (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field. * Function prototype: void Fp51Mul(Fp51 *out, const Fp51 *f, const Fp51 *g); * Input register: rdi: out; rsi: f; rdx: g; fp51 is an array of [u64; 5]. * rdi: out, array pointer of output parameter fp51. * rsi: pointer f of the input source data fp51 array. * rdx: pointer g of the input source data fp51 array. * Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15. * Output register: None * Function/Macro Call: None */ void Fp51Mul(Fp51 *out, const Fp51 *f, const Fp51 *g); /** * Function description: out = f ^ 2 (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field. * Function prototype: void Fp51Square(Fp51 *out, const Fp51 *f); * Input register: rdi: out; rsi: f; fp51 is an array of [u64; 5] * rdi: out, array pointer of output parameter fp51. * rsi: pointer f of the input source data fp51 array. * Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15. * Output register: None * Function/Macro Call: None */ void Fp51Square(Fp51 *out, const Fp51 *f); /** * Function description: out = f * 121666 (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field. * Function prototype: void Fp51MulScalar(Fp51 *out, const Fp51 *f, const uint32_t scalar); * Input register: rdi: out; rsi: f; fp51 is an array of [u64; 5] * rdi: out, array pointer of output parameter fp51. * rsi: pointer f of the input source data fp51 array. * Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15. * Output register: None * Function/Macro Call: None */ void Fp51MulScalar(Fp51 *out, const Fp51 *in); #ifdef HITLS_CRYPTO_X25519_X8664 typedef uint64_t Fp64[4]; /** * Function description: out = f * g (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field. * Function prototype: void Fp64Mul(Fp64 h, const Fp64 f, const Fp64 g); * Input register: rdi: out; rsi: f; rdx: g; Fp64 is an array of [u64; 4]. * rdi: out, array pointer of output parameter Fp64. * rsi: pointer f of the input source data Fp64 array. * rdx: pointer g of the input source data Fp64 array. * Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15. * Output register: None * Function/Macro Call: None */ void Fp64Mul(Fp64 out, const Fp64 f, const Fp64 g); /** * Function description: out = f ^ 2 (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field. * Function prototype: void Fp64Sqr(Fp64 h, const Fp64 f); * Input register: rdi: out; rsi: f; Fp64 is an array of [u64; 4] * rdi: out, array pointer of output parameter Fp64. * rsi: pointer f of the input source data Fp64 array. * Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15. * Output register: None * Function/Macro Call: None */ void Fp64Sqr(Fp64 out, const Fp64 f); /** * Function description: out = f * 121666 (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field. * Function prototype: void Fp64MulScalar(Fp64 h, Fp64 f); * Input register: rdi: out; rsi: f; Fp64 is an array of [u64; 4] * rdi: out, array pointer of output parameter Fp64. * rsi: pointer f of the input source data Fp64 array. * Modify the register as follows: rax, rbx, rcx, rdx, rsp, rbp, rsi, rdi, r8-r15. * Output register: None * Function/Macro Call: None */ void Fp64MulScalar(Fp64 out, Fp64 f); /** * Function description: out = f + g (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field. * Function prototype: void Fp64Add(Fp64 h, const Fp64 f, const Fp64 g); * Input register: rdi: out; rsi: f; Fp64 is an array of [u64; 4] * rdi: out, array pointer of output parameter Fp64. * rsi: pointer f of the input source data Fp64 array. * rdx: pointer g of the input source data Fp64 array. * Modify the register as follows: rax, rcx, r8-r11. * Output register: None * Function/Macro Call: None */ void Fp64Add(Fp64 out, const Fp64 f, const Fp64 g); /** * Function description: out = f - g (mod p), p = 2 ^ 255 - 19, which is the modulus of curve25519 field. * Function prototype: void Fp64Sub(Fp64 h, const Fp64 f, const Fp64 g); * Input register: rdi: out; rsi: f; Fp64 is an array of [u64; 4] * rdi: out, array pointer of output parameter Fp64. * rsi: pointer f of the input source data Fp64 array. * rdx: pointer g of the input source data Fp64 array. * Modify the register as follows: rax, rcx, r8-r11. * Output register: None * Function/Macro Call: None */ void Fp64Sub(Fp64 out, const Fp64 f, const Fp64 g); /** * Function description: data conversion. * Function prototype: void Fp64PolyToData(uint8_t *out, const Fp64 f); * Input register: rdi: out; rsi: f; Fp64 is an array of [u64; 4] * rdi: out, array pointer of output parameter Fp64. * rsi: pointer f of the input source data Fp64 array. * Modify the register as follows: rax, rcx, r8-r11. * Output register: None * Function/Macro Call: None */ void Fp64PolyToData(uint8_t *out, const Fp64 f); #endif #ifdef __cplusplus } #endif #endif /* HITLS_CRYPTO_X25519 */ #endif // X25519_ASM_H
2302_82127028/openHiTLS-examples_1556
crypto/curve25519/src/x25519_asm.h
C
unknown
6,217
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #ifndef CRYPT_DH_H #define CRYPT_DH_H #include "hitls_build.h" #ifdef HITLS_CRYPTO_DH #include <stdint.h> #include "crypt_types.h" #include "crypt_algid.h" #include "bsl_params.h" #ifdef __cplusplus extern "C" { #endif /* __cpluscplus */ #ifndef CRYPT_DH_TRY_CNT_MAX #define CRYPT_DH_TRY_CNT_MAX 100 #endif /* DH key parameter */ typedef struct DH_Para CRYPT_DH_Para; /* DH key context */ typedef struct DH_Ctx CRYPT_DH_Ctx; /** * @ingroup dh * @brief dh Allocate the context of dh. * * @retval (CRYPT_DH_Ctx *) Pointer to the memory space of the allocated context * @retval NULL Invalid null pointer */ CRYPT_DH_Ctx *CRYPT_DH_NewCtx(void); /** * @ingroup dh * @brief dh Allocate the context of dh. * * @param libCtx [IN] Library context * * @retval (CRYPT_DH_Ctx *) Pointer to the memory space of the allocated context * @retval NULL Invalid null pointer */ CRYPT_DH_Ctx *CRYPT_DH_NewCtxEx(void *libCtx); /** * @ingroup dh * @brief Copy the DH context. After the duplicated context is used up, call CRYPT_DH_FreeCtx to release the memory. * * @param ctx [IN] Source DH context * * @return CRYPT_DH_Ctx DH context pointer * If the operation fails, null is returned. */ CRYPT_DH_Ctx *CRYPT_DH_DupCtx(CRYPT_DH_Ctx *ctx); /** * @ingroup dh * @brief dh Release context structure of dh key * * @param ctx [IN] Indicates the pointer to the context structure to be released. The ctx is set NULL by the invoker. */ void CRYPT_DH_FreeCtx(CRYPT_DH_Ctx *ctx); /** * @ingroup dh * @brief dh Allocate key parameter structure space * * @param para [IN] DH External parameter * * @retval (CRYPT_DH_Para *) Pointer to the memory space of the allocated context * @retval NULL Invalid null pointer */ CRYPT_DH_Para *CRYPT_DH_NewPara(const CRYPT_DhPara *para); /** * @ingroup dh * @brief Release dh key parameter structure * * @param para [IN] Pointer to the key parameter structure to be released. The parameter is set NULL by the invoker. */ void CRYPT_DH_FreePara(CRYPT_DH_Para *dhPara); /** * @ingroup dh * @brief Set the data of the key parameter structure to the key structure. * * @param ctx [IN] Key structure for setting related parameters. The key specification is 1024-8192 bits. * @param para [IN] Key parameters * * @retval CRYPT_NULL_INPUT Invalid null pointer input. * @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect. * @retval CRYPT_MEM_ALLOC_FAIL Internal Memory Allocation Error * @retval BN error code: An error occurred in the internal BigNum calculation. * @retval CRYPT_SUCCESS Set successfully. */ int32_t CRYPT_DH_SetPara(CRYPT_DH_Ctx *ctx, const CRYPT_DhPara *para); /** * @ingroup dh * @brief Obtain the key structure parameters. * * @param ctx [IN] Key structure * @param para [OUT] Obtained key parameter. * * @retval CRYPT_NULL_INPUT Invalid null pointer input. * @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect. * @retval BN error code: An error occurred in the internal BigNum calculation. * @retval CRYPT_SUCCESS Set successfully. */ int32_t CRYPT_DH_GetPara(const CRYPT_DH_Ctx *ctx, CRYPT_DhPara *para); /** * @ingroup dh * @brief Set a parameter based on the parameter ID. * * @param id [IN] Parameter ID * * @retval (CRYPT_DH_Para *) Pointer to the memory space of the allocated context * @retval NULL Invalid null pointer */ CRYPT_DH_Para *CRYPT_DH_NewParaById(CRYPT_PKEY_ParaId id); /** * @ingroup dh * @brief Obtain the parameter ID. * * @param ctx [IN] Key structure * * @retval ID. If the context is invalid, CRYPT_PKEY_PARAID_MAX is returned. */ CRYPT_PKEY_ParaId CRYPT_DH_GetParaId(const CRYPT_DH_Ctx *ctx); /** * @ingroup dh * @brief Obtain the valid length of the key. * * @param ctx [IN] Structure from which the key length is expected to be obtained * * @retval 0 The input is incorrect or the corresponding key structure does not have a valid key length. * @retval uint32_t Valid key length */ uint32_t CRYPT_DH_GetBits(const CRYPT_DH_Ctx *ctx); /** * @ingroup dh * @brief Generate the DH key pair. * * @param ctx [IN] dh Context structure * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect. * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval CRYPT_DH_RAND_GENRATE_ERROR Unable to generate results within the specified number of attempts * @retval BN error code: An error occurred in the internal BigNum calculation. * @retval CRYPT_SUCCESS The key pair is successfully generated. */ int32_t CRYPT_DH_Gen(CRYPT_DH_Ctx *ctx); /** * @ingroup dh * @brief DH key exchange * * @param ctx [IN] dh Context structure * @param pubKey [IN] Public key data * @param shareKey [OUT] Shared key * @param shareKeyLen [IN/OUT] The input parameter is the length of the shareKey, * and the output parameter is the valid length of the shareKey. * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_DH_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient. * @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect. * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval BN error. An error occurs in the internal BigNum operation. * @retval CRYPT_SUCCESS Key exchange succeeded. */ int32_t CRYPT_DH_ComputeShareKey(const CRYPT_DH_Ctx *ctx, const CRYPT_DH_Ctx *pubKey, uint8_t *shareKey, uint32_t *shareKeyLen); /** * @ingroup dh * @brief DH Set the private key. * * @param ctx [OUT] dh Context structure * @param prv [IN] Private key * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_DH_PARA_ERROR The key parameter is incorrect. * @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect. * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval BN error. An error occurs in the internal BigNum operation. * @retval CRYPT_SUCCESS Set successfully. */ int32_t CRYPT_DH_SetPrvKey(CRYPT_DH_Ctx *ctx, const CRYPT_DhPrv *prv); /** * @ingroup dh * @brief DH Set the public key data. * * @param ctx [OUT] dh Context structure * @param pub [IN] Public key data * * @retval CRYPT_NULL_INPUT Error null pointer input * @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect. * @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect. * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval BN error. An error occurs in the internal BigNum operation. * @retval CRYPT_SUCCESS Set successfully. */ int32_t CRYPT_DH_SetPubKey(CRYPT_DH_Ctx *ctx, const CRYPT_DhPub *pub); /** * @ingroup dh * @brief DH Obtain the private key data. * * @param ctx [IN] dh Context structure * @param prv [OUT] Private key data * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_DH_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient. * @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect. * @retval BN error. An error occurs in the internal BigNum operation. * @retval CRYPT_SUCCESS obtained successfully. */ int32_t CRYPT_DH_GetPrvKey(const CRYPT_DH_Ctx *ctx, CRYPT_DhPrv *prv); /** * @ingroup dh * @brief DH Obtain the public key data. * * @param ctx [IN] dh Context structure * @param pub [OUT] Public key data * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_DH_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient. * @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect. * @retval BN error. An error occurs in the internal BigNum operation. * @retval CRYPT_SUCCESS Obtained successfully. */ int32_t CRYPT_DH_GetPubKey(const CRYPT_DH_Ctx *ctx, CRYPT_DhPub *pub); #ifdef HITLS_BSL_PARAMS /** * @ingroup dh * @brief DH Set the private key. * * @param ctx [OUT] dh Context structure * @param para [IN] Private key * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_DH_PARA_ERROR The key parameter is incorrect. * @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect. * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval BN error. An error occurs in the internal BigNum operation. * @retval CRYPT_SUCCESS Set successfully. */ int32_t CRYPT_DH_SetPrvKeyEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para); /** * @ingroup dh * @brief DH Set the public key data. * * @param ctx [OUT] dh Context structure * @param para [IN] Public key data * * @retval CRYPT_NULL_INPUT Error null pointer input * @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect. * @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect. * @retval CRYPT_MEM_ALLOC_FAIL Memory allocation failure * @retval BN error. An error occurs in the internal BigNum operation. * @retval CRYPT_SUCCESS Set successfully. */ int32_t CRYPT_DH_SetPubKeyEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para); /** * @ingroup dh * @brief DH Obtain the private key data. * * @param ctx [IN] dh Context structure * @param para [OUT] Private key data * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_DH_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient. * @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect. * @retval BN error. An error occurs in the internal BigNum operation. * @retval CRYPT_SUCCESS obtained successfully. */ int32_t CRYPT_DH_GetPrvKeyEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para); /** * @ingroup dh * @brief DH Obtain the public key data. * * @param ctx [IN] dh Context structure * @param para [OUT] Public key data * * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_DH_BUFF_LEN_NOT_ENOUGH The buffer length is insufficient. * @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect. * @retval BN error. An error occurs in the internal BigNum operation. * @retval CRYPT_SUCCESS Obtained successfully. */ int32_t CRYPT_DH_GetPubKeyEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para); /** * @ingroup dh * @brief Set the data of the key parameter structure to the key structure. * * @param ctx [IN] Key structure for setting related parameters. The key specification is 1024-8192 bits. * @param para [IN] Key parameters * * @retval CRYPT_NULL_INPUT Invalid null pointer input. * @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect. * @retval CRYPT_MEM_ALLOC_FAIL Internal Memory Allocation Error * @retval BN error code: An error occurred in the internal BigNum calculation. * @retval CRYPT_SUCCESS Set successfully. */ int32_t CRYPT_DH_SetParaEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para); /** * @ingroup dh * @brief Obtain the key structure parameters. * * @param ctx [IN] Key structure * @param para [OUT] Obtained key parameter. * * @retval CRYPT_NULL_INPUT Invalid null pointer input. * @retval CRYPT_DH_PARA_ERROR The key parameter data is incorrect. * @retval BN error code: An error occurred in the internal BigNum calculation. * @retval CRYPT_SUCCESS Set successfully. */ int32_t CRYPT_DH_GetParaEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para); #endif /** * @ingroup dh * @brief dh Compare public keys and parameters * * @param a [IN] dh Context structure * @param b [IN] dh Context structure * * @return CRYPT_SUCCESS is the same * @retval CRYPT_NULL_INPUT Invalid null pointer input * @retval CRYPT_DH_KEYINFO_ERROR The key information is incorrect. * @retval CRYPT_DH_PUBKEY_NOT_EQUAL Public Keys are not equal * @retval CRYPT_DH_PARA_ERROR The parameter data is incorrect. * @retval CRYPT_DH_PARA_NOT_EQUAL The parameters are not equal. */ int32_t CRYPT_DH_Cmp(const CRYPT_DH_Ctx *a, const CRYPT_DH_Ctx *b); /** * @ingroup dh * @brief DH control interface * * @param ctx [IN] dh Context structure * @param opt [IN] Operation mode * @param val [IN] Parameter * @param len [IN] val length * * @retval CRYPT_NULL_INPUT Error null pointer input * @retval CRYPT_SUCCESS obtained successfully. */ int32_t CRYPT_DH_Ctrl(CRYPT_DH_Ctx *ctx, int32_t opt, void *val, uint32_t len); /** * @ingroup dh * @brief dh get security bits * * @param ctx [IN] dh Context structure * * @retval security bits */ int32_t CRYPT_DH_GetSecBits(const CRYPT_DH_Ctx *ctx); #ifdef HITLS_CRYPTO_DH_CHECK /** * @ingroup dh * @brief check the key pair consistency * * @param checkType [IN] check type * @param pkey1 [IN] dh key context structure * @param pkey2 [IN] dh key context structure * * @retval CRYPT_SUCCESS check success. * Others. For details, see error code in errno. */ int32_t CRYPT_DH_Check(uint32_t checkType, const CRYPT_DH_Ctx *pkey1, const CRYPT_DH_Ctx *pkey2); #endif // HITLS_CRYPTO_DH_CHECK #ifdef __cplusplus } #endif #endif // HITLS_CRYPTO_DH #endif // CRYPT_DH_H
2302_82127028/openHiTLS-examples_1556
crypto/dh/include/crypt_dh.h
C
unknown
13,923
/* * This file is part of the openHiTLS project. * * openHiTLS is licensed under the Mulan PSL v2. * You can use this software according to the terms and conditions of the Mulan PSL v2. * You may obtain a copy of Mulan PSL v2 at: * * http://license.coscl.org.cn/MulanPSL2 * * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. * See the Mulan PSL v2 for more details. */ #include "hitls_build.h" #ifdef HITLS_CRYPTO_DH #include "crypt_errno.h" #include "securec.h" #include "bsl_sal.h" #include "bsl_err_internal.h" #include "crypt_bn.h" #include "crypt_utils.h" #include "crypt_dh.h" #include "dh_local.h" #include "sal_atomic.h" #include "crypt_local_types.h" #include "crypt_params_key.h" CRYPT_DH_Ctx *CRYPT_DH_NewCtx(void) { CRYPT_DH_Ctx *ctx = BSL_SAL_Malloc(sizeof(CRYPT_DH_Ctx)); if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } (void)memset_s(ctx, sizeof(CRYPT_DH_Ctx), 0, sizeof(CRYPT_DH_Ctx)); BSL_SAL_ReferencesInit(&(ctx->references)); return ctx; } CRYPT_DH_Ctx *CRYPT_DH_NewCtxEx(void *libCtx) { CRYPT_DH_Ctx *ctx = CRYPT_DH_NewCtx(); if (ctx == NULL) { return NULL; } ctx->libCtx = libCtx; return ctx; } static CRYPT_DH_Para *ParaMemGet(uint32_t bits) { CRYPT_DH_Para *para = BSL_SAL_Calloc(1u, sizeof(CRYPT_DH_Para)); if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } para->p = BN_Create(bits); para->g = BN_Create(bits); para->id = CRYPT_PKEY_PARAID_MAX; if (para->p == NULL || para->g == NULL) { CRYPT_DH_FreePara(para); BSL_ERR_PUSH_ERROR(CRYPT_DH_CREATE_PARA_FAIL); return NULL; } return para; } static int32_t NewParaCheck(const CRYPT_DhPara *para) { if (para == NULL || para->p == NULL || para->g == NULL || para->pLen == 0 || para->gLen == 0 || (para->q == NULL && para->qLen != 0)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (para->pLen > BN_BITS_TO_BYTES(DH_MAX_PBITS)) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } if (para->gLen > para->pLen) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } if (para->q == NULL) { return CRYPT_SUCCESS; } if (para->qLen > para->pLen) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } return CRYPT_SUCCESS; } CRYPT_DH_Para *CRYPT_DH_NewPara(const CRYPT_DhPara *para) { if (NewParaCheck(para) != CRYPT_SUCCESS) { return NULL; } uint32_t modBits = BN_BYTES_TO_BITS(para->pLen); CRYPT_DH_Para *retPara = ParaMemGet(modBits); if (retPara == NULL) { return NULL; } int32_t ret = BN_Bin2Bn(retPara->p, para->p, para->pLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ret = BN_Bin2Bn(retPara->g, para->g, para->gLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } if (para->q == NULL) { return retPara; // The parameter q does not exist, this function is ended early. } retPara->q = BN_Create(modBits); if (retPara->q == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_CREATE_PARA_FAIL); goto ERR; } ret = BN_Bin2Bn(retPara->q, para->q, para->qLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } retPara->id = CRYPT_PKEY_PARAID_MAX; // No ID is passed in this function. Assign a invalid ID temporarily. return retPara; ERR: CRYPT_DH_FreePara(retPara); return NULL; } void CRYPT_DH_FreePara(CRYPT_DH_Para *dhPara) { if (dhPara == NULL) { return; } BN_Destroy(dhPara->p); BN_Destroy(dhPara->q); BN_Destroy(dhPara->g); BSL_SAL_FREE(dhPara); } void CRYPT_DH_FreeCtx(CRYPT_DH_Ctx *ctx) { if (ctx == NULL) { return; } int val = 0; BSL_SAL_AtomicDownReferences(&(ctx->references), &val); if (val > 0) { return; } CRYPT_DH_FreePara(ctx->para); BN_Destroy(ctx->x); BN_Destroy(ctx->y); BSL_SAL_ReferencesFree(&(ctx->references)); BSL_SAL_FREE(ctx); } static int32_t ParaQCheck(BN_BigNum *q, BN_BigNum *r) { // 1. Determine the length. if (BN_Bits(q) < DH_MIN_QBITS) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } // 2. Parity and even judgment if (BN_GetBit(q, 0) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } // 3. Compare q and r. if (BN_Cmp(q, r) >= 0) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } // 4. Check the pq multiple relationship. BN_Optimizer *opt = BN_OptimizerCreate(); if (opt == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = BN_Div(NULL, r, r, q, opt); BN_OptimizerDestroy(opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } // (p - 1) % q == 0 if (!BN_IsZero(r)) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } return CRYPT_SUCCESS; } static int32_t ParaDataCheck(const CRYPT_DH_Para *para) { int32_t ret; const BN_BigNum *p = para->p; const BN_BigNum *g = para->g; // 1. Determine the length. uint32_t pBits = BN_Bits(p); if (pBits < DH_MIN_PBITS || pBits > DH_MAX_PBITS) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } // 2. P parity and g value judgment // p is an odd number if (BN_GetBit(p, 0) == 0) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } // g != 0 && g != 1 if (BN_IsZero(g) || BN_IsOne(g)) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } BN_BigNum *r = BN_Create(pBits + 1); if (r == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } // r = p - 1 ret = BN_SubLimb(r, p, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } // g < p - 1 if (BN_Cmp(g, r) >= 0) { ret = CRYPT_DH_PARA_ERROR; BSL_ERR_PUSH_ERROR(ret); goto EXIT; } if (para->q != NULL) { ret = ParaQCheck(para->q, r); } EXIT: BN_Destroy(r); return ret; } static CRYPT_DH_Para *ParaDup(const CRYPT_DH_Para *para) { CRYPT_DH_Para *ret = BSL_SAL_Malloc(sizeof(CRYPT_DH_Para)); if (ret == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } ret->p = BN_Dup(para->p); ret->q = BN_Dup(para->q); ret->g = BN_Dup(para->g); ret->id = para->id; if (ret->p == NULL || ret->g == NULL) { CRYPT_DH_FreePara(ret); BSL_ERR_PUSH_ERROR(CRYPT_DH_CREATE_PARA_FAIL); return NULL; } if (para->q != NULL && ret->q == NULL) { CRYPT_DH_FreePara(ret); BSL_ERR_PUSH_ERROR(CRYPT_DH_CREATE_PARA_FAIL); return NULL; } return ret; } CRYPT_DH_Ctx *CRYPT_DH_DupCtx(CRYPT_DH_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return NULL; } CRYPT_DH_Ctx *newKeyCtx = BSL_SAL_Calloc(1, sizeof(CRYPT_DH_Ctx)); if (newKeyCtx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return NULL; } // If x, y and para is not empty, copy the value. GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->x, ctx->x, BN_Dup(ctx->x), CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->y, ctx->y, BN_Dup(ctx->y), CRYPT_MEM_ALLOC_FAIL); GOTO_ERR_IF_SRC_NOT_NULL(newKeyCtx->para, ctx->para, ParaDup(ctx->para), CRYPT_MEM_ALLOC_FAIL); newKeyCtx->libCtx = ctx->libCtx; BSL_SAL_ReferencesInit(&(newKeyCtx->references)); return newKeyCtx; ERR: CRYPT_DH_FreeCtx(newKeyCtx); return NULL; } static int32_t DhSetPara(CRYPT_DH_Ctx *ctx, CRYPT_DH_Para *para) { int32_t ret = ParaDataCheck(para); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } BN_Destroy(ctx->x); BN_Destroy(ctx->y); CRYPT_DH_FreePara(ctx->para); ctx->x = NULL; ctx->y = NULL; ctx->para = para; return CRYPT_SUCCESS; } int32_t CRYPT_DH_SetPara(CRYPT_DH_Ctx *ctx, const CRYPT_DhPara *para) { if (ctx == NULL || para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DH_Para *dhPara = CRYPT_DH_NewPara(para); if (dhPara == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_NEW_PARA_FAIL); return CRYPT_EAL_ERR_NEW_PARA_FAIL; } int32_t ret = DhSetPara(ctx, dhPara); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); CRYPT_DH_FreePara(dhPara); } return ret; } int32_t CRYPT_DH_GetPara(const CRYPT_DH_Ctx *ctx, CRYPT_DhPara *para) { if (ctx == NULL || para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } int32_t ret = BN_Bn2Bin(ctx->para->p, para->p, &(para->pLen)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } if (ctx->para->q == NULL) { para->q = NULL; para->qLen = 0; } else { ret = BN_Bn2Bin(ctx->para->q, para->q, &(para->qLen)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } } ret = BN_Bn2Bin(ctx->para->g, para->g, &(para->gLen)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } static int32_t PubCheck(const BN_BigNum *y, const BN_BigNum *minP) { // y != 0, y != 1 if (BN_IsZero(y) || BN_IsOne(y)) { BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR); return CRYPT_DH_KEYINFO_ERROR; } // y < p - 1 if (BN_Cmp(y, minP) >= 0) { BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR); return CRYPT_DH_KEYINFO_ERROR; } return CRYPT_SUCCESS; } // Get p-2 or q-1 static int32_t GetXLimb(BN_BigNum *xLimb, const BN_BigNum *p, const BN_BigNum *q) { if (q != NULL) { // xLimb = q - 1 return BN_SubLimb(xLimb, q, 1); } // xLimb = p - 2 return BN_SubLimb(xLimb, p, 2); } static void RefreshCtx(CRYPT_DH_Ctx *dhCtx, BN_BigNum *x, BN_BigNum *y, int32_t ret) { if (ret == CRYPT_SUCCESS) { BN_Destroy(dhCtx->x); BN_Destroy(dhCtx->y); dhCtx->x = x; dhCtx->y = y; } else { BN_Destroy(x); BN_Destroy(y); } } /* SP800-56Ar3 5_6_1_1_4 Key-Pair Generation by Testing Candidates */ static int32_t DH_GenSp80056ATestCandidates(CRYPT_DH_Ctx *ctx) { int32_t ret; uint32_t bits = BN_Bits(ctx->para->p); uint32_t qbits = BN_Bits(ctx->para->q); /* If s is not the maximum security strength that can be support by (p, q, g), then return an error. */ uint32_t s = (uint32_t)CRYPT_DH_GetSecBits(ctx); if (bits == 0 || qbits == 0 || s == 0) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } /* 2*s <= n <= len(q), set n = 2*s */ uint32_t n = 2 * s; BN_BigNum *x = BN_Create(bits); BN_BigNum *y = BN_Create(bits); BN_BigNum *twoPowN = BN_Create(n); BN_Mont *mont = BN_MontCreate(ctx->para->p); BN_BigNum *m = ctx->para->q; BN_Optimizer *opt = BN_OptimizerCreate(); if (x == NULL || y == NULL || mont == NULL || opt == NULL || twoPowN == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); goto ERR; } ret = BN_SetLimb(twoPowN, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } ret = BN_Lshift(twoPowN, twoPowN, n); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } /* Set M = min(2^N, q), the minimum of 2^N and q. */ if (BN_Cmp(twoPowN, m) < 0) { m = twoPowN; } for (int32_t cnt = 0; cnt < CRYPT_DH_TRY_CNT_MAX; cnt++) { /* c in the interval [0, 2N - 1] */ ret = BN_RandRangeEx(ctx->libCtx, x, twoPowN); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } /* x = c + 1 */ ret = BN_AddLimb(x, x, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } /* If c > M - 2, (i.e. c + 1 >= M) continue */ if (BN_Cmp(x, m) >= 0) { continue; } ret = BN_MontExpConsttime(y, ctx->para->g, x, mont, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } goto ERR; // The function exits successfully. } ret = CRYPT_DH_RAND_GENERATE_ERROR; BSL_ERR_PUSH_ERROR(ret); ERR: RefreshCtx(ctx, x, y, ret); BN_Destroy(twoPowN); BN_MontDestroy(mont); BN_OptimizerDestroy(opt); return ret; } static int32_t DH_GenSp80056ASafePrime(CRYPT_DH_Ctx *ctx) { int32_t ret; uint32_t bits = BN_Bits(ctx->para->p); BN_BigNum *x = BN_Create(bits); BN_BigNum *y = BN_Create(bits); BN_BigNum *minP = BN_Create(bits); BN_BigNum *xLimb = BN_Create(bits); BN_Mont *mont = BN_MontCreate(ctx->para->p); BN_Optimizer *opt = BN_OptimizerCreate(); if (x == NULL || y == NULL || minP == NULL || xLimb == NULL || mont == NULL || opt == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_SubLimb(minP, ctx->para->p, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = GetXLimb(xLimb, ctx->para->p, ctx->para->q); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } for (int32_t cnt = 0; cnt < CRYPT_DH_TRY_CNT_MAX; cnt++) { /* Generate private key x for [1, q-1] or [1, p-2] */ ret = BN_RandRangeEx(ctx->libCtx, x, xLimb); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_AddLimb(x, x, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } /* Calculate the public key y. */ ret = BN_MontExpConsttime(y, ctx->para->g, x, mont, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } /* Check whether the public key meets the requirements. If not, try to generate the key again. */ // y != 0, y != 1, y < p - 1 if (BN_IsZero(y) || BN_IsOne(y) || BN_Cmp(y, minP) >= 0) { continue; } goto EXIT; // The function exits successfully. } ret = CRYPT_DH_RAND_GENERATE_ERROR; BSL_ERR_PUSH_ERROR(ret); EXIT: RefreshCtx(ctx, x, y, ret); BN_Destroy(minP); BN_Destroy(xLimb); BN_MontDestroy(mont); BN_OptimizerDestroy(opt); return ret; } int32_t CRYPT_DH_Gen(CRYPT_DH_Ctx *ctx) { if (ctx == NULL || ctx->para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } int32_t s = CRYPT_DH_GetSecBits(ctx); if (ctx->para->q != NULL && s != 0) { return DH_GenSp80056ATestCandidates(ctx); } return DH_GenSp80056ASafePrime(ctx); } static int32_t ComputeShareKeyInputCheck(const CRYPT_DH_Ctx *ctx, const CRYPT_DH_Ctx *pubKey, const uint8_t *shareKey, const uint32_t *shareKeyLen) { if (ctx == NULL || pubKey == NULL || shareKey == NULL || shareKeyLen == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } if (ctx->x == NULL || pubKey->y == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR); return CRYPT_DH_KEYINFO_ERROR; } if (BN_Bytes(ctx->para->p) > *shareKeyLen) { BSL_ERR_PUSH_ERROR(CRYPT_DH_BUFF_LEN_NOT_ENOUGH); return CRYPT_DH_BUFF_LEN_NOT_ENOUGH; } return CRYPT_SUCCESS; } static void CheckAndFillZero(uint8_t *shareKey, uint32_t *shareKeyLen, uint32_t bytes) { int32_t i; if (*shareKeyLen == bytes) { // (*shareKeyLen > bytes) is not possible return; } uint32_t fill = bytes - *shareKeyLen; for (i = (int32_t)*shareKeyLen - 1; i >= 0; i--) { shareKey[i + (int32_t)fill] = shareKey[i]; } for (i = 0; i < (int32_t)fill; i++) { shareKey[i] = 0; } *shareKeyLen = bytes; } int32_t CRYPT_DH_ComputeShareKey(const CRYPT_DH_Ctx *ctx, const CRYPT_DH_Ctx *pubKey, uint8_t *shareKey, uint32_t *shareKeyLen) { uint32_t bytes = 0; int32_t ret = ComputeShareKeyInputCheck(ctx, pubKey, shareKey, shareKeyLen); if (ret != CRYPT_SUCCESS) { return ret; } uint32_t bits = BN_Bits(ctx->para->p); BN_BigNum *tmp = BN_Create(bits); BN_Mont *mont = BN_MontCreate(ctx->para->p); BN_Optimizer *opt = BN_OptimizerCreate(); if (tmp == NULL || mont == NULL || opt == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_SubLimb(tmp, ctx->para->p, 1); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } /* Check whether the public key meets the requirements. */ ret = PubCheck(pubKey->y, tmp); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_MontExpConsttime(tmp, pubKey->y, ctx->x, mont, opt); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } ret = BN_Bn2Bin(tmp, shareKey, shareKeyLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto EXIT; } // no need to filled zero in the leading. if ((ctx->flags & CRYPT_DH_NO_PADZERO) == 0) { bytes = BN_BITS_TO_BYTES(bits); CheckAndFillZero(shareKey, shareKeyLen, bytes); } EXIT: BN_Destroy(tmp); BN_MontDestroy(mont); BN_OptimizerDestroy(opt); return ret; } static int32_t PrvLenCheck(const CRYPT_DH_Ctx *ctx, const CRYPT_DhPrv *prv) { if (ctx->para->q != NULL) { if (BN_Bytes(ctx->para->q) < prv->len) { BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR); return CRYPT_DH_KEYINFO_ERROR; } } else { if (BN_Bytes(ctx->para->p) < prv->len) { BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR); return CRYPT_DH_KEYINFO_ERROR; } } return CRYPT_SUCCESS; } int32_t CRYPT_DH_SetPrvKey(CRYPT_DH_Ctx *ctx, const CRYPT_DhPrv *prv) { if (ctx == NULL || prv == NULL || prv->data == NULL || prv->len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } int32_t ret = PrvLenCheck(ctx, prv); if (ret != CRYPT_SUCCESS) { return ret; } BN_BigNum *bnX = BN_Create(BN_BYTES_TO_BITS(prv->len)); BN_BigNum *xLimb = BN_Create(BN_Bits(ctx->para->p) + 1); if (bnX == NULL || xLimb == NULL) { ret = CRYPT_MEM_ALLOC_FAIL; BSL_ERR_PUSH_ERROR(ret); goto ERR; } GOTO_ERR_IF(GetXLimb(xLimb, ctx->para->p, ctx->para->q), ret); GOTO_ERR_IF(BN_Bin2Bn(bnX, prv->data, prv->len), ret); // Satisfy x <= q - 1 or x <= p - 2 if (BN_Cmp(bnX, xLimb) > 0) { ret = CRYPT_DH_KEYINFO_ERROR; BSL_ERR_PUSH_ERROR(ret); goto ERR; } // x != 0 if (BN_IsZero(bnX)) { ret = CRYPT_DH_KEYINFO_ERROR; BSL_ERR_PUSH_ERROR(ret); goto ERR; } BN_Destroy(xLimb); BN_Destroy(ctx->x); ctx->x = bnX; return ret; ERR: BN_Destroy(bnX); BN_Destroy(xLimb); return ret; } // No parameter information is required for setting the public key. // Therefore, the validity of the public key is not checked during the setting. // The validity of the public key is checked during the calculation of the shared key. int32_t CRYPT_DH_SetPubKey(CRYPT_DH_Ctx *ctx, const CRYPT_DhPub *pub) { if (ctx == NULL || pub == NULL || pub->data == NULL || pub->len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (pub->len > BN_BITS_TO_BYTES(DH_MAX_PBITS)) { BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR); return CRYPT_DH_KEYINFO_ERROR; } BN_BigNum *bnY = BN_Create(BN_BYTES_TO_BITS(pub->len)); if (bnY == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_MEM_ALLOC_FAIL); return CRYPT_MEM_ALLOC_FAIL; } int32_t ret = BN_Bin2Bn(bnY, pub->data, pub->len); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); goto ERR; } BN_Destroy(ctx->y); ctx->y = bnY; return ret; ERR: BN_Destroy(bnY); return ret; } int32_t CRYPT_DH_GetPrvKey(const CRYPT_DH_Ctx *ctx, CRYPT_DhPrv *prv) { if (ctx == NULL || prv == NULL || prv->data == NULL || prv->len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->x == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR); return CRYPT_DH_KEYINFO_ERROR; } if (ctx->para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } if (ctx->para->q != NULL) { if (BN_Bytes(ctx->para->q) > prv->len) { BSL_ERR_PUSH_ERROR(CRYPT_DH_BUFF_LEN_NOT_ENOUGH); return CRYPT_DH_BUFF_LEN_NOT_ENOUGH; } } else { if (BN_Bytes(ctx->para->p) > prv->len) { BSL_ERR_PUSH_ERROR(CRYPT_DH_BUFF_LEN_NOT_ENOUGH); return CRYPT_DH_BUFF_LEN_NOT_ENOUGH; } } int32_t ret = BN_Bn2Bin(ctx->x, prv->data, &(prv->len)); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t CRYPT_DH_GetPubKey(const CRYPT_DH_Ctx *ctx, CRYPT_DhPub *pub) { if (ctx == NULL || pub == NULL || pub->data == NULL || pub->len == 0) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (ctx->para == NULL || ctx->para->p == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } if (ctx->y == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_KEYINFO_ERROR); return CRYPT_DH_KEYINFO_ERROR; } uint32_t pubLen = BN_Bytes(ctx->para->p); if (pubLen > pub->len) { BSL_ERR_PUSH_ERROR(CRYPT_DH_BUFF_LEN_NOT_ENOUGH); return CRYPT_DH_BUFF_LEN_NOT_ENOUGH; } // RFC 8446 requires the dh public value should be encoded as a big-endian integer and padded to // the left with zeros to the size of p in bytes. int32_t ret = BN_Bn2BinFixZero(ctx->y, pub->data, pubLen); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); } pub->len = pubLen; return ret; } #ifdef HITLS_BSL_PARAMS int32_t CRYPT_DH_SetParaEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DhPara dhPara = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_DH_P, &(dhPara.p), &(dhPara.pLen)); (void)GetConstParamValue(para, CRYPT_PARAM_DH_Q, &(dhPara.q), &(dhPara.qLen)); (void)GetConstParamValue(para, CRYPT_PARAM_DH_G, &(dhPara.g), &(dhPara.gLen)); return CRYPT_DH_SetPara(ctx, &dhPara); } int32_t CRYPT_DH_GetParaEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DhPara dhPara = {0}; BSL_Param *paramP = GetParamValue(para, CRYPT_PARAM_DH_P, &(dhPara.p), &(dhPara.pLen)); BSL_Param *paramQ = GetParamValue(para, CRYPT_PARAM_DH_Q, &(dhPara.q), &(dhPara.qLen)); BSL_Param *paramG = GetParamValue(para, CRYPT_PARAM_DH_G, &(dhPara.g), &(dhPara.gLen)); int32_t ret = CRYPT_DH_GetPara(ctx, &dhPara); if (ret != CRYPT_SUCCESS) { BSL_ERR_PUSH_ERROR(ret); return ret; } paramP->useLen = dhPara.pLen; paramQ->useLen = dhPara.qLen; paramG->useLen = dhPara.gLen; return CRYPT_SUCCESS; } int32_t CRYPT_DH_SetPrvKeyEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DhPrv prv = {0}; (void)GetConstParamValue(para, CRYPT_PARAM_DH_PRVKEY, &prv.data, &prv.len); return CRYPT_DH_SetPrvKey(ctx, &prv); } int32_t CRYPT_DH_SetPubKeyEx(CRYPT_DH_Ctx *ctx, const BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DhPub pub = {0}; if (GetConstParamValue(para, CRYPT_PARAM_DH_PUBKEY, &pub.data, &pub.len) == NULL) { (void)GetConstParamValue(para, CRYPT_PARAM_PKEY_ENCODE_PUBKEY, (uint8_t **)&pub.data, &pub.len); } return CRYPT_DH_SetPubKey(ctx, &pub); } int32_t CRYPT_DH_GetPrvKeyEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DhPrv prv = {0}; BSL_Param *paramPrv = GetParamValue(para, CRYPT_PARAM_DH_PRVKEY, &prv.data, &(prv.len)); int32_t ret = CRYPT_DH_GetPrvKey(ctx, &prv); if (ret != CRYPT_SUCCESS) { return ret; } paramPrv->useLen = prv.len; return CRYPT_SUCCESS; } int32_t CRYPT_DH_GetPubKeyEx(const CRYPT_DH_Ctx *ctx, BSL_Param *para) { if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } CRYPT_DhPub pub = {0}; BSL_Param *paramPub = GetParamValue(para, CRYPT_PARAM_DH_PUBKEY, &pub.data, &(pub.len)); if (paramPub == NULL) { paramPub = GetParamValue(para, CRYPT_PARAM_PKEY_ENCODE_PUBKEY, &pub.data, &(pub.len)); } int32_t ret = CRYPT_DH_GetPubKey(ctx, &pub); if (ret != CRYPT_SUCCESS) { return ret; } paramPub->useLen = pub.len; return ret; } #endif uint32_t CRYPT_DH_GetBits(const CRYPT_DH_Ctx *ctx) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } if (ctx->para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } return BN_Bits(ctx->para->p); } static uint32_t CRYPT_DH_GetPrvKeyLen(const CRYPT_DH_Ctx *ctx) { return BN_Bytes(ctx->x); } static uint32_t CRYPT_DH_GetPubKeyLen(const CRYPT_DH_Ctx *ctx) { if (ctx->para != NULL) { return BN_Bytes(ctx->para->p); } if (ctx->y != NULL) { return BN_Bytes(ctx->y); } BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } static uint32_t CRYPT_DH_GetSharedKeyLen(const CRYPT_DH_Ctx *ctx) { if (ctx->para != NULL) { return BN_Bytes(ctx->para->p); } BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } #ifdef HITLS_CRYPTO_DH_CHECK static int32_t DhKeyPairCheck(const CRYPT_DH_Ctx *pub, const CRYPT_DH_Ctx *prv) { int32_t ret; if (prv == NULL || pub == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (prv->para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_DH_PARA_ERROR); return CRYPT_DH_PARA_ERROR; } ret = CRYPT_FFC_KeyPairCheck(prv->x, pub->y, prv->para->p, prv->para->g); if (ret == CRYPT_PAIRWISE_CHECK_FAIL) { ret = CRYPT_DH_PAIRWISE_CHECK_FAIL; BSL_ERR_PUSH_ERROR(ret); } return ret; } /* * SP800-56a 5.6.2.1.2 * for check an FFC key pair. */ static int32_t DhPrvKeyCheck(const CRYPT_DH_Ctx *pkey) { if (pkey == NULL || pkey->para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } int32_t ret = CRYPT_FFC_PrvCheck(pkey->x, pkey->para->p, pkey->para->q); if (ret == CRYPT_INVALID_KEY) { ret = CRYPT_DH_INVALID_PRVKEY; BSL_ERR_PUSH_ERROR(ret); } return ret; } int32_t CRYPT_DH_Check(uint32_t checkType, const CRYPT_DH_Ctx *pkey1, const CRYPT_DH_Ctx *pkey2) { switch (checkType) { case CRYPT_PKEY_CHECK_KEYPAIR: return DhKeyPairCheck(pkey1, pkey2); case CRYPT_PKEY_CHECK_PRVKEY: return DhPrvKeyCheck(pkey1); default: BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } } #endif // HITLS_CRYPTO_DH_CHECK int32_t CRYPT_DH_Cmp(const CRYPT_DH_Ctx *a, const CRYPT_DH_Ctx *b) { RETURN_RET_IF(a == NULL || b == NULL, CRYPT_NULL_INPUT); RETURN_RET_IF(a->y == NULL || b->y == NULL, CRYPT_DH_KEYINFO_ERROR); RETURN_RET_IF(BN_Cmp(a->y, b->y) != 0, CRYPT_DH_PUBKEY_NOT_EQUAL); // para must be both null and non-null. RETURN_RET_IF((a->para == NULL) != (b->para == NULL), CRYPT_DH_PARA_ERROR); if (a->para != NULL) { RETURN_RET_IF(BN_Cmp(a->para->p, b->para->p) != 0 || BN_Cmp(a->para->q, b->para->q) != 0 || BN_Cmp(a->para->g, b->para->g) != 0, CRYPT_DH_PARA_NOT_EQUAL); } return CRYPT_SUCCESS; } int32_t CRYPT_DH_SetParamById(CRYPT_DH_Ctx *ctx, CRYPT_PKEY_ParaId id) { CRYPT_DH_Para *para = CRYPT_DH_NewParaById(id); if (para == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_EAL_ERR_NEW_PARA_FAIL); return CRYPT_EAL_ERR_NEW_PARA_FAIL; } int32_t ret = DhSetPara(ctx, para); if (ret != CRYPT_SUCCESS) { CRYPT_DH_FreePara(para); } return ret; } static int32_t CRYPT_DH_GetLen(const CRYPT_DH_Ctx *ctx, GetLenFunc func, void *val, uint32_t len) { if (val == NULL || len != sizeof(int32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } *(int32_t *)val = func(ctx); return CRYPT_SUCCESS; } static int32_t CRYPT_DH_SetFlag(CRYPT_DH_Ctx *ctx, const void *val, uint32_t len) { if (val == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } if (len != sizeof(uint32_t)) { BSL_ERR_PUSH_ERROR(CRYPT_DH_SET_FLAG_LEN_ERROR); return CRYPT_DH_SET_FLAG_LEN_ERROR; } uint32_t flag = *(const uint32_t *)val; if (flag == 0 || flag >= CRYPT_DH_MAXFLAG) { BSL_ERR_PUSH_ERROR(CRYPT_DH_FLAG_NOT_SUPPORT_ERROR); return CRYPT_DH_FLAG_NOT_SUPPORT_ERROR; } ctx->flags |= flag; return CRYPT_SUCCESS; } int32_t CRYPT_DH_Ctrl(CRYPT_DH_Ctx *ctx, int32_t opt, void *val, uint32_t len) { if (ctx == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return CRYPT_NULL_INPUT; } switch (opt) { case CRYPT_CTRL_GET_PARAID: return CRYPT_DH_GetLen(ctx, (GetLenFunc)CRYPT_DH_GetParaId, val, len); case CRYPT_CTRL_GET_BITS: return CRYPT_DH_GetLen(ctx, (GetLenFunc)CRYPT_DH_GetBits, val, len); case CRYPT_CTRL_GET_SECBITS: return CRYPT_DH_GetLen(ctx, (GetLenFunc)CRYPT_DH_GetSecBits, val, len); case CRYPT_CTRL_GET_PUBKEY_LEN: return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DH_GetPubKeyLen); case CRYPT_CTRL_GET_PRVKEY_LEN: return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DH_GetPrvKeyLen); case CRYPT_CTRL_GET_SHARED_KEY_LEN: return GetUintCtrl(ctx, val, len, (GetUintCallBack)CRYPT_DH_GetSharedKeyLen); case CRYPT_CTRL_SET_PARA_BY_ID: return CRYPT_DH_SetParamById(ctx, *(CRYPT_PKEY_ParaId *)val); case CRYPT_CTRL_SET_DH_FLAG: return CRYPT_DH_SetFlag(ctx, val, len); case CRYPT_CTRL_UP_REFERENCES: if (val == NULL || len != (uint32_t)sizeof(int)) { BSL_ERR_PUSH_ERROR(CRYPT_INVALID_ARG); return CRYPT_INVALID_ARG; } return BSL_SAL_AtomicUpReferences(&(ctx->references), (int *)val); default: break; } BSL_ERR_PUSH_ERROR(CRYPT_DH_UNSUPPORTED_CTRL_OPTION); return CRYPT_DH_UNSUPPORTED_CTRL_OPTION; } /** * @ingroup dh * @brief dh get security bits * * @param ctx [IN] dh Context structure * * @retval security bits */ int32_t CRYPT_DH_GetSecBits(const CRYPT_DH_Ctx *ctx) { if (ctx == NULL || ctx->para == NULL || ctx->para->p == NULL) { BSL_ERR_PUSH_ERROR(CRYPT_NULL_INPUT); return 0; } if (ctx->para->q == NULL) { return BN_SecBits(BN_Bits(ctx->para->p), -1); } return BN_SecBits(BN_Bits(ctx->para->p), BN_Bits(ctx->para->q)); } #endif /* HITLS_CRYPTO_DH */
2302_82127028/openHiTLS-examples_1556
crypto/dh/src/dh_core.c
C
unknown
32,906