本文整理汇总了Python中builtins.bytes方法的典型用法代码示例。如果您正苦于以下问题:Python builtins.bytes方法的具体用法?Python builtins.bytes怎么用?Python builtins.bytes使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类builtins
的用法示例。
在下文中一共展示了builtins.bytes方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: no
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def no(mytype, argnums=(1,)):
"""
A shortcut for the disallow_types decorator that disallows only one type
(in any position in argnums).
Example use:
>>> class newstr(object):
... @no('bytes')
... def __add__(self, other):
... pass
>>> newstr(u'1234') + b'1234' #doctest: +IGNORE_EXCEPTION_DETAIL
Traceback (most recent call last):
...
TypeError: argument can't be bytes
The object can also be passed directly, but passing the string helps
to prevent circular import problems.
"""
if isinstance(argnums, Integral):
argnums = (argnums,)
disallowed_types = [mytype] * len(argnums)
return disallow_types(argnums, disallowed_types)
示例2: SmartStr
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def SmartStr(string, encoding="utf8"):
"""Forces the string to be an encoded byte string."""
if six.PY3:
if isinstance(string, str):
return string.encode(encoding, "ignore")
elif isinstance(string, bytes):
return string
elif hasattr(string, "__bytes__"):
return string.__bytes__()
# If there is no dedicated __bytes__ method, just encode the
# unicode string as utf8.
return bytes(SmartUnicode(string), "utf8")
if six.PY2:
if isinstance(string, str):
return string
elif hasattr(string, "__bytes__"):
return string.__bytes__()
# Encode the result of the __str__ method.
return str(string).encode(encoding)
示例3: from_settings
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def from_settings(cls, settings):
my_level = settings.get('SC_LOG_LEVEL', 'INFO')
my_name = settings.get('SC_LOGGER_NAME', 'sc-logger')
my_output = settings.get('SC_LOG_STDOUT', True)
my_json = settings.get('SC_LOG_JSON', False)
my_dir = settings.get('SC_LOG_DIR', 'logs')
my_bytes = settings.get('SC_LOG_MAX_BYTES', '10MB')
my_file = settings.get('SC_LOG_FILE', 'main.log')
my_backups = settings.get('SC_LOG_BACKUPS', 5)
logger = LogFactory.get_instance(json=my_json,
name=my_name,
stdout=my_output,
level=my_level,
dir=my_dir,
file=my_file,
bytes=my_bytes,
backups=my_backups)
return cls(logger)
示例4: bin2ip
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def bin2ip(ipval):
"""Converts a 16-bytes binary blob to an IPv4 or IPv6 standard
representation. See ip2bin().
"""
try:
socket.inet_aton(ipval)
return ipval
except (TypeError, socket.error):
pass
try:
socket.inet_pton(socket.AF_INET6, ipval)
return ipval
except (TypeError, socket.error):
pass
try:
return int2ip(ipval)
except TypeError:
pass
if ipval[:12] == b'\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\xff\xff':
return socket.inet_ntoa(ipval[12:])
return socket.inet_ntop(socket.AF_INET6, ipval)
示例5: _extract_header
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def _extract_header(nsis_file, firstheader):
inflated_data, data_size = inflate_header(nsis_file, firstheader.data_offset)
header = Header._make(_header_pack.unpack_from(inflated_data))
firstheader.header = header
firstheader._raw_header = bytes(inflated_data)
firstheader._raw_header_c_size = data_size
# Parse the block headers.
block_headers = []
for i in range(BLOCKS_COUNT):
header_offset = i * _blockheader_pack.size
block_header = BlockHeader._make(_blockheader_pack.unpack_from(
header.raw_blocks[header_offset:]))
block_headers.append(block_header)
header.blocks = block_headers
# Parse the install types.
header.install_types = [
struct.unpack_from('<I', header.raw_install_types[i:])[0]
for i in range(0, len(header.raw_install_types), 4)]
return header
示例6: process_json
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def process_json(self, data, name):
"""
Processes as a JSON
:param data:
:param name:
:return:
"""
if data is None or len(data) == 0:
return
ret = []
try:
lines = [x.strip() for x in data.split(bytes(b'\n'))]
for idx, line in enumerate(lines):
ret.append(self.process_json_line(line, name, idx))
except Exception as e:
logger.debug('Exception in processing JSON %s : %s' % (name, e))
self.trace_logger.log(e)
return ret
示例7: process_mod
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def process_mod(self, data, name):
"""
Processing one modulus per line
:param data:
:param name:
:return:
"""
ret = []
try:
lines = [x.strip() for x in data.split(bytes(b'\n'))]
for idx, line in enumerate(lines):
sub = self.process_mod_line(line, name, idx)
ret.append(sub)
except Exception as e:
logger.debug('Error in line mod file processing %s : %s' % (name, e))
self.trace_logger.log(e)
return ret
示例8: csvfile_to_wb
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def csvfile_to_wb(csv_filename):
'''Open a CSV file and return an openpyxl workbook.'''
logger.log(
DEBUG_DETAILED,
'Converting CSV file {} into an XLSX workbook.'.format(csv_filename))
with open(csv_filename) as csv_file:
dialect = csv.Sniffer().sniff(csv_file.read())
if USING_PYTHON2:
for attr in dir(dialect):
a = getattr(dialect, attr)
if type(a) == unicode:
setattr(dialect, attr, bytes(a))
csv_file.seek(0)
reader = csv.reader(csv_file, dialect)
wb = pyxl.Workbook()
ws = wb.active
for row_index, row in enumerate(reader, 1):
for column_index, cell in enumerate(row, 1):
if cell not in ('', None):
ws.cell(row=row_index, column=column_index).value = cell
return (wb, dialect)
示例9: _check_oracles
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def _check_oracles(padding_oracle=None, decryption_oracle=None, block_size=16):
"""Check if padding or decryption oracle works"""
if not padding_oracle and not decryption_oracle:
log.critical_error("Give padding_oracle and/or decryption_oracle functions")
if decryption_oracle:
try:
decryption_oracle(bytes(b'B' * block_size))
except NotImplementedError:
log.critical_error("decryption_oracle not implemented")
except Exception as e:
log.critical_error("Error in first call to decryption_oracle: {}".format(e.message))
if padding_oracle:
try:
padding_oracle(payload=bytes(b'B'*block_size), iv=bytes(b'A'*block_size))
except NotImplementedError:
log.critical_error("padding_oracle not implemented")
except Exception as e:
log.critical_error("Error in first call to padding_oracle: {}".format(e.message))
示例10: aes_bytes_to_poly_blocks
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def aes_bytes_to_poly_blocks(ciphertext, additional, block_size=16):
"""Convert ciphertext to list of GF(2^128)"""
size_additional = len(additional)*8
size_ciphertext = len(ciphertext)*8
if len(ciphertext) % block_size != 0:
ciphertext += bytes(b'\x00' * (block_size - len(ciphertext)%block_size))
if len(additional) % block_size != 0:
additional += bytes(b'\x00' * (block_size - len(additional)%block_size))
blocks = []
blocks.extend([additional[block_size*i:(block_size*i)+block_size] for i in range(len(additional)//block_size)])
blocks.extend([ciphertext[block_size*i:(block_size*i)+block_size] for i in range(len(ciphertext)//block_size)])
blocks.append(i2b(size_additional, size=(block_size//2)*8, endian='big') + i2b(size_ciphertext, size=(block_size//2)*8, endian='big'))
blocks = list(map(aes_polynomial, blocks))
return blocks
示例11: test_parity
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def test_parity():
key = key_1024
print("\nTest: parity")
plaintext1 = bytes(b"Some plaintext ") + random_bytes(10) + bytes(b" anything can it be")
plaintext2 = bytes(b"Some plaintext ") + random_bytes(10) + bytes(b" anything can it be2")
ciphertext1 = h2b(subprocess.check_output(["python", rsa_oracles_path, "encrypt", key.identifier,
b2h(plaintext1)]).strip().decode())
ciphertext2 = h2b(subprocess.check_output(["python", rsa_oracles_path, "encrypt", key.identifier,
b2h(plaintext2)]).strip().decode())
key.texts.append({'cipher': b2i(ciphertext1)})
key.texts.append({'cipher': b2i(ciphertext2)})
msgs_recovered = parity(parity_oracle, key.publickey())
assert msgs_recovered[0] == b2i(plaintext1)
assert msgs_recovered[1] == b2i(plaintext2)
key.clear_texts()
示例12: encrypt
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def encrypt(self, content):
"""Encrypt a given content and return (iv, encrypted content)
"""
from builtins import bytes
if not isinstance(content, bytes):
raise TypeError('Content needs to be bytes')
iv = os.urandom(16)
aes = AES.new(self.aes_key, AES.MODE_CBC, iv)
return iv, aes.encrypt(pkcs5_pad(content))
示例13: pkcs5_unpad
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def pkcs5_unpad(data):
"""Do PKCS5 unpadding to data and return
"""
data_bytes = bytes(data)
return data_bytes[0:-data_bytes[-1]]
示例14: load
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def load(cls, path):
"""Load a migration from a given file"""
with open(path, 'r', encoding='utf-8') as fp:
content = fp.read()
checksum = bytes(hashlib.sha256(content.encode('utf-8')).digest())
# Should use enum but python3 requires importing an extra library
# Reconsidering the use of enums. This is a binary decision.
# Boolean will work just fine.
is_python = bool(re.findall(r"\.(py)$", os.path.abspath(path)))
return cls(os.path.abspath(path), os.path.basename(path),
is_python, content, checksum)
示例15: SmartUnicode
# 需要导入模块: import builtins [as 别名]
# 或者: from builtins import bytes [as 别名]
def SmartUnicode(string, encoding="utf8"):
"""Forces the string into a unicode object."""
if six.PY3:
if isinstance(string, bytes):
return string.decode(encoding, "ignore")
# Call the object's __str__ method which should return an unicode
# object.
return str(string)
elif six.PY2:
if isinstance(string, str):
return string.decode(encoding)
return unicode(string)