This commit is contained in:
Xes
2025-08-14 22:41:49 +02:00
parent 2de81ccc46
commit 8ce45119b6
39774 changed files with 4309466 additions and 0 deletions

View File

@@ -0,0 +1,7 @@
Copyright (c) 2012 Anthony Ferrara
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

View File

@@ -0,0 +1,20 @@
{
"name": "ircmaxell/password-compat",
"description": "A compatibility library for the proposed simplified password hashing algorithm: https://wiki.php.net/rfc/password_hash",
"keywords": ["password", "hashing"],
"homepage": "https://github.com/ircmaxell/password_compat",
"license": "MIT",
"authors": [
{
"name": "Anthony Ferrara",
"email": "ircmaxell@php.net",
"homepage": "http://blog.ircmaxell.com"
}
],
"require-dev": {
"phpunit/phpunit": "4.*"
},
"autoload": {
"files": ["lib/password.php"]
}
}

View File

@@ -0,0 +1,314 @@
<?php
/**
* A Compatibility library with PHP 5.5's simplified password hashing API.
*
* @author Anthony Ferrara <ircmaxell@php.net>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @copyright 2012 The Authors
*/
namespace {
if (!defined('PASSWORD_BCRYPT')) {
/**
* PHPUnit Process isolation caches constants, but not function declarations.
* So we need to check if the constants are defined separately from
* the functions to enable supporting process isolation in userland
* code.
*/
define('PASSWORD_BCRYPT', 1);
define('PASSWORD_DEFAULT', PASSWORD_BCRYPT);
define('PASSWORD_BCRYPT_DEFAULT_COST', 10);
}
if (!function_exists('password_hash')) {
/**
* Hash the password using the specified algorithm
*
* @param string $password The password to hash
* @param int $algo The algorithm to use (Defined by PASSWORD_* constants)
* @param array $options The options for the algorithm to use
*
* @return string|false The hashed password, or false on error.
*/
function password_hash($password, $algo, array $options = array()) {
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_hash to function", E_USER_WARNING);
return null;
}
if (is_null($password) || is_int($password)) {
$password = (string) $password;
}
if (!is_string($password)) {
trigger_error("password_hash(): Password must be a string", E_USER_WARNING);
return null;
}
if (!is_int($algo)) {
trigger_error("password_hash() expects parameter 2 to be long, " . gettype($algo) . " given", E_USER_WARNING);
return null;
}
$resultLength = 0;
switch ($algo) {
case PASSWORD_BCRYPT:
$cost = PASSWORD_BCRYPT_DEFAULT_COST;
if (isset($options['cost'])) {
$cost = $options['cost'];
if ($cost < 4 || $cost > 31) {
trigger_error(sprintf("password_hash(): Invalid bcrypt cost parameter specified: %d", $cost), E_USER_WARNING);
return null;
}
}
// The length of salt to generate
$raw_salt_len = 16;
// The length required in the final serialization
$required_salt_len = 22;
$hash_format = sprintf("$2y$%02d$", $cost);
// The expected length of the final crypt() output
$resultLength = 60;
break;
default:
trigger_error(sprintf("password_hash(): Unknown password hashing algorithm: %s", $algo), E_USER_WARNING);
return null;
}
$salt_requires_encoding = false;
if (isset($options['salt'])) {
switch (gettype($options['salt'])) {
case 'NULL':
case 'boolean':
case 'integer':
case 'double':
case 'string':
$salt = (string) $options['salt'];
break;
case 'object':
if (method_exists($options['salt'], '__tostring')) {
$salt = (string) $options['salt'];
break;
}
case 'array':
case 'resource':
default:
trigger_error('password_hash(): Non-string salt parameter supplied', E_USER_WARNING);
return null;
}
if (PasswordCompat\binary\_strlen($salt) < $required_salt_len) {
trigger_error(sprintf("password_hash(): Provided salt is too short: %d expecting %d", PasswordCompat\binary\_strlen($salt), $required_salt_len), E_USER_WARNING);
return null;
} elseif (0 == preg_match('#^[a-zA-Z0-9./]+$#D', $salt)) {
$salt_requires_encoding = true;
}
} else {
$buffer = '';
$buffer_valid = false;
if (function_exists('mcrypt_create_iv') && !defined('PHALANGER')) {
$buffer = mcrypt_create_iv($raw_salt_len, MCRYPT_DEV_URANDOM);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && function_exists('openssl_random_pseudo_bytes')) {
$buffer = openssl_random_pseudo_bytes($raw_salt_len);
if ($buffer) {
$buffer_valid = true;
}
}
if (!$buffer_valid && @is_readable('/dev/urandom')) {
$f = fopen('/dev/urandom', 'r');
$read = PasswordCompat\binary\_strlen($buffer);
while ($read < $raw_salt_len) {
$buffer .= fread($f, $raw_salt_len - $read);
$read = PasswordCompat\binary\_strlen($buffer);
}
fclose($f);
if ($read >= $raw_salt_len) {
$buffer_valid = true;
}
}
if (!$buffer_valid || PasswordCompat\binary\_strlen($buffer) < $raw_salt_len) {
$bl = PasswordCompat\binary\_strlen($buffer);
for ($i = 0; $i < $raw_salt_len; $i++) {
if ($i < $bl) {
$buffer[$i] = $buffer[$i] ^ chr(mt_rand(0, 255));
} else {
$buffer .= chr(mt_rand(0, 255));
}
}
}
$salt = $buffer;
$salt_requires_encoding = true;
}
if ($salt_requires_encoding) {
// encode string with the Base64 variant used by crypt
$base64_digits =
'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
$bcrypt64_digits =
'./ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
$base64_string = base64_encode($salt);
$salt = strtr(rtrim($base64_string, '='), $base64_digits, $bcrypt64_digits);
}
$salt = PasswordCompat\binary\_substr($salt, 0, $required_salt_len);
$hash = $hash_format . $salt;
$ret = crypt($password, $hash);
if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) != $resultLength) {
return false;
}
return $ret;
}
/**
* Get information about the password hash. Returns an array of the information
* that was used to generate the password hash.
*
* array(
* 'algo' => 1,
* 'algoName' => 'bcrypt',
* 'options' => array(
* 'cost' => PASSWORD_BCRYPT_DEFAULT_COST,
* ),
* )
*
* @param string $hash The password hash to extract info from
*
* @return array The array of information about the hash.
*/
function password_get_info($hash) {
$return = array(
'algo' => 0,
'algoName' => 'unknown',
'options' => array(),
);
if (PasswordCompat\binary\_substr($hash, 0, 4) == '$2y$' && PasswordCompat\binary\_strlen($hash) == 60) {
$return['algo'] = PASSWORD_BCRYPT;
$return['algoName'] = 'bcrypt';
list($cost) = sscanf($hash, "$2y$%d$");
$return['options']['cost'] = $cost;
}
return $return;
}
/**
* Determine if the password hash needs to be rehashed according to the options provided
*
* If the answer is true, after validating the password using password_verify, rehash it.
*
* @param string $hash The hash to test
* @param int $algo The algorithm used for new password hashes
* @param array $options The options array passed to password_hash
*
* @return boolean True if the password needs to be rehashed.
*/
function password_needs_rehash($hash, $algo, array $options = array()) {
$info = password_get_info($hash);
if ($info['algo'] != $algo) {
return true;
}
switch ($algo) {
case PASSWORD_BCRYPT:
$cost = isset($options['cost']) ? $options['cost'] : PASSWORD_BCRYPT_DEFAULT_COST;
if ($cost != $info['options']['cost']) {
return true;
}
break;
}
return false;
}
/**
* Verify a password against a hash using a timing attack resistant approach
*
* @param string $password The password to verify
* @param string $hash The hash to verify against
*
* @return boolean If the password matches the hash
*/
function password_verify($password, $hash) {
if (!function_exists('crypt')) {
trigger_error("Crypt must be loaded for password_verify to function", E_USER_WARNING);
return false;
}
$ret = crypt($password, $hash);
if (!is_string($ret) || PasswordCompat\binary\_strlen($ret) != PasswordCompat\binary\_strlen($hash) || PasswordCompat\binary\_strlen($ret) <= 13) {
return false;
}
$status = 0;
for ($i = 0; $i < PasswordCompat\binary\_strlen($ret); $i++) {
$status |= (ord($ret[$i]) ^ ord($hash[$i]));
}
return $status === 0;
}
}
}
namespace PasswordCompat\binary {
if (!function_exists('PasswordCompat\\binary\\_strlen')) {
/**
* Count the number of bytes in a string
*
* We cannot simply use strlen() for this, because it might be overwritten by the mbstring extension.
* In this case, strlen() will count the number of *characters* based on the internal encoding. A
* sequence of bytes might be regarded as a single multibyte character.
*
* @param string $binary_string The input string
*
* @internal
* @return int The number of bytes
*/
function _strlen($binary_string) {
if (function_exists('mb_strlen')) {
return mb_strlen($binary_string, '8bit');
}
return strlen($binary_string);
}
/**
* Get a substring based on byte limits
*
* @see _strlen()
*
* @param string $binary_string The input string
* @param int $start
* @param int $length
*
* @internal
* @return string The substring
*/
function _substr($binary_string, $start, $length) {
if (function_exists('mb_substr')) {
return mb_substr($binary_string, $start, $length, '8bit');
}
return substr($binary_string, $start, $length);
}
/**
* Check if current PHP version is compatible with the library
*
* @return boolean the check result
*/
function check() {
static $pass = NULL;
if (is_null($pass)) {
if (function_exists('crypt')) {
$hash = '$2y$04$usesomesillystringfore7hnbRJHxXVLeakoG8K30oukPsA.ztMG';
$test = crypt("password", $hash);
$pass = $test == $hash;
} else {
$pass = false;
}
}
return $pass;
}
}
}

View File

@@ -0,0 +1,6 @@
<?php
require "lib/password.php";
echo "Test for functionality of compat library: " . (PasswordCompat\binary\check() ? "Pass" : "Fail");
echo "\n";

View File

@@ -0,0 +1 @@
vendor

19
vendor/ircmaxell/security-lib/LICENSE vendored Normal file
View File

@@ -0,0 +1,19 @@
Copyright (c) 2011 The Authors
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.

15
vendor/ircmaxell/security-lib/README.md vendored Normal file
View File

@@ -0,0 +1,15 @@
SecurityLib
===========
This is a base set of libraries used in other projects. This isn't useful on its own...
License
-------
MIT, see LICENSE.
Security Vulnerabilities
========================
If you have found a security issue, please contact the author directly at [me@ircmaxell.com](mailto:me@ircmaxell.com).

View File

@@ -0,0 +1,31 @@
{
"name": "ircmaxell/security-lib",
"type": "library",
"description": "A Base Security Library",
"keywords": [],
"homepage": "https://github.com/ircmaxell/SecurityLib",
"license": "MIT",
"authors": [
{
"name": "Anthony Ferrara",
"email": "ircmaxell@ircmaxell.com",
"homepage": "http://blog.ircmaxell.com"
}
],
"require-dev": {
"mikey179/vfsStream": "1.1.*"
},
"require": {
"php": ">=5.3.2"
},
"autoload": {
"psr-0": {
"SecurityLib": "lib"
}
},
"extra": {
"branch-alias": {
"dev-master": "1.0.x-dev"
}
}
}

55
vendor/ircmaxell/security-lib/composer.lock generated vendored Normal file
View File

@@ -0,0 +1,55 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at http://getcomposer.org/doc/01-basic-usage.md#composer-lock-the-lock-file"
],
"hash": "098e204bfe65a46e1866261c43a5ae88",
"packages": [
],
"packages-dev": [
{
"name": "mikey179/vfsStream",
"version": "v1.1.0",
"source": {
"type": "git",
"url": "https://github.com/mikey179/vfsStream",
"reference": "v1.1.0"
},
"dist": {
"type": "zip",
"url": "https://github.com/mikey179/vfsStream/zipball/v1.1.0",
"reference": "v1.1.0",
"shasum": ""
},
"require": {
"php": ">=5.3.0"
},
"type": "library",
"autoload": {
"psr-0": {
"org\\bovigo\\vfs": "src/main/php"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"BSD"
],
"homepage": "http://vfs.bovigo.org/",
"time": "2012-08-25 05:49:29"
}
],
"aliases": [
],
"minimum-stability": "stable",
"stability-flags": [
],
"platform": {
"php": ">=5.3.2"
},
"platform-dev": [
]
}

View File

@@ -0,0 +1,82 @@
<?php
/**
* The base abstract factory used by all PasswordLib factories
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Core
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version Build @@version@@
*/
namespace SecurityLib;
/**
* The base abstract factory used by all PasswordLib factories
*
* @category PHPPasswordLib
* @package Core
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
*/
abstract class AbstractFactory {
/**
* Register a type with the factory by name
*
* This is an internal method to check if a provided class name implements
* an interface, and if it does to append that class to an internal array
* by name.
*
* @param string $type The name of the variable to store the class
* @param string $implements The interface to validate against
* @param string $name The name of this particular class
* @param string $class The fully qualified class name
* @param boolean $instantiate Should the class be stored instantiated
*
* @return void
* @throws InvalidArgumentException If class does not implement interface
*/
protected function registerType(
$type,
$implements,
$name,
$class,
$instantiate = false
) {
$name = strtolower($name);
$refl = new \ReflectionClass($class);
if (!$refl->implementsInterface($implements)) {
$message = sprintf('Class must implement %s', $implements);
throw new \InvalidArgumentException($message);
}
if ($instantiate) {
$class = new $class;
}
$this->{$type}[$name] = $class;
}
/**
* Load a set of classes from a directory into the factory
*
* @param string $directory The directory to search for classes in
* @param string $namespace The namespace prefix for any found classes
* @param string $callback The callback with which to register the class
*
* @return void
*/
protected function loadFiles($directory, $namespace, $callback) {
foreach (new \DirectoryIterator($directory) as $file) {
$filename = $file->getBasename();
if ($file->isFile() && substr($filename, -4) == '.php') {
$name = substr($filename, 0, -4);
$class = $namespace . $name;
call_user_func($callback, $name, $class);
}
}
}
}

View File

@@ -0,0 +1,114 @@
<?php
/**
* A Utility class for converting between raw binary strings and a given
* list of characters
*
* PHP version 5.3
*
* @category PHPSecurityLib
* @package Core
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version Build @@version@@
*/
namespace SecurityLib;
/**
* A Utility class for converting between raw binary strings and a given
* list of characters
*
* @category PHPSecurityLib
* @package Core
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
*/
class BaseConverter {
/**
* Convert from a raw binary string to a string of characters
*
* @param string $string The string to convert from
* @param string $characters The list of characters to convert to
*
* @return string The converted string
*/
public static function convertFromBinary($string, $characters) {
if ($string === '' || empty($characters)) {
return '';
}
$string = str_split($string);
$callback = function($str) {
return ord($str);
};
$string = array_map($callback, $string);
$converted = static::baseConvert($string, 256, strlen($characters));
$callback = function ($num) use ($characters) {
return $characters[$num];
};
$ret = implode('', array_map($callback, $converted));
return $ret;
}
/**
* Convert to a raw binary string from a string of characters
*
* @param string $string The string to convert from
* @param string $characters The list of characters to convert to
*
* @return string The converted string
*/
public static function convertToBinary($string, $characters) {
if (empty($string) || empty($characters)) {
return '';
}
$string = str_split($string);
$callback = function($str) use ($characters) {
return strpos($characters, $str);
};
$string = array_map($callback, $string);
$converted = static::baseConvert($string, strlen($characters), 256);
$callback = function ($num) {
return chr($num);
};
return implode('', array_map($callback, $converted));
}
/**
* Convert an array of input blocks to another numeric base
*
* This function was modified from an implementation found on StackOverflow.
* Special Thanks to @KeithRandall for supplying the implementation.
*
* @param int[] $source The source number, as an array
* @param int $srcBase The source base as an integer
* @param int $dstBase The destination base as an integer
*
* @see http://codegolf.stackexchange.com/questions/1620/arb/1626#1626
* @return int[] An array of integers in the encoded base
*/
public static function baseConvert(array $source, $srcBase, $dstBase) {
if ($dstBase < 2) {
$message = sprintf('Invalid Destination Base: %d', $dstBase);
throw new \InvalidArgumentException($message);
}
$result = array();
$count = count($source);
while ($count) {
$itMax = $count;
$remainder = $count = $loop = 0;
while($loop < $itMax) {
$dividend = $source[$loop++] + $remainder * $srcBase;
$remainder = $dividend % $dstBase;
$res = ($dividend - $remainder) / $dstBase;
if ($count || $res) {
$source[$count++] = $res;
}
}
$result[] = $remainder;
}
return array_reverse($result);
}
}

View File

@@ -0,0 +1,65 @@
<?php
/**
* A class for arbitrary precision math functions
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Core
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version Build @@version@@
*/
namespace SecurityLib;
/**
* A class for arbitrary precision math functions
*
* @category PHPPasswordLib
* @package Core
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
*/
abstract class BigMath {
/**
* Get an instance of the big math class
*
* This is NOT a singleton. It simply loads the proper strategy
* given the current server configuration
*
* @return \PasswordLib\Core\BigMath A big math instance
*/
public static function createFromServerConfiguration() {
//@codeCoverageIgnoreStart
if (extension_loaded('gmp')) {
return new \SecurityLib\BigMath\GMP();
} elseif (extension_loaded('bcmath')) {
return new \SecurityLib\BigMath\BCMath();
} else {
return new \SecurityLib\BigMath\PHPMath();
}
//@codeCoverageIgnoreEnd
}
/**
* Add two numbers together
*
* @param string $left The left argument
* @param string $right The right argument
*
* @return A base-10 string of the sum of the two arguments
*/
abstract public function add($left, $right);
/**
* Subtract two numbers
*
* @param string $left The left argument
* @param string $right The right argument
*
* @return A base-10 string of the difference of the two arguments
*/
abstract public function subtract($left, $right);
}

View File

@@ -0,0 +1,50 @@
<?php
/**
* A class for arbitrary precision math functions implemented using bcmath
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Core
* @subpackage BigMath
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version Build @@version@@
*/
namespace SecurityLib\BigMath;
/**
* A class for arbitrary precision math functions implemented using bcmath
*
* @category PHPPasswordLib
* @package Core
* @subpackage BigMath
*/
class BCMath extends \SecurityLib\BigMath {
/**
* Add two numbers together
*
* @param string $left The left argument
* @param string $right The right argument
*
* @return A base-10 string of the sum of the two arguments
*/
public function add($left, $right) {
return bcadd($left, $right, 0);
}
/**
* Subtract two numbers
*
* @param string $left The left argument
* @param string $right The right argument
*
* @return A base-10 string of the difference of the two arguments
*/
public function subtract($left, $right) {
return bcsub($left, $right);
}
}

View File

@@ -0,0 +1,50 @@
<?php
/**
* A class for arbitrary precision math functions implemented using GMP
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Core
* @subpackage BigMath
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version Build @@version@@
*/
namespace SecurityLib\BigMath;
/**
* A class for arbitrary precision math functions implemented using GMP
*
* @category PHPPasswordLib
* @package Core
* @subpackage BigMath
*/
class GMP extends \SecurityLib\BigMath {
/**
* Add two numbers together
*
* @param string $left The left argument
* @param string $right The right argument
*
* @return A base-10 string of the sum of the two arguments
*/
public function add($left, $right) {
return gmp_strval(gmp_add($left, $right));
}
/**
* Subtract two numbers
*
* @param string $left The left argument
* @param string $right The right argument
*
* @return A base-10 string of the difference of the two arguments
*/
public function subtract($left, $right) {
return gmp_strval(gmp_sub($left, $right));
}
}

View File

@@ -0,0 +1,170 @@
<?php
/**
* A class for arbitrary precision math functions implemented in PHP
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Core
* @subpackage BigMath
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version Build @@version@@
*/
namespace SecurityLib\BigMath;
use SecurityLib\BaseConverter;
/**
* A class for arbitrary precision math functions implemented in PHP
*
* @category PHPPasswordLib
* @package Core
* @subpackage BigMath
*/
class PHPMath extends \SecurityLib\BigMath {
/**
* Add two numbers together
*
* @param string $left The left argument
* @param string $right The right argument
*
* @return A base-10 string of the sum of the two arguments
*/
public function add($left, $right) {
if (empty($left)) {
return $right;
} elseif (empty($right)) {
return $left;
}
$negative = '';
if ($left[0] == '-' && $right[0] == '-') {
$negative = '-';
$left = substr($left, 1);
$right = substr($right, 1);
} elseif ($left[0] == '-') {
return $this->subtract($right, substr($left, 1));
} elseif ($right[0] == '-') {
return $this->subtract($left, substr($right, 1));
}
$left = $this->normalize($left);
$right = $this->normalize($right);
$result = BaseConverter::convertFromBinary(
$this->addBinary($left, $right),
'0123456789'
);
return $negative . $result;
}
/**
* Subtract two numbers
*
* @param string $left The left argument
* @param string $right The right argument
*
* @return A base-10 string of the difference of the two arguments
*/
public function subtract($left, $right) {
if (empty($left)) {
return $right;
} elseif (empty($right)) {
return $left;
} elseif ($right[0] == '-') {
return $this->add($left, substr($right, 1));
} elseif ($left[0] == '-') {
return '-' . $this->add(ltrim($left, '-'), $right);
}
$left = $this->normalize($left);
$right = $this->normalize($right);
$results = $this->subtractBinary($left, $right);
$result = BaseConverter::convertFromBinary($results[1], '0123456789');
return $results[0] . $result;
}
/**
* Add two binary strings together
*
* @param string $left The left argument
* @param string $right The right argument
*
* @return string The binary result
*/
protected function addBinary($left, $right) {
$len = max(strlen($left), strlen($right));
$left = str_pad($left, $len, chr(0), STR_PAD_LEFT);
$right = str_pad($right, $len, chr(0), STR_PAD_LEFT);
$result = '';
$carry = 0;
for ($i = 0; $i < $len; $i++) {
$sum = ord($left[$len - $i - 1])
+ ord($right[$len - $i - 1])
+ $carry;
$result .= chr($sum % 256);
$carry = $sum >> 8;
}
while ($carry) {
$result .= chr($carry % 256);
$carry >>= 8;
}
return strrev($result);
}
/**
* Subtract two binary strings using 256's compliment
*
* @param string $left The left argument
* @param string $right The right argument
*
* @return string The binary result
*/
protected function subtractBinary($left, $right) {
$len = max(strlen($left), strlen($right));
$left = str_pad($left, $len, chr(0), STR_PAD_LEFT);
$right = str_pad($right, $len, chr(0), STR_PAD_LEFT);
$right = $this->compliment($right);
$result = $this->addBinary($left, $right);
if (strlen($result) > $len) {
// Positive Result
$carry = substr($result, 0, -1 * $len);
$result = substr($result, strlen($carry));
return array(
'',
$this->addBinary($result, $carry)
);
}
return array('-', $this->compliment($result));
}
/**
* Take the 256 base compliment
*
* @param string $string The binary string to compliment
*
* @return string The complimented string
*/
protected function compliment($string) {
$result = '';
$len = strlen($string);
for ($i = 0; $i < $len; $i++) {
$result .= chr(255 - ord($string[$i]));
}
return $result;
}
/**
* Transform a string number into a binary string using base autodetection
*
* @param string $string The string to transform
*
* @return string The binary transformed number
*/
protected function normalize($string) {
return BaseConverter::convertToBinary(
$string,
'0123456789'
);
}
}

View File

@@ -0,0 +1,117 @@
<?php
/**
* The Enum base class for Enum functionality
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Core
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version Build @@version@@
*/
namespace SecurityLib;
use \ReflectionObject;
/**
* The Enum base class for Enum functionality
*
* This is based off of the SplEnum class implementation (which is only available
* as a PECL extension in 5.3)
*
* @see http://www.php.net/manual/en/class.splenum.php
* @category PHPPasswordLib
* @package Core
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
*/
abstract class Enum {
/**
* A default value of null is provided. Override this to set your own default
*/
const __DEFAULT = null;
/**
* @var string The name of the constant this instance is using
*/
protected $name = '';
/**
* @var scalar The value of the constant this instance is using.
*/
protected $value = '';
/**
* Creates a new value of the Enum type
*
* @param mixed $value The value this instance represents
* @param boolean $strict Not Implemented at this time
*
* @return void
* @throws UnexpectedValueException If the value is not a constant
*/
public function __construct($value = null, $strict = false) {
if (is_null($value)) {
$value = static::__DEFAULT;
}
$validValues = $this->getConstList();
$this->name = array_search($value, $validValues);
if (!$this->name) {
throw new \UnexpectedValueException(
'Value not a const in enum ' . get_class($this)
);
}
$this->value = $value;
}
/**
* Cast the current object to a string and return its value
*
* @return mixed the current value of the instance
*/
public function __toString() {
return (string) $this->value;
}
/**
* Compare two enums using numeric comparison
*
* @param Enum $arg The enum to compare this instance to
*
* @return int 0 if same, 1 if the argument is greater, -1 else
*/
public function compare(Enum $arg) {
if ($this->value == $arg->value) {
return 0;
} elseif ($this->value > $arg->value) {
return -1;
} else {
return 1;
}
}
/**
* Returns all constants (including values) as an associative array
*
* @param boolean $include_default Include the __default magic value?
*
* @return array All of the constants found against this instance
*/
public function getConstList($include_default = false) {
static $constCache = array();
$class = get_class($this);
if (!isset($constCache[$class])) {
$reflector = new ReflectionObject($this);
$constCache[$class] = $reflector->getConstants();
}
if (!$include_default) {
$constants = $constCache[$class];
unset($constants['__DEFAULT']);
return $constants;
}
return $constCache[$class];
}
}

View File

@@ -0,0 +1,360 @@
<?php
/**
* A hash utility data mapper class
*
* This class's purpose is to store information about hash algorithms that is
* otherwise unavailable during runtime. Some information is available (such
* as the output size), but is included anyway for performance and completeness
* reasons.
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version Build @@version@@
*/
namespace SecurityLib;
/**
* A hash utility data mapper class
*
* This class's purpose is to store information about hash algorithms that is
* otherwise unavailable during runtime. Some information is available (such
* as the output size), but is included anyway for performance and completeness
* reasons.
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
*/
class Hash {
/**
* This array contains information about each hash function available to PHP
* at the present time. Block sizes are not available from functions, so they
* must be hard coded.
*
* The "secure" indicates the strength of the hash and whether or not any known
* cryptographic attacks exist for the hash function. This will only apply when
* using the hash functions for situations that require cryptographic strength
* such as message signing. For other uses the insecure ones can have valid
* uses.
*
* @var array An array of information about each supported hash function
*/
protected static $hashInfo = array(
'md2' => array(
'HashSize' => 128,
'BlockSize' => 128,
'secure' => false,
),
'md4' => array(
'HashSize' => 128,
'BlockSize' => 512,
'secure' => false,
),
'md5' => array(
'HashSize' => 128,
'BlockSize' => 512,
'secure' => false,
),
'sha1' => array(
'HashSize' => 160,
'BlockSize' => 512,
'secure' => false,
),
'sha224' => array(
'HashSize' => 224,
'BlockSize' => 512,
'secure' => true,
),
'sha256' => array(
'HashSize' => 256,
'BlockSize' => 512,
'secure' => true,
),
'sha384' => array(
'HashSize' => 384,
'BlockSize' => 1024,
'secure' => true,
),
'sha512' => array(
'HashSize' => 512,
'BlockSize' => 1024,
'secure' => true,
),
'ripemd128' => array(
'HashSize' => 128,
'BlockSize' => 512,
'secure' => true,
),
'ripemd160' => array(
'HashSize' => 160,
'BlockSize' => 512,
'secure' => true,
),
'ripemd256' => array(
'HashSize' => 256,
'BlockSize' => 512,
'secure' => true,
),
'ripemd320' => array(
'HashSize' => 320,
'BlockSize' => 512,
'secure' => true,
),
'whirlpool' => array(
'HashSize' => 512,
'BlockSize' => 512,
'secure' => true,
),
'tiger128,3' => array(
'HashSize' => 128,
'BlockSize' => 512,
'secure' => true,
),
'tiger160,3' => array(
'HashSize' => 160,
'BlockSize' => 512,
'secure' => true,
),
'tiger192,3' => array(
'HashSize' => 192,
'BlockSize' => 512,
'secure' => true,
),
'tiger128,4' => array(
'HashSize' => 128,
'BlockSize' => 512,
'secure' => true,
),
'tiger160,4' => array(
'HashSize' => 160,
'BlockSize' => 512,
'secure' => true,
),
'tiger192,4' => array(
'HashSize' => 192,
'BlockSize' => 512,
'secure' => true,
),
'snefru' => array(
'HashSize' => 256,
'BlockSize' => 512,
'secure' => false,
),
'snefru256' => array(
'HashSize' => 256,
'BlockSize' => 512,
'secure' => false,
),
'gost' => array(
'HashSize' => 256,
'BlockSize' => 256,
'secure' => false,
),
'adler32' => array(
'HashSize' => 32,
'BlockSize' => 16,
'secure' => false,
),
'crc32' => array(
'HashSize' => 32,
'BlockSize' => 32,
'secure' => false,
),
'crc32b' => array(
'HashSize' => 32,
'BlockSize' => 32,
'secure' => false,
),
'salsa10' => array(
'HashSize' => 512,
'BlockSize' => 512,
'secure' => true,
),
'salsa20' => array(
'HashSize' => 512,
'BlockSize' => 512,
'secure' => true,
),
'haval128,3' => array(
'HashSize' => 128,
'BlockSize' => 1024,
'secure' => false,
),
'haval160,3' => array(
'HashSize' => 160,
'BlockSize' => 1024,
'secure' => false,
),
'haval192,3' => array(
'HashSize' => 192,
'BlockSize' => 1024,
'secure' => false,
),
'haval224,3' => array(
'HashSize' => 224,
'BlockSize' => 1024,
'secure' => false,
),
'haval256,3' => array(
'HashSize' => 256,
'BlockSize' => 1024,
'secure' => false,
),
'haval128,4' => array(
'HashSize' => 128,
'BlockSize' => 1024,
'secure' => false,
),
'haval160,4' => array(
'HashSize' => 160,
'BlockSize' => 1024,
'secure' => false,
),
'haval192,4' => array(
'HashSize' => 192,
'BlockSize' => 1024,
'secure' => false,
),
'haval224,4' => array(
'HashSize' => 224,
'BlockSize' => 1024,
'secure' => false,
),
'haval256,4' => array(
'HashSize' => 256,
'BlockSize' => 1024,
'secure' => false,
),
'haval128,5' => array(
'HashSize' => 128,
'BlockSize' => 1024,
'secure' => false,
),
'haval160,5' => array(
'HashSize' => 160,
'BlockSize' => 1024,
'secure' => false,
),
'haval192,5' => array(
'HashSize' => 192,
'BlockSize' => 1024,
'secure' => false,
),
'haval224,5' => array(
'HashSize' => 224,
'BlockSize' => 1024,
'secure' => false,
),
'haval256,5' => array(
'HashSize' => 256,
'BlockSize' => 1024,
'secure' => false,
),
'joaat' => array(
'HashSize' => 32,
'BlockSize' => 64,
'secure' => false,
),
'fnv132' => array(
'HashSize' => 32,
'BlockSize' => 32,
'secure' => false,
),
'fnv164' => array(
'HashSize' => 64,
'BlockSize' => 64,
'secure' => false,
),
);
/**
* Get the block size of the specified function in bytes
*
* @param string $hash The hash function to look up
*
* @return int The number of bytes in the block function
*/
public static function getBlockSize($hash) {
return static::getBlockSizeInBits($hash) / 8;
}
/**
* Get the block size of the specified function in bits
*
* @param string $hash The hash function to look up
*
* @return int The number of bits in the block function
*/
public static function getBlockSizeInBits($hash) {
if (isset(static::$hashInfo[$hash]['BlockSize'])) {
return static::$hashInfo[$hash]['BlockSize'];
}
return 0;
}
/**
* Get the output size of the specified function in bytes
*
* @param string $hash The hash function to look up
*
* @return int The number of bytes outputted by the hash function
*/
public static function getHashSize($hash) {
return static::getHashSizeInBits($hash) / 8;
}
/**
* Get the output size of the specified function in bits
*
* @param string $hash The hash function to look up
*
* @return int The number of bits outputted by the hash function
*/
public static function getHashSizeInBits($hash) {
if (isset(static::$hashInfo[$hash]['HashSize'])) {
return static::$hashInfo[$hash]['HashSize'];
}
return 0;
}
/**
* Check to see if the hash function specified is available
*
* @param string $hash The hash function to look up
*
* @return boolean If the hash function is available in this version of PHP
*/
public static function isAvailable($hash) {
return in_array($hash, hash_algos());
}
/**
* Check to see if the specified hash function is secure enough for
* cryptographic uses
*
* The "secure" indicates the strength of the hash and whether or not any known
* cryptographic attacks exist for the hash function. This will only apply when
* using the hash functions for situations that require cryptographic strength
* such as message signing. For other uses the insecure ones can have valid
* uses.
*
* @param string $hash The hash function to look up
*
* @return bolean If the function is secure
*/
public static function isSecure($hash) {
if (isset(static::$hashInfo[$hash])) {
return static::$hashInfo[$hash]['secure'];
}
return false;
}
}

View File

@@ -0,0 +1,59 @@
<?php
/**
* The strength FlyweightEnum class
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Core
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version Build @@version@@
*/
namespace SecurityLib;
/**
* The strength FlyweightEnum class
*
* All mixing strategies must extend this class
*
* @category PHPPasswordLib
* @package Core
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
*/
class Strength extends Enum {
/**
* We provide a default value of VeryLow so that we don't accidentally over
* state the strength if we forget to pass in a value...
*/
const __DEFAULT = self::VERYLOW;
/**
* This represents Non-Cryptographic strengths. It should not be used any time
* that security or confidentiality is at stake
*/
const VERYLOW = 1;
/**
* This represents the bottom line of Cryptographic strengths. It may be used
* for low security uses where some strength is required.
*/
const LOW = 3;
/**
* This is the general purpose Cryptographical strength. It should be suitable
* for all uses except the most sensitive.
*/
const MEDIUM = 5;
/**
* This is the highest strength available. It should not be used unless the
* high strength is needed, due to hardware constraints (and entropy
* limitations).
*/
const HIGH = 7;
}

View File

@@ -0,0 +1,66 @@
<?php
/**
* The Mixer strategy interface.
*
* All mixing strategies must implement this interface
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @version Build @@version@@
*/
namespace SecurityLib;
/**
* The Utility trait.
*
* Contains methods used internally to this library.
*
* @category PHPPasswordLib
* @package Random
* @author Scott Arciszewski <scott@arciszewski.me>
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @codeCoverageIgnore
*/
abstract class Util {
/**
* Return the length of a string, even in the presence of
* mbstring.func_overload
*
* @param string $string the string we're measuring
* @return int
*/
public static function safeStrlen($string)
{
if (\function_exists('mb_strlen')) {
return \mb_strlen($string, '8bit');
}
return \strlen($string);
}
/**
* Return a string contained within a string, even in the presence of
* mbstring.func_overload
*
* @param string $string The string we're searching
* @param int $start What offset should we begin
* @param int|null $length How long should the substring be?
* (default: the remainder)
* @return string
*/
public static function safeSubstr($string, $start = 0, $length = null)
{
if (\function_exists('mb_substr')) {
return \mb_substr($string, $start, $length, '8bit');
} elseif ($length !== null) {
return \substr($string, $start, $length);
}
return \substr($string, $start);
}
}

View File

@@ -0,0 +1,13 @@
{
"name": "SecurityLib/Core",
"description": "Common implementations",
"keywords": ["security"],
"license": "MIT",
"require": {
"php": ">=5.3"
},
"autoload": {
"psr-0": { "SecurityLib\\SecurityLib": "" }
},
"target-dir": "SecurityLib\\SecurityLib"
}

View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<phpunit backupGlobals="true"
backupStaticAttributes="false"
bootstrap="test/bootstrap.php"
colors="false"
convertErrorsToExceptions="true"
convertNoticesToExceptions="true"
convertWarningsToExceptions="true"
forceCoversAnnotation="false"
mapTestClassNameToCoveredClassName="false"
processIsolation="false"
stopOnError="false"
stopOnFailure="false"
stopOnIncomplete="false"
stopOnSkipped="false"
testSuiteLoaderClass="PHPUnit_Runner_StandardTestSuiteLoader"
strict="false"
verbose="false">
<testsuites>
<testsuite name="Unit">
<directory>test/Unit</directory>
</testsuite>
</testsuites>
<filter>
<whitelist>
<directory suffix=".php">lib/</directory>
</whitelist>
</filter>
</phpunit>

View File

@@ -0,0 +1,41 @@
<?php
/**
* The interface that all hash implementations must implement
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @license http://www.gnu.org/licenses/lgpl-2.1.html LGPL v 2.1
*/
namespace PasswordLibTest\Mocks;
/**
* The interface that all hash implementations must implement
*
* @category PHPPasswordLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
*/
class AbstractMock {
protected $callbacks = array();
public static function init() {}
public function __construct(array $callbacks = array()) {
$this->callbacks = $callbacks;
}
public function __call($name, array $args = array()) {
if (isset($this->callbacks[$name])) {
return call_user_func_array($this->callbacks[$name], $args);
}
return null;
}
}

View File

@@ -0,0 +1,31 @@
<?php
/**
* The interface that all hash implementations must implement
*
* PHP version 5.3
*
* @category PHPSecurityLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @license http://www.gnu.org/licenses/lgpl-2.1.html LGPL v 2.1
*/
namespace SecurityLibTest\Mocks;
/**
* The interface that all hash implementations must implement
*
* @category PHPSecurityLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
*/
class Enum extends \SecurityLib\Enum {
const Value1 = 1;
const Value2 = 2;
const Value3 = 3;
const Value4 = 4;
}

View File

@@ -0,0 +1,49 @@
<?php
/**
* The interface that all hash implementations must implement
*
* PHP version 5.3
*
* @category PHPSecurityLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @license http://www.gnu.org/licenses/lgpl-2.1.html LGPL v 2.1
*/
namespace SecurityLibTest\Mocks;
/**
* The interface that all hash implementations must implement
*
* @category PHPSecurityLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
*/
class Factory extends \SecurityLib\AbstractFactory {
protected $callbacks = array();
public static function init() {}
public function __construct(array $callbacks = array()) {
$this->callbacks = $callbacks;
}
public function __call($name, array $args = array()) {
if (isset($this->callbacks[$name])) {
return call_user_func_array($this->callbacks[$name], $args);
}
return null;
}
public function registerType($a1, $a2, $a3, $a4, $a5 = false) {
return parent::registerType($a1, $a2, $a3, $a4, $a5);
}
public function loadFiles($dir, $name, $method) {
return parent::loadFiles($dir, $name, $method);
}
}

View File

@@ -0,0 +1,29 @@
<?php
/**
* The interface that all hash implementations must implement
*
* PHP version 5.3
*
* @category PHPSecurityLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @license http://www.gnu.org/licenses/lgpl-2.1.html LGPL v 2.1
*/
namespace SecurityLibTest\Mocks;
/**
* The interface that all hash implementations must implement
*
* @category PHPSecurityLib
* @package Hash
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
*/
class Strength extends \SecurityLib\Strength {
const MEDIUMLOW = 4;
const SUPERHIGH = 999;
}

View File

@@ -0,0 +1,67 @@
<?php
use SecurityLibTest\Mocks\Factory;
use org\bovigo\vfs\vfsStream;
class Unit_Core_AbstractFactoryTest extends PHPUnit_Framework_TestCase {
protected function setUp() {
$root = vfsStream::setup('SecurityLibTest');
//Setup Folders
$core = vfsStream::newDirectory('Core')->at($root);
$af = vfsStream::newDirectory('AbstractFactory')->at($core);
// Create Files
vfsStream::newFile('test.php')->at($af);
vfsStream::newFile('Some234Foo234Bar98Name.php')->at($af);
vfsStream::newFile('Invalid.csv')->at($af);
vfsStream::newFile('badlocation.php')->at($core);
}
/**
* @covers SecurityLib\AbstractFactory::registerType
*/
public function testRegisterType() {
$factory = new Factory;
$factory->registerType('test', 'iteratoraggregate', 'foo', 'ArrayObject', false);
}
/**
* @covers SecurityLib\AbstractFactory::registerType
* @expectedException InvalidArgumentException
*/
public function testRegisterTypeFail() {
$factory = new Factory;
$factory->registerType('test', 'iterator', 'foo', 'ArrayObject', false);
}
/**
* @covers SecurityLib\AbstractFactory::registerType
*/
public function testRegisterTypeInstantiate() {
$factory = new Factory;
$factory->registerType('test', 'iteratoraggregate', 'foo', 'ArrayObject', true);
}
public function testLoadFiles() {
$dir = vfsStream::url('SecurityLibTest/Core/AbstractFactory');
$result = array();
$callback = function($name, $class) use (&$result) {
$result[$name] = $class;
};
$factory = new Factory();
$factory->loadFiles($dir, 'foo\\', $callback);
$expect = array(
'test' => 'foo\\test',
'Some234Foo234Bar98Name' => 'foo\\Some234Foo234Bar98Name'
);
$this->assertEquals($expect, $result);
}
}

View File

@@ -0,0 +1,69 @@
<?php
use SecurityLib\BaseConverter;
class Unit_Core_BaseConverterTest extends PHPUnit_Framework_TestCase {
public static function provideConvertFromBinary() {
$return = array(
array('', '', ''),
array(chr(0), '012', '0'),
array(chr(9), '01', '1001'),
array(chr(1) . chr(2) . chr(3), '0123456789', '66051'),
);
return $return;
}
public static function provideConvertToFromBinary() {
$return = array();
$str = chr(1) . chr(0);
for ($i = 2; $i < 256; $i++) {
$str .= chr($i);
$return[] = array($str, strrev($str));
}
return $return;
}
/**
* @covers SecurityLib\BaseConverter::convertFromBinary
* @covers SecurityLib\BaseConverter::baseConvert
* @dataProvider provideConvertFromBinary
*/
public function testConvertFromBinary($from, $to, $expect) {
$result = BaseConverter::convertFromBinary($from, $to);
$this->assertEquals($expect, $result);
}
/**
* @covers SecurityLib\BaseConverter::convertToBinary
* @covers SecurityLib\BaseConverter::baseConvert
* @dataProvider provideConvertFromBinary
*/
public function testConvertToBinary($expect, $from, $str) {
$result = BaseConverter::convertToBinary($str, $from);
$result = ltrim($result, chr(0));
$expect = ltrim($expect, chr(0));
$this->assertEquals($expect, $result);
}
/**
* @covers SecurityLib\BaseConverter::convertToBinary
* @covers SecurityLib\BaseConverter::convertFromBinary
* @covers SecurityLib\BaseConverter::baseConvert
* @dataProvider provideConvertToFromBinary
*/
public function testConvertToAndFromBinary($str, $from) {
return false;
$result1 = BaseConverter::convertFromBinary($str, $from);
$result = BaseConverter::convertToBinary($result1, $from);
$this->assertEquals($str, $result);
}
/**
* @covers SecurityLib\BaseConverter::baseConvert
* @expectedException InvalidArgumentException
*/
public function testBaseConvertFailure() {
BaseConverter::baseConvert(array(1), 1, 1);
}
}

View File

@@ -0,0 +1,30 @@
<?php
require_once __DIR__ . '/../BigMathTest.php';
class Unit_Core_BigMath_BCMathTest extends Unit_Core_BigMathTest {
protected static $mathImplementations = array();
protected function setUp() {
if (!extension_loaded('bcmath')) {
$this->markTestSkipped('BCMath is not loaded');
}
}
/**
* @dataProvider provideAddTest
*/
public function testAdd($left, $right, $expected) {
$obj = new \SecurityLib\BigMath\BCMath;
$this->assertEquals($expected, $obj->add($left, $right));
}
/**
* @dataProvider provideSubtractTest
*/
public function testSubtract($left, $right, $expected) {
$obj = new \SecurityLib\BigMath\BCMath;
$this->assertEquals($expected, $obj->subtract($left, $right));
}
}

View File

@@ -0,0 +1,30 @@
<?php
require_once __DIR__ . '/../BigMathTest.php';
class Unit_Core_BigMath_GMPTest extends Unit_Core_BigMathTest {
protected static $mathImplementations = array();
protected function setUp() {
if (!extension_loaded('gmp')) {
$this->markTestSkipped('BCMath is not loaded');
}
}
/**
* @dataProvider provideAddTest
*/
public function testAdd($left, $right, $expected) {
$obj = new \SecurityLib\BigMath\GMP;
$this->assertEquals($expected, $obj->add($left, $right));
}
/**
* @dataProvider provideSubtractTest
*/
public function testSubtract($left, $right, $expected) {
$obj = new \SecurityLib\BigMath\GMP;
$this->assertEquals($expected, $obj->subtract($left, $right));
}
}

View File

@@ -0,0 +1,24 @@
<?php
require_once __DIR__ . '/../BigMathTest.php';
class Unit_Core_BigMath_PHPMathTest extends Unit_Core_BigMathTest {
protected static $mathImplementations = array();
/**
* @dataProvider provideAddTest
*/
public function testAdd($left, $right, $expected) {
$obj = new \SecurityLib\BigMath\PHPMath;
$this->assertEquals($expected, $obj->add($left, $right));
}
/**
* @dataProvider provideSubtractTest
*/
public function testSubtract($left, $right, $expected) {
$obj = new \SecurityLib\BigMath\PHPMath;
$this->assertEquals($expected, $obj->subtract($left, $right));
}
}

View File

@@ -0,0 +1,46 @@
<?php
class Unit_Core_BigMathTest extends PHPUnit_Framework_TestCase {
protected static $mathImplementations = array();
public static function provideAddTest() {
$ret = array(
array('1', '1', '2'),
array('11', '11', '22'),
array('1111111111', '1111111111', '2222222222'),
array('555', '555', '1110'),
array('-10', '10', '0'),
array('10', '-10', '0'),
array('-10', '-10', '-20'),
array('0', '0', '0'),
array('5', '0', '5'),
);
return $ret;
}
public static function provideSubtractTest() {
return array(
array('1', '1', '0'),
array('6', '3', '3'),
array('200', '250', '-50'),
array('10', '300', '-290'),
array('-1', '-1', '0'),
array('-5', '5', '-10'),
array('5', '-5', '10'),
array('0', '0', '0'),
array('5', '0', '5'),
);
}
public function testCreateFromServerConfiguration() {
$instance = \SecurityLib\BigMath::createFromServerConfiguration();
if (extension_loaded('bcmath')) {
$this->assertEquals('SecurityLib\\BigMath\\BCMath', get_class($instance));
} elseif (extension_loaded('gmp')) {
$this->assertEquals('SecurityLib\\BigMath\\GMP', get_class($instance));
} else {
$this->assertEquals('SecurityLib\\BigMath\\PHPMath', get_class($instance));
}
}
}

View File

@@ -0,0 +1,61 @@
<?php
use SecurityLibTest\Mocks\Enum;
class Unit_Core_EnumTest extends PHPUnit_Framework_TestCase {
public static function provideTestCompare() {
return array(
array(new Enum(Enum::Value1), new Enum(Enum::Value1), 0),
array(new Enum(Enum::Value2), new Enum(Enum::Value1), -1),
array(new Enum(Enum::Value1), new Enum(Enum::Value2), 1),
);
}
/**
* @expectedException UnexpectedValueException
*/
public function testConstructFail() {
$obj = new Enum();
}
public function testConstruct() {
$obj = new Enum(Enum::Value3);
$this->assertTrue($obj instanceof \SecurityLib\Enum);
}
public function testToString() {
$obj = new Enum(Enum::Value3);
$this->assertEquals('3', (string) $obj);
}
/**
* @covers SecurityLib\Core\Enum::compare
* @dataProvider provideTestCompare
*/
public function testCompare(Enum $from, Enum $to, $expected) {
$this->assertEquals($expected, $from->compare($to));
}
public function testGetConstList() {
$obj = new Enum(Enum::Value3);
$const = $obj->getConstList();
$this->assertEquals(array(
'Value1' => 1,
'Value2' => 2,
'Value3' => 3,
'Value4' => 4,
), $const);
}
public function testGetConstListWithDefault() {
$obj = new Enum(Enum::Value3);
$const = $obj->getConstList(true);
$this->assertEquals(array(
'__DEFAULT' => null,
'Value1' => 1,
'Value2' => 2,
'Value3' => 3,
'Value4' => 4,
), $const);
}
}

View File

@@ -0,0 +1,35 @@
<?php
use SecurityLib\Strength;
class Unit_Core_StrengthTest extends PHPUnit_Framework_TestCase {
public function testConstruct() {
$obj = new Strength(Strength::LOW);
$this->assertTrue($obj instanceof \SecurityLib\Strength);
$this->assertTrue($obj instanceof \SecurityLib\Enum);
}
public function testGetConstList() {
$obj = new Strength();
$const = $obj->getConstList();
$this->assertEquals(array(
'VERYLOW' => 1,
'LOW' => 3,
'MEDIUM' => 5,
'HIGH' => 7,
), $const);
}
public function testGetConstListWithDefault() {
$obj = new Strength();
$const = $obj->getConstList(true);
$this->assertEquals(array(
'__DEFAULT' => 1,
'VERYLOW' => 1,
'LOW' => 3,
'MEDIUM' => 5,
'HIGH' => 7,
), $const);
}
}

View File

@@ -0,0 +1,20 @@
<?php
namespace SecurityLib;
/**
* Highly recommended that his be run with and without setting
* mbstring.func_overload = 7
* in your php.ini file to verify its correctness.
*/
class UtilTest extends \PHPUnit_Framework_TestCase {
public function testSafeStrlen() {
$this->assertEquals(Util::safeStrlen("\x03\x3f"), 2);
}
public function testSafeSubstr() {
$a = "abcdefg\x03\x3fhijk";
$b = "\x03\x3f";
$this->assertEquals(Util::safeSubstr($a, 7, 2), $b);
}
}

View File

@@ -0,0 +1,49 @@
<?php
/**
* Bootstrap the library. This registers a simple autoloader for autoloading
* classes
*
* If you are using this library inside of another that uses a similar
* autoloading system, you can use that autoloader instead of this file.
*
* PHP version 5.3
*
* @category PHPPasswordLib
* @package test
* @author Anthony Ferrara <ircmaxell@ircmaxell.com>
* @copyright 2011 The Authors
* @license http://opensource.org/licenses/bsd-license.php New BSD License
* @license http://www.gnu.org/licenses/lgpl-2.1.html LGPL v 2.1
*/
namespace SecurityLibTest;
ini_set('memory_limit', '1G');
/**
* The simple autoloader for the PasswordLibTest libraries.
*
* This does not use the PRS-0 standards due to the namespace prefix and directory
* structure
*
* @param string $class The class name to load
*
* @return void
*/
spl_autoload_register(function ($class) {
$nslen = strlen(__NAMESPACE__);
if (substr($class, 0, $nslen) != __NAMESPACE__) {
//Only autoload libraries from this package
return;
}
$path = substr(str_replace('\\', '/', $class), $nslen);
$path = __DIR__ . $path . '.php';
if (file_exists($path)) {
require $path;
}
});
define('PATH_ROOT', dirname(__DIR__));
require_once dirname(__DIR__) . '/vendor/autoload.php';