Python binascii.hexlify() Examples

The following are 30 code examples of binascii.hexlify(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module binascii , or try the search function .
Example #1
Source File: ssl_.py    From gist-alfred with MIT License 6 votes vote down vote up
def assert_fingerprint(cert, fingerprint):
    """
    Checks if given fingerprint matches the supplied certificate.

    :param cert:
        Certificate as bytes object.
    :param fingerprint:
        Fingerprint as string of hexdigits, can be interspersed by colons.
    """

    fingerprint = fingerprint.replace(':', '').lower()
    digest_length = len(fingerprint)
    hashfunc = HASHFUNC_MAP.get(digest_length)
    if not hashfunc:
        raise SSLError(
            'Fingerprint of invalid length: {0}'.format(fingerprint))

    # We need encode() here for py32; works on py2 and p33.
    fingerprint_bytes = unhexlify(fingerprint.encode())

    cert_digest = hashfunc(cert).digest()

    if not _const_compare_digest(cert_digest, fingerprint_bytes):
        raise SSLError('Fingerprints did not match. Expected "{0}", got "{1}".'
                       .format(fingerprint, hexlify(cert_digest))) 
Example #2
Source File: events.py    From hyper-h2 with MIT License 6 votes vote down vote up
def _bytes_representation(data):
    """
    Converts a bytestring into something that is safe to print on all Python
    platforms.

    This function is relatively expensive, so it should not be called on the
    mainline of the code. It's safe to use in things like object repr methods
    though.
    """
    if data is None:
        return None

    hex = binascii.hexlify(data)

    # This is moderately clever: on all Python versions hexlify returns a byte
    # string. On Python 3 we want an actual string, so we just check whether
    # that's what we have.
    if not isinstance(hex, str):  # pragma: no cover
        hex = hex.decode('ascii')

    return hex 
Example #3
Source File: getbms.py    From BatteryMonitor with GNU General Public License v2.0 6 votes vote down vote up
def x(self):
    """ Get data from BMS board"""
    command = bytes.fromhex('DD A5 03 00 FF FD 77')
    dat = self.getbmsdat(self.ser,command)
    self.rawi[0] = int.from_bytes(dat[2:4], byteorder = 'big',signed=True)
#    print (self.rawi)
#    self.line1 = [ 0 for i in range(int(len(dat)))]
#    for i in range(0,int(len(dat))):
  #    print (dat[i*2:i*2+2])
  #    print (int.from_bytes(dat[i:i+1], byteorder = 'big'))
#      self.line1[i] = int.from_bytes(dat[i:i+1], byteorder = 'big')
#    print (binascii.hexlify(dat))
#    print (self.line1)


  # voltages
    command = bytes.fromhex('DD A5 04 00 FF FC 77')
    voltages = self.getbmsdat(self.ser,command)
    for i in range(0,numcells):
      self.rawv[i+1] = int.from_bytes(voltages[i*2:i*2+2], byteorder = 'big')\
                       /1000.00
      self.rawv[i+1] = self.rawv[i+1]+self.rawv[i]
  #  print (self.rawv)
  #  print (binascii.hexlify(voltages)) 
Example #4
Source File: _symantec.py    From sslyze with GNU Affero General Public License v3.0 6 votes vote down vote up
def get_distrust_timeline(
        cls, verified_certificate_chain: List[Certificate]
    ) -> Optional[SymantecDistrustTimelineEnum]:
        has_whitelisted_cert = False
        has_blacklisted_cert = False

        # Is there a Symantec root certificate in the chain?
        for certificate in verified_certificate_chain:
            key_hash = binascii.hexlify(get_public_key_sha256(certificate)).decode("ascii")
            if key_hash in cls._CA_KEYS_BLACKLIST:
                has_blacklisted_cert = True
            if key_hash in cls._CA_KEYS_WHITELIST:
                has_whitelisted_cert = True

        distrust_enum = None
        if has_blacklisted_cert and not has_whitelisted_cert:
            leaf_cert = verified_certificate_chain[0]
            if leaf_cert.not_valid_before < datetime(year=2016, month=6, day=1):
                distrust_enum = SymantecDistrustTimelineEnum.MARCH_2018
            else:
                distrust_enum = SymantecDistrustTimelineEnum.SEPTEMBER_2018
        return distrust_enum 
Example #5
Source File: bmstest.py    From BatteryMonitor with GNU General Public License v2.0 6 votes vote down vote up
def switchfets(port='/dev/ttyUSB0'):
  """ switch charge and discharge fets """
  print ('(03)=Both FETs off')
  print ('(01)=Discharge FET on, Charge FET off')
  print ('(02)=Discharge FET off, Charge FET on')
  print ('(00)=Both FETs on')
  usercmd = input("Enter numeric option> ")
  ser = bmscore.openbms(port)
  command = bytes.fromhex('DD A5 03 00 FF FD 77')
  print ('command=',binascii.hexlify(command))
  data=bmscore.getbmsdat(ser,command)
  print ('reply=',binascii.hexlify(data))
  command = bytes.fromhex('DD A5 04 00 FF FC 77')
  print ('command=',binascii.hexlify(command))
  data=bmscore.getbmsdat(ser,command)
  print ('reply=',binascii.hexlify(data))
  command = bytes.fromhex('DD 5A 00 02 56 78 FF 30 77')
  data=bmscore.getbmsdat(ser,command)
  print ('reply=',binascii.hexlify(data))
  usercmd=b'\xE1\x02\x00'+bytes.fromhex(usercmd)
  command = b'\xDD\x5A'+usercmd+bmscore.crccalc(usercmd).to_bytes(2, byteorder='big')+b'\x77'
  print (binascii.hexlify(command))
  bmscore.getbmsdat(ser,command)
  command = bytes.fromhex('DD 5A 01 02 00 00 FF FD 77')
  bmscore.getbmsdat(ser,command) 
Example #6
Source File: apk.py    From dcc with Apache License 2.0 6 votes vote down vote up
def _dump_additional_attributes(additional_attributes):
    """ try to parse additional attributes, but ends up to hexdump if the scheme is unknown """

    attributes_raw = io.BytesIO(additional_attributes)
    attributes_hex = binascii.hexlify(additional_attributes)

    if not len(additional_attributes):
        return attributes_hex

    len_attribute, = unpack('<I', attributes_raw.read(4))
    if len_attribute != 8:
        return attributes_hex

    attr_id, = unpack('<I', attributes_raw.read(4))
    if attr_id != APK._APK_SIG_ATTR_V2_STRIPPING_PROTECTION:
        return attributes_hex
        
    scheme_id, = unpack('<I', attributes_raw.read(4))

    return "stripping protection set, scheme %d" % scheme_id 
Example #7
Source File: skype.py    From Radium with Apache License 2.0 6 votes vote down vote up
def get_md5_hash(self, enc_hex, key):
        # convert hash from hex to binary
        enc_binary = binascii.unhexlify(enc_hex)

        # retrieve the salt
        salt = hashlib.sha1('\x00\x00\x00\x00' + key).digest() + hashlib.sha1('\x00\x00\x00\x01' + key).digest()

        # encrypt value used with the XOR operation
        aes_key = self.aes_encrypt(struct.pack('I', 0) * 4, salt[0:32])[0:16]

        # XOR operation
        decrypted = []
        for d in range(16):
            decrypted.append(struct.unpack('B', enc_binary[d])[0] ^ struct.unpack('B', aes_key[d])[0])

        # cast the result byte
        tmp = ''
        for dec in decrypted:
            tmp = tmp + struct.pack(">I", dec).strip('\x00')

        # byte to hex
        return binascii.hexlify(tmp)

    # used for dictionary attack, if user specify a specific file 
Example #8
Source File: exceptions.py    From smbprotocol with MIT License 6 votes vote down vote up
def message(self):
        error_details_msg = ""
        for error_detail in self.error_details:
            if isinstance(error_detail, SMB2SymbolicLinkErrorResponse):
                detail_msg = self._get_symlink_error_detail_msg(error_detail)
            elif isinstance(error_detail, SMB2ShareRedirectErrorContext):
                detail_msg = self._get_share_redirect_detail_msg(error_detail)
            else:
                # unknown error details in response, output raw bytes
                detail_msg = "Raw: %s" % binascii.hexlify(error_detail).decode('utf-8')

            # the first details message is set differently
            if error_details_msg == "":
                error_details_msg = "%s - %s" % (error_details_msg, detail_msg)
            else:
                error_details_msg = "%s, %s" % (error_details_msg, detail_msg)

        status_hex = format(self.status, 'x')
        error_message = "%s: 0x%s%s" % (str(self.header['status']),
                                        status_hex, error_details_msg)
        return "Received unexpected status from the server: %s" % error_message 
Example #9
Source File: website.py    From pinnwand with MIT License 6 votes vote down vote up
def get(self, file_id: str) -> None:  # type: ignore
        """Get a file from the database and show it in hex."""

        with database.session() as session:
            file = (
                session.query(database.File)
                .filter(database.File.slug == file_id)
                .first()
            )

            if not file:
                raise tornado.web.HTTPError(404)

            if file.paste.exp_date < datetime.now():
                session.delete(file.paste)
                session.commit()

                log.warn(
                    "FileRaw.get: paste was expired, is your cronjob running?"
                )

                raise tornado.web.HTTPError(404)

            self.set_header("Content-Type", "text/plain; charset=utf-8")
            self.write(binascii.hexlify(file.raw.encode("latin1"))) 
Example #10
Source File: address.py    From monero-python with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def with_payment_id(self, payment_id=0):
        """Integrates payment id into the address.

        :param payment_id: int, hexadecimal string or :class:`PaymentID <monero.numbers.PaymentID>`
                    (max 64-bit long)

        :rtype: `IntegratedAddress`
        :raises: `TypeError` if the payment id is too long
        """
        payment_id = numbers.PaymentID(payment_id)
        if not payment_id.is_short():
            raise TypeError("Payment ID {0} has more than 64 bits and cannot be integrated".format(payment_id))
        prefix = const.INTADDRR_NETBYTES[const.NETS.index(self.net)]
        data = bytearray([prefix]) + self._decoded[1:65] + struct.pack('>Q', int(payment_id))
        checksum = bytearray(keccak_256(data).digest()[:4])
        return IntegratedAddress(base58.encode(hexlify(data + checksum))) 
Example #11
Source File: sessions.py    From cherrypy with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_id(self):
        """Return a new session id."""
        return binascii.hexlify(os.urandom(20)).decode('ascii') 
Example #12
Source File: __init__.py    From asn1tools with MIT License 6 votes vote down vote up
def _convert_hexstring(input_spec,
                       output_spec,
                       output_codec,
                       type_name,
                       hexstring):
    try:
        encoded = binascii.unhexlify(hexstring)
    except Exception as e:
        raise TypeError("'{}': {}".format(hexstring, str(e)))

    decoded = input_spec.decode(type_name, encoded)

    if output_codec in ['gser', 'xer', 'jer']:
        decoded = output_spec.encode(type_name, decoded, indent=4).strip()
    else:
        decoded = binascii.hexlify(output_spec.encode(type_name, decoded))

    print(decoded.decode('latin-1')) 
Example #13
Source File: sifter.py    From sandsifter with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self):
        while self.ts.run:
            while self.ts.pause:
                self.checkkey()
                time.sleep(.1)

            (self.maxy,self.maxx) = self.stdscr.getmaxyx()

            self.sx = 1
            self.sy = max((self.maxy + 1 - (self.T.IL + self.T.UL + 5 + 2))/2, 0)

            self.checkkey()

            synth_insn = cstr2py(self.T.r.raw_insn)

            if synth_insn and not self.ts.pause:
                self.draw()

            if self.do_tick:
                self.ticks = self.ticks + 1
                if self.ticks & self.TICK_MASK == 0:
                    with open(TICK, 'w') as f:
                        f.write("%s" % hexlify(synth_insn))

            time.sleep(self.TIME_SLICE) 
Example #14
Source File: apk.py    From dcc with Apache License 2.0 5 votes vote down vote up
def _dump_digests_or_signatures(digests_or_sigs):

    infos = ""
    for i,dos in enumerate(digests_or_sigs):

        infos += "\n"
        infos += " [%d]\n" % i
        infos += "  - Signature Id : %s\n" % APK._APK_SIG_ALGO_IDS.get(dos[0], hex(dos[0]))
        infos += "  - Digest: %s" % binascii.hexlify(dos[1])

    return infos 
Example #15
Source File: xer.py    From asn1tools with MIT License 5 votes vote down vote up
def encode(self, data):
        element = ElementTree.Element(self.name)

        if data[1] > 0:
            encoded = int(binascii.hexlify(data[0]), 16)
            encoded |= (0x80 << (8 * len(data[0])))
            element.text = bin(encoded)[10:10 + data[1]].upper()

        return element 
Example #16
Source File: main.py    From asn1tools with MIT License 5 votes vote down vote up
def decode(foo, name, encoded):
    print('  Input: {}'.format(binascii.hexlify(encoded).decode('ascii')))
    decoded = foo.decode(name, encoded)
    print('  Output: {}'.format(decoded)) 
Example #17
Source File: __init__.py    From asn1tools with MIT License 5 votes vote down vote up
def __init__(self, type_name, expected_tag, actual_tag, offset):
        message = "Expected {} with tag '{}' at offset {}, but got '{}'.".format(
            type_name,
            binascii.hexlify(expected_tag).decode('ascii'),
            offset,
            binascii.hexlify(actual_tag).decode('ascii'))
        super(DecodeTagError, self).__init__(message) 
Example #18
Source File: main.py    From asn1tools with MIT License 5 votes vote down vote up
def encode(foo, name, decoded):
    print('  Input: {}'.format(decoded))
    encoded = foo.encode(name, decoded)
    print('  Output: {} ({} bytes)'.format(binascii.hexlify(encoded).decode('ascii'),
                                           len(encoded))) 
Example #19
Source File: ssl_.py    From misp42splunk with GNU Lesser General Public License v3.0 5 votes vote down vote up
def assert_fingerprint(cert, fingerprint):
    """
    Checks if given fingerprint matches the supplied certificate.

    :param cert:
        Certificate as bytes object.
    :param fingerprint:
        Fingerprint as string of hexdigits, can be interspersed by colons.
    """

    fingerprint = fingerprint.replace(":", "").lower()
    digest_length = len(fingerprint)
    hashfunc = HASHFUNC_MAP.get(digest_length)
    if not hashfunc:
        raise SSLError("Fingerprint of invalid length: {0}".format(fingerprint))

    # We need encode() here for py32; works on py2 and p33.
    fingerprint_bytes = unhexlify(fingerprint.encode())

    cert_digest = hashfunc(cert).digest()

    if not _const_compare_digest(cert_digest, fingerprint_bytes):
        raise SSLError(
            'Fingerprints did not match. Expected "{0}", got "{1}".'.format(
                fingerprint, hexlify(cert_digest)
            )
        ) 
Example #20
Source File: wallet.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_address(self, major, minor):
        """
        Calculates sub-address for account index (`major`) and address index within
        the account (`minor`).

        :rtype: :class:`BaseAddress <monero.address.BaseAddress>`
        """
        # ensure indexes are within uint32
        if major < 0 or major >= 2**32:
            raise ValueError('major index {} is outside uint32 range'.format(major))
        if minor < 0 or minor >= 2**32:
            raise ValueError('minor index {} is outside uint32 range'.format(minor))
        master_address = self.address()
        if major == minor == 0:
            return master_address
        master_svk = unhexlify(self.view_key())
        master_psk = unhexlify(self.address().spend_key())
        # m = Hs("SubAddr\0" || master_svk || major || minor)
        hsdata = b''.join([
                b'SubAddr\0', master_svk,
                struct.pack('<I', major), struct.pack('<I', minor)])
        m = keccak_256(hsdata).digest()
        # D = master_psk + m * B
        D = ed25519.edwards_add(
                ed25519.decodepoint(master_psk),
                ed25519.scalarmult_B(ed25519.decodeint(m)))
        # C = master_svk * D
        C = ed25519.scalarmult(D, ed25519.decodeint(master_svk))
        netbyte = bytearray([const.SUBADDR_NETBYTES[const.NETS.index(master_address.net)]])
        data = netbyte + ed25519.encodepoint(D) + ed25519.encodepoint(C)
        checksum = keccak_256(data).digest()[:4]
        return address.SubAddress(base58.encode(hexlify(data + checksum))) 
Example #21
Source File: address.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def view_key(self):
        """Returns public view key.

        :rtype: str
        """
        return hexlify(self._decoded[33:65]).decode() 
Example #22
Source File: __init__.py    From dcc with Apache License 2.0 5 votes vote down vote up
def _fix_value(self, value):
        """
        Return a cleaned version of a value
        according to the specification:
        > Char	   ::=   	#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]

        See https://www.w3.org/TR/xml/#charsets

        :param value: a value to clean
        :return: the cleaned value
        """
        if not self.__charrange or not self.__replacement:
            if sys.maxunicode == 0xFFFF:
                # Fix for python 2.x, surrogate pairs does not match in regex
                self.__charrange = re.compile(u'^([\u0020-\uD7FF\u0009\u000A\u000D\uE000-\uFFFD]|[\uD800-\uDBFF][\uDC00-\uDFFF])*$')
                # TODO: this regex is slightly wrong... surrogates are not matched as pairs.
                self.__replacement = re.compile(u'[^\u0020-\uDBFF\u0009\u000A\u000D\uE000-\uFFFD\uDC00-\uDFFF]')
            else:
                self.__charrange = re.compile(u'^[\u0020-\uD7FF\u0009\u000A\u000D\uE000-\uFFFD\U00010000-\U0010FFFF]*$')
                self.__replacement = re.compile(u'[^\u0020-\uD7FF\u0009\u000A\u000D\uE000-\uFFFD\U00010000-\U0010FFFF]')

        # Reading string until \x00. This is the same as aapt does.
        if "\x00" in value:
            self.packerwarning = True
            log.warning("Null byte found in attribute value at position {}: "
                        "Value(hex): '{}'".format(
                value.find("\x00"),
                binascii.hexlify(value.encode("utf-8"))))
            value = value[:value.find("\x00")]

        if not self.__charrange.match(value):
            log.warning("Invalid character in value found. Replacing with '_'.")
            self.packerwarning = True
            value = self.__replacement.sub('_', value)
        return value 
Example #23
Source File: apk.py    From dcc with Apache License 2.0 5 votes vote down vote up
def __str__(self):
        return "\n".join([
            '{0:s}'.format(str(self.signed_data)),
            'signatures : {0}'.format(_dump_digests_or_signatures(self.signatures)),
            'public key : {0}'.format(binascii.hexlify(self.public_key)),
        ]) 
Example #24
Source File: address.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def spend_key(self):
        """Returns public spend key.

        :rtype: str
        """
        return hexlify(self._decoded[1:33]).decode() 
Example #25
Source File: address.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __repr__(self):
        return base58.encode(hexlify(self._decoded)) 
Example #26
Source File: seed.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def generate_hex(n_bytes=32):
    """Generate a secure and random hexadecimal string. 32 bytes by default, but arguments can override.

    :rtype: str
    """
    h = hexlify(urandom(n_bytes))
    return "".join(h.decode("utf-8")) 
Example #27
Source File: seed.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def sc_reduce(self, input):
        integer = ed25519.decodeint(input)
        modulo = integer % ed25519.l
        return hexlify(ed25519.encodeint(modulo)).decode() 
Example #28
Source File: ed25519.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def public_from_secret_hex(hk):
    return binascii.hexlify(public_from_secret(binascii.unhexlify(hk))).decode() 
Example #29
Source File: jsonrpc.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_transaction(self, blob, relay=True):
        res = self.raw_request('/sendrawtransaction', {
            'tx_as_hex': six.ensure_text(binascii.hexlify(blob)),
            'do_not_relay': not relay})
        if res['status'] == 'OK':
            return res
        raise exceptions.TransactionBroadcastError(
                "{status}: {reason}".format(**res),
                details=res) 
Example #30
Source File: address.py    From monero-python with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def base_address(self):
        """Returns the base address without payment id.
        :rtype: :class:`Address`
        """
        prefix = const.MASTERADDR_NETBYTES[const.NETS.index(self.net)]
        data = bytearray([prefix]) + self._decoded[1:65]
        checksum = keccak_256(data).digest()[:4]
        return Address(base58.encode(hexlify(data + checksum)))