· 6 years ago · Mar 14, 2019, 11:30 AM
1<?php echo 'RSA'?>
2<html>
3<head>
4<title>Test</title>
5</head>
6<form action="index.php" method="post">
7 <textarea name="text"></textarea>
8 <input type="submit" value="Start" onclick="">
9</form>
10</html>
11
12<?php
13if(isset($_POST['text'])){
14 $keys = RSA::generateKeys();
15 $publicKey = $keys[0];
16 $secretKey = $keys[1];
17
18 echo '<b> MESSAGE: </b>:'.$_POST['text'].'</br>';
19 $enc = RSA::encript($_POST['text'], $publicKey);
20 echo '<b> ENCRIPTION: </b>'.$enc.'</br>';
21 $dec = RSA::decript($enc, $secretKey);
22 echo '<b> DECRIPTION: </b>'.$dec.'</br>';
23}
24
25class Key{
26 public $key;
27 public $n;
28 public function __construct($key,$n){
29 $this->key = $key;
30 $this->n = $n;
31
32 }
33}
34class RSA{
35
36 public static function generateKeys(){
37 $primes = RSA::primes(120);
38 $p = $primes[rand(0, count($primes)-1)];
39 $q = $primes[rand(0, count($primes)-1)];
40
41 $n = $p*$q;
42 $m = ($p-1)*($q-1);
43 $e = RSA::e($m);
44 $d = RSA::d($e,$m);
45
46 return array(new Key($e, $n),new Key($d, $n));
47
48 }
49 public static function encript($message,Key $pk){
50 $ret = "";
51 for($i=0;$i<strlen($message);$i++){
52 //echo '[char:'.$message[$i].' code'.ord($message[$i]).']';
53 $x = bcpowmod(ord($message[$i]),$pk->key,$pk->n);
54
55 $ret = $ret.($x).' ';
56 }
57 $ret = substr($ret, 0,strlen($ret)-1);
58 return $ret;
59 }
60 public static function decript($message,Key $sk){
61 $message = explode(' ', $message);
62 $ret = "";
63 for($i=0;$i<count($message);$i++){
64 $x = bcpowmod(($message[$i]),$sk->key,$sk->n);
65 $ret = $ret.chr($x).' ';
66 }
67 $ret = substr($ret, 0,strlen($ret)-1);
68 return str_replace(' ', '', $ret);
69 }
70
71
72 private static function primes($n){
73 $arr = array($n);
74 for($i=0;$i<$n;$i++){
75 $arr[$i]=true;
76 }
77 $ret = array();
78 for($s = 2 ; $s < $n; $s++){
79 if($arr[$s]){
80 $ret[]=$s;
81 for($j=$s*2;$j<$n;$j+=$s){
82 $arr[$j]=false;
83 }
84 }
85 }
86 return $ret;
87 }
88 private static function e($m){
89 for($i=2;$i<$m;$i++){
90 if(RSA::gdc($i,$m)==1) return $i;
91 }
92 return 1;
93 }
94 private static function d($e,$m){
95 for($k=0;2<3;$k++){
96 if(($k*$m+1)%$e==0) {
97 return ($k*$m+1)/$e;
98 }
99 }
100 return 0;
101 }
102
103 private static function gdc($a,$b){
104 if($a%$b==0)
105 return $b;
106 return RSA::gdc($b,$a % $b );
107 }
108
109}
110
111?>