genPrim(); $q=$this->genPrim(); $this->n=bcmul($p,$q); $z=bcmul(bcsub($p,1),bcsub($q,1)); $this->d=$this->calc_d($z); $this->e=$this->calc_e($this->d,$z); $_SESSION['phpgw_session']['publ_key'] = $this->d; $_SESSION['phpgw_session']['priv_key'] = $this->e; $_SESSION['phpgw_session']['modulus'] = $this->n; } else { $this->e = $_SESSION['phpgw_session']['publ_key']; $this->d = $_SESSION['phpgw_session']['priv_key']; $this->n = $_SESSION['phpgw_session']['modulus'] ; } session_write_close(); } function encode($string){ $result = ""; for($i=0; $i < strlen($string); $i+=3) $result .= $this->encode_(ord($string[$i]).ord($string[$i+1]).ord($string[$i+2]),$this->e,$this->n)." "; return $result; } function decode($string){ $nums = split(" ",$string); foreach($nums as $todec) if (ord($todec) > 1){ $num = $this->decode_($todec,$this->d,$this->n); $num1 = substr($num,0,3); $num2 = substr($num,3,3); $num3 = substr($num,6,3); ($num1 > 1) && $result .= chr($num1); ($num2 > 1) && $result .= chr($num2); ($num3 > 1) && $result .= chr($num3); } return $result; } function get_publKey(){ return $_SESSION['phpgw_session']['publ_key']; } function get_mod(){ return $_SESSION['phpgw_session']['modulus']; } private function isPrime($Num){ $result = true; if($Num == 2 || $Num == 3) return true; if($Num % 2 == 0) return false; for($Divisor = 3; $Divisor < (sqrt($Num)+1); $Divisor+=2) { $Res = $Num % $Divisor; if($Res == 0) { $result=false; break; } } return $result; } private function genPrim(){ $num=rand(100000,5000000); $i=$num; while($i++) if ($this->isPrime($i)) return $i; } private function GCD($e,$m) { $y = $e; $x = $m; while (bccomp($y, 0) != 0) { // modulus function $w = bcsub($x, bcmul($y, bcdiv($x, $y, 0)));; $x = $y; $y = $w; } return $x; } // // Calculating E under conditions: // GCD(N,E) = 1 and 1GCD($e, $m), '1') != 0){ $e = '5'; $step = '2'; while(bccomp($this->GCD($e, $m), '1') != 0){ $e = bcadd($e, $step); if($step == '2'){ $step = '4'; }else{ $step = '2'; } } } return $e; } private function calc_e ($Ee,$Em) { $u1 = '1'; $u2 = '0'; $u3 = $Em; $v1 = '0'; $v2 = '1'; $v3 = $Ee; while (bccomp($v3, 0) != 0) { $qq = bcdiv($u3, $v3, 0); $t1 = bcsub($u1, bcmul($qq, $v1)); $t2 = bcsub($u2, bcmul($qq, $v2)); $t3 = bcsub($u3, bcmul($qq, $v3)); $u1 = $v1; $u2 = $v2; $u3 = $v3; $v1 = $t1; $v2 = $t2; $v3 = $t3; $z = '1'; } $uu = $u1; $vv = $u2; if (bccomp($vv, 0) == -1) { $inverse = bcadd($vv, $Em); } else { $inverse = $vv; } return $inverse; } private function encode_($val,$e,$n){ return bcpowmod($val,$e,$n); } private function decode_($val,$d,$n){ return bcpowmod($val,$d,$n); } } ?>