3.2.0 • Published 6 months ago

@alessiofrittoli/crypto-key v3.2.0

Weekly downloads
-
License
MIT
Repository
github
Last release
6 months ago

Crypto Key šŸ”‘

NPM Latest Version Coverage Status Socket Status NPM Monthly Downloads Dependencies

GitHub Sponsor

Lightweight TypeScript library for Node.js Cryptographic keys

Table of Contents


Getting started

The crypto-key library it's part of the crypto utility libraries and can be installed by running the following command:

npm i @alessiofrittoli/crypto-key

or using pnpm

pnpm i @alessiofrittoli/crypto-key

API Reference

This module supports different input data types and it uses the coerceToUint8Array utility function from @alessiofrittoli/crypto-buffer to convert it to a Uint8Array.

Hash Class

The Hash class provides utility methods for hashing strings and validating hashed values using cryptographic algorithms.\ It supports a variety of algorithms based on the OpenSSL version available on the platform.

Methods
Hash.digest()

Generates a hash of a given string using a specified cryptographic algorithm.

ParameterTypeDefaultDescription
inputcrypto.BinaryLike-The data to be hashed.
algorithmAlgo.Hash \| Algo.OtherHash'SHA-256'(Optional) The cryptographic hash algorithm.

Returns

Type: Buffer

The resulting hash digest Buffer.


Hash.isValid()

Compares input data with a hashed value to verify if they match.

ParameterTypeDefaultDescription
inputcrypto.BinaryLike-The raw input data.
digestCoerceToUint8ArrayInput-The hash digest value to compare against.
algorithmAlgo.Hash \| Algo.OtherHash'SHA-256'(Optional) The hash algorithm previously used while generating the hashed data.

Returns

Type: boolean

true if the input matches the hashed digest value, false otherwise.


Example Usage
Generating a Hash
import { Hash } from '@alessiofrittoli/crypto-key'
// or
import { Hash } from '@alessiofrittoli/crypto-key/Hash'

console.log(
  Hash.digest( 'raw string value' )
    .toString( 'hex' )
)
Validating a Hash
import { Hash } from '@alessiofrittoli/crypto-key'
// or
import { Hash } from '@alessiofrittoli/crypto-key/Hash'

const rawInput	= 'raw string value'
const hash		= Hash.digest( rawInput )
const isValid	= Hash.isValid( rawInput, hash )

console.log( isValid ) // Outputs: `true`

Hmac Class

The Hmac class provides utility methods for generating and validating HMAC (Hash-based Message Authentication Code) values using cryptographic algorithms.

Methods
Hmac.digest()

Generates a Hash-based Message Authentication Code (HMAC) for a given message using a secret key.

ParameterTypeDefaultDescription
messagecrypto.BinaryLike-The data to be hashed.
secretcrypto.BinaryLike \| crypto.KeyObject-The secret key to use for generating the HMAC.
algorithmAlgo.Hash'SHA-256'(Optional) The cryptographic hash algorithm.
encodingBufferEncoding-(Optional) The encoding for the output string.
optionsstream.TransformOptions-(Optional) Additional stream transform options.

Returns

Type: HmacReturnType<T>

The resulting HMAC value. If encoding is specified, the output is a string in the specified encoding; otherwise, a Buffer.


Hmac.isValid()

Validates a given HMAC value against a message and secret key.

ParameterTypeDefaultDescription
digestCoerceToUint8ArrayInput-The HMAC digest to validate.
messagecrypto.BinaryLike-The original message used to generate the HMAC.
secretcrypto.BinaryLike \| crypto.KeyObject-The secret key used for generating the HMAC.
algorithmAlgo.Hash'SHA-256'(Optional) The hash algorithm used for generating the HMAC.
encodingBufferEncoding-(Optional) The encoding used to generate the hash output.
optionsstream.TransformOptions-(Optional) Additional stream transform options used for generating the HMAC.

Returns

Type: boolean

true if the provided HMAC matches the generated one. false otherwise.


Example Usage
Generating an HMAC
import { Hmac } from '@alessiofrittoli/crypto-key'
// or
import { Hmac } from '@alessiofrittoli/crypto-key/Hmac'

console.log(
  Hmac.digest( 'raw string value', 'mysecretkey', 'SHA-256', 'hex' )
) // Outputs the HMAC value in HEX format.
Validating an HMAC
import { Hmac } from '@alessiofrittoli/crypto-key'
// or
import { Hmac } from '@alessiofrittoli/crypto-key/Hmac'

const message	= 'raw string value'
const secret	= 'mysecretkey'
const hmac		= Hmac.digest( message, secret )

console.log(
  Hmac.isValid( hmac, message, secret )
) // Outputs: `true`

Scrypt Class

The Scrypt class provides methods for hashing and securely comparing keys using the scrypt key derivation algorithm.\ It supports customizable options for computational cost, memory usage, and parallelization to balance security and performance.

Scrypt Type Interfaces
ScryptOptions

Defines customization options for the scrypt algorithm.

PropertyTypeDefaultDescription
costnumber16384Computational cost factor. Must be a power of 2. Higher values increase security but are slower.
blockSizenumber8Memory cost factor. Higher values increase memory usage, improving security against GPU attacks.
parallelizationnumber1Parallelization factor. Determines how many threads can be used.
maxmemnumber32 * 1024 * 1024 (32MB)Maximum memory (in bytes) to be used during key derivation.
Nnumber16384Alias for cost.
rnumber8Alias for blockSize.
pnumber1Alias for parallelization.
Scopecost (N)blockSize (r)parallelization (p)maxmem
Standard security (default)163848132 MB
High security6553616164 MB
Limited resources81924116 MB

ScryptHashOptions

Defines options for the hash and isValid methods.

PropertyTypeDefaultDescription
lengthnumber64The hash length. Must be between 16 and 256.
saltLengthnumber32The salt length. Must be between 16 and 64.
optionsScryptOptionsSee aboveCustom options for the scrypt algorithm.

Methods
Scrypt.hash()

Generates a hash for a given key using the scrypt key derivation algorithm.

ParameterTypeDefaultDescription
keycrypto.BinaryLike-The key to hash.
optionsScryptHashOptions-(Optional) Configuration options for hashing.

Returns

Type: Buffer

A Buffer containing the salt (first saltLength bytes) followed by the derived hash.


Scrypt.isValid()

Validates the given key with the given hash.

ParameterTypeDefaultDescription
keycrypto.BinaryLike-The key to validate.
hashCoerceToUint8ArrayInput-The hash to compare against.
optionsScryptHashOptions-(Optional) Configuration options. Must match those used for hashing.

Returns

Type: boolean

true if the key is valid, false otherwise.


Example Usage
Hashing a Key
import { Scrypt } from '@alessiofrittoli/crypto-key'
// or
import { Scrypt } from '@alessiofrittoli/crypto-key/Scrypt'

console.log(
  Scrypt.hash( 'user-provided-password' )
    .toString( 'hex' )
) // Outputs the hash in HEX format.
Validating a Key
import { Scrypt } from '@alessiofrittoli/crypto-key'
// or
import { Scrypt } from '@alessiofrittoli/crypto-key/Scrypt'

import { Scrypt } from './Scrypt';

const password	= 'user-provided-password';
const hash		= Scrypt.hash( password, { length: 32, saltLength: 16 } )

console.log(
  Scrypt.isValid( password, hash, { length: 32, saltLength: 16 } )
) // Outputs: true

Development

Install depenendencies

npm install

or using pnpm

pnpm i

Build the source code

Run the following command to test and build code for distribution.

pnpm build

ESLint

warnings / errors check.

pnpm lint

Jest

Run all the defined test suites by running the following:

# Run tests and watch file changes.
pnpm test:watch

# Run tests in a CI environment.
pnpm test:ci

Run tests with coverage.

An HTTP server is then started to serve coverage files from ./coverage folder.

āš ļø You may see a blank page the first time you run this command. Simply refresh the browser to see the updates.

test:coverage:serve

Contributing

Contributions are truly welcome!

Please refer to the Contributing Doc for more information on how to start contributing to this project.

Help keep this project up to date with GitHub Sponsor.

GitHub Sponsor


Security

If you believe you have found a security vulnerability, we encourage you to responsibly disclose this and NOT open a public issue. We will investigate all legitimate reports. Email security@alessiofrittoli.it to disclose any security vulnerabilities.

Made with ā˜•

3.2.0

6 months ago

3.1.0

7 months ago

3.0.0

7 months ago

2.2.0

9 months ago

2.1.0

9 months ago

2.0.0

10 months ago

1.0.0

11 months ago