INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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] a = [0, 0, 0, 0] # Convert ciphertext to (ints ^...
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._counter[i] = 0 # Overflow else: ...
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_efuse(offs) for offs in offsets...
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 Value)")) print("-" * 88) for category in set...
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_freq = self._esp.get_crystal_freq() clk_sel0, clk_sel1, dac_clk_div = EFUSE_CLK_SETTINGS[apb_freq] s...
Return the raw ( unformatted ) numeric value of the efuse bits
def get_raw(self): """ Return the raw (unformatted) numeric value of the efuse bits Returns a simple integer or (for some subclasses) a bitstring. """ value = self.parent.read_efuse(self.data_reg_offs) return (value & self.mask) >> self.shift
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 (value & (1 << self.read_disable_bit)) == 0
This algorithm is the equivalent of esp_crc8 () in ESP32 ROM code
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 value 0x00. """ result = 0x00 for b in struct.unpack("B" * 6, raw_mac): result ^= b for _ in rang...
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 """ def popcnt(b): """ Return number of "1" bits set in 'b' """ return len([x for x in bin(b) if...
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 * self.__y, p ) ) % p x3 = ( l * l - 2 * ...
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.
def check_supported_function(func, check_func): """ 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...
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.
def LoadFirmwareImage(chip, filename): """ 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 ESP8266ROMFirmwa...
Generator to read SLIP packets from a serial port. Yields one full SLIP packet at a time raises exception on timeout or invalid data.
def slip_reader(port, trace_function): """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. """ partial_packet = None ...
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.index("MB")]) * 1024 * 1024 elif "KB" in size: return int(size[:size.index("KB")]) * 1024 else: ...
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 bootloader image # unpack the (potential) image header magic, _, flash_mode, flash_...
Main function for esptool
def main(custom_commandline=None): """ 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 ...
Any argument starting with
def expand_file_arguments(): """ 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. """ new_args = [] expanded = False ...
Use serial access to detect the chip type.
def detect_chip(port=DEFAULT_PORT, baud=ESP_ROM_BAUD, connect_mode='default_reset', trace_enabled=False): """ 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 com...
Execute a command with command check the result code and throw an appropriate FatalError if it fails.
def check_command(self, op_description, op=None, data=b'', chk=0, timeout=DEFAULT_TIMEOUT): """ Execute a command with 'command', check the result code and throw an appropriate FatalError if it fails. Returns the "result" of a successful command. """ val, data = self.com...
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, if the EN pin on the dev board does not have # enoug...
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): last_error = self._connect_attempt(mode=mode, esp32r0...
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 types (!) val, data = self...
Write to memory address in target
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. """ return self.check_command("write target memory", self.ESP_WRITE_REG, ...
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
def update_reg(self, addr, mask, new_val): """ 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. """ shift = _mask_to_shift(mask) val = self.read_reg(a...
Start downloading compressed data to Flash ( performs an erase )
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_SIZE) to write. """ num_blocks = (compsize + self.FLASH_WRITE_SIZE - 1) // self.FLASH_WRITE_SIZE erase_blocks = ...
Send SPI attach command to enable the SPI flash pins
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 ROM has it as a SPI command. """ # last 3 bytes in ESP_SPI_ATTACH argument are reserved values arg = struct.pack('<I', hsp...
Tell the ESP bootloader the parameters of the chip
def flash_set_parameters(self, size): """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 ignore...
Run an arbitrary SPI flash command.
def run_spiflash_command(self, spiflash_command, data=b"", read_bits=0): """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 ac...
Read up to 24 bits ( num_bytes ) of SPI flash status register contents via RDSR RDSR2 RDSR3 commands
def read_status(self, num_bytes=2): """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. """ SPIFLASH_RDSR = 0x05 SPIFLASH_RDSR2...
Write up to 24 bits ( num_bytes ) of new status register
def write_status(self, new_status, num_bytes=2, set_non_volatile=False): """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 ...
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) | ((id1 & MAX_UINT24) << 8)
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) elif ((mac1 >...
Calculate an erase size given a specific size in bytes.
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 = 16 sector_size = self.FLASH_SECTOR_SIZE num_sectors = (size + sector_size - 1) // sector_size s...
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) rd_disable = (word0 >> 16) & 0x1 # reading of BLOCK1 is NOT ALLOWED so we assume valid key is progr...
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.read_efuse(0) rd_disable = (word0 >> 19) & 0x1 if rd_disable == 0: """ we can read the flash_cryp...
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) except TypeError: # P...
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 beginning of the data. Remaining bytes are kept in this segment object (and the start address is adjusted to match.) """ result = copy.copy(self) result.data = self.data[:split...
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_data = f.read(size) if len(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) file_pos = f.tell() # file_pos is position in the .bin file if self.elf_sha256_offset >= file_...
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.pack('<II', segment.addr, len(segment_data))) f.write(segment_data) ...
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.include_in_checksum: checksum = ESPLoader.checksum(seg.data, checksum...
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: with open("%s0x%05x.bin" % (basename, irom_segment.addr - ES...
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 else: irom_offs = 0 return "%s-...
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 segment_len_remainder = segment_end_pos % self.IROM_ALIGN if segment_len_r...
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 itself, removing the need for strong random generator and producing deterministic (reproducible) signatures. See RFC 6979 for more details. """ secexp = se...
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 output larger than the curv...
def sign(self, data, entropy=None, hashfunc=None, sigencode=sigencode_string, k=None): """ 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 nis...
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: data_section = None stub = { ...
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): ''' 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 ...
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
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 256-bit using the same algorithm used by hardware if 3/4 Coding Scheme is set. """ key = keyfile.read() if len(key) not in [24, 32]: raise esptool.FatalError...
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 would do so. Can be used with a pre-loaded key to update a secure bootloader. """ if args.iv is not None: print("WARNING: --iv argument is for TESTING PURPOSES ONLY...
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.keyfile) sk = ecdsa.SigningKey.generate(curve=ecdsa.NIST256p) with open(args...
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.read() signature = sk.sign_deterministic(binary_content, hashlib.sha256) # bac...
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 = sk.get_verifying_key() elif b"-BEGIN PUBLIC KEY" in key_data: ...
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()) print("%s public key extracted to %s" % (args.keyfile.name, args.public_key...
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 value. """ tweak_range = [] if (flash_crypt_config & 1) != 0: tweak_range += range(67) if (flash_crypt_conf...
Apply XOR tweak values to the key derived from flash offset offset. This matches the ESP32 hardware flash encryption.
def _flash_encryption_tweak_key(key, offset, tweak_range): """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 ...
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('').join(result)
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: return False if not curve.contains_point( x, y ): return False...
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 = signature.r s = signature.s if r < 1 or r > n-1: return False if s < 1 or s > n-1: 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 knows a few hi...
def sign( self, hash, random_k ): """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 ...
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.
def polynomial_reduce_mod( poly, polymod, p ): """Reduce poly by polymod, integer arithmetic modulo p. Polynomials are represented as lists of coefficients of increasing powers of x.""" # This module has been tested only by extensive use # in calculating modular square roots. # Just to make this easy, re...
Polynomial multiplication modulo a polynomial over ints mod p.
def polynomial_multiply_mod( m1, m2, polymod, p ): """Polynomial multiplication modulo a polynomial over ints mod p. Polynomials are represented as lists of coefficients of increasing powers of x.""" # This is just a seat-of-the-pants implementation. # This module has been tested only by extensive use # ...
Polynomial exponentiation modulo a polynomial over ints mod p.
def polynomial_exp_mod( base, exponent, polymod, p ): """Polynomial exponentiation modulo a polynomial over ints mod p. Polynomials are represented as lists of coefficients of increasing powers of x.""" # Based on the Handbook of Applied Cryptography, algorithm 2.227. # This module has been tested only by ...
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 = a % n if 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 < p assert 1 < p if a == 0: return 0 ...
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 is the GCD, and ud*a+...
Greatest common divisor using Euclid s algorithm.
def gcd2(a, b): """Greatest common divisor using Euclid's algorithm.""" while a: a, b = b%a, a return b
Greatest common divisor.
def gcd( *a ): """Greatest common divisor. Usage: gcd( [ 2, 4, 6 ] ) or: gcd( 2, 4, 6 ) """ if len( a ) > 1: return reduce( gcd2, a ) if hasattr( a[0], "__iter__" ): return reduce( gcd2, a[0] ) return a[0]
Least common multiple.
def lcm( *a ): """Least common multiple. Usage: lcm( [ 3, 4, 5 ] ) or: lcm( 3, 4, 5 ) """ if len( a ) > 1: return reduce( lcm2, a ) if hasattr( a[0], "__iter__" ): return reduce( lcm2, a[0] ) return a[0]
Decompose n into a list of ( prime exponent ) pairs.
def factorization( n ): """Decompose n into a list of (prime,exponent) pairs.""" assert isinstance( n, integer_types ) if n < 2: return [] result = [] d = 2 # Test the small primes: for d in smallprimes: if d > n: break q, r = divmod( n, d ) if r == 0: count = 1 while d <= n: ...
Return the Euler totient function of n.
def phi( n ): """Return the Euler totient function of n.""" assert isinstance( n, integer_types ) if n < 3: return 1 result = 1 ff = factorization( n ) for f in ff: e = f[1] if e > 1: result = result * f[0] ** (e-1) * ( f[0] - 1 ) else: result = result * ( f[0] - 1 ) return resu...
Return the Carmichael function of a number that is represented as a list of ( prime exponent ) pairs.
def carmichael_of_factorized( f_list ): """Return the Carmichael function of a number that is represented as a list of (prime,exponent) pairs. """ if len( f_list ) < 1: return 1 result = carmichael_of_ppower( f_list[0] ) for i in range( 1, len( f_list ) ): result = lcm( result, carmichael_of_ppower( f...
Carmichael function of the given power of the given prime.
def carmichael_of_ppower( pp ): """Carmichael function of the given power of the given prime. """ p, a = pp if p == 2 and a > 2: return 2**(a-2) else: return (p-1) * p**(a-1)
Return the order of x in the multiplicative group mod m.
def order_mod( x, m ): """Return the order of x in the multiplicative group mod m. """ # Warning: this implementation is not very clever, and will # take a long time if m is very large. if m <= 1: return 0 assert gcd( x, m ) == 1 z = x result = 1 while z != 1: z = ( z * x ) % m result = re...
Return the largest factor of a relatively prime to b.
def largest_factor_relatively_prime( a, b ): """Return the largest factor of a relatively prime to b. """ while 1: d = gcd( a, b ) if d <= 1: break b = d while 1: q, r = divmod( a, d ) if r > 0: break a = q return a
Return True if x is prime False otherwise.
def is_prime( n ): """Return True if x is prime, False otherwise. We use the Miller-Rabin test, as given in Menezes et al. p. 138. This test is not exact: there are composite values n for which it returns True. In testing the odd numbers from 10000001 to 19999999, about 66 composites got past the first te...
Return the smallest prime larger than the starting value.
def next_prime( starting_value ): "Return the smallest prime larger than the starting value." if starting_value < 2: return 2 result = ( starting_value + 1 ) | 1 while not is_prime( result ): result = result + 2 return result
Uses feeder to read and convert from in_stream and write to out_stream.
def _feed_stream(feeder, in_stream, out_stream, block_size = BLOCK_SIZE): 'Uses feeder to read and convert from in_stream and write to out_stream.' while True: chunk = in_stream.read(block_size) if not chunk: break converted = feeder.feed(chunk) out_stream.write(conv...
Encrypts a stream of bytes from in_stream to out_stream using mode.
def encrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT): 'Encrypts a stream of bytes from in_stream to out_stream using mode.' encrypter = Encrypter(mode, padding = padding) _feed_stream(encrypter, in_stream, out_stream, block_size)
Decrypts a stream of bytes from in_stream to out_stream using mode.
def decrypt_stream(mode, in_stream, out_stream, block_size = BLOCK_SIZE, padding = PADDING_DEFAULT): 'Decrypts a stream of bytes from in_stream to out_stream using mode.' decrypter = Decrypter(mode, padding = padding) _feed_stream(decrypter, in_stream, out_stream, block_size)
Provide bytes to encrypt ( or decrypt ) returning any bytes possible from this or any previous calls to feed.
def feed(self, data = None): '''Provide bytes to encrypt (or decrypt), returning any bytes possible from this or any previous calls to feed. Call with None or an empty string to flush the mode of operation and return any final bytes; no further calls to feed may be m...
Return a random integer k such that 1 < = k < order uniformly distributed across that range. For simplicity this only behaves well if order is fairly close ( but below ) a power of 256. The try - try - again algorithm we use takes longer and longer time ( on average ) to complete as order falls rising to a maximum of a...
def randrange(order, entropy=None): """Return a random integer k such that 1 <= k < order, uniformly distributed across that range. For simplicity, this only behaves well if 'order' is fairly close (but below) a power of 256. The try-try-again algorithm we use takes longer and longer time (on average) t...
Create AUTHORS file using git commits.
def generate_authors(git_dir): """Create AUTHORS file using git commits.""" authors = [] emails = [] git_log_cmd = ['git', 'log', '--format=%aN|%aE'] tmp_authors = _run_shell_command(git_log_cmd, git_dir).split('\n') for author_str in tmp_authors: author, email = author_str.split('|') ...
Initalizes root node of the tree i. e depth = 0
def _initalize_tree(self, position, momentum, slice_var, stepsize): """ Initalizes root node of the tree, i.e depth = 0 """ position_bar, momentum_bar, _ = self.simulate_dynamics(self.model, position, momentum, stepsize, sel...
Recursively builds a tree for proposing new position and momentum
def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize): """ Recursively builds a tree for proposing new position and momentum """ # Parameter names in algorithm (here -> representation in algorithm) # position -> theta, momentum -> r, slice_var -> u, di...
Returns a sample using a single iteration of NUTS
def _sample(self, position, stepsize): """ Returns a sample using a single iteration of NUTS """ # Re-sampling momentum momentum = np.random.normal(0, 1, len(position)) # Initializations depth = 0 position_backward, position_forward = position, position ...
Method to return samples using No U Turn Sampler
def sample(self, initial_pos, num_samples, stepsize=None, return_type='dataframe'): """ Method to return samples using No U Turn Sampler Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the starting ...
Returns a generator type object whose each iteration yields a sample
def generate_sample(self, initial_pos, num_samples, stepsize=None): """ Returns a generator type object whose each iteration yields a sample Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, the starting ...
Recursively builds a tree for proposing new position and momentum
def _build_tree(self, position, momentum, slice_var, direction, depth, stepsize, position0, momentum0): """ Recursively builds a tree for proposing new position and momentum """ if depth == 0: position_bar, momentum_bar, candidate_set_size, accept_set_bool =\ ...
Returns samples using No U Turn Sampler with dual averaging
def sample(self, initial_pos, num_adapt, num_samples, stepsize=None, return_type='dataframe'): """ Returns samples using No U Turn Sampler with dual averaging Parameters ---------- initial_pos: A 1d array like object Vector representing values of parameter position, ...