/** * @return string */ public function __debugInfo() { return ['value' => self::SAFE_OUTPUT, 'bytes' => ByteString::strlen($this->value)]; }
/** * @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; }
/** * Validates the given string is a correct byte stream for a GUID. * * This does some seemingly crazy things, but basically it validates that the given value will be within the set * of possible GUID's that GUID::create() can produce. * * @param string $guid * * @return bool */ private static function validate($guid) { if (ByteString::strlen($guid) !== 16) { return false; } $byte = $guid[6]; $byte = (ord($byte) & 0xf0) >> 4; if ($byte !== 4) { return false; } $byte = $guid[8]; $byte = ord($byte) & 0xc0; if ($byte !== 0x80) { return false; } return true; }