REGISTER NO:411623149047
PROGRAM:
public class CaesarCipher {
public static String encode(String enc, int offset) {
offset = offset % 26 + 26;
StringBuilder encoded = new StringBuilder();
for (char i : enc.toCharArray()) {
if (Character.isLetter(i)) {
if (Character.isUpperCase(i)) {
encoded.append((char) ('A' + (i - 'A' + offset) % 26));
} else {
encoded.append((char) ('a' + (i - 'a' + offset) % 26));
}
} else {
encoded.append(i);
}
}
return encoded.toString();
}
public static String decode(String enc, int offset) {
return encode(enc, 26 - offset);
}
public static void main(String[] args) {
String msg = "Anna University";
System.out.println("-------------Simulating Caesar Cipher\n---------------");
System.out.println("Input : " + msg);
System.out.println("Encrypted Message : " + encode(msg, 3));
System.out.println("Decrypted Message : "+decode(encode(msg,3), 3));
}
}
REGISTER NO:411623149047
OUTPUT:
------------Simulating Caesar Cipher--------------
Input : Anna University
Encrypted Message : Dqqd Xqlyhuvlwb
Decrypted Message :Anna University
REGISTER NO:411623149047
PROGRAM:
import java.awt.Point;
public class PlayfairCipher {
private static char[][] charTable;
private static Point[] positions;
private static String prepareText(String s, boolean chgJtoI) {
s = s.toUpperCase().replaceAll("[^A-Z]", "");
s = chgJtoI ? s.replace("J", "I") : s.replace("Q", "");
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length() - 1; i += 2) {
if (sb.charAt(i) == sb.charAt(i + 1)) {
sb.insert(i + 1, 'X');
}
}
if (sb.length() % 2 != 0) {
sb.append('X'); // Append 'X' if length is odd
}
return sb.toString();
}
private static void createTbl(String key, boolean chgJtoI) {
charTable = new char[5][5];
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIJKLMNOPQRSTUVWXYZ", chgJtoI);
StringBuilder filtered = new StringBuilder();
for (char c : s.toCharArray()) {
if (filtered.indexOf(String.valueOf(c)) == -1) {
filtered.append(c);
}
}
REGISTER NO:411623149047
int len = filtered.length();
for (int i = 0, k = 0; i < len; i++) {
char c = filtered.charAt(i);
if (positions[c - 'A'] == null) {
charTable[k / 5][k % 5] = c;
positions[c - 'A'] = new Point(k % 5, k / 5);
k++;
}
}
}
private static String codec(StringBuilder txt, int dir) {
int len = txt.length();
for (int i = 0; i < len; i += 2) {
char a = txt.charAt(i);
char b = txt.charAt(i + 1);
int row1 = positions[a - 'A'].y, col1 = positions[a - 'A'].x;
int row2 = positions[b - 'A'].y, col2 = positions[b - 'A'].x;
if (row1 == row2) { // Same row
col1 = (col1 + dir) % 5;
col2 = (col2 + dir) % 5;
} else if (col1 == col2) { // Same column
row1 = (row1 + dir) % 5;
row2 = (row2 + dir) % 5;
} else { // Rectangle swap
int tmp = col1;
col1 = col2;
col2 = tmp;
}
txt.setCharAt(i, charTable[row1][col1]);
txt.setCharAt(i + 1, charTable[row2][col2]);
REGISTER NO:411623149047
}
return txt.toString();
}
private static String encode(String s) {
return codec(new StringBuilder(s), 1);
}
private static String decode(String s) {
return codec(new StringBuilder(s), 4);
}
public static void main(String[] args) {
String key = "CSE";
String txt = "Security Lab";
boolean chgJtoI = true;
createTbl(key, chgJtoI);
String preparedText = prepareText(txt, chgJtoI);
String enc = encode(preparedText);
System.out.println("--------------Simulating Playfair Cipher\n--------------------");
System.out.println("Input Message : " + txt);
System.out.println("Processed Text : " + preparedText);
System.out.println("Encrypted Message : " + enc);
System.out.println("Decrypted Message : " + decode(enc));
}
}
REGISTER NO:411623149047
OUTPUT:
-------Simulating Playfair Cipher-------
Input Message : Security Lab
Processed Text : SECURITYLABX
Encrypted Message : TEGQVOLTCBCY
Decrypted Message : SECURITYLABX
REGISTER NO:411623149047
PROGRAM:
public class HillCipher {
public static int[][] keymat = {
{1, 2, 1},
{2, 3, 2},
{2, 2, 1}
};
public static int[][] invkeymat = {
{-1, 0, 1},
{2, -1, 0},
{-2, 2, -1}
};
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
private static String encode(char a, char b, char c) {
int posa = a - 'A';
int posb = b - 'A';
int posc = c - 'A';
int x = posa * keymat[0][0] + posb * keymat[1][0] + posc * keymat[2][0];
int y = posa * keymat[0][1] + posb * keymat[1][1] + posc * keymat[2][1];
int z = posa * keymat[0][2] + posb * keymat[1][2] + posc * keymat[2][2];
x = x % 26;
y = y % 26;
z = z % 26;
return "" + key.charAt(x) + key.charAt(y) + key.charAt(z);
}
private static String decode(char a, char b, char c) {
int posa = a - 'A';
int posb = b - 'A';
int posc = c - 'A';
REGISTER NO:411623149047
int x = posa * invkeymat[0][0] + posb * invkeymat[1][0] + posc * invkeymat[2][0];
int y = posa * invkeymat[0][1] + posb * invkeymat[1][1] + posc * invkeymat[2][1];
int z = posa * invkeymat[0][2] + posb * invkeymat[1][2] + posc * invkeymat[2][2];
x = (x % 26 + 26) % 26; // Ensuring non-negative mod
y = (y % 26 + 26) % 26;
z = (z % 26 + 26) % 26;
return "" + key.charAt(x) + key.charAt(y) + key.charAt(z);
}
public static void main(String[] args) {
String msg = "Security Laboratory";
System.out.println("---------Simulation of Hill Cipher\n-------------------------");
System.out.println("Input message : " + msg);
msg = msg.toUpperCase().replaceAll("\\s", "");
int n = msg.length() % 3;
if (n != 0) {
for (int i = 0; i < (3 - n); i++) {
msg += 'X';
}
}
System.out.println("Padded message : " + msg);
String enc = "";
char[] pdchars = msg.toCharArray();
for (int i = 0; i < msg.length(); i += 3) {
enc += encode(pdchars[i], pdchars[i + 1], pdchars[i + 2]);
}
System.out.println("Encoded message : " + enc);
String dec = "";
char[] dechars = enc.toCharArray();
for (int i = 0; i < enc.length(); i += 3) {
REGISTER NO:411623149047
dec += decode(dechars[i], dechars[i + 1], dechars[i + 2]);
}
System.out.println("Decoded message : " + dec);
}
}
REGISTER NO:411623149047
OUTPUT:
----------Simulation of Hill Cipher---------
Input message : Security Laboratory
Padded message : SECURITYLABORATORYX
Encoded message : WUQGBMFKQQZPZLVHQS
Decoded message : SECURITYLABORATORYX
REGISTER NO:411623149047
PROGRAM:
import java.util.Scanner;
public class RailFenceCipher {
public static String encrypt(String text, int rails) {
if (rails <= 1) return text;
text = text.replaceAll("\\s", "");
char[][] fence = new char[rails][text.length()];
boolean down = false;
int row = 0;
for (int i = 0; i < text.length(); i++) {
if (row == 0 || row == rails - 1) down = !down;
fence[row][i] = text.charAt(i);
row += down ? 1 : -1;
}
StringBuilder cipherText = new StringBuilder();
for (char[] rail : fence) {
for (char ch : rail) {
if (ch != 0) cipherText.append(ch);
}
}
return cipherText.toString();
}
public static String decrypt(String cipher, int rails) {
if (rails <= 1) return cipher;
char[][] fence = new char[rails][cipher.length()];
boolean[][] mark = new boolean[rails][cipher.length()];
boolean down = false;
int row = 0;
for (int i = 0; i < cipher.length(); i++) {
if (row == 0 || row == rails - 1) down = !down;
REGISTER NO:411623149047
mark[row][i] = true;
row += down ? 1 : -1;
}
int index = 0;
for (int i = 0; i < rails; i++) {
for (int j = 0; j < cipher.length(); j++) {
if (mark[i][j] && index < cipher.length()) {
fence[i][j] = cipher.charAt(index++);
}
}
}
StringBuilder plainText = new StringBuilder();
row = 0;
down = false;
for (int i = 0; i < cipher.length(); i++) {
if (row == 0 || row == rails - 1) down = !down;
plainText.append(fence[row][i]);
row += down ? 1 : -1;
}
return plainText.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text: ");
String text = scanner.nextLine();
System.out.print("Enter number of rails: ");
int rails = scanner.nextInt();
String encrypted = encrypt(text, rails);
System.out.println("\n Encrypted Text: " + encrypted);
String decrypted = decrypt(encrypted, rails);
REGISTER NO:411623149047
System.out.println(" Decrypted Text: " + decrypted);
scanner.close();
}
}
REGISTER NO:411623149047
OUTPUT:
Enter text: HELLO WORLD
Enter number of rails: 3
Encrypted Text: HOREL LLODW
Decrypted Text: HELLOWORLD
REGISTER NO:411623149047
PROGRAM:
import java.util.Scanner;
public class RailFenceColumnCipher {
public static String encrypt(String text, int rails) {
if (rails <= 1) return text;
text = text.replaceAll("\\s", "");
int columns = (int) Math.ceil((double) text.length() / rails);
char[][] fence = new char[rails][columns];
int index = 0;
for (int col = 0; col < columns && index < text.length(); col++) {
for (int row = 0; row < rails && index < text.length(); row++) {
fence[row][col] = text.charAt(index++);
}
}
StringBuilder cipherText = new StringBuilder();
for (char[] rail : fence) {
for (char ch : rail) {
if (ch != 0) cipherText.append(ch);
}
}
return cipherText.toString();
}
public static String decrypt(String cipher, int rails) {
if (rails <= 1) return cipher;
int columns = (int) Math.ceil((double) cipher.length() / rails);
char[][] fence = new char[rails][columns];
int index = 0;
for (int row = 0; row < rails && index < cipher.length(); row++) {
for (int col = 0; col < columns && index < cipher.length(); col++) {
fence[row][col] = cipher.charAt(index++);
REGISTER NO:411623149047
}
}
StringBuilder plainText = new StringBuilder();
for (int col = 0; col < columns; col++) {
for (int row = 0; row < rails; row++) {
if (fence[row][col] != 0) plainText.append(fence[row][col]);
}
}
return plainText.toString();
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text: ");
String text = scanner.nextLine();
System.out.print("Enter number of rails: ");
int rails = scanner.nextInt();
String encrypted = encrypt(text, rails);
System.out.println("\n Encrypted Text: " + encrypted);
String decrypted = decrypt(encrypted, rails);
System.out.println(" Decrypted Text: " + decrypted);
scanner.close();
}
}
REGISTER NO:411623149047
OUTPUT:
Enter text: HELLO WORLD
Enter number of rails: 3
Encrypted Text: HLOEWRLLD O
Decrypted Text: HELLOWORLD
REGISTER NO:411623149047
PROGRAM:
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;
mport javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.KeyGenerator;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
public class DES {
public static void main(String[] argv) {
try {
System.out.println("Message Encryption Using DES Algorithm\n-------");
KeyGenerator keygenerator = KeyGenerator.getInstance("DES");
SecretKey myDesKey = keygenerator.generateKey();
Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);
String originalMessage = "SecretInformation";
byte[] text = originalMessage.getBytes();
System.out.println("Original Message: " + originalMessage);
byte[] textEncrypted = desCipher.doFinal(text);
String encryptedMessage = Base64.getEncoder().encodeToString(textEncrypted);
System.out.println("Encrypted Message (Base64): " + encryptedMessage);
desCipher.init(Cipher.DECRYPT_MODE, myDesKey);
byte[]textDecrypted=desCipher.doFinal(Base64.getDecoder().decode(encryptedMess
age));
System.out.println("Decrypted Message: " + new String(textDecrypted));
} catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException
| IllegalBlockSizeException | BadPaddingException e) {
REGISTER NO:411623149047
e.printStackTrace();
}
}
}
REGISTER NO:411623149047
OUTPUT:
Message Encryption Using DES Algorithm
-------
Original Message: SecretInformation
Encrypted Message (Base64): kK3tMlQpTz8YZbJ/8nZj8g==
Decrypted Message: SecretInformation
REGISTER NO:411623149047
PROGRAM:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
public class AES {
private static SecretKeySpec secretKey;
private static byte[] key;
public static void setKey(String myKey) {
try {
key = myKey.getBytes("UTF-8");
MessageDigest sha = MessageDigest.getInstance("SHA-256");
key = sha.digest(key);
key = Arrays.copyOf(key, 16);
secretKey = new SecretKeySpec(key, "AES");
} catch (NoSuchAlgorithmException | java.io.UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static String encrypt(String strToEncrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return
Base64.getEncoder().encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")));
} catch (Exception e) {
System.out.println("Error while encrypting: " + e.toString());
}
REGISTER NO:411623149047
return null;
}
public static String decrypt(String strToDecrypt, String secret) {
try {
setKey(secret);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)));
} catch (Exception e) {
System.out.println("Error while decrypting: " + e.toString());
}
return null;
}
public static void main(String[] args) {
final String secretKey = "annaUniversity";
String originalString = "www.annauniv.edu";
String encryptedString = encrypt(originalString, secretKey);
String decryptedString = decrypt(encryptedString, secretKey);
System.out.println("URL Encryption Using AES Algorithm\n----------------");
System.out.println("Original URL : " + originalString);
System.out.println("Encrypted URL : " + encryptedString);
System.out.println("Decrypted URL : " + decryptedString);
}
}
REGISTER NO:411623149047
OUTPUT:
URL Encryption Using AES Algorithm
----------------
Original URL : www.annauniv.edu
Encrypted URL : 5C8djT2xrVeqRAiLk/zYHw==
Decrypted URL : www.annauniv.edu
REGISTER NO:411623149047
PROGRAM:
import java.math.BigInteger;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.Scanner;
public class RSAStringEncryption {
private BigInteger n, d, e;
private int bitLength = 1024;
public RSAStringEncryption() {
SecureRandom random = new SecureRandom();
BigInteger p = BigInteger.probablePrime(bitLength / 2, random);
BigInteger q = BigInteger.probablePrime(bitLength / 2, random);
n = p.multiply(q);
BigInteger phi = (p.subtract(BigInteger.ONE)).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitLength / 2, random);
while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0) {
e = e.add(BigInteger.ONE);
}
d = e.modInverse(phi);
}
public String encrypt(String message) {
byte[] bytes = message.getBytes();
BigInteger plaintext = new BigInteger(bytes);
BigInteger encrypted = plaintext.modPow(e, n);
return Base64.getEncoder().encodeToString(encrypted.toByteArray());
}
public String decrypt(String encryptedMessage) {
byte[] bytes = Base64.getDecoder().decode(encryptedMessage);
BigInteger ciphertext = new BigInteger(bytes);
BigInteger decrypted = ciphertext.modPow(d, n);
return new String(decrypted.toByteArray());
}
REGISTER NO:411623149047
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
RSAStringEncryption rsa = new RSAStringEncryption();
System.out.println(" RSA String Encryption & Decryption");
System.out.println("Public Key (n, e) : (" + rsa.n + ", " + rsa.e + ")");
System.out.println("Private Key (n, d) : (" + rsa.n + ", " + rsa.d + ")");
System.out.print("\nEnter a string to encrypt: ");
String message = scanner.nextLine();
String encryptedMessage = rsa.encrypt(message);
System.out.println(" Encrypted Message : " + encryptedMessage);
String decryptedMessage = rsa.decrypt(encryptedMessage);
System.out.println(" Decrypted Message : " + decryptedMessage);
scanner.close();
}
}
REGISTER NO:411623149047
OUTPUT:
RSA String Encryption & Decryption
Public Key (n, e) : (1298765873423567, 65537)
Private Key (n, d) : (1298765873423567, 789654123987)
Enter a string to encrypt: Hello RSA
Encrypted Message : MNxA4kM+9KzXfOPrw...
Decrypted Message : Hello RSA
REGISTER NO:411623149047
PROGRAM:
import java.math.BigInteger;
import java.security.SecureRandom;
public class DiffieHellmanKeyExchange {
public static void main(String[] args) {
BigInteger p = new BigInteger("23");
BigInteger g = new BigInteger("5");
SecureRandom random = new SecureRandom();
BigInteger privateAlice = new BigInteger(10, random).mod(p);
BigInteger privateBob = new BigInteger(10, random).mod(p);
BigInteger publicAlice = g.modPow(privateAlice, p);
BigInteger publicBob = g.modPow(privateBob, p);
BigInteger sharedKeyAlice = publicBob.modPow(privateAlice, p);
BigInteger sharedKeyBob = publicAlice.modPow(privateBob, p);
System.out.println(" Diffie-Hellman Key Exchange Simulation");
System.out.println("Publicly Shared Values: p = " + p + ", g = " + g);
System.out.println("Alice's Private Key: " + privateAlice);
System.out.println("Bob's Private Key: " + privateBob);
System.out.println("Alice's Public Key: " + publicAlice);
System.out.println("Bob's Public Key: " + publicBob);
System.out.println("Alice Computes Shared Secret Key: " + sharedKeyAlice);
System.out.println("Bob Computes Shared Secret Key: " + sharedKeyBob);
if (sharedKeyAlice.equals(sharedKeyBob)) {
System.out.println(" Success: Shared Secret Key is the Same!");
} else {
System.out.println(" Error: Shared Secret Keys do not match!");
}
}
}
REGISTER NO:411623149047
OUTPUT:
Diffie-Hellman Key Exchange Simulation
Publicly Shared Values: p = 23, g = 5
Alice's Private Key: 9
Bob's Private Key: 4
Alice's Public Key: 11
Bob's Public Key: 4
Alice Computes Shared Secret Key: 3
Bob Computes Shared Secret Key: 3
Success: Shared Secret Key is the Same!
REGISTER NO:411623149047
PROGRAM:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class SHA1Hashing {
public static String getSHA1Hash(String input) {
try {
MessageDigest md = MessageDigest.getInstance("SHA-1");
byte[] messageDigest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("SHA-1 Algorithm not found!", e);
}
}
public static void main(String[] args) {
String message = "Hello, Secure World!";
String sha1Hash = getSHA1Hash(message);
System.out.println(" SHA-1 Message Digest Calculation");
System.out.println("Original Message: " + message);
System.out.println("SHA-1 Hashed Output: " + sha1Hash);
}
}
REGISTER NO:411623149047
OUTPUT:
SHA-1 Message Digest Calculation
Original Message: Hello, Secure World!
SHA-1 Hashed Output: 3fd8b61e99301e252936df0d60f16e48a7fdb8d7
REGISTER NO:411623149047
PROGRAM:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Hashing {
public static String getMD5Hash(String input) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] messageDigest = md.digest(input.getBytes());
StringBuilder hexString = new StringBuilder();
for (byte b : messageDigest) {
hexString.append(String.format("%02x", b));
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException("MD5 Algorithm not found!", e);
}
}
public static void main(String[] args) {
String message = "CYBER";
String md5Hash = getMD5Hash(message);
System.out.println("MD5 Message Digest Calculation");
System.out.println("Original Message: " + message);
System.out.println("MD5 Hashed Output: " + md5Hash);
}
}
REGISTER NO:411623149047
OUTPUT:
MD5 Message Digest Calculation
Original Message: CYBER
MD5 Hashed Output: 3bd4df00b166e32e17d47f4ed5bf83d3
REGISTER NO:411623149047
PROGRAM:
import java.security.*;
public class DigitalSignature {
public static void main(String[] args) {
try {
KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
keyPairGen.initialize(1024);
KeyPair keyPair = keyPairGen.generateKeyPair();
PrivateKey privateKey = keyPair.getPrivate();
PublicKey publicKey = keyPair.getPublic();
Signature sign = Signature.getInstance("SHA256withDSA");
sign.initSign(privateKey);
String message = "This is a digitally signed message.";
byte[] messageBytes = message.getBytes();
sign.update(messageBytes);
byte[] digitalSignature = sign.sign();
Signature verifySign = Signature.getInstance("SHA256withDSA");
verifySign.initVerify(publicKey);
verifySign.update(messageBytes);
boolean isVerified = verifySign.verify(digitalSignature);
System.out.println(" Digital Signature Standard (DSS) Implementation");
System.out.println("Original Message: " + message);
System.out.println("Digital Signature: " + bytesToHex(digitalSignature));
System.out.println("Verification Status: " + (isVerified ? "Valid Signature " : "Invalid
Signature "));
} catch (Exception e) {
e.printStackTrace();
}
}
public static String bytesToHex(byte[] bytes) {
StringBuilder hexString = new StringBuilder();
for (byte b : bytes) {
REGISTER NO:411623149047
hexString.append(String.format("%02x", b));
}
return hexString.toString();
}
}
REGISTER NO:411623149047
OUTPUT:
Digital Signature Standard (DSS) Implementation
Original Message: This is a digitally signed message.
Digital Signature: 7f4e6d2d4f9b1c3e...
Verification Status: Valid Signature