0% found this document useful (0 votes)
8 views31 pages

C and Java Encryption Algorithms Guide

Uploaded by

vgovinda36
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)
8 views31 pages

C and Java Encryption Algorithms Guide

Uploaded by

vgovinda36
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

1.

Write a C program that contains a string (char pointer) with a value \Hello

World’. The program should XOR each character in this string with 0 and

displays the result.

#include<stdio.h>

#include<string.h>

int main()

char str[24],c[4];

int i,x;

printf("Enter the string:");

scanf("%s",str);

x=strlen(str);

for(i=0;i<=x;i++)

c[i]=str[i]^0;

printf("The result of XOR operation is: %s",c);

}
OUTPUT:

Enter the string: Helloworld

The result of XOR operation is: Helloworld


2. 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.

#include <stdio.h>

#include<stdlib.h>

void main()

char str[]="Hello World";

char str1[11];

char str2[11]=str[];

int i,len;

len = strlen(str);

for(i=0;i<len;i++)

str1[i] = str[i]&127;

printf("%c",str1[i]);

printf("\n");

for(i=0;i<len;i++)

str3[i] = str2[i]^127;

printf("%c",str3[i]);
}

printf("\n");

Output:

Hello World

Hello World

Hello World
3. Write a Java program to perform encryption and decryption using the following

algorithms:

a) Caesar Cipher

import [Link];

public class CaesarCipherExample

public static final String ALPHABET = "abcdefghijklmnopqrstuvwxyz";

public static String encryptData(String inputStr, int shiftKey)

inputStr = [Link]();

String encryptStr = "";

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

int pos = [Link]([Link](i));

int encryptPos = (shiftKey + pos) % 26;

char encryptChar = [Link](encryptPos);

encryptStr += encryptChar;

return encryptStr;

public static String decryptData(String inputStr, int shiftKey)

{
inputStr = [Link]();

String decryptStr = "";

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

int pos = [Link]([Link](i));

int decryptPos = (pos - shiftKey) % 26;

if (decryptPos < 0){

decryptPos = [Link]() + decryptPos;

char decryptChar = [Link](decryptPos);

decryptStr += decryptChar;

return decryptStr;

public static void main(String[] args)

Scanner sc = new Scanner([Link]);

[Link]("Enter a string for encryption using Caesar Cipher: ");

String inputStr = [Link]();

[Link]("Enter the value by which each character in the plaintext message

gets shifted: ");

int shiftKey = [Link]([Link]());

[Link]("Encrypted Data ===> "+encryptData(inputStr, shiftKey));


[Link]("Decrypted Data ===> "+decryptData(encryptData(inputStr, shif

tKey), shiftKey));

[Link]();

Output:

Enter a string for encryption using Caesar Cipher:

chanti

Enter the value by which each character in the plaintext message gets shifted:

Encrypted Data ===> ejcpvk

Decrypted Data ===> chanti


b) Hill Cipher

class GFG

static void getKeyMatrix(String key, int keyMatrix[][])

int k = 0;

for (int i = 0; i < 3; i++)

for (int j = 0; j < 3; j++)

keyMatrix[i][j] = ([Link](k)) % 65;

k++;

static void encrypt(int cipherMatrix[][],

int keyMatrix[][],

int messageVector[][])

int x, i, j;

for (i = 0; i < 3; i++)

for (j = 0; j < 1; j++)


{

cipherMatrix[i][j] = 0;

for (x = 0; x < 3; x++)

cipherMatrix[i][j] +=

keyMatrix[i][x] * messageVector[x][j];

cipherMatrix[i][j] = cipherMatrix[i][j] % 26;

static void HillCipher(String message, String key)

int [][]keyMatrix = new int[3][3];

getKeyMatrix(key, keyMatrix);

int [][]messageVector = new int[3][1];

for (int i = 0; i < 3; i++)

messageVector[i][0] = ([Link](i)) % 65;

int [][]cipherMatrix = new int[3][1];

encrypt(cipherMatrix, keyMatrix, messageVector);

String CipherText="";
for (int i = 0; i < 3; i++)

CipherText += (char)(cipherMatrix[i][0] + 65);

[Link](" Ciphertext:" + CipherText);

public static void main(String[] args)

String message = "ACT";

String key = "GYBNQKURP";

HillCipher(message, key);

Output:

Ciphertext:POH
c) Substitution Cipher

Import [Link].*;

import [Link].*;

public class SubstitutionCipher

static Scanner sc = new Scanner([Link]);

static BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

public static void main(String[] args) throws IOException

String a = "abcdefghijklmnopqrstuvwxyz";

String b = "zyxwvutsrqponmlkjihgfedcba";

[Link]("Enter any string: ");

String str = [Link]();

String decrypt = "";

char c;

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

c = [Link](i); int

j = [Link](c);

decrypt = decrypt+[Link](j);

[Link]("The encrypted data is: " +decrypt);

}
}

Output:

Enter any string: aceho

The encrypted data is: zxvsl


4. Write a C/JAVA program to implement the Blowfish algorithm logic.

import [Link].*;

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link] ;

class Blowfish

byte[ ] skey = new byte[1000];

String skeyString;

static byte[ ] raw;

String inputMessage,encryptedData,decryptedMessage;

public Blowfish()

try

generateSymmetricKey();

inputMessage=[Link](null,"Enter message to encrypt");

byte[] ibyte = [Link]();

byte[] ebyte=encrypt(raw, ibyte);

String encryptedData = new String(ebyte);


[Link]("Encrypted message "+encryptedData);

[Link](null,"Encrypted Data "+"\n"+encryptedData);

byte[] dbyte= decrypt(raw,ebyte);

String decryptedMessage = new String(dbyte);

[Link]("Decrypted message "+decryptedMessage);

[Link](null,"Decrypted Data "+"\n"+decryptedMessage);

catch(Exception e)

[Link](e);

void generateSymmetricKey()

try

Random r = new Random();

int num = [Link](10000);

String knum = [Link](num);

byte[] knumb = [Link]();

skey=getRawKey(knumb);

skeyString = new String(skey);

[Link]("Blowfish Symmetric key = "+skeyString);


}

catch(Exception e)

[Link](e);

private static byte[] getRawKey(byte[] seed) throws Exception

KeyGenerator kgen = [Link]("Blowfish");

SecureRandom sr = [Link]("SHA1PRNG");

[Link](seed);

[Link](128, sr);

SecretKey skey = [Link]();

raw = [Link]();

return raw;

private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception

SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");

Cipher cipher = [Link]("Blowfish");

[Link](Cipher.ENCRYPT_MODE, skeySpec);

byte[] encrypted = [Link](clear);

return encrypted;
}

private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception

SecretKeySpec skeySpec = new SecretKeySpec(raw, "Blowfish");

Cipher cipher = [Link]("Blowfish");

[Link](Cipher.DECRYPT_MODE, skeySpec);

byte[] decrypted = [Link](encrypted);

return decrypted;

public static void main(String args[])

Blowfish bf = new Blowfish();

Output:

Blowfish Symmetric key = hÿ/p!1╖t\_°▬[Link]

╠←y╨■ΓÖed message

Decrypted message chanti


5. Write a C/JAVA program to implement the Rijndael algorithm logic.

import [Link].*;

import [Link].*;

import [Link].*;

import [Link].*;

public class AES

public static String asHex (byte buf[])

StringBuffer strbuf = new StringBuffer([Link] * 2);

int i;

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

if (((int) buf[i] & 0xff) < 0x10)

[Link]("0");

[Link]([Link]((int) buf[i] & 0xff, 16));

return [Link]();

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

String message="AES still rocks!!";


KeyGenerator kgen = [Link]("AES");

[Link](128);

SecretKey skey = [Link]();

byte[] raw = [Link]();

SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");

Cipher cipher = [Link]("AES");

[Link](Cipher.ENCRYPT_MODE, skeySpec);

byte[] encrypted = [Link](([Link] == 0 ? message : args[0]).getBytes());

[Link]("encrypted string: " + asHex(encrypted));

[Link](Cipher.DECRYPT_MODE, skeySpec);

byte[] original = [Link](encrypted);

String originalString = new String(original);

[Link]("Original string: " + originalString + " " + asHex(original));

Output:

Encrypted string:

ab3eb43880e1fcb8858e822faebf447793c8d4b02f8decd630b5d3f5d203afe1

Original string: AES still rocks!! 414553207374696c6c20726f636b732121


6. Write a Java program to implement the DES algorithm logic.

import [Link].*;

import [Link]; import

[Link]; import

[Link]; import

[Link];

import [Link];

import [Link]; import

[Link]; import

[Link].BASE64Decoder;

import [Link].BASE64Encoder;

public class DES

private static final String UNICODE_FORMAT = "UTF8";

public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";

privateKeySpecmyKeySpec;

privateSecretKeyFactorymySecretKeyFactory;

private Cipher cipher;

byte[] keyAsBytes;

private String myEncryptionKey;

private String myEncryptionScheme; SecretKey key;

static BufferedReader br = new BufferedReader(new InputStreamReader([Link]));

public DES() throws Exception


{

myEncryptionKey= "ThisIsSecretEncryptionKey";

myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;

keyAsBytes = [Link](UNICODE_FORMAT);

myKeySpec = new DESedeKeySpec(keyAsBytes);

mySecretKeyFactory = [Link](myEncryptionScheme);

cipher = [Link](myEncryptionScheme);

key = [Link](myKeySpec);

public String encrypt(String unencryptedString)

String encryptedString = null;

try

[Link](Cipher.ENCRYPT_MODE, key);

byte[] plainText = [Link](UNICODE_FORMAT);

byte[] encryptedText = [Link](plainText);

BASE64Encoder base64encoder = new BASE64Encoder();

encryptedString = [Link](encryptedText);

catch (Exception )

[Link]();
}

returnencryptedString;

public String decrypt(String encryptedString)

String decryptedText=null;

try

[Link](Cipher.DECRYPT_MODE, key);

BASE64Decoder base64decoder = new BASE64Decoder();

byte[]encryptedText = [Link](encryptedString);

byte[]plainText = [Link](encryptedText);

decryptedText= bytes2String(plainText);

catch (Exception e)

[Link]();

returndecryptedText;

private static String bytes2String(byte[] bytes)

{ StringBufferstringBuffer = new StringBuffer();

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


{

[Link]((char) bytes[i]);

[Link]();

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

[Link]("Enter the string: ");

DES myEncryptor= new DES();

String stringToEncrypt = [Link]();

String encrypted = [Link](stringToEncrypt);

String decrypted = [Link](encrypted);

[Link]("\nString To Encrypt: " +stringToEncrypt);

[Link]("\nEncrypted Value : " +encrypted);

[Link]("\nDecrypted Value : " +decrypted);

[Link]("");

}
Output:

Enter the string: Welcome String

To Encrypt: Welcome

Encrypted Value: BPQMwc0wKvg=

Decrypted Value: Welcome


7. JavaScript. Consider the end user as one of the parties (Alice) and the

JavaScript application as other party (bob).

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

import [Link];

public class DiffeHellman

public final static int pValue = 47;

public final static int gValue = 71;

public final static int XaValue = 9;

public final static int XbValue = 14;

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

BigInteger p = new BigInteger([Link](pValue));

BigInteger g = new BigInteger([Link](gValue));

BigInteger Xa = new BigInteger([Link](XaValue));

BigInteger Xb = new BigInteger([Link](XbValue));

createKey();
int bitLength = 512;

SecureRandom rnd = new SecureRandom();

p = [Link](bitLength, rnd);

g =[Link](bitLength, rnd);

createSpecificKey(p, g);

public static void createKey() throws Exception

KeyPairGenerator kpg = [Link]("DiffieHellman");

[Link](512);

KeyPair kp = [Link]();

KeyFactory kfactory = [Link]("DiffieHellman");

DHPublicKeySpec kspec = (DHPublicKeySpec) [Link]([Link](),

[Link]);

[Link]("Public key is: " +kspec);

public static void createSpecificKey(BigInteger p, BigInteger g) throws Exception

KeyPairGenerator kpg = [Link]("DiffieHellman");

DHParameterSpec param = new DHParameterSpec(p, g);

[Link](param);

KeyPair kp = [Link]();

KeyFactory kfactory = [Link]("DiffieHellman");


DHPublicKeySpec kspec = (DHPublicKeySpec) [Link]([Link](),

[Link]);

[Link]("\nPublic key is : " +kspec);

Output:

Public key is: [Link]@18ac738

Public key is: [Link]@15dfd77


8. Calculate the message digest of a text using the SHA-1 algorithm in JAVA.

import [Link];

import [Link];

import [Link];

public class GFG {

public static String encryptThisString(String input)

try {

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

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

BigInteger no = new BigInteger(1, messageDigest);

String hashtext = [Link](16);

while ([Link]() < 32) {

hashtext = "0" + hashtext;

return hashtext;

catch (NoSuchAlgorithmException e) {

throw new RuntimeException(e);

public static void main(String args[]) throws NoSuchAlgorithmException


{

[Link]("HashCode Generated by SHA-1 for: ");

String s1 = "GeeksForGeeks";

[Link]("\n" + s1 + " : " + encryptThisString(s1));

String s2 = "hello world";

[Link]("\n" + s2 + " : " + encryptThisString(s2));

Output:

HashCode Generated by SHA-1 for:

GeeksForGeeks: addf120b430021c36c232c99ef8d926aea2acd6b

Hello world: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed


9. Write a Java program to implement RSA Algorithm

import [Link].*;

import [Link].*;

class RSA

public static void main(String args[])

int p, q, n, z, d = 0, e, i;

int msg = 12;

double c;

BigInteger msgback;

p = 3;

q = 11;

n = p * q;

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

[Link]("the value of z = " + z);

for (e = 2; e < z; e++)

if (gcd(e, z) == 1)

break;

}
}

[Link]("the value of e = " + e);

for (i = 0; i <= 9; i++)

int x = 1 + (i * z);

if (x % e == 0)

d = x / e;

break;

[Link]("the value of d = " + d);

c = ([Link](msg, e)) % n;

[Link]("Encrypted message is : " + c);

BigInteger N = [Link](n);

BigInteger C = [Link](c).toBigInteger();

msgback = ([Link](d)).mod(N);

[Link]("Decrypted message is : "+ msgback);

static int gcd(int e, int z)

if (e == 0)

return z;
else

return gcd(z % e, e);

Output:

Common questions

Powered by AI

The Blowfish algorithm ensures secure encryption by using a variable-length key (up to 448 bits), which makes exhaustive search difficult. It is a symmetric key cipher using a Feistel network structure, meaning each round consists of an expansion permutation and a substitution based on the key. This increases complexity. The implementation involves generating a symmetric key from a seed, and the encryption/decryption functions use this key to transform the data accordingly. The key generation and secure transformation steps crucially ensure security by making patterns hard to predict .

In the DES algorithm, a key specification is crucial for ensuring appropriate encryption and decryption. The key is defined through a DESedeKeySpec, which handles the format and byte specification of the key. The key, when initialized in a cipher, determines the transformation process it will apply during encryption by calling the init method, allowing it to encrypt and later decrypt any given message accurately. This specification encapsulates key generation and storage in a secure manner, preventing unauthorized access or modification .

The Substitution Cipher encrypts messages by replacing each letter with another letter from a predefined substitution alphabet, making it a form of monoalphabetic cipher. Each letter substitution is fixed. By contrast, the Caesar Cipher shifts all letters in the text by a fixed number of positions in the alphabet (defined by the shift key), which can be seen as a transposition of the alphabet. While both are simple encryption techniques, Substitution Ciphers can use non-contiguous mapping, whereas Caesar uses uniform shift mapping .

In the Caesar Cipher, each letter in the plaintext is shifted a certain number of places down the alphabet according to the shift key. The encryptData function performs this by finding the position of each character in the alphabet, adding the shift key, and using the resulting position to find the encrypted character. Decryption reverses this by subtracting the shift key from each character's position to recover the original message. The shift key determines the number of positions each character is shifted, thus controlling the encryption and decryption process .

RSA encryption involves several computational steps. Key generation starts with selecting two prime numbers, p and q, computing n = pq and φ(n) = (p-1)(q-1). An encryption key e is chosen such that 1 < e < φ(n) and gcd(e, φ(n)) = 1. A decryption key d is found as the modular multiplicative inverse of e modulo φ(n). For encryption, the ciphertext is computed as c = m^e mod n for message m. Decryption uses d to compute m = c^d mod n, recovering the original message. The reliance on number theory and difficulty of factoring ensures its security .

The Hill Cipher uses a key matrix to encrypt messages. First, a key string is converted to a key matrix, where each character is mapped to a numerical value (usually ASCII value minus a certain constant like 65). The message is also converted into a vector of numeric values. Then, matrix multiplication of the key matrix and message vector is performed, followed by taking modulo 26 of the result to ensure it maps back to alphabetic characters. The resulting numerical values are converted back to characters to form the cipher text .

Diffie-Hellman key exchange algorithm allows two parties to create a shared secret key over an insecure channel. It requires each party to agree on two large prime numbers, p (prime) and g (a primitive root modulo p), known publicly. Each party then selects a private key and computes a public key to share with the other. They then each compute the shared secret using the other's public key raised to the power of their private key, modulo p. The shared secret key is identical for both parties due to the mathematical properties of the algorithm .

The SHA-1 algorithm generates a message digest by taking an input message and processing it into a fixed 160-bit hash value. It works iteratively by updating an internal state with blocks of 512 bits at a time until the entire message is processed. Important steps include message padding (ensuring the message is a multiple of 512 bits long), and processing through a series of bitwise operations and modular additions. The final hash is produced by concatenating the output of the last iteration, representing the message digest .

The XOR operation with 0 on any character in a C program is essentially a non-operation. This is because XORing anything with 0 leaves the original value unchanged, which is why in the provided C program, when the string "Hello World" undergoes XOR with 0, the output remains "Hello World" .

Java provides several advantages for implementing cryptographic algorithms like AES compared to C. Java's strong standard library support through packages like javax.crypto facilitates easy access to pre-defined classes and methods for encryption, ensuring security and correctness. Java's built-in exception handling aids in managing cryptographic errors gracefully. Its platform independence and automatic memory management reduce the risk of memory-related vulnerabilities. In contrast, C allows fine-grained control but at the cost of increased complexity and the potential for bugs like buffer overflows, making Java a safer and more productive choice for high-level cryptographic implementations .

You might also like