1 <?php
2 /**
3 * @package FrameworkOnFramework
4 * @subpackage utils
5 * @copyright Copyright (C) 2010-2016 Nicholas K. Dionysopoulos / Akeeba Ltd. All rights reserved.
6 * @license GNU General Public License version 2 or later; see LICENSE.txt
7 */
8
9 // Protect from unauthorized access
10 defined('FOF_INCLUDED') or die;
11
12 /**
13 * Abstract AES encryption class
14 */
15 abstract class FOFEncryptAesAbstract
16 {
17 /**
18 * Trims or zero-pads a key / IV
19 *
20 * @param string $key The key or IV to treat
21 * @param int $size The block size of the currently used algorithm
22 *
23 * @return null|string Null if $key is null, treated string of $size byte length otherwise
24 */
25 public function resizeKey($key, $size)
26 {
27 if (empty($key))
28 {
29 return null;
30 }
31
32 $keyLength = strlen($key);
33
34 if (function_exists('mb_strlen'))
35 {
36 $keyLength = mb_strlen($key, 'ASCII');
37 }
38
39 if ($keyLength == $size)
40 {
41 return $key;
42 }
43
44 if ($keyLength > $size)
45 {
46 if (function_exists('mb_substr'))
47 {
48 return mb_substr($key, 0, $size, 'ASCII');
49 }
50
51 return substr($key, 0, $size);
52 }
53
54 return $key . str_repeat("\0", ($size - $keyLength));
55 }
56
57 /**
58 * Returns null bytes to append to the string so that it's zero padded to the specified block size
59 *
60 * @param string $string The binary string which will be zero padded
61 * @param int $blockSize The block size
62 *
63 * @return string The zero bytes to append to the string to zero pad it to $blockSize
64 */
65 protected function getZeroPadding($string, $blockSize)
66 {
67 $stringSize = strlen($string);
68
69 if (function_exists('mb_strlen'))
70 {
71 $stringSize = mb_strlen($string, 'ASCII');
72 }
73
74 if ($stringSize == $blockSize)
75 {
76 return '';
77 }
78
79 if ($stringSize < $blockSize)
80 {
81 return str_repeat("\0", $blockSize - $stringSize);
82 }
83
84 $paddingBytes = $stringSize % $blockSize;
85
86 return str_repeat("\0", $blockSize - $paddingBytes);
87 }
88 }