Passed
Pull Request — develop (#53)
by Peter
03:13
created
library/tiqr/Tiqr/OATH/OCRA.php 2 patches
Spacing   +75 added lines, -75 removed lines patch added patch discarded remove patch
@@ -58,18 +58,18 @@  discard block
 block discarded – undo
58 58
     private static function _hexStr2Bytes(string $hex, int $maxBytes, string $parameterName) : string
59 59
     {
60 60
         $len = strlen($hex);
61
-        if ( ($len !== 0) && (! ctype_xdigit($hex)) ) {
61
+        if (($len !== 0) && (!ctype_xdigit($hex))) {
62 62
             throw new InvalidArgumentException("Parameter '$parameterName' contains non hex digits");
63 63
         }
64
-        if ( $len % 2 !== 0 ) {
64
+        if ($len % 2 !== 0) {
65 65
             throw new InvalidArgumentException("Parameter '$parameterName' contains odd number of hex digits");
66 66
         }
67
-        if ( $len > $maxBytes * 2) {
67
+        if ($len > $maxBytes * 2) {
68 68
             throw new InvalidArgumentException("Parameter '$parameterName' too long");
69 69
         }
70 70
         // hex2bin logs PHP warnings when $hex contains invalid characters or has uneven length. Because we
71 71
         // check for these conditions above hex2bin() should always be silent
72
-        $res=hex2bin($hex);
72
+        $res = hex2bin($hex);
73 73
         if (false === $res) {
74 74
             throw new InvalidArgumentException("Parameter '$parameterName' could not be decoded");
75 75
         }
@@ -125,83 +125,83 @@  discard block
 block discarded – undo
125 125
         $cryptoFunction = $components[1];
126 126
         $dataInput = strtolower($components[2]); // lower here so we can do case insensitive comparisons
127 127
 
128
-        if(stripos($cryptoFunction, "hotp-sha1")!==false)
128
+        if (stripos($cryptoFunction, "hotp-sha1") !== false)
129 129
             $crypto = "sha1";
130
-        elseif(stripos($cryptoFunction, "hotp-sha256")!==false)
130
+        elseif (stripos($cryptoFunction, "hotp-sha256") !== false)
131 131
             $crypto = "sha256";
132
-        elseif(stripos($cryptoFunction, "hotp-sha512")!==false)
132
+        elseif (stripos($cryptoFunction, "hotp-sha512") !== false)
133 133
             $crypto = "sha512";
134 134
         else {
135 135
             throw new InvalidArgumentException('Unsupported OCRA CryptoFunction');
136 136
         }
137 137
 
138 138
         // The Cryptofucntion must ha a truncation of 0, 4-10
139
-        $codeDigits_str = substr($cryptoFunction, strrpos($cryptoFunction, "-")+1);
140
-        if (! ctype_digit($codeDigits_str)) {
139
+        $codeDigits_str = substr($cryptoFunction, strrpos($cryptoFunction, "-") + 1);
140
+        if (!ctype_digit($codeDigits_str)) {
141 141
             throw new InvalidArgumentException('Unsupported OCRA CryptoFunction');
142 142
         }
143
-        $codeDigits = (integer)$codeDigits_str;
143
+        $codeDigits = (integer) $codeDigits_str;
144 144
         if (($codeDigits != 0) && (($codeDigits < 4) || ($codeDigits > 10))) {
145 145
             throw new InvalidArgumentException('Unsupported OCRA CryptoFunction');
146 146
         }
147 147
                 
148 148
         // The size of the byte array message to be encrypted
149 149
         // Counter
150
-        if($dataInput[0] == "c" ) {
150
+        if ($dataInput[0] == "c") {
151 151
             // Fix the length of the HEX string
152
-            while(strlen($counter) < 16)
153
-                $counter = "0" . $counter;
154
-            $counterLength=8;
152
+            while (strlen($counter) < 16)
153
+                $counter = "0".$counter;
154
+            $counterLength = 8;
155 155
         }
156 156
         // Question
157
-        if($dataInput[0] == "q" ||
158
-                stripos($dataInput, "-q")!==false) {
159
-            while(strlen($question) < 256)
160
-                $question = $question . "0";
161
-            $questionLength=128;
157
+        if ($dataInput[0] == "q" ||
158
+                stripos($dataInput, "-q") !== false) {
159
+            while (strlen($question) < 256)
160
+                $question = $question."0";
161
+            $questionLength = 128;
162 162
         }
163 163
 
164 164
         // Password
165
-        if(stripos($dataInput, "psha1")!==false) {
166
-            while(strlen($password) < 40)
167
-                $password = "0" . $password;
168
-            $passwordLength=20;
165
+        if (stripos($dataInput, "psha1") !== false) {
166
+            while (strlen($password) < 40)
167
+                $password = "0".$password;
168
+            $passwordLength = 20;
169 169
         }
170 170
     
171
-        if(stripos($dataInput, "psha256")!==false) {
172
-            while(strlen($password) < 64)
173
-                $password = "0" . $password;
174
-            $passwordLength=32;
171
+        if (stripos($dataInput, "psha256") !== false) {
172
+            while (strlen($password) < 64)
173
+                $password = "0".$password;
174
+            $passwordLength = 32;
175 175
         }
176 176
         
177
-        if(stripos($dataInput, "psha512")!==false) {
178
-            while(strlen($password) < 128)
179
-                $password = "0" . $password;
180
-            $passwordLength=64;
177
+        if (stripos($dataInput, "psha512") !== false) {
178
+            while (strlen($password) < 128)
179
+                $password = "0".$password;
180
+            $passwordLength = 64;
181 181
         }
182 182
         
183 183
         // sessionInformation
184
-        if(stripos($dataInput, "s064") !==false) {
185
-            while(strlen($sessionInformation) < 128)
186
-                $sessionInformation = "0" . $sessionInformation;
184
+        if (stripos($dataInput, "s064") !== false) {
185
+            while (strlen($sessionInformation) < 128)
186
+                $sessionInformation = "0".$sessionInformation;
187 187
 
188
-            $sessionInformationLength=64;
189
-        } else if(stripos($dataInput, "s128") !==false) {
190
-            while(strlen($sessionInformation) < 256)
191
-                $sessionInformation = "0" . $sessionInformation;
188
+            $sessionInformationLength = 64;
189
+        } else if (stripos($dataInput, "s128") !== false) {
190
+            while (strlen($sessionInformation) < 256)
191
+                $sessionInformation = "0".$sessionInformation;
192 192
         
193
-            $sessionInformationLength=128;
194
-        } else if(stripos($dataInput, "s256") !==false) {
195
-            while(strlen($sessionInformation) < 512)
196
-                $sessionInformation = "0" . $sessionInformation;
193
+            $sessionInformationLength = 128;
194
+        } else if (stripos($dataInput, "s256") !== false) {
195
+            while (strlen($sessionInformation) < 512)
196
+                $sessionInformation = "0".$sessionInformation;
197 197
         
198
-            $sessionInformationLength=256;
199
-        } else if(stripos($dataInput, "s512") !==false) {
200
-            while(strlen($sessionInformation) < 128)
201
-                $sessionInformation = "0" . $sessionInformation;
198
+            $sessionInformationLength = 256;
199
+        } else if (stripos($dataInput, "s512") !== false) {
200
+            while (strlen($sessionInformation) < 128)
201
+                $sessionInformation = "0".$sessionInformation;
202 202
         
203
-            $sessionInformationLength=64;
204
-        } else if (stripos($dataInput, "-s") !== false ) {
203
+            $sessionInformationLength = 64;
204
+        } else if (stripos($dataInput, "-s") !== false) {
205 205
             // deviation from spec. Officially 's' without a length indicator is not in the reference implementation.
206 206
             // RFC is ambigious. However we have supported this in Tiqr since day 1, so we continue to support it.
207 207
 
@@ -210,27 +210,27 @@  discard block
 block discarded – undo
210 210
             // to prevent matching the "s" in the password input e.g. "psha1".
211 211
             // [C] | QFxx | [PH | Snnn | TG] : Challenge-Response computation
212 212
             // [C] | QFxx | [PH | TG] : Plain Signature computation
213
-            while(strlen($sessionInformation) < 128)
214
-                $sessionInformation = "0" . $sessionInformation;
213
+            while (strlen($sessionInformation) < 128)
214
+                $sessionInformation = "0".$sessionInformation;
215 215
             
216
-            $sessionInformationLength=64;
216
+            $sessionInformationLength = 64;
217 217
         }
218 218
         
219 219
         
220 220
              
221 221
         // TimeStamp
222
-        if($dataInput[0] == "t" ||
222
+        if ($dataInput[0] == "t" ||
223 223
                 stripos($dataInput, "-t") !== false) {
224
-            while(strlen($timeStamp) < 16)
225
-                $timeStamp = "0" . $timeStamp;
226
-            $timeStampLength=8;
224
+            while (strlen($timeStamp) < 16)
225
+                $timeStamp = "0".$timeStamp;
226
+            $timeStampLength = 8;
227 227
         }
228 228
 
229 229
         // Put the bytes of "ocraSuite" parameters into the message
230 230
         
231
-        $msg = array_fill(0,$ocraSuiteLength+$counterLength+$questionLength+$passwordLength+$sessionInformationLength+$timeStampLength+1, 0);
231
+        $msg = array_fill(0, $ocraSuiteLength + $counterLength + $questionLength + $passwordLength + $sessionInformationLength + $timeStampLength + 1, 0);
232 232
                 
233
-        for($i=0;$i<strlen($ocraSuite);$i++) {
233
+        for ($i = 0; $i < strlen($ocraSuite); $i++) {
234 234
             $msg[$i] = $ocraSuite[$i];
235 235
         }
236 236
         
@@ -239,9 +239,9 @@  discard block
 block discarded – undo
239 239
 
240 240
         // Put the bytes of "Counter" to the message
241 241
         // Input is HEX encoded
242
-        if($counterLength > 0 ) {
242
+        if ($counterLength > 0) {
243 243
             $bArray = self::_hexStr2Bytes($counter, $counterLength, 'counter');
244
-            for ($i=0;$i<strlen($bArray);$i++) {
244
+            for ($i = 0; $i < strlen($bArray); $i++) {
245 245
                 $msg [$i + $ocraSuiteLength + 1] = $bArray[$i];
246 246
             }
247 247
         }
@@ -249,41 +249,41 @@  discard block
 block discarded – undo
249 249
 
250 250
         // Put the bytes of "question" to the message
251 251
         // Input is text encoded
252
-        if($questionLength > 0 ) {
252
+        if ($questionLength > 0) {
253 253
             $bArray = self::_hexStr2Bytes($question, $questionLength, 'question');
254
-            for ($i=0;$i<strlen($bArray);$i++) {
254
+            for ($i = 0; $i < strlen($bArray); $i++) {
255 255
                 $msg [$i + $ocraSuiteLength + 1 + $counterLength] = $bArray[$i];
256 256
             }
257 257
         }
258 258
 
259 259
         // Put the bytes of "password" to the message
260 260
         // Input is HEX encoded
261
-        if($passwordLength > 0){
261
+        if ($passwordLength > 0) {
262 262
             $bArray = self::_hexStr2Bytes($password, $passwordLength, 'password');
263
-            for ($i=0;$i<strlen($bArray);$i++) {
263
+            for ($i = 0; $i < strlen($bArray); $i++) {
264 264
                 $msg [$i + $ocraSuiteLength + 1 + $counterLength + $questionLength] = $bArray[$i];
265 265
             }
266 266
         }
267 267
 
268 268
         // Put the bytes of "sessionInformation" to the message
269 269
         // Input is HEX encoded
270
-        if($sessionInformationLength > 0 ){
270
+        if ($sessionInformationLength > 0) {
271 271
             $bArray = self::_hexStr2Bytes($sessionInformation, $sessionInformationLength, 'sessionInformation');
272
-            for ($i=0;$i<strlen($bArray);$i++) {
272
+            for ($i = 0; $i < strlen($bArray); $i++) {
273 273
                 $msg [$i + $ocraSuiteLength + 1 + $counterLength + $questionLength + $passwordLength] = $bArray[$i];
274 274
             }
275 275
         }
276 276
 
277 277
         // Put the bytes of "time" to the message
278 278
         // Input is HEX encoded value of minutes
279
-        if($timeStampLength > 0){
279
+        if ($timeStampLength > 0) {
280 280
             $bArray = self::_hexStr2Bytes($timeStamp, $timeStampLength, 'timeStamp');
281
-            for ($i=0;$i<strlen($bArray);$i++) {
281
+            for ($i = 0; $i < strlen($bArray); $i++) {
282 282
                 $msg [$i + $ocraSuiteLength + 1 + $counterLength + $questionLength + $passwordLength + $sessionInformationLength] = $bArray[$i];
283 283
             }
284 284
         }
285 285
         
286
-        $byteKey = self::_hexStr2Bytes($key, strlen($key)/2, 'key');
286
+        $byteKey = self::_hexStr2Bytes($key, strlen($key) / 2, 'key');
287 287
               
288 288
         $msg = implode("", $msg);
289 289
 
@@ -308,23 +308,23 @@  discard block
 block discarded – undo
308 308
     static function _oath_truncate(string $hash, int $length = 6) : string
309 309
     {
310 310
         // Convert to dec
311
-        foreach(str_split($hash,2) as $hex)
311
+        foreach (str_split($hash, 2) as $hex)
312 312
         {
313
-            $hmac_result[]=hexdec($hex);
313
+            $hmac_result[] = hexdec($hex);
314 314
         }
315 315
     
316 316
         // Find offset
317 317
         $offset = $hmac_result[count($hmac_result) - 1] & 0xf;
318 318
     
319 319
         $v = strval(
320
-            (($hmac_result[$offset+0] & 0x7f) << 24 ) |
321
-            (($hmac_result[$offset+1] & 0xff) << 16 ) |
322
-            (($hmac_result[$offset+2] & 0xff) << 8 ) |
323
-            ($hmac_result[$offset+3] & 0xff)
320
+            (($hmac_result[$offset + 0] & 0x7f) << 24) |
321
+            (($hmac_result[$offset + 1] & 0xff) << 16) |
322
+            (($hmac_result[$offset + 2] & 0xff) << 8) |
323
+            ($hmac_result[$offset + 3] & 0xff)
324 324
         );
325 325
 
326 326
         // Prefix truncated string with 0's to ensure it always has the required length
327
-        $v=str_pad($v, $length, "0", STR_PAD_LEFT);
327
+        $v = str_pad($v, $length, "0", STR_PAD_LEFT);
328 328
 
329 329
         $v = substr($v, strlen($v) - $length);
330 330
         return $v;
Please login to merge, or discard this patch.
Braces   +45 added lines, -33 removed lines patch added patch discarded remove patch
@@ -125,13 +125,13 @@  discard block
 block discarded – undo
125 125
         $cryptoFunction = $components[1];
126 126
         $dataInput = strtolower($components[2]); // lower here so we can do case insensitive comparisons
127 127
 
128
-        if(stripos($cryptoFunction, "hotp-sha1")!==false)
129
-            $crypto = "sha1";
130
-        elseif(stripos($cryptoFunction, "hotp-sha256")!==false)
131
-            $crypto = "sha256";
132
-        elseif(stripos($cryptoFunction, "hotp-sha512")!==false)
133
-            $crypto = "sha512";
134
-        else {
128
+        if(stripos($cryptoFunction, "hotp-sha1")!==false) {
129
+                    $crypto = "sha1";
130
+        } elseif(stripos($cryptoFunction, "hotp-sha256")!==false) {
131
+                    $crypto = "sha256";
132
+        } elseif(stripos($cryptoFunction, "hotp-sha512")!==false) {
133
+                    $crypto = "sha512";
134
+        } else {
135 135
             throw new InvalidArgumentException('Unsupported OCRA CryptoFunction');
136 136
         }
137 137
 
@@ -149,56 +149,65 @@  discard block
 block discarded – undo
149 149
         // Counter
150 150
         if($dataInput[0] == "c" ) {
151 151
             // Fix the length of the HEX string
152
-            while(strlen($counter) < 16)
153
-                $counter = "0" . $counter;
152
+            while(strlen($counter) < 16) {
153
+                            $counter = "0" . $counter;
154
+            }
154 155
             $counterLength=8;
155 156
         }
156 157
         // Question
157 158
         if($dataInput[0] == "q" ||
158 159
                 stripos($dataInput, "-q")!==false) {
159
-            while(strlen($question) < 256)
160
-                $question = $question . "0";
160
+            while(strlen($question) < 256) {
161
+                            $question = $question . "0";
162
+            }
161 163
             $questionLength=128;
162 164
         }
163 165
 
164 166
         // Password
165 167
         if(stripos($dataInput, "psha1")!==false) {
166
-            while(strlen($password) < 40)
167
-                $password = "0" . $password;
168
+            while(strlen($password) < 40) {
169
+                            $password = "0" . $password;
170
+            }
168 171
             $passwordLength=20;
169 172
         }
170 173
     
171 174
         if(stripos($dataInput, "psha256")!==false) {
172
-            while(strlen($password) < 64)
173
-                $password = "0" . $password;
175
+            while(strlen($password) < 64) {
176
+                            $password = "0" . $password;
177
+            }
174 178
             $passwordLength=32;
175 179
         }
176 180
         
177 181
         if(stripos($dataInput, "psha512")!==false) {
178
-            while(strlen($password) < 128)
179
-                $password = "0" . $password;
182
+            while(strlen($password) < 128) {
183
+                            $password = "0" . $password;
184
+            }
180 185
             $passwordLength=64;
181 186
         }
182 187
         
183 188
         // sessionInformation
184 189
         if(stripos($dataInput, "s064") !==false) {
185
-            while(strlen($sessionInformation) < 128)
186
-                $sessionInformation = "0" . $sessionInformation;
190
+            while(strlen($sessionInformation) < 128) {
191
+                            $sessionInformation = "0" . $sessionInformation;
192
+            }
187 193
 
188 194
             $sessionInformationLength=64;
189 195
         } else if(stripos($dataInput, "s128") !==false) {
190
-            while(strlen($sessionInformation) < 256)
191
-                $sessionInformation = "0" . $sessionInformation;
196
+            while(strlen($sessionInformation) < 256) {
197
+                            $sessionInformation = "0" . $sessionInformation;
198
+            }
192 199
         
193 200
             $sessionInformationLength=128;
194 201
         } else if(stripos($dataInput, "s256") !==false) {
195
-            while(strlen($sessionInformation) < 512)
196
-                $sessionInformation = "0" . $sessionInformation;
202
+            while(strlen($sessionInformation) < 512) {
203
+                            $sessionInformation = "0" . $sessionInformation;
204
+            }
197 205
         
198 206
             $sessionInformationLength=256;
199 207
         } else if(stripos($dataInput, "s512") !==false) {
200
-            while(strlen($sessionInformation) < 128)
201
-                $sessionInformation = "0" . $sessionInformation;
208
+            while(strlen($sessionInformation) < 128) {
209
+                            $sessionInformation = "0" . $sessionInformation;
210
+            }
202 211
         
203 212
             $sessionInformationLength=64;
204 213
         } else if (stripos($dataInput, "-s") !== false ) {
@@ -210,8 +219,9 @@  discard block
 block discarded – undo
210 219
             // to prevent matching the "s" in the password input e.g. "psha1".
211 220
             // [C] | QFxx | [PH | Snnn | TG] : Challenge-Response computation
212 221
             // [C] | QFxx | [PH | TG] : Plain Signature computation
213
-            while(strlen($sessionInformation) < 128)
214
-                $sessionInformation = "0" . $sessionInformation;
222
+            while(strlen($sessionInformation) < 128) {
223
+                            $sessionInformation = "0" . $sessionInformation;
224
+            }
215 225
             
216 226
             $sessionInformationLength=64;
217 227
         }
@@ -221,8 +231,9 @@  discard block
 block discarded – undo
221 231
         // TimeStamp
222 232
         if($dataInput[0] == "t" ||
223 233
                 stripos($dataInput, "-t") !== false) {
224
-            while(strlen($timeStamp) < 16)
225
-                $timeStamp = "0" . $timeStamp;
234
+            while(strlen($timeStamp) < 16) {
235
+                            $timeStamp = "0" . $timeStamp;
236
+            }
226 237
             $timeStampLength=8;
227 238
         }
228 239
 
@@ -289,10 +300,11 @@  discard block
 block discarded – undo
289 300
 
290 301
         $hash = self::_hmac($crypto, $byteKey, $msg);
291 302
 
292
-        if ($codeDigits == 0)
293
-            $result = $hash;
294
-        else
295
-            $result = self::_oath_truncate($hash, $codeDigits);
303
+        if ($codeDigits == 0) {
304
+                    $result = $hash;
305
+        } else {
306
+                    $result = self::_oath_truncate($hash, $codeDigits);
307
+        }
296 308
              
297 309
         return $result;
298 310
     }
Please login to merge, or discard this patch.
library/tiqr/Tiqr/OATH/OCRAParser.php 1 patch
Indentation   +201 added lines, -201 removed lines patch added patch discarded remove patch
@@ -2,32 +2,32 @@  discard block
 block discarded – undo
2 2
 
3 3
 class OATH_OCRAParser {
4 4
 
5
-	private $OCRASuite = NULL;
5
+    private $OCRASuite = NULL;
6 6
 
7
-	private $OCRAVersion = NULL;
7
+    private $OCRAVersion = NULL;
8 8
 
9
-	private $CryptoFunctionType = NULL;
10
-	private $CryptoFunctionHash = NULL;
11
-	private $CryptoFunctionHashLength = NULL;
12
-	private $CryptoFunctionTruncation = NULL;
9
+    private $CryptoFunctionType = NULL;
10
+    private $CryptoFunctionHash = NULL;
11
+    private $CryptoFunctionHashLength = NULL;
12
+    private $CryptoFunctionTruncation = NULL;
13 13
 
14
-	private $C = FALSE;
15
-	private $Q = FALSE;
16
-	private $QType = 'N';
17
-	private $QLength = 8;
14
+    private $C = FALSE;
15
+    private $Q = FALSE;
16
+    private $QType = 'N';
17
+    private $QLength = 8;
18 18
 
19
-	private $P = FALSE;
20
-	private $PType = 'SHA1';
21
-	private $PLength = 20;
19
+    private $P = FALSE;
20
+    private $PType = 'SHA1';
21
+    private $PLength = 20;
22 22
 
23
-	private $S = FALSE;
24
-	private $SLength = 64;
23
+    private $S = FALSE;
24
+    private $SLength = 64;
25 25
 
26
-	private $T = FALSE;
27
-	private $TLength = 60; // 1M
28
-	private $TPeriods = array('H' => 3600, 'M' => 60, 'S' => 1);
26
+    private $T = FALSE;
27
+    private $TLength = 60; // 1M
28
+    private $TPeriods = array('H' => 3600, 'M' => 60, 'S' => 1);
29 29
 
30
-	private $supportedHashFunctions = array('SHA1' => 20, 'SHA256' => 32, 'SHA512' => 64);
30
+    private $supportedHashFunctions = array('SHA1' => 20, 'SHA256' => 32, 'SHA512' => 64);
31 31
 
32 32
 
33 33
     /**
@@ -35,149 +35,149 @@  discard block
 block discarded – undo
35 35
      * @throws Exception
36 36
      */
37 37
     public function __construct(String $ocraSuite) {
38
-		$this->parseOCRASuite($ocraSuite);
39
-	}
38
+        $this->parseOCRASuite($ocraSuite);
39
+    }
40 40
 
41
-	/**
42
-	 * Inspired by https://github.com/bdauvergne/python-oath
41
+    /**
42
+     * Inspired by https://github.com/bdauvergne/python-oath
43 43
      *
44 44
      * @throws Exception
45
-	 */
46
-	private function parseOCRASuite($ocraSuite) {
47
-		if (!is_string($ocraSuite)) {
48
-			throw new Exception('OCRASuite not in string format: ' . var_export($ocraSuite, TRUE));
49
-		}
50
-
51
-		$ocraSuite = strtoupper($ocraSuite);
52
-		$this->OCRASuite = $ocraSuite;
53
-
54
-		$s = explode(':', $ocraSuite);
55
-		if (count($s) != 3) {
56
-			throw new Exception('Invalid OCRASuite format: ' . var_export($ocraSuite, TRUE));
57
-		}
58
-
59
-		$algo = explode('-', $s[0]);
60
-		if (count($algo) != 2) {
61
-			throw new Exception('Invalid OCRA version: ' . var_export($s[0], TRUE));
62
-		}
63
-
64
-		if ($algo[0] !== 'OCRA') {
65
-			throw new Exception('Unsupported OCRA algorithm: ' . var_export($algo[0], TRUE));
66
-		}
67
-
68
-		if ($algo[1] !== '1') {
69
-			throw new Exception('Unsupported OCRA version: ' . var_export($algo[1], TRUE));
70
-		}
71
-		$this->OCRAVersion = $algo[1];
72
-
73
-		$cf = explode('-', $s[1]);
74
-		if (count($cf) != 3) {
75
-			throw new Exception('Invalid OCRA suite crypto function: ' . var_export($s[1], TRUE));
76
-		}
77
-
78
-		if ($cf[0] !== 'HOTP') {
79
-			throw new Exception('Unsupported OCRA suite crypto function: ' . var_export($cf[0], TRUE));
80
-		}
81
-		$this->CryptoFunctionType = $cf[0];
82
-
83
-		if (!array_key_exists($cf[1], $this->supportedHashFunctions)) {
84
-			throw new Exception('Unsupported hash function in OCRA suite crypto function: ' . var_export($cf[1], TRUE));
85
-		}
86
-		$this->CryptoFunctionHash = $cf[1];
87
-		$this->CryptoFunctionHashLength = $this->supportedHashFunctions[$cf[1]];
88
-
89
-		if (!preg_match('/^\d+$/', $cf[2]) || (($cf[2] < 4 || $cf[2] > 10) && $cf[2] != 0)) {
90
-			throw new Exception('Invalid OCRA suite crypto function truncation length: ' . var_export($cf[2], TRUE));
91
-		}
92
-		$this->CryptoFunctionTruncation = intval($cf[2]);
93
-
94
-		$di = explode('-', $s[2]);
95
-		if (count($cf) == 0) {
96
-			throw new Exception('Invalid OCRA suite data input: ' . var_export($s[2], TRUE));
97
-		}
98
-
99
-		$data_input = array();
100
-		foreach($di as $elem) {
101
-			$letter = $elem[0];
102
-			if (array_key_exists($letter, $data_input)) {
103
-				throw new Exception('Duplicate field in OCRA suite data input: ' . var_export($elem, TRUE));
104
-			}
105
-			$data_input[$letter] = 1;
106
-
107
-			if ($letter === 'C' && strlen($elem) == 1) {
108
-				$this->C = TRUE;
109
-			} elseif ($letter === 'Q') {
110
-				if (strlen($elem) == 1) {
111
-					$this->Q = TRUE;
112
-				} elseif (preg_match('/^Q([AHN])(\d+)$/', $elem, $match)) {
113
-					$q_len = intval($match[2]);
114
-					if ($q_len < 4 || $q_len > 64) {
115
-						throw new Exception('Invalid OCRA suite data input question length: ' . var_export($q_len, TRUE));
116
-					}
117
-					$this->Q = TRUE;
118
-					$this->QType = $match[1];
119
-					$this->QLength = $q_len;
120
-				} else {
121
-					throw new Exception('Invalid OCRA suite data input question: ' . var_export($elem, TRUE));
122
-				}
123
-			} elseif ($letter === 'P') {
124
-				if (strlen($elem) == 1) {
125
-					$this->P = TRUE;
126
-				} else {
127
-					$p_algo = substr($elem, 1);
128
-					if (!array_key_exists($p_algo, $this->supportedHashFunctions)) {
129
-						throw new Exception('Unsupported OCRA suite PIN hash function: ' . var_export($elem, TRUE));
130
-					}
131
-					$this->P = TRUE;
132
-					$this->PType = $p_algo;
133
-					$this->PLength = $this->supportedHashFunctions[$p_algo];
134
-				}
135
-			} elseif ($letter === 'S') {
136
-				if (strlen($elem) == 1) {
137
-					$this->S = TRUE;
138
-				} elseif (preg_match('/^S(\d+)$/', $elem, $match)) {
139
-					$s_len = intval($match[1]);
140
-					if ($s_len <= 0 || $s_len > 512) {
141
-						throw new Exception('Invalid OCRA suite data input session information length: ' . var_export($s_len, TRUE));
142
-					}
143
-
144
-					$this->S = TRUE;
145
-					$this->SLength = $s_len;
146
-				} else {
147
-					throw new Exception('Invalid OCRA suite data input session information length: ' . var_export($elem, TRUE));
148
-				}
149
-			} elseif ($letter === 'T') {
150
-				if (strlen($elem) == 1) {
151
-					$this->T = TRUE;
152
-				} elseif (preg_match('/^T(\d+[HMS])+$/', $elem)) {
153
-					preg_match_all('/(\d+)([HMS])/', $elem, $match);
154
-
155
-					if (count($match[1]) !== count(array_unique($match[2]))) {
156
-						throw new Exception('Duplicate definitions in OCRA suite data input timestamp: ' . var_export($elem, TRUE));
157
-					}
158
-
159
-					$length = 0;
160
-					for ($i = 0; $i < count($match[1]); $i++) {
161
-						$length += intval($match[1][$i]) * $this->TPeriods[$match[2][$i]];
162
-					}
163
-					if ($length <= 0) {
164
-						throw new Exception('Invalid OCRA suite data input timestamp: ' . var_export($elem, TRUE));
165
-					}
166
-
167
-					$this->T = TRUE;
168
-					$this->TLength = $length;
169
-				} else {
170
-					throw new Exception('Invalid OCRA suite data input timestamp: ' . var_export($elem, TRUE));
171
-				}
172
-			} else {
173
-				throw new Exception('Unsupported OCRA suite data input field: ' . var_export($elem, TRUE));
174
-			}
175
-		}
176
-
177
-		if (!$this->Q) {
178
-			throw new Exception('OCRA suite data input question not defined: ' . var_export($s[2], TRUE));
179
-		}
180
-	}
45
+     */
46
+    private function parseOCRASuite($ocraSuite) {
47
+        if (!is_string($ocraSuite)) {
48
+            throw new Exception('OCRASuite not in string format: ' . var_export($ocraSuite, TRUE));
49
+        }
50
+
51
+        $ocraSuite = strtoupper($ocraSuite);
52
+        $this->OCRASuite = $ocraSuite;
53
+
54
+        $s = explode(':', $ocraSuite);
55
+        if (count($s) != 3) {
56
+            throw new Exception('Invalid OCRASuite format: ' . var_export($ocraSuite, TRUE));
57
+        }
58
+
59
+        $algo = explode('-', $s[0]);
60
+        if (count($algo) != 2) {
61
+            throw new Exception('Invalid OCRA version: ' . var_export($s[0], TRUE));
62
+        }
63
+
64
+        if ($algo[0] !== 'OCRA') {
65
+            throw new Exception('Unsupported OCRA algorithm: ' . var_export($algo[0], TRUE));
66
+        }
67
+
68
+        if ($algo[1] !== '1') {
69
+            throw new Exception('Unsupported OCRA version: ' . var_export($algo[1], TRUE));
70
+        }
71
+        $this->OCRAVersion = $algo[1];
72
+
73
+        $cf = explode('-', $s[1]);
74
+        if (count($cf) != 3) {
75
+            throw new Exception('Invalid OCRA suite crypto function: ' . var_export($s[1], TRUE));
76
+        }
77
+
78
+        if ($cf[0] !== 'HOTP') {
79
+            throw new Exception('Unsupported OCRA suite crypto function: ' . var_export($cf[0], TRUE));
80
+        }
81
+        $this->CryptoFunctionType = $cf[0];
82
+
83
+        if (!array_key_exists($cf[1], $this->supportedHashFunctions)) {
84
+            throw new Exception('Unsupported hash function in OCRA suite crypto function: ' . var_export($cf[1], TRUE));
85
+        }
86
+        $this->CryptoFunctionHash = $cf[1];
87
+        $this->CryptoFunctionHashLength = $this->supportedHashFunctions[$cf[1]];
88
+
89
+        if (!preg_match('/^\d+$/', $cf[2]) || (($cf[2] < 4 || $cf[2] > 10) && $cf[2] != 0)) {
90
+            throw new Exception('Invalid OCRA suite crypto function truncation length: ' . var_export($cf[2], TRUE));
91
+        }
92
+        $this->CryptoFunctionTruncation = intval($cf[2]);
93
+
94
+        $di = explode('-', $s[2]);
95
+        if (count($cf) == 0) {
96
+            throw new Exception('Invalid OCRA suite data input: ' . var_export($s[2], TRUE));
97
+        }
98
+
99
+        $data_input = array();
100
+        foreach($di as $elem) {
101
+            $letter = $elem[0];
102
+            if (array_key_exists($letter, $data_input)) {
103
+                throw new Exception('Duplicate field in OCRA suite data input: ' . var_export($elem, TRUE));
104
+            }
105
+            $data_input[$letter] = 1;
106
+
107
+            if ($letter === 'C' && strlen($elem) == 1) {
108
+                $this->C = TRUE;
109
+            } elseif ($letter === 'Q') {
110
+                if (strlen($elem) == 1) {
111
+                    $this->Q = TRUE;
112
+                } elseif (preg_match('/^Q([AHN])(\d+)$/', $elem, $match)) {
113
+                    $q_len = intval($match[2]);
114
+                    if ($q_len < 4 || $q_len > 64) {
115
+                        throw new Exception('Invalid OCRA suite data input question length: ' . var_export($q_len, TRUE));
116
+                    }
117
+                    $this->Q = TRUE;
118
+                    $this->QType = $match[1];
119
+                    $this->QLength = $q_len;
120
+                } else {
121
+                    throw new Exception('Invalid OCRA suite data input question: ' . var_export($elem, TRUE));
122
+                }
123
+            } elseif ($letter === 'P') {
124
+                if (strlen($elem) == 1) {
125
+                    $this->P = TRUE;
126
+                } else {
127
+                    $p_algo = substr($elem, 1);
128
+                    if (!array_key_exists($p_algo, $this->supportedHashFunctions)) {
129
+                        throw new Exception('Unsupported OCRA suite PIN hash function: ' . var_export($elem, TRUE));
130
+                    }
131
+                    $this->P = TRUE;
132
+                    $this->PType = $p_algo;
133
+                    $this->PLength = $this->supportedHashFunctions[$p_algo];
134
+                }
135
+            } elseif ($letter === 'S') {
136
+                if (strlen($elem) == 1) {
137
+                    $this->S = TRUE;
138
+                } elseif (preg_match('/^S(\d+)$/', $elem, $match)) {
139
+                    $s_len = intval($match[1]);
140
+                    if ($s_len <= 0 || $s_len > 512) {
141
+                        throw new Exception('Invalid OCRA suite data input session information length: ' . var_export($s_len, TRUE));
142
+                    }
143
+
144
+                    $this->S = TRUE;
145
+                    $this->SLength = $s_len;
146
+                } else {
147
+                    throw new Exception('Invalid OCRA suite data input session information length: ' . var_export($elem, TRUE));
148
+                }
149
+            } elseif ($letter === 'T') {
150
+                if (strlen($elem) == 1) {
151
+                    $this->T = TRUE;
152
+                } elseif (preg_match('/^T(\d+[HMS])+$/', $elem)) {
153
+                    preg_match_all('/(\d+)([HMS])/', $elem, $match);
154
+
155
+                    if (count($match[1]) !== count(array_unique($match[2]))) {
156
+                        throw new Exception('Duplicate definitions in OCRA suite data input timestamp: ' . var_export($elem, TRUE));
157
+                    }
158
+
159
+                    $length = 0;
160
+                    for ($i = 0; $i < count($match[1]); $i++) {
161
+                        $length += intval($match[1][$i]) * $this->TPeriods[$match[2][$i]];
162
+                    }
163
+                    if ($length <= 0) {
164
+                        throw new Exception('Invalid OCRA suite data input timestamp: ' . var_export($elem, TRUE));
165
+                    }
166
+
167
+                    $this->T = TRUE;
168
+                    $this->TLength = $length;
169
+                } else {
170
+                    throw new Exception('Invalid OCRA suite data input timestamp: ' . var_export($elem, TRUE));
171
+                }
172
+            } else {
173
+                throw new Exception('Unsupported OCRA suite data input field: ' . var_export($elem, TRUE));
174
+            }
175
+        }
176
+
177
+        if (!$this->Q) {
178
+            throw new Exception('OCRA suite data input question not defined: ' . var_export($s[2], TRUE));
179
+        }
180
+    }
181 181
 
182 182
     /** Generate an OCRA challenge question according to the ocra suite specified in the constructor
183 183
      * @return String: The randomly generated OCRA question
@@ -190,50 +190,50 @@  discard block
 block discarded – undo
190 190
      * Note that the question string is the exact question string a specified in the OCRA strandard (RFC 6287)
191 191
      * The challenge is not yet hex encoded as expected by OCRA::generateOCRA()
192 192
      */
193
-	public function generateChallenge() : String {
194
-		$q_length = $this->QLength;
195
-		$q_type = $this->QType;
193
+    public function generateChallenge() : String {
194
+        $q_length = $this->QLength;
195
+        $q_type = $this->QType;
196 196
 
197 197
         $bytes = Tiqr_Random::randomBytes($q_length);
198 198
 
199
-		switch($q_type) {
200
-			case 'A':
201
-				$challenge = base64_encode($bytes);
202
-				$tr = implode("", unpack('H*', $bytes));
203
-				$challenge = rtrim(strtr($challenge, '+/', $tr), '=');
204
-				break;
205
-			case 'H':
206
-				$challenge = implode("", unpack('H*', $bytes));
207
-				break;
208
-			case 'N':
209
-				$challenge = implode("", unpack('N*', $bytes));
210
-				break;
211
-			default:
212
-				throw new Exception('Unsupported OCRASuite challenge type: ' . var_export($q_type, TRUE));
213
-				break;
214
-		}
215
-
216
-		$challenge = substr($challenge, 0, $q_length);
217
-
218
-		return $challenge;
219
-	}
220
-
221
-
222
-	/**
223
-	 * Constant time string comparison, see http://codahale.com/a-lesson-in-timing-attacks/
224
-	 */
225
-	public static function constEqual(string $s1, string $s2): bool {
226
-		if (strlen($s1) != strlen($s2)) {
227
-			return FALSE;
228
-		}
229
-
230
-		$result = TRUE;
231
-		$length = strlen($s1);
232
-		for ($i = 0; $i < $length; $i++) {
233
-			$result &= ($s1[$i] == $s2[$i]);
234
-		}
235
-
236
-		return (boolean)$result;
237
-	}
199
+        switch($q_type) {
200
+            case 'A':
201
+                $challenge = base64_encode($bytes);
202
+                $tr = implode("", unpack('H*', $bytes));
203
+                $challenge = rtrim(strtr($challenge, '+/', $tr), '=');
204
+                break;
205
+            case 'H':
206
+                $challenge = implode("", unpack('H*', $bytes));
207
+                break;
208
+            case 'N':
209
+                $challenge = implode("", unpack('N*', $bytes));
210
+                break;
211
+            default:
212
+                throw new Exception('Unsupported OCRASuite challenge type: ' . var_export($q_type, TRUE));
213
+                break;
214
+        }
215
+
216
+        $challenge = substr($challenge, 0, $q_length);
217
+
218
+        return $challenge;
219
+    }
220
+
221
+
222
+    /**
223
+     * Constant time string comparison, see http://codahale.com/a-lesson-in-timing-attacks/
224
+     */
225
+    public static function constEqual(string $s1, string $s2): bool {
226
+        if (strlen($s1) != strlen($s2)) {
227
+            return FALSE;
228
+        }
229
+
230
+        $result = TRUE;
231
+        $length = strlen($s1);
232
+        for ($i = 0; $i < $length; $i++) {
233
+            $result &= ($s1[$i] == $s2[$i]);
234
+        }
235
+
236
+        return (boolean)$result;
237
+    }
238 238
 
239 239
 }
Please login to merge, or discard this patch.
library/tiqr/Tiqr/Message/APNS2.php 1 patch
Spacing   +19 added lines, -19 removed lines patch added patch discarded remove patch
@@ -20,11 +20,11 @@  discard block
 block discarded – undo
20 20
         $options = $this->getOptions();
21 21
         if (isset($options['apns.proxy_host_url'])) {
22 22
             // Override CURL options to connect to a HTTP/1.1 to HTTP/2 proxy
23
-            $curl_options[CURLOPT_URL] = $options['apns.proxy_host_url'] . '/3/device/' . $this->getAddress();
23
+            $curl_options[CURLOPT_URL] = $options['apns.proxy_host_url'].'/3/device/'.$this->getAddress();
24 24
             $curl_options[CURLOPT_PORT] = $options['apns.proxy_host_port'] ?? 443;
25 25
             // Use HTTP/1.1 instead of HTTP/2
26 26
             $curl_options[CURLOPT_HTTP_VERSION] = CURL_HTTP_VERSION_1_1;
27
-            $this->logger->notice(sprintf('Using HTTP/1.1 CURL Proxy URL: "%s" and port "%s"',  $curl_options[CURLOPT_URL], $curl_options[CURLOPT_URL]));
27
+            $this->logger->notice(sprintf('Using HTTP/1.1 CURL Proxy URL: "%s" and port "%s"', $curl_options[CURLOPT_URL], $curl_options[CURLOPT_URL]));
28 28
         }
29 29
         else {
30 30
             $version_info = curl_version();
@@ -35,7 +35,7 @@  discard block
 block discarded – undo
35 35
 
36 36
         // Get the UID from the client certificate we use for authentication, this
37 37
         // is set to the bundle ID.
38
-        $options=$this->getOptions();
38
+        $options = $this->getOptions();
39 39
         $cert_filename = $options['apns.certificate'];
40 40
         if (strlen($cert_filename) == 0) {
41 41
             throw new RuntimeException('apns.certificate option not set');
@@ -47,7 +47,7 @@  discard block
 block discarded – undo
47 47
             );
48 48
         }
49 49
 
50
-        $cert=openssl_x509_parse( $cert_file_contents );
50
+        $cert = openssl_x509_parse($cert_file_contents);
51 51
         if (false === $cert) {
52 52
             throw new RuntimeException('Error parsing APNS client certificate');
53 53
         }
@@ -72,42 +72,42 @@  discard block
 block discarded – undo
72 72
         $authProvider = AuthProvider\Certificate::create($authProviderOptions);
73 73
 
74 74
         // Create the push message
75
-        $alert=Alert::create();
75
+        $alert = Alert::create();
76 76
         $alert->setBody($this->getText());
77 77
         // Note: It is possible to specify a title and a subtitle: $alert->setTitle() && $alert->setSubtitle()
78 78
         //       The tiqr service currently does not implement this.
79
-        $payload=Payload::create()->setAlert($alert);
79
+        $payload = Payload::create()->setAlert($alert);
80 80
         $payload->setSound('default');
81 81
         foreach ($this->getCustomProperties() as $name => $value) {
82 82
             $payload->setCustomValue($name, $value);
83 83
         }
84 84
         $this->logger->debug(sprintf('JSON Payload: %s', $payload->toJson()));
85
-        $notification=new Notification($payload, $this->getAddress());
85
+        $notification = new Notification($payload, $this->getAddress());
86 86
         // Set expiration to 30 seconds from now, same as Message_APNS
87 87
         $now = new DateTime();
88
-        $expirationInstant=$now->add(new DateInterval('PT30S'));
88
+        $expirationInstant = $now->add(new DateInterval('PT30S'));
89 89
         $notification->setExpirationAt($expirationInstant);
90 90
 
91 91
         // Send the push message
92 92
         $client = new Client($authProvider, $options['apns.environment'] == 'production', $curl_options);
93 93
         $client->addNotification($notification);
94
-        $responses=$client->push();
95
-        if ( sizeof($responses) != 1) {
96
-            $this->logger->warning(sprintf('Unexpected number responses. Expected 1, got %d', sizeof($responses)) );
94
+        $responses = $client->push();
95
+        if (sizeof($responses) != 1) {
96
+            $this->logger->warning(sprintf('Unexpected number responses. Expected 1, got %d', sizeof($responses)));
97 97
             if (sizeof($responses) == 0) {
98 98
                 $this->logger->warning('Could not determine whether the notification was sent');
99 99
                 return;
100 100
             }
101 101
         }
102 102
         /** @var \Pushok\Response $response */
103
-        $response = reset($responses);  // Get first response from the array
104
-        $deviceToken=$response->getDeviceToken() ?? '';
103
+        $response = reset($responses); // Get first response from the array
104
+        $deviceToken = $response->getDeviceToken() ?? '';
105 105
         // A canonical UUID that is the unique ID for the notification. E.g. 123e4567-e89b-12d3-a456-4266554400a0
106
-        $apnsId=$response->getApnsId() ?? '';
106
+        $apnsId = $response->getApnsId() ?? '';
107 107
         // Status code. E.g. 200 (Success), 410 (The device token is no longer active for the topic.)
108
-        $statusCode=$response->getStatusCode();
108
+        $statusCode = $response->getStatusCode();
109 109
         $this->logger->info(sprintf('Got response with ApnsId "%s", status %s for deviceToken "%s"', $apnsId, $statusCode, $deviceToken));
110
-        if ( strcasecmp($deviceToken, $this->getAddress()) ) {
110
+        if (strcasecmp($deviceToken, $this->getAddress())) {
111 111
         $this->logger->warning(sprintf('Unexpected deviceToken in response. Expected: "%s"; got: "%s"', $this->getAddress(), $deviceToken));
112 112
         }
113 113
         if ($statusCode == 200) {
@@ -115,9 +115,9 @@  discard block
 block discarded – undo
115 115
             return;
116 116
         }
117 117
 
118
-        $reasonPhrase=$response->getReasonPhrase(); // E.g. The device token is no longer active for the topic.
119
-        $errorReason=$response->getErrorReason(); // E.g. Unregistered
120
-        $errorDescription=$response->getErrorDescription(); // E.g. The device token is inactive for the specified topic.
118
+        $reasonPhrase = $response->getReasonPhrase(); // E.g. The device token is no longer active for the topic.
119
+        $errorReason = $response->getErrorReason(); // E.g. Unregistered
120
+        $errorDescription = $response->getErrorDescription(); // E.g. The device token is inactive for the specified topic.
121 121
 
122 122
         $this->logger->error(sprintf('Error sending APNS2 push notification. APNS ID: "%s"; deviceToken: "%s"; Error: "%s" "%s" "%s"', $apnsId, $deviceToken, $reasonPhrase, $errorReason, $errorDescription));
123 123
         throw new RuntimeException(
Please login to merge, or discard this patch.