Python six.int2byte() Examples

The following are 30 code examples of six.int2byte(). 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 six , or try the search function .
Example #1
Source File: bits.py    From virtualchain with GNU General Public License v3.0 6 votes vote down vote up
def btc_tx_der_encode_integer(r):
    """
    Return a DER-encoded integer

    Based on code from python-ecdsa (https://github.com/warner/python-ecdsa)
    by Brian Warner.  Subject to the MIT license.
    """
    # borrowed from python-ecdsa
    if r < 0:
        raise ValueError('cannot support negative numbers')

    h = ("%x" % r).encode()
    if len(h) % 2:
        h = b("0") + h
    s = binascii.unhexlify(h)
    num = s[0] if isinstance(s[0], integer_types) else ord(s[0])
    if num <= 0x7f:
        return b("\x02") + int2byte(len(s)) + s
    else:
        # DER integers are two's complement, so if the first byte is
        # 0x80-0xff then we need an extra 0x00 byte to prevent it from
        # looking negative.
        return b("\x02") + int2byte(len(s)+1) + b("\x00") + s 
Example #2
Source File: encoder.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _SignedVarintEncoder():
  """Return an encoder for a basic signed varint value (does not include
  tag)."""

  def EncodeSignedVarint(write, value, unused_deterministic=None):
    if value < 0:
      value += (1 << 64)
    bits = value & 0x7f
    value >>= 7
    while value:
      write(six.int2byte(0x80|bits))
      bits = value & 0x7f
      value >>= 7
    return write(six.int2byte(bits))

  return EncodeSignedVarint 
Example #3
Source File: encoder.py    From coremltools with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _SignedVarintEncoder():
  """Return an encoder for a basic signed varint value (does not include
  tag)."""

  def EncodeSignedVarint(write, value):
    if value < 0:
      value += (1 << 64)
    bits = value & 0x7f
    value >>= 7
    while value:
      write(six.int2byte(0x80|bits))
      bits = value & 0x7f
      value >>= 7
    return write(six.int2byte(bits))

  return EncodeSignedVarint 
Example #4
Source File: encoder.py    From lambda-packs with MIT License 6 votes vote down vote up
def _SignedVarintEncoder():
  """Return an encoder for a basic signed varint value (does not include
  tag)."""

  def EncodeSignedVarint(write, value, unused_deterministic=None):
    if value < 0:
      value += (1 << 64)
    bits = value & 0x7f
    value >>= 7
    while value:
      write(six.int2byte(0x80|bits))
      bits = value & 0x7f
      value >>= 7
    return write(six.int2byte(bits))

  return EncodeSignedVarint 
Example #5
Source File: encoder.py    From auto-alt-text-lambda-api with MIT License 6 votes vote down vote up
def _SignedVarintEncoder():
  """Return an encoder for a basic signed varint value (does not include
  tag)."""

  def EncodeSignedVarint(write, value):
    if value < 0:
      value += (1 << 64)
    bits = value & 0x7f
    value >>= 7
    while value:
      write(six.int2byte(0x80|bits))
      bits = value & 0x7f
      value >>= 7
    return write(six.int2byte(bits))

  return EncodeSignedVarint 
Example #6
Source File: encoder.py    From luci-py with Apache License 2.0 6 votes vote down vote up
def _SignedVarintEncoder():
  """Return an encoder for a basic signed varint value (does not include
  tag)."""

  def EncodeSignedVarint(write, value, unused_deterministic=None):
    if value < 0:
      value += (1 << 64)
    bits = value & 0x7f
    value >>= 7
    while value:
      write(six.int2byte(0x80|bits))
      bits = value & 0x7f
      value >>= 7
    return write(six.int2byte(bits))

  return EncodeSignedVarint 
Example #7
Source File: oxx_fields.py    From ryu with Apache License 2.0 6 votes vote down vote up
def _normalize_user(oxx, mod, k, uv):
    try:
        from_user = getattr(mod, oxx + '_from_user')
        (n, v, m) = from_user(k, uv)
    except:
        return (k, uv)
    # apply mask
    if m is not None:
        v = b''.join(six.int2byte(_ord(x) & _ord(y)) for (x, y) in zip(v, m))
    try:
        to_user = getattr(mod, oxx + '_to_user')
        (k2, uv2) = to_user(n, v, m)
    except:
        return (k, uv)
    assert k2 == k
    return (k2, uv2) 
Example #8
Source File: u2f.py    From privacyidea with GNU Affero General Public License v3.0 6 votes vote down vote up
def parse_response_data(resp_data):
    """
    According to https://fidoalliance.org/specs/fido-u2f-v1.0-nfc-bt-amendment-20150514/fido-u2f-raw-message-formats.html#authentication-response-message-success
    the response is made up of
    0:      user presence byte
    1-4:    counter
    5-:     signature

    :param resp_data: response data from the FIDO U2F client
    :type resp_data: hex string
    :return: tuple of user_presence_byte(byte), counter(int),
        signature(hexstring)
    """
    resp_data_bin = binascii.unhexlify(resp_data)
    user_presence = six.int2byte(six.indexbytes(resp_data_bin, 0))
    signature = resp_data_bin[5:]
    counter = struct.unpack(">L", resp_data_bin[1:5])[0]
    return user_presence, counter, signature 
Example #9
Source File: encoder.py    From go2mapillary with GNU General Public License v3.0 6 votes vote down vote up
def _SignedVarintEncoder():
  """Return an encoder for a basic signed varint value (does not include
  tag)."""

  def EncodeSignedVarint(write, value):
    if value < 0:
      value += (1 << 64)
    bits = value & 0x7f
    value >>= 7
    while value:
      write(six.int2byte(0x80|bits))
      bits = value & 0x7f
      value >>= 7
    return write(six.int2byte(bits))

  return EncodeSignedVarint 
Example #10
Source File: bits.py    From virtualchain with GNU General Public License v3.0 6 votes vote down vote up
def btc_tx_der_encode_length(l):
    """
    Return a DER-encoded length field

    Based on code from python-ecdsa (https://github.com/warner/python-ecdsa)
    by Brian Warner.  Subject to the MIT license.
    """
    if l < 0:
        raise ValueError("length cannot be negative")

    if l < 0x80:
        return int2byte(l)
    s = ("%x" % l).encode()
    if len(s) % 2:
        s = b("0") + s
    s = binascii.unhexlify(s)
    llen = len(s)
    return int2byte(0x80 | llen) + s 
Example #11
Source File: SSL.py    From oss-ftp with MIT License 6 votes vote down vote up
def set_alpn_protos(self, protos):
        """
        Specify the clients ALPN protocol list.

        These protocols are offered to the server during protocol negotiation.

        :param protos: A list of the protocols to be offered to the server.
            This list should be a Python list of bytestrings representing the
            protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
        """
        # Take the list of protocols and join them together, prefixing them
        # with their lengths.
        protostr = b''.join(
            chain.from_iterable((int2byte(len(p)), p) for p in protos)
        )

        # Build a C string from the list. We don't need to save this off
        # because OpenSSL immediately copies the data out.
        input_str = _ffi.new("unsigned char[]", protostr)
        input_str_len = _ffi.cast("unsigned", len(protostr))
        _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len) 
Example #12
Source File: SSL.py    From oss-ftp with MIT License 6 votes vote down vote up
def set_alpn_protos(self, protos):
        """
        Specify the client's ALPN protocol list.

        These protocols are offered to the server during protocol negotiation.

        :param protos: A list of the protocols to be offered to the server.
            This list should be a Python list of bytestrings representing the
            protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
        """
        # Take the list of protocols and join them together, prefixing them
        # with their lengths.
        protostr = b''.join(
            chain.from_iterable((int2byte(len(p)), p) for p in protos)
        )

        # Build a C string from the list. We don't need to save this off
        # because OpenSSL immediately copies the data out.
        input_str = _ffi.new("unsigned char[]", protostr)
        input_str_len = _ffi.cast("unsigned", len(protostr))
        _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len) 
Example #13
Source File: utils.py    From oss-ftp with MIT License 6 votes vote down vote up
def _truncate_digest(digest, order_bits):
    digest_len = len(digest)

    if 8 * digest_len > order_bits:
        digest_len = (order_bits + 7) // 8
        digest = digest[:digest_len]

    if 8 * digest_len > order_bits:
        rshift = 8 - (order_bits & 0x7)
        assert 0 < rshift < 8

        mask = 0xFF >> rshift << rshift

        # Set the bottom rshift bits to 0
        digest = digest[:-1] + six.int2byte(six.indexbytes(digest, -1) & mask)

    return digest 
Example #14
Source File: writer_text.py    From ion-python with Apache License 2.0 6 votes vote down vote up
def _bytes_text(code_point_iter, quote, prefix=b'', suffix=b''):
    quote_code_point = None if len(quote) == 0 else six.byte2int(quote)
    buf = BytesIO()
    buf.write(prefix)
    buf.write(quote)
    for code_point in code_point_iter:
        if code_point == quote_code_point:
            buf.write(b'\\' + quote)
        elif code_point == six.byte2int(b'\\'):
            buf.write(b'\\\\')
        elif _is_printable_ascii(code_point):
            buf.write(six.int2byte(code_point))
        else:
            buf.write(_escape(code_point))
    buf.write(quote)
    buf.write(suffix)
    return buf.getvalue() 
Example #15
Source File: encoder.py    From sklearn-theano with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _SignedVarintEncoder():
  """Return an encoder for a basic signed varint value (does not include
  tag)."""

  def EncodeSignedVarint(write, value):
    if value < 0:
      value += (1 << 64)
    bits = value & 0x7f
    value >>= 7
    while value:
      write(six.int2byte(0x80|bits))
      bits = value & 0x7f
      value >>= 7
    return write(six.int2byte(bits))

  return EncodeSignedVarint 
Example #16
Source File: utils.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _truncate_digest(digest, order_bits):
    digest_len = len(digest)

    if 8 * digest_len > order_bits:
        digest_len = (order_bits + 7) // 8
        digest = digest[:digest_len]

    if 8 * digest_len > order_bits:
        rshift = 8 - (order_bits & 0x7)
        assert 0 < rshift < 8

        mask = 0xFF >> rshift << rshift

        # Set the bottom rshift bits to 0
        digest = digest[:-1] + six.int2byte(six.indexbytes(digest, -1) & mask)

    return digest 
Example #17
Source File: SSL.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def set_alpn_protos(self, protos):
        """
        Specify the clients ALPN protocol list.

        These protocols are offered to the server during protocol negotiation.

        :param protos: A list of the protocols to be offered to the server.
            This list should be a Python list of bytestrings representing the
            protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
        """
        # Take the list of protocols and join them together, prefixing them
        # with their lengths.
        protostr = b''.join(
            chain.from_iterable((int2byte(len(p)), p) for p in protos)
        )

        # Build a C string from the list. We don't need to save this off
        # because OpenSSL immediately copies the data out.
        input_str = _ffi.new("unsigned char[]", protostr)
        input_str_len = _ffi.cast("unsigned", len(protostr))
        _lib.SSL_CTX_set_alpn_protos(self._context, input_str, input_str_len) 
Example #18
Source File: SSL.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def set_alpn_protos(self, protos):
        """
        Specify the client's ALPN protocol list.

        These protocols are offered to the server during protocol negotiation.

        :param protos: A list of the protocols to be offered to the server.
            This list should be a Python list of bytestrings representing the
            protocols to offer, e.g. ``[b'http/1.1', b'spdy/2']``.
        """
        # Take the list of protocols and join them together, prefixing them
        # with their lengths.
        protostr = b''.join(
            chain.from_iterable((int2byte(len(p)), p) for p in protos)
        )

        # Build a C string from the list. We don't need to save this off
        # because OpenSSL immediately copies the data out.
        input_str = _ffi.new("unsigned char[]", protostr)
        input_str_len = _ffi.cast("unsigned", len(protostr))
        _lib.SSL_set_alpn_protos(self._ssl, input_str, input_str_len) 
Example #19
Source File: _der.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def encode_der(tag, *children):
    length = 0
    for child in children:
        length += len(child)
    chunks = [six.int2byte(tag)]
    if length < 0x80:
        chunks.append(six.int2byte(length))
    else:
        length_bytes = int_to_bytes(length)
        chunks.append(six.int2byte(0x80 | len(length_bytes)))
        chunks.append(length_bytes)
    chunks.extend(children)
    return b"".join(chunks) 
Example #20
Source File: text_encoder.py    From training_results_v0.5 with Apache License 2.0 5 votes vote down vote up
def decode_list(self, ids):
    numres = self._num_reserved_ids
    decoded_ids = []
    int2byte = six.int2byte
    for id_ in ids:
      if 0 <= id_ < numres:
        decoded_ids.append(RESERVED_TOKENS_BYTES[int(id_)])
      else:
        decoded_ids.append(int2byte(id_ - numres))
    # Python3: join byte arrays and then decode string
    return decoded_ids 
Example #21
Source File: padding.py    From jak with Apache License 2.0 5 votes vote down vote up
def pad(data, bs=16):
    """PKCS#7 Padding. Takes a bytestring data and an optional blocksize 'bs'"""
    length = bs - (len(data) % bs)
    data += six.int2byte(length) * length
    return data 
Example #22
Source File: des_c.py    From python-ntlm3 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def decrypt(self, str):
        # block - UChar[]
        block = []

        for i in six.iterbytes(str):
            block.append(i)

        # print block
        block = des_ecb_encrypt(block, self.KeySched, 0)

        res = b''
        for i in block:
            res = res + six.int2byte(i)

        return res 
Example #23
Source File: encoder.py    From coremltools with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _VarintEncoder():
  """Return an encoder for a basic varint value (does not include tag)."""

  def EncodeVarint(write, value):
    bits = value & 0x7f
    value >>= 7
    while value:
      write(six.int2byte(0x80|bits))
      bits = value & 0x7f
      value >>= 7
    return write(six.int2byte(bits))

  return EncodeVarint 
Example #24
Source File: reader_ops_test.py    From deep_image_model with Apache License 2.0 5 votes vote down vote up
def testZLibFlushRecord(self):
    fn = self._WriteRecordsToFile([b"small record"], "small_record")
    with open(fn, "rb") as h:
      buff = h.read()

    # creating more blocks and trailing blocks shouldn't break reads
    compressor = zlib.compressobj(9, zlib.DEFLATED, zlib.MAX_WBITS)

    output = b""
    for c in buff:
      if isinstance(c, int):
        c = six.int2byte(c)
      output += compressor.compress(c)
      output += compressor.flush(zlib.Z_FULL_FLUSH)

    output += compressor.flush(zlib.Z_FULL_FLUSH)
    output += compressor.flush(zlib.Z_FULL_FLUSH)
    output += compressor.flush(zlib.Z_FINISH)

    # overwrite the original file with the compressed data
    with open(fn, "wb") as h:
      h.write(output)

    with self.test_session() as sess:
      options = tf.python_io.TFRecordOptions(
          compression_type=TFRecordCompressionType.ZLIB)
      reader = tf.TFRecordReader(name="test_reader", options=options)
      queue = tf.FIFOQueue(1, [tf.string], shapes=())
      key, value = reader.read(queue)
      queue.enqueue(fn).run()
      queue.close().run()
      k, v = sess.run([key, value])
      self.assertTrue(tf.compat.as_text(k).startswith("%s:" % fn))
      self.assertAllEqual(b"small record", v) 
Example #25
Source File: hkdf.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _expand(self, key_material):
        output = [b""]
        counter = 1

        while self._algorithm.digest_size * (len(output) - 1) < self._length:
            h = hmac.HMAC(key_material, self._algorithm, backend=self._backend)
            h.update(output[-1])
            h.update(self._info)
            h.update(six.int2byte(counter))
            output.append(h.finalize())
            counter += 1

        return b"".join(output)[:self._length] 
Example #26
Source File: des.py    From python-ntlm3 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, key_str):
        k = str_to_key56(key_str)
        k = key56_to_key64(k)

        key_str = b''
        for i in k:
            key_str += six.int2byte(i & 0xFF)

        self.des_c_obj = des_c.DES(key_str) 
Example #27
Source File: padding.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _padding(self, size):
        return six.int2byte(size) * size 
Example #28
Source File: des_c.py    From python-ntlm3 with GNU Lesser General Public License v3.0 5 votes vote down vote up
def encrypt(self, plaintext):
        # block - UChar[]

        block = []
        for i in plaintext:
            block.append(i)

        block = des_ecb_encrypt(block, self.KeySched, 1)

        res = b''

        for i in block:
            res += six.int2byte(i)

        return res 
Example #29
Source File: padding.py    From teleport with Apache License 2.0 5 votes vote down vote up
def _padding(self, size):
        return six.int2byte(0) * (size - 1) + six.int2byte(size) 
Example #30
Source File: text_encoder.py    From training_results_v0.5 with Apache License 2.0 5 votes vote down vote up
def decode(self, ids, strip_extraneous=False):
    if strip_extraneous:
      ids = strip_ids(ids, list(range(self._num_reserved_ids or 0)))
    numres = self._num_reserved_ids
    decoded_ids = []
    int2byte = six.int2byte
    for id_ in ids:
      if 0 <= id_ < numres:
        decoded_ids.append(RESERVED_TOKENS_BYTES[int(id_)])
      else:
        decoded_ids.append(int2byte(id_ - numres))
    if six.PY2:
      return "".join(decoded_ids)
    # Python3: join byte arrays and then decode string
    return b"".join(decoded_ids).decode("utf-8", "replace")