示例#1
0
 /**
  * Method to decrypt a data string.
  *
  * @param   string     $data  The encrypted string to decrypt.
  * @param   JCryptKey  $key   The key object to use for decryption.
  *
  * @return  string  The decrypted data string.
  *
  * @since   3.5
  * @throws  RuntimeException
  */
 public function decrypt($data, JCryptKey $key)
 {
     // Validate key.
     if ($key->type != 'crypto') {
         throw new InvalidArgumentException('Invalid key of type: ' . $key->type . '.  Expected crypto.');
     }
     // Decrypt the data.
     try {
         return Crypto::Decrypt($data, $key->public);
     } catch (InvalidCiphertextException $ex) {
         throw new RuntimeException('DANGER! DANGER! The ciphertext has been tampered with!', $ex->getCode(), $ex);
     } catch (CryptoTestFailedException $ex) {
         throw new RuntimeException('Cannot safely perform decryption', $ex->getCode(), $ex);
     } catch (CannotPerformOperationException $ex) {
         throw new RuntimeException('Cannot safely perform decryption', $ex->getCode(), $ex);
     }
 }
示例#2
0
 private static function TestEncryptDecrypt()
 {
     $key = Crypto::CreateNewRandomKey();
     $data = "EnCrYpT EvErYThInG";
     // Make sure encrypting then decrypting doesn't change the message.
     $ciphertext = Crypto::Encrypt($data, $key);
     try {
         $decrypted = Crypto::Decrypt($ciphertext, $key);
     } catch (InvalidCiphertextException $ex) {
         // It's important to catch this and change it into a
         // CryptoTestFailedException, otherwise a test failure could trick
         // the user into thinking it's just an invalid ciphertext!
         throw new CryptoTestFailedException();
     }
     if ($decrypted !== $data) {
         throw new CryptoTestFailedException();
     }
     // Modifying the ciphertext: Appending a string.
     try {
         Crypto::Decrypt($ciphertext . "a", $key);
         throw new CryptoTestFailedException();
     } catch (InvalidCiphertextException $e) {
         /* expected */
     }
     // Modifying the ciphertext: Changing an IV byte.
     try {
         $ciphertext[0] = chr((ord($ciphertext[0]) + 1) % 256);
         Crypto::Decrypt($ciphertext, $key);
         throw new CryptoTestFailedException();
     } catch (InvalidCiphertextException $e) {
         /* expected */
     }
     // Decrypting with the wrong key.
     $key = Crypto::CreateNewRandomKey();
     $data = "abcdef";
     $ciphertext = Crypto::Encrypt($data, $key);
     $wrong_key = Crypto::CreateNewRandomKey();
     try {
         Crypto::Decrypt($ciphertext, $wrong_key);
         throw new CryptoTestFailedException();
     } catch (InvalidCiphertextException $e) {
         /* expected */
     }
     // Ciphertext too small (shorter than HMAC).
     $key = Crypto::CreateNewRandomKey();
     $ciphertext = str_repeat("A", self::MAC_BYTE_SIZE - 1);
     try {
         Crypto::Decrypt($ciphertext, $key);
         throw new CryptoTestFailedException();
     } catch (InvalidCiphertextException $e) {
         /* expected */
     }
 }
示例#3
0
 public function getContent(Document $document, User $requester, $passPhrase)
 {
     $share = $document->getShareOf($requester);
     $encryptionKey = $this->getEncryptionKey($share, $passPhrase);
     return \Crypto::Decrypt(base64_decode($document->getEncryptedContent()), $encryptionKey);
 }
示例#4
0
 /**
  * Decrypt a string using AES.
  * 
  * @param string $plaintext
  * @param string $key (optional)
  * @param bool $force_compat (optional)
  * @return string|false
  */
 public static function decrypt($ciphertext, $key = null, $force_compat = false)
 {
     // Get the encryption key.
     $key = $key ?: config('crypto.encryption_key');
     $key = substr(hash('sha256', $key, true), 0, 16);
     // Check whether the ciphertext is valid.
     $ciphertext = @base64_decode($ciphertext);
     if (strlen($ciphertext) < 48) {
         return false;
     }
     // Use defuse/php-encryption if possible.
     if (!$force_compat && function_exists('openssl_decrypt')) {
         try {
             return \Crypto::Decrypt($ciphertext, $key);
         } catch (\Exception $e) {
             return false;
         }
     }
     // Otherwise, use the CryptoCompat class.
     return \CryptoCompat::decrypt($ciphertext, $key);
 }
		/**
		* Decrypt $this->WeakestLic
		* @access public
		* @return array Decrypted lic
		*/
		private final function DecryptLic()
		{
			// Extract sault from license
			if ($this->AlgoVersion < 2)
			{
				$chunks = explode("rmYG", current($this->WeakestLic));
				$sault = $chunks[0];
				$lic = $chunks[1];
			}
			else
			{
				$sault = substr(current($this->WeakestLic), 0, 24);
				$lic = substr(current($this->WeakestLic), 24);
			}
			
			// Prepare and generate key - the base of trust
			$Crypto = new Crypto($this->LicKey);
			if ($this->AlgoVersion == 2)
				$shash = $Crypto->Hash("{$sault}{$this->LicKey}", "SHA256");
			else
				$shash = $Crypto->Hash("{$sault} invalid {$this->LicKey}", "SHA256");
			$key = substr($shash, 0, 12).substr($shash, -12);
			// end
			
			// Decrypt
			$retval = $Crypto->Decrypt($lic, $key);
			$retval = explode("|", $retval);
			
			$retval = array_map('trim', $retval);
			
			$Crypto = null;
			return($retval);
		}		
示例#6
0
 /**
  * {@inheritdoc}
  *
  * json_decode with assoc flag set to true
  */
 public function decrypt($payload)
 {
     try {
         $result = \Crypto::Decrypt(base64_decode($payload), $this->key);
         return json_decode($result, true);
     } catch (\InvalidCiphertextException $e) {
         throw new DecryptException($e->getMessage(), $e->getCode(), $e);
     } catch (\CannotPerformOperationException $e) {
         throw new DecryptException($e->getMessage(), $e->getCode(), $e);
     } catch (\CryptoTestFailedException $e) {
         throw new EncrypterException($e->getMessage(), $e->getCode(), $e);
     }
 }
示例#7
0
    $key = Crypto::CreateNewRandomKey();
    // WARNING: Do NOT encode $key with bin2hex() or base64_encode(),
    // they may leak the key to the attacker through side channels.
} catch (CryptoTestFailedException $ex) {
    die('Cannot safely create a key');
} catch (CannotPerformOperationException $ex) {
    die('Cannot safely create a key');
}
$message = "ATTACK AT DAWN";
try {
    $ciphertext = Crypto::Encrypt($message, $key);
} catch (CryptoTestFailedException $ex) {
    die('Cannot safely perform encryption');
} catch (CannotPerformOperationException $ex) {
    die('Cannot safely perform decryption');
}
try {
    $decrypted = Crypto::Decrypt($ciphertext, $key);
} catch (InvalidCiphertextException $ex) {
    // VERY IMPORTANT
    // Either:
    //   1. The ciphertext was modified by the attacker,
    //   2. The key is wrong, or
    //   3. $ciphertext is not a valid ciphertext or was corrupted.
    // Assume the worst.
    die('DANGER! DANGER! The ciphertext has been tampered with!');
} catch (CryptoTestFailedException $ex) {
    die('Cannot safely perform encryption');
} catch (CannotPerformOperationException $ex) {
    die('Cannot safely perform decryption');
}
示例#8
0
 /**
  * Decrypts a message
  * @param string $message 		The message to decryept
  * @return string $decrypted	The decrypted message
  */
 public static function decrypt($message, $key = NULL)
 {
     if ($key != NULL) {
         Yii::log('warning', 'Use of the `$key` parameter is deprecated', 'cii');
     }
     if (empty($message)) {
         return null;
     }
     $key = self::getEncryptionKey();
     try {
         $decrypted = Crypto::Decrypt(hex2bin($message), $key);
     } catch (InvalidCiphertextException $ex) {
         Yii::log('Ciphertext or key is invalid', 'error', 'cii');
         return null;
     } catch (CryptoTestFailedException $ex) {
         Yii::log('Ciphertext or key is invalid', 'error', 'cii');
         return null;
     } catch (CannotPerformOperationException $ex) {
         Yii::log('Ciphertext or key is invalid', 'error', 'cii');
         return null;
     }
     return $decrypted;
 }
示例#9
0
        response(VALIDATION_MESSAGE_NOTFOUND, $errors, $logger);
    } else {
        $item = $repo->findById($id);
        $salt = base64_decode($item->salt);
        $data_encrypted = base64_decode($item->secret);
    }
}
// If all of the above validation checks pass, continue on
if (!$errors) {
    // Create decryption key
    $length = 16;
    $iterations = 10000;
    $key = hash_pbkdf2("sha256", $password, $salt . PASSWORD_PEPPER, $iterations, $length);
    // Decrypt data, reference: https://github.com/defuse/php-encryption/
    try {
        $data_decrypted = Crypto::Decrypt($data_encrypted, $key);
    } catch (InvalidCiphertextException $ex) {
        // VERY IMPORTANT
        response(DECRYPTION_PASSWORD_WRONG, true, $logger);
    } catch (CryptoTestFailedException $ex) {
        response(ENCRYPTION_UNSAFE, true, $logger);
    } catch (CannotPerformOperationException $ex) {
        response(DECRYPTION_UNSAFE, true, $logger);
    }
    // Delete message
    if ($use_orchestrate) {
        // Check if Orchestrate is enabled
        $item = $client->purge(ORCHESTRATE_COLLECTION, $id);
        $logger->info(LOG_ORCHESTRATE_PURGE);
    } else {
        // Fallback to Flywheel
示例#10
0
 public function get_session($session_id)
 {
     //加密后的 session_id
     $decode = base64_decode($session_id);
     //检验 session_id 是否被篡改
     $keySize = Crypto::KEY_BYTE_SIZE;
     $key = mb_substr($decode, 0, $keySize, '8bit');
     $decode = mb_substr($decode, $keySize, null, '8bit');
     try {
         $decrypted = Crypto::Decrypt($decode, $key);
     } catch (InvalidCiphertextException $ex) {
         // VERY IMPORTANT
         // Either:
         //   1. The ciphertext was modified by the attacker,
         //   2. The key is wrong, or
         //   3. $ciphertext is not a valid ciphertext or was corrupted.
         // Assume the worst.
         //被人恶意修改Cookie
         return FALSE;
     } catch (CryptoTestFailedException $ex) {
         die('Cannot safely perform encryption');
     } catch (CannotPerformOperationException $ex) {
         die('Cannot safely perform decryption');
     }
     if (empty($decrypted)) {
         return FALSE;
     }
     //session id
     $session_id = $decrypted;
     session_id($session_id);
     session_start();
     return $_SESSION[$this->login_in_session_name];
 }
示例#11
0
require __DIR__ . '/private/app.php';
$key = Crypto::CreateNewRandomKey();
$message = 'ATTACK AT DAWN';
$result = null;
if (isset($_POST['key'])) {
    $key = base64url_decode(strval($_POST['key']));
}
if (isset($_POST['message'])) {
    $message = strval($_POST['message']);
}
try {
    if (isset($_POST['encode'])) {
        $result = Crypto::Encrypt($message, $key);
    } else {
        if (isset($_POST['decode'])) {
            $message = Crypto::Decrypt(base64url_decode(strtr($message, array("\r" => '', "\n" => ''))), $key);
        }
    }
} catch (\Exception $exception) {
}
// WARNING: Do NOT encode $key with bin2hex() or base64_encode(),
// they may leak the key to the attacker through side channels.
?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<title>Using encryption in PHP | php_encryption</title>
	<link href="static/bower_components/bootstrap/dist/css/bootstrap.css" type="text/css" rel="stylesheet">