0% found this document useful (0 votes)
83 views30 pages

C and Java Encryption Programs

Uploaded by

Sathish Koppoju
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)
83 views30 pages

C and Java Encryption Programs

Uploaded by

Sathish Koppoju
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.

XOR a string with a Zero


AIM: 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 display the result.
PROGRAM:
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
main()
{
char str[]="Hello World";
char str1[11];
int i,len;
len=strlen(str);
for(i=0;i<len;i++)
{
str1[i]=str[i]^0;
printf("%c",str1[i]);
}
printf(“\n”);
}
OUTPUT:
[Link] a string with a 127
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.
PROGRAM:
#include<stdlib.h>
#include<string.h>
#include<stdio.h>
void main()
{
char str[]="Hello World";
int i,len;
len=strlen(str);
printf("AND:");
for(i=0;i<len;i++)
{
printf("%c",str[i]&127);
}
printf(“\n”);
printf("XOR:");
for(i=0;i<len;i++)
{
printf("%c",str[i]^127);
}
printf(“\nnOR”);
for(i=0;i<len;i++)
{
printf("%c",str[i]|127);
}
printf(“\n”);
}
OUTPUT:

[Link] & Decryption using Cipher Algorithms


AIM: Write a Java program to perform encryption and decryption using the following
algorithms:
a) Ceaser Cipher
b) Substitution Cipher
c) Hill Cipher
PROGRAM:
a) Ceaser Cipher
import [Link];
import [Link];
import [Link];
import [Link];
import [Link].*;
public class CeaserCipher
{
static Scanner sc=new Scanner([Link]);
static BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
public static void main(String[] args) throws IOException
{
[Link]("Enter any String: "); String str = [Link]();
[Link]("\nEnter the Key: ");
int key = [Link]();
String encrypted = encrypt(str, key);
[Link]("\nEncrypted String is: " +encrypted);
String decrypted = decrypt(encrypted, key);
[Link]("\nDecrypted String is: " +decrypted);
[Link]("\n");
}
public static String encrypt(String str, int key)
{
String encrypted = "";
for(int i = 0; i < [Link](); i++)
{
int c = [Link](i);
if ([Link](c))
{
c = c + (key % 26);
if (c > 'Z')
c = c - 26;
}
else if ([Link](c))
{
c = c + (key % 26);
if (c > 'z')
c = c - 26;
}
encrypted += (char) c;
}
return encrypted;
}
public static String decrypt(String str, int key)

{
String decrypted = "";
for(int i = 0; i < [Link](); i++)
{
int c = [Link](i);
if ([Link](c))
{
c = c - (key % 26);
if (c < 'A')
c = c + 26;
}
else if ([Link](c))
{
c = c - (key % 26);
if (c < 'a')
c = c + 26;
}
decrypted += (char) c;
}
return decrypted;
}
}
OUTPUT:

b) Substitution Cipher
PROGRAM:
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:
c)Hill Cipher
PROGRAM:
import [Link].*;
import [Link].*;
import [Link].*;
public class HillCipher
{
static float[][] decrypt = new float[3][1];
static float[][] a = new float[3][3];
static float[][] b = new float[3][3];
static float[][] mes = new float[3][1];
static float[][] res = new float[3][1];
static BufferedReader br = new BufferedReader(new InputStreamReader([Link]));
static Scanner sc = new Scanner([Link]);
public static void main(String[] args) throws IOException
{
getkeymes();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++)
{
res[i][j]=res[i][j]+a[i][k]*mes[k][j];
}
[Link]("\nEncrypted string is : ");
for(int i=0;i<3;i++)
{
[Link]((char)(res[i][0]%26+97));
res[i][0]=res[i][0];
}
inverse();
for(int i=0;i<3;i++)
for(int j=0;j<1;j++)
for(int k=0;k<3;k++)
{
decrypt[i][j] = decrypt[i][j]+b[i][k]*res[k][j];
}
[Link]("\nDecrypted string is : ");
for(int i=0;i<3;i++)
{
[Link]((char)(decrypt[i][0]%26+97));
}
[Link]("\n");
}
public static void getkeymes() throws IOException
{
[Link]("Enter 3x3 matrix for key (It should be inversible): ");
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
a[i][j] = [Link]();
[Link]("\nEnter a 3 letter string: ");
String msg = [Link]();
for(int i=0;i<3;i++)
mes[i][0] = [Link](i)-97;
}
public static void inverse()
{
float p,q;
float[][] c = a;
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
//a[i][j]=[Link]();
if(i==j)
b[i][j]=1;
else b[i][j]=0;
}
for(int k=0;k<3;k++)
{
for(int i=0;i<3;i++)
{
p = c[i][k];
q = c[k][k];
for(int j=0;j<3;j++)
{
if(i!=k)
{
c[i][j] = c[i][j]*q-p*c[k][j];
b[i][j] = b[i][j]*q-p*b[k][j];
}
}
}
}
for(int i=0;i<3;i++)
for(int j=0;j<3;j++)
{
b[i][j] = b[i][j]/c[i][i];
}
[Link]("");
[Link]("\nInverse Matrix is : ");
for(int i=0;i<3;i++)
{
for(int j=0;j<3;j++)
[Link](b[i][j] + " ");
[Link]("\n");
}
}
}
OUTPUT:
[Link] program for DES Algorithm logic
AIM: Write a Java program to implement the DES algorithm logic.
PROGRAM:
import [Link].*;
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
import [Link];
class DES
{
byte[] skey = new byte[1000];
String skeyString;
static byte[] raw;
String inputMessage,encryptedData,decryptedMessage;
public DES()
{
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]("DES Symmetric key = "+skeyString);
}
catch(Exception e)
{
[Link](e);
}
}
private static byte[] getRawKey(byte[] seed) throws Exception
{
KeyGenerator kgen = [Link]("DES");
SecureRandom sr = [Link]("SHA1PRNG");
[Link](seed);
[Link](56, sr);
SecretKey skey = [Link]();
raw = [Link]();
return raw;
}
private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception
{
SecretKeySpec skeySpec = new SecretKeySpec(raw, "DES");
Cipher cipher = [Link]("DES");
[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, "DES");
Cipher cipher = [Link]("DES");
[Link](Cipher.DECRYPT_MODE, skeySpec);
byte[] decrypted = [Link](encrypted);
return decrypted;
}
public static void main(String args[])
{
DES des = new DES();
}
}
OUTPUT:
5. Program to implement BlowFish algorithm logic
AIM: Write a C/JAVA program to implement the BlowFish algorithm logic.
PROGRAM:
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:
6. Program to implement Rijndael algorithm logic
AIM: Write a C/JAVA program to implement the Rijndael algorithm logic.
PROGRAM:
import [Link].*;
import [Link].*;
class AES
{
private 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 in Hexadecimal: " + asHex(original));
[Link]("Original String: " + originalString);
}
}

OUTPUT:

7. Encrypt a string using BlowFish algorithm


AIM: Write the RC4 logic in Java Using Java cryptography; encrypt the text “Hello world” using
Blowfish. Create your own key using Java key tool
PROGRAM:
import [Link].*;
public class RC4
{
public static void main(String[] args) throws Exception
{
KeyGenerator kg=[Link]("RC4");
SecretKey skey=[Link]();
Cipher c=[Link]("RC4");
[Link](Cipher.ENCRYPT_MODE,skey);
String inputText="Hello World";
byte[] encrypted=[Link]([Link]());
[Link](Cipher.DECRYPT_MODE,skey);
byte[] decrypted=[Link](encrypted);
[Link]("Original String: "+inputText);
[Link]("Encrypted: "+new String(encrypted));
[Link]("Decrypted: "+new String(decrypted));
}
}
OUTPUT:

8. RSA Algorithm
AIM: Write a Java program to implement RSA Algorithm.
PROGRAM:
import [Link];
import [Link];
import [Link].*;
import [Link];
import [Link];
public class RSA
{
static Scanner sc = new Scanner([Link]);
public static void main(String[] args)
{
[Link]("Enter a Prime number: ");
BigInteger p = [Link]();
[Link]("Enter another prime number: ");
BigInteger q = [Link]();
BigInteger n = [Link](q);
BigInteger n2 = [Link]([Link]).multiply([Link]([Link]));
BigInteger e = generateE(n2);
BigInteger d = [Link](n2);
[Link]("Encryption keys are: " + e + ", " + n);
[Link]("Decryption keys are: " + d + ", " + n);
}
public static BigInteger generateE(BigInteger fiofn)
{
int y, intGCD;
BigInteger e;
BigInteger gcd;
Random x = new Random();
do
{
y = [Link]([Link]()-1);
String z = [Link](y);
e = new BigInteger(z);
gcd = [Link](e);
intGCD = [Link]();
}
while(y <= 2 || intGCD != 1);
return e;
}
}
OUTPUT:

9. Diffie-Hellman
AIM: Implement the Diffie-Hellman Key Exchange mechanism using HTML and JavaScript.
PROGRAM:
<script>
function power(a,b,p)
{
if (b == 1)
return a;
else
return(([Link](a, b)) % p);
}
var P=21, G=9, x, a=4, y, b=3, ka, kb;
[Link]("The value of P:" + P + "<br>");
[Link]("The value of G:" + G + "<br>");
[Link]("The private key a for Alice:" +a + "<br>");
[Link]("The private key b for Bob:" + b + "<br>");
x = power(G, a, P);
y = power(G, b, P);
ka = power(y, a, P);
kb = power(x, b, P);
[Link]("Secret key for the Alice is:" +ka + "<br>");
[Link]("Secret key for the Bob is:" +kb + "<br>");
</script>

OUTPUT:

10. SHA-1
AIM: Calculate the message digest of a text using the SHA-1 algorithm in JAVA.
PROGRAM:
import [Link];
import [Link];
public class SHA1
{
public static void main(String args[]) throws Exception
{
String input = "Hello World";
try
{
MessageDigest md = [Link]("SHA-1");
[Link]("MessageDigest Object Info");
[Link]("Message: "+[Link]());
[Link]("Provider: "+[Link]());
byte[] messageDigest = [Link]([Link]());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = [Link](16);
while ([Link]() < 32)
{
hashtext = "0" + hashtext;
}
[Link]("HashCode Generated");
[Link](input+" : "+hashtext);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
OUTPUT:
11. Message Digest Algorithm5 (MD5)
AIM: Calculate the message digest of a text using the MD-5 algorithm in JAVA.
PROGRAM:
import [Link];
import [Link];
public class MD5
{
public static void main(String args[]) throws Exception
{
String input = "Hello World";
try
{
MessageDigest md = [Link]("MD5");
[Link]("MessageDigest Object Info");
[Link]("Message: "+[Link]());
[Link]("Provider: "+[Link]());
byte[] messageDigest = [Link]([Link]());
BigInteger no = new BigInteger(1, messageDigest);
String hashtext = [Link](16);
while ([Link]() < 32)
{
hashtext = "0" + hashtext;
}
[Link]("HashCode Generated");
[Link](input+" : "+hashtext);
}
catch (Exception e)
{
throw new RuntimeException(e);
}
}
}
OUTPUT:

Common questions

Powered by AI

The Caesar Cipher's shift value must be within the range of the alphabet (0-25 for English) to ensure that the result of shifting stays within the bounds of valid alphabetic characters. If the shift exceeds this range, it wraps around, effectively nullifying larger shifts back to smaller, equivalent ones. This constraint ensures that both encryption and decryption can consistently map input characters to valid alphabetic outputs and reverse the mappings accurately .

The Hill Cipher uses matrix multiplication for both encryption and decryption processes. A message is represented as a vector and multiplied by a key matrix to produce the encrypted message. For decryption, the inverse of the key matrix is used. The significance of the key matrix's inversibility ensures that decryption is feasible; without an inverse, retrieving the original message from the encrypted text is impossible .

In the DES implementation, a symmetric key is generated using Java's KeyGenerator class. Randomness is introduced through a SecureRandom object seeded with a randomly generated number. This randomness ensures that each execution potentially produces a unique symmetric key, enhancing security by making the key difficult to predict or reproduce .

To convert a plaintext message into encrypted data using the Blowfish algorithm, the program selects or generates a symmetric key using KeyGenerator and SecureRandom classes. The plaintext is then converted to bytes, encrypted using a Cipher instance initialized with the key, and processed through doFinal() to produce encrypted bytes. During decryption, the same key is used in reverse to ensure that the encrypted data is accurately converted back to its original form, maintaining integrity by ensuring that the transformation is lossless and reversible .

Both DES and AES use symmetric key encryption, but they differ significantly in their operation modes. DES performs block encryption with a 56-bit key and operates on 64-bit blocks, utilizing a smaller key space, making it more vulnerable to brute force attacks. AES, on the other hand, uses varying key lengths (128, 192, or 256 bits) on 128-bit blocks, providing enhanced security. AES's design also includes a series of operations such as substitution-permutation networks, making it more resistant to cryptanalysis compared to the simpler, Feistel network approach of DES .

The primary function of XOR operations in this context is to manipulate and potentially obfuscate data by performing a bitwise operation. When applied to the string 'Hello World', each character is XORed with a specified value (127 in the example), altering the binary data of the string. The XOR operation between a character and zero results in the character itself, which highlights that using XOR with zero is a no-op .

Message digests are computed using hashing algorithms such as SHA-1 and MD5 by processing the input message into fixed-size blocks and applying a series of transformations. Padding is used to ensure that the input message is a multiple of the block size required by the hashing algorithm, while length encoding (typically adding the length of the original message in bits) ensures that differing inputs ultimately produce distinct hashes. These steps prevent potential hash collisions and ensure the completeness and consistency of the hashing process .

The Diffie-Hellman key exchange is based on principles of modular arithmetic and the difficulty of the discrete logarithm problem. Two parties agree on a large prime number and a base, then exchange computed values derived from their private keys. The shared secret is computed by each party independently using the other's public value. Since no direct key is transmitted, potential interceptors cannot easily derive it without solving the discrete logarithm problem, which is computationally infeasible .

Digital signature generation differs from encryption in that it primarily ensures authenticity and integrity rather than confidentiality. A digital signature involves hashing the message to create a digest, then encrypting this digest with the sender's private key. For verification, the recipient uses the sender's public key to decrypt the signature back into a hash and compares it with a newly generated hash of the message. These cryptographic processes confirm that the message has not been altered and authenticates the sender's identity .

Modular arithmetic is crucial in the RSA algorithm for both key generation and the encryption/decryption processes. Public and private keys are derived using Euler's totient function, which involves the calculation of a modulus from two prime numbers. The public key exponent 'e' and the private key 'd' are calculated such that 'd' is the modular inverse of 'e' modulo (p-1)(q-1), ensuring that encryption and decryption operations are feasible and reversible via modular arithmetic operations .

You might also like