def password( seed = None ):
'''Generate a 128 bit password from seed'''
if not seed: return 16
password = list( b85encode( seed ). decode( 'latin_1' ))
pass_len = len( password ) # always 20
ornament = int. from_bytes( seed[ 12: ], 'little')
for chr_class in ( '0123456789', 'abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '.,:[]/' ):
pass_len += 1
ornament, pos = divmod( ornament, pass_len )
ornament, char = divmod( ornament, len( chr_class ))
password. insert( pos, chr_class[ char ])
result = { 'password': ''. join( password )}
result[ None ] = result[ 'password' ]
return result
# btc
python类b85encode()的实例源码
def test_decode_base85(self):
if sys.version_info.major != 3 or \
sys.version_info.minor < 4:
self.fail('Base85 support not available for the current Python version!')
data_bytes = self._random_bytes()
encoded_bytes = base64.b85encode(data_bytes)
result = self._transformer.decode('base85', encoded_bytes)
self.assertIsInstance(result, tuple)
self.assertIsNone(result[1]), 'An error occurred during Base85 decoding'
self.assertIsInstance(result[0], bytes,
'Base85 decoding result should be bytes or bytearray, ' \
'got %s instead' % type(result[0]))
self.assertEqual(data_bytes, result[0])
data_str = self._random_str()
self.assertRaises(TypeError, functools.partial(
self._transformer.decode, 'base85', data_str),
'Unexpected exception raised')
def setUp(self):
self.msg = ("Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean condimentum consectetur purus quis"
" dapibus. Fusce venenatis lacus ut rhoncus faucibus. Cras sollicitudin commodo sapien, sed bibendu"
"m velit maximus in. Aliquam ac metus risus. Sed cursus ornare luctus. Integer aliquet lectus id ma"
"ssa blandit imperdiet. Ut sed massa eget quam facilisis rutrum. Mauris eget luctus nisl. Sed ut el"
"it iaculis, faucibus lacus eget, sodales magna. Nunc sed commodo arcu. In hac habitasse platea dic"
"tumst. Integer luctus aliquam justo, at vestibulum dolor iaculis ac. Etiam laoreet est eget odio r"
"utrum, vel malesuada lorem rhoncus. Cras finibus in neque eu euismod. Nulla facilisi. Nunc nec ali"
"quam quam, quis ullamcorper leo. Nunc egestas lectus eget est porttitor, in iaculis felis sceleris"
"que. In sem elit, fringilla id viverra commodo, sagittis varius purus. Pellentesque rutrum loborti"
"s neque a facilisis. Mauris id tortor placerat, aliquam dolor ac, venenatis arcu.")
self.contact = create_contact()
self.settings = Settings(logfile_masking=True)
compressed = zlib.compress(b'abcdefghijk', level=COMPRESSION_LEVEL)
file_key = os.urandom(KEY_LENGTH)
encrypted = encrypt_and_sign(compressed, key=file_key)
encrypted += file_key
encoded = base64.b85encode(encrypted)
self.short_f_data = (int_to_bytes(1) + int_to_bytes(2) + b'testfile.txt' + US_BYTE + encoded)
def _encode_token(self, token):
"""
takes a token as input, if token is in encoding dictionary, looks its
hash up and returns it. else, hashes it, checks it for collisions
(overkill) while updating en(de)coding dictionaries.
:param token: str: token.
:return: str: hashed token
"""
if token in self.encode_dictionary:
return self.encode_dictionary[token]
else:
hashed_token, salt = hash_token(token,
hash_function=self.hash_function,
salt_length=self.salt_length,
salt=self.one_salt)
while hashed_token in self.decode_dictionary:
hashed_token, salt = hash_token(token,
hash_function=self.hash_function,
salt_length=self.salt_length,
salt=None)
self.decode_dictionary[hashed_token] = (token,
base64.b85encode(salt).decode())
self.encode_dictionary[token] = hashed_token
return hashed_token
def hash_token(token, hash_function='sha256', salt_length=32, salt=None):
"""
takes a token and hashes it along with a random salt of given length,
according to the specified hash function.
:param token: str: string of any length
:param hash_function: str: hash function to use (check hashlib library).
:param salt_length: int: salt length in bytes.
:param salt: bytes: only used for tests, specifies which salt to use.
:return: str, bytes: hashed token (base85-decoded) and the random salt used.
"""
if salt is None:
salt = os.urandom(salt_length)
token_hasher = hashlib.new(hash_function)
token_hasher.update(token.encode() + salt)
token_digest = token_hasher.digest()
token_base85 = base64.b85encode(token_digest)
hashed_token = token_base85.decode()
return hashed_token, salt
def random_string(length=TRACKER_PASSWORD_LENGTH_MIN):
salt = b85encode(urandom(length))
return salt.decode()
def hash_password(password, salt):
hashed = b85encode(shash(password, salt[:User.SALT_LENGTH]))
return hashed.decode()[:User.PASSWORD_LENGTH]
def run_backup(self, args):
"""Run the backup operation."""
chunksize = args.chunksize
encodefunc = base64.b85encode #FIXME: add arg
infile = open(args.infile, "rb")
infile_size = os.path.getsize(infile.name)
outfile = args.outfile
inputhash = hashlib.sha256()
framedata = self.frame_data_func(args)
qr_count = infile_size / chunksize + 1
self.logger.info('Original file size: %dKiB', infile_size / 1024)
self.logger.info('Total number of QR codes: %d', qr_count)
exporter = self.setup_exporter(args, qr_count)
qr_number = 0
sizesofar = 0
while True:
bindata = infile.read(chunksize)
if not bindata: break
frame = framedata(bindata, qr_count, sizesofar)
inputhash.update(bindata)
sizesofar += len(bindata)
qr_number += 1
self.logger.info('Exporting QR %d of %d', qr_number, qr_count)
encdata = encodefunc(frame).decode()
qr = pyqrcode.create(encdata)
exporter.add_qr(qr)
exporter.finish(inputhash)
self.logger.info('Finished exporting')
if args.sha256:
print('SHA-256 of input: %s' % inputhash.hexdigest())
def encode(self, enc, data):
assert isinstance(data, (bytearray, bytes))
enc = enc.lower()
assert self._in_list(enc, ENCODINGS),\
'Unknown encoding %s' % enc
if enc == 'base64':
output = base64.b64encode(data)
elif enc == 'base64 url':
output = base64.urlsafe_b64encode(data)
elif enc == 'base32':
output = base64.b32encode(data)
elif enc == 'base85':
output = base64.b85encode(data)
elif enc == 'hex':
output = codecs.encode(data, 'hex')
elif enc == 'url':
# urllib requires str?
output = urllibparse.quote_plus(data.decode())
output = output.encode()
elif enc == 'html':
# html module requires str?
output = html_encode(data.decode())
output = output.encode()
elif enc == 'rot13':
output = codecs.encode(data.decode(), 'rot_13')
output = output.encode()
elif enc == 'utf8':
output = codecs.encode(data.decode(), 'utf8')
elif enc == 'utf16':
output = codecs.encode(data.decode(), 'utf16')
else:
output = data
return output
def test_encode_base85(self):
if sys.version_info.major != 3 or \
sys.version_info.minor < 4:
self.fail('Base85 support not available for the current Python version!')
data_bytes = self._random_bytes()
encoded_bytes = base64.b85encode(data_bytes)
result_bytes = self._transformer.encode('base85', data_bytes)
self.assertIsInstance(result_bytes, bytes,
'Base85 encoding result should be bytes or bytearray, ' \
'got %s instead' % type(result_bytes))
self.assertEqual(encoded_bytes, result_bytes)
data_str = self._random_str()
self.assertRaises(TypeError, functools.partial(
self._transformer.encode, 'base85', data_str),
'Unexpected exception raised')
def test_b85_padding(self):
eq = self.assertEqual
eq(base64.b85encode(b"x", pad=True), b'cmMzZ')
eq(base64.b85encode(b"xx", pad=True), b'cz6H+')
eq(base64.b85encode(b"xxx", pad=True), b'czAdK')
eq(base64.b85encode(b"xxxx", pad=True), b'czAet')
eq(base64.b85encode(b"xxxxx", pad=True), b'czAetcmMzZ')
eq(base64.b85decode(b'cmMzZ'), b"x\x00\x00\x00")
eq(base64.b85decode(b'cz6H+'), b"xx\x00\x00")
eq(base64.b85decode(b'czAdK'), b"xxx\x00")
eq(base64.b85decode(b'czAet'), b"xxxx")
eq(base64.b85decode(b'czAetcmMzZ'), b"xxxxx\x00\x00\x00")
def test_b85_padding(self):
eq = self.assertEqual
eq(base64.b85encode(b"x", pad=True), b'cmMzZ')
eq(base64.b85encode(b"xx", pad=True), b'cz6H+')
eq(base64.b85encode(b"xxx", pad=True), b'czAdK')
eq(base64.b85encode(b"xxxx", pad=True), b'czAet')
eq(base64.b85encode(b"xxxxx", pad=True), b'czAetcmMzZ')
eq(base64.b85decode(b'cmMzZ'), b"x\x00\x00\x00")
eq(base64.b85decode(b'cz6H+'), b"xx\x00\x00")
eq(base64.b85decode(b'czAdK'), b"xxx\x00")
eq(base64.b85decode(b'czAet'), b"xxxx")
eq(base64.b85decode(b'czAetcmMzZ'), b"xxxxx\x00\x00\x00")
def test_invalid_encoding_raises_fr(self):
# Setup
payload = binascii.unhexlify('3f264d4189d7a091') + US_BYTE + base64.b85encode(b'filedata')
# Test
self.assertFR("Error: Received file name had invalid encoding.", process_received_file, payload, self.nick)
def test_invalid_name_raises_fr(self):
# Setup
payload = b'\x01filename' + US_BYTE + base64.b85encode(b'filedata')
# Test
self.assertFR("Error: Received file had an invalid name.", process_received_file, payload, self.nick)
def test_invalid_data_raises_fr(self):
# Setup
payload = b'testfile.txt' + US_BYTE + base64.b85encode(b'filedata') + b'\x01'
# Test
self.assertFR("Error: Received file had invalid encoding.", process_received_file, payload, self.nick)
def test_invalid_key_raises_fr(self):
# Setup
payload = b'testfile.txt' + US_BYTE + base64.b85encode(b'filedata')
# Test
self.assertFR("Error: Received file had an invalid key.", process_received_file, payload, self.nick)
def test_decryption_fail_raises_fr(self):
# Setup
f_data = encrypt_and_sign(b'filedata', self.key)[::-1]
payload = b'testfile.txt' + US_BYTE + base64.b85encode(f_data)
# Test
self.assertFR("Error: Decryption of file data failed.", process_received_file, payload, self.nick)
def test_successful_reception(self):
# Setup
compressed = zlib.compress(b'filedata', level=COMPRESSION_LEVEL)
f_data = encrypt_and_sign(compressed, self.key) + self.key
payload = b'testfile.txt' + US_BYTE + base64.b85encode(f_data)
# Test
self.assertIsNone(process_received_file(payload, self.nick))
self.assertTrue(os.path.isfile(f'{DIR_RX_FILES}Alice/testfile.txt'))