Class Phalcon\Encryption\Crypt
Código fuente en GitHub
Namespace |
Phalcon\Encryption |
|
Uses |
Phalcon\Encryption\Crypt\CryptInterface, Phalcon\Encryption\Crypt\Exception\Exception, Phalcon\Encryption\Crypt\Exception\Mismatch, Phalcon\Encryption\Crypt\PadFactory |
|
Implements |
CryptInterface |
Proporciona capacidades de encriptado a las aplicaciones Phalcon.
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);
Constantes
const DEFAULT_ALGORITHM = sha256;
const DEFAULT_CIPHER = aes-256-cfb;
const PADDING_ANSI_X_923 = 1;
const PADDING_DEFAULT = 0;
const PADDING_ISO_10126 = 3;
const PADDING_ISO_IEC_7816_4 = 4;
const PADDING_PKCS7 = 2;
const PADDING_SPACE = 6;
const PADDING_ZERO = 5;
Propiedades
/**
* @var string
*/
protected authData = ;
/**
* @var string
*/
protected authTag = ;
/**
* @var int
*/
protected authTagLength = 16;
/**
* Available cipher methods.
*
* @var array
*/
protected availableCiphers;
/**
* @var string
*/
protected cipher;
/**
* The name of hashing algorithm.
*
* @var string
*/
protected hashAlgorithm;
/**
* The cipher iv length.
*
* @var int
*/
protected ivLength = 16;
/**
* @var string
*/
protected key = ;
/**
* @var int
*/
protected padding = 0;
/**
* @var PadFactory
*/
protected padFactory;
/**
* Whether calculating message digest enabled or not.
*
* @var bool
*/
protected useSigning = true;
Métodos
public function __construct( string $cipher = static-constant-access, bool $useSigning = bool, PadFactory $padFactory = null );
Crypt constructor.
public function decrypt( string $input, string $key = null ): string;
Desencripta un texto encriptado.
$encrypted = $crypt->decrypt(
$encrypted,
"T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"
);
public function decryptBase64( string $input, string $key = null, bool $safe = bool ): string;
Desencripta un texto que está codificado como cadena en base64.
public function encrypt( string $input, string $key = null ): string;
Encripta un texto.
$encrypted = $crypt->encrypt(
"Top secret",
"T4\xb1\x8d\xa9\x98\x05\\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3"
);
public function encryptBase64( string $input, string $key = null, bool $safe = bool ): string;
Encripta un texto devolviendo el resultado como cadena en base64.
public function getAuthData(): string;
Returns the auth data
public function getAuthTag(): string;
Returns the auth tag
public function getAuthTagLength(): int;
Returns the auth tag length
public function getAvailableCiphers(): array;
Devuelve una lista de cifrados disponibles.
public function getAvailableHashAlgorithms(): array;
Devuelve una lista de algoritmos hash registrados adecuados para hash_hmac.
public function getCipher(): string;
Devuelve el cifrado actual
public function getHashAlgorithm(): string;
Obtiene el nombre del algoritmo de hash.
public function getKey(): string;
Devuelve la clave de encriptación
public function isValidDecryptLength( string $input ): bool;
Returns if the input length for decryption is valid or not (number of bytes required by the cipher).
public function setAuthData( string $data ): CryptInterface;
public function setAuthTag( string $tag ): CryptInterface;
public function setAuthTagLength( int $length ): CryptInterface;
public function setCipher( string $cipher ): CryptInterface;
Establece el algoritmo de cifrado para el encriptado y desencriptado de los datos.
public function setHashAlgorithm( string $hashAlgorithm ): CryptInterface;
Establece el nombre del algoritmo de hash.
public function setKey( string $key ): CryptInterface;
Establece la clave de encriptación.
The $key
should have been previously generated in a cryptographically safe way.
Clave incorrecta: “le password”
Better (but still unsafe) -> “#1dj8$=dp?.ak//j1V$~%*0X”
Clave buena: “T4\xb1\x8d\xa9\x98\x05\\x8c\xbe\x1d\x07&[\x99\x18\xa4~Lc1\xbeW\xb3”
public function setPadding( int $scheme ): CryptInterface;
Cambia el esquema de relleno usado.
public function useSigning( bool $useSigning ): CryptInterface;
Establece si se debe usar el cálculo del resumen del mensaje.
protected function checkCipherHashIsAvailable( string $cipher, string $type ): void;
Checks if a cipher or a hash algorithm is available
protected function cryptPadText( string $input, string $mode, int $blockSize, int $paddingType ): string;
Rellena los textos antes de la encriptación. See cryptopad
protected function cryptUnpadText( string $input, string $mode, int $blockSize, int $paddingType ): string;
Elimina un relleno de un texto.
Si la función detecta que el texto no tiene relleno, lo devolverá sin modificar.
protected function decryptGcmCcmAuth( string $mode, string $cipherText, string $decryptKey, string $iv ): string;
protected function decryptGetUnpadded( string $mode, int $blockSize, string $decrypted ): string;
protected function encryptGcmCcm( string $mode, string $padded, string $encryptKey, string $iv ): string;
protected function encryptGetPadded( string $mode, string $input, int $blockSize ): string;
protected function initializeAvailableCiphers(): Crypt;
Inicializa los algoritmos de cifrado disponibles.
protected function phpFunctionExists( string $name ): bool;
@todo to be removed when we get traits
protected function phpOpensslCipherIvLength( string $cipher ): int | bool;
protected function phpOpensslRandomPseudoBytes( int $length );
Interface Phalcon\Encryption\Crypt\CryptInterface
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt |
Interfaz para Phalcon\Crypt
Métodos
public function decrypt( string $input, string $key = null ): string;
Desencripta un texto
public function decryptBase64( string $input, string $key = null ): string;
Desencripta un texto que está codificado como cadena en base64
public function encrypt( string $input, string $key = null ): string;
Encripta un texto
public function encryptBase64( string $input, string $key = null ): string;
Encripta un texto devolviendo el resultado como cadena en base64
public function getAuthData(): string;
Devuelve datos de autenticación
public function getAuthTag(): string;
Devuelve la etiqueta de autenticación
public function getAuthTagLength(): int;
Devuelve el tamaño de la etiqueta de autenticación
public function getAvailableCiphers(): array;
Devuelve una lista de cifrados disponibles
public function getCipher(): string;
Devuelve el cifrado actual
public function getKey(): string;
Devuelve la clave de encriptación
public function setAuthData( string $data ): CryptInterface;
Establece los datos de autenticación
public function setAuthTag( string $tag ): CryptInterface;
Establece la etiqueta de autenticación
public function setAuthTagLength( int $length ): CryptInterface;
Establece el tamaño de la etiqueta de autenticación
public function setCipher( string $cipher ): CryptInterface;
Establece el algoritmo de cifrado
public function setKey( string $key ): CryptInterface;
Establece la clave de encriptación
public function setPadding( int $scheme ): CryptInterface;
Cambia el esquema de relleno usado.
public function useSigning( bool $useSigning ): CryptInterface;
Sets if the calculating message digest must be used.
Class Phalcon\Encryption\Crypt\Exception\Exception
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt\Exception |
|
Extends |
\Exception |
Las excepciones lanzadas desde Phalcon\Crypt usarán esta clase
Class Phalcon\Encryption\Crypt\Exception\Mismatch
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt\Exception |
|
Extends |
Exception |
Las excepciones lanzadas en Phalcon\Crypt usarán esta clase.
Class Phalcon\Encryption\Crypt\PadFactory
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt |
|
Uses |
Phalcon\Encryption\Crypt, Phalcon\Encryption\Crypt\Padding\PadInterface, Phalcon\Factory\AbstractFactory, Phalcon\Support\Helper\Arr\Get |
|
Extends |
AbstractFactory |
Class PadFactory
@package Phalcon\Crypt
Propiedades
/**
* @var string
*/
protected exception = Phalcon\\Encryption\\Crypt\\Exception\\Exception;
Métodos
public function __construct( array $services = [] );
Constructor AdapterFactory.
public function newInstance( string $name ): PadInterface;
Crea una nueva instancia del adaptador
public function padNumberToService( int $number ): string;
Gets a Crypt pad constant and returns the unique service name for the padding class
protected function getServices(): array;
Class Phalcon\Encryption\Crypt\Padding\Ansi
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt\Padding |
|
Implements |
PadInterface |
Class Ansi
@package Phalcon\Encryption\Crypt\Padding
Métodos
public function pad( int $paddingSize ): string;
public function unpad( string $input, int $blockSize ): int;
Class Phalcon\Encryption\Crypt\Padding\Iso10126
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt\Padding |
|
Implements |
PadInterface |
Class Iso10126
@package Phalcon\Encryption\Crypt\Padding
Métodos
public function pad( int $paddingSize ): string;
public function unpad( string $input, int $blockSize ): int;
Class Phalcon\Encryption\Crypt\Padding\IsoIek
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt\Padding |
|
Implements |
PadInterface |
Class IsoIek
@package Phalcon\Encryption\Crypt\Padding
Métodos
public function pad( int $paddingSize ): string;
public function unpad( string $input, int $blockSize ): int;
Class Phalcon\Encryption\Crypt\Padding\Noop
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt\Padding |
|
Implements |
PadInterface |
Class Noop
@package Phalcon\Encryption\Crypt\Padding
Métodos
public function pad( int $paddingSize ): string;
public function unpad( string $input, int $blockSize ): int;
Interface Phalcon\Encryption\Crypt\Padding\PadInterface
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt\Padding |
Interface for Phalcon\Encryption\Crypt\Padding
Métodos
public function pad( int $paddingSize ): string;
public function unpad( string $input, int $blockSize ): int;
Class Phalcon\Encryption\Crypt\Padding\Pkcs7
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt\Padding |
|
Implements |
PadInterface |
Class Pkcs7
@package Phalcon\Encryption\Crypt\Padding
Métodos
public function pad( int $paddingSize ): string;
public function unpad( string $input, int $blockSize ): int;
Class Phalcon\Encryption\Crypt\Padding\Space
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt\Padding |
|
Implements |
PadInterface |
Class Space
@package Phalcon\Encryption\Crypt\Padding
Métodos
public function pad( int $paddingSize ): string;
public function unpad( string $input, int $blockSize ): int;
Class Phalcon\Encryption\Crypt\Padding\Zero
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Crypt\Padding |
|
Implements |
PadInterface |
Class Zero
@package Phalcon\Encryption\Crypt\Padding
Métodos
public function pad( int $paddingSize ): string;
public function unpad( string $input, int $blockSize ): int;
Class Phalcon\Encryption\Security
Código fuente en GitHub
Namespace |
Phalcon\Encryption |
|
Uses |
Phalcon\Di\DiInterface, Phalcon\Di\AbstractInjectionAware, Phalcon\Http\RequestInterface, Phalcon\Encryption\Security\Random, Phalcon\Encryption\Security\Exception, Phalcon\Session\ManagerInterface |
|
Extends |
AbstractInjectionAware |
Este componente provee un conjunto de funciones para mejorar la seguridad en aplicaciones Phalcon
$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
}
}
Constantes
const CRYPT_ARGON2I = 10;
const CRYPT_ARGON2ID = 11;
const CRYPT_BCRYPT = 0;
const CRYPT_BLOWFISH = 4;
const CRYPT_BLOWFISH_A = 5;
const CRYPT_BLOWFISH_X = 6;
const CRYPT_BLOWFISH_Y = 7;
const CRYPT_DEFAULT = 0;
const CRYPT_EXT_DES = 2;
const CRYPT_MD5 = 3;
const CRYPT_SHA256 = 8;
const CRYPT_SHA512 = 9;
const CRYPT_STD_DES = 1;
Propiedades
/**
* @var int
*/
protected defaultHash;
/**
* @var int
*/
protected numberBytes = 16;
/**
* @var Random
*/
protected random;
/**
* @var string|null
*/
protected requestToken;
/**
* @var string|null
*/
protected token;
/**
* @var string|null
*/
protected tokenKey;
/**
* @var string
*/
protected tokenKeySessionId = $PHALCON/CSRF/KEY$;
/**
* @var string
*/
protected tokenValueSessionId = $PHALCON/CSRF$;
/**
* @var int
*/
protected workFactor = 10;
/**
* @var SessionInterface|null
*/
private localSession;
/**
* @var RequestInterface|null
*/
private localRequest;
Métodos
public function __construct( SessionInterface $session = null, RequestInterface $request = null );
Security constructor.
public function checkHash( string $password, string $passwordHash, int $maxPassLength = int ): bool;
Comprueba si una contraseña de texto plano y su versión hash coinciden
public function checkToken( string $tokenKey = null, mixed $tokenValue = null, bool $destroyIfValid = bool ): bool;
Comprueba si el token CSRF enviado en la consulta es el mismo que el almacenado en la sesión actual
public function computeHmac( string $data, string $key, string $algo, bool $raw = bool ): string;
Calcula un HMAC
public function destroyToken(): Security;
Elimina el valor y clave del token CSRF de la sesión
public function getDefaultHash(): int;
Devuelve el hash predeterminado
public function getHashInformation( string $hash ): array;
Returns information regarding a hash
public function getRandom(): Random;
Devuelve una instancia del generador seguro de números aleatorio
public function getRandomBytes(): int;
Devuelve un número de bytes a ser generados por el generador pseudoaleatorio de openssl
public function getRequestToken(): string | null;
Devuelve el valor del token CSRF para la petición actual.
public function getSaltBytes( int $numberBytes = int ): string;
Generate a >22-length pseudo random string to be used as salt for passwords
public function getSessionToken(): string | null;
Devuelve el valor del token CSRF en sesión
public function getToken(): string | null;
Genera un token pseudo aleatorio para ser usado como valor en inputs en el chequeo de CSRF
public function getTokenKey(): string | null;
Genera un token pseudo aleatorio para ser usando como nombre en inputs en el chequeo de CSRF
public function getWorkFactor(): int;
public function hash( string $password, array $options = [] ): string;
Crea un hash de contraseña utilizando bcrypt con una sal pseudo aleatoria
public function isLegacyHash( string $passwordHash ): bool;
Comprueba si una contraseña hash es un hash bcrypt válido
public function setDefaultHash( int $defaultHash ): Security;
Establece el hash por defecto
public function setRandomBytes( int $randomBytes ): Security;
Establece un número de bytes a ser generados por el generador pseudo aleatorio de openssl
public function setWorkFactor( int $workFactor ): Security;
Establece el factor de trabajo
protected function getLocalService( string $name, string $property );
Class Phalcon\Encryption\Security\Exception
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security |
|
Extends |
\Exception |
Phalcon\Encryption\Security\Exception
Las excepciones lanzadas en Phalcon\Security usarán esta clase
Class Phalcon\Encryption\Security\JWT\Builder
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT |
|
Uses |
Phalcon\Encryption\Security\JWT\Exceptions\ValidatorException, 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 |
JWT Builder
@link https://tools.ietf.org/html/rfc7519
Propiedades
/**
* @var CollectionInterface
*/
private claims;
/**
* @var Encode
*/
private encode;
/**
* @var CollectionInterface
*/
private jose;
/**
* @var string
*/
private passphrase;
/**
* @var SignerInterface
*/
private signer;
Métodos
public function __construct( SignerInterface $signer );
Constructor.
public function addClaim( string $name, mixed $value ): Builder;
Adds a custom claim
public function addHeader( string $name, mixed $value ): Builder;
Adds a custom header
public function getAudience();
public function getClaims(): array;
public function getContentType(): string | null;
public function getExpirationTime(): int | null;
public function getHeaders(): array;
public function getId(): string | null;
public function getIssuedAt(): int | null;
public function getIssuer(): string | null;
public function getNotBefore(): int | null;
public function getPassphrase(): string;
public function getSubject(): string | null;
public function getToken(): Token;
public function init(): Builder;
public function setAudience( mixed $audience ): Builder;
El reclamo “aud” (audiencia) identifica a los destinatarios para los que el JWT está destinado. Cada uno de los principales destinados a procesar el JWT DEBE se identifica con un valor en el reclamo de audiencia. Si el procesamiento principal del reclamo no se identifica con un valor en el reclamo “aud” cuando esta reclamación está presente, entonces el JWT DEBE ser rechazado. En el caso general, el valor “aud” es un vector de cadenas sensibles a mayúsculas y minúsculas, cada una contiene un valor StringOrURI. En el caso especial cuando el JWT tiene una audiencia, el valor “aud” PUEDE ser una cadena única sensible a mayúsculas y minúsculas que contiene un valor StringOrURI. La interpretación de los valores de la audiencia es generalmente específica de la aplicación. El uso de este reclamo es OPCIONAL.
public function setContentType( string $contentType ): Builder;
Establece el encabezado de tipo de contenido ‘cty’
public function setExpirationTime( int $timestamp ): Builder;
El reclamo “exp” (tiempo de caducidad) identifica el tiempo de expiración durante o después del cual el JWT NO DEBE ser aceptado para su procesamiento. El procesamiento del reclamo “exp” requiere que la fecha/hora actual DEBE ser anterior a la fecha/hora de vencimiento listada en el reclamo “exp”. Los implementadores PUEDEN proporcionar un pequeño margen de maniobra, por lo general no mayor de de unos pocos minutos, para tener en cuenta la desviación del reloj. Su valor DEBE ser un número que contenga un valor NumericDate. El uso de este reclamo es OPCIONAL.
public function setId( string $id ): Builder;
El reclamo “jti” (JWT ID) proporciona un identificador único para el JWT. El valor del identificador DEBE ser asignado de una manera que asegure que hay una probabilidad despreciable de que el mismo valor será asignado accidentalmente a un objeto de datos diferente; si la aplicación utiliza múltiples emisores, las colisiones DEBEN ser prevenidas entre los valores producidos por diferentes emisores también. El reclamo “jti” se puede usar para prevenir que el JWT se vuelva a reproducir. El valor “jti” es una cadena sensible a mayúsculas y minúsculas. El uso de este reclamo es OPCIONAL.
public function setIssuedAt( int $timestamp ): Builder;
El reclamo “iat” (emitida en) identifica el tiempo en el que el JWT fue emitido. Este reclamo se puede utilizar para determinar la edad del JWT. Su valor DEBE ser un número que contenga un valor NumericDate. El uso de este reclamo es OPCIONAL.
public function setIssuer( string $issuer ): Builder;
El reclamo “iss” (emisor) identifica al principal que emite el JWT. La tramitación de este reclamo es generalmente específica para la aplicación. El valor “iss” es una cadena sensible a mayúsculas y minúsculas que contiene un valor StringOrURI. El uso de este reclamo es OPCIONAL.
public function setNotBefore( int $timestamp ): Builder;
El reclamo “nbf” (no antes) identifica el tiempo anterior al cual el JWT NO DEBE ser aceptado para su procesamiento. El procesamiento del reclamo “nbf” requiere que la fecha/hora actual DEBE ser posterior o igual a la fecha/hora no anterior listada en el reclamo “nbf”. Los implementadores PUEDEN proporcionar un pequeño margen de maniobra, por lo general no mayor de de unos pocos minutos, para tener en cuenta la desviación del reloj. Su valor DEBE ser un número que contenga un valor NumericDate. El uso de este reclamo es OPCIONAL.
public function setPassphrase( string $passphrase ): Builder;
public function setSubject( string $subject ): Builder;
El reclamo “sub” (asunto) identifica el principal que es el sujeto del JWT. Los reclamos en un JWT son normalmente sentencias sobre el asunto. El valor del asunto DEBE ser localmente único en el contexto del emisor o ser único globalmente. La tramitación de este reclamo es generalmente específica para la aplicación. El valor “sub” es una cadena sensible a mayúsculas y minúsculas que contiene un valor StringOrURI. El uso de este reclamo es OPCIONAL.
protected function setClaim( string $name, mixed $value ): Builder;
Sets a registered claim
Class Phalcon\Encryption\Security\JWT\Exceptions\UnsupportedAlgorithmException
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Exceptions |
|
Uses |
Exception |
|
Extends |
Exception |
Exception thrown when the algorithm is not supported for JWT
Class Phalcon\Encryption\Security\JWT\Exceptions\ValidatorException
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Exceptions |
|
Uses |
Exception |
|
Extends |
Exception |
Exception thrown when the validation does not pass for JWT
Abstract Class Phalcon\Encryption\Security\JWT\Signer\AbstractSigner
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Signer |
|
Implements |
SignerInterface |
Abstract class helping with the signer classes
Propiedades
/**
* @var string
*/
protected algorithm = "";
Métodos
public function getAlgorithm(): string;
Class Phalcon\Encryption\Security\JWT\Signer\Hmac
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Signer |
|
Uses |
Phalcon\Encryption\Security\JWT\Exceptions\UnsupportedAlgorithmException |
|
Extends |
AbstractSigner |
HMAC signing class
Métodos
public function __construct( string $algo = string );
Constructor Hmac.
public function getAlgHeader(): string;
Devuelve el valor que se utiliza para la cabecera “alg”
public function sign( string $payload, string $passphrase ): string;
Firma una carga útil usando la contraseña
public function verify( string $source, string $payload, string $passphrase ): bool;
Verificar una fuente pasada con una carga útil y una contraseña
Class Phalcon\Encryption\Security\JWT\Signer\None
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Signer |
|
Implements |
SignerInterface |
No signing class
Métodos
public function getAlgHeader(): string;
Devuelve el valor que se utiliza para la cabecera “alg”
public function getAlgorithm(): string;
Devuelve el algoritmo usado
public function sign( string $payload, string $passphrase ): string;
Firma una carga útil usando la contraseña
public function verify( string $source, string $payload, string $passphrase ): bool;
Verificar una fuente pasada con una carga útil y una contraseña
Interface Phalcon\Encryption\Security\JWT\Signer\SignerInterface
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Signer |
Interface for JWT Signer classes
Métodos
public function getAlgHeader(): string;
Devuelve el valor que se utiliza para la cabecera “alg”
public function getAlgorithm(): string;
Devuelve el algoritmo usado
public function sign( string $payload, string $passphrase ): string;
Firma una carga útil usando la contraseña
public function verify( string $source, string $payload, string $passphrase ): bool;
Verificar una fuente pasada con una carga útil y una contraseña
Abstract Class Phalcon\Encryption\Security\JWT\Token\AbstractItem
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Token |
Abstract helper class for Tokens
Propiedades
/**
* @var array
*/
protected data;
Métodos
public function getEncoded(): string;
Class Phalcon\Encryption\Security\JWT\Token\Enum
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Token |
Constants for Tokens. It offers constants for Headers as well as Claims
@link https://tools.ietf.org/html/rfc7519
Constantes
const ALGO = alg;
const AUDIENCE = aud;
const CONTENT_TYPE = cty;
const EXPIRATION_TIME = exp;
const ID = jti;
const ISSUED_AT = iat;
const ISSUER = iss;
const NOT_BEFORE = nbf;
const SUBJECT = sub;
const TYPE = typ;
Class Phalcon\Encryption\Security\JWT\Token\Item
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Token |
|
Extends |
AbstractItem |
Storage class for a Token Item
Métodos
public function __construct( array $payload, string $encoded );
Constructor Item.
public function get( string $name, mixed $defaultValue = null ): mixed | null;
public function getPayload(): array;
public function has( string $name ): bool;
Class Phalcon\Encryption\Security\JWT\Token\Parser
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Token |
|
Uses |
InvalidArgumentException, Phalcon\Support\Helper\Json\Decode |
Token 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.
Propiedades
/**
* @var Decode
*/
private decode;
Métodos
public function __construct( Decode $decode = null );
public function parse( string $token ): Token;
Analiza un token y lo devuelve
Class Phalcon\Encryption\Security\JWT\Token\Signature
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Token |
|
Extends |
AbstractItem |
Signature class containing the encoded data and the hash.
Métodos
public function __construct( string $hash = string, string $encoded = string );
Constructor Signature.
public function getHash(): string;
Class Phalcon\Encryption\Security\JWT\Token\Token
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT\Token |
|
Uses |
Phalcon\Encryption\Security\JWT\Signer\SignerInterface, Phalcon\Encryption\Security\JWT\Validator |
Token Class.
A container for Token related data. It stores the claims, headers, signature and payload. It also calculates and returns the token string.
@link https://tools.ietf.org/html/rfc7519
Propiedades
/**
* @var Item
*/
private claims;
/**
* @var Item
*/
private headers;
/**
* @var Signature
*/
private signature;
Métodos
public function __construct( Item $headers, Item $claims, Signature $signature );
Constructor Token.
public function getClaims(): Item;
Return the registered claims
public function getHeaders(): Item;
Return the registered headers
public function getPayload(): string;
Return the payload
public function getSignature(): Signature;
Return the signature
public function getToken(): string;
Return the token
public function validate( Validator $validator ): array;
public function verify( SignerInterface $signer, string $key ): bool;
Verify the signature
Class Phalcon\Encryption\Security\JWT\Validator
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security\JWT |
|
Uses |
Phalcon\Encryption\Security\JWT\Exceptions\ValidatorException, Phalcon\Encryption\Security\JWT\Signer\SignerInterface, Phalcon\Encryption\Security\JWT\Token\Enum, Phalcon\Encryption\Security\JWT\Token\Token |
Class Validator
Propiedades
/**
* @var array
*/
private claims;
/**
* @var array
*/
private errors;
/**
* @var int
*/
private timeShift = 0;
/**
* @var Token
*/
private token;
Métodos
public function __construct( Token $token, int $timeShift = int );
Constructor Validator.
public function get( string $claim ): mixed | null;
Return the value of a claim
public function getErrors(): array;
Return an array with validation errors (if any)
public function set( string $claim, mixed $value ): Validator;
Set the value of a claim, for comparison with the token values
public function setToken( Token $token ): Validator;
Set the token to be validated
public function validateAudience( mixed $audience ): Validator;
Validate the audience
public function validateExpiration( int $timestamp ): Validator;
Validate the expiration time of the token
public function validateId( string $id ): Validator;
Validate the id of the token
public function validateIssuedAt( int $timestamp ): Validator;
Validate the issued at (iat) of the token
public function validateIssuer( string $issuer ): Validator;
Validate the issuer of the token
public function validateNotBefore( int $timestamp ): Validator;
Validate the notbefore (nbf) of the token
public function validateSignature( SignerInterface $signer, string $passphrase ): Validator;
Validate the signature of the token
Class Phalcon\Encryption\Security\Random
Código fuente en GitHub
Namespace |
Phalcon\Encryption\Security |
Phalcon\Encryption\Security\Random
Clase generadora segura de números aleatorios.
Proporciona un generador seguro de números aleatorios que es adecuado para generar clave de sesión en cookies HTTP, etc.
Phalcon\Encryption\Security\Random
could be mainly useful for:
- Generación de claves (por ejemplo, generación de claves complicadas)
- Generando contraseñas aleatorias para nuevas cuentas de usuario
- Sistemas de cifrado
$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
echo $random->uuid(); // db082997-2572-4e2c-a046-5eefe97b1235
echo $random->uuid(); // da2aa0e2-b4d0-4e3c-99f5-f5ef62c57fe2
echo $random->uuid(); // 75e6b628-c562-4117-bb76-61c4153455a9
echo $random->uuid(); // dc446df1-0848-4d05-b501-4af3c220c13d
// 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); // 774SJD3vgP
Esta clase toma prestada parcialmente la librería SecureRandom de Ruby
@link https://ruby-doc.org/stdlib-2.2.2/libdoc/securerandom/rdoc/SecureRandom.html
Métodos
public function base58( int $len = null ): string;
Genera una cadena base58 aleatoria
Si $len no se especifica, se asume 16. Puede ser más grande en el futuro. El resultado puede contener caracteres alfanuméricos excepto 0, O, I y 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 @throws Exception If secure random number generator is not available or unexpected partial read
public function base62( int $len = null ): string;
Genera una cadena base62 aleatoria
Si $len no se especifica, se asume 16. Puede ser más grande en el futuro.
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 @throws Exception If secure random number generator is not available or unexpected partial read
public function base64( int $len = null ): string;
Genera una cadena base64 aleatoria
Si $len no se especifica, se asume 16. Puede ser más grande en el futuro. La longitud de la cadena resultante suele ser mayor de $len. Fórmula del tamaño: 4 * ($len / 3) y redondeado a un múltiplo de 4.
$random = new \Phalcon\Encryption\Security\Random();
echo $random->base64(12); // 3rcq39QzGK9fUqh8
@throws Exception If secure random number generator is not available or unexpected partial read
public function base64Safe( int $len = null, bool $padding = bool ): string;
Genera una cadena base64 de URL segura aleatoria
Si $len no se especifica, se asume 16. Puede ser más grande en el futuro. La longitud de la cadena resultante suele ser mayor de $len.
Por defecto, el relleno no se genera porque “=” se puede usar como un delimitador de URL. El resultado puede contener A-Z, a-z, 0-9, “-“ y “_”. “=” también se usa si $padding es verdadero. Consulte RFC 3548 para la definición de base64 segura para URL.
$random = new \Phalcon\Encryption\Security\Random();
echo $random->base64Safe(); // GD8JojhzSTrqX7Q8J6uug
@link https://www.ietf.org/rfc/rfc3548.txt @throws Exception If secure random number generator is not available or unexpected partial read
public function bytes( int $len = int ): string;
Genera una cadena binaria aleatoria
El método Random::bytes
devuelve una cadena y acepta como entrada un entero representando la longitud en bytes a devolver.
Si $len no se especifica, se asume 16. Puede ser más grande en el futuro. El resultado puede contener cualquier byte: “x00” - “xFF”.
$random = new \Phalcon\Encryption\Security\Random();
$bytes = $random->bytes();
var_dump(bin2hex($bytes));
// Possible output: string(32) "00f6c04b144b41fad6a59111c126e1ee"
@throws Exception If secure random number generator is not available or unexpected partial read
public function hex( int $len = null ): string;
Genera una cadena hexadecimal aleatoria
Si $len no se especifica, se asume 16. Puede ser más grande en el futuro. La longitud de la cadena resultante suele ser mayor de $len.
$random = new \Phalcon\Encryption\Security\Random();
echo $random->hex(10); // a29f470508d5ccb8e289
@throws Exception If secure random number generator is not available or unexpected partial read
public function number( int $len ): int;
Genera un número aleatorio entre 0 y $len
Returns an integer: 0 <= result <= $len.
$random = new \Phalcon\Encryption\Security\Random();
echo $random->number(16); // 8
@throws Exception If secure random number generator is not available, unexpected partial read or $len <= 0
public function uuid(): string;
Genera un UUID aleatorio v4 (IDentificador Único Universal)
La versión 4 de UUID es puramente aleatoria (excepto la versión). No contiene información significativa como dirección MAC, hora, etc. Ver RFC 4122 para detalles del UUID.
Este algoritmo establece el número de versión (4 bits) así como dos bits reservados. Todos los demás bits (los 122 bits restantes) se establecen usando una fuente de datos aleatoria o pseudoaleatoria. Los UUID de versión 4 tienen la forma xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx donde x es cualquier dígito hexadecimal e y es uno de 8, 9, A o B (p. ej., f47ac10b-58cc-4372-a567-0e02b2c3d479).
$random = new \Phalcon\Encryption\Security\Random();
echo $random->uuid(); // 1378c906-64bb-4f81-a8d6-4ae1bfcdec22
@link https://www.ietf.org/rfc/rfc4122.txt @throws Exception If secure random number generator is not available or unexpected partial read
protected function base( string $alphabet, int $base, mixed $n = null ): string;
Genera una cadena aleatoria basada en el número ($base) de caracteres ($alphabet).
Si $n no se especifica, se asume 16. Puede ser más grande en el futuro.
@throws Exception If secure random number generator is not available or unexpected partial read