-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathPatternMatcher.java
More file actions
54 lines (45 loc) · 2.18 KB
/
PatternMatcher.java
File metadata and controls
54 lines (45 loc) · 2.18 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
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class PatternMatcher {
// PII Patterns
private static final Pattern EMAIL_PATTERN = Pattern.compile("[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,6}");
private static final Pattern PHONE_PATTERN = Pattern
.compile("\\b\\d{10}\\b|\\b\\d{3}[-.\\s]\\d{3}[-.\\s]\\d{4}\\b");
private static final Pattern CREDIT_CARD_PATTERN = Pattern.compile("\\b(?:\\d{4}[-\\s]?){3}\\d{4}\\b");
// Malicious Patterns (Simple keywords for demonstration)
private static final Pattern MALICIOUS_KEYWORD_PATTERN = Pattern
.compile("(?i)(password\\s*=|eval\\(|exec\\(|rm\\s+-rf|malware|virus|hack)");
public List<String> scanFile(File file) {
List<String> findings = new ArrayList<>();
if (!file.canRead()) {
findings.add("Error: Cannot read file.");
return findings;
}
try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
String line;
int lineNumber = 0;
while ((line = reader.readLine()) != null) {
lineNumber++;
checkPattern(line, lineNumber, EMAIL_PATTERN, "Potential Email", findings);
checkPattern(line, lineNumber, PHONE_PATTERN, "Potential Phone Number", findings);
checkPattern(line, lineNumber, CREDIT_CARD_PATTERN, "Potential Credit Card", findings);
checkPattern(line, lineNumber, MALICIOUS_KEYWORD_PATTERN, "Suspicious Keyword", findings);
}
} catch (IOException e) {
findings.add("Error reading file: " + e.getMessage());
}
return findings;
}
private void checkPattern(String line, int lineNumber, Pattern pattern, String type, List<String> findings) {
Matcher matcher = pattern.matcher(line);
if (matcher.find()) {
findings.add(String.format("[Line %d] %s found: %s", lineNumber, type, matcher.group()));
}
}
}