Installations
npm install js-crypto-utils
Developer Guide
Typescript
Yes
Module System
CommonJS
Node Version
20.7.0
NPM Version
10.1.0
Score
70.9
Supply Chain
94.5
Quality
74.5
Maintenance
50
Vulnerability
87.6
License
Releases
Contributors
Languages
TypeScript (85.79%)
JavaScript (13.86%)
Shell (0.35%)
Developer
Download Statistics
Total Downloads
144,565
Last Day
18
Last Week
152
Last Month
1,400
Last Year
25,485
GitHub Statistics
159 Stars
2,631 Commits
17 Forks
6 Watching
3 Branches
4 Contributors
Bundle Size
438.14 kB
Minified
114.94 kB
Minified + Gzipped
Package Meta Information
Latest Version
1.0.7
Package Id
js-crypto-utils@1.0.7
Unpacked Size
511.77 kB
Size
131.00 kB
File Count
16
NPM Version
10.1.0
Node Version
20.7.0
Publised On
27 Sept 2023
Total Downloads
Cumulative downloads
Total Downloads
144,565
Last day
-85.6%
18
Compared to previous day
Last week
-48.1%
152
Compared to previous week
Last month
54%
1,400
Compared to previous month
Last year
84.1%
25,485
Compared to previous year
Daily Downloads
Weekly Downloads
Monthly Downloads
Yearly Downloads
JavaScript Cryptographic Utilities for Browsers and Node.js Crypto-Suite Compatibility
WARNING: At this time this solution should be considered suitable for research and experimentation, further code and security review is needed before utilization in a production application.
Overview
This library is being developed to provide unified cryptographic APIs for browsers and Node.js. There currently exist various sophisticated cryptographic suites for JavaScript that are implemented as native functions, e.g., WebCrypto API and crypto
in Node.js. However, they have different interfaces and are NOT supported at all platforms. For instance, FireFox cannot be fed PKCS8-formatted private key in WebCrypto API but Chrome does. On the other hand, such suites have not been designed to keep compatibility to existing non-Web cryptographic suites like OpenSSL. This can be seen from the fact that WebCrypto API does not support PEM-formatted keys. Hence we (actually I!) need to write ugly codes so as to enable apps to work in various environments. From this observation, we aim that this library provides support functions to fill such gaps among JS cryptographic suites and that between JavaScript and other popular crypto suites.
Firstly, this library provides following functions that works in most modern browsers and Node.js.
- ECDSA signing, verification, key generation (P-256/P-384/P-521/P-256K)
- RSA-PSS/RSASSA-PKCS1-v1_5 signing, verification, key generation.
- Encryption using ECDH and HKDF.
- Encryption using RSA-OAEP.
- Public/private key format conversion between JWK and PEM/DER (SPKI for public/PKCS8 for private)
- Generation of JWK Thumbprint
- Generation of X.509 public key certificate from JWK and extraction of JWK public key from X.509 public key certificate. Additionally, this library provides random, hash, AES, HMAC, HKDF, and PBKDF functions.
Module structure
The module structure of this library can be illustrated as follows.
/**
* index.js
* Structure of API
* |-- Key (Key object handling EC and RSA public/private keys)
* |
* |-- pkc (public key crypto, EC and RSA)
* | |-- generateKey
* | |-- encrypt
* | |-- decrypt
* | |-- sign
* | |-- verify
* |
* |-- x509
* | |-- toJwk
* | |-- fromJwk
* | |-- parse (to verify)
* |
* |-- aes
* |-- random
* |-- hash
* |-- hmac
* |-- hkdf
* |-- pbkdf
*/
We should note that most of this library's functions are independently available through NPM and GitHub as modules. In other words, this library is being developed as an integrated wrapper of those independent modules. The independent modules are listed as follows:
Key
: https://github.com/junkurihara/jscu/tree/develop/packages/js-crypto-key-utilspkc
(EC): https://github.com/junkurihara/jscu/tree/develop/packages/js-crypto-ecpkc
(RSA): https://github.com/junkurihara/jscu/tree/develop/packages/js-crypto-rsax509
: https://github.com/junkurihara/jscu/tree/develop/packages/js-x509-utilsaes
: https://github.com/junkurihara/jscu/tree/develop/packages/js-crypto-aesrandom
: https://github.com/junkurihara/jscu/tree/develop/packages/js-crypto-randomhash
: https://github.com/junkurihara/jscu/tree/develop/packages/js-crypto-hashhkdf
: https://github.com/junkurihara/jscu/tree/develop/packages/js-crypto-hkdfpbkdf
: https://github.com/junkurihara/jscu/tree/develop/packages/js-crypto-pbkdfhmac
: https://github.com/junkurihara/jscu/tree/develop/packages/js-crypto-hmac
Please refer to the above repos for further information.
NOTE: If you would use only few modules and employ neither Key
nor pkc
, we highly recommend use our independent modules since those independent ones are relatively small and this library would be overkill.
Installation
At your project directory, do either one of the following.
- From npm/yarn:
1$ npm install --save js-crypto-utils // npm 2$ yarn add js-crypto-utils // yarn
- From GitHub:
1$ git clone https://github.com/junkurihara/jscu.git 2$ cd js-crypto-utils/packages/js-crypto-utils 3& yarn build
Then you should import the package as follows.
1import jscu from 'js-crypto-utils'; // for npm 2import jscu from 'path/to/js-crypto-utils/dist/index.js'; // for github
The bundled file is also given as js-crypto-utils/dist/jscu.bundle.js
for a use case where the module is imported as a window.jscu
object via script
tags.
Usage
NOTE: This library always uses jscu.Key
objects as instances of public and private keys, and the Key
object can be instantiated from and can export ones in various formats. For the detailed usage of Key
object, please refer to another GitHub repo.
Key generation, sign and verify
1// case of ECDSA 2jscu.pkc.generateKey( // key generation 3 'EC', // ECDSA or ECDH key pair 4 {namedCurve: 'P-256'} // or 'P-384', 'P-521', 'P-256K' 5) 6.then( async (keyPair) => { // get a key pair in jscu.Key object 7 const msg = new Uint8Array(32); 8 for(let i = 0; i < 32; i++) msg[i] = 0xFF & i; 9 10 const sig = await jscu.pkc.sign(msg, keyPair.privateKey, 'SHA-256'); // uint8array 11 const result = await jscu.pkc.verify(msg, sig, keyPair.publicKey, 'SHA-256'); // true or false 12});
1// case of RSA 2jscu.pkc.generateKey( // key generation 3 'RSA', // RSA key pair 4 {modulusLength: 2048} 5) 6.then( async (keyPair) => { // get a key pair in jscu.Key object 7 const msg = new Uint8Array(32); 8 for(let i = 0; i < 32; i++) msg[i] = 0xFF & i; 9 10 // case of RSA-PSS 11 // RSASSA-PKCS1-v1_5 is supported as well. see test files. 12 const sig = await jscu.pkc.sign(msg, keyPair.privateKey, 'SHA-256', {name: 'RSA-PSS', saltLength: 32}); // uint8array 13 const result = await jscu.pkc.verify(msg, sig, keyPair.publicKey, 'SHA-256', {name: 'RSA-PSS', saltLength: 32}); // true or false 14});
Encryption and decryption through ECDH with AES-GCM of 256 bits key and SHA-256 based HKDF
1const msg = new Uint8Array(32); 2for(let i = 0; i < 32; i++) msg[i] = 0xFF & i; 3 4const remotePublicKey = {...}; // destination's publicKey in jscu.Key object 5const remotePrivateKey = {...}; // destination's privateKey in jscu.Key object 6 7jscu.pkc.generateKey( // key generation 8 'EC', // ECDSA or ECDH key pair 9 {namedCurve: 'P-256'} // or 'P-384', 'P-521', 'P-256K' 10).then( async (keyPair) => { // get a key pair in jscu.Key object 11 //////////////////////////// 12 // encryption at my side 13 //////////////////////////// 14 const optionsEncryption = { 15 privateKey: keyPair.privateKey, // for ECDH, my private key 16 hash: 'SHA-256', // for HKDF 17 encrypt: 'AES-GCM', // for encryption of message, if message is a key, 'AES-KW' can be used as well. 18 keyLength: 32, // key length of AES 19 info: '' // for HKDF 20 }; 21 const encrypted = await jscu.pkc.encrypt(msg, remotePublicKey, optionsEncryption); 22 // now you get the encrypted message 23 24 //////////////////////////// 25 // decryption at remote side 26 //////////////////////////// 27 const optionsDecryption = { 28 publicKey: keyPair.publicKey, // for ECDH, my public key 29 hash: 'SHA-256', // for HKDF 30 encrypt: 'AES-GCM', // for encryption of message. 'AES-KW' can be used as well 31 keyLength: 32, // key length of AES 32 info: '', // for HKDF 33 salt: encrypted.salt, // for HKDF 34 iv: encrypted.iv // for AES 35 }; 36 const decrypted = await jscu.pkc.decrypt(encrypted.data, remotePrivateKey, optionsDecryption); 37 // now you get decrypted message 38});
Note that AES and HKDF are independently available from jscu.aes
and jscu.hkdf
as well as random
and hash
. Also note that the HKDF employed in this library is the one specified in RFC5869 (https://tools.ietf.org/html/rfc5869).
RSA-OAEP encryption and decryption
1const msg = new Uint8Array(32); 2for(let i = 0; i < 32; i++) msg[i] = 0xFF & i; 3 4const publicKey = {...}; // publicKey in jscu.Key object 5const privateKey = {...}; // privateKey in jscu.Key object 6 7jscu.pkc.encrypt( 8 msg, 9 publicKey, 10 {hash: 'SHA-256'} // for OAEP 11).then( (encrypted) => { 12 // now you get the encrypted message 13 return jscu.pkc.decrypt( 14 encrypted, 15 privateKey, 16 {hash: 'SHA-256'}); // for OAEP 17}).then( (decrypted) => { 18 // now you get the decrypted message 19})
Converting between Json Web Key (JWK) and SPKI-formatted (public key) or PKCS8-formatted (private key) PEM/DER
We shall explain the conversion using an example of elliptic curve cryptography keys. First let an elliptic curve crypto public key is given in the form of JWK (RFC7517) as follows:
1const publicJwk = {kty: 'EC', crv: 'P-256', x: '...', y: '...'};
Given JWKs can be converted to the PEM/DER formatted keys in the following procedure.
1const publicKeyObject = new jscu.Key('jwk', publicJwk); 2const publicAsn = await publicKeyObject.export( 3 'pem', // output format is in string PEM, 'der' is also available 4 { 5 compact: false // if true, compressed form of keys are obtained 6 });
This library also re-convert keys in PEM/DER to JWK as follows.
1const publicKeyObjectR = new jscu.Key('pem', publicASN); 2const publicJwkR = publicKeyObjectR.export('jwk');
Note that JWK/DER/PEM-formatted RSA keys can be handled in the similar manner to the above.
Generation of self-signed X.509 certificate from JWK-formatted public key
1const publicJwk = {kty: 'EC', crv: 'P-256', x: '...', y: '...'}; // public key to be signed 2const privateJwk = {ktyp: 'EC', crv: 'P-256', x: '...', y: '...', d: '...'}; // private key 3 4const name = { // this is optional 5 countryName: 'JP', 6 stateOrProvinceName: 'Tokyo', 7 localityName: 'Chiyoda', 8 organizationName: 'example', 9 organizationalUnitName: 'Research', 10 commonName: 'example.com' 11 }; 12 13// generation from JWK 14jscu.keyUtil.x509.fromJwk( 15 publicJwk, 16 privateJwk, 17 'pem', 18 { 19 signature: 'ecdsa-with-sha256', // signature algorithm 20 days: 365, // expired in days 21 issuer: name, // issuer 22 subject: name // assume that issuer = subject, i.e., self-signed certificate 23 }, 24 'pem' // output signature is in PEM. DER-encoded signature is available with 'der'. 25).then( (cert) => { 26 // now you get the certificate in PEM string 27});
For signature
, rsassaPss
(RSA-PSS) and sha*WithRSAEncryption
(RSASSA-PKCS1-v1_5) are available as well. When rsassaPss
is specified, saltLength
and hash
are required as its params.
Extract JWK from X.509 certificate
1const crtsample = '-----BEGIN CERTIFICATE-----...'; 2const jwkey = jscu.keyUtil.x509.toJwk(crtsample, 'pem'); 3// now you get JWK public key from PEM-formatted certificate
Notes
One of the listed APIs/libraries is automatically chosen and leveraged for each implemented function, and unified interfaces are provided for browsers and Node.js.
-
ECDSA and ECDH:
- WebCrypto API for browsers
- NodeCrypto for Node.js
- elliptic for browsers
-
RSA-PSS, RSASSA-PKCS1-v1_5, RSA-OAEP (RSA-PSSS does not work in Edge)
- WebCrypto API for browsers
- NodeCrypto for Node.js
-
Key format conversion:
- WebCrypto API for browsers
- asn1.js for browsers and Node.js
-
X.509 generation from JWK, and extraction of JWK from X.509
- WebCrypto API for browsers
- NodeCrypto for Node.js
- elliptic for browsers
-
AES: (may not work in IE)
- WebCrypto API for browsers
- NodeCrypto for Node.js
-
Random, hash, HKDF, HMAC, JWK Thumbprint
- WebCrypto API for browsers
- NodeCrypto for Node.js
IE is completely out of our scope now.
Especially for Hash functions, we shall use the following pure JS implementation for some browsers (WebCrypto does not support SHA-3 yet). SHA-1 doesn't work in Edge. I believe Edge should be discarded ASAP.
License
Licensed under the MIT license, see LICENSE
file.
No vulnerabilities found.
Reason
30 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 10
Reason
no dangerous workflow patterns detected
Reason
no binaries found in the repo
Reason
license file detected
Details
- Info: project has a license file: LICENSE:0
- Info: FSF or OSI recognized license: MIT License: LICENSE:0
Reason
0 existing vulnerabilities detected
Reason
Found 0/27 approved changesets -- score normalized to 0
Reason
detected GitHub workflow tokens with excessive permissions
Details
- Warn: no topLevel permission defined: .github/workflows/ci-test.yml:1
- Info: no jobLevel write permissions found
Reason
dependency not pinned by hash detected -- score normalized to 0
Details
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-test.yml:30: update your workflow using https://app.stepsecurity.io/secureworkflow/junkurihara/jscu/ci-test.yml/develop?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-test.yml:33: update your workflow using https://app.stepsecurity.io/secureworkflow/junkurihara/jscu/ci-test.yml/develop?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-test.yml:41: update your workflow using https://app.stepsecurity.io/secureworkflow/junkurihara/jscu/ci-test.yml/develop?enable=pin
- Warn: third-party GitHubAction not pinned by hash: .github/workflows/ci-test.yml:71: update your workflow using https://app.stepsecurity.io/secureworkflow/junkurihara/jscu/ci-test.yml/develop?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-test.yml:80: update your workflow using https://app.stepsecurity.io/secureworkflow/junkurihara/jscu/ci-test.yml/develop?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-test.yml:81: update your workflow using https://app.stepsecurity.io/secureworkflow/junkurihara/jscu/ci-test.yml/develop?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-test.yml:119: update your workflow using https://app.stepsecurity.io/secureworkflow/junkurihara/jscu/ci-test.yml/develop?enable=pin
- Warn: GitHub-owned GitHubAction not pinned by hash: .github/workflows/ci-test.yml:121: update your workflow using https://app.stepsecurity.io/secureworkflow/junkurihara/jscu/ci-test.yml/develop?enable=pin
- Warn: npmCommand not pinned by hash: .github/workflows/ci-test.yml:51
- Info: 0 out of 7 GitHub-owned GitHubAction dependencies pinned
- Info: 0 out of 1 third-party GitHubAction dependencies pinned
- Info: 0 out of 1 npmCommand dependencies pinned
Reason
no effort to earn an OpenSSF best practices badge detected
Reason
security policy file not detected
Details
- Warn: no security policy file detected
- Warn: no security file to analyze
- Warn: no security file to analyze
- Warn: no security file to analyze
Reason
project is not fuzzed
Details
- Warn: no fuzzer integrations found
Reason
branch protection not enabled on development/release branches
Details
- Warn: branch protection not enabled for branch 'develop'
- Warn: branch protection not enabled for branch 'master'
Reason
SAST tool is not run on all commits -- score normalized to 0
Details
- Warn: 0 commits out of 30 are checked with a SAST tool
Score
4.4
/10
Last Scanned on 2025-01-27
The Open Source Security Foundation is a cross-industry collaboration to improve the security of open source software (OSS). The Scorecard provides security health metrics for open source projects.
Learn MoreOther packages similar to js-crypto-utils
minimalistic-crypto-utils
Minimalistic tools for JS crypto modules
bigint-crypto-utils
Arbitrary precision modular arithmetic, cryptographically secure random numbers and strong probable prime generation/testing. It works in modern browsers, Angular, React, Node.js, etc. since it uses the native JS implementation of BigInt
js-encoding-utils
Miscellaneous Encoding Utilities for Crypto-related Objects in JavaScript
js-crypto-key-utils
Universal Module for Cryptographic Key Utilities in JavaScript, including PEM-JWK converters