Cryptography

2 min read

Several low-level methods are available to handle encryption. You may also consider the JOSE functions for high-level requirements.

Hash

Use the hash function for basic hashes.

hash(input: Buffer | string, algoritm: CryptHashAlgorithm): string;

The algorithm is one of "md5", "sha1", "sha256", or "sha512". The output is provided as a hexadecimal string.

You can use the more secure pbkdf2 algorithm to hash passwords.

pbkdf2: (
  password: string | Buffer,
  salt: string | Buffer,
  iterations?: number,
  keylen?: number,
  digest?: CryptHashAlgorithm
) => Promise<Buffer>;

HMAC

Use the hmac function for basic HMAC signatures. The algorithm is one of "md5", "sha1", "sha256", or "sha512".

hmac(input: Buffer | string, secret: Buffer | string, algoritm: CryptHashAlgorithm): string;

The output is provided as a hexadecimal string.

Ed25519

Methods for handling elliptic curve signatures using the Ed25519 algorithm.

generateEd25519KeyPair(): Promise<{
  private: string;
  public: string;
}>;
signEd25519(input: Buffer | string, privateKey: Buffer | string): string;
verifyEd25519(
  input: Buffer | string,
  signature: Buffer | string,
  publicKey: Buffer | string
): boolean;

RSA

Methods for signing and verifying RSA signatures. Output is provided in base64 format.

generateRsaKeyPair(
  modulusLength: 1024 | 2048 = 2048,
  format: 'der' | 'pem' = 'pem'
): Promise<{
  private: string;
  public: string;
}>;
signRsa(input: Buffer | string, privateKey: Buffer | string): string;
verifyRsa(
  input: Buffer | string,
  signature: Buffer | string,
  publicKey: Buffer | string
): boolean;

Constant time comparison

You can use this method to check if two strings or buffers are equal in constant time. Use this when checking security credentials to prevent timing attacks.

compare(a: Buffer | string, b: Buffer | string): boolean;

Random bytes

Generate a cryptographic strong sequence of random bytes. The output is provided as a buffer.

randomBytes(length: number): Buffer;

X509 certificates

Parse an X509 certificate (SSL certificate, for example).

x509(pem: string) => CryptCertificate;
type CryptCertificate = {
  ca: boolean;
  fingerprint: string;
  fingerprint256: string;
  issuer: string;
  publicKey: string;
  raw: string;
  serialNumber: string;
  subject: string;
  subjectAltName: string[];
  validFrom: string;
  validTo: string;
};