File size: 7,810 Bytes
97a064a
 
 
e340e25
97a064a
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
import random
import string
import torch

def txt_to_list(filename):
    with open(filename, 'r') as file:
        lines = file.readlines()
    # Strip whitespace and return
    return [line.strip() for line in lines]
    
commonpasswords_list = txt_to_list('10-million-password-list-top-1000000.txt')
englishwords_list = txt_to_list('words.txt')

#Remove any single alphabet letter
commonpasswords_list = [item for item in commonpasswords_list if not (isinstance(item, str) and len(item) == 1 and item.isalpha())]
englishwords_list = [item for item in englishwords_list if not (isinstance(item, str) and len(item) == 1 and item.isalpha())]


#Remove '', which would cause error
englishwords_list.remove('')
#Double check whether it works
any(elem in commonpasswords_list for elem in list(string.ascii_lowercase))
any(elem in englishwords_list for elem in list(string.ascii_lowercase))

topwords_list = txt_to_list('top-1000-nouns.txt')
#Remove any single alphabet letter

topwords_list = [item for item in topwords_list if not (isinstance(item, str) and len(item) == 1 and item.isalpha())]


#Remove '', which would cause error
#Double check whether it works
any(elem in topwords_list for elem in list(string.ascii_lowercase))
topwords_list[0] = 'time'


common_passwords = commonpasswords_list
dictionary_words = englishwords_list

def generate_password(length=12, use_uppercase=True, use_lowercase=True, 
                       use_numbers=True, use_symbols=True, dictionary = True):
    # Define the character sets
    uppercase = string.ascii_uppercase
    lowercase = string.ascii_lowercase
    numbers = string.digits
    symbols = "!@#$%^&*()-_+=[]{}|:;<>,.?/"
    
    # Build the character pool based on the user's requirements
    character_pool = ""
    if use_uppercase:
        character_pool += uppercase
    if use_lowercase:
        character_pool += lowercase
    if use_numbers:
        character_pool += numbers
    if use_symbols:
        character_pool += symbols

    # Check if character pool is empty
    if not character_pool:
        raise ValueError("No character sets selected!")

    # Generate the password
    while True:
        
        password = ''.join(random.choice(character_pool) for _ in range(length))
        
        # Check if password contains any common English word
        if not any(word in password.lower() for word in common_passwords):
            if dictionary:
                if not any(word in password.lower() for word in dictionary_words):
                    return password
                    break
            return password
            break
    
    
# Load model directly
from transformers import AutoTokenizer, AutoModelForSequenceClassification

tokenizer = AutoTokenizer.from_pretrained("DunnBC22/codebert-base-Password_Strength_Classifier")
model = AutoModelForSequenceClassification.from_pretrained("DunnBC22/codebert-base-Password_Strength_Classifier")



# Put the model in evaluation mode
#The model classifies passwords as one of the following:0.Weak  1.Medium  2.Strong

model.eval()

# Input the password you generate, you could also manually input
text = generate_password(12)
#text = input()


# Tokenize input text
inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True, max_length=512)

# Get logits
with torch.no_grad():
    logits = model(**inputs).logits

# Get predictions
predictions = torch.argmax(logits, dim=1)


def strength_indicator(value):
    # Define a mapping of index to label
    index_to_label = {
        0: "Weak",
        1: "Medium",
        2: "Strong"
    }
    
    # Check if the input value is within the valid range
    if value not in index_to_label:
        raise ValueError("Input should be an integer ranging from 0 to 2.")
    
    # Return the corresponding label
    return index_to_label[value]


strength_indicator(predictions.item())


##This is just a python function and no user interface

def AssessYourPassword(manual=True):
    model.eval()

# Input the password you generate, you could also manually input
    if manual:
        text = input()
    else:
        print('Please input the length of your password:')
        n = input()
        text = generate_password(int(n))
    


# Tokenize input text
    inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True, max_length=512)

# Get logits
    with torch.no_grad():
        logits = model(**inputs).logits

# Get predictions
    predictions = torch.argmax(logits, dim=1)
    strength = strength_indicator(predictions.item())
    if not manual:
        print(f'This is the generated password: {text}')    
    return print(f'Password Strength: {strength}')






import gradio as gr
import random
import string
import torch

model.eval()


def generate_password(length=12, use_uppercase=True, use_lowercase=True,
                      use_numbers=True, use_symbols=True, dictionary=True, easy_mode=False):
    if easy_mode:
        numbers = "1234567890"
        special_chars = "!@#$%^&*"
        chosen_words = [random.choice(topwords_list) for _ in range(2)]
        chosen_words = [word.capitalize() if random.choice([True, False]) else word for word in chosen_words]
        chosen_numbers = "".join(random.choice(numbers) for _ in range(3))
        chosen_special_char = random.choice(special_chars)
        components = chosen_words + [chosen_numbers, chosen_special_char]
        random.shuffle(components)
        password = "".join(components)
    else:
        uppercase = string.ascii_uppercase
        lowercase = string.ascii_lowercase
        numbers = string.digits
        symbols = "!@#$%^&*()-_+=[]{}|:;<>,.?/"
        character_pool = ""
        if use_uppercase:
            character_pool += uppercase
        if use_lowercase:
            character_pool += lowercase
        if use_numbers:
            character_pool += numbers
        if use_symbols:
            character_pool += symbols
        if not character_pool:
            raise ValueError("No character sets selected!")
        password = ''.join(random.choice(character_pool) for _ in range(length))
    return password

def AssessYourPassword_UI_v2(option, length, use_uppercase, use_lowercase, 
                             use_numbers, use_symbols, dictionary_allowed, text_input):
    model.eval()
    
    if option == "Manual":
        text = text_input
    elif option == "Easy Mode":
        text = generate_password(easy_mode=True)
    else:
        text = generate_password(length, use_uppercase, use_lowercase, 
                                 use_numbers, use_symbols, not dictionary_allowed)

    inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True, max_length=512)
    with torch.no_grad():
        logits = model(**inputs).logits
    predictions = torch.argmax(logits, dim=1)
    strength = strength_indicator(predictions.item())

    if option == "Manual":
        output_password = "You provided: " + text
    else:
        output_password = "Generated: " + text
    
    return output_password, f'Password Strength: {strength}'

iface_v2 = gr.Interface(
    fn=AssessYourPassword_UI_v2,
    inputs=[
        gr.Radio(["Manual", "Generated", "Easy Mode"], label="Password Input Method"),
        gr.Slider(minimum=6, maximum=24, default=12, step=1, label="Password Length"),
        gr.Checkbox(label="Use Uppercase Letters", default=True),
        gr.Checkbox(label="Use Lowercase Letters", default=True),
        gr.Checkbox(label="Use Numbers", default=True),
        gr.Checkbox(label="Use Symbols", default=True),
        gr.Checkbox(label="Allow Dictionary Words", default=False),
        gr.Textbox(default="Type password or length here", label="Input")
    ],
    outputs=[
        "text",
        "text"
    ]
)

iface_v2.launch(share=True, debug=True)