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

1 (A) Implementing Symmetric Key Algorithms - DES

The document provides implementations of various cryptographic algorithms including symmetric key algorithms (DES and AES), asymmetric key algorithms (RSA), key exchange algorithms (Diffie-Hellman), message digest calculation (SHA-1), and digital signature creation (Digital Signature Standard). Each section includes code examples in Java and JavaScript demonstrating how to encrypt, decrypt, and generate keys and signatures. The implementations cover both theoretical concepts and practical coding applications for secure data transmission.
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)
28 views15 pages

1 (A) Implementing Symmetric Key Algorithms - DES

The document provides implementations of various cryptographic algorithms including symmetric key algorithms (DES and AES), asymmetric key algorithms (RSA), key exchange algorithms (Diffie-Hellman), message digest calculation (SHA-1), and digital signature creation (Digital Signature Standard). Each section includes code examples in Java and JavaScript demonstrating how to encrypt, decrypt, and generate keys and signatures. The implementations cover both theoretical concepts and practical coding applications for secure data transmission.
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

1(a) Implementing symmetric key algorithms -DES

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.KeyGenerator;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.SecretKey;

import java.util.Base64; // For better output formatting

public class DES {

public static void main(String[] argv) {

try {

System.out.println("Message Encryption Using DES Algorithm\n------");

// Initialize the KeyGenerator for DES

KeyGenerator keygenerator = KeyGenerator.getInstance("DES");

SecretKey myDesKey = keygenerator.generateKey();

// Initialize Cipher object for DES encryption (with ECB mode and PKCS5Padding)

Cipher desCipher = Cipher.getInstance("DES/ECB/PKCS5Padding");

// Initialize the cipher for encryption mode

desCipher.init(Cipher.ENCRYPT_MODE, myDesKey);

// Input message
byte[] text = "Secret Information ".getBytes();

// Print original message (in byte and string format)

System.out.println("Message [Byte Format] : " + Base64.getEncoder().encodeToString(text));

System.out.println("Message : " + new String(text));

// Perform encryption

byte[] textEncrypted = desCipher.doFinal(text);

System.out.println("Encrypted Message (Base64) : " +


Base64.getEncoder().encodeToString(textEncrypted));

// Initialize the cipher for decryption mode

desCipher.init(Cipher.DECRYPT_MODE, myDesKey);

// Perform decryption

byte[] textDecrypted = desCipher.doFinal(textEncrypted);

System.out.println("Decrypted Message: " + new String(textDecrypted));

} catch (NoSuchAlgorithmException e) {

e.printStackTrace();

} catch (NoSuchPaddingException e) {

e.printStackTrace();

} catch (InvalidKeyException e) {

e.printStackTrace();

} catch (IllegalBlockSizeException e) {

e.printStackTrace();

} catch (BadPaddingException e) {

e.printStackTrace();
}

1(b). Implementing symmetric key algorithms - AES

import java.io.UnsupportedEncodingException;

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;

// Method to set the key for AES

public static void setKey(String myKey) {

MessageDigest sha = null;

try {

key = myKey.getBytes("UTF-8"); // Convert the string to bytes using UTF-8 encoding

sha = MessageDigest.getInstance("SHA-1"); // SHA-1 hashing

key = sha.digest(key); // Apply SHA-1 to the key

key = Arrays.copyOf(key, 16); // Use only the first 16 bytes for AES-128

secretKey = new SecretKeySpec(key, "AES"); // Create AES key


} catch (NoSuchAlgorithmException | UnsupportedEncodingException e) {

e.printStackTrace();

// Encrypt method using AES

public static String encrypt(String strToEncrypt, String secret) {

try {

setKey(secret); // Set the AES key

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // AES algorithm with ECB


mode and PKCS5 padding

cipher.init(Cipher.ENCRYPT_MODE, secretKey); // Initialize the cipher for encryption

byte[] encryptedBytes = cipher.doFinal(strToEncrypt.getBytes("UTF-8")); // Encrypt the string

return Base64.getEncoder().encodeToString(encryptedBytes); // Return the encrypted string


in Base64 format

} catch (Exception e) {

System.out.println("Error while encrypting: " + e.toString());

return null;

// Decrypt method using AES

public static String decrypt(String strToDecrypt, String secret) {

try {

setKey(secret); // Set the AES key

Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding"); // AES algorithm with ECB


mode and PKCS5 padding

cipher.init(Cipher.DECRYPT_MODE, secretKey); // Initialize the cipher for decryption


byte[] decryptedBytes = cipher.doFinal(Base64.getDecoder().decode(strToDecrypt)); //
Decrypt the Base64 string

return new String(decryptedBytes, "UTF-8"); // Return the decrypted string

} catch (Exception e) {

System.out.println("Error while decrypting: " + e.toString());

return null;

public static void main(String[] args) {

// Secret key to be used for encryption and decryption

final String secretKey = "annaUniversity";

String originalString = "www.annauniv.edu"; // String to be encrypted

// Encrypt the original string

String encryptedString = AES.encrypt(originalString, secretKey);

// Decrypt the encrypted string

String decryptedString = AES.decrypt(encryptedString, secretKey);

// Print results

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);

}
2(a) Implementing asymmetric key algorithms

<!DOCTYPE html>

<html lang="en">

<head>

<meta charset="UTF-8">

<meta name="viewport" content="width=device-width, initial-scale=1.0">

<title>RSA Encryption</title>

</head>

<body>

<center>

<h1>RSA Algorithm</h1>

<h2>Implemented Using HTML & Javascript</h2>

<hr>

<table>

<tr>

<td>Enter First Prime Number:</td>

<td><input type="number" value="53" id="p"></td>

</tr>

<tr>

<td>Enter Second Prime Number:</td>

<td><input type="number" value="59" id="q"></td>

</tr>

<tr>

<td>Enter the Message (cipher text):<br>[A=1, B=2,...]</td>

<td><input type="number" value="89" id="msg"></td>

</tr>
<tr>

<td>Public Key (n):</td>

<td><p id="publickey"></p></td>

</tr>

<tr>

<td>Exponent (e):</td>

<td><p id="exponent"></p></td>

</tr>

<tr>

<td>Private Key (d):</td>

<td><p id="privatekey"></p></td>

</tr>

<tr>

<td>Cipher Text:</td>

<td><p id="ciphertext"></p></td>

</tr>

<tr>

<td><button onclick="RSA();">Apply RSA</button></td>

</tr>

</table>

</center>

<script type="text/javascript">

function RSA() {

var gcd, p, q, no, n, t, e, d, ct;

// GCD function to calculate greatest common divisor


gcd = function (a, b) { return (!b) ? a : gcd(b, a % b); };

// Fetch values from input fields

p = parseInt(document.getElementById('p').value);

q = parseInt(document.getElementById('q').value);

no = parseInt(document.getElementById('msg').value);

// Calculate n and t (Euler's Totient Function)

n = p * q;

t = (p - 1) * (q - 1);

// Find the public exponent e such that 1 < e < t and gcd(e, t) = 1

for (e = 2; e < t; e++) {

if (gcd(e, t) == 1) {

break;

// Find the private exponent d such that (d * e) % t = 1

for (d = 2; d < t; d++) {

if ((d * e) % t == 1) {

break;

// RSA encryption: ct = (no ^ e) % n

ct = modExp(no, e, n);
// Display results

document.getElementById('publickey').innerHTML = "n = " + n;

document.getElementById('exponent').innerHTML = "e = " + e;

document.getElementById('privatekey').innerHTML = "d = " + d;

document.getElementById('ciphertext').innerHTML = "Cipher Text: " + ct;

// Function to perform modular exponentiation (base^exp % mod)

function modExp(base, exp, mod) {

var result = 1;

base = base % mod;

while (exp > 0) {

if (exp % 2 === 1) {

result = (result * base) % mod;

exp = Math.floor(exp / 2);

base = (base * base) % mod;

return result;

</script>

</body>

</html>
2(b) Implementing Key exchange algorithms

public class DiffieHellman {

// Modular exponentiation function to calculate (base^exp) % mod

public static int modExp(int base, int exp, int mod) {

int result = 1;

base = base % mod; // Handle case where base is larger than mod

while (exp > 0) {

if (exp % 2 == 1) {

result = (result * base) % mod;

exp = exp >> 1; // Right shift exponent by 1 (exp = exp / 2)

base = (base * base) % mod;

return result;

public static void main(String args[]) {

int p = 23; // publicly known prime number

int g = 5; // publicly known primitive root

int x = 4; // Alice's private secret

int y = 3; // Bob's private secret

// Alice sends (g^x) % p

int aliceSends = modExp(g, x, p);

// Bob computes (Alice's value^y) % p


int bobComputes = modExp(aliceSends, y, p);

// Bob sends (g^y) % p

int bobSends = modExp(g, y, p);

// Alice computes (Bob's value^x) % p

int aliceComputes = modExp(bobSends, x, p);

// The shared secret is the same for both Alice and Bob

int sharedSecret = modExp(g, x * y, p);

System.out.println("Simulation of Diffie-Hellman Key Exchange Algorithm\


n-------------------------");

System.out.println("Alice Sends: " + aliceSends);

System.out.println("Bob Computes: " + bobComputes);

System.out.println("Bob Sends: " + bobSends);

System.out.println("Alice Computes: " + aliceComputes);

System.out.println("Shared Secret: " + sharedSecret);

// Check if shared secrets match

if (aliceComputes == sharedSecret && bobComputes == sharedSecret) {

System.out.println("Success: Shared Secrets Match! " + sharedSecret);

} else {

System.out.println("Error: Shared Secrets do not match");

}
3. Calculate the message digest of a text using the SHA1 algorithm

import java.security.*;

public class SHA1Example {

public static void main(String[] a) {

try {

// Create SHA-1 MessageDigest instance

MessageDigest md = MessageDigest.getInstance("SHA-1");

// Print details about the MessageDigest instance

System.out.println("Message digest object info:\n-----------------");

System.out.println("Algorithm = " + md.getAlgorithm());

System.out.println("Provider = " + md.getProvider());

System.out.println("ToString = " + md.toString());

// Compute SHA-1 for an empty string

String input = "";

md.update(input.getBytes());

byte[] output = md.digest();

System.out.println("\nSHA1(\"" + input + "\") = " + bytesToHex(output));

// Compute SHA-1 for string "abc"

input = "abc";

md.update(input.getBytes());

output = md.digest();

System.out.println("\nSHA1(\"" + input + "\") = " + bytesToHex(output));

// Compute SHA-1 for string "abcdefghijklmnopqrstuvwxyz"


input = "abcdefghijklmnopqrstuvwxyz";

md.update(input.getBytes());

output = md.digest();

System.out.println("\nSHA1(\"" + input + "\") = " + bytesToHex(output));

} catch (Exception e) {

System.out.println("Exception: " + e);

// Helper method to convert byte array to hex string

private static String bytesToHex(byte[] b) {

char hexDigit[] = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

StringBuilder buf = new StringBuilder();

for (byte aB : b) {

buf.append(hexDigit[(aB >> 4) & 0x0f]);

buf.append(hexDigit[aB & 0x0f]);

return buf.toString();

4. Implement the SIGNATURE SCHEME - Digital Signature Standard

import java.security.*;

import java.util.Scanner;

import java.util.Base64;

public class CreatingDigitalSignature {


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

// Create scanner to read user input

Scanner sc = new Scanner(System.in);

System.out.println("Enter some text:");

String msg = sc.nextLine();

// Generate the key pair (private and public keys)

KeyPairGenerator keyPairGen = KeyPairGenerator.getInstance("DSA");

keyPairGen.initialize(2048); // Initializing key pair generator with 2048-bit key size

KeyPair pair = keyPairGen.generateKeyPair();

PrivateKey privKey = pair.getPrivate(); // Get the private key

// Initialize the signature object with SHA256withDSA algorithm

Signature sign = Signature.getInstance("SHA256withDSA");

sign.initSign(privKey); // Initialize the signature with the private key

// Convert the message to bytes

byte[] bytes = msg.getBytes();

// Update the signature object with the message bytes

sign.update(bytes);

// Generate the digital signature

byte[] signature = sign.sign();

// Close the scanner


sc.close();

// Print the digital signature as a Base64 encoded string

System.out.println("Digital signature for given text:");

System.out.println(Base64.getEncoder().encodeToString(signature));

5.

You might also like