-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathFileToPassword.py
More file actions
187 lines (144 loc) · 5.47 KB
/
Copy pathFileToPassword.py
File metadata and controls
187 lines (144 loc) · 5.47 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
import os
import hashlib
import string
import getpass
import time
import subprocess
import glob
import argparse
import platform
from cryptography.hazmat.primitives.kdf.pbkdf2 import PBKDF2HMAC
from cryptography.hazmat.primitives import hashes
default_length = 20
def parse_arguments():
global ARGS
parser = argparse.ArgumentParser()
parser.add_argument("-L", "--length", type=int, default=default_length, help="Length of the generated password.")
parser.add_argument("-H", "--hidden", action="store_true", help="Hide final generated password.")
ARGS = parser.parse_args()
if ARGS.length < 4:
parser.error('Password length must be at least 4')
if ARGS.hidden:
print(f"Output hidden")
if ARGS.length != default_length:
print(f"Output length: {ARGS.length}")
print()
parse_arguments()
def hash_file(file_path):
file_hash = hashlib.sha256()
with open(file_path, "rb") as f:
chunk = f.read(64 * 1024)
while chunk:
file_hash.update(chunk)
chunk = f.read(64 * 1024)
return file_hash.digest()
def get_index(size, byte_stream):
byte_count = max(1, ((size - 1).bit_length() + 7) // 8)
limit = 1 << (byte_count * 8)
limit -= limit % size
while True:
value = 0
for _ in range(byte_count):
value = (value << 8) | next(byte_stream)
if value < limit:
return value % size
def get_bytes(key):
counter = 0
while True:
for byte in hashlib.sha256(key + counter.to_bytes(8, "big")).digest():
yield byte
counter += 1
def generate_password(file_hash, password_key, length=20):
if not password_key:
raise ValueError("Password can't be empty.")
if length < 4:
raise ValueError("Password length must be at least 4.")
uppercase_characters = string.ascii_uppercase
lowercase_characters = string.ascii_lowercase
number_characters = string.digits
special_characters = "!@#$%^&*()?"
valid_characters = uppercase_characters + lowercase_characters + number_characters + special_characters
kdf = PBKDF2HMAC(
algorithm=hashes.SHA256(),
length=64,
salt=file_hash,
iterations=100000
)
key = kdf.derive(password_key.encode())
byte_stream = get_bytes(key)
required_characters = [
uppercase_characters[get_index(len(uppercase_characters), byte_stream)],
lowercase_characters[get_index(len(lowercase_characters), byte_stream)],
number_characters[get_index(len(number_characters), byte_stream)],
special_characters[get_index(len(special_characters), byte_stream)]
]
remaining_characters = [
valid_characters[get_index(len(valid_characters), byte_stream)]
for _ in range(4, length)
]
password_characters = required_characters + remaining_characters
for i in range(len(password_characters) - 1, 0, -1):
swap_index = get_index(i + 1, byte_stream)
password_characters[i], password_characters[swap_index] = password_characters[swap_index], password_characters[i]
return "".join(password_characters)
def get_file():
script_dir = os.path.dirname(os.path.abspath(__file__))
while True:
file = input("Enter file name: ")
paths = glob.glob(f"{script_dir}/{file}.*", recursive=True)
result = None
if len(paths) > 1:
print(f"'{file}' is ambiguous between the following paths:")
for path in paths:
print(f" - {path}")
print("Please specify the file name more clearly.\n")
continue
elif len(paths) == 1:
result = paths[0]
elif os.path.isfile(os.path.join(script_dir, file)):
result = os.path.join(script_dir, file)
if result is None:
print(f"'{file}' was not found. Try again.\n")
continue
return result
def get_password():
while True:
password = getpass.getpass("[Input Hidden] Enter a password key: ")
if password == "":
print("Password can't be empty. Try again.\n")
continue
password_confirm = getpass.getpass("[Input Hidden] Confirm password key: ")
if password == password_confirm:
return password
elif password_confirm == "":
print("Confirmation skipped")
return password
else:
print("Passwords don't match. Try again.\n")
def mask_password(password):
return "*" * len(password)
def copy_to_clipboard(password):
commands = {
"Windows": [["clip"]],
"Darwin": [["pbcopy"]]
}.get(platform.system(), [["wl-copy"], ["xclip", "-selection", "clipboard"], ["xsel", "--clipboard", "--input"]])
for command in commands:
try:
subprocess.run(command, text=True, input=password, check=True)
print("\nPassword copied!")
break
except (OSError, subprocess.CalledProcessError):
continue
else:
print("\nCould not copy to clipboard.")
file_path = get_file()
password_key = get_password()
hashed_file = hash_file(file_path)
generated_password = generate_password(hashed_file, password_key, length=ARGS.length)
if ARGS.hidden:
print(f"\n\nGenerated Password: {mask_password(generated_password)}")
else:
print(f"\n\nGenerated Password: {generated_password}")
input("Press enter to copy and close...")
copy_to_clipboard(generated_password)
time.sleep(0.5)