Skip to content

Class: default

Cryptographic functions for hashing, random number generation, and key pair generation.

Example

ts
import cryptoh, { HashAlgorithm } from "cryptoh";

async function main() {
  // 👤 User registration (secure password storage)
  const password = "My$ecureP@ssword123";

  // Generate a unique salt for the user
  const salt = await cryptoh.random.generateSalt(16);

  // Concatenate password + salt and generate the hash
  const hashedPassword = await cryptoh.hash.generate(password + salt, HashAlgorithm.SHA512);

  console.log("Salt:", salt);
  console.log("Hashed password:", hashedPassword);

  // You would typically save this salt and hashedPassword to your database
  const storedCredentials = { salt, hashedPassword };

  // 👤 User login (password verification)
  const passwordAttempt = "My$ecureP@ssword123";

  // Recreate the hash with the stored salt and compare it to the stored hash
  const isPasswordValid = await cryptoh.hash.verify(
    passwordAttempt + storedCredentials.salt,
    storedCredentials.hashedPassword,
    HashAlgorithm.SHA512
  );

  console.log("Is password valid?", isPasswordValid); // true if matches

  // 🔐 Digital signature for sensitive payload (e.g., tokens, receipts, or important data)
  const payload = JSON.stringify({
    userId: 789,
    email: "user@example.com",
    timestamp: Date.now()
  });

  // Generate an RSA key pair
  const { publicKey, privateKey } = await cryptoh.keyPair.generate();

  // Sign the payload with the private key
  const signature = await cryptoh.sign.generate(payload, privateKey);

  console.log("Signature (base64):", Buffer.from(signature, "hex").toString("base64"));

  // Verify the signature using the public key
  const isSignatureValid = await cryptoh.sign.verify(payload, signature, publicKey);

  console.log("Is signature valid?", isSignatureValid); // true if signature matches
}

main();

Author

Heliomar Marques

Enumeration

algorithm

ts
static algorithm: typeof HashAlgorithm = HashAlgorithm;

The default hash algorithm used for hashing operations.

Default Value

ts
HashAlgorithm.SHA512

Hash Functions

hash

ts
static hash: object;

Hashing functions for generating and comparing hashes.

Generate Hash

generate()
ts
generate(text, algorithm): Promise<string>;

Generates a hash for the given text using the specified hash algorithm.

Parameters
text

string

The input text to hash.

algorithm

HashAlgorithm = HashAlgorithm.SHA512

The hash algorithm to use. Defaults to SHA512.

Returns

Promise<string>

A Promise that resolves to the generated hash as a hexadecimal string.

Throws

Will throw an error if the input text is empty or whitespace or if the algorithm is not supported.

Example
js
const hashedValue = await cryptor.hash.generate('myPassword');
console.log(hashedValue); // Outputs the hashed value of 'myPassword'

Verify Hash

verify()
ts
verify(
   text, 
   hash, 
algorithm): Promise<boolean>;

Compares a given text with a hash to determine if they match.

Parameters
text

string

The input text to compare.

hash

string

The hash to compare against.

algorithm

HashAlgorithm = HashAlgorithm.SHA512

The hash algorithm used for generating the hash. Defaults to SHA512.

Returns

Promise<boolean>

A Promise that resolves to true if the text matches the hash, false otherwise.

Throws

Will throw an error if the input text or hash is empty or whitespace.

Example
js
const isMatch = await cryptor.hash.verify('myPassword', hashedValue);
console.log(isMatch); // Outputs true if the text matches the hash, otherwise false

Key Pair Functions

keyPair

ts
static keyPair: object;

Key pair generation functions for creating RSA key pairs.

Generate Key Pair

generate()
ts
generate(): Promise<KeyPair>;

Generates a new 2048-bit RSA key pair and returns it as an object with publicKey and privateKey properties.

Returns

Promise<KeyPair>

A Promise that resolves to an object with publicKey and privateKey properties, both as PEM-formatted strings.

Throws

Will throw an error if key generation fails.

Example
js
const keyPair = await cryptor.keyPair.generate();
console.log(keyPair.publicKey); // Outputs the PEM-formatted public key
console.log(keyPair.privateKey); // Outputs the PEM-formatted private key

Random Functions

random

ts
static random: object;

Random number generation functions for generating cryptographically secure random values.

Generate Salt

generateSalt()
ts
generateSalt(length): Promise<string>;

Generates a cryptographically secure random salt value as a hexadecimal string.

Parameters
length

number = 16

The length of the salt in bytes. Defaults to 16.

Returns

Promise<string>

A Promise that resolves to a hexadecimal string representing the generated salt.

Throws

Will throw an error if the length is less than or equal to 0.

Example
js
const salt = await cryptor.random.generateSalt();
console.log(salt); // Outputs a random hexadecimal string of length 16.

Signature Functions

sign

ts
static sign: object;

Digital signature functions for signing and verifying data.

Generate Signature

generate()
ts
generate(
   data, 
   privateKey, 
algorithm): Promise<string>;

Generates a digital signature for the given data using the provided private key.

Parameters
data

string

The data to sign.

privateKey

string

The PEM-formatted private key to use for signing.

algorithm

HashAlgorithm = HashAlgorithm.SHA256

The hash algorithm used for signing. Defaults to SHA256.

Returns

Promise<string>

A Promise that resolves to the generated digital signature as a hexadecimal string.

Throws

Will throw an error if the input data or private key is empty or whitespace.

Example
js
const payload = JSON.stringify({id: 123, nome: "Heliomar", timestamp: Date.now()})
const  { publicKey, privateKey } = await cryptor.keyPair.generate();

const signature = await cryptor.sign.generate(payload, privateKey);
console.log(Buffer.from(signature).toString("base64"));

const isValid = await cryptor.sign.verify(payload, signature, publicKey);
console.log(isValid); // Outputs true

Verify Signature

verify()
ts
verify(
   data, 
   signature, 
   publicKey, 
algorithm): Promise<boolean>;

Verifies a digital signature against the given data using the public key.

Parameters
data

string

The data that was originally signed.

signature

string

The signature to verify.

publicKey

string

The PEM-formatted public key to use for verification.

algorithm

HashAlgorithm = HashAlgorithm.SHA256

The hash algorithm used for signing. Defaults to SHA256.

Returns

Promise<boolean>

A Promise that resolves to true if the signature is valid, false otherwise.

Throws

Will throw an error if the input data, signature, or public key is empty or whitespace.

Example
js
const isValid = await cryptor.sign.verify(payload, signature, publicKey);
console.log(isValid); // Outputs true if the signature is valid, otherwise false