Skip to main content

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

Generate a data signature

Availability

Agent

Parameters

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

Returns

Nothing

Description

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 method returns immediately. The hash is processed asynchronously, however, and the signature returned to the mandatory callback function via its own signature parameter. The signature is returned as a blob. Signatures can be verified using the crypto.verify() method.

Passing an invalid mode or a malformed key will trigger a runtime error. Other errors are passed into the callback function’s error parameter, which will be null if no error occurred.

Note Use of this method is rate-limited: please see the crypto page for details.

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.