Skip to content

Commit

Permalink
updates to Exceptions
Browse files Browse the repository at this point in the history
  • Loading branch information
terrafrost committed Dec 31, 2018
1 parent c6f9807 commit 17e6938
Show file tree
Hide file tree
Showing 15 changed files with 170 additions and 52 deletions.
47 changes: 26 additions & 21 deletions phpseclib/Crypt/Common/SymmetricKey.php
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,11 @@
use phpseclib\Common\Functions\Strings;
use phpseclib\Math\BigInteger;
use phpseclib\Math\BinaryField;
use phpseclib\Exception\BadDecryptionException;
use phpseclib\Exception\BadModeException;
use phpseclib\Exception\InconsistentSetupException;
use phpseclib\Exception\InsufficientSetupException;
use phpseclib\Exception\UnsupportedAlgorithmException;

/**
* Base Class for all \phpseclib\Crypt\* cipher classes
Expand Down Expand Up @@ -580,15 +585,15 @@ abstract class SymmetricKey
*
* @param string $mode
* @access public
* @throws \InvalidArgumentException if an invalid / unsupported mode is provided
* @throws BadModeException if an invalid / unsupported mode is provided
*/
public function __construct($mode)
{
$mode = strtolower($mode);
// necessary because of 5.6 compatibility; we can't do isset(self::MODE_MAP[$mode]) in 5.6
$map = self::MODE_MAP;
if (!isset($map[$mode])) {
throw new \InvalidArgumentException('No valid mode has been specified');
throw new BadModeException('No valid mode has been specified');
}

$mode = self::MODE_MAP[$mode];
Expand All @@ -608,15 +613,15 @@ public function __construct($mode)
break;
case self::MODE_GCM:
if ($this->block_size != 16) {
throw new \InvalidArgumentException('GCM is only valid for block ciphers with a block size of 128 bits');
throw new BadModeException('GCM is only valid for block ciphers with a block size of 128 bits');
}
if (!isset(self::$gcmField)) {
self::$gcmField = new BinaryField(128, 7, 2, 1, 0);
}
$this->paddable = false;
break;
default:
throw new \InvalidArgumentException('No valid mode has been specified');
throw new BadModeException('No valid mode has been specified');
}

$this->mode = $mode;
Expand All @@ -630,21 +635,21 @@ public function __construct($mode)
* @access public
* @param string $iv
* @throws \LengthException if the IV length isn't equal to the block size
* @throws \InvalidArgumentException if an IV is provided when one shouldn't be
* @throws \BadMethodCallException if an IV is provided when one shouldn't be
* @internal Can be overwritten by a sub class, but does not have to be
*/
public function setIV($iv)
{
if ($this->mode == self::MODE_ECB) {
throw new \InvalidArgumentException('This mode does not require an IV.');
throw new \BadMethodCallException('This mode does not require an IV.');
}

if ($this->mode == self::MODE_GCM) {
throw new \InvalidArgumentException('Use setNonce instead');
throw new \BadMethodCallException('Use setNonce instead');
}

if (!$this->usesIV()) {
throw new \InvalidArgumentException('This algorithm does not use an IV.');
throw new \BadMethodCallExceptionn('This algorithm does not use an IV.');
}

if (strlen($iv) != $this->block_size) {
Expand All @@ -667,7 +672,7 @@ public function setIV($iv)
public function setNonce($nonce)
{
if ($this->mode != self::MODE_GCM) {
throw new \RuntimeException('Nonces are only used in GCM mode.');
throw new \BadMethodCallException('Nonces are only used in GCM mode.');
}

$this->nonce = $nonce;
Expand Down Expand Up @@ -762,7 +767,7 @@ public function setKeyLength($length)

if (is_string($this->key) && strlen($this->key) != $this->explicit_key_length) {
$this->key = false;
throw new \LengthException('Key has already been set and is not ' .$this->explicit_key_length . ' bytes long');
throw new InconsistentSetupException('Key has already been set and is not ' .$this->explicit_key_length . ' bytes long');
}
}

Expand All @@ -783,7 +788,7 @@ public function setKeyLength($length)
public function setKey($key)
{
if ($this->explicit_key_length !== false && strlen($key) != $this->explicit_key_length) {
throw new \LengthException('Key length has already been set to ' . $this->explicit_key_length . ' bytes and this key is ' . strlen($key) . ' bytes');
throw new InconsistentSetupException('Key length has already been set to ' . $this->explicit_key_length . ' bytes and this key is ' . strlen($key) . ' bytes');
}

$this->key = $key;
Expand Down Expand Up @@ -932,7 +937,7 @@ public function setPassword($password, $method = 'pbkdf2', ...$func_args)
}
break;
default:
throw new \InvalidArgumentException($method . ' is not a supported password hashing method');
throw new UnsupportedAlgorithmException($method . ' is not a supported password hashing method');
}

$this->setKey($key);
Expand Down Expand Up @@ -1359,7 +1364,7 @@ public function decrypt($ciphertext)

if ($this->mode == self::MODE_GCM) {
if ($this->oldtag === false) {
throw new \UnexpectedValueException('Authentication Tag has not been set');
throw new InsufficientSetupException('Authentication Tag has not been set');
}

$oldIV = $this->iv;
Expand All @@ -1379,7 +1384,7 @@ public function decrypt($ciphertext)
$newtag = $cipher->encrypt($s);
if ($this->oldtag != substr($newtag, 0, strlen($newtag))) {
$this->oldtag = false;
throw new \UnexpectedValueException('Derived authentication tag and supplied authentication tag do not match');
throw new BadDecryptionException('Derived authentication tag and supplied authentication tag do not match');
}
$this->oldtag = false;
return $plaintext;
Expand Down Expand Up @@ -1679,7 +1684,7 @@ public function decrypt($ciphertext)
public function getTag($length = 16)
{
if ($this->mode != self::MODE_GCM) {
throw new \RuntimeException('Only GCM mode utilizes authentication tags');
throw new \BadMethodCallException('Only GCM mode utilizes authentication tags');
}

// the tag is basically a single encrypted block of a 128-bit cipher. it can't be greater than 16
Expand Down Expand Up @@ -1710,7 +1715,7 @@ public function getTag($length = 16)
public function setTag($tag)
{
if ($this->mode != self::MODE_GCM) {
throw new \RuntimeException('Only GCM mode utilizes authentication tags');
throw new \BadMethodCallException('Only GCM mode utilizes authentication tags');
}

$length = strlen($tag);
Expand Down Expand Up @@ -1981,7 +1986,7 @@ public function enableContinuousBuffer()
}

if ($this->mode == self::MODE_GCM) {
throw new \RuntimeException('This mode does not run in continuous mode');
throw new \BadMethodCallException('This mode does not run in continuous mode');
}

$this->continuousBuffer = true;
Expand Down Expand Up @@ -2246,7 +2251,7 @@ protected function setup()

if ($this->mode == self::MODE_GCM) {
if ($this->nonce === false) {
throw new \UnexpectedValueException('No nonce has been defined');
throw new InsufficientSetupException('No nonce has been defined');
}
if (!in_array($this->engine, [self::ENGINE_LIBSODIUM, self::ENGINE_OPENSSL_GCM])) {
$this->setupGCM();
Expand All @@ -2257,12 +2262,12 @@ protected function setup()

if ($this->iv === false && !in_array($this->mode, [self::MODE_STREAM, self::MODE_ECB])) {
if ($this->mode != self::MODE_GCM || !in_array($this->engine, [self::ENGINE_LIBSODIUM, self::ENGINE_OPENSSL_GCM])) {
throw new \UnexpectedValueException('No IV has been defined');
throw new InsufficientSetupException('No IV has been defined');
}
}

if ($this->key === false) {
throw new \UnexpectedValueException('No key has been defined');
throw new InsufficientSetupException('No key has been defined');
}

$this->encryptIV = $this->decryptIV = $this->iv;
Expand Down Expand Up @@ -2360,7 +2365,7 @@ protected function unpad($text)
$length = ord($text[strlen($text) - 1]);

if (!$length || $length > $this->block_size) {
throw new \LengthException("The ciphertext has an invalid padding length ($length) compared to the block size ({$this->block_size})");
throw new BadDecryptionException("The ciphertext has an invalid padding length ($length) compared to the block size ({$this->block_size})");
}

return substr($text, 0, -$length);
Expand Down
5 changes: 3 additions & 2 deletions phpseclib/Crypt/DES.php
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@
namespace phpseclib\Crypt;

use phpseclib\Crypt\Common\BlockCipher;
use phpseclib\Exception\BadModeException;

/**
* Pure-PHP implementation of DES.
Expand Down Expand Up @@ -585,12 +586,12 @@ class DES extends BlockCipher
*
* @param int $mode
* @access public
* @throws \InvalidArgumentException if an invalid / unsupported mode is provided
* @throws BadModeException if an invalid / unsupported mode is provided
*/
public function __construct($mode)
{
if ($mode == self::MODE_STREAM) {
throw new \InvalidArgumentException('Block ciphers cannot be ran in stream mode');
throw new BadModeException('Block ciphers cannot be ran in stream mode');
}

parent::__construct($mode);
Expand Down
7 changes: 4 additions & 3 deletions phpseclib/Crypt/DSA.php
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@
use phpseclib\Crypt\ECDSA\Signature\ASN1 as ASN1Signature;
use phpseclib\Exception\UnsupportedOperationException;
use phpseclib\Exception\NoKeyLoadedException;
use phpseclib\Exception\InsufficientSetupException;

/**
* Pure-PHP FIPS 186-4 compliant implementation of DSA.
Expand Down Expand Up @@ -200,7 +201,7 @@ public static function createKey(...$args)
} else if (!count($args)) {
$private = self::createParameters();
} else {
throw new \InvalidArgumentException('Valid parameters are either two integers (L and N), a single DSA object or no parameters at all.');
throw new InsufficientSetupException('Valid parameters are either two integers (L and N), a single DSA object or no parameters at all.');
}

$private->x = BigInteger::randomRange(self::$one, $private->q->subtract(self::$one));
Expand Down Expand Up @@ -465,7 +466,7 @@ public function sign($message, $format = 'ASN1')
}

if (empty($this->p)) {
throw new \RuntimeException('DSA Prime P is not set');
throw new InsufficientSetupException('DSA Prime P is not set');
}

if (self::$engines['OpenSSL'] && in_array($this->hash->getHash(), openssl_get_md_methods())) {
Expand Down Expand Up @@ -552,7 +553,7 @@ public function verify($message, $signature, $format = 'ASN1')
}

if (empty($this->p)) {
throw new \RuntimeException('DSA Prime P is not set');
throw new InsufficientSetupException('DSA Prime P is not set');
}

if (self::$engines['OpenSSL'] && in_array($this->hash->getHash(), openssl_get_md_methods())) {
Expand Down
16 changes: 9 additions & 7 deletions phpseclib/Crypt/ECDSA.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,9 @@
use phpseclib\Crypt\Common\AsymmetricKey;
use phpseclib\Exception\UnsupportedCurveException;
use phpseclib\Exception\UnsupportedOperationException;
use phpseclib\Exception\UnsupportedAlgorithmException;
use phpseclib\Exception\NoKeyLoadedException;
use phpseclib\Exception\InsufficientSetupException;
use phpseclib\File\ASN1;
use phpseclib\File\ASN1\Maps\ECParameters;
use phpseclib\Crypt\ECDSA\BaseCurves\TwistedEdwards as TwistedEdwardsCurve;
Expand Down Expand Up @@ -216,11 +218,11 @@ public function load($key, $type = false)

if ($components['curve'] instanceof Ed25519 && $this->hashManuallySet && $this->hash->getHash() != 'sha512') {
$this->clearKey();
throw new \RuntimeException('Ed25519 only supports sha512 as a hash');
throw new UnsupportedAlgorithmException('Ed25519 only supports sha512 as a hash');
}
if ($components['curve'] instanceof Ed448 && $this->hashManuallySet && $this->hash->getHash() != 'shake256-912') {
$this->clearKey();
throw new \RuntimeException('Ed448 only supports shake256 with a length of 114 bytes');
throw new UnsupportedAlgorithmException('Ed448 only supports shake256 with a length of 114 bytes');
}

$this->curve = $components['curve'];
Expand Down Expand Up @@ -426,7 +428,7 @@ public function getParameters($type = 'PKCS1')
public function getEngine()
{
if (!isset($this->curve)) {
throw new \RuntimeException('getEngine should not be called until after a key has been loaded');
throw new InsufficientSetupException('getEngine should not be called until after a key has been loaded');
}

if ($this->curve instanceof TwistedEdwardsCurve) {
Expand Down Expand Up @@ -455,10 +457,10 @@ public function setContext($context = null)
return;
}
if (!is_string($context)) {
throw new \RuntimeException('setContext expects a string');
throw new \InvalidArgumentException('setContext expects a string');
}
if (strlen($context) > 255) {
throw new \RuntimeException('The context is supposed to be, at most, 255 bytes long');
throw new \LengthException('The context is supposed to be, at most, 255 bytes long');
}
$this->context = $context;
}
Expand All @@ -472,10 +474,10 @@ public function setContext($context = null)
public function setHash($hash)
{
if ($this->curve instanceof Ed25519 && $this->hash != 'sha512') {
throw new \RuntimeException('Ed25519 only supports sha512 as a hash');
throw new UnsupportedAlgorithmException('Ed25519 only supports sha512 as a hash');
}
if ($this->curve instanceof Ed448 && $this->hash != 'shake256-912') {
throw new \RuntimeException('Ed448 only supports shake256 with a length of 114 bytes');
throw new UnsupportedAlgorithmException('Ed448 only supports shake256 with a length of 114 bytes');
}

parent::setHash($hash);
Expand Down
3 changes: 2 additions & 1 deletion phpseclib/Crypt/RC2.php
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@
namespace phpseclib\Crypt;

use phpseclib\Crypt\Common\BlockCipher;
use phpseclib\Exception\BadModeException;

/**
* Pure-PHP implementation of RC2.
Expand Down Expand Up @@ -271,7 +272,7 @@ class RC2 extends BlockCipher
public function __construct($mode)
{
if ($mode == self::MODE_STREAM) {
throw new \InvalidArgumentException('Block ciphers cannot be ran in stream mode');
throw new BadModeException('Block ciphers cannot be ran in stream mode');
}

parent::__construct($mode);
Expand Down
12 changes: 6 additions & 6 deletions phpseclib/Crypt/RSA.php
Original file line number Diff line number Diff line change
Expand Up @@ -1139,7 +1139,7 @@ private function mgf1($mgfSeed, $maskLen)
* @access private
* @param string $m
* @param string $l
* @throws \OutOfBoundsException if strlen($m) > $this->k - 2 * $this->hLen - 2
* @throws \LengthException if strlen($m) > $this->k - 2 * $this->hLen - 2
* @return string
*/
private function rsaes_oaep_encrypt($m, $l = '')
Expand All @@ -1152,7 +1152,7 @@ private function rsaes_oaep_encrypt($m, $l = '')
// be output.

if ($mLen > $this->k - 2 * $this->hLen - 2) {
throw new \OutOfBoundsException('Message too long');
throw new \LengthException('Message too long');
}

// EME-OAEP encoding
Expand Down Expand Up @@ -1257,12 +1257,12 @@ private function rsaes_oaep_decrypt($c, $l = '')
* @access private
* @param string $m
* @return bool|string
* @throws \OutOfBoundsException if strlen($m) > $this->k
* @throws \LengthException if strlen($m) > $this->k
*/
private function raw_encrypt($m)
{
if (strlen($m) > $this->k) {
throw new \OutOfBoundsException('Message too long');
throw new \LengthException('Message too long');
}

$temp = $this->os2ip($m);
Expand All @@ -1278,7 +1278,7 @@ private function raw_encrypt($m)
* @access private
* @param string $m
* @param bool $pkcs15_compat optional
* @throws \OutOfBoundsException if strlen($m) > $this->k - 11
* @throws \LengthException if strlen($m) > $this->k - 11
* @return bool|string
*/
private function rsaes_pkcs1_v1_5_encrypt($m, $pkcs15_compat = false)
Expand All @@ -1288,7 +1288,7 @@ private function rsaes_pkcs1_v1_5_encrypt($m, $pkcs15_compat = false)
// Length checking

if ($mLen > $this->k - 11) {
throw new \OutOfBoundsException('Message too long');
throw new \LengthException('Message too long');
}

// EME-PKCS1-v1_5 encoding
Expand Down
Loading

0 comments on commit 17e6938

Please sign in to comment.