On this page

Crypto Module

The Functions' crypto module provides hashing, HMAC, signing, and verification helpers for PubNub Functions. Use it to protect data and validate messages in real time.

Import the module:

1const crypto = require('crypto');

Available algorithms

List supported algorithms with crypto.ALGORITHM.

1console.log(crypto.ALGORITHM);
2// -> ED25519, ECDSA_P256_SHA1, ECDSA_P256_SHA256, ECDSA_P256_SHA512, HMAC_SHA1, HMAC_SHA256, HMAC_SHA512

HMAC

Generate an HMAC signature with hmac(). Output is Base64‑encoded.

Usage: hmac(key, msg, algorithm)

  • key: signature key
  • msg: message to sign
  • algorithm: one of crypto.ALGORITHM.HMAC_*
1crypto.hmac(base64.btoa('sharedSecretKey'), 'secretPayload', crypto.ALGORITHM.HMAC_SHA1).then((result) => {
2 console.log(result.replace('-', '+').replace('_', '/'));
3}).catch((error) => {
4 console.log(error)
5});

SHA‑1

Create a SHA‑1 hash with sha1().

Usage: sha1(msg)

  • msg: message to hash
1crypto.sha1('secretPayload').then((result2) => {
2 console.log("secretPayload:" + result2);
3}).catch((error) => {
4 console.log(error)
5});

SHA‑256

Create a SHA‑256 hash with sha256().

Usage: sha256(msg)

  • msg: message to hash
1crypto.sha256('secretPayload').then((result2) => {
2 console.log("secretPayload:" + result2);
3}).catch((error) => {
4 console.log(error)
5});

SHA‑512

Create a SHA‑512 hash with sha512().

Usage: sha512(msg)

  • msg: message to hash
1crypto.sha512('secretPayload').then((result2) => {
2 console.log("secretPayload:" + result2);
3}).catch((error) => {
4 console.log(error)
5});

Private and public key examples

1const secretKey_ed25519 = {
2 'kty' : 'EdDSA',
3 'crv' : 'Ed25519',
4 'sk' : 'bfk0DBOMwYi1_kRk66o_f8IGotVcNDRwfnTJ_ATiDrs',
5 'use' : 'sig',
6};
7const publicKey_ed25519 = {
8 'kty' : 'EdDSA',
9 'crv' : 'Ed25519',
10 'pk' : 'wNrBAsRTMYbiXcQxKEcjU-qr24eLFSrrjgAfktkCM6c',
11 'use' : 'sig',
12};

Sign

Sign a message with a key and algorithm using sign().

Usage: sign(key, msg, algorithm)

  • key: private key for signing
  • msg: message to sign
  • algorithm: one of crypto.ALGORITHM.*
1crypto.sign(privateKey, 'secretPayload', crypto.ALGORITHM.ECDSA_P256_SHA1).then((result4) => {
2 console.log(result4);
3}).catch((error) => {
4 console.log(error)
5});

Verify

Verify a signature with verify().

Usage: verify(sig, key, msg, algorithm)

  • sig: existing signature
  • key: public key for verification
  • msg: original message
  • algorithm: one of crypto.ALGORITHM.*
1crypto.verify(<existing_signature>, publicKey, 'secretPayload', crypto.ALGORITHM.ECDSA_P256_SHA1).then((results) => {
2 console.log(results)
3}).catch((error) => {
4 console.log(error)
5});
Functions support

If you need help with a scenario not covered here, contact PubNub Support.

Last updated on