· 7 years ago · Oct 16, 2018, 05:54 PM
1#include <iostream>
2#include <conio.h>
3#include <stdio.h>
4#include <stdlib.h>
5#include <string.h>
6#include <locale.h>
7
8using namespace std;
9
10int mod_aX(int a,int x,int p)
11{
12int rez=0;
13rez=a;
14for(int i=2;i<=x;i++)
15{
16rez*=a;
17while(rez>=p){rez-=p;}
18}
19if(x==1)
20{
21while(rez>=p){rez-=p; }
22}
23return rez;
24}
25
26// РаÑширенный алгоритм Евклида , понадобитÑÑ Ð¿Ñ€Ð¸ нах обр Ñлемента
27// d=ÐОД(a,b) e x,y :ax + by = d.
28void extended_euclid(unsigned long a, unsigned long b, long *x, long *y, long *d)
29{
30 long q, r, x1, x2, y1, y2;
31 if (b == 0)
32 {
33 *d = a, *x = 1, *y = 0;
34 return;
35 }
36 x2 = 1, x1 = 0, y2 = 0, y1 = 1;
37 while (b > 0)
38 {
39 q = a / b, r = a - q * b;
40 *x = x2 - q * x1, *y = y2 - q * y1;
41 a = b, b = r;
42 x2 = x1, x1 = *x, y2 = y1, y1 = *y;
43 }
44 *d = a, *x = x2, *y = y2;
45}
46
47//Ищем обратный Ñлемент по модулю
48long inverse(unsigned long a, unsigned long n)
49{
50 long d, x, y;
51 extended_euclid(a, n, &x, &y, &d);
52if (d != 1){return 0;}
53 else
54 return x;
55}
56void D_H(long p=30803,long g=2,long XA=1000,long XB=2000)
57{
58int a=1000,b=2000;
59long A,B,K;
60 cout << " *** D_H ***" << endl;
61 A=mod_aX(g,a,p);
62 cout << "OpenKey A:" << A << endl;
63 B=mod_aX(g,b,p);
64 cout << "OpenKey B:" << B << endl;
65 K=mod_aX(A,b,p);
66 cout << "SecretKey A:" << K << endl;
67 K=mod_aX(B,a,p);
68 cout << "SecretKey B:" << K << endl;
69 cout << "Press Enter" << endl;
70 cin.get();
71}
72 void El_Gamal(long p=30803,long g=2,long c=500,long k=600,long M=11111)
73 {
74 long a,b,y;
75 y=mod_aX(g,c,p);
76 a=mod_aX(g,k,p);
77 b=mod_aX(y,k,p);
78 b=mod_aX((b*M),1,p);
79 cout << " *** El_Gamal ***" << endl;
80 cout << "Sipher (" << a << ";" << b << ")" << endl;
81 cout << "Press Enter" << endl;
82 cin.get();
83 }
84 void RSA(long p=131,long q=227,long d=3,long m=11111)
85 {
86
87 long e=inverse(d,p);
88 long P=mod_aX(m,e,(p*q));
89 cout << " *** RSA ***" << endl;
90 cout << P << endl;
91 cout << "Press Enter" << endl;
92 cin.get();
93 }
94
95 void Shamir(long p=30803,long d1=501,long d2=601,long m=11111)
96
97{
98long C1,C2,C3;
99long e1,e2;
100e1=inverse(d1,(p-1));
101e2=inverse(d2,(p-1));
102cout << " *** Shamir ***" << endl;
103cout << "Start message: " << m << endl;
104C1=mod_aX(m,e1,p);
105cout << "Encripting by A: " << C1 << endl;
106C2=mod_aX(C1,e2,p);
107cout << "Encripting by B: " << C2 << endl;
108C3=mod_aX(C2,d1,p);
109cout << "Decripting by A: " << C3 << endl;
110m=mod_aX(C2,d2,p);
111cout << "Decripting by B(message from A): " << m << endl;
112cout << m << endl;
113cout << "Press Enter" << endl;
114cin.get();
115
116}
117
118 int main()
119 {
120 RSA();
121 D_H();
122 El_Gamal();
123 Shamir();
124 }