# -*- coding: utf-8 -*-

import hashlib
import json
import uuid
import struct
import sys
from collections import defaultdict
from Crypto.PublicKey import RSA
from Crypto.Cipher import PKCS1_OAEP
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from zipfile import ZipFile
from os import path

def _unpad(text, k = 16):
    nl = len(text)
    val = int(text[-1])
    if val > k:
        raise ValueError('Input is not padded or padding is corrupt')
    if not all([x==val for x in text[nl-val:nl]]):
        raise ValueError('Input is not padded or padding is corrupt')
    l = nl - val
    return text[:l]

def decrypt_mobile_private_key(recovery_password, user_id, encrypted_key):
    wrap_key = hashlib.pbkdf2_hmac("sha1", recovery_password, user_id, 10000, 32)
    iv = bytes(chr(0) * 16, 'utf-8')
    cipher = AES.new(wrap_key, AES.MODE_CBC, iv)
    prv_key = _unpad(cipher.decrypt(encrypted_key))
    return prv_key

passphrase_file = sys.argv[1]
mobile_key_path = sys.argv[2]
mobile_key_pass = sys.argv[3] if len(sys.argv) > 3 else None

with open(passphrase_file) as file:
    obj = json.loads(file.read())
    userId = obj["userId"]
    encryptedPassphrase = obj["encryptedKey"]

with open(mobile_key_path, 'r') as _file:
    mobile_key_pem = _file.read()
    mobile_key = RSA.importKey(mobile_key_pem, passphrase=mobile_key_pass)
    mobile_cipher = PKCS1_OAEP.new(mobile_key, SHA256)

    passphrase = mobile_cipher.decrypt(bytes.fromhex(encryptedPassphrase))
    print('Passphsrae: ' + passphrase.decode("utf-8"))
