-
Notifications
You must be signed in to change notification settings - Fork 108
/
Vigenere.class.php
57 lines (53 loc) · 1.56 KB
/
Vigenere.class.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
<?php
class Vigenere
{
public function Mod($a, $b){
return ($a % $b + $b) % $b;
}
public function cipher($input, $key, $encipher){
$keyLen = strlen($key);
for ($i = 0; $i < $keyLen; ++$i)
if (!ctype_alpha($key[$i]))
return ""; // Error
$output = "";
$nonAlphaCharCount = 0;
$inputLen = strlen($input);
for ($i = 0; $i < $inputLen; ++$i)
{
if (ctype_alpha($input[$i]))
{
$cIsUpper = ctype_upper($input[$i]);
$offset = ord($cIsUpper ? 'A' : 'a');
$keyIndex = ($i - $nonAlphaCharCount) % $keyLen;
$k = ord($cIsUpper ? strtoupper($key[$keyIndex]) : strtolower($key[$keyIndex])) - $offset;
$k = $encipher ? $k : -$k;
$ch = chr(($this->Mod(((ord($input[$i]) + $k) - $offset), 26)) + $offset);
$output .= $ch;
}
else
{
$output .= $input[$i];
++$nonAlphaCharCount;
}
}
return $output;
}
public function encrypt($input, $key, $times = 1){
$str = $input;
$count = 0;
while ($count < $times) {
$str = $this->cipher($str, $key, true);
$count++;
}
return $str;
}
public function decrypt($input, $key){
$str = $input;
$count = 0;
while ($count < $times) {
$str = $this->cipher($str, $key, false);
$count++;
}
return $str;
}
}