0% found this document useful (0 votes)
6 views19 pages

Computer Security Practicals

The document outlines a series of Java programs implementing various encryption techniques, including Caesar Cipher, Playfair Cipher, One-Time Pad Vigenere Cipher, and a Three-Rotor Machine Cipher. Each program features methods for encryption and decryption, along with additional functionalities such as brute-force attacks and key matrix construction. The programs are designed to demonstrate the principles of mono-alphabetic and poly-alphabetic substitution techniques in computer security.

Uploaded by

Anup Patel
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)
6 views19 pages

Computer Security Practicals

The document outlines a series of Java programs implementing various encryption techniques, including Caesar Cipher, Playfair Cipher, One-Time Pad Vigenere Cipher, and a Three-Rotor Machine Cipher. Each program features methods for encryption and decryption, along with additional functionalities such as brute-force attacks and key matrix construction. The programs are designed to demonstrate the principles of mono-alphabetic and poly-alphabetic substitution techniques in computer security.

Uploaded by

Anup Patel
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

MSCIT-7 Computer security practicals

[Link] a menu driven program to implement [mono-alphabetic substitution technique] casear


cipher encrypt/decrypt algoritham and also perform cryptanalytic brute-force attack to print all
translation of plaintext using all possible key values.

import [Link].*;
import [Link].*;

public class P01CaesarCipher {

private String text = "", convertedtext = "";

P01CaesarCipher(String s) {

text = s;
}

public String EncryptCaeser(int ekey) {

for (int i = 0; i < [Link](); i++) {

int pasc = (int) [Link](i);

if (pasc >= 65 && pasc <= 90) {


int bvalue = pasc - 65;
int newasc = 65+(bvalue + ekey) % 26;
convertedtext += (char) newasc;

}
else if (pasc >= 97 && pasc <= 122) {
int bvalue = pasc - 97;
int newasc = 97+(bvalue + ekey) % 26;
convertedtext += (char) newasc;

}
else
{
convertedtext += (char) [Link](i);
}
}
return convertedtext;
}

public String DecryptCeaser(int dkey){


convertedtext = "";
for(int i=0;i<[Link]();i++){
int casc = (int) [Link](i);

if (casc >= 65 && casc <= 90) {


int bvalue = casc - 65;
int newasc = ((bvalue - dkey) %26)<0 ? (90 - ((dkey - bvalue)%26)+1) : (65-((dkey -
bvalue)%26));
convertedtext += (char) newasc;

}
MSCIT-7 Computer security practicals
else if (casc >= 97 && casc <= 122) {
int bvalue = casc - 97;
int newasc = ((bvalue - dkey) %26)<0 ? (122 - ((dkey - bvalue)%26)+1) : (97-((dkey
- bvalue)%26));
convertedtext += (char) newasc;

}
else
{
convertedtext += (char) [Link](i);
}
}
return convertedtext;
}

public void BruteForceAttack(){


for(int dkey=0; dkey<=25;dkey++){
String ctext = DecryptCeaser(dkey);
[Link]("Plain Text ["+dkey+"]"+ctext);
}
}
}

[Link] a menu driven program to implement [mono-alphabetic substitution technique] playfair


cipher encrypt/decrypt algoritham.

public class P02PlayFairCipher {

private String key="",text="";


private char[][]kMat = new char[5][5];

public P02PlayFairCipher(String k)
{
key = k;
}
public void keyConstruct(){
StringBuffer sbk = new StringBuffer([Link]());

//Loop to Remove Duplicate Characters Into Key.....


for(int i=0;i<[Link]();i++){
String sk = [Link](i,i+1);

if(([Link](sk) != [Link](sk)) || [Link]("J")){


[Link](i);
}
}
//Loop To Add Remainting Alphabets to Key...
for(int i=65;i<=90;i++){
String ch = [Link]((char)i);
if(([Link](ch)<0) && ![Link]("J")){
[Link](ch);
}
}
MSCIT-7 Computer security practicals
String nKey = new String(sbk);
[Link]("New Key : "+nKey);

//LOOP To Arrange New Key To Matrix Except 'J'


int k=0;
for(int i=0;i<5;i++){
for(int j=0;j<5;j++){
char ch = [Link](k++);
kMat[i][j] = ch;
}
}
[Link]("\n Key Matrix");
[Link]("-------------");

for(int i=0;i<5;i++){
for(int j=0;j<5;j++){

[Link](kMat[i][j] + " ");


}
[Link]();
}
}
public String EncryptPF(String p){
String plain = p, nplain="",cipher="";

//Append 'X' in-Between of two Same Caharacters

StringBuffer psb = new StringBuffer(plain);


for(int i=0;i<[Link]()-1;i++){
if([Link](i) == [Link](i+1))
[Link](i+1, 'X');
}

//Make Plain Text In Even Length


if([Link]()%2 == 1)[Link]('X');
String PP = new String(psb);

//Create 2D Array for Storring


//plaint text For its row/col no From Key Matrix
char[]pArray = [Link]();
int []pRow = new int[[Link]()];
int []pCol = new int[[Link]()];

for(int i=0;i<[Link]();i++){
char c = [Link](i);
for(int m=0;m<5;m++){
for(int n=0;n<5;n++){
if(kMat[m][n]==c){
pRow[i] = m;
pCol[i] = n;
}
}
}
}
//Print Plain Text Array Along With Row/Col Values
MSCIT-7 Computer security practicals
for(int i=0;i<[Link]();i++){
[Link](pArray[i] + " " + pRow[i] + " " + pCol[i]);
}
for(int i=0; i<[Link]();i=i+2){
//Characters Are in Same row
if(pRow[i] == pRow[i]+1){
if(pCol[i] == 4){
pCol[i] = 0;
pCol[i+1] = pCol[i+1] + 1;
}
else if(pCol[i+1] == 4){
pCol[i+1] = 0;
pCol[i] = pCol[i] + 1;
}
else
{
int temp = pCol[i];
pCol[i] = pCol[i+1];
pCol[i+1] = temp;
}
}
//Characters Are In Same Column
else if(pCol[i] == pCol[i+1]){
if(pRow[i] == 0){
pRow[i] = 4;
pRow[i+1] = pRow[i+1] - 1;
}
else if(pRow[i+1] == 0){
pRow[i+1] = 4;
pRow[i] = pRow[i] - 1;
}
else{
int temp = pRow[i];
pRow[i] = pRow[i+1];
pRow[i+1] = temp;
}
}
//Characters Are Inserted Row And Column
else{
int temp = pRow[i];
pRow[i] = pRow[i+1];
pRow[i+1] = temp;
}
}
//Construct Cipher Text From key Matrix
//According To Row And Column Arrays

for(int i = 0 ;i<[Link]();i++){
cipher += kMat[pRow[i]][pCol[i]];
}
return cipher;
}

public String DecryptPF(String c){


String cipher=c,plain="";
MSCIT-7 Computer security practicals

//Create 2D Array For Storing..


//Plain Text With its Row/Col no From Key Matrix

char[]cArray = [Link]();
int[]cRow = new int[[Link]()];
int[]cCol = new int[[Link]()];

for(int i=0;i<[Link]();i++){
char CC = [Link](i);
for(int m=0;m<5;m++){
for(int n=0;n<5;n++){
if(kMat[m][n] == CC){
cRow[i] = m;
cCol[i] = n;
}
}
}
}
//Print Cipher text Array Along With Row/Col Values
for(int i=0;i<[Link]();i++){
[Link](cArray[i] + " " + cRow[i] + " " + cCol[i]);

}
//Decrypt Characater According to Play Fair Algo [Rules]
for(int i=0;i<[Link]();i=i+2){
//Characters Are in Same Row
if(cRow[i] == cRow[i+1]){
if(cCol[i] == 0){
cCol[i] = 4;
cCol[i+1] = cCol[i+1] - 1;
}
else if(cCol[i+1] == 0){
cCol[i+1] = 4;
cCol[i] = cCol[i] - 1;
}
else{
int temp = cCol[i];
cCol[i] = cCol[i+1];
cCol[i+1] = temp;
}
}
//Characters Are in Same Column
else if(cCol[i] == cCol[i+1]){
if(cRow[i] == 4){
cRow[i] = 0;
cRow[i+1] = cRow[i+1] + 1;
}
else if(cRow[i+1] == 4){
cRow[i+1] = 0;
cRow[i] = cRow[i]+1;
}
else{
int temp = cRow[i];
cRow[i] = cRow[i+1];
MSCIT-7 Computer security practicals
cRow[i+1] = temp;
}
}
//Characters Are Inserted Row And Col
else{
int temp = cRow[i];
cRow[i] = cRow[i+1];
cRow[i+1] = temp;
}
}
//Construct Plain Text From Key Matrix
//According To Row And Col Arrays
for(int i=0; i <[Link]();i++){
plain += kMat[cRow[i]][cCol[i]];
}
//Removing 'X' Characters From Plain Text
StringBuffer psb = new StringBuffer(plain);
int len = [Link]();

//Rem,oving Last X Character


//IF String Length Is Even and Last Char is 'X'
if((len%2 == 0) && ([Link]("X") == len-1)){
[Link](len-1);
}

//Rem,oving other X Character


//if X is Found and Prev And Next Char is Same
for(int i=0;i<[Link]();i++){
if([Link](i) == 'X'){
if([Link](i-1) == [Link](i+1)){
[Link](i);
}
}
}
String newPlain = new String(psb);
return newPlain;
}
}

3. write a menu driven program to implement [poly-alphabetic substitution technique] one time
pad vigenere cipher encrypt/decrypt algoritham.

package Practicals;

public class P03OTPVigenereCipher {

public String key="", text;

public String EncryptOTP(String s){


MSCIT-7 Computer security practicals
text =s;
String Cipher="";

for(int i=0;i<[Link]();i++){

char ch = (char)([Link](i));

if([Link](ch)){
int no = (int)[Link]([Link]()*100)%26;
key += (char)(65 + no);
}
else
{
int no = (int)[Link]([Link]()*100)%26;
key += (char)(97 + no);
}
}
for(int i=0;i<[Link]();i++){
if([Link]([Link](i))){
int pindex = (int)[Link](i) - 65;
int kindex = (int)[Link](i)-65;
int newindex = 65+(pindex+kindex)%26;
Cipher += (char)newindex;
}
else
{
int pindex = (int)[Link](i) - 97;
int kindex = (int)[Link](i)-97;
int newindex = 97+(pindex+kindex)%26;
Cipher += (char)newindex;
}
}

[Link]("The Key Text Is : " + key);


return Cipher;

public String DecryptOTP(String s){

text = s;
String plain = "";
[Link]("The Key Text Is : " + key);

for(int i=0;i<[Link]();i++){
if([Link]([Link](i))){
int cindex = (int)[Link](i) - 65;
int kindex = (int)[Link](i)-65;
int newindex = (cindex-kindex)<0?(90-(kindex - cindex) + 1) : (65+(cindex -
kindex));
plain += (char) newindex;
}else
MSCIT-7 Computer security practicals
{
int cindex = (int)[Link](i) - 97;
int kindex = (int)[Link](i)-97;
int newindex = (cindex-kindex)<0?(122-(kindex - cindex) + 1) : (97+(cindex -
kindex));
plain += (char)newindex;
}
}

return plain;
}

4. write a menu driven program to implement [rotor machine technique] 3-rotor machines
cipher encrypt/decrypt algoritham.

package Practicals;

public class P04ThreeRotorCipher {

String text="";
int [][]slow={{24,25,26,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23},
{21,3,15,1,19,10,14,26,20,8,16,7,22,4,11,5,17,9,12,23,18,2,25,6,24,13}};

int [][]medium={{26,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},
{20,1,6,4,15,3,14,12,23,5,16,2,22,19,11,18,25,24,13,7,10,8,21,9,26,17}};

int [][]fast={{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},
{8,18,26,17,20,22,10,3,13,11,4,23,5,24,9,12,25,16,19,6,15,21,2,7,1,14}};

public P04ThreeRotorCipher()
{
text="";
}
public void drawScreen(){

[Link]("\t\t\tThree Rotor Machine");


[Link]("---------------------------------------------------------------------");

for(int i=0;i<26;i++)
{
[Link]("\t"+(char)(i+65)+"|\t");
[Link](slow[0][i]+"\t");
[Link](slow[1][i]+"\t|");
[Link](medium[0][i]+"\t");
[Link](medium[1][i]+"\t|");
[Link](fast[0][i]+"\t");
[Link](fast[1][i]+"\t|");
[Link]((char)(i+65));
[Link]();
}
[Link]("-----------------------------------------------------------------------");
[Link]("\t Slow Rotor\t Medium Rotor\t Fast Rotor");
MSCIT-7 Computer security practicals
}
public String Encrypt3Rotor(String s)
{
text=s;
int index,j,k;
StringBuffer sb=new StringBuffer();

for(int i=0;i<[Link]();i++)
{
if([Link]([Link](i)))
index=(int) [Link](i)-65;
else
index=(int) [Link](i)-97;
//Fetch value of index position in first column of Slow
j=slow[0][index];
k=0;
while(slow[1][k]!=j)k++;

//Fetch value of Kth Position in first column of medium


j=medium[0][k];
k=0;
while(medium[1][k]!=j)k++;

//Fetch value of Kth Position in first column of fast


j=fast[0][k];
k=0;
while(fast[1][k]!=j)k++;

char ch;
if([Link]([Link](i)))
{
ch=(char)(k+65);
[Link](ch);
}
else
{
ch=(char)(k+97);
[Link](ch);
}
}
String cipher=new String(sb);
return cipher;
}
public String Decrypt3Rotor(String s)
{

text=s;
int index,j,k;
StringBuffer sb=new StringBuffer();

for(int i=0;i<[Link]();i++)
{
if([Link]([Link](i)))
index=(int)[Link](i)-65;
else
MSCIT-7 Computer security practicals
index=(int)[Link](i)-97;
//Fetch value of Index Position in first column of fast
j=fast[1][index];
k=0;
while(fast[0][k]!=j)k++;

//Fetch value of Indedx Position in first column of Medium


j=medium[1][k];
k=0;
while(medium[0][k]!=j)k++;

//Fetch value of Index Position in first column of Slow


j=slow[1][k];
k=0;
while(slow[0][k]!=j)k++;

char ch;
if([Link]([Link](i)))
{
ch=(char)(k+65);
[Link](ch);
}
else
{
ch=(char)(k+97);
[Link](ch);

}
}
String plain=new String(sb);
return plain;
}
}

6. write a menu driven program to implement encrypt/decrypt using columnar transposition.

package Practicals;

public class P06ColTransCipher {

private String text = "";


int[] key;
char[][] matrix;

public String EncryptColTrans(String s) {

StringBuffer sb = new StringBuffer();


text = s;
int plen = [Link]();
int row = 2, col = 0;
boolean flag = true;

if ((plen % 2) == 0) {
col = plen / 2;
} else {
MSCIT-7 Computer security practicals
col = (plen + 1) / 2;
}

key = new int[col];


matrix = new char[row][col];

int no = 0;
int i = 0;

while (i < col) {


flag = true;
no = (int) ([Link]([Link]() * 100) % col);

//if Random No Is Repeated then Re calculate it.....


for (int j = 0; j < i; j++) {
if (key[j] == no) {
flag = false;
break;
}
}
if (flag) {
// [Link]("NUMBER "+no);
key[i] = no;
i++;
}
}

//Arragneing The Plain Text Into Two Dimentional Arrry...


int k = 0;
for (i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if (k < plen) {
matrix[i][j] = [Link](k);
}
k++;
[Link](matrix[i][j] + " ");
}
[Link]();
}

for (i = 0; i < col; i++) {


for (int j = 0; j < col; j++) {
if (key[j] == i) {
for (k = 0; k < row; k++) {
if (matrix[k][j] != ' ') {
[Link](matrix[k][j]);
}
}
}
}
}

String Cipher = new String(sb);


return Cipher;
}
MSCIT-7 Computer security practicals

public String DecryptColTrans(String s){

text = s;
int plen = [Link]();
int row = 2, col=0;
boolean flag = true;

if((plen%2) == 0)
col = plen/2;
else
col = (plen+1)/2;
matrix = new char[row][col];

int i,k,p = 0;
for (i = 0; i < col; i++) {
for (int j = 0; j < col; j++) {
if (key[j] == i) {
for (k = 0; k < row; k++) {
if(p<plen)
matrix[k][j] = [Link](p);

p++;
}
}
}
}

StringBuffer cb = new StringBuffer();

for(i=0;i<row;i++){
for(int j=0; j<col;j++){
if(matrix[i][j] != ' ')
[Link](matrix[i][j]);
}
}
String plain = new String(cb);
return plain;
}

[Link] a computer program that implements fast exponentiation(successive squaring) modulo


n.

package Practicals;

import [Link].*;
/**
*
* @author AyazPanar
*/
public class P07FastExpoMain {

public int FastExpo(int a,int b,int n){


MSCIT-7 Computer security practicals

long t=0,c=0;

if(b==0)
return 1;

t=FastExpo(a,b/2,n);
c=(t*t)%n;

if(b%2==1)
c=(c*a)%n;

[Link]("C = " + c + "\t T = " + t + "\t N = " + b);


return(int)c;
}
public static void main(String[] args) throws IOException{

P07FastExpoMain obj = new P07FastExpoMain();


BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

[Link]("Enter Base Value : ");


int a =[Link]([Link]());

[Link]("Enter Exponent Value : ");


int b =[Link]([Link]());

[Link]("Enter Mod Value : ");


int n =[Link]([Link]());

[Link]([Link](a, b, n));
}
}

[Link] a computer program that implements public key cryptography and RSA algoritham.

import [Link];
import [Link];

public class RSAExample {

private static final int BIT_LENGTH = 2048;

public static void main(String[] args) {


// Step 1: Generate public and private keys
KeyPair keyPair = generateKeyPair();

// Step 2: Encrypt a message


String message = "Hello, RSA!";
BigInteger encryptedMessage = encrypt(message, [Link]());

// Step 3: Decrypt the message


String decryptedMessage = decrypt(encryptedMessage, [Link]());

// Step 4: Print results


[Link]("Original Message: " + message);
MSCIT-7 Computer security practicals
[Link]("Encrypted Message: " + encryptedMessage);
[Link]("Decrypted Message: " + decryptedMessage);
}

private static KeyPair generateKeyPair() {


SecureRandom random = new SecureRandom();
BigInteger p = [Link](BIT_LENGTH / 2, random);
BigInteger q = [Link](BIT_LENGTH / 2, random);
BigInteger n = [Link](q);
BigInteger phi = [Link]([Link]).multiply([Link]([Link]));
BigInteger e = [Link](65537); // Commonly used public exponent
BigInteger d = [Link](phi);

PublicKey publicKey = new PublicKey(n, e);


PrivateKey privateKey = new PrivateKey(n, d);

return new KeyPair(publicKey, privateKey);


}

private static BigInteger encrypt(String message, PublicKey publicKey) {


BigInteger m = new BigInteger([Link]());
return [Link]([Link](), [Link]());
}

private static String decrypt(BigInteger encryptedMessage, PrivateKey privateKey) {


BigInteger decryptedMessage = [Link]([Link](),
[Link]());
return new String([Link]());
}

static class KeyPair {


private final PublicKey publicKey;
private final PrivateKey privateKey;

KeyPair(PublicKey publicKey, PrivateKey privateKey) {


[Link] = publicKey;
[Link] = privateKey;
}

PublicKey getPublicKey() {
return publicKey;
}

PrivateKey getPrivateKey() {
return privateKey;
}
}

static class PublicKey {


private final BigInteger modulus;
private final BigInteger exponent;

PublicKey(BigInteger modulus, BigInteger exponent) {


[Link] = modulus;
[Link] = exponent;
MSCIT-7 Computer security practicals
}

BigInteger getModulus() {
return modulus;
}

BigInteger getExponent() {
return exponent;
}
}

static class PrivateKey {


private final BigInteger modulus;
private final BigInteger exponent;

PrivateKey(BigInteger modulus, BigInteger exponent) {


[Link] = modulus;
[Link] = exponent;
}

BigInteger getModulus() {
return modulus;
}

BigInteger getExponent() {
return exponent;
}
}
}

[Link] a computer program that implements cryptographic hash function.

package Practicals;
import [Link].*;
import [Link].*;
import [Link].BASE64Encoder;

public class P09CryptoHashFunction {

private String filepath;

public P09CryptoHashFunction(String fpath)


{
filepath = fpath;
}
public String GenrateMessageDigest() throws Exception{

DigestInputStream in = null;

MessageDigest md = [Link]("MD5");

try{

in = new DigestInputStream(new FileInputStream(filepath),md);


}catch(FileNotFoundException fnfe){
MSCIT-7 Computer security practicals

[Link]("Error : Invalid File Path Or File Name ");


[Link](0);
}
byte[] buffer = new byte[8192];
int length;

while([Link](buffer) != -1);

byte[] raw = [Link]();

BASE64Encoder encoder = new BASE64Encoder();


String base64 = [Link](raw);

return base64;
}
}

10. write a menu driven program to implement


Digital signatures algoritham.
import [Link].*;
import [Link];

public class DigitalSignatureDemo {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

try {
KeyPair keyPair = generateKeyPair();

while (true) {
[Link]("1. Sign Message");
[Link]("2. Verify Signature");
[Link]("3. Exit");
[Link]("Choose an option: ");

int choice = [Link]();


[Link](); // Consume the newline character
MSCIT-7 Computer security practicals
switch (choice) {
case 1:
[Link]("Enter the message to sign: ");
String message = [Link]();
byte[] signature = signMessage(message, [Link]());
[Link]("Signature: " + bytesToHex(signature));
break;
case 2:
[Link]("Enter the message: ");
String originalMessage = [Link]();
[Link]("Enter the signature: ");
String signatureInput = [Link]();
boolean isVerified = verifySignature(originalMessage,
hexToBytes(signatureInput), [Link]());
if (isVerified) {
[Link]("Signature is valid!");
} else {
[Link]("Signature is invalid!");
}
break;
case 3:
[Link]("Exiting program.");
[Link](0);
default:
[Link]("Invalid choice. Please enter a valid option.");
}
}
} catch (Exception e) {
[Link]();
}
}

private static KeyPair generateKeyPair() throws NoSuchAlgorithmException {


MSCIT-7 Computer security practicals
KeyPairGenerator keyPairGenerator = [Link]("RSA");
[Link](2048);
return [Link]();
}

private static byte[] signMessage(String message, PrivateKey privateKey) throws Exception {


Signature signature = [Link]("SHA256withRSA");
[Link](privateKey);
[Link]([Link]());
return [Link]();
}

private static boolean verifySignature(String message, byte[] signature, PublicKey publicKey)


throws Exception {
Signature verifier = [Link]("SHA256withRSA");
[Link](publicKey);
[Link]([Link]());
return [Link](signature);
}

private static String bytesToHex(byte[] bytes) {


StringBuilder result = new StringBuilder();
for (byte b : bytes) {
[Link]([Link]("%02X", b));
}
return [Link]();
}

private static byte[] hexToBytes(String hex) {


int len = [Link]();
byte[] data = new byte[len / 2];
for (int i = 0; i < len; i += 2) {
data[i / 2] = (byte) (([Link]([Link](i), 16) << 4)
MSCIT-7 Computer security practicals
+ [Link]([Link](i + 1), 16));
}
return data;
}
}

You might also like