0% found this document useful (0 votes)
32 views11 pages

Cns Lab Programs

Lab pand fourth progress for computers and science students can learn with
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)
32 views11 pages

Cns Lab Programs

Lab pand fourth progress for computers and science students can learn with
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/ 11

1b.......

// Caesar cipher
import java.util.Scanner;
public class caesar{
public static String encrypt(String str, int key)
{
String encrypted = "";
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (Character.isUpperCase(c))
{
c = (char) (c + key);
if (c > 'Z') {
c = (char) (c - 26);
}
}
else if (Character.isLowerCase(c))
{
c = (char) (c + key);
if (c > 'z')
{
c = (char) (c - 26);
}
}
encrypted += c;
}
return encrypted;
}
public static String decrypt(String str, int key)
{
String decrypted = "";
for (int i = 0; i < str.length(); i++)
{
char c = str.charAt(i);
if (Character.isUpperCase(c))
{
c = (char) (c - key);
if (c < 'A')
{
c = (char) (c + 26);
}
} else if (Character.isLowerCase(c))
{
c = (char) (c - key);
if (c < 'a')
{
c = (char) (c + 26);
}
}
decrypted += c;
}
return decrypted;
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
System.out.println("Enter any string: ");
String inputStr = sc.nextLine();
System.out.println("Enter the key: ");
int shiftKey = Integer.valueOf(sc.nextLine());
System.out.println("Encrypted string is: " + encrypt(inputStr, shiftKey));
System.out.println("Decrypted string is: " + decrypt(encrypt(inputStr, shiftKey), shiftKey));
sc.close();
}
}

1c....

#include <stdio.h>
int main() {
char *str="Hello World";
char result[12];
for(int i=0;str[i]!='\0';i++)
{
result[i]=str[i]^0;
}
result[11]='\0';
printf("XOR-ed Result:%s",result);
}

2b....
//SubstitutionCipher
import java.io.*;
import java.util.*;

public class Main {


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

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


String a = "abcdefghijklmnopqrstuvwxyz";
String b1 = "zyxwvutsrqponmlkjihgfedcba";
String b2 = "bcdefghijklmnopqrstuvwxyza";
String b3 = "cdefghijklmnopqrstuvwxyzab";
System.out.print("Enter any string: ");
String str = br.readLine().toLowerCase();
String decrypt1 = "";
String decrypt2 = "";
String decrypt3 = "";
for (int i = 0; i < str.length(); i++) {
char c = str.charAt(i);
int j = a.indexOf(c);

// If character is not in the alphabet (e.g., space or punctuation), keep it as is


if (j == -1) {
decrypt1 += c;
decrypt2 += c;
decrypt3 += c;
} else {
decrypt1 += b1.charAt(j); // Substitute using b1
decrypt2 += b2.charAt(j); // Substitute using b2
decrypt3 += b3.charAt(j); // Substitute using b3
}
}
System.out.println("The encrypted data using b1 is: " + decrypt1);
System.out.println("The encrypted data using b2 is: " + decrypt2);
System.out.println("The encrypted data using b3 is: " + decrypt3);
}
}

2c...
#include <stdio.h>
int main() {
char *str="Hello World";
char AND[12];
char OR[12];
char XOR[12];
for(int i=0;str[i]!='\0';i++)
{
AND[i]=str[i]&127;
OR[i]=str[i]|127;
XOR[i]=str[i]^127;
}
AND[11]='\0';
OR[11]='\0';
XOR[11]='\0';
printf("AND Result:%s",AND);
printf("\nOR-ed Result:%s",OR);
printf("\nXOR-ed Result:%s",XOR);
}

3.....
//hill cipher
class hillcipher {
public static int[][] keymat = new int[][] { { 17, 17, 5 }, { 21, 18, 21 }, { 2, 2, 19 } };
public static int[][] invkeymat = new int[][] { { 4, 9, 15 }, { 15, 17, 6 }, { 24, 0, 17 } };
public static String key = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";

private static String encode(char a, char b, char c) {


String ret = "";
int x, y, z;
int posa = (int) a - 65;
int posb = (int) b - 65;
int posc = (int) c - 65;
x = posa * keymat[0][0] + posb * keymat[1][0] + posc * keymat[2][0];
y = posa * keymat[0][1] + posb * keymat[1][1] + posc * keymat[2][1];
z = posa * keymat[0][2] + posb * keymat[1][2] + posc * keymat[2][2];

a = key.charAt(x % 26);
b = key.charAt(y % 26);
c = key.charAt(z % 26);

ret = "" + a + b + c;
return ret;
}

private static String decode(char a, char b, char c) {


String ret = "";
int x, y, z;
int posa = (int) a - 65;
int posb = (int) b - 65;
int posc = (int) c - 65;
x = posa * invkeymat[0][0] + posb * invkeymat[1][0] + posc * invkeymat[2][0];
y = posa * invkeymat[0][1] + posb * invkeymat[1][1] + posc * invkeymat[2][1];
z = posa * invkeymat[0][2] + posb * invkeymat[1][2] + posc * invkeymat[2][2];

a = key.charAt((x % 26 < 0) ? (26 + x % 26) : (x % 26));


b = key.charAt((y % 26 < 0) ? (26 + y % 26) : (y % 26));
c = key.charAt((z % 26 < 0) ? (26 + z % 26) : (z % 26));

ret = "" + a + b + c;
return ret;
}

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


String msg;
String enc = "";
String dec = "";
int n;

msg = ("paymoremoney");
System.out.println("Simulation of Hill Cipher\n-------------------------");
System.out.println("Input message : " + msg);

msg = msg.toUpperCase();
msg = msg.replaceAll("\\s", ""); // Remove spaces
n = msg.length() % 3;

if (n != 0) { // Pad the message if length is not a multiple of 3


for (int i = 1; i <= (3 - n); i++) {
msg += 'X';
}
}

System.out.println("Padded message : " + msg);


char[] pdchars = msg.toCharArray();

// Encoding
for (int i = 0; i < msg.length(); i += 3) {
enc += encode(pdchars[i], pdchars[i + 1], pdchars[i + 2]);
}
System.out.println("Encoded message : " + enc);

// Decoding
char[] dechars = enc.toCharArray();
for (int i = 0; i < enc.length(); i += 3) {
dec += decode(dechars[i], dechars[i + 1], dechars[i + 2]);
}
System.out.println("Decoded message : " + dec);
}
}
4.....
//DES
import java.io.*;
import java.security.*;
import java.security.spec.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class DES3 {


private static Cipher encrypt;
private static Cipher decrypt;
private static final byte[] initialization_vector = { 22, 33, 11, 44, 55, 99, 66, 77 };
public static void main(String[] args) {
String textFile = "C:/Users/HP/OneDrive/Desktop/input.txt";
String encryptedData = "C:/Users/HP/OneDrive/Desktop/encrypteddata.txt";
String decryptedData = "C:/Users/HP/OneDrive/Desktop/decrypteddata.txt";
try {
SecretKey scrtkey = KeyGenerator.getInstance("DES").generateKey();
AlgorithmParameterSpec aps = new IvParameterSpec(initialization_vector);
encrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
encrypt.init(Cipher.ENCRYPT_MODE, scrtkey, aps);
decrypt = Cipher.getInstance("DES/CBC/PKCS5Padding");
decrypt.init(Cipher.DECRYPT_MODE, scrtkey, aps);
encryption(new FileInputStream(textFile), new FileOutputStream(encryptedData));
decryption(new FileInputStream(encryptedData), new FileOutputStream(decryptedData));
System.out.println("The encrypted and decrypted files have been created successfully.");
}
catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException |
InvalidAlgorithmParameterException | IOException e)
{
e.printStackTrace();
}
}
private static void encryption(InputStream input, OutputStream output) throws IOException {
output = new CipherOutputStream(output, encrypt);
writeBytes(input, output);
}
private static void decryption(InputStream input, OutputStream output) throws IOException {
input = new CipherInputStream(input, decrypt);
writeBytes(input, output);
}
private static void writeBytes(InputStream input, OutputStream output) throws IOException {
byte[] writeBuffer = new byte[512];
int readBytes = 0;
while ((readBytes = input.read(writeBuffer)) >= 0) {
output.write(writeBuffer, 0, readBytes);
}
output.close();
input.close();
}
}
5....
//Blowfish
import java.io.*;
import java.security.*;
import javax.crypto.*;
import javax.crypto.spec.*;

public class BlowfishFile {


private static final String ALGORITHM = "Blowfish";
private static String key = "BRECW";
private static final String SAMPLE_FILE_PATH = "C:/Users/HP/OneDrive/Desktop/input.txt";
private static final String ENCRYPTED_FILE_PATH =
"C:/Users/HP/OneDrive/Desktop/encrypteddata1.txt";
private static final String DECRYPTED_FILE_PATH =
"C:/Users/HP/OneDrive/Desktop/decrypteddata2.txt";

public static void main(String[] args) {


File sampleFile = new File(SAMPLE_FILE_PATH);
File encryptedFile = new File(ENCRYPTED_FILE_PATH);
File decryptedFile = new File(DECRYPTED_FILE_PATH);

try {
encrypt(sampleFile, encryptedFile);
decrypt(encryptedFile, decryptedFile);
} catch (Exception e) {
e.printStackTrace();
}
}

public static void encrypt(File sampleFile, File outputFile) throws Exception {


doCrypto(Cipher.ENCRYPT_MODE, sampleFile, outputFile);
}

public static void decrypt(File sampleFile, File outputFile) throws Exception {


doCrypto(Cipher.DECRYPT_MODE, sampleFile, outputFile);
}

private static void doCrypto(int cipherMode, File sampleFile, File outputFile) throws Exception {
Key secretKey = new SecretKeySpec(key.getBytes(), ALGORITHM);
Cipher cipher = Cipher.getInstance(ALGORITHM);
cipher.init(cipherMode, secretKey);

InputStream inputStream = new FileInputStream(sampleFile);


byte[] inputBytes = new byte[(int) sampleFile.length()];
inputStream.read(inputBytes);

byte[] outputBytes = cipher.doFinal(inputBytes);

OutputStream outputStream = new FileOutputStream(outputFile);


outputStream.write(outputBytes);

inputStream.close();
outputStream.close();
}
}
6....
//AES or Rijndael
import javax.crypto.*;
import javax.crypto.spec.GCMParameterSpec;
import java.util.Base64;

public class AES1 {


private SecretKey key;
private final int KEY_SIZE = 128;
private final int DATA_LENGTH = 128;
private Cipher encryptionCipher;

public void init() throws Exception {


KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
keyGenerator.init(KEY_SIZE);
key = keyGenerator.generateKey();
}

public String encrypt(String data) throws Exception {


byte[] dataInBytes = data.getBytes();
encryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
encryptionCipher.init(Cipher.ENCRYPT_MODE, key);
byte[] encryptedBytes = encryptionCipher.doFinal(dataInBytes);
return encode(encryptedBytes);
}

public String decrypt(String encryptedData) throws Exception {


byte[] dataInBytes = decode(encryptedData);
Cipher decryptionCipher = Cipher.getInstance("AES/GCM/NoPadding");
GCMParameterSpec spec = new GCMParameterSpec(DATA_LENGTH, encryptionCipher.getIV());
decryptionCipher.init(Cipher.DECRYPT_MODE, key, spec);
byte[] decryptedBytes = decryptionCipher.doFinal(dataInBytes);
return new String(decryptedBytes);
}

private String encode(byte[] data) {


return Base64.getEncoder().encodeToString(data);
}

private byte[] decode(String data) {


return Base64.getDecoder().decode(data);
}

public static void main(String[] args) {


try {
AES1 AES1 = new AES1();
AES1.init();
String encryptedData = AES1.encrypt("This is CSE");
String decryptedData = AES1.decrypt(encryptedData);
System.out.println("Encrypted Data : " + encryptedData);
System.out.println("Decrypted Data : " + decryptedData);
} catch (Exception ignored) { }
}
}
7....
//rc4
import java.io.*;
class rc4 {
public static void main(String[] args) throws IOException {
int temp;
String plaintext;
String key;
int[] s = new int[256];
int[] k = new int[256];
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nENTER PLAIN TEXT\t");
plaintext = reader.readLine();
System.out.print("\n\nENTER KEY TEXT\t\t");
key = reader.readLine();
// Convert plaintext and key to character arrays
char[] plaintextChars = plaintext.toCharArray();
char[] keyChars = key.toCharArray();
// Initialize arrays for cipher and decryption
int[] cipher = new int[plaintext.length()];
int[] decrypted = new int[plaintext.length()];
int[] plaintextInts = new int[plaintext.length()];
int[] keyInts = new int[key.length()];
for (int i = 0; i < plaintext.length(); i++) {
plaintextInts[i] = plaintextChars[i];
}
for (int i = 0; i < key.length(); i++) {
keyInts[i] = keyChars[i];
}
for (int i = 0; i < 256; i++) {
s[i] = i;
k[i] = keyInts[i % key.length()];
}
int j = 0;
for (int i = 0; i < 256; i++) {
j = (j + s[i] + k[i]) % 256;
temp = s[i];
s[i] = s[j];
s[j] = temp;
}
int i = 0, z;
j = 0;
for (int l = 0; l < plaintext.length(); l++) {
i = (i + 1) % 256;
j = (j + s[i]) % 256;
temp = s[i];
s[i] = s[j];
s[j] = temp;
z = s[(s[i] + s[j]) % 256];
cipher[l] = z ^ plaintextInts[l];
decrypted[l] = z ^ cipher[l];
}
System.out.print("\n\nENCRYPTED:\t\t");
display(cipher);
System.out.print("\n\nDECRYPTED:\t\t");
display(decrypted);
}
static void display(int[] data) {
for (int value : data) {
System.out.print((char) value);
}
}
}

8....
//RSA (Rivest, Shamir, Adleman)
import java.util.*;
import java.math.*;

class rsa {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
int p,q,n,z,d=0,e,i;
System.out.println("Enter the number to be encrypted and decrypted");
int msg=sc.nextInt();
double c;
BigInteger msgback;
System.out.println("Enter 1st prime number p");
p=sc.nextInt();
System.out.println("Enter 2nd prime number q");
q=sc.nextInt();
n=p*q;
z=(p-1)*(q-1);
System.out.println("the value of z = "+z);
for(e=2;e<z;e++) {
if(gcd(e,z)==1) { // e is for public key exponent
break; }
}
System.out.println("the value of e = "+e);
for(i=0;i<=9;i++)
{
int x=1+(i*z);
if(x%e==0) //d is for private key exponent
{
d=x/e;
break;
}
}
System.out.println("the value of d = "+d);
c=(Math.pow(msg,e))%n;
System.out.println("Encrypted message is : -");
System.out.println(c);
BigInteger N = BigInteger.valueOf(n); //converting int value of n to BigInteger
//converting float value of c to BigInteger
BigInteger C = BigDecimal.valueOf(c).toBigInteger();
msgback = (C.pow(d)).mod(N);
System.out.println("Derypted message is : -");
System.out.println(msgback); }

static int gcd(int e, int z) {


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

9....
//Diffie–Hellman Key Exchange

import java.util.*;
class Diffie_Hellman {
public static void main(String args[]) {
Scanner sc=new Scanner(System.in);
System.out.println("Enter modulo(p)");
int p=sc.nextInt();
System.out.println("Enter primitive root of "+p);
int g=sc.nextInt();
System.out.println("Choose 1st secret no of A");
int a=sc.nextInt();
System.out.println("Choose 2nd secret no of B");
int b=sc.nextInt();
int A = (int)Math.pow(g,a)%p;
int B = (int)Math.pow(g,b)%p;

int S_A = (int)Math.pow(B,a)%p;


int S_B =(int)Math.pow(A,b)%p;

if(S_A==S_B) {
System.out.println("Al and can communicate with each other!!!");
System.out.println("They share a secret no = "+S_A); }

else {
System.out.println("A and B cannot communicate with each other!!!");
}
}
}

10...
//Sha
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

class Sha {
public static byte[] getSHA(String input) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-512");
return md.digest(input.getBytes(StandardCharsets.UTF_8));
}

public static String toHexString(byte[] hash) {


BigInteger number = new BigInteger(1, hash);
StringBuilder hexString = new StringBuilder(number.toString(16));
while (hexString.length() < 32) {
hexString.insert(0, "0");
}
return hexString.toString();
}

public static void main(String args[]) {


try {
System.out.println("HashCode Generated by SHA-512 for:");
String s1 = "This is SHA-512";
System.out.println("\n" + s1 + ": " + toHexString(getSHA(s1)));

String s2 = "Use Hash Function";


System.out.println("\n" + s2 + ": " + toHexString(getSHA(s2)));
} catch (NoSuchAlgorithmException e) {
System.out.println("Exception thrown for incorrect algorithm: " + e);
}
}
}

11.....
// MD5
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {


public static String getMd5Hash(String input) {
try {
// static getInstance() method is called with hashing MD5
MessageDigest md = MessageDigest.getInstance("MD5");
// calculating message digest of an input that return array of byte
byte[] messageDigest = md.digest(input.getBytes());
// converting byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// converting message digest into hex value
String hashtext = no.toString(16);
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
}
return hashtext;
}
// for specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}

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


String s = "This is CSE";
System.out.println("The plain text is: " + s);
System.out.println("HashCode Generated for the string is: " + getMd5Hash(s));
}
}

You might also like