forked from baumann-at/base45-php
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase45.php
75 lines (66 loc) · 1.76 KB
/
base45.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
<?php
/*
Base45 endocing/decoding
Specification: https://datatracker.ietf.org/doc/draft-faltstrom-base45/
30.3.2021
Chris Baumann - [email protected]
*/
$charset = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ $%*+-./:";
function divmod($x, $y) {
$resX = floor($x / $y);
$resY = $x % $y;
return(array($resX, $resY));
}
function str2buffer($s) {
$res = array();
for ($i=0; $i<strlen($s); $i++) {
$res[] = ord($s[$i]);
}
return($res);
}
function b45str2buffer($s) {
global $charset;
$res = array();
for ($i=0; $i<strlen($s); $i++) {
$p = strpos($charset, $s[$i]);
if ($p === false) {
throw new Exception('Invalid base45 value');
} else {
$res[] = $p;
}
}
return($res);
}
function base45_encode($input) {
global $charset;
$buffer = str2buffer($input);
$res = '';
for ($i=0; $i<count($buffer); $i+=2) {
if (count($buffer) - $i > 1) {
$x = ($buffer[$i] << 8) + $buffer[$i+1];
list($e, $rest) = divmod($x, 45 * 45);
list($d, $c) = divmod($rest, 45);
$res .= @$charset[$c] . @$charset[$d] . @$charset[$e];
} else {
list($d, $c) = divmod($buffer[$i], 45);
$res .= @$charset[$c] . @$charset[$d];
}
}
return($res);
}
function base45_decode($input) {
$buffer = b45str2buffer($input);
$res = '';
for ($i=0; $i<count($buffer); $i+=3) {
if (count($buffer) - $i >= 3) {
$x = $buffer[$i] + $buffer[$i+1] * 45 + $buffer[$i+2] * 45 * 45;
list($a, $b) = divmod($x, 256);
$res .= chr($a) . chr($b);
} else {
$x = $buffer[$i] + $buffer[$i+1] * 45;
$res .= chr($x);
}
}
return($res);
}
?>