Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions benchmark.php
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
<?php
use \Defuse\Crypto\Crypto;

require_once'autoload.php';

function showResults($type, $start, $end, $count)
Expand Down
103 changes: 54 additions & 49 deletions src/Crypto.php
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,7 @@ final class Crypto

/**
* Use this to generate a random encryption key.
*
*
* @return string
*/
public static function createNewRandomKey()
Expand All @@ -67,12 +67,12 @@ public static function createNewRandomKey()
}

/**
*
*
* Encrypts a message.
* $plaintext is the message to encrypt.
* $key is the encryption key, a value generated by CreateNewRandomKey().
* You MUST catch exceptions thrown by this function. See docs above.
*
*
* @param string $plaintext
* @param string $key
* @return string
Expand All @@ -82,8 +82,7 @@ public static function encrypt($plaintext, $key)
{
self::runtimeTest();

if (self::ourStrlen($key) !== self::KEY_BYTE_SIZE)
{
if (self::ourStrlen($key) !== self::KEY_BYTE_SIZE) {
throw new Ex\CannotPerformOperationException("Key is the wrong size.");
}

Expand All @@ -94,7 +93,7 @@ public static function encrypt($plaintext, $key)
// Generate a random initialization vector.
self::ensureFunctionExists("openssl_cipher_iv_length");
$ivsize = \openssl_cipher_iv_length(self::CIPHER_METHOD);
if ($ivsize === FALSE || $ivsize <= 0) {
if ($ivsize === false || $ivsize <= 0) {
throw new Ex\CannotPerformOperationException(
"Could not get the IV length from OpenSSL"
);
Expand All @@ -116,7 +115,7 @@ public static function encrypt($plaintext, $key)
* $ciphertext is the ciphertext to decrypt.
* $key is the key that the ciphertext was encrypted with.
* You MUST catch exceptions thrown by this function. See docs above.
*
*
* @param string $ciphertext
* @param string $key
* @return type
Expand All @@ -134,11 +133,11 @@ public static function decrypt($ciphertext, $key)
);
}
$hmac = self::ourSubstr($ciphertext, 0, self::MAC_BYTE_SIZE);
if ($hmac === FALSE) {
if ($hmac === false) {
throw new Ex\CannotPerformOperationException();
}
$ciphertext = self::ourSubstr($ciphertext, self::MAC_BYTE_SIZE);
if ($ciphertext === FALSE) {
if ($ciphertext === false) {
throw new Ex\CannotPerformOperationException();
}

Expand All @@ -153,7 +152,7 @@ public static function decrypt($ciphertext, $key)
// Extract the initialization vector from the ciphertext.
self::EnsureFunctionExists("openssl_cipher_iv_length");
$ivsize = \openssl_cipher_iv_length(self::CIPHER_METHOD);
if ($ivsize === FALSE || $ivsize <= 0) {
if ($ivsize === false || $ivsize <= 0) {
throw new Ex\CannotPerformOperationException(
"Could not get the IV length from OpenSSL"
);
Expand All @@ -164,11 +163,11 @@ public static function decrypt($ciphertext, $key)
);
}
$iv = self::ourSubstr($ciphertext, 0, $ivsize);
if ($iv === FALSE) {
if ($iv === false) {
throw new Ex\CannotPerformOperationException();
}
$ciphertext = self::ourSubstr($ciphertext, $ivsize);
if ($ciphertext === FALSE) {
if ($ciphertext === false) {
throw new Ex\CannotPerformOperationException();
}

Expand All @@ -177,9 +176,9 @@ public static function decrypt($ciphertext, $key)
return $plaintext;
} else {
/*
* We throw an exception instead of returning FALSE because we want
* We throw an exception instead of returning false because we want
* a script that doesn't handle this condition to CRASH, instead
* of thinking the ciphertext decrypted to the value FALSE.
* of thinking the ciphertext decrypted to the value false.
*/
throw new Ex\InvalidCiphertextException(
"Integrity check failed."
Expand Down Expand Up @@ -219,7 +218,7 @@ public static function runtimeTest()
$test_state = 2;

self::ensureFunctionExists('openssl_get_cipher_methods');
if (\in_array(self::CIPHER_METHOD, \openssl_get_cipher_methods()) === FALSE) {
if (\in_array(self::CIPHER_METHOD, \openssl_get_cipher_methods()) === false) {
throw new Ex\CryptoTestFailedException("Cipher method not supported.");
}

Expand Down Expand Up @@ -247,9 +246,9 @@ public static function runtimeTest()

/**
* Never call this method directly!
*
*
* Unauthenticated message encryption.
*
*
* @param string $plaintext
* @param string $key
* @param string $iv
Expand Down Expand Up @@ -279,9 +278,9 @@ private static function plainEncrypt($plaintext, $key, $iv)

/**
* Never call this method directly!
*
*
* Unauthenticated message deryption.
*
*
* @param string $ciphertext
* @param string $key
* @param string $iv
Expand All @@ -299,7 +298,7 @@ private static function plainDecrypt($ciphertext, $key, $iv)
OPENSSL_RAW_DATA,
$iv
);
if ($plaintext === FALSE) {
if ($plaintext === false) {
throw new Ex\CannotPerformOperationException(
"openssl_decrypt() failed."
);
Expand All @@ -310,7 +309,7 @@ private static function plainDecrypt($ciphertext, $key, $iv)

/**
* Returns a random binary string of length $octets bytes.
*
*
* @param int $octets
* @return string (raw binary)
* @throws Ex\CannotPerformOperationException
Expand All @@ -320,7 +319,7 @@ private static function secureRandom($octets)
self::ensureFunctionExists('openssl_random_pseudo_bytes');
$secure = false;
$random = \openssl_random_pseudo_bytes($octets, $secure);
if ($random === FALSE || $secure === FALSE) {
if ($random === false || $secure === false) {
throw new Ex\CannotPerformOperationException(
"openssl_random_pseudo_bytes() failed."
);
Expand All @@ -331,7 +330,7 @@ private static function secureRandom($octets)
/**
* Use HKDF to derive multiple keys from one.
* http://tools.ietf.org/html/rfc5869
*
*
* @param string $hash Hash Function
* @param string $ikm Initial Keying Material
* @param int $length How many bytes?
Expand Down Expand Up @@ -390,15 +389,15 @@ private static function HKDF($hash, $ikm, $length, $info = '', $salt = null)

// ORM = first L octets of T
$orm = self::ourSubstr($t, 0, $length);
if ($orm === FALSE) {
if ($orm === false) {
throw new Ex\CannotPerformOperationException();
}
return $orm;
}

/**
* Verify a HMAC without crypto side-channels
*
*
* @staticvar boolean $native Use native hash_equals()?
* @param string $correct_hmac HMAC string (raw binary)
* @param string $message Ciphertext (raw binary)
Expand All @@ -410,7 +409,7 @@ private static function verifyHMAC($correct_hmac, $message, $key)
{
static $native = null;
$message_hmac = \hash_hmac(self::HASH_FUNCTION, $message, $key, true);

if ($native === null) {
$native = \function_exists('hash_equals');
}
Expand Down Expand Up @@ -453,22 +452,26 @@ private static function testEncryptDecrypt()
// the user into thinking it's just an invalid ciphertext!
throw new Ex\CryptoTestFailedException();
}
if($decrypted !== $data) {
if ($decrypted !== $data) {
throw new Ex\CryptoTestFailedException();
}

// Modifying the ciphertext: Appending a string.
try {
self::decrypt($ciphertext . "a", $key);
throw new Ex\CryptoTestFailedException();
} catch (Ex\InvalidCiphertextException $e) { /* expected */ }
} catch (Ex\InvalidCiphertextException $e) {
/* expected */
}

// Modifying the ciphertext: Changing an IV byte.
try {
$ciphertext[0] = chr((ord($ciphertext[0]) + 1) % 256);
self::decrypt($ciphertext, $key);
throw new Ex\CryptoTestFailedException();
} catch (Ex\InvalidCiphertextException $e) { /* expected */ }
} catch (Ex\InvalidCiphertextException $e) {
/* expected */
}

// Decrypting with the wrong key.
$key = self::createNewRandomKey();
Expand All @@ -478,20 +481,24 @@ private static function testEncryptDecrypt()
try {
self::decrypt($ciphertext, $wrong_key);
throw new Ex\CryptoTestFailedException();
} catch (Ex\InvalidCiphertextException $e) { /* expected */ }
} catch (Ex\InvalidCiphertextException $e) {
/* expected */
}

// Ciphertext too small (shorter than HMAC).
$key = self::createNewRandomKey();
$ciphertext = \str_repeat("A", self::MAC_BYTE_SIZE - 1);
try {
self::decrypt($ciphertext, $key);
throw new Ex\CryptoTestFailedException();
} catch (Ex\InvalidCiphertextException $e) { /* expected */ }
} catch (Ex\InvalidCiphertextException $e) {
/* expected */
}
}

/**
* Run-time testing
*
*
* @throws Ex\CryptoTestFailedException
*/
private static function HKDFTestVector()
Expand Down Expand Up @@ -530,7 +537,7 @@ private static function HKDFTestVector()

/**
* Run-Time tests
*
*
* @throws Ex\CryptoTestFailedException
*/
private static function HMACTestVector()
Expand All @@ -546,7 +553,7 @@ private static function HMACTestVector()

/**
* Run-time tests
*
*
* @throws Ex\CryptoTestFailedException
*/
private static function AESTestVector()
Expand Down Expand Up @@ -592,10 +599,9 @@ private static function hexToBytes($hex_string)
return \pack("H*", $hex_string);
}


/**
* If the constant doesn't exist, throw an exception
*
*
* @param string $name
* @throws Ex\CannotPerformOperationException
*/
Expand All @@ -608,7 +614,7 @@ private static function ensureConstantExists($name)

/**
* If the functon doesn't exist, throw an exception
*
*
* @param string $name Function name
* @throws Ex\CannotPerformOperationException
*/
Expand All @@ -627,7 +633,7 @@ private static function ensureFunctionExists($name)

/**
* Safe string length
*
*
* @staticvar boolean $exists
* @param string $str
* @return int
Expand All @@ -640,7 +646,7 @@ private static function ourStrlen($str)
}
if ($exists) {
$length = \mb_strlen($str, '8bit');
if ($length === FALSE) {
if ($length === false) {
throw new Ex\CannotPerformOperationException(
"mb_strlen() failed."
);
Expand All @@ -650,10 +656,10 @@ private static function ourStrlen($str)
return \strlen($str);
}
}

/**
* Safe substring
*
*
* @staticvar boolean $exists
* @param string $str
* @param int $start
Expand All @@ -666,8 +672,7 @@ private static function ourSubstr($str, $start, $length = null)
if ($exists === null) {
$exists = \function_exists('mb_substr');
}
if ($exists)
{
if ($exists) {
// mb_substr($str, 0, NULL, '8bit') returns an empty string on PHP
// 5.3, so we have to find the length ourselves.
if (!isset($length)) {
Expand All @@ -689,9 +694,9 @@ private static function ourSubstr($str, $start, $length = null)
}
}
/**
* Convert a binary string into a hexadecimal string without cache-timing
* Convert a binary string into a hexadecimal string without cache-timing
* leaks
*
*
* @param string $bin_string (raw binary)
* @return string
*/
Expand All @@ -707,11 +712,11 @@ public static function binToHex($bin_string)
}
return $hex;
}

/**
* Convert a hexadecimal string into a binary string without cache-timing
* Convert a hexadecimal string into a binary string without cache-timing
* leaks
*
*
* @param string $hex_string
* @return string (raw binary)
*/
Expand All @@ -721,7 +726,7 @@ public static function hexToBin($hex_string)
$bin = '';
$hex_len = self::ourStrlen($hex_string);
$state = 0;

while ($hex_pos < $hex_len) {
$c = \ord($hex_string[$hex_pos]);
$c_num = $c ^ 48;
Expand Down
2 changes: 1 addition & 1 deletion src/Exception/CannotPerformOperationException.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@

class CannotPerformOperation extends \Defuse\Crypto\Exception\CryptoException
{

}
2 changes: 1 addition & 1 deletion src/Exception/CryptoTestFailedException.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@

class CryptoTestFailedException extends \Defuse\Crypto\Exception\CryptoException
{

}
2 changes: 1 addition & 1 deletion src/Exception/InvalidCiphertextException.php
Original file line number Diff line number Diff line change
Expand Up @@ -3,5 +3,5 @@

class InvalidCiphertextException extends \Defuse\Crypto\Exception\CryptoException
{

}
Loading