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:
Name | Type | Default | Description |
---|---|---|---|
secure | boolean | false | Decide to use a more secure generation, preventing the use of an entropy cache |
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 secure random data
Method to generate a secure random data of the desired length.
createSafeRandomData
public createSafeRandomData (
length: number
): Buffer;
Parameters:
Name | Type | Default | Description |
---|---|---|---|
length Required | number | The random data output length in bytes |
Outputs:
As output, it will return a Buffer <Buffer cc 2b.....cd a1 08>
Generate random password
Method to generate a random password with this set of characters: A-Z a-z 0-9 + = /
.
genRandomPassword
public genRandomPassword (
length: number
): string;
Parameters:
Name | Type | Default | Description |
---|---|---|---|
length Required | number | The password output length |
Outputs:
As output, it will return a string of this format: jh2EducrV7yH8tGAc8Jkdcso
Usage:
async createUserPassword(): Promise<string> {
const newPassword = this.cryptographyService.genRandomPassword(24);
...
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:
Name | Type | Default | Description |
---|---|---|---|
length | number | 256 | The symmetric key output length |
Outputs:
As output, it will return an object of type KeyObject.
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...
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=