Navigation

Utility Packages

JSON Web Tokens (utils.jwt)

The utils.jwt package provides methods for working with JSON Web Tokens.

Method Description
utils.jwt.encode() Generates an encoded JSON Web Token string for a given payload, signingMethod, and secret.
utils.jwt.decode() Decodes the payload of a JSON Web Token string.
utils.jwt.encode()

Generates an encoded JSON Web Token string for the payload based on the specified signingMethod and secret.

utils.jwt.encode(signingMethod, payload, secret, customHeaderFields)
Parameter Type Description
signingMethod String

The cryptographic algorithm to use when encoding the JWT. Realm supports the following JWT signing methods:

Signing Method Description
"HS256" HMAC using SHA-256
"HS384" HMAC using SHA-384
"HS512" HMAC using SHA-512
"RS256" RSASSA-PKCS1-v1_5 using SHA-256
"RS384" RSASSA-PKCS1-v1_5 using SHA-384
"RS512" RSASSA-PKCS1-v1_5 using SHA-512
"ES256" ECDSA using P-256 and SHA-256
"ES384" ECDSA using P-384 and SHA-384
"ES512" ECDSA using P-512 and SHA-512
"PS256" RSASSA-PSS using SHA-256 and MGF1 with SHA-256
"PS384" RSASSA-PSS using SHA-384 and MGF1 with SHA-384
"PS512" RSASSA-PSS using SHA-512 and MGF1 with SHA-512
payload Object A JSON object that specifies the token’s claims and any additional related data.
secret String

A secret string that Realm uses to sign the token. The value of the string depends on the signing method that you use:

Signing Methods Description
"HS256"
"HS384"
"HS512"
A random string.
"RS256"
"RS384"
"RS512"
An RSA-SHA private key in PKCS#8 format.
"PS256"
"PS384"
"PS512"
An RSA-PSS private key in PKCS#8 format.
"ES256"
"ES384"
"ES512"
An ECDSA private key in PKCS#8 format.
customHeaderFields Object A JSON object that specifies additional fields to include in the JWT’s JOSE header.
Returns:A JSON Web Token string encoded for the provided payload.

Example

Consider the following JWT claims object:

{
  "sub": "1234567890",
  "name": "Joe Example",
  "iat": 1565721223187
}

We can encode the claims object as a JWT string by calling utils.jwt.encode(). The following function encodes the JWT using the HS512 signing method and the secret "SuperSecret":

exports = function() {
  const signingMethod = "HS512";
  const payload = {
    "sub": "1234567890",
    "name": "Joe Example",
    "iat": 1565721223187
  };
  const secret = "SuperSecret";
  return utils.jwt.encode(signingMethod, payload, secret);
}

The function returns the following JWT string:

eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvZSBTY2htb2UiLCJpYXQiOjE1NjU3MjEyMjMxODd9.-QL15ldu2BYuJokNWT6YRiwZQIiIpvq6Kyv-C6qslNdNiUVxo8zqLJZ1iEkNf2yZKMIrQuMCtIC1tzd2H31AxA
utils.jwt.decode()

Decodes the payload of the provided JSON Web Token string. The value of key must correspond to the secret value that was used to encode the JWT string.

utils.jwt.decode(jwtString, key, returnHeader)
Parameter Type Description
jwtString String A JSON Web Token string that encodes a set of claims signed with a secret value.
key String

A string that Realm uses to verify the token signature. The value of the string depends on the signing method that you use:

Signing Methods Description
"HS256"
"HS384"
"HS512"
The random string that was used to sign the token.
"RS256"
"RS384"
"RS512"
The RSA-SHA public key that corresponds to the private key that was used to sign the token.
"PS256"
"PS384"
"PS512"
The RSA-PSS public key that corresponds to the private key that was used to sign the token.
"ES256"
"ES384"
"ES512"
The ECDSA public key that corresponds to the private key that was used to sign the token.
returnHeader Boolean If true, return the JWT’s JOSE header in addition to the decoded payload.
Returns:If returnHeader is false, returns the decoded EJSON payload.

If returnHeader is true, returns an object that contains the JOSE header in the header field and the decoded EJSON payload in the payload field.

{
  "header": {
    "<JOSE Header Field>": <JOSE Header Value>,
    ...
  },
  "payload": {
    "<JWT Claim Field>": <JWT Claim Value>,
    ...
  }
}

Example

Consider the following signed JWT string:

eyJhbGciOiJIUzUxMiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvZSBTY2htb2UiLCJpYXQiOjE1NjU3MjEyMjMxODd9.-QL15ldu2BYuJokNWT6YRiwZQIiIpvq6Kyv-C6qslNdNiUVxo8zqLJZ1iEkNf2yZKMIrQuMCtIC1tzd2H31AxA

The JWT was signed using the HS512 signing method with the secret value "SuperSecret". We can decode the JWT’s claims object utils.jwt.decode(). The following function decodes the JWT string:

exports = function(jwtString) {
  const key = "SuperSecret";
  return utils.jwt.decode(jwtString, key);
}

The function returns the following EJSON representation of the JWT payload:

{
  "sub": "1234567890",
  "name": "Joe Example",
  "iat": { "$numberDouble": 1565721223187 }
}

Cryptography (utils.crypto)

The utils.crypto package provides methods for working with cryptographic algorithms.

Method Description
utils.crypto.encrypt() Generates an encrypted text string from a given text string using a specific encryption method and key.
utils.crypto.decrypt() Decrypts a provided text string using a specific encryption method and key.
utils.crypto.sign() Generates a cryptographically unique signature for a given message using a private key.
utils.crypto.verify() Verifies that a signature is valid for a given message and public key.
utils.crypto.hmac() Generates an HMAC signature from a given input and secret.
utils.crypto.hash() Generates a hash value for a given input and hash function.
utils.crypto.encrypt()

Generates an encrypted text string from the provided text using the specified encryption method and key.

utils.crypto.encrypt(encryptionType, message, key)
Parameter Type Description
encryptionType String

The type of encryption with which to encrypt the message. The following encryption types are supported:

message String The text string that you want to encrypt.
key String

A cryptographic key used to encrypt the text. The key you should use depends on the encryption method:

Encryption Type Encryption Key
AES A 16-byte, 24-byte, or 32-byte random string
Returns:A BSON Binary object that contains the text string encrypted with the specified encryption type and key.

Example

Assume that we have defined a Value named aesEncryptionKey that contains the following 32-byte AES encryption key:

"603082712271C525E087BD999A4E0738"

We can encrypt a message with this key using the following Realm function:

exports = function(message) {
  const key = context.values.get("aesEncryptionKey");
  const encryptedMessage = utils.crypto.encrypt("aes", message, key);
  return encryptedMessage.toBase64();
}

If we use the function to encrypt the message "MongoDB is great!", it returns the following encrypted base64 string:

"WPBuIvJ6Bity43Uh822dW8QlVYVJaFUiDeUjlTiJXzptUuTYIKPlXekBQAJb"
utils.crypto.decrypt()

Decrypts the provided text string using the specified encryption type and key. If both the encryption type and key are the same as those used to encrypt, this returns the original, unencrypted text.

utils.crypto.decrypt(encryptionType, encryptedMessage, key)
Parameter Type Description
encryptionType String

The type of encryption that was used to encrypt the provided text. The following encryption types are supported:

encryptedMessage BSON.Binary A BSON Binary that encodes the encrypted text string that you want to decrypt.
key String

A cryptographic key used to decrypt the text. The key you should use depends on the encryption type:

Encryption Type Encryption Key
AES A 16-byte, 24-byte, or 32-byte random string
Returns:A BSON Binary object that contains the decrypted message.

If the provided encrypted message was encrypted with the specified method and key, then the decrypted message is identical to the original message.

Example

Assume that we have defined a Value named aesEncryptionKey that contains the following 32-byte AES encryption key:

"603082712271C525E087BD999A4E0738"

We can decrypt a message that was encrypted with this key using the following Realm function:

exports = function(encryptedMessage) {
  // The encrypted message must be a BSON.Binary
  if(typeof encryptedMessage === "string") {
    encryptedMessage = BSON.Binary.fromBase64(encryptedMessage)
  }
  const key = context.values.get("aesEncryptionKey");
  const decryptedMessage = utils.crypto.decrypt("aes", encryptedMessage, key);
  return decryptedMessage.text();
}

If we use the function to decrypt the encrypted message, it returns the original, unencrypted string:

"MongoDB is great!"
utils.crypto.sign()

Generates a cryptographically unique signature for a message using a private key. The signature can be verified with the corresponding public key to ensure that the signer has access to the private key and that the message content has not been altered since it was signed.

utils.crypto.sign(encryptionType, message, privateKey, signatureScheme)
Parameter Type Description
encryptionType String

The type of encryption that was used to generate the private/public key pair. The following encryption types are supported:

message String The text string that you want to sign.
privateKey String

A private key generated with the specified encryption type.

Key Format

Not all RSA keys use the same format. Realm can only sign messages with a private key that conforms to the standard PKCS#1 format. Private keys in this format have the header -----BEGIN RSA PRIVATE KEY-----.

You can use the following shell script to generate a valid RSA private/public key pair and save each key to its own text file:

# Generate an RSA SSH key pair
# Save the key to a file called `rsa_key` when prompted
ssh-keygen -t rsa -m PEM -b 2048 -C "2048-bit RSA Key"

# Private Key
cat rsa_key > rsa.private.txt
# Public Key
ssh-keygen -f rsa_key.pub -e -m pem > rsa.public.txt
signatureScheme String

Optional. Default: "pss"

The padding scheme that the signature should use. Realm supports signing messages with the following schemes:

Returns:A BSON.Binary cryptographic signature for the message signed using the specified private key.

Example

Assume that we have defined a Value named rsaPrivateKey that contains the following RSA private key:

-----BEGIN RSA PRIVATE KEY-----
MIICXAIBAAKBgQDVsEjse2qO4v3p8RM/q8Rqzloc1lee34yoYuKZ2cemuUu8Jpc7
KFO1+aJpXdbSPZNhGLdANn8f2oMIZ1R9hgEJRn/Qm/YyC4RPTGg55nzHqSlziNZJ
JAyEUyU7kx5+Kb6ktgojhk8ocZRkorM8FEylkrKzgSrfay0PcWHPsKlmeQIDAQAB
AoGAHlVK1L7kLmpMbuP4voYMeLjYE9XdVEEZf2GiFwLSE3mkJY44033y/Bb2lgxr
DScOf675fFUAEK59ATlhxfu6s6rgx+g9qQQ+mL74YZWPqiZHBPjyMRaBalDVC4QF
YJ+DopFcB8hY2ElXnbK70ALmVYNjw3RdmC97h0YfOsQcWW0CQQD18aeuPNicVnse
Ku22vvhvQYlabaQh4xdkEIxz1TthZj48f61wZwEMipYqOAc5XEtDlNnxgeipv0yF
RHstUjwXAkEA3m0Br/U/vC9evuXppWbONana08KLgfELyd3Uw9jG7VKJZTBH5mS8
7CB68aEF8egrJpo8Ss8BkWrvCxYDb4Y77wJAUlbOMZozVtvpKidrIFR9Lho91uWA
Hsw9h4W20AzibXBig7SnJ0uE4WMAdS/+0yhgFkceVCmO8E2YW8Gaj4jJjwJASxtg
AHy+ItuUEL4uIW4Pn8tVW0BMP3qX0niXyfI/ag/+2S5uePv3V3y4RzNqgH83Yved
+FziWKpVQdcTHeuj/QJBAJl1G3WFruk0llIoKKbKljaEiCm1WCTcuEPbdOtkJYvO
9ZYQg/fji70FERkq2KHtY7aLhCHzy0d4n9xgE/pjV+I=
-----END RSA PRIVATE KEY-----

We can sign a message with this key using the following Realm function:

exports = function(message) {
  const rsaPrivateKey = context.values.get("rsaPrivateKey");
  const signature = utils.crypto.sign("rsa", message, rsaPrivateKey, "pss");
  return signature;
}

If we use the function to sign the message "MongoDB is great!", it returns a BSON.Binary signature that evaluates to the following base64 string:

"SpfXcJwPbypArt+XuYQyuZqU52YCAY/sZj2kiuin2b6/RzyM4Ek3n3spOtqZJqxn1tfQavxIX4V+prbs74/pOaQkCLekl9Hoa1xOzSKcGoRd8U+n1+UBY3d3cyODGMpyr8Tim2HZAeLPE/D3Q36/K+jpgjvrJFXsJoAy5/PV7iEGV1fkzogmZtXWDcUUBBTTNPY4qZTzjNhL4RAFOc7Mfci+ojE/lLsNaumUVU1/Eky4vasmyjqunm+ULCcRmgWtGDMGHaQV4OXC2LMUe9GOqd3Q9ghCe0Vlhn25oTh8cXoGpd1Fr8wolNa//9dUqSM+QYDpZJXGLShX/Oa8mPwJZKDKHtqrS+2vE6S4dDWR7zKDza+DeovOeCih71QyuSYMXSz+WWGgfLzv/syhmUXP/mjqgLmJU6Kwg5htajDoylpzLC0BLGT4zDZEwBrq/AjwRs/EPjYdFgGCt1WCbbVlDyXvvH1ekDrzACzumhiMSZNNa+ZH3JmMJxTCQWDfiTeAfkauaaZHKIj2q2/QE7vuAhNcVPJ2YgpXnvnQHJpEZBc/Y3Q6JLxom6+cGC4P//9d++r2cwzXIkqD+wSGZVSVtpm5CLtWMRSK5FX2dv16bM+LE8ozoRvtMUDTrQ8SSSDGxyuYbvN9b2fYYPcWpCMchqOBXV6eZGoMldaHX3Qy5h8="
utils.crypto.verify()

Checks that the provided signature is valid for the specified message and public key.

If the signature is valid, it guarantees that the signer has access to the corresponding private key and that the message content has not been altered since it was signed.

utils.crypto.verify(encryptionType, message, publicKey, signature, signatureScheme)
Parameter Type Description
encryptionType String

The type of encryption that was used to generate the private/public key pair. The following encryption types are supported:

message String The text string for which you want to verify the signature. If the signature is valid, this is the exact message that was signed.
publicKey String

The public key for which you want to verify the signature. If the signature is valid, this is the corresponding public key of the private key that was used to sign the message.

Key Format

Not all RSA keys use the same format. Realm can only verify signatures with RSA keys that conform to the standard PKCS#1 format. Public keys in this format have the header -----BEGIN RSA PUBLIC KEY-----.

You can use the following shell script to generate a valid RSA private/public key pair and save each key to its own text file:

# Generate an RSA SSH key pair
# Save the key to a file called `rsa_key` when prompted
ssh-keygen -t rsa -m PEM -b 2048 -C "2048-bit RSA Key"

# Private Key
cat rsa_key > rsa.private.txt
# Public Key
ssh-keygen -f rsa_key.pub -e -m pem > rsa.public.txt
signature BSON.Binary The signature that you want to verify.
signatureScheme String

Optional. Default: "pss"

The padding scheme that the signature uses. Realm supports verifying signatures that use the following schemes:

Returns:A boolean that, if true, indicates whether or not the signature is valid for the provided message and public key.

Example

We received a message with a signature in BSON.Binary format and want to verify that the message was signed with the private key that corresponds to the sender’s RSA public key:

-----BEGIN RSA PUBLIC KEY-----
MIGJAoGBANWwSOx7ao7i/enxEz+rxGrOWhzWV57fjKhi4pnZx6a5S7wmlzsoU7X5
omld1tI9k2EYt0A2fx/agwhnVH2GAQlGf9Cb9jILhE9MaDnmfMepKXOI1kkxDIRT
JTuTHn4pvqS2CiOGTyhxlGSiszwUTKWSsrOBKt9rLQ9xYc+wqWZ5AgMBAAE=
-----END RSA PUBLIC KEY-----

We can use the following Realm function to verify the RSA signature:

exports = function(message, rsaPublicKey, signature) {
  const isValid = utils.crypto.verify("rsa", message, rsaPublicKey, signature, "pss");
  return isValid; // true if the signature matches, else false
}
utils.crypto.hmac()

Generates an HMAC signature from the provided input and secret. This is useful when communicating with third-party HTTP services that require signed requests.

utils.crypto.hmac(input, secret, hash_function, output_format)
Parameter Type Description
input string The input for which you would like to generate a signature.
secret string The secret key to use when generating the signature.
hash_function string The name of the hashing function to use when generating the signature. The following functions are supported: "sha1", "sha256", "sha512".
output_format string The format of the generated signature. Can be either "hex" for a hex string, or "base64" for a Base64 string.
Returns:The signature of the input, in the format specified by output_format.
utils.crypto.hash()

Generates a hash value for the provided input using the specified hash function.

utils.crypto.hash(hash_function, input)
Parameter Type Description
hash_function string The name of the hashing function. The following functions are supported: "sha1", "sha256", "md5".
input string or BSON.Binary Required. The input for which you would like to generate a hash value.
Returns:A hash value for the provided input generated by the specified hashing function.