Saltar para o conteúdo principal
Versão: 20 R5 BETA

CryptoKey

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

This class is available from the 4D class store.

Exemplo

O código abaixo de exemplo firma e verifica uma mensagem utilizando um novo par de chaves ECDSA, por exemplo para criar um token web JSON ES256.

 // Generate a new ECDSA key pair
$key:=4D. CryptoKey.new(New object("type";"ECDSA";"curve";"prime256v1"))

// Get signature as base64
$message:="hello world"
$signature:=$key.sign($message;New object("hash";"SHA256"))

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

Resumo

| 4D.CryptoKey.new( settings : Object ) : 4D.CryptoKey    creates a new 4D.CryptoKey object encapsulating an encryption key pair | | .curve : Text    normalised curve name of the key | | .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    the size of the key in 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()

História
ReleaseMudanças
18 R4Adicionado

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

ParâmetroTipoDescrição
settingsObject->Parâmetros para gerar ou carregar um par de chaves
result4D. CryptoKey<-Object encapsulating an encryption key pair

The 4D.CryptoKey.new() function creates a new 4D.CryptoKey object encapsulating an encryption key pair, based upon the settings object parameter. Permite gerar uma nova chave RSA o ECDSA, ou carregar um par de chaves existente desde uma definição PEM.

parâmetros

PropriedadeTipoDescrição
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.
  • curvetextNome da curva ECDSA
    pemtextDefinição PEM de uma chave de cifrado a carregar
    sizeintegerTamanho da chave RSA em bits

    CryptoKey

    The returned CryptoKey object encapsulates an encryption key pair. É um objeto compartido e, portanto, pode ser utilizado por vários processos 4D simultaneamente.

    .curve

    História
    ReleaseMudanças
    18 R4Adicionado

    .curve : Text

    Defined only for ECDSA keys: the normalised curve name of the key. Normalmente "prime256v1" para ES256 (por defeito), "secp384r1" para ES384, "secp521r1" para ES512.

    .decrypt()

    História
    ReleaseMudanças
    18 R4Adicionado

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

    ParâmetroTipoDescrição
    messageText->Message string to be decoded using options.encodingEncrypted and decrypted.
    optionsObject->Opções de codificação
    ResultadosObject<-Estado

    The .decrypt() function decrypts the message parameter using the private key. O algoritmo utilizado depende do tipo da chave.

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

    opções

    PropriedadeTipoDescrição
    hashtextAlgoritmo Digest a utilizar. Por exemplo: "SHA256", "SHA384", ou "SHA512".
    encodingEncryptedtextEncoding used to convert the message parameter into the binary representation to decrypt. Pode ser "Base64", ou "Base64URL". Por padrão é "Base64".
    encodingDecryptedtextCodificação utilizada para converter a mensagem binário decifrado na string de resultados. Pode ser "UTF-8", "Base64" ou "Base64URL". Por padrão é "UTF-8".

    Resultado

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

    PropriedadeTipoDescrição
    successbooleanTrue se a mensagem tiver sido decifrada com ê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()

    História
    ReleaseMudanças
    18 R4Adicionado

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

    ParâmetroTipoDescrição
    messageText->Message string to be encoded using options.encodingDecrypted and encrypted.
    optionsObject->Opções de decodificação
    ResultadosText<-Message encrypted and encoded using the options.encodingEncrypted

    The .encrypt() function encrypts the message parameter using the public key. O algoritmo utilizado depende do tipo da chave.

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

    opções
    PropriedadeTipoDescrição
    hashtextAlgoritmo Digest a utilizar. Por exemplo: "SHA256", "SHA384", ou "SHA512".
    encodingEncryptedtextCodificação utilizada para converter a mensagem binária criptografada na string resultante. Pode ser "Base64", ou "Base64URL". Por padrão é "Base64".
    encodingDecryptedtextEncoding used to convert the message parameter into the binary representation to encrypt. Pode ser "UTF-8", "Base64" ou "Base64URL". Por padrão é "UTF-8".

    Resultado

    O valor devolvido é uma mensagem encriptada.

    .getPrivateKey()

    História
    ReleaseMudanças
    18 R4Adicionado

    .getPrivateKey() : Text

    ParâmetroTipoDescrição
    ResultadosText<-Chave privada em 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

    O valor devolvido é a chave privada.

    .getPublicKey()

    História
    ReleaseMudanças
    18 R4Adicionado

    .getPublicKey() : Text

    ParâmetroTipoDescrição
    ResultadosText<-Chave pública em 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

    O valor devolvido é a chave pública.


    .pem

    História
    ReleaseMudanças
    18 R4Adicionado

    .pem : Text

    Definição PEM de uma chave de cifrado a carregar. Se a chave for uma chave privada, será deduzido dela a chave pública RSA ou ECDSA.

    .sign()

    História
    ReleaseMudanças
    18 R4Adicionado

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

    ParâmetroTipoDescrição
    messageText->String mensagem a assinar
    optionsObject->Opções de assinatura
    ResultadosText<-Signature in Base64 or Base64URL representation, depending on "encoding" option

    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.

    opções

    PropriedadeTipoDescrição
    hashtextAlgoritmo Digest a utilizar. Por exemplo: "SHA256", "SHA384", ou "SHA512". Quando utilizar para produzir um JWT, o tamanho de hash deve coincidir com o tamanho do algoritmo PS@, ES@, RS@ ou PS@
    encodingEncryptedtextCodificação utilizada para converter a mensagem binária criptografada na string resultante. Pode ser "Base64", ou "Base64URL". Por padrão é "Base64".
    pssbooleanUtiliza Probabilistic Signature Scheme (PSS). Ignorado se a chave não for uma chave RSA. Pass true when producing a JWT for PS@ algorithm
    encodingtextRepresentation of provided signature. Possible values are "Base64" or "Base64URL". Por padrão é "Base64".

    Resultado

    The utf8 representation of the message string.

    .size

    História
    ReleaseMudanças
    18 R4Adicionado

    .size : Integer

    Defined only for RSA keys: the size of the key in bits. .

    .type

    História
    ReleaseMudanças
    18 R4Adicionado

    .type : Text

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

    • "RSA": an RSA key pair, using settings.size as .size.
    • "ECDSA": an Elliptic Curve Digital Signature Algorithm key pair, using settings.curve as .curve. Lembre que chaves ECDSA não podem ser usadas para a criptografia mas só pela assinatura.
    • "PEM": a key pair definition in PEM format, using settings.pem as .pem.

    .verify()

    História
    ReleaseMudanças
    18 R4Adicionado

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

    ParâmetroTipoDescrição
    messageText->String de mensagem utilizada para gerar a assinatura
    signatureText->Signature to verify, in Base64 or Base64URL representation, depending on options.encoding value
    optionsObject->Opções de assinatura
    ResultadosObject<-Estado da verificação

    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.

    opções

    PropriedadeTipoDescrição
    hashtextAlgoritmo Digest a utilizar. Por exemplo: "SHA256", "SHA384", ou "SHA512". Quando utilizar para produzir um JWT, o tamanho de hash deve coincidir com o tamanho do algoritmo PS@, ES@, RS@ ou PS@
    pssbooleanUtiliza Probabilistic Signature Scheme (PSS). Ignorado se a chave não for uma chave RSA. Pass true when verifying a JWT for PS@ algorithm
    encodingtextCodificação utilizada para converter a mensagem binária criptografada na string resultante. Pode ser "Base64", ou "Base64URL". Por padrão é "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.

    PropriedadeTipoDescrição
    successbooleanTrue se a assinatura corresponder com a mensagem
    errorscollectionIf success is false, may contain a collection of errors