本文整理汇总了Python中six.int2byte函数的典型用法代码示例。如果您正苦于以下问题:Python int2byte函数的具体用法?Python int2byte怎么用?Python int2byte使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了int2byte函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __test__
def __test__(self, exponent, secret, compressed_secret):
with self.assertRaises(InvalidSecretError):
Secret(compressed=False, payload=b''.join([
serialize_beint(exponent, 32)]))
with self.assertRaises(InvalidSecretError):
Secret(compressed=True, payload=b''.join([
serialize_beint(exponent, 32)]))
obj = Secret(payload=b''.join([serialize_beint(exponent, 32)]))
self.assertEqual(obj, secret)
self.assertEqual(obj.exponent, exponent)
self.assertFalse(obj.compressed)
with self.assertRaises(InvalidSecretError):
Secret(compressed=False, payload=b''.join([
serialize_beint(exponent, 32),
six.int2byte(0x01)]))
with self.assertRaises(InvalidSecretError):
Secret(compressed=True, payload=b''.join([
serialize_beint(exponent, 32),
six.int2byte(0x01)]))
obj = Secret(payload=b''.join([
serialize_beint(exponent, 32),
six.int2byte(0x01)]))
self.assertEqual(obj, compressed_secret)
self.assertEqual(obj.exponent, exponent)
self.assertTrue(obj.compressed)
示例2: rldecode
def rldecode(data):
"""
RunLength decoder (Adobe version) implementation based on PDF Reference
version 1.4 section 3.3.4:
The RunLengthDecode filter decodes data that has been encoded in a
simple byte-oriented format based on run length. The encoded data
is a sequence of runs, where each run consists of a length byte
followed by 1 to 128 bytes of data. If the length byte is in the
range 0 to 127, the following length + 1 (1 to 128) bytes are
copied literally during decompression. If length is in the range
129 to 255, the following single byte is to be copied 257 - length
(2 to 128) times during decompression. A length value of 128
denotes EOD.
"""
decoded = b''
i = 0
while i < len(data):
#print 'data[%d]=:%d:' % (i,ord(data[i]))
length = six.indexbytes(data,i)
if length == 128:
break
if length >= 0 and length < 128:
for j in range(i+1,(i+1)+(length+1)):
decoded+=six.int2byte(six.indexbytes(data,j))
#print 'length=%d, run=%s' % (length+1,run)
i = (i+1) + (length+1)
if length > 128:
run = six.int2byte(six.indexbytes(data,i+1))*(257-length)
#print 'length=%d, run=%s' % (257-length,run)
decoded+=run
i = (i+1) + 1
return decoded
示例3: test_read_rain_collector_type
def test_read_rain_collector_type(self, mock_read_config_setting):
mock_read_config_setting.return_value = six.int2byte(0b10101110)
collector_type = RainCollectorTypeSerial(self.communicator.read_rain_collector_type())
self.assertEqual(RainCollectorTypeSerial.millimeters_0_1, collector_type)
mock_read_config_setting.assert_called_once_with('2B', '01')
mock_read_config_setting.reset_mock()
mock_read_config_setting.return_value = six.int2byte(0b10011110)
collector_type = RainCollectorTypeSerial(self.communicator.read_rain_collector_type())
self.assertEqual(RainCollectorTypeSerial.millimeters_0_2, collector_type)
mock_read_config_setting.assert_called_once_with('2B', '01')
mock_read_config_setting.reset_mock()
mock_read_config_setting.return_value = six.int2byte(0b10001110)
collector_type = RainCollectorTypeSerial(self.communicator.read_rain_collector_type())
self.assertEqual(RainCollectorTypeSerial.inches_0_01, collector_type)
mock_read_config_setting.assert_called_once_with('2B', '01')
示例4: xor
def xor(key, data):
"""
Perform cyclical exclusive or operations on ``data``.
The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If
the key is smaller than the provided ``data``, the ``key`` will be
repeated.
Args:
key(int or bytes): The key to xor ``data`` with.
data(bytes): The data to perform the xor operation on.
Returns:
bytes: The result of the exclusive or operation.
Examples:
>>> from pwny import *
>>> xor(5, b'ABCD')
b'DGFA'
>>> xor(5, b'DGFA')
b'ABCD'
>>> xor(b'pwny', b'ABCDEFGHIJKLMNOPQRSTUVWXYZ')
b'15-=51)19=%5=9!)!%=-%!9!)-'
>>> xor(b'pwny', b'15-=51)19=%5=9!)!%=-%!9!)-')
b'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
"""
if type(key) is int:
key = six.int2byte(key)
key_len = len(key)
return b''.join(
six.int2byte(c ^ six.indexbytes(key, i % key_len))
for i, c in enumerate(six.iterbytes(data))
)
示例5: encode
def encode(self, input, errors='strict'):
"""
Encode string to byte array
:param input: string (unicode) object to convert to byte array
:param errors: defines the error handling to apply
:return: returns a tuple (output object, length consumed)
"""
encode_buffer = b''
consumed = 0
for character in input:
consumed += 1
num = None
try:
num = self._encoding_map[ord(character)]
except KeyError:
if errors == 'replace':
num = 0x3f
elif errors == 'ignore':
pass
else:
raise ValueError("'%s' codec can't encode character %r in position %d" %
(self.NAME, character, consumed - 1))
if num is not None:
if num & 0xff00:
encode_buffer += int2byte(self._ESCAPE)
encode_buffer += int2byte(num & 0xff)
return encode_buffer, consumed
示例6: _serialize_derint
def _serialize_derint(n):
n_str = serialize_bignum(n)
return b''.join([
six.int2byte(0x02),
six.int2byte(len(n_str)),
n_str,
])
示例7: print_codepage
def print_codepage(printer, codepage):
if codepage.isdigit():
codepage = int(codepage)
printer._raw(CODEPAGE_CHANGE + six.int2byte(codepage))
printer._raw("after")
else:
printer.charcode(codepage)
sep = ""
# Table header
printer.set(text_type='B')
printer._raw(" {}\n".format(sep.join(map(lambda s: hex(s)[2:], range(0, 16)))))
printer.set()
# The table
for x in range(0, 16):
# First column
printer.set(text_type='B')
printer._raw("{} ".format(hex(x)[2:]))
printer.set()
for y in range(0, 16):
byte = six.int2byte(x * 16 + y)
if byte in (ESC, CTL_LF, CTL_FF, CTL_CR, CTL_HT, CTL_VT):
byte = ' '
printer._raw(byte)
printer._raw(sep)
printer._raw('\n')
示例8: test_read_setup_bit
def test_read_setup_bit(self, mock_read_config_setting):
mock_read_config_setting.return_value = six.int2byte(0b10101110)
bit = self.communicator.read_setup_bit(0b10)
self.assertEqual(0b10, bit)
mock_read_config_setting.assert_called_once_with('2B', '01')
mock_read_config_setting.reset_mock()
mock_read_config_setting.return_value = six.int2byte(0b10101101)
bit = self.communicator.read_setup_bit(0b10)
self.assertEqual(0b00, bit)
mock_read_config_setting.assert_called_once_with('2B', '01')
mock_read_config_setting.reset_mock()
mock_read_config_setting.return_value = six.int2byte(0b10101101)
bit = self.communicator.read_setup_bit(0b110)
self.assertEqual(0b100, bit)
mock_read_config_setting.assert_called_once_with('2B', '01')
mock_read_config_setting.reset_mock()
mock_read_config_setting.return_value = six.int2byte(0b10101111)
bit = self.communicator.read_setup_bit(0b110)
self.assertEqual(0b110, bit)
mock_read_config_setting.assert_called_once_with('2B', '01')
示例9: respond_to_client_hello
def respond_to_client_hello(self, message):
""" Establishing new connection to id_b, send a 128 bit response consisting of
8 bytes challenge, and a H_k(id_a, id_b, R_a) truncated to 8 bytes.
"""
# Verify that incoming packet has correct length
if not len(message) == 18:
_logger.info('Wrong length of client hello')
return
# Verify incoming MAC
expected_mac = handshake_mac(self.shared_key, message[:-8])
if not constant_time_compare(message[-8:], expected_mac):
_logger.info('Incorrect mac for client hello')
return
# Check that version is supported
client_version = decode_version(message[1:2])
if not client_version == self.version:
# reply with supported version, and copy of client's message
_logger.info('Unsupported version of client hello')
msg = (six.int2byte(Message.version_not_supported) +
encode_version(self.version) +
message[2:10])
mac = handshake_mac(self.shared_key, msg)
self._send(msg + mac)
return
self.R_a = rng(8)
self.R_b = message[2:10]
msg = six.int2byte(Message.server_hello) + self.R_a
mac = handshake_mac(self.shared_key, msg, self.R_b)
self.state = ServerState.wait_for_sa_proposal
self._send(msg + mac)
示例10: _serialize_derint
def _serialize_derint(n):
n_str = BigNum(n).serialize()
return b''.join([
six.int2byte(0x02),
six.int2byte(len(n_str)),
n_str,
])
示例11: generate_key
def generate_key(self, slot, algorithm, pin_policy=PIN_POLICY.DEFAULT,
touch_policy=TOUCH_POLICY.DEFAULT):
if ALGO.is_rsa(algorithm):
ensure_not_cve201715361_vulnerable_firmware_version(self.version)
if algorithm not in self.supported_algorithms:
raise UnsupportedAlgorithm(
'Algorithm not supported on this YubiKey: {}'
.format(algorithm),
algorithm_id=algorithm)
data = Tlv(TAG.ALGO, six.int2byte(algorithm))
if pin_policy:
data += Tlv(TAG.PIN_POLICY, six.int2byte(pin_policy))
if touch_policy:
data += Tlv(TAG.TOUCH_POLICY, six.int2byte(touch_policy))
data = Tlv(0xac, data)
resp = self.send_cmd(INS.GENERATE_ASYMMETRIC, 0, slot, data)
if algorithm in [ALGO.RSA1024, ALGO.RSA2048]:
data = _parse_tlv_dict(Tlv(resp[1:]).value)
return rsa.RSAPublicNumbers(
int_from_bytes(data[0x82], 'big'),
int_from_bytes(data[0x81], 'big')
).public_key(default_backend())
elif algorithm in [ALGO.ECCP256, ALGO.ECCP384]:
curve = ec.SECP256R1 if algorithm == ALGO.ECCP256 else ec.SECP384R1
return ec.EllipticCurvePublicNumbers.from_encoded_point(
curve(),
resp[5:]
).public_key(default_backend())
raise UnsupportedAlgorithm(
'Invalid algorithm: {}'.format(algorithm),
algorithm_id=algorithm)
示例12: __bytes__
def __bytes__(self):
first_byte = utils.setbit(0, 7, self.fin)
first_byte = utils.setbit(first_byte, 6, self.rsv1)
first_byte = utils.setbit(first_byte, 5, self.rsv2)
first_byte = utils.setbit(first_byte, 4, self.rsv3)
first_byte = first_byte | self.opcode
second_byte = utils.setbit(self.length_code, 7, self.mask)
b = six.int2byte(first_byte) + six.int2byte(second_byte)
if self.payload_length < 126:
pass
elif self.payload_length < MAX_16_BIT_INT:
# '!H' pack as 16 bit unsigned short
# add 2 byte extended payload length
b += struct.pack('!H', self.payload_length)
elif self.payload_length < MAX_64_BIT_INT:
# '!Q' = pack as 64 bit unsigned long long
# add 8 bytes extended payload length
b += struct.pack('!Q', self.payload_length)
else:
raise ValueError("Payload length exceeds 64bit integer")
if self.masking_key:
b += self.masking_key
return b
示例13: get_graphics_control_ext
def get_graphics_control_ext(self, duration=0.1, dispose=2,
transparent_flag=0, transparency_index=0):
"""
Graphics Control Extension. A sort of header at the start of
each image. Specifies duration and transparancy.
Dispose
-------
* 0 - No disposal specified.
* 1 - Do not dispose. The graphic is to be left in place.
* 2 - Restore to background color. The area used by the graphic
must be restored to the background color.
* 3 - Restore to previous. The decoder is required to restore the
area overwritten by the graphic with what was there prior to
rendering the graphic.
* 4-7 -To be defined.
"""
bb = '\x21\xF9\x04'
# low bit 1 == transparency,
bb += six.int2byte(((dispose & 3) << 2) | (transparent_flag & 1))
# 2nd bit 1 == user input , next 3 bits, the low two of which are used,
# are dispose.
bb += itob(int(duration * 100)) # in 100th of seconds
bb += six.int2byte(transparency_index) # transparency index
bb += '\x00' # end
return bb
示例14: itob
def itob(i):
"""Integer to two bytes"""
# devide in two parts (bytes)
i1 = i % 256
i2 = int(i / 256)
# make string (little endian)
return six.int2byte(i1) + six.int2byte(i2)
示例15: nasm_null_safe_mutable_data_finalizer
def nasm_null_safe_mutable_data_finalizer(env, code, data):
"""
Simple data allocation strategy that expects the code to be in a writable
segment. We just append the data to the end of the code.
"""
if data or env.buffers:
# Determine length of nullify + shellcode and adjust data pointer
xor_offsets = []
masked_data = OrderedDict()
for datum, (offset, orig_datum) in six.iteritems(data):
xor_offsets.extend([
offset + i
for i, b in enumerate(six.iterbytes(datum))
if b in (0, 10, 13)
])
masked_datum = b''.join([
six.int2byte(b) if b not in (0, 10, 13)
else six.int2byte(b ^ 0xff)
for b in six.iterbytes(datum)
])
masked_data[masked_datum] = (offset, orig_datum)
if xor_offsets:
# Build code to restore NUL, \r and \n
temp_reg = env.TEMP_REG[env.target.bits]
null_code = env.reg_load(env.BL, 255) + \
env.reg_load(temp_reg, env.OFFSET_REG)
last_offset = 0
for offset in xor_offsets:
offset -= last_offset
null_code.extend(
env.reg_add(temp_reg, offset) +
['xor [%s], bl' % temp_reg]
)
last_offset += offset
code = ['\t%s' % line for line in null_code] + code
data = masked_data
code_len = len(asm('\n'.join(code), target=env.target))
adjust_ebp = env.reg_add(env.OFFSET_REG, code_len)
return [
'\tjmp __getpc1',
'__getpc0:',
'\tpop %s' % env.OFFSET_REG,
] + [
'\t%s' % line for line in adjust_ebp
] + [
'\tjmp __realstart',
'__getpc1:',
'\tcall __getpc0',
'__realstart:',
] + code + _pack_data(data)
else:
return code