#!/usr/bin/env python3

import argparse

arg_parser = argparse.ArgumentParser(
    description="BitBot log decrypting utility")

arg_parser.add_argument("key",
    help="Location of private key for decrypting given log file")
arg_parser.add_argument("log", help="Location of the log file to decrypt")

args = arg_parser.parse_args()

import base64
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.asymmetric import padding

def a_decrypt(key, data):
    out = key.decrypt(base64.b64decode(data), padding.OAEP(
        mgf=padding.MGF1(algorithm=hashes.SHA256()),
        algorithm=hashes.SHA256(), label=None))
    return out.decode("utf8")

with open(args.key, "rb") as key_file:
    key_content = key_file.read()
key = serialization.load_pem_private_key(
    key_content, password=None, backend=default_backend())

with open(args.log) as log_file:
    lines = log_file.read().split("\n")
lines = filter(None, lines)

for line in lines:
    if line[0] == "\x02":
        line = a_decrypt(key, line[1:])
    print(line)