A comprehensive implementation of the SM2 cryptographic algorithm with multikey support, designed for both Node.js and browser environments.
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.
- SM2 key pair generation with secure defaults
- Digital signature creation and verification
- SM3 message digest calculation
- Support for compressed public keys
- 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
- W3C Data Integrity Proofs compatibility
- Verifiable Credentials support
- Document canonicalization (URDNA2015)
- Cross-platform compatibility
- Memory-safe key operations
- Protected private key handling
- Comprehensive input validation
- Proper error handling
- 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
- 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
- RDF Dataset Normalization 1.0
- Deterministic document canonicalization
- URDNA2015 algorithm implementation
npm install @instun/sm2-multikey
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 });
const suite = {
...cryptosuite,
signer: () => key.signer(),
verifier: () => key.verifier()
};
// 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'
});
- Node.js 16.x or later
- OpenSSL 1.1.1 or later with SM2 support
- Modern browsers with ES6+ support
- Protected private key operations
- Key format validation
- Secure key generation
- Proper error handling
Core class for SM2 key pair operations.
Creates a new SM2 key pair.
- Parameters:
options
(Object, optional)id
(string): Key identifiercontroller
(string): Controller identifier
- Returns: SM2Multikey instance
- Throws:
ArgumentError
: If options are invalidKeyError
: If key generation failsFormatError
: If key encoding fails
Imports a key from Multikey format.
- Parameters:
key
(Object): Multikey formatted key data
- Returns: SM2Multikey instance
- Throws:
ArgumentError
: If key object is invalidFormatError
: If key format is invalid
Imports a key from JWK format.
- Parameters:
options
(Object)jwk
(Object): JWK key datasecretKey
(boolean, optional): Whether to import private keyid
(string, optional): Key identifiercontroller
(string, optional): Controller identifier
- Returns: SM2Multikey instance
- Throws:
ArgumentError
: If JWK is invalidFormatError
: If JWK format is incorrect
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 invalidKeyError
: If required key is not available
Creates a signing function for this key pair.
- Returns: Object with properties:
algorithm
(string): 'SM2'id
(string): Key identifiersign
(Function): Signing function- Parameters:
data
(Buffer|Uint8Array): Data to sign
- Returns: Promise Signature
- Parameters:
- Throws:
KeyError
if private key is not available
Creates a verification function for this key pair.
- Returns: Object with properties:
algorithm
(string): 'SM2'id
(string): Key identifierverify
(Function): Verification function- Parameters:
data
(Buffer|Uint8Array): Original datasignature
(Buffer|Uint8Array): Signature to verify
- Returns: Promise Verification result
- Parameters:
- Throws:
KeyError
if public key is not available
Implementation of the SM2 2023 cryptographic suite for Data Integrity.
name
(string): 'sm2-2023'requiredAlgorithm
(string): 'SM2'
Canonicalizes a JSON-LD document.
- Parameters:
input
(Object|string): JSON-LD documentoptions
(Object, optional): Canonicalization optionsalgorithm
(string): Canonicalization algorithm (default: 'URDNA2015')format
(string): Output format (default: 'application/n-quads')
- Returns: Promise Canonicalized N-Quads string
- Throws:
JsonLdError
if canonicalization fails
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
The library provides several error types for specific failure cases:
Thrown when an invalid argument is provided.
- Properties:
message
: Error descriptioncode
: Error code (ERR_ARGUMENT_INVALID)argument
: Name of the invalid argument
Thrown when a key operation fails.
- Properties:
message
: Error descriptioncode
: Error code (ERR_KEY_*)operation
: Failed operation name
Thrown when a format conversion fails.
- Properties:
message
: Error descriptioncode
: Error code (ERR_FORMAT_*)format
: Name of the problematic format
Base class for SM2-specific errors.
- Properties:
message
: Error descriptioncode
: Error codecause
: 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
Copyright (c) 2024 Instun, Inc. All rights reserved.