#!/usr/bin/env python3
#
#  Check if a key encrypted by new-credentials can be decrypted with
#  a given password. Designed as a test tool
#
#  Usage: 
#    check-key-password <key file> <password>
#
#        key-file: a .enc file created by new-credentials.
#        password: The password handed to new-credentials
#
#  Bugs:
#    The password is available on the command line, opening for attacks
#    based on process information in /sys etc.
#
#  Copyright (c) 2020-2021 Alec Leamas


# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.



import base64
import sys

from cryptography.fernet import Fernet, InvalidToken
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import hashes
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.exceptions import InvalidSignature


def cipherFernet(password):
    key = PBKDF2HMAC(algorithm=hashes.SHA256(), length=32, salt=b'abcd',
                     iterations=1000,
                     backend=default_backend()).derive(password)
    return Fernet(base64.urlsafe_b64encode(key))


def decrypt1(ciphertext, password):
    return cipherFernet(password).decrypt(ciphertext)

def main():
    """Indeed: main function."""
    if  len(sys.argv) != 3:
        print("Usage: check-key-password <key file> <password>")
        sys.exit(2)
    with open(sys.argv[1], 'r') as f:
        encrypted = f.read()
    try: 
        decrypt1(encrypted.encode(), sys.argv[2].encode())
    except (InvalidToken, InvalidSignature):
        print("decryption failed")
        sys.exit(1)
    print("decryption OK")

if __name__ == '__main__':
    main()
