public function testBase64Decode() { self::assertSame('!!?*!~Za_-c@#$2üäas!', Encryption::base64Decode('ISE_KiF-WmFfLWNAIyQyw7zDpGFzIQ')); // self::assertSame('3_-4bbc2_-3', Security::sanitizeBase64('3/+4bbc2/+3==')); }
/** * Verifies that a sigend + encrypted string is valid and returns the * decrypted string. * * This method... * * 1. ...takes the iv from the beginning of the string * 2. ...does a base64_decode of the rest of the string * 3. ...checks that the ssl encryption is correct (decrypts the string with * the correct cipher and password). * 4. ...checks that the salt is present and at the beginning of the the * string. * 5. ...removes the random characters from the end of the string * * * BE CAREFUL!!! * * Never let the message from the EncryptionException be visible to the user. * This could result in a security risk. * The exception message is only for debugging purpose. * * If the data that has been encrypted wasn't a string, it gets serialized by * this method. * * @param string $encryptedData * @return mixed * @throws EncryptionException */ public function decrypt($encryptedData) { $encryptedData = explode('.', $encryptedData); if (count($encryptedData) !== 1 && count($encryptedData) !== 2) { throw new EncryptionException('The encrypted string did not have a correct iv.'); } if (count($encryptedData) === 1) { // No IV has been chosen $iv = ''; $encryptedData = Encryption::base64Decode($encryptedData[0]); } elseif (count($encryptedData) === 2) { // IV present $iv = $encryptedData[0]; if (!$iv) { throw new EncryptionException('IV was empty.'); } $encryptedData = Encryption::base64Decode($encryptedData[1]); } if (!$encryptedData) { throw new EncryptionException('Encrypted string is not base64.'); } $iv = $this->padIv($iv, $this->cipherIvLength); $decrypted = openssl_decrypt($encryptedData, $this->cipher, $this->password, true, $iv); if ($decrypted === false) { throw new EncryptionException('Encrypted string is not correctly openssl encrypted.'); } $saltLength = strlen($this->salt); if (substr($decrypted, 0, $saltLength) !== $this->salt) { throw new EncryptionException('Encrypted string does not contain the salt.'); } $dataInfoLength = 2; $dataInfo = substr($decrypted, $saltLength, $dataInfoLength); if ($dataInfo !== self::SERIALIZE_NONE . '-' && $dataInfo !== self::SERIALIZE_PHP . '-' && $dataInfo !== self::SERIALIZE_JSON . '-') { throw new EncryptionException('Encrypted string does not contain data information.'); } $data = substr($decrypted, $saltLength + $dataInfoLength, strlen($decrypted) - $saltLength - $dataInfoLength - $this->nonceChars); switch ($dataInfo) { case self::SERIALIZE_PHP . '-': $data = @unserialize($data); break; case self::SERIALIZE_JSON . '-': $data = @json_decode($data, true); break; } return $data; }