Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

CC Lab Spiral.

Download as pdf or txt
Download as pdf or txt
You are on page 1of 28

INDEX

EX.NO DATE EXCERCISE STAFF SIGN

1. XOR String with Zero

2. XOR String with 127

3. Encryption And Decryption Using Algorithm.

4. DES Algorithm Logic

5. BlowFish Algorithm Logic

6. Rijndael Algorithm Logic

7. Cryptography Using BlowFish

8. RSA Algorithm

9. Diffie-Hellman Key Exchange

10. SHA Algorithm


XOR String with Zero

AIM:

To write a c program that contain XOR each character in this string with zero.

Source Code:

#include<stdlib.h>

#include<conio.h>

#include<string.h>

#include<stdio.h>

void main()

clrscr();

char str[] = "HelloWorld";

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

getch();

}
Output:

Result:
Thus the program was successfully executed.
XOR a string with 127

Aim:
To write a C program that contain a string with a value hello world with AND or and 127.

SOURCE CODE:

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<stdlib.h>

void main()
{
clrscr();

char str[]="Hello World";

char str1[11];

char str2[11];

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++)
{
str2[i]=str[i]^127;

printf("%c", str2[i]);
}
printf("\n");

getch();
}
Output:

Result:
Thus the program was successfully executed.
Encryption And Decryption Using Algorithm

Aim:
To write a java program to perform encryption and decryption using algorithm.

Source Code:

a) Ceaser Cipher

import java.io.BufferedReader:

import java.io.IOException:

import java.io.InputStreamReader:

import java.util.Scanner:

public class CeaserCipher {


static Scanner sc-new Scanner(System.in);

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); public static void


main(String[] args) throws IOException {

// TODO code application logic here

System.out.print("Enter any String: "); String str = br.readLine(); System.out.print("\nEnter the Key: ");

int key sc.nextInt():

String encrypted = encrypt(str, key):

System.out.println("\nEncrypted String is: "+encrypted): String decrypted = decrypt(encrypted. key);


System.out.println("\nDecrypted String is: "+decrypted); System.out.println("\n");

public static String encrypt(String str, int key)

String encrypted = "";

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


{

int c = str.charAt(i):

if (Character.isUpperCase(c))

c=c+(key % 26);

if (c>'Z') cc-26:

else if (Character.isLowerCase(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 < str.length(): i++)

int c = str.charAt(i):

if (Character.isUpperCase(c))

c=c(key% 26):

if (c<'A') c = c + 26:

else if (Character.isLowerCase(c))
{

c=c-(key% 26); thu

if (c'a') cc+26:

}
decrypted += (char) c:
}
}
return decrypted;
}

b) Substitution Cipher

PROGRAM:

import java.io.*;

import java.util.*;

public class SubstitutionCipher {

static Scanner sc = new Scanner(System.in);

static BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

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

// TODO code application logic here


String a = "abcdefghijklmnopqrstuvwxyz";

String b = "zyxwvutsrqponmlkjihgfedcba": System.out.print("Enter any string: ");

String str = br.readLine():

String decrypt = "";

char c:

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

c = str.charAt(i):

int j = a.indexOf(c):

decrypt = decrypt+b.charAt(j):

System.out.println("The encrypted data is: "+decrypt);

c)Hill Cipher

PROGRAM:

import java.io.*;

import java.util.*;

import java.io.*;

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(System.in)):

static Scanner sc = new Scanner(System.in);


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

/ TODO code application logic here /

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]:
}

System.out.print("\nEncrypted string is: ");

for(int i=0;i<3;i++)
{
System.out.print((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]:

} System.out.print("\nDecrypted string is: ");

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

{ System.out.print((char)(decrypt[i][0]%26+97));
}

System.out.print("\n");

} public static void getkeymes() throws IOException { System.out.println("Enter 3x3 matrix for key (It
should be inversible): ");

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

a[i][j] = sc.nextFloat();

System.out.print("\nEnter a 3 letter string: ");

String msg = br.readLine();

for(int i=0;i<3;i++) mes[i][0] = msg.charAt(i)-97;

public static void inverse()

floatp.q: float[][] c = a:

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

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

//a[i][j]=sc.nextFloat():

if(ij) 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:i++)

{
if(i!=k)
{
c[i][j]c[i][j]*q-p*c[k][j]:
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]:
}

System.out.println("");

System.out.println("\nInverse Matrix is: ");


for(int i=0;i<3;i++)
{
for(int j=0;j<3:j++)
System.out.print(b[i][j] + " ");
System.out.print("\n"):
}
}
}
Output:

Result:

Thus the program was successfully executed.


DES Algorithm logic
Aim:
To write a java program to implement the DES algorithm logic.

SOURCE CODE:

import javax.crypto.*;
import javax.crypto.spec.SecretKeySpec;
public class DESAlgorithm {
public static void main(String[] args) throws Exception {
String plainText = "Hello, world!";
String key = "mySecretKey"; // Replace with your secret key

// Encryption
byte[] encrypted = encrypt(plainText, key);
System.out.println("Encrypted text: " + new String(encrypted));

// Decryption
String decrypted = decrypt(encrypted, key);
System.out.println("Decrypted text: " + decrypted);
}
public static byte[] encrypt(String plainText, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
SecretKey secretKey = new SecretKeySpec(key.getBytes(), "DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
return cipher.doFinal(plainText.getBytes());
}
public static String decrypt(byte[] cipherText, String key) throws Exception {
Cipher cipher = Cipher.getInstance("DES");
SecretKey secretKey = new SecretKeySpec(key.getBytes(), "DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey);
byte[] decryptedBytes = cipher.doFinal(cipherText);
return new String(decryptedBytes);
}
}
Output:

Result:
Thus the above program was successfully executed.
BLOWFISH Algorithm Logic

Aim:
To write a program to implement the Blowfish algorithm Logic.

Source Code:

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class BlowfishExample {

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


String key = "MySecretKey";
String text = "Hello, world!";

byte[] encrypted = encrypt(key, text);


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

String decrypted = decrypt(key, encrypted);


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

public static byte[] encrypt(String key, String text) throws Exception {


SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
return cipher.doFinal(text.getBytes());
}

public static String decrypt(String key, byte[] encrypted) throws Exception {


SecretKeySpec secretKeySpec = new SecretKeySpec(key.getBytes(), "Blowfish");
Cipher cipher = Cipher.getInstance("Blowfish");
cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
byte[] decrypted = cipher.doFinal(encrypted);
return new String(decrypted);
}
}
Output:

Result:

Thus the program was successfully executed.


Rijndael Algorithm Logic

AIM:

To write a program to implement the Rijndael algorithm logic.

SOURCE CODE:

import javax.crypto.*;

import javax.crypto.spec.*;

class Rijndael {

private static String asHex(byte buf[]) {

StringBuffer strbuf = new

StringBuffer(buf.length*2);

int i;

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

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

strbuf.append("0");

strbuf.append(Long.toString((int)buf[i]&0xff,16));

return strbuf.toString();

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

String message = "ONLINE SMART TRAINER";

//Get the KeyGenerator

KeyGenerator kgen=
KeyGenerator.getInstance("AES");

kgen.init(128); //192 and 256 bits may not be

available

//Generate the secret key specs.

SecretKey skey = kgen.generateKey();

byte[] raw = skey.getEncoded();

SecretKeySpec skeySpec= new

SecretKeySpec(raw,"AES");

// Instantiate the cipher

Cipher cipher = Cipher.getInstance("AES");

cipher.init(Cipher. ENCRYPT_MODE,skeySpec);

byte encrypted=

cipher.doFinal((args.length==0? message:

args[0]).getBytes());

System.out.println("Encrypted String: " +

asHex(encrypted));

cipher.init(Cipher.DECRYPT_MODE,skeySpec);

byte[]original=cipher.doFinal(encrypted);

String originalString=new String(original);

System.out.println("Original String in

Hexadecimal: " + asHex(original));

System.out.println("Original String: " + originalString);

}
Output:

Result:

Thus the program was successfully executed.


Cryptography Using BlowFish

Aim:

To write java Cryptography, encrypt the text “Hello World” using BlowFish.

Source Code:

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.security.SecureRandom;

public class Main {


public static void main(String[] args) throws Exception {
String text = “hello world”;

// Generate a Blowfish key


KeyGenerator keyGenerator = KeyGenerator.getInstance(“Blowfish”);
keyGenerator.init(new SecureRandom());
SecretKey secretKey = keyGenerator.generateKey();

// Create a Cipher instance for encryption


Cipher cipher = Cipher.getInstance(“Blowfish”);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);

// Encrypt the text


byte[] encryptedBytes = cipher.doFinal(text.getBytes(StandardCharsets.UTF_8));

// Print the encrypted text


System.out.println(“Encrypted text: “ + new String(encryptedBytes, StandardCharsets.UTF_8));
}}
Output:

Result:
Thus the program was successfully executed.
RSA Algorithm

AIM:

To write a program to implement the RSA algorithm.

SOURCE CODE:

import java.math.*;
import java.util.*;
class RSA {
public static void main(String args[])
{
int p, q, n, z, d = 0, e, i;

// The number to be encrypted and decrypted


int msg = 12;
double c;
BigInteger msgback;

// 1st prime number p


p = 3;

// 2nd prime number q


q = 11;
n = p * q;
z = (p - 1) * (q - 1);
System.out.println("the value of z = " + z);

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

// e is for public key exponent


if (gcd(e, z) == 1) {
break;
}
}
System.out.println("the value of e = " + e);
for (i = 0; i <= 9; i++) {
int x = 1 + (i * z);

// d is for private key exponent


if (x % e == 0) {
d = x / e;
break;
}
}
System.out.println("the value of d = " + d);
c = (Math.pow(msg, e)) % n;
System.out.println("Encrypted message is : " + c);

// converting int value of n to BigInteger


BigInteger N = BigInteger.valueOf(n);

// converting float value of c to BigInteger


BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
System.out.println("Decrypted message is : "
+ msgback);
}

static int gcd(int e, int z)


{
if (e == 0)
return z;
else
return gcd(z % e, e);
}
}

Output:

Result:
Thus the program was successfully executed
Diffie-Hellman Key Exchange

Aim:
To implement the Diffie-Hellman Key Exchange mechanism using HTML and Javascript.

Source Code:

<script>

// This program calculates the Key for two persons


// using the Diffie-Hellman Key exchange algorithm

// Power function to return value of a ^ b mod P


function power(a, b, p)
{
if (b == 1)
return a;
else
return((Math.pow(a, b)) % p);
}

// Driver code
var P, G, x, a, y, b, ka, kb;

// Both the persons will be agreed upon the


// public keys G and P

// A prime number P is taken


P = 23;
document.write("The value of P:" + P + "<br>");

// A primitive root for P, G is taken


G = 9;
document.write("The value of G:" + G + "<br>");

// Alice will choose the private key a


// a is the chosen private key
a = 4;
document.write("The private key a for Alice:" +
a + "<br>");
// Gets the generated key
x = power(G, a, P);

// Bob will choose the private key b


// b is the chosen private key
b = 3;
document.write("The private key b for Bob:" +
b + "<br>");
// Gets the generated key
y = power(G, b, P);

// Generating the secret key after the exchange


// of keys
ka = power(y, a, P); // Secret key for Alice
kb = power(x, b, P); // Secret key for Bob

document.write("Secret key for the Alice is:" +


ka + "<br>");
document.write("Secret key for the Bob is:" +
kb + "<br>");
// This code is contributed by Ankita saini

</script>

Output:

Result:
Thus the program was successfully executed.
SHA Algorithm

Aim:
To calculate the message digest of a text using the SHA-1 algorithm in java.

Source Code:

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA1Example {


public static void main(String[] args) {
String text = "Hello, world!";

try {
MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
byte[] digest = sha1.digest(text.getBytes());
StringBuilder hexString = new StringBuilder();

for (byte b : digest) {


hexString.append(String.format("%02x", b));
}

System.out.println("SHA-1 Hash: " + hexString.toString());


} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
}
Output:

Result:

Thus the program was successfully executed.

You might also like