Wednesday 9 January 2019

Java program to demonstrate working of A5/1 (CSS)


#include <stdio.h>
#include <stdlib.h>
// Defines for register's size
#define SIZE1 19
#define SIZE2 22
#define SIZE3 23
#define SIZE4 8
// Define clock bit
#define REG1CLOCK 8
#define REGCLOCK 10
// Define byte
#define BYTE 8
// Other defines
#define ZERO 0
#define ONE 1
#define TWO 2
// Struct that holds 3 registers:
// Register X - 18 bits (clock bit = 8)
// Register Y - 21 bits (clock bit = 10)
// Register Z - 22 bits (clock bit = 10)
// The struct also holds the Keystream Byte (8 bits).
struct Registers{
int x[SIZE1];
int y[SIZE2];
int z[SIZE3];
int out[SIZE4];
};
// Function Prototypes
int majority(int x, int y, int z); // Function which checks if specified register is in the majority by comparing the clock bite.
void shift(struct Registers *regs, int size); // Function that shifts the values in the registers
void output(int size, int counter,struct Registers *ptr); // Function to output appropriate data. (Register values and keystream).

int main(){
// Define the struct with pre-defined set of data.
struct Registers registers = { {1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1},{1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1},{1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0}};
struct Registers *registersPointer = &registers; // Pointer to the 'registers' struct.
// First output the data, that are initialized to the registers at the start.
output(ZERO,ZERO,registersPointer);
// Variable for for loop
int i = ZERO;
// Iterate through the byte (8 times)
for(i = 0; i < BYTE; i++){
// Store the majority value from the clock bit in m (x[8], y[10], z[10]).
int m = majority(registers.x[REG1CLOCK],registers.y[REGCLOCK],registers.z[REGCLOCK]);
// Compare and shift the x register only if part of the majority.
if(registers.x[REG1CLOCK] == m){
shift(registersPointer,SIZE1);
}
// Compare and shift the y register only if part of the majority.
if(registers.y[REGCLOCK] ==m){
shift(registersPointer,SIZE2);
}
// Compare and shift the z register only if part of the majority.
if(registers.z[REGCLOCK] ==m){
shift(registersPointer,SIZE3);
}
// Set the keystream bit (start from the back).
registersPointer -> out[SIZE4-i] = registers.x[SIZE1-1] ^ registers.y[SIZE2-1] ^ registers.z[SIZE3-1];
output(SIZE4-i,ONE,registersPointer); // Output the values including the keystream.
}
// Output the final value.
output(ZERO,TWO,registersPointer);
return 0;
}
// Function to check if the majority of clock bit.
int majority(int x, int y, int z){
if( x == y){
return x;
}else if(y == z){
return y;
}else if(x == z){
return z;
}
return 0;
}

// Function to compare register's bit using XOR operation and swap.
void shift(struct Registers *registers,int registerSize){
int swap = 0;
// Check which register are we dealing with (SIZE1 = register X, SIZE2 = register Y, SIZE3 = register Z).
// After that compare using XOR operation the last register's bits to find out the swap bit.
if(registerSize == SIZE1){
swap = registers -> x[SIZE1 - 1] ^ registers -> x[SIZE1 - 2] ^ registers -> x[SIZE1 - 3] ^ registers -> x[SIZE1 - 6];
}else if(registerSize == SIZE2){
swap = registers -> y[SIZE2-1] ^ registers -> y[SIZE2-2];
}else if(registerSize == SIZE3){
swap = registers -> z[SIZE3-1] ^ registers -> z[SIZE3-2] ^ registers -> z[SIZE3-3] ^ registers -> z[SIZE3-15];
}
// Iterate through the register,
// Check which register we are dealing with,
// Check if we are at element 0, if so then put the swap value.
// Otherwise change current element to element-1.
for(int f = (registerSize-1); f >= 0;f--){
if(registerSize == SIZE1){
if(f == 0){
registers -> x[f] = swap;
}else{
registers -> x[f] = registers -> x[f-1];
}

}else if(registerSize == SIZE2){
if(f == 0){
registers -> y[f] = swap;
}else{
registers -> y[f] = registers -> y[f-1];
}

}else if(registerSize == SIZE3){
if(f == 0){
registers -> z[f] = swap;
}else{
registers -> z[f] = registers -> z[f-1];
}
}
}
}

// Function to output the data.
void output(int outvalue, int go, struct Registers *registers){
int b = 0;
// If the first or second time outputing, output appropriate message.
if(go == ZERO){
printf("ORGINAL CONTENT OF X, Y and Z.");
}
if(go == TWO){
printf("\nLAST CONTENT OF X, Y and Z.");
}
// Output values for register X.
printf("\nValue for x: ");
for(b =0; b < SIZE1 ;b++){
printf("%d,",registers->x[b]);
}
// Output values for register Y.
printf("\nValue for y: ");
for(b = 0; b < SIZE2 ;b++){
printf("%x,",registers->y[b]);
}
// Output values for register Z.
printf("\nValue for z: ");
for(b = 0; b < SIZE3;b++){
printf("%d,",registers->z[b]);
}

// Output values for the KeyStream.
if(go != ZERO && go != TWO){
printf("\nKeystream (X ^ Y ^ Z): ");
for(int i = outvalue ; i <= SIZE4;i++){
printf("%d,",registers->out[i]);
}
}
printf("\n");
}

Output:

codept@codeptL2-16 ~/Desktop $ gcc a5.c
codept@codeptL2-16 ~/Desktop $ ./a.out
ORGINAL CONTENT OF X, Y and Z.
Value for x: 1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,
Value for y: 1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,
Value for z: 1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,

Value for x: 0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,
Value for y: 1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,
Value for z: 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,
Keystream (X ^ Y ^ Z): 1,

Value for x: 0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,
Value for y: 0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,
Value for z: 1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,
Keystream (X ^ Y ^ Z): 0,1,

Value for x: 0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,
Value for y: 1,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,
Value for z: 1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,0,
Keystream (X ^ Y ^ Z): 0,0,1,

Value for x: 0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,
Value for y: 0,1,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,
Value for z: 1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,
Keystream (X ^ Y ^ Z): 0,0,0,1,

Value for x: 0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,
Value for y: 1,0,1,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,
Value for z: 1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,0,
Keystream (X ^ Y ^ Z): 0,0,0,0,1,

Value for x: 0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,
Value for y: 1,0,1,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,
Value for z: 0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,1,
Keystream (X ^ Y ^ Z): 0,0,0,0,0,1,

Value for x: 0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,1,
Value for y: 0,1,0,1,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,1,
Value for z: 1,0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,
Keystream (X ^ Y ^ Z): 1,0,0,0,0,0,1,

Value for x: 0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,
Value for y: 1,0,1,0,1,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,
Value for z: 1,0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,
Keystream (X ^ Y ^ Z): 1,1,0,0,0,0,0,1,

LAST CONTENT OF X, Y and Z.
Value for x: 0,0,0,0,0,0,0,1,0,1,0,1,0,1,0,1,0,1,0,
Value for y: 1,0,1,0,1,0,1,1,0,0,1,1,0,0,1,1,0,0,1,1,0,0,
Value for z: 1,0,1,1,1,1,1,1,0,0,0,0,1,1,1,1,0,0,0,0,1,1,1,
codept@codeptL2-16 ~/Desktop $


Python program to implement Overlap Add method (DSP)


def givep(f,l):
    temp=f/l
    if(f%l==0):
        P=temp+1
    else:
        P=temp+2
    return P

def returnx(l,p,n,mat1):
    x=[[0 for row in range(0,int(n))] for col in range(0,int(p))]
    z=int(0)
    lenmat1=len(mat1)
    for row in range(0,p-1):
        value=0
        for col in range(0,n):
            if(value<l):
                if(z<lenmat1):
                    x[row][col]=mat1[z]
                    value=value+1
                    z=z+1
                else:
                    x[row][col]=0
    return x
   
   
def findy(p,n,l,x,mat2):
    sfinal=[]
    h=len(mat2)
    run=n-h
    for z in range(1,run+1):
        mat2.append(0)
    y=[[0 for row in range(0,int(n))] for col in range(0,int(p))]
    temp=[]
    for i in range(0,p):
        for j in range(0,n):
            temp.append(x[i][j])
        sfinal=convol(temp,mat2)
        for j in range(0,n):
            y[i][j]=sfinal[j]
        del sfinal[:]
        del temp[:]
    return y
   

def inputmat(z):
    mat=[]
    for v in range(1,z+1):
        q=int(input('Enter %d element : '%(v)))
        mat.append(q)
    return mat

def check_diff(mat1,mat2):
    x=len(mat1)
    h=len(mat2)
    temp=[]
    if(x>h):
        run=x-h
        for z in range(1,run+1):
            mat2.append(0)
        temp=convol(mat1,mat2)
        return mat1,mat2
    else:
         run=h-x
         for z in range(1,run+1):
            mat1.append(0)
         temp=convol(mat2,mat1)
         return mat2,mat1
       

def convol(large,small):
    lenlarge=len(large)
    templist=[0]*lenlarge
    temp=0
    yn=[]
    #print('Last Element is : %d'%(large[lenlarge-1]))
    #convol=[]
    convol=[[0 for row in range(0,lenlarge)] for col in range(0,lenlarge)]
    for r in range(0,lenlarge):
        if(r>0):
            first=large[0]
            last=large[lenlarge-1]
            for q in range(0,lenlarge):
                if(q>0 & q<lenlarge):
                    templist[q]=large[q-1]
                    convol[r][q]=templist[q]
                else:
                    templist[0]=last
                    convol[r][q]=templist[q]
            for p in range(0,lenlarge):
                large[p]=templist[p]
        else:
            for p in range(0,lenlarge):
                convol[r][p]=large[p]
    yn=matmul(convol,small)
    return yn

def matmul(convol1,small):
    final=[]
    lenlarge=len(convol1)
    for i in range(0,lenlarge):
        total=0
        for j in range(0,lenlarge):
            total2=convol1[j][i]*small[j]
            total=total+total2
        final.append(total)
    return final

def giveans(yn,n,p,l):
    ans=[]
    var=0
    temp=[]
    for i in range(0,p):
        for j in range(0,n):
            if(j<l):
                if not temp:
                    var=yn[i][j]
                    ans.append(var)
                else:
                    var=yn[i][j]
                    var=var+temp[0]
                    ans.append(var)
                    del temp[0]
            else:
                temp.append(yn[i][j])
    a=len(ans)
    del ans[a-1]
    return ans

def printvalue(p,n,mat,var):
    printit=[]
    values=1
    for i in range(0,p):
        print('%s%d : '%(var,values))
        for j in range(0,n):
            printit.append(mat[i][j])
        print(printit)
        del printit[:]
        values+=1
           

def main():
    print('\n'*5)
    mat1=[]
    large=[]
    small=[]
    x=[]
    yn=[]
    ans=[]
    f=int(input('Enter the length of the x(n) matrix : '))
    mat1=inputmat(f)
    m=int(input('Enter the length of the h(n) matrix : '))
    mat2=inputmat(m)
    l=int(input('Enter the value of l : '))
    n=l+m-1
    p=int(givep(f,l))
    print('The value of p is : %d '%(p))
    print('The value of n is : %d '%(n))
    print('\nx(n) : ')
    print(mat1)
    print ('h(n) : ')
    print(mat2)
    x=returnx(l,p,n,mat1)
    print('\nThe Different values of X(inputs) : ')
    variable='X'
    printvalue(p,n,x,variable)
    variable='Y'
    yn=findy(p,n,l,x,mat2)
    print('\nThe Different values of Y(Output) : ')
    printvalue(p,n,yn,variable)
    ans=giveans(yn,n,p,l)
    print('\n****** Final answer of overlap add method ******* : ')
    print(ans)
 
if __name__=="__main__":
    main()
   
Output:

codept@codeptL2-11 /media/codept/USB STICK/p $ python overlap.py

Enter the length of the x(n) matrix : 12
Enter 1 element : 1
Enter 2 element : 1
Enter 3 element : 0
Enter 4 element : 0
Enter 5 element : 3
Enter 6 element : 5
Enter 7 element : 1
Enter 8 element : 1
Enter 9 element : 0
Enter 10 element : 0
Enter 11 element : 3
Enter 12 element : 5
Enter the length of the h(n) matrix : 3
Enter 1 element : 1
Enter 2 element : 2
Enter 3 element : 3
Enter the value of l : 3
The value of p is : 5
The value of n is : 5

x(n) :
[1, 1, 0, 0, 3, 5, 1, 1, 0, 0, 3, 5]
h(n) :
[1, 2, 3]

The Different values of X(inputs) :
X1 :
[1, 1, 0, 0, 0]
X2 :
[0, 3, 5, 0, 0]
X3 :
[1, 1, 0, 0, 0]
X4 :
[0, 3, 5, 0, 0]
X5 :
[0, 0, 0, 0, 0]

The Different values of Y(Output) :
Y1 :
[1, 3, 5, 3, 0]
Y2 :
[0, 3, 11, 19, 15]
Y3 :
[1, 3, 5, 3, 0]
Y4 :
[0, 3, 11, 19, 15]
Y5 :
[0, 0, 0, 0, 0]

****** Final answer of overlap add method ******* :
[1, 3, 5, 3, 3, 11, 20, 18, 5, 3, 3, 11, 19, 15]

Python program to implement RSA(Rivest, Shamir, & Adleman) algorithm (CSS)

class RSA:
    def __init__(self, p=13, q=17, e=19):
        self.p = p
        self.q = q
        self.n = p*q
        self.phi_n = (p-1)*(q-1)
        self.e = e
        self.d = int(self.find_d())
        self.message = None
        self.cipher = None

    def find_d(self):
        for i in range(1, 1000):
            if ((self.phi_n*i)+1) % self.e == 0:
                return (((self.phi_n*i)+1) / self.e)

    def encrypt(self):
        self.cipher = (self.message**self.e) % self.n

    def destroy_message(self):
        self.message = None

    def decrypt(self):
        self.message = (self.cipher**self.d) % self.n


if __name__ == "__main__":
    p, q, e = input("Enter the values for p q e : ").split(' ')
    rsa = RSA(int(p), int(q), int(e))
    message = int(input("Enter Your message to be encrypted(ONLY INT): "))
    rsa.message = message
    rsa.encrypt()
    rsa.destroy_message()
    print("The encrypted value is :", rsa.cipher)
    rsa.decrypt()
    print("The decrypted value is :", rsa.message)

Output:

codept@codept-04 ~/Desktop/chan $ python3 RSA.py
Enter the values for p q e : 73 151 11
Enter Your message to be encrypted(ONLY INT): 23
The encrypted value is : 5281
The decrypted value is : 23

Java program to implement MD5 (CSS)

import java.util.*;
class MD5
{
    private static final int   INIT_A     = 0x67452301;
    private static final int   INIT_B     = (int) 0xEFCDAB89L;
    private static final int   INIT_C     = (int) 0x98BADCFEL;
    private static final int   INIT_D     = 0x10325476;
    private static final int[] SHIFT_AMTS = { 7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21 };
    private static final int[] TABLE_T    = new int[64];
    static
    {
        for (int i = 0; i < 64; i++)
            TABLE_T[i] = (int) (long) ((1L << 32) * Math.abs(Math.sin(i + 1)));
    }

    public static byte[] computeMD5(byte[] message)
    {
        int messageLenBytes = message.length;
        int numBlocks = ((messageLenBytes + 8) >>> 6) + 1;
        int totalLen = numBlocks << 6;
        byte[] paddingBytes = new byte[totalLen - messageLenBytes];
        paddingBytes[0] = (byte) 0x80;
        long messageLenBits = (long) messageLenBytes << 3;
        for (int i = 0; i < 8; i++)
        {
            paddingBytes[paddingBytes.length - 8 + i] = (byte) messageLenBits;
            messageLenBits >>>= 8;
        }
        int a = INIT_A;
        int b = INIT_B;
        int c = INIT_C;
        int d = INIT_D;
        int[] buffer = new int[16];
        for (int i = 0; i < numBlocks; i++)
        {
            int index = i << 6;
            for (int j = 0; j < 64; j++, index++)
                buffer[j >>> 2] = ((int) ((index < messageLenBytes) ? message[index]
                        : paddingBytes[index - messageLenBytes]) << 24)
                        | (buffer[j >>> 2] >>> 8);
            int originalA = a;
            int originalB = b;
            int originalC = c;
            int originalD = d;
            for (int j = 0; j < 64; j++)
            {
                int div16 = j >>> 4;
                int f = 0;
                int bufferIndex = j;
                switch (div16)
                {
                    case 0:
                        f = (b & c) | (~b & d);
                        break;
                    case 1:
                        f = (b & d) | (c & ~d);
                        bufferIndex = (bufferIndex * 5 + 1) & 0x0F;
                        break;
                    case 2:
                        f = b ^ c ^ d;
                        bufferIndex = (bufferIndex * 3 + 5) & 0x0F;
                        break;
                    case 3:
                        f = c ^ (b | ~d);
                        bufferIndex = (bufferIndex * 7) & 0x0F;
                        break;
                }
                int temp = b
                        + Integer.rotateLeft(a + f + buffer[bufferIndex]
                                + TABLE_T[j],
                                SHIFT_AMTS[(div16 << 2) | (j & 3)]);
                a = d;
                d = c;
                c = b;
                b = temp;
            }
            a += originalA;
            b += originalB;
            c += originalC;
            d += originalD;
        }
        byte[] md5 = new byte[16];
        int count = 0;
        for (int i = 0; i < 4; i++)
        {
            int n = (i == 0) ? a : ((i == 1) ? b : ((i == 2) ? c : d));
            for (int j = 0; j < 4; j++)
            {
                md5[count++] = (byte) n;
                n >>>= 8;
            }
        }
        return md5;
    }

    public static String toHexString(byte[] b)
    {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < b.length; i++)
        {
            sb.append(String.format("%02X", b[i] & 0xFF));
        }
        return sb.toString();
    }

    public static void main(String[] args)
    {
String[] testStrings= new String[4];
Scanner dc= new Scanner(System.in);
System.out.println("Enter 4 input strings:");
for(int i=0;i<4;i++)
testStrings[i]= dc.nextLine();
        for (String in : testStrings)
            System.out.println("0x" + toHexString(computeMD5(in.getBytes()))
                    + " <== \"" + in + "\"");
        return;
    }
}

/*
Output:
codept@codept-05 ~/Desktop $ java MD5
Enter 4 input strings:
Hello World
MD5
keyword
beco 
0xB10A8DB164E0754105B7A99BE72E3FE5 <== "Hello World"
0x7F138A09169B250E9DCB378140907378 <== "MD5"
0xD7DF5B64DF1181EF1D62D646A13AA860 <== "keyword"
0x43C348CF5E74DAB638CF1251DFD41803 <== "beco"
codept@codept-05 ~/Desktop $

*/

Python program to implement Digital Signature (CSS)


import random

'''
Euclid's algorithm for determining the greatest common divisor
Use iteration to make it faster for larger integers
'''
def gcd(a, b):
while b != 0:
a, b = b, a % b
return a

'''
Euclid's extended algorithm for finding the multiplicative inverse of two numbers
'''
def multiplicative_inverse(e, phi):
d = 0
x1 = 0
x2 = 1
y1 = 1
temp_phi = phi
while e > 0:
temp1 = temp_phi/e
temp2 = temp_phi - temp1 * e
temp_phi = e
e = temp2
x = x2- temp1* x1
y = d - temp1 * y1
x2 = x1
x1 = x
d = y1
y1 = y
if temp_phi == 1:
return d + phi

'''
Tests to see if a number is prime.
'''
def is_prime(num):
if num == 2:
return True
if num < 2 or num % 2 == 0:
return False
for n in range(3, int(num**0.5)+2, 2):
if num % n == 0:
return False
return True

def generate_keypair(p, q):
if not (is_prime(p) and is_prime(q)):
raise ValueError('Both numbers must be prime.')
elif p == q:
raise ValueError('p and q cannot be equal')
#n = pq
n = p * q

#Phi is the totient of n
phi = (p-1) * (q-1)

#Choose an integer e such that e and phi(n) are coprime
e = random.randrange(1, phi)

#Use Euclid's Algorithm to verify that e and phi(n) are comprime
g = gcd(e, phi)
while g != 1:
e = random.randrange(1, phi)
g = gcd(e, phi)

#Use Extended Euclid's Algorithm to generate the private key
d = multiplicative_inverse(e, phi)
#Return public and private keypair
#Public key is (e, n) and private key is (d, n)
return ((e, n), (d, n))

def encrypt(pk, plaintext):
#Unpack the key into it's components
key, n = pk
#Convert each letter in the plaintext to numbers based on the character using a^b mod m
cipher = [(ord(char) ** key) % n for char in plaintext]
#Return the array of bytes
return cipher

def decrypt(pk, ciphertext):
#Unpack the key into its components
key, n = pk
#Generate the plaintext based on the ciphertext and key using a^b mod m
plain = [chr((char ** key) % n) for char in ciphertext]
#Return the array of bytes as a string
return ''.join(plain)

if __name__ == '__main__':
'''
Detect if the script is being run directly by the user
'''
print ("Digital Signature Encrypter/ Decrypter\n")
p = int(input("Enter a prime number (17, 19, 23, etc): "))
q = int(raw_input("Enter another prime number (Not one you entered above): "))
print ("Generating your public/private keypairs now . . .")
public, private = generate_keypair(p, q)
print ("Your public key is ", public ," and your private key is ", private)
message = raw_input("Enter a message to encrypt with your private key: ")
encrypted_msg = encrypt(private, message)
print ("Your encrypted message is: ")
print (''.join(map(lambda x: str(x), encrypted_msg)))
print ("Decrypting message with public key ", public ," . . .")
print ("Your message is:")
print (decrypt(public, encrypted_msg))

Output:

codept@codept-05 ~/Desktop $ python digi.py
Digital Signature Encrypter/ Decrypter

Enter a prime number (17, 19, 23, etc): 17
Enter another prime number (Not one you entered above): 23
Generating your public/private keypairs now . . .
('Your public key is ', (205, 391), ' and your private key is ', (261, 391))
Enter a message to encrypt with your private key: keyboard
Your encrypted message is:
6522020264382122275257
('Decrypting message with public key ', (205, 391), ' . . .')
Your message is:
keyboard
codept@codept-05 ~/Desktop $

Java program to implement Diffie Hellman Algorithm (CSS)


import java.io.*;
import java.math.BigInteger;

public class Deffie{
public static void main(String[]args)throws IOException
{
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter prime number:");
BigInteger p=new BigInteger(br.readLine());
System.out.print("Enter primitive root of "+p+":");
BigInteger g=new BigInteger(br.readLine());
System.out.println("Enter value for Alice private kay less than "+p+":");
BigInteger x=new BigInteger(br.readLine());
BigInteger R1=g.modPow(x,p);
System.out.println("R1="+R1);
System.out.print("Enter value for Bob private key less than "+p+":");
BigInteger y=new BigInteger(br.readLine());
BigInteger R2=g.modPow(y,p);
System.out.println("R2="+R2);
BigInteger k1=R2.modPow(x,p);
System.out.println("Key calculated at Alice's side:"+k1);
BigInteger k2=R1.modPow(y,p);
System.out.println("Key calculated at Bob's side:"+k2);
System.out.println("deffie hellman secret key Encryption has Taken");
}

}

Output:

codept@codept-04 ~/Desktop/chan $ java Deffie
Enter prime number:
23
Enter primitive root of 23:5
Enter value for Alice private kay less than 23:
4
R1=4
Enter value for Bob private key less than 23:7
R2=17
Key calculated at Alice's side:8
Key calculated at Bob's side:8
deffie hellman secret key Encryption has Taken

Python Program to implement playfair (CSS)


        ip = input("Enter the keyword: ")
    ip2 = input("Enter Your message: ")
    ip = list(ip)
    ip2 = list(ip2)

    keyword = []
    for x in ip:
        if x not in keyword:
            keyword.extend(x)

    key_list = [chr(x) for x in range(97, 97+26)
                if chr(x) not in keyword]
    key_list = keyword + key_list
    key_list = [x.upper() for x in key_list]
    key_list.remove('J')

    ip2 = [x.upper() for x in ip2]
    for n, i in enumerate(ip2):
        if i == 'J':
            ip2[n] = 'I'
    if len(ip2) % 2 != 0:
        ip2.extend('X')

    n = 0
    message = []
    while n < len(ip2)-1:
        if ip2[n] == ip2[n+1]:
            message.extend(ip2[n])
            message.extend('X')
            message.extend(ip2[n+1])
            message.extend('X')
        else:
            message.extend(ip2[n])
            message.extend(ip2[n+1])
        n += 2
    # print(message)

    n = 0
    matrix = {}
    for i in range(1, 6):
        for j in range(1, 6):
            matrix[key_list[n]] = [i, j]
            n += 1
    # print(matrix)

    n = 0
    output = []
    while n <= len(message)-1:
        a = matrix[message[n]]
        b = matrix[message[n+1]]
        if a[0] == b[0]:
            a[0] += 1
            b[0] += 1
        if a[1] == b[1]:
            a[1] += 1
            b[1] += 1

        if a[0] > 5:
            a[0] = 1
        if a[1] > 5:
            a[1] = 1
        if b[0] > 5:
            b[0] = 1
        if b[1] > 5:
            b[1] = 1

        if a[0] == b[0] or a[1] == b[1]:
            output.append([a[0], b[1]])
            output.append([a[1], b[0]])

        if a[0] != b[0] and a[1] != b[1]:
            output.append([a[0], b[1]])
            output.append([a[1], b[0]])

        n += 2

    k = list(matrix.keys())
    v = list(matrix.values())
    cipher_text = ""
    for i in output:
        cipher_text += k[v.index(i)]
    print("The Encrypted text is: ", cipher_text)


    '''
    Output:

    codept@codept-04 ~/Desktop/exp2 $ python3 playfair.py 
    Enter the keyword: keyword
    Enter Your message: playfair
    The Encrypted text is:  SHBMIEFN
    '''

Python program to implement Transposition cipher (CSS)

key = list(input("Enter your key: "))
matrix = {}
for i in key:
    matrix[i] = []

message = list(input("Enter your message: "))
temp = 0
for i in message:
    matrix[key[temp]].append(i)
    temp += 1
    if temp >= len(key):
        temp = 0

output = []
temp = len(sorted(matrix.items()))
print("The Encrypted text is: ", end="")
for i, v in sorted(matrix.items()):
    print("".join(v), end="")
print(" ")

Java program to implement Wumpus world. (AI)


import java.util.*;
class Environment
{
Scanner scr=new Scanner(System.in);
//char w[][]=new char[5][5];
int np; //number of pits
int wp,gp; // wumpus position gold position
int pos[]; // position of pits
int b_pos[]=new int[20];
int s_pos[]=new int[20];
void accept(String w[][])
{
for(int i=0;i<20;++i)
{
b_pos[i]=-1;
s_pos[i]=-1;
}
for(int i=0;i<5;++i)
for(int j=0;j<5;++j)
w[i][j]="";
int count=1;
System.out.println("The positions are as follows.");
for(int i=1;i<=4;++i)
{
System.out.println("\n-----------------------------------------------------------------");
System.out.print("|\t");
for(int j=1;j<=4;++j)
System.out.print((count++)+"\t|\t");
}
System.out.println("\n-----------------------------------------------------------------");
System.out.println("\nAgent start position: 13");
w[4][1]="A";
System.out.println("\nEnter the number of pits.");
np=scr.nextInt();
pos=new int[np];
System.out.println("Positions of pit, gold and wumpus should not overlap.");
System.out.println("Enter the position of pits.");
for(int i=0;i<np;++i)
{
pos[i]=scr.nextInt();
show_sense(pos[i],1,w);
}
System.out.println("Enter the position of wumpus.");
wp=scr.nextInt();
show_sense(wp,2,w);
System.out.println("Enter the position of gold.");
gp=scr.nextInt();
insert(w);
}
void insert(String w[][])
{
int temp=0;
int count=0;
int flag1=0,flag2=0;
for(int i=0;i<np;++i)
{
temp=pos[i];
count=0;
for(int j=1;j<=4;++j)
{
for(int k=1;k<=4;++k)
{
++count;
if(count==temp)
w[j][k]+="P";
else
if(count==gp && flag1==0)
{
w[j][k]+="G";
flag1=1;
}
else
if(count==wp && flag2==0)
{
w[j][k]+="W";
flag2=1;
}
}
}
}
display(w);
}
void show_sense(int a,int b,String w[][])
{
int t1,t2,t3,t4;
t1=a-1;
t2=a+1;
t3=a+4;
t4=a-4;
if(a==5 || a==9)
t1=0;
if(a==8 || a==12)
t2=0;
if(a==4)
t2=0;
if(a==13)
t1=0;

if(t3>16)
t3=0;
if(t4<0)
t4=0;
//int temp[]=new int[4];
if(b==1)
{b_pos[0]=t1;b_pos[1]=t2;b_pos[2]=t3;b_pos[3]=t4;}
else
if(b==2)
{s_pos[0]=t1;s_pos[1]=t2;s_pos[2]=t3;s_pos[3]=t4;}
int temp1,count;
for(int i=0;i<4;++i)
{
if(b==1)
temp1=b_pos[i];
else
temp1=s_pos[i];
count=0;
for(int j=1;j<=4;++j)
{
for(int k=1;k<=4;++k)
{
++count;
if(count==temp1 && b==1 && !w[j][k].contains("B"))
{
w[j][k]+="B";
}
else
if(count==temp1 && b==2 && !w[j][k].contains("S"))
w[j][k]+="S";
}
}
}
//display(w);
}
void display(String w[][])
{
System.out.println("\nThe environment for problem is as follows.\n");
for(int i=1;i<=4;++i)
{
System.out.println("\n-----------------------------------------------------------------");
System.out.print("|\t");
for(int j=1;j<=4;++j)
System.out.print(w[i][j]+"\t|\t");
}
System.out.println("\n-----------------------------------------------------------------");
}
}
class tiles
{
int safe=0;
int unsafe=0;
int wump=0;
int pit=0;
int gold=0;
int doubt_pit=0;
int doubt_wump=0;
String env;
int num=0;
int br=0;
int bl=0;
int bu=0;
int bd=0;
int visited=0;
int l,r,u,d;
String back="";
tiles(String s,int n)
{
env=s;
num=n;
l=r=u=d=0;
if(n==9 || n==5)
bl=1;
if(n==8 || n==12)
br=1;
if(n==1)
{
bu=1;bl=1;
}
if(n==13)
{
bd=1;bl=1;
}
if(n==4)
{
bu=1;br=1;
}
if(n==16)
{
bd=1;br=1;
}
}
int sense()
{
if(env.contains("B"))
return 1;
else
if(env.contains("S"))
return 2;
else
if(env.contains("G"))
return 3;
if(env.contains("W"))
return 4;
else
return 0;
}
}
class wumpus
{
static int scream=0;
static int score=0;
static int complete=0;
static boolean check(tiles t)
{
int temp=t.sense();
if(temp==1 || temp==2)
return false;
return true;
}
public static void main(String args[])
{
Scanner scr=new Scanner(System.in);
Environment e=new Environment();
String w[][]=new String[5][5];
e.accept(w);
System.out.println("\n\nFinding the solution...");
tiles t[]=new tiles[17];
int c=1;
out:for(int i=1;i<5;++i)
{
for(int j=1;j<5;++j)
{
if(c>16)
break out;
t[c]=new tiles(w[i][j],c);
++c;
}
}
t[13].safe=1;
t[13].visited=1;
int pos=13;
int condition;
int limit=0;
String temp1,temp2;
do
{
++limit;
condition=-1;
if(t[pos].env.contains("G"))
{
complete=1;
System.out.println("Gold Found!!");
break;
}

if(t[pos].br!=1 && t[pos].r!=1 && t[pos+1].doubt_pit<1 && t[pos+1].doubt_wump<1 && t[pos+1].pit!=1 && t[pos+1].wump!=1 && !(t[pos].back.contains("r") && (t[pos].l!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) ))
{
////////////
temp1="l";
///////////
t[pos].r=1;
++pos;
System.out.println("\nfront pos="+pos);
++score;
//t[pos].visited=1;
////////////////
t[pos].back+=temp1;
////////////////
condition=t[pos].sense();
if(condition==3)
{complete=1;break;}
else
if(condition==1 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_pit+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_pit+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1 )
t[pos-1].doubt_pit+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_pit+=1;

t[pos].safe=1;
}
else
if(condition==2 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_wump+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_wump+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_wump+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_wump+=1;

t[pos].safe=1;
}
/*else
if(condition==4)
{
score=score+100;
t[pos].safe=1;
}*/
else
if(condition==0)
t[pos].safe=1;
t[pos].visited=1;
}
else
if(t[pos].bl!=1 && t[pos].l!=1 && t[pos-1].doubt_pit<1 && t[pos-1].doubt_wump<1 && t[pos-1].pit!=1 && t[pos-1].wump!=1 && !(t[pos].back.contains("l") && (t[pos].r!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) ))
{
////////////////////
temp1="r";
///////////////////
t[pos].l=1;
pos=pos-1;
System.out.println("\nback pos= "+pos);
++score;
//t[pos].visited=1;

//////////////////////
t[pos].back+=temp1;
/////////////////////
condition=t[pos].sense();
if(condition==3)
{complete=1;break;}
else
if(condition==1 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_pit+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_pit+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_pit+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_pit+=1;
t[pos].safe=1;
}
else
if(condition==2 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_wump+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_wump+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_wump+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_wump+=1;
t[pos].safe=1;
}
else
if(condition==0)
t[pos].safe=1;
t[pos].visited=1;
}
else
if(t[pos].bu!=1 && t[pos].u!=1 && (pos-4)>=1 && t[pos-4].doubt_pit<1 && t[pos-4].doubt_wump<1 && t[pos-4].pit!=1 && t[pos-1].wump!=1 && !(t[pos].back.contains("u") && (t[pos].l!=1 || t[pos].r!=1 || t[pos].d!=1) && check(t[pos]) ))
{
/////////////////////
temp1="d";
/////////////////////
t[pos].u=1;
pos=pos-4;
System.out.println("\nUp pos= "+pos);
++score;
//t[pos].visited=1;
///////////////////////
t[pos].back+=temp1;
/////////////////////
condition=t[pos].sense();
if(condition==3)
{complete=1;break;}
else
if(condition==1 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_pit+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_pit+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_pit+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_pit+=1;
t[pos].safe=1;
}
else
if(condition==2 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_wump+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_wump+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_wump+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_wump+=1;

t[pos].safe=1;
}
else
if(condition==0)
t[pos].safe=1;

t[pos].visited=1;
}
else
if(t[pos].bd!=1 && t[pos].d!=1 && (pos+4)<=16 && t[pos+4].doubt_pit<1 && t[pos+4].doubt_wump<1 && t[pos+4].pit!=1 && t[pos+4].wump!=1)
{
/////////////////
temp1="u";
////////////////
t[pos].d=1;
pos=pos+4;
System.out.println("\ndown pos= "+pos);
++score;
//t[pos].visited=1;

//////////////////

t[pos].back+=temp1;
//////////////////
condition=t[pos].sense();
if(condition==3)
{complete=1;break;}
else
if(condition==1 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_pit+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_pit+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_pit+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_pit+=1;

t[pos].safe=1;
}
else
if(condition==2 && t[pos].visited==0)
{
if(t[pos].br!=1 && t[pos+1].safe!=1)
t[pos+1].doubt_wump+=1;
if(t[pos].bu!=1 && (pos-4)>=1 && t[pos-4].safe!=1)
t[pos-4].doubt_wump+=1;
if(t[pos].bl!=1 && t[pos-1].safe!=1)
t[pos-1].doubt_wump+=1;
if(t[pos].bd!=1 && (pos+4)<=16 && t[pos+4].safe!=1)
t[pos+4].doubt_wump+=1;

t[pos].safe=1;
}
else
if(condition==0)
t[pos].safe=1;

t[pos].visited=1;
}
else
if(limit>50)
{
int temp3=pos;
int flag_1=0,flag2=0,flag3=0,flag4=0;

System.out.println("\nCurrently at position "+temp3+".\nThinking....");
//if(!(t[pos].back.contains("r") && (t[pos].l!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) ))
while(t[pos].visited==1 && t[pos].br!=1)
{
++pos;
++score;
}


if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].br==1 && t[pos].visited==1 && t[pos].safe!=1))
{
//System.out.println("\nUnsuccessful at pos "+pos);
pos=temp3;
//System.out.println("\nBack at pos "+pos);
flag_1=1;
}

if(flag_1==0)
t[pos].back+="l";

//if(!(t[pos].back.contains("u") && (t[pos].l!=1 || t[pos].r!=1 || t[pos].d!=1) && check(t[pos]) ))
while(pos+4>=1 && t[pos].bu!=1 && t[pos].visited==1)
{
pos-=4;
++score;
}

if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].bu==1 && t[pos].visited==1 && t[pos].safe!=1))
{
//System.out.println("\nUnsuccessful at pos "+pos);
pos=temp3;
//System.out.println("\nBack at pos "+pos);
flag3=1;
}

if(flag3==0)
t[pos].back+="d";

//if(!(t[pos].back.contains("l") && (t[pos].r!=1 || t[pos].u!=1 || t[pos].d!=1) && check(t[pos]) ))
while(t[pos].visited==1 && t[pos].bl!=1)
{
--pos;
++score;
}

if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].bl==1 && t[pos].visited==1 && t[pos].safe!=1))
{
//System.out.println("\nUnsuccessful at pos "+pos);
pos=temp3;
//System.out.println("\nBack at pos "+pos);
flag2=1;
}

if(flag2==0)
t[pos].back+="r";



//if(!(t[pos].back.contains("d") && (t[pos].l!=1 || t[pos].r!=1 || t[pos].u!=1) && check(t[pos]) ))
while(pos+4<=16 && t[pos].bd!=1 && t[pos].visited==1)
{
pos+=4;
++score;
}

if(t[pos].pit==1 || t[pos].wump==1 || (t[pos].bd==1 && t[pos].visited==1 && t[pos].safe!=1))
{
//System.out.println("\nUnsuccessful at pos "+pos);
pos=temp3;
//System.out.println("\nBack at pos "+pos);
flag4=1;
}
//t[pos-1].r=0;
//++pos;
//if(!t[pos].env.contains("P") && !t[pos].env.contains("W"))

if(flag4==0)
t[pos].back+="u";

t[pos].safe=1;
t[pos].visited=1;
System.out.println("reached at position "+pos);
limit=0;
}
if(t[pos].env.contains("W") && scream!=1)
{
score+=100;
scream=1;
t[pos].safe=1;
System.out.println("\n\nWumpus killed >--0-->");
t[pos].env.replace("W"," ");
for(int l=1;l<=16;++l)
{
t[l].doubt_wump=0;
t[l].env.replace("S"," ");
}
}

if(t[pos].env.contains("P"))
{
score+=50;
t[pos].pit=1;
System.out.println("\n\nFallen in pit of position "+pos+".");
}

for(int k=1;k<=16;++k)
{
if(t[k].doubt_pit==1 && t[k].doubt_wump==1)
{
t[k].doubt_pit=0;
t[k].doubt_wump=0;
t[k].safe=1;
}
}

for(int y=1;y<=16;++y)
{
if(t[y].doubt_wump>1)
{
t[y].wump=1;
for(int h=1;h<=16;++h)
{
if(h!=y)
{
t[h].doubt_wump=0;
t[h].env.replace("S"," ");
}
}

}

}

///////////////////////////
for(int y=1;y<=16;++y)
{
if(t[y].doubt_pit>1)
{t[y].pit=1;
//System.out.println("\nPit confirmed at position "+y);
}
}
///////////////////////////


try{Thread.sleep(200);}catch(Exception p){}

}
while(complete==0);

if(complete==1)
{
//score=score*2;
//if(scream==1)
//score-=100;

score*=-1;
score+=1000;
}
System.out.println("The score of the agent till he reaches gold is "+score+".\nNow he will return back following the best explored path.");

}
}

Output:

codept@aiktc20 ~/Desktop $ javac wumpus.java
codept@aiktc20 ~/Desktop $ java wumpus
The positions are as follows.

-----------------------------------------------------------------
| 1 | 2 | 3 | 4 |
-----------------------------------------------------------------
| 5 | 6 | 7 | 8 |
-----------------------------------------------------------------
| 9 | 10 | 11 | 12 |
-----------------------------------------------------------------
| 13 | 14 | 15 | 16 |
-----------------------------------------------------------------

Agent start position: 13

Enter the number of pits.
4
Positions of pit, gold and wumpus should not overlap.
Enter the position of pits.
10
7
4
9
Enter the position of wumpus.
6
Enter the position of gold.
11

The environment for problem is as follows.


-----------------------------------------------------------------
| | S | B | P |
-----------------------------------------------------------------
| BS | BW | SP | B |
-----------------------------------------------------------------
| BP | BSP | BG | |
-----------------------------------------------------------------
| AB | B | | |
-----------------------------------------------------------------


Finding the solution...

front pos=14

back pos= 13

Up pos= 9


Fallen in pit of position 9.

down pos= 13

Currently at position 13.
Thinking....
reached at position 15

Currently at position 15.
Thinking....
reached at position 16

Currently at position 16.
Thinking....
reached at position 12

back pos= 11
Gold Found!!
The score of the agent till he reaches gold is 941.
Now he will return back following the best explored path.
codept@aiktc20 ~/Desktop $