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.
Prog
#include
main()
'
char str{]="Hello World":
char strI[1 1];
int ivlen;
len=stel
for(i=0:i<
stel i}=stefi}0:
print{("%c",stel [i)):
)
(st
++)
printt("\n");
}
Output:
Hello World
© scanned with OKEN Scanner2.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
void main()
{
char str{]="Hello World";
char stri{11]:
char str2[11]=str[};
int iJen;
len = strlen(str);
for(i=0;i
intmain(intarge, char** argv)
7
charbuffer[100];
strncpy (buffer, argv[1], 100);
// We axe passing command line
// argument to printf
print£ (buffer);
return0;
}
Since printf has a variable number of arguments, it must use the format string to determine the
number of arguments. In the case above, the attacker can pass the string “%p Yep Yop Yop %p
%p Yop Yop Yop Yp %p %p %p %p %p” and fool the printf into thinking it has 15 arguments. It
Will naively print the next 15 addresses on the stack, thinking they are its arguments:
$ Ja.out "%p %p %p %p Yp %p %p %p %p Yop %p Yp Yep %p %p"
Oxtfffdddd 0x64 Oxt7ec1289 Oxtfffdbdf Oxffffdbde (nil) Oxflffdces Oxfftfde64 (nil)
0x25207025 0x70252070 0x20702520 0x25207025 0x70252070 0x20702520
Atabout 10 arguments up the stack, we can see a repeating pattern of 0x252070 — those are our
%ps on the stack! We start our string with AAAA to see this more explicitly
$ Ja.out “AAAA%p %p %p %p Yop %p %p %p Yp Yep"
AAAA Oxffffdde8 0x64 Oxf7ec 1289 Oxffffdbef Oxffffdbee (nil) Oxffffded4 Oxfttfde74 (nil)
0x41414141
© scanned with OKEN ScannerThe 0x41414141 is the hex representation of AAAA. We now have a way to pass an arbitrary
value (in this case, we're passing 0x4 1414141) as an argument to printf. At this point we will
take advantage of another format string feature: in a format specifier, we can also select a
specific argument. For example, printf("%2$x", 1, 2, 3) will print 2. In general, we can do
printf(“%$x") to select an arbitrary argument to printf. In our case, we see that 0x41414141 is
the 10th argument to printf, so we can simplify our string! :
$ Ja.out 'AAAA%108p
AAAA0x41414141
© scanned with OKEN Scanner4.Write a JAVA Program to perform eneryption and decryption.using
A.Ceaser Cipher B. Transposition Cipher
The Caesar Cipher technique is one of the earliest and simplest method of encryption
technique. It’s simply a type of substitution cipher, i., each letter of a given text is replaced
by a letter some fixed number of positions down the alphabet. For example with a shift of 1. A
would be replaced by B, B would become C, and so on. The method is apparently named after
Julius Caesar, who apparently used it’ to communicate with his officials.
Thus to cipher a given text we need an integer value, known as shift which indicates the
number of position each letter of the text has been moved down.
The encryption can be represented using modular arithmetic by first transforming the letters
into numbers, according to the scheme, A = 0, B = ,.... Z = 25. Encryption of a letter bya
shift n can be described mathematically as.
E,,(x) = (a + n)mod 26
(Encryption Phase with shift n)
Dy(x) = (a — n)mod 26
(Decryption Phase with shift n)
A[BIC|DIE]F
AJBIC
Algorithm for Caesar Cipher:
Input:
1. A String of lower-case letters, called Text.
2. An Integer between 0-25 denoting the required shift.
Procedure:
+ Traverse the given text one character at a time.
+ For each character, transform the given character as per the rule, depending on whether
we're encrypting or decrypting the text.
+ Return the new string generated
Program that receives a Text (string) and Shift value(integer) and returns the encrypted text.
Program:
import java.io. BufferedReader;
import java.io.lOException;
import java.io.InputStreamReader:
Page 1
© scanned with OKEN Scannerimport 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 Strin;
String str = br.readLine();
System.out.print(""\nEnter the Key: ");
int key = se.nextInt():
String enerypted = encrypt(str, key);
System.out.printin("\nEncrypted String is: " +encrypted);
String decrypted = decrypt(encrypted, key
System.out.printIn(""nDecrypted String is: " +decrypted);
System.out.printin("\n");
public static String enerypt(String str, int key)
{
String encrypted
for(int i= 0; i'Z’)
c= 0-26;
else if (Character.isLowerCase(c)) {
c=ct (key % 26);
if (¢>'2)
c=c-26;
}
encrypted += (char) c:
}
return encrypted;
}
public static String decrypt(String str, int key)
{ String decrypted = ""; for(int i = 0; i ‘hamxer’.
If the plaintext has an odd number of characters, append an 'x’ to the end to make it even.
Break the plaintext into pairs of letters. e.g. 'hamxer’ -> "ha mx er’
The algorithm now works on each of the letter pairs.
a
4.
5.
6.
Locate the letters in the key square, (the examples given are using the key square above)
a. Ifthe letters are in different rows and columns, replace the pair with the letters on the
same row respectively but at the other pair of corners of the rectangle defined by the
original pair. The order is important — the first encrypted letter of the pair is the one
that lies on the same row as the first plaintext letter. 'ha' -> 'bo', 'es' -> ‘il’
© scanned with OKEN Scannerb. Ifthe letters appear on the same row of the table, replace them with the letters to
ng around to the left side of the row if a
their immediate right respectively (wrapp
letter in the original pair was on the right side of the row). 'ma' -> ‘or’, ‘Ip’ > ‘pq?
c. Ifthe letters appear on the same column of the table, replace them with the letters
immediately below respectively (wrapping around to the top side of the column if'a
letter in the original pair was on the bottom side of the column). 'tk' -> ‘dt, ‘pv’ > ‘vo!
Clarification with pictures - Assume one wants to encrypt the digraph OR. There are three
general cases: [1]
1 m**a*
2, eee
3, eee
4. lt ts*
5, te aee
Hence, al ->ms
6. te eee
7. thybd
g teas
9, teaee
10, #*##*
Hence, hb -> yd
Tia" * 2%
12.**y**
13.4 HH
14. * qe
15. #*# wee
Hence, ng ->yw
© scanned with OKEN ScannerProgram:
import java.awt.Point;
import java.util. Scanner;
public class PlayfairCipher {
private static char{]{] charTable;
private static Point[] positions;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in):
String key = prompt("Enter an encryption key (min length 6): ", sc, 6):
String txt = prompt("Enter the message: ", sc, 1);
String jti = prompt("Replace J with I? y/n:". se, 1);
boolean changeJtol = jtiequalslgnoreCase(""y");
createTable(key, changeJtol);
String enc = encode(prepareText(txt, changeJtol));
System.out.printf("YnEncoded message: %n%s%n", enc);
System.out.printf("%nDecoded message: %on%s%n", decode(enc)):
}
private static String prompt(String promptText, Scanner sc, int minLen) {
String s;
do {
System.out.print(promptText);
s = sc.nextLine().trimQ;
} while (s.length() < minLen):
return s;
}
private static String prepareText(String s, boolean changeJtol) {
s = s.toUpperCase().replaceAll("[*A-Z]", ""):
return changeJtol ? s.replace("J", "I" place("Q". ");
,;
private static void createTable(String key, boolean changeltol) {
charTable = new char[5][5]:
positions = new Point[26];
String s = prepareText(key + "ABCDEFGHIKLMNOPQRSTUV WXYZ", changeltol):
int Ien = s.length(;
for (int i = 0, k= 0; i < len: i++) {
char c= s.charAt(i);
if (positions[e - 'A'] = null) {
charTablefk / 5][k % 5] =:
positions{c - 'A'] = new Point(k % 5, k/ 5);
kt
}
}
}
private static String encode(String s) {
StringBuilder sb = new StringBuilder(s);
for (int i = 0; i < sb.length(); i += 2) {
© scanned with OKEN ScannerIC (== sh.length() = 1)
sbaippend(sb,length() % 2
b.charAt(i),
sbainsert(i + 1.'X?);
)
return codee(sb, 1);
}
private stati
return cod
}
private 1g codee(
nt len textlength();
for (int i= 0 i
ing decode(String s) {
e(new StringBuilder(s), 4);
ringBuilder text, int direction) {
positionsfa -'A"
positions{b
int coll = positions[a -
int col2 7
if (rowl
coll = (coll + direction) % 5;
col2 + direction) % 5;
se i col2) {
rowl = (rowl + direction) % 5;
row2 = (row2 + direction) % 5;
}else {
int tmp = coll;
coll = col2;
col2 = tmp;
}
text.setCharAt(i, charTable{row!][col1});
textsetCharAt(i + 1, charTable[row2][col2});
}
return text.toString);
}
}
Outpt
Enter an encryption key (min length 6): 000000
Enter the message: addy
Replace J with 1? yin: y
Encoded message:
BEID
Decoded message:
ADDY
© scanned with OKEN Scanner6.Write a C/Java program to implement DES Logic
Program:
import java.util
import java.io.BufferedReader;
import java.io.InputStreamReader:
import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey:
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder:
import sun.mise.BASE64Encoder:
public class DES {
private static final String UNICODE_FORMAT = "U TF8";
public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
private KeySpec myKeySpec:
private SecretKeyFactory mySecretKeyFactory;
private Cipher cipher;
byte[] keyAsBytes;
private String myEneryptionKey;
private String myEncryptionScheme;
SecretKey key;
static BufferedReader br = new BufferedReader(new
InputStreamReader(System.in)); public DES() throws Exception {
TODO code application logic here
myEneryptionKey = "ThislsSecre
DESEDE_ENCRYPTION_SCHEM
myEneryptionKey.getBytes(UNICOD!
cryptionKey"; myEneryptionScheme =
eyAsBytes =
‘ORMAT); myKeySpec = new
Page 23
© scanned with OKEN ScannerDESedeKeySpee(keyAsBytes);
: clory = SecretK cyFactory wetlnstance(myLneryptionScheme); cipher =
Cipher.getInstance(myt
key = mySecreiKe
lory.generateSecret(myKeySpec);
}
public String encrypt(String unencryptedString)
{ String eneryptedString = null;
try {
cipher.init(Cipher.ENCRYPT_MODE. key);
byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
byte[] eneryptedText = cipher.doFinal(plain Text);
BASE64Encoder base64encoder = new BASE64Encoder();
encryptedString = base64encoder.encode(encryptedText); }
catch (Exception e) {
e.printStackTrace(); }
return encryptedString; }
public String decrypt(String encryptedString)
{ String decryptedText=null;
try {
cipher.init(Cipher DECRYPT_MODE. key):
BASE64Decoder base64decoder = new BASE64Decoder();
base64decoder.decodeBuffer(encryptedString); by
cipher.doFinal(encryptedText); decryptedTey
bytes2String(plainText); }
catch (Exception e) {
e.printStackTrace(); }
return decryptedText; }
private static String bytes2String(byte[] bytes) { StringButfer stringButter = new
StringBuffer();
for (int i= 0; i
#include
Iho find ged
int ged(int a, int h)
{
int temp;
while(1)
{
temp = a%h;
}
}
int main0)
{
1/2 random prime numbers
double p= 3;
double q=7;
double n=p*q;
double count;
double totient = (p-1)*(q-1);
public key
i/e stands for encrypt
INfor checking co-prime which satisfies e>1
while(e
inelude
1/ Power function to return value ofa b mod P
Tong long int power(long long int a, long long int b,
long long int P)
{
if(b==1)
return a;
else
return (((long long int)pow(a, b)) % P);
}
Driver program
int main()
{
long long int P, G. x. a. y. b, ka, kb
// Both the persons will be agreed upon the
1/ public keys G and P
P= 23; // A prime number P is taken
printf("The value of P : Ylld\n", P);
G=9; // A primitve root for P, G is taken
printf("The value of G : %lld\n\n", G);
/ Alice will choose the private key a
a= 4;///a is the chosen private key
printf(!"The private key a for Alice : %lld\n", a);
x= power(G, a, P);// gets the generated key
// Bob will choose the private key b
b = 3: //bis the chosen private key
print{("The private key b for Bob : %lld\n\n", b);
a
© scanned with OKEN ScannerY= power(G, b, P); // gets the generated key
// Generating the secret key after the exchange
Hof keys
ka= power(y, a, P); // Secret key for Alice
kb = power(x, b, P); // Secret key for Bob
printf("Secret key for the Alice is : %lld\n", ka);
printf("Secret Key for the Bob is : %lld\n", kb);
return 0;
}
Output:
The value of P : 23
The value of G :9
The private key a for Alice : 4
The private key b for Bob : 3
Secret key for the Alice is : 9
Secret Key for the Bob is : 9
© scanned with OKEN Scannera
10. Calculate the Message Digest of a text using the SHA-I Algorithm in
Java
Pro
// Java program to calculate SHA-I hash value
import java.math.Biginteger;
import java.security.MessageDigest;
import java.security. NoSuchAlgorithmException:
public class GFG {
public static String encryptThisString(String input)
{
try {
1 getInstance() method is called with algorithm SHA-1
MessageDigest md = MessageDigest.getInstance(""SHA-I");
// digest() method is called
/to calculate message digest of the input string
// returned as array of byte
byte[] messageDigest = md.digest(input.getBytes());
// Convert byte array into signum representation
BigInteger no = new BigInteger(1, messageDigest);
// Convert message digest into hex value
String hashtext = no.toString(16);
/I Add preceding 0s to make it 32 bit
while (hashtext.length() < 32) {
hashtext = "0" + hashtext;
// return the HashText
return hashtext;
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
11 Driver code
public static void main(String argsf}) throws
NoSuchAlgorithmException
{
System.out.printin("HashCode Generated by SHA-I for:
String s1 = "GeeksForGeeks";
System.out printin("\n" + s1 +
String s2 = "hello world";
System.out println("\n" + s2 +" : "+ encryptThisString(s2));
" + encryptThisString(s1));
© scanned with OKEN Scanner
2Outpu
HashCode Generated by SHA-1 for:
GeeksForGeeks : addf120b430021c36c232¢9%ef8d926aea2acd6b
hello world : 2aac6c35c94felb4 | Sdbe95408b9ce9 | eeBdGed
© scanned with OKEN Scanner11.Calculate the Message digest of a text using MD5 hash
in Java
2. SHA-I
3. SHA-256
This Algorithms are initialize in static method called getInstance(). Afier selecting the
algorithm it calculate the digest value and return the results in byte array.
BigInteger class is used, which converts the resultant byte array into its sign-magnitude
representation. :
This representation converts into hex format to get the MessageDigest
Examples:
Input: hello world
Output: Seb63bbbe0 | eeed093cb22bb8f5acdc3
PROGRAM:
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
// Java program to calculate MD5 hash value
public class MD5 {
public static String getMdS (String input)
{
try{
// Static getInstance method is called with hashing MD5
MessageDigest md = MessageDigest.get Instance ("MD5") ;
// digest () method is called to calculate message digest
// of an input digest () return array of byte
byte[] messageDigest = md.digest (input.getBytes());
@7 Convert byte array ints ¢ gam representation
Biginteger no = new BigInteger (1, messageDigest) ;
// Convert message digest into hex value
String hashtext = no.toString(16) ;
while(hashtext.length() < 32) {
hashtext = "0"+ hashtext;
Z
© scanned with OKEN Scannerreturn hashtext;
}
// For specifying wrong message digest algorithms
catch (NoSuchAlgorithmException e) {
throw new RuntimeException (e);
}
}
// Driver code
public static void main(String args[]) throws
NoSuchAlgorithmException
i‘
String s = "GeeksForGeeks";
System.out.println("Your HashCode Generated by MDS is: "+
getMdS(s));
}
}
Output:
Your HashCode Generated by MDS is: €39b9c178b2c9be4e99b141d956c6FF6
© scanned with OKEN Scanner12. Demonstrate how sniffing software works
Wh:
is network sniffing?
Computers communicate by broadcasting messages on a network using IP addresses. Once a
message has been sent on a network, the recipient computer with the matching IP address
responds with its MAC address.
Network sniffing is the process of intercepting data packets sent over a network. This can
be done by the specialized software program or hardware equipment. Sniffing can be used to:
+ Capture sensitive data such as login credentials
+ Eavesdrop on chat messages
+ Capture files have been transmitted over a network
The following are protocols that are vulnerable to sniffing
+ Telnet
+ Rlogin
+ HTTP
+ SMTP
+ NNTP
* POP
+ PIP
+ IMAP
The above protocols are vulnerable if login details are sent in plain text
External
Sniffer
2
“ © iD wowtechpandaorg/dashboards- Gy! QPsme Luteta Stet GY G =
| | Dashboard | Personal Contacts Manager v1.0
CET CES
1 Roderick Chekoko 9990988 kr@krcom Edi
2 Manin Dawn m 88mar.com aig
3 Fernie Ngome 555 fagoma@yaheo.com eds
[| 5 > aeidy Kotinds o7ss076112——_bamel@gmalicom fs
| | 6 Smich Jones 09875465456 jones @space.com Edt |
| | Total Records Counts5
© scanned with OKEN ScannerGo back to Wireshark and stop the live capture
WG Capturing from Wireless Network Connection [Wireshark 1.10.2 (SVI
Stop five canture
Filter for HTTP protocol results only using the filter textbox
View Go Capture Analyze
Edit
Af "Wireless Network Connection [Wireshark 1.10.2 (SVN Ri
Statistics
Filter for HTTP protocol results only
Locate the Info column and look for entries with the HTTP verb POST and click on it
[Elerion ce i Se
Protecol Length Info
WrTp 433 GET / HITP/1.1
cia Pa ET
Look for POST verb under Info column
HTTP 1188 HTTP/1.1 200 OK (text/h
233 HTTP/1.1 200 0K | Ceext/pl
‘es nomi
HTTP 567 Ge /dashboard. php HTTP/
a 200 OK (text /ht
Just below the log entries, there is a panel with a summary of captured data. Look for
the summary that says Line-based text data: application/x-www-form-urlencoded
© scanned with OKEN Scanner[ll een Seats Pes
Be Ue Yer Go Geter dee eam
oe nms OAKS
to ito a US (ea)
Twomey Joe mono 5
seta OH aaao umns %
‘aUPOST arabes have bees captared a past
le to view the plaintext values of all the POST variables
submitted to
the server via HTTP protocol,
What is a MAC Flooding?
MAC flooding is a network sniffing technique that floods the switeh MAC table with fake
MAC addresses. This leads to overloading the switch memory and makes it et
the switch has been compromised, it sends the broadcast me:
network. This makes it possible to snitY data packets as th
a hub, Once
ages to all computers on a
y sent on the network,
Counter Measures against MAC flooding
+ Some switehes have the port securi
feature. This feature ean be used to limit the
number of MAC addresses on the ports, It can also be used to maintain a secure MAC
address table in addition to the one provided by the switch,
Authentication, Authorization and Accounting servers can be used to filter discovered
MAC addresses.
Sniffing Counter M
sures
Restriction to network physical media highly reduces the chances ot'a network suit
been installed
+ Eneryptin
they are transmitted over the network greatly reduces their
value as they are difficult to decrypt,
Changing the network to a Seet
network been snitted,
Shell (SSU)network also reduces the chances of the
© scanned with OKEN ScannerVe Quests
Explain security attacks.
Explain Security Services
- Explain AES Algorithm
Lists block cipher modes of operation
Explain about Kerberos.
Explain about X.509 Certificate
Explain IPSEC Architecture
wen anR WN
Explain Combining Security Associations and Key and
Management.
9. Explain key elements of the SNMP model?
10. Write about viruses? And related threats
© scanned with OKEN Scanner