diff --git a/libs/derive_string.py b/libs/derive_string.py index 0b18952..06ecebd 100644 --- a/libs/derive_string.py +++ b/libs/derive_string.py @@ -1,10 +1,16 @@ #!/usr/bin/env python from hashlib import sha3_256 -from itertools import count +from itertools import count, islice from Crypto.Cipher import ChaCha20 from math import floor, ceil from time import sleep +from os import environ +from sys import stderr + +def debug(*args): + if 'DEBUG' in environ: + print(*args, file=stderr) def chacha_bits(input, bit_count): zerobyte = (0).to_bytes(length=1, byteorder='big') @@ -12,36 +18,37 @@ def chacha_bits(input, bit_count): i = 0 while True: - print('-----------------------------') + debug(f'--- BITS {i} ---') start_bit = bit_count * i start_byte = start_bit // 8 start_padding = start_bit % 8 - print('start_bit', start_bit) - print('start_byte', start_byte) - print('start_padding', start_padding) + debug('start_bit', start_bit) + debug('start_byte', start_byte) + debug('start_padding', start_padding) end_bit = bit_count * i + bit_count end_byte = end_bit // 8 end_padding = 8 - (end_bit % 8) - print('end_bit', end_bit) - print('end_byte', end_byte) - print('end_padding', end_padding) + debug('end_bit', end_bit) + debug('end_byte', end_byte) + debug('end_padding', end_padding) byte_count = (end_byte - start_byte) + 1 - print('byte_count', byte_count) + debug('byte_count', byte_count) cipher.seek(start_byte) - ciphertext = cipher.encrypt(zerobyte*byte_count) - print('ciphertext', bin(int.from_bytes(ciphertext, byteorder='big'))) - shifted_ciphertext = int.from_bytes(ciphertext, byteorder='big') >> end_padding - print('shifted_ciphertext', bin(shifted_ciphertext)) + cipherint = int.from_bytes(cipher.encrypt(zerobyte*byte_count), byteorder='big') + debug('ciphertext', bin(cipherint)) + shifted_cipherint = cipherint >> end_padding + debug('shifted_ciphertext', bin(shifted_cipherint)) bit_mask = int('1'*bit_count, 2) - print('bit_mask', bin(bit_mask)) - masked_ciphertext = shifted_ciphertext & bit_mask - print('masked_ciphertext', bin(masked_ciphertext)) + debug('bit_mask', bin(bit_mask)) + masked_cipherint = shifted_cipherint & bit_mask + debug('masked_ciphertext', bin(masked_cipherint)) - yield masked_ciphertext + debug('') + yield masked_cipherint i += 1 @@ -49,15 +56,15 @@ def chacha_chracter(input, choices): get_bits = chacha_bits(input, len(choices).bit_length()) while True: - choice = next(get_bits) - if choice < len(choices): - yield choices[choice] + key = next(get_bits) + if key < len(choices): + yield choices[key] def derive_string(input, length, choices): get_character = chacha_chracter(input, choices) - return ''.join(next(get_character) for i in range(length)) + return bytes(islice(get_character, length)) print( - derive_string(b'12345', length=100, choices='abcdefghijklmnopqrstuvwxyz0123456789') + derive_string(b'12344', length=100, choices=b'abcdefghijklmnopqrstuvwxyz0123456789') )