0% found this document useful (0 votes)
97 views16 pages

NAS Codes: 1) Demonstrate Use of Symmetric Encryption and Decryption Algorithm

The document provides code examples for implementing various symmetric and asymmetric encryption algorithms: 1) A transposition cipher encryption/decryption example in Java. 2) A single DES encryption/decryption example in Java. 3) A single AES encryption/decryption example in Java using CBC mode with PKCS5 padding. 4) An RSA encryption/decryption example in Java using public/private key generation and modular exponentiation. 5) A Diffie-Hellman key exchange example in Java demonstrating exponential key agreement.

Uploaded by

Vaibhav Kukadi
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)
97 views16 pages

NAS Codes: 1) Demonstrate Use of Symmetric Encryption and Decryption Algorithm

The document provides code examples for implementing various symmetric and asymmetric encryption algorithms: 1) A transposition cipher encryption/decryption example in Java. 2) A single DES encryption/decryption example in Java. 3) A single AES encryption/decryption example in Java using CBC mode with PKCS5 padding. 4) An RSA encryption/decryption example in Java using public/private key generation and modular exponentiation. 5) A Diffie-Hellman key exchange example in Java demonstrating exponential key agreement.

Uploaded by

Vaibhav Kukadi
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/ 16

NAS Codes

1)Demonstrate use of symmetric encryption and decryption algorithm.

//Transposition(one of Encryption Technique)==NAS Prac_No-1

class Test_Transposition {

public static void main(String[] args){

String PlainText = "Welcome To Network Administration and Security";

String rst = transposition_encrypt(PlainText, 8);

System.out.println("Original Message==\n"+PlainText);

System.out.println("After Transposition==\n"+rst);

public static String transposition_encrypt(String plain, int Key){

int col = 0;

int a = 0;

String result = "";

String row;

col = plain.length()/Key;

if( plain.length()%Key != 0 )

col += 1;

char[] Plain_Arr = plain.toCharArray();

char[][] Plain_Arr2 = new char[col][Key];

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

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

if(a<plain.length()){
Plain_Arr2[i][j]=Plain_Arr[a++];

}else break;

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

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

if(Plain_Arr2[j][i]!=0)

result += Plain_Arr2[j][i];

return result;

OP==

2) To implement a single DES

//DES==NAS Prac_No-2
import java.util.*;

import javax.crypto.BadPaddingException;

import javax.crypto.Cipher;

import javax.crypto.IllegalBlockSizeException;

import javax.crypto.KeyGenerator;

import javax.crypto.NoSuchPaddingException;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.DESKeySpec;

import java.io.*;

import java.security.InvalidKeyException;

import java.security.NoSuchAlgorithmException;

import java.security.spec.InvalidKeySpecException;

class DES{

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


InvalidKeyException, InvalidKeySpecException, NoSuchPaddingException, IllegalBlockSizeException,
BadPaddingException {

String message="This is a confidential message.";

byte[] myMessage =message.getBytes(); //string to byte array as DES works on bytes

KeyGenerator Mygenerator = KeyGenerator.getInstance("DES");

SecretKey myDesKey = Mygenerator.generateKey();

Cipher myCipher = Cipher.getInstance("DES");

myCipher.init(Cipher.ENCRYPT_MODE, myDesKey);

byte[] myEncryptedBytes=myCipher.doFinal(myMessage);
myCipher.init(Cipher.DECRYPT_MODE, myDesKey);

byte[] myDecryptedBytes=myCipher.doFinal(myEncryptedBytes);

String encrypteddata=new String(myEncryptedBytes);

String decrypteddata=new String(myDecryptedBytes);

System.out.println("Message : "+ message);

System.out.println("Encrypted - "+ encrypteddata);

System.out.println("Decrypted Message - "+ decrypteddata);

OP==

3)To implement a single AES

//AES==NAS Prac_No-3

import java.nio.charset.StandardCharsets;

import java.security.spec.KeySpec;
import java.util.Base64;

import javax.crypto.Cipher;

import javax.crypto.SecretKey;

import javax.crypto.SecretKeyFactory;

import javax.crypto.spec.IvParameterSpec;

import javax.crypto.spec.PBEKeySpec;

import javax.crypto.spec.SecretKeySpec;

class AES {

private static final String SECRET_KEY

= "my_super_secret_key_ho_ho_ho";

private static final String SALT = "ssshhhhhhhhhhh!!!!";

public static String encrypt(String strToEncrypt)

try {

byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0,

0, 0, 0, 0, 0, 0, 0, 0 };

IvParameterSpec ivspec

= new IvParameterSpec(iv);

SecretKeyFactory factory

= SecretKeyFactory.getInstance(

"PBKDF2WithHmacSHA256");

KeySpec spec = new PBEKeySpec(


SECRET_KEY.toCharArray(), SALT.getBytes(),

65536, 256);

SecretKey tmp = factory.generateSecret(spec);

SecretKeySpec secretKey = new SecretKeySpec(

tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance(

"AES/CBC/PKCS5Padding");

cipher.init(Cipher.ENCRYPT_MODE, secretKey,

ivspec);

return Base64.getEncoder().encodeToString(

cipher.doFinal(strToEncrypt.getBytes(

StandardCharsets.UTF_8)));

catch (Exception e) {

System.out.println("Error while encrypting: "

+ e.toString());

return null;

public static String decrypt(String strToDecrypt)

try {

byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0,

0, 0, 0, 0, 0, 0, 0, 0 };

IvParameterSpec ivspec
= new IvParameterSpec(iv);

SecretKeyFactory factory

= SecretKeyFactory.getInstance(

"PBKDF2WithHmacSHA256");

KeySpec spec = new PBEKeySpec(

SECRET_KEY.toCharArray(), SALT.getBytes(),

65536, 256);

SecretKey tmp = factory.generateSecret(spec);

SecretKeySpec secretKey = new SecretKeySpec(

tmp.getEncoded(), "AES");

Cipher cipher = Cipher.getInstance(

"AES/CBC/PKCS5PADDING");

cipher.init(Cipher.DECRYPT_MODE, secretKey,

ivspec);

return new String(cipher.doFinal(

Base64.getDecoder().decode(strToDecrypt)));

catch (Exception e) {

System.out.println("Error while decrypting: "

+ e.toString());

return null;

class AES_Main {
public static void main(String[] args)

String originalString = "HelloPRMITR";

String encryptedString

= AES.encrypt(originalString);

String decryptedString

= AES.decrypt(encryptedString);

System.out.println("Oginal String=="+originalString);

System.out.println("Encrypted String=="+encryptedString);

System.out.println("Decrypted String=="+decryptedString);

OP==

4) To implement RSA encryption /decryption algorithm.

//RSA==NAS Prac_No-4

import java.math.*;
import java.util.*;

class Test_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);

System.out.println("the value of z = " + z);

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

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

BigInteger N = BigInteger.valueOf(n);

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

OP==
5)Diffie-Hellman key exchange (exponential key exchange)

//Diffie-Hellman key exchange==NAS Prac_No-5

import java.util.*;

class Test_DHAlgEx {

public static void main(String[] args)

long P, G, x, a, y, b, ka, kb;

Scanner sc = new Scanner(System.in);

System.out.println("Both the users should be agreed upon the public keys G and P");

System.out.println("Enter value for public key G:");

G = sc.nextLong();

System.out.println("Enter value for public key P:");

P = sc.nextLong();

System.out.println("Enter value for private key a selected by user1:");

a = sc.nextLong();

System.out.println("Enter value for private key b selected by user2:");

b = sc.nextLong();

x = calculatePower(G, a, P);
y = calculatePower(G, b, P);

ka = calculatePower(y, a, P);

kb = calculatePower(x, b, P);

System.out.println("Secret key for User1 is:" + ka);

System.out.println("Secret key for User2 is:" + kb);

private static long calculatePower(long x, long y, long P)

long result = 0;

if (y == 1){

return x;

else{

result = ((long)Math.pow(x, y)) % P;

return result;

OP==
6) To find MAC (Message Authentication Code) algorithm for cryptographic checksum.

//MAC==NAS Prac_No-6

import java.security.Key;

import java.security.SecureRandom;

import javax.crypto.KeyGenerator;

import javax.crypto.Mac;

class Test_MacSample {

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

KeyGenerator keyGen = KeyGenerator.getInstance("DES");

SecureRandom secRandom = new SecureRandom();

keyGen.init(secRandom);
Key key = keyGen.generateKey();

Mac mac = Mac.getInstance("HmacSHA256");

mac.init(key);

String msg = new String("HelloPrmitrStudents");

byte[] bytes = msg.getBytes();

byte[] macResult = mac.doFinal(bytes);

System.out.println("Mac result:");

System.out.println(new String(macResult));

OP==

7) //MD==NAS Prac_No-7

import java.math.BigInteger;

import java.security.MessageDigest;

import java.security.NoSuchAlgorithmException;

class Test_MD5 {
public static String getMd5(String input)

try {

MessageDigest md = MessageDigest.getInstance("MD5");

byte[] messageDigest = md.digest(input.getBytes());

BigInteger no = new BigInteger(1, messageDigest);

String hashtext = no.toString(16);

while (hashtext.length() < 32) {

hashtext = "0" + hashtext;

return hashtext;

catch (NoSuchAlgorithmException e) {

throw new RuntimeException(e);

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

String s = "GeeksForGeeks";

System.out.println("Your HashCode Generated by MD5 is: " + getMd5(s));

}
OP==

You might also like