0% found this document useful (0 votes)
9 views15 pages

datascience_da10

The document contains multiple Java programs implementing various cryptographic algorithms including Playfair Cipher, RSA, SHA-1, MD5, RC4, Digital Signature Standard, and AES key expansion. Each program demonstrates encryption, decryption, or hashing functionalities, showcasing how to handle user input and process data securely. The code snippets are structured to provide clear examples of each algorithm's implementation in Java.
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)
9 views15 pages

datascience_da10

The document contains multiple Java programs implementing various cryptographic algorithms including Playfair Cipher, RSA, SHA-1, MD5, RC4, Digital Signature Standard, and AES key expansion. Each program demonstrates encryption, decryption, or hashing functionalities, showcasing how to handle user input and process data securely. The code snippets are structured to provide clear examples of each algorithm's implementation in Java.
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
You are on page 1/ 15

2.

write a java program to perform encryption and decryption using the


following algorithm
(ii) playfair cipher
import java.util.*;

public class PlayfairCipher {


private char[][] keySquare = new char[5][5];
private String key;

public PlayfairCipher(String key) {


this.key = key;
generateKeySquare();
}

private void generateKeySquare() {


String alphabet = "ABCDEFGHIKLMNOPQRSTUVWXYZ"; // J is omitted
String keyString = key.toUpperCase().replaceAll("J", "I") + alphabet;
Set<Character> used = new LinkedHashSet<>();

for (char c : keyString.toCharArray()) {


if (Character.isLetter(c)) {
used.add(c);
}
}

Iterator<Character> it = used.iterator();
for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
keySquare[i][j] = it.next();
}
}
}
private String prepareText(String text) {
text = text.toUpperCase().replaceAll("J", "I").replaceAll("[^A-Z]", "");
StringBuilder prepared = new StringBuilder();

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


prepared.append(text.charAt(i));
if (i < text.length() - 1 && text.charAt(i) == text.charAt(i + 1)) {
prepared.append('X');
}
}

if (prepared.length() % 2 != 0) {
prepared.append('X');
}
return prepared.toString();
}

private String processDigraphs(String text, boolean encrypt) {


StringBuilder result = new StringBuilder();
text = prepareText(text);

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


char a = text.charAt(i);
char b = text.charAt(i + 1);
int[] posA = findPosition(a);
int[] posB = findPosition(b);

if (posA[0] == posB[0]) { // Same row


result.append(keySquare[posA[0]][(posA[1] + (encrypt ? 1 : 4)) % 5]);
result.append(keySquare[posB[0]][(posB[1] + (encrypt ? 1 : 4)) % 5]);
} else if (posA[1] == posB[1]) { // Same column
result.append(keySquare[(posA[0] + (encrypt ? 1 : 4)) % 5][posA[1]]);
result.append(keySquare[(posB[0] + (encrypt ? 1 : 4)) % 5][posB[1]]);
} else { // Rectangle swap
result.append(keySquare[posA[0]][posB[1]]);
result.append(keySquare[posB[0]][posA[1]]);
}
}
return result.toString();
}

private int[] findPosition(char c) {


for (int i = 0; i < 5; i++) {
for (int j = 0; j < 5; j++) {
if (keySquare[i][j] == c) {
return new int[]{i, j};
}
}
}
return null;
}

public String encrypt(String text) {


return processDigraphs(text, true);
}

public String decrypt(String text) {


return processDigraphs(text, false);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter key: ");
String key = scanner.nextLine();

PlayfairCipher cipher = new PlayfairCipher(key);

System.out.print("Enter message: ");


String message = scanner.nextLine();

String encrypted = cipher.encrypt(message);


System.out.println("Encrypted: " + encrypted);

String decrypted = cipher.decrypt(encrypted);


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

scanner.close();
}
}

3. Write a program to implement RSA algorithm.

import java.math.BigInteger;
import java.util.Random;
import java.util.Scanner;

public class RSAAlgorithm {


private BigInteger p, q, n, phi, e, d;
private int bitLength = 1024;
private Random rand;

public RSAAlgorithm() {
rand = new Random();
p = BigInteger.probablePrime(bitLength / 2, rand);
q = BigInteger.probablePrime(bitLength / 2, rand);
n = p.multiply(q);
phi = p.subtract(BigInteger.ONE).multiply(q.subtract(BigInteger.ONE));
e = BigInteger.probablePrime(bitLength / 2, rand);

while (phi.gcd(e).compareTo(BigInteger.ONE) > 0 && e.compareTo(phi) < 0)


{
e = BigInteger.probablePrime(bitLength / 2, rand);
}
d = e.modInverse(phi);
}

public BigInteger encrypt(BigInteger message) {


return message.modPow(e, n);
}

public BigInteger decrypt(BigInteger encrypted) {


return encrypted.modPow(d, n);
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
RSAAlgorithm rsa = new RSAAlgorithm();

System.out.println("Public Key: (" + rsa.e + ", " + rsa.n + ")");


System.out.println("Private Key: (" + rsa.d + ", " + rsa.n + ")");

System.out.print("Enter message (numeric): ");


BigInteger message = scanner.nextBigInteger();

BigInteger encrypted = rsa.encrypt(message);


System.out.println("Encrypted: " + encrypted);
BigInteger decrypted = rsa.decrypt(encrypted);
System.out.println("Decrypted: " + decrypted);

scanner.close();
}
}

4. calculate message digest of a text using SHA -1 algorithm in JAVA


import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

public class SHA1Digest {


public static String calculateSHA1(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(e);
}
}

public static void main(String[] args) {


Scanner scanner = new Scanner(System.in);
System.out.print("Enter text: ");
String text = scanner.nextLine();

String sha1Hash = calculateSHA1(text);


System.out.println("SHA-1 Digest: " + sha1Hash);

scanner.close();
}
}

5. Calculate message digest of a text using MD5 algorithm in JAVA

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;

public class MD5Digest {


public static String calculateMD5(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(e);
}
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter text: ");
String text = scanner.nextLine();

String md5Hash = calculateMD5(text);


System.out.println("MD5 Digest: " + md5Hash);

scanner.close();
}
}

8. Implement RC4 algorithm and check the following input using java
Enter plaintext : hello
Enter key of same length : yello
plaintext in bytes : 104 101 108 108 111
keystream is : 248 30 202 165 16
Cipher text is : 144 123 166 201 127
Plaintext after decryption : 104 101 108 108 111

import java.util.Scanner;

public class RC4Cipher {


private byte[] S = new byte[256];
private int i, j;

public RC4Cipher(String key) {


byte[] keyBytes = key.getBytes();
initializeSBox(keyBytes);
}
private void initializeSBox(byte[] key) {
for (i = 0; i < 256; i++) {
S[i] = (byte) i;
}
j = 0;
for (i = 0; i < 256; i++) {
j = (j + S[i] + key[i % key.length]) & 0xFF;
swap(i, j);
}
i = j = 0;
}

private void swap(int a, int b) {


byte temp = S[a];
S[a] = S[b];
S[b] = temp;
}

private byte getKeystreamByte() {


i = (i + 1) & 0xFF;
j = (j + S[i]) & 0xFF;
swap(i, j);
return S[(S[i] + S[j]) & 0xFF];
}

public byte[] encryptDecrypt(byte[] input) {


byte[] output = new byte[input.length];
for (int k = 0; k < input.length; k++) {
output[k] = (byte) (input[k] ^ getKeystreamByte());
}
return output;
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);

System.out.print("Enter plaintext: ");


String plaintext = scanner.nextLine();

System.out.print("Enter key of same length: ");


String key = scanner.nextLine();

if (plaintext.length() != key.length()) {
System.out.println("Error: Key length must be the same as plaintext
length.");
scanner.close();
return;
}

RC4Cipher rc4 = new RC4Cipher(key);


byte[] plaintextBytes = plaintext.getBytes();

System.out.print("Plaintext in bytes: ");


for (byte b : plaintextBytes) {
System.out.print((b & 0xFF) + " ");
}
System.out.println();

byte[] cipherBytes = rc4.encryptDecrypt(plaintextBytes);

System.out.print("Cipher text is: ");


for (byte b : cipherBytes) {
System.out.print((b & 0xFF) + " ");
}
System.out.println();

RC4Cipher rc4Decrypt = new RC4Cipher(key);


byte[] decryptedBytes = rc4Decrypt.encryptDecrypt(cipherBytes);

System.out.print("Plaintext after decryption: ");


for (byte b : decryptedBytes) {
System.out.print((b & 0xFF) + " ");
}
System.out.println();

scanner.close();
}
}

9. Implement the SIGNATURE SCHEME - Digital Signature Standard.

import java.security.*;
import java.util.Base64;
import java.util.Scanner;

public class DigitalSignatureDSS {

public static KeyPair generateKeyPair() throws NoSuchAlgorithmException {


KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");
keyPairGen.initialize(1024);
return keyPairGen.generateKeyPair();
}

public static byte[] signData(String data, PrivateKey privateKey) throws


Exception {
Signature signature = Signature.getInstance("SHA1withDSA");
signature.initSign(privateKey);
signature.update(data.getBytes());
return signature.sign();
}

public static boolean verifySignature(String data, byte[] signatureBytes,


PublicKey publicKey) throws Exception {
Signature signature = Signature.getInstance("SHA1withDSA");
signature.initVerify(publicKey);
signature.update(data.getBytes());
return signature.verify(signatureBytes);
}

public static void main(String[] args) {


try {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter message: ");
String message = scanner.nextLine();

KeyPair keyPair = generateKeyPair();


byte[] signatureBytes = signData(message, keyPair.getPrivate());

System.out.println("Generated Signature: " +


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

boolean isVerified = verifySignature(message, signatureBytes,


keyPair.getPublic());
System.out.println("Signature Verification: " + (isVerified ? "Valid" :
"Invalid"));

scanner.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}

10. Generate first five keys for the initial key : ThisIsA128BitKey in AES
algorithm using java.
sample output:
Round 0: 54684973497341313238624B657921
Round 1: 96392E2B8BDE6E8A3C5C36E5A7D441D3
Round 2: 0FEF946C7D6DBD592C019D928E72E5E1
Round 3: 27341A879D8389E63F65F2B041D4D0B3
Round 4: D0BCE5E63C05A9D2B2A5E4D73A2DFB6F
Round 5: 92E87DF5A1D457FA12F5D4BC8A374D5A

import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

public class AESKeyExpansion {


private static final int KEY_SIZE = 16; // 128-bit key
private static final int NUM_ROUNDS = 5;
private static final byte[] RCON = {
(byte) 0x01, (byte) 0x02, (byte) 0x04, (byte) 0x08, (byte) 0x10
};

public static void main(String[] args) {


byte[] key = "ThisIsA128BitKey".getBytes();
byte[][] expandedKeys = keyExpansion(key);

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


System.out.print("Round " + i + ": ");
for (byte b : expandedKeys[i]) {
System.out.printf("%02X", b);
}
System.out.println();
}
}

private static byte[][] keyExpansion(byte[] key) {


byte[][] expandedKeys = new byte[NUM_ROUNDS + 1][KEY_SIZE];
System.arraycopy(key, 0, expandedKeys[0], 0, KEY_SIZE);

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


byte[] temp = Arrays.copyOf(expandedKeys[i - 1], KEY_SIZE);
keyScheduleCore(temp, i - 1);
for (int j = 0; j < KEY_SIZE; j++) {
expandedKeys[i][j] = (byte) (expandedKeys[i - 1][j] ^ temp[j]);
}
}
return expandedKeys;
}

private static void keyScheduleCore(byte[] key, int round) {


byte temp = key[0];
System.arraycopy(key, 1, key, 0, 3);
key[3] = temp;

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


key[i] = sBox(key[i]);
}
key[0] ^= RCON[round];
}
private static byte sBox(byte input) {
int[] sbox = {
0x63, 0x7c, 0x77, 0x7b, 0xf2, 0x6b, 0x6f, 0xc5, 0x30, 0x01, 0x67,
0x2b, 0xfe, 0xd7, 0xab, 0x76
};
return (byte) sbox[input & 0x0F];
}
}

You might also like