Skip to main content

crypto.sign(mode, message, privateKey, callback)

Generate a data signature




Name Type Description
mode Constant The hashing type
message String or blob The data to be signed, up to 64KB in size
privateKey String or blob The private key used to sign the data
callback Function The function into which the signature is passed




This method performs a hash on the specified message using the provided key. What kind of hash is applied is determined by the constant passed into the mode parameter.

Currently, only one hash type is supported: the SHA256 RSA signature scheme, which is selected by passing the constant crypto.RSASSA_PKCS1_SHA256 into mode. The value of key must be an RSA private key: DER-encoded PKCS#1 or PKCS#8. Only keys between 1024 and 4096 bits in length (inclusive) are supported. Keys must not be password encrypted.

The message to be signed must not be larger than 65536 bytes (64KB).

The method returns immediately. The hash is processed asynchronously and the signature returned to the mandatory callback function via its signature parameter. The signature is returned as a blob. Signatures can be verified using crypto.verify().

Passing an invalid mode or a malformed key will cause an exception to be thrown.

Usage Rate Limits

Use of crypto.sign() will be rate-limited as follows. Each agent has 40 usage credits which will be spent according to the length of the key used to sign or verify the data on a per-call basis:

credits used = key length in bits ÷ 1024

Credits are topped up at the fixed rate of two credits per second.

If you make a call when you have no usage credits, an exception will be thrown. Other errors are passed into the callback function’s error parameter, which will be null if no error occurred.

Note We reserve the right to alter the number of credits provided to an agent, the rate of renewal and the cost per key.

Example Code

The following code shows how a simple string can be signed using a pre-existing RSA private key in PKCS#1 format taken from a .key file. The first function, decodePrivatePem(), is used to convert such a key for use with crypto.sign() by extracting the key data from between the header and footer. Enter the command

openssl genrsa -out rsa.key 2048

into a terminal on your computer to generate a fresh private key.

The second function, hexString(), formats output bytes into hexadecimal characters and is used to display the signature generated by crypto.sign().

The following code is an alternative to the code above: it shows how a simple string can be signed using a pre-existing RSA private key in PKCS#8 format (rather than PKCS#1, as above) taken from a .pem file. The first function, decodePrivate8Pem(), is used to convert the PKCS#8 key for use with crypto.sign().

Enter the command

openssl req -x509 -nodes -newkey rsa:2048 -batch -keyout key.pem

into a terminal on your computer to generate a fresh private key.