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

@instun/sm2-multikey

v2.0.0

Published

A JavaScript library for generating and working with SM2Multikey key pairs. Compatible with both Node.js and fibjs runtimes.

Downloads

164

Readme

SM2 Multikey Library

A comprehensive implementation of the SM2 cryptographic algorithm with multikey support, designed for both Node.js and browser environments.

Overview

The SM2 Multikey library provides a complete implementation of the SM2 cryptographic algorithm with support for the W3C Multikey format. It is specifically designed for:

  • Verifiable Credentials: Create and verify digital credentials using SM2 signatures
  • Digital Signatures: Generate and verify SM2 signatures with SM3 digest
  • Key Management: Handle SM2 key pairs in multiple formats
  • Data Integrity: Create and verify Data Integrity Proofs
  • Cross-Platform: Consistent API across Node.js and browser environments

The library implements a pluggable architecture that allows for platform-specific optimizations while maintaining a consistent API. In Node.js environments, it leverages native crypto implementations for optimal performance, while in browsers it uses a pure JavaScript implementation.

Features

Cryptographic Operations

  • SM2 key pair generation with secure defaults
  • Digital signature creation and verification
  • SM3 message digest calculation
  • Support for compressed public keys

Key Management

  • Multiple key format support:
    • JSON Web Key (JWK)
    • W3C Multikey format
    • Support for key compression
  • Secure key import/export operations
  • Key format validation and error handling

Standards Integration

  • W3C Data Integrity Proofs compatibility
  • Verifiable Credentials support
  • Document canonicalization (URDNA2015)
  • Cross-platform compatibility

Security

  • Memory-safe key operations
  • Protected private key handling
  • Comprehensive input validation
  • Proper error handling

Standards Compliance

Cryptographic Standards

  • GB/T 32918.1-2016: SM2 Elliptic Curve Cryptography
    • Key generation and management
    • Digital signature algorithms
    • Public key encryption
  • GB/T 32905-2016: SM3 Cryptographic Hash Algorithm
    • Message digest calculation
    • Data integrity verification

W3C Standards

  • Data Integrity 1.0
    • Proof creation and verification
    • Document canonicalization
    • Signature suite implementation
  • Verifiable Credentials
    • Credential issuance and verification
    • Proof format compatibility
    • Multikey format support

Additional Standards

  • RDF Dataset Normalization 1.0
    • Deterministic document canonicalization
    • URDNA2015 algorithm implementation

Installation

npm install @instun/sm2-multikey

Usage

Basic Key Operations

import { SM2Multikey, cryptosuite } from '@instun/sm2-multikey';

// Generate a new key pair
const key = await SM2Multikey.generate({
  controller: 'did:example:123'
});

// Create and verify signatures
const signer = key.signer();
const signature = await signer.sign({ data });
const isValid = await key.verifier().verify({ data, signature });

Data Integrity Integration

const suite = {
  ...cryptosuite,
  signer: () => key.signer(),
  verifier: () => key.verifier()
};

Key Export/Import

// Export key
const exported = key.export({
  publicKey: true,
  secretKey: false,
  includeContext: true
});

// Import from JWK
const imported = SM2Multikey.fromJwk({
  jwk,
  id: 'key-1',
  controller: 'did:example:123'
});

Platform Requirements

  • Node.js 16.x or later
  • OpenSSL 1.1.1 or later with SM2 support
  • Modern browsers with ES6+ support

Security Features

  • Protected private key operations
  • Key format validation
  • Secure key generation
  • Proper error handling

API Documentation

SM2Multikey Class

Core class for SM2 key pair operations.

Static Methods

generate(options)

Creates a new SM2 key pair.

  • Parameters:
    • options (Object, optional)
      • id (string): Key identifier
      • controller (string): Controller identifier
  • Returns: SM2Multikey instance
  • Throws:
    • ArgumentError: If options are invalid
    • KeyError: If key generation fails
    • FormatError: If key encoding fails
from(key)

Imports a key from Multikey format.

  • Parameters:
    • key (Object): Multikey formatted key data
  • Returns: SM2Multikey instance
  • Throws:
    • ArgumentError: If key object is invalid
    • FormatError: If key format is invalid
fromJwk(options)

Imports a key from JWK format.

  • Parameters:
    • options (Object)
      • jwk (Object): JWK key data
      • secretKey (boolean, optional): Whether to import private key
      • id (string, optional): Key identifier
      • controller (string, optional): Controller identifier
  • Returns: SM2Multikey instance
  • Throws:
    • ArgumentError: If JWK is invalid
    • FormatError: If JWK format is incorrect

Instance Methods

export(options)

Exports the key pair in specified format.

  • Parameters:
    • options (Object, optional)
      • publicKey (boolean): Export public key (default: true)
      • secretKey (boolean): Export private key (default: false)
      • includeContext (boolean): Include @context field (default: false)
      • raw (boolean): Export in raw format (default: false)
      • canonicalize (boolean): Sort properties (default: false)
  • Returns: Exported key object
  • Throws:
    • ArgumentError: If options are invalid
    • KeyError: If required key is not available
signer()

Creates a signing function for this key pair.

  • Returns: Object with properties:
    • algorithm (string): 'SM2'
    • id (string): Key identifier
    • sign (Function): Signing function
      • Parameters:
        • data (Buffer|Uint8Array): Data to sign
      • Returns: Promise Signature
  • Throws: KeyError if private key is not available
verifier()

Creates a verification function for this key pair.

  • Returns: Object with properties:
    • algorithm (string): 'SM2'
    • id (string): Key identifier
    • verify (Function): Verification function
      • Parameters:
        • data (Buffer|Uint8Array): Original data
        • signature (Buffer|Uint8Array): Signature to verify
      • Returns: Promise Verification result
  • Throws: KeyError if public key is not available

Cryptographic Suite

Implementation of the SM2 2023 cryptographic suite for Data Integrity.

Properties

  • name (string): 'sm2-2023'
  • requiredAlgorithm (string): 'SM2'

Methods

canonize(input, options)

Canonicalizes a JSON-LD document.

  • Parameters:
    • input (Object|string): JSON-LD document
    • options (Object, optional): Canonicalization options
      • algorithm (string): Canonicalization algorithm (default: 'URDNA2015')
      • format (string): Output format (default: 'application/n-quads')
  • Returns: Promise Canonicalized N-Quads string
  • Throws: JsonLdError if canonicalization fails
createVerifier(options)

Creates a verifier for SM2 signatures.

  • Parameters:
    • options (Object)
      • verificationMethod (Object): Verification method object
        • Must contain valid SM2 public key data
        • Must specify key format (JWK or Multikey)
  • Returns: Verifier object with verify() method
  • Throws: Error if verification method is invalid

Error Types

The library provides several error types for specific failure cases:

ArgumentError

Thrown when an invalid argument is provided.

  • Properties:
    • message: Error description
    • code: Error code (ERR_ARGUMENT_INVALID)
    • argument: Name of the invalid argument

KeyError

Thrown when a key operation fails.

  • Properties:
    • message: Error description
    • code: Error code (ERR_KEY_*)
    • operation: Failed operation name

FormatError

Thrown when a format conversion fails.

  • Properties:
    • message: Error description
    • code: Error code (ERR_FORMAT_*)
    • format: Name of the problematic format

SM2Error

Base class for SM2-specific errors.

  • Properties:
    • message: Error description
    • code: Error code
    • cause: Original error (if any)

Each error includes:

  • Descriptive error message
  • Specific error code for programmatic handling
  • Original error cause when applicable
  • Additional context-specific properties

License

Copyright (c) 2024 Instun, Inc. All rights reserved.