Crypto Combine
Crypto Combine
// Close resources
serverSocket.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
desClient.java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Base64;
import java.util.Scanner;
Client side:
2.Consider a sender and receiver who need to exchange data confidentially
using symmetric encryption. Write program that implements AES encryption
and decryption using a 128 bits key size and 128 bit plaintext size.
CODE:
AesServer.java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Base64;
// Close resources
serverSocket.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
AesClient.java
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.SecretKeySpec;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.Socket;
import java.util.Base64;
import java.util.Scanner;
// Close resources
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
OUTPUT:
Server side:
Client side:
1. User A want to communicate to user B but they want to user Asymmetric
Key Cryptography by using RSA algorithms send message to each other.
Encrypt message at sender side and decrypt it at receiver side.
CODE:
RSAServer.java
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.spec.PKCS8EncodedKeySpec;
import java.util.Base64;
import javax.crypto.Cipher;
// Close resources
serverSocket.close();
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
// Close resources
socket.close();
} catch (Exception e) {
e.printStackTrace();
}
}
OUTPUT:
Sender side:
Receiver side:
2. Develop a MD5 hash algorithm that finds the Message Authentication Code
(MAC).
CODE:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
try {
String mac = generateMAC(message, key);
System.out.println("Message Authentication Code (MAC): " + mac);
} catch (NoSuchAlgorithmException e) {
System.err.println("MD5 algorithm not found.");
}
}
OUTPUT:
3. Find a Message Authentication Code (MAC) for given variable size message
by using SHA-128 and SHA-256 Hash algorithm Measure the Time
consumptions for varying message size for both SHA-128 and SHA-256.
CODE:
import java.security.*;
import java.util.Random;
OUTPUT:
RC4
import java.util.Scanner;
class RC4Algorithm {
static int[] K = new int[256];
static int[] S = new int[256];
static int keylength;
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("\n==========================RC4Algorithm===================
=======\n");
System.out.print("\nEnter plain text: ");
String inpuString = sc.nextLine();
System.out.print("Enter Key: ");
String inpuString2 = sc.nextLine();
char[] plainText = inpuString.toCharArray();
char[] byteKey = inpuString2.toCharArray();
//Initialize and permute key and state
initAndPermute(byteKey);
char[] cipherText = encryptRC4(plainText);
System.out.print("\nCipher Text: ");
for (int i = 0; i < cipherText.length; i++) {
System.out.print(cipherText[i]);
}
//Initialize and permute key and state
initAndPermute(byteKey);
char[] decryptedText = decryptRC4(cipherText);
System.out.print("\nDecrypted Text: ");
for (int i = 0; i < decryptedText.length; i++) {
System.out.print(decryptedText[i]);
}
System.out.print("\n\n==========================RC4Algorithm=================
=========\n");
sc.close();
}
private static void initAndPermute(char[] byteKey) {
if (byteKey.length > 256 || byteKey.length < 1) {
System.out.println("Key length must be between 1 to 256 chars");
} else {
// Creation of initial state and key bytes
keylength = byteKey.length;
for (int i = 0; i < 256; i++) {
S[i] = i;
K[i] = byteKey[i % keylength];
}
// Permuting state bytes based on values of key bytes
int j = 0;
for (int i = 0; i < 256; i++) {
j = (j + S[i] + K[i]) % 256;
int temp = S[i];
S[i] = S[j];
S[j] = temp;
}
}
}
private static char[] encryptRC4(char[] plainText) {
char[] cipherText = new char[plainText.length];
int i = 0;
int j = 0;
int key;
int plainTextLen = 0;
while (plainTextLen < plainText.length) {
// Key generation
i = (i + 1) % 256;
j = (j + S[i]) % 256;
int temp = S[i];
S[i] = S[j];
S[j] = temp;
key = S[(S[i] + S[j]) % 256];
// Encryption
cipherText[plainTextLen] = (char) (plainText[plainTextLen] ^ key);
plainTextLen++;
}
return cipherText;
}
private static char[] decryptRC4(char[] cipherText) {
char[] plainText = new char[cipherText.length];
int i = 0;
int j = 0;
int key;
int cipherLen = 0;
while (cipherLen < cipherText.length) {
// Key generation
i = (i + 1) % 256;
j = (j + S[i]) % 256;
int temp = S[i];
S[i] = S[j];
S[j] = temp;
key = S[(S[i] + S[j]) % 256];
// Encryption
plainText[cipherLen] = (char) (cipherText[cipherLen] ^ key);
cipherLen++;
}
return plainText;
}
}
IDEA
def _mul(x, y):
assert 0 <= x <= 0xFFFF
assert 0 <= y <= 0xFFFF
if x == 0:
x = 0x10000
if y == 0:
y = 0x10000
r = (x * y) % 0x10001
if r == 0x10000:
r = 0
y1 = _mul(x1, z1)
y2 = (x2 + z2) % 0x10000
y3 = (x3 + z3) % 0x10000
y4 = _mul(x4, z4)
p = y1 ^ y3
q = y2 ^ y4
s = _mul(p, z5)
t = _mul((q + s) % 0x10000, z6)
u = (s + t) % 0x10000
x1 = y1 ^ t
x2 = y2 ^ u
x3 = y3 ^ t
x4 = y4 ^ u
class IDEA:
def __init__(self, key):
self._keys = None
self.change_key(key)
sub_keys = []
for i in range(9 * 6):
sub_keys.append((key >> (112 - 16 * (i % 8))) % 0x10000)
if i % 8 == 7:
key = ((key << 25) | (key >> 103)) % modulus
keys = []
for i in range(9):
round_keys = sub_keys[6 * i: 6 * (i + 1)]
keys.append(tuple(round_keys))
self._keys = tuple(keys)
for i in range(8):
round_keys = self._keys[i]
x2, x3 = x3, x2
# Note: The words x2 and x3 are not permuted in the last round
# So here we use x1, x3, x2, x4 as input instead of x1, x2, x3, x4
# in order to cancel the last permutation x2, x3 = x3, x2
y1, y2, y3, y4 = _KA_layer(x1, x3, x2, x4, self._keys[8])
ciphertext = (y1 << 48) | (y2 << 32) | (y3 << 16) | y4
return ciphertext
def main():
# key = 0x00000000000000000000000000000000
# plain = 0x8000000000000000
# cipher = 0x8001000180008000
key = 0x2BD6459F82C5B300952C49104881FF48
plain = 0xF129A6601EF62A47
cipher = 0xEA024714AD5C4D84
my_IDEA = IDEA(key)
encrypted = my_IDEA.encrypt(plain)
assert encrypted == cipher
if __name__ == '__main__':
main()
# Diffie-Hellman Code
def prime_checker(p):
# Checks If the number entered is a Prime Number or not
if p < 1:
return -1
elif p > 1:
if p == 2:
return 1
for i in range(2, p):
if p % i == 0:
return -1
return 1
l = []
while 1:
P = int(input("Enter P : "))
if prime_checker(P) == -1:
print("Number Is Not Prime, Please Enter Again!")
continue
break
while 1:
G = int(input(f"Enter The Primitive Root Of {P} : "))
if primitive_check(G, P, l) == -1:
print(f"Number Is Not A Primitive Root Of {P}, Please Try Again!")
continue
break
# Private Keys
x1, x2 = int(input("Enter The Private Key Of User 1 : ")), int(
input("Enter The Private Key Of User 2 : "))
while 1:
if x1 >= P or x2 >= P:
print(f"Private Key Of Both The Users Should Be Less Than {P}!")
continue
break
# Calculate Public Keys
y1, y2 = pow(G, x1) % P, pow(G, x2) % P
if k1 == k2:
print("Keys Have Been Exchanged Successfully")
else:
print("Keys Have Not Been Exchanged Successfully")
# Simplified AES implementation in Python 3
import sys
# S-Box
sBox = [
0x9, 0x4, 0xa, 0xb, 0xd, 0x1, 0x8, 0x5,
0x6, 0x2, 0x0, 0x3, 0xc, 0xe, 0xf, 0x7
]
# Inverse S-Box
sBoxI = [
0xa, 0x5, 0x9, 0xb, 0x1, 0x7, 0x8, 0xf,
0x6, 0x0, 0x2, 0x3, 0xc, 0x4, 0xd, 0xe
]
def intToVec(n):
"""Convert a 2-byte integer into a 4-element vector"""
return [n >> 12, (n >> 4) & 0xf, (n >> 8) & 0xf, n & 0xf]
def vecToInt(m):
"""Convert a 4-element vector into 2-byte integer"""
return (m[0] << 12) + (m[2] << 8) + (m[1] << 4) + m[3]
def keyExp(key):
"""Generate the three round keys"""
def sub2Nib(b):
"""Swap each nibble and substitute it using sBox"""
return sBox[b >> 4] + (sBox[b & 0x0f] << 4)
def encrypt(ptext):
"""Encrypt plaintext block"""
def mixCol(s):
return [s[0] ^ mult(4, s[2]), s[1] ^ mult(4, s[3]),
s[2] ^ mult(4, s[0]), s[3] ^ mult(4, s[1])]
def decrypt(ctext):
"""Decrypt ciphertext block"""
def iMixCol(s):
return [mult(9, s[0]) ^ mult(2, s[2]), mult(9, s[1]) ^ mult(2, s[3]),
mult(9, s[2]) ^ mult(2, s[0]), mult(9, s[3]) ^ mult(2, s[1])]
if __name__ == '__main__':
# Get plaintext and key from user input
plaintext = int(input("Enter plaintext (16-bit integer in binary format): "),
2)
key = int(input("Enter key (16-bit integer in binary format): "), 2)
# Generate round keys
keyExp(key)