Skip to main content
Version: 2.x

Generics

This section contains some generic methods to perform typical operations

Generate an UUIDv4

Method to generate a UUID version 4.

genUUID

public genUUID (
secure = false
): string;

Parameters:

NameTypeDefaultDescription
secure RequiredbooleanfalseDecide to use a more secure generation using entropy

Outputs:

As output, it will return a string of this format 0E928AD4-4D11-4C7C-A83A-8DD7361FFC01

Usage:

async someAwesomeMethod(): Promise<string> {
const newUUID = this.cryptographyService.genUUID(true);
...
return newUUID;
}

Generate random password

Method to generate a random password with this set of characters: a-z 0-9 if hex used, or A-Z a-z 0-9 + = / if base64 used.

genRandomPassword

public genRandomPassword (
length: number,
encoding: 'base64' | 'hex'
): string;

Parameters:

NameTypeDefaultDescription
length RequirednumberThe password output length
encoding Requiredbase64 | hexThe password output format hexadecimal or base64

Outputs:

As output, it will return a string of this format:

  • base64: jh2EducrV7yH8tGAc8Jkdcso
  • hex: b4da8e4aba39c9f70dde717d

Usage:

async createUserPassword(): Promise<string> {
const newPassword = this.cryptographyService.genRandomPassword(24, 'base64');
...
return newPassword;
}

Generate symmetric key

Method to generate a cryptographically secure SymmetricKey in KeyObject format to use in subsequent encryption/decryption operations.

generateSymmetricKey

public generateSymmetricKey (
length: number = 256
): KeyObject;

Parameters:

NameTypeDefaultDescription
lengthnumber256The symmetric key output length

Outputs:

As output, it will return an object of type KeyObject.

info

If you want to export this KeyObject to different types, you can access the .export method

Usage:

async createSymmetricKey(): Promise<void> {
const new32KeySize = this.cryptographyService.generateSymmetricKey(32);
console.log(new32KeySize.export().toString('hex')); // f32.....4ee

const aes128KeySize = this.cryptographyService.generateSymmetricKey(128);
console.log(aes128KeySize.export().toString('hex')); // e89.....41e

const aes192KeySize = this.cryptographyService.generateSymmetricKey(192);
console.log(aes192KeySize.export().toString('base64')); // 8OI.....ZQ=

const aes256KeySize = this.cryptographyService.generateSymmetricKey(256);
console.log(aes256KeySize.export()); // <Buffer cc 2b.....cd a1 08>
}

🛟 Tips

Remember that...
info

Remember that buffers could be transformed to utf8, hex, base64, latin,... using the toString() method.

let passwordAsBuffer: Buffer = someMethodThatReturnsABuffer();

console.log(passwordAsBuffer.toString('hex')) // f32.....4ee
console.log(passwordAsBuffer.toString('base64')) // 8OI.....ZQ=