Options
All
  • Public
  • Public/Protected
  • All
Menu

Web Crypto Tools

Build Version web-crypto-tools is released under the MIT license Contributors

This project is a set of tools to facilitate and give good defaults for use of the native Web Crypto API.

This project depends on the browser implementation of Crypto API and TextEncoder API, which are both current implemented on all green browsers. If you do need to support IE or any older browser, you should look for available polyfills.

The native browser implementation of crypto algorithms are much more fast and secure than any other JavaScript library out there. But at the same time, it is a low level API that relies on you to decide every little detail of it, so this project will give you good defaults and a better developer experience, and still let you decide if you prefer use other algorithms or extra protections. Be aware that, even if this project facilitates the use of the Web Crypto API, it will not prevent you from make any mistakes if you have no idea about cryptography concepts, so take your time to study a little before use it in a real project.

In the end, this is a simple collection of stateless functions, values and types, that can be individually imported and used. The minified project has currently only about 3kb in total and it is also tree-shaking friendly, so you can end up using even less.

:gear: Usage

Install it at your project

npm install @webcrypto/tools --save

Encrypt everything

import {
  generateBaseCryptoKey,
  deriveCryptKey,
  generateSalt,
  encryptValue,
  decryptValue,
  decode,
} from '@webcrypto/tools';

// get any data, string or typed arrays
const originalData = 'any data';

// create a secure base key that cannot be reverted to the original key value
const baseKey = await generateBaseCryptoKey('any raw key');

// create new keys for each crypto operation from the base key
const cryptoKey = await deriveCryptKey(baseKey, generateSalt());

// encrypt any value with military level security
const [cryptoValue, nonce] = await encryptValue(originalData, cryptoKey);

// decrypt your value when necessary
const decryptedValue = await decryptValue(cryptoValue, cryptoKey, nonce);

// the decrypted value should be the same of the original
expect(originalData).toEqual(decode(decryptedValue));

:book: Documentation

The documentation with all available API and options at our GitHub Pages.

The test cases are also quite readable and can be used as example for all the possible API uses.

License

MIT

Index

Type aliases

CryptoAlgorithm

CryptoAlgorithm: string | RsaOaepParams | AesCtrParams | AesCbcParams | AesCmacParams | AesGcmParams | AesCfbParams

Params for Encrypt / Decrypt Algorithms at Web Crypto API

CryptoKeyUsage

CryptoKeyUsage: "encrypt" | "decrypt" | "deriveKey" | "deriveBits" | "wrapKey" | "sign" | "verify" | "unwrapKey"

Possible uses of Crypto Keys

DeriveAlgorithm

DeriveAlgorithm: string | EcdhKeyDeriveParams | DhKeyDeriveParams | ConcatParams | HkdfCtrParams | Pbkdf2Params

Derive Key Algorithms at at Web Crypto API

DerivedAlgorithmFor

DerivedAlgorithmFor: string | AesDerivedKeyParams | HmacImportParams | ConcatParams | HkdfCtrParams | Pbkdf2Params

Derive Algorithms Params for Web Crypto API

ImportAlgorithm

ImportAlgorithm: string | RsaHashedImportParams | EcKeyImportParams | HmacImportParams | DhImportKeyParams | AesKeyAlgorithm

Import Key Algorithms at Web Crypto API

OriginalKeyFormat

OriginalKeyFormat: "raw" | "pkcs8" | "spki" | "jwk"

Import Key Web Crypto Algorithms

TypedArray

TypedArray: Int8Array | Int16Array | Int32Array | Uint8Array | Uint16Array | Uint32Array | Uint8ClampedArray | Float32Array | Float64Array | DataView | ArrayBuffer

TypedArray used in Web Crypto API Algorithms

Variables

Const PBKDF2_ITERATIONS_DEFAULT

PBKDF2_ITERATIONS_DEFAULT: number = 50000

Default number of iterations used with PBKDF2 algorithm

Functions

decode

  • Decode a ArrayBuffer value to a string. If the given value is already a string, then the value will be returned without any transformation.

    Parameters

    Returns string

    The transformed given value as a string.

decryptValue

  • Decrypt a value with the given Crypto Key and Algorithm

    Parameters

    • data: TypedArray

      Value to be encrypted.

    • cryptoKey: CryptoKey

      The Crypto Key used in encryption.

    • nonceOrAlgorithm: TypedArray | CryptoAlgorithm

      The nonce used for AES encryption or the custom algorithm.

    Returns Promise<ArrayBuffer>

    A promise with the decrypt value

deriveCryptKey

  • Derives a base Crypto Key to new one that can be used in encrypt / decrypt algorithms or any other possible uses in CryptoKeyUsage.

    Parameters

    • cryptoBaseKey: CryptoKey

      The base Crypto Key to be derive.

    • salt: TypedArray

      The salt value to be used with the default PBKDF2 derive algorithm.

    • Optional iterations: undefined | number

      The number of iterations to be used with the default PBKDF2 derive algorithm. Default value: PBKDF2_ITERATIONS_DEFAULT.

    • Optional keyUsages: CryptoKeyUsage[]

      The new uses of the new derive Crypto Key. Default value: ['encrypt', 'decrypt'].

    Returns Promise<CryptoKey>

    A promise with the derived Crypto Key for other uses.

  • Derives a base Crypto Key to new one that can be used in encrypt / decrypt algorithms or any other possible uses in CryptoKeyUsage.

    Parameters

    • cryptoBaseKey: CryptoKey

      The base Crypto Key to be derive.

    • salt: TypedArray

      The salt value to be used with the default PBKDF2 derive algorithm.

    • Optional algorithmFor: DerivedAlgorithmFor

      The algorithm where the derived Crypto Key will be used. Default value: { name: 'AES-GCM', length: 256 }.

    • Optional keyUsages: CryptoKeyUsage[]

      The new uses of the new derive Crypto Key. Default value: ['encrypt', 'decrypt'].

    Returns Promise<CryptoKey>

    A promise with the derived Crypto Key for other uses.

  • Derives a base Crypto Key to new one that can be used in encrypt / decrypt algorithms or any other possible uses in CryptoKeyUsage.

    Parameters

    • cryptoBaseKey: CryptoKey

      The base Crypto Key to be derive.

    • deriveAlgorithm: DeriveAlgorithm

      The algorithm to be used when deriving the Crypto Key.

    • Optional algorithmFor: DerivedAlgorithmFor

      The algorithm where the derived Crypto Key will be used. Default value: { name: 'AES-GCM', length: 256 }.

    • Optional keyUsages: CryptoKeyUsage[]

      The new uses of the new derive Crypto Key. Default value: ['encrypt', 'decrypt'].

    Returns Promise<CryptoKey>

    A promise with the derived Crypto Key for other uses.

encode

  • Encode a string value to a Typed Array as Uint8Array. If the given value is already a Typed Array, then the value will be returned without any transformation.

    Parameters

    Returns TypedArray

    The transformed given value as a Typed Array.

encryptValue

  • Encrypt a value with the given Crypto Key and Algorithm

    Parameters

    • data: string | TypedArray

      Value to be encrypted.

    • cryptoKey: CryptoKey

      The Crypto Key to be used in encryption.

    • Default value algorithm: CryptoAlgorithm = { name: 'AES-GCM', iv: generateNonce() } as AesGcmParams

      The algorithm to be used in encryption. Default to AES-GCM.

    Returns Promise<[]>

    A promise with the encrypted value and the used nonce, if used with the encryption algorithm.

generateBaseCryptoKey

  • Creates a base Crypto Key from the original raw key, by default this base key should just be used to protect the original key to be discovery, and should not be used directly to any encrypt / decrypt algorithm. The generated base crypto key should be used just to derive new ones, that then will be used to encrypt / decrypt algorithms.

    Parameters

    • rawKey: string | TypedArray | JsonWebKey

      The original key to start the encrypt process.

    • Default value algorithm: ImportAlgorithm = "PBKDF2"

      The algorithm used to import the key.

    • Default value keyUsages: KeyUsage[] = ['deriveKey']

      The uses for the generated Crypto Key.

    • Default value format: OriginalKeyFormat = "raw"

      Input format for the raw key.

    Returns Promise<CryptoKey>

    A promise with the base Crypto Key.

generateHash

  • generateHash(data: string | TypedArray, algorithm?: string | Algorithm): Promise<ArrayBuffer>
  • Generates a hash value for the given value.

    Parameters

    • data: string | TypedArray

      Seed value to generate a hash.

    • Default value algorithm: string | Algorithm = "SHA-256"

      The algorithm to be used when generating the hash.

    Returns Promise<ArrayBuffer>

    A promise containing the hash value.

generateNonce

  • generateNonce(byteSize?: number): Uint8Array
  • Generates random value to be used as nonce with encryption algorithms.

    Parameters

    • Default value byteSize: number = 16

      The byte size of the generated random value.

    Returns Uint8Array

    The random value.

generateRandomValues

  • generateRandomValues(byteSize?: number): Uint8Array
  • Generates random value as a typed array of Uint8Array.

    Parameters

    • Default value byteSize: number = 8

      The byte size of the generated random value.

    Returns Uint8Array

    The random value.

generateSalt

  • generateSalt(byteSize?: number): Uint8Array
  • Generates random value to be used as salt with encryption algorithms.

    Parameters

    • Default value byteSize: number = 8

      The byte size of the generated random value.

    Returns Uint8Array

    The random value.

getCryptoObject

  • getCryptoObject(): Crypto
  • Returns the crypto object depending on browser support. IE11 has support for the Crypto API, but it is in a different global scope.

    Returns Crypto

    The Crypto object.

isTypedArray

  • isTypedArray(data: unknown): data is TypedArray
  • Type Guard to Typed Array.

    Parameters

    • data: unknown

      Any data to be checked.

    Returns data is TypedArray

    Verify if the given data is a Typed Array.

Legend

Generated using TypeDoc