def generateResponse (nonce, key=16*'00', ourNonce = None, debug=False): """ Given a nonce picked by the verifier computes the response of the prover. nonce -- the nonce as given by the verifier. our_nonce -- the nonce of the prover (in case he choses one). debug -- output the intermediate steps. """ nt = _decipher(nonce, key) nt2 = nt[1:]+nt[:1] nr = ourNonce or os.urandom(8) d1 = _decipher (nr, key) buff = int (_hexlify (d1), 16) ^ int (_hexlify (nt2), 16) buff = buff & 0xffffffffffffff00 >> 8 | buff & 0x00000000000000ff << 56 d2 = _decipher (_unhexlify(hex (buff)[2:-1]), key) if debug: print 'nt =', _hexlify (nt) print 'nt2 =', _hexlify (nt2) print 'D1 =', _hexlify (d1) print 'Buff =', hex(buff)[2:-1] print 'D2 =', _hexlify(d2) print 'D1 || D2 =', _hexlify (d1) + _hexlify (d2) return (d1 + d2, nr)
def hexlify(b: (bytes, bytearray)) -> (bytes, bytearray): """ bytes -> hex :param b: the bytes you want to convert to hex :return: the hex string representation of the specified bytes """ return _hexlify(b).decode("utf8")
def getrandbits(self, k): """ getrandbits(k) -> x. Generates a long int with k random bits. Used for covering very large ranges""" if k <= 0: raise ValueError('number of bits must be greater than zero') if k != int(k): raise TypeError('number of bits should be an integer') bytes = (k + 7) // 8 # bits / 8 and rounded up data = self._cache[self._pos:self._pos + bytes] bytes_left = self._cache_size - self._pos if bytes >= bytes_left: if bytes > self._cache_size: data = ''.join((data, self._source(bytes - bytes_left))) self.refresh() else: self.refresh() self._pos = bytes - bytes_left data = ''.join((data, self._cache[:self._pos])) else: self._pos += bytes return long(_hexlify(data), 16) >> (bytes * 8 - k) # trim excess bits
def seed(self, a=None): """Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If a is not None or an int or long, hash(a) is used instead. If a is an int or long, a is used directly. Distinct values between 0 and 27814431486575L inclusive are guaranteed to yield distinct internal states (this guarantee is specific to the default Wichmann-Hill generator). """ if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) if not isinstance(a, (int, long)): a = hash(a) a, x = divmod(a, 30268) a, y = divmod(a, 30306) a, z = divmod(a, 30322) self._seed = (int(x) + 1, int(y) + 1, int(z) + 1) self.gauss_next = None return
def seed(self, a=None): """Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If a is not None or an int or long, hash(a) is used instead. """ if a is None: try: # Seed with enough bytes to span the 19937 bit # state space for the Mersenne Twister a = long(_hexlify(_urandom(2500)), 16) except NotImplementedError: import time a = long(time.time() * 256) # use fractional seconds super(Random, self).seed(a) self.gauss_next = None
def seed(self, a=None): """Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If a is not None or an int or long, hash(a) is used instead. If a is an int or long, a is used directly. Distinct values between 0 and 27814431486575L inclusive are guaranteed to yield distinct internal states (this guarantee is specific to the default Wichmann-Hill generator). """ if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) # use fractional seconds if not isinstance(a, (int, long)): a = hash(a) a, x = divmod(a, 30268) a, y = divmod(a, 30306) a, z = divmod(a, 30322) self._seed = int(x)+1, int(y)+1, int(z)+1 self.gauss_next = None
def getrandbits(self, k): if k <= 0: raise ValueError('number of bits must be greater than zero') if k != int(k): raise TypeError('number of bits should be an integer') bytes = (k + 7) // 8 x = long(_hexlify(_urandom(bytes)), 16) return x >> bytes * 8 - k
def decipherSendMode (data, key): assert not len(data) % len(key) iv = 8*'00' res = [] while len(data): iv = _hexlify(_simpleDES(crc.mergeList(key), xorit(iv, data[0:8]))) res.append(iv) data = data[8:] return _unhexlify (''.join(res))
def getrandbits(self, k): """getrandbits(k) -> x. Generates a long int with k random bits.""" if k <= 0: raise ValueError("number of bits must be greater than zero") if k != int(k): raise TypeError("number of bits should be an integer") bytes = (k + 7) // 8 x = long(_hexlify(_urandom(bytes)), 16) return x >> bytes * 8 - k
def getrandbits(self, k): """getrandbits(k) -> x. Generates a long int with k random bits.""" if k <= 0: raise ValueError('number of bits must be greater than zero') if k != int(k): raise TypeError('number of bits should be an integer') bytes = (k + 7) // 8 # bits / 8 and rounded up x = long(_hexlify(_urandom(bytes)), 16) return x >> (bytes * 8 - k) # trim excess bits
def seed(self, a=None): if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) super(Random, self).seed(a) self.gauss_next = None
def seed(self, a = None): if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) super(Random, self).seed(a) self.gauss_next = None
def do_initializations(): sys.path.insert(0, 'solutions') # to avoid needing an __init__.py in the 'solutions' directory if not args.seed: # do as random.py source code to generate a random seed try: from os import urandom as _urandom from binascii import hexlify as _hexlify a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) # use fractional seconds args.seed = a import random random.seed(args.seed)
def seed(self, a = None): if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) if not isinstance(a, (int, long)): a = hash(a) a, x = divmod(a, 30268) a, y = divmod(a, 30306) a, z = divmod(a, 30322) self._seed = (int(x) + 1, int(y) + 1, int(z) + 1) self.gauss_next = None
def seed(self, a=None): if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) if not isinstance(a, (int, long)): a = hash(a) a, x = divmod(a, 30268) a, y = divmod(a, 30306) a, z = divmod(a, 30322) self._seed = (int(x) + 1, int(y) + 1, int(z) + 1) self.gauss_next = None
def seed(self, a=None): # """Initialize internal state from hashable object. # None or no argument seeds from current time or from an operating # system specific randomness source if available. # If a is not None or an int or long, hash(a) is used instead. # """ if a is None: try: a = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time a = long(time.time() * 256) # use fractional seconds super(Random, self).seed(a) self.gauss_next = None
def seed(self, x=None, *args): """For consistent cross-platform seeding, provide an integer seed. """ if x is None: # Use same random seed code copied from Python's random.Random try: x = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time x = long(time.time() * 256) # use fractional seconds elif not isinstance(x, _Integral): # Use the hash of the input seed object. Note this does not give # consistent results cross-platform--between Python versions or # between 32-bit and 64-bit systems. x = hash(x) self.rng_iterator.seed(x, *args, mix_extras=True)
def seed(self, x=None, *args): """For consistent cross-platform seeding, provide an integer seed. """ if x is None: # Use same random seed code copied from Python's random.Random try: x = int(_hexlify(_urandom(16)), 16) except NotImplementedError: import time x = int(time.time() * 256) # use fractional seconds elif not isinstance(x, _Integral): # Use the hash of the input seed object. Note this does not give # consistent results cross-platform--between Python versions or # between 32-bit and 64-bit systems. x = hash(x) self.rng_iterator.seed(x, *args, mix_extras=True)
def seed(self, a=None, minstates=recstates): """Initialize internal state from hashable object. None or no argument seeds from current time or from an operating system specific randomness source if available. If a is not None or an int or long, hash(a) is used instead. If a is an int or long, a is used directly. Distinct values between 0 and 27814431486575L inclusive are guaranteed to yield distinct internal states (this guarantee is specific to the default Wichmann-Hill generator). This has been modified to produce infinite distinct internal states, or at least whatever your RAM and CPU allow for. The number of possible internal states will always be equal to or greater than the value of the seed. To change the number of possible internal states, call setsecurity(num_of_states) or use getsecurity() to see how many there are. The reason I modified the code to work this way is to ensure every unique seed generates unique output, over a large enough number of pseudo-random numbers generated. """ if a is None: try: a = (long(_hexlify(_urandom(64)), 16)+1)*minstates except NotImplementedError: import time a = long(time.time()*256+1)*minstates # use units of 1/256 seconds and multiply by an insanely huge number so that you don't run into any upper boundaries if not isinstance(a, (int, long)): a = hash(a)*minstates # use the hash of the seed and multiply by an insanely huge number so that you don't run into any upper boundaries while abs(a) < minstates: a = hash(str(a))*minstates if a >= minstates: self.setsecurity(a) else: self.setsecurity(minstates) a, x = divmod(a, xmod1) a, y = divmod(a, xmod2) a, z = divmod(a, xmod3) self._seed = int(x)+1, int(y)+1, int(z)+1 self.gauss_next = None
def _mbdb_string(mbdb, pos): ''' parse a string from the mbdb file. The string length is encoded in 2 bytes prior to the string. If the length is 0xffff, this indicates an empty string. The string is decoded as uft 8 and if that fails, the bytes are returned as hexstring. ''' size = int.from_bytes(mbdb[pos:pos + 2], 'big') if size == 65535: return '', pos + 2 else: val = mbdb[pos + 2:pos + 2 + size] try: val = val.decode('utf8') except: val = _hexlify(val).decode('utf8') return val, pos + 2 + size
def create_seed_value(): """Creates a seed value for the `random` module, should one not be provided by the user. This code is simply a reproduction of the code from random.py in the standard library. Returns a seed value. """ from binascii import hexlify as _hexlify from os import urandom as _urandom try: seed = long(_hexlify(_urandom(16)), 16) except NotImplementedError: import time seed = long(time.time() * 256) # use fractional seconds return seed
def seed(self, a=None): """Initialize internal state of the random number generator. None or no argument seeds from current time or from an operating system specific randomness source if available. If a is not None or is an int or long, hash(a) is used instead. Hash values for some types are nondeterministic when the PYTHONHASHSEED environment variable is enabled. """ if a is None: try: # Seed with enough bytes to span the 19937 bit # state space for the Mersenne Twister a = long(_hexlify(_urandom(2500)), 16) except NotImplementedError: import time a = long(time.time() * 256) # use fractional seconds super(Random, self).seed(a) self.gauss_next = None
def seed(self, a=None): """Initialize internal state of the random number generator. None or no argument seeds from current time or from an operating system specific randomness source if available. If a is not None or is an int or long, hash(a) is used instead. Hash values for some types are nondeterministic when the PYTHONHASHSEED environment variable is enabled. """ if a is None: try: # Seed with enough bytes to span the 19937 bit # state space for the Mersenne Twister a = int(_hexlify(_urandom(2500)), 16) except NotImplementedError: import time a = int(time.time() * 256) # use fractional seconds super(Random, self).seed(a) self.gauss_next = None
def strhex(x): return _hexlify(x).decode('ascii').upper()
SYS_UPDATE_FILE = "retrofreak-system-update.img" UPDATE_PUB_KEY_FILE = "update.pub" REQUEST_PRV_KEY_FILE = "request.prv" # secrets # ROM secret ROM_SECRET = unhexlify("6F5BC7F1068C3D60D6A62E757739453A") # secret used to decrypt system update files (not app updates) SYSTEM_SECRET = unhexlify("9B589B3E3ACC4E2DC5389E7FF0C7C0BE") # used to encrypt console's DNA (serial #) for generating update requests REQUEST_SECRET = unhexlify("D7A1066CE2DC0D5A8636D1E8D0965E90") # RockChip RC4 key RKFW_KEY = unhexlify("7c4e0304550509072d2c7b38170d1711") # utilities hexlify = lambda b: _hexlify(b).decode("utf8").upper() # enums class RKFW_ChipID(IntEnum): RK3066 = 0x60 RK3188 = 0x70 class RKFW_Type(IntEnum): UPDATE = 0 RKAF = 1 # structures class RKFW_Header(Structure):
def random(self): return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
def random(self): """Get the next random number in the range [0.0, 1.0).""" return (long(_hexlify(_urandom(7)), 16) >> 3) * RECIP_BPF
def _from_bytes(value, dummy, _int=int, _hexlify=_hexlify): """An implementation of int.from_bytes for python 2.x.""" return _int(_hexlify(value), 16)
isDes -- for the special case of TDES where k1 = k2 (DES). """ if isDES: sessionKey = ourNonce[:4] + nonce[:4] assert len(sessionKey) is 8 return sessionKey else: sessionKey = ourNonce[:4] + nonce[:4] + ourNonce[4:] + nonce[4:] assert len(sessionKey) is 16 return sessionKey def isDES (key): """ Returns True if a given 3DES key is used to actually do DES. """ h = len (key) / 2 return key[:h] == key[h:] if __name__ == '__main__': nonce = 0x6e7577944adffc0c _nonce = _unhexlify (hex (nonce)[2:]) ourNonce = 0x1122334455667788 _ourNonce = _unhexlify (hex (ourNonce)[2:]) response, nr = generateResponse (_nonce, ourNonce = _ourNonce, debug=True) print 'Response = ', _hexlify (response) print 'Nonce = ', _hexlify (nr) print 'Verification ok?', verifyResponse ('AD6CC16025CCFB7B', nr) print 'Session key = ', _hexlify (deriveSessionKey (_nonce, ourNonce = _ourNonce, isDES=True))
def hexlify(raw_bytes): if type(raw_bytes) is bytes: return _hexlify(raw_bytes).decode() return _hexlify(raw_bytes)
def hexlify(b: (bytes, bytearray)) -> str: return _hexlify(b).decode("utf8")
def strhex(x): assert x is not None """Produce a hex-string representation of a sequence of bytes.""" return _hexlify(x).decode('ascii').upper()
def _db_parse_file_column(bytes_): ''' parse the plist in the file column of the Files table of iOS10+ backups ''' # NOTE: using the plistlib parser failed, not sure why p = _biplist.readPlistFromString(bytes_) # check if we have the same fields as in our reference sample if set(p.keys()) != _known_plist_keys: raise PlistParseError( 'someting in file column of Files table in Manifest.db changed') # we have only seen backups where $version, $archiver and $top have fixed # values, so raise exception when we hit some other value version = p.get('$version') if version != 100000: raise PlistParseError('$version != 100000') archiver = p.get('$archiver') if archiver != 'NSKeyedArchiver': raise PlistParseError('$archiver != NSKeyedArchiver') root_uid = p.get('$top').get('root') if root_uid.integer != 1: raise PlistParseError("$top['root'] != Uid(1)") # the interesting data is in the $objects field objects = p.get('$objects') # first field is expected to be $null if objects[0] != '$null': raise PlistParseError("$objects[0] != $null") # check if we have any new types of of fields #if len(set(objects[1].keys()) - _known_object_keys) != 0: # raise PlistParseError("$objects[1] fields do not match known fields: {:s}".format(str(objects[1].keys()))) uid = objects[1].get('UserID') # contents modification time mtime = _datetime(*list(_gmtime(objects[1].get('LastModified'))[0:7]) + [_UTC]) inode = objects[1].get('InodeNumber') mode = objects[1].get('Mode') # determine filetype and permissions based on mode filetype = FileType(mode & 0xE000) permissions = oct(mode & 0x1FFF) # metadata-change time ctime = _datetime(*list(_gmtime(objects[1].get('LastStatusChange'))[0:7]) + [_UTC]) gid = objects[1].get('GroupID') # birth-time (aka creation time) btime = _datetime(*list(_gmtime(objects[1].get('Birth'))[0:7]) + [_UTC]) size = objects[1].get('Size') # not sure what this is protection = objects[1].get('ProtectionClass') # apparently since iOS11 the plist includes a field 'Flags' in the plist # field as well, but I've only seen value 0 in my backups if objects[1].get('Flags', 0) != 0: raise PearBackError('assumption on plist flags field broken') # the Uid stored in 'RelativePath' seems to point to index in 'objects' # where the actual value is stored. The Uid.integer property gives the # integer value relpath = objects[objects[1].get('RelativePath').integer] # something similar for the '$class', which seems to be 'MBFile' always class_ = objects[objects[1].get('$class').integer].get('$classname') if class_ != 'MBFile': raise PlistParseError('assumption broken: $class is not always MBFile') # extended attributes are not always present, but if they are, they seem to # be pointed to by the UID value in the 'ExtendedAttributes' fields. The # target item then contains a bplist with key-value pairs under the key # 'NS.data' if 'ExtendedAttributes' in objects[1]: ea_idx = objects[1]['ExtendedAttributes'].integer extended_attributes = _biplist.readPlistFromString( objects[ea_idx].get('NS.data')) else: extended_attributes = None # target is only available when type is a symlink and its value indicates # the index of the property in the $objects field if filetype == FileType.Symlink: if 'Target' not in objects[1]: raise PlistParseError('Assumption broken on symlinks') tgt_idx = objects[1]['Target'].integer linktarget = objects[tgt_idx] else: linktarget = None # digest is also not always present, it works similar as above two fields, # let's store hex string instead of bytes if 'Digest' in objects[1]: d_idx = objects[1]['Digest'].integer digest = objects[d_idx] if type(digest) == dict: digest = digest['NS.data'] digest = _hexlify(digest).decode() else: digest = _hexlify(digest).decode() else: digest = None # convert to our named tuple and return object return _plistvals(uid, gid, mtime, ctime, btime, inode, mode, filetype, permissions, size, protection, relpath, extended_attributes, linktarget, digest)
from binascii import hexlify as _hexlify from hashlib import sha256, new from functools import wraps from . import segwit_addr from . import Base58 import sys check_decode = Base58.check_decode check_encode = Base58.check_encode bech32_decode = segwit_addr.decode bech32_encode = segwit_addr.encode ripemd160 = lambda x: new('ripemd160', x) _hex = lambda x: hex(int(x))[2:] hexlify = lambda x: _hexlify(x).decode() if sys.version > "3" else _hexlify(x) dsha256 = lambda x: sha256(sha256().digest(x)).digest() def MoNscript(m, n, publickeylist): # Be careful the order of publickeylist, which will change your address. Then redeem unsuccessfully if isinstance(publickeylist, list) or isinstance(publickeylist, tuple)\ and (isinstance(m, int) and isinstance(n) and m <= n and m >= 1): m += 80 n += 80 start = [bytes.fromhex(_hex(m))] for pk in publickeylist: pk = pk if isinstance(pk, bytes) else bytes.fromhex(pk) start += [bytes.fromhex(hex(len(pk))[2:]), pk] start += [bytes.fromhex(_hex(n)), bytes.fromhex("ae")] else: raise NotImplementedError("Can not handle your input")
from .Base58 import check_decode, check_encode from .segwit_addr import decode, encode from .func import tolittle_endian, tobig_endian, dsha256 from .opcodes import OPCODE_DICT from .sighash import SIGHASH from .address import P2WSHoP2SHAddress from binascii import hexlify as _hexlify from hashlib import sha256 from functools import partial from collections import OrderedDict from json import dumps, loads from pprint import pprint _hex = lambda x: hex(int(x))[2:] hexlify = lambda x: _hexlify(x).decode() # ordinary scriptPubKey def P2SH(script, otherplaces=False): strx = lambda x: "a914{}87".format(x) if script[0] in ["2", "3"]: # same operation to P2WSH-P2SH/P2WPKH-P2SH return strx(hexlify(check_decode(script))) if len(script) == 66 and not otherplaces: return strx( hashlib.new('ripemd160', sha256(bytes.fromhex(script)).digest()).hexdigest())
def hexlify(x): return _hexlify(codecs.latin_1_encode(x)[0])