0% found this document useful (0 votes)
38 views22 pages

C and Java Encryption Program Examples

Uploaded by

abhit.21205
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)
38 views22 pages

C and Java Encryption Program Examples

Uploaded by

abhit.21205
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

Program: 01

Aim: Write a C program that contains a string (char pointer) with a value
\Hello Word'. The programs should XOR each character in this string
with 0 and display the result.
Source code:
#include <stdio.h>

int main() {

// Define the string

char str[] = "Hello Word"; // Corrected to "Hello Word" (with proper quotes)

char xorKey = 0; // XOR key

printf("Original string: %s\n", str);

// Iterate through the string and XOR each character with 0

printf("XOR result (character by character):\n");

for (int i = 0; str[i] != '\0'; i++) {

char xorResult = str[i] ^ xorKey; // XOR with 0

printf("Character '%c' XOR 0 = '%c'\n", str[i], xorResult);

return 0;

}
Program: 02
Aim: Write a C program that contains a string (char pointer) with a value
\Hello World’. The program should AND or and XOR each character in
this string with 127 and display the result. Also provide input and
output.
Source code:
#include <stdio.h>

int main() {

// Define the string

char str[] = "Hello World"; // Corrected to "Hello World" (with proper quotes)

char andKey = 127; // AND key

char xorKey = 127; // XOR key

printf("Original string: %s\n", str);

// Iterate through the string and perform AND operation

printf("AND result (character by character):\n");

for (int i = 0; str[i] != '\0'; i++) {

char andResult = str[i] C andKey; // AND with 127

printf("Character '%c' AND 127 = '%c'\n", str[i], andResult);

// Iterate through the string and perform XOR operation

printf("\nXOR result (character by character):\n");

for (int i = 0; str[i] != '\0'; i++) {

char xorResult = str[i] ^ xorKey; // XOR with 127

printf("Character '%c' XOR 127 = '%c'\n", str[i], xorResult);

return 0;

}
Program: 03
Aim: Write a Java program to perform encryption and decryption using
the following algorithms:
a) Ceaser Cipher
b) Substitution Cipher
c) Hill Cipher

Source code:
import [Link];

import [Link];

public class EncryptionAlgorithms {

// Caesar Cipher

public static String caesarCipherEncrypt(String text, int shift) {

StringBuilder result = new StringBuilder();

for (char c : [Link]()) {

if ([Link](c)) {

char base = [Link](c) ? 'A' : 'a';

[Link]((char) ((c - base + shift) % 26 + base));

} else {

[Link](c);

return [Link]();

public static String caesarCipherDecrypt(String text, int shift) {

return caesarCipherEncrypt(text, 26 - shift);

}
// Substitution Cipher

public static String substitutionCipherEncrypt(String text, String key) {

StringBuilder result = new StringBuilder();

String alphabet = "ABCDEFGHIJKLMNOPǪRSTUVWXYZ";

text = [Link]();

for (char c : [Link]()) {

if ([Link](c)) {

[Link]([Link]([Link](c)));

} else {

[Link](c);

return [Link]();

public static String substitutionCipherDecrypt(String text, String key) {

StringBuilder result = new StringBuilder();

String alphabet = "ABCDEFGHIJKLMNOPǪRSTUVWXYZ";

text = [Link]();

for (char c : [Link]()) {

if ([Link](c)) {

[Link]([Link]([Link](c)));

} else {

[Link](c);

return [Link]();

}
// Hill Cipher

public static String hillCipherEncrypt(String text, int[][] keyMatrix, int n) {

text = [Link]().replaceAll("[^A-Z]", "");

while ([Link]() % n != 0) {

text += 'X';

StringBuilder result = new StringBuilder();

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

int[] vector = new int[n];

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

vector[j] = [Link](i + j) - 'A';

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

int sum = 0;
for (int col = 0; col < n; col++) {

sum += keyMatrix[row][col] * vector[col];

[Link]((char) ((sum % 26) + 'A'));

return [Link]();

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

// Caesar Cipher Example

[Link]("Enter text for Caesar Cipher:");


String caesarText = [Link]();

[Link]("Enter shift value:");

int shift = [Link]();

[Link](); // Consume newline

String caesarEncrypted = caesarCipherEncrypt(caesarText, shift);

[Link]("Caesar Cipher Encrypted: " + caesarEncrypted);

[Link]("Caesar Cipher Decrypted: " + caesarCipherDecrypt(caesarEncrypted,


shift));

// Substitution Cipher Example

[Link]("\nEnter text for Substitution Cipher:");

String substitutionText = [Link]();


String substitutionKey = "ǪWERTYUIOPASDFGHJKLZXCVBNM";

String substitutionEncrypted = substitutionCipherEncrypt(substitutionText,


substitutionKey);

[Link]("Substitution Cipher Encrypted: " + substitutionEncrypted);

[Link]("Substitution Cipher Decrypted: " +


substitutionCipherDecrypt(substitutionEncrypted, substitutionKey));

// Hill Cipher Example

[Link]("\nEnter text for Hill Cipher:");

String hillText = [Link]();


int[][] keyMatrix = {

{2, 3},

{1, 4}

};

String hillEncrypted = hillCipherEncrypt(hillText, keyMatrix, 2);

[Link]("Hill Cipher Encrypted: " + hillEncrypted);

}
Program: 04
Aim: Write a Java program to implement the DES algorithm logic.
Source code:
import [Link];

public class DESAlgorithm {

// Simplified permutation function

private static String permute(String input, int[] permTable) {

StringBuilder output = new StringBuilder();

for (int index : permTable) {

[Link]([Link](index - 1)); // Convert to 0-based index

return [Link]();

// Simplified XOR operation

private static String xor(String str1, String str2) {

StringBuilder result = new StringBuilder();

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

[Link]([Link](i) == [Link](i) ? '0' : '1');

return [Link]();

// DES round function (simplified)

private static String roundFunction(String right, String key) {

// Expansion permutation (dummy example for conceptual purposes)

int[] expansionTable = {4, 1, 2, 3, 2, 3, 4, 1};

String expandedRight = permute(right, expansionTable);


// XOR with key

String xored = xor(expandedRight, key);

// Dummy substitution function

String substituted = [Link](0, 4); // Just take first 4 bits for simplicity

// Permutation (dummy)

int[] permTable = {2, 4, 3, 1};

return permute(substituted, permTable);

// DES encryption (simplified, 1 round)

private static String desEncrypt(String plaintext, String key) {

// Initial permutation (dummy example)

int[] initialPerm = {2, 4, 3, 1, 6, 8, 5, 7};


String permutedText = permute(plaintext, initialPerm);

// Split into left and right halves

String left = [Link](0, 4);

String right = [Link](4);

// Perform one round of encryption

String newRight = xor(left, roundFunction(right, key));

String newLeft = right;

// Combine halves

String combined = newLeft + newRight;

// Final permutation (dummy example)

int[] finalPerm = {4, 1, 3, 5, 7, 2, 8, 6};

return permute(combined, finalPerm);


}

public static void main(String[] args) {

Scanner scanner = new Scanner([Link]);

// Input plaintext and key

[Link]("Enter 8-bit plaintext:");

String plaintext = [Link]();

[Link]("Enter 8-bit key:");

String key = [Link]();

// Encrypt using DES logic

String encrypted = desEncrypt(plaintext, key);

[Link]("Encrypted text: " + encrypted);

}
Program: 05
Aim: Write a C/JAVA program to implement the Blowfish algorithm
logic.
Source code:
#include <stdio.h>

#include <stdint.h>

#define ROUNDS 16

// Simplified S-boxes (for demonstration only)

uint32_t S[4][256] = {

{0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7}, // Only a few values for simplicity

{0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99},

{0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16},

{0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e}

};

// Simplified P-array (for demonstration only)

uint32_t P[ROUNDS + 2] = {

0x243f6a88, 0x85a308d3, 0x13198a2e, 0x03707344,

0xa4093822, 0x299f31d0, 0x082efa98, 0xec4e6c89,

0x452821e6, 0x38d01377, 0xbe5466cf, 0x34e90c6c,

0xc0ac29b7, 0xc97c50dd, 0x3f84d5b5, 0xb5470917,

0x9216d5d9, 0x8979fb1b

};

// Simplified F function

uint32_t F(uint32_t x) {

uint8_t a = (x >> 24) C 0xFF;

uint8_t b = (x >> 16) C 0xFF;

uint8_t c = (x >> 8) C 0xFF;

uint8_t d = x C 0xFF;
return ((S[0][a] + S[1][b]) ^ S[2][c]) + S[3][d];

}
// Blowfish encryption

void blowfishEncrypt(uint32_t *left, uint32_t *right) {

uint32_t L = *left, R = *right;

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

L ^= P[i];

R ^= F(L);

// Swap L and R

uint32_t temp = L;

L = R;
R = temp;

// Undo last swap

uint32_t temp = L;

L = R;

R = temp;

R ^= P[ROUNDS];

L ^= P[ROUNDS + 1];

*left = L;

*right = R;

int main() {

uint32_t left = 0x01234567; // Example plaintext (left half)

uint32_t right = 0x89abcdef; // Example plaintext (right half)

printf("Plaintext: %08x %08x\n", left, right);

blowfishEncrypt(Cleft, Cright);

printf("Ciphertext: %08x %08x\n", left, right);

return 0;

}
Program: 06
Aim: Write a C program to implement the Rijndael algorithm logic.
Source code:
#include <stdio.h>

#include <stdint.h>

#include <string.h>

#define Nb 4 // Number of columns in the state

#define Nk 4 // Key length (in 32-bit words)

#define Nr 10 // Number of rounds

// S-Box for SubBytes step

static const uint8_t SBox[256] = {

0x63, 0x7C, 0x77, 0x7B, 0xF2, 0x6B, 0x6F, 0xC5, 0x30, 0x01, 0x67, 0x2B, 0xFE, 0xD7, 0xAB,
0x76,

// (remaining entries omitted for brevity)

};

// Rijndael key schedule expansion table and implementation details go here...

// (For simplicity, the code assumes a pre-expanded key)

// Key expansion function (to be completed for full implementation)

void KeyExpansion(const uint8_t* key, uint8_t* roundKeys) {

// Dummy implementation; for production, implement key expansion logic

// SubBytes transformation

void SubBytes(uint8_t state[4][4]) {

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

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

state[i][j] = SBox[state[i][j]];
}

// ShiftRows transformation

void ShiftRows(uint8_t state[4][4]) {

uint8_t temp;

// Row 1

temp = state[1][0];

state[1][0] = state[1][1];

state[1][1] = state[1][2];

state[1][2] = state[1][3];

state[1][3] = temp;

// Row 2

temp = state[2][0];

state[2][0] = state[2][2];

state[2][2] = temp;

temp = state[2][1];

state[2][1] = state[2][3];

state[2][3] = temp;

// Row 3

temp = state[3][3];

state[3][3] = state[3][2];
state[3][2] = state[3][1];

state[3][1] = state[3][0];

state[3][0] = temp;

}
// AddRoundKey transformation

void AddRoundKey(uint8_t state[4][4], const uint8_t* roundKey) {

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


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

state[i][j] ^= roundKey[i * 4 + j];

// AES encryption for a single block

void AES_Encrypt(uint8_t* input, uint8_t* output, const uint8_t* roundKeys) {

uint8_t state[4][4];

// Copy input to state array

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

state[i % 4][i / 4] = input[i];

// Initial round

AddRoundKey(state, roundKeys);

// Main rounds

for (int round = 1; round < Nr; round++) {

SubBytes(state);

ShiftRows(state);

// MixColumns(state); // Omitted for brevity

AddRoundKey(state, roundKeys + round * 16);

// Final round

SubBytes(state);

ShiftRows(state);
AddRoundKey(state, roundKeys + Nr * 16);

// Copy state to output array

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

output[i] = state[i % 4][i / 4];

int main() {

// Example input: 16-byte plaintext and 16-byte key

uint8_t plaintext[16] = {

0x32, 0x88, 0x31, 0xE0, 0x43, 0x5A, 0x31, 0x37,

0xF6, 0x30, 0x98, 0x07, 0xA8, 0x8D, 0xA2, 0x34

};

uint8_t key[16] = {

0x2B, 0x7E, 0x15, 0x16, 0x28, 0xAE, 0xD2, 0xA6,

0xAB, 0xF7, 0x9E, 0xD8, 0x49, 0xF7, 0xCF, 0xF3

};

uint8_t roundKeys[176]; // Placeholder for round keys

KeyExpansion(key, roundKeys);

uint8_t ciphertext[16];

AES_Encrypt(plaintext, ciphertext, roundKeys);

printf("Ciphertext: \n");

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

printf("%02X ", ciphertext[i]);

printf("\n");

return 0;

}
Program: 07
Aim: Write a Java program to implement RSA Algorithm.
Source code:
import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class RSAExample {

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

// Generate RSA key pair

KeyPairGenerator keyGen = [Link]("RSA");

[Link](2048); // Key size

KeyPair keyPair = [Link]();

PublicKey publicKey = [Link]();

PrivateKey privateKey = [Link]();

// Extract key specifications

KeyFactory keyFactory = [Link]("RSA");

RSAPublicKeySpec publicSpec = [Link](publicKey,


[Link]);

RSAPrivateKeySpec privateSpec = [Link](privateKey,


[Link]);

[Link]("Public Key: ");

[Link]("Modulus: " + [Link]());


[Link]("Exponent: " + [Link]());

[Link]("\nPrivate Key: ");

[Link]("Modulus: " + [Link]());

[Link]("Exponent: " + [Link]());

// Message to encrypt

String message = "Hello, RSA!";

[Link]("\nOriginal Message: " + message);

// Encrypt the message using the public key

Cipher encryptCipher = [Link]("RSA");

[Link](Cipher.ENCRYPT_MODE, publicKey);

byte[] encryptedMessage = [Link]([Link]());

[Link]("Encrypted Message (Hex): " + bytesToHex(encryptedMessage));

// Decrypt the message using the private key

Cipher decryptCipher = [Link]("RSA");

[Link](Cipher.DECRYPT_MODE, privateKey);

byte[] decryptedMessage = [Link](encryptedMessage);

[Link]("Decrypted Message: " + new String(decryptedMessage));

// Helper method to convert bytes to hex

public static String bytesToHex(byte[] bytes) {

StringBuilder hexString = new StringBuilder();

for (byte b : bytes) {

String hex = [Link](0xFF C b);

if ([Link]() == 1) {

[Link]('0');

[Link](hex);

return [Link]();

}}
Program: 08
Aim: Implement the Diffie-Hellman Key Exchange mechanism using
HTML and JavaScript.
Source code:
<!DOCTYPE html>

<html>

<head>

<title>Diffie-Hellman Key Exchange</title>

</head>

<body>

<h1>Diffie-Hellman Key Exchange</h1>

<p>Enter values for prime number (p) and base (g):</p>

<form id="dhForm">

<label for="prime">Prime number (p):</label>

<input type="number" id="prime" required><br><br>

<label for="base">Base (g):</label>

<input type="number" id="base" required><br><br>

<label for="privateA">Private Key of User A:</label>

<input type="number" id="privateA" required><br><br>

<label for="privateB">Private Key of User B:</label>

<input type="number" id="privateB" required><br><br>

<button type="button" onclick="performKeyExchange()">Calculate</button>

</form>

<h3>Results:</h3>

<p id="result"></p>
<script>

function performKeyExchange() {

const p = parseInt([Link]('prime').value);

const g = parseInt([Link]('base').value);

const privateA = parseInt([Link]('privateA').value);

const privateB = parseInt([Link]('privateB').value);

if (isNaN(p) || isNaN(g) || isNaN(privateA) || isNaN(privateB)) {

[Link]('result').innerText = 'Please enter valid numbers for all fields.';

return;

// Calculate public keys

const publicA = [Link](g, privateA) % p;

const publicB = [Link](g, privateB) % p;

// Calculate shared keys

const sharedKeyA = [Link](publicB, privateA) % p;

const sharedKeyB = [Link](publicA, privateB) % p;

const result = `Public Key of User A: ${publicA}\n` +

`Public Key of User B: ${publicB}\n` +

`Shared Key (User A's calculation): ${sharedKeyA}\n` +

`Shared Key (User B's calculation): ${sharedKeyB}`;

[Link]('result').innerText = result;

</script>

</body>

</html>
Program: 09
Aim: Calculate the message digest of a text using the SHA-1 algorithm
in JAVA.
Source code:
import [Link];

public class SHA1Example {

public static void main(String[] args) {

try {

// Input text

String text = "Hello, SHA-1!";

[Link]("Original Text: " + text);

// Create MessageDigest instance for SHA-1

MessageDigest md = [Link]("SHA-1");

// Perform the hash computation

byte[] messageDigest = [Link]([Link]());

// Convert the byte array to hexadecimal format

StringBuilder hexString = new StringBuilder();

for (byte b : messageDigest) {

String hex = [Link](0xff C b);

if ([Link]() == 1) {

[Link]('0');

[Link](hex);

// Display the message digest

[Link]("Message Digest (SHA-1): " + [Link]());

} catch (Exception e) {

[Link]();
}}}
Program: 10
Aim: Calculate the message digest of a text using theMD5 algorithm in
JAVA.
Source code:
import [Link];

import [Link];

import [Link];

public class MD5HashExample {

public static void main(String[] args) {


Scanner scanner = new Scanner([Link]);

// Input: Get text from the user

[Link]("Enter text to compute MD5 hash: ");

String input = [Link]();

try {

// Compute MD5 hash

String md5Hash = calculateMD5(input);

// Output: Display the MD5 hash

[Link]("MD5 Hash: " + md5Hash);

} catch (NoSuchAlgorithmException e) {

[Link]("Error: MD5 algorithm not found!");

[Link]();

public static String calculateMD5(String input) throws NoSuchAlgorithmException {


// Create a MessageDigest instance for MD5

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

// Compute the hash in bytes

byte[] hashBytes = [Link]([Link]());

// Convert the byte array to a hexadecimal string

StringBuilder hexString = new StringBuilder();

for (byte b : hashBytes) {

// Convert each byte to a two-digit hex value

String hex = [Link](0xFF C b);

if ([Link]() == 1) {

[Link]('0');

[Link](hex);

return [Link]();

You might also like