#!env python3
import base64
import sys

from Crypto.Cipher import AES


def main():
    if len(sys.argv) != 2:
        print('Error: command parameters missed.')
        print('Usage:')
        print('{} ENCRYPTED_PASSWORD'.format(sys.argv[0]))
        print('    ENCRYPTED_PASSWORD  encrypted password in base64 format, read from database.')
        return

    enc_password = sys.argv[1]

    # base64 decode
    enc_bin = base64.b64decode(enc_password.encode(), validate=True)
    if len(enc_bin) <= 16:
        print('Error: invalid encrypted password, bad length.')
        return

    # prepare key and iv
    key = [0xd6, 0xb6, 0x6e, 0x3b, 0x41, 0xc4, 0x33, 0x13, 0xaa, 0x61, 0xc9, 0x47, 0x82, 0xfc, 0x84, 0x50,
           0x85, 0x53, 0x3a, 0x01, 0x97, 0x2d, 0xca, 0xba, 0x87, 0xbc, 0x27, 0x20, 0x29, 0xde, 0x87, 0x67,
           ]
    iv = [0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00]
    aes = AES.new(bytearray(key), AES.MODE_CBC, bytearray(iv))

    # do decrypt
    try:
        dec_bin = aes.decrypt(enc_bin)
    except Exception as e:
        print('Error: got exception when decrypt.')
        return

    # check #pkcs7 padding
    length = len(dec_bin)
    pad = int(dec_bin[length-1])
    if pad > 16:
        print('Error: can not decrypt, invalid encrypted data.')
        return
    for i in range(pad):
        if dec_bin[length-i - 1] != pad:
            print('Error: can not decrypt, invalid encrypted data.')
            return

    # remove padding
    dec_bin = dec_bin[:length-pad]

    # remove random data
    dec_password = dec_bin[16:].decode()

    # output decrypted result
    print(dec_password)


if __name__ == '__main__':
    main()
