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
Functions
Section titled “Functions”hash()
Section titled “hash()”hash(data: string | Buffer, algorithm: HashAlgorithm, hashEncoding?: 'hex' | 'base64'): stringCalculates the hash of the data with the given algorithm, using Node.js crypto.createHash. Strings are hashed as UTF-8.
| Parameter | Type | Description |
|---|---|---|
data | string | Buffer | Data to hash. |
algorithm | HashAlgorithm | Hash algorithm, for example sha256. |
hashEncoding | 'hex' | 'base64' | Encoding of the returned hash. Default: hex. |
Returns: string · Availability: Server
createKeyPair()
Section titled “createKeyPair()”createKeyPair(bits?: number): KeyPairGenerates a new RSA key pair. Both keys are PEM-encoded in PKCS#1 format.
| Parameter | Type | Description |
|---|---|---|
bits | number | Key length in bits. Default: 2048. |
Returns: KeyPair · Availability: Server
createCa()
Section titled “createCa()”createCa(caKeyPair: KeyPair, subjectAttributes: SubjectAttribute[], options?: CreateCertificateOptions): stringCreates a self-signed certificate authority (CA) certificate for the key pair. Use the result with createCertificateFromCsr() to issue certificates.
| Parameter | Type | Description |
|---|---|---|
caKeyPair | KeyPair | Key pair of the CA. |
subjectAttributes | SubjectAttribute[] | Distinguished name of the CA. See createCsr(). |
options | CreateCertificateOptions | Validity, extensions and digest. isCertificateAuthority is always set to true. See createCertificateFromCsr(). |
Returns: string, the certificate in PEM format · Availability: Server
createCsr()
Section titled “createCsr()”createCsr(csrKeyPair: KeyPair, subjectAttributes: SubjectAttribute[]): stringCreates a certificate signing request (CSR) for the public key of the key pair, signed with its private key using SHA-512.
| Parameter | Type | Description |
|---|---|---|
csrKeyPair | KeyPair | Key pair the certificate is requested for. |
subjectAttributes | SubjectAttribute[] | Distinguished name of the subject. |
SubjectAttribute fields
Each entry is one attribute of the distinguished name, in the format of node-forge.
| Field | Type | Required | Description |
|---|---|---|---|
name | string | No | Attribute name, such as commonName, organizationName or countryName. Give either name, shortName or type. |
shortName | string | No | Short attribute name, such as CN, O or C. |
type | string | No | Attribute OID. |
value | any[] | string | No | Attribute value. |
extensions | any[] | No | Extensions, as node-forge defines them. |
Returns: string, the CSR in PEM format · Availability: Server
createCertificateFromCsr()
Section titled “createCertificateFromCsr()”createCertificateFromCsr(csrPem: string, ca: string, caKeyPair: KeyPair, options?: CreateCertificateOptions): stringIssues a certificate for a CSR, signed with the CA’s private key. The certificate is valid from now for the given number of days.
| Parameter | Type | Description |
|---|---|---|
csrPem | string | The CSR in PEM format. |
ca | string | The CA certificate in PEM format; its subject becomes the issuer. An empty string makes the certificate self-signed. |
caKeyPair | KeyPair | Key pair of the CA. |
options | CreateCertificateOptions | Validity, extensions and digest. |
CreateCertificateOptions fields
| Field | Type | Required | Description |
|---|---|---|---|
subjectAltNames | string[] | No | DNS names for the subject alternative name extension. Cannot be combined with a subjectAltName entry in extensions. |
isCertificateAuthority | boolean | No | If true, adds or completes a basicConstraints extension with cA: true. |
validityDays | number | No | Validity in days. Default: 365. |
extensions | any[] | No | Certificate extensions in node-forge format. |
messageDigestAlgorithm | 'md5' | 'sha1' | 'sha256' | 'sha384' | 'sha512' | 'sha512/224' | 'sha512/256' | No | Digest 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()
Section titled “loadTlsCertificateFromWebsite()”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.
| Parameter | Type | Description |
|---|---|---|
hostname | string | Host to connect to. |
port | number | Port. Default: 443. |
servername | string | Server name sent for SNI. Default: hostname. |
Returns: Promise<DetailedPeerCertificate>, a Node.js tls certificate object · Availability: Server
CryptoJs.encrypt()
Section titled “CryptoJs.encrypt()”encrypt(plaintext: string, passphrase: string, config?: CryptoJsConfig): stringEncrypts 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.
| Parameter | Type | Description |
|---|---|---|
plaintext | string | Text to encrypt. It is encoded as UTF-8. |
passphrase | string | Passphrase the key is derived from. |
config | CryptoJsConfig | Cipher settings. Must match the settings used for decryption. |
CryptoJsConfig fields
Unlike CryptoJS itself, sizes are given in bits and modes as strings.
| Field | Type | Required | Description |
|---|---|---|---|
mode | 'CBC' | 'CFB' | 'OFB' | 'CTR' | 'ECB' | No | Block cipher mode. Default: CBC. |
padding | 'Pkcs7' | 'NoPadding' | No | Padding scheme, applied in every mode as CryptoJS does. Default: Pkcs7. |
keySize | number | No | Key size in bits. Default: 256. |
ivSize | number | No | IV size in bits, ignored for ECB. Default: 128. |
hasher | 'md5' | 'sha1' | 'sha256' | No | Digest used by the key derivation. Default: md5. |
iterations | number | No | Iterations of the key derivation. Default: 1. |
saltSize | number | No | Salt 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.
CryptoJs.decrypt()
Section titled “CryptoJs.decrypt()”decrypt(ciphertextB64: string, passphrase: string, config?: CryptoJsConfig): stringDecrypts 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.
| Parameter | Type | Description |
|---|---|---|
ciphertextB64 | string | Encrypted text. |
passphrase | string | Passphrase used for encryption. |
config | CryptoJsConfig | Cipher settings used for encryption. See CryptoJs.encrypt(). |
Returns: string · Availability: Server
Properties
Section titled “Properties”crypto
Section titled “crypto”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
Classes
Section titled “Classes”KeyPair
Section titled “KeyPair”An RSA key pair, as returned by createKeyPair(). The constructor is private.
fromPemFormat()
Section titled “fromPemFormat()”fromPemFormat(publicPem: string, privatePem: string): KeyPairCreates 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(…).
| Parameter | Type | Description |
|---|---|---|
publicPem | string | Public key in PEM format. |
privatePem | string | Private key in PEM format. |
Returns: KeyPair · Availability: Server
publicPem
Section titled “publicPem”readonly publicPem: stringThe public key in PEM format.
Type: string · Availability: Server
privatePem
Section titled “privatePem”readonly privatePem: stringThe private key in PEM format.
Type: string · Availability: Server
publicDer
Section titled “publicDer”get publicDer(): forge.util.ByteStringBufferThe public key in DER format, as a node-forge byte buffer.
Type: forge.util.ByteStringBuffer · Availability: Server
privateDer
Section titled “privateDer”get privateDer(): forge.util.ByteStringBufferThe private key in DER format, as a node-forge byte buffer.
Type: forge.util.ByteStringBuffer · Availability: Server
SimplePgp
Section titled “SimplePgp”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()
Section titled “constructor()”constructor(options: SimplePgpOptions)Creates an instance with the given keys and passphrases.
| Parameter | Type | Description |
|---|---|---|
options | SimplePgpOptions | Keys and passphrases. Required. |
SimplePgpOptions fields
| Field | Type | Required | Description |
|---|---|---|---|
publicKey | string | string[] | No | One or more armored public keys, used to encrypt and to verify signatures. |
privateKey | string | string[] | No | One or more armored private keys, used to decrypt and to sign. |
passphrase | string | string[] | No | Passphrases that unlock the private keys. They are also the passwords for encryptWithPassphrase() and decryptWithPassphrase(). |
iv | string | No | Not used. |
generateKeyPair()
Section titled “generateKeyPair()”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.
| Parameter | Type | Description |
|---|---|---|
options | KeyOptions | openpgp’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()
Section titled “encryptWithPublicKey()”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.
| Parameter | Type | Description |
|---|---|---|
data | string | Buffer | Data to encrypt. |
options.algorithm | string | Symmetric cipher, an openpgp enums.symmetric key. Default: aes256. |
options.compression | string | Compression, 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()
Section titled “encryptWithPassphrase()”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().
| Parameter | Type | Description |
|---|---|---|
data | string | Buffer | Data to encrypt. |
options | object | algorithm, compression and format, as for encryptWithPublicKey(). |
Returns: Promise<string> or Promise<Buffer>, depending on format · Availability: Server
decryptWithPrivateKey()
Section titled “decryptWithPrivateKey()”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.
| Parameter | Type | Description |
|---|---|---|
encryptedMessage | string | Buffer | The encrypted message. |
options.verifySignature | boolean | If 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()
Section titled “decryptWithPassphrase()”decryptWithPassphrase(encryptedMessage: string | Buffer): Promise<DecryptMessageResult & { data: Buffer }>Decrypts a message that was encrypted with a passphrase, trying the passphrases of the instance.
| Parameter | Type | Description |
|---|---|---|
encryptedMessage | string | Buffer | The encrypted message, armored or binary. |
Returns: Promise of openpgp’s DecryptMessageResult, with the decrypted bytes in data · Availability: Server
signWithPrivateKey()
Section titled “signWithPrivateKey()”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.
| Parameter | Type | Description |
|---|---|---|
data | string | Buffer | Data to sign. |
options.detachedSignature | boolean | If 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()
Section titled “verifyWithPublicKey()”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.
| Parameter | Type | Description |
|---|---|---|
signedMessage / unsignedData | string | Buffer | The signed message, or the original data when a detached signature is given. |
signature | string | The detached signature, armored. |
options.expectSigned | boolean | If 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.
HashAlgorithm
Section titled “HashAlgorithm”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
CreateCertificateOptions
Section titled “CreateCertificateOptions”Options for createCa() and createCertificateFromCsr(). The fields are listed under createCertificateFromCsr().
Availability: Server
SimplePgpOptions
Section titled “SimplePgpOptions”Options for the SimplePgp constructor. The fields are listed under SimplePgp.
Availability: Server