Cybersecurity Algorithms in Java: From Caesar Cipher to Firewall
1) Ceasar Cipher :
import java.
Util.*;
class substitutionTech {
private char[] alphaBets = “ABCDEFGHIJKLMNOPQRSTUVWXYZ”.ToCharArray();
private int key = 3;
private Scanner scanner;
substitutionTech() {
scanner = new Scanner(System.In);
askQuestion();
}
public void askQuestion() {
System.Out.
println(
“Operations:\n\tQ: Quite\n\tG: Get key\n\tS: Set new key\n\tE: Encrypt sting\n\tD: Decrypt string“);
loop: while (true) {
System.Out.Print(“>> “);
char response = Character.ToUpperCase(scanner.NextLine().CharAt(0));
switch (response) {
case ‘G’:
getkey();
break;
case ‘S’:g
setkey();
break;
case ‘S’:g
setkey();
break;
case ‘E’:
encrypt();
break;
case ‘D’:
decrypt();
break;
case ‘Q’:
break loop;
default:
System.Out.Println(“Not a valid answer :(“);
}
}
}
private void setkey() {
System.Out.Print(“Enter key: “);
key = Integer.ParseInt(scanner.NextLine());
System.Out.Println(“Key changed!!”);
}
private void getkey() {
System.Out.Println(“Key is: ” + Integer.ToString(key));
}
private void encrypt() {
System.Out.Print(“Enter text: “);
char[] temp = scanner.NextLine().ToUpperCase().Replace(” “, “#”).ToCharArray();
System.Out.Println(“Encrypted text: “);
for (char c : temp) {
if (c == ‘#’) {
System.Out.Print(” “);
} else {
System.Out.Print(alphaBets[getIndex(c, 0)]);
}
}
System.Out.Println(“”);
}
private void decrypt() {
System.Out.Print(“Enter text: “);
char[] temp = scanner.NextLine().ToUpperCase().Replace(” “, “#”).ToCharArray();
System.Out.Println(“Decrypted text: “);
for (char c : temp) {
if (c == ‘#’) {
System.Out.Print(” “);
} else {
System.Out.Print(alphaBets[getIndex(c, 1)]);
}
}
System.Out.Println(“”);
}
private int getIndex(char c, int type) {
int i;
int aLength = alphaBets.Length;
for (i = 0; i < aLength; i++) {
if (alphaBets[i] == c) {
break;
}
}
if (type == 0) {
i = (i + key) % 26;
} else {
i = ((i – key) < 0) ? ((i – key) + aLength) % 26 : (i – key) % 26;
}
return i;
}
}
class CaesarCipher {
public static void main(String[] args) {
new substitutionTech();
}
}
2)
RSA
6import java.Io.*;
import java.Math.*;
import java.Util.*;
public class RSAlgo {
public static double gcd(double a, double h) {
double temp;
while (true) {
temp = a % h;
if (temp == 0)
return h;
a = h;
h = temp;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.In);
System.Out.Print(“Set P: “);
double p = sc.NextDouble();
System.Out.Print(“Set Q: “);
double q = sc.NextDouble();
double n = p * q;
double e = 2;
double phi = (p – 1) * (q – 1);
while (e < phi) {
if (gcd(e, phi) == 1)
break;
else
e++;
}
int k = 2;
double d = (1 + (k * phi)) / e;
System.Out.Print(“Set Msg: “);
double msg = sc.NextDouble();
System.Out.Println(“Message data = ” + msg);
double c = Math.Pow(msg, e);
c = c % n;
System.Out.Println(“Encrypted data = ” + c);
double m = Math.Pow(c, d);
m = m % n;
System.Out.Println(“Original Message Sent = ” + m);
3)MAC
import java.Math.BigInteger;
import java.Security.MessageDigest;
import java.Security.NoSuchAlgorithmException;
public class Md5Hash {
public static String getMd5(String input)
{
try {
MessageDigest md = MessageDigest.GetInstance(“MD5”);
byte[] messageDigest = md.Digest(input.GetBytes());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = no.ToString(16);
while (hashtext.Length() < 32) {
hashtext = “0” + hashtext;
}
return hashtext;
}
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
public static void main(String args[]) throws NoSuchAlgorithmException
{
System.Out.Println(“For null: ” + getMd5(“”));
System.Out.Println(“For Simple Text: ” + getMd5(“This is my text”));
System.Out.Println(“For Simple Number: ” + getMd5(“12345”));
}
}
4)
Digital Signature
import java.Security.KeyPair;
import java.Security.KeyPairGenerator;
import java.Security.PrivateKey;
import java.Security.PublicKey;
import java.Security.SecureRandom;
import java.Security.Signature;
import java.Util.Base64;
import java.Util.Scanner;
public class DigitalSigningAlgo {
private static final String SIGNING_ALGORITHM = “SHA256withRSA”;
private static final String RSA = “RSA”;
private static Scanner sc;
public static byte[] Create_Digital_Signature(
byte[] input,
PrivateKey Key)
throws Exception {
Signature signature = Signature.GetInstance(SIGNING_ALGORITHM);
signature.InitSign(Key);
signature.Update(input);
return signature.Sign();
}
public static KeyPair Generate_RSA_KeyPair()
throws Exception {
SecureRandom secureRandom = new SecureRandom();
KeyPairGenerator keyPairGenerator = KeyPairGenerator.GetInstance(RSA);
keyPairGenerator.Initialize(2048, secureRandom);
return keyPairGenerator.GenerateKeyPair();
}
public static boolean Verify_Digital_Signature(
byte[] input,
byte[] signatureToVerify,
PublicKey key)
throws Exception {
Signature signature = Signature.GetInstance(SIGNING_ALGORITHM);
signature.InitVerify(key);
signature.Update(input);
return signature.Verify(signatureToVerify);
}
public static void main(String args[])
throws Exception {
String input = “GEEKSFORGEEKS IS A”
+ ” COMPUTER SCIENCE PORTAL”;
KeyPair keyPair = Generate_RSA_KeyPair();
byte[] signature = Create_Digital_Signature(
input.GetBytes(),
keyPair.GetPrivate());
System.Out.Println(
“Signature Value:\n “
+ Base64.GetEncoder().EncodeToString(signature));
System.Out.Println(
“Verification: “
+ Verify_Digital_Signature(
input.GetBytes(),
signature, keyPair.GetPublic()));
}
5) Key Exchange (Diffe hellman)
import java.Util.Scanner;
class DiffeHellmanAlgo {
private static long power(long a, long b, long p)
{
if (b == 1)
return a;
else
return (((long)Math.Pow(a, b)) % p);
}
public static void main(String args[])
{
long P, G, x, a, y, b, ka, kb;
Scanner sc = new Scanner(System.In);
System.Out.Println(“Both the user should be agreed upon the public key genration.”);
System.Out.Print(“Enter value for public key P: “);
P = sc.NextLong();
// P = 23;
System.Out.Print(“Enter value for public key G: “);
G = sc.NextLong();
// G = 9;
System.Out.Print(“Enter value for private key A: “);
a = sc.NextLong();
// a = 4;
System.Out.Print(“Enter value for private key B: “);
b = sc.NextLong();
// b = 3;
x = power(G, a, P);
y = power(G, b, P);
ka = power(y, a, P);
kb = power(x, b, P);
System.Out.Println(“”);
System.Out.Println(“The private key a for User 1:”
+ a);
System.Out.Println(“The private key b for User 2:”
+ b);
System.Out.Println(“Secret key for the User 1 is:”
+ ka);
System.Out.Println(“Secret key for the User 2 is:”
+ kb);
6) IPSecurity Import java.Net.InetAddress; Import java.Util.Scanner;
public class IPSecurity {
// List of allowed IP addresses
// 10.0.0.1 Rejected ip
private static final String[] ALLOWED_IPS = {
“127.0.0.1”, // localhost
“192.168.115.1”,
“192.168.1.211”
};
public static void main(String[] args) {
Scanner sc = new Scanner(System.In);
while (true) {
String clientIP = “”;
System.Out.Print(“Client IP (Press Enter to use your IP): “);
clientIP = sc.NextLine();
if (clientIP.IsEmpty()) {
clientIP = getIp();
}
if (isAllowedIP(clientIP)) {
System.Out.Println(“Accepted connection from: ” + clientIP);
// Handle the accepted connection (You can add your logic here)
} else {
System.Out.Println(“Rejected connection from: ” + clientIP);
// Close the connection (No actual connection is being made in this code)
}
}
}
private static boolean isAllowedIP(String ip) {
for (String allowedIP : ALLOWED_IPS) {
if (allowedIP.Equals(ip)) {
return true;
return false;
}
private static String getIp() {
String systemIpAddress = “”;
try {
InetAddress localhost = InetAddress.GetLocalHost();
systemIpAddress = localhost.GetHostAddress();
} catch (Exception e) {
e.PrintStackTrace();
}
return systemIpAddress;
}
}
7)Firewall Import java.Io.BufferedReader; Import java.Io.IOException; Import java.Io.InputStreamReader;
public class FirewallRuleConfiguration {
public static void main(String[] args) {
try {
// Add a firewall rule to block incoming traffic from a specific IP address (change the IP address as needed)
String addRuleCommand = “netsh advfirewall firewall add rule name=\”BlockIP\” dir=in action=block remoteip=192.168.1.100″;
executeCommand(addRuleCommand);
// List all configured firewall rules
String listRulesCommand = “netsh advfirewall firewall show rule name=all”;
executeCommand(listRulesCommand);
} catch (IOException e) {
e.PrintStackTrace();
}
}
private static void executeCommand(String command) throws IOException {
ProcessBuilder processBuilder = new ProcessBuilder(“cmd.Exe”, “/c”, command);
processBuilder.RedirectErrorStream(true);
Process process = processBuilder.Start();
// Read and display the output of the command
BufferedReader reader = new BufferedReader(new InputStreamReader(process.GetInputStream()));
String line;
while ((line = reader.ReadLine()) != null) {
System.Out.Println(line);
}
try {
int exitCode = process.WaitFor();
System.Out.Println(“Command executed with exit code: ” + exitCode);
} catch (InterruptedException e) {
e.PrintStackTrace();
}
