0% found this document useful (0 votes)
3 views13 pages

Is Lab Remaining Syllabus Programs

The document contains Java implementations of various cryptographic algorithms and techniques, including symmetric ciphers (AES and RC4), RSA-based digital signatures, random alphanumeric string generation, subset sum problem, MD5 hash authentication, and the ElGamal cryptosystem. Each section provides code examples, explanations of the algorithms, and notes on their usage. The implementations demonstrate key generation, encryption, decryption, and signature verification processes.

Uploaded by

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

Is Lab Remaining Syllabus Programs

The document contains Java implementations of various cryptographic algorithms and techniques, including symmetric ciphers (AES and RC4), RSA-based digital signatures, random alphanumeric string generation, subset sum problem, MD5 hash authentication, and the ElGamal cryptosystem. Each section provides code examples, explanations of the algorithms, and notes on their usage. The implementations demonstrate key generation, encryption, decryption, and signature verification processes.

Uploaded by

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

Program Number is as per IS LAB syllabus.

1. Implementation of symmetric cipher algorithm(AES and RC4)

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.util.Base64;

public class CommonCryptoTemplate {

public static void main(String[] args) throws Exception {

// Choose algorithm: "AES" or "RC4"


String algorithm = "AES"; // change to "RC4" when needed

// Generate a secret key for the chosen algorithm


KeyGenerator keyGen = KeyGenerator.getInstance(algorithm);
if (algorithm.equals("AES"))
keyGen.init(128); // AES requires fixed key size (128/192/256)
SecretKey secretKey = keyGen.generateKey();

// Create Cipher instance


Cipher cipher = Cipher.getInstance(algorithm);

// Sample plaintext
String plaintext = "Hello from Information Security Lab!";

// Encrypt
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
String encryptedText = Base64.getEncoder().encodeToString(encryptedBytes);
System.out.println("Algorithm Used : " + algorithm);
System.out.println("Original Text : " + plaintext);
System.out.println("Encrypted Text : " + encryptedText);

// Decrypt
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(encryptedText));
String decryptedText = new String(decryptedBytes);
System.out.println("Decrypted Text : " + decryptedText);
}
}
For AES, keep
String algorithm = "AES";

For RC4, change to


String algorithm = "RC4";

(Note: RC4 is supported as "RC4" or "ARCFOUR" depending on your JDK version — if "RC4" gives
an error, try "ARCFOUR".)
RC4 Key Size Details
 RC4 supports variable key lengths — typically from 40 bits up to 2048 bits.
 However, most practical implementations (and Java’s KeyGenerator) usually use:
o 128 bits (16 bytes) — common, secure default
o Or 40 bits (5 bytes) — for legacy systems

2. Program for Random Number Generation using a subset of digits and alphabets.

import java.util.Random;

public class RandomAlphanumericGenerator {

// Define subset of characters (digits + letters)


private static final String CHAR_SUBSET = "1357924680ACEGIKZ"; // Example subset

public static String generateRandomString(int length) {


Random random = new Random();
StringBuilder sb = new StringBuilder(length);

for (int i = 0; i < length; i++) {


int index = random.nextInt(CHAR_SUBSET.length());
sb.append(CHAR_SUBSET.charAt(index));
}

return sb.toString();
}

public static void main(String[] args) {


int length = 6;

String randomCode = generateRandomString(length);


System.out.println("Random Alphanumeric Code: " + randomCode);
}
}

Output:

3. A Java program for implementation of RSA based signature system.

RSA-based digital signature system, includes:

1. Key pair generation (public/private key)


2. Signing a message
3. Verifying the signature

It uses Java's built-in java.security libraries to accomplish this.

import java.security.*;

import java.util.Base64;
public class RSASignatureDemo {

// Method to generate RSA key pair

public static KeyPair generateRSAKeyPair() throws NoSuchAlgorithmException {

KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");

keyGen.initialize(2048); // You can use 1024 or 4096 depending on security


requirements

return keyGen.generateKeyPair();

// Method to sign a message using a private key

public static String signMessage(String message, PrivateKey privateKey) throws


Exception {

Signature signature = Signature.getInstance("SHA256withRSA");

signature.initSign(privateKey);

signature.update(message.getBytes("UTF-8"));

byte[] signatureBytes = signature.sign();

return Base64.getEncoder().encodeToString(signatureBytes);

// Method to verify the signature using a public key

public static boolean verifySignature(String message, String signatureStr, PublicKey


publicKey) throws Exception {

Signature signature = Signature.getInstance("SHA256withRSA");

signature.initVerify(publicKey);

signature.update(message.getBytes("UTF-8"));

byte[] signatureBytes = Base64.getDecoder().decode(signatureStr);


return signature.verify(signatureBytes);

public static void main(String[] args) {

try {

// 1. Generate RSA key pair

KeyPair keyPair = generateRSAKeyPair();

PublicKey publicKey = keyPair.getPublic();

PrivateKey privateKey = keyPair.getPrivate();

// 2. Define a message

String message = "This is a confidential message.";

// 3. Sign the message

String digitalSignature = signMessage(message, privateKey);

System.out.println("Digital Signature (Base64):\n" + digitalSignature);

// 4. Verify the signature

boolean isCorrect = verifySignature(message, digitalSignature, publicKey);

System.out.println("\nSignature verification result: " + (isCorrect ? "VALID" :


"INVALID"));

} catch (Exception e) {

e.printStackTrace();

}
}

Output:

Explanation:

 KeyPairGenerator: Generates RSA public/private keys.


 Signature class: Used to compute and verify the digital signature.
 Uses SHA-256 hashing with RSA encryption (SHA256withRSA), which is secure and
commonly used.
 The signature is encoded/decoded using Base64 for easy display and transmission.

4. Implementation of subset sum using Java.

Given a set of integers and a sum value, determine if there's a subset of the given set with a sum equal
to the given sum.

Given a set of integers and a sum value, determine if there's a subset of the given set with a
sum equal to the given sum.

public class SubsetSum {

// Returns true if there is a subset of set[] with sum equal to given sum

public static boolean isSubsetSum(int[] set, int sum) {

int n = set.length;

boolean[][] dp = new boolean[n + 1][sum + 1];

// If sum is 0, answer is true (empty subset)

for (int i = 0; i <= n; i++) {

dp[i][0] = true;

}
// If sum is not 0 and set is empty, answer is false

for (int j = 1; j <= sum; j++) {

dp[0][j] = false;

// Fill the subset table in bottom-up manner

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= sum; j++) {

if (set[i - 1] > j) {

dp[i][j] = dp[i - 1][j]; // Can't include current element

} else {

dp[i][j] = dp[i - 1][j] || dp[i - 1][j - set[i - 1]];

return dp[n][sum];

public static void main(String[] args) {

int[] set = {34, 14, 12, 5, 2};

int sum = 19;

if (isSubsetSum(set, sum)) {

System.out.println("Found a subset with given sum " + sum);


} else {

System.out.println("No subset with given sum " + sum);

Output:

Explanation:

 We use a 2D boolean DP table dp where dp[i][j] will be true if there is a subset of


the first i elements in the array that sums to j.
 The answer is dp[n][sum] where n is the total number of elements.

5. A java program for authenticating the given signature using MD5 hash Algorithm.

This program authenticates (verifies) a signature by comparing the MD5 hash of some data
with a given signature hash.

Here’s a simple example where:

 You take an input message (like a string).


 Compute its MD5 hash.
 Compare it to a given MD5 hash signature.
 If they match, authentication passes.

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

public class MD5SignatureAuth {

// Method to compute MD5 hash of a string and return it as hex

public static String getMD5Hash(String input) {

try {
MessageDigest md = MessageDigest.getInstance("MD5");

byte[] messageDigest = md.digest(input.getBytes());

// Convert byte array into signum representation

StringBuilder hexString = new StringBuilder();

for (byte b : messageDigest) {

String hex = Integer.toHexString(0xff & b);

if (hex.length() == 1) hexString.append('0'); // Pad with zero

hexString.append(hex);

return hexString.toString();

} catch (NoSuchAlgorithmException e) {

throw new RuntimeException(e);

// Method to authenticate given data against a signature hash

public static boolean authenticate(String data, String givenSignature) {

String computedHash = getMD5Hash(data);

return computedHash.equalsIgnoreCase(givenSignature);

public static void main(String[] args) {

String data = "Hello, this is a message!";


String signature = "b4a9812a18f7a8f5947efc3ea4944a3a"; // Example MD5 hash of the
data

if (data.startsWith("'") && data.endsWith("'"))

data = data.substring(1, data.length() - 1);

System.out.println("Data string: '" + data + "'");

System.out.println("Length: " + data.length());

String computedHash = getMD5Hash(data);

System.out.println("Computed MD5 hash: " + computedHash);

System.out.println("Given signature: " + signature);

boolean isAuthentic = authenticate(data, signature);

if (isAuthentic) {

System.out.println("Signature verified. Authentication successful.");

} else {

System.out.println("Signature verification failed. Authentication unsuccessful.");

Output:
G:\IS\cns programs>java MD5SignatureAuth

Data string: 'Hello, this is a message!'

Length: 25

Computed MD5 hash: b4a9812a18f7a8f5947efc3ea4944a3a

Given signature: b4a9812a18f7a8f5947efc3ea4944a3a

Signature verified. Authentication successful.

7.Implementation of Elgamal Cryptosystem

This example includes key generation, encryption, and decryption. The code uses
BigInteger for handling large numbers and modular arithmetic, which is essential for
ElGamal.

What ElGamal needs:

 A large prime ppp


 A generator ggg of the multiplicative group mod ppp
 Private key xxx, randomly chosen from [1,p−2][1, p-2][1,p−2]
 Public key y=gxmod py = g^x \mod py=gxmodp

ElGamal encryption of message mmm:

 Choose random k∈[1,p−2]k \in [1, p-2]k∈[1,p−2]


 Compute c1=gkmod pc_1 = g^k \mod pc1=gkmodp
 Compute c2=m×ykmod pc_2 = m \times y^k \mod pc2=m×ykmodp
 Ciphertext is pair (c1,c2)(c_1, c_2)(c1,c2)

ElGamal decryption of ciphertext (c1,c2)(c_1, c_2)(c1,c2):

 Compute s=c1xmod ps = c_1^x \mod ps=c1xmodp


 Compute m=c2×s−1mod pm = c_2 \times s^{-1} \mod pm=c2×s−1modp (where
s−1s^{-1}s−1 is modular inverse of sss)
import java.math.BigInteger;
import java.security.SecureRandom;

public class ElGamal {

private BigInteger p; // large prime


private BigInteger g; // generator
private BigInteger x; // private key
private BigInteger y; // public key
private SecureRandom random;

public ElGamal(int bitLength) {


random = new SecureRandom();
// Generate a large prime p
p = BigInteger.probablePrime(bitLength, random);
// Choose g such that 1 < g < p-1
g = new BigInteger(bitLength - 1, random);
while (g.compareTo(BigInteger.ONE) <= 0 || g.compareTo(p.subtract(BigInteger.ONE))
>= 0) {
g = new BigInteger(bitLength - 1, random);
}
// Private key x: random in [1, p-2]
x = new BigInteger(bitLength - 2, random);
while (x.compareTo(BigInteger.ONE) < 0 || x.compareTo(p.subtract(BigInteger.TWO))
> 0) {
x = new BigInteger(bitLength - 2, random);
}
// Public key y = g^x mod p
y = g.modPow(x, p);
}

// Getters for public parameters


public BigInteger getP() { return p; }
public BigInteger getG() { return g; }
public BigInteger getY() { return y; }
public BigInteger getX() { return x; } // private key, keep secret

// Encryption: input message m < p


public BigInteger[] encrypt(BigInteger m) {
if (m.compareTo(p) >= 0) {
throw new IllegalArgumentException("Message too large");
}

// Random k in [1, p-2]


BigInteger k = new BigInteger(p.bitLength() - 2, random);
while (k.compareTo(BigInteger.ONE) < 0 || k.compareTo(p.subtract(BigInteger.TWO))
> 0) {
k = new BigInteger(p.bitLength() - 2, random);
}

BigInteger c1 = g.modPow(k, p);


BigInteger c2 = (m.multiply(y.modPow(k, p))).mod(p);

return new BigInteger[]{c1, c2};


}

// Decryption
public BigInteger decrypt(BigInteger c1, BigInteger c2) {
BigInteger s = c1.modPow(x, p);
BigInteger sInv = s.modInverse(p);
BigInteger m = (c2.multiply(sInv)).mod(p);
return m;
}

public static void main(String[] args) {


int bitLength = 512; // size of prime in bits
ElGamal elgamal = new ElGamal(bitLength);

System.out.println("Public parameters:");
System.out.println("p = " + elgamal.getP());
System.out.println("g = " + elgamal.getG());
System.out.println("y = " + elgamal.getY());
System.out.println();

// Example message as BigInteger (should be < p)


BigInteger message = new BigInteger("1234567890");
System.out.println("Original message: " + message);

BigInteger[] ciphertext = elgamal.encrypt(message);


System.out.println("Ciphertext:");
System.out.println("c1 = " + ciphertext[0]);
System.out.println("c2 = " + ciphertext[1]);

BigInteger decrypted = elgamal.decrypt(ciphertext[0], ciphertext[1]);


System.out.println("Decrypted message: " + decrypted);

if (message.equals(decrypted)) {
System.out.println("Decryption successful, message matches.");
} else {
System.out.println("Decryption failed.");
}
}
}

Notes:

 This example uses a random prime and random generator ggg, which is usually more
complex in real cryptographic systems where ggg is a known generator of a subgroup.
 The message mmm must be a BigInteger less than ppp.
 The message here is a number — if you want to encrypt arbitrary text, you’ll need to
convert it into a BigInteger (e.g., via byte arrays).
 For simplicity, the code prints everything. In practice, private keys should never be
printed.

Output:

You might also like