npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@payello-module/encryption

v1.20240509.725

Published

Encryption Module

Downloads

28

Readme

Encryption Module

This TypeScript module provides powerful encryption and hashing functionalities to enhance the security of your applications. Utilize industry-standard algorithms such as SHA, AES, RSA, and HMAC to protect your data effectively. Additionally, leverage advanced techniques like Bcrypt, TOTP, Base32 encoding, and CryptoUtil for robust security measures.

Features

  • SHA hashing: Includes support for SHA-1, SHA-256, SHA-384, and SHA-512 hashing algorithms.
  • AES-256 encryption: Enables encryption and decryption using CryptoKey functionality, with features like random IV generation and JWK export.
  • RSA-2048 encryption: Implementation of RSA encryption for secure data handling.
  • HMAC-SHA hashing: Supports HMAC with SHA-1, SHA-256, and SHA-512 for added security.
  • Hybrid Crypto: Combines RSA-2048 and AES-GCM encryption methods to protect data using both public key encryption and symmetric key encryption.
  • Bcrypt: Secure password hashing technique designed to resist brute-force attacks and scale effectively with hardware improvements.
  • TOTP: Time-based one-time password (TOTP) algorithm support for enhanced authentication security.
  • Base32 encoding: Enables encoding and decoding data using the Base32 encoding scheme.
  • CryptoUtil: Provides access to advanced encryption functions such as SubtleCrypto, getRandomValues(), and randomUUID(), delivering a comprehensive Web Crypto API implementation.
  • BIP39 Mnemonic Generator and Validator: Generates and validates BIP39 mnemonic phrases used for deterministic seed generation.

Installation

To include this module in your project, you will need to install it from your preferred package registry or include it from its source location.

If this module is published on a package registry, you can install it using npm or yarn:

npm install @payello-module/encryption
# or
yarn add @payello-module/encryption

Usage

AES-256 Encryption and Decryption

The Aes256 class provides methods for encrypting and decrypting data using the Advanced Encryption Standard (AES) with a block size of 128 bits and a key size of 256 bits.

Constructor

Creates an instance of Aes256 with a specified encryption key and optional initialization vector.

  • key: The encryption key as a CryptoKey object.
  • initializationVector: Optional. The initialization vector as a Uint8Array. If not provided, a new one is randomly generated.

Encrypting Data

To encrypt an ArrayBuffer using the current key and initialization vector:

import { Aes256 } from '@payello-module/encryption';

const aes = new Aes256(encryptionKey, initializationVector);
aes.encryptData(data).then((encryptedData) => {
    console.log('Encrypted data:', encryptedData);
});

The encryptData method takes an ArrayBuffer as input and returns a promise that resolves to the encrypted data as an ArrayBuffer.

Decrypting Data

To decrypt an encrypted ArrayBuffer using the current key and initialization vector:

import { Aes256 } from '@payello-module/encryption';

const aes = new Aes256(encryptionKey, initializationVector);
aes.decryptData(encryptedData).then((decryptedData) => {
    console.log('Decrypted data:', decryptedData);
});

The decryptData method decrypts the input ArrayBuffer and returns a promise that resolves to the decrypted data as an ArrayBuffer.

Key Management

  • exportKey: Returns the CryptoKey used for encryption and decryption.
  • exportJwk: Returns a promise that resolves to a JSON Web Key (JWK) and the initialization vector used.
  • static importJwk: Creates a new Aes256 instance with a specified JWK and initialization vector.
  • static create: Generates a new Aes256 instance with a randomly created key and initialization vector.

Base32 Encoding and Decoding

The Base32 class provides functionality for encoding and decoding data using the Base32 algorithm. Base32 encoding is used to convert binary data into a human-readable format that is safe for use in text-based protocols or data formats.

Encoding

To encode data using Base32:

import { Base32 } from '@payello-module/encryption';

// Encode data as Base32
const encodedData = Base32.encode('Your data here');
console.log(encodedData);

The encode method of the Base32 class allows you to encode a string or an array of numbers as Base32. By default, it returns the encoded data as a string. If you pass true as the second argument, it will return the encoded data as a Uint8Array.

Decoding

To decode data encoded in Base32:

import { Base32 } from '@payello-module/encryption';

// Decode Base32 data
const decodedData = Base32.decode('Encoded data here');
console.log(decodedData);

The decode method of the Base32 class allows you to decode a Base32-encoded string or an array of numbers. By default, it returns the decoded data as a string. If you pass true as the second argument, it will return the decoded data as a Uint8Array.

Bcrypt

The Bcrypt class provides functionality for cryptographic hashing and encryption using the Bcrypt algorithm.

Random Number Generation

  • random(len: number): Array<number>: Generates cryptographically secure random bytes of the specified length.

  • _randomFallback(len: number): Array<number>: Fallback function to generate pseudo-random bytes for environments where secure random number generation is not available.

  • setRandomFallback(random: function(number): Array<number>): void: Sets a custom pseudo-random number generator function as a fallback if no secure random implementation is available.

Salt Generation

  • genSaltSync(rounds?: number, seed_length?: number): string: Synchronously generates a salt with the option to specify the number of rounds.

  • genSalt(rounds: number | function, seed_length: number | function, callback?: function): Promise: Asynchronously generates a salt with the option to specify the number of rounds.

Hashing

  • hashSync(s: string, salt?: number | string): string: Synchronously generates a hash for the given string with an optional salt.

  • hash(s: string, salt: number | string, callback: function, progressCallback: function): Promise: Asynchronously generates a hash for the given string with a salt.

Comparison

  • compareSync(s: string, hash: string): boolean: Synchronously compares a string against a hash and returns true if they match.

  • compare(s: string, hash: string, callback: function, progressCallback: function): Promise: Asynchronously compares a string against a hash.

Utility Functions

  • getRounds(hash: string): number: Extracts the number of encryption rounds used from a hash.

  • getSalt(hash: string): string: Extracts the salt portion from a hash without validating the hash.

  • encodeBase64(b: Array<number>, len: number): string: Encodes a byte array to base64 using the custom bcrypt alphabet.

  • decodeBase64(s: string, len: number): Array<number>: Decodes a base64 encoded string to a byte array using the custom bcrypt alphabet.

Safe String Comparison

  • safeStringCompare(known: string, unknown: string): boolean: Compares two strings of the same length in constant time for secure comparison.

HMAC SHA Hashing Utility

The HmacSha class provides utility methods for HMAC SHA hashing with different algorithms such as SHA-1, SHA-256, and SHA-512.

Algorithm Identifier

The ALGORITHM property in the HmacSha class represents the algorithm identifier used for HMAC hashing. This identifier can be of different types like AlgorithmIdentifier, RsaHashedImportParams, EcKeyImportParams, HmacImportParams, or AesKeyAlgorithm.

Encrypting Data

To encrypt data using HMAC SHA-512:

import { HmacSha512 } from '@payello-module/encryption';

// Encrypt data with HMAC SHA-512
HmacSha512.encrypt('Your data here', 'Your secret key here').then((hash) => {
    console.log(hash);
});

The encrypt method of the HmacSha512 class allows you to encrypt plain text data using HMAC SHA-512 hashing. It takes the data to encrypt, the secret key for encryption, and an optional boolean parameter returnRaw (default or false) to control the return type.

Verifying Data

To verify data with an HMAC SHA-512 signature:

import { HmacSha512 } from '@payello-module/encryption';

// Verify data with HMAC SHA-512 signature
HmacSha512.verify('Your data here', 'HMAC signature here', 'Your secret key here').then((isValid) => {
    console.log(isValid);
});

The verify method of the HmacSha512 class allows you to compare plain text data against an HMAC SHA-512 signature using the secret key. It returns a boolean indicating whether the verification succeeded.

Hybrid Crypto

The HybridCrypto class provides functionality for hybrid cryptography, combining symmetric and asymmetric encryption techniques for secure data handling.

Constructor

To create a new instance of the HybridCrypto class with a key pair:

import { HybridCrypto } from '@payello-module/encryption';

// Initialize with a key pair
const hybridCrypto = new HybridCrypto(keyPair);

The constructor of the HybridCrypto class initializes a new instance with a provided RSA key pair for encryption and decryption operations. The keyPair parameter can be a partial CryptoKeyPair object, providing either privateKey or publicKey.

Encrypt Data

To encrypt data using AES-GCM with a generated symmetric key and then encrypt the symmetric key using RSA-OAEP with the public key from the key pair:

// Encrypt data
const encryptedData = await hybridCrypto.encryptData(data);
console.log(encryptedData);

The encryptData method encrypts the provided data as an ArrayBuffer using AES-GCM with a generated symmetric key and then encrypts the symmetric key with RSA-OAEP. It returns an object containing the initialization vector (iv), the encrypted data, and the encrypted symmetric key.

Decrypt Data

To decrypt data encrypted with AES-GCM and RSA-OAEP:

// Decrypt data
const decryptedData = await hybridCrypto.decryptData(iv, encryptedData, encryptedKey);
console.log(decryptedData);

The decryptData method decrypts the provided encrypted data using AES-GCM with the symmetric key, which is decrypted using RSA-OAEP with the private key from the key pair. It returns the decrypted data as an ArrayBuffer.

Key Operations

The HybridCrypto class provides methods for key import, export, generation, and encryption/decryption operations:

  • exportPrivateKey: Exports the private key as a JSON Web Key.
  • exportPublicKey: Exports the public key as a JSON Web Key.
  • importPrivateKey: Imports an RSA private key from a JSON Web Key object.
  • importPublicKey: Imports an RSA public key from a JSON Web Key object.
  • importKeys: Imports both RSA private and public keys from JSON Web Key objects.
  • create: Generates a new RSA key pair.
  • createKeys: Generates new RSA key pairs, exports them as base64-encoded strings.
  • importAndEncrypt: Imports a public key, encrypts a string, and returns the encrypted result.
  • importAndDecrypt: Imports a private key, decrypts an encrypted string, and returns the decrypted result.

These methods facilitate key handling, encryption, and decryption in hybrid cryptographic scenarios.

RSA 2048 Encryption and Decryption

The Rsa2048 class provides functionalities for encrypting and decrypting data using the RSA-OAEP cipher suite with a 2048-bit key. RSA encryption is asymmetric encryption that uses a public key to encrypt data and a private key to decrypt it securely.

Constructor

Construct an instance of Rsa2048 with a given key pair:

import { Rsa2048 } from '@payello-module/encryption';

// Initialize with a key pair
const rsa = new Rsa2048({ publicKey, privateKey });

The constructor of the Rsa2048 class accepts an object containing RSA public and/or private keys in the CryptoKeyPair format.

Encrypting Data

To encrypt data using the RSA public key:

import { Rsa2048 } from '@payello-module/encryption';

// Encrypt data
const encryptedData = await rsa.encryptData(dataToEncrypt);

The encryptData method takes an ArrayBuffer of data to be encrypted and returns a Promise that resolves to an ArrayBuffer of the encrypted data.

Decrypting Data

To decrypt data using the RSA private key:

import { Rsa2048 } from '@payello-module/encryption';

// Decrypt data
const decryptedData = await rsa.decryptData(dataToDecrypt);

The decryptData method receives an ArrayBuffer of data to be decrypted and returns a Promise that resolves to an ArrayBuffer of the decrypted data.

Key Operations

  • exportPrivateKey: Export the RSA private key as a JSON Web Key (JWK).
  • exportPublicKey: Export the RSA public key as a JSON Web Key (JWK).
  • importPrivateKey: Import an RSA private key from a JWK and create an Rsa2048 instance.
  • importPublicKey: Import an RSA public key from a JWK and create an Rsa2048 instance.
  • importKeys: Import both private and public keys from JWKs and create an Rsa2048 instance.
  • create: Generate a new RSA key pair and create an Rsa2048 instance.

Secure Hash Algorithms (SHA)

The Sha1, Sha256, Sha384, and Sha512 classes provide functionality for generating SHA-1, SHA-256, SHA-384, and SHA-512 hash values respectively. These algorithms are part of the Secure Hash Algorithm (SHA) family and are commonly used for cryptographic purposes such as data integrity verification.

Generating Hash Values

To generate hash values using SHA algorithms:

import { Sha1, Sha256, Sha384, Sha512 } from '@payello-module/encryption';

// Generate SHA-1 hash
const sha1Hash = await Sha1.digest('Data to hash');
console.log(sha1Hash);

// Generate raw SHA-256 hash
const sha256RawHash = await Sha256.digest('Data to hash', true);
console.log(sha256RawHash);

The digest method of each SHA class allows you to generate a hash value for the provided data. You can pass a string or a Uint8Array as input. By default, the hash value is returned as a string. If you pass true as the second argument, the method returns the hash value as a Uint8Array.

  • For Sha1, use Sha1.digest().
  • For Sha256, use Sha256.digest() with an additional argument to receive raw data.
  • For Sha384 and Sha512, use Sha384.digest() and Sha512.digest() respectively in a similar manner.

Note: The digest method returns a Promise that resolves with the generated hash value.

Remember to handle errors and asynchronous behavior appropriately when using these SHA classes in your applications.

TOTP (Time-Based One-Time Password)

The TOTP class provides functionalities for generating, parsing, and verifying Time-Based One-Time Passwords (TOTPs) according to the RFC 6238 standard. TOTPs are commonly used for two-factor authentication to enhance security.

Generating a Key

To generate a new TOTP key:

import { TOTP } from '@payello-module/authentication';

// Generate a TOTP key as a string
const keyString = TOTP.generateKey();
console.log(keyString);

// Generate a TOTP key as a Uint8Array
const keyUint8 = TOTP.generateKey(true);
console.log(keyUint8);

The generateKey method of the TOTP class is used to create a new TOTP key. It can return the key as a string or a Uint8Array depending on the returnRaw parameter passed.

Parsing a Key

To parse a TOTP key from a string:

import { TOTP } from '@payello-module/authentication';

// Parse a TOTP key from a string
const keyUint8 = TOTP.parseKey('Your TOTP key here');
console.log(keyUint8);

The parseKey method of the TOTP class converts a TOTP key from a human-readable string format to a Uint8Array.

Generating TOTP URI

To generate a TOTP URI for provisioning:

import { TOTP } from '@payello-module/authentication';

const uri = TOTP.generateUri('Your TOTP key', 'Account Name', 'Issuer Name');
console.log(uri);

The generateUri method of the TOTP class creates a TOTP URI for provisioning a TOTP key with an account and issuer name.

Generating TOTP Code

To generate a TOTP code for authentication:

import { TOTP } from '@payello-module/authentication';

// Generate a TOTP code
const code = await TOTP.getCode('Your TOTP key');
console.log(code);

The getCode method of the TOTP class generates a TOTP code based on the provided key, time (optional), and counter (optional).

Verifying TOTP Code

To verify a TOTP code:

import { TOTP } from '@payello-module/authentication';

const verification = await TOTP.verifyCode('The TOTP code', 'The TOTP key');
console.log(verification);

The verifyCode method of the TOTP class verifies a given TOTP code against a key within an allowed time window. It returns the delta (time-step difference) if successful, or false if the code is invalid.

BIP39 Mnemonic Generator and Validator

The Bip39 class provides methods for generating, validating, and converting between mnemonic phrases and cryptographic entropy as defined in the BIP-39 standard. BIP-39 is a specification for creating a mnemonic phrase to securely back up and recover a deterministic wallet.

Assert Entropy

The assertEntropy method validates that the provided entropy is a Uint8Array.

import { Bip39 } from '@payello-module/encryption';

// Validate entropy
Bip39.assertEntropy(entropyData);

Generate Mnemonic

The generateMnemonic method generates a BIP-39 compliant mnemonic phrase using a specified wordlist and strength (optional, default is 128).

import { Bip39 } from '@payello-module/encryption';

// Generate mnemonic
const mnemonic = await Bip39.generateMnemonic(wordlist, strength);

Derive Checksum Bits

The deriveChecksumBits method calculates the checksum bits for the provided entropy.

import { Bip39 } from '@payello-module/encryption';

// Calculate checksum bits
const checksumBits = await Bip39.deriveChecksumBits(entropyData);

Mnemonic to Entropy

The mnemonicToEntropy method converts a BIP-39 mnemonic phrase to its corresponding cryptographic entropy in the form of a Uint8Array.

import { Bip39 } from '@payello-module/encryption';

// Convert mnemonic to entropy
const entropy = await Bip39.mnemonicToEntropy(mnemonic, wordlist);

Entropy to Mnemonic

The entropyToMnemonic method converts cryptographic entropy (in Uint8Array format) back to a BIP-39 mnemonic phrase.

import { Bip39 } from '@payello-module/encryption';

// Convert entropy to mnemonic
const mnemonic = await Bip39.entropyToMnemonic(entropyData, wordlist);

Validate Mnemonic

The validateMnemonic method checks whether a given mnemonic phrase is valid according to the specified wordlist.

import { Bip39 } from '@payello-module/encryption';

// Validate mnemonic
const isValid = await Bip39.validateMnemonic(mnemonic, wordlist);

Salt

The salt method generates a salt from a passphrase for use in cryptographic operations.

import { Bip39 } from '@payello-module/encryption';

// Generate salt from passphrase
const salt = Bip39.salt(passphrase);

Mnemonic to Seed

The mnemonicToSeed method derives a seed Uint8Array from a BIP-39 mnemonic phrase with an optional passphrase.

import { Bip39 } from '@payello-module/encryption';

// Derive seed from mnemonic
const seed = await Bip39.mnemonicToSeed(mnemonic, passphrase);

These methods provide a comprehensive set of functionalities for working with BIP-39 mnemonics in secure cryptographic operations.

API Reference

Please refer to the inline comments within the module source code for detailed API reference and additional functionalities.

Contributing

We welcome contributions to this module! Please consider the following guidelines when contributing:

  1. Fork the repository and create your branch from main.
  2. If you've added code that should be tested, add tests.
  3. Ensure your code passes existing tests.
  4. Ensure your code follows the existing code style.
  5. Issue that pull request!