Monday, October 22, 2018

Diffie–Hellman key exchange using C programming language


This is a code for Diffie–Hellman key exchange using C programming language.



Diffie–Hellman key exchange:-
Source code:-

#include <stdio.h>
int compute(int a, int m, int n)
{
int r;
int y = 1;

while (m > 0)
{
r = m % 2;

if (r == 1)
y = (y*a) % n;
a = a*a % n;

m = m / 2;
}

return y;
}
int main()
{
int p = 23;
int g = 5;

int a, b;
int A, B;
a = 6;
A = compute(g, a, p);

b = 15;
B = compute(g, b, p);
int keyA = compute(B, a, p);
int keyB = compute(A, b, p);

printf("Alice's Secret Key is %d\nBob's Secret Key is %d", keyA, keyB);

return 0;
}

Output:-


Elliptic curve cryptography using C programming language


This is a code for Elliptic curve cryptography using C programming language.



Elliptic curve cryptography:-
Source code:-

#include <iostream>
#include<math.h>
using namespace std;

int main(){
    int p,a,b,x,y;
    float temp;
    cin>>p>>a>>b;
    x = 0;
    cout<<"x\t"<<"y\t"<<"points"<<endl;
    while(x<p){
        temp = sqrt(((x*x*x) + x + 1) % p);
        y = temp;
        if(y == temp)
        {
            cout<<x<<"\t";
            cout<<y<<"\t";
            cout<<"("<<x<<","<<y<<") ";
            cout<<"("<<x<<","<<"-"<<y<<")";
        }
        else{
            cout<<x<<"\t";
            cout<<y<<"\t";
            cout<<"-";
            cout<<"-";
        }
        cout<<endl;
        x++;
    }
    return 0;
}


Output:-


Euclidean algorithm using C programming language


This is a code for Euclidean algorithm using C programming language.



Euclidean algorithm:-
Source code:-

#include <stdio.h>
int greatestCommonDivisor(int m, int n)
{
    int r;
    if((m == 0) || (n == 0))
        return 0;
    else if((m < 0) || (n < 0))
        return -1;

    do
    {
        r = m % n;
        if(r == 0)
            break;
        m = n;
        n = r;
    }
    while(1);

    return n;
}

int main(void)
{
    int num1 = 600, num2 = 120;
    int gcd = greatestCommonDivisor(num1, num2); 

    printf("The GCD of %d and %d is %d\n", num1, num2, gcd);

    getchar();
   return 0;
}


Output:-


Extended euclidean cipher using C programming language


This is a code for Extended euclidean using C programming language.



Extended euclidean :-
Source code:-

#include<stdio.h>
#include<conio.h>
int main()
{
    int r1,a,r2,b,r,q,s1,s2,t1,t2,s,t;
    printf("Enter the value of a and b:");
    scanf("%d%d",&a,&b);
    r1=a;
    r2=b;
    s1=1,s2=0,t1=0,t2=1;
    while(r2>0)
    {
        q=r1/r2;
        r=r1-q*r2;
        s=s1-q*s2;
        t=t1-q*t2;
        printf(" %d    %d   %d     %d      %d   %d  %d  %d   %d   %d \n",q,r1,r2,r,s1,s2,s,t1,t2,t);
        r1=r2;
        r2=r;
        s1=s2;
        s2=s;
        t1=t2;
        t2=t;
    }
    printf(" %d   *   %d   +   %d    *   %d   = gcd(%d,%d) = %d \n",s,a,t,b,a,b,r1);
    getch();
}


Output:-


OTP ( One-time pad ) using C programming language


This is a code for OTP ( One-time pad )
 using C programming language.




OTP Encryption:-
Source code:-

#include<stdio.h>
#include<string.h>
#include<ctype.h>
main()
{
int i,j,len1,len2,numstr[100],numkey[100],numcipher[100];
 char str[100],key[100],cipher[100];
 printf("Enter a string text to encrypt\n");
 gets(str);
 for(i=0,j=0;i<strlen(str);i++)
 {
  if(str[i]!=' ')
  {
   str[j]=toupper(str[i]);   
   j++;
  }
 }
 str[j]='\0';
    for(i=0;i<strlen(str);i++)
    {
     numstr[i]=str[i]-'A';    
    }   
    printf("Enter key string of random text\n");
    gets(key);
 for(i=0,j=0;i<strlen(key);i++)
 {
  if(key[i]!=' ')
  {
   key[j]=toupper(key[i]);   
   j++;
  }
 }
 key[j]='\0';
    for(i=0;i<strlen(key);i++)
    {
     numkey[i]=key[i]-'A';    
    }  
    
    for(i=0;i<strlen(str);i++)
    {
     numcipher[i]=numstr[i]+numkey[i];
    }
    for(i=0;i<strlen(str);i++)
    {
     if(numcipher[i]>25)
     {
      numcipher[i]=numcipher[i]-26;
     }
    }
    printf("One Time Pad Cipher text is\n");
    for(i=0;i<strlen(str);i++)
    {
      printf("%c",(numcipher[i]+'A')); 
    }
    printf("\n");
}

Output:-


Playfair cipher using C programming language


This is a code for Playfair cipher using C programming language.



Playfair cipher:-
Source code:-

#include<stdio.h>
#include<conio.h>
#include<string.h>
#include<ctype.h>
#define MX 5  
void playfair(char ch1, char ch2, char key[MX][MX]) {  
int i, j, w, x, y, z;  
    FILE * out;  
    if ((out = fopen("cipher.txt", "a+")) == NULL) {  
printf("File Currupted.");  
    }  
    for (i = 0; i < MX; i++) {  
        for (j = 0; j < MX; j++) {  
            if (ch1 == key[i][j]) {  
                w = i;  
                x = j;  
            } else if (ch2 == key[i][j]) {  
                y = i;  
                z = j;  
            }  
        }  
    }  
    //printf("%d%d %d%d",w,x,y,z);  
    if (w == y) {  
        x = (x + 1) % 5;  
        z = (z + 1) % 5;  
printf("%c%c", key[w][x], key[y][z]);  
fprintf(out, "%c%c", key[w][x], key[y][z]);  
    } else if (x == z) {  
        w = (w + 1) % 5;  
        y = (y + 1) % 5;  
printf("%c%c", key[w][x], key[y][z]);  
fprintf(out, "%c%c", key[w][x], key[y][z]);  
    } else {  
printf("%c%c", key[w][z], key[y][x]);  
fprintf(out, "%c%c", key[w][z], key[y][x]);  
    }  
fclose(out);  
}  
int main() {  
int i, j, k = 0, l, m = 0, n;  
    char key[MX][MX], keyminus[25], keystr[10], str[25] = {  
        0  
    };  
    char alpa[26] = {  
        'A',  
        'B',  
        'C',  
        'D',  
        'E',  
        'F',  
        'G',  
        'H',  
        'I',  
        'J',  
        'K',  
        'L',  
        'M',  
        'N',  
        'O',  
        'P',  
        'Q',  
        'R',  
        'S',  
        'T',  
        'U',  
        'V',  
        'W',  
        'X',  
        'Y ',  
        'Z'  
    };  
printf("\nEnter key:");  
    gets(keystr);  
printf("\nEnter the plain text:");  
    gets(str);  
    n = strlen(keystr);  
    //convert the characters to uppertext
    for (i = 0; i < n; i++) {  
        if (keystr[i] == 'j') keystr[i] = 'i';  
        else if (keystr[i] == 'J') keystr[i] = 'I';  
keystr[i] = toupper(keystr[i]);  
    }  
    //convert all the characters of plaintext to uppertext
    for (i = 0; i<strlen(str); i++) {  
        if (str[i] == 'j') str[i] = 'i';  
        else if (str[i] == 'J') str[i] = 'I';  
str[i] = toupper(str[i]);  
    }  
    // store all characters except key  
    j = 0;  
    for (i = 0; i < 26; i++) {  
        for (k = 0; k < n; k++) {  
            if (keystr[k] == alpa[i]) break;  
            else if (alpa[i] == 'J') break;  
        }  
        if (k == n) {  
keyminus[j] = alpa[i];  
            j++;  
        }  
    }  
    //construct key keymatrix
    k = 0;  
    for (i = 0; i < MX; i++) {  
        for (j = 0; j < MX; j++) {  
            if (k < n) {  
                key[i][j] = keystr[k];  
                k++;  
            } else {  
                key[i][j] = keyminus[m];  
                m++;  
            }  
printf("%c ", key[i][j]);  
        }  
printf("\n");  
    }  
printf("\n\nEntered text :%s\nCipher Text :", str);  
    for (i = 0; i<strlen(str); i++) {  
        if (str[i] == 'J') str[i] = 'I';  
        if (str[i + 1] == '\0') playfair(str[i], 'X', key);  
        else {  
            if (str[i + 1] == 'J') str[i + 1] = 'I';  
            if (str[i] == str[i + 1]) playfair(str[i], 'X', key);  
            else {  
playfair(str[i], str[i + 1], key);  
                i++;  
            }  
        }  
    }  
getch();  
}

Output:-


Rail fence cipher using C programming language


This is a code for Rail fence cipher using C programming language.



Rail fence cipher:-
Source code:-

#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{ int i,j,k,l;
char a[20],c[20],d[20];
//clrscr();
printf("\n**********RailFence**********");
printf("\nEnter the input string: ");
gets(a);
l=strlen(a);
for(i=0,j=0;i<l;i++)
{ if(i%2==0)
c[j++]=a[i];
}
for(i=0;i<l;i++)
{ if(i%2==1)
c[j++]=a[i];
}
c[j]='\0';
printf("\nCipher text after applying rail fence: ");
printf("\n%s",c);
if(l%2==0)
k=l/2;
else
k=(l/2)+l;
for(i=0,j=0;i<k;i++)
{ d[j]=c[i];
j=j+2;
}
for(i=k,j=1;i<l;i++)
{ d[j]=c[i];
j=j+2;
}

getch();
}

Output:-


RSA Algorithm in C programming language


This is a code for RSA in C programming language.



RSA:-
Source code:-

#include<stdio.h>
#include<math.h>
int gcd(int a, int h)
{
    int temp;
    while(1)
    {
        temp = a%h;
        if(temp==0)
        return h;
        a = h;
        h = temp;
    }
}

int main()
{
    //2 random prime numbers
    double p = 3;
    double q = 7;
    double n=p*q;
    double count;
    double totient = (p-1)*(q-1);
    double e=2;
    while(e<totient){
    count = gcd(e,totient);
    if(count==1)
        break;
    else
        e++;
    }
    double d;
    double k = 2;
    d = (1 + (k*totient))/e;
    double msg = 12;
    double c = pow(msg,e);
    double m = pow(c,d);
    c=fmod(c,n);
    m=fmod(m,n);

    printf("Message data = %lf",msg);
    printf("\np = %lf",p);
    printf("\nq = %lf",q);
    printf("\nn = pq = %lf",n);
    printf("\ntotient = %lf",totient);
    printf("\ne = %lf",e);
    printf("\nd = %lf",d);
    printf("\nEncrypted data = %lf",c);
    printf("\nOriginal Message Sent = %lf",m);

    return 0;
}

Output:-


ASCII code for String using C programming language


This is a code for ASCII code for String using C programming language.



ASCII :-
Source code:-

#include<stdio.h>
#include<conio.h>
int main()
{
char arr[100];
long a=0,b=0,c;
long int s=0;
int i,n=5,j;
long dummy,remainder=0,binary=0,base=1;
long binaryval,hexadecimalval=0,k=1,rm;

printf("Enter the string : ");
for(i=0;i<n;i++)
{
scanf("%c",&arr[i]);
}
printf("ASCII code for string : ");
for(i=0;i<n;i++)
{
printf("%d ",arr[i]);
}
printf("\n");
for(i=0;i<n;i++)
{       remainder=0,binary=0,base=1;
dummy=arr[i];
while(dummy>0)
{
remainder=dummy%2;
binary=binary+remainder*base;
dummy=dummy/2;
base=base*10;
}
printf("\n 8 Bit code for %c(%d) is 0%ld",arr[i],arr[i],binary);
a=0,b=0;
a=binary;
b=a/10000;
printf("\n Left half : %ld",b);
s=0;
for(j=1;j<=4;j++)
{
s=a%10000;
}
printf("\tRight half : %.4ld",s);
hexadecimalval=0,k=1;
binaryval=s*10000+b;
printf("\n after swap : %.8ld",binaryval);
while(binaryval!=0)
{
rm=binaryval%10;
hexadecimalval=hexadecimalval+rm*k;
k=k*2;
binaryval=binaryval/10;
}
printf("\n Equivalent hexadecimal value :  %ld",hexadecimalval);
}
getch();
}

Output:-

Caesar cipher encryption and decryption using C programming language


This is a code for Caesar cipher encryption and decryption using C programming language.



Caesar cipher encryption:-
Source code:-

#include<conio.h>
#include<stdio.h>
int main()
{
int key,i;
char msg[100],ch;
printf("enter string to be encrypt");
scanf("%s",&msg);
printf("enter key");
scanf("%d",&key);
for(i=0;msg[i]!='\0';i++)
{
ch=msg[i];
if(ch>='a'&&ch<='z')
{
ch=ch+key;
if(ch>'z')
{
ch=ch-'z'+'a'-1;

}
msg[i]=ch;

}
else if (ch>='A'&&ch<'Z'){
ch=ch+key;
if(ch>'Z')
{
ch=ch-'Z'+'A'-1;
}
msg[i]=ch;
}
}
printf("encrypted msg:%s",msg);
return 0;
}


Output:-


                                                                                                            

Caesar cipher decryption:-
Source code :-

#include<conio.h>
#include<stdio.h>
int main()
{
int key,i;
char msg[100],ch;
printf("enter string to be encrypt");
scanf("%s",&msg);
printf("enter key");
scanf("%d",&key);
for(i=0;msg[i]!='\0';i++)
{
ch=msg[i];
if(ch>='a'&&ch<='z')
{
ch=ch-key;
if(ch>'z')
{
ch=ch-'z'+'a'-1;

}
msg[i]=ch;

}
else if (ch>='A'&&ch<'Z')
{
ch=ch-key;
if(ch>'Z')
{
ch=ch-'Z'+'A'-1;
}
msg[i]=ch;
}
}
printf("encrypted msg:%s",msg);
return 0;
}

Output:-


Short Over View of BlockChain

Real Estate
Introduction

A blockchain, originally block chain, is a growing list of records, called blocks, which are linked using cryptography. Each block contains a cryptographic hash of the previous block, a timestamp, and transaction data. By design, a blockchain is resistant to modification of the data.


Decentralized Peers

Rather than the centralized “Hub and Spoke” type of network, Blockchain is a decentralized peer to peer network. Where each NODE has a copy of the ledger.


Legacy Network  Blockchain Network


Centralized DB  Distributed Ledgers



How Blockchain Technology Works




Blockchain - Social Networking

Blockchain in social networking


Introduction to Blockchain Technology
Blockchain is normally associated with Bitcoin and other cryptocurrencies, but it is efficiently a database that’s authenticated by a wider community, rather than a middle authority. It’s a collection of records that a crowd oversees and maintains, rather than relying on a single entity, which most expected hosts data on a particular server. Of course, a physical database kept on paper could never be supervised by tens of thousands of peers. That’s where computers, and the internet, come in. Each “block” stands for a number of transactional records, and the “chain” component links them all together with a hash function. As records are shaped, they are established by a distributed network of computers and paired up with the preceding entry in the chain, thereby generating a chain of blocks or a Blockchain.
Blockchain Risks and Opportunities
Opportunities:
The potential opportunities of blockchain technology will be examined in this article under three broad categories as follows:

1. Commerce
The first recognizable niche that comes to mind when the blockchain is mentioned is commerce. The first ever successful implementation of the blockchain framework resulted in Bitcoin, a payment processing architecture. This, and the fact that the majority of the blockchain applications that have been launched since then have been focused on cryptocurrencies has led some to believe that crypto is all there is to blockchains.

The entire framework of global commerce presents a veritable opportunity for blockchain implementation. Blockchain technology can be applied to almost every aspect of commerce. One of the most valuable opportunity for blockchain adoption in commerce is the area of cross-border transactions. The current framework for cross-border transactions is one that involves a number of processes and checks that slow down the transactions and even make them quite expensive. Blockchain technology has the potential to create a borderless network architecture that will enable cross-border transactions to happen almost instantaneously.
2. Government
Government is charged with a whole host of duties and responsibilities that must be discharged for the benefit of the citizens. Blockchain technology has a vital role to play in government especially in the context of the 21st-century world. Blockchains can be utilized for identity management systems, document processing, safeguarding financial and state services, as well as transmitting sensitive information just to mention a few.
Risks:
The blockchain risks can be broadly classified under three categories:
Standard risks:
Blockchain technologies expose institutions to risks that are similar to those associated with current business processes but introduce nuances for which entities need to account.

Value transfer risks:
Blockchain enables peer-to-peer transfer of value without the need for a central intermediary. The value transferred could be assets, identity, or information. This new business model exposes the interacting parties to new risks that were previously managed by central intermediaries.
Smart contract risks:
Smart contracts can potentially encode complex business, financial, and legal arrangements on the blockchain, and could result in the risk associated with the one-to-one mapping of these arrangements from the physical to the digital framework.
Key challenges
One of the challenges of blockchain is in its very nature: the distributed ledger. Because every endpoint has to have a copy of the entire blockchain, and that blockchain is constantly growing as more things are added, the system gets slower, taking up more space. If the same sort of system was implemented under a medical records system, you can see where it would become untenable very quickly.
The biggest challenge of blockchain is the lack of awareness of the technology, and the lack of understanding how it works.
Case study
Blockchain in social networking:
Whether you are a social media marketer the one who is offering services to businesses or a business owner who is making use of social media to reach customers, it is quite important that you understand that social media is about to go through a striking shift.
The blockchain is unsettling a number of industries, and social media is among those which is likely to feel the ramifications of blockchain disruption first. Companies actually used to create their brands on platforms like Facebook and Twitter are about to realize that all that investment of time may have been for nought. As it is going to change the platforms consumers and businesses use and how they network, social media marketing will go through a disturbance which they never expected and even it never did before.

Problems Identified
1. Control over data
Social network users currently have no control over their data. Once a user has an account on a social network it is as if they relinquish their right to their personal information and control over content. Total control is in the hands of social network owners who dictate what is to be viewed by users and what is not. And with such control, the social network platform owners are able to profit from their users without the users’ consent.
2. Privacy
If the recent Facebook data breach is anything to go by, then the current social networks are proving to have poor security. Users are susceptible to attacks which are known to expose their personal information.
3. Single Point of Failure
Because of their centralized nature, conventional social networks are vulnerable to attacks that often lead to costly losses. Hackers only have one point of attack, which ones breached they can get access to a flood of users’ information. For example, in 2012 a hacker broke into LinkedIn network and got away with some 6.5 million encrypted passwords and posted them on a Russian hacker forum. Four years later another hacker who goes by the name Peace was selling more of LinkedIn hacked user information. He claimed that the total count of data stolen from LinkedIn reached 167 million and not 6.5 million as thought before. Of which 117 million had both email and encrypted passwords.

Solutions Provided
Blockchain technology is the long-awaited cure to issues affecting the current breed of social networks. The following features are what make Blockchain technology so groundbreaking.
1. Transparency
Blockchain distributed nature eliminates the control of platforms by a single entity. And since every transaction on the Blockchain-based platform is tracked and audited by several servers and developers, it becomes impossible for anyone to tamper with the data.
2. Control over data
By eliminating intermediaries, users on decentralized social networks will own and control their data. Blockchain technology ensures that whatever you post on the social network can be traced anywhere it goes and never be duplicated. And the best part is that if you delete it, it is deleted in the whole system and no unauthorized third parties can access and benefit from it.


3. Relevant content
Once control of your social network platforms is in your hands, you get to dictate the type of content you would like to see. Therefore you don’t get unwanted advertisements on your platforms that only benefit the advertisers and not you.

4. Earning from social media activity
Blockchain-based platforms enable you and your viewers, listeners, readers, depending on the content you create, to build a direct relationship that is monetarily beneficial to you.

Market Competition
As we are entering an era of change, a global phenomenon will soon emerge as philosophies and beliefs shift and unexposed cultures experience new technologies. In 20-30 years from now we are going to enter into a super economy, where the content is much more equally distributed between the global populations.

Right now the margins of distribution are narrow, and this is about to change. This is disruptive change that can happen overnight. People will be able to buy essential products, solar panels, mobile phones, etc. This could change markets on a global scale as disadvantaged populations can more easily communicate.

Kodak was liquidated overnight when Nokia chose to ship their mobile phones with cameras. The same could happen with social media and the banking system. This could herald a sea change in global economics. Only one single form of social media has to accommodate micro-payments in order for this to happen. Once they integrate with the Blockchain, then boom! Something big is happening. From there it will spread like wildfire. There will be a big change in the landscape of social media companies. The first to leap will gain the most traction, then the others must also conform or die. Social media companies will have no justification to exist if they do not get onboard.

The next question is what will happen to all the advertisers on social media? Revenues of companies that make money from advertisements (Google, Yahoo, Facebook, etc.) will go down. There would be less justification to charge your user base money for advertisements. Major businesses may be rendered obsolete – this will be the next disruption of the chain. Social media products may no longer be a necessary advertising platform. Existing companies will try to ensure they are not outgrown when equivalent open source platforms rise quickly and establish firm footings in fresh soil.

Future Trends
1) More earning
The combination of social networks and cryptocurrencies enabled with blockchain development is another tempting example of the future of social platforms. When decentralized platforms become common, users of social networks will have the option of choosing the platforms on which to establish a network.
              The ability to earn small amounts of cryptocurrencies for their activities will attract users to platforms where contributions to platform growth are rewarded. Think about how much time you spend currently on social networking sites like Twitter and Facebook and imagine if each publication you won earned you a small amount of Bitcoin. A future of social networks enabled for encryption is really intriguing.
2) No more spams
Smart contracts and blockchain development technology will also influence the dissemination of false content. The current social media networks are flooded with everything from false news to spam bots. In the social media networks of the future, the distribution of content will be based on verified information and the propagation of traceable data. The ability to block content and its collaborators is a tempting option for brand creators.

3) No fraudulent impressions
There will be a growing interest in identities verified online. With massive bot issues on social media platforms such as Facebook and Twitter, business owners are increasingly looking for reaching reliable platforms for their customers where they can increase their marketing ROI.

Diffie–Hellman key exchange using C programming language

This is a code for  Diffie–Hellman key exchange  using C programming language. Diffie–Hellman key exchange :- Source code:- #in...