0% found this document useful (0 votes)
18 views20 pages

Encryption and Decryption Algorithms

This document contains programs to implement encryption and decryption algorithms including Caesar cipher, substitution cipher, Vigenere cipher, RC4 algorithm, and DES algorithm. It includes the Java/C code to perform encryption and decryption with these algorithms along with sample inputs, outputs, and explanations of the code. The programs were submitted as part of a course project for a master's degree in computer applications.

Uploaded by

aishwarya kalyan
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)
18 views20 pages

Encryption and Decryption Algorithms

This document contains programs to implement encryption and decryption algorithms including Caesar cipher, substitution cipher, Vigenere cipher, RC4 algorithm, and DES algorithm. It includes the Java/C code to perform encryption and decryption with these algorithms along with sample inputs, outputs, and explanations of the code. The programs were submitted as part of a course project for a master's degree in computer applications.

Uploaded by

aishwarya kalyan
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

Activity on

Information Security
Submitted in partial fulfillment of the requirements
for the award of degree

MASTER OF COMPUTER APPLICATIONS


Of
KLE TECHNOLOGICAL UNIVERSITY’s
[Link] College of Engineering and Technology
By

Aishwarya J Vantamutte( 02FE21MCA004)


Aishwarya Kalyan.( 02FE21MCA005)
Kiran Shelake(02FE21MCA020)
Vidyashree Kambar(02FE21MCA059)

Course in-charge

Prof. Aishwarya Hundekar


MCA Dept.

DEPARTMENT OF MASTER OF COMPUTER APPLICATIONS


KLE TECHNOLOGICAL UNIVERSITY’s
[Link] College of Engineering and Technology
Udyambag Belagavi, Karnataka.
April – 2023
1) Write a program to perform encryption and decryption using the following
algorithms:
a) Ceaser Cipher
import [Link];
public class CeaserCipher
{
public static void main(String[] args)
{
Scanner input = new Scanner([Link]);
[Link]("Enter the plaintext: ");
String plaintext = [Link]();
[Link]("Enter the key (a number from 1 to 25): ");
int key = [Link]();
String ciphertext = encrypt(plaintext, key);
[Link]("Ciphertext: " + ciphertext);
String decryptedText = decrypt(ciphertext, key);
[Link]("Decrypted Text: " + decryptedText);
}
public static String encrypt(String plaintext, int key)
{
StringBuilder ciphertext = new StringBuilder();
for (char c : [Link]())
{
if ([Link](c))
{
if ([Link](c))
{
[Link]((char) ((c - 'A' + key) % 26 + 'A'));
}
else
{
[Link]((char) ((c - 'a' + key) % 26 + 'a'));
}
}
else
{
[Link](c);
}
}
return [Link]();
}
public static String decrypt(String ciphertext, int key)
{
StringBuilder decryptedText = new StringBuilder();
for (char c : [Link]())
{
if ([Link](c))
{
if ([Link](c))
{
[Link]((char) ((c - 'A' - key + 26) % 26 + 'A'));
}
else
{
[Link]((char) ((c - 'a' - key + 26) % 26 + 'a'));
}
}
else
{
[Link](c);
}
}
return [Link]();
}
}
Output:
Enter the plaintext: Aishu
Enter the key (a number from 1 to 25): 12
Ciphertext: Muetg
Decrypted Text: Aishu

b) Substitution Cipher
import [Link];
import [Link];
import [Link];
public class SubstitutionCipher
{
private static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";
public static void main(String[] args)
{
Scanner input = new Scanner([Link]);
[Link]("Enter the plaintext: ");
String plaintext = [Link]();
[Link]("Enter the key (a string of 26 unique lowercase letters): ");
String key = [Link]();
String ciphertext = encrypt(plaintext, key);
[Link]("Ciphertext: " + ciphertext);
String decryptedText = decrypt(ciphertext, key);
[Link]("Decrypted Text: " + decryptedText);
}
public static String encrypt(String plaintext, String key)
{
Map<Character, Character> substitutionMap = new HashMap<>();
for (int i = 0; i < [Link](); i++)
{
[Link]([Link](i), [Link](i));
}
StringBuilder ciphertext = new StringBuilder();
for (char c : [Link]())
{
if ([Link](c))
{
char substituted = [Link]([Link](c));
if ([Link](c))
{
substituted = [Link](substituted);
}
[Link](substituted);
}
else
{
[Link](c);

}
}
return [Link]();
}
public static String decrypt(String ciphertext, String key)
{
Map<Character, Character> substitutionMap = new HashMap<>();
for (int i = 0; i < [Link](); i++)
{
[Link]([Link](i), [Link](i));
}
StringBuilder decryptedText = new StringBuilder();
for (char c : [Link]())
{
if ([Link](c))
{
char substituted = [Link]([Link](c));
if ([Link](c))
{
substituted = [Link](substituted);
}
[Link](substituted);
}
else {
[Link](c);
}
}
return [Link]();
}
}
Output:
Enter the plaintext: Info
Enter the key (a string of 26 unique lowercase letters): mnbvcxzlkjhgfdsapoiuytrewq
Ciphertext: Kdxs
Decrypted Text: Info

c) Vignere cipher
import [Link];
public class VigenereCipher
{
public static void main(String[] args)
{
Scanner input = new Scanner([Link]);
[Link]("Enter the plaintext: ");
String plaintext = [Link]();
[Link]("Enter the key (a string of characters): ");
String key = [Link]();
String ciphertext = encrypt(plaintext, key);
[Link]("Ciphertext: " + ciphertext);
String decryptedText = decrypt(ciphertext, key);
[Link]("Decrypted Text: " + decryptedText);
}
public static String encrypt(String plaintext, String key)
{
StringBuilder ciphertext = new StringBuilder();
int keyIndex = 0;
for (char c : [Link]())
{
if ([Link](c))
{
int shift = [Link](keyIndex) - 'a';
char substituted = shiftChar(c, shift);
[Link](substituted);
keyIndex = (keyIndex + 1) % [Link]();
}
else
{
[Link](c);
}
}
return [Link]();
}
public static String decrypt(String ciphertext, String key)
{
StringBuilder decryptedText = new StringBuilder();
int keyIndex = 0;
for (char c : [Link]())
{
if ([Link](c))
{
int shift = [Link](keyIndex) - 'a';
char substituted = shiftChar(c, -shift);
[Link](substituted);
keyIndex = (keyIndex + 1) % [Link]();
}
else
{
[Link](c);
}
}
return [Link]();
}
private static char shiftChar(char c, int shift)
{
if ([Link](c))
{
return (char) ('A' + (c - 'A' + shift + 26) % 26);
}
else {
return (char) ('a' + (c - 'a' + shift + 26) % 26);
}
}
}
Output:
Enter the plaintext: Secure
Enter the key (a string of characters): key
Ciphertext: Ciaevc
Decrypted Text: Secure

2) Write a C program to implement the RC4 algorithm logic


#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void rc4(unsigned char *plaintext, unsigned char *key, int plaintext_len, unsigned char
*ciphertext)
{
int i, j, k;
unsigned char S[256], T[256];

// Key Scheduling Algorithm


for (i = 0; i < 256; i++)
{
S[i] = i;
T[i] = key[i % strlen(key)];
}

j = 0;
for (i = 0; i < 256; i++)
{
j = (j + S[i] + T[i]) % 256;
// Swap values of S[i] and S[j]
unsigned char temp = S[i];
S[i] = S[j];
S[j] = temp;
}

// Pseudo-Random Generation Algorithm


i = j = 0;
for (k = 0; k < plaintext_len; k++)
{
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap values of S[i] and S[j]
unsigned char temp = S[i];
S[i] = S[j];
S[j] = temp;
// XOR plaintext with pseudo-random byte
ciphertext[k] = plaintext[k] ^ S[(S[i] + S[j]) % 256];
}
}
int main()
{
unsigned char plaintext[] = "Hello, world!";
unsigned char key[] = "secret";
int plaintext_len = strlen(plaintext);
unsigned char ciphertext[plaintext_len];
rc4(plaintext, key, plaintext_len, ciphertext);
printf("Plaintext: %s\n", plaintext);
printf("Ciphertext: ");
for (int i = 0; i < plaintext_len; i++)
{
printf("%02x", ciphertext[i]);
}
printf("\n");
return 0;
}
Output:
Plaintext: Hello, world!
Ciphertext: a553be70ed88f6d15db9d7b8d2

3) Write a Java program to implement the DES algorithm logic


import [Link];
import [Link];
import [Link];
import [Link];
import [Link].Base64;
public class DESExample {
public static void main(String[] args) throws Exception
{
String plaintext = "This is a test message.";
String keyString = "secretdeskey";
byte[] keyBytes = [Link]();
DESKeySpec keySpec = new DESKeySpec(keyBytes);
SecretKeyFactory keyFactory = [Link]("DES");
SecretKey key = [Link](keySpec);

Cipher cipher = [Link]("DES/ECB/PKCS5Padding");


[Link](Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = [Link]([Link]());
String encryptedText = [Link]().encodeToString(encryptedBytes);
[Link]("Encrypted text: " + encryptedText);

[Link](Cipher.DECRYPT_MODE, key);
byte[] decryptedBytes =[Link]([Link]().decode(encryptedText));
String decryptedText = new String(decryptedBytes);
[Link]("Decrypted text: " + decryptedText);
}
}

Output:
Encrypted text: H43+hmnCzCpWWJSrTB6W2w4TMDuotX7b
Decrypted text: This is a test message.

4) Using Java Cryptography, encrypt the text “Hello world” using BlowFish. Create
your own key using Java keytool.
➢ Sure, here are the steps to encrypt the text "Hello world" using BlowFish algorithm
and a custom key generated using Java keytool:
Step 1: Generate a Secret Key using Java KeytoolJava Keytool is a command- line t
ool that can generate cryptographic keys and certificates. Here, we'll use it to generate
a secret key for BlowFish encryption.
Open a terminal window and type the following command:
key tool -genkey -alias mykey -keyalg Blowfish -keysize 128 -storetype JCEKS -keystore
[Link]
This command will generate a new secret key with the alias mykey, using the BlowFish
algorithm with a key size of 128 bits. The key will be stored in a Java Cryptography
Extension KeyStore (JCEKS) format in the file [Link]. During this process, you will
be prompted to enter a password to protect the key store.
Step 2: Implement the Encryption in Java
Next, we'll write a Java program to encrypt the text "Hello world" using the BlowFish
algorithm and the secret key we generated in step 1.
Import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
public class BlowFishEncryption {
public static void main(String[] args) throws Exception
{
KeyStore ks = [Link]("JCEKS");
FileInputStream fis = new FileInputStream("[Link]");
[Link](fis, "keystore-password".toCharArray());
Key key = [Link]("mykey", "key-password".toCharArray());
String plaintext = "Hello world";
byte[] plaintextBytes = [Link](StandardCharsets.UTF_8);

Cipher cipher = [Link]("Blowfish/ECB/PKCS5Padding");


[Link](Cipher.ENCRYPT_MODE, new SecretKeySpec([Link](),
"Blowfish"));
byte[] ciphertextBytes = [Link](plaintextBytes);
[Link]([Link](ci
phertextBytes));
}
}
Step 3: Run the Java Program

Compile and run the Java program to encrypt the text "Hello world". The output will be a
hexadecimal string representing the encrypted text.
javac [Link]
java BlowFishEncryption
Output: C2E2C050D83FD116

5) Write a Java program to implement RSA Algoithm


import [Link];
import [Link];
public class RSA {
private final static BigInteger one = new BigInteger("1");
private final static SecureRandom random = new SecureRandom();
private BigInteger privateKey;
private BigInteger publicKey;
private BigInteger modulus;
// generate an N-bit (roughly) public and private key
public RSA(int N)
{
BigInteger p = [Link](N/2, random);
BigInteger q = [Link](N/2, random);
BigInteger phi = ([Link](one)).multiply([Link](one));
modulus = [Link](q);
publicKey = new BigInteger("65537");
// common value in practice = 2^16+1
privateKey = [Link](phi);
}
public BigInteger encrypt(BigInteger message)
{
return [Link](publicKey, modulus);
}
public BigInteger decrypt(BigInteger encrypted)
{
return [Link](privateKey, modulus);
}
public static void main(String[] args) {
int N = 1024;
RSA keypair = new RSA(N);
BigInteger message = new BigInteger("123456789");
BigInteger encrypted = [Link](message);
BigInteger decrypted = [Link](encrypted);
[Link]("Original message: " + message);
[Link]("Encrypted message: " + encrypted);
[Link]("Decrypted message: " + decrypted);
}
}

Output:
Original message: 123456789
Encrypted message:
4895022605174390876949854878055987974521778862663678143955606143682
0085761884622544762299006286604095683730075475192295988997179015644
2379787501437713126795032599574396738837391441505678956444749053636
9044961680475306722031251925920625403064531381094158785239887176458
0358085233994435541412188529030368922690
Decrypted message: 123456789
6) Implement the Diffie-Hellman Key Exchange mechanism using HTML and
JavaScript. Consider the end user as one of the parties (Alice) and the JavaScript
application as other party (bob).
<!DOCTYPE html>
<html>
<head>
<title>Diffie-Hellman Key Exchange</title>
<script type="text/javascript">
// Alice's variables
var aliceSecretKey;
var alicePublicKey;

// Bob's variables
var bobSecretKey;
var bobPublicKey;

// Shared variables
var sharedSecretKey;

function generateKeys() {
// Generate Alice's secret key
aliceSecretKey = [Link]([Link]() * 100) + 1;

// Generate Bob's secret key


bobSecretKey = [Link]([Link]() * 100) + 1;

// Generate Alice's public key


alicePublicKey = [Link](2, aliceSecretKey) % 97;

// Generate Bob's public key


bobPublicKey = [Link](2, bobSecretKey) % 97;

sharedSecretKey = [Link](bobPublicKey, aliceSecretKey) %97;


}

function displayKeys() {
[Link]("aliceSecretKey").innerHTML = aliceSecretKey;
[Link]("alicePublicKey").innerHTML = alicePublicKey;
[Link]("bobSecretKey").innerHTML = bobSecretKey;
[Link]("bobPublicKey").innerHTML = bobPublicKey;

[Link]("sharedSecretKey").innerHTML = sharedSecretKey;
}
</script>
</head>
<body>
<h1>Diffie-Hellman Key Exchange</h1>
<button onclick="generateKeys(); displayKeys();">Generate Keys</button>
<br><br>
<table>
<tr>
<th>Alice</th>
<th>Bob</th>
<th>Shared Secret Key</th>
</td>
<td>
Secrete Key:<span id=”aliceSecretKey”></span><br>
Public Key:<span id=”alicePublicKey”></span>
</td>
<td>
<span id=”sharedSecretKey”></span>
</td>
</tr>
</table>
</body>
</html>
Output:

7) Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
import [Link];
import [Link];

public class SHA1 {


public static void main(String[] args) {
String text = "Hello world";
try
{
MessageDigest sha1 = [Link]("SHA-1");
[Link]([Link]());
byte[] digest = [Link]();
StringBuilder sb = new StringBuilder();
for (byte b : digest) {
[Link]([Link]("%02x", b));
}
String sha1Hex = [Link]();
[Link]("SHA-1 message digest of \"" + text + "\": " + sha1Hex);
}
catch (NoSuchAlgorithmException e)
{
[Link]("SHA-1 algorithm not supported");
}
}
}
Output:
7b502c3a1f48c8609ae212cdfb639dee39673f5e

8) Explore the Intrusion Detection System “Snort”


Snort is a popular open-source Intrusion Detection System (IDS) that can monitor network
traffic for signs of suspicious activity and alert system administrators to potential security
threats. Snort is widely used by organizations and individuals to improve the security of their
networks and systems.
Here are some key features of Snort:
➢ Network packet capture: Snort can capture network packets and analyze them in real-
time, looking for signs of suspicious activity or malicious traffic.
➢ Packet analysis and logging: Snort can analyse packets and generate logs of the
traffic, which can be used for troubleshooting and forensic analysis.
➢ Protocol analysis: Snort can identify and analyse different network protocols,
including TCP, UDP, ICMP, HTTP, FTP, and others.
➢ Signature-based detection: Snort can use signatures to identify specific patterns of
network traffic that are associated with known threats.
➢ Anomaly-based detection: Snort can use statistical analysis to identify traffic patterns
that deviate from normal behaviour, which can be an indication of an attack.
➢ Customization: Snort is highly customizable, allowing users to create their own rules
and alerts based on their specific security requirements.
➢ Integration with other security tools: Snort can be integrated with other security tools,
such as firewalls and intrusion prevention systems, to provide a comprehensive
security solution.
Snort has a large and active user community that contributes to the development and
improvement of the software. Additionally, there are many third-party plugins and tools that
can be used to enhance the functionality of Snort.
Overall, Snort is a powerful and flexible IDS that can help organizations and individuals
detect and prevent security threats on their networks.
9) Study of Anti-Intrusion Technique – Honey pot
➢ A honeypot is a security technique that involves creating a network decoy that appears
to be an easy target for attackers, but in reality, it is designed to attract and detect
malicious activity. The concept of honeypots is based on the idea of deception, which
is used to lure attackers away from actual production systems and gather information
about their behaviour.
➢ A honeypot can be a virtual or physical network that is specifically designed to look
vulnerable and attractive to attackers. It can be deployed in several different ways,
including as a standalone system or as part of a larger network.
➢ When an attacker attempts to compromise a honeypot, they trigger an alert, which can
be used to alert system administrators of a potential security threat. In addition to
alerting system administrators, honeypots can be used to gather intelligence about
attackers, including their tactics and methods, which can be used to improve overall
security posture.
➢ There are several types of honeypots, including low-interaction honeypots and high-
interaction honeypots. Low-interaction honeypots emulate specific vulnerabilities or
services, while high-interaction honeypots are full-fledged systems that allow
attackers to interact with the system and provide more detailed information about the
attacker's behaviour.
Advantages of using honeypots:
➢ Early detection of potential security threats
➢ Gathering intelligence about attackers
➢ Diverting attackers away from actual production systems
➢ Improving overall security posture by identifying weaknesses and vulnerabilities in
existing systems
➢ Cost-effective security solution
Disadvantages to using honeypots:
➢ High maintenance costs
➢ Risk of false positives and false alarms
➢ The possibility of attackers using honeypots to launch attacks against actual
production systems.

10) Study of IP based Authentication


➢ IP-based authentication is a security mechanism that is used to grant or restrict
authentication method, the user's IP address is used to verify their identity instead of a
username and password combination.
➢ IP-based authentication is often used in conjunction with other security measures,
such as firewalls or VPNs, to provide an additional layer of security. By using IP-
based authentication, system administrators can limit access to specific IP addresses
or ranges of IP addresses, which can help to prevent unauthorized access to a network
or system.
➢ One of the main advantages of IP-based authentication is that it is a simple and easy-
to-implement security solution. It does not require any additional software or
hardware, and it can be set up quickly and easily.
➢ However, there are also some disadvantages to IP-based authentication. One of the
main drawbacks is that it is not a foolproof security solution, as IP addresses can be
easily spoofed or manipulated. In addition, IP-based authentication may not be
practical in situations where users are accessing a system from multiple locations or
devices.
➢ Overall, IP-based authentication can be an effective security mechanism when used in
conjunction with other security measures. It is a simple and easy-to- implement
solution, but it should not be relied upon as the sole means of securing a network or
system. System administrators should also consider using additional security
measures, such as strong passwords, two-factor authentication, or biometric
authentication, to provide a more comprehensive security solution.

Common questions

Powered by AI

RC4 is a stream cipher and processes data one byte at a time, while DES is a block cipher that works on fixed-size blocks of data, typically 64 bits. RSA is asymmetrical, using a pair of public and private keys, unlike the symmetric nature of RC4 and DES. RC4's simplicity and speed are contrasted by its lesser security compared to DES and RSA, which are designed for greater data integrity and confidentiality .

The Diffie-Hellman key exchange method securely allows two parties to establish a shared secret over an unsecured channel. Each party generates a public key from a private secret, exchanges the public keys, and then computes the shared secret using their private key and the received public key. The method ensures security by making it computationally difficult to derive the private keys from public keys due to the discrete logarithm problem .

Customization in Snort allows users to define specific signatures that match unique network traffic patterns, enabling precise detection of known threats. This flexibility in rule creation improves the effectiveness of its signature-based detection by allowing it to adapt to emerging threats and specific organizational needs. However, requires detailed knowledge to implement correctly .

SHA-1 is used to compute a fixed-size 160-bit hash value from input data. The process involves iterative rounds of bit manipulations and mathematical operations on the data. The significance lies in its ability to produce a unique digest for any input, ensuring data integrity by detecting changed data. However, due to vulnerabilities found in SHA-1, its use is being deprecated in favor of more secure algorithms .

Honeypots provide early detection of threats, gather intelligence on attacker behavior, divert attackers from real systems, and identify vulnerabilities, thus improving security posture. They are cost-effective and can provide in-depth insights into attack methods. However, honeypots have high maintenance costs and the risk of false positives. Additionally, there is a risk of attackers discovering the honeypots and potentially using them to attack legitimate systems .

Caesar Cipher uses a single key to shift all letters by the same amount, while Substitution Cipher uses a unique mapping of the alphabet defined by a key. Vigenere Cipher uses a sequence of shifts defined by a repeating keyword. The Caesar Cipher is simple and can be easily broken, while Substitution Cipher is more complex due to its larger keyspace. Vigenere Cipher adds complexity by varying the shift, making it more secure against frequency analysis compared to the other two .

Generating a cryptographic key with Java Keytool involves using a command to create a key within a keystore file, specifying details such as the algorithm (Blowfish) and key size. The key is secured with a password. The generated key can then be loaded in a Java program to initialize a Cipher object for encryption in the specific mode (e.g., Blowfish/ECB/PKCS5Padding).

Snort's high level of customization allows users to create specific rules and alerts based on individual security needs, making it highly adaptable to different network environments. This flexibility enhances its utility as an Intrusion Detection System by allowing integration with various security tools, thus providing a comprehensive security solution. However, it requires expert knowledge to optimize and manage effectively, which can be a limitation for some organizations .

Implementation of IP-based authentication should consider the ease of spoofing IP addresses, the need for additional security measures like firewalls or VPNs, and the limitations in scenarios where users access networks from multiple devices or locations. Although simple and easy to set up, it should not be relied upon solely, and should be supplemented with stronger authentication methods to enhance security .

RSA is more secure because it relies on the computational difficulty of factorizing large composite numbers, making it resistant to brute force attacks unlike simpler methods like Caesar Cipher. Symmetric methods like RC4 depend on secret keys that are vulnerable to interception. RSA's public and private key system enhances its security by not requiring sharing of the private key .

You might also like