Skip to content

Sys.Crypto

Sys.Crypto provides cryptographic helpers for server-side code: hashing, RSA key pairs, a small certificate authority for X.509 certificates, OpenPGP encryption and signing through SimplePgp, and AES encryption compatible with the CryptoJS library. For anything not covered, the Node.js crypto module and the node-forge library are available as they are.

Availability: Server

hash(data: string | Buffer, algorithm: HashAlgorithm, hashEncoding?: 'hex' | 'base64'): string

Calculates the hash of the data with the given algorithm, using Node.js crypto.createHash. Strings are hashed as UTF-8.

ParameterTypeDescription
datastring | BufferData to hash.
algorithmHashAlgorithmHash algorithm, for example sha256.
hashEncoding'hex' | 'base64'Encoding of the returned hash. Default: hex.

Returns: string · Availability: Server

createKeyPair(bits?: number): KeyPair

Generates a new RSA key pair. Both keys are PEM-encoded in PKCS#1 format.

ParameterTypeDescription
bitsnumberKey length in bits. Default: 2048.

Returns: KeyPair · Availability: Server

createCa(caKeyPair: KeyPair, subjectAttributes: SubjectAttribute[], options?: CreateCertificateOptions): string

Creates a self-signed certificate authority (CA) certificate for the key pair. Use the result with createCertificateFromCsr() to issue certificates.

ParameterTypeDescription
caKeyPairKeyPairKey pair of the CA.
subjectAttributesSubjectAttribute[]Distinguished name of the CA. See createCsr().
optionsCreateCertificateOptionsValidity, extensions and digest. isCertificateAuthority is always set to true. See createCertificateFromCsr().

Returns: string, the certificate in PEM format · Availability: Server

createCsr(csrKeyPair: KeyPair, subjectAttributes: SubjectAttribute[]): string

Creates a certificate signing request (CSR) for the public key of the key pair, signed with its private key using SHA-512.

ParameterTypeDescription
csrKeyPairKeyPairKey pair the certificate is requested for.
subjectAttributesSubjectAttribute[]Distinguished name of the subject.

SubjectAttribute fields

Each entry is one attribute of the distinguished name, in the format of node-forge.

FieldTypeRequiredDescription
namestringNoAttribute name, such as commonName, organizationName or countryName. Give either name, shortName or type.
shortNamestringNoShort attribute name, such as CN, O or C.
typestringNoAttribute OID.
valueany[] | stringNoAttribute value.
extensionsany[]NoExtensions, as node-forge defines them.

Returns: string, the CSR in PEM format · Availability: Server

createCertificateFromCsr(csrPem: string, ca: string, caKeyPair: KeyPair, options?: CreateCertificateOptions): string

Issues a certificate for a CSR, signed with the CA’s private key. The certificate is valid from now for the given number of days.

ParameterTypeDescription
csrPemstringThe CSR in PEM format.
castringThe CA certificate in PEM format; its subject becomes the issuer. An empty string makes the certificate self-signed.
caKeyPairKeyPairKey pair of the CA.
optionsCreateCertificateOptionsValidity, extensions and digest.

CreateCertificateOptions fields

FieldTypeRequiredDescription
subjectAltNamesstring[]NoDNS names for the subject alternative name extension. Cannot be combined with a subjectAltName entry in extensions.
isCertificateAuthoritybooleanNoIf true, adds or completes a basicConstraints extension with cA: true.
validityDaysnumberNoValidity in days. Default: 365.
extensionsany[]NoCertificate extensions in node-forge format.
messageDigestAlgorithm'md5' | 'sha1' | 'sha256' | 'sha384' | 'sha512' | 'sha512/224' | 'sha512/256'NoDigest used for the certificate signature. If omitted, node-forge signs with SHA-1.

Returns: string, the certificate in PEM format · Availability: Server

const caKeys = Sys.Crypto.createKeyPair()
const caPem = Sys.Crypto.createCa(caKeys, [{ shortName: 'CN', value: 'Example Root CA' }], {
validityDays: 3650,
messageDigestAlgorithm: 'sha256',
})
const serverKeys = Sys.Crypto.createKeyPair()
const csrPem = Sys.Crypto.createCsr(serverKeys, [{ shortName: 'CN', value: 'app.example.com' }])
const certPem = Sys.Crypto.createCertificateFromCsr(csrPem, caPem, caKeys, {
subjectAltNames: ['app.example.com'],
messageDigestAlgorithm: 'sha256',
})

Note

The certificates get no serial number of their own: node-forge’s default serial 00 is used for every certificate issued.

loadTlsCertificateFromWebsite(hostname: string, port?: number, servername?: string): Promise<DetailedPeerCertificate>

Connects to a TLS server and returns the certificate it presents, with its issuer chain in issuerCertificate. The root certificate’s reference to itself is removed, so the result can be serialized. The promise rejects if the connection fails, including when the certificate cannot be verified.

ParameterTypeDescription
hostnamestringHost to connect to.
portnumberPort. Default: 443.
servernamestringServer name sent for SNI. Default: hostname.

Returns: Promise<DetailedPeerCertificate>, a Node.js tls certificate object · Availability: Server

encrypt(plaintext: string, passphrase: string, config?: CryptoJsConfig): string

Encrypts text with a passphrase in the same way as CryptoJS.AES.encrypt(plaintext, passphrase, cfg).toString() of the CryptoJS library. Use it to exchange data with systems that use CryptoJS. With no configuration, it uses CryptoJS’s defaults: AES-256-CBC with PKCS#7 padding and an MD5-based key derivation.

ParameterTypeDescription
plaintextstringText to encrypt. It is encoded as UTF-8.
passphrasestringPassphrase the key is derived from.
configCryptoJsConfigCipher settings. Must match the settings used for decryption.

CryptoJsConfig fields

Unlike CryptoJS itself, sizes are given in bits and modes as strings.

FieldTypeRequiredDescription
mode'CBC' | 'CFB' | 'OFB' | 'CTR' | 'ECB'NoBlock cipher mode. Default: CBC.
padding'Pkcs7' | 'NoPadding'NoPadding scheme, applied in every mode as CryptoJS does. Default: Pkcs7.
keySizenumberNoKey size in bits. Default: 256.
ivSizenumberNoIV size in bits, ignored for ECB. Default: 128.
hasher'md5' | 'sha1' | 'sha256'NoDigest used by the key derivation. Default: md5.
iterationsnumberNoIterations of the key derivation. Default: 1.
saltSizenumberNoSalt size in bits. Default: 64.

Returns: string, Base64 text in the OpenSSL Salted__ format · Availability: Server

Note

CryptoJs.decrypt() always reads an 8-byte salt. Text encrypted with a saltSize other than 64 cannot be decrypted again.

decrypt(ciphertextB64: string, passphrase: string, config?: CryptoJsConfig): string

Decrypts Base64 text in the Salted__ format, as produced by CryptoJS or by CryptoJs.encrypt(), like CryptoJS.AES.decrypt(ciphertext, passphrase, cfg).toString(CryptoJS.enc.Utf8). Throws an error if the format is wrong or the passphrase or configuration does not match.

ParameterTypeDescription
ciphertextB64stringEncrypted text.
passphrasestringPassphrase used for encryption.
configCryptoJsConfigCipher settings used for encryption. See CryptoJs.encrypt().

Returns: string · Availability: Server

The Node.js crypto module, re-exported as is.

const token = Sys.Crypto.crypto.randomBytes(32).toString('hex')

Type: typeof crypto · Availability: Server

The node-forge library (npm package node-forge, version ^1.3.3), re-exported as is.

const cert = Sys.Crypto.forge.pki.certificateFromPem(certPem)

Type: typeof forge · Availability: Server

An RSA key pair, as returned by createKeyPair(). The constructor is private.

fromPemFormat(publicPem: string, privatePem: string): KeyPair

Creates a key pair from existing PEM-encoded keys, for example ones loaded from a configuration item. It is called on the class: Sys.Crypto.KeyPair.fromPemFormat(…).

ParameterTypeDescription
publicPemstringPublic key in PEM format.
privatePemstringPrivate key in PEM format.

Returns: KeyPair · Availability: Server

readonly publicPem: string

The public key in PEM format.

Type: string · Availability: Server

readonly privatePem: string

The private key in PEM format.

Type: string · Availability: Server

get publicDer(): forge.util.ByteStringBuffer

The public key in DER format, as a node-forge byte buffer.

Type: forge.util.ByteStringBuffer · Availability: Server

get privateDer(): forge.util.ByteStringBuffer

The private key in DER format, as a node-forge byte buffer.

Type: forge.util.ByteStringBuffer · Availability: Server

Encrypts, decrypts, signs and verifies data with OpenPGP (npm package openpgp, version ^6.1.0). Create an instance with the keys and passphrases to use; each method picks the ones it needs.

const { publicKey, privateKey } = await Sys.Crypto.SimplePgp.generateKeyPair({
userIDs: [{ name: 'Example App', email: 'app@example.com' }],
passphrase: 'key-passphrase',
})
const pgp = new Sys.Crypto.SimplePgp({ publicKey, privateKey, passphrase: 'key-passphrase' })
const encrypted = await pgp.encryptWithPublicKey('Confidential')
const { data } = await pgp.decryptWithPrivateKey(encrypted, { verifySignature: true })
constructor(options: SimplePgpOptions)

Creates an instance with the given keys and passphrases.

ParameterTypeDescription
optionsSimplePgpOptionsKeys and passphrases. Required.

SimplePgpOptions fields

FieldTypeRequiredDescription
publicKeystring | string[]NoOne or more armored public keys, used to encrypt and to verify signatures.
privateKeystring | string[]NoOne or more armored private keys, used to decrypt and to sign.
passphrasestring | string[]NoPassphrases that unlock the private keys. They are also the passwords for encryptWithPassphrase() and decryptWithPassphrase().
ivstringNoNot used.
generateKeyPair(options: KeyOptions & { format?: 'armored' }): Promise<SerializedKeyPair<string> & { revocationCertificate: string }>
generateKeyPair(options: KeyOptions & { format: 'binary' }): Promise<SerializedKeyPair<Uint8Array> & { revocationCertificate: string }>
generateKeyPair(options: KeyOptions & { format: 'object' }): Promise<KeyPair & { revocationCertificate: string }>

Generates a new OpenPGP key pair with openpgp’s generateKey. It is called on the class: Sys.Crypto.SimplePgp.generateKeyPair(…). The result has privateKey, publicKey and revocationCertificate.

ParameterTypeDescription
optionsKeyOptionsopenpgp’s key generation options, such as userIDs (required), passphrase, type and rsaBits. format sets the key format; default: armored.

Returns: Promise of the key pair · Availability: Server

encryptWithPublicKey(data: string | Buffer, options?: { algorithm?: keyof typeof enums.symmetric; compression?: keyof typeof enums.compression; format?: 'binary' }): Promise<Buffer>
encryptWithPublicKey(data: string | Buffer, options?: { algorithm?: keyof typeof enums.symmetric; compression?: keyof typeof enums.compression; format?: 'armored' | undefined }): Promise<string>
encryptWithPublicKey(data: string | Buffer, options?: { algorithm?: keyof typeof enums.symmetric; compression?: keyof typeof enums.compression; format?: 'armored' | 'binary' }): Promise<string | Buffer>

Encrypts data for the holders of the public keys. If the instance also has private keys, the message is signed with them.

ParameterTypeDescription
datastring | BufferData to encrypt.
options.algorithmstringSymmetric cipher, an openpgp enums.symmetric key. Default: aes256.
options.compressionstringCompression, an openpgp enums.compression key. Default: uncompressed.
options.format'armored' | 'binary'armored returns ASCII-armored text, binary a Buffer. Default: armored.

Returns: Promise<string> or Promise<Buffer>, depending on format · Availability: Server

encryptWithPassphrase(data: string | Buffer, options?: { algorithm?: keyof typeof enums.symmetric; compression?: keyof typeof enums.compression; format?: 'binary' }): Promise<Buffer>
encryptWithPassphrase(data: string | Buffer, options?: { algorithm?: keyof typeof enums.symmetric; compression?: keyof typeof enums.compression; format?: 'armored' | undefined }): Promise<string>
encryptWithPassphrase(data: string | Buffer, options?: { algorithm?: keyof typeof enums.symmetric; compression?: keyof typeof enums.compression; format?: 'armored' | 'binary' }): Promise<string | Buffer>

Encrypts data symmetrically with the passphrases of the instance; any one of them can decrypt it. The options are the same as for encryptWithPublicKey().

ParameterTypeDescription
datastring | BufferData to encrypt.
optionsobjectalgorithm, compression and format, as for encryptWithPublicKey().

Returns: Promise<string> or Promise<Buffer>, depending on format · Availability: Server

decryptWithPrivateKey(encryptedMessage: string | Buffer, options: { verifySignature: boolean }): Promise<DecryptMessageResult & { data: Buffer }>

Decrypts a message with the private keys of the instance. Armored and binary messages are both accepted.

ParameterTypeDescription
encryptedMessagestring | BufferThe encrypted message.
options.verifySignaturebooleanIf true, signatures are checked against the public keys of the instance.

Returns: Promise of openpgp’s DecryptMessageResult: data holds the decrypted bytes, signatures the signature verification results · Availability: Server

decryptWithPassphrase(encryptedMessage: string | Buffer): Promise<DecryptMessageResult & { data: Buffer }>

Decrypts a message that was encrypted with a passphrase, trying the passphrases of the instance.

ParameterTypeDescription
encryptedMessagestring | BufferThe encrypted message, armored or binary.

Returns: Promise of openpgp’s DecryptMessageResult, with the decrypted bytes in data · Availability: Server

signWithPrivateKey(data: string | Buffer, options?: { detachedSignature?: boolean; format?: 'binary' }): Promise<Buffer>
signWithPrivateKey(data: string | Buffer, options?: { detachedSignature?: boolean; format?: 'armored' | undefined }): Promise<string>
signWithPrivateKey(data: string | Buffer, options?: { detachedSignature?: boolean; format?: 'armored' | 'binary' }): Promise<string | Buffer>

Signs data with the private keys of the instance.

ParameterTypeDescription
datastring | BufferData to sign.
options.detachedSignaturebooleanIf true, returns only the signature; otherwise the signed message including the data. Default: false.
options.format'armored' | 'binary'Output format. Default: armored.

Returns: Promise<string> or Promise<Buffer>, depending on format · Availability: Server

verifyWithPublicKey(signedMessage: string | Buffer, options?: VerifyOptions): Promise<VerifyMessageResult<string>>
verifyWithPublicKey(unsignedData: string | Buffer, signature: string, options?: VerifyOptions): Promise<VerifyMessageResult<string>>

Verifies a signed message, or data with a detached armored signature, against the public keys of the instance.

ParameterTypeDescription
signedMessage / unsignedDatastring | BufferThe signed message, or the original data when a detached signature is given.
signaturestringThe detached signature, armored.
options.expectSignedbooleanIf true, verification fails with an error when the message is not validly signed.

Returns: Promise of openpgp’s VerifyMessageResult · Availability: Server

Note

A signed message that is not armored must be passed as Base64 text. A Buffer is first converted to UTF-8 text and then decoded as Base64, so raw binary messages fail to verify.

type HashAlgorithm = 'blake2b512' | 'blake2s256' | 'md4' | 'md5' | 'md5-sha1' | 'ripemd160' | 'rsa-sha1' | 'sha1' | 'sha224' | 'sha256' | 'sha3-224' | 'sha3-256' | 'sha3-384' | 'sha3-512' | 'sha384' | 'sha512' | 'sha512-224' | 'sha512-256' | 'shake128' | 'shake256' | 'sm3' | 'whirlpool'

Hash algorithms accepted by hash(). Which of them work depends on the OpenSSL build of the server’s Node.js.

Availability: Server

Options for createCa() and createCertificateFromCsr(). The fields are listed under createCertificateFromCsr().

Availability: Server

Options for the SimplePgp constructor. The fields are listed under SimplePgp.

Availability: Server