[securemail] Update Composer dependencies

- Update phpseclib/phpseclib to version 2.0.4
- Update singpolyma/openpgp-php to version 0.3.0
This commit is contained in:
Hypolite Petovan 2019-02-10 08:44:29 -05:00
parent 37dd8a938b
commit af672ecd1b
161 changed files with 13940 additions and 7678 deletions

21
securemail/composer.json Normal file
View file

@ -0,0 +1,21 @@
{
"name": "friendica-addons/securemail",
"description": "Send notification mail encrypted with user-defined public GPG key.",
"type": "friendica-addon",
"authors": [
{
"name": "Fabio Comuni",
"homepage": "https://kirgroup.com/profile/fabrixxm",
"role": "Developer"
}
],
"require": {
"phpseclib/phpseclib": "^2.0",
"singpolyma/openpgp-php": "^0.3.0"
},
"license": "AGPL-3.0+",
"minimum-stability": "stable",
"config": {
"autoloader-suffix": "SecuremailAddon"
}
}

153
securemail/composer.lock generated Normal file
View file

@ -0,0 +1,153 @@
{
"_readme": [
"This file locks the dependencies of your project to a known state",
"Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies",
"This file is @generated automatically"
],
"content-hash": "b3a33a493eae34d9245ca7cc1b4572ea",
"packages": [
{
"name": "phpseclib/phpseclib",
"version": "2.0.4",
"source": {
"type": "git",
"url": "https://github.com/phpseclib/phpseclib.git",
"reference": "ab8028c93c03cc8d9c824efa75dc94f1db2369bf"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/ab8028c93c03cc8d9c824efa75dc94f1db2369bf",
"reference": "ab8028c93c03cc8d9c824efa75dc94f1db2369bf",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"phing/phing": "~2.7",
"phpunit/phpunit": "~4.0",
"sami/sami": "~2.0",
"squizlabs/php_codesniffer": "~2.0"
},
"suggest": {
"ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.",
"ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.",
"ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.",
"ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations."
},
"type": "library",
"autoload": {
"files": [
"phpseclib/bootstrap.php"
],
"psr-4": {
"phpseclib\\": "phpseclib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jim Wigginton",
"email": "terrafrost@php.net",
"role": "Lead Developer"
},
{
"name": "Patrick Monnerat",
"email": "pm@datasphere.ch",
"role": "Developer"
},
{
"name": "Andreas Fischer",
"email": "bantu@phpbb.com",
"role": "Developer"
},
{
"name": "Hans-Jürgen Petrich",
"email": "petrich@tronic-media.com",
"role": "Developer"
},
{
"name": "Graham Campbell",
"email": "graham@alt-three.com",
"role": "Developer"
}
],
"description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.",
"homepage": "http://phpseclib.sourceforge.net",
"keywords": [
"BigInteger",
"aes",
"asn.1",
"asn1",
"blowfish",
"crypto",
"cryptography",
"encryption",
"rsa",
"security",
"sftp",
"signature",
"signing",
"ssh",
"twofish",
"x.509",
"x509"
],
"time": "2016-10-04T00:57:04+00:00"
},
{
"name": "singpolyma/openpgp-php",
"version": "0.3.0",
"source": {
"type": "git",
"url": "https://github.com/singpolyma/openpgp-php.git",
"reference": "6006111bbc4c3b6cb8f0acb7d6c4a7047df366e8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/singpolyma/openpgp-php/zipball/6006111bbc4c3b6cb8f0acb7d6c4a7047df366e8",
"reference": "6006111bbc4c3b6cb8f0acb7d6c4a7047df366e8",
"shasum": ""
},
"require": {
"phpseclib/phpseclib": ">=2.0.0 <=2.0.4"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"type": "library",
"autoload": {
"classmap": [
"lib/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Unlicense"
],
"authors": [
{
"name": "Arto Bendiken",
"email": "arto.bendiken@gmail.com"
},
{
"name": "Stephen Paul Weber",
"email": "singpolyma@singpolyma.net"
}
],
"description": "Pure-PHP implementation of the OpenPGP Message Format (RFC 4880)",
"time": "2017-04-12T21:23:15+00:00"
}
],
"packages-dev": [],
"aliases": [],
"minimum-stability": "stable",
"stability-flags": [],
"prefer-stable": false,
"prefer-lowest": false,
"platform": [],
"platform-dev": []
}

7
securemail/vendor/autoload.php vendored Normal file
View file

@ -0,0 +1,7 @@
<?php
// autoload.php @generated by Composer
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInitSecuremailAddon::getLoader();

View file

@ -0,0 +1,445 @@
<?php
/*
* This file is part of Composer.
*
* (c) Nils Adermann <naderman@naderman.de>
* Jordi Boggiano <j.boggiano@seld.be>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
namespace Composer\Autoload;
/**
* ClassLoader implements a PSR-0, PSR-4 and classmap class loader.
*
* $loader = new \Composer\Autoload\ClassLoader();
*
* // register classes with namespaces
* $loader->add('Symfony\Component', __DIR__.'/component');
* $loader->add('Symfony', __DIR__.'/framework');
*
* // activate the autoloader
* $loader->register();
*
* // to enable searching the include path (eg. for PEAR packages)
* $loader->setUseIncludePath(true);
*
* In this example, if you try to use a class in the Symfony\Component
* namespace or one of its children (Symfony\Component\Console for instance),
* the autoloader will first look for the class under the component/
* directory, and it will then fallback to the framework/ directory if not
* found before giving up.
*
* This class is loosely based on the Symfony UniversalClassLoader.
*
* @author Fabien Potencier <fabien@symfony.com>
* @author Jordi Boggiano <j.boggiano@seld.be>
* @see http://www.php-fig.org/psr/psr-0/
* @see http://www.php-fig.org/psr/psr-4/
*/
class ClassLoader
{
// PSR-4
private $prefixLengthsPsr4 = array();
private $prefixDirsPsr4 = array();
private $fallbackDirsPsr4 = array();
// PSR-0
private $prefixesPsr0 = array();
private $fallbackDirsPsr0 = array();
private $useIncludePath = false;
private $classMap = array();
private $classMapAuthoritative = false;
private $missingClasses = array();
private $apcuPrefix;
public function getPrefixes()
{
if (!empty($this->prefixesPsr0)) {
return call_user_func_array('array_merge', $this->prefixesPsr0);
}
return array();
}
public function getPrefixesPsr4()
{
return $this->prefixDirsPsr4;
}
public function getFallbackDirs()
{
return $this->fallbackDirsPsr0;
}
public function getFallbackDirsPsr4()
{
return $this->fallbackDirsPsr4;
}
public function getClassMap()
{
return $this->classMap;
}
/**
* @param array $classMap Class to filename map
*/
public function addClassMap(array $classMap)
{
if ($this->classMap) {
$this->classMap = array_merge($this->classMap, $classMap);
} else {
$this->classMap = $classMap;
}
}
/**
* Registers a set of PSR-0 directories for a given prefix, either
* appending or prepending to the ones previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 root directories
* @param bool $prepend Whether to prepend the directories
*/
public function add($prefix, $paths, $prepend = false)
{
if (!$prefix) {
if ($prepend) {
$this->fallbackDirsPsr0 = array_merge(
(array) $paths,
$this->fallbackDirsPsr0
);
} else {
$this->fallbackDirsPsr0 = array_merge(
$this->fallbackDirsPsr0,
(array) $paths
);
}
return;
}
$first = $prefix[0];
if (!isset($this->prefixesPsr0[$first][$prefix])) {
$this->prefixesPsr0[$first][$prefix] = (array) $paths;
return;
}
if ($prepend) {
$this->prefixesPsr0[$first][$prefix] = array_merge(
(array) $paths,
$this->prefixesPsr0[$first][$prefix]
);
} else {
$this->prefixesPsr0[$first][$prefix] = array_merge(
$this->prefixesPsr0[$first][$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-4 directories for a given namespace, either
* appending or prepending to the ones previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
* @param bool $prepend Whether to prepend the directories
*
* @throws \InvalidArgumentException
*/
public function addPsr4($prefix, $paths, $prepend = false)
{
if (!$prefix) {
// Register directories for the root namespace.
if ($prepend) {
$this->fallbackDirsPsr4 = array_merge(
(array) $paths,
$this->fallbackDirsPsr4
);
} else {
$this->fallbackDirsPsr4 = array_merge(
$this->fallbackDirsPsr4,
(array) $paths
);
}
} elseif (!isset($this->prefixDirsPsr4[$prefix])) {
// Register directories for a new namespace.
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
} elseif ($prepend) {
// Prepend directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
(array) $paths,
$this->prefixDirsPsr4[$prefix]
);
} else {
// Append directories for an already registered namespace.
$this->prefixDirsPsr4[$prefix] = array_merge(
$this->prefixDirsPsr4[$prefix],
(array) $paths
);
}
}
/**
* Registers a set of PSR-0 directories for a given prefix,
* replacing any others previously set for this prefix.
*
* @param string $prefix The prefix
* @param array|string $paths The PSR-0 base directories
*/
public function set($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr0 = (array) $paths;
} else {
$this->prefixesPsr0[$prefix[0]][$prefix] = (array) $paths;
}
}
/**
* Registers a set of PSR-4 directories for a given namespace,
* replacing any others previously set for this namespace.
*
* @param string $prefix The prefix/namespace, with trailing '\\'
* @param array|string $paths The PSR-4 base directories
*
* @throws \InvalidArgumentException
*/
public function setPsr4($prefix, $paths)
{
if (!$prefix) {
$this->fallbackDirsPsr4 = (array) $paths;
} else {
$length = strlen($prefix);
if ('\\' !== $prefix[$length - 1]) {
throw new \InvalidArgumentException("A non-empty PSR-4 prefix must end with a namespace separator.");
}
$this->prefixLengthsPsr4[$prefix[0]][$prefix] = $length;
$this->prefixDirsPsr4[$prefix] = (array) $paths;
}
}
/**
* Turns on searching the include path for class files.
*
* @param bool $useIncludePath
*/
public function setUseIncludePath($useIncludePath)
{
$this->useIncludePath = $useIncludePath;
}
/**
* Can be used to check if the autoloader uses the include path to check
* for classes.
*
* @return bool
*/
public function getUseIncludePath()
{
return $this->useIncludePath;
}
/**
* Turns off searching the prefix and fallback directories for classes
* that have not been registered with the class map.
*
* @param bool $classMapAuthoritative
*/
public function setClassMapAuthoritative($classMapAuthoritative)
{
$this->classMapAuthoritative = $classMapAuthoritative;
}
/**
* Should class lookup fail if not found in the current class map?
*
* @return bool
*/
public function isClassMapAuthoritative()
{
return $this->classMapAuthoritative;
}
/**
* APCu prefix to use to cache found/not-found classes, if the extension is enabled.
*
* @param string|null $apcuPrefix
*/
public function setApcuPrefix($apcuPrefix)
{
$this->apcuPrefix = function_exists('apcu_fetch') && ini_get('apc.enabled') ? $apcuPrefix : null;
}
/**
* The APCu prefix in use, or null if APCu caching is not enabled.
*
* @return string|null
*/
public function getApcuPrefix()
{
return $this->apcuPrefix;
}
/**
* Registers this instance as an autoloader.
*
* @param bool $prepend Whether to prepend the autoloader or not
*/
public function register($prepend = false)
{
spl_autoload_register(array($this, 'loadClass'), true, $prepend);
}
/**
* Unregisters this instance as an autoloader.
*/
public function unregister()
{
spl_autoload_unregister(array($this, 'loadClass'));
}
/**
* Loads the given class or interface.
*
* @param string $class The name of the class
* @return bool|null True if loaded, null otherwise
*/
public function loadClass($class)
{
if ($file = $this->findFile($class)) {
includeFile($file);
return true;
}
}
/**
* Finds the path to the file where the class is defined.
*
* @param string $class The name of the class
*
* @return string|false The path if found, false otherwise
*/
public function findFile($class)
{
// class map lookup
if (isset($this->classMap[$class])) {
return $this->classMap[$class];
}
if ($this->classMapAuthoritative || isset($this->missingClasses[$class])) {
return false;
}
if (null !== $this->apcuPrefix) {
$file = apcu_fetch($this->apcuPrefix.$class, $hit);
if ($hit) {
return $file;
}
}
$file = $this->findFileWithExtension($class, '.php');
// Search for Hack files if we are running on HHVM
if (false === $file && defined('HHVM_VERSION')) {
$file = $this->findFileWithExtension($class, '.hh');
}
if (null !== $this->apcuPrefix) {
apcu_add($this->apcuPrefix.$class, $file);
}
if (false === $file) {
// Remember that this class does not exist.
$this->missingClasses[$class] = true;
}
return $file;
}
private function findFileWithExtension($class, $ext)
{
// PSR-4 lookup
$logicalPathPsr4 = strtr($class, '\\', DIRECTORY_SEPARATOR) . $ext;
$first = $class[0];
if (isset($this->prefixLengthsPsr4[$first])) {
$subPath = $class;
while (false !== $lastPos = strrpos($subPath, '\\')) {
$subPath = substr($subPath, 0, $lastPos);
$search = $subPath . '\\';
if (isset($this->prefixDirsPsr4[$search])) {
$pathEnd = DIRECTORY_SEPARATOR . substr($logicalPathPsr4, $lastPos + 1);
foreach ($this->prefixDirsPsr4[$search] as $dir) {
if (file_exists($file = $dir . $pathEnd)) {
return $file;
}
}
}
}
}
// PSR-4 fallback dirs
foreach ($this->fallbackDirsPsr4 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr4)) {
return $file;
}
}
// PSR-0 lookup
if (false !== $pos = strrpos($class, '\\')) {
// namespaced class name
$logicalPathPsr0 = substr($logicalPathPsr4, 0, $pos + 1)
. strtr(substr($logicalPathPsr4, $pos + 1), '_', DIRECTORY_SEPARATOR);
} else {
// PEAR-like class name
$logicalPathPsr0 = strtr($class, '_', DIRECTORY_SEPARATOR) . $ext;
}
if (isset($this->prefixesPsr0[$first])) {
foreach ($this->prefixesPsr0[$first] as $prefix => $dirs) {
if (0 === strpos($class, $prefix)) {
foreach ($dirs as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
}
}
}
// PSR-0 fallback dirs
foreach ($this->fallbackDirsPsr0 as $dir) {
if (file_exists($file = $dir . DIRECTORY_SEPARATOR . $logicalPathPsr0)) {
return $file;
}
}
// PSR-0 include paths.
if ($this->useIncludePath && $file = stream_resolve_include_path($logicalPathPsr0)) {
return $file;
}
return false;
}
}
/**
* Scope isolated include.
*
* Prevents access to $this/self from included files.
*/
function includeFile($file)
{
include $file;
}

21
securemail/vendor/composer/LICENSE vendored Normal file
View file

@ -0,0 +1,21 @@
Copyright (c) Nils Adermann, Jordi Boggiano
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,58 @@
<?php
// autoload_classmap.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'MCryptWrapper' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp_mcrypt_wrapper.php',
'OpenPGP' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_AsymmetricSessionKeyPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_CompressedDataPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_Crypt_RSA' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp_crypt_rsa.php',
'OpenPGP_Crypt_Symmetric' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp_crypt_symmetric.php',
'OpenPGP_EncryptedDataPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_ExperimentalPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_IntegrityProtectedDataPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_LiteralDataPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_MarkerPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_Message' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_ModificationDetectionCodePacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_OnePassSignaturePacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_Packet' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_PublicKeyPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_PublicSubkeyPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_S2K' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SecretKeyPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SecretSubkeyPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_EmbeddedSignaturePacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_ExportableCertificationPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_FeaturesPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_IssuerPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_KeyExpirationTimePacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_KeyFlagsPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_KeyServerPreferencesPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_NotationDataPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PolicyURIPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PreferredCompressionAlgorithmsPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PreferredHashAlgorithmsPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PreferredKeyServerPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PreferredSymmetricAlgorithmsPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PrimaryUserIDPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_ReasonforRevocationPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_RegularExpressionPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_RevocablePacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_RevocationKeyPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_SignatureCreationTimePacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_SignatureExpirationTimePacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_SignatureTargetPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_SignersUserIDPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_Subpacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_TrustSignaturePacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SymmetricSessionKeyPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_TrustPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_UserAttributePacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_UserIDPacket' => $vendorDir . '/singpolyma/openpgp-php/lib/openpgp.php',
);

View file

@ -0,0 +1,10 @@
<?php
// autoload_files.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'decc78cc4436b1292c6c0d151b19445c' => $vendorDir . '/phpseclib/phpseclib/phpseclib/bootstrap.php',
);

View file

@ -0,0 +1,9 @@
<?php
// autoload_namespaces.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
);

View file

@ -0,0 +1,10 @@
<?php
// autoload_psr4.php @generated by Composer
$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);
return array(
'phpseclib\\' => array($vendorDir . '/phpseclib/phpseclib/phpseclib'),
);

View file

@ -0,0 +1,70 @@
<?php
// autoload_real.php @generated by Composer
class ComposerAutoloaderInitSecuremailAddon
{
private static $loader;
public static function loadClassLoader($class)
{
if ('Composer\Autoload\ClassLoader' === $class) {
require __DIR__ . '/ClassLoader.php';
}
}
public static function getLoader()
{
if (null !== self::$loader) {
return self::$loader;
}
spl_autoload_register(array('ComposerAutoloaderInitSecuremailAddon', 'loadClassLoader'), true, true);
self::$loader = $loader = new \Composer\Autoload\ClassLoader();
spl_autoload_unregister(array('ComposerAutoloaderInitSecuremailAddon', 'loadClassLoader'));
$useStaticLoader = PHP_VERSION_ID >= 50600 && !defined('HHVM_VERSION') && (!function_exists('zend_loader_file_encoded') || !zend_loader_file_encoded());
if ($useStaticLoader) {
require_once __DIR__ . '/autoload_static.php';
call_user_func(\Composer\Autoload\ComposerStaticInitSecuremailAddon::getInitializer($loader));
} else {
$map = require __DIR__ . '/autoload_namespaces.php';
foreach ($map as $namespace => $path) {
$loader->set($namespace, $path);
}
$map = require __DIR__ . '/autoload_psr4.php';
foreach ($map as $namespace => $path) {
$loader->setPsr4($namespace, $path);
}
$classMap = require __DIR__ . '/autoload_classmap.php';
if ($classMap) {
$loader->addClassMap($classMap);
}
}
$loader->register(true);
if ($useStaticLoader) {
$includeFiles = Composer\Autoload\ComposerStaticInitSecuremailAddon::$files;
} else {
$includeFiles = require __DIR__ . '/autoload_files.php';
}
foreach ($includeFiles as $fileIdentifier => $file) {
composerRequireSecuremailAddon($fileIdentifier, $file);
}
return $loader;
}
}
function composerRequireSecuremailAddon($fileIdentifier, $file)
{
if (empty($GLOBALS['__composer_autoload_files'][$fileIdentifier])) {
require $file;
$GLOBALS['__composer_autoload_files'][$fileIdentifier] = true;
}
}

View file

@ -0,0 +1,88 @@
<?php
// autoload_static.php @generated by Composer
namespace Composer\Autoload;
class ComposerStaticInitSecuremailAddon
{
public static $files = array (
'decc78cc4436b1292c6c0d151b19445c' => __DIR__ . '/..' . '/phpseclib/phpseclib/phpseclib/bootstrap.php',
);
public static $prefixLengthsPsr4 = array (
'p' =>
array (
'phpseclib\\' => 10,
),
);
public static $prefixDirsPsr4 = array (
'phpseclib\\' =>
array (
0 => __DIR__ . '/..' . '/phpseclib/phpseclib/phpseclib',
),
);
public static $classMap = array (
'MCryptWrapper' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp_mcrypt_wrapper.php',
'OpenPGP' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_AsymmetricSessionKeyPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_CompressedDataPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_Crypt_RSA' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp_crypt_rsa.php',
'OpenPGP_Crypt_Symmetric' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp_crypt_symmetric.php',
'OpenPGP_EncryptedDataPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_ExperimentalPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_IntegrityProtectedDataPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_LiteralDataPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_MarkerPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_Message' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_ModificationDetectionCodePacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_OnePassSignaturePacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_Packet' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_PublicKeyPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_PublicSubkeyPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_S2K' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SecretKeyPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SecretSubkeyPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_EmbeddedSignaturePacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_ExportableCertificationPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_FeaturesPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_IssuerPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_KeyExpirationTimePacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_KeyFlagsPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_KeyServerPreferencesPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_NotationDataPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PolicyURIPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PreferredCompressionAlgorithmsPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PreferredHashAlgorithmsPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PreferredKeyServerPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PreferredSymmetricAlgorithmsPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_PrimaryUserIDPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_ReasonforRevocationPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_RegularExpressionPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_RevocablePacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_RevocationKeyPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_SignatureCreationTimePacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_SignatureExpirationTimePacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_SignatureTargetPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_SignersUserIDPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_Subpacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SignaturePacket_TrustSignaturePacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_SymmetricSessionKeyPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_TrustPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_UserAttributePacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
'OpenPGP_UserIDPacket' => __DIR__ . '/..' . '/singpolyma/openpgp-php/lib/openpgp.php',
);
public static function getInitializer(ClassLoader $loader)
{
return \Closure::bind(function () use ($loader) {
$loader->prefixLengthsPsr4 = ComposerStaticInitSecuremailAddon::$prefixLengthsPsr4;
$loader->prefixDirsPsr4 = ComposerStaticInitSecuremailAddon::$prefixDirsPsr4;
$loader->classMap = ComposerStaticInitSecuremailAddon::$classMap;
}, null, ClassLoader::class);
}
}

View file

@ -0,0 +1,141 @@
[
{
"name": "phpseclib/phpseclib",
"version": "2.0.4",
"version_normalized": "2.0.4.0",
"source": {
"type": "git",
"url": "https://github.com/phpseclib/phpseclib.git",
"reference": "ab8028c93c03cc8d9c824efa75dc94f1db2369bf"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/phpseclib/phpseclib/zipball/ab8028c93c03cc8d9c824efa75dc94f1db2369bf",
"reference": "ab8028c93c03cc8d9c824efa75dc94f1db2369bf",
"shasum": ""
},
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"phing/phing": "~2.7",
"phpunit/phpunit": "~4.0",
"sami/sami": "~2.0",
"squizlabs/php_codesniffer": "~2.0"
},
"suggest": {
"ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations.",
"ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.",
"ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.",
"ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations."
},
"time": "2016-10-04T00:57:04+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"files": [
"phpseclib/bootstrap.php"
],
"psr-4": {
"phpseclib\\": "phpseclib/"
}
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"MIT"
],
"authors": [
{
"name": "Jim Wigginton",
"email": "terrafrost@php.net",
"role": "Lead Developer"
},
{
"name": "Patrick Monnerat",
"email": "pm@datasphere.ch",
"role": "Developer"
},
{
"name": "Andreas Fischer",
"email": "bantu@phpbb.com",
"role": "Developer"
},
{
"name": "Hans-Jürgen Petrich",
"email": "petrich@tronic-media.com",
"role": "Developer"
},
{
"name": "Graham Campbell",
"email": "graham@alt-three.com",
"role": "Developer"
}
],
"description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.",
"homepage": "http://phpseclib.sourceforge.net",
"keywords": [
"BigInteger",
"aes",
"asn.1",
"asn1",
"blowfish",
"crypto",
"cryptography",
"encryption",
"rsa",
"security",
"sftp",
"signature",
"signing",
"ssh",
"twofish",
"x.509",
"x509"
]
},
{
"name": "singpolyma/openpgp-php",
"version": "0.3.0",
"version_normalized": "0.3.0.0",
"source": {
"type": "git",
"url": "https://github.com/singpolyma/openpgp-php.git",
"reference": "6006111bbc4c3b6cb8f0acb7d6c4a7047df366e8"
},
"dist": {
"type": "zip",
"url": "https://api.github.com/repos/singpolyma/openpgp-php/zipball/6006111bbc4c3b6cb8f0acb7d6c4a7047df366e8",
"reference": "6006111bbc4c3b6cb8f0acb7d6c4a7047df366e8",
"shasum": ""
},
"require": {
"phpseclib/phpseclib": ">=2.0.0 <=2.0.4"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"time": "2017-04-12T21:23:15+00:00",
"type": "library",
"installation-source": "dist",
"autoload": {
"classmap": [
"lib/"
]
},
"notification-url": "https://packagist.org/downloads/",
"license": [
"Unlicense"
],
"authors": [
{
"name": "Arto Bendiken",
"email": "arto.bendiken@gmail.com"
},
{
"name": "Stephen Paul Weber",
"email": "singpolyma@singpolyma.net"
}
],
"description": "Pure-PHP implementation of the OpenPGP Message Format (RFC 4880)"
}
]

View file

@ -3,3 +3,4 @@ phpseclib Lead Developer: TerraFrost (Jim Wigginton)
phpseclib Developers: monnerat (Patrick Monnerat) phpseclib Developers: monnerat (Patrick Monnerat)
bantu (Andreas Fischer) bantu (Andreas Fischer)
petrich (Hans-Jürgen Petrich) petrich (Hans-Jürgen Petrich)
GrahamCampbell (Graham Campbell)

View file

@ -1,83 +0,0 @@
# Changelog
## 0.3.9 - 2014-11-09
- PHP 5.6 improvements ([#482](https://github.com/phpseclib/phpseclib/pull/482), [#491](https://github.com/phpseclib/phpseclib/issues/491))
## 0.3.8 - 2014-09-12
- improve support for indef lengths in File_ASN1
- add hmac-sha2-256 support to Net_SSH2
- make it so negotiated algorithms can be seen before Net_SSH2 login
- add sha256-96 and sha512-96 to Crypt_Hash
- window size handling adjustments in Net_SSH2
## 0.3.7 - 2014-07-05
- auto-detect public vs private keys
- add file_exists, is_dir, is_file, readlink and symlink to Net_SFTP
- add support for recursive nlist and rawlist
- make it so nlist and rawlist can return pre-sorted output
- make it so callback functions can make exec() return early
- add signSPKAC and saveSPKAC methods to File_X509
- add support for PKCS8 keys in Crypt_RSA
- add pbkdf1 support to setPassword() in Crypt_Base
- add getWindowColumns, getWindowRows, setWindowColumns, setWindowRows to Net_SSH2
- add support for filenames with spaces in them to Net_SCP
## 0.3.6 - 2014-02-23
- add preliminary support for custom SSH subsystems
- add ssh-agent support
## 0.3.5 - 2013-07-11
- numerous SFTP changes:
- chown
- chgrp
- truncate
- improved file type detection
- put() can write to te middle of a file
- mkdir accepts the same paramters that PHP's mkdir does
- the ability to upload/download 2GB files
- across-the-board speedups for the various encryption algorithms
- multi-factor authentication support for Net_SSH2
- a $callback parameter for Net_SSH2::exec
- new classes:
- Net_SFTP_StreamWrapper
- Net_SCP
- Crypt_Twofish
- Crypt_Blowfish
## 0.3.1 - 2012-11-20
- add Net_SSH2::enableQuietMode() for suppressing stderr
- add Crypt_RSA::__toString() and Crypt_RSA::getSize()
- fix problems with File_X509::validateDate(), File_X509::sign() and Crypt_RSA::verify()
- use OpenSSL to speed up modular exponention in Math_BigInteger
- improved timeout functionality in Net_SSH2
- add support for SFTPv2
- add support for CRLs in File_X509
- SSH-2.0-SSH doesn't implement hmac-*-96 correctly
## 0.3.0 - 2012-07-08
- add support for reuming Net_SFTP::put()
- add support for recursive deletes and recursive chmods to Net_SFTP
- add setTimeout() to Net_SSH2
- add support for PBKDF2 to the various Crypt_* classes via setPassword()
- add File_X509 and File_ASN1
- add the ability to decode various formats in Crypt_RSA
- make Net_SSH2::getServerPublicHostKey() return a printer-friendly version of the public key
## 0.2.2 - 2011-05-09
- CFB and OFB modes were added to all block ciphers
- support for interactive mode was added to Net_SSH2
- Net_SSH2 now has limited keyboard_interactive authentication support
- support was added for PuTTY formatted RSA private keys and XML formatted RSA private keys
- Crypt_RSA::loadKey() will now try all key types automatically
= add support for AES-128-CBC and DES-EDE3-CFB encrypted RSA private keys
- add Net_SFTP::stat(), Net_SFTP::lstat() and Net_SFTP::rawlist()
- logging was added to Net_SSH1
- the license was changed to the less restrictive MIT license

View file

@ -1,4 +1,4 @@
Copyright 2007-2013 TerraFrost and other contributors Copyright 2007-2016 TerraFrost and other contributors
http://phpseclib.sourceforge.net/ http://phpseclib.sourceforge.net/
Permission is hereby granted, free of charge, to any person obtaining Permission is hereby granted, free of charge, to any person obtaining

View file

@ -1,14 +1,14 @@
# phpseclib - PHP Secure Communications Library # phpseclib - PHP Secure Communications Library
[![Build Status](https://secure.travis-ci.org/phpseclib/phpseclib.png?branch=master)](http://travis-ci.org/phpseclib/phpseclib) [![Build Status](https://travis-ci.org/phpseclib/phpseclib.svg?branch=2.0)](https://travis-ci.org/phpseclib/phpseclib)
MIT-licensed pure-PHP implementations of an arbitrary-precision integer MIT-licensed pure-PHP implementations of an arbitrary-precision integer
arithmetic library, fully PKCS#1 (v2.1) compliant RSA, DES, 3DES, RC4, Rijndael, arithmetic library, fully PKCS#1 (v2.1) compliant RSA, DES, 3DES, RC4, Rijndael,
AES, Blowfish, Twofish, SSH-1, SSH-2, SFTP, and X.509 AES, Blowfish, Twofish, SSH-1, SSH-2, SFTP, and X.509
* [Download (0.3.9)](http://sourceforge.net/projects/phpseclib/files/phpseclib0.3.9.zip/download) * [Download (1.0.4)](http://sourceforge.net/projects/phpseclib/files/phpseclib1.0.4.zip/download)
* [Browse Git](https://github.com/phpseclib/phpseclib) * [Browse Git](https://github.com/phpseclib/phpseclib)
* [Code Coverage Report](http://phpseclib.bantux.org/code_coverage/master/latest/) * [Code Coverage Report](http://phpseclib.bantux.org/code_coverage/2.0/latest/)
<img src="http://phpseclib.sourceforge.net/pear-icon.png" alt="PEAR Channel" width="16" height="16"> <img src="http://phpseclib.sourceforge.net/pear-icon.png" alt="PEAR Channel" width="16" height="16">
PEAR Channel: [phpseclib.sourceforge.net](http://phpseclib.sourceforge.net/pear.htm) PEAR Channel: [phpseclib.sourceforge.net](http://phpseclib.sourceforge.net/pear.htm)
@ -16,7 +16,7 @@ PEAR Channel: [phpseclib.sourceforge.net](http://phpseclib.sourceforge.net/pear.
## Documentation ## Documentation
* [Documentation / Manual](http://phpseclib.sourceforge.net/) * [Documentation / Manual](http://phpseclib.sourceforge.net/)
* [API Documentation](http://phpseclib.bantux.org/api/master/) (generated by Sami) * [API Documentation](http://phpseclib.bantux.org/api/2.0/) (generated by Sami)
## Support ## Support
@ -40,7 +40,7 @@ Dependencies are managed via Composer.
2. Install Dependencies 2. Install Dependencies
``` sh ``` sh
php composer.phar install --dev php composer.phar install
``` ```
## Contributing ## Contributing

View file

@ -0,0 +1,76 @@
{
"name": "phpseclib/phpseclib",
"type": "library",
"description": "PHP Secure Communications Library - Pure-PHP implementations of RSA, AES, SSH2, SFTP, X.509 etc.",
"keywords": [
"security",
"crypto",
"cryptography",
"encryption",
"signature",
"signing",
"rsa",
"aes",
"blowfish",
"twofish",
"ssh",
"sftp",
"x509",
"x.509",
"asn1",
"asn.1",
"BigInteger"
],
"homepage": "http://phpseclib.sourceforge.net",
"license": "MIT",
"authors": [
{
"name": "Jim Wigginton",
"email": "terrafrost@php.net",
"role": "Lead Developer"
},
{
"name": "Patrick Monnerat",
"email": "pm@datasphere.ch",
"role": "Developer"
},
{
"name": "Andreas Fischer",
"email": "bantu@phpbb.com",
"role": "Developer"
},
{
"name": "Hans-Jürgen Petrich",
"email": "petrich@tronic-media.com",
"role": "Developer"
},
{
"name": "Graham Campbell",
"email": "graham@alt-three.com",
"role": "Developer"
}
],
"require": {
"php": ">=5.3.3"
},
"require-dev": {
"phing/phing": "~2.7",
"phpunit/phpunit": "~4.0",
"sami/sami": "~2.0",
"squizlabs/php_codesniffer": "~2.0"
},
"suggest": {
"ext-libsodium": "SSH2/SFTP can make use of some algorithms provided by the libsodium-php extension.",
"ext-openssl": "Install the OpenSSL extension in order to speed up a wide variety of cryptographic operations.",
"ext-mcrypt": "Install the Mcrypt extension in order to speed up a few other cryptographic operations.",
"ext-gmp": "Install the GMP (GNU Multiple Precision) extension in order to speed up arbitrary precision integer arithmetic operations."
},
"autoload": {
"files": [
"phpseclib/bootstrap.php"
],
"psr-4": {
"phpseclib\\": "phpseclib/"
}
}
}

1819
securemail/vendor/phpseclib/phpseclib/composer.lock generated vendored Normal file

File diff suppressed because it is too large Load diff

View file

@ -5,23 +5,27 @@
* *
* Uses mcrypt, if available/possible, and an internal implementation, otherwise. * Uses mcrypt, if available/possible, and an internal implementation, otherwise.
* *
* PHP versions 4 and 5 * PHP version 5
* *
* If {@link Crypt_AES::setKeyLength() setKeyLength()} isn't called, it'll be calculated from * NOTE: Since AES.php is (for compatibility and phpseclib-historical reasons) virtually
* {@link Crypt_AES::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's 136-bits * just a wrapper to Rijndael.php you may consider using Rijndael.php instead of
* it'll be null-padded to 192-bits and 192 bits will be the key length until {@link Crypt_AES::setKey() setKey()} * to save one include_once().
*
* If {@link self::setKeyLength() setKeyLength()} isn't called, it'll be calculated from
* {@link self::setKey() setKey()}. ie. if the key is 128-bits, the key length will be 128-bits. If it's 136-bits
* it'll be null-padded to 192-bits and 192 bits will be the key length until {@link self::setKey() setKey()}
* is called, again, at which point, it'll be recalculated. * is called, again, at which point, it'll be recalculated.
* *
* Since Crypt_AES extends Crypt_Rijndael, some functions are available to be called that, in the context of AES, don't * Since \phpseclib\Crypt\AES extends \phpseclib\Crypt\Rijndael, some functions are available to be called that, in the context of AES, don't
* make a whole lot of sense. {@link Crypt_AES::setBlockLength() setBlockLength()}, for instance. Calling that function, * make a whole lot of sense. {@link self::setBlockLength() setBlockLength()}, for instance. Calling that function,
* however possible, won't do anything (AES has a fixed block length whereas Rijndael has a variable one). * however possible, won't do anything (AES has a fixed block length whereas Rijndael has a variable one).
* *
* Here's a short example of how to use this library: * Here's a short example of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'Crypt/AES.php'; * include 'vendor/autoload.php';
* *
* $aes = new Crypt_AES(); * $aes = new \phpseclib\Crypt\AES();
* *
* $aes->setKey('abcdefghijklmnop'); * $aes->setKey('abcdefghijklmnop');
* *
@ -35,118 +39,33 @@
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category Crypt * @category Crypt
* @package Crypt_AES * @package AES
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2008 Jim Wigginton * @copyright 2008 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
/** namespace phpseclib\Crypt;
* Include Crypt_Rijndael
*/
if (!class_exists('Crypt_Rijndael')) {
include_once 'Rijndael.php';
}
/**#@+
* @access public
* @see Crypt_AES::encrypt()
* @see Crypt_AES::decrypt()
*/
/**
* Encrypt / decrypt using the Counter mode.
*
* Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
*/
define('CRYPT_AES_MODE_CTR', CRYPT_MODE_CTR);
/**
* Encrypt / decrypt using the Electronic Code Book mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
*/
define('CRYPT_AES_MODE_ECB', CRYPT_MODE_ECB);
/**
* Encrypt / decrypt using the Code Book Chaining mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
*/
define('CRYPT_AES_MODE_CBC', CRYPT_MODE_CBC);
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
*/
define('CRYPT_AES_MODE_CFB', CRYPT_MODE_CFB);
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
*/
define('CRYPT_AES_MODE_OFB', CRYPT_MODE_OFB);
/**#@-*/
/**#@+
* @access private
* @see Crypt_Base::Crypt_Base()
*/
/**
* Toggles the internal implementation
*/
define('CRYPT_AES_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
/**
* Toggles the mcrypt implementation
*/
define('CRYPT_AES_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
/**#@-*/
/** /**
* Pure-PHP implementation of AES. * Pure-PHP implementation of AES.
* *
* @package Crypt_AES * @package AES
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @access public * @access public
*/ */
class Crypt_AES extends Crypt_Rijndael class AES extends Rijndael
{ {
/**
* The namespace used by the cipher for its constants.
*
* @see Crypt_Base::const_namespace
* @var String
* @access private
*/
var $const_namespace = 'AES';
/** /**
* Dummy function * Dummy function
* *
* Since Crypt_AES extends Crypt_Rijndael, this function is, technically, available, but it doesn't do anything. * Since \phpseclib\Crypt\AES extends \phpseclib\Crypt\Rijndael, this function is, technically, available, but it doesn't do anything.
* *
* @see Crypt_Rijndael::setBlockLength() * @see \phpseclib\Crypt\Rijndael::setBlockLength()
* @access public * @access public
* @param Integer $length * @param int $length
*/ */
function setBlockLength($length) function setBlockLength($length)
{ {
@ -159,9 +78,9 @@ class Crypt_AES extends Crypt_Rijndael
* Valid key lengths are 128, 192, and 256. If the length is less than 128, it will be rounded up to * Valid key lengths are 128, 192, and 256. If the length is less than 128, it will be rounded up to
* 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount. * 128. If the length is greater than 128 and invalid, it will be rounded down to the closest valid amount.
* *
* @see Crypt_Rijndael:setKeyLength() * @see \phpseclib\Crypt\Rijndael:setKeyLength()
* @access public * @access public
* @param Integer $length * @param int $length
*/ */
function setKeyLength($length) function setKeyLength($length)
{ {
@ -180,10 +99,10 @@ class Crypt_AES extends Crypt_Rijndael
* *
* Rijndael supports five different key lengths, AES only supports three. * Rijndael supports five different key lengths, AES only supports three.
* *
* @see Crypt_Rijndael:setKey() * @see \phpseclib\Crypt\Rijndael:setKey()
* @see setKeyLength() * @see setKeyLength()
* @access public * @access public
* @param String $key * @param string $key
*/ */
function setKey($key) function setKey($key)
{ {
@ -193,15 +112,15 @@ class Crypt_AES extends Crypt_Rijndael
$length = strlen($key); $length = strlen($key);
switch (true) { switch (true) {
case $length <= 16: case $length <= 16:
$this->key_size = 16; $this->key_length = 16;
break; break;
case $length <= 24: case $length <= 24:
$this->key_size = 24; $this->key_length = 24;
break; break;
default: default:
$this->key_size = 32; $this->key_length = 32;
} }
$this->_setupEngine(); $this->_setEngine();
} }
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -5,7 +5,7 @@
* *
* Uses mcrypt, if available, and an internal implementation, otherwise. * Uses mcrypt, if available, and an internal implementation, otherwise.
* *
* PHP versions 4 and 5 * PHP version 5
* *
* Useful resources are as follows: * Useful resources are as follows:
* *
@ -14,9 +14,9 @@
* Here's a short example of how to use this library: * Here's a short example of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'Crypt/Blowfish.php'; * include 'vendor/autoload.php';
* *
* $blowfish = new Crypt_Blowfish(); * $blowfish = new \phpseclib\Crypt\Blowfish();
* *
* $blowfish->setKey('12345678901234567890123456789012'); * $blowfish->setKey('12345678901234567890123456789012');
* *
@ -26,26 +26,8 @@
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category Crypt * @category Crypt
* @package Crypt_Blowfish * @package Blowfish
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @author Hans-Juergen Petrich <petrich@tronic-media.com> * @author Hans-Juergen Petrich <petrich@tronic-media.com>
* @copyright 2007 Jim Wigginton * @copyright 2007 Jim Wigginton
@ -53,111 +35,32 @@
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
/** namespace phpseclib\Crypt;
* Include Crypt_Base
*
* Base cipher class
*/
if (!class_exists('Crypt_Base')) {
include_once 'Base.php';
}
/**#@+
* @access public
* @see Crypt_Blowfish::encrypt()
* @see Crypt_Blowfish::decrypt()
*/
/**
* Encrypt / decrypt using the Counter mode.
*
* Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
*/
define('CRYPT_BLOWFISH_MODE_CTR', CRYPT_MODE_CTR);
/**
* Encrypt / decrypt using the Electronic Code Book mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
*/
define('CRYPT_BLOWFISH_MODE_ECB', CRYPT_MODE_ECB);
/**
* Encrypt / decrypt using the Code Book Chaining mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
*/
define('CRYPT_BLOWFISH_MODE_CBC', CRYPT_MODE_CBC);
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
*/
define('CRYPT_BLOWFISH_MODE_CFB', CRYPT_MODE_CFB);
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
*/
define('CRYPT_BLOWFISH_MODE_OFB', CRYPT_MODE_OFB);
/**#@-*/
/**#@+
* @access private
* @see Crypt_Base::Crypt_Base()
*/
/**
* Toggles the internal implementation
*/
define('CRYPT_BLOWFISH_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
/**
* Toggles the mcrypt implementation
*/
define('CRYPT_BLOWFISH_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
/**#@-*/
/** /**
* Pure-PHP implementation of Blowfish. * Pure-PHP implementation of Blowfish.
* *
* @package Crypt_Blowfish * @package Blowfish
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @author Hans-Juergen Petrich <petrich@tronic-media.com> * @author Hans-Juergen Petrich <petrich@tronic-media.com>
* @access public * @access public
*/ */
class Crypt_Blowfish extends Crypt_Base class Blowfish extends Base
{ {
/** /**
* Block Length of the cipher * Block Length of the cipher
* *
* @see Crypt_Base::block_size * @see \phpseclib\Crypt\Base::block_size
* @var Integer * @var int
* @access private * @access private
*/ */
var $block_size = 8; var $block_size = 8;
/**
* The default password key_size used by setPassword()
*
* @see Crypt_Base::password_key_size
* @see Crypt_Base::setPassword()
* @var Integer
* @access private
*/
var $password_key_size = 56;
/**
* The namespace used by the cipher for its constants.
*
* @see Crypt_Base::const_namespace
* @var String
* @access private
*/
var $const_namespace = 'BLOWFISH';
/** /**
* The mcrypt specific name of the cipher * The mcrypt specific name of the cipher
* *
* @see Crypt_Base::cipher_name_mcrypt * @see \phpseclib\Crypt\Base::cipher_name_mcrypt
* @var String * @var string
* @access private * @access private
*/ */
var $cipher_name_mcrypt = 'blowfish'; var $cipher_name_mcrypt = 'blowfish';
@ -165,8 +68,8 @@ class Crypt_Blowfish extends Crypt_Base
/** /**
* Optimizing value while CFB-encrypting * Optimizing value while CFB-encrypting
* *
* @see Crypt_Base::cfb_init_len * @see \phpseclib\Crypt\Base::cfb_init_len
* @var Integer * @var int
* @access private * @access private
*/ */
var $cfb_init_len = 500; var $cfb_init_len = 500;
@ -174,12 +77,12 @@ class Crypt_Blowfish extends Crypt_Base
/** /**
* The fixed subkeys boxes ($sbox0 - $sbox3) with 256 entries each * The fixed subkeys boxes ($sbox0 - $sbox3) with 256 entries each
* *
* S-Box 1 * S-Box 0
* *
* @access private * @access private
* @var array * @var array
*/ */
var $sbox0 = array ( var $sbox0 = array(
0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99, 0xd1310ba6, 0x98dfb5ac, 0x2ffd72db, 0xd01adfb7, 0xb8e1afed, 0x6a267e96, 0xba7c9045, 0xf12c7f99,
0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e, 0x24a19947, 0xb3916cf7, 0x0801f2e2, 0x858efc16, 0x636920d8, 0x71574e69, 0xa458fea3, 0xf4933d7e,
0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013, 0x0d95748f, 0x728eb658, 0x718bcd58, 0x82154aee, 0x7b54a41d, 0xc25a59b5, 0x9c30d539, 0x2af26013,
@ -340,7 +243,7 @@ class Crypt_Blowfish extends Crypt_Base
/** /**
* P-Array consists of 18 32-bit subkeys * P-Array consists of 18 32-bit subkeys
* *
* @var array $parray * @var array
* @access private * @access private
*/ */
var $parray = array( var $parray = array(
@ -354,7 +257,7 @@ class Crypt_Blowfish extends Crypt_Base
* *
* Holds the expanded key [p] and the key-depended s-boxes [sb] * Holds the expanded key [p] and the key-depended s-boxes [sb]
* *
* @var array $bctx * @var array
* @access private * @access private
*/ */
var $bctx; var $bctx;
@ -362,43 +265,72 @@ class Crypt_Blowfish extends Crypt_Base
/** /**
* Holds the last used key * Holds the last used key
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $kl; var $kl;
/** /**
* Sets the key. * The Key Length (in bytes)
* *
* Keys can be of any length. Blowfish, itself, requires the use of a key between 32 and max. 448-bits long. * @see \phpseclib\Crypt\Base::setKeyLength()
* If the key is less than 32-bits we NOT fill the key to 32bit but let the key as it is to be compatible * @var int
* with mcrypt because mcrypt act this way with blowfish key's < 32 bits. * @access private
* @internal The max value is 256 / 8 = 32, the min value is 128 / 8 = 16. Exists in conjunction with $Nk
* because the encryption / decryption / key schedule creation requires this number and not $key_length. We could
* derive this from $key_length or vice versa, but that'd mean we'd have to do multiple shift operations, so in lieu
* of that, we'll just precompute it once.
*/
var $key_length = 16;
/**
* Sets the key length.
* *
* If the key is more than 448-bits, we trim the excess bits. * Key lengths can be between 32 and 448 bits.
*
* If the key is not explicitly set, or empty, it'll be assumed a 128 bits key to be all null bytes.
* *
* @access public * @access public
* @see Crypt_Base::setKey() * @param int $length
* @param String $key
*/ */
function setKey($key) function setKeyLength($length)
{ {
$keylength = strlen($key); if ($length < 32) {
$this->key_length = 7;
if (!$keylength) { } elseif ($length > 448) {
$key = "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"; $this->key_length = 56;
} elseif ($keylength > 56) { } else {
$key = substr($key, 0, 56); $this->key_length = $length >> 3;
} }
parent::setKey($key); parent::setKeyLength($length);
}
/**
* Test for engine validity
*
* This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine()
*
* @see \phpseclib\Crypt\Base::isValidEngine()
* @param int $engine
* @access public
* @return bool
*/
function isValidEngine($engine)
{
if ($engine == self::ENGINE_OPENSSL) {
if ($this->key_length != 16) {
return false;
}
$this->cipher_name_openssl_ecb = 'bf-ecb';
$this->cipher_name_openssl = 'bf-' . $this->_openssl_translate_mode();
}
return parent::isValidEngine($engine);
} }
/** /**
* Setup the key (expansion) * Setup the key (expansion)
* *
* @see Crypt_Base::_setupKey() * @see \phpseclib\Crypt\Base::_setupKey()
* @access private * @access private
*/ */
function _setupKey() function _setupKey()
@ -455,8 +387,8 @@ class Crypt_Blowfish extends Crypt_Base
* Encrypts a block * Encrypts a block
* *
* @access private * @access private
* @param String $in * @param string $in
* @return String * @return string
*/ */
function _encryptBlock($in) function _encryptBlock($in)
{ {
@ -491,8 +423,8 @@ class Crypt_Blowfish extends Crypt_Base
* Decrypts a block * Decrypts a block
* *
* @access private * @access private
* @param String $in * @param string $in
* @return String * @return string
*/ */
function _decryptBlock($in) function _decryptBlock($in)
{ {
@ -519,30 +451,28 @@ class Crypt_Blowfish extends Crypt_Base
$sb_2[$r >> 8 & 0xff]) + $sb_2[$r >> 8 & 0xff]) +
$sb_3[$r & 0xff]; $sb_3[$r & 0xff];
} }
return pack("N*", $r ^ $p[0], $l ^ $p[1]); return pack("N*", $r ^ $p[0], $l ^ $p[1]);
} }
/** /**
* Setup the performance-optimized function for de/encrypt() * Setup the performance-optimized function for de/encrypt()
* *
* @see Crypt_Base::_setupInlineCrypt() * @see \phpseclib\Crypt\Base::_setupInlineCrypt()
* @access private * @access private
*/ */
function _setupInlineCrypt() function _setupInlineCrypt()
{ {
$lambda_functions =& Crypt_Blowfish::_getLambdaFunctions(); $lambda_functions =& self::_getLambdaFunctions();
// We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function. // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function.
// (Currently, for Blowfish, one generated $lambda_function cost on php5.5@32bit ~100kb unfreeable mem and ~180kb on php5.5@64bit)
// After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one. // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one.
$gen_hi_opt_code = (bool)( count($lambda_functions) < 10); $gen_hi_opt_code = (bool)(count($lambda_functions) < 10);
switch (true) { // Generation of a unique hash for our generated code
case $gen_hi_opt_code:
$code_hash = md5(str_pad("Crypt_Blowfish, {$this->mode}, ", 32, "\0") . $this->key);
break;
default:
$code_hash = "Crypt_Blowfish, {$this->mode}"; $code_hash = "Crypt_Blowfish, {$this->mode}";
if ($gen_hi_opt_code) {
$code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key);
} }
if (!isset($lambda_functions[$code_hash])) { if (!isset($lambda_functions[$code_hash])) {

View file

@ -5,7 +5,7 @@
* *
* Uses mcrypt, if available, and an internal implementation, otherwise. * Uses mcrypt, if available, and an internal implementation, otherwise.
* *
* PHP versions 4 and 5 * PHP version 5
* *
* Useful resources are as follows: * Useful resources are as follows:
* *
@ -16,9 +16,9 @@
* Here's a short example of how to use this library: * Here's a short example of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'Crypt/DES.php'; * include 'vendor/autoload.php';
* *
* $des = new Crypt_DES(); * $des = new \phpseclib\Crypt\DES();
* *
* $des->setKey('abcdefgh'); * $des->setKey('abcdefgh');
* *
@ -32,170 +32,87 @@
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category Crypt * @category Crypt
* @package Crypt_DES * @package DES
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2007 Jim Wigginton * @copyright 2007 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
/** namespace phpseclib\Crypt;
* Include Crypt_Base
*
* Base cipher class
*/
if (!class_exists('Crypt_Base')) {
include_once 'Base.php';
}
/**#@+
* @access private
* @see Crypt_DES::_setupKey()
* @see Crypt_DES::_processBlock()
*/
/**
* Contains $keys[CRYPT_DES_ENCRYPT]
*/
define('CRYPT_DES_ENCRYPT', 0);
/**
* Contains $keys[CRYPT_DES_DECRYPT]
*/
define('CRYPT_DES_DECRYPT', 1);
/**#@-*/
/**#@+
* @access public
* @see Crypt_DES::encrypt()
* @see Crypt_DES::decrypt()
*/
/**
* Encrypt / decrypt using the Counter mode.
*
* Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
*/
define('CRYPT_DES_MODE_CTR', CRYPT_MODE_CTR);
/**
* Encrypt / decrypt using the Electronic Code Book mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
*/
define('CRYPT_DES_MODE_ECB', CRYPT_MODE_ECB);
/**
* Encrypt / decrypt using the Code Book Chaining mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
*/
define('CRYPT_DES_MODE_CBC', CRYPT_MODE_CBC);
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
*/
define('CRYPT_DES_MODE_CFB', CRYPT_MODE_CFB);
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
*/
define('CRYPT_DES_MODE_OFB', CRYPT_MODE_OFB);
/**#@-*/
/**#@+
* @access private
* @see Crypt_Base::Crypt_Base()
*/
/**
* Toggles the internal implementation
*/
define('CRYPT_DES_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
/**
* Toggles the mcrypt implementation
*/
define('CRYPT_DES_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
/**#@-*/
/** /**
* Pure-PHP implementation of DES. * Pure-PHP implementation of DES.
* *
* @package Crypt_DES * @package DES
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @access public * @access public
*/ */
class Crypt_DES extends Crypt_Base class DES extends Base
{ {
/**#@+
* @access private
* @see \phpseclib\Crypt\DES::_setupKey()
* @see \phpseclib\Crypt\DES::_processBlock()
*/
/**
* Contains $keys[self::ENCRYPT]
*/
const ENCRYPT = 0;
/**
* Contains $keys[self::DECRYPT]
*/
const DECRYPT = 1;
/**#@-*/
/** /**
* Block Length of the cipher * Block Length of the cipher
* *
* @see Crypt_Base::block_size * @see \phpseclib\Crypt\Base::block_size
* @var Integer * @var int
* @access private * @access private
*/ */
var $block_size = 8; var $block_size = 8;
/** /**
* The Key * Key Length (in bytes)
* *
* @see Crypt_Base::key * @see \phpseclib\Crypt\Base::setKeyLength()
* @see setKey() * @var int
* @var String
* @access private * @access private
*/ */
var $key = "\0\0\0\0\0\0\0\0"; var $key_length = 8;
/**
* The default password key_size used by setPassword()
*
* @see Crypt_Base::password_key_size
* @see Crypt_Base::setPassword()
* @var Integer
* @access private
*/
var $password_key_size = 8;
/**
* The namespace used by the cipher for its constants.
*
* @see Crypt_Base::const_namespace
* @var String
* @access private
*/
var $const_namespace = 'DES';
/** /**
* The mcrypt specific name of the cipher * The mcrypt specific name of the cipher
* *
* @see Crypt_Base::cipher_name_mcrypt * @see \phpseclib\Crypt\Base::cipher_name_mcrypt
* @var String * @var string
* @access private * @access private
*/ */
var $cipher_name_mcrypt = 'des'; var $cipher_name_mcrypt = 'des';
/**
* The OpenSSL names of the cipher / modes
*
* @see \phpseclib\Crypt\Base::openssl_mode_names
* @var array
* @access private
*/
var $openssl_mode_names = array(
self::MODE_ECB => 'des-ecb',
self::MODE_CBC => 'des-cbc',
self::MODE_CFB => 'des-cfb',
self::MODE_OFB => 'des-ofb'
// self::MODE_CTR is undefined for DES
);
/** /**
* Optimizing value while CFB-encrypting * Optimizing value while CFB-encrypting
* *
* @see Crypt_Base::cfb_init_len * @see \phpseclib\Crypt\Base::cfb_init_len
* @var Integer * @var int
* @access private * @access private
*/ */
var $cfb_init_len = 500; var $cfb_init_len = 500;
@ -203,11 +120,11 @@ class Crypt_DES extends Crypt_Base
/** /**
* Switch for DES/3DES encryption * Switch for DES/3DES encryption
* *
* Used only if $engine == CRYPT_DES_MODE_INTERNAL * Used only if $engine == self::ENGINE_INTERNAL
* *
* @see Crypt_DES::_setupKey() * @see self::_setupKey()
* @see Crypt_DES::_processBlock() * @see self::_processBlock()
* @var Integer * @var int
* @access private * @access private
*/ */
var $des_rounds = 1; var $des_rounds = 1;
@ -215,17 +132,17 @@ class Crypt_DES extends Crypt_Base
/** /**
* max possible size of $key * max possible size of $key
* *
* @see Crypt_DES::setKey() * @see self::setKey()
* @var String * @var string
* @access private * @access private
*/ */
var $key_size_max = 8; var $key_length_max = 8;
/** /**
* The Key Schedule * The Key Schedule
* *
* @see Crypt_DES::_setupKey() * @see self::_setupKey()
* @var Array * @var array
* @access private * @access private
*/ */
var $keys; var $keys;
@ -237,9 +154,9 @@ class Crypt_DES extends Crypt_Base
* with each byte containing all bits in the same state as the * with each byte containing all bits in the same state as the
* corresponding bit in the index value. * corresponding bit in the index value.
* *
* @see Crypt_DES::_processBlock() * @see self::_processBlock()
* @see Crypt_DES::_setupKey() * @see self::_setupKey()
* @var Array * @var array
* @access private * @access private
*/ */
var $shuffle = array( var $shuffle = array(
@ -378,7 +295,7 @@ class Crypt_DES extends Crypt_Base
* *
* Indexing this table with each source byte performs the initial bit permutation. * Indexing this table with each source byte performs the initial bit permutation.
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $ipmap = array( var $ipmap = array(
@ -420,7 +337,7 @@ class Crypt_DES extends Crypt_Base
* Inverse IP mapping helper table. * Inverse IP mapping helper table.
* Indexing this table with a byte value reverses the bit order. * Indexing this table with a byte value reverses the bit order.
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $invipmap = array( var $invipmap = array(
@ -464,7 +381,7 @@ class Crypt_DES extends Crypt_Base
* Each box ($sbox1-$sbox8) has been vectorized, then each value pre-permuted using the * Each box ($sbox1-$sbox8) has been vectorized, then each value pre-permuted using the
* P table: concatenation can then be replaced by exclusive ORs. * P table: concatenation can then be replaced by exclusive ORs.
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $sbox1 = array( var $sbox1 = array(
@ -489,7 +406,7 @@ class Crypt_DES extends Crypt_Base
/** /**
* Pre-permuted S-box2 * Pre-permuted S-box2
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $sbox2 = array( var $sbox2 = array(
@ -514,7 +431,7 @@ class Crypt_DES extends Crypt_Base
/** /**
* Pre-permuted S-box3 * Pre-permuted S-box3
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $sbox3 = array( var $sbox3 = array(
@ -539,7 +456,7 @@ class Crypt_DES extends Crypt_Base
/** /**
* Pre-permuted S-box4 * Pre-permuted S-box4
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $sbox4 = array( var $sbox4 = array(
@ -564,7 +481,7 @@ class Crypt_DES extends Crypt_Base
/** /**
* Pre-permuted S-box5 * Pre-permuted S-box5
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $sbox5 = array( var $sbox5 = array(
@ -589,7 +506,7 @@ class Crypt_DES extends Crypt_Base
/** /**
* Pre-permuted S-box6 * Pre-permuted S-box6
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $sbox6 = array( var $sbox6 = array(
@ -614,7 +531,7 @@ class Crypt_DES extends Crypt_Base
/** /**
* Pre-permuted S-box7 * Pre-permuted S-box7
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $sbox7 = array( var $sbox7 = array(
@ -639,7 +556,7 @@ class Crypt_DES extends Crypt_Base
/** /**
* Pre-permuted S-box8 * Pre-permuted S-box8
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $sbox8 = array( var $sbox8 = array(
@ -661,6 +578,28 @@ class Crypt_DES extends Crypt_Base
0x00000820, 0x00020020, 0x08000000, 0x08020800 0x00000820, 0x00020020, 0x08000000, 0x08020800
); );
/**
* Test for engine validity
*
* This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine()
*
* @see \phpseclib\Crypt\Base::isValidEngine()
* @param int $engine
* @access public
* @return bool
*/
function isValidEngine($engine)
{
if ($this->key_length_max == 8) {
if ($engine == self::ENGINE_OPENSSL) {
$this->cipher_name_openssl_ecb = 'des-ecb';
$this->cipher_name_openssl = 'des-' . $this->_openssl_translate_mode();
}
}
return parent::isValidEngine($engine);
}
/** /**
* Sets the key. * Sets the key.
* *
@ -672,16 +611,16 @@ class Crypt_DES extends Crypt_Base
* *
* If the key is not explicitly set, it'll be assumed to be all zero's. * If the key is not explicitly set, it'll be assumed to be all zero's.
* *
* @see Crypt_Base::setKey() * @see \phpseclib\Crypt\Base::setKey()
* @access public * @access public
* @param String $key * @param string $key
*/ */
function setKey($key) function setKey($key)
{ {
// We check/cut here only up to max length of the key. // We check/cut here only up to max length of the key.
// Key padding to the proper length will be done in _setupKey() // Key padding to the proper length will be done in _setupKey()
if (strlen($key) > $this->key_size_max) { if (strlen($key) > $this->key_length_max) {
$key = substr($key, 0, $this->key_size_max); $key = substr($key, 0, $this->key_length_max);
} }
// Sets the key // Sets the key
@ -691,46 +630,46 @@ class Crypt_DES extends Crypt_Base
/** /**
* Encrypts a block * Encrypts a block
* *
* @see Crypt_Base::_encryptBlock() * @see \phpseclib\Crypt\Base::_encryptBlock()
* @see Crypt_Base::encrypt() * @see \phpseclib\Crypt\Base::encrypt()
* @see Crypt_DES::encrypt() * @see self::encrypt()
* @access private * @access private
* @param String $in * @param string $in
* @return String * @return string
*/ */
function _encryptBlock($in) function _encryptBlock($in)
{ {
return $this->_processBlock($in, CRYPT_DES_ENCRYPT); return $this->_processBlock($in, self::ENCRYPT);
} }
/** /**
* Decrypts a block * Decrypts a block
* *
* @see Crypt_Base::_decryptBlock() * @see \phpseclib\Crypt\Base::_decryptBlock()
* @see Crypt_Base::decrypt() * @see \phpseclib\Crypt\Base::decrypt()
* @see Crypt_DES::decrypt() * @see self::decrypt()
* @access private * @access private
* @param String $in * @param string $in
* @return String * @return string
*/ */
function _decryptBlock($in) function _decryptBlock($in)
{ {
return $this->_processBlock($in, CRYPT_DES_DECRYPT); return $this->_processBlock($in, self::DECRYPT);
} }
/** /**
* Encrypts or decrypts a 64-bit block * Encrypts or decrypts a 64-bit block
* *
* $mode should be either CRYPT_DES_ENCRYPT or CRYPT_DES_DECRYPT. See * $mode should be either self::ENCRYPT or self::DECRYPT. See
* {@link http://en.wikipedia.org/wiki/Image:Feistel.png Feistel.png} to get a general * {@link http://en.wikipedia.org/wiki/Image:Feistel.png Feistel.png} to get a general
* idea of what this function does. * idea of what this function does.
* *
* @see Crypt_DES::_encryptBlock() * @see self::_encryptBlock()
* @see Crypt_DES::_decryptBlock() * @see self::_decryptBlock()
* @access private * @access private
* @param String $block * @param string $block
* @param Integer $mode * @param int $mode
* @return String * @return string
*/ */
function _processBlock($block, $mode) function _processBlock($block, $mode)
{ {
@ -810,7 +749,7 @@ class Crypt_DES extends Crypt_Base
/** /**
* Creates the key schedule * Creates the key schedule
* *
* @see Crypt_Base::_setupKey() * @see \phpseclib\Crypt\Base::_setupKey()
* @access private * @access private
*/ */
function _setupKey() function _setupKey()
@ -1291,8 +1230,8 @@ class Crypt_DES extends Crypt_Base
$d = (($key['d'] >> 4) & 0x0FFFFFF0) | ($key['c'] & 0x0F); $d = (($key['d'] >> 4) & 0x0FFFFFF0) | ($key['c'] & 0x0F);
$keys[$des_round] = array( $keys[$des_round] = array(
CRYPT_DES_ENCRYPT => array(), self::ENCRYPT => array(),
CRYPT_DES_DECRYPT => array_fill(0, 32, 0) self::DECRYPT => array_fill(0, 32, 0)
); );
for ($i = 0, $ki = 31; $i < 16; ++$i, $ki-= 2) { for ($i = 0, $ki = 31; $i < 16; ++$i, $ki-= 2) {
$c <<= $shifts[$i]; $c <<= $shifts[$i];
@ -1311,33 +1250,33 @@ class Crypt_DES extends Crypt_Base
(($dp >> 16) & 0x0000FF00) | (($dp >> 8) & 0x000000FF); (($dp >> 16) & 0x0000FF00) | (($dp >> 8) & 0x000000FF);
$val2 = (($cp << 8) & 0xFF000000) | (($cp << 16) & 0x00FF0000) | $val2 = (($cp << 8) & 0xFF000000) | (($cp << 16) & 0x00FF0000) |
(($dp >> 8) & 0x0000FF00) | ( $dp & 0x000000FF); (($dp >> 8) & 0x0000FF00) | ( $dp & 0x000000FF);
$keys[$des_round][CRYPT_DES_ENCRYPT][ ] = $val1; $keys[$des_round][self::ENCRYPT][ ] = $val1;
$keys[$des_round][CRYPT_DES_DECRYPT][$ki - 1] = $val1; $keys[$des_round][self::DECRYPT][$ki - 1] = $val1;
$keys[$des_round][CRYPT_DES_ENCRYPT][ ] = $val2; $keys[$des_round][self::ENCRYPT][ ] = $val2;
$keys[$des_round][CRYPT_DES_DECRYPT][$ki ] = $val2; $keys[$des_round][self::DECRYPT][$ki ] = $val2;
} }
} }
switch ($this->des_rounds) { switch ($this->des_rounds) {
case 3: // 3DES keys case 3: // 3DES keys
$this->keys = array( $this->keys = array(
CRYPT_DES_ENCRYPT => array_merge( self::ENCRYPT => array_merge(
$keys[0][CRYPT_DES_ENCRYPT], $keys[0][self::ENCRYPT],
$keys[1][CRYPT_DES_DECRYPT], $keys[1][self::DECRYPT],
$keys[2][CRYPT_DES_ENCRYPT] $keys[2][self::ENCRYPT]
), ),
CRYPT_DES_DECRYPT => array_merge( self::DECRYPT => array_merge(
$keys[2][CRYPT_DES_DECRYPT], $keys[2][self::DECRYPT],
$keys[1][CRYPT_DES_ENCRYPT], $keys[1][self::ENCRYPT],
$keys[0][CRYPT_DES_DECRYPT] $keys[0][self::DECRYPT]
) )
); );
break; break;
// case 1: // DES keys // case 1: // DES keys
default: default:
$this->keys = array( $this->keys = array(
CRYPT_DES_ENCRYPT => $keys[0][CRYPT_DES_ENCRYPT], self::ENCRYPT => $keys[0][self::ENCRYPT],
CRYPT_DES_DECRYPT => $keys[0][CRYPT_DES_DECRYPT] self::DECRYPT => $keys[0][self::DECRYPT]
); );
} }
} }
@ -1345,12 +1284,12 @@ class Crypt_DES extends Crypt_Base
/** /**
* Setup the performance-optimized function for de/encrypt() * Setup the performance-optimized function for de/encrypt()
* *
* @see Crypt_Base::_setupInlineCrypt() * @see \phpseclib\Crypt\Base::_setupInlineCrypt()
* @access private * @access private
*/ */
function _setupInlineCrypt() function _setupInlineCrypt()
{ {
$lambda_functions =& Crypt_DES::_getLambdaFunctions(); $lambda_functions =& self::_getLambdaFunctions();
// Engine configuration for: // Engine configuration for:
// - DES ($des_rounds == 1) or // - DES ($des_rounds == 1) or
@ -1358,21 +1297,20 @@ class Crypt_DES extends Crypt_Base
$des_rounds = $this->des_rounds; $des_rounds = $this->des_rounds;
// We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function. // We create max. 10 hi-optimized code for memory reason. Means: For each $key one ultra fast inline-crypt function.
// (Currently, for DES, one generated $lambda_function cost on php5.5@32bit ~135kb unfreeable mem and ~230kb on php5.5@64bit)
// (Currently, for TripleDES, one generated $lambda_function cost on php5.5@32bit ~240kb unfreeable mem and ~340kb on php5.5@64bit)
// After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one // After that, we'll still create very fast optimized code but not the hi-ultimative code, for each $mode one
$gen_hi_opt_code = (bool)( count($lambda_functions) < 10 ); $gen_hi_opt_code = (bool)( count($lambda_functions) < 10 );
// Generation of a uniqe hash for our generated code // Generation of a unique hash for our generated code
switch (true) { $code_hash = "Crypt_DES, $des_rounds, {$this->mode}";
case $gen_hi_opt_code: if ($gen_hi_opt_code) {
// For hi-optimized code, we create for each combination of // For hi-optimized code, we create for each combination of
// $mode, $des_rounds and $this->key its own encrypt/decrypt function. // $mode, $des_rounds and $this->key its own encrypt/decrypt function.
$code_hash = md5(str_pad("Crypt_DES, $des_rounds, {$this->mode}, ", 32, "\0") . $this->key);
break;
default:
// After max 10 hi-optimized functions, we create generic // After max 10 hi-optimized functions, we create generic
// (still very fast.. but not ultra) functions for each $mode/$des_rounds // (still very fast.. but not ultra) functions for each $mode/$des_rounds
// Currently 2 * 5 generic functions will be then max. possible. // Currently 2 * 5 generic functions will be then max. possible.
$code_hash = "Crypt_DES, $des_rounds, {$this->mode}"; $code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key);
} }
// Is there a re-usable $lambda_functions in there? If not, we have to create it. // Is there a re-usable $lambda_functions in there? If not, we have to create it.
@ -1402,8 +1340,8 @@ class Crypt_DES extends Crypt_Base
// No futher initialisation of the $keys schedule is necessary. // No futher initialisation of the $keys schedule is necessary.
// That is the extra performance boost. // That is the extra performance boost.
$k = array( $k = array(
CRYPT_DES_ENCRYPT => $this->keys[CRYPT_DES_ENCRYPT], self::ENCRYPT => $this->keys[self::ENCRYPT],
CRYPT_DES_DECRYPT => $this->keys[CRYPT_DES_DECRYPT] self::DECRYPT => $this->keys[self::DECRYPT]
); );
$init_encrypt = ''; $init_encrypt = '';
$init_decrypt = ''; $init_decrypt = '';
@ -1412,22 +1350,21 @@ class Crypt_DES extends Crypt_Base
// In generic optimized code mode, we have to use, as the best compromise [currently], // In generic optimized code mode, we have to use, as the best compromise [currently],
// our key schedule as $ke/$kd arrays. (with hardcoded indexes...) // our key schedule as $ke/$kd arrays. (with hardcoded indexes...)
$k = array( $k = array(
CRYPT_DES_ENCRYPT => array(), self::ENCRYPT => array(),
CRYPT_DES_DECRYPT => array() self::DECRYPT => array()
); );
for ($i = 0, $c = count($this->keys[CRYPT_DES_ENCRYPT]); $i < $c; ++$i) { for ($i = 0, $c = count($this->keys[self::ENCRYPT]); $i < $c; ++$i) {
$k[CRYPT_DES_ENCRYPT][$i] = '$ke[' . $i . ']'; $k[self::ENCRYPT][$i] = '$ke[' . $i . ']';
$k[CRYPT_DES_DECRYPT][$i] = '$kd[' . $i . ']'; $k[self::DECRYPT][$i] = '$kd[' . $i . ']';
} }
$init_encrypt = '$ke = $self->keys[CRYPT_DES_ENCRYPT];'; $init_encrypt = '$ke = $self->keys[self::ENCRYPT];';
$init_decrypt = '$kd = $self->keys[CRYPT_DES_DECRYPT];'; $init_decrypt = '$kd = $self->keys[self::DECRYPT];';
break; break;
} }
// Creating code for en- and decryption. // Creating code for en- and decryption.
$crypt_block = array(); $crypt_block = array();
foreach (array(CRYPT_DES_ENCRYPT, CRYPT_DES_DECRYPT) as $c) { foreach (array(self::ENCRYPT, self::DECRYPT) as $c) {
/* Do the initial IP permutation. */ /* Do the initial IP permutation. */
$crypt_block[$c] = ' $crypt_block[$c] = '
$in = unpack("N*", $in); $in = unpack("N*", $in);
@ -1494,8 +1431,8 @@ class Crypt_DES extends Crypt_Base
'init_crypt' => $init_crypt, 'init_crypt' => $init_crypt,
'init_encrypt' => $init_encrypt, 'init_encrypt' => $init_encrypt,
'init_decrypt' => $init_decrypt, 'init_decrypt' => $init_decrypt,
'encrypt_block' => $crypt_block[CRYPT_DES_ENCRYPT], 'encrypt_block' => $crypt_block[self::ENCRYPT],
'decrypt_block' => $crypt_block[CRYPT_DES_DECRYPT] 'decrypt_block' => $crypt_block[self::DECRYPT]
) )
); );
} }

View file

@ -7,10 +7,10 @@
* *
* md2, md5, md5-96, sha1, sha1-96, sha256, sha256-96, sha384, and sha512, sha512-96 * md2, md5, md5-96, sha1, sha1-96, sha256, sha256-96, sha384, and sha512, sha512-96
* *
* If {@link Crypt_Hash::setKey() setKey()} is called, {@link Crypt_Hash::hash() hash()} will return the HMAC as opposed to * If {@link self::setKey() setKey()} is called, {@link self::hash() hash()} will return the HMAC as opposed to
* the hash. If no valid algorithm is provided, sha1 will be used. * the hash. If no valid algorithm is provided, sha1 will be used.
* *
* PHP versions 4 and 5 * PHP version 5
* *
* {@internal The variable names are the same as those in * {@internal The variable names are the same as those in
* {@link http://tools.ietf.org/html/rfc2104#section-2 RFC2104}.}} * {@link http://tools.ietf.org/html/rfc2104#section-2 RFC2104}.}}
@ -18,9 +18,9 @@
* Here's a short example of how to use this library: * Here's a short example of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'Crypt/Hash.php'; * include 'vendor/autoload.php';
* *
* $hash = new Crypt_Hash('sha1'); * $hash = new \phpseclib\Crypt\Hash('sha1');
* *
* $hash->setKey('abcdefg'); * $hash->setKey('abcdefg');
* *
@ -28,64 +28,50 @@
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category Crypt * @category Crypt
* @package Crypt_Hash * @package Hash
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2007 Jim Wigginton * @copyright 2007 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
/**#@+ namespace phpseclib\Crypt;
* @access private
* @see Crypt_Hash::Crypt_Hash() use phpseclib\Math\BigInteger;
*/
/**
* Toggles the internal implementation
*/
define('CRYPT_HASH_MODE_INTERNAL', 1);
/**
* Toggles the mhash() implementation, which has been deprecated on PHP 5.3.0+.
*/
define('CRYPT_HASH_MODE_MHASH', 2);
/**
* Toggles the hash() implementation, which works on PHP 5.1.2+.
*/
define('CRYPT_HASH_MODE_HASH', 3);
/**#@-*/
/** /**
* Pure-PHP implementations of keyed-hash message authentication codes (HMACs) and various cryptographic hashing functions. * Pure-PHP implementations of keyed-hash message authentication codes (HMACs) and various cryptographic hashing functions.
* *
* @package Crypt_Hash * @package Hash
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @access public * @access public
*/ */
class Crypt_Hash class Hash
{ {
/**#@+
* @access private
* @see \phpseclib\Crypt\Hash::__construct()
*/
/**
* Toggles the internal implementation
*/
const MODE_INTERNAL = 1;
/**
* Toggles the mhash() implementation, which has been deprecated on PHP 5.3.0+.
*/
const MODE_MHASH = 2;
/**
* Toggles the hash() implementation, which works on PHP 5.1.2+.
*/
const MODE_HASH = 3;
/**#@-*/
/** /**
* Hash Parameter * Hash Parameter
* *
* @see Crypt_Hash::setHash() * @see self::setHash()
* @var Integer * @var int
* @access private * @access private
*/ */
var $hashParam; var $hashParam;
@ -93,8 +79,8 @@ class Crypt_Hash
/** /**
* Byte-length of compression blocks / key (Internal HMAC) * Byte-length of compression blocks / key (Internal HMAC)
* *
* @see Crypt_Hash::setAlgorithm() * @see self::setAlgorithm()
* @var Integer * @var int
* @access private * @access private
*/ */
var $b; var $b;
@ -102,8 +88,8 @@ class Crypt_Hash
/** /**
* Byte-length of hash output (Internal HMAC) * Byte-length of hash output (Internal HMAC)
* *
* @see Crypt_Hash::setHash() * @see self::setHash()
* @var Integer * @var int
* @access private * @access private
*/ */
var $l = false; var $l = false;
@ -111,8 +97,8 @@ class Crypt_Hash
/** /**
* Hash Algorithm * Hash Algorithm
* *
* @see Crypt_Hash::setHash() * @see self::setHash()
* @var String * @var string
* @access private * @access private
*/ */
var $hash; var $hash;
@ -120,8 +106,8 @@ class Crypt_Hash
/** /**
* Key * Key
* *
* @see Crypt_Hash::setKey() * @see self::setKey()
* @var String * @var string
* @access private * @access private
*/ */
var $key = false; var $key = false;
@ -129,8 +115,8 @@ class Crypt_Hash
/** /**
* Outer XOR (Internal HMAC) * Outer XOR (Internal HMAC)
* *
* @see Crypt_Hash::setKey() * @see self::setKey()
* @var String * @var string
* @access private * @access private
*/ */
var $opad; var $opad;
@ -138,8 +124,8 @@ class Crypt_Hash
/** /**
* Inner XOR (Internal HMAC) * Inner XOR (Internal HMAC)
* *
* @see Crypt_Hash::setKey() * @see self::setKey()
* @var String * @var string
* @access private * @access private
*/ */
var $ipad; var $ipad;
@ -147,22 +133,22 @@ class Crypt_Hash
/** /**
* Default Constructor. * Default Constructor.
* *
* @param optional String $hash * @param string $hash
* @return Crypt_Hash * @return \phpseclib\Crypt\Hash
* @access public * @access public
*/ */
function Crypt_Hash($hash = 'sha1') function __construct($hash = 'sha1')
{ {
if ( !defined('CRYPT_HASH_MODE') ) { if (!defined('CRYPT_HASH_MODE')) {
switch (true) { switch (true) {
case extension_loaded('hash'): case extension_loaded('hash'):
define('CRYPT_HASH_MODE', CRYPT_HASH_MODE_HASH); define('CRYPT_HASH_MODE', self::MODE_HASH);
break; break;
case extension_loaded('mhash'): case extension_loaded('mhash'):
define('CRYPT_HASH_MODE', CRYPT_HASH_MODE_MHASH); define('CRYPT_HASH_MODE', self::MODE_MHASH);
break; break;
default: default:
define('CRYPT_HASH_MODE', CRYPT_HASH_MODE_INTERNAL); define('CRYPT_HASH_MODE', self::MODE_INTERNAL);
} }
} }
@ -175,7 +161,7 @@ class Crypt_Hash
* Keys can be of any length. * Keys can be of any length.
* *
* @access public * @access public
* @param optional String $key * @param string $key
*/ */
function setKey($key = false) function setKey($key = false)
{ {
@ -188,7 +174,7 @@ class Crypt_Hash
* As set by the constructor or by the setHash() method. * As set by the constructor or by the setHash() method.
* *
* @access public * @access public
* @return String * @return string
*/ */
function getHash() function getHash()
{ {
@ -199,7 +185,7 @@ class Crypt_Hash
* Sets the hash function. * Sets the hash function.
* *
* @access public * @access public
* @param String $hash * @param string $hash
*/ */
function setHash($hash) function setHash($hash)
{ {
@ -231,19 +217,19 @@ class Crypt_Hash
switch ($hash) { switch ($hash) {
case 'md2': case 'md2':
$mode = CRYPT_HASH_MODE == CRYPT_HASH_MODE_HASH && in_array('md2', hash_algos()) ? $mode = CRYPT_HASH_MODE == self::MODE_HASH && in_array('md2', hash_algos()) ?
CRYPT_HASH_MODE_HASH : CRYPT_HASH_MODE_INTERNAL; self::MODE_HASH : self::MODE_INTERNAL;
break; break;
case 'sha384': case 'sha384':
case 'sha512': case 'sha512':
$mode = CRYPT_HASH_MODE == CRYPT_HASH_MODE_MHASH ? CRYPT_HASH_MODE_INTERNAL : CRYPT_HASH_MODE; $mode = CRYPT_HASH_MODE == self::MODE_MHASH ? self::MODE_INTERNAL : CRYPT_HASH_MODE;
break; break;
default: default:
$mode = CRYPT_HASH_MODE; $mode = CRYPT_HASH_MODE;
} }
switch ( $mode ) { switch ($mode) {
case CRYPT_HASH_MODE_MHASH: case self::MODE_MHASH:
switch ($hash) { switch ($hash) {
case 'md5': case 'md5':
$this->hash = MHASH_MD5; $this->hash = MHASH_MD5;
@ -256,7 +242,7 @@ class Crypt_Hash
$this->hash = MHASH_SHA1; $this->hash = MHASH_SHA1;
} }
return; return;
case CRYPT_HASH_MODE_HASH: case self::MODE_HASH:
switch ($hash) { switch ($hash) {
case 'md5': case 'md5':
$this->hash = 'md5'; $this->hash = 'md5';
@ -306,22 +292,22 @@ class Crypt_Hash
* Compute the HMAC. * Compute the HMAC.
* *
* @access public * @access public
* @param String $text * @param string $text
* @return String * @return string
*/ */
function hash($text) function hash($text)
{ {
$mode = is_array($this->hash) ? CRYPT_HASH_MODE_INTERNAL : CRYPT_HASH_MODE; $mode = is_array($this->hash) ? self::MODE_INTERNAL : CRYPT_HASH_MODE;
if (!empty($this->key) || is_string($this->key)) { if (!empty($this->key) || is_string($this->key)) {
switch ( $mode ) { switch ($mode) {
case CRYPT_HASH_MODE_MHASH: case self::MODE_MHASH:
$output = mhash($this->hash, $text, $this->key); $output = mhash($this->hash, $text, $this->key);
break; break;
case CRYPT_HASH_MODE_HASH: case self::MODE_HASH:
$output = hash_hmac($this->hash, $text, $this->key, true); $output = hash_hmac($this->hash, $text, $this->key, true);
break; break;
case CRYPT_HASH_MODE_INTERNAL: case self::MODE_INTERNAL:
/* "Applications that use keys longer than B bytes will first hash the key using H and then use the /* "Applications that use keys longer than B bytes will first hash the key using H and then use the
resultant L byte string as the actual key to HMAC." resultant L byte string as the actual key to HMAC."
@ -337,14 +323,14 @@ class Crypt_Hash
$output = call_user_func($this->hash, $output); // step 7 $output = call_user_func($this->hash, $output); // step 7
} }
} else { } else {
switch ( $mode ) { switch ($mode) {
case CRYPT_HASH_MODE_MHASH: case self::MODE_MHASH:
$output = mhash($this->hash, $text); $output = mhash($this->hash, $text);
break; break;
case CRYPT_HASH_MODE_HASH: case self::MODE_HASH:
$output = hash($this->hash, $text, true); $output = hash($this->hash, $text, true);
break; break;
case CRYPT_HASH_MODE_INTERNAL: case self::MODE_INTERNAL:
$output = call_user_func($this->hash, $text); $output = call_user_func($this->hash, $text);
} }
} }
@ -356,7 +342,7 @@ class Crypt_Hash
* Returns the hash length (in bytes) * Returns the hash length (in bytes)
* *
* @access public * @access public
* @return Integer * @return int
*/ */
function getLength() function getLength()
{ {
@ -367,7 +353,7 @@ class Crypt_Hash
* Wrapper for MD5 * Wrapper for MD5
* *
* @access private * @access private
* @param String $m * @param string $m
*/ */
function _md5($m) function _md5($m)
{ {
@ -378,7 +364,7 @@ class Crypt_Hash
* Wrapper for SHA1 * Wrapper for SHA1
* *
* @access private * @access private
* @param String $m * @param string $m
*/ */
function _sha1($m) function _sha1($m)
{ {
@ -391,7 +377,7 @@ class Crypt_Hash
* See {@link http://tools.ietf.org/html/rfc1319 RFC1319}. * See {@link http://tools.ietf.org/html/rfc1319 RFC1319}.
* *
* @access private * @access private
* @param String $m * @param string $m
*/ */
function _md2($m) function _md2($m)
{ {
@ -467,7 +453,7 @@ class Crypt_Hash
* See {@link http://en.wikipedia.org/wiki/SHA_hash_functions#SHA-256_.28a_SHA-2_variant.29_pseudocode SHA-256 (a SHA-2 variant) pseudocode - Wikipedia}. * See {@link http://en.wikipedia.org/wiki/SHA_hash_functions#SHA-256_.28a_SHA-2_variant.29_pseudocode SHA-256 (a SHA-2 variant) pseudocode - Wikipedia}.
* *
* @access private * @access private
* @param String $m * @param string $m
*/ */
function _sha256($m) function _sha256($m)
{ {
@ -511,14 +497,15 @@ class Crypt_Hash
// Extend the sixteen 32-bit words into sixty-four 32-bit words // Extend the sixteen 32-bit words into sixty-four 32-bit words
for ($i = 16; $i < 64; $i++) { for ($i = 16; $i < 64; $i++) {
// @codingStandardsIgnoreStart
$s0 = $this->_rightRotate($w[$i - 15], 7) ^ $s0 = $this->_rightRotate($w[$i - 15], 7) ^
$this->_rightRotate($w[$i - 15], 18) ^ $this->_rightRotate($w[$i - 15], 18) ^
$this->_rightShift( $w[$i - 15], 3); $this->_rightShift( $w[$i - 15], 3);
$s1 = $this->_rightRotate($w[$i - 2], 17) ^ $s1 = $this->_rightRotate($w[$i - 2], 17) ^
$this->_rightRotate($w[$i - 2], 19) ^ $this->_rightRotate($w[$i - 2], 19) ^
$this->_rightShift( $w[$i - 2], 10); $this->_rightShift( $w[$i - 2], 10);
// @codingStandardsIgnoreEnd
$w[$i] = $this->_add($w[$i - 16], $s0, $w[$i - 7], $s1); $w[$i] = $this->_add($w[$i - 16], $s0, $w[$i - 7], $s1);
} }
// Initialize hash value for this chunk // Initialize hash value for this chunk
@ -572,14 +559,10 @@ class Crypt_Hash
* Pure-PHP implementation of SHA384 and SHA512 * Pure-PHP implementation of SHA384 and SHA512
* *
* @access private * @access private
* @param String $m * @param string $m
*/ */
function _sha512($m) function _sha512($m)
{ {
if (!class_exists('Math_BigInteger')) {
include_once 'Math/BigInteger.php';
}
static $init384, $init512, $k; static $init384, $init512, $k;
if (!isset($k)) { if (!isset($k)) {
@ -594,9 +577,9 @@ class Crypt_Hash
); );
for ($i = 0; $i < 8; $i++) { for ($i = 0; $i < 8; $i++) {
$init384[$i] = new Math_BigInteger($init384[$i], 16); $init384[$i] = new BigInteger($init384[$i], 16);
$init384[$i]->setPrecision(64); $init384[$i]->setPrecision(64);
$init512[$i] = new Math_BigInteger($init512[$i], 16); $init512[$i] = new BigInteger($init512[$i], 16);
$init512[$i]->setPrecision(64); $init512[$i]->setPrecision(64);
} }
@ -626,7 +609,7 @@ class Crypt_Hash
); );
for ($i = 0; $i < 80; $i++) { for ($i = 0; $i < 80; $i++) {
$k[$i] = new Math_BigInteger($k[$i], 16); $k[$i] = new BigInteger($k[$i], 16);
} }
} }
@ -645,7 +628,7 @@ class Crypt_Hash
foreach ($chunks as $chunk) { foreach ($chunks as $chunk) {
$w = array(); $w = array();
for ($i = 0; $i < 16; $i++) { for ($i = 0; $i < 16; $i++) {
$temp = new Math_BigInteger($this->_string_shift($chunk, 8), 256); $temp = new BigInteger($this->_string_shift($chunk, 8), 256);
$temp->setPrecision(64); $temp->setPrecision(64);
$w[] = $temp; $w[] = $temp;
} }
@ -741,7 +724,7 @@ class Crypt_Hash
} }
// Produce the final hash value (big-endian) // Produce the final hash value (big-endian)
// (Crypt_Hash::hash() trims the output for hashes but not for HMACs. as such, we trim the output here) // (\phpseclib\Crypt\Hash::hash() trims the output for hashes but not for HMACs. as such, we trim the output here)
$temp = $hash[0]->toBytes() . $hash[1]->toBytes() . $hash[2]->toBytes() . $hash[3]->toBytes() . $temp = $hash[0]->toBytes() . $hash[1]->toBytes() . $hash[2]->toBytes() . $hash[3]->toBytes() .
$hash[4]->toBytes() . $hash[5]->toBytes(); $hash[4]->toBytes() . $hash[5]->toBytes();
if ($this->l != 48) { if ($this->l != 48) {
@ -755,10 +738,10 @@ class Crypt_Hash
* Right Rotate * Right Rotate
* *
* @access private * @access private
* @param Integer $int * @param int $int
* @param Integer $amt * @param int $amt
* @see _sha256() * @see self::_sha256()
* @return Integer * @return int
*/ */
function _rightRotate($int, $amt) function _rightRotate($int, $amt)
{ {
@ -771,10 +754,10 @@ class Crypt_Hash
* Right Shift * Right Shift
* *
* @access private * @access private
* @param Integer $int * @param int $int
* @param Integer $amt * @param int $amt
* @see _sha256() * @see self::_sha256()
* @return Integer * @return int
*/ */
function _rightShift($int, $amt) function _rightShift($int, $amt)
{ {
@ -786,9 +769,9 @@ class Crypt_Hash
* Not * Not
* *
* @access private * @access private
* @param Integer $int * @param int $int
* @see _sha256() * @see self::_sha256()
* @return Integer * @return int
*/ */
function _not($int) function _not($int)
{ {
@ -799,11 +782,11 @@ class Crypt_Hash
* Add * Add
* *
* _sha256() adds multiple unsigned 32-bit integers. Since PHP doesn't support unsigned integers and since the * _sha256() adds multiple unsigned 32-bit integers. Since PHP doesn't support unsigned integers and since the
* possibility of overflow exists, care has to be taken. Math_BigInteger() could be used but this should be faster. * possibility of overflow exists, care has to be taken. BigInteger could be used but this should be faster.
* *
* @param Integer $... * @param int $...
* @return Integer * @return int
* @see _sha256() * @see self::_sha256()
* @access private * @access private
*/ */
function _add() function _add()
@ -827,9 +810,9 @@ class Crypt_Hash
* *
* Inspired by array_shift * Inspired by array_shift
* *
* @param String $string * @param string $string
* @param optional Integer $index * @param int $index
* @return String * @return string
* @access private * @access private
*/ */
function _string_shift(&$string, $index = 1) function _string_shift(&$string, $index = 1)

View file

@ -5,7 +5,7 @@
* *
* Uses mcrypt, if available, and an internal implementation, otherwise. * Uses mcrypt, if available, and an internal implementation, otherwise.
* *
* PHP versions 4 and 5 * PHP version 5
* *
* Useful resources are as follows: * Useful resources are as follows:
* *
@ -14,9 +14,9 @@
* Here's a short example of how to use this library: * Here's a short example of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'Crypt/RC2.php'; * include 'vendor/autoload.php';
* *
* $rc2 = new Crypt_RC2(); * $rc2 = new \phpseclib\Crypt\RC2();
* *
* $rc2->setKey('abcdefgh'); * $rc2->setKey('abcdefgh');
* *
@ -26,106 +26,28 @@
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category Crypt * @category Crypt
* @package Crypt_RC2 * @package RC2
* @author Patrick Monnerat <pm@datasphere.ch> * @author Patrick Monnerat <pm@datasphere.ch>
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
/** namespace phpseclib\Crypt;
* Include Crypt_Base
*
* Base cipher class
*/
if (!class_exists('Crypt_Base')) {
include_once 'Base.php';
}
/**#@+
* @access public
* @see Crypt_RC2::encrypt()
* @see Crypt_RC2::decrypt()
*/
/**
* Encrypt / decrypt using the Counter mode.
*
* Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
*/
define('CRYPT_RC2_MODE_CTR', CRYPT_MODE_CTR);
/**
* Encrypt / decrypt using the Electronic Code Book mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
*/
define('CRYPT_RC2_MODE_ECB', CRYPT_MODE_ECB);
/**
* Encrypt / decrypt using the Code Book Chaining mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
*/
define('CRYPT_RC2_MODE_CBC', CRYPT_MODE_CBC);
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
*/
define('CRYPT_RC2_MODE_CFB', CRYPT_MODE_CFB);
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
*/
define('CRYPT_RC2_MODE_OFB', CRYPT_MODE_OFB);
/**#@-*/
/**#@+
* @access private
* @see Crypt_RC2::Crypt_RC2()
*/
/**
* Toggles the internal implementation
*/
define('CRYPT_RC2_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
/**
* Toggles the mcrypt implementation
*/
define('CRYPT_RC2_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
/**#@-*/
/** /**
* Pure-PHP implementation of RC2. * Pure-PHP implementation of RC2.
* *
* @package Crypt_RC2 * @package RC2
* @access public * @access public
*/ */
class Crypt_RC2 extends Crypt_Base class RC2 extends Base
{ {
/** /**
* Block Length of the cipher * Block Length of the cipher
* *
* @see Crypt_Base::block_size * @see \phpseclib\Crypt\Base::block_size
* @var Integer * @var int
* @access private * @access private
*/ */
var $block_size = 8; var $block_size = 8;
@ -133,37 +55,48 @@ class Crypt_RC2 extends Crypt_Base
/** /**
* The Key * The Key
* *
* @see Crypt_Base::key * @see \phpseclib\Crypt\Base::key
* @see setKey() * @see self::setKey()
* @var String * @var string
* @access private * @access private
*/ */
var $key = "\0"; var $key;
/** /**
* The default password key_size used by setPassword() * The Original (unpadded) Key
* *
* @see Crypt_Base::password_key_size * @see \phpseclib\Crypt\Base::key
* @see Crypt_Base::setPassword() * @see self::setKey()
* @var Integer * @see self::encrypt()
* @see self::decrypt()
* @var string
* @access private * @access private
*/ */
var $password_key_size = 16; // = 128 bits var $orig_key;
/** /**
* The namespace used by the cipher for its constants. * Don't truncate / null pad key
* *
* @see Crypt_Base::const_namespace * @see \phpseclib\Crypt\Base::_clearBuffers()
* @var String * @var bool
* @access private * @access private
*/ */
var $const_namespace = 'RC2'; var $skip_key_adjustment = true;
/**
* Key Length (in bytes)
*
* @see \phpseclib\Crypt\RC2::setKeyLength()
* @var int
* @access private
*/
var $key_length = 16; // = 128 bits
/** /**
* The mcrypt specific name of the cipher * The mcrypt specific name of the cipher
* *
* @see Crypt_Base::cipher_name_mcrypt * @see \phpseclib\Crypt\Base::cipher_name_mcrypt
* @var String * @var string
* @access private * @access private
*/ */
var $cipher_name_mcrypt = 'rc2'; var $cipher_name_mcrypt = 'rc2';
@ -171,8 +104,8 @@ class Crypt_RC2 extends Crypt_Base
/** /**
* Optimizing value while CFB-encrypting * Optimizing value while CFB-encrypting
* *
* @see Crypt_Base::cfb_init_len * @see \phpseclib\Crypt\Base::cfb_init_len
* @var Integer * @var int
* @access private * @access private
*/ */
var $cfb_init_len = 500; var $cfb_init_len = 500;
@ -180,20 +113,31 @@ class Crypt_RC2 extends Crypt_Base
/** /**
* The key length in bits. * The key length in bits.
* *
* @see Crypt_RC2::setKeyLength() * @see self::setKeyLength()
* @see Crypt_RC2::setKey() * @see self::setKey()
* @var Integer * @var int
* @access private * @access private
* @internal Should be in range [1..1024]. * @internal Should be in range [1..1024].
* @internal Changing this value after setting the key has no effect. * @internal Changing this value after setting the key has no effect.
*/ */
var $default_key_length = 1024; var $default_key_length = 1024;
/**
* The key length in bits.
*
* @see self::isValidEnine()
* @see self::setKey()
* @var int
* @access private
* @internal Should be in range [1..1024].
*/
var $current_key_length;
/** /**
* The Key Schedule * The Key Schedule
* *
* @see Crypt_RC2::_setupKey() * @see self::_setupKey()
* @var Array * @var array
* @access private * @access private
*/ */
var $keys; var $keys;
@ -202,8 +146,8 @@ class Crypt_RC2 extends Crypt_Base
* Key expansion randomization table. * Key expansion randomization table.
* Twice the same 256-value sequence to save a modulus in key expansion. * Twice the same 256-value sequence to save a modulus in key expansion.
* *
* @see Crypt_RC2::setKey() * @see self::setKey()
* @var Array * @var array
* @access private * @access private
*/ */
var $pitable = array( var $pitable = array(
@ -276,8 +220,8 @@ class Crypt_RC2 extends Crypt_Base
/** /**
* Inverse key expansion randomization table. * Inverse key expansion randomization table.
* *
* @see Crypt_RC2::setKey() * @see self::setKey()
* @var Array * @var array
* @access private * @access private
*/ */
var $invpitable = array( var $invpitable = array(
@ -316,55 +260,68 @@ class Crypt_RC2 extends Crypt_Base
); );
/** /**
* Default Constructor. * Test for engine validity
* *
* Determines whether or not the mcrypt extension should be used. * This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine()
* *
* $mode could be: * @see \phpseclib\Crypt\Base::__construct()
* * @param int $engine
* - CRYPT_RC2_MODE_ECB
*
* - CRYPT_RC2_MODE_CBC
*
* - CRYPT_RC2_MODE_CTR
*
* - CRYPT_RC2_MODE_CFB
*
* - CRYPT_RC2_MODE_OFB
*
* If not explicitly set, CRYPT_RC2_MODE_CBC will be used.
*
* @see Crypt_Base::Crypt_Base()
* @param optional Integer $mode
* @access public * @access public
* @return bool
*/ */
function Crypt_RC2($mode = CRYPT_RC2_MODE_CBC) function isValidEngine($engine)
{ {
parent::Crypt_Base($mode); switch ($engine) {
$this->setKey(''); case self::ENGINE_OPENSSL:
if ($this->current_key_length != 128 || strlen($this->orig_key) < 16) {
return false;
}
$this->cipher_name_openssl_ecb = 'rc2-ecb';
$this->cipher_name_openssl = 'rc2-' . $this->_openssl_translate_mode();
}
return parent::isValidEngine($engine);
} }
/** /**
* Sets the key length * Sets the key length.
* *
* Valid key lengths are 1 to 1024. * Valid key lengths are 8 to 1024.
* Calling this function after setting the key has no effect until the next * Calling this function after setting the key has no effect until the next
* Crypt_RC2::setKey() call. * \phpseclib\Crypt\RC2::setKey() call.
* *
* @access public * @access public
* @param Integer $length in bits * @param int $length in bits
*/ */
function setKeyLength($length) function setKeyLength($length)
{ {
if ($length >= 1 && $length <= 1024) { if ($length < 8) {
$this->default_key_length = 8;
} elseif ($length > 1024) {
$this->default_key_length = 128;
} else {
$this->default_key_length = $length; $this->default_key_length = $length;
} }
$this->current_key_length = $this->default_key_length;
parent::setKeyLength($length);
}
/**
* Returns the current key length
*
* @access public
* @return int
*/
function getKeyLength()
{
return $this->current_key_length;
} }
/** /**
* Sets the key. * Sets the key.
* *
* Keys can be of any length. RC2, itself, uses 1 to 1024 bit keys (eg. * Keys can be of any length. RC2, itself, uses 8 to 1024 bit keys (eg.
* strlen($key) <= 128), however, we only use the first 128 bytes if $key * strlen($key) <= 128), however, we only use the first 128 bytes if $key
* has more then 128 bytes in it, and set $key to a single null byte if * has more then 128 bytes in it, and set $key to a single null byte if
* it is empty. * it is empty.
@ -372,18 +329,21 @@ class Crypt_RC2 extends Crypt_Base
* If the key is not explicitly set, it'll be assumed to be a single * If the key is not explicitly set, it'll be assumed to be a single
* null byte. * null byte.
* *
* @see Crypt_Base::setKey() * @see \phpseclib\Crypt\Base::setKey()
* @access public * @access public
* @param String $key * @param string $key
* @param Integer $t1 optional Effective key length in bits. * @param int $t1 optional Effective key length in bits.
*/ */
function setKey($key, $t1 = 0) function setKey($key, $t1 = 0)
{ {
$this->orig_key = $key;
if ($t1 <= 0) { if ($t1 <= 0) {
$t1 = $this->default_key_length; $t1 = $this->default_key_length;
} else if ($t1 > 1024) { } elseif ($t1 > 1024) {
$t1 = 1024; $t1 = 1024;
} }
$this->current_key_length = $t1;
// Key byte count should be 1..128. // Key byte count should be 1..128.
$key = strlen($key) ? substr($key, 0, 128) : "\x00"; $key = strlen($key) ? substr($key, 0, 128) : "\x00";
$t = strlen($key); $t = strlen($key);
@ -413,17 +373,64 @@ class Crypt_RC2 extends Crypt_Base
// Prepare the key for mcrypt. // Prepare the key for mcrypt.
$l[0] = $this->invpitable[$l[0]]; $l[0] = $this->invpitable[$l[0]];
array_unshift($l, 'C*'); array_unshift($l, 'C*');
parent::setKey(call_user_func_array('pack', $l)); parent::setKey(call_user_func_array('pack', $l));
} }
/**
* Encrypts a message.
*
* Mostly a wrapper for \phpseclib\Crypt\Base::encrypt, with some additional OpenSSL handling code
*
* @see self::decrypt()
* @access public
* @param string $plaintext
* @return string $ciphertext
*/
function encrypt($plaintext)
{
if ($this->engine == self::ENGINE_OPENSSL) {
$temp = $this->key;
$this->key = $this->orig_key;
$result = parent::encrypt($plaintext);
$this->key = $temp;
return $result;
}
return parent::encrypt($plaintext);
}
/**
* Decrypts a message.
*
* Mostly a wrapper for \phpseclib\Crypt\Base::decrypt, with some additional OpenSSL handling code
*
* @see self::encrypt()
* @access public
* @param string $ciphertext
* @return string $plaintext
*/
function decrypt($ciphertext)
{
if ($this->engine == self::ENGINE_OPENSSL) {
$temp = $this->key;
$this->key = $this->orig_key;
$result = parent::decrypt($ciphertext);
$this->key = $temp;
return $result;
}
return parent::decrypt($ciphertext);
}
/** /**
* Encrypts a block * Encrypts a block
* *
* @see Crypt_Base::_encryptBlock() * @see \phpseclib\Crypt\Base::_encryptBlock()
* @see Crypt_Base::encrypt() * @see \phpseclib\Crypt\Base::encrypt()
* @access private * @access private
* @param String $in * @param string $in
* @return String * @return string
*/ */
function _encryptBlock($in) function _encryptBlock($in)
{ {
@ -464,11 +471,11 @@ class Crypt_RC2 extends Crypt_Base
/** /**
* Decrypts a block * Decrypts a block
* *
* @see Crypt_Base::_decryptBlock() * @see \phpseclib\Crypt\Base::_decryptBlock()
* @see Crypt_Base::decrypt() * @see \phpseclib\Crypt\Base::decrypt()
* @access private * @access private
* @param String $in * @param string $in
* @return String * @return string
*/ */
function _decryptBlock($in) function _decryptBlock($in)
{ {
@ -506,15 +513,34 @@ class Crypt_RC2 extends Crypt_Base
return pack('vvvv', $r0, $r1, $r2, $r3); return pack('vvvv', $r0, $r1, $r2, $r3);
} }
/**
* Setup the \phpseclib\Crypt\Base::ENGINE_MCRYPT $engine
*
* @see \phpseclib\Crypt\Base::_setupMcrypt()
* @access private
*/
function _setupMcrypt()
{
if (!isset($this->key)) {
$this->setKey('');
}
parent::_setupMcrypt();
}
/** /**
* Creates the key schedule * Creates the key schedule
* *
* @see Crypt_Base::_setupKey() * @see \phpseclib\Crypt\Base::_setupKey()
* @access private * @access private
*/ */
function _setupKey() function _setupKey()
{ {
// Key has already been expanded in Crypt_RC2::setKey(): if (!isset($this->key)) {
$this->setKey('');
}
// Key has already been expanded in \phpseclib\Crypt\RC2::setKey():
// Only the first value must be altered. // Only the first value must be altered.
$l = unpack('Ca/Cb/v*', $this->key); $l = unpack('Ca/Cb/v*', $this->key);
array_unshift($l, $this->pitable[$l['a']] | ($l['b'] << 8)); array_unshift($l, $this->pitable[$l['a']] | ($l['b'] << 8));
@ -526,24 +552,24 @@ class Crypt_RC2 extends Crypt_Base
/** /**
* Setup the performance-optimized function for de/encrypt() * Setup the performance-optimized function for de/encrypt()
* *
* @see Crypt_Base::_setupInlineCrypt() * @see \phpseclib\Crypt\Base::_setupInlineCrypt()
* @access private * @access private
*/ */
function _setupInlineCrypt() function _setupInlineCrypt()
{ {
$lambda_functions = &Crypt_RC2::_getLambdaFunctions(); $lambda_functions =& self::_getLambdaFunctions();
// The first 10 generated $lambda_functions will use the $keys hardcoded as integers // The first 10 generated $lambda_functions will use the $keys hardcoded as integers
// for the mixing rounds, for better inline crypt performance [~20% faster]. // for the mixing rounds, for better inline crypt performance [~20% faster].
// But for memory reason we have to limit those ultra-optimized $lambda_functions to an amount of 10. // But for memory reason we have to limit those ultra-optimized $lambda_functions to an amount of 10.
$keys = $this->keys; // (Currently, for Crypt_RC2, one generated $lambda_function cost on php5.5@32bit ~60kb unfreeable mem and ~100kb on php5.5@64bit)
if (count($lambda_functions) >= 10) { $gen_hi_opt_code = (bool)(count($lambda_functions) < 10);
foreach ($this->keys as $k => $v) {
$keys[$k] = '$keys[' . $k . ']';
}
}
$code_hash = md5(str_pad("Crypt_RC2, {$this->mode}, ", 32, "\0") . implode(',', $keys)); // Generation of a unique hash for our generated code
$code_hash = "Crypt_RC2, {$this->mode}";
if ($gen_hi_opt_code) {
$code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key);
}
// Is there a re-usable $lambda_functions in there? // Is there a re-usable $lambda_functions in there?
// If not, we have to create it. // If not, we have to create it.
@ -551,6 +577,16 @@ class Crypt_RC2 extends Crypt_Base
// Init code for both, encrypt and decrypt. // Init code for both, encrypt and decrypt.
$init_crypt = '$keys = $self->keys;'; $init_crypt = '$keys = $self->keys;';
switch (true) {
case $gen_hi_opt_code:
$keys = $this->keys;
default:
$keys = array();
foreach ($this->keys as $k => $v) {
$keys[$k] = '$keys[' . $k . ']';
}
}
// $in is the current 8 bytes block which has to be en/decrypt // $in is the current 8 bytes block which has to be en/decrypt
$encrypt_block = $decrypt_block = ' $encrypt_block = $decrypt_block = '
$in = unpack("v4", $in); $in = unpack("v4", $in);

View file

@ -5,7 +5,7 @@
* *
* Uses mcrypt, if available, and an internal implementation, otherwise. * Uses mcrypt, if available, and an internal implementation, otherwise.
* *
* PHP versions 4 and 5 * PHP version 5
* *
* Useful resources are as follows: * Useful resources are as follows:
* *
@ -18,9 +18,9 @@
* Here's a short example of how to use this library: * Here's a short example of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'Crypt/RC4.php'; * include 'vendor/autoload.php';
* *
* $rc4 = new Crypt_RC4(); * $rc4 = new \phpseclib\Crypt\RC4();
* *
* $rc4->setKey('abcdefgh'); * $rc4->setKey('abcdefgh');
* *
@ -34,108 +34,59 @@
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category Crypt * @category Crypt
* @package Crypt_RC4 * @package RC4
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2007 Jim Wigginton * @copyright 2007 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
/** namespace phpseclib\Crypt;
* Include Crypt_Base
*
* Base cipher class
*/
if (!class_exists('Crypt_Base')) {
include_once 'Base.php';
}
/**#@+
* @access private
* @see Crypt_RC4::Crypt_RC4()
*/
/**
* Toggles the internal implementation
*/
define('CRYPT_RC4_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
/**
* Toggles the mcrypt implementation
*/
define('CRYPT_RC4_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
/**#@-*/
/**#@+
* @access private
* @see Crypt_RC4::_crypt()
*/
define('CRYPT_RC4_ENCRYPT', 0);
define('CRYPT_RC4_DECRYPT', 1);
/**#@-*/
/** /**
* Pure-PHP implementation of RC4. * Pure-PHP implementation of RC4.
* *
* @package Crypt_RC4 * @package RC4
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @access public * @access public
*/ */
class Crypt_RC4 extends Crypt_Base class RC4 extends Base
{ {
/**#@+
* @access private
* @see \phpseclib\Crypt\RC4::_crypt()
*/
const ENCRYPT = 0;
const DECRYPT = 1;
/**#@-*/
/** /**
* Block Length of the cipher * Block Length of the cipher
* *
* RC4 is a stream cipher * RC4 is a stream cipher
* so we the block_size to 0 * so we the block_size to 0
* *
* @see Crypt_Base::block_size * @see \phpseclib\Crypt\Base::block_size
* @var Integer * @var int
* @access private * @access private
*/ */
var $block_size = 0; var $block_size = 0;
/** /**
* The default password key_size used by setPassword() * Key Length (in bytes)
* *
* @see Crypt_Base::password_key_size * @see \phpseclib\Crypt\RC4::setKeyLength()
* @see Crypt_Base::setPassword() * @var int
* @var Integer
* @access private * @access private
*/ */
var $password_key_size = 128; // = 1024 bits var $key_length = 128; // = 1024 bits
/**
* The namespace used by the cipher for its constants.
*
* @see Crypt_Base::const_namespace
* @var String
* @access private
*/
var $const_namespace = 'RC4';
/** /**
* The mcrypt specific name of the cipher * The mcrypt specific name of the cipher
* *
* @see Crypt_Base::cipher_name_mcrypt * @see \phpseclib\Crypt\Base::cipher_name_mcrypt
* @var String * @var string
* @access private * @access private
*/ */
var $cipher_name_mcrypt = 'arcfour'; var $cipher_name_mcrypt = 'arcfour';
@ -143,7 +94,7 @@ class Crypt_RC4 extends Crypt_Base
/** /**
* Holds whether performance-optimized $inline_crypt() can/should be used. * Holds whether performance-optimized $inline_crypt() can/should be used.
* *
* @see Crypt_Base::inline_crypt * @see \phpseclib\Crypt\Base::inline_crypt
* @var mixed * @var mixed
* @access private * @access private
*/ */
@ -152,8 +103,8 @@ class Crypt_RC4 extends Crypt_Base
/** /**
* The Key * The Key
* *
* @see Crypt_RC4::setKey() * @see self::setKey()
* @var String * @var string
* @access private * @access private
*/ */
var $key = "\0"; var $key = "\0";
@ -161,8 +112,8 @@ class Crypt_RC4 extends Crypt_Base
/** /**
* The Key Stream for decryption and encryption * The Key Stream for decryption and encryption
* *
* @see Crypt_RC4::setKey() * @see self::setKey()
* @var Array * @var array
* @access private * @access private
*/ */
var $stream; var $stream;
@ -172,13 +123,45 @@ class Crypt_RC4 extends Crypt_Base
* *
* Determines whether or not the mcrypt extension should be used. * Determines whether or not the mcrypt extension should be used.
* *
* @see Crypt_Base::Crypt_Base() * @see \phpseclib\Crypt\Base::__construct()
* @return Crypt_RC4 * @return \phpseclib\Crypt\RC4
* @access public * @access public
*/ */
function Crypt_RC4() function __construct()
{ {
parent::Crypt_Base(CRYPT_MODE_STREAM); parent::__construct(Base::MODE_STREAM);
}
/**
* Test for engine validity
*
* This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine()
*
* @see \phpseclib\Crypt\Base::__construct()
* @param int $engine
* @access public
* @return bool
*/
function isValidEngine($engine)
{
switch ($engine) {
case Base::ENGINE_OPENSSL:
switch (strlen($this->key)) {
case 5:
$this->cipher_name_openssl = 'rc4-40';
break;
case 8:
$this->cipher_name_openssl = 'rc4-64';
break;
case 16:
$this->cipher_name_openssl = 'rc4';
break;
default:
return false;
}
}
return parent::isValidEngine($engine);
} }
/** /**
@ -196,8 +179,8 @@ class Crypt_RC4 extends Crypt_Base
* {@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009} * {@link http://www.rsa.com/rsalabs/node.asp?id=2009 http://www.rsa.com/rsalabs/node.asp?id=2009}
* {@link http://en.wikipedia.org/wiki/Related_key_attack http://en.wikipedia.org/wiki/Related_key_attack} * {@link http://en.wikipedia.org/wiki/Related_key_attack http://en.wikipedia.org/wiki/Related_key_attack}
* *
* @param String $iv * @param string $iv
* @see Crypt_RC4::setKey() * @see self::setKey()
* @access public * @access public
*/ */
function setIV($iv) function setIV($iv)
@ -205,35 +188,41 @@ class Crypt_RC4 extends Crypt_Base
} }
/** /**
* Sets the key. * Sets the key length
* *
* Keys can be between 1 and 256 bytes long. If they are longer then 256 bytes, the first 256 bytes will * Keys can be between 1 and 256 bytes long.
* be used. If no key is explicitly set, it'll be assumed to be a single null byte.
* *
* @access public * @access public
* @see Crypt_Base::setKey() * @param int $length
* @param String $key
*/ */
function setKey($key) function setKeyLength($length)
{ {
parent::setKey(substr($key, 0, 256)); if ($length < 8) {
$this->key_length = 1;
} elseif ($length > 2048) {
$this->key_length = 256;
} else {
$this->key_length = $length >> 3;
}
parent::setKeyLength($length);
} }
/** /**
* Encrypts a message. * Encrypts a message.
* *
* @see Crypt_Base::decrypt() * @see \phpseclib\Crypt\Base::decrypt()
* @see Crypt_RC4::_crypt() * @see self::_crypt()
* @access public * @access public
* @param String $plaintext * @param string $plaintext
* @return String $ciphertext * @return string $ciphertext
*/ */
function encrypt($plaintext) function encrypt($plaintext)
{ {
if ($this->engine == CRYPT_MODE_MCRYPT) { if ($this->engine != Base::ENGINE_INTERNAL) {
return parent::encrypt($plaintext); return parent::encrypt($plaintext);
} }
return $this->_crypt($plaintext, CRYPT_RC4_ENCRYPT); return $this->_crypt($plaintext, self::ENCRYPT);
} }
/** /**
@ -242,25 +231,46 @@ class Crypt_RC4 extends Crypt_Base
* $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)). * $this->decrypt($this->encrypt($plaintext)) == $this->encrypt($this->encrypt($plaintext)).
* At least if the continuous buffer is disabled. * At least if the continuous buffer is disabled.
* *
* @see Crypt_Base::encrypt() * @see \phpseclib\Crypt\Base::encrypt()
* @see Crypt_RC4::_crypt() * @see self::_crypt()
* @access public * @access public
* @param String $ciphertext * @param string $ciphertext
* @return String $plaintext * @return string $plaintext
*/ */
function decrypt($ciphertext) function decrypt($ciphertext)
{ {
if ($this->engine == CRYPT_MODE_MCRYPT) { if ($this->engine != Base::ENGINE_INTERNAL) {
return parent::decrypt($ciphertext); return parent::decrypt($ciphertext);
} }
return $this->_crypt($ciphertext, CRYPT_RC4_DECRYPT); return $this->_crypt($ciphertext, self::DECRYPT);
} }
/**
* Encrypts a block
*
* @access private
* @param string $in
*/
function _encryptBlock($in)
{
// RC4 does not utilize this method
}
/**
* Decrypts a block
*
* @access private
* @param string $in
*/
function _decryptBlock($in)
{
// RC4 does not utilize this method
}
/** /**
* Setup the key (expansion) * Setup the key (expansion)
* *
* @see Crypt_Base::_setupKey() * @see \phpseclib\Crypt\Base::_setupKey()
* @access private * @access private
*/ */
function _setupKey() function _setupKey()
@ -277,7 +287,7 @@ class Crypt_RC4 extends Crypt_Base
} }
$this->stream = array(); $this->stream = array();
$this->stream[CRYPT_RC4_DECRYPT] = $this->stream[CRYPT_RC4_ENCRYPT] = array( $this->stream[self::DECRYPT] = $this->stream[self::ENCRYPT] = array(
0, // index $i 0, // index $i
0, // index $j 0, // index $j
$keyStream $keyStream
@ -287,12 +297,12 @@ class Crypt_RC4 extends Crypt_Base
/** /**
* Encrypts or decrypts a message. * Encrypts or decrypts a message.
* *
* @see Crypt_RC4::encrypt() * @see self::encrypt()
* @see Crypt_RC4::decrypt() * @see self::decrypt()
* @access private * @access private
* @param String $text * @param string $text
* @param Integer $mode * @param int $mode
* @return String $text * @return string $text
*/ */
function _crypt($text, $mode) function _crypt($text, $mode)
{ {

File diff suppressed because it is too large Load diff

View file

@ -3,57 +3,36 @@
/** /**
* Random Number Generator * Random Number Generator
* *
* The idea behind this function is that it can be easily replaced with your own crypt_random_string() * PHP version 5
* function. eg. maybe you have a better source of entropy for creating the initial states or whatever.
*
* PHP versions 4 and 5
* *
* Here's a short example of how to use this library: * Here's a short example of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'Crypt/Random.php'; * include 'vendor/autoload.php';
* *
* echo bin2hex(crypt_random_string(8)); * echo bin2hex(\phpseclib\Crypt\Random::string(8));
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category Crypt * @category Crypt
* @package Crypt_Random * @package Random
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2007 Jim Wigginton * @copyright 2007 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
// laravel is a PHP framework that utilizes phpseclib. laravel workbenches may, independently, namespace phpseclib\Crypt;
// have phpseclib as a requirement as well. if you're developing such a program you may encounter
// a "Cannot redeclare crypt_random_string()" error.
if (!function_exists('crypt_random_string')) {
/**
* "Is Windows" test
*
* @access private
*/
define('CRYPT_RANDOM_IS_WINDOWS', strtoupper(substr(PHP_OS, 0, 3)) === 'WIN');
/**
* Pure-PHP Random Number Generator
*
* @package Random
* @author Jim Wigginton <terrafrost@php.net>
* @access public
*/
class Random
{
/** /**
* Generate a random string. * Generate a random string.
* *
@ -61,16 +40,28 @@ if (!function_exists('crypt_random_string')) {
* microoptimizations because this function has the potential of being called a huge number of times. * microoptimizations because this function has the potential of being called a huge number of times.
* eg. for RSA key generation. * eg. for RSA key generation.
* *
* @param Integer $length * @param int $length
* @return String * @return string
* @access public
*/ */
function crypt_random_string($length) static function string($length)
{ {
if (CRYPT_RANDOM_IS_WINDOWS) { if (version_compare(PHP_VERSION, '7.0.0', '>=')) {
try {
return \random_bytes($length);
} catch (\Throwable $e) {
// If a sufficient source of randomness is unavailable, random_bytes() will throw an
// object that implements the Throwable interface (Exception, TypeError, Error).
// We don't actually need to do anything here. The string() method should just continue
// as normal. Note, however, that if we don't have a sufficient source of randomness for
// random_bytes(), most of the other calls here will fail too, so we'll end up using
// the PHP implementation.
}
}
if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
// method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call. // method 1. prior to PHP 5.3 this would call rand() on windows hence the function_exists('class_alias') call.
// ie. class_alias is a function that was introduced in PHP 5.3 // ie. class_alias is a function that was introduced in PHP 5.3
if (function_exists('mcrypt_create_iv') && function_exists('class_alias')) { if (extension_loaded('mcrypt') && function_exists('class_alias')) {
return mcrypt_create_iv($length); return mcrypt_create_iv($length);
} }
// method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was, // method 2. openssl_random_pseudo_bytes was introduced in PHP 5.3.0 but prior to PHP 5.3.4 there was,
@ -86,12 +77,12 @@ if (!function_exists('crypt_random_string')) {
// https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80 // https://github.com/php/php-src/blob/7014a0eb6d1611151a286c0ff4f2238f92c120d6/win32/winutil.c#L80
// //
// we're calling it, all the same, in the off chance that the mcrypt extension is not available // we're calling it, all the same, in the off chance that the mcrypt extension is not available
if (function_exists('openssl_random_pseudo_bytes') && version_compare(PHP_VERSION, '5.3.4', '>=')) { if (extension_loaded('openssl') && version_compare(PHP_VERSION, '5.3.4', '>=')) {
return openssl_random_pseudo_bytes($length); return openssl_random_pseudo_bytes($length);
} }
} else { } else {
// method 1. the fastest // method 1. the fastest
if (function_exists('openssl_random_pseudo_bytes')) { if (extension_loaded('openssl')) {
return openssl_random_pseudo_bytes($length); return openssl_random_pseudo_bytes($length);
} }
// method 2 // method 2
@ -109,7 +100,7 @@ if (!function_exists('crypt_random_string')) {
// surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're // surprisingly slower than method 2. maybe that's because mcrypt_create_iv does a bunch of error checking that we're
// not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir // not doing. regardless, this'll only be called if this PHP script couldn't open /dev/urandom due to open_basedir
// restrictions or some such // restrictions or some such
if (function_exists('mcrypt_create_iv')) { if (extension_loaded('mcrypt')) {
return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM); return mcrypt_create_iv($length, MCRYPT_DEV_URANDOM);
} }
} }
@ -149,13 +140,13 @@ if (!function_exists('crypt_random_string')) {
session_start(); session_start();
$v = $seed = $_SESSION['seed'] = pack('H*', sha1( $v = $seed = $_SESSION['seed'] = pack('H*', sha1(
serialize($_SERVER) . (isset($_SERVER) ? phpseclib_safe_serialize($_SERVER) : '') .
serialize($_POST) . (isset($_POST) ? phpseclib_safe_serialize($_POST) : '') .
serialize($_GET) . (isset($_GET) ? phpseclib_safe_serialize($_GET) : '') .
serialize($_COOKIE) . (isset($_COOKIE) ? phpseclib_safe_serialize($_COOKIE) : '') .
serialize($GLOBALS) . phpseclib_safe_serialize($GLOBALS) .
serialize($_SESSION) . phpseclib_safe_serialize($_SESSION) .
serialize($_OLD_SESSION) phpseclib_safe_serialize($_OLD_SESSION)
)); ));
if (!isset($_SESSION['count'])) { if (!isset($_SESSION['count'])) {
$_SESSION['count'] = 0; $_SESSION['count'] = 0;
@ -194,44 +185,26 @@ if (!function_exists('crypt_random_string')) {
// //
// http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives // http://en.wikipedia.org/wiki/Cryptographically_secure_pseudorandom_number_generator#Designs_based_on_cryptographic_primitives
switch (true) { switch (true) {
case phpseclib_resolve_include_path('Crypt/AES.php'): case class_exists('\phpseclib\Crypt\AES'):
if (!class_exists('Crypt_AES')) { $crypto = new AES(Base::MODE_CTR);
include_once 'AES.php';
}
$crypto = new Crypt_AES(CRYPT_AES_MODE_CTR);
break; break;
case phpseclib_resolve_include_path('Crypt/Twofish.php'): case class_exists('\phpseclib\Crypt\Twofish'):
if (!class_exists('Crypt_Twofish')) { $crypto = new Twofish(Base::MODE_CTR);
include_once 'Twofish.php';
}
$crypto = new Crypt_Twofish(CRYPT_TWOFISH_MODE_CTR);
break; break;
case phpseclib_resolve_include_path('Crypt/Blowfish.php'): case class_exists('\phpseclib\Crypt\Blowfish'):
if (!class_exists('Crypt_Blowfish')) { $crypto = new Blowfish(Base::MODE_CTR);
include_once 'Blowfish.php';
}
$crypto = new Crypt_Blowfish(CRYPT_BLOWFISH_MODE_CTR);
break; break;
case phpseclib_resolve_include_path('Crypt/TripleDES.php'): case class_exists('\phpseclib\Crypt\TripleDES'):
if (!class_exists('Crypt_TripleDES')) { $crypto = new TripleDES(Base::MODE_CTR);
include_once 'TripleDES.php';
}
$crypto = new Crypt_TripleDES(CRYPT_DES_MODE_CTR);
break; break;
case phpseclib_resolve_include_path('Crypt/DES.php'): case class_exists('\phpseclib\Crypt\DES'):
if (!class_exists('Crypt_DES')) { $crypto = new DES(Base::MODE_CTR);
include_once 'DES.php';
}
$crypto = new Crypt_DES(CRYPT_DES_MODE_CTR);
break; break;
case phpseclib_resolve_include_path('Crypt/RC4.php'): case class_exists('\phpseclib\Crypt\RC4'):
if (!class_exists('Crypt_RC4')) { $crypto = new RC4();
include_once 'RC4.php';
}
$crypto = new Crypt_RC4();
break; break;
default: default:
user_error('crypt_random_string requires at least one symmetric cipher be loaded'); user_error(__CLASS__ . ' requires at least one symmetric cipher be loaded');
return false; return false;
} }
@ -261,40 +234,37 @@ if (!function_exists('crypt_random_string')) {
} }
} }
if (!function_exists('phpseclib_resolve_include_path')) { if (!function_exists('phpseclib_safe_serialize')) {
/** /**
* Resolve filename against the include path. * Safely serialize variables
* *
* Wrapper around stream_resolve_include_path() (which was introduced in * If a class has a private __sleep() method it'll give a fatal error on PHP 5.2 and earlier.
* PHP 5.3.2) with fallback implementation for earlier PHP versions. * PHP 5.3 will emit a warning.
* *
* @param string $filename * @param mixed $arr
* @return mixed Filename (string) on success, false otherwise.
* @access public * @access public
*/ */
function phpseclib_resolve_include_path($filename) function phpseclib_safe_serialize(&$arr)
{ {
if (function_exists('stream_resolve_include_path')) { if (is_object($arr)) {
return stream_resolve_include_path($filename); return '';
} }
if (!is_array($arr)) {
// handle non-relative paths return serialize($arr);
if (file_exists($filename)) {
return realpath($filename);
} }
// prevent circular array recursion
$paths = PATH_SEPARATOR == ':' ? if (isset($arr['__phpseclib_marker'])) {
preg_split('#(?<!phar):#', get_include_path()) : return '';
explode(PATH_SEPARATOR, get_include_path()); }
foreach ($paths as $prefix) { $safearr = array();
// path's specified in include_path don't always end in / $arr['__phpseclib_marker'] = true;
$ds = substr($prefix, -1) == DIRECTORY_SEPARATOR ? '' : DIRECTORY_SEPARATOR; foreach (array_keys($arr) as $key) {
$file = $prefix . $ds . $filename; // do not recurse on the '__phpseclib_marker' key itself, for smaller memory usage
if (file_exists($file)) { if ($key !== '__phpseclib_marker') {
return realpath($file); $safearr[$key] = phpseclib_safe_serialize($arr[$key]);
} }
} }
unset($arr['__phpseclib_marker']);
return false; return serialize($safearr);
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -5,14 +5,14 @@
* *
* Uses mcrypt, if available, and an internal implementation, otherwise. Operates in the EDE3 mode (encrypt-decrypt-encrypt). * Uses mcrypt, if available, and an internal implementation, otherwise. Operates in the EDE3 mode (encrypt-decrypt-encrypt).
* *
* PHP versions 4 and 5 * PHP version 5
* *
* Here's a short example of how to use this library: * Here's a short example of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'Crypt/TripleDES.php'; * include 'vendor/autoload.php';
* *
* $des = new Crypt_TripleDES(); * $des = new \phpseclib\Crypt\TripleDES();
* *
* $des->setKey('abcdefghijklmnopqrstuvwx'); * $des->setKey('abcdefghijklmnopqrstuvwx');
* *
@ -26,99 +26,64 @@
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category Crypt * @category Crypt
* @package Crypt_TripleDES * @package TripleDES
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2007 Jim Wigginton * @copyright 2007 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
/** namespace phpseclib\Crypt;
* Include Crypt_DES
*/
if (!class_exists('Crypt_DES')) {
include_once 'DES.php';
}
/**
* Encrypt / decrypt using inner chaining
*
* Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (CRYPT_DES_MODE_CBC3).
*/
define('CRYPT_DES_MODE_3CBC', -2);
/**
* Encrypt / decrypt using outer chaining
*
* Outer chaining is used by SSH-2 and when the mode is set to CRYPT_DES_MODE_CBC.
*/
define('CRYPT_DES_MODE_CBC3', CRYPT_DES_MODE_CBC);
/** /**
* Pure-PHP implementation of Triple DES. * Pure-PHP implementation of Triple DES.
* *
* @package Crypt_TripleDES * @package TripleDES
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @access public * @access public
*/ */
class Crypt_TripleDES extends Crypt_DES class TripleDES extends DES
{ {
/** /**
* The default password key_size used by setPassword() * Encrypt / decrypt using inner chaining
* *
* @see Crypt_DES::password_key_size * Inner chaining is used by SSH-1 and is generally considered to be less secure then outer chaining (self::MODE_CBC3).
* @see Crypt_Base::password_key_size */
* @see Crypt_Base::setPassword() const MODE_3CBC = -2;
* @var Integer
/**
* Encrypt / decrypt using outer chaining
*
* Outer chaining is used by SSH-2 and when the mode is set to \phpseclib\Crypt\Base::MODE_CBC.
*/
const MODE_CBC3 = Base::MODE_CBC;
/**
* Key Length (in bytes)
*
* @see \phpseclib\Crypt\TripleDES::setKeyLength()
* @var int
* @access private * @access private
*/ */
var $password_key_size = 24; var $key_length = 24;
/** /**
* The default salt used by setPassword() * The default salt used by setPassword()
* *
* @see Crypt_Base::password_default_salt * @see \phpseclib\Crypt\Base::password_default_salt
* @see Crypt_Base::setPassword() * @see \phpseclib\Crypt\Base::setPassword()
* @var String * @var string
* @access private * @access private
*/ */
var $password_default_salt = 'phpseclib'; var $password_default_salt = 'phpseclib';
/**
* The namespace used by the cipher for its constants.
*
* @see Crypt_DES::const_namespace
* @see Crypt_Base::const_namespace
* @var String
* @access private
*/
var $const_namespace = 'DES';
/** /**
* The mcrypt specific name of the cipher * The mcrypt specific name of the cipher
* *
* @see Crypt_DES::cipher_name_mcrypt * @see \phpseclib\Crypt\DES::cipher_name_mcrypt
* @see Crypt_Base::cipher_name_mcrypt * @see \phpseclib\Crypt\Base::cipher_name_mcrypt
* @var String * @var string
* @access private * @access private
*/ */
var $cipher_name_mcrypt = 'tripledes'; var $cipher_name_mcrypt = 'tripledes';
@ -126,8 +91,8 @@ class Crypt_TripleDES extends Crypt_DES
/** /**
* Optimizing value while CFB-encrypting * Optimizing value while CFB-encrypting
* *
* @see Crypt_Base::cfb_init_len * @see \phpseclib\Crypt\Base::cfb_init_len
* @var Integer * @var int
* @access private * @access private
*/ */
var $cfb_init_len = 750; var $cfb_init_len = 750;
@ -135,27 +100,27 @@ class Crypt_TripleDES extends Crypt_DES
/** /**
* max possible size of $key * max possible size of $key
* *
* @see Crypt_TripleDES::setKey() * @see self::setKey()
* @see Crypt_DES::setKey() * @see \phpseclib\Crypt\DES::setKey()
* @var String * @var string
* @access private * @access private
*/ */
var $key_size_max = 24; var $key_length_max = 24;
/** /**
* Internal flag whether using CRYPT_DES_MODE_3CBC or not * Internal flag whether using self::MODE_3CBC or not
* *
* @var Boolean * @var bool
* @access private * @access private
*/ */
var $mode_3cbc; var $mode_3cbc;
/** /**
* The Crypt_DES objects * The \phpseclib\Crypt\DES objects
* *
* Used only if $mode_3cbc === true * Used only if $mode_3cbc === true
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $des; var $des;
@ -167,61 +132,82 @@ class Crypt_TripleDES extends Crypt_DES
* *
* $mode could be: * $mode could be:
* *
* - CRYPT_DES_MODE_ECB * - \phpseclib\Crypt\Base::MODE_ECB
* *
* - CRYPT_DES_MODE_CBC * - \phpseclib\Crypt\Base::MODE_CBC
* *
* - CRYPT_DES_MODE_CTR * - \phpseclib\Crypt\Base::MODE_CTR
* *
* - CRYPT_DES_MODE_CFB * - \phpseclib\Crypt\Base::MODE_CFB
* *
* - CRYPT_DES_MODE_OFB * - \phpseclib\Crypt\Base::MODE_OFB
* *
* - CRYPT_DES_MODE_3CBC * - \phpseclib\Crypt\TripleDES::MODE_3CBC
* *
* If not explicitly set, CRYPT_DES_MODE_CBC will be used. * If not explicitly set, \phpseclib\Crypt\Base::MODE_CBC will be used.
* *
* @see Crypt_DES::Crypt_DES() * @see \phpseclib\Crypt\DES::__construct()
* @see Crypt_Base::Crypt_Base() * @see \phpseclib\Crypt\Base::__construct()
* @param optional Integer $mode * @param int $mode
* @access public * @access public
*/ */
function Crypt_TripleDES($mode = CRYPT_DES_MODE_CBC) function __construct($mode = Base::MODE_CBC)
{ {
switch ($mode) { switch ($mode) {
// In case of CRYPT_DES_MODE_3CBC, we init as CRYPT_DES_MODE_CBC // In case of self::MODE_3CBC, we init as CRYPT_DES_MODE_CBC
// and additional flag us internally as 3CBC // and additional flag us internally as 3CBC
case CRYPT_DES_MODE_3CBC: case self::MODE_3CBC:
parent::Crypt_Base(CRYPT_DES_MODE_CBC); parent::__construct(Base::MODE_CBC);
$this->mode_3cbc = true; $this->mode_3cbc = true;
// This three $des'es will do the 3CBC work (if $key > 64bits) // This three $des'es will do the 3CBC work (if $key > 64bits)
$this->des = array( $this->des = array(
new Crypt_DES(CRYPT_DES_MODE_CBC), new DES(Base::MODE_CBC),
new Crypt_DES(CRYPT_DES_MODE_CBC), new DES(Base::MODE_CBC),
new Crypt_DES(CRYPT_DES_MODE_CBC), new DES(Base::MODE_CBC),
); );
// we're going to be doing the padding, ourselves, so disable it in the Crypt_DES objects // we're going to be doing the padding, ourselves, so disable it in the \phpseclib\Crypt\DES objects
$this->des[0]->disablePadding(); $this->des[0]->disablePadding();
$this->des[1]->disablePadding(); $this->des[1]->disablePadding();
$this->des[2]->disablePadding(); $this->des[2]->disablePadding();
break; break;
// If not 3CBC, we init as usual // If not 3CBC, we init as usual
default: default:
parent::Crypt_Base($mode); parent::__construct($mode);
} }
} }
/**
* Test for engine validity
*
* This is mainly just a wrapper to set things up for \phpseclib\Crypt\Base::isValidEngine()
*
* @see \phpseclib\Crypt\Base::__construct()
* @param int $engine
* @access public
* @return bool
*/
function isValidEngine($engine)
{
if ($engine == self::ENGINE_OPENSSL) {
$this->cipher_name_openssl_ecb = 'des-ede3';
$mode = $this->_openssl_translate_mode();
$this->cipher_name_openssl = $mode == 'ecb' ? 'des-ede3' : 'des-ede3-' . $mode;
}
return parent::isValidEngine($engine);
}
/** /**
* Sets the initialization vector. (optional) * Sets the initialization vector. (optional)
* *
* SetIV is not required when CRYPT_DES_MODE_ECB is being used. If not explicitly set, it'll be assumed * SetIV is not required when \phpseclib\Crypt\Base::MODE_ECB is being used. If not explicitly set, it'll be assumed
* to be all zero's. * to be all zero's.
* *
* @see Crypt_Base::setIV() * @see \phpseclib\Crypt\Base::setIV()
* @access public * @access public
* @param String $iv * @param string $iv
*/ */
function setIV($iv) function setIV($iv)
{ {
@ -233,6 +219,32 @@ class Crypt_TripleDES extends Crypt_DES
} }
} }
/**
* Sets the key length.
*
* Valid key lengths are 64, 128 and 192
*
* @see \phpseclib\Crypt\Base:setKeyLength()
* @access public
* @param int $length
*/
function setKeyLength($length)
{
$length >>= 3;
switch (true) {
case $length <= 8:
$this->key_length = 8;
break;
case $length <= 16:
$this->key_length = 16;
break;
default:
$this->key_length = 24;
}
parent::setKeyLength($length);
}
/** /**
* Sets the key. * Sets the key.
* *
@ -244,24 +256,24 @@ class Crypt_TripleDES extends Crypt_DES
* If the key is not explicitly set, it'll be assumed to be all null bytes. * If the key is not explicitly set, it'll be assumed to be all null bytes.
* *
* @access public * @access public
* @see Crypt_DES::setKey() * @see \phpseclib\Crypt\DES::setKey()
* @see Crypt_Base::setKey() * @see \phpseclib\Crypt\Base::setKey()
* @param String $key * @param string $key
*/ */
function setKey($key) function setKey($key)
{ {
$length = strlen($key); $length = $this->explicit_key_length ? $this->key_length : strlen($key);
if ($length > 8) { if ($length > 8) {
$key = str_pad(substr($key, 0, 24), 24, chr(0)); $key = str_pad(substr($key, 0, 24), 24, chr(0));
// if $key is between 64 and 128-bits, use the first 64-bits as the last, per this: // if $key is between 64 and 128-bits, use the first 64-bits as the last, per this:
// http://php.net/function.mcrypt-encrypt#47973 // http://php.net/function.mcrypt-encrypt#47973
//$key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24); $key = $length <= 16 ? substr_replace($key, substr($key, 0, 8), 16) : substr($key, 0, 24);
} else { } else {
$key = str_pad($key, 8, chr(0)); $key = str_pad($key, 8, chr(0));
} }
parent::setKey($key); parent::setKey($key);
// And in case of CRYPT_DES_MODE_3CBC: // And in case of self::MODE_3CBC:
// if key <= 64bits we not need the 3 $des to work, // if key <= 64bits we not need the 3 $des to work,
// because we will then act as regular DES-CBC with just a <= 64bit key. // because we will then act as regular DES-CBC with just a <= 64bit key.
// So only if the key > 64bits (> 8 bytes) we will call setKey() for the 3 $des. // So only if the key > 64bits (> 8 bytes) we will call setKey() for the 3 $des.
@ -275,15 +287,15 @@ class Crypt_TripleDES extends Crypt_DES
/** /**
* Encrypts a message. * Encrypts a message.
* *
* @see Crypt_Base::encrypt() * @see \phpseclib\Crypt\Base::encrypt()
* @access public * @access public
* @param String $plaintext * @param string $plaintext
* @return String $cipertext * @return string $cipertext
*/ */
function encrypt($plaintext) function encrypt($plaintext)
{ {
// parent::en/decrypt() is able to do all the work for all modes and keylengths, // parent::en/decrypt() is able to do all the work for all modes and keylengths,
// except for: CRYPT_DES_MODE_3CBC (inner chaining CBC) with a key > 64bits // except for: self::MODE_3CBC (inner chaining CBC) with a key > 64bits
// if the key is smaller then 8, do what we'd normally do // if the key is smaller then 8, do what we'd normally do
if ($this->mode_3cbc && strlen($this->key) > 8) { if ($this->mode_3cbc && strlen($this->key) > 8) {
@ -302,10 +314,10 @@ class Crypt_TripleDES extends Crypt_DES
/** /**
* Decrypts a message. * Decrypts a message.
* *
* @see Crypt_Base::decrypt() * @see \phpseclib\Crypt\Base::decrypt()
* @access public * @access public
* @param String $ciphertext * @param string $ciphertext
* @return String $plaintext * @return string $plaintext
*/ */
function decrypt($ciphertext) function decrypt($ciphertext)
{ {
@ -353,13 +365,13 @@ class Crypt_TripleDES extends Crypt_DES
* outputs. The reason is due to the fact that the initialization vector's change after every encryption / * outputs. The reason is due to the fact that the initialization vector's change after every encryption /
* decryption round when the continuous buffer is enabled. When it's disabled, they remain constant. * decryption round when the continuous buffer is enabled. When it's disabled, they remain constant.
* *
* Put another way, when the continuous buffer is enabled, the state of the Crypt_DES() object changes after each * Put another way, when the continuous buffer is enabled, the state of the \phpseclib\Crypt\DES() object changes after each
* encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that * encryption / decryption round, whereas otherwise, it'd remain constant. For this reason, it's recommended that
* continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them), * continuous buffers not be used. They do offer better security and are, in fact, sometimes required (SSH uses them),
* however, they are also less intuitive and more likely to cause you problems. * however, they are also less intuitive and more likely to cause you problems.
* *
* @see Crypt_Base::enableContinuousBuffer() * @see \phpseclib\Crypt\Base::enableContinuousBuffer()
* @see Crypt_TripleDES::disableContinuousBuffer() * @see self::disableContinuousBuffer()
* @access public * @access public
*/ */
function enableContinuousBuffer() function enableContinuousBuffer()
@ -377,8 +389,8 @@ class Crypt_TripleDES extends Crypt_DES
* *
* The default behavior. * The default behavior.
* *
* @see Crypt_Base::disableContinuousBuffer() * @see \phpseclib\Crypt\Base::disableContinuousBuffer()
* @see Crypt_TripleDES::enableContinuousBuffer() * @see self::enableContinuousBuffer()
* @access public * @access public
*/ */
function disableContinuousBuffer() function disableContinuousBuffer()
@ -394,8 +406,8 @@ class Crypt_TripleDES extends Crypt_DES
/** /**
* Creates the key schedule * Creates the key schedule
* *
* @see Crypt_DES::_setupKey() * @see \phpseclib\Crypt\DES::_setupKey()
* @see Crypt_Base::_setupKey() * @see \phpseclib\Crypt\Base::_setupKey()
* @access private * @access private
*/ */
function _setupKey() function _setupKey()
@ -425,4 +437,24 @@ class Crypt_TripleDES extends Crypt_DES
// setup our key // setup our key
parent::_setupKey(); parent::_setupKey();
} }
/**
* Sets the internal crypt engine
*
* @see \phpseclib\Crypt\Base::__construct()
* @see \phpseclib\Crypt\Base::setPreferredEngine()
* @param int $engine
* @access public
* @return int
*/
function setPreferredEngine($engine)
{
if ($this->mode_3cbc) {
$this->des[0]->setPreferredEngine($engine);
$this->des[1]->setPreferredEngine($engine);
$this->des[2]->setPreferredEngine($engine);
}
return parent::setPreferredEngine($engine);
}
} }

View file

@ -5,7 +5,7 @@
* *
* Uses mcrypt, if available, and an internal implementation, otherwise. * Uses mcrypt, if available, and an internal implementation, otherwise.
* *
* PHP versions 4 and 5 * PHP version 5
* *
* Useful resources are as follows: * Useful resources are as follows:
* *
@ -14,9 +14,9 @@
* Here's a short example of how to use this library: * Here's a short example of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'Crypt/Twofish.php'; * include 'vendor/autoload.php';
* *
* $twofish = new Crypt_Twofish(); * $twofish = new \phpseclib\Crypt\Twofish();
* *
* $twofish->setKey('12345678901234567890123456789012'); * $twofish->setKey('12345678901234567890123456789012');
* *
@ -26,26 +26,8 @@
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category Crypt * @category Crypt
* @package Crypt_Twofish * @package Twofish
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @author Hans-Juergen Petrich <petrich@tronic-media.com> * @author Hans-Juergen Petrich <petrich@tronic-media.com>
* @copyright 2007 Jim Wigginton * @copyright 2007 Jim Wigginton
@ -53,92 +35,23 @@
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
/** namespace phpseclib\Crypt;
* Include Crypt_Base
*
* Base cipher class
*/
if (!class_exists('Crypt_Base')) {
include_once 'Base.php';
}
/**#@+
* @access public
* @see Crypt_Twofish::encrypt()
* @see Crypt_Twofish::decrypt()
*/
/**
* Encrypt / decrypt using the Counter mode.
*
* Set to -1 since that's what Crypt/Random.php uses to index the CTR mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Counter_.28CTR.29
*/
define('CRYPT_TWOFISH_MODE_CTR', CRYPT_MODE_CTR);
/**
* Encrypt / decrypt using the Electronic Code Book mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Electronic_codebook_.28ECB.29
*/
define('CRYPT_TWOFISH_MODE_ECB', CRYPT_MODE_ECB);
/**
* Encrypt / decrypt using the Code Book Chaining mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher-block_chaining_.28CBC.29
*/
define('CRYPT_TWOFISH_MODE_CBC', CRYPT_MODE_CBC);
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Cipher_feedback_.28CFB.29
*/
define('CRYPT_TWOFISH_MODE_CFB', CRYPT_MODE_CFB);
/**
* Encrypt / decrypt using the Cipher Feedback mode.
*
* @link http://en.wikipedia.org/wiki/Block_cipher_modes_of_operation#Output_feedback_.28OFB.29
*/
define('CRYPT_TWOFISH_MODE_OFB', CRYPT_MODE_OFB);
/**#@-*/
/**#@+
* @access private
* @see Crypt_Base::Crypt_Base()
*/
/**
* Toggles the internal implementation
*/
define('CRYPT_TWOFISH_MODE_INTERNAL', CRYPT_MODE_INTERNAL);
/**
* Toggles the mcrypt implementation
*/
define('CRYPT_TWOFISH_MODE_MCRYPT', CRYPT_MODE_MCRYPT);
/**#@-*/
/** /**
* Pure-PHP implementation of Twofish. * Pure-PHP implementation of Twofish.
* *
* @package Crypt_Twofish * @package Twofish
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @author Hans-Juergen Petrich <petrich@tronic-media.com> * @author Hans-Juergen Petrich <petrich@tronic-media.com>
* @access public * @access public
*/ */
class Crypt_Twofish extends Crypt_Base class Twofish extends Base
{ {
/**
* The namespace used by the cipher for its constants.
*
* @see Crypt_Base::const_namespace
* @var String
* @access private
*/
var $const_namespace = 'TWOFISH';
/** /**
* The mcrypt specific name of the cipher * The mcrypt specific name of the cipher
* *
* @see Crypt_Base::cipher_name_mcrypt * @see \phpseclib\Crypt\Base::cipher_name_mcrypt
* @var String * @var string
* @access private * @access private
*/ */
var $cipher_name_mcrypt = 'twofish'; var $cipher_name_mcrypt = 'twofish';
@ -146,8 +59,8 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* Optimizing value while CFB-encrypting * Optimizing value while CFB-encrypting
* *
* @see Crypt_Base::cfb_init_len * @see \phpseclib\Crypt\Base::cfb_init_len
* @var Integer * @var int
* @access private * @access private
*/ */
var $cfb_init_len = 800; var $cfb_init_len = 800;
@ -155,10 +68,10 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* Q-Table * Q-Table
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $q0 = array ( var $q0 = array(
0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76, 0xA9, 0x67, 0xB3, 0xE8, 0x04, 0xFD, 0xA3, 0x76,
0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38, 0x9A, 0x92, 0x80, 0x78, 0xE4, 0xDD, 0xD1, 0x38,
0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C, 0x0D, 0xC6, 0x35, 0x98, 0x18, 0xF7, 0xEC, 0x6C,
@ -196,10 +109,10 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* Q-Table * Q-Table
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $q1 = array ( var $q1 = array(
0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8, 0x75, 0xF3, 0xC6, 0xF4, 0xDB, 0x7B, 0xFB, 0xC8,
0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B, 0x4A, 0xD3, 0xE6, 0x6B, 0x45, 0x7D, 0xE8, 0x4B,
0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1, 0xD6, 0x32, 0xD8, 0xFD, 0x37, 0x71, 0xF1, 0xE1,
@ -237,10 +150,10 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* M-Table * M-Table
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $m0 = array ( var $m0 = array(
0xBCBC3275, 0xECEC21F3, 0x202043C6, 0xB3B3C9F4, 0xDADA03DB, 0x02028B7B, 0xE2E22BFB, 0x9E9EFAC8, 0xBCBC3275, 0xECEC21F3, 0x202043C6, 0xB3B3C9F4, 0xDADA03DB, 0x02028B7B, 0xE2E22BFB, 0x9E9EFAC8,
0xC9C9EC4A, 0xD4D409D3, 0x18186BE6, 0x1E1E9F6B, 0x98980E45, 0xB2B2387D, 0xA6A6D2E8, 0x2626B74B, 0xC9C9EC4A, 0xD4D409D3, 0x18186BE6, 0x1E1E9F6B, 0x98980E45, 0xB2B2387D, 0xA6A6D2E8, 0x2626B74B,
0x3C3C57D6, 0x93938A32, 0x8282EED8, 0x525298FD, 0x7B7BD437, 0xBBBB3771, 0x5B5B97F1, 0x474783E1, 0x3C3C57D6, 0x93938A32, 0x8282EED8, 0x525298FD, 0x7B7BD437, 0xBBBB3771, 0x5B5B97F1, 0x474783E1,
@ -278,10 +191,10 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* M-Table * M-Table
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $m1 = array ( var $m1 = array(
0xA9D93939, 0x67901717, 0xB3719C9C, 0xE8D2A6A6, 0x04050707, 0xFD985252, 0xA3658080, 0x76DFE4E4, 0xA9D93939, 0x67901717, 0xB3719C9C, 0xE8D2A6A6, 0x04050707, 0xFD985252, 0xA3658080, 0x76DFE4E4,
0x9A084545, 0x92024B4B, 0x80A0E0E0, 0x78665A5A, 0xE4DDAFAF, 0xDDB06A6A, 0xD1BF6363, 0x38362A2A, 0x9A084545, 0x92024B4B, 0x80A0E0E0, 0x78665A5A, 0xE4DDAFAF, 0xDDB06A6A, 0xD1BF6363, 0x38362A2A,
0x0D54E6E6, 0xC6432020, 0x3562CCCC, 0x98BEF2F2, 0x181E1212, 0xF724EBEB, 0xECD7A1A1, 0x6C774141, 0x0D54E6E6, 0xC6432020, 0x3562CCCC, 0x98BEF2F2, 0x181E1212, 0xF724EBEB, 0xECD7A1A1, 0x6C774141,
@ -319,10 +232,10 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* M-Table * M-Table
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $m2 = array ( var $m2 = array(
0xBC75BC32, 0xECF3EC21, 0x20C62043, 0xB3F4B3C9, 0xDADBDA03, 0x027B028B, 0xE2FBE22B, 0x9EC89EFA, 0xBC75BC32, 0xECF3EC21, 0x20C62043, 0xB3F4B3C9, 0xDADBDA03, 0x027B028B, 0xE2FBE22B, 0x9EC89EFA,
0xC94AC9EC, 0xD4D3D409, 0x18E6186B, 0x1E6B1E9F, 0x9845980E, 0xB27DB238, 0xA6E8A6D2, 0x264B26B7, 0xC94AC9EC, 0xD4D3D409, 0x18E6186B, 0x1E6B1E9F, 0x9845980E, 0xB27DB238, 0xA6E8A6D2, 0x264B26B7,
0x3CD63C57, 0x9332938A, 0x82D882EE, 0x52FD5298, 0x7B377BD4, 0xBB71BB37, 0x5BF15B97, 0x47E14783, 0x3CD63C57, 0x9332938A, 0x82D882EE, 0x52FD5298, 0x7B377BD4, 0xBB71BB37, 0x5BF15B97, 0x47E14783,
@ -360,10 +273,10 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* M-Table * M-Table
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $m3 = array ( var $m3 = array(
0xD939A9D9, 0x90176790, 0x719CB371, 0xD2A6E8D2, 0x05070405, 0x9852FD98, 0x6580A365, 0xDFE476DF, 0xD939A9D9, 0x90176790, 0x719CB371, 0xD2A6E8D2, 0x05070405, 0x9852FD98, 0x6580A365, 0xDFE476DF,
0x08459A08, 0x024B9202, 0xA0E080A0, 0x665A7866, 0xDDAFE4DD, 0xB06ADDB0, 0xBF63D1BF, 0x362A3836, 0x08459A08, 0x024B9202, 0xA0E080A0, 0x665A7866, 0xDDAFE4DD, 0xB06ADDB0, 0xBF63D1BF, 0x362A3836,
0x54E60D54, 0x4320C643, 0x62CC3562, 0xBEF298BE, 0x1E12181E, 0x24EBF724, 0xD7A1ECD7, 0x77416C77, 0x54E60D54, 0x4320C643, 0x62CC3562, 0xBEF298BE, 0x1E12181E, 0x24EBF724, 0xD7A1ECD7, 0x77416C77,
@ -401,7 +314,7 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* The Key Schedule Array * The Key Schedule Array
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $K = array(); var $K = array();
@ -409,7 +322,7 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* The Key depended S-Table 0 * The Key depended S-Table 0
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $S0 = array(); var $S0 = array();
@ -417,7 +330,7 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* The Key depended S-Table 1 * The Key depended S-Table 1
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $S1 = array(); var $S1 = array();
@ -425,7 +338,7 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* The Key depended S-Table 2 * The Key depended S-Table 2
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $S2 = array(); var $S2 = array();
@ -433,7 +346,7 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* The Key depended S-Table 3 * The Key depended S-Table 3
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $S3 = array(); var $S3 = array();
@ -441,47 +354,48 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* Holds the last used key * Holds the last used key
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $kl; var $kl;
/** /**
* Sets the key. * The Key Length (in bytes)
* *
* Keys can be of any length. Twofish, itself, requires the use of a key that's 128, 192 or 256-bits long. * @see Crypt_Twofish::setKeyLength()
* If the key is less than 256-bits we round the length up to the closest valid key length, * @var int
* padding $key with null bytes. If the key is more than 256-bits, we trim the excess bits. * @access private
*/
var $key_length = 16;
/**
* Sets the key length.
* *
* If the key is not explicitly set, it'll be assumed a 128 bits key to be all null bytes. * Valid key lengths are 128, 192 or 256 bits
* *
* @access public * @access public
* @see Crypt_Base::setKey() * @param int $length
* @param String $key
*/ */
function setKey($key) function setKeyLength($length)
{ {
$keylength = strlen($key);
switch (true) { switch (true) {
case $keylength <= 16: case $length <= 128:
$key = str_pad($key, 16, "\0"); $this->key_length = 16;
break; break;
case $keylength <= 24: case $length <= 192:
$key = str_pad($key, 24, "\0"); $this->key_length = 24;
break; break;
case $keylength < 32: default:
$key = str_pad($key, 32, "\0"); $this->key_length = 32;
break;
case $keylength > 32:
$key = substr($key, 0, 32);
} }
parent::setKey($key);
parent::setKeyLength($length);
} }
/** /**
* Setup the key (expansion) * Setup the key (expansion)
* *
* @see Crypt_Base::_setupKey() * @see \phpseclib\Crypt\Base::_setupKey()
* @access private * @access private
*/ */
function _setupKey() function _setupKey()
@ -506,9 +420,9 @@ class Crypt_Twofish extends Crypt_Base
switch (strlen($this->key)) { switch (strlen($this->key)) {
case 16: case 16:
list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[1], $le_longs[2]); list($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[1], $le_longs[2]);
list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[3], $le_longs[4]); list($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[3], $le_longs[4]);
for ($i = 0, $j = 1; $i < 40; $i+= 2,$j+= 2) { for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) {
$A = $m0[$q0[$q0[$i] ^ $key[ 9]] ^ $key[1]] ^ $A = $m0[$q0[$q0[$i] ^ $key[ 9]] ^ $key[1]] ^
$m1[$q0[$q1[$i] ^ $key[10]] ^ $key[2]] ^ $m1[$q0[$q1[$i] ^ $key[10]] ^ $key[2]] ^
$m2[$q1[$q0[$i] ^ $key[11]] ^ $key[3]] ^ $m2[$q1[$q0[$i] ^ $key[11]] ^ $key[3]] ^
@ -529,9 +443,9 @@ class Crypt_Twofish extends Crypt_Base
} }
break; break;
case 24: case 24:
list ($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[1], $le_longs[2]); list($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[1], $le_longs[2]);
list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[3], $le_longs[4]); list($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[3], $le_longs[4]);
list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[5], $le_longs[6]); list($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[5], $le_longs[6]);
for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) {
$A = $m0[$q0[$q0[$q1[$i] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^ $A = $m0[$q0[$q0[$q1[$i] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^
$m1[$q0[$q1[$q1[$i] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^ $m1[$q0[$q1[$q1[$i] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^
@ -553,10 +467,10 @@ class Crypt_Twofish extends Crypt_Base
} }
break; break;
default: // 32 default: // 32
list ($sf, $se, $sd, $sc) = $this->_mdsrem($le_longs[1], $le_longs[2]); list($sf, $se, $sd, $sc) = $this->_mdsrem($le_longs[1], $le_longs[2]);
list ($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[3], $le_longs[4]); list($sb, $sa, $s9, $s8) = $this->_mdsrem($le_longs[3], $le_longs[4]);
list ($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[5], $le_longs[6]); list($s7, $s6, $s5, $s4) = $this->_mdsrem($le_longs[5], $le_longs[6]);
list ($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[7], $le_longs[8]); list($s3, $s2, $s1, $s0) = $this->_mdsrem($le_longs[7], $le_longs[8]);
for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) { for ($i = 0, $j = 1; $i < 40; $i+= 2, $j+= 2) {
$A = $m0[$q0[$q0[$q1[$q1[$i] ^ $key[25]] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^ $A = $m0[$q0[$q0[$q1[$q1[$i] ^ $key[25]] ^ $key[17]] ^ $key[ 9]] ^ $key[1]] ^
$m1[$q0[$q1[$q1[$q0[$i] ^ $key[26]] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^ $m1[$q0[$q1[$q1[$q0[$i] ^ $key[26]] ^ $key[18]] ^ $key[10]] ^ $key[2]] ^
@ -589,9 +503,9 @@ class Crypt_Twofish extends Crypt_Base
* _mdsrem function using by the twofish cipher algorithm * _mdsrem function using by the twofish cipher algorithm
* *
* @access private * @access private
* @param String $A * @param string $A
* @param String $B * @param string $B
* @return Array * @return array
*/ */
function _mdsrem($A, $B) function _mdsrem($A, $B)
{ {
@ -618,7 +532,9 @@ class Crypt_Twofish extends Crypt_Base
$u^= 0x7fffffff & ($t >> 1); $u^= 0x7fffffff & ($t >> 1);
// Add the modular polynomial on underflow. // Add the modular polynomial on underflow.
if ($t & 0x01) $u^= 0xa6 ; if ($t & 0x01) {
$u^= 0xa6 ;
}
// Remove t * (a + 1/a) * (x^3 + x). // Remove t * (a + 1/a) * (x^3 + x).
$B^= ($u << 24) | ($u << 8); $B^= ($u << 24) | ($u << 8);
@ -635,8 +551,8 @@ class Crypt_Twofish extends Crypt_Base
* Encrypts a block * Encrypts a block
* *
* @access private * @access private
* @param String $in * @param string $in
* @return String * @return string
*/ */
function _encryptBlock($in) function _encryptBlock($in)
{ {
@ -691,8 +607,8 @@ class Crypt_Twofish extends Crypt_Base
* Decrypts a block * Decrypts a block
* *
* @access private * @access private
* @param String $in * @param string $in
* @return String * @return string
*/ */
function _decryptBlock($in) function _decryptBlock($in)
{ {
@ -746,29 +662,27 @@ class Crypt_Twofish extends Crypt_Base
/** /**
* Setup the performance-optimized function for de/encrypt() * Setup the performance-optimized function for de/encrypt()
* *
* @see Crypt_Base::_setupInlineCrypt() * @see \phpseclib\Crypt\Base::_setupInlineCrypt()
* @access private * @access private
*/ */
function _setupInlineCrypt() function _setupInlineCrypt()
{ {
$lambda_functions =& Crypt_Twofish::_getLambdaFunctions(); $lambda_functions =& self::_getLambdaFunctions();
// Max. 10 Ultra-Hi-optimized inline-crypt functions. After that, we'll (still) create very fast code, but not the ultimate fast one. // Max. 10 Ultra-Hi-optimized inline-crypt functions. After that, we'll (still) create very fast code, but not the ultimate fast one.
$gen_hi_opt_code = (bool)( count($lambda_functions) < 10 ); // (Currently, for Crypt_Twofish, one generated $lambda_function cost on php5.5@32bit ~140kb unfreeable mem and ~240kb on php5.5@64bit)
$gen_hi_opt_code = (bool)(count($lambda_functions) < 10);
switch (true) { // Generation of a unique hash for our generated code
case $gen_hi_opt_code:
$code_hash = md5(str_pad("Crypt_Twofish, {$this->mode}, ", 32, "\0") . $this->key);
break;
default:
$code_hash = "Crypt_Twofish, {$this->mode}"; $code_hash = "Crypt_Twofish, {$this->mode}";
if ($gen_hi_opt_code) {
$code_hash = str_pad($code_hash, 32) . $this->_hashInlineCryptFunction($this->key);
} }
if (!isset($lambda_functions[$code_hash])) { if (!isset($lambda_functions[$code_hash])) {
switch (true) { switch (true) {
case $gen_hi_opt_code: case $gen_hi_opt_code:
$K = $this->K; $K = $this->K;
$init_crypt = ' $init_crypt = '
static $S0, $S1, $S2, $S3; static $S0, $S1, $S2, $S3;
if (!$S0) { if (!$S0) {
@ -786,7 +700,6 @@ class Crypt_Twofish extends Crypt_Base
for ($i = 0; $i < 40; ++$i) { for ($i = 0; $i < 40; ++$i) {
$K[] = '$K_' . $i; $K[] = '$K_' . $i;
} }
$init_crypt = ' $init_crypt = '
$S0 = $self->S0; $S0 = $self->S0;
$S1 = $self->S1; $S1 = $self->S1;

View file

@ -3,52 +3,36 @@
/** /**
* Pure-PHP ANSI Decoder * Pure-PHP ANSI Decoder
* *
* PHP versions 4 and 5 * PHP version 5
* *
* If you call read() in Net_SSH2 you may get {@link http://en.wikipedia.org/wiki/ANSI_escape_code ANSI escape codes} back. * If you call read() in \phpseclib\Net\SSH2 you may get {@link http://en.wikipedia.org/wiki/ANSI_escape_code ANSI escape codes} back.
* They'd look like chr(0x1B) . '[00m' or whatever (0x1B = ESC). They tell a * They'd look like chr(0x1B) . '[00m' or whatever (0x1B = ESC). They tell a
* {@link http://en.wikipedia.org/wiki/Terminal_emulator terminal emulator} how to format the characters, what * {@link http://en.wikipedia.org/wiki/Terminal_emulator terminal emulator} how to format the characters, what
* color to display them in, etc. File_ANSI is a {@link http://en.wikipedia.org/wiki/VT100 VT100} terminal emulator. * color to display them in, etc. \phpseclib\File\ANSI is a {@link http://en.wikipedia.org/wiki/VT100 VT100} terminal emulator.
*
* LICENSE: 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.
* *
* @category File * @category File
* @package File_ANSI * @package ANSI
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2012 Jim Wigginton * @copyright 2012 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
namespace phpseclib\File;
/** /**
* Pure-PHP ANSI Decoder * Pure-PHP ANSI Decoder
* *
* @package File_ANSI * @package ANSI
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @access public * @access public
*/ */
class File_ANSI class ANSI
{ {
/** /**
* Max Width * Max Width
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $max_x; var $max_x;
@ -56,7 +40,7 @@ class File_ANSI
/** /**
* Max Height * Max Height
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $max_y; var $max_y;
@ -64,7 +48,7 @@ class File_ANSI
/** /**
* Max History * Max History
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $max_history; var $max_history;
@ -72,7 +56,7 @@ class File_ANSI
/** /**
* History * History
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $history; var $history;
@ -80,7 +64,7 @@ class File_ANSI
/** /**
* History Attributes * History Attributes
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $history_attrs; var $history_attrs;
@ -88,7 +72,7 @@ class File_ANSI
/** /**
* Current Column * Current Column
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $x; var $x;
@ -96,7 +80,7 @@ class File_ANSI
/** /**
* Current Row * Current Row
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $y; var $y;
@ -104,7 +88,7 @@ class File_ANSI
/** /**
* Old Column * Old Column
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $old_x; var $old_x;
@ -112,15 +96,31 @@ class File_ANSI
/** /**
* Old Row * Old Row
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $old_y; var $old_y;
/**
* An empty attribute cell
*
* @var object
* @access private
*/
var $base_attr_cell;
/**
* The current attribute cell
*
* @var object
* @access private
*/
var $attr_cell;
/** /**
* An empty attribute row * An empty attribute row
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $attr_row; var $attr_row;
@ -128,7 +128,7 @@ class File_ANSI
/** /**
* The current screen text * The current screen text
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $screen; var $screen;
@ -136,83 +136,45 @@ class File_ANSI
/** /**
* The current screen attributes * The current screen attributes
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $attrs; var $attrs;
/**
* The current foreground color
*
* @var String
* @access private
*/
var $foreground;
/**
* The current background color
*
* @var String
* @access private
*/
var $background;
/**
* Bold flag
*
* @var Boolean
* @access private
*/
var $bold;
/**
* Underline flag
*
* @var Boolean
* @access private
*/
var $underline;
/**
* Blink flag
*
* @var Boolean
* @access private
*/
var $blink;
/**
* Reverse flag
*
* @var Boolean
* @access private
*/
var $reverse;
/**
* Color flag
*
* @var Boolean
* @access private
*/
var $color;
/** /**
* Current ANSI code * Current ANSI code
* *
* @var String * @var string
* @access private * @access private
*/ */
var $ansi; var $ansi;
/**
* Tokenization
*
* @var array
* @access private
*/
var $tokenization;
/** /**
* Default Constructor. * Default Constructor.
* *
* @return File_ANSI * @return \phpseclib\File\ANSI
* @access public * @access public
*/ */
function File_ANSI() function __construct()
{ {
$attr_cell = new \stdClass();
$attr_cell->bold = false;
$attr_cell->underline = false;
$attr_cell->blink = false;
$attr_cell->background = 'black';
$attr_cell->foreground = 'white';
$attr_cell->reverse = false;
$this->base_attr_cell = clone $attr_cell;
$this->attr_cell = clone $attr_cell;
$this->setHistory(200); $this->setHistory(200);
$this->setDimensions(80, 24); $this->setDimensions(80, 24);
} }
@ -222,8 +184,8 @@ class File_ANSI
* *
* Resets the screen as well * Resets the screen as well
* *
* @param Integer $x * @param int $x
* @param Integer $y * @param int $y
* @access public * @access public
*/ */
function setDimensions($x, $y) function setDimensions($x, $y)
@ -232,25 +194,17 @@ class File_ANSI
$this->max_y = $y - 1; $this->max_y = $y - 1;
$this->x = $this->y = 0; $this->x = $this->y = 0;
$this->history = $this->history_attrs = array(); $this->history = $this->history_attrs = array();
$this->attr_row = array_fill(0, $this->max_x + 1, ''); $this->attr_row = array_fill(0, $this->max_x + 2, $this->base_attr_cell);
$this->screen = array_fill(0, $this->max_y + 1, ''); $this->screen = array_fill(0, $this->max_y + 1, '');
$this->attrs = array_fill(0, $this->max_y + 1, $this->attr_row); $this->attrs = array_fill(0, $this->max_y + 1, $this->attr_row);
$this->foreground = 'white';
$this->background = 'black';
$this->bold = false;
$this->underline = false;
$this->blink = false;
$this->reverse = false;
$this->color = false;
$this->ansi = ''; $this->ansi = '';
} }
/** /**
* Set the number of lines that should be logged past the terminal height * Set the number of lines that should be logged past the terminal height
* *
* @param Integer $x * @param int $x
* @param Integer $y * @param int $y
* @access public * @access public
*/ */
function setHistory($history) function setHistory($history)
@ -261,7 +215,7 @@ class File_ANSI
/** /**
* Load a string * Load a string
* *
* @param String $source * @param string $source
* @access public * @access public
*/ */
function loadString($source) function loadString($source)
@ -273,11 +227,12 @@ class File_ANSI
/** /**
* Appdend a string * Appdend a string
* *
* @param String $source * @param string $source
* @access public * @access public
*/ */
function appendString($source) function appendString($source)
{ {
$this->tokenization = array('');
for ($i = 0; $i < strlen($source); $i++) { for ($i = 0; $i < strlen($source); $i++) {
if (strlen($this->ansi)) { if (strlen($this->ansi)) {
$this->ansi.= $source[$i]; $this->ansi.= $source[$i];
@ -294,6 +249,8 @@ class File_ANSI
default: default:
continue 2; continue 2;
} }
$this->tokenization[] = $this->ansi;
$this->tokenization[] = '';
// http://ascii-table.com/ansi-escape-sequences-vt-100.php // http://ascii-table.com/ansi-escape-sequences-vt-100.php
switch ($this->ansi) { switch ($this->ansi) {
case "\x1B[H": // Move cursor to upper left corner case "\x1B[H": // Move cursor to upper left corner
@ -315,7 +272,7 @@ class File_ANSI
case "\x1B[K": // Clear screen from cursor right case "\x1B[K": // Clear screen from cursor right
$this->screen[$this->y] = substr($this->screen[$this->y], 0, $this->x); $this->screen[$this->y] = substr($this->screen[$this->y], 0, $this->x);
array_splice($this->attrs[$this->y], $this->x + 1); array_splice($this->attrs[$this->y], $this->x + 1, $this->max_x - $this->x, array_fill($this->x, $this->max_x - $this->x - 1, $this->base_attr_cell));
break; break;
case "\x1B[2K": // Clear entire line case "\x1B[2K": // Clear entire line
$this->screen[$this->y] = str_repeat(' ', $this->x); $this->screen[$this->y] = str_repeat(' ', $this->x);
@ -323,6 +280,7 @@ class File_ANSI
break; break;
case "\x1B[?1h": // set cursor key to application case "\x1B[?1h": // set cursor key to application
case "\x1B[?25h": // show the cursor case "\x1B[?25h": // show the cursor
case "\x1B(B": // set united states g0 character set
break; break;
case "\x1BE": // Move to next line case "\x1BE": // Move to next line
$this->_newLine(); $this->_newLine();
@ -330,6 +288,10 @@ class File_ANSI
break; break;
default: default:
switch (true) { switch (true) {
case preg_match('#\x1B\[(\d+)B#', $this->ansi, $match): // Move cursor down n lines
$this->old_y = $this->y;
$this->y+= $match[1];
break;
case preg_match('#\x1B\[(\d+);(\d+)H#', $this->ansi, $match): // Move cursor to screen location v,h case preg_match('#\x1B\[(\d+);(\d+)H#', $this->ansi, $match): // Move cursor to screen location v,h
$this->old_x = $this->x; $this->old_x = $this->x;
$this->old_y = $this->y; $this->old_y = $this->y;
@ -338,65 +300,44 @@ class File_ANSI
break; break;
case preg_match('#\x1B\[(\d+)C#', $this->ansi, $match): // Move cursor right n lines case preg_match('#\x1B\[(\d+)C#', $this->ansi, $match): // Move cursor right n lines
$this->old_x = $this->x; $this->old_x = $this->x;
$x = $match[1] - 1; $this->x+= $match[1];
break;
case preg_match('#\x1B\[(\d+)D#', $this->ansi, $match): // Move cursor left n lines
$this->old_x = $this->x;
$this->x-= $match[1];
break; break;
case preg_match('#\x1B\[(\d+);(\d+)r#', $this->ansi, $match): // Set top and bottom lines of a window case preg_match('#\x1B\[(\d+);(\d+)r#', $this->ansi, $match): // Set top and bottom lines of a window
break; break;
case preg_match('#\x1B\[(\d*(?:;\d*)*)m#', $this->ansi, $match): // character attributes case preg_match('#\x1B\[(\d*(?:;\d*)*)m#', $this->ansi, $match): // character attributes
$attr_cell = &$this->attr_cell;
$mods = explode(';', $match[1]); $mods = explode(';', $match[1]);
foreach ($mods as $mod) { foreach ($mods as $mod) {
switch ($mod) { switch ($mod) {
case 0: // Turn off character attributes case 0: // Turn off character attributes
$this->attrs[$this->y][$this->x] = ''; $attr_cell = clone $this->base_attr_cell;
if ($this->bold) $this->attrs[$this->y][$this->x].= '</b>';
if ($this->underline) $this->attrs[$this->y][$this->x].= '</u>';
if ($this->blink) $this->attrs[$this->y][$this->x].= '</blink>';
if ($this->color) $this->attrs[$this->y][$this->x].= '</span>';
if ($this->reverse) {
$temp = $this->background;
$this->background = $this->foreground;
$this->foreground = $temp;
}
$this->bold = $this->underline = $this->blink = $this->color = $this->reverse = false;
break; break;
case 1: // Turn bold mode on case 1: // Turn bold mode on
if (!$this->bold) { $attr_cell->bold = true;
$this->attrs[$this->y][$this->x] = '<b>';
$this->bold = true;
}
break; break;
case 4: // Turn underline mode on case 4: // Turn underline mode on
if (!$this->underline) { $attr_cell->underline = true;
$this->attrs[$this->y][$this->x] = '<u>';
$this->underline = true;
}
break; break;
case 5: // Turn blinking mode on case 5: // Turn blinking mode on
if (!$this->blink) { $attr_cell->blink = true;
$this->attrs[$this->y][$this->x] = '<blink>';
$this->blink = true;
}
break; break;
case 7: // Turn reverse video on case 7: // Turn reverse video on
$this->reverse = !$this->reverse; $attr_cell->reverse = !$attr_cell->reverse;
$temp = $this->background; $temp = $attr_cell->background;
$this->background = $this->foreground; $attr_cell->background = $attr_cell->foreground;
$this->foreground = $temp; $attr_cell->foreground = $temp;
$this->attrs[$this->y][$this->x] = '<span style="color: ' . $this->foreground . '; background: ' . $this->background . '">';
if ($this->color) {
$this->attrs[$this->y][$this->x] = '</span>' . $this->attrs[$this->y][$this->x];
}
$this->color = true;
break; break;
default: // set colors default: // set colors
//$front = $this->reverse ? &$this->background : &$this->foreground; //$front = $attr_cell->reverse ? &$attr_cell->background : &$attr_cell->foreground;
$front = &$this->{ $this->reverse ? 'background' : 'foreground' }; $front = &$attr_cell->{ $attr_cell->reverse ? 'background' : 'foreground' };
//$back = $this->reverse ? &$this->foreground : &$this->background; //$back = $attr_cell->reverse ? &$attr_cell->foreground : &$attr_cell->background;
$back = &$this->{ $this->reverse ? 'foreground' : 'background' }; $back = &$attr_cell->{ $attr_cell->reverse ? 'foreground' : 'background' };
switch ($mod) { switch ($mod) {
// @codingStandardsIgnoreStart
case 30: $front = 'black'; break; case 30: $front = 'black'; break;
case 31: $front = 'red'; break; case 31: $front = 'red'; break;
case 32: $front = 'green'; break; case 32: $front = 'green'; break;
@ -414,30 +355,25 @@ class File_ANSI
case 45: $back = 'magenta'; break; case 45: $back = 'magenta'; break;
case 46: $back = 'cyan'; break; case 46: $back = 'cyan'; break;
case 47: $back = 'white'; break; case 47: $back = 'white'; break;
// @codingStandardsIgnoreEnd
default: default:
user_error('Unsupported attribute: ' . $mod); //user_error('Unsupported attribute: ' . $mod);
$this->ansi = ''; $this->ansi = '';
break 2; break 2;
} }
unset($temp);
$this->attrs[$this->y][$this->x] = '<span style="color: ' . $this->foreground . '; background: ' . $this->background . '">';
if ($this->color) {
$this->attrs[$this->y][$this->x] = '</span>' . $this->attrs[$this->y][$this->x];
}
$this->color = true;
} }
} }
break; break;
default: default:
user_error("{$this->ansi} unsupported\r\n"); //user_error("{$this->ansi} is unsupported\r\n");
} }
} }
$this->ansi = ''; $this->ansi = '';
continue; continue;
} }
$this->tokenization[count($this->tokenization) - 1].= $source[$i];
switch ($source[$i]) { switch ($source[$i]) {
case "\r": case "\r":
$this->x = 0; $this->x = 0;
@ -445,12 +381,32 @@ class File_ANSI
case "\n": case "\n":
$this->_newLine(); $this->_newLine();
break; break;
case "\x08": // backspace
if ($this->x) {
$this->x--;
$this->attrs[$this->y][$this->x] = clone $this->base_attr_cell;
$this->screen[$this->y] = substr_replace(
$this->screen[$this->y],
$source[$i],
$this->x,
1
);
}
break;
case "\x0F": // shift case "\x0F": // shift
break; break;
case "\x1B": // start ANSI escape code case "\x1B": // start ANSI escape code
$this->tokenization[count($this->tokenization) - 1] = substr($this->tokenization[count($this->tokenization) - 1], 0, -1);
//if (!strlen($this->tokenization[count($this->tokenization) - 1])) {
// array_pop($this->tokenization);
//}
$this->ansi.= "\x1B"; $this->ansi.= "\x1B";
break; break;
default: default:
$this->attrs[$this->y][$this->x] = clone $this->attr_cell;
if ($this->x > strlen($this->screen[$this->y])) {
$this->screen[$this->y] = str_repeat(' ', $this->x);
}
$this->screen[$this->y] = substr_replace( $this->screen[$this->y] = substr_replace(
$this->screen[$this->y], $this->screen[$this->y],
$source[$i], $source[$i],
@ -498,26 +454,84 @@ class File_ANSI
$this->y++; $this->y++;
} }
/**
* Returns the current coordinate without preformating
*
* @access private
* @return string
*/
function _processCoordinate($last_attr, $cur_attr, $char)
{
$output = '';
if ($last_attr != $cur_attr) {
$close = $open = '';
if ($last_attr->foreground != $cur_attr->foreground) {
if ($cur_attr->foreground != 'white') {
$open.= '<span style="color: ' . $cur_attr->foreground . '">';
}
if ($last_attr->foreground != 'white') {
$close = '</span>' . $close;
}
}
if ($last_attr->background != $cur_attr->background) {
if ($cur_attr->background != 'black') {
$open.= '<span style="background: ' . $cur_attr->background . '">';
}
if ($last_attr->background != 'black') {
$close = '</span>' . $close;
}
}
if ($last_attr->bold != $cur_attr->bold) {
if ($cur_attr->bold) {
$open.= '<b>';
} else {
$close = '</b>' . $close;
}
}
if ($last_attr->underline != $cur_attr->underline) {
if ($cur_attr->underline) {
$open.= '<u>';
} else {
$close = '</u>' . $close;
}
}
if ($last_attr->blink != $cur_attr->blink) {
if ($cur_attr->blink) {
$open.= '<blink>';
} else {
$close = '</blink>' . $close;
}
}
$output.= $close . $open;
}
$output.= htmlspecialchars($char);
return $output;
}
/** /**
* Returns the current screen without preformating * Returns the current screen without preformating
* *
* @access private * @access private
* @return String * @return string
*/ */
function _getScreen() function _getScreen()
{ {
$output = ''; $output = '';
$last_attr = $this->base_attr_cell;
for ($i = 0; $i <= $this->max_y; $i++) { for ($i = 0; $i <= $this->max_y; $i++) {
for ($j = 0; $j <= $this->max_x + 1; $j++) { for ($j = 0; $j <= $this->max_x; $j++) {
if (isset($this->attrs[$i][$j])) { $cur_attr = $this->attrs[$i][$j];
$output.= $this->attrs[$i][$j]; $output.= $this->_processCoordinate($last_attr, $cur_attr, isset($this->screen[$i][$j]) ? $this->screen[$i][$j] : '');
} $last_attr = $this->attrs[$i][$j];
if (isset($this->screen[$i][$j])) {
$output.= htmlspecialchars($this->screen[$i][$j]);
}
} }
$output.= "\r\n"; $output.= "\r\n";
} }
$output = substr($output, 0, -2);
// close any remaining open tags
$output.= $this->_processCoordinate($last_attr, $this->base_attr_cell, '');
return rtrim($output); return rtrim($output);
} }
@ -525,35 +539,36 @@ class File_ANSI
* Returns the current screen * Returns the current screen
* *
* @access public * @access public
* @return String * @return string
*/ */
function getScreen() function getScreen()
{ {
return '<pre style="color: white; background: black" width="' . ($this->max_x + 1) . '">' . $this->_getScreen() . '</pre>'; return '<pre width="' . ($this->max_x + 1) . '" style="color: white; background: black">' . $this->_getScreen() . '</pre>';
} }
/** /**
* Returns the current screen and the x previous lines * Returns the current screen and the x previous lines
* *
* @access public * @access public
* @return String * @return string
*/ */
function getHistory() function getHistory()
{ {
$scrollback = ''; $scrollback = '';
$last_attr = $this->base_attr_cell;
for ($i = 0; $i < count($this->history); $i++) { for ($i = 0; $i < count($this->history); $i++) {
for ($j = 0; $j <= $this->max_x + 1; $j++) { for ($j = 0; $j <= $this->max_x + 1; $j++) {
if (isset($this->history_attrs[$i][$j])) { $cur_attr = $this->history_attrs[$i][$j];
$scrollback.= $this->history_attrs[$i][$j]; $scrollback.= $this->_processCoordinate($last_attr, $cur_attr, isset($this->history[$i][$j]) ? $this->history[$i][$j] : '');
} $last_attr = $this->history_attrs[$i][$j];
if (isset($this->history[$i][$j])) {
$scrollback.= htmlspecialchars($this->history[$i][$j]);
}
} }
$scrollback.= "\r\n"; $scrollback.= "\r\n";
} }
$base_attr_cell = $this->base_attr_cell;
$this->base_attr_cell = $last_attr;
$scrollback.= $this->_getScreen(); $scrollback.= $this->_getScreen();
$this->base_attr_cell = $base_attr_cell;
return '<pre style="color: white; background: black" width="' . ($this->max_x + 1) . '">' . $scrollback . '</pre>'; return '<pre width="' . ($this->max_x + 1) . '" style="color: white; background: black">' . $scrollback . '</span></pre>';
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,47 @@
<?php
/**
* Pure-PHP ASN.1 Parser
*
* PHP version 5
*
* @category File
* @package ASN1
* @author Jim Wigginton <terrafrost@php.net>
* @copyright 2012 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
*/
namespace phpseclib\File\ASN1;
/**
* ASN.1 Element
*
* Bypass normal encoding rules in phpseclib\File\ASN1::encodeDER()
*
* @package ASN1
* @author Jim Wigginton <terrafrost@php.net>
* @access public
*/
class Element
{
/**
* Raw element value
*
* @var string
* @access private
*/
var $element;
/**
* Constructor
*
* @param string $encoded
* @return \phpseclib\File\ASN1\Element
* @access public
*/
function __construct($encoded)
{
$this->element = $encoded;
}
}

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -3,94 +3,77 @@
/** /**
* Pure-PHP implementation of SCP. * Pure-PHP implementation of SCP.
* *
* PHP versions 4 and 5 * PHP version 5
* *
* The API for this library is modeled after the API from PHP's {@link http://php.net/book.ftp FTP extension}. * The API for this library is modeled after the API from PHP's {@link http://php.net/book.ftp FTP extension}.
* *
* Here's a short example of how to use this library: * Here's a short example of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'Net/SCP.php'; * include 'vendor/autoload.php';
* include 'Net/SSH2.php';
* *
* $ssh = new Net_SSH2('www.domain.tld'); * $ssh = new \phpseclib\Net\SSH2('www.domain.tld');
* if (!$ssh->login('username', 'password')) { * if (!$ssh->login('username', 'password')) {
* exit('bad login'); * exit('bad login');
* } * }
* $scp = new \phpseclib\Net\SCP($ssh);
* $scp = new Net_SCP($ssh); *
* $scp->put('abcd', str_repeat('x', 1024*1024)); * $scp->put('abcd', str_repeat('x', 1024*1024));
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category Net * @category Net
* @package Net_SCP * @package SCP
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2010 Jim Wigginton * @copyright 2010 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
/**#@+ namespace phpseclib\Net;
* @access public
* @see Net_SCP::put()
*/
/**
* Reads data from a local file.
*/
define('NET_SCP_LOCAL_FILE', 1);
/**
* Reads data from a string.
*/
define('NET_SCP_STRING', 2);
/**#@-*/
/**#@+
* @access private
* @see Net_SCP::_send()
* @see Net_SCP::_receive()
*/
/**
* SSH1 is being used.
*/
define('NET_SCP_SSH1', 1);
/**
* SSH2 is being used.
*/
define('NET_SCP_SSH2', 2);
/**#@-*/
/** /**
* Pure-PHP implementations of SCP. * Pure-PHP implementations of SCP.
* *
* @package Net_SCP * @package SCP
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @access public * @access public
*/ */
class Net_SCP class SCP
{ {
/**#@+
* @access public
* @see \phpseclib\Net\SCP::put()
*/
/**
* Reads data from a local file.
*/
const SOURCE_LOCAL_FILE = 1;
/**
* Reads data from a string.
*/
const SOURCE_STRING = 2;
/**#@-*/
/**#@+
* @access private
* @see \phpseclib\Net\SCP::_send()
* @see \phpseclib\Net\SCP::_receive()
*/
/**
* SSH1 is being used.
*/
const MODE_SSH1 = 1;
/**
* SSH2 is being used.
*/
const MODE_SSH2 = 2;
/**#@-*/
/** /**
* SSH Object * SSH Object
* *
* @var Object * @var object
* @access private * @access private
*/ */
var $ssh; var $ssh;
@ -98,7 +81,7 @@ class Net_SCP
/** /**
* Packet Size * Packet Size
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $packet_size; var $packet_size;
@ -106,7 +89,7 @@ class Net_SCP
/** /**
* Mode * Mode
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $mode; var $mode;
@ -116,27 +99,18 @@ class Net_SCP
* *
* Connects to an SSH server * Connects to an SSH server
* *
* @param String $host * @param \phpseclib\Net\SSH1|\phpseclin\Net\SSH2 $ssh
* @param optional Integer $port * @return \phpseclib\Net\SCP
* @param optional Integer $timeout
* @return Net_SCP
* @access public * @access public
*/ */
function Net_SCP($ssh) function __construct($ssh)
{ {
if (!is_object($ssh)) { if ($ssh instanceof SSH2) {
return; $this->mode = self::MODE_SSH2;
} } elseif ($ssh instanceof SSH1) {
switch (strtolower(get_class($ssh))) {
case 'net_ssh2':
$this->mode = NET_SCP_SSH2;
break;
case 'net_ssh1':
$this->packet_size = 50000; $this->packet_size = 50000;
$this->mode = NET_SCP_SSH1; $this->mode = self::MODE_SSH1;
break; } else {
default:
return; return;
} }
@ -146,25 +120,25 @@ class Net_SCP
/** /**
* Uploads a file to the SCP server. * Uploads a file to the SCP server.
* *
* By default, Net_SCP::put() does not read from the local filesystem. $data is dumped directly into $remote_file. * By default, \phpseclib\Net\SCP::put() does not read from the local filesystem. $data is dumped directly into $remote_file.
* So, for example, if you set $data to 'filename.ext' and then do Net_SCP::get(), you will get a file, twelve bytes * So, for example, if you set $data to 'filename.ext' and then do \phpseclib\Net\SCP::get(), you will get a file, twelve bytes
* long, containing 'filename.ext' as its contents. * long, containing 'filename.ext' as its contents.
* *
* Setting $mode to NET_SCP_LOCAL_FILE will change the above behavior. With NET_SCP_LOCAL_FILE, $remote_file will * Setting $mode to self::SOURCE_LOCAL_FILE will change the above behavior. With self::SOURCE_LOCAL_FILE, $remote_file will
* contain as many bytes as filename.ext does on your local filesystem. If your filename.ext is 1MB then that is how * contain as many bytes as filename.ext does on your local filesystem. If your filename.ext is 1MB then that is how
* large $remote_file will be, as well. * large $remote_file will be, as well.
* *
* Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take * Currently, only binary mode is supported. As such, if the line endings need to be adjusted, you will need to take
* care of that, yourself. * care of that, yourself.
* *
* @param String $remote_file * @param string $remote_file
* @param String $data * @param string $data
* @param optional Integer $mode * @param int $mode
* @param optional Callable $callback * @param callable $callback
* @return Boolean * @return bool
* @access public * @access public
*/ */
function put($remote_file, $data, $mode = NET_SCP_STRING, $callback = null) function put($remote_file, $data, $mode = self::SOURCE_STRING, $callback = null)
{ {
if (!isset($this->ssh)) { if (!isset($this->ssh)) {
return false; return false;
@ -179,13 +153,13 @@ class Net_SCP
return false; return false;
} }
if ($this->mode == NET_SCP_SSH2) { if ($this->mode == self::MODE_SSH2) {
$this->packet_size = $this->ssh->packet_size_client_to_server[NET_SSH2_CHANNEL_EXEC] - 4; $this->packet_size = $this->ssh->packet_size_client_to_server[SSH2::CHANNEL_EXEC] - 4;
} }
$remote_file = basename($remote_file); $remote_file = basename($remote_file);
if ($mode == NET_SCP_STRING) { if ($mode == self::SOURCE_STRING) {
$size = strlen($data); $size = strlen($data);
} else { } else {
if (!is_file($data)) { if (!is_file($data)) {
@ -209,7 +183,7 @@ class Net_SCP
$sent = 0; $sent = 0;
while ($sent < $size) { while ($sent < $size) {
$temp = $mode & NET_SCP_STRING ? substr($data, $sent, $this->packet_size) : fread($fp, $this->packet_size); $temp = $mode & self::SOURCE_STRING ? substr($data, $sent, $this->packet_size) : fread($fp, $this->packet_size);
$this->_send($temp); $this->_send($temp);
$sent+= strlen($temp); $sent+= strlen($temp);
@ -219,7 +193,7 @@ class Net_SCP
} }
$this->_close(); $this->_close();
if ($mode != NET_SCP_STRING) { if ($mode != self::SOURCE_STRING) {
fclose($fp); fclose($fp);
} }
@ -233,9 +207,9 @@ class Net_SCP
* the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the * the operation was unsuccessful. If $local_file is defined, returns true or false depending on the success of the
* operation * operation
* *
* @param String $remote_file * @param string $remote_file
* @param optional String $local_file * @param string $local_file
* @return Mixed * @return mixed
* @access public * @access public
*/ */
function get($remote_file, $local_file = false) function get($remote_file, $local_file = false)
@ -291,16 +265,16 @@ class Net_SCP
/** /**
* Sends a packet to an SSH server * Sends a packet to an SSH server
* *
* @param String $data * @param string $data
* @access private * @access private
*/ */
function _send($data) function _send($data)
{ {
switch ($this->mode) { switch ($this->mode) {
case NET_SCP_SSH2: case self::MODE_SSH2:
$this->ssh->_send_channel_packet(NET_SSH2_CHANNEL_EXEC, $data); $this->ssh->_send_channel_packet(SSH2::CHANNEL_EXEC, $data);
break; break;
case NET_SCP_SSH1: case self::MODE_SSH1:
$data = pack('CNa*', NET_SSH1_CMSG_STDIN_DATA, strlen($data), $data); $data = pack('CNa*', NET_SSH1_CMSG_STDIN_DATA, strlen($data), $data);
$this->ssh->_send_binary_packet($data); $this->ssh->_send_binary_packet($data);
} }
@ -309,24 +283,24 @@ class Net_SCP
/** /**
* Receives a packet from an SSH server * Receives a packet from an SSH server
* *
* @return String * @return string
* @access private * @access private
*/ */
function _receive() function _receive()
{ {
switch ($this->mode) { switch ($this->mode) {
case NET_SCP_SSH2: case self::MODE_SSH2:
return $this->ssh->_get_channel_packet(NET_SSH2_CHANNEL_EXEC, true); return $this->ssh->_get_channel_packet(SSH2::CHANNEL_EXEC, true);
case NET_SCP_SSH1: case self::MODE_SSH1:
if (!$this->ssh->bitmap) { if (!$this->ssh->bitmap) {
return false; return false;
} }
while (true) { while (true) {
$response = $this->ssh->_get_binary_packet(); $response = $this->ssh->_get_binary_packet();
switch ($response[NET_SSH1_RESPONSE_TYPE]) { switch ($response[SSH1::RESPONSE_TYPE]) {
case NET_SSH1_SMSG_STDOUT_DATA: case NET_SSH1_SMSG_STDOUT_DATA:
extract(unpack('Nlength', $response[NET_SSH1_RESPONSE_DATA])); extract(unpack('Nlength', $response[SSH1::RESPONSE_DATA]));
return $this->ssh->_string_shift($response[NET_SSH1_RESPONSE_DATA], $length); return $this->ssh->_string_shift($response[SSH1::RESPONSE_DATA], $length);
case NET_SSH1_SMSG_STDERR_DATA: case NET_SSH1_SMSG_STDERR_DATA:
break; break;
case NET_SSH1_SMSG_EXITSTATUS: case NET_SSH1_SMSG_EXITSTATUS:
@ -350,10 +324,10 @@ class Net_SCP
function _close() function _close()
{ {
switch ($this->mode) { switch ($this->mode) {
case NET_SCP_SSH2: case self::MODE_SSH2:
$this->ssh->_close_channel(NET_SSH2_CHANNEL_EXEC, true); $this->ssh->_close_channel(SSH2::CHANNEL_EXEC, true);
break; break;
case NET_SCP_SSH1: case self::MODE_SSH1:
$this->ssh->disconnect(); $this->ssh->disconnect();
} }
} }

File diff suppressed because it is too large Load diff

View file

@ -7,54 +7,41 @@
* *
* PHP version 5 * PHP version 5
* *
* LICENSE: 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.
*
* @category Net * @category Net
* @package Net_SFTP_Stream * @package SFTP
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2013 Jim Wigginton * @copyright 2013 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net * @link http://phpseclib.sourceforge.net
*/ */
namespace phpseclib\Net\SFTP;
use phpseclib\Crypt\RSA;
use phpseclib\Net\SFTP;
/** /**
* SFTP Stream Wrapper * SFTP Stream Wrapper
* *
* @package Net_SFTP_Stream * @package SFTP
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @access public * @access public
*/ */
class Net_SFTP_Stream class Stream
{ {
/** /**
* SFTP instances * SFTP instances
* *
* Rather than re-create the connection we re-use instances if possible * Rather than re-create the connection we re-use instances if possible
* *
* @var Array * @var array
*/ */
static $instances; static $instances;
/** /**
* SFTP instance * SFTP instance
* *
* @var Object * @var object
* @access private * @access private
*/ */
var $sftp; var $sftp;
@ -62,7 +49,7 @@ class Net_SFTP_Stream
/** /**
* Path * Path
* *
* @var String * @var string
* @access private * @access private
*/ */
var $path; var $path;
@ -70,7 +57,7 @@ class Net_SFTP_Stream
/** /**
* Mode * Mode
* *
* @var String * @var string
* @access private * @access private
*/ */
var $mode; var $mode;
@ -78,7 +65,7 @@ class Net_SFTP_Stream
/** /**
* Position * Position
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $pos; var $pos;
@ -86,7 +73,7 @@ class Net_SFTP_Stream
/** /**
* Size * Size
* *
* @var Integer * @var int
* @access private * @access private
*/ */
var $size; var $size;
@ -94,7 +81,7 @@ class Net_SFTP_Stream
/** /**
* Directory entries * Directory entries
* *
* @var Array * @var array
* @access private * @access private
*/ */
var $entries; var $entries;
@ -102,7 +89,7 @@ class Net_SFTP_Stream
/** /**
* EOF flag * EOF flag
* *
* @var Boolean * @var bool
* @access private * @access private
*/ */
var $eof; var $eof;
@ -112,7 +99,7 @@ class Net_SFTP_Stream
* *
* Technically this needs to be publically accessible so PHP can set it directly * Technically this needs to be publically accessible so PHP can set it directly
* *
* @var Resource * @var resource
* @access public * @access public
*/ */
var $context; var $context;
@ -120,7 +107,7 @@ class Net_SFTP_Stream
/** /**
* Notification callback function * Notification callback function
* *
* @var Callable * @var callable
* @access public * @access public
*/ */
var $notification; var $notification;
@ -128,8 +115,8 @@ class Net_SFTP_Stream
/** /**
* Registers this class as a URL wrapper. * Registers this class as a URL wrapper.
* *
* @param optional String $protocol The wrapper name to be registered. * @param string $protocol The wrapper name to be registered.
* @return Boolean True on success, false otherwise. * @return bool True on success, false otherwise.
* @access public * @access public
*/ */
static function register($protocol = 'sftp') static function register($protocol = 'sftp')
@ -137,8 +124,7 @@ class Net_SFTP_Stream
if (in_array($protocol, stream_get_wrappers(), true)) { if (in_array($protocol, stream_get_wrappers(), true)) {
return false; return false;
} }
$class = function_exists('get_called_class') ? get_called_class() : __CLASS__; return stream_wrapper_register($protocol, get_called_class());
return stream_wrapper_register($protocol, $class);
} }
/** /**
@ -146,15 +132,11 @@ class Net_SFTP_Stream
* *
* @access public * @access public
*/ */
function Net_SFTP_Stream() function __construct()
{ {
if (defined('NET_SFTP_STREAM_LOGGING')) { if (defined('NET_SFTP_STREAM_LOGGING')) {
echo "__construct()\r\n"; echo "__construct()\r\n";
} }
if (!class_exists('Net_SFTP')) {
include_once 'Net/SFTP.php';
}
} }
/** /**
@ -165,13 +147,24 @@ class Net_SFTP_Stream
* If "notification" is set as a context parameter the message code for successful login is * If "notification" is set as a context parameter the message code for successful login is
* NET_SSH2_MSG_USERAUTH_SUCCESS. For a failed login it's NET_SSH2_MSG_USERAUTH_FAILURE. * NET_SSH2_MSG_USERAUTH_SUCCESS. For a failed login it's NET_SSH2_MSG_USERAUTH_FAILURE.
* *
* @param String $path * @param string $path
* @return String * @return string
* @access private * @access private
*/ */
function _parse_path($path) function _parse_path($path)
{ {
$orig = $path;
extract(parse_url($path) + array('port' => 22)); extract(parse_url($path) + array('port' => 22));
if (isset($query)) {
$path.= '?' . $query;
} elseif (preg_match('/(\?|\?#)$/', $orig)) {
$path.= '?';
}
if (isset($fragment)) {
$path.= '#' . $fragment;
} elseif ($orig[strlen($orig) - 1] == '#') {
$path.= '#';
}
if (!isset($host)) { if (!isset($host)) {
return false; return false;
@ -187,7 +180,7 @@ class Net_SFTP_Stream
if ($host[0] == '$') { if ($host[0] == '$') {
$host = substr($host, 1); $host = substr($host, 1);
global $$host; global $$host;
if (!is_object($$host) || get_class($$host) != 'Net_SFTP') { if (($$host instanceof SFTP) === false) {
return false; return false;
} }
$this->sftp = $$host; $this->sftp = $$host;
@ -201,7 +194,7 @@ class Net_SFTP_Stream
if (isset($context[$scheme]['sftp'])) { if (isset($context[$scheme]['sftp'])) {
$sftp = $context[$scheme]['sftp']; $sftp = $context[$scheme]['sftp'];
} }
if (isset($sftp) && is_object($sftp) && get_class($sftp) == 'Net_SFTP') { if (isset($sftp) && $sftp instanceof SFTP) {
$this->sftp = $sftp; $this->sftp = $sftp;
return $path; return $path;
} }
@ -211,7 +204,7 @@ class Net_SFTP_Stream
if (isset($context[$scheme]['password'])) { if (isset($context[$scheme]['password'])) {
$pass = $context[$scheme]['password']; $pass = $context[$scheme]['password'];
} }
if (isset($context[$scheme]['privkey']) && is_object($context[$scheme]['privkey']) && get_Class($context[$scheme]['privkey']) == 'Crypt_RSA') { if (isset($context[$scheme]['privkey']) && $context[$scheme]['privkey'] instanceof RSA) {
$pass = $context[$scheme]['privkey']; $pass = $context[$scheme]['privkey'];
} }
@ -219,11 +212,11 @@ class Net_SFTP_Stream
return false; return false;
} }
// casting $pass to a string is necessary in the event that it's a Crypt_RSA object // casting $pass to a string is necessary in the event that it's a \phpseclib\Crypt\RSA object
if (isset(self::$instances[$host][$port][$user][(string) $pass])) { if (isset(self::$instances[$host][$port][$user][(string) $pass])) {
$this->sftp = self::$instances[$host][$port][$user][(string) $pass]; $this->sftp = self::$instances[$host][$port][$user][(string) $pass];
} else { } else {
$this->sftp = new Net_SFTP($host, $port); $this->sftp = new SFTP($host, $port);
$this->sftp->disableStatCache(); $this->sftp->disableStatCache();
if (isset($this->notification) && is_callable($this->notification)) { if (isset($this->notification) && is_callable($this->notification)) {
/* if !is_callable($this->notification) we could do this: /* if !is_callable($this->notification) we could do this:
@ -257,11 +250,11 @@ class Net_SFTP_Stream
/** /**
* Opens file or URL * Opens file or URL
* *
* @param String $path * @param string $path
* @param String $mode * @param string $mode
* @param Integer $options * @param int $options
* @param String $opened_path * @param string $opened_path
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _stream_open($path, $mode, $options, &$opened_path) function _stream_open($path, $mode, $options, &$opened_path)
@ -280,14 +273,17 @@ class Net_SFTP_Stream
if ($this->size === false) { if ($this->size === false) {
if ($this->mode[0] == 'r') { if ($this->mode[0] == 'r') {
return false; return false;
} else {
$this->sftp->touch($path);
$this->size = 0;
} }
} else { } else {
switch ($this->mode[0]) { switch ($this->mode[0]) {
case 'x': case 'x':
return false; return false;
case 'w': case 'w':
case 'c':
$this->sftp->truncate($path, 0); $this->sftp->truncate($path, 0);
$this->size = 0;
} }
} }
@ -299,8 +295,8 @@ class Net_SFTP_Stream
/** /**
* Read from stream * Read from stream
* *
* @param Integer $count * @param int $count
* @return Mixed * @return mixed
* @access public * @access public
*/ */
function _stream_read($count) function _stream_read($count)
@ -341,8 +337,8 @@ class Net_SFTP_Stream
/** /**
* Write to stream * Write to stream
* *
* @param String $data * @param string $data
* @return Mixed * @return mixed
* @access public * @access public
*/ */
function _stream_write($data) function _stream_write($data)
@ -352,7 +348,7 @@ class Net_SFTP_Stream
return false; return false;
} }
$result = $this->sftp->put($this->path, $data, NET_SFTP_STRING, $this->pos); $result = $this->sftp->put($this->path, $data, SFTP::SOURCE_STRING, $this->pos);
if (isset($this->notification) && is_callable($this->notification)) { if (isset($this->notification) && is_callable($this->notification)) {
if (!$result) { if (!$result) {
call_user_func($this->notification, STREAM_NOTIFY_FAILURE, STREAM_NOTIFY_SEVERITY_ERR, $this->sftp->getLastSFTPError(), NET_SFTP_OPEN, 0, 0); call_user_func($this->notification, STREAM_NOTIFY_FAILURE, STREAM_NOTIFY_SEVERITY_ERR, $this->sftp->getLastSFTPError(), NET_SFTP_OPEN, 0, 0);
@ -376,7 +372,7 @@ class Net_SFTP_Stream
/** /**
* Retrieve the current position of a stream * Retrieve the current position of a stream
* *
* @return Integer * @return int
* @access public * @access public
*/ */
function _stream_tell() function _stream_tell()
@ -394,7 +390,7 @@ class Net_SFTP_Stream
* will return false. do fread($fp, 1) and feof() will then return true. do fseek($fp, 10) on ablank file and feof() * will return false. do fread($fp, 1) and feof() will then return true. do fseek($fp, 10) on ablank file and feof()
* will return false. do fread($fp, 1) and feof() will then return true. * will return false. do fread($fp, 1) and feof() will then return true.
* *
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _stream_eof() function _stream_eof()
@ -405,9 +401,9 @@ class Net_SFTP_Stream
/** /**
* Seeks to specific location in a stream * Seeks to specific location in a stream
* *
* @param Integer $offset * @param int $offset
* @param Integer $whence * @param int $whence
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _stream_seek($offset, $whence) function _stream_seek($offset, $whence)
@ -433,10 +429,10 @@ class Net_SFTP_Stream
/** /**
* Change stream options * Change stream options
* *
* @param String $path * @param string $path
* @param Integer $option * @param int $option
* @param Mixed $var * @param mixed $var
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _stream_metadata($path, $option, $var) function _stream_metadata($path, $option, $var)
@ -467,8 +463,8 @@ class Net_SFTP_Stream
/** /**
* Retrieve the underlaying resource * Retrieve the underlaying resource
* *
* @param Integer $cast_as * @param int $cast_as
* @return Resource * @return resource
* @access public * @access public
*/ */
function _stream_cast($cast_as) function _stream_cast($cast_as)
@ -479,8 +475,8 @@ class Net_SFTP_Stream
/** /**
* Advisory file locking * Advisory file locking
* *
* @param Integer $operation * @param int $operation
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _stream_lock($operation) function _stream_lock($operation)
@ -492,12 +488,12 @@ class Net_SFTP_Stream
* Renames a file or directory * Renames a file or directory
* *
* Attempts to rename oldname to newname, moving it between directories if necessary. * Attempts to rename oldname to newname, moving it between directories if necessary.
* If newname exists, it will be overwritten. This is a departure from what Net_SFTP * If newname exists, it will be overwritten. This is a departure from what \phpseclib\Net\SFTP
* does. * does.
* *
* @param String $path_from * @param string $path_from
* @param String $path_to * @param string $path_to
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _rename($path_from, $path_to) function _rename($path_from, $path_to)
@ -511,7 +507,7 @@ class Net_SFTP_Stream
$path_from = $this->_parse_path($path_from); $path_from = $this->_parse_path($path_from);
$path_to = parse_url($path_to); $path_to = parse_url($path_to);
if ($path_from == false) { if ($path_from === false) {
return false; return false;
} }
@ -547,9 +543,9 @@ class Net_SFTP_Stream
* string longname * string longname
* ATTRS attrs * ATTRS attrs
* *
* @param String $path * @param string $path
* @param Integer $options * @param int $options
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _dir_opendir($path, $options) function _dir_opendir($path, $options)
@ -566,7 +562,7 @@ class Net_SFTP_Stream
/** /**
* Read entry from directory handle * Read entry from directory handle
* *
* @return Mixed * @return mixed
* @access public * @access public
*/ */
function _dir_readdir() function _dir_readdir()
@ -580,7 +576,7 @@ class Net_SFTP_Stream
/** /**
* Rewind directory handle * Rewind directory handle
* *
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _dir_rewinddir() function _dir_rewinddir()
@ -592,7 +588,7 @@ class Net_SFTP_Stream
/** /**
* Close directory handle * Close directory handle
* *
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _dir_closedir() function _dir_closedir()
@ -605,10 +601,10 @@ class Net_SFTP_Stream
* *
* Only valid $options is STREAM_MKDIR_RECURSIVE * Only valid $options is STREAM_MKDIR_RECURSIVE
* *
* @param String $path * @param string $path
* @param Integer $mode * @param int $mode
* @param Integer $options * @param int $options
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _mkdir($path, $mode, $options) function _mkdir($path, $mode, $options)
@ -629,10 +625,10 @@ class Net_SFTP_Stream
* STREAM_MKDIR_RECURSIVE is supposed to be set. Also, when I try it out with rmdir() I get 8 as * STREAM_MKDIR_RECURSIVE is supposed to be set. Also, when I try it out with rmdir() I get 8 as
* $options. What does 8 correspond to? * $options. What does 8 correspond to?
* *
* @param String $path * @param string $path
* @param Integer $mode * @param int $mode
* @param Integer $options * @param int $options
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _rmdir($path, $options) function _rmdir($path, $options)
@ -648,9 +644,9 @@ class Net_SFTP_Stream
/** /**
* Flushes the output * Flushes the output
* *
* See <http://php.net/fflush>. Always returns true because Net_SFTP doesn't cache stuff before writing * See <http://php.net/fflush>. Always returns true because \phpseclib\Net\SFTP doesn't cache stuff before writing
* *
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _stream_flush() function _stream_flush()
@ -661,7 +657,7 @@ class Net_SFTP_Stream
/** /**
* Retrieve information about a file resource * Retrieve information about a file resource
* *
* @return Mixed * @return mixed
* @access public * @access public
*/ */
function _stream_stat() function _stream_stat()
@ -676,8 +672,8 @@ class Net_SFTP_Stream
/** /**
* Delete a file * Delete a file
* *
* @param String $path * @param string $path
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _unlink($path) function _unlink($path)
@ -693,13 +689,13 @@ class Net_SFTP_Stream
/** /**
* Retrieve information about a file * Retrieve information about a file
* *
* Ignores the STREAM_URL_STAT_QUIET flag because the entirety of Net_SFTP_Stream is quiet by default * Ignores the STREAM_URL_STAT_QUIET flag because the entirety of \phpseclib\Net\SFTP\Stream is quiet by default
* might be worthwhile to reconstruct bits 12-16 (ie. the file type) if mode doesn't have them but we'll * might be worthwhile to reconstruct bits 12-16 (ie. the file type) if mode doesn't have them but we'll
* cross that bridge when and if it's reached * cross that bridge when and if it's reached
* *
* @param String $path * @param string $path
* @param Integer $flags * @param int $flags
* @return Mixed * @return mixed
* @access public * @access public
*/ */
function _url_stat($path, $flags) function _url_stat($path, $flags)
@ -720,8 +716,8 @@ class Net_SFTP_Stream
/** /**
* Truncate stream * Truncate stream
* *
* @param Integer $new_size * @param int $new_size
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _stream_truncate($new_size) function _stream_truncate($new_size)
@ -740,12 +736,12 @@ class Net_SFTP_Stream
* Change stream options * Change stream options
* *
* STREAM_OPTION_WRITE_BUFFER isn't supported for the same reason stream_flush isn't. * STREAM_OPTION_WRITE_BUFFER isn't supported for the same reason stream_flush isn't.
* The other two aren't supported because of limitations in Net_SFTP. * The other two aren't supported because of limitations in \phpseclib\Net\SFTP.
* *
* @param Integer $option * @param int $option
* @param Integer $arg1 * @param int $arg1
* @param Integer $arg2 * @param int $arg2
* @return Boolean * @return bool
* @access public * @access public
*/ */
function _stream_set_option($option, $arg1, $arg2) function _stream_set_option($option, $arg1, $arg2)
@ -772,9 +768,9 @@ class Net_SFTP_Stream
* If NET_SFTP_STREAM_LOGGING is defined all calls will be output on the screen and then (regardless of whether or not * If NET_SFTP_STREAM_LOGGING is defined all calls will be output on the screen and then (regardless of whether or not
* NET_SFTP_STREAM_LOGGING is enabled) the parameters will be passed through to the appropriate method. * NET_SFTP_STREAM_LOGGING is enabled) the parameters will be passed through to the appropriate method.
* *
* @param String * @param string
* @param Array * @param array
* @return Mixed * @return mixed
* @access public * @access public
*/ */
function __call($name, $arguments) function __call($name, $arguments)
@ -797,5 +793,3 @@ class Net_SFTP_Stream
return call_user_func_array(array($this, $name), $arguments); return call_user_func_array(array($this, $name), $arguments);
} }
} }
Net_SFTP_Stream::register();

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

View file

@ -1,18 +1,18 @@
<?php <?php
/** /**
* Pure-PHP ssh-agent client. * Pure-PHP ssh-agent client.
* *
* PHP versions 4 and 5 * PHP version 5
* *
* Here are some examples of how to use this library: * Here are some examples of how to use this library:
* <code> * <code>
* <?php * <?php
* include 'System/SSH/Agent.php'; * include 'vendor/autoload.php';
* include 'Net/SSH2.php';
* *
* $agent = new System_SSH_Agent(); * $agent = new \phpseclib\System\SSH\Agent();
* *
* $ssh = new Net_SSH2('www.domain.tld'); * $ssh = new \phpseclib\Net\SSH2('www.domain.tld');
* if (!$ssh->login('username', $agent)) { * if (!$ssh->login('username', $agent)) {
* exit('Login Failed'); * exit('Login Failed');
* } * }
@ -22,26 +22,8 @@
* ?> * ?>
* </code> * </code>
* *
* LICENSE: 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.
*
* @category System * @category System
* @package System_SSH_Agent * @package SSH\Agent
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @copyright 2014 Jim Wigginton * @copyright 2014 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License * @license http://www.opensource.org/licenses/mit-license.html MIT License
@ -49,189 +31,93 @@
* @internal See http://api.libssh.org/rfc/PROTOCOL.agent * @internal See http://api.libssh.org/rfc/PROTOCOL.agent
*/ */
/**#@+ namespace phpseclib\System\SSH;
* Message numbers
*
* @access private
*/
// to request SSH1 keys you have to use SSH_AGENTC_REQUEST_RSA_IDENTITIES (1)
define('SYSTEM_SSH_AGENTC_REQUEST_IDENTITIES', 11);
// this is the SSH2 response; the SSH1 response is SSH_AGENT_RSA_IDENTITIES_ANSWER (2).
define('SYSTEM_SSH_AGENT_IDENTITIES_ANSWER', 12);
define('SYSTEM_SSH_AGENT_FAILURE', 5);
// the SSH1 request is SSH_AGENTC_RSA_CHALLENGE (3)
define('SYSTEM_SSH_AGENTC_SIGN_REQUEST', 13);
// the SSH1 response is SSH_AGENT_RSA_RESPONSE (4)
define('SYSTEM_SSH_AGENT_SIGN_RESPONSE', 14);
/**#@-*/
/** use phpseclib\Crypt\RSA;
* Pure-PHP ssh-agent client identity object use phpseclib\System\SSH\Agent\Identity;
*
* Instantiation should only be performed by System_SSH_Agent class.
* This could be thought of as implementing an interface that Crypt_RSA
* implements. ie. maybe a Net_SSH_Auth_PublicKey interface or something.
* The methods in this interface would be getPublicKey, setSignatureMode
* and sign since those are the methods phpseclib looks for to perform
* public key authentication.
*
* @package System_SSH_Agent
* @author Jim Wigginton <terrafrost@php.net>
* @access internal
*/
class System_SSH_Agent_Identity
{
/**
* Key Object
*
* @var Crypt_RSA
* @access private
* @see System_SSH_Agent_Identity::getPublicKey()
*/
var $key;
/**
* Key Blob
*
* @var String
* @access private
* @see System_SSH_Agent_Identity::sign()
*/
var $key_blob;
/**
* Socket Resource
*
* @var Resource
* @access private
* @see System_SSH_Agent_Identity::sign()
*/
var $fsock;
/**
* Default Constructor.
*
* @param Resource $fsock
* @return System_SSH_Agent_Identity
* @access private
*/
function System_SSH_Agent_Identity($fsock)
{
$this->fsock = $fsock;
}
/**
* Set Public Key
*
* Called by System_SSH_Agent::requestIdentities()
*
* @param Crypt_RSA $key
* @access private
*/
function setPublicKey($key)
{
$this->key = $key;
$this->key->setPublicKey();
}
/**
* Set Public Key
*
* Called by System_SSH_Agent::requestIdentities(). The key blob could be extracted from $this->key
* but this saves a small amount of computation.
*
* @param String $key_blob
* @access private
*/
function setPublicKeyBlob($key_blob)
{
$this->key_blob = $key_blob;
}
/**
* Get Public Key
*
* Wrapper for $this->key->getPublicKey()
*
* @param Integer $format optional
* @return Mixed
* @access public
*/
function getPublicKey($format = null)
{
return !isset($format) ? $this->key->getPublicKey() : $this->key->getPublicKey($format);
}
/**
* Set Signature Mode
*
* Doesn't do anything as ssh-agent doesn't let you pick and choose the signature mode. ie.
* ssh-agent's only supported mode is CRYPT_RSA_SIGNATURE_PKCS1
*
* @param Integer $mode
* @access public
*/
function setSignatureMode($mode)
{
}
/**
* Create a signature
*
* See "2.6.2 Protocol 2 private key signature request"
*
* @param String $message
* @return String
* @access public
*/
function sign($message)
{
// the last parameter (currently 0) is for flags and ssh-agent only defines one flag (for ssh-dss): SSH_AGENT_OLD_SIGNATURE
$packet = pack('CNa*Na*N', SYSTEM_SSH_AGENTC_SIGN_REQUEST, strlen($this->key_blob), $this->key_blob, strlen($message), $message, 0);
$packet = pack('Na*', strlen($packet), $packet);
if (strlen($packet) != fputs($this->fsock, $packet)) {
user_error('Connection closed during signing');
}
$length = current(unpack('N', fread($this->fsock, 4)));
$type = ord(fread($this->fsock, 1));
if ($type != SYSTEM_SSH_AGENT_SIGN_RESPONSE) {
user_error('Unable to retreive signature');
}
$signature_blob = fread($this->fsock, $length - 1);
// the only other signature format defined - ssh-dss - is the same length as ssh-rsa
// the + 12 is for the other various SSH added length fields
return substr($signature_blob, strlen('ssh-rsa') + 12);
}
}
/** /**
* Pure-PHP ssh-agent client identity factory * Pure-PHP ssh-agent client identity factory
* *
* requestIdentities() method pumps out System_SSH_Agent_Identity objects * requestIdentities() method pumps out \phpseclib\System\SSH\Agent\Identity objects
* *
* @package System_SSH_Agent * @package SSH\Agent
* @author Jim Wigginton <terrafrost@php.net> * @author Jim Wigginton <terrafrost@php.net>
* @access internal * @access internal
*/ */
class System_SSH_Agent class Agent
{ {
/**#@+
* Message numbers
*
* @access private
*/
// to request SSH1 keys you have to use SSH_AGENTC_REQUEST_RSA_IDENTITIES (1)
const SSH_AGENTC_REQUEST_IDENTITIES = 11;
// this is the SSH2 response; the SSH1 response is SSH_AGENT_RSA_IDENTITIES_ANSWER (2).
const SSH_AGENT_IDENTITIES_ANSWER = 12;
// the SSH1 request is SSH_AGENTC_RSA_CHALLENGE (3)
const SSH_AGENTC_SIGN_REQUEST = 13;
// the SSH1 response is SSH_AGENT_RSA_RESPONSE (4)
const SSH_AGENT_SIGN_RESPONSE = 14;
/**#@-*/
/**@+
* Agent forwarding status
*
* @access private
*/
// no forwarding requested and not active
const FORWARD_NONE = 0;
// request agent forwarding when opportune
const FORWARD_REQUEST = 1;
// forwarding has been request and is active
const FORWARD_ACTIVE = 2;
/**#@-*/
/**
* Unused
*/
const SSH_AGENT_FAILURE = 5;
/** /**
* Socket Resource * Socket Resource
* *
* @var Resource * @var resource
* @access private * @access private
*/ */
var $fsock; var $fsock;
/**
* Agent forwarding status
*
* @access private
*/
var $forward_status = self::FORWARD_NONE;
/**
* Buffer for accumulating forwarded authentication
* agent data arriving on SSH data channel destined
* for agent unix socket
*
* @access private
*/
var $socket_buffer = '';
/**
* Tracking the number of bytes we are expecting
* to arrive for the agent socket on the SSH data
* channel
*/
var $expected_bytes = 0;
/** /**
* Default Constructor * Default Constructor
* *
* @return System_SSH_Agent * @return \phpseclib\System\SSH\Agent
* @access public * @access public
*/ */
function System_SSH_Agent() function __construct()
{ {
switch (true) { switch (true) {
case isset($_SERVER['SSH_AUTH_SOCK']): case isset($_SERVER['SSH_AUTH_SOCK']):
@ -255,9 +141,9 @@ class System_SSH_Agent
* Request Identities * Request Identities
* *
* See "2.5.2 Requesting a list of protocol 2 keys" * See "2.5.2 Requesting a list of protocol 2 keys"
* Returns an array containing zero or more System_SSH_Agent_Identity objects * Returns an array containing zero or more \phpseclib\System\SSH\Agent\Identity objects
* *
* @return Array * @return array
* @access public * @access public
*/ */
function requestIdentities() function requestIdentities()
@ -266,14 +152,14 @@ class System_SSH_Agent
return array(); return array();
} }
$packet = pack('NC', 1, SYSTEM_SSH_AGENTC_REQUEST_IDENTITIES); $packet = pack('NC', 1, self::SSH_AGENTC_REQUEST_IDENTITIES);
if (strlen($packet) != fputs($this->fsock, $packet)) { if (strlen($packet) != fputs($this->fsock, $packet)) {
user_error('Connection closed while requesting identities'); user_error('Connection closed while requesting identities');
} }
$length = current(unpack('N', fread($this->fsock, 4))); $length = current(unpack('N', fread($this->fsock, 4)));
$type = ord(fread($this->fsock, 1)); $type = ord(fread($this->fsock, 1));
if ($type != SYSTEM_SSH_AGENT_IDENTITIES_ANSWER) { if ($type != self::SSH_AGENT_IDENTITIES_ANSWER) {
user_error('Unable to request identities'); user_error('Unable to request identities');
} }
@ -282,17 +168,17 @@ class System_SSH_Agent
for ($i = 0; $i < $keyCount; $i++) { for ($i = 0; $i < $keyCount; $i++) {
$length = current(unpack('N', fread($this->fsock, 4))); $length = current(unpack('N', fread($this->fsock, 4)));
$key_blob = fread($this->fsock, $length); $key_blob = fread($this->fsock, $length);
$key_str = 'ssh-rsa ' . base64_encode($key_blob);
$length = current(unpack('N', fread($this->fsock, 4))); $length = current(unpack('N', fread($this->fsock, 4)));
$key_comment = fread($this->fsock, $length); if ($length) {
$key_str.= ' ' . fread($this->fsock, $length);
}
$length = current(unpack('N', substr($key_blob, 0, 4))); $length = current(unpack('N', substr($key_blob, 0, 4)));
$key_type = substr($key_blob, 4, $length); $key_type = substr($key_blob, 4, $length);
switch ($key_type) { switch ($key_type) {
case 'ssh-rsa': case 'ssh-rsa':
if (!class_exists('Crypt_RSA')) { $key = new RSA();
include_once 'Crypt/RSA.php'; $key->loadKey($key_str);
}
$key = new Crypt_RSA();
$key->loadKey('ssh-rsa ' . base64_encode($key_blob) . ' ' . $key_comment);
break; break;
case 'ssh-dss': case 'ssh-dss':
// not currently supported // not currently supported
@ -300,7 +186,7 @@ class System_SSH_Agent
} }
// resources are passed by reference by default // resources are passed by reference by default
if (isset($key)) { if (isset($key)) {
$identity = new System_SSH_Agent_Identity($this->fsock); $identity = new Identity($this->fsock);
$identity->setPublicKey($key); $identity->setPublicKey($key);
$identity->setPublicKeyBlob($key_blob); $identity->setPublicKeyBlob($key_blob);
$identities[] = $identity; $identities[] = $identity;
@ -310,4 +196,113 @@ class System_SSH_Agent
return $identities; return $identities;
} }
/**
* Signal that agent forwarding should
* be requested when a channel is opened
*
* @param Net_SSH2 $ssh
* @return bool
* @access public
*/
function startSSHForwarding($ssh)
{
if ($this->forward_status == self::FORWARD_NONE) {
$this->forward_status = self::FORWARD_REQUEST;
}
}
/**
* Request agent forwarding of remote server
*
* @param Net_SSH2 $ssh
* @return bool
* @access private
*/
function _request_forwarding($ssh)
{
$request_channel = $ssh->_get_open_channel();
if ($request_channel === false) {
return false;
}
$packet = pack(
'CNNa*C',
NET_SSH2_MSG_CHANNEL_REQUEST,
$ssh->server_channels[$request_channel],
strlen('auth-agent-req@openssh.com'),
'auth-agent-req@openssh.com',
1
);
$ssh->channel_status[$request_channel] = NET_SSH2_MSG_CHANNEL_REQUEST;
if (!$ssh->_send_binary_packet($packet)) {
return false;
}
$response = $ssh->_get_channel_packet($request_channel);
if ($response === false) {
return false;
}
$ssh->channel_status[$request_channel] = NET_SSH2_MSG_CHANNEL_OPEN;
$this->forward_status = self::FORWARD_ACTIVE;
return true;
}
/**
* On successful channel open
*
* This method is called upon successful channel
* open to give the SSH Agent an opportunity
* to take further action. i.e. request agent forwarding
*
* @param Net_SSH2 $ssh
* @access private
*/
function _on_channel_open($ssh)
{
if ($this->forward_status == self::FORWARD_REQUEST) {
$this->_request_forwarding($ssh);
}
}
/**
* Forward data to SSH Agent and return data reply
*
* @param string $data
* @return data from SSH Agent
* @access private
*/
function _forward_data($data)
{
if ($this->expected_bytes > 0) {
$this->socket_buffer.= $data;
$this->expected_bytes -= strlen($data);
} else {
$agent_data_bytes = current(unpack('N', $data));
$current_data_bytes = strlen($data);
$this->socket_buffer = $data;
if ($current_data_bytes != $agent_data_bytes + 4) {
$this->expected_bytes = ($agent_data_bytes + 4) - $current_data_bytes;
return false;
}
}
if (strlen($this->socket_buffer) != fwrite($this->fsock, $this->socket_buffer)) {
user_error('Connection closed attempting to forward data to SSH agent');
}
$this->socket_buffer = '';
$this->expected_bytes = 0;
$agent_reply_bytes = current(unpack('N', fread($this->fsock, 4)));
$agent_reply_data = fread($this->fsock, $agent_reply_bytes);
$agent_reply_data = current(unpack('a*', $agent_reply_data));
return pack('Na*', $agent_reply_bytes, $agent_reply_data);
}
} }

View file

@ -0,0 +1,158 @@
<?php
/**
* Pure-PHP ssh-agent client.
*
* PHP version 5
*
* @category System
* @package SSH\Agent
* @author Jim Wigginton <terrafrost@php.net>
* @copyright 2009 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
* @internal See http://api.libssh.org/rfc/PROTOCOL.agent
*/
namespace phpseclib\System\SSH\Agent;
use phpseclib\System\SSH\Agent;
/**
* Pure-PHP ssh-agent client identity object
*
* Instantiation should only be performed by \phpseclib\System\SSH\Agent class.
* This could be thought of as implementing an interface that phpseclib\Crypt\RSA
* implements. ie. maybe a Net_SSH_Auth_PublicKey interface or something.
* The methods in this interface would be getPublicKey and sign since those are the
* methods phpseclib looks for to perform public key authentication.
*
* @package SSH\Agent
* @author Jim Wigginton <terrafrost@php.net>
* @access internal
*/
class Identity
{
/**
* Key Object
*
* @var \phpseclib\Crypt\RSA
* @access private
* @see self::getPublicKey()
*/
var $key;
/**
* Key Blob
*
* @var string
* @access private
* @see self::sign()
*/
var $key_blob;
/**
* Socket Resource
*
* @var resource
* @access private
* @see self::sign()
*/
var $fsock;
/**
* Default Constructor.
*
* @param resource $fsock
* @return \phpseclib\System\SSH\Agent\Identity
* @access private
*/
function __construct($fsock)
{
$this->fsock = $fsock;
}
/**
* Set Public Key
*
* Called by \phpseclib\System\SSH\Agent::requestIdentities()
*
* @param \phpseclib\Crypt\RSA $key
* @access private
*/
function setPublicKey($key)
{
$this->key = $key;
$this->key->setPublicKey();
}
/**
* Set Public Key
*
* Called by \phpseclib\System\SSH\Agent::requestIdentities(). The key blob could be extracted from $this->key
* but this saves a small amount of computation.
*
* @param string $key_blob
* @access private
*/
function setPublicKeyBlob($key_blob)
{
$this->key_blob = $key_blob;
}
/**
* Get Public Key
*
* Wrapper for $this->key->getPublicKey()
*
* @param int $format optional
* @return mixed
* @access public
*/
function getPublicKey($format = null)
{
return !isset($format) ? $this->key->getPublicKey() : $this->key->getPublicKey($format);
}
/**
* Set Signature Mode
*
* Doesn't do anything as ssh-agent doesn't let you pick and choose the signature mode. ie.
* ssh-agent's only supported mode is \phpseclib\Crypt\RSA::SIGNATURE_PKCS1
*
* @param int $mode
* @access public
*/
function setSignatureMode($mode)
{
}
/**
* Create a signature
*
* See "2.6.2 Protocol 2 private key signature request"
*
* @param string $message
* @return string
* @access public
*/
function sign($message)
{
// the last parameter (currently 0) is for flags and ssh-agent only defines one flag (for ssh-dss): SSH_AGENT_OLD_SIGNATURE
$packet = pack('CNa*Na*N', Agent::SSH_AGENTC_SIGN_REQUEST, strlen($this->key_blob), $this->key_blob, strlen($message), $message, 0);
$packet = pack('Na*', strlen($packet), $packet);
if (strlen($packet) != fputs($this->fsock, $packet)) {
user_error('Connection closed during signing');
}
$length = current(unpack('N', fread($this->fsock, 4)));
$type = ord(fread($this->fsock, 1));
if ($type != Agent::SSH_AGENT_SIGN_RESPONSE) {
user_error('Unable to retrieve signature');
}
$signature_blob = fread($this->fsock, $length - 1);
// the only other signature format defined - ssh-dss - is the same length as ssh-rsa
// the + 12 is for the other various SSH added length fields
return substr($signature_blob, strlen('ssh-rsa') + 12);
}
}

View file

@ -1,39 +0,0 @@
<?php
/**
* Pure-PHP ssh-agent client wrapper
*
* PHP versions 4 and 5
*
* Originally System_SSH_Agent was accessed as System/SSH_Agent.php instead of
* System/SSH/Agent.php. The problem with this is that PSR0 compatible autoloaders
* don't support that kind of directory layout hence the package being moved and
* this "alias" being created to maintain backwards compatibility.
*
* LICENSE: 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.
*
* @category System
* @package System_SSH_Agent
* @author Jim Wigginton <terrafrost@php.net>
* @copyright 2014 Jim Wigginton
* @license http://www.opensource.org/licenses/mit-license.html MIT License
* @link http://phpseclib.sourceforge.net
* @internal See http://api.libssh.org/rfc/PROTOCOL.agent
*/
require_once 'SSH/Agent.php';

View file

@ -0,0 +1,16 @@
<?php
/**
* Bootstrapping File for phpseclib
*
* @license http://www.opensource.org/licenses/mit-license.html MIT License
*/
if (extension_loaded('mbstring')) {
// 2 - MB_OVERLOAD_STRING
if (ini_get('mbstring.func_overload') & 2) {
throw new \UnexpectedValueException(
'Overloading of string functions using mbstring.func_overload ' .
'is not supported by phpseclib.'
);
}
}

View file

@ -0,0 +1,4 @@
.DS_Store
.tmp
pkg
tmp

View file

@ -0,0 +1,18 @@
language: php
php:
- 5.3
- 5.4
- 5.5
- 5.6
- 7.0
- hhvm
# - nightly
env:
- PHPSECLIB="2.0.0"
- PHPSECLIB="2.0.1"
- PHPSECLIB="2.0.2"
- PHPSECLIB="2.0.3"
- PHPSECLIB="2.0.4"
before_script: 'sed -i "s/\"phpseclib\/phpseclib\": \"[^\"]*/\"phpseclib\/phpseclib\": \"$PHPSECLIB/" composer.json && composer install --prefer-source --dev'

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1 @@
README.md

View file

@ -30,7 +30,8 @@ Users
OpenPGP.php is currently being used in the following projects: OpenPGP.php is currently being used in the following projects:
* <http://drupal.org/project/openpgp> * <https://drupal.org/project/openpgp>
* <https://wordpress.org/plugins/wp-pgp-encrypted-emails/>
Download Download
-------- --------

View file

@ -1 +1 @@
0.0.1 0.3.0

View file

@ -0,0 +1,24 @@
{
"name": "singpolyma/openpgp-php",
"description": "Pure-PHP implementation of the OpenPGP Message Format (RFC 4880)",
"license": "Unlicense",
"authors": [
{
"name": "Arto Bendiken",
"email": "arto.bendiken@gmail.com"
},
{
"name": "Stephen Paul Weber",
"email": "singpolyma@singpolyma.net"
}
],
"require": {
"phpseclib/phpseclib": ">=2.0.0 <=2.0.4"
},
"require-dev": {
"phpunit/phpunit": "~4.0"
},
"autoload": {
"classmap": ["lib/"]
}
}

View file

@ -0,0 +1,31 @@
<?php
require_once dirname(__FILE__).'/../lib/openpgp.php';
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
/* Parse secret key from STDIN, the key must not be password protected */
$wkey = OpenPGP_Message::parse(file_get_contents('php://stdin'));
$wkey = $wkey[0];
$string = "This\nis\na\ntest.";
/* Create a new literal data packet */
$data = new OpenPGP_LiteralDataPacket($string, array('format' => 'u', 'filename' => 'stuff.txt'));
$data->normalize(true); // Clearsign-style normalization of the LiteralDataPacket
/* Create a signer from the key */
$sign = new OpenPGP_Crypt_RSA($wkey);
/* The message is the signed data packet */
$m = $sign->sign($data);
/* Generate clearsigned data */
$packets = $m->signatures()[0];
echo "-----BEGIN PGP SIGNED MESSAGE-----\nHash: SHA256\n\n";
// Output normalised data. You could convert line endings here
// without breaking the signature, but do not add any
// trailing whitespace to lines.
echo preg_replace("/^-/", "- -", $packets[0]->data)."\n";
echo OpenPGP::enarmor($packets[1][0]->to_bytes(), "PGP SIGNATURE");
?>

View file

@ -0,0 +1,27 @@
<?php
// USAGE: php examples/deASCIIdeCrypt.php secretkey.asc password message.asc
// This will fail if the algo on key or message is not 3DES or AES
require_once dirname(__FILE__).'/../lib/openpgp.php';
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
require_once dirname(__FILE__).'/../lib/openpgp_crypt_symmetric.php';
$keyASCII = file_get_contents($argv[1]);
$msgASCII = file_get_contents($argv[3]);
$keyEncrypted = OpenPGP_Message::parse(OpenPGP::unarmor($keyASCII, 'PGP PRIVATE KEY BLOCK'));
// Try each secret key packet
foreach($keyEncrypted as $p) {
if(!($p instanceof OpenPGP_SecretKeyPacket)) continue;
$key = OpenPGP_Crypt_Symmetric::decryptSecretKey($argv[2], $p);
$msg = OpenPGP_Message::parse(OpenPGP::unarmor($msgASCII, 'PGP MESSAGE'));
$decryptor = new OpenPGP_Crypt_RSA($key);
$decrypted = $decryptor->decrypt($msg);
var_dump($decrypted);
}

View file

@ -0,0 +1,15 @@
<?php
require_once dirname(__FILE__).'/../lib/openpgp.php';
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
require_once dirname(__FILE__).'/../lib/openpgp_crypt_symmetric.php';
$key = OpenPGP_Message::parse(file_get_contents(dirname(__FILE__) . '/../tests/data/helloKey.gpg'));
$data = new OpenPGP_LiteralDataPacket('This is text.', array('format' => 'u', 'filename' => 'stuff.txt'));
$encrypted = OpenPGP_Crypt_Symmetric::encrypt($key, new OpenPGP_Message(array($data)));
// Now decrypt it with the same key
$decryptor = new OpenPGP_Crypt_RSA($key);
$decrypted = $decryptor->decrypt($encrypted);
var_dump($decrypted);

View file

@ -0,0 +1,31 @@
<?php
require_once dirname(__FILE__).'/../lib/openpgp.php';
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
$rsa = new \phpseclib\Crypt\RSA();
$k = $rsa->createKey(512);
$rsa->loadKey($k['privatekey']);
$nkey = new OpenPGP_SecretKeyPacket(array(
'n' => $rsa->modulus->toBytes(),
'e' => $rsa->publicExponent->toBytes(),
'd' => $rsa->exponent->toBytes(),
'p' => $rsa->primes[2]->toBytes(),
'q' => $rsa->primes[1]->toBytes(),
'u' => $rsa->coefficients[2]->toBytes()
));
$uid = new OpenPGP_UserIDPacket('Test <test@example.com>');
$wkey = new OpenPGP_Crypt_RSA($nkey);
$m = $wkey->sign_key_userid(array($nkey, $uid));
// Serialize private key
print $m->to_bytes();
// Serialize public key message
$pubm = clone($m);
$pubm[0] = new OpenPGP_PublicKeyPacket($pubm[0]);
$public_bytes = $pubm->to_bytes();

View file

@ -0,0 +1,22 @@
<?php
require_once dirname(__FILE__).'/../lib/openpgp.php';
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
/* Parse secret key from STDIN, the key must not be password protected */
$wkey = OpenPGP_Message::parse(file_get_contents('php://stdin'));
$wkey = $wkey[0];
/* Create a new literal data packet */
$data = new OpenPGP_LiteralDataPacket('This is text.', array('format' => 'u', 'filename' => 'stuff.txt'));
/* Create a signer from the key */
$sign = new OpenPGP_Crypt_RSA($wkey);
/* The message is the signed data packet */
$m = $sign->sign($data);
/* Output the raw message bytes to STDOUT */
echo $m->to_bytes();
?>

View file

@ -0,0 +1,18 @@
<?php
require_once dirname(__FILE__).'/../lib/openpgp.php';
require_once dirname(__FILE__).'/../lib/openpgp_crypt_rsa.php';
/* Parse public key from STDIN */
$wkey = OpenPGP_Message::parse(file_get_contents('php://stdin'));
/* Parse signed message from file named "t" */
$m = OpenPGP_Message::parse(file_get_contents('t'));
/* Create a verifier for the key */
$verify = new OpenPGP_Crypt_RSA($wkey);
/* Dump verification information to STDOUT */
var_dump($verify->verify($m));
?>

View file

@ -5,7 +5,7 @@
* (RFC 4880). * (RFC 4880).
* *
* @package OpenPGP * @package OpenPGP
* @version 0.0.1 * @version 0.3.0
* @author Arto Bendiken <arto.bendiken@gmail.com> * @author Arto Bendiken <arto.bendiken@gmail.com>
* @author Stephen Paul Weber <singpolyma@singpolyma.net> * @author Stephen Paul Weber <singpolyma@singpolyma.net>
* @see http://github.com/bendiken/openpgp-php * @see http://github.com/bendiken/openpgp-php
@ -1327,6 +1327,22 @@ class OpenPGP_PublicKeyPacket extends OpenPGP_Packet {
function __construct($key=array(), $algorithm='RSA', $timestamp=NULL, $version=4) { function __construct($key=array(), $algorithm='RSA', $timestamp=NULL, $version=4) {
parent::__construct(); parent::__construct();
if($key instanceof OpenPGP_PublicKeyPacket) {
$this->algorithm = $key->algorithm;
$this->key = array();
// Restrict to only the fields we need
foreach (self::$key_fields[$this->algorithm] as $field) {
$this->key[$field] = $key->key[$field];
}
$this->key_id = $key->key_id;
$this->fingerprint = $key->fingerprint;
$this->timestamp = $key->timestamp;
$this->version = $key->version;
$this->v3_days_of_validity = $key->v3_days_of_validity;
} else {
$this->key = $key; $this->key = $key;
if(is_string($this->algorithm = $algorithm)) { if(is_string($this->algorithm = $algorithm)) {
$this->algorithm = array_search($this->algorithm, self::$algorithms); $this->algorithm = array_search($this->algorithm, self::$algorithms);
@ -1338,6 +1354,7 @@ class OpenPGP_PublicKeyPacket extends OpenPGP_Packet {
$this->key_id = substr($this->fingerprint(), -8); $this->key_id = substr($this->fingerprint(), -8);
} }
} }
}
// Find self signatures in a message, these often contain metadata about the key // Find self signatures in a message, these often contain metadata about the key
function self_signatures($message) { function self_signatures($message) {
@ -1685,10 +1702,19 @@ class OpenPGP_LiteralDataPacket extends OpenPGP_Packet {
$this->timestamp = isset($opt['timestamp']) ? $opt['timestamp'] : time(); $this->timestamp = isset($opt['timestamp']) ? $opt['timestamp'] : time();
} }
function normalize() { function normalize($clearsign=false) {
if($clearsign && ($this->format != 'u' && $this->format != 't')) {
$this->format = 'u'; // Clearsign must be text
}
if($this->format == 'u' || $this->format == 't') { // Normalize line endings if($this->format == 'u' || $this->format == 't') { // Normalize line endings
$this->data = str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", $this->data))); $this->data = str_replace("\n", "\r\n", str_replace("\r", "\n", str_replace("\r\n", "\n", $this->data)));
} }
if($clearsign) {
// When clearsigning, do not sign over trailing whitespace
$this->data = preg_replace('/\s+\r/', "\r", $this->data);
}
} }
function read() { function read() {

View file

@ -7,7 +7,11 @@
*/ */
// From http://phpseclib.sourceforge.net/ // From http://phpseclib.sourceforge.net/
require_once 'Crypt/RSA.php'; use phpseclib\Crypt\RSA as Crypt_RSA;
use phpseclib\Math\BigInteger as Math_BigInteger;
define('CRYPT_RSA_ENCRYPTION_PKCS1', Crypt_RSA::ENCRYPTION_PKCS1);
define('CRYPT_RSA_SIGNATURE_PKCS1', Crypt_RSA::SIGNATURE_PKCS1);
require_once dirname(__FILE__).'/openpgp.php'; require_once dirname(__FILE__).'/openpgp.php';
@include_once dirname(__FILE__).'/openpgp_crypt_symmetric.php'; /* For encrypt/decrypt */ @include_once dirname(__FILE__).'/openpgp_crypt_symmetric.php'; /* For encrypt/decrypt */
@ -150,7 +154,7 @@ class OpenPGP_Crypt_RSA {
if(!$sig) { if(!$sig) {
$sig = new OpenPGP_SignaturePacket($packet, 'RSA', strtoupper($hash)); $sig = new OpenPGP_SignaturePacket($packet, 'RSA', strtoupper($hash));
$sig->signature_type = 0x13; $sig->signature_type = 0x13;
$sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_KeyFlagsPacket(array(0x01, 0x02)); $sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_KeyFlagsPacket(array(0x01 | 0x02));
$sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_IssuerPacket($keyid); $sig->hashed_subpackets[] = new OpenPGP_SignaturePacket_IssuerPacket($keyid);
$packet[] = $sig; $packet[] = $sig;
} }
@ -241,8 +245,18 @@ class OpenPGP_Crypt_RSA {
$rsa = self::crypt_rsa_key($mod, $exp); $rsa = self::crypt_rsa_key($mod, $exp);
if($private) { if($private) {
if($packet->key['p'] && $packet->key['q']) $rsa->primes = array($packet->key['p'], $packet->key['q']); /**
if($packet->key['u']) $rsa->coefficients = array($packet->key['u']); * @see https://github.com/phpseclib/phpseclib/issues/1113
* Primes and coefficients now use BigIntegers.
**/
//set the primes
if($packet->key['p'] && $packet->key['q'])
$rsa->primes = array(
1 => new Math_BigInteger($packet->key['p'], 256),
2 => new Math_BigInteger($packet->key['q'], 256)
);
// set the coefficients
if($packet->key['u']) $rsa->coefficients = array(2 => new Math_BigInteger($packet->key['u'], 256));
} }
return $rsa; return $rsa;

View file

@ -1,20 +1,24 @@
<?php <?php
use phpseclib\Crypt\TripleDES as Crypt_TripleDES;
use phpseclib\Crypt\AES as Crypt_AES;
use phpseclib\Crypt\Random;
define('CRYPT_DES_MODE_CFB', Crypt_TripleDES::MODE_CFB);
define('CRYPT_AES_MODE_CFB', Crypt_AES::MODE_CFB);
require_once dirname(__FILE__).'/openpgp.php'; require_once dirname(__FILE__).'/openpgp.php';
@include_once dirname(__FILE__).'/openpgp_crypt_rsa.php'; @include_once dirname(__FILE__).'/openpgp_crypt_rsa.php';
@include_once dirname(__FILE__).'/openpgp_mcrypt_wrapper.php'; @include_once dirname(__FILE__).'/openpgp_mcrypt_wrapper.php';
@include_once 'Crypt/AES.php';
@include_once 'Crypt/TripleDES.php';
require_once 'Crypt/Random.php'; // part of phpseclib is absolutely required
class OpenPGP_Crypt_Symmetric { class OpenPGP_Crypt_Symmetric {
public static function encrypt($passphrases_and_keys, $message, $symmetric_algorithm=9) { public static function encrypt($passphrases_and_keys, $message, $symmetric_algorithm=9) {
list($cipher, $key_bytes, $key_block_bytes) = self::getCipher($symmetric_algorithm); list($cipher, $key_bytes, $key_block_bytes) = self::getCipher($symmetric_algorithm);
if(!$cipher) throw new Exception("Unsupported cipher"); if(!$cipher) throw new Exception("Unsupported cipher");
$prefix = crypt_random_string($key_block_bytes); $prefix = Random::string($key_block_bytes);
$prefix .= substr($prefix, -2); $prefix .= substr($prefix, -2);
$key = crypt_random_string($key_bytes); $key = Random::string($key_bytes);
$cipher->setKey($key); $cipher->setKey($key);
$to_encrypt = $prefix . $message->to_bytes(); $to_encrypt = $prefix . $message->to_bytes();
@ -36,7 +40,7 @@ class OpenPGP_Crypt_Symmetric {
$esk = pack('n', OpenPGP::bitlength($esk)) . $esk; $esk = pack('n', OpenPGP::bitlength($esk)) . $esk;
array_unshift($encrypted, new OpenPGP_AsymmetricSessionKeyPacket($pass->algorithm, $pass->fingerprint(), $esk)); array_unshift($encrypted, new OpenPGP_AsymmetricSessionKeyPacket($pass->algorithm, $pass->fingerprint(), $esk));
} else if(is_string($pass)) { } else if(is_string($pass)) {
$s2k = new OpenPGP_S2K(crypt_random_string(10)); $s2k = new OpenPGP_S2K(Random::string(10));
$cipher->setKey($s2k->make_key($pass, $key_bytes)); $cipher->setKey($s2k->make_key($pass, $key_bytes));
$esk = $cipher->encrypt(chr($symmetric_algorithm) . $key); $esk = $cipher->encrypt(chr($symmetric_algorithm) . $key);
array_unshift($encrypted, new OpenPGP_SymmetricSessionKeyPacket($s2k, $esk, $symmetric_algorithm)); array_unshift($encrypted, new OpenPGP_SymmetricSessionKeyPacket($s2k, $esk, $symmetric_algorithm));
@ -143,38 +147,32 @@ class OpenPGP_Crypt_Symmetric {
$cipher = NULL; $cipher = NULL;
switch($algo) { switch($algo) {
case 2: case 2:
if(class_exists('Crypt_TripleDES')) {
$cipher = new Crypt_TripleDES(CRYPT_DES_MODE_CFB); $cipher = new Crypt_TripleDES(CRYPT_DES_MODE_CFB);
$key_bytes = 24; $key_bytes = 24;
$key_block_bytes = 8; $key_block_bytes = 8;
}
break; break;
case 3: case 3:
if(defined('MCRYPT_CAST_128')) { if(defined('MCRYPT_CAST_128')) {
$cipher = new MCryptWrapper(MCRYPT_CAST_128); $cipher = new MCryptWrapper(MCRYPT_CAST_128);
} else {
throw new Exception("Unsupported cipher: you must have mcrypt installed to use CAST5");
} }
break; break;
case 7: case 7:
if(class_exists('Crypt_AES')) {
$cipher = new Crypt_AES(CRYPT_AES_MODE_CFB); $cipher = new Crypt_AES(CRYPT_AES_MODE_CFB);
$cipher->setKeyLength(128); $cipher->setKeyLength(128);
}
break; break;
case 8: case 8:
if(class_exists('Crypt_AES')) {
$cipher = new Crypt_AES(CRYPT_AES_MODE_CFB); $cipher = new Crypt_AES(CRYPT_AES_MODE_CFB);
$cipher->setKeyLength(192); $cipher->setKeyLength(192);
}
break; break;
case 9: case 9:
if(class_exists('Crypt_AES')) {
$cipher = new Crypt_AES(CRYPT_AES_MODE_CFB); $cipher = new Crypt_AES(CRYPT_AES_MODE_CFB);
$cipher->setKeyLength(256); $cipher->setKeyLength(256);
}
break; break;
} }
if(!$cipher) return array(NULL, NULL, NULL); // Unsupported cipher if(!$cipher) return array(NULL, NULL, NULL); // Unsupported cipher
if(!isset($key_bytes)) $key_bytes = $cipher->key_size; if(!isset($key_bytes)) $key_bytes = isset($cipher->key_size)?$cipher->key_size:$cipher->key_length;
if(!isset($key_block_bytes)) $key_block_bytes = $cipher->block_size; if(!isset($key_block_bytes)) $key_block_bytes = $cipher->block_size;
return array($cipher, $key_bytes, $key_block_bytes); return array($cipher, $key_bytes, $key_block_bytes);
} }

View file

@ -0,0 +1,27 @@
<phpunit bootstrap="tests/bootstrap.php">
<testsuites>
<testsuite name="Serialization">
<file>tests/suite.php</file>
</testsuite>
<testsuite name="Fingerprint">
<file>tests/suite.php</file>
</testsuite>
<testsuite name="MessageVerification">
<file>tests/phpseclib_suite.php</file>
</testsuite>
<testsuite name="KeyVerification">
<file>tests/phpseclib_suite.php</file>
</testsuite>
<testsuite name="Decryption">
<file>tests/phpseclib_suite.php</file>
</testsuite>
<testsuite name="Encryption">
<file>tests/phpseclib_suite.php</file>
</testsuite>
</testsuites>
</phpunit>

View file

@ -0,0 +1,2 @@
<?php
@include_once dirname(__FILE__) . '/../vendor/autoload.php';

View file

@ -0,0 +1 @@
´$Test Key (RSA) <testkey@example.org>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1 @@
´$Test Key (DSA) <testkey@example.com>

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1 @@
´+Test Key (DSA sign-only) <test@example.net>

Binary file not shown.

Binary file not shown.

View file

@ -0,0 +1 @@
´.Test Key (RSA sign-only) <testkey@example.net>

Binary file not shown.

Some files were not shown because too many files have changed in this diff Show more