-
Notifications
You must be signed in to change notification settings - Fork 14
/
GeneratePasswordViewModel.java
89 lines (68 loc) 路 2.77 KB
/
GeneratePasswordViewModel.java
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
package com.gero.newpass.viewmodel;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;
import java.security.SecureRandom;
public class GeneratePasswordViewModel extends ViewModel {
private final MutableLiveData<String> passwordLiveData = new MutableLiveData<>();
private final MutableLiveData<Boolean> uppercaseStateLiveData = new MutableLiveData<>();
private final MutableLiveData<Boolean> numberStateLiveData = new MutableLiveData<>();
private final MutableLiveData<Boolean> specialStateLiveData = new MutableLiveData<>();
private boolean uppercase = true;
private boolean number = true;
private boolean special = false;
private int length = 14;
public GeneratePasswordViewModel() {
generatePassword();
uppercaseStateLiveData.setValue(uppercase);
numberStateLiveData.setValue(number);
specialStateLiveData.setValue(special);
}
public LiveData<String> getPasswordLiveData() { return passwordLiveData; }
public LiveData<Boolean> getUppercaseStateLiveData() {
return uppercaseStateLiveData;
}
public LiveData<Boolean> getNumberStateLiveData() {
return numberStateLiveData;
}
public LiveData<Boolean> getSpecialStateLiveData() {
return specialStateLiveData;
}
public void generatePassword() {
String password = generateRandomPassword(length, uppercase, number, special);
passwordLiveData.setValue(password);
}
public void setPasswordLength(int length) {
this.length = length;
generatePassword();
}
public void toggleUppercase() {
uppercase = !uppercase;
uppercaseStateLiveData.setValue(uppercase);
generatePassword();
}
public void toggleNumber() {
number = !number;
numberStateLiveData.setValue(number);
generatePassword();
}
public void toggleSpecial() {
special = !special;
specialStateLiveData.setValue(special);
generatePassword();
}
private String generateRandomPassword(int length, boolean uppercase, boolean number, boolean special) {
String charSet1 = (uppercase) ? "ABCDEFGHIJKLMNOPQRSTUVWXYZ" : "";
String charSet2 = "abcdefghijklmnopqrstuvwxyz";
String charSet3 = (number) ? "0123456789" : "";
String charSet4 = (special) ? "?#%{}@!$()[]" : "";
String characters = charSet1 + charSet2 + charSet3 + charSet4;
SecureRandom random = new SecureRandom();
StringBuilder sb = new StringBuilder(length);
for (int i = 0; i < length; i++) {
int randomIndex = random.nextInt(characters.length());
sb.append(characters.charAt(randomIndex));
}
return sb.toString();
}
}