crypto
The crypto built-in module is available only inside a PubNub Function. Its asynchronous methods hash, sign, and verify values.
1const crypto = require('crypto');
ALGORITHM
crypto.ALGORITHM lists the supported algorithms: ED25519, ECDSA_P256_SHA1, ECDSA_P256_SHA256, ECDSA_P256_SHA512, HMAC_SHA1, HMAC_SHA256, HMAC_SHA512.
1console.log(crypto.ALGORITHM);
2// -> ED25519, ECDSA_P256_SHA1, ECDSA_P256_SHA256, ECDSA_P256_SHA512, HMAC_SHA1, HMAC_SHA256, HMAC_SHA512
hmac
hmac(key, msg, algorithm)
* required
| Parameter | Description |
|---|---|
key *Type: String | Signature key. |
msg *Type: String | Message to sign. |
algorithm *Type: String | One of crypto.ALGORITHM.HMAC_*. |
Returns: Promise resolving to a Base64-encoded HMAC signature.
1const crypto = require('crypto');
2const base64 = require('codec/base64');
3crypto.hmac(base64.btoa('sharedSecretKey'), 'secretPayload', crypto.ALGORITHM.HMAC_SHA1).then((result) => {
4 console.log(result);
5}).catch((error) => {
6 console.log(error);
7});
sha1, sha256, sha512
sha1(msg), sha256(msg), sha512(msg)
* required
| Parameter | Description |
|---|---|
msg *Type: String | Message to hash. |
Returns: Promise resolving to the hash of msg.
1const crypto = require('crypto');
2crypto.sha256('secretPayload').then((result) => {
3 console.log('secretPayload:' + result);
4}).catch((error) => {
5 console.log(error);
6});
sign
sign(key, msg, algorithm)
* required
| Parameter | Description |
|---|---|
key *Type: Object | Private key for signing. |
msg *Type: String | Message to sign. |
algorithm *Type: String | One of crypto.ALGORITHM.*. |
Returns: Promise resolving to the signature.
A private or public key for ED25519 takes this shape:
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};
1const crypto = require('crypto');
2crypto.sign(privateKey, 'secretPayload', crypto.ALGORITHM.ECDSA_P256_SHA1).then((result) => {
3 console.log(result);
4}).catch((error) => {
5 console.log(error);
6});
verify
verify(sig, key, msg, algorithm)
* required
| Parameter | Description |
|---|---|
sig *Type: String | Signature to verify. |
key *Type: Object | Public key for verification. |
msg *Type: String | Original message. |
algorithm *Type: String | One of crypto.ALGORITHM.*. |
Returns: Promise resolving to the verification result.
1const crypto = require('crypto');
2crypto.verify(existingSignature, publicKey, 'secretPayload', crypto.ALGORITHM.ECDSA_P256_SHA1).then((result) => {
3 console.log(result);
4}).catch((error) => {
5 console.log(error);
6});
Related reference
- Modules and libraries. Every built-in module available inside a Function.
- codec. Base64 encoding used to prepare keys for
hmac().