RSA CRYPT ENCRYPT

 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
function encode_rsa($data, $key, $exp) {
$out = "";
$len = strlen($data);
$key_length = strlen($key);
$exp = gmp_init(bin2hex($exp), 16);
$key = gmp_init(bin2hex($key), 16);
$block_size = $key_length - 4;
for ($i = 0; $i < $len; $i += $block_size) {
$block = substr($data, $i, $block_size);
$size = strlen($block);
if ($size == $key_length - 4) {
$enc_data = chr($size >> 32 & 0xFF).chr($size >> 16 & 0xFF).chr($size >> 8 & 0xFF).chr($size & 0xFF);
$enc_data .= $block;
} else {
$size--; // wtf????
$enc_data = chr($size >> 32 & 0xFF).chr($size >> 16 & 0xFF).chr($size >> 8 & 0xFF).chr($size & 0xFF);
$enc_data .= str_repeat("\0", $key_length - 5 - $size).$block;
}
$hex = gmp_strval(gmp_powm('0x'.bin2hex($enc_data), $exp, $key), 16);
$out .= pack('H*', str_repeat("0", $key_length * 2 - strlen($hex)).$hex);
}
return $out;
}
function decode_rsa($data, $key, $exp) {
$out = "";
$key_length = strlen($key);
$exp = gmp_init(bin2hex($exp), 16);
$key = gmp_init(bin2hex($key), 16);
$blocks = strlen($data) / $key_length;
for ($i = 0; $i < $blocks; ++$i) {
$block = substr($data, $i * $key_length, $key_length);
$hex = gmp_strval(gmp_powm('0x'.bin2hex($block), $exp, $key), 16);
$s = pack('H*', str_repeat("0", $key_length * 2 - strlen($hex)).$hex);
$size = ord($s[0]) << 32 | ord($s[1]) << 16 | ord($s[2]) << 8 | ord($s[3]);
if ($size == $key_length - 4) {
$out .= substr($s, -$size);
} else
$out .= substr($s, $key_length - 1 - $size);
}
return $out;
}