0% found this document useful (0 votes)
8 views27 pages

Package Exp

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
8 views27 pages

Package Exp

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

package exp5;

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;

// Firewall class to handle IP-based access control


class Firewall {
private static final String ALLOWED_IP = "192.168.1.1"; // Simulated IP,
only this IP is allowed access.

// Method to check if the given IP is allowed.


public static boolean isIPAllowed(String ip) {
return ALLOWED_IP.equals(ip); // Returns true if the IP matches
ALLOWED_IP, false otherwise.
}
}

// Encryption class to handle encryption of data


class Encryption {
private static SecretKey secretKey; // The secret AES encryption key.

// Method to generate a new AES key.


private static SecretKey generateKey() throws Exception {
KeyGenerator keyGen = KeyGenerator.getInstance("AES"); // Uses AES
algorithm.
keyGen.init(256); // Sets the key size to 256 bits.
return keyGen.generateKey(); // Returns the generated key.
}

// 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();
}
}

// Method to encrypt data using AES.


public static String encrypt(String data) throws Exception {
Cipher cipher = Cipher.getInstance("AES"); // Get AES cipher
instance.
cipher.init(Cipher.ENCRYPT_MODE, secretKey); // Initialize it in
encryption mode with the secret key.
byte[] encryptedBytes = cipher.doFinal(data.getBytes()); // Encrypt
the input data.
return Base64.getEncoder().encodeToString(encryptedBytes); // Encode
the result in Base64 and return it.
}
}

// GUI class for the login interface


class LoginGUI {

// Method to create the login frame.


public void createLoginFrame() {
JFrame frame = new JFrame("Login System with Encryption"); // Create
the main frame.
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); // Ensure the
application exits on close.
frame.setSize(400, 300); // Set the size of the frame.
frame.setLayout(new BorderLayout()); // Use BorderLayout for
organization.

// Background panel for aesthetics.


JPanel backgroundPanel = new JPanel();
backgroundPanel.setBackground(new Color(220, 240, 255)); // Light
blue background color.
backgroundPanel.setLayout(new GridBagLayout()); // Center-aligns
components.
frame.add(backgroundPanel, BorderLayout.CENTER); // Add the panel to
the frame.

// Login panel to hold input fields and buttons.


JPanel loginPanel = new JPanel();
loginPanel.setBackground(new Color(220, 240, 255));
loginPanel.setLayout(new GridLayout(3, 2, 10, 10)); // GridLayout
with 3 rows, 2 columns.

// Username label and input field.


JLabel userLabel = new JLabel("Username:");
JTextField usernameField = new JTextField(10); // Field for username
input.

// Password label and input field.


JLabel passLabel = new JLabel("Password:");
JPasswordField passwordField = new JPasswordField(10); // Field for
password input.

// Login button for user to submit credentials.


JButton loginButton = new JButton("Login");

// Align labels to the right for better UI.


userLabel.setHorizontalAlignment(SwingConstants.RIGHT);
passLabel.setHorizontalAlignment(SwingConstants.RIGHT);

// Add components to the login panel.


loginPanel.add(userLabel);
loginPanel.add(usernameField);
loginPanel.add(passLabel);
loginPanel.add(passwordField);
loginPanel.add(new JLabel()); // Spacer for alignment.
loginPanel.add(loginButton);
// Add login panel to the background panel.
backgroundPanel.add(loginPanel);

// Label to display login status messages.


JLabel statusLabel = new JLabel("", SwingConstants.CENTER);
statusLabel.setFont(new Font("Arial", Font.PLAIN, 14)); // Set font
for readability.
statusLabel.setForeground(Color.RED); // Default text color.
frame.add(statusLabel, BorderLayout.SOUTH); // Position at the
bottom.

// Event listener for the login button.


loginButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
String username = usernameField.getText(); // Get inputted
username.
String password = new String(passwordField.getPassword()); //
Get 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.

// Open the admin dashboard on successful login.

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);
}
}
});

frame.setVisible(true); // Display the login frame.


}

// Method to open a URL in the default web browser.


private void openURL(String url) {
try {
URI uri = new URI(url); // Create URI from the URL string.
if (Desktop.isDesktopSupported()) {
Desktop.getDesktop().browse(uri); // Open the URL in the
default browser.
} else {
System.out.println("Desktop is not supported on this
system.");
}
} catch (Exception e) {
e.printStackTrace(); // Log the exception.
System.out.println("Failed to open the URL: " + e.getMessage());
}
}
}

// 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.

// List to store encrypted username-password pairs for tracking.


private static final List<String[]> storedCredentials = new
ArrayList<>();

// Method to create and display the login GUI.


public static void createAndShowLoginGUI() {
LoginGUI gui = new LoginGUI();
gui.createLoginFrame(); // Call to initialize the login frame.
}

// Method to authenticate user credentials.


public static boolean authenticate(String username, String password)
throws Exception {
String encryptedUsername = Encryption.encrypt(username); // Encrypt
the inputted username.
String encryptedPassword = Encryption.encrypt(password); // Encrypt
the inputted password.

// Store the processed credentials in the list.


storedCredentials.add(new String[]{encryptedUsername,
encryptedPassword});

// Log stored credentials for debugging.


System.out.println("Stored Credentials: ");
for (String[] credentials : storedCredentials) {
System.out.println("Username: " + credentials[0] + ", Password: "
+ credentials[1]);
}

// Return true if both username and password match the stored valid
credentials.
return encryptedUsername.equals(encryptedValidUsername) &&
encryptedPassword.equals(encryptedValidPassword);
}

public static void main(String[] args) {


try {
// Define the valid credentials for login.
String validUsername = "admin";
String validPassword = "password123";

// Encrypt the valid credentials for comparison during


authentication.
encryptedValidUsername = Encryption.encrypt(validUsername);
encryptedValidPassword = Encryption.encrypt(validPassword);

// Log the encrypted credentials for debugging purposes.


System.out.println("Encrypted Username: " +
encryptedValidUsername);
System.out.println("Encrypted Password: " +
encryptedValidPassword);

// Launch the login GUI.

javax.swing.SwingUtilities.invokeLater(Security::createAndShowLoginGUI);
} catch (Exception e) {
e.printStackTrace(); // Log any exceptions that occur.
}
}
}

Code Explanation: Line by Line and Function by Function

Purpose Overview:

The program implements a secure login system with the following features:

1. Firewall for IP-based access control.


2. AES encryption for storing and verifying credentials.
3. Graphical User Interface (GUI) for user interaction.
4. Encapsulation, association, and software design principles are incorporated.

1. Firewall Class

Purpose: Restricts access to the application based on an IP address.

• Static Attribute:

java
Copy code
private static final String ALLOWED_IP = "192.168.1.1";

o Holds the only allowed IP address for the application.


• Static Method:

java
Copy code
public static boolean isIPAllowed(String ip);

o Takes an IP as input and compares it to ALLOWED_IP.


o Returns true if the IP matches, restricting access to other IPs.
• Encapsulation:
o IP control logic is hidden within the class, providing a clean interface
(isIPAllowed).

2. Encryption Class

Purpose: Handles AES encryption for credentials, ensuring sensitive data is securely stored.

• Static Attribute:

java
Copy code
private static SecretKey secretKey;

o Holds the AES key for encryption.


• Static Block:

java
Copy code
static {
try {
secretKey = generateKey();
} catch (Exception e) {
e.printStackTrace();
}
}

o Generates a unique AES SecretKey when the program starts.


o This represents encapsulation of key generation logic.
• Static Method:

java
Copy code
private static SecretKey generateKey() throws Exception;

o Generates a 256-bit AES key using KeyGenerator.


java
Copy code
public static String encrypt(String data) 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();

o Creates a Swing JFrame with:


 Text fields for username and password.
 A button for login.
 A status label for messages.
• Event Handling:

java
Copy code
loginButton.addActionListener(new ActionListener() {...});

oAuthenticates the user when the login button is clicked:


1. Validates the IP using Firewall.isIPAllowed.
2. Calls Security.authenticate for credential verification.
3. Updates the status label based on results.
• URL Handling:

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

Purpose: Orchestrates authentication and manages stored credentials.

Attributes:

• encryptedValidUsername & encryptedValidPassword: Store the AES-encrypted


valid credentials.
• storedCredentials: Stores all attempted login credentials for tracking.

Main Methods:

• createAndShowLoginGUI:
o Launches the GUI by instantiating LoginGUI.
• authenticate:

java
Copy code
public static boolean authenticate(String username, String password)
throws Exception;

o Encrypts the input username and password.


o Compares them with the stored valid credentials.
o Logs the encrypted inputs to storedCredentials for auditing.

Association:

• Security interacts with both LoginGUI (UI logic) and Encryption (encryption logic).

Software Design Features

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.

How the System Works

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";

// Encrypt the valid credentials to store in the program.


encryptedValidUsername = Encryption.encrypt(validUsername);
encryptedValidPassword = Encryption.encrypt(validPassword);

// Log the encrypted credentials (for debugging).


System.out.println("Encrypted Username: " + encryptedValidUsername);
System.out.println("Encrypted Password: " + encryptedValidPassword);

// Launch the login GUI.

javax.swing.SwingUtilities.invokeLater(Security::createAndShowLoginGUI);
} catch (Exception e) {
e.printStackTrace(); // Log any exceptions.
}
}

1. Encrypting valid credentials:


o The program encrypts the hardcoded valid username ("admin") and password
("password123") using the Encryption.encrypt() method.
o These encrypted values are logged for debugging purposes, and they are stored in
the variables encryptedValidUsername and encryptedValidPassword.
2. Launching the GUI:
o The Security.createAndShowLoginGUI() method is invoked, which calls the
LoginGUI.createLoginFrame() method to display the login screen.

Step 2: User Interacts with the GUI

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.

Step 3: User Inputs Data

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.

Step 4: Handling Login Button Click

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.

// Open the admin dashboard on successful login.


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);
}
}
});

Step 4.1: Firewall Check


• Condition: Firewall.isIPAllowed("192.168.1.1")
o This method checks whether the IP "192.168.1.1" is allowed.
o In this case, it will return true since "192.168.1.1" is the allowed IP.
o If the IP wasn't allowed, the program would display "Access Denied by
Firewall." and not proceed further.

Step 4.2: Authentication

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);

// Store the encrypted credentials in the list.


storedCredentials.add(new String[]{encryptedUsername,
encryptedPassword});

// Log stored credentials for debugging.


System.out.println("Stored Credentials: ");
for (String[] credentials : storedCredentials) {
System.out.println("Username: " + credentials[0] + ", Password: " +
credentials[1]);
}

// 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.

openURL("http://localhost/website/admin_dashboard.php"); // Open the admin


dashboard page.

• "Login Successful!" appears in green.


• The browser opens the URL ("http://localhost/website/admin_dashboard.php"),
simulating a redirect to the admin dashboard (in the case of a real application, this would
open a webpage).

Step 6: Invalid Credentials (If the User Enters Wrong Data)

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.

• The program will display "Invalid Credentials" in red text.

Step 7: Handling Errors

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. Firewall Check (Firewall.isIPAllowed("192.168.1.1")): If the IP isn't allowed,


deny access.
2. Authentication Check (Security.authenticate()):
o Encrypt inputted credentials.
o Compare encrypted credentials with the stored valid ones.
o If valid, show a success message and redirect to the dashboard.
o If invalid, show an error message.
3. Error Handling: Any issues during encryption, login, or browsing trigger error
messages.
Example Scenario:

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.

What You Will See on the Screen (Login GUI)

The login window will look something like this:

• 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] |
----------------------------------------------

Step-by-Step Example of User Interaction:

Step 1: Entering Correct Credentials

Let's say you enter the correct credentials: admin for the username and password123 for the
password.

1. Username: admin
2. Password: password123

What happens behind the scenes:

• 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.

What You Will See:

• Success Message: You will see a message in green that says:

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.

Step 2: Entering Incorrect Credentials

Now, let's enter incorrect credentials, for example:

1. Username: wronguser
2. Password: wrongpass

What happens behind the scenes:

• 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.

What You Will See:

• Error Message: You will see a red message that says:

Copy code
Invalid Credentials.

• No URL Opening: Since the credentials are invalid, the URL will not open.

Step 3: Attempting to Login with Other Invalid Data

You can keep trying different usernames and passwords, such as:
1. Username: admin
2. Password: wrongpassword

What happens behind the scenes:

• The program will check the input credentials.


• It will match the username (admin) but the password (wrongpassword) won't match.
• The program will display an "Invalid Credentials" message because both username and
password need to be correct.

What You Will See:

• Error Message: You will see a message in red like:

Copy code
Invalid Credentials.

Step 4: Edge Case (Firewall Denied Access)

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.

What happens behind the scenes:

• The program will check if the IP 192.168.1.1 is allowed by the firewall.


• If the IP doesn't match (for instance, if the program is configured to deny certain IPs), it
will deny access.

What You Will See:

• 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.

Complete Example Walkthrough:

1. Run the Program


o The program opens the login window.
2. Enter Correct Credentials (admin, password123)
o You enter admin in the username field and password123 in the password field.
o Click Login.
o The program encrypts the credentials and compares them with the valid stored
credentials.
o Since the credentials match, it shows the message:

Copy code
Login Successful!

o It opens the URL (http://localhost/website/admin_dashboard.php).


3. Enter Incorrect Credentials
o You enter wronguser in the username field and wrongpass in the password field.
o Click Login.
o The program encrypts the credentials and compares them with the valid
credentials.
o Since they don't match, it shows the message:

Copy code
Invalid Credentials.

4. Firewall Denial (if IP is not allowed)


o The program checks the firewall IP.
o If the IP is not allowed (for example, if it's changed), it shows:

csharp
Copy code
Access Denied by Firewall.

Example of What Would Appear in the Console:

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"}

Summary of User Interaction Flow:

1. Username and Password input.


2. Encryption of inputs and comparison with stored valid credentials.
3. Based on the result:
o Success: Show "Login Successful!" and open the admin dashboard.
o Failure: Show "Invalid Credentials" and deny login.
o Firewall Issue: Show "Access Denied by Firewall" if the IP is not allowed.

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:

• The Cipher.getInstance("AES") method creates a Cipher instance for AES


encryption.
• The cipher.init(Cipher.ENCRYPT_MODE, secretKey) sets the cipher to encrypt data
using the provided secretKey.
• The doFinal(data.getBytes()) method encrypts the data (username/password).

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:

• SecretKey secretKey stores the key generated by the KeyGenerator.


• It is passed into the Cipher.init() method to initialize the cipher for encryption.

4. javax.swing.* (Swing GUI Libraries)

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.

5. java.awt.* (Abstract Window Toolkit Libraries)

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).

7. java.util.ArrayList and java.util.List

These are classes from the java.util package that are used to store and manage collections of
objects.

• List<String[]> storedCredentials = new ArrayList<>(): This creates an


ArrayList that will store pairs of encrypted usernames and passwords. Each pair is
stored as an array of strings.
• storedCredentials.add(new String[]{encryptedUsername,
encryptedPassword}): This adds the encrypted username-password pair to the list.

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.

• Base64.getEncoder().encodeToString(encryptedBytes): This method encodes the


encrypted bytes into a Base64 string, making the ciphertext printable as text.

9. java.awt.event.* (Event Handling Libraries)

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.

Summary of Libraries Used in the Program

• javax.crypto: Used for encryption and key management.


• javax.swing: Provides classes for creating the graphical user interface (GUI).
• java.awt: Provides additional GUI components and layout managers.
• java.net: Used to handle the URI and open a web browser.
• java.util: Used for managing collections and encoding data (Base64).
• java.awt.event: Used for handling events like button clicks.

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.

Examples and Explanation:

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

public static boolean isIPAllowed(String ip) { // Controlled access


return ALLOWED_IP.equals(ip); // Only compares with the allowed IP
}
Encapsulation in Encryption:

• 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

private static SecretKey generateKey() throws Exception { // Internal helper


method
KeyGenerator keyGen = KeyGenerator.getInstance("AES");
keyGen.init(256);
return keyGen.generateKey();
}

public static String encrypt(String data) throws Exception { // Public access


to functionality
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(data.getBytes());
return Base64.getEncoder().encodeToString(encryptedBytes);
}

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;

public static boolean authenticate(String username, String password) throws


Exception {
// Exposed functionality with internal security logic
String encryptedUsername = Encryption.encrypt(username);
String encryptedPassword = Encryption.encrypt(password);

return encryptedUsername.equals(encryptedValidUsername) &&


encryptedPassword.equals(encryptedValidPassword);
}

2. Coupling

Definition:
Coupling refers to the degree of dependency between classes or components.
Types of Coupling:

1. Loose Coupling: Preferred, where classes are independent of each other.


2. Tight Coupling: Discouraged, where classes are heavily dependent on each other.

Examples and Analysis:

Loose Coupling:

• Between LoginGUI and Security:


LoginGUI uses the Security class for authentication, but it doesn’t know the details of
how authentication works. This modular design allows the authentication logic to change
without impacting the GUI.

java
Copy code
if (Security.authenticate(username, password)) { // Loose coupling
statusLabel.setText("Login Successful!");
}

Tight Coupling:

• Between Encryption and Security:


Security relies on Encryption to encrypt credentials. If the encryption algorithm
changes, both classes must be updated.

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.

Examples and Analysis:

LoginGUI Aggregates Swing Components:

• 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

Security Aggregates Stored Credentials:

• The storedCredentials list in Security holds encrypted credentials. These credentials


are independent objects that can exist without the Security class.

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.

Is it present in the code?

• No custom inheritance is implemented in this program.


• The program relies on the Java API, where classes like JFrame and JPanel inherit from
their respective parent classes.

Examples:

• JFrame inherits from java.awt.Frame.


• JPanel inherits from javax.swing.JComponent.

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:

1. High Cohesion: A class has a single, well-defined responsibility.


2. Low Cohesion: A class has multiple, unrelated responsibilities.
Examples and Analysis:

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.

You might also like