-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathelgamal.php
93 lines (84 loc) · 2.19 KB
/
elgamal.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
class elgamal
{
var $x;
var $p;
var $g;
var $y;
var $text;
function isPrime($number)
{
// 1 is not prime
if ($number == 1) {
return false;
}
// 2 is the only even prime number
if ($number == 2) {
return true;
}
// square root algorithm speeds up testing of bigger prime numbers
$x = sqrt($number);
$x = floor($x);
for ($i = 2; $i <= $x; ++$i) {
if ($number % $i == 0) {
break;
}
}
if ($x == $i - 1) {
return true;
} else {
return false;
}
}
function getKey()
{
//todo mendapatkan kunci publik
if (!$this->isPrime($this->p)) {
echo "[+] Pastikan kolom bilangan prima adalah bilangan prima\n";
exit("keluar");
}
return bcpowmod($this->g, $this->x, $this->p);
}
function pecahString()
{
//todo memecah teks menjadi array
return str_split($this->text);
}
function getAscii()
{
foreach ($this->pecahString() as $pecahan) {
$ascii[] = ord($pecahan);
}
return $ascii;
}
function encrypt()
{
//menggabungkan delta dan gamma menjadi array setiap m
foreach ($this->getAscii() as $m) {
$k = $this->getK($m);
$cipher[] = bcpowmod($this->g, $k, $this->p); //gamma
$cipher[] = bcmod(bcmul(bcpow($this->getKey(), $k), $m), $this->p); //delta
}
return $cipher;
}
function decrypt()
{
$cipher = $this->cipher;
for ($i = 0; $i < count($cipher); $i++) {
if ($i % 2 != 0) {
$delta[] = $cipher[$i]; //indeks ganjil
} else {
$gamma[] = $cipher[$i]; // indeks genap
}
}
$pangkat = $this->p - 1 - $this->x;
for ($i = 0; $i < count($gamma); $i++) {
$xxxx[] = chr(bcmod(bcmul($delta[$i], bcpow($gamma[$i], $pangkat)), $this->p));
}
return implode('', $xxxx);
}
function getK()
{
return rand(1, ($this->p - 2)); //random number
}
}