Skip to content
This repository has been archived by the owner on Jan 29, 2020. It is now read-only.

Commit

Permalink
Merge branch 'imel96-zf5256' into develop
Browse files Browse the repository at this point in the history
  • Loading branch information
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 8 deletions.
23 changes: 18 additions & 5 deletions src/Symmetric/Mcrypt.php
100644 → 100755
Original file line number Diff line number Diff line change
Expand Up @@ -219,20 +219,33 @@ public function getKeySize()

/**
* Set the encryption key
* If the key is longer than maximum supported, it will be truncated by getKey().
*
* @param string $key
* @throws Exception\InvalidArgumentException
* @return Mcrypt
*/
public function setKey($key)
{
if (empty($key)) {
$keyLen = strlen($key);

if (!$keyLen) {
throw new Exception\InvalidArgumentException('The key cannot be empty');
}
if (strlen($key) < $this->getKeySize()) {
throw new Exception\InvalidArgumentException(
'The size of the key must be at least of ' . $this->getKeySize() . ' bytes'
);
$keySizes = mcrypt_module_get_supported_key_sizes($this->supportedAlgos[$this->algo]);
$maxKey = $this->getKeySize();

/*
* blowfish has $keySizes empty, meaning it can have arbitrary key length.
* the others are more picky.
*/
if (!empty($keySizes) && $keyLen < $maxKey) {

if (!in_array($keyLen, $keySizes)) {
throw new Exception\InvalidArgumentException(
"The size of the key must be one of "
. implode(", ", $keySizes) . " bytes or longer");
}
}
$this->key = $key;

Expand Down
17 changes: 14 additions & 3 deletions test/Symmetric/McryptTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -113,9 +113,20 @@ public function testSetEmptyKey()

public function testSetShortKey()
{
$this->setExpectedException('Zend\Crypt\Symmetric\Exception\InvalidArgumentException');
$result = $this->mcrypt->setKey('short');
$output = $this->mcrypt->encrypt('test');
foreach ($this->mcrypt->getSupportedAlgorithms() as $algo) {
$this->mcrypt->setAlgorithm($algo);
try {
$result = $this->mcrypt->setKey('four');
} catch (\Exception $ex) {
$result = $ex;
}
if ($algo != 'blowfish') {
$this->assertInstanceOf('Zend\Crypt\Symmetric\Exception\InvalidArgumentException',
$result);
} else {
$this->assertInstanceof('Zend\Crypt\Symmetric\Mcrypt', $result);
}
}
}

public function testSetSalt()
Expand Down

0 comments on commit 0d8d71c

Please sign in to comment.