This module contains functions to perform cryptographic operations in XQuery. The cryptographic module was based on a draft of the EXPath Cryptographic Module. It provides the following functionality: creation of message authentication codes (HMAC), derivation of keys from passwords, password hashing, creation and verification of signatures, generation and conversion of keys, secure random bytes, encryption and decryption, and creation and validation of XML Digital Signatures.
All functions are in the http://expath.org/ns/crypto namespace, to which the crypto prefix is statically bound.
All errors are in the http://expath.org/ns/error namespace, to which the experr prefix is statically bound.
| Signature | crypto:hmac( $value as (xs:string | xs:base64Binary | xs:hexBinary), $key as (xs:string | xs:base64Binary | xs:hexBinary), $algorithm as xs:string, $encoding as xs:string? := ()) as xs:string |
|---|
| Summary | Creates an authentication code for the specified $value via a cryptographic hash function:
$value must be a string or binary item.$key must not be empty.$algorithm describes the hash algorithm which is used for encryption. Currently supported are md5, sha1, sha256, sha384, sha512. Default is md5.$encoding must either be hex or base64; it specifies the encoding of the returned authentication code. Default is base64.
|
|---|
| Errors | CX0013 | The hashing algorithm is not supported. | CX0014 | The encoding method is not supported. | CX0019 | The key is invalid. |
|
|---|
| Examples | crypto:hmac('message', 'secretkey', 'md5', 'hex') Return the message authentication code 34D1E3818B347252A75A4F6D747B21C2. |
|---|
| Signature | crypto:pbkdf2( $password as xs:string, $salt as (xs:string | xs:base64Binary | xs:hexBinary), $iterations as xs:integer, $length as xs:integer, $algorithm as xs:string? := ()) as xs:hexBinary |
|---|
| Summary | Derives a key from the specified $password with PBKDF2 (Password-Based Key Derivation Function 2). The function is suited for storing passwords, as each derivation takes a configurable amount of time:
$salt must not be empty. It should be random and unique for each password; it can be stored along with the derived key.$iterations is the number of hash iterations. A high value (600,000 or more for SHA-256) slows down brute-force attacks.$length is the length of the derived key in bytes.$algorithm is the hash algorithm of the underlying HMAC. Supported are SHA-1, SHA-224, SHA-256, SHA-384, SHA-512, SHA-512/224 and SHA-512/256. Default is SHA-256.
|
|---|
| Errors | CX0013 | The hashing algorithm is not supported. | CX0019 | The key is invalid. |
|
|---|
| Examples | crypto:pbkdf2('password', 'salt', 4096, 32) Return the derived key C5E478D59288C841AA530DB6845C4C8D962893A001CE4E11A4963873AA98134A.
let $salt := crypto:random-bytes(16)
let $key := crypto:pbkdf2('secret', $salt, 600000, 32)
return db:put-value('users', { 'salt': $salt, 'key': $key }, 'jane') Store the salt and the derived key of a user password; a login attempt is checked by deriving the key again with the stored salt. crypto:hash-password does the same in a single string. |
|---|
crypto:hash-password and crypto:verify-password store passwords as self-describing strings in the PHC string format: $argon2id$v=19$m=19456,t=2,p=1$salt$hash for Argon2id and $pbkdf2-sha256$i=600000$salt$hash for PBKDF2, with the salt and the hash encoded as Base64 without padding. The scheme, its parameters and a random salt are included, so the parameters can be changed later without invalidating stored hashes. Argon2id hashes are compatible with other implementations of the format, such as libsodium.
Added: New function.
| Signature | crypto:hash-password( $password as xs:string, $options as map(*)? := {}) as xs:string |
|---|
| Summary | Hashes the specified $password with a random salt, and returns the hash in the PHC string format. The following $options are available:
| option | default | description |
|---|
scheme | argon2id | Hashing scheme: argon2id (Argon2id, memory-hard) or pbkdf2 (PBKDF2, for environments that require FIPS-approved algorithms). | iterations | 2 or 600000 | Number of passes (Argon2id, default: 2) or iterations (PBKDF2, default: 600000). | memory | 19456 | Memory size in KiB (Argon2id only): at least 8 times parallelism, at most 262144 (256 MiB). | parallelism | 1 | Number of lanes (Argon2id only). | hash | SHA-256 | Hash algorithm of the underlying HMAC (PBKDF2 only): SHA-1, SHA-256, SHA-384 or SHA-512. | salt-length | 16 | Length of the random salt in bytes (Argon2id: at least 8; at most 1024). | length | 32 | Length of the hash in bytes (Argon2id: at least 4; at most 1024). |
The defaults follow the OWASP recommendations. Options of the other scheme are rejected.
|
|---|
| Errors | CX0013 | The hashing algorithm is not supported. | CX0021 | The algorithm is not supported. |
|
|---|
| Examples | db:put-value('users', crypto:hash-password('secret'), 'jane') Stores the Argon2id hash of a user password.
crypto:hash-password('secret', { 'scheme': 'pbkdf2' }) Returns a PBKDF2 hash, e.g. $pbkdf2-sha256$i=600000$…. |
|---|
Added: New function.
| Signature | crypto:verify-password( $password as xs:string, $hash as xs:string) as xs:boolean |
|---|
| Summary | Checks if the specified $password matches a $hash created by crypto:hash-password. The hashes are compared in constant time. |
|---|
| Errors | CX0030 | The password hash is invalid. |
|
|---|
| Examples | crypto:verify-password(
'password',
'$pbkdf2-sha256$i=4096$c2FsdA$xeR41ZKIyEGqUw22hFxMjZYok6ABzk4RpJY4c6qYE0o'
) Result: true(). Uses a PBKDF2 test vector from RFC 7914.
crypto:verify-password(
'password',
'$argon2id$v=19$m=64,t=2,p=1$c29tZXNhbHQ$FqGkmHNGCd0BRW2kBt6fPZ2pPmyGwwChL8FGUhTOSSI'
) Result: true(). Checks an Argon2id hash with a small memory size. |
|---|
The algorithms of crypto:sign, crypto:verify, crypto:encrypt, crypto:decrypt, crypto:derive and crypto:generate-key are named as in the Web Cryptography API. The $algorithm argument is either a string (the algorithm name) or a map with the name and additional parameters. Names are case-insensitive. Hash names are SHA-1, SHA-256, SHA-384 and SHA-512 (the hyphen is optional). Each function only accepts algorithms of its purpose. The parameters for key generation (length, modulus-length, named-curve) are only accepted by crypto:generate-key, which in turn only accepts them and hash.
| Name |
Purpose |
Key type |
Parameters |
HMAC |
signatures (MAC) |
secret key |
hash (mandatory); key generation: length in bits (default: block size of the hash, e.g. 512 for SHA-256; minimum: length of the hash, e.g. 256; maximum: 8192) |
RSASSA-PKCS1-v1_5 |
signatures |
RSA |
hash (mandatory for signatures); key generation: modulus-length in bits (default: 2048, maximum: 16384) |
RSA-PSS |
signatures |
RSA |
hash (mandatory for signatures), salt-length (default: length of the hash); key generation: modulus-length in bits (default: 2048, maximum: 16384) |
ECDSA |
signatures |
EC (curves P-256, P-384, P-521) |
hash (mandatory for signatures), signature-format: p1363 (concatenated r and s values, as in JWS; default) or der; key generation: named-curve (mandatory) |
Ed25519, Ed448 |
signatures |
EdDSA |
– |
AES-CBC |
encryption |
secret key (16, 24 or 32 bytes) |
iv (16 bytes); key generation: length in bits (128, 192 or 256; default: 256) |
AES-GCM |
encryption |
secret key (16, 24 or 32 bytes) |
iv (12 bytes recommended), additional-data (authenticated, but not encrypted), tag-length in bits (default: 128); key generation: length in bits (128, 192 or 256; default: 256) |
RSA-OAEP |
encryption |
RSA |
hash (mandatory; also used for MGF1); key generation: modulus-length in bits (default: 2048, maximum: 16384) |
HKDF |
key derivation |
secret key |
hash (mandatory), salt, info (strings or binary items) |
ECDH |
key agreement |
EC (curves P-256, P-384, P-521) |
public (mandatory: public key of the other party); key generation: named-curve (mandatory) |
X25519 |
key agreement |
X25519 |
public (mandatory: public key of the other party) |
The algorithm must always be supplied and is never derived from the key or from the processed data: if an algorithm is taken from untrusted input (such as the alg header of a JWT), an attacker can choose a weaker algorithm. The names of JSON Web Algorithms (HS256, RS256, ES256, EdDSA, A256GCM, …) are not supported: they can be mapped to the corresponding algorithm maps in the application code, e.g. HS256 to { 'name': 'HMAC', 'hash': 'SHA-256' }.
Keys are accepted in the following formats:
- A string or binary item with a PEM block (
-----BEGIN …-----) is parsed as PEM key; text before the block is ignored. Supported types are PUBLIC KEY (X.509 SubjectPublicKeyInfo), PRIVATE KEY (PKCS #8), RSA PUBLIC KEY and RSA PRIVATE KEY (legacy PKCS #1 format), EC PRIVATE KEY (SEC1 format, as written by openssl ecparam -genkey; a preceding EC PARAMETERS block is skipped), and CERTIFICATE (X.509 certificate; the public key is extracted, the certificate chain is not validated). Encrypted private keys are rejected; they can be decrypted with openssl pkcs8 -topk8 -nocrypt. - Any other string is a secret key (UTF-8 encoded).
- Any other binary item is a key in DER format (X.509 SubjectPublicKeyInfo or certificate for public keys, PKCS #8 for private keys) or, for secret-key algorithms, the raw secret key.
- A map is a JSON Web Key (JWK) with the key type
kty: RSA (n, e, plus d and optionally p, q, dp, dq, qi for private keys), EC (crv, x, y, plus d), OKP (crv with Ed25519, Ed448 or X25519, x, plus d) or oct (k). Unknown members are ignored. If use, key_ops or alg are supplied, they must match the operation and the algorithm.
The key must match the algorithm: for example, an RSA key cannot be used for ECDSA, and a PEM key cannot be used for HMAC. A public key is required for verification and encryption, and a private key for signing, decryption and key agreement; a JWK with a private part can be used for both.
crypto:sign and crypto:verify create and verify signatures and message authentication codes of strings and binary items. They can be used to process JSON Web Tokens (JWT), webhook signatures, signed URLs and other signed data.
Added: New function.
| Signature | crypto:sign( $value as (xs:string | xs:base64Binary | xs:hexBinary), $key as (xs:string | xs:base64Binary | xs:hexBinary | map(*)), $algorithm as (xs:string | map(*))) as xs:base64Binary |
|---|
| Summary | Creates a signature or message authentication code for the specified $value with the specified key and algorithm. Strings are UTF-8 encoded. |
|---|
| Errors | CX0013 | The hashing algorithm is not supported. | CX0019 | The key is invalid. | CX0021 | The algorithm is not supported. | CX0027 | Signature cannot be processed. Added to the official specification. | CX0029 | The key does not match the algorithm or the operation. |
|
|---|
| Examples | crypto:sign('message', 'secret', { 'name': 'HMAC', 'hash': 'SHA-256' })
=> bin:to-base64url() Result: 'i19IcCmVwVmMVz2x4hhmqbgl1KeU0WnXBgoDYFeWNgs'
crypto:sign(
'message',
file:read-text('private.pem'),
{ 'name': 'RSASSA-PKCS1-v1_5', 'hash': 'SHA-256' }
) Sign data with an RSA private key in PEM format, e.g. created via openssl genpkey -algorithm RSA -out private.pem.
let $hs256 := { 'name': 'HMAC', 'hash': 'SHA-256' }
let $secret := 'wJalrXUtnFEMI/K7MDENG+bPxRfiCYEXAMPLEKEY'
return fold-left(
('20120215', 'us-east-1', 'iam', 'aws4_request'),
`AWS4{ $secret }`,
fn($key, $data) { crypto:sign($data, $key, $hs256) }
) => xs:hexBinary() => string() Result: 'F4780E2D9F65FA895F9C67B32CE1BAF0B0D8A43505A000A1A9E090D414DB404D'. Derives the signing key of the AWS Signature Version 4 example: each authentication code is used as binary key of the next step. |
|---|
Added: New function.
| Signature | crypto:verify( $value as (xs:string | xs:base64Binary | xs:hexBinary), $signature as (xs:base64Binary | xs:hexBinary), $key as (xs:string | xs:base64Binary | xs:hexBinary | map(*)), $algorithm as (xs:string | map(*))) as xs:boolean |
|---|
| Summary | Checks if $signature is a valid signature or message authentication code of the specified $value for the specified key and algorithm. Strings are UTF-8 encoded. false is returned for wrong or malformed signatures; message authentication codes are compared in constant time. |
|---|
| Errors | CX0013 | The hashing algorithm is not supported. | CX0019 | The key is invalid. | CX0021 | The algorithm is not supported. | CX0029 | The key does not match the algorithm or the operation. |
|
|---|
| Examples | let $hs256 := { 'name': 'HMAC', 'hash': 'SHA-256' }
let $signature := crypto:sign('message', 'secret', $hs256)
return crypto:verify('message', $signature, 'secret', $hs256) Result: true()
let $jwt := 'eyJhbGciOiJFZERTQSJ9.RXhhbXBsZSBvZiBFZDI1NTE5IHNpZ25pbmc.hgyY0il_MGCjP0JzlnLWG1PPOt7-09PGcvMg3AIbQR6dWbhijcNR4ki4iylGjg5BhVsPt9g7sVvpAr_MuM0KAg'
let $jwk := {
'kty': 'OKP', 'crv': 'Ed25519',
'x': '11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo'
}
let $parts := tokenize($jwt, '\.')
return crypto:verify(
`{ $parts[1] }.{ $parts[2] }`,
bin:from-base64url($parts[3]),
$jwk,
'Ed25519'
) Result: true(). Verifies the signature of a JSON Web Token (example from RFC 8037) with a public key in JWK format. |
|---|
Added: New function.
| Signature | crypto:generate-key( $algorithm as (xs:string | map(*))) as map(*) |
|---|
| Summary | Generates a key for the specified algorithm. For HMAC, a JSON Web Key with a random secret is returned. For the other algorithms, a key pair is returned as map with the entries public and private, both JSON Web Keys. The parameters for key generation are listed in the algorithm table. The keys can be converted to other formats with crypto:export-key. |
|---|
| Errors | CX0013 | The hashing algorithm is not supported. | CX0021 | The algorithm is not supported. |
|
|---|
| Examples | let $keys := crypto:generate-key({ 'name': 'ECDSA', 'named-curve': 'P-256' })
return map:keys($keys?public) Result: 'kty', 'crv', 'x', 'y'
let $keys := crypto:generate-key({ 'name': 'ECDSA', 'named-curve': 'P-256' })
let $alg := { 'name': 'ECDSA', 'hash': 'SHA-256' }
let $signature := crypto:sign('message', $keys?private, $alg)
return crypto:verify('message', $signature, $keys?public, $alg) Result: true() |
|---|
Added: New function.
| Signature | crypto:export-key( $key as (xs:string | xs:base64Binary | xs:hexBinary | map(*)), $format as enum('jwk', 'pem', 'spki', 'pkcs8', 'raw')) as item() |
|---|
| Summary | Converts the specified $key, supplied in one of the formats described in Keys, to the specified $format. A string that is no PEM key is treated as secret key, and a binary item must be a key in DER format; binary secret keys can be supplied as JWK, e.g. { 'kty': 'oct', 'k': bin:to-base64url($bytes) }. Private keys are exported as private keys, unless a public format is requested:
jwk: JSON Web Key (map).pem: PEM string (PUBLIC KEY or PRIVATE KEY).spki: DER-encoded public key (X.509 SubjectPublicKeyInfo; xs:base64Binary).pkcs8: DER-encoded private key (PKCS #8; xs:base64Binary).raw: Secret key, or public EC point (uncompressed) or EdDSA key (xs:base64Binary).
The public key of an EdDSA private key in PEM or DER format cannot be derived, and the key cannot be exported as JWK or in a public format.
|
|---|
| Errors | |
|---|
| Examples | crypto:export-key({
'kty': 'OKP', 'crv': 'Ed25519',
'x': '11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo'
}, 'pem') Returns the public key as PEM string with the Base64 body MCowBQYDK2VwAyEA11qYAYKxCrfVS/7TyWQHOg7hcvPapiMlrwIaaPcHURo=.
crypto:export-key(file:read-text('private.pem'), 'jwk') Converts a private key in PEM format to a JSON Web Key. |
|---|
Added: New function.
| Signature | crypto:thumbprint( $key as (xs:string | xs:base64Binary | xs:hexBinary | map(*))) as xs:string |
|---|
| Summary | Returns the JWK thumbprint of the specified $key (SHA-256, base64url-encoded). Thumbprints are often used as key identifiers (kid). For private keys, the thumbprint of the public key is returned. |
|---|
| Errors | |
|---|
| Examples | crypto:thumbprint({
'kty': 'OKP', 'crv': 'Ed25519',
'x': '11qYAYKxCrfVS_7TyWQHOg7hcvPapiMlrwIaaPcHURo'
}) Result: 'kPrK_qmxVWaYVA9wwBF6Iuo3vVzz7TxHCTwXBygrS4k'. Uses the example from RFC 8037. |
|---|
Added: New function.
| Signature | crypto:derive( $key as (xs:string | xs:base64Binary | xs:hexBinary | map(*)), $algorithm as (xs:string | map(*)), $length as xs:positiveInteger? := ()) as xs:base64Binary |
|---|
| Summary | Derives bytes from the specified $key with the specified algorithm:
HKDF derives keys from a secret key (RFC 5869). The default $length is the length of the hash, and the maximum is 255 times the length of the hash.ECDH and X25519 compute a shared secret from the private $key and the public key of the other party (supplied as public in the algorithm map). By default, the complete secret is returned; with $length, it is truncated. The secret should not be used as key directly, but passed on to HKDF.
|
|---|
| Errors | CX0013 | The hashing algorithm is not supported. | CX0019 | The key is invalid. | CX0021 | The algorithm is not supported. | CX0029 | The key does not match the algorithm or the operation. |
|
|---|
| Examples | crypto:derive(
xs:hexBinary('0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B0B'),
{ 'name': 'HKDF', 'hash': 'SHA-256' },
42
) => xs:hexBinary() => string() Result: '8DA4E775A563C18F715F802A063C5A31B8A11F5C5EE1879EC3454E5F3C738D2D9D201395FAA4B61A96C8'. Test case 3 of RFC 5869.
let $alice := crypto:generate-key('X25519')
let $bob := crypto:generate-key('X25519')
let $secret1 := crypto:derive($alice?private, { 'name': 'X25519', 'public': $bob?public })
let $secret2 := crypto:derive($bob?private, { 'name': 'X25519', 'public': $alice?public })
return $secret1 = $secret2 Result: true(). Both parties compute the same secret. |
|---|
Added: New function.
| Signature | crypto:random-bytes( $length as xs:nonNegativeInteger) as xs:base64Binary |
|---|
| Summary | Returns $length cryptographically strong random bytes. Unlike the functions of the Random Module, it can be used for salts, nonces, tokens and secret keys. |
|---|
| Examples | crypto:random-bytes(32) => bin:to-base64url() Creates a random token. |
|---|
Added: New function.
| Signature | crypto:equal( $value1 as (xs:string | xs:base64Binary | xs:hexBinary), $value2 as (xs:string | xs:base64Binary | xs:hexBinary)) as xs:boolean |
|---|
| Summary | Checks if two strings or binary items are equal. The comparison takes the same time for all inputs of the same length, which prevents timing attacks when secrets such as API keys or tokens are compared. Strings are UTF-8 encoded. |
|---|
| Examples | crypto:equal('secret', 'secret') Result: true() |
|---|
crypto:encrypt and crypto:decrypt encrypt and decrypt strings and binary items:
- The
$type must be symmetric (the same secret key is used for encryption and decryption) or asymmetric (data is encrypted with a public key and decrypted with the corresponding private key), and it must match the algorithm. - Recommended algorithms are
AES-GCM (authenticated encryption, which detects tampered data on decryption), AES-CBC and RSA-OAEP. The data of RSA-OAEP must be shorter than the key size minus twice the hash length minus 2 bytes, e.g. 190 bytes for a 2048-bit key and SHA-256. - If no
iv is supplied, a random initialization vector (IV) is generated and prepended to the encrypted data, and it is expected in front of the data on decryption. As a result, encryptions of the same message look different each time. If an iv is supplied, the encrypted data is returned without IV, which is compatible with other implementations (e.g. the Web Cryptography API). The IV must never be reused with the same key. - For compatibility, the legacy names
AES (equivalent to AES-CBC) and RSA are still supported. RSA uses OAEP padding with SHA-256, but MGF1 with SHA-1, which is incompatible with RSA-OAEP and other implementations; use { 'name': 'RSA-OAEP', 'hash': 'SHA-256' } for new data.
Updated: Keys can be supplied as JWK maps and X.509 certificates; algorithms of the Web Cryptography API.
| Signature | crypto:encrypt( $value as (xs:string | xs:base64Binary | xs:hexBinary), $type as xs:string, $key as (xs:string | xs:base64Binary | xs:hexBinary | map(*)), $algorithm as (xs:string | map(*))) as xs:base64Binary |
|---|
| Summary | Encrypts the specified $value with the specified $key, supplied in one of the formats described in Keys (the secret key for symmetric and the public key for asymmetric encryption), and the specified algorithm. |
|---|
| Errors | CX0016 | No such padding. | CX0017 | Incorrect padding. | CX0018 | The encryption type is not supported. | CX0019 | The key is invalid. | CX0020 | Illegal block size. | CX0021 | The algorithm is not supported. | CX0029 | The key does not match the algorithm or the operation. |
|
|---|
| Examples | crypto:encrypt('message', 'symmetric', 'keykeykeykeykeyk', 'AES-GCM') Encrypt input data; the result starts with a random IV.
crypto:encrypt(
xs:hexBinary('00000000000000000000000000000000'),
'symmetric',
{ 'kty': 'oct', 'k': 'AAAAAAAAAAAAAAAAAAAAAA' },
{ 'name': 'AES-GCM', 'iv': xs:hexBinary('000000000000000000000000') }
) => xs:hexBinary() => string() Result: '0388DACE60B6A392F328C2B971B2FE78AB6E47D42CEC13BDF53A67B21257BDDF'. Test case 2 of the GCM specification: the result consists of the ciphertext and the authentication tag.
crypto:encrypt(
'message',
'asymmetric',
file:read-text('public.pem'),
{ 'name': 'RSA-OAEP', 'hash': 'SHA-256' }
) Encrypt input data with a public key, e.g. created via openssl genpkey -algorithm RSA -out private.pem and openssl pkey -in private.pem -pubout -out public.pem. |
|---|
Updated: Keys can be supplied as JWK maps and X.509 certificates; algorithms of the Web Cryptography API; new $options parameter.
| Signature | crypto:decrypt( $value as (xs:string | xs:base64Binary | xs:hexBinary), $type as xs:string, $key as (xs:string | xs:base64Binary | xs:hexBinary | map(*)), $algorithm as (xs:string | map(*)), $options as map(*)? := {}) as (xs:string | xs:base64Binary) |
|---|
| Summary | Decrypts the specified $value with the specified $key, supplied in one of the formats described in Keys (the secret key for symmetric and the private key for asymmetric encryption), and the specified algorithm. The following $options are available:
| option | default | description |
|---|
binary | false() | Return the decrypted data as xs:base64Binary item. By default, it is returned as UTF-8 decoded string. |
|
|---|
| Errors | CX0016 | No such padding. | CX0017 | Incorrect padding. | CX0018 | The encryption type is not supported. | CX0019 | The key is invalid. | CX0020 | Illegal block size. | CX0021 | The algorithm is not supported. | CX0029 | The key does not match the algorithm or the operation. |
|
|---|
| Examples | let $encrypted := crypto:encrypt('message', 'symmetric', 'keykeykeykeykeyk', 'AES-GCM')
return crypto:decrypt($encrypted, 'symmetric', 'keykeykeykeykeyk', 'AES-GCM') Result: 'message'
let $key := crypto:generate-key({ 'name': 'AES-GCM' })
let $alg := { 'name': 'AES-GCM', 'iv': crypto:random-bytes(12) }
let $encrypted := crypto:encrypt(xs:hexBinary('CAFE'), 'symmetric', $key, $alg)
return crypto:decrypt($encrypted, 'symmetric', $key, $alg, { 'binary': true() })
=> xs:hexBinary() => string() Result: 'CAFE'. Encrypts and decrypts binary data with a generated key and an explicit IV. |
|---|
XML Signatures are used to sign data. In our case, the data which is signed is an XQuery node. The following example shows the basic structure of an XML signature.
XML Signature
<Signature>
<SignedInfo>
<CanonicalizationMethod/>
<SignatureMethod/>
<Reference>
<Transforms/>
<DigestMethod/>
<DigestValue/>
</Reference>
<Reference/>
</SignedInfo>
<SignatureValue/>
<KeyInfo/>
<Object/>
</Signature>
- SignedInfo contains or references the signed data and lists algorithm information
- Reference references the signed node
- Transforms contains transformations (i.e. XPath expressions) that are applied to the input node in order to sign a subset
- DigestValue holds digest value of the transformed references
- SignatureValue contains the Base64 encoded value of the encrypted digest of the
SignedInfo element - KeyInfo provides information on the key that is used to validate the signature
- Object contains the node which is signed if the signature is of type
enveloping
Signature Types
Depending on the signature type, the signature element is either placed as a child of the signed node (enveloped type), or directly contains the signed node (enveloping type). Detached signatures are so far not supported.
Digital Certificate
The generate-signature function allows to pass a digital certificate. This certificate holds parameters that allow to access key information stored in a Java key store which is then used to sign the input document. Passing a digital certificate simply helps re-using the same key pair to sign and validate data. The digital certificate is passed as a node and has the following form:
<digital-certificate>
<keystore-type>JKS</keystore-type>
<keystore-password>...</keystore-password>
<key-alias>...</key-alias>
<private-key-password>...</private-key-password>
<keystore-uri>...</keystore-uri>
</digital-certificate>
| Signature | crypto:generate-signature( $node as xnode(), $canonicalization as xs:string, $digest as xs:string, $signature as xs:string, $prefix as xs:string, $type as xs:string, $ext1 as item() := (), $ext2 as xnode() := ()) as document-node() |
|---|
| Summary | Generates a signature:
$canonicalization must either be inclusive-with-comments, inclusive, exclusive-with-comments or exclusive. Default is inclusive-with-comments.$digest must be one of the following: SHA1, SHA256 or SHA512. Default is SHA256.$signature must be one of the following: RSA_SHA1, RSA_SHA256, RSA_SHA512, DSA_SHA1 or DSA_SHA256. Default is RSA_SHA256.- Signatures that were created with
SHA1 are rejected by the secure validation of current Java versions, and can no longer be validated with crypto:validate-signature. $prefix may be empty and prefixes the Signature element accordingly.$type is the signature type. It must either be enveloped or enveloping (detached signatures are not supported so far). Default is enveloped.$ext1 may either be an XPath expression or a digital certificate.- If
$ext2 is specified as well, $ext1 is an arbitrary XPath expression which specifies a subset of the document that is to be signed, and $ext2 is the digital certificate used to sign the input document. - Digital certificates refer to a keystore, which requires
admin permission.
|
|---|
| Errors | CX0001 | The canonicalization algorithm is not supported. | CX0002 | The digest algorithm is not supported. | CX0003 | The signature algorithm is not supported. | CX0004 | The XPath expression is invalid. | CX0005 | The root element of argument $digital-certificate must have the name 'digital-certificate'. | CX0007 | The keystore is null. | CX0012 | Cannot find key for alias in given keystore. | CX0023 | An invalid certificate alias is specified. Added to the official specification. | CX0024 | The algorithm is invalid. Added to the official specification. | CX0025 | An I/O Exception occurred. Added to the official specification. | CX0026 | Keystore cannot be processed. Added to the official specification. | CX0027 | Signature cannot be processed. Added to the official specification. | CX0028 | The specified signature type is not supported. Added to the official specification. |
|
|---|
| Signature | crypto:validate-signature( $node as xnode()) as xs:booleanadmin |
|---|
| Summary | Checks if the specified $node contains a Signature element and whether the signature is valid. In this case true is returned. If the signature is invalid the function returns false. admin permission is required if the signature references external resources. |
|---|
| Errors | CX0015 | Cannot find Signature element. | CX0025 | An I/O Exception occurred. Added to the official specification. | CX0027 | Signature cannot be processed. Added to the official specification. |
|
|---|
| Code | Description |
|---|
CX0001 | The canonicalization algorithm is not supported. |
CX0002 | The digest algorithm is not supported. |
CX0003 | The signature algorithm is not supported. |
CX0004 | The XPath expression is invalid. |
CX0005 | The root element of argument $digital-certificate must have the name 'digital-certificate'. |
CX0006 | The child element of argument $digital-certificate having position $position must have the name $child-element-name. |
CX0007 | The keystore is null. |
CX0008 | I/O error while reading keystore. |
CX0009 | Permission denied to read keystore. |
CX0010 | The keystore URL is invalid. |
CX0011 | The keystore type is not supported. |
CX0012 | Cannot find key for alias in given keystore. |
CX0013 | The hashing algorithm is not supported. |
CX0014 | The encoding method is not supported. |
CX0015 | Cannot find Signature element. |
CX0016 | No such padding. |
CX0017 | Incorrect padding. |
CX0018 | The encryption type is not supported. |
CX0019 | The key is invalid. |
CX0020 | Illegal block size. |
CX0021 | The algorithm is not supported. |
CX0023 | An invalid certificate alias is specified. Added to the official specification. |
CX0024 | The algorithm is invalid. Added to the official specification. |
CX0025 | An I/O Exception occurred. Added to the official specification. |
CX0026 | Keystore cannot be processed. Added to the official specification. |
CX0027 | Signature cannot be processed. Added to the official specification. |
CX0028 | The specified signature type is not supported. Added to the official specification. |
CX0029 | The key does not match the algorithm or the operation. |
CX0030 | The password hash is invalid. |
CX0031 | The key cannot be exported. |
Version 14.0- Added:
crypto:sign, crypto:verify, crypto:generate-key, crypto:export-key, crypto:thumbprint, crypto:derive, crypto:hash-password, crypto:verify-password, crypto:random-bytes, crypto:equal. - Updated:
crypto:encrypt, crypto:decrypt: Keys can be supplied as JWK maps and X.509 certificates; algorithms of the Web Cryptography API (AES-CBC, AES-GCM, RSA-OAEP) with explicit IVs, additional data and tag lengths. - Updated:
crypto:decrypt: New $options parameter for binary results.
Version 13.0Version 9.3Version 7.0