Package Exp
Package Exp
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.net.URI;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
// Static block runs once when the class is loaded to initialize the
encryption key.
static {
try {
secretKey = generateKey(); // Generate a unique key.
System.out.println("SecretKey changes every time a person logs
in: " + secretKey);
} catch (Exception e) {
e.printStackTrace();
}
}
openURL("http://localhost/website/admin_dashboard.php");
} else {
statusLabel.setText("Invalid Credentials."); //
Show invalid credentials message.
statusLabel.setForeground(Color.RED); // Keep
text color red.
}
} else {
statusLabel.setText("Access Denied by Firewall."); //
Show firewall access denial.
statusLabel.setForeground(Color.RED);
}
} catch (Exception ex) {
ex.printStackTrace(); // Log the exception.
statusLabel.setText("Error: " + ex.getMessage()); // Show
error message.
statusLabel.setForeground(Color.RED);
}
}
});
// Main Security class containing logic for authentication and storing data
class Security {
private static String encryptedValidUsername; // Encrypted valid
username.
private static String encryptedValidPassword; // Encrypted valid
password.
// Return true if both username and password match the stored valid
credentials.
return encryptedUsername.equals(encryptedValidUsername) &&
encryptedPassword.equals(encryptedValidPassword);
}
javax.swing.SwingUtilities.invokeLater(Security::createAndShowLoginGUI);
} catch (Exception e) {
e.printStackTrace(); // Log any exceptions that occur.
}
}
}
Purpose Overview:
The program implements a secure login system with the following features:
1. Firewall Class
• Static Attribute:
java
Copy code
private static final String ALLOWED_IP = "192.168.1.1";
java
Copy code
public static boolean isIPAllowed(String ip);
2. Encryption Class
Purpose: Handles AES encryption for credentials, ensuring sensitive data is securely stored.
• Static Attribute:
java
Copy code
private static SecretKey secretKey;
java
Copy code
static {
try {
secretKey = generateKey();
} catch (Exception e) {
e.printStackTrace();
}
}
java
Copy code
private static SecretKey generateKey() throws Exception;
o Takes a string (data) as input, encrypts it using AES, and returns the Base64-
encoded string.
• Association:
o Encryption is associated with Security, as Security relies on Encryption for
credential processing.
3. LoginGUI Class
Purpose: Creates the user interface (UI) for login and handles user interaction.
Main Components:
• UI Construction:
java
Copy code
public void createLoginFrame();
java
Copy code
loginButton.addActionListener(new ActionListener() {...});
java
Copy code
private void openURL(String url);
o Opens a URL (e.g., admin dashboard) in the default browser if login is successful.
Encapsulation:
• UI elements and event-handling logic are encapsulated within the class, maintaining
modularity.
4. Security Class
Attributes:
Main Methods:
• createAndShowLoginGUI:
o Launches the GUI by instantiating LoginGUI.
• authenticate:
java
Copy code
public static boolean authenticate(String username, String password)
throws Exception;
Association:
• Security interacts with both LoginGUI (UI logic) and Encryption (encryption logic).
1. Encapsulation:
o Sensitive operations like encryption, IP filtering, and UI handling are
encapsulated in dedicated classes.
2. Association:
o Security depends on Encryption and LoginGUI, while LoginGUI interacts with
Firewall for IP control.
3. Inheritance:
o Not explicitly present. This is a composition-focused design.
4. Modularity:
o Classes are modular, each handling a distinct responsibility:
Firewall: IP access control.
Encryption: Credential security.
LoginGUI: User interface.
Security: Authentication logic.
1. Setup:
o encrypts the valid credentials (admin, password123) and starts the login
main
GUI.
2. Login Process:
o The user inputs credentials.
o Firewall checks if the IP is allowed.
o Security validates encrypted credentials.
o On success, the program opens an admin dashboard.
3. Security:
o Credentials are securely encrypted using AES.
o Attempts are logged for tracking.
Step 1: Launching the Application
When you run the program, the main method in the Security class is executed.
java
Copy code
public static void main(String[] args) {
try {
String validUsername = "admin";
String validPassword = "password123";
javax.swing.SwingUtilities.invokeLater(Security::createAndShowLoginGUI);
} catch (Exception e) {
e.printStackTrace(); // Log any exceptions.
}
}
When the login window opens, the user will see two text fields: one for the username and one for
the password, along with a "Login" button.
Let's assume the user enters the following data in the fields:
• Username: admin
• Password: password123
After inputting these details, the user clicks the "Login" button.
The ActionListener attached to the login button triggers the following method:
java
Copy code
loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText(); // Get the inputted
username.
String password = new String(passwordField.getPassword()); // Get the
inputted password.
try {
// Check if the IP is allowed by the firewall.
if (Firewall.isIPAllowed("192.168.1.1")) {
// Authenticate the username and password.
if (Security.authenticate(username, password)) {
statusLabel.setText("Login Successful!"); // Display
success message.
statusLabel.setForeground(Color.GREEN); // Change text
color to green.
Now that the IP is allowed, the program checks the user's credentials by calling
Security.authenticate(username, password).
java
Copy code
public static boolean authenticate(String username, String password) throws
Exception {
// Encrypt the inputted username and password.
String encryptedUsername = Encryption.encrypt(username);
String encryptedPassword = Encryption.encrypt(password);
// Return true if both username and password match the encrypted valid
credentials.
return encryptedUsername.equals(encryptedValidUsername) &&
encryptedPassword.equals(encryptedValidPassword);
}
• Condition: encryptedUsername.equals(encryptedValidUsername)
o The inputted username ("admin") is encrypted using the Encryption.encrypt()
method, and the encrypted value is compared with encryptedValidUsername
(the encrypted version of "admin").
o Since the username matches, this condition is true.
• Condition: encryptedPassword.equals(encryptedValidPassword)
o Similarly, the inputted password ("password123") is encrypted and compared
with encryptedValidPassword (the encrypted version of "password123").
o Since the password also matches, this condition is true.
o If both conditions are true, the method returns true, meaning the user is
authenticated successfully.
Step 5: Successful Login
Back in the ActionListener, since the credentials are valid, the program displays:
java
Copy code
statusLabel.setText("Login Successful!"); // Login success message.
statusLabel.setForeground(Color.GREEN); // Change text color to green.
If the user enters incorrect credentials (e.g., username: wronguser, password: wrongpass), the
program will fail at the authentication stage:
java
Copy code
statusLabel.setText("Invalid Credentials.");
statusLabel.setForeground(Color.RED); // Error message in red.
If any unexpected errors occur, such as a failed encryption or other issues, they will be caught in
the catch block:
java
Copy code
catch (Exception ex) {
ex.printStackTrace(); // Log the exception.
statusLabel.setText("Error: " + ex.getMessage()); // Display error
message.
statusLabel.setForeground(Color.RED); // Show error in red.
}
• The error will be printed to the console, and the user will see an error message in red
text.
Summary of Conditions and Flow
1. Program Launch: When you run the program, the following happens:
o The program starts and initializes the login GUI.
o The encrypted valid credentials (admin and password123) are already set in the
code as the correct login details.
• Username field: A text box where you will enter the username.
• Password field: A password box where you will enter the password.
• Login Button: A button to submit your login credentials.
Here is a simplified version of the user interface that will be shown to you:
markdown
Copy code
----------------------------------------------
| Login System with Encryption |
----------------------------------------------
| Username: [_______________] |
| Password: [_______________] |
| |
| [Login Button] |
----------------------------------------------
Let's say you enter the correct credentials: admin for the username and password123 for the
password.
1. Username: admin
2. Password: password123
• The program will take the inputted username (admin) and password (password123).
• The program will then encrypt both the username and password using the
Encryption.encrypt() method.
• The program compares the encrypted values of the username and password with the
stored encrypted valid credentials.
• Since the credentials match, it proceeds to display a successful login message.
Copy code
Login Successful!
• URL Opening: The program will then attempt to open the URL
(http://localhost/website/admin_dashboard.php), which you might not actually
see unless you have a real server running on your machine. But if the system supports it,
it will open a browser window.
1. Username: wronguser
2. Password: wrongpass
• The program will take the inputted username (wronguser) and password (wrongpass).
• The program will encrypt both of these credentials and compare the encrypted values
with the stored valid encrypted credentials (admin and password123).
• Since they do not match, the program will display an "Invalid Credentials" message.
Copy code
Invalid Credentials.
• No URL Opening: Since the credentials are invalid, the URL will not open.
You can keep trying different usernames and passwords, such as:
1. Username: admin
2. Password: wrongpassword
Copy code
Invalid Credentials.
If the firewall check fails, meaning the IP is not allowed (for example, changing the IP to
something like 192.168.2.1), the program will show an access denied message.
• Firewall Denial Message: The program will display this red message:
csharp
Copy code
Access Denied by Firewall.
• No Login Attempt: It won't even try to authenticate the credentials if the firewall check
fails.
Copy code
Login Successful!
Copy code
Invalid Credentials.
csharp
Copy code
Access Denied by Firewall.
When you run the program and try to log in, the console will print out messages like these:
On successful login:
vbnet
Copy code
Encrypted Username: {Encrypted String for "admin"}
Encrypted Password: {Encrypted String for "password123"}
Login Successful!
Stored Credentials:
Username: {Encrypted String for "admin"}, Password: {Encrypted String for
"password123"}
On invalid credentials:
vbnet
Copy code
Invalid Credentials.
Stored Credentials:
Username: {Encrypted String for "wronguser"}, Password: {Encrypted String for
"wrongpass"}
1. javax.crypto.Cipher
This is a class in the Java Cryptography Extension (JCE) API. It is used to perform encryption
and decryption operations on data. In your program, it is used for:
• Encryption: The Cipher class provides methods to encrypt plaintext into ciphertext
using a specific algorithm (e.g., AES).
• Decryption: It can also decrypt the ciphertext back into plaintext if the same algorithm
and key are used.
In your code:
2. javax.crypto.KeyGenerator
This class is used to generate encryption keys for cryptographic operations. In your program, it
generates an AES key for encrypting and decrypting the username and password.
• Key Generation: The KeyGenerator.getInstance("AES") creates a key generator for
the AES encryption algorithm.
• The keyGen.init(256) method initializes the generator to produce 256-bit keys.
• The keyGen.generateKey() creates the actual secret key used in encryption.
3. javax.crypto.SecretKey
This interface represents a secret key used in symmetric encryption algorithms, such as AES.
The secret key is the shared key used for both encryption and decryption in symmetric
cryptography.
In your program:
These libraries are used for building graphical user interfaces (GUIs) in Java. They provide
classes for creating windows, buttons, text fields, labels, and other UI components. In your
program, the following Swing components are used:
• JFrame: Represents the main window of the application. In your code, the frame object
represents the login window where users enter their credentials.
• JPanel: A container for organizing components. The backgroundPanel and loginPanel
are both instances of JPanel used to organize the layout and components in the login
window.
• JLabel: A component for displaying text. In your code, userLabel, passLabel, and
statusLabel are used to display text like "Username", "Password", and the status of the
login (e.g., success or failure).
• JTextField: A single-line text input field. The usernameField allows the user to input
their username.
• JPasswordField: A specialized text field for password input, where the characters are
hidden (shown as dots or stars). The passwordField allows the user to input their
password securely.
• JButton: A button that can be clicked by the user. The loginButton is used to submit
the login form.
• GridLayout and GridBagLayout: These are layout managers that control the positioning
and arrangement of the components in the GUI.
The java.awt package provides classes for user interface components and event handling. It is
often used alongside Swing, as seen in your program.
• BorderLayout: A layout manager that arranges components into five areas: north, south,
east, west, and center. In your program, it is used for organizing the main window
(frame).
• GridBagLayout: A flexible layout manager that aligns components using a grid. It is
used to place the loginPanel within the backgroundPanel.
• Color: A class used to define and manipulate colors. In your program, the background
color of panels is set using new Color(220, 240, 255), which creates a light blue
color.
• Font: A class that defines fonts. In your program, it's used to set the font for the
statusLabel.
• SwingConstants: A class that contains constants for various swing components.
SwingConstants.RIGHT is used to align text labels to the right.
6. java.net.URI
This class represents a Uniform Resource Identifier (URI) and is used to work with URLs (web
addresses).
• URI uri = new URI(url): This creates a URI object from the provided URL string (in
this case, a URL to the admin dashboard).
• Desktop.getDesktop().browse(uri): This opens the URI in the default web browser
(if supported by the operating system).
These are classes from the java.util package that are used to store and manage collections of
objects.
8. java.util.Base64
This is a utility class for encoding and decoding data in Base64 format. Base64 encoding is often
used to convert binary data into text format, which is useful for storing or transmitting data.
This package contains classes used for event handling (e.g., mouse clicks, button presses, etc.).
• ActionListener: An interface that listens for actions on components like buttons. In
your program, the ActionListener for the loginButton listens for a click event and
executes the login logic.
1. Encapsulation
Definition:
Encapsulation is the bundling of data and methods that operate on that data into a single unit (a
class). It also restricts access to internal implementation details using access modifiers like
private.
Encapsulation in Firewall:
• Data Encapsulation:
The ALLOWED_IP field is private, and the isIPAllowed() method provides controlled
access.
o This ensures that only valid IPs can be compared, protecting the data integrity.
java
Copy code
private static final String ALLOWED_IP = "192.168.1.1"; // Encapsulated data
• Behavior Encapsulation:
The generateKey() and encrypt() methods hide the internal details of key generation
and encryption. Users of this class only need to call encrypt().
java
Copy code
private static SecretKey secretKey; // Encapsulated secret key
Encapsulation in Security:
• Data Encapsulation:
Sensitive information such as encryptedValidUsername and
encryptedValidPassword is private. Only the authenticate() method can access
these fields.
java
Copy code
private static String encryptedValidUsername; // Sensitive data hidden
private static String encryptedValidPassword;
2. Coupling
Definition:
Coupling refers to the degree of dependency between classes or components.
Types of Coupling:
Loose Coupling:
java
Copy code
if (Security.authenticate(username, password)) { // Loose coupling
statusLabel.setText("Login Successful!");
}
Tight Coupling:
java
Copy code
String encryptedUsername = Encryption.encrypt(username); // Tight coupling
String encryptedPassword = Encryption.encrypt(password);
3. Aggregation
Definition:
Aggregation is a "has-a" relationship where one class contains references to objects of another
class. The contained objects can exist independently.
• The LoginGUI class contains objects like JFrame, JPanel, and JButton. These
components can exist independently of the LoginGUI class.
java
Copy code
JFrame frame = new JFrame("Login System with Encryption"); // Aggregation
JPanel backgroundPanel = new JPanel(); // Aggregation
JButton loginButton = new JButton("Login"); // Aggregation
java
Copy code
private static final List<String[]> storedCredentials = new ArrayList<>(); //
Aggregation
storedCredentials.add(new String[]{encryptedUsername, encryptedPassword});
4. Inheritance
Definition:
Inheritance is a relationship where one class derives from another, inheriting its properties and
methods.
Examples:
java
Copy code
JFrame frame = new JFrame(); // Inherits from java.awt.Frame
JPanel panel = new JPanel(); // Inherits from javax.swing.JComponent
5. Cohesion
Definition:
Cohesion refers to how closely related and focused the responsibilities of a class or module are.
High cohesion is desirable, as it makes a class easier to maintain and understand.
Types of Cohesion:
High Cohesion:
• Firewall Class:
This class is responsible only for IP-based access control. It has a single, focused
responsibility.
java
Copy code
public static boolean isIPAllowed(String ip) { // Single responsibility
return ALLOWED_IP.equals(ip);
}
• Encryption Class:
Handles only encryption-related functionality (key generation and data encryption). It
doesn’t mix unrelated logic.
java
Copy code
public static String encrypt(String data) throws Exception { // Single
responsibility
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}
Moderate Cohesion:
• Security Class:
Handles authentication and manages the list of stored credentials. While related,
managing stored credentials could be delegated to another class to improve cohesion.
java
Copy code
public static boolean authenticate(String username, String password) throws
Exception {
// Handles authentication, could delegate credential storage
}
Low Cohesion:
• LoginGUI Class:
The GUI class handles multiple responsibilities, including creating the interface and
invoking authentication. This could be split into a dedicated class for GUI creation and
another for user input handling.
Summary Table
Found in
Concept Examples Type
Code?
Private fields like secretKey, ALLOWED_IP,
Encapsulation Yes Data and behavior
and controlled methods like encrypt().
Loose: LoginGUI and Security. Tight:
Coupling Yes Loose/Tight
Security and Encryption.
LoginGUI aggregates Swing components.
Aggregation Yes Shared objects
Security aggregates credentials.
Inherited behavior from Java API (e.g.,
Inheritance No custom N/A
JFrame inherits from Frame).
High: Firewall, Encryption. Moderate:
Cohesion Yes High/Moderate/Low
Security. Low: LoginGUI.