def test_get_default(self): config.init() config.wipe() for _ in range(64): appid, key = random.uniform(256), random.uniform(256) value = config.get(appid, key) self.assertEqual(value, bytes())
def test_set_get(self): config.wipe() for _ in range(64): appid, key = random.uniform(256), random.uniform(256) value = random.bytes(128) config.set(appid, key, value) value2 = config.get(appid, key) self.assertEqual(value, value2)
async def check_mnemonic(ctx, mnemonic: str) -> bool: words = mnemonic.split() index = random.uniform(len(words) // 2) # first half result = await MnemonicKeyboard('Type %s. word' % (index + 1)) if result != words[index]: return False index = len(words) // 2 + random.uniform(len(words) // 2) # second half result = await MnemonicKeyboard('Type %s. word' % (index + 1)) return result == words[index]
def gen_clsag_sig(self, ring_size=11, index=None): msg = random.bytes(32) amnt = crypto.sc_init(random.uniform(0xFFFFFF) + 12) priv = crypto.random_scalar() msk = crypto.random_scalar() alpha = crypto.random_scalar() P = crypto.scalarmult_base(priv) C = crypto.add_keys2(msk, amnt, crypto.xmr_H()) Cp = crypto.add_keys2(alpha, amnt, crypto.xmr_H()) ring = [] for i in range(ring_size - 1): tk = TmpKey( crypto.encodepoint( crypto.scalarmult_base(crypto.random_scalar())), crypto.encodepoint( crypto.scalarmult_base(crypto.random_scalar())), ) ring.append(tk) index = index if index is not None else random.uniform(len(ring)) ring.insert(index, TmpKey(crypto.encodepoint(P), crypto.encodepoint(C))) ring2 = list(ring) mg_buffer = [] self.assertTrue( crypto.point_eq(crypto.scalarmult_base(priv), crypto.decodepoint(ring[index].dest))) self.assertTrue( crypto.point_eq( crypto.scalarmult_base(crypto.sc_sub(msk, alpha)), crypto.point_sub(crypto.decodepoint(ring[index].commitment), Cp), )) mlsag.generate_clsag_simple( msg, ring, CtKey(priv, msk), alpha, Cp, index, mg_buffer, ) sD = crypto.decodepoint(mg_buffer[-1]) sc1 = crypto.decodeint(mg_buffer[-2]) scalars = [crypto.decodeint(x) for x in mg_buffer[1:-2]] H = crypto.new_point() sI = crypto.new_point() crypto.hash_to_point_into(H, crypto.encodepoint(P)) crypto.scalarmult_into(sI, H, priv) # I = p*H return msg, scalars, sc1, sI, sD, ring2, Cp
async def check_mnemonic(ctx, mnemonic: str) -> bool: words = mnemonic.split() # check a word from the first half index = random.uniform(len(words) // 2) if not await check_word(ctx, words, index): return False # check a word from the second half index = random.uniform(len(words) // 2) + len(words) // 2 if not await check_word(ctx, words, index): return False return True
def test_set_get_interfaces(self): ifaces = msg.get_interfaces() self.assertEqual(ifaces, ()) for n in range(1, 9): ifaces = tuple((random.uniform(0x10000) for _ in range(n))) msg.set_interfaces(ifaces) ifaces2 = msg.get_interfaces() self.assertEqual(ifaces, ifaces2)
def test_uniform(self): c = {} for i in range(15): c[i] = 0 for _ in range(15000): r = random.uniform(15) c[r] += 1 for i in range(15): self.assertAlmostEqual(c[r], 1000, delta=200)
def test_error_location(self): mnemonics = [ "duckling enlarge academic academic agency result length solution fridge kidney coal piece deal husband erode duke ajar critical decision keyboard", "theory painting academic academic armed sweater year military elder discuss acne wildlife boring employer fused large satoshi bundle carbon diagnose anatomy hamster leaves tracks paces beyond phantom capital marvel lips brave detect luck", ] for mnemonic in mnemonics: data = tuple(slip39.mnemonic_to_indices(mnemonic)) self.assertEqual(slip39.rs1024_error_index(data), None) for i in range(len(data)): for _ in range(50): error_data = error_data = data[:i] + (data[i] ^ (random.uniform(1023) + 1), ) + data[i + 1:] self.assertEqual(slip39.rs1024_error_index(error_data), i)
def msg_register_sign(challenge: bytes, app_id: bytes) -> bytes: from apps.common import seed # derivation path is m/U2F'/r'/r'/r'/r'/r'/r'/r'/r' keypath = [0x80000000 | random.uniform(0xf0000000) for _ in range(0, 8)] nodepath = [_U2F_KEY_PATH] + keypath # prepare signing key from random path, compute decompressed public key node = seed.get_root_without_passphrase('nist256p1') node.derive_path(nodepath) pubkey = nist256p1.publickey(node.private_key(), False) # first half of keyhandle is keypath keybuf = ustruct.pack('>8L', *keypath) # second half of keyhandle is a hmac of app_id and keypath keybase = hmac.Hmac(node.private_key(), app_id, hashlib.sha256) keybase.update(keybuf) keybase = keybase.digest() # hash the request data together with keyhandle and pubkey dig = hashlib.sha256() dig.update(b'\x00') # uint8_t reserved; dig.update(app_id) # uint8_t appId[32]; dig.update(challenge) # uint8_t chal[32]; dig.update(keybuf) # uint8_t keyHandle[64]; dig.update(keybase) dig.update(pubkey) # uint8_t pubKey[65]; dig = dig.digest() # sign the digest and convert to der sig = nist256p1.sign(_U2F_ATT_PRIV_KEY, dig, False) sig = der.encode_seq((sig[1:33], sig[33:])) # pack to a response buf, resp = make_struct( resp_cmd_register( len(keybuf) + len(keybase), len(_U2F_ATT_CERT), len(sig))) resp.registerId = _U2F_REGISTER_ID utils.memcpy(resp.pubKey, 0, pubkey, 0, len(pubkey)) resp.keyHandleLen = len(keybuf) + len(keybase) utils.memcpy(resp.keyHandle, 0, keybuf, 0, len(keybuf)) utils.memcpy(resp.keyHandle, len(keybuf), keybase, 0, len(keybase)) utils.memcpy(resp.cert, 0, _U2F_ATT_CERT, 0, len(_U2F_ATT_CERT)) utils.memcpy(resp.sig, 0, sig, 0, len(sig)) resp.status = _SW_NO_ERROR return buf
def generate_key_handle(self) -> None: # derivation path is m/U2F'/r'/r'/r'/r'/r'/r'/r'/r' path = [HARDENED | random.uniform(0x80000000) for _ in range(0, 8)] nodepath = [_U2F_KEY_PATH] + path # prepare signing key from random path, compute decompressed public key self.node = seed.derive_node_without_passphrase(nodepath, "nist256p1") # first half of keyhandle is keypath keypath = ustruct.pack("<8L", *path) # second half of keyhandle is a hmac of rp_id_hash and keypath mac = hmac.Hmac(self.node.private_key(), self.rp_id_hash, hashlib.sha256) mac.update(keypath) self.id = keypath + mac.digest()
def cmd_init(req: Cmd) -> Cmd: if req.cid == 0: return cmd_error(req.cid, _ERR_INVALID_CID) elif req.cid == _CID_BROADCAST: # uint32_t except 0 and 0xffffffff resp_cid = random.uniform(0xFFFFFFFE) + 1 else: resp_cid = req.cid buf, resp = make_struct(resp_cmd_init()) utils.memcpy(resp.nonce, 0, req.data, 0, len(req.data)) resp.cid = resp_cid resp.versionInterface = _U2FHID_IF_VERSION resp.versionMajor = 2 resp.versionMinor = 0 resp.versionBuild = 0 resp.capFlags = _CAPFLAG_WINK return Cmd(req.cid, req.cmd, buf)
def newsid(self): while True: sid = random.uniform(0xffffffff) + 1 if sid not in self.handling_tasks: return sid
def rand_pswd(size=8): """Generate a random password of fixed length """ charset = "12346789ACDEFGHJKLMNPQRTUVWXYabcdefghijkmnopqrstuvwxyz" return "".join(charset[random.uniform(len(charset))] for _ in range(size))
def add(self): while True: i, j = random.uniform(4), random.uniform(4) if self.m[i][j] == 0: self.m[i][j] = 2 break
async def reset_device(ctx, msg): from trezor.ui.text import Text from trezor.crypto import hashlib, random, bip39 from trezor.ui.keyboard import MnemonicKeyboard from trezor.messages.EntropyRequest import EntropyRequest from trezor.messages.Success import Success from trezor.messages import FailureType from trezor.messages import ButtonRequestType from trezor.messages.wire_types import EntropyAck from apps.management.change_pin import request_pin_confirm from apps.common.confirm import require_confirm from apps.common import storage if __debug__: global internal_entropy if msg.strength not in (128, 192, 256): raise wire.FailureError( FailureType.ProcessError, 'Invalid strength (has to be 128, 192 or 256 bits)') if storage.is_initialized(): raise wire.FailureError(FailureType.UnexpectedMessage, 'Already initialized') internal_entropy = random.bytes(32) # display internal entropy if msg.display_random: entropy_lines = chunks(hexlify(internal_entropy).decode(), 16) entropy_content = Text('Internal entropy', ui.ICON_RESET, ui.MONO, *entropy_lines) await require_confirm(ctx, entropy_content, ButtonRequestType.ResetDevice) # request new PIN if msg.pin_protection: curpin = '' newpin = await request_pin_confirm(ctx) else: curpin = '' newpin = '' # request external entropy and compute mnemonic external_entropy_ack = await ctx.call(EntropyRequest(), EntropyAck) ehash = hashlib.sha256() ehash.update(internal_entropy) ehash.update(external_entropy_ack.entropy) entropy = ehash.digest() mnemonic = bip39.from_data(entropy[:msg.strength // 8]) # mnemonic safety warning warning_content = Text('Backup your seed', ui.ICON_NOCOPY, ui.NORMAL, 'Never make a digital', 'copy of your recovery', 'seed and never upload', 'it online!') await require_confirm(ctx, warning_content, ButtonRequestType.ResetDevice, confirm='I understand', cancel=None) # ask to write down mnemonic await show_mnemonic(mnemonic) # ask for random word to check correctness words = mnemonic.split() index = random.uniform(len(words)) res = await MnemonicKeyboard('Type %s. word' % (index + 1)) if res != words[index]: content = Text('Wrong entry!', ui.ICON_CLEAR, 'You have entered', 'wrong seed word.', 'Please, reconnect', 'the device and try again.', icon_color=ui.RED) ui.display.clear() await content raise wire.FailureError(FailureType.DataError, 'Wrong entry') # write into storage if curpin != newpin: config.change_pin(curpin, newpin) storage.load_settings(label=msg.label, use_passphrase=msg.passphrase_protection) storage.load_mnemonic(mnemonic) # show success message content = Text('Backup is done!', ui.ICON_CONFIRM, 'Never make a digital', 'copy of your recovery', 'seed and never upload', 'it online!', icon_color=ui.GREEN) await require_confirm(ctx, content, ButtonRequestType.ResetDevice, confirm='Finish setup', cancel=None) return Success(message='Initialized')
def random_entry(): while True: appid, key = 1 + random.uniform(255), random.uniform(256) if appid != PINAPP or key != PINKEY: break return appid, key
def generate(): while True: session_id = random.uniform(0xffffffff) + 1 if session_id not in opened: return session_id