def _raw_image_data_to_encrypted_data(self, raw_image_file_data): logging.info('Raw data: %s.' % raw_image_file_data[:10]) base64_image_file_data = base64.b64encode(raw_image_file_data) logging.info('Cipher encoding data. Len: %d.' % len(base64_image_file_data)) encrypted_data = self.cipher.encode(base64_image_file_data) # Compute integrity check on the encrypted data, which should be base64 # (in the case of V8Cipher, this includes the jsonified data). if self.cipher.__class__.__name__ == 'V8Cipher': _to_hash = \ encrypted_data['iv'] + \ encrypted_data['salt'] + \ encrypted_data['ct'] logging.info('Integrity hash input: %s...' % _to_hash[:48]) integrity_check_value = sha256hash(_to_hash) logging.info('Integrity hash value: %s.' % integrity_check_value) else: integrity_check_value = sha256hash(encrypted_data) logging.info('Cipher finished. Combined len: %d.' % len(_to_hash)) # For V8Cipher, we have to tease apart the JSON in order to set the # encrypted_data string correctly. if self.cipher.__class__.__name__ == 'V8Cipher': encrypted_data = \ integrity_check_value + \ encrypted_data['iv'] + \ encrypted_data['salt'] + \ encrypted_data['ct'] logging.info('Returning encrypted data.') return encrypted_data
def appendblock(self, new_block): # insert optional verification new_block_hash = util.sha256hash(str(new_block).encode('utf-8')) self.BLOCKS[new_block_hash] = new_block self.TAIL_BLOCK = new_block_hash if 'msg_id' in new_block and 'vote' in new_block: self.updatevotes(new_block['msg_id'], new_block['vote'])
def verifysignature(self, prev_hash, salt): '''We can make this crypto as easy or as difficult as we want is valid if last digit of hash is less or equal to 3 (increase this to make faster) ''' result = util.sha256hash((str(prev_hash) + salt).encode('utf-8')) if result % 10 <= 3: return True else: return False
def main(argv): # Parse arguments from the user. parser = argparse.ArgumentParser( prog='cryptogram', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument( '-q', '--quality', type=int, default=95, help='Quality to save encrypted image in range (0,95].') parser.add_argument('-p', '--password', type=str, default=None, required=True, help='Password to encrypt image with.') parser.add_argument('-s', '--symbol_shape', type=str, default='two_square', help='SymbolShape to use.') parser.add_argument('-i', '--image', type=str, default=None, help='Path to input image.', required=True) parser.add_argument('-e', '--encrypt', type=str, default=None, help='Encrypted image output filename.') parser.add_argument('-d', '--decrypt', type=str, default=None, help='Decrypted image output filename.') parser.add_argument( '-m', '--max_output_dimension', type=int, default=2048, help='Maximum image dimension (applies to height and width).') parser.add_argument('-w', '--fixed_width', type=int, default=None, help='Exact width specification.') FLAGS = parser.parse_args() symbol_shape = _AVAILABLE_SHAPES[FLAGS.symbol_shape] quality = FLAGS.quality cipher = Cipher(FLAGS.password, command_line=True) if FLAGS.image and FLAGS.encrypt: logging.info('Image to encrypt: %s.' % FLAGS.image) # Determine file size. image_buffer = cStringIO.StringIO() with open(FLAGS.image, 'rb') as fh: image_buffer.write(fh.read()) length = fh.tell() logging.info('%s has size %d.' % (FLAGS.image, length)) # Reorient the image, if necessary as determined by auto_orient. reoriented_image_buffer = cStringIO.StringIO() orient = Orientation.Orientation(FLAGS.image) if orient.auto_orient(reoriented_image_buffer): logging.info( 'Reoriented the image so reassigning the image_buffer.') del image_buffer image_buffer = reoriented_image_buffer # Update codec based on wh_ratio from given image. image_buffer.seek(0) _image = Image.open(image_buffer) _width, _height = _image.size logging.info('Width: %d. Height: %d.' % (_width, _height)) wh_ratio = _width / float(_height) logging.info('Original image wh_ratio: %.2f.' % wh_ratio) codec = Codec(symbol_shape, wh_ratio, Base64MessageSymbolCoder(), Base64SymbolSignalCoder(), fixed_width=FLAGS.fixed_width) crypto = Encrypt(image_buffer, codec, cipher) encrypted_data = crypto.upload_encrypt(FLAGS.max_output_dimension) logging.info('Encrypted data length: %d.' % len(encrypted_data)) # TODO(tierney): Set somewhere more appropriately. header = 'aesthete' codec.set_direction('encode') codec.set_data(header + encrypted_data) codec.start() while True: im = codec.get_result() if im: break logging.info('Progress: %.2f%%.' % \ (100. * codec.get_percent_complete())) time.sleep(0.5) logging.info('Saving encrypted jpeg with quality %d.' % quality) with open(FLAGS.encrypt, 'w') as out_file: im.save(out_file, 'JPEG', quality=quality) with open(FLAGS.encrypt) as fh: fh.read() logging.info('Encrypted image size: %d bytes.' % fh.tell()) logging.info('Encrypted image data expansion %.2f.' % \ (fh.tell() / float(length))) del codec if not FLAGS.decrypt: return if FLAGS.image and FLAGS.encrypt and FLAGS.decrypt: read_back_image = Image.open(FLAGS.encrypt) elif FLAGS.image and not FLAGS.encrypt and FLAGS.decrypt: logging.info('Reading message we did not encrypt.') with open(FLAGS.image, 'rb') as fh: fh.read() logging.info('Encrypted image filesize: %d.' % fh.tell()) read_back_image = Image.open(FLAGS.image) _width, _height = read_back_image.size wh_ratio = _width / float(_height) codec = Codec(symbol_shape, wh_ratio, Base64MessageSymbolCoder(), Base64SymbolSignalCoder()) codec.set_direction('decode') codec.set_data(read_back_image) codec.start() while True: binary_decoding = codec.get_result() if binary_decoding: break logging.info('Progress: %.2f%%.' % \ (100. * codec.get_percent_complete())) time.sleep(0.5) if FLAGS.encrypt and FLAGS.decrypt: logging.info('Byte for byte diff: %d.' % \ byte_for_byte_compare(encrypted_data, binary_decoding)) # Required "un"-filtering to base64 data. def _base64_pad(s): mod = len(s) % 4 if mod == 0: return s return s + (4 - mod) * '=' # padded_decoding = _base64_pad(binary_decoding) _integrity_check = binary_decoding[0:64] _to_check = binary_decoding[64:] logging.info('Input to integrity check: %s...' % _to_check[:48]) integrity_check_value = sha256hash(_to_check) logging.info('Extracted integrity check: %s.' % _integrity_check) logging.info('Calculated integrity check: %s.' % integrity_check_value) _iv = binary_decoding[64:86] _salt = binary_decoding[86:97] _ct = binary_decoding[97:] decoded = {'iv': _iv, 'salt': _salt, 'ct': _ct} json_str = JSONEncoder().encode(decoded) if _integrity_check != integrity_check_value: logging.warning('Integrity check mismatch') else: logging.info('Integrity check passed.') decrypted_decoded = cipher.decode(json_str) extracted_data = base64.b64decode(decrypted_decoded) if FLAGS.image and FLAGS.decrypt: with open(FLAGS.decrypt, 'wb') as fh: fh.write(extracted_data) logging.info('Saved decrypted file: %s.' % FLAGS.decrypt)
def main(argv): # Parse arguments from the user. parser = argparse.ArgumentParser( prog='cryptogram', formatter_class=argparse.ArgumentDefaultsHelpFormatter) parser.add_argument('-q', '--quality', type=int, default=95, help='Quality to save encrypted image in range (0,95].') parser.add_argument('-p', '--password', type=str, default=None, required=True, help='Password to encrypt image with.') parser.add_argument('-s', '--symbol_shape', type=str, default='two_square', help='SymbolShape to use.') parser.add_argument('-i', '--image', type=str, default=None, help='Path to input image.', required=True) parser.add_argument('-e', '--encrypt', type=str, default=None, help='Encrypted image output filename.') parser.add_argument('-d', '--decrypt', type=str, default=None, help='Decrypted image output filename.') parser.add_argument('-m', '--max_output_dimension', type=int, default=2048, help='Maximum image dimension (applies to height and width).') parser.add_argument('-w', '--fixed_width', type=int, default=None, help='Exact width specification.') FLAGS = parser.parse_args() symbol_shape = _AVAILABLE_SHAPES[FLAGS.symbol_shape] quality = FLAGS.quality cipher = Cipher(FLAGS.password, command_line=True) if FLAGS.image and FLAGS.encrypt: logging.info('Image to encrypt: %s.' % FLAGS.image) # Determine file size. image_buffer = cStringIO.StringIO() with open(FLAGS.image, 'rb') as fh: image_buffer.write(fh.read()) length = fh.tell() logging.info('%s has size %d.' % (FLAGS.image, length)) # Reorient the image, if necessary as determined by auto_orient. reoriented_image_buffer = cStringIO.StringIO() orient = Orientation.Orientation(FLAGS.image) if orient.auto_orient(reoriented_image_buffer): logging.info('Reoriented the image so reassigning the image_buffer.') del image_buffer image_buffer = reoriented_image_buffer # Update codec based on wh_ratio from given image. image_buffer.seek(0) _image = Image.open(image_buffer) _width, _height = _image.size logging.info('Width: %d. Height: %d.' % (_width, _height)) wh_ratio = _width / float(_height) logging.info('Original image wh_ratio: %.2f.' % wh_ratio) codec = Codec(symbol_shape, wh_ratio, Base64MessageSymbolCoder(), Base64SymbolSignalCoder(), fixed_width = FLAGS.fixed_width) crypto = Encrypt(image_buffer, codec, cipher) encrypted_data = crypto.upload_encrypt(FLAGS.max_output_dimension) logging.info('Encrypted data length: %d.' % len(encrypted_data)) # TODO(tierney): Set somewhere more appropriately. header = 'aesthete' codec.set_direction('encode') codec.set_data(header + encrypted_data) codec.start() while True: im = codec.get_result() if im: break logging.info('Progress: %.2f%%.' % \ (100. * codec.get_percent_complete())) time.sleep(0.5) logging.info('Saving encrypted jpeg with quality %d.' % quality) with open(FLAGS.encrypt, 'w') as out_file: im.save(out_file, 'JPEG', quality=quality) with open(FLAGS.encrypt) as fh: fh.read() logging.info('Encrypted image size: %d bytes.' % fh.tell()) logging.info('Encrypted image data expansion %.2f.' % \ (fh.tell() / float(length))) del codec if not FLAGS.decrypt: return if FLAGS.image and FLAGS.encrypt and FLAGS.decrypt: read_back_image = Image.open(FLAGS.encrypt) elif FLAGS.image and not FLAGS.encrypt and FLAGS.decrypt: logging.info('Reading message we did not encrypt.') with open(FLAGS.image, 'rb') as fh: fh.read() logging.info('Encrypted image filesize: %d.' % fh.tell()) read_back_image = Image.open(FLAGS.image) _width, _height = read_back_image.size wh_ratio = _width / float(_height) codec = Codec(symbol_shape, wh_ratio, Base64MessageSymbolCoder(), Base64SymbolSignalCoder()) codec.set_direction('decode') codec.set_data(read_back_image) codec.start() while True: binary_decoding = codec.get_result() if binary_decoding: break logging.info('Progress: %.2f%%.' % \ (100. * codec.get_percent_complete())) time.sleep(0.5) if FLAGS.encrypt and FLAGS.decrypt: logging.info('Byte for byte diff: %d.' % \ byte_for_byte_compare(encrypted_data, binary_decoding)) # Required "un"-filtering to base64 data. def _base64_pad(s): mod = len(s) % 4 if mod == 0: return s return s + (4 - mod) * '=' # padded_decoding = _base64_pad(binary_decoding) _integrity_check = binary_decoding[0:64] _to_check = binary_decoding[64:] logging.info('Input to integrity check: %s...' % _to_check[:48]) integrity_check_value = sha256hash(_to_check) logging.info('Extracted integrity check: %s.' % _integrity_check) logging.info('Calculated integrity check: %s.' % integrity_check_value) _iv = binary_decoding[64:86] _salt = binary_decoding[86:97] _ct = binary_decoding[97:] decoded = {'iv':_iv, 'salt':_salt, 'ct':_ct} json_str = JSONEncoder().encode(decoded) if _integrity_check != integrity_check_value: logging.warning('Integrity check mismatch') else: logging.info('Integrity check passed.') decrypted_decoded = cipher.decode(json_str) extracted_data = base64.b64decode(decrypted_decoded) if FLAGS.image and FLAGS.decrypt: with open(FLAGS.decrypt, 'wb') as fh: fh.write(extracted_data) logging.info('Saved decrypted file: %s.' % FLAGS.decrypt)