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:
- Key Management: Handle SM2 key pairs in multiple formats
- Digital Signatures: Generate and verify SM2 signatures with SM3 digest
- 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
- ECDH key agreement for secure shared secret derivation
- 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
- 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
npm install @instun/sm2-multikeyimport { SM2Multikey } 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 });
// Derive shared secret with another key (ECDH)
const otherKey = await SM2Multikey.generate();
const sharedSecret = await key.deriveSecret({ publicKey: otherKey });// 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:
KeyErrorif 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:
KeyErrorif public key is not available
Derives a shared secret using ECDH key agreement with another public key.
- Parameters:
options(Object)publicKey(SM2Multikey|Object): Remote public key for agreementremotePublicKey(SM2Multikey|Object): Alias for publicKey (backward compatibility)
- Returns: Promise Derived shared secret (32 bytes)
- Throws:
KeyError: If no private key is availableArgumentError: If remote public key is invalidSM2Error: If key agreement fails
Example:
// Generate two key pairs
const alice = SM2Multikey.generate();
const bob = SM2Multikey.generate();
// Derive shared secrets
const aliceSecret = await alice.deriveSecret({ publicKey: bob });
const bobSecret = await bob.deriveSecret({ publicKey: alice });
// Secrets should be identical
console.log(Buffer.from(aliceSecret).equals(Buffer.from(bobSecret))); // trueIndicates whether this key supports key agreement operations.
- Type: boolean
- Value: Always true for SM2 keys
- Usage: Check if key supports deriveSecret functionality
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.