Sunday, December 31, 2017

C Programming - Encription using XOR

#include<stdio.h>

int main()
{
    int a = 0,b = 0,temp = 0,val_a = 0,val_b = 0;

    /* Used for XOR shift */
    int  p = 0;

    int xor_only = -1,xor_shift = -1;

    printf("Enter two numbers\n");   
    scanf("%d %d",&a,&b);
   
    printf("Enter p, the xor shift  value for encription \n");   
    scanf("%d",&p);   

    if(p > 32)
        return;
       
    xor_only = xor_fn(a,b);
   
    printf("result of xor = %d\n",xor_only);

    xor_shift = xor_shift_fn(a,b,p);   
    printf("xor encripted value  = %d\n",xor_shift);

    /* retrieve the value of a from value shifted xored */
    val_a  = xor_decrypt_fn(xor_shift,a,p);
    printf("val_a retrieved = %d\n",val_a);
   
    /* retrieve the value of b from value shifted xored */
    val_b  = xor_decrypt_fn(xor_shift,b,p);
    printf("val_b retrieved = %d\n",val_b);

    return 0;
}

int xor_fn(int a,int b)
{
    return (a^b);
}

/* USED for encription using XOR, 'p' being the entropy */
int xor_shift_fn(int a, int b, int p)
{
    return (xor_fn(a<<p,b<<p));
}

int xor_decrypt_fn(int encripted_val, int val, int p)
{
    encripted_val =  encripted_val >> p;
    return (xor_fn(encripted_val,val));
}


No comments:

Post a Comment