/** * @param string $encrypted * * @throws CryptoException * * @return string */ public function decrypt($encrypted) { if (!$encrypted || !is_string($encrypted)) { throw new CryptoException(sprintf(self::ERR_CANNOT_DECRYPT, gettype($encrypted))); } // Sanity check size of payload is larger than MAC + NONCE if (ByteString::strlen($encrypted) < self::NONCE_SIZE_BYTES + \Sodium\CRYPTO_AUTH_BYTES) { throw new CryptoException(self::ERR_SIZE); } // Split into nonce, mac, and encrypted payload $nonce = ByteString::substr($encrypted, 0, self::NONCE_SIZE_BYTES); $mac = ByteString::substr($encrypted, self::NONCE_SIZE_BYTES, \Sodium\CRYPTO_AUTH_BYTES); $encrypted = ByteString::substr($encrypted, self::NONCE_SIZE_BYTES + \Sodium\CRYPTO_AUTH_BYTES); // Verify MAC try { $isVerified = \Sodium\crypto_auth_verify($mac, $nonce . $encrypted, $this->authSecret->getValue()); } catch (Exception $ex) { throw new CryptoException(sprintf(self::ERR_DECODE_UNEXPECTED, $ex->getMessage()), $ex->getCode(), $ex); } if (!$isVerified) { throw new CryptoException(self::ERR_DECODE); } // Decrypt authenticated payload try { $unencrypted = \Sodium\crypto_secretbox_open($encrypted, $nonce, $this->cryptoSecret->getValue()); } catch (Exception $ex) { throw new CryptoException(sprintf(self::ERR_DECRYPT, $ex->getMessage()), $ex->getCode(), $ex); } return $unencrypted; }
public function testExtendedOpaqueUsesDifferentKey() { $testString = 'test value'; $original = new OpaqueProperty($testString); $extended = new ExtendedOpaqueProperty($testString); $reflect = new ReflectionClass($original); $prop = $reflect->getProperty('noise'); $prop->setAccessible(true); $originalNoise = $prop->getValue(); $reflect = new ReflectionClass($extended); $prop = $reflect->getProperty('noise'); $prop->setAccessible(true); $extendedNoise = $prop->getValue(); $this->assertNotSame($originalNoise, $extendedNoise); $this->assertSame($original->getValue(), $extended->getValue()); }