text
stringlengths
81
112k
Describe operation and args needed for server side completion. :type service: str :param service: The AWS service name. :type operation: str :param operation: The AWS operation name. :type param: str :param param: The name of the parameter being completed. This must ...
Create a CompleterDescriber for a service. :type service_name: str :param service_name: The name of the service, e.g. 'ec2' :return: A CompleterDescriber object. def create_completer_query(self, service_name): """Create a CompleterDescriber for a service. :type service_name: ...
Retrieve server side completions. :type service: str :param service: The service name, e.g. 'ec2', 'iam'. :type operation: str :param operation: The operation name, in the casing used by the CLI (words separated by hyphens), e.g. 'describe-instances', 'delete-us...
Convert restructured text to basic text output. This function removes most of the decorations added in restructured text. This function is used to generate documentation we can show to users in a cross platform manner. Basic indentation and list formatting are kept, but many RST features are ...
Read the config file if it exists, else read the default config. Creates the user config file if it doesn't exist using the template. :type config_template: str :param config_template: The config template file name. :type config_file: str :param config_file: (Optional) The con...
Load the config file if it exists, else read the default config. :type template_path: str :param template_path: The template config file path. :type config_path: str :param config_path: The user's config file path. :rtype: :class:`configobj.ConfigObj` :return: The conf...
Write the default config from a template. :type template_path: str :param template_path: The template config file path. :type config_path: str :param config_path: The user's config file path. :type overwrite: bool :param overwrite: (Optional) Determines whether to over...
Retrieve the specified pygments style. If the specified style is not found, the vim style is returned. :type style_name: str :param style_name: The pygments style name. :rtype: :class:`pygments.style.StyleMeta` :return: Pygments style info. def style_factory(self, style_name)...
Change the profile used for server side completions. def change_profile(self, profile_name): """Change the profile used for server side completions.""" self._server_side_completer = self._create_server_side_completer( session=botocore.session.Session(profile=profile_name))
Given a line, return a list of suggestions. def autocomplete(self, line): """Given a line, return a list of suggestions.""" current_length = len(line) self._current_line = line if current_length == 1 and self._last_position > 1: # Reset state. This is likely from a user com...
Open application's history buffer in an editor. :type command: list :param command: The dot command as a list split on whitespace, e.g ``['.foo', 'arg1', 'arg2']`` :type application: AWSShell :param application: The application object. def run(self, command, application): ...
Get or set the profile. If .profile is called with no args, the current profile is displayed. If the .profile command is called with a single arg, then the current profile for the application will be set to the new value. def run(self, command, application): """Get or set the ...
Handle running a given dot command from a user. :type command: str :param command: The full dot command string, e.g. ``.edit``, of ``.profile prod``. :type application: AWSShell :param application: The application object. def handle_cmd(self, command, application): ...
Load the config from the config file or template. def load_config(self): """Load the config from the config file or template.""" config = Config() self.config_obj = config.load('awsshellrc') self.config_section = self.config_obj['aws-shell'] self.model_completer.match_fuzzy = se...
Save the config to the config file. def save_config(self): """Save the config to the config file.""" self.config_section['match_fuzzy'] = self.model_completer.match_fuzzy self.config_section['enable_vi_bindings'] = self.enable_vi_bindings self.config_section['show_completion_columns'] =...
Create the :class:`KeyManager`. The inputs to KeyManager are expected to be callable, so we can't use the standard @property and @attrib.setter for these attributes. Lambdas cannot contain assignments so we're forced to define setters. :rtype: :class:`KeyManager` :return: A Key...
Calculate how well the search string matches the word. def calculate_score(search_string, word): """Calculate how well the search string matches the word.""" # See the module docstring for a high level description # of what we're trying to do. # * If the search string is larger than the word, we know ...
Find all matches in the `collection` for the specified `word`. If `word` is empty, returns all items in `collection`. :type word: str :param word: The substring to search for. :type collection: collection, usually a list :param collection: A collection of words to match. :rtype: list of stri...
Create the toolbar handler. :type get_fuzzy_match: callable :param fuzzy_match: Gets the fuzzy matching config. :type get_enable_vi_bindings: callable :param get_enable_vi_bindings: Gets the vi (or emacs) key bindings config. :type get_show_completion_columns: call...
Generate default layout. Returns a ``Layout`` instance. :param message: Text to be used as prompt. :param lexer: Lexer to be used for the highlighting. :param is_password: `bool` or `CLIFilter`. When True, display input as '*'. :param reserve_space_for_menu: When True, make sure that a minimal hei...
Cross platform temporary file creation. This is an alternative to ``tempfile.NamedTemporaryFile`` that also works on windows and avoids the "file being used by another process" error. def temporary_file(mode): """Cross platform temporary file creation. This is an alternative to ``tempfile.NamedTe...
Return the file for a given filename. If you want binary content use ``mode='rb'``. def file_contents(self, filename, binary=False): """Return the file for a given filename. If you want binary content use ``mode='rb'``. """ if binary: mode = 'rb' else: ...
Load the completion index for a given CLI version. :type version_string: str :param version_string: The AWS CLI version, e.g "1.9.2". :raises: :class:`IndexLoadError <exceptions.IndexLoadError>` def load_index(self, version_string): """Load the completion index for a given CLI version...
Load completions from the completion index. Updates the following attributes: * commands * subcommands * global_opts * args_opts def load_completions(self): """Load completions from the completion index. Updates the following attributes: ...
Decrypt a block of cipher text using the AES block cipher. def decrypt(self, ciphertext): 'Decrypt a block of cipher text using the AES block cipher.' if len(ciphertext) != 16: raise ValueError('wrong block length') rounds = len(self._Kd) - 1 (s1, s2, s3) = [3, 2, 1] ...
Increment the counter (overflow rolls back to 0). def increment(self): '''Increment the counter (overflow rolls back to 0).''' for i in xrange(len(self._counter) - 1, -1, -1): self._counter[i] += 1 if self._counter[i] < 256: break # Carry the one self....
Dump raw efuse data registers def dump(esp, _efuses, args): """ Dump raw efuse data registers """ for block in range(len(EFUSE_BLOCK_OFFS)): print("EFUSE block %d:" % block) offsets = [x + EFUSE_BLOCK_OFFS[block] for x in range(EFUSE_BLOCK_LEN[block])] print(" ".join(["%08x" % esp.read_...
Print a human-readable summary of efuse contents def summary(esp, efuses, args): """ Print a human-readable summary of efuse contents """ ROW_FORMAT = "%-22s %-50s%s= %s %s %s" print(ROW_FORMAT.replace("-50", "-12") % ("EFUSE_NAME", "Description", "", "[Meaningful Value]", "[Readable/Writeable]", "(Hex Val...
Write the values in the efuse write registers to the efuse hardware, then refresh the efuse read registers. def write_efuses(self): """ Write the values in the efuse write registers to the efuse hardware, then refresh the efuse read registers. """ # Configure clock apb_...
Return the raw (unformatted) numeric value of the efuse bits Returns a simple integer or (for some subclasses) a bitstring. def get_raw(self): """ Return the raw (unformatted) numeric value of the efuse bits Returns a simple integer or (for some subclasses) a bitstring. """ va...
Return true if the efuse is readable by software def is_readable(self): """ Return true if the efuse is readable by software """ if self.read_disable_bit is None: return True # read cannot be disabled value = (self.parent.read_efuse(0) >> 16) & 0xF # RD_DIS values return (...
This algorithm is the equivalent of esp_crc8() in ESP32 ROM code This is CRC-8 w/ inverted polynomial value 0x8C & initial value 0x00. def calc_crc(raw_mac): """ This algorithm is the equivalent of esp_crc8() in ESP32 ROM code This is CRC-8 w/ inverted polynomial value 0x8C & initial ...
Takes 24 byte sequence to be represented in 3/4 encoding, returns 8 words suitable for writing "encoded" to an efuse block def apply_34_encoding(self, inbits): """ Takes 24 byte sequence to be represented in 3/4 encoding, returns 8 words suitable for writing "encoded" to an efuse block ...
Is the point (x,y) on this curve? def contains_point( self, x, y ): """Is the point (x,y) on this curve?""" return ( y * y - ( x * x * x + self.__a * x + self.__b ) ) % self.__p == 0
Return a new point that is twice the old. def double( self ): """Return a new point that is twice the old.""" if self == INFINITY: return INFINITY # X9.62 B.3: p = self.__curve.p() a = self.__curve.a() l = ( ( 3 * self.__x * self.__x + a ) * \ numbertheory.inverse_mod( 2 * s...
Scales timeouts which are size-specific def timeout_per_mb(seconds_per_mb, size_bytes): """ Scales timeouts which are size-specific """ result = seconds_per_mb * (size_bytes / 1e6) if result < DEFAULT_TIMEOUT: return DEFAULT_TIMEOUT return result
Decorator implementation that wraps a check around an ESPLoader bootloader function to check if it's supported. This is used to capture the multidimensional differences in functionality between the ESP8266 & ESP32 ROM loaders, and the software stub that runs on both. Not possible to do this cleanly ...
Load a firmware image. Can be for ESP8266 or ESP32. ESP8266 images will be examined to determine if they are original ROM firmware images (ESP8266ROMFirmwareImage) or "v2" OTA bootloader images. Returns a BaseFirmwareImage subclass, either ESP8266ROMFirmwareImage (v1) or ESP8266V2FirmwareImage (v2). d...
Generator to read SLIP packets from a serial port. Yields one full SLIP packet at a time, raises exception on timeout or invalid data. Designed to avoid too many calls to serial.read(1), which can bog down on slow systems. def slip_reader(port, trace_function): """Generator to read SLIP packets from a...
Align the position in the file to the next block of specified size def align_file_position(f, size): """ Align the position in the file to the next block of specified size """ align = (size - 1) - (f.tell() % size) f.seek(align, 1)
Given a flash size of the type passed in args.flash_size (ie 512KB or 1MB) then return the size in bytes. def flash_size_bytes(size): """ Given a flash size of the type passed in args.flash_size (ie 512KB or 1MB) then return the size in bytes. """ if "MB" in size: return int(size[:size.inde...
Pad to the next alignment boundary def pad_to(data, alignment, pad_character=b'\xFF'): """ Pad to the next alignment boundary """ pad_mod = len(data) % alignment if pad_mod != 0: data += pad_character * (alignment - pad_mod) return data
Modify the flash mode & size bytes if this looks like an executable bootloader image def _update_image_flash_params(esp, address, args, image): """ Modify the flash mode & size bytes if this looks like an executable bootloader image """ if len(image) < 8: return image # not long enough to be a bootlo...
Main function for esptool custom_commandline - Optional override for default arguments parsing (that uses sys.argv), can be a list of custom arguments as strings. Arguments and their values need to be added as individual items to the list e.g. "-b 115200" thus becomes ['-b', '115200']. def main(custom_com...
Any argument starting with "@" gets replaced with all values read from a text file. Text file arguments can be split by newline or by space. Values are added "as-is", as if they were specified in this order on the command line. def expand_file_arguments(): """ Any argument starting with "@" gets replaced w...
Use serial access to detect the chip type. We use the UART's datecode register for this, it's mapped at the same address on ESP8266 & ESP32 so we can use one memory read and compare to the datecode register for each chip type. This routine automatically performs ESPLoader.conne...
Execute a command with 'command', check the result code and throw an appropriate FatalError if it fails. Returns the "result" of a successful command. def check_command(self, op_description, op=None, data=b'', chk=0, timeout=DEFAULT_TIMEOUT): """ Execute a command with 'command', check...
A single connection attempt, with esp32r0 workaround options def _connect_attempt(self, mode='default_reset', esp32r0_delay=False): """ A single connection attempt, with esp32r0 workaround options """ # esp32r0_delay is a workaround for bugs with the most common auto reset # circuit and Windows...
Try connecting repeatedly until successful, or giving up def connect(self, mode='default_reset'): """ Try connecting repeatedly until successful, or giving up """ print('Connecting...', end='') sys.stdout.flush() last_error = None try: for _ in range(7): ...
Read memory address in target def read_reg(self, addr): """ Read memory address in target """ # we don't call check_command here because read_reg() function is called # when detecting chip type, and the way we check for success (STATUS_BYTES_LENGTH) is different # for different chip typ...
Write to memory address in target Note: mask option is not supported by stub loaders, use update_reg() function. def write_reg(self, addr, value, mask=0xFFFFFFFF, delay_us=0): """ Write to memory address in target Note: mask option is not supported by stub loaders, use update_reg() function. ...
Update register at 'addr', replace the bits masked out by 'mask' with new_val. new_val is shifted left to match the LSB of 'mask' Returns just-written value of register. def update_reg(self, addr, mask, new_val): """ Update register at 'addr', replace the bits masked out by 'mask' with...
Start downloading compressed data to Flash (performs an erase) Returns number of blocks (size self.FLASH_WRITE_SIZE) to write. def flash_defl_begin(self, size, compsize, offset): """ Start downloading compressed data to Flash (performs an erase) Returns number of blocks (size self.FLASH_WRITE...
Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32 ROM has it as a SPI command. def flash_spi_attach(self, hspi_arg): """Send SPI attach command to enable the SPI flash pins ESP8266 ROM does this when you send flash_begin, ESP32...
Tell the ESP bootloader the parameters of the chip Corresponds to the "flashchip" data structure that the ROM has in RAM. 'size' is in bytes. All other flash parameters are currently hardcoded (on ESP8266 these are mostly ignored by ROM code, on ESP32 I'm not sure.) def flash...
Run an arbitrary SPI flash command. This function uses the "USR_COMMAND" functionality in the ESP SPI hardware, rather than the precanned commands supported by hardware. So the value of spiflash_command is an actual command byte, sent over the wire. After writing command byte, ...
Read up to 24 bits (num_bytes) of SPI flash status register contents via RDSR, RDSR2, RDSR3 commands Not all SPI flash supports all three commands. The upper 1 or 2 bytes may be 0xFF. def read_status(self, num_bytes=2): """Read up to 24 bits (num_bytes) of SPI flash status register con...
Write up to 24 bits (num_bytes) of new status register num_bytes can be 1, 2 or 3. Not all flash supports the additional commands to write the second and third byte of the status register. When writing 2 bytes, esptool also sends a 16-byte WRSR command (as some flash types use ...
Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function def chip_id(self): """ Read Chip ID from efuse - the equivalent of the SDK system_get_chip_id() function """ id0 = self.read_reg(self.ESP_OTP_MAC0) id1 = self.read_reg(self.ESP_OTP_MAC1) return (id0 >> 24)...
Read MAC from OTP ROM def read_mac(self): """ Read MAC from OTP ROM """ mac0 = self.read_reg(self.ESP_OTP_MAC0) mac1 = self.read_reg(self.ESP_OTP_MAC1) mac3 = self.read_reg(self.ESP_OTP_MAC3) if (mac3 != 0): oui = ((mac3 >> 16) & 0xff, (mac3 >> 8) & 0xff, mac3 & 0xff...
Calculate an erase size given a specific size in bytes. Provides a workaround for the bootloader erase bug. def get_erase_size(self, offset, size): """ Calculate an erase size given a specific size in bytes. Provides a workaround for the bootloader erase bug.""" sectors_per_block = 1...
Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1 this bit is at position 16 in EFUSE_BLK0_RDATA0_REG def is_flash_encryption_key_valid(self): """ Bit 0 of efuse_rd_disable[3:0] is mapped to BLOCK1 this bit is at position 16 in EFUSE_BLK0_RDATA0_REG """ word0 = self.read_efuse(0) ...
bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config this bit is at position 19 in EFUSE_BLK0_RDATA0_REG def get_flash_crypt_config(self): """ bit 3 in efuse_rd_disable[3:0] is mapped to flash_crypt_config this bit is at position 19 in EFUSE_BLK0_RDATA0_REG """ word0 = self.re...
Read MAC from EFUSE region def read_mac(self): """ Read MAC from EFUSE region """ words = [self.read_efuse(2), self.read_efuse(1)] bitstring = struct.pack(">II", *words) bitstring = bitstring[2:8] # trim the 2 byte CRC try: return tuple(ord(b) for b in bitstring) ...
Return a new ImageSegment which splits "split_len" bytes from the beginning of the data. Remaining bytes are kept in this segment object (and the start address is adjusted to match.) def split_image(self, split_len): """ Return a new ImageSegment which splits "split_len" bytes from the ...
Load the next segment from the image file def load_segment(self, f, is_irom_segment=False): """ Load the next segment from the image file """ file_offs = f.tell() (offset, size) = struct.unpack('<II', f.read(8)) self.warn_if_unusual_segment(offset, size, is_irom_segment) segment...
If SHA256 digest of the ELF file needs to be inserted into this segment, do so. Returns segment data. def maybe_patch_segment_data(self, f, segment_data): """If SHA256 digest of the ELF file needs to be inserted into this segment, do so. Returns segment data.""" segment_len = len(segment_data) ...
Save the next segment to the image file, return next checksum value if provided def save_segment(self, f, segment, checksum=None): """ Save the next segment to the image file, return next checksum value if provided """ segment_data = self.maybe_patch_segment_data(f, segment.data) f.write(struct...
Calculate checksum of loaded image, based on segments in segment array. def calculate_checksum(self): """ Calculate checksum of loaded image, based on segments in segment array. """ checksum = ESPLoader.ESP_CHECKSUM_MAGIC for seg in self.segments: if seg.incl...
Append ESPLoader checksum to the just-written image def append_checksum(self, f, checksum): """ Append ESPLoader checksum to the just-written image """ align_file_position(f, 16) f.write(struct.pack(b'B', checksum))
Save a set of V1 images for flashing. Parameter is a base filename. def save(self, basename): """ Save a set of V1 images for flashing. Parameter is a base filename. """ # IROM data goes in its own plain binary file irom_segment = self.get_irom_segment() if irom_segment is not None: ...
Derive a default output name from the ELF name. def default_output_name(self, input_file): """ Derive a default output name from the ELF name. """ irom_segment = self.get_irom_segment() if irom_segment is not None: irom_offs = irom_segment.addr - ESP8266ROM.IROM_MAP_START el...
Save the next segment to the image file, return next checksum value if provided def save_flash_segment(self, f, segment, checksum=None): """ Save the next segment to the image file, return next checksum value if provided """ segment_end_pos = f.tell() + len(segment.data) + self.SEG_HEADER_LEN s...
Calculates 'k' from data itself, removing the need for strong random generator and producing deterministic (reproducible) signatures. See RFC 6979 for more details. def sign_digest_deterministic(self, digest, hashfunc=None, sigencode=sigencode_string): """ Calculates 'k' from data itsel...
hashfunc= should behave like hashlib.sha1 . The output length of the hash (in bytes) must not be longer than the length of the curve order (rounded up to the nearest byte), so using SHA256 with nist256p is ok, but SHA256 with nist192p is not. (In the 2**-96ish unlikely event of a hash ou...
Wrap an ELF file into a stub 'dict' def wrap_stub(elf_file): """ Wrap an ELF file into a stub 'dict' """ print('Wrapping ELF file %s...' % elf_file) e = esptool.ELFFile(elf_file) text_section = e.get_section('.text') try: data_section = e.get_section('.data') except ValueError: ...
order - order of the DSA generator used in the signature secexp - secure exponent (private key) in numeric form hash_func - reference to the same hash function used for generating hash data - hash in binary form of the signing data def generate_k(order, secexp, hash_func, data): ''' ...
Returns an iterator over 'chunk_len' chunks of 'source' def get_chunks(source, chunk_len): """ Returns an iterator over 'chunk_len' chunks of 'source' """ return (source[i: i + chunk_len] for i in range(0, len(source), chunk_len))
Endian-swap each word in 'source' bitstring def endian_swap_words(source): """ Endian-swap each word in 'source' bitstring """ assert len(source) % 4 == 0 words = "I" * (len(source) // 4) return struct.pack("<" + words, *struct.unpack(">" + words, source))
Swap the order of the words in 'source' bitstring def swap_word_order(source): """ Swap the order of the words in 'source' bitstring """ assert len(source) % 4 == 0 words = "I" * (len(source) // 4) return struct.pack(words, *reversed(struct.unpack(words, source)))
Load a 256-bit key, similar to stored in efuse, from a file 192-bit keys will be extended to 256-bit using the same algorithm used by hardware if 3/4 Coding Scheme is set. def _load_hardware_key(keyfile): """ Load a 256-bit key, similar to stored in efuse, from a file 192-bit keys will be extended to...
Calculate the digest of a bootloader image, in the same way the hardware secure boot engine would do so. Can be used with a pre-loaded key to update a secure bootloader. def digest_secure_bootloader(args): """ Calculate the digest of a bootloader image, in the same way the hardware secure boot engine w...
Generate an ECDSA signing key for signing secure boot images (post-bootloader) def generate_signing_key(args): """ Generate an ECDSA signing key for signing secure boot images (post-bootloader) """ if os.path.exists(args.keyfile): raise esptool.FatalError("ERROR: Key file %s already exists" % args.keyf...
Sign a data file with a ECDSA private key, append binary signature to file contents def sign_data(args): """ Sign a data file with a ECDSA private key, append binary signature to file contents """ sk = _load_ecdsa_signing_key(args) # calculate signature of binary data binary_content = args.datafile.re...
Verify a previously signed binary image, using the ECDSA public key def verify_signature(args): """ Verify a previously signed binary image, using the ECDSA public key """ key_data = args.keyfile.read() if b"-BEGIN EC PRIVATE KEY" in key_data: sk = ecdsa.SigningKey.from_pem(key_data) vk = s...
Load an ECDSA private key and extract the embedded public key as raw binary data. def extract_public_key(args): """ Load an ECDSA private key and extract the embedded public key as raw binary data. """ sk = _load_ecdsa_signing_key(args) vk = sk.get_verifying_key() args.public_keyfile.write(vk.to_string...
Return a list of the bit indexes that the "key tweak" applies to, as determined by the FLASH_CRYPT_CONFIG 4 bit efuse value. def _flash_encryption_tweak_range(flash_crypt_config=0xF): """ Return a list of the bit indexes that the "key tweak" applies to, as determined by the FLASH_CRYPT_CONFIG 4 bit efuse v...
Apply XOR "tweak" values to the key, derived from flash offset 'offset'. This matches the ESP32 hardware flash encryption. tweak_range is a list of bit indexes to apply the tweak to, as generated by _flash_encryption_tweak_range() from the FLASH_CRYPT_CONFIG efuse value. Return tweaked key def _f...
Convert integer x into a string of bytes, as per X9.62. def int_to_string( x ): """Convert integer x into a string of bytes, as per X9.62.""" assert x >= 0 if x == 0: return b('\0') result = [] while x: ordinal = x & 0xFF result.append(int2byte(ordinal)) x >>= 8 result.reverse() return b('')...
Convert a string of bytes into an integer, as per X9.62. def string_to_int( s ): """Convert a string of bytes into an integer, as per X9.62.""" result = 0 for c in s: if not isinstance(c, int): c = ord( c ) result = 256 * result + c return result
Is (x,y) a valid public key based on the specified generator? def point_is_valid( generator, x, y ): """Is (x,y) a valid public key based on the specified generator?""" # These are the tests specified in X9.62. n = generator.order() curve = generator.curve() if x < 0 or n <= x or y < 0 or n <= y: retur...
Verify that signature is a valid signature of hash. Return True if the signature is valid. def verifies( self, hash, signature ): """Verify that signature is a valid signature of hash. Return True if the signature is valid. """ # From X9.62 J.3.1. G = self.generator n = G.order() r = ...
Return a signature for the provided hash, using the provided random nonce. It is absolutely vital that random_k be an unpredictable number in the range [1, self.public_key.point.order()-1]. If an attacker can guess random_k, he can compute our private key from a single signature. Also, if an attacker...
Raise base to exponent, reducing by modulus def modular_exp( base, exponent, modulus ): "Raise base to exponent, reducing by modulus" if exponent < 0: raise NegativeExponentError( "Negative exponents (%d) not allowed" \ % exponent ) return pow( base, exponent, modulus )
Reduce poly by polymod, integer arithmetic modulo p. Polynomials are represented as lists of coefficients of increasing powers of x. def polynomial_reduce_mod( poly, polymod, p ): """Reduce poly by polymod, integer arithmetic modulo p. Polynomials are represented as lists of coefficients of increasing powe...
Polynomial multiplication modulo a polynomial over ints mod p. Polynomials are represented as lists of coefficients of increasing powers of x. def polynomial_multiply_mod( m1, m2, polymod, p ): """Polynomial multiplication modulo a polynomial over ints mod p. Polynomials are represented as lists of coefficie...
Polynomial exponentiation modulo a polynomial over ints mod p. Polynomials are represented as lists of coefficients of increasing powers of x. def polynomial_exp_mod( base, exponent, polymod, p ): """Polynomial exponentiation modulo a polynomial over ints mod p. Polynomials are represented as lists of coeffi...
Jacobi symbol def jacobi( a, n ): """Jacobi symbol""" # Based on the Handbook of Applied Cryptography (HAC), algorithm 2.149. # This function has been tested by comparison with a small # table printed in HAC, and by extensive use in calculating # modular square roots. assert n >= 3 assert n%2 == 1 a...
Modular square root of a, mod p, p prime. def square_root_mod_prime( a, p ): """Modular square root of a, mod p, p prime.""" # Based on the Handbook of Applied Cryptography, algorithms 3.34 to 3.39. # This module has been tested for all values in [0,p-1] for # every prime p from 3 to 1229. assert 0 <= a <...
Inverse of a mod m. def inverse_mod( a, m ): """Inverse of a mod m.""" if a < 0 or m <= a: a = a % m # From Ferguson and Schneier, roughly: c, d = a, m uc, vc, ud, vd = 1, 0, 0, 1 while c != 0: q, c, d = divmod( d, c ) + ( c, ) uc, vc, ud, vd = ud - q*uc, vd - q*vc, uc, vc # At this point, d ...