Giter VIP home page Giter VIP logo

crypto-ld's Introduction

Cryptographic Key Pair Library for Linked Data (crypto-ld)

Node.js CI NPM Version

A Javascript library for generating and performing common operations on Linked Data cryptographic key pairs.

Table of Contents

Background

See also (related specs):

Supported Key Types (crypto-ld versions 4+)

This library provides general Linked Data cryptographic key generation functionality, but does not support any individual key type by default.

To use it, you must install individual driver libraries for each cryptographic key type. The following libraries are currently supported.

Type Crypto Suite Library Usage
Ed25519 Ed25519VerificationKey2020 (recommended), Ed25519VerificationKey2018 (legacy) ed25519-verification-key-2020 >=1.0 (recommended), ed25519-verification-key-2018 >=2.0 (legacy) Signatures, VCs, zCaps, DIDAuth
X25519/Curve25519 X25519KeyAgreementKey2019 x25519-key-agreement-key-2019 >=4.0 ECDH key agreement, JWE/CWE encryption with minimal-cipher
Secp256k1 EcdsaSecp256k1VerificationKey2019 ecdsa-secp256k1-verification-key-2019 Signatures, VCs, zCaps, DIDAuth, HD Wallets

Legacy Supported Key Types (crypto-ld versions <=3)

In the previous version (v3.x) of crypto-ld, the RSA and Ed25519 suites were bundled with crypto-ld (as opposed to residing in standalone packages). For previous usage instructions of bundled RSA, Ed25519 and standalone Curve25519/x25519-key-pair type keys, see the README for crypto-ld v3.9.

Choosing a Key Type

For digital signatures using the jsonld-signatures, signing of Verifiable Credentials using vc-js, authorization capabilities, and DIDAuth operations:

  • Prefer Ed25519VerificationKey2020 type keys, by default.
  • Use EcdsaSepc256k1 keys if your use case requires it (for example, if you're developing for a Bitcoin-based or Ethereum-based ledger), or if you require Hierarchical Deterministic (HD) wallet functionality.

For key agreement protocols for encryption operations:

Security

As with most security- and cryptography-related tools, the overall security of your system will largely depend on your design decisions.

Install

  • Node.js 14.0+ is required.

To install locally (for development):

git clone https://github.com/digitalbazaar/crypto-ld.git
cd crypto-ld
npm install

Usage

Installing Support for Key Types

In order to use this library, you will need to import and install driver libraries for key types you'll be working with via the use() method.

To use the library with one or more supported suites:

import {Ed25519VerificationKey2020} from '@digitalbazaar/ed25519-verification-key-2020';
import {X25519KeyAgreementKey2020} from '@digitalbazaar/x25519-key-agreement-key-2020';

import {CryptoLD} from 'crypto-ld';
const cryptoLd = new CryptoLD();

cryptoLd.use(Ed25519VerificationKey2020);
cryptoLd.use(X25519KeyAgreementKey2020);

const edKeyPair = await cryptoLd.generate({type: 'Ed25519VerificationKey2020'});

Generating a new public/private key pair

To generate a new public/private key pair: cryptoLd.generate(options):

  • {string} [type] Suite name, required.
  • {string} [controller] Optional controller URI or DID to initialize the generated key. (This will also init the key id.)
  • {string} [seed] Optional deterministic seed value (only supported by some key types, such as ed25519) from which to generate the key.

Importing a key pair from storage

To create an instance of a public/private key pair from data imported from storage, use cryptoLd.from():

const serializedKeyPair = { ... };

const keyPair = await cryptoLd.from(serializedKeyPair);

Note that only installed key types are supported, if you try to create a key pair via from() for an unsupported type, an error will be thrown.

Common individual key pair operations

The full range of operations will depend on key type. Here are some common operations supported by all key types.

Exporting the public key only

To export just the public key of a pair - use export():

keyPair.export({publicKey: true});
// ->
{
  type: 'Ed25519VerificationKey2020',
  id: 'did:example:1234#z6MkszZtxCmA2Ce4vUV132PCuLQmwnaDD5mw2L23fGNnsiX3',
  controller: 'did:example:1234',
  publicKeyMultibase: 'zEYJrMxWigf9boyeJMTRN4Ern8DJMoCXaLK77pzQmxVjf'
}

Exporting the full public-private key pair

To export the full key pair, including private key (warning: this should be a carefully considered operation, best left to dedicated Key Management Systems):

keyPair.export({publicKey: true, privateKey: true});
// ->
{
  type: 'Ed25519VerificationKey2020',
  id: 'did:example:1234#z6MkszZtxCmA2Ce4vUV132PCuLQmwnaDD5mw2L23fGNnsiX3',
  controller: 'did:example:1234',
  publicKeyMultibase: 'zEYJrMxWigf9boyeJMTRN4Ern8DJMoCXaLK77pzQmxVjf',
  privateKeyMultibase: 'z4E7Q4neNHwv3pXUNzUjzc6TTYspqn9Aw6vakpRKpbVrCzwKWD4hQDHnxuhfrTaMjnR8BTp9NeUvJiwJoSUM6xHAZ'
}

Generating and verifying key fingerprint

To generate a fingerprint:

keyPair.fingerprint();
// ->
'z6MkszZtxCmA2Ce4vUV132PCuLQmwnaDD5mw2L23fGNnsiX3'

To verify a fingerprint:

keyPair.verifyFingerprint({
  fingerprint: 'z6MkszZtxCmA2Ce4vUV132PCuLQmwnaDD5mw2L23fGNnsiX3'
});
// ->
{ valid: true }

Operations on signature-related key pairs

For key pairs that are related to signature and verification (that extend from the LDVerifierKeyPair class), two additional operations must be supported:

Creating a signer function

In order to perform a cryptographic signature, you need to create a sign function, and then invoke it.

const keyPair = await cryptoLd.generate({type: 'Ed25519VerificationKey2020'});

const {sign} = keyPair.signer();

const data = 'test data to sign';
const signatureValue = await sign({data});

Creating a verifier function

In order to verify a cryptographic signature, you need to create a verify function, and then invoke it (passing it the data to verify, and the signature).

const keyPair = await cryptoLd.generate({type: 'Ed25519VerificationKey2020'});

const {verify} = keyPair.verifier();

const {valid} = await verify({data, signature});

Contribute

See the contribute file!

PRs accepted.

If editing the Readme, please conform to the standard-readme specification.

Commercial Support

Commercial support for this library is available upon request from Digital Bazaar: [email protected]

License

New BSD License (3-clause) ยฉ Digital Bazaar

crypto-ld's People

Contributors

aljones15 avatar davidlehn avatar dlongley avatar dmitrizagidulin avatar ender503 avatar gannan08 avatar mattcollier avatar pmcb55 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

crypto-ld's Issues

Add a fromKeyId() class method.

  • Takes a key id and a documentLoader
  • Checks fetched document for the correct context supported by that crypto suite.
  • Checks that the key is not revoked.

Archive this repository

Remove sodium-native entirely

Apparently, there's no way for npm to create reproducible builds using package lock files and no optional dependencies, so we should remove sodium-native from the optional dependencies and use the node-forge implementation for old versions of node.js.

Fix linting errors

There are several violations of the max-len 80 rule such as:

https://github.com/digitalbazaar/crypto-ld/blob/master/lib/Ed25519KeyPair.js#L15-L17

I addressed this in one file by using eslint-disable, but for some reason this trick doesn't work in the Ed25519KeyPair.js file. When the eslint directives are put in place, the doc generation script no longer outputs a doc for this file.

https://github.com/digitalbazaar/crypto-ld/blob/master/lib/RSAKeyPair.js#L30

What we really need is to figure out the syntax that would allow us to wrap these link lines so that we don't need the eslint-disable.

Need to reduce bundle size

We're presently including an entire TLS implementation along with this package, which is totally unnecessary. We need to fix that. I'm not sure if we can easily fix that here or if it needs to be done at the forge layer -- or if we need to replace forge with something else where we're using it.

Use sodium for node only.

Using sodium-universal causes webpacked code to pull in ~90KB of unneeded code. Currently the only use in browsers is for ed25519 key generation which is also in forge. Could switch to non-universal sodium for node and just forge for browsers.

TODO/FIXME Count 9

Failed to install with the node v11.12.0

I got these errors when I install the crypto-ld with node v11.12.0, because of the engines field specifies the node version must be "8.3.0".

Could I send the pull request to change it to { "engines" : { "node" : ">=8.3.0" } }? ๐Ÿ˜ƒ

$ yarn add crypto-ld
[1/4] ๐Ÿ”  Resolving packages...
[2/4] ๐Ÿšš  Fetching packages...
error [email protected]: The engine "node" is incompatible with this module. Expected version "^8.3.0". Got "11.12.0"
error Found incompatible module
info Visit https://yarnpkg.com/en/docs/cli/install for documentation about this command.
error Command failed with exit code 1.
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.

What happened to RSAKeyPair?

In this commit the RSAKeyPair class was removed from the repo in order to be placed into rsa-verification, but that repo is still empty. Did this migration never finish? Did that class simply go poof?

I'm trying to use jsig to attach a publicKey record to an activitypub actor, and every example I find points at an RSAKeyPair class that seemingly vanished in 2019.

Error: Module did not self-register.

.../node_modules/crypto-ld/node_modules/sodium-native/index.js:1
    Error: Module did not self-register.
        at Object.Module._extensions..node (internal/modules/cjs/loader.js:807:18)

Encountering this when attempting to use http-signature-zcap-verify... Not sure exactly why.

Refactor _suiteForType helper.

I think we're playing a little fast and loose with this API (maybe you pass a doc, maybe you pass some options, if the thing you pass isn't defined its treated the same as no type being passed ... and so on). I could see someone getting tripped up on this in the future. So we might want it to be a little cleaner, but won't hold up the PR for it.

Originally posted by @dlongley in #60 (comment)

Deprecation / Maintenance Status

Is this library still being maintained?
I'm implementing data integrity proofs for zcaps and I was having trouble to find what library is resposible for what part of the data integrity signing / verification procedure.
It did not seem to be very compatible with the data-integrity, eddsa-2022-cryptosuite, and jsonld-signatures libraries to me, and there haven't been code changes for 2 years.

Best, Laurin

Different behavior in Ed25519KeyPair's verify method in Node 10 VS 12

I created a test to reproduce the error:
https://gist.github.com/gjgd/8117bb3b2b3f1cbb79c170e5125b27bf

In Node12, both tests pass (ie the verify method returns { verified: true } with a valid jws, and { verified: false } with an invalid jws)

In Node10, the second test fails (ie the verify method returns { verified: true } with a valid jws, and { verified: true } with an invalid jws)

I tracked down the bug to this part of the crypto-ld's library:

if(env.nodejs && require('semver').gte(process.version, '12.0.0')) {
const bs58 = require('bs58');
const publicKeyBytes = util.base58Decode({
decode: bs58.decode,
keyMaterial: key.publicKeyBase58,
type: 'public'
});
const _publicKey = require('./ed25519PublicKeyNode12');
// create a Node public key
const publicKey = _publicKey.create({publicKeyBytes});
const {verify} = require('crypto');
return {
async verify({data, signature}) {
return verify(
null, Buffer.from(data.buffer, data.byteOffset, data.length),
publicKey, signature);
}
};
}
if(env.nodejs) {
const sodium = require('sodium-native');
const bs58 = require('bs58');
const publicKey = util.base58Decode({
decode: bs58.decode,
keyMaterial: key.publicKeyBase58,
type: 'public'
});
return {
async verify({data, signature}) {
return sodium.crypto_sign_verify_detached(
Buffer.from(signature.buffer, signature.byteOffset, signature.length),
Buffer.from(data.buffer, data.byteOffset, data.length),
publicKey);
}
};
}

In the first part of the condition (Node 12), if there is garbage at the end of the signature, the signature will be invalid
However in the second part of the condition (Node 10), if there is garbage at the end of the signature, the signature will still be valid because the end of the signature will be ignored

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.