Encryption\Crypt
ClassSource on GitHubProvides encryption capabilities to Phalcon applications.
use Phalcon\Crypt;
$crypt = new Crypt();
$crypt->setCipher("aes-256-ctr");
$key =
"T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3";
$input = "The message to be encrypted";
$encrypted = $crypt->encrypt($input, $key);
echo $crypt->decrypt($encrypted, $key);Phalcon\Encryption\Crypt- implementsPhalcon\Encryption\Crypt\CryptInterface
Uses Phalcon\Encryption\Crypt\CryptInterface · Phalcon\Encryption\Crypt\Exception\DecryptionFailed · Phalcon\Encryption\Crypt\Exception\EmptyDecryptionKey · Phalcon\Encryption\Crypt\Exception\EmptyEncryptionKey · Phalcon\Encryption\Crypt\Exception\EncryptionFailed · Phalcon\Encryption\Crypt\Exception\Exception · Phalcon\Encryption\Crypt\Exception\InvalidAuthTagLength · Phalcon\Encryption\Crypt\Exception\InvalidDecryptLength · Phalcon\Encryption\Crypt\Exception\InvalidPaddingSize · Phalcon\Encryption\Crypt\Exception\IvLengthCalculationFailed · Phalcon\Encryption\Crypt\Exception\Mismatch · Phalcon\Encryption\Crypt\Exception\MissingAuthData · Phalcon\Encryption\Crypt\Exception\MissingOpensslExtension · Phalcon\Encryption\Crypt\Exception\RandomBytesGenerationFailed · Phalcon\Encryption\Crypt\Exception\UnsupportedAlgorithm · Phalcon\Encryption\Crypt\PadFactory · Phalcon\Traits\Php\Base64Trait · Phalcon\Traits\Php\HashTrait · Phalcon\Traits\Php\InfoTrait · Phalcon\Traits\Php\OpensslTrait
Method Summary
public__construct(string$cipher = self::DEFAULT_CIPHER,bool$useSigning = true,PadFactory$padFactory = null)Crypt constructor.publicstringdecrypt(string$input,string$key = null)Decrypts an encrypted text.publicstringdecryptBase64(string$input,string$key = null,bool$safe = false)Decrypt a text that is coded as a base64 string.publicstringencrypt(string$input,string$key = null)Encrypts a text.publicstringencryptBase64(string$input,string$key = null,bool$safe = false)Encrypts a text returning the result as a base64 string.publicstringgetAuthData()Returns the auth datapublicstringgetAuthTag()Returns the auth tagpublicintgetAuthTagLength()Returns the auth tag lengthpublicarraygetAvailableCiphers()Returns a list of available ciphers.publicarraygetAvailableHashAlgorithms()Return a list of registered hashing algorithms suitable for hash_hmac.publicstringgetCipher()Returns the current cipherpublicstringgetHashAlgorithm()Get the name of hashing algorithm.publicstringgetKey()Returns the encryption keypublicboolisValidDecryptLength( string$input )Returns if the input length for decryption is valid or notpublicCryptInterfacesetAuthData( string$data )publicCryptInterfacesetAuthTag( string$tag )publicCryptInterfacesetAuthTagLength( int$length )publicCryptInterfacesetCipher( string$cipher )Sets the cipher algorithm for data encryption and decryption.publicstaticsetHashAlgorithm( string$hashAlgorithm )Set the name of hashing algorithm.publicCryptInterfacesetKey( string$key )Sets the encryption key.publicCryptInterfacesetPadding( int$scheme )Changes the padding scheme used.publicCryptInterfaceuseSigning( bool$useSigning )Sets if the calculating message digest must used.protectedvoidcheckCipherHashIsAvailable(string$cipher,string$type)Checks if a cipher or a hash algorithm is availableprotectedstringcryptPadText(string$input,string$mode,int$blockSize,int$paddingType)Pads texts before encryption. SeeprotectedstringcryptUnpadText(string$input,string$mode,int$blockSize,int$paddingType)Removes a padding from a text.protectedstringdecryptGcmCcmAuth(string$mode,string$cipherText,string$decryptKey,string$iv)protectedstringdecryptGetUnpadded(string$mode,int$blockSize,string$decrypted)protectedstringencryptGcmCcm(string$mode,string$padded,string$encryptKey,string$iv)protectedstringencryptGetPadded(string$mode,string$input,int$blockSize)protectedstaticinitializeAvailableCiphers()Initialize available cipher algorithms.Constants
stringDEFAULT_ALGORITHM = "sha256"stringDEFAULT_CIPHER = "aes-256-cfb"intPADDING_ANSI_X_923 = 1PaddingintPADDING_DEFAULT = 0intPADDING_ISO_10126 = 3intPADDING_ISO_IEC_7816_4 = 4intPADDING_PKCS7 = 2intPADDING_SPACE = 6intPADDING_ZERO = 5Properties
protectedstring$authData = ""protectedstring$authTag = ""protectedint$authTagLength = 16protectedarray$availableCiphers = []Available cipher methods.protectedstring$cipher = self::DEFAULT_CIPHERprotectedstring$hashAlgorithm = self::DEFAULT_ALGORITHMThe name of hashing algorithm.protectedarray$hashLengthCache = []Memoized strlen(hash($algo, "", true)) results, keyed by algorithm name. The hash output length is deterministic for a given algorithm, so this collapses the per-decrypt strlen+hash call to a single hash lookup after warm-up.protectedint$ivLength = 16The cipher iv length.protectedstring$key = ""protectedPadFactory$padFactoryprotectedint$padding = 0protectedbool$useSigning = trueWhether calculating message digest enabled or not.Methods
__construct()
public function __construct(
string $cipher = self::DEFAULT_CIPHER,
bool $useSigning = true,
PadFactory $padFactory = null
);Crypt constructor.
decrypt()
public function decrypt(
string $input,
string $key = null
): string;Decrypts an encrypted text.
$encrypted = $crypt->decrypt(
$encrypted,
"T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"
);decryptBase64()
public function decryptBase64(
string $input,
string $key = null,
bool $safe = false
): string;Decrypt a text that is coded as a base64 string.
encrypt()
public function encrypt(
string $input,
string $key = null
): string;Encrypts a text.
$encrypted = $crypt->encrypt(
"Top secret",
"T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"
);encryptBase64()
public function encryptBase64(
string $input,
string $key = null,
bool $safe = false
): string;Encrypts a text returning the result as a base64 string.
getAuthData()
public function getAuthData(): string;Returns the auth data
getAuthTag()
public function getAuthTag(): string;Returns the auth tag
getAuthTagLength()
public function getAuthTagLength(): int;Returns the auth tag length
getAvailableCiphers()
public function getAvailableCiphers(): array;Returns a list of available ciphers.
getAvailableHashAlgorithms()
public function getAvailableHashAlgorithms(): array;Return a list of registered hashing algorithms suitable for hash_hmac.
getCipher()
public function getCipher(): string;Returns the current cipher
getHashAlgorithm()
public function getHashAlgorithm(): string;Get the name of hashing algorithm.
getKey()
public function getKey(): string;Returns the encryption key
isValidDecryptLength()
public function isValidDecryptLength( string $input ): bool;Returns if the input length for decryption is valid or not (number of bytes required by the cipher).
setAuthData()
public function setAuthData( string $data ): CryptInterface;setAuthTag()
public function setAuthTag( string $tag ): CryptInterface;setAuthTagLength()
public function setAuthTagLength( int $length ): CryptInterface;setCipher()
public function setCipher( string $cipher ): CryptInterface;Sets the cipher algorithm for data encryption and decryption.
setHashAlgorithm()
public function setHashAlgorithm( string $hashAlgorithm ): static;Set the name of hashing algorithm.
setKey()
public function setKey( string $key ): CryptInterface;Sets the encryption key.
The $key should have been previously generated in a cryptographically
safe way.
Bad key: “le password”
Better (but still unsafe) -> “#1dj8$=dp?.ak//j1V$~%*0X”
Good key: “T4\xb1\x8d\xa9\x98\x05\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3”
setPadding()
public function setPadding( int $scheme ): CryptInterface;Changes the padding scheme used.
useSigning()
public function useSigning( bool $useSigning ): CryptInterface;Sets if the calculating message digest must used.
checkCipherHashIsAvailable()
protected function checkCipherHashIsAvailable(
string $cipher,
string $type
): void;Checks if a cipher or a hash algorithm is available
cryptPadText()
protected function cryptPadText(
string $input,
string $mode,
int $blockSize,
int $paddingType
): string;Pads texts before encryption. See cryptopad
cryptUnpadText()
protected function cryptUnpadText(
string $input,
string $mode,
int $blockSize,
int $paddingType
): string;Removes a padding from a text.
If the function detects that the text was not padded, it will return it unmodified.
decryptGcmCcmAuth()
protected function decryptGcmCcmAuth(
string $mode,
string $cipherText,
string $decryptKey,
string $iv
): string;decryptGetUnpadded()
protected function decryptGetUnpadded(
string $mode,
int $blockSize,
string $decrypted
): string;encryptGcmCcm()
protected function encryptGcmCcm(
string $mode,
string $padded,
string $encryptKey,
string $iv
): string;encryptGetPadded()
protected function encryptGetPadded(
string $mode,
string $input,
int $blockSize
): string;initializeAvailableCiphers()
protected function initializeAvailableCiphers(): static;Initialize available cipher algorithms.
Encryption\Crypt\CryptInterface
InterfaceSource on GitHubInterface for Phalcon\Crypt
Phalcon\Contracts\Encryption\Crypt\CryptPhalcon\Encryption\Crypt\CryptInterface
Uses Phalcon\Contracts\Encryption\Crypt\Crypt
Encryption\Crypt\Exception\DecryptionFailed
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\DecryptionFailed
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\EmptyDecryptionKey
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\EmptyDecryptionKey
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\EmptyEncryptionKey
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\EmptyEncryptionKey
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\EncryptionFailed
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\EncryptionFailed
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\Exception
ClassSource on GitHubExceptions thrown in Phalcon\Crypt use this class
\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\DecryptionFailedPhalcon\Encryption\Crypt\Exception\EmptyDecryptionKeyPhalcon\Encryption\Crypt\Exception\EmptyEncryptionKeyPhalcon\Encryption\Crypt\Exception\EncryptionFailedPhalcon\Encryption\Crypt\Exception\InvalidAuthTagLengthPhalcon\Encryption\Crypt\Exception\InvalidDecryptLengthPhalcon\Encryption\Crypt\Exception\InvalidPaddingSizePhalcon\Encryption\Crypt\Exception\IvLengthCalculationFailedPhalcon\Encryption\Crypt\Exception\MismatchPhalcon\Encryption\Crypt\Exception\MissingAuthDataPhalcon\Encryption\Crypt\Exception\MissingOpensslExtensionPhalcon\Encryption\Crypt\Exception\RandomBytesGenerationFailedPhalcon\Encryption\Crypt\Exception\UnsupportedAlgorithm
Encryption\Crypt\Exception\InvalidAuthTagLength
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\InvalidAuthTagLength
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\InvalidDecryptLength
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\InvalidDecryptLength
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\InvalidPaddingSize
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\InvalidPaddingSize
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\IvLengthCalculationFailed
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\IvLengthCalculationFailed
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\Mismatch
ClassSource on GitHubExceptions thrown in Phalcon\Crypt will use this class.
\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\Mismatch
Encryption\Crypt\Exception\MissingAuthData
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\MissingAuthData
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\MissingOpensslExtension
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\MissingOpensslExtension
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\RandomBytesGenerationFailed
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\RandomBytesGenerationFailed
Method Summary
Methods
__construct()
public function __construct();Encryption\Crypt\Exception\UnsupportedAlgorithm
ClassSource on GitHub\ExceptionPhalcon\Encryption\Crypt\Exception\ExceptionPhalcon\Encryption\Crypt\Exception\UnsupportedAlgorithm
Method Summary
Methods
__construct()
public function __construct(
string $type,
string $cipher
);Encryption\Crypt\PadFactory
ClassSource on GitHubFactory for creating pad classes
Phalcon\Factory\AbstractConfigFactoryPhalcon\Factory\AbstractFactoryPhalcon\Encryption\Crypt\PadFactory
Uses Phalcon\Encryption\Crypt · Phalcon\Encryption\Crypt\Padding\PadInterface · Phalcon\Factory\AbstractFactory
Method Summary
public__construct( array$services = [] )AdapterFactory constructor.publicPadInterfacenewInstance( string$name )Create a new instance of the adapterpublicstringpadNumberToService( int$number )Gets a Crypt pad constant and returns the unique service name for theprotectedarraygetServices()Properties
protectedstring$exception = "Phalcon\Encryption\Crypt\Exception\Exception"Methods
__construct()
public function __construct( array $services = [] );AdapterFactory constructor.
newInstance()
public function newInstance( string $name ): PadInterface;Create a new instance of the adapter
padNumberToService()
public function padNumberToService( int $number ): string;Gets a Crypt pad constant and returns the unique service name for the padding class
getServices()
protected function getServices(): array;Encryption\Crypt\Padding\Ansi
ClassSource on GitHubClass Ansi
@package Phalcon\Encryption\Crypt\Padding
Phalcon\Encryption\Crypt\Padding\Ansi- implementsPhalcon\Encryption\Crypt\Padding\PadInterface
Method Summary
Methods
pad()
public function pad( int $paddingSize ): string;unpad()
public function unpad(
string $input,
int $blockSize
): int;Encryption\Crypt\Padding\Iso10126
ClassSource on GitHubClass Iso10126
@package Phalcon\Encryption\Crypt\Padding
Phalcon\Encryption\Crypt\Padding\Iso10126- implementsPhalcon\Encryption\Crypt\Padding\PadInterface
Method Summary
Methods
pad()
public function pad( int $paddingSize ): string;unpad()
public function unpad(
string $input,
int $blockSize
): int;Encryption\Crypt\Padding\IsoIek
ClassSource on GitHubClass IsoIek
@package Phalcon\Encryption\Crypt\Padding
Phalcon\Encryption\Crypt\Padding\IsoIek- implementsPhalcon\Encryption\Crypt\Padding\PadInterface
Method Summary
Methods
pad()
public function pad( int $paddingSize ): string;unpad()
public function unpad(
string $input,
int $blockSize
): int;Encryption\Crypt\Padding\Noop
ClassSource on GitHubClass Noop
@package Phalcon\Encryption\Crypt\Padding
Phalcon\Encryption\Crypt\Padding\Noop- implementsPhalcon\Encryption\Crypt\Padding\PadInterface
Method Summary
Methods
pad()
public function pad( int $paddingSize ): string;unpad()
public function unpad(
string $input,
int $blockSize
): int;Encryption\Crypt\Padding\PadInterface
InterfaceSource on GitHubInterface for Phalcon\Encryption\Crypt\Padding
Phalcon\Contracts\Encryption\Crypt\Padding\PadPhalcon\Encryption\Crypt\Padding\PadInterface
Uses Phalcon\Contracts\Encryption\Crypt\Padding\Pad
Encryption\Crypt\Padding\Pkcs7
ClassSource on GitHubClass Pkcs7
@package Phalcon\Encryption\Crypt\Padding
Phalcon\Encryption\Crypt\Padding\Pkcs7- implementsPhalcon\Encryption\Crypt\Padding\PadInterface
Method Summary
Methods
pad()
public function pad( int $paddingSize ): string;unpad()
public function unpad(
string $input,
int $blockSize
): int;Encryption\Crypt\Padding\Space
ClassSource on GitHubClass Space
@package Phalcon\Encryption\Crypt\Padding
Phalcon\Encryption\Crypt\Padding\Space- implementsPhalcon\Encryption\Crypt\Padding\PadInterface
Method Summary
Methods
pad()
public function pad( int $paddingSize ): string;unpad()
public function unpad(
string $input,
int $blockSize
): int;Encryption\Crypt\Padding\Zero
ClassSource on GitHubClass Zero
@package Phalcon\Encryption\Crypt\Padding
Phalcon\Encryption\Crypt\Padding\Zero- implementsPhalcon\Encryption\Crypt\Padding\PadInterface
Method Summary
Methods
pad()
public function pad( int $paddingSize ): string;unpad()
public function unpad(
string $input,
int $blockSize
): int;Encryption\Security
ClassSource on GitHubThis component provides a set of functions to improve the security in Phalcon applications
$login = $this->request->getPost("login");
$password = $this->request->getPost("password");
$user = Users::findFirstByLogin($login);
if ($user) {
if ($this->security->checkHash($password, $user->password)) {
// The password is valid
}
}stdClassPhalcon\Di\AbstractInjectionAwarePhalcon\Encryption\Security- implementsPhalcon\Contracts\Encryption\Security\Security
Uses Phalcon\Contracts\Encryption\Security\Security · Phalcon\Di\AbstractInjectionAware · Phalcon\Di\DiInterface · Phalcon\Encryption\Security\Exception · Phalcon\Encryption\Security\Exceptions\UnknownHashAlgorithm · Phalcon\Encryption\Security\Random · Phalcon\Http\RequestInterface · Phalcon\Session\ManagerInterface · Phalcon\Traits\Php\HashTrait
Method Summary
public__construct(SessionInterface$session = null,RequestInterface$request = null)Security constructor.publicboolcheckHash(string$password,string$passwordHash,int$maxPassLength = 0)Checks a plain text password and its hash version to check if thepublicboolcheckToken(string$tokenKey = null,mixed$tokenValue = null,bool$destroyIfValid = true)Check if the CSRF token sent in the request is the same that the currentpublicstringcomputeHmac(string$data,string$key,string$algorithm,bool$raw = false)Computes a HMACpublicstaticdestroyToken()Removes the value of the CSRF token and key from sessionpublicintgetDefaultHash()Returns the default hashpublicarraygetHashInformation( string$hash )Returns information regarding a hashpublicRandomgetRandom()Returns a secure random number generator instancepublicintgetRandomBytes()Returns a number of bytes to be generated by the openssl pseudo randompublicstring|nullgetRequestToken()Returns the value of the CSRF token for the current request.publicstringgetSaltBytes( int$numberBytes = 0 )Generate a >22-length pseudo random string to be used as salt forpublicstring|nullgetSessionToken()Returns the value of the CSRF token in sessionpublicstring|nullgetToken()Generates a pseudo random token value to be used as input's value in apublicstring|nullgetTokenKey()Generates a pseudo random token key to be used as input's name in a CSRFpublicintgetWorkFactor()publicstringhash(string$password,array$options = [])Creates a password hash using bcrypt with a pseudo random saltpublicboolisLegacyHash( string$passwordHash )Checks if a password hash is a valid bcrypt's hashpublicstaticrefreshToken()Forces the regeneration of the CSRF token and key, writing the newpublicstaticsetAutoRefresh( bool$autoRefresh )Toggles automatic regeneration of the CSRF token on every call topublicstaticsetDefaultHash( int$defaultHash )Sets the default hashpublicstaticsetRandomBytes( int$randomBytes )Sets a number of bytes to be generated by the openssl pseudo randompublicstaticsetWorkFactor( int$workFactor )Sets the work factorprotectedgetLocalService(string$name,string$property)Constants
intCRYPT_ARGON2I = 10intCRYPT_ARGON2ID = 11intCRYPT_BCRYPT = 0intCRYPT_BLOWFISH = 4intCRYPT_BLOWFISH_A = 5intCRYPT_BLOWFISH_X = 6intCRYPT_BLOWFISH_Y = 7intCRYPT_DEFAULT = 0intCRYPT_EXT_DES = 2intCRYPT_MD5 = 3intCRYPT_SHA256 = 8intCRYPT_SHA512 = 9intCRYPT_STD_DES = 1Properties
protectedbool$autoRefresh = trueprotectedint$defaultHash = self::CRYPT_DEFAULTprotectedint$numberBytes = 16protectedRandom$randomprotectedstring|null$requestToken = nullprotectedstring|null$token = nullprotectedstring|null$tokenKey = nullprotectedstring$tokenKeySessionId = "$PHALCON/CSRF/KEY$"protectedstring$tokenValueSessionId = "$PHALCON/CSRF$"protectedint$workFactor = 10Methods
__construct()
public function __construct(
SessionInterface $session = null,
RequestInterface $request = null
);Security constructor.
checkHash()
public function checkHash(
string $password,
string $passwordHash,
int $maxPassLength = 0
): bool;Checks a plain text password and its hash version to check if the password matches
checkToken()
public function checkToken(
string $tokenKey = null,
mixed $tokenValue = null,
bool $destroyIfValid = true
): bool;Check if the CSRF token sent in the request is the same that the current in session
computeHmac()
public function computeHmac(
string $data,
string $key,
string $algorithm,
bool $raw = false
): string;Computes a HMAC
destroyToken()
public function destroyToken(): static;Removes the value of the CSRF token and key from session
getDefaultHash()
public function getDefaultHash(): int;Returns the default hash
getHashInformation()
public function getHashInformation( string $hash ): array;Returns information regarding a hash
getRandom()
public function getRandom(): Random;Returns a secure random number generator instance
getRandomBytes()
public function getRandomBytes(): int;Returns a number of bytes to be generated by the openssl pseudo random generator
getRequestToken()
public function getRequestToken(): string|null;Returns the value of the CSRF token for the current request.
getSaltBytes()
public function getSaltBytes( int $numberBytes = 0 ): string;Generate a >22-length pseudo random string to be used as salt for passwords
getSessionToken()
public function getSessionToken(): string|null;Returns the value of the CSRF token in session
getToken()
public function getToken(): string|null;Generates a pseudo random token value to be used as input’s value in a CSRF check
getTokenKey()
public function getTokenKey(): string|null;Generates a pseudo random token key to be used as input’s name in a CSRF check
getWorkFactor()
public function getWorkFactor(): int;hash()
public function hash(
string $password,
array $options = []
): string;Creates a password hash using bcrypt with a pseudo random salt
Any defaultHash value that is not explicitly handled (including the
deprecated, unimplemented constants) resolves to bcrypt.
isLegacyHash()
public function isLegacyHash( string $passwordHash ): bool;Checks if a password hash is a valid bcrypt’s hash
refreshToken()
public function refreshToken(): static;Forces the regeneration of the CSRF token and key, writing the new values to the session even when auto-refresh has been disabled. Useful after a successful login or any other state change where rotating the token is appropriate.
setAutoRefresh()
public function setAutoRefresh( bool $autoRefresh ): static;Toggles automatic regeneration of the CSRF token on every call to
getToken() / getTokenKey(). When set to false, existing session
values are reused (no session write), and a new token is only minted
when none is present or refreshToken() is called explicitly.
setDefaultHash()
public function setDefaultHash( int $defaultHash ): static;Sets the default hash
setRandomBytes()
public function setRandomBytes( int $randomBytes ): static;Sets a number of bytes to be generated by the openssl pseudo random generator
setWorkFactor()
public function setWorkFactor( int $workFactor ): static;Sets the work factor
getLocalService()
protected function getLocalService(
string $name,
string $property
);Encryption\Security\Exception
ClassSource on GitHubPhalcon\Encryption\Security\Exception
Exceptions thrown in Phalcon\Security will use this class
\ExceptionPhalcon\Encryption\Security\Exception
Encryption\Security\Exceptions\InvalidRandomInput
ClassSource on GitHub\ExceptionPhalcon\Encryption\Security\ExceptionPhalcon\Encryption\Security\Exceptions\InvalidRandomInput
Uses Phalcon\Encryption\Security\Exception
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\Exceptions\UnknownHashAlgorithm
ClassSource on GitHub\ExceptionPhalcon\Encryption\Security\ExceptionPhalcon\Encryption\Security\Exceptions\UnknownHashAlgorithm
Uses Phalcon\Encryption\Security\Exception
Method Summary
Methods
__construct()
public function __construct( string $algo );Encryption\Security\JWT\Builder
ClassSource on GitHubJWT Builder
@link https://tools.ietf.org/html/rfc7519
Phalcon\Encryption\Security\JWT\Builder
Uses Phalcon\Encryption\Security\JWT\Exceptions\EmptyPassphrase · Phalcon\Encryption\Security\JWT\Exceptions\InvalidAudience · Phalcon\Encryption\Security\JWT\Exceptions\InvalidExpirationTime · Phalcon\Encryption\Security\JWT\Exceptions\InvalidNotBefore · Phalcon\Encryption\Security\JWT\Exceptions\ValidatorException · Phalcon\Encryption\Security\JWT\Exceptions\WeakPassphrase · Phalcon\Encryption\Security\JWT\Signer\SignerInterface · Phalcon\Encryption\Security\JWT\Token\Enum · Phalcon\Encryption\Security\JWT\Token\Item · Phalcon\Encryption\Security\JWT\Token\Signature · Phalcon\Encryption\Security\JWT\Token\Token · Phalcon\Support\Collection · Phalcon\Support\Collection\CollectionInterface · Phalcon\Support\Helper\Json\Encode · Phalcon\Traits\Php\Base64Trait
Method Summary
public__construct( SignerInterface$signer )Builder constructor.publicstaticaddClaim(string$name,mixed$value)Adds a custom claimpublicstaticaddHeader(string$name,mixed$value)Adds a custom claimpublicgetAudience()publicarraygetClaims()publicstring|nullgetContentType()publicint|nullgetExpirationTime()publicarraygetHeaders()publicstring|nullgetId()publicint|nullgetIssuedAt()publicstring|nullgetIssuer()publicint|nullgetNotBefore()publicstringgetPassphrase()publicstring|nullgetSubject()publicTokengetToken()publicstaticinit()publicstaticsetAudience( mixed$audience )The "aud" (audience) claim identifies the recipients that the JWT ispublicstaticsetContentType( string$contentType )Sets the content type header 'cty'publicstaticsetExpirationTime( int$timestamp )The "exp" (expiration time) claim identifies the expiration time onpublicstaticsetId( string$jwtId )The "jti" (JWT ID) claim provides a unique identifier for the JWT.publicstaticsetIssuedAt( int$timestamp )The "iat" (issued at) claim identifies the time at which the JWT waspublicstaticsetIssuer( string$issuer )The "iss" (issuer) claim identifies the principal that issued thepublicstaticsetNotBefore( int$timestamp )The "nbf" (not before) claim identifies the time before which the JWTpublicstaticsetPassphrase( string$passphrase )publicstaticsetSubject( string$subject )The "sub" (subject) claim identifies the principal that is theprotectedBuildersetClaim(string$name,mixed$value)Sets a registered claimMethods
__construct()
public function __construct( SignerInterface $signer );Builder constructor.
addClaim()
public function addClaim(
string $name,
mixed $value
): static;Adds a custom claim
addHeader()
public function addHeader(
string $name,
mixed $value
): static;Adds a custom claim
getAudience()
public function getAudience();getClaims()
public function getClaims(): array;getContentType()
public function getContentType(): string|null;getExpirationTime()
public function getExpirationTime(): int|null;getHeaders()
public function getHeaders(): array;getId()
public function getId(): string|null;getIssuedAt()
public function getIssuedAt(): int|null;getIssuer()
public function getIssuer(): string|null;getNotBefore()
public function getNotBefore(): int|null;getPassphrase()
public function getPassphrase(): string;getSubject()
public function getSubject(): string|null;getToken()
public function getToken(): Token;init()
public function init(): static;setAudience()
public function setAudience( mixed $audience ): static;The “aud” (audience) claim identifies the recipients that the JWT is intended for. Each principal intended to process the JWT MUST identify itself with a value in the audience claim. If the principal processing the claim does not identify itself with a value in the “aud” claim when this claim is present, then the JWT MUST be rejected. In the general case, the “aud” value is an array of case- sensitive strings, each containing a StringOrURI value. In the special case when the JWT has one audience, the “aud” value MAY be a single case-sensitive string containing a StringOrURI value. The interpretation of audience values is generally application specific. Use of this claim is OPTIONAL.
setContentType()
public function setContentType( string $contentType ): static;Sets the content type header ‘cty’
setExpirationTime()
public function setExpirationTime( int $timestamp ): static;The “exp” (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the “exp” claim requires that the current date/time MUST be before the expiration date/time listed in the “exp” claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.
setId()
public function setId( string $jwtId ): static;The “jti” (JWT ID) claim provides a unique identifier for the JWT. The identifier value MUST be assigned in a manner that ensures that there is a negligible probability that the same value will be accidentally assigned to a different data object; if the application uses multiple issuers, collisions MUST be prevented among values produced by different issuers as well. The “jti” claim can be used to prevent the JWT from being replayed. The “jti” value is a case- sensitive string. Use of this claim is OPTIONAL.
setIssuedAt()
public function setIssuedAt( int $timestamp ): static;The “iat” (issued at) claim identifies the time at which the JWT was issued. This claim can be used to determine the age of the JWT. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.
setIssuer()
public function setIssuer( string $issuer ): static;The “iss” (issuer) claim identifies the principal that issued the JWT. The processing of this claim is generally application specific. The “iss” value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.
setNotBefore()
public function setNotBefore( int $timestamp ): static;The “nbf” (not before) claim identifies the time before which the JWT MUST NOT be accepted for processing. The processing of the “nbf” claim requires that the current date/time MUST be after or equal to the not-before date/time listed in the “nbf” claim. Implementers MAY provide for some small leeway, usually no more than a few minutes, to account for clock skew. Its value MUST be a number containing a NumericDate value. Use of this claim is OPTIONAL.
setPassphrase()
public function setPassphrase( string $passphrase ): static;setSubject()
public function setSubject( string $subject ): static;The “sub” (subject) claim identifies the principal that is the subject of the JWT. The claims in a JWT are normally statements about the subject. The subject value MUST either be scoped to be locally unique in the context of the issuer or be globally unique. The processing of this claim is generally application specific. The “sub” value is a case-sensitive string containing a StringOrURI value. Use of this claim is OPTIONAL.
setClaim()
protected function setClaim(
string $name,
mixed $value
): Builder;Sets a registered claim
Encryption\Security\JWT\Exceptions\EmptyPassphrase
ClassSource on GitHubExceptionPhalcon\Encryption\Security\JWT\Exceptions\ValidatorExceptionPhalcon\Encryption\Security\JWT\Exceptions\EmptyPassphrase
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Exceptions\InvalidAudience
ClassSource on GitHubExceptionPhalcon\Encryption\Security\JWT\Exceptions\ValidatorExceptionPhalcon\Encryption\Security\JWT\Exceptions\InvalidAudience
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Exceptions\InvalidAudienceType
ClassSource on GitHubExceptionPhalcon\Encryption\Security\JWT\Exceptions\ValidatorExceptionPhalcon\Encryption\Security\JWT\Exceptions\InvalidAudienceType
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Exceptions\InvalidClaims
ClassSource on GitHubInvalidArgumentExceptionPhalcon\Encryption\Security\JWT\Exceptions\InvalidClaims
Uses InvalidArgumentException
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Exceptions\InvalidExpirationTime
ClassSource on GitHubExceptionPhalcon\Encryption\Security\JWT\Exceptions\ValidatorExceptionPhalcon\Encryption\Security\JWT\Exceptions\InvalidExpirationTime
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Exceptions\InvalidHeader
ClassSource on GitHubInvalidArgumentExceptionPhalcon\Encryption\Security\JWT\Exceptions\InvalidHeader
Uses InvalidArgumentException
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Exceptions\InvalidNotBefore
ClassSource on GitHubExceptionPhalcon\Encryption\Security\JWT\Exceptions\ValidatorExceptionPhalcon\Encryption\Security\JWT\Exceptions\InvalidNotBefore
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Exceptions\MalformedJwtString
ClassSource on GitHubInvalidArgumentExceptionPhalcon\Encryption\Security\JWT\Exceptions\MalformedJwtString
Uses InvalidArgumentException
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Exceptions\MissingJwtTypHeader
ClassSource on GitHubInvalidArgumentExceptionPhalcon\Encryption\Security\JWT\Exceptions\MissingJwtTypHeader
Uses InvalidArgumentException
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Exceptions\UnsupportedAlgorithmException
ClassSource on GitHubException thrown when the algorithm is not supported for JWT
ExceptionPhalcon\Encryption\Security\JWT\Exceptions\UnsupportedAlgorithmException
Uses Exception
Encryption\Security\JWT\Exceptions\UnsupportedHmacAlgorithm
ClassSource on GitHubExceptionPhalcon\Encryption\Security\JWT\Exceptions\UnsupportedAlgorithmExceptionPhalcon\Encryption\Security\JWT\Exceptions\UnsupportedHmacAlgorithm
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Exceptions\ValidatorException
ClassSource on GitHubException thrown when the validation does not pass for JWT
ExceptionPhalcon\Encryption\Security\JWT\Exceptions\ValidatorExceptionPhalcon\Encryption\Security\JWT\Exceptions\EmptyPassphrasePhalcon\Encryption\Security\JWT\Exceptions\InvalidAudiencePhalcon\Encryption\Security\JWT\Exceptions\InvalidAudienceTypePhalcon\Encryption\Security\JWT\Exceptions\InvalidExpirationTimePhalcon\Encryption\Security\JWT\Exceptions\InvalidNotBeforePhalcon\Encryption\Security\JWT\Exceptions\WeakPassphrase
Uses Exception
Encryption\Security\JWT\Exceptions\WeakPassphrase
ClassSource on GitHubExceptionPhalcon\Encryption\Security\JWT\Exceptions\ValidatorExceptionPhalcon\Encryption\Security\JWT\Exceptions\WeakPassphrase
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\JWT\Signer\AbstractSigner
AbstractSource on GitHubAbstract class helping with the signer classes
Phalcon\Encryption\Security\JWT\Signer\AbstractSigner- implementsPhalcon\Encryption\Security\JWT\Signer\SignerInterface
Method Summary
Properties
protectedstring$algorithm = ""Methods
getAlgorithm()
public function getAlgorithm(): string;Encryption\Security\JWT\Signer\Hmac
ClassSource on GitHubHMAC signing class
Phalcon\Encryption\Security\JWT\Signer\AbstractSignerPhalcon\Encryption\Security\JWT\Signer\Hmac
Uses Phalcon\Encryption\Security\JWT\Exceptions\UnsupportedAlgorithmException · Phalcon\Encryption\Security\JWT\Exceptions\UnsupportedHmacAlgorithm · Phalcon\Traits\Php\HashTrait
Method Summary
public__construct( string$algo = "sha512" )Hmac constructor.publicstringgetAlgHeader()Return the value that is used for the "alg" headerpublicstringsign(string$payload,string$passphrase)Sign a payload using the passphrasepublicboolverify(string$source,string$payload,string$passphrase)Verify a passed source with a payload and passphraseMethods
__construct()
public function __construct( string $algo = "sha512" );Hmac constructor.
getAlgHeader()
public function getAlgHeader(): string;Return the value that is used for the “alg” header
sign()
public function sign(
string $payload,
string $passphrase
): string;Sign a payload using the passphrase
verify()
public function verify(
string $source,
string $payload,
string $passphrase
): bool;Verify a passed source with a payload and passphrase
Encryption\Security\JWT\Signer\None
ClassSource on GitHubNo signing class
Phalcon\Encryption\Security\JWT\Signer\None- implementsPhalcon\Encryption\Security\JWT\Signer\SignerInterface
Method Summary
publicstringgetAlgHeader()Return the value that is used for the "alg" headerpublicstringgetAlgorithm()Return the algorithm usedpublicstringsign(string$payload,string$passphrase)Sign a payload using the passphrasepublicboolverify(string$source,string$payload,string$passphrase)Verify a passed source with a payload and passphraseMethods
getAlgHeader()
public function getAlgHeader(): string;Return the value that is used for the “alg” header
getAlgorithm()
public function getAlgorithm(): string;Return the algorithm used
sign()
public function sign(
string $payload,
string $passphrase
): string;Sign a payload using the passphrase
verify()
public function verify(
string $source,
string $payload,
string $passphrase
): bool;Verify a passed source with a payload and passphrase
Encryption\Security\JWT\Signer\SignerInterface
InterfaceSource on GitHubInterface for JWT Signer classes
Phalcon\Contracts\Encryption\Security\JWT\Signer\SignerPhalcon\Encryption\Security\JWT\Signer\SignerInterface
Uses Phalcon\Contracts\Encryption\Security\JWT\Signer\Signer
Encryption\Security\JWT\Token\AbstractItem
AbstractSource on GitHubAbstract helper class for Tokens
Phalcon\Encryption\Security\JWT\Token\AbstractItem
Method Summary
Properties
protectedarray$data = []Methods
getEncoded()
public function getEncoded(): string;Encryption\Security\JWT\Token\Enum
ClassSource on GitHubConstants for Tokens. It offers constants for Headers as well as Claims
@link https://tools.ietf.org/html/rfc7519
Phalcon\Encryption\Security\JWT\Token\Enum
Constants
stringALGO = "alg"stringAUDIENCE = "aud"ClaimsstringCONTENT_TYPE = "cty"stringEXPIRATION_TIME = "exp"stringID = "jti"stringISSUED_AT = "iat"stringISSUER = "iss"stringNOT_BEFORE = "nbf"stringSUBJECT = "sub"stringTYPE = "typ"HeadersEncryption\Security\JWT\Token\Item
ClassSource on GitHubStorage class for a Token Item
Phalcon\Encryption\Security\JWT\Token\AbstractItemPhalcon\Encryption\Security\JWT\Token\Item
Method Summary
public__construct(array$payload,string$encoded)Item constructor.publicmixed|nullget(string$name,mixed$defaultValue = null)publicarraygetPayload()publicboolhas( string$name )Methods
__construct()
public function __construct(
array $payload,
string $encoded
);Item constructor.
get()
public function get(
string $name,
mixed $defaultValue = null
): mixed|null;getPayload()
public function getPayload(): array;has()
public function has( string $name ): bool;Encryption\Security\JWT\Token\Parser
ClassSource on GitHubToken Parser class.
It parses a token by validating if it is formed properly and splits it into three parts. The headers are decoded, then the claims and finally the signature. It returns a token object populated with the decoded information.
Phalcon\Encryption\Security\JWT\Token\Parser
Uses InvalidArgumentException · Phalcon\Encryption\Security\JWT\Exceptions\InvalidClaims · Phalcon\Encryption\Security\JWT\Exceptions\InvalidHeader · Phalcon\Encryption\Security\JWT\Exceptions\MalformedJwtString · Phalcon\Encryption\Security\JWT\Exceptions\MissingJwtTypHeader · Phalcon\Support\Helper\Json\Decode · Phalcon\Traits\Php\Base64Trait
Method Summary
public__construct( Decode$decode = null )publicTokenparse( string$token )Parse a token and return itMethods
__construct()
public function __construct( Decode $decode = null );parse()
public function parse( string $token ): Token;Parse a token and return it
Encryption\Security\JWT\Token\Signature
ClassSource on GitHubSignature class containing the encoded data and the hash.
Phalcon\Encryption\Security\JWT\Token\AbstractItemPhalcon\Encryption\Security\JWT\Token\Signature
Method Summary
Methods
__construct()
public function __construct(
string $hash = "",
string $encoded = ""
);Signature constructor.
getHash()
public function getHash(): string;Encryption\Security\JWT\Token\Token
ClassSource on GitHubToken Class.
A container for Token related data. It stores the claims, headers, signature and payload. It also calculates and returns the token string.
@property Item $claims @property Item $headers @property Signature $signature
@link https://tools.ietf.org/html/rfc7519
Phalcon\Encryption\Security\JWT\Token\Token
Uses Phalcon\Encryption\Security\JWT\Signer\SignerInterface · Phalcon\Encryption\Security\JWT\Validator
Method Summary
public__construct(Item$headers,Item$claims,Signature$signature)Token constructor.publicItemgetClaims()Return the registered claimspublicItemgetHeaders()Return the registered headerspublicstringgetPayload()Return the payloadpublicSignaturegetSignature()Return the signaturepublicstringgetToken()Return the tokenpublicarrayvalidate( Validator$validator )Validate the token against the claims registered in the validator.publicboolverify(SignerInterface$signer,string$key)Verify the signatureMethods
__construct()
public function __construct(
Item $headers,
Item $claims,
Signature $signature
);Token constructor.
getClaims()
public function getClaims(): Item;Return the registered claims
getHeaders()
public function getHeaders(): Item;Return the registered headers
getPayload()
public function getPayload(): string;Return the payload
getSignature()
public function getSignature(): Signature;Return the signature
getToken()
public function getToken(): string;Return the token
validate()
public function validate( Validator $validator ): array;Validate the token against the claims registered in the validator.
Only claims that have a value in the validator are checked. A claim left as null expresses no expectation and is skipped.
verify()
public function verify(
SignerInterface $signer,
string $key
): bool;Verify the signature
Encryption\Security\JWT\Validator
ClassSource on GitHubClass Validator
Phalcon\Encryption\Security\JWT\Validator
Uses DateTimeImmutable · Phalcon\Encryption\Security\JWT\Exceptions\InvalidAudienceType · Phalcon\Encryption\Security\JWT\Exceptions\ValidatorException · Phalcon\Encryption\Security\JWT\Signer\SignerInterface · Phalcon\Encryption\Security\JWT\Token\Enum · Phalcon\Encryption\Security\JWT\Token\Token · Phalcon\Time\Clock\ClockInterface
Method Summary
public__construct(Token$token,int$timeShift = 0,ClockInterface$clock = null)Validator constructor.publicmixed|nullget( string$claim )Return the value of a claimpublicarraygetErrors()Return an array with validation errors (if any)publicstaticset(string$claim,mixed$value)Set the value of a claim, for comparison with the token valuespublicstaticsetToken( Token$token )Set the token to be validatedpublicstaticvalidateAudience( mixed$audience )Validate the audiencepublicstaticvalidateClaim(string$name,mixed$value)Validate a claimpublicstaticvalidateExpiration( int$timestamp )Validate the expiration time of the tokenpublicstaticvalidateId( string$id = null )Validate the id of the tokenpublicstaticvalidateIssuedAt( int$timestamp )Validate the issued at (iat) of the tokenpublicstaticvalidateIssuer( string$issuer = null )Validate the issuer of the tokenpublicstaticvalidateNotBefore( int$timestamp )Validate the notbefore (nbf) of the tokenpublicstaticvalidateSignature(SignerInterface$signer,string$passphrase)Validate the signature of the tokenpublicstaticvalidateSubject( string$subject = null )Validate the subject of the tokenMethods
__construct()
public function __construct(
Token $token,
int $timeShift = 0,
ClockInterface $clock = null
);Validator constructor.
get()
public function get( string $claim ): mixed|null;Return the value of a claim
getErrors()
public function getErrors(): array;Return an array with validation errors (if any)
set()
public function set(
string $claim,
mixed $value
): static;Set the value of a claim, for comparison with the token values
setToken()
public function setToken( Token $token ): static;Set the token to be validated
validateAudience()
public function validateAudience( mixed $audience ): static;Validate the audience
validateClaim()
public function validateClaim(
string $name,
mixed $value
): static;Validate a claim
validateExpiration()
public function validateExpiration( int $timestamp ): static;Validate the expiration time of the token
validateId()
public function validateId( string $id = null ): static;Validate the id of the token
A null id expresses no expectation and is skipped.
validateIssuedAt()
public function validateIssuedAt( int $timestamp ): static;Validate the issued at (iat) of the token
A token issued at exactly $timestamp is valid. Only a token issued after it, i.e. in the future, is rejected.
validateIssuer()
public function validateIssuer( string $issuer = null ): static;Validate the issuer of the token
A null issuer expresses no expectation and is skipped.
validateNotBefore()
public function validateNotBefore( int $timestamp ): static;Validate the notbefore (nbf) of the token
A token is valid at exactly $timestamp. Only a timestamp before the “nbf” claim is rejected.
validateSignature()
public function validateSignature(
SignerInterface $signer,
string $passphrase
): static;Validate the signature of the token
validateSubject()
public function validateSubject( string $subject = null ): static;Validate the subject of the token
A null subject expresses no expectation and is skipped.
Encryption\Security\Random
ClassSource on GitHubPhalcon\Encryption\Security\Random
Secure random number generator class.
Provides secure random number generator which is suitable for generating session key in HTTP cookies, etc.
Phalcon\Encryption\Security\Random could be mainly useful for:
- Key generation (e.g. generation of complicated keys)
- Generating random passwords for new user accounts
- Encryption systems
$random = new \Phalcon\Encryption\Security\Random();
// Random binary string
$bytes = $random->bytes();
// Random hex string
echo $random->hex(10); // a29f470508d5ccb8e289
echo $random->hex(10); // 533c2f08d5eee750e64a
echo $random->hex(11); // f362ef96cb9ffef150c9cd
echo $random->hex(12); // 95469d667475125208be45c4
echo $random->hex(13); // 05475e8af4a34f8f743ab48761
// Random base62 string
echo $random->base62(); // z0RkwHfh8ErDM1xw
// Random base64 string
echo $random->base64(12); // XfIN81jGGuKkcE1E
echo $random->base64(12); // 3rcq39QzGK9fUqh8
echo $random->base64(); // DRcfbngL/iOo9hGGvy1TcQ==
echo $random->base64(16); // SvdhPcIHDZFad838Bb0Swg==
// Random URL-safe base64 string
echo $random->base64Safe(); // PcV6jGbJ6vfVw7hfKIFDGA
echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug
echo $random->base64Safe(8); // mGyy0evy3ok
echo $random->base64Safe(null, true); // DRrAgOFkS4rvRiVHFefcQ==
// Random UUID (version 4) - returns a string
echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235
echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2
// For other UUID versions (1, 3, 5, 6, 7) or object-based access use the
// Phalcon\Encryption\Security\Uuid factory instead:
//
// $uuid = new \Phalcon\Encryption\Security\Uuid();
// echo $uuid->v1(); // time-based
// echo $uuid->v6(); // reordered time-based (sortable)
// echo $uuid->v7(); // Unix-timestamp based (sortable)
// Random number between 0 and $len
echo $random->number(256); // 84
echo $random->number(256); // 79
echo $random->number(100); // 29
echo $random->number(300); // 40
// Random base58 string
echo $random->base58(); // 4kUgL2pdQMSCQtjE
echo $random->base58(); // Umjxqf7ZPwh765yR
echo $random->base58(24); // qoXcgmw4A9dys26HaNEdCRj9
echo $random->base58(7); // 774SJD3vgPThis class partially borrows SecureRandom library from Ruby
@link https://ruby-doc.org/stdlib-2.2.2/libdoc/securerandom/rdoc/SecureRandom.html
Phalcon\Encryption\Security\Random
Uses Phalcon\Encryption\Security\Exceptions\InvalidRandomInput
Method Summary
publicstringbase58( int$len = 16 )Generates a random base58 stringpublicstringbase62( int$len = 16 )Generates a random base62 stringpublicstringbase64( int$len = 16 )Generates a random base64 stringpublicstringbase64Safe(int$len = 16,bool$padding = false)Generates a random URL-safe base64 stringpublicstringbytes( int$len = 16 )Generates a random binary stringpublicstringhex( int$len = 16 )Generates a random hex stringpublicintnumber( int$len )Generates a random number between 0 and $lenpublicstringuuid()Generates a v4 random UUID (Universally Unique IDentifier)protectedstringbase(string$alphabet,int$base,mixed$number = 16)Generates a random string based on the number ($base) of charactersMethods
base58()
public function base58( int $len = 16 ): string;Generates a random base58 string
The result may contain alphanumeric characters except 0, O, I and l.
It is similar to Phalcon\Encryption\Security\Random::base64() but has been
modified to avoid both non-alphanumeric characters and letters which
might look ambiguous when printed.
$random = new \Phalcon\Encryption\Security\Random();
echo $random->base58(); // 4kUgL2pdQMSCQtjE@see \Phalcon\Encryption\Security\Random:base64 @link https://en.wikipedia.org/wiki/Base58
base62()
public function base62( int $len = 16 ): string;Generates a random base62 string
It is similar to Phalcon\Encryption\Security\Random::base58() but has been
modified to provide the largest value that can safely be used in URLs
without needing to take extra characters into consideration because it is
[A-Za-z0-9].
$random = new \Phalcon\Encryption\Security\Random();
echo $random->base62(); // z0RkwHfh8ErDM1xw@see \Phalcon\Encryption\Security\Random:base58
base64()
public function base64( int $len = 16 ): string;Generates a random base64 string
The length of the result string is usually greater of $len. Size formula: 4 * ($len / 3) rounded up to a multiple of 4.
$random = new \Phalcon\Encryption\Security\Random();
echo $random->base64(12); // 3rcq39QzGK9fUqh8base64Safe()
public function base64Safe(
int $len = 16,
bool $padding = false
): string;Generates a random URL-safe base64 string
The length of the result string is usually greater of $len.
By default, padding is not generated because “=” may be used as a URL delimiter. The result may contain A-Z, a-z, 0-9, “-” and “_”. “=” is also used if $padding is true. See RFC 3548 for the definition of URL-safe base64.
$random = new \Phalcon\Encryption\Security\Random();
echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug@link https://www.ietf.org/rfc/rfc3548.txt
bytes()
public function bytes( int $len = 16 ): string;Generates a random binary string
The Random::bytes method returns a string and accepts as input an int
representing the length in bytes to be returned.
If $len is not specified, 16 is assumed. It may be larger in future. The result may contain any byte: “x00” - “xFF”.
$random = new \Phalcon\Encryption\Security\Random();
$bytes = $random->bytes();
var_dump(bin2hex($bytes));
// Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee"hex()
public function hex( int $len = 16 ): string;Generates a random hex string
The length of the result string is usually greater of $len.
$random = new \Phalcon\Encryption\Security\Random();
echo $random->hex(10); // a29f470508d5ccb8e289number()
public function number( int $len ): int;Generates a random number between 0 and $len
Returns an integer: 0 <= result <= $len.
$random = new \Phalcon\Encryption\Security\Random();
echo $random->number(16); // 8uuid()
public function uuid(): string;Generates a v4 random UUID (Universally Unique IDentifier)
The version 4 UUID is purely random (except the version). It does not contain meaningful information such as MAC address, time, etc. See RFC 4122 for details of UUID.
Delegates to Phalcon\Encryption\Security\Uuid::v4(). For other UUID
versions or object-based access use that class directly.
$random = new \Phalcon\Encryption\Security\Random();
echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22@link https://www.ietf.org/rfc/rfc4122.txt
base()
protected function base(
string $alphabet,
int $base,
mixed $number = 16
): string;Generates a random string based on the number ($base) of characters ($alphabet).
Encryption\Security\Uuid
ClassSource on GitHubFactory that generates UUIDs of versions 1 through 7.
Each call creates a new immutable version object. Cast to string for the UUID value; use the returned object for additional methods such as getDateTime() or getNode().
Phalcon\Encryption\Security\Uuid
Uses Phalcon\Encryption\Security\Uuid\Version1 · Phalcon\Encryption\Security\Uuid\Version3 · Phalcon\Encryption\Security\Uuid\Version4 · Phalcon\Encryption\Security\Uuid\Version5 · Phalcon\Encryption\Security\Uuid\Version6 · Phalcon\Encryption\Security\Uuid\Version7
Method Summary
publicVersion1v1()Generates a version 1 (time-based) UUID.publicVersion3v3(string$namespaceName,string$name)Generates a version 3 (name-based MD5) UUID.publicVersion4v4()Generates a version 4 (random) UUID.publicVersion5v5(string$namespaceName,string$name)Generates a version 5 (name-based SHA-1) UUID.publicVersion6v6()Generates a version 6 (reordered time-based) UUID.publicVersion7v7()Generates a version 7 (Unix timestamp) UUID.Methods
v1()
public function v1(): Version1;Generates a version 1 (time-based) UUID.
v3()
public function v3(
string $namespaceName,
string $name
): Version3;Generates a version 3 (name-based MD5) UUID.
v4()
public function v4(): Version4;Generates a version 4 (random) UUID.
v5()
public function v5(
string $namespaceName,
string $name
): Version5;Generates a version 5 (name-based SHA-1) UUID.
v6()
public function v6(): Version6;Generates a version 6 (reordered time-based) UUID.
v7()
public function v7(): Version7;Generates a version 7 (Unix timestamp) UUID.
Encryption\Security\Uuid\AbstractUuid
AbstractSource on GitHubShared base for all UUID version objects.
Phalcon\Encryption\Security\Uuid\AbstractUuid- implementsPhalcon\Encryption\Security\Uuid\UuidInterface
Method Summary
publicstring__toString()Returns the UUID string.publicstringjsonSerialize()Returns the UUID string for JSON serialisation.protectedstringformat( string$hex )Formats a 32-character hex string as a canonical UUID string.protectedNodeProviderInterfacegetNodeProvider()Returns the shared SysNodeProvider instance, creating it on first call.protectedstringnamespaceToBytes( string$uuid )Converts a canonical UUID string to its 16-byte binary representation.protected\DateTimeImmutableuuidTimestampToDateTime( mixed$timestamp )Converts a 60-bit UUID timestamp (100-ns intervals since UUID epoch) toConstants
stringMAX = "ffffffff-ffff-ffff-ffff-ffffffffffff"stringNIL = "00000000-0000-0000-0000-000000000000"intTIME_OFFSET_INT = 0x01B21DD213814000100-nanosecond intervals between UUID epoch (1582-10-15) and Unix epoch (1970-01-01).Properties
protectedNodeProviderInterface|null$nodeProvider = nullCached SysNodeProvider instance - shared within the request via static.protectedstring$uid = ""The generated UUID string.Methods
__toString()
public function __toString(): string;Returns the UUID string.
jsonSerialize()
public function jsonSerialize(): string;Returns the UUID string for JSON serialisation.
format()
protected function format( string $hex ): string;Formats a 32-character hex string as a canonical UUID string.
getNodeProvider()
protected function getNodeProvider(): NodeProviderInterface;Returns the shared SysNodeProvider instance, creating it on first call. The static property means one discovery per request regardless of how many VersionN objects are constructed.
namespaceToBytes()
protected function namespaceToBytes( string $uuid ): string;Converts a canonical UUID string to its 16-byte binary representation.
uuidTimestampToDateTime()
protected function uuidTimestampToDateTime( mixed $timestamp ): \DateTimeImmutable;Converts a 60-bit UUID timestamp (100-ns intervals since UUID epoch) to a DateTimeImmutable. Used by Version1 and Version6.
Encryption\Security\Uuid\NodeProviderInterface
InterfaceSource on GitHubPhalcon\Contracts\Encryption\Security\Uuid\NodeProviderPhalcon\Encryption\Security\Uuid\NodeProviderInterface
Uses Phalcon\Contracts\Encryption\Security\Uuid\NodeProvider
Encryption\Security\Uuid\RandomNodeProvider
ClassSource on GitHubGenerates a random 48-bit node with the multicast bit set.
Used as a fallback when no hardware MAC address is available.
@link https://www.ietf.org/rfc/rfc4122.txt Section 4.5
Phalcon\Encryption\Security\Uuid\RandomNodeProvider- implementsPhalcon\Encryption\Security\Uuid\NodeProviderInterface
Method Summary
Methods
getNode()
public function getNode(): string;Returns a random 12-character hex node with the multicast bit set.
Encryption\Security\Uuid\SysNodeProvider
ClassSource on GitHubDiscovers the hardware MAC address and returns it as a 12-character hex node.
Two-layer cache:
- Instance property - free on all calls after the first within this instance.
- APCu - cross-request within the same PHP-FPM worker (optional).
Falls back to RandomNodeProvider if no valid MAC address is found.
Platform support: Linux - reads /sys/class/net/*/address macOS - passthru(“ifconfig 2>&1”) Windows - passthru(“ipconfig /all 2>&1”) FreeBSD - passthru(“netstat -i -f link 2>&1”)
Phalcon\Encryption\Security\Uuid\SysNodeProvider- implementsPhalcon\Encryption\Security\Uuid\NodeProviderInterface
Uses Phalcon\Traits\Php\FileTrait · Phalcon\Traits\Php\InfoTrait
Method Summary
Methods
getNode()
public function getNode(): string;Returns the hardware MAC address as a 12-character hex string. Result is cached in the instance property and optionally in APCu.
Encryption\Security\Uuid\TimeBasedUuidInterface
InterfaceSource on GitHubPhalcon\Contracts\Encryption\Security\Uuid\TimeBasedUuidPhalcon\Encryption\Security\Uuid\TimeBasedUuidInterface
Uses Phalcon\Contracts\Encryption\Security\Uuid\TimeBasedUuid
Encryption\Security\Uuid\UuidInterface
InterfaceSource on GitHubMarker interface for UUID version adapters.
Also carries the standard RFC 4122 namespace UUIDs as constants.
Phalcon\Contracts\Encryption\Security\Uuid\UuidPhalcon\Encryption\Security\Uuid\UuidInterface
Uses Phalcon\Contracts\Encryption\Security\Uuid\Uuid
Encryption\Security\Uuid\Version1
ClassSource on GitHubGenerates a version 1 (time-based) UUID.
The timestamp is the number of 100-nanosecond intervals since October 15, 1582 00:00:00.00 UTC (the UUID epoch). The node is resolved via SysNodeProvider (hardware MAC, APCu-cached) with RandomNodeProvider as fallback.
@link https://www.ietf.org/rfc/rfc4122.txt
Phalcon\Encryption\Security\Uuid\AbstractUuidPhalcon\Encryption\Security\Uuid\Version1- implementsPhalcon\Encryption\Security\Uuid\TimeBasedUuidInterface
Method Summary
public__construct(\DateTimeInterface$dateTime = null,mixed$node = null)public\DateTimeImmutablegetDateTime()Returns a DateTimeImmutable built from the UUID's embedded timestamp.publicstringgetNode()Returns the 12-character hex node embedded in the UUID.Methods
__construct()
public function __construct(
\DateTimeInterface $dateTime = null,
mixed $node = null
);getDateTime()
public function getDateTime(): \DateTimeImmutable;Returns a DateTimeImmutable built from the UUID’s embedded timestamp.
getNode()
public function getNode(): string;Returns the 12-character hex node embedded in the UUID.
Encryption\Security\Uuid\Version3
ClassSource on GitHubGenerates a version 3 (name-based MD5) UUID.
Given a namespace UUID and a name string, produces a deterministic UUID by hashing namespace bytes + name with MD5, then stamping version/variant.
@link https://www.ietf.org/rfc/rfc4122.txt
Phalcon\Encryption\Security\Uuid\AbstractUuidPhalcon\Encryption\Security\Uuid\Version3
Method Summary
Methods
__construct()
public function __construct(
string $namespaceName,
string $name
);Encryption\Security\Uuid\Version4
ClassSource on GitHubGenerates a version 4 (random) UUID.
All 122 non-fixed bits are random. Identical algorithm to Phalcon\Encryption\Security\Random::uuid().
@link https://www.ietf.org/rfc/rfc4122.txt
Phalcon\Encryption\Security\Uuid\AbstractUuidPhalcon\Encryption\Security\Uuid\Version4
Method Summary
Methods
__construct()
public function __construct();Encryption\Security\Uuid\Version5
ClassSource on GitHubGenerates a version 5 (name-based SHA-1) UUID.
Given a namespace UUID and a name string, produces a deterministic UUID by hashing namespace bytes + name with SHA-1 (first 16 bytes used), then stamping version/variant bits.
@link https://www.ietf.org/rfc/rfc4122.txt
Phalcon\Encryption\Security\Uuid\AbstractUuidPhalcon\Encryption\Security\Uuid\Version5
Method Summary
Methods
__construct()
public function __construct(
string $namespaceName,
string $name
);Encryption\Security\Uuid\Version6
ClassSource on GitHubGenerates a version 6 (reordered time-based) UUID.
Uses the same 60-bit UUID timestamp as version 1 but rearranges the fields so the most-significant time bits come first, producing UUIDs that sort lexicographically in chronological order.
@link https://www.rfc-editor.org/rfc/rfc9562
Phalcon\Encryption\Security\Uuid\AbstractUuidPhalcon\Encryption\Security\Uuid\Version6- implementsPhalcon\Encryption\Security\Uuid\TimeBasedUuidInterface
Method Summary
public__construct()public\DateTimeImmutablegetDateTime()Returns a DateTimeImmutable built from the UUID's embedded timestamp.publicstringgetNode()Returns the 12-character hex node embedded in the UUID.Methods
__construct()
public function __construct();getDateTime()
public function getDateTime(): \DateTimeImmutable;Returns a DateTimeImmutable built from the UUID’s embedded timestamp.
getNode()
public function getNode(): string;Returns the 12-character hex node embedded in the UUID.
Encryption\Security\Uuid\Version7
ClassSource on GitHubGenerates a version 7 (Unix timestamp) UUID per RFC 9562.
Layout (128 bits): unix_ts_ms (48) | ver=7 (4) | rand_a (12) | var=10 (2) | rand_b (62)
@link https://www.rfc-editor.org/rfc/rfc9562
Phalcon\Encryption\Security\Uuid\AbstractUuidPhalcon\Encryption\Security\Uuid\Version7
Method Summary
Methods
__construct()
public function __construct();