Saltar al contenido principal
Versión: Siguiente

CryptoKey

The CryptoKey class in the 4D language encapsulates an asymmetric encryption key pair.

This class is available from the 4D class store.

Ejemplo

El siguiente código de ejemplo firma y verifica un mensaje utilizando un nuevo par de llaves ECDSA, por ejemplo para hacer un token web JSON ES256.

 // Generar un nuevo par de llaves ECDSA
$key:=4D.CryptoKey.new(New object("type";"ECDSA";"curve";"prime256v1"))

// Obtener la firma como base64
$message:="hello world"
$signature:=$key.sign($message;New object("hash";"SHA256"))

// Verificar firma
$status:=$key.verify($message;$signature;New object("hash";"SHA256"))
ASSERT($status.success)

Resumen

| 4D.CryptoKey.new( settings : Object ) : 4D.CryptoKey
creates a new 4D.CryptoKey object encapsulating an encryption key pair | | .curve : Text
nombre de la curva normalizada de la llave | | .decrypt( message : Text ; options : Object ) : Object
decrypts the message parameter using the private key | | .encrypt( message : Text ; options : Object ) : Text
encrypts the message parameter using the public key | | .getPrivateKey() : Text
returns the private key of the CryptoKey object | | .getPublicKey() : Text
returns the public key of the CryptoKey object | | .sign (message : Text ; options : Object) : Text
signs the utf8 representation of a message string | | .size : Integer
el tamaño de la llave en bits | | .type : Text
name of the key type - "RSA", "ECDSA", "PEM" | | .verify( message : Text ; signature : Text ; options : Object) : object
verifies the base64 signature against the utf8 representation of message |

4D.CryptoKey.new()

Historia
LanzamientoModificaciones
18 R4Añadidos

4D.CryptoKey.new( settings : Object ) : 4D.CryptoKey

ParámetrosTipoDescripción
settingsObject->Parámetros para generar o cargar un par de llaves
result4D.CryptoKey<-Objeto que encapsula un par de llaves de cifrado

The 4D.CryptoKey.new() function creates a new 4D.CryptoKey object encapsulating an encryption key pair, based upon the settings object parameter. Permite generar una nueva llave RSA o ECDSA, o cargar un par de llaves existente desde una definición PEM.

settings

PropiedadTipoDescripción
typetextDefines the type of the key to create:
  • "RSA": generates a RSA key pair, using .size as size.
  • "ECDSA": generates an Elliptic Curve Digital Signature Algorithm key pair, using .curve as curve. Note that ECDSA keys cannot be used for encryption but only for signature.
  • "PEM": loads a key pair definition in PEM format, using .pem.
  • curvetextNombre de la curva ECDSA
    pemtextDefinición PEM de una llave de cifrado a cargar
    sizeintegerTamaño de la llave RSA en bits

    CryptoKey

    The returned CryptoKey object encapsulates an encryption key pair. Es un objeto compartido y, por tanto, puede ser utilizado por varios procesos 4D simultáneamente.

    .curve

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .curve : Text

    Definido sólo para las llaves ECDSA: el nombre de la curva normalizada de la llave. Generalmente "prime256v1" para ES256 (por defecto), "secp384r1" para ES384, "secp521r1" para ES512.

    .decrypt()

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .decrypt( message : Text ; options : Object ) : Object

    ParámetrosTipoDescripción
    messageText->Message string to be decoded using options.encodingEncrypted and decrypted.
    optionsObject->Opciones de decodificación
    ResultObject<-Estado

    The .decrypt() function decrypts the message parameter using the private key. El algoritmo utilizado depende del tipo de la llave.

    The key must be a RSA key, the algorithm is RSA-OAEP (see RFC 3447).

    opciones

    PropiedadTipoDescripción
    hashtextAlgoritmo Digest a utilizar. Por ejemplo: "SHA256", "SHA384" o "SHA512".
    encodingEncryptedtextEncoding used to convert the message parameter into the binary representation to decrypt. Puede ser "Base64", o "Base64URL". Por defecto es "Base64".
    encodingDecryptedtextCodificación utilizada para convertir el mensaje binario descifrado en la cadena de resultados. Puede ser "UTF-8", "Base64", o "Base64URL". Por defecto es "UTF-8".

    Resultado

    The function returns a status object with success property set to true if the message could be successfully decrypted.

    PropiedadTipoDescripción
    successbooleanTrue si el mensaje ha sido descifrado con éxito
    resulttextMessage decrypted and decoded using the options.encodingDecrypted
    errorscollectionIf success is false, may contain a collection of errors

    In case the message couldn't be decrypted because it was not encrypted with the same key or algorithm, the status object being returned contains an error collection in status.errors.

    .encrypt()

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .encrypt( message : Text ; options : Object ) : Text

    ParámetrosTipoDescripción
    messageText->Message string to be encoded using options.encodingDecrypted and encrypted.
    optionsObject->Opciones de codificación
    ResultText<-Message encrypted and encoded using the options.encodingEncrypted

    The .encrypt() function encrypts the message parameter using the public key. El algoritmo utilizado depende del tipo de la llave.

    The key must be a RSA key, the algorithm is RSA-OAEP (see RFC 3447).

    opciones
    PropiedadTipoDescripción
    hashtextAlgoritmo Digest a utilizar. Por ejemplo: "SHA256", "SHA384" o "SHA512".
    encodingEncryptedtextCodificación utilizada para convertir el mensaje binario encriptado en la cadena de resultados. Puede ser "Base64", o "Base64URL". Por defecto es "Base64".
    encodingDecryptedtextEncoding used to convert the message parameter into the binary representation to encrypt. Puede ser "UTF-8", "Base64", o "Base64URL". Por defecto es "UTF-8".

    Resultado

    El valor devuelto es un mensaje encriptado.

    .getPrivateKey()

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .getPrivateKey() : Text

    ParámetrosTipoDescripción
    ResultText<-Llave privada en formato PEM

    The .getPrivateKey() function returns the private key of the CryptoKey object in PEM format, or an empty string if none is available.

    Resultado

    El valor devuelto es la llave privada.

    .getPublicKey()

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .getPublicKey() : Text

    ParámetrosTipoDescripción
    ResultText<-Llave pública en formato PEM

    The .getPublicKey() function returns the public key of the CryptoKey object in PEM format, or an empty string if none is available.

    Resultado

    El valor devuelto es la llave pública.


    .pem

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .pem : Text

    Definición PEM de una llave de cifrado a cargar. Si la llave es una llave privada, se deducirá de ella la llave pública RSA o ECDSA.

    .sign()

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .sign (message : Text ; options : Object) : Text

    ParámetrosTipoDescripción
    messageText->Cadena mensaje a firmar
    optionsObject->Opciones de firma
    ResultText<-Firma en representación Base64 o Base64URL, según la opción "encoding

    The .sign() function signs the utf8 representation of a message string using the CryptoKey object keys and provided options. It returns its signature in base64 or base64URL format, depending on the value of the options.encoding attribute you passed.

    The CryptoKey must contain a valid private key.

    opciones

    PropiedadTipoDescripción
    hashtextAlgoritmo Digest a utilizar. Por ejemplo: "SHA256", "SHA384" o "SHA512". Cuando se utiliza para producir un JWT, el tamaño del hash debe coincidir con el tamaño del algoritmo PS@, ES@, RS@ o PS@
    encodingEncryptedtextCodificación utilizada para convertir el mensaje binario encriptado en la cadena de resultados. Puede ser "Base64", o "Base64URL". Por defecto es "Base64".
    pssbooleanUtilice el Probabilistic Signature Scheme (PSS). Se ignora si la llave no es una llave RSA. Pass true when producing a JWT for PS@ algorithm
    encodingtextRepresentation of provided signature. Possible values are "Base64" or "Base64URL". Por defecto es "Base64".

    Resultado

    The utf8 representation of the message string.

    .size

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .size : Integer

    Definido sólo para llaves RSA: el tamaño de la llave en bits. .

    .type

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .type : Text

    Contains the name of the key type - "RSA", "ECDSA", "PEM" .

    • "RSA": un par de llaves RSA, utilizando settings.size como .size.
    • "ECDSA": un par de llaves del Algoritmo de Firma Digital de Curva Elíptica, utilizando settings.curve como .curve. Tenga en cuenta que las llaves ECDSA no pueden utilizarse para el cifrado, sino sólo para la firma.
    • "PEM": a key pair definition in PEM format, using settings.pem as .pem.

    .verify()

    Historia
    LanzamientoModificaciones
    18 R4Añadidos

    .verify( message : Text ; signature : Text ; options : Object) : object

    ParámetrosTipoDescripción
    messageText->Cadena mensaje utilizada para generar la firma
    signatureText->Signature to verify, in Base64 or Base64URL representation, depending on options.encoding value
    optionsObject->Opciones de firma
    ResultObject<-Estado de la verificación

    The .verify() function verifies the base64 signature against the utf8 representation of message using the CryptoKey object keys and provided options.

    The CryptoKey must contain a valid public key.

    opciones

    PropiedadTipoDescripción
    hashtextAlgoritmo Digest a utilizar. Por ejemplo: "SHA256", "SHA384" o "SHA512". Cuando se utiliza para producir un JWT, el tamaño del hash debe coincidir con el tamaño del algoritmo PS@, ES@, RS@ o PS@
    pssbooleanUtilice el Probabilistic Signature Scheme (PSS). Se ignora si la llave no es una llave RSA. Pass true when verifying a JWT for PS@ algorithm
    encodingtextEncoding used to convert the binary encrypted message into the result string. Can be "Base64", or "Base64URL". Por defecto es "Base64".

    Resultado

    The function returns a status object with success property set to true if message could be successfully verified (i.e. the signature matches).

    In case the signature couldn't be verified because it was not signed with the same message, key or algorithm, the status object being returned contains an error collection in status.errors.

    PropiedadTipoDescripción
    successbooleanTrue si la firma coincide con el mensaje
    errorscollectionIf success is false, may contain a collection of errors