Install sm-crypto via npm
masterTo use the SM2, SM3, and SM4 cryptographic algorithms in your JavaScript project, install the package using npm:
npm install --save sm-cryptorepository·master·Indexed 22 days ago
https://github.com/juneandgreen/sm-cryptoA JavaScript implementation of Chinese National Standard (Guomi) cryptographic algorithms, including SM2 (asymmetric encryption, signing, and verification), SM3 (hashing and HMAC), and SM4 (symmetric block cipher). Version 0.5.4 supports various cipher modes, padding options like PKCS#7, and key pair management.
To use the SM2, SM3, and SM4 cryptographic algorithms in your JavaScript project, install the package using npm:
npm install --save sm-cryptoThe sm4 module provides symmetric encryption and decryption. It supports different modes and padding options.
Parameters:
msg: The data to encrypt/decrypt (UTF-8 string or byte array).key: A 128-bit key (hex string or byte array).options object:padding: 'none' (defaults to PKCS#7; passing 'pkcs#5' also uses PKCS#7).output: 'array' (returns a byte array instead of a string).mode: 'cbc' (default is ECB; requires iv).iv: Initialization Vector (required for 'cbc' mode).Note: Decryption defaults to returning a UTF-8 string.
const sm4 = require('sm-crypto').sm4
const msg = 'hello world!'
const key = '0123456789abcdeffedcba9876543210'
// Default (PKCS#7, ECB)
let encryptData = sm4.encrypt(msg, key)
// CBC Mode with IV and no padding
let encryptDataCBC = sm4.encrypt(msg, key, {
mode: 'cbc',
iv: 'fedcba98765432100123456789abcdef',
padding: 'none'
})
// Decrypting to a byte array
let decryptData = sm4.decrypt(encryptData, key, {
padding: 'none',
output: 'array'
})Use the sm2 module to generate hex-encoded key pairs. You can also compress public keys to a shorter format (66 bits) and verify the validity of a public key.
Key Features:
generateKeyPairHex(): Generates a new key pair.compressPublicKeyHex(publicKey): Compresses a 130-bit public key to 66 bits.comparePublicKeyHex(key1, key2): Checks if two public keys are equivalent.verifyPublicKey(publicKey): Validates the public key.getPublicKeyFromPrivateKey(privateKey): Derives the public key from a private key.Note on Custom Randomness: You can pass custom random values to generateKeyPairHex, but you must ensure they are cryptographically secure.
const sm2 = require('sm-crypto').sm2
// Generate key pair
let keypair = sm2.generateKeyPairHex()
let publicKey = keypair.publicKey
let privateKey = keypair.privateKey
// Compress and compare
const compressedPublicKey = sm2.compressPublicKeyHex(publicKey)
sm2.comparePublicKeyHex(publicKey, compressedPublicKey)
// Verify
sm2.verifyPublicKey(publicKey)
// Derive public key from private key
let derivedPublicKey = sm2.getPublicKeyFromPrivateKey(privateKey)You can obtain an elliptic curve point using getPoint(). These points can be passed into the pointPool option during signing to improve performance.
const sm2 = require('sm-crypto').sm2
let point = sm2.getPoint()The sm3 module provides hashing and HMAC functionality.
sm3(data): Computes the SM3 hash of the input string or byte array.sm3(data, { key: '...' }): Computes the HMAC using the provided key (hex string or byte array).const sm3 = require('sm-crypto').sm3
// Standard Hash
let hashData = sm3('abc')
// HMAC
hashData = sm3('abc', {
key: 'daac25c1512fe50f79b0e4526b93f5c0e1460cef40b6dd44af13caec62e8c60e0d885f3c6d6fb51e530889e6fd4ac743a6d332e68a0f2a3923f42585dceb93e9'
})Perform asymmetric encryption and decryption using SM2. You can specify the cipherMode to control the order of the C1, C2, and C3 components.
Cipher Modes:
1 (Default): C1C3C20: C1C2C3Important Note: Ciphertext may automatically append 04 during decryption. If your ciphertext was generated by other tools that include 04, you must manually remove it before passing it to doDecrypt.
const sm2 = require('sm-crypto').sm2
const cipherMode = 1 // 1 - C1C3C2, 0 - C1C2C3
// String input/output
let encryptData = sm2.doEncrypt(msgString, publicKey, cipherMode)
let decryptData = sm2.doDecrypt(encryptData, privateKey, cipherMode)
// Array input/output
let encryptDataArr = sm2.doEncrypt(msgArray, publicKey, cipherMode)
let decryptDataArr = sm2.doDecrypt(encryptDataArr, privateKey, cipherMode, {output: 'array'})The sm2 module supports various signing modes, including pure signing (without SM3 hashing), DER encoding, and performance optimizations.
Options for doSignature and doVerifySignature:
hash (boolean, default true): If false, performs a pure signature without SM3 hashing.der (boolean): If true, uses DER encoding/decoding.publicKey (string): Providing the public key during signing skips the public key derivation step, increasing speed.userId (string, max 8192 chars): Custom user ID for the signature (default is '1234567812345678').pointPool (Array): An array of pre-generated elliptic curve points (via sm2.getPoint()) to speed up signing.Example: Pure Signature (No Hash, DER encoded):
const sm2 = require('sm-crypto').sm2
// Pure signature + DER encoding
let sigValueHex = sm2.doSignature(msg, privateKey, {
hash: false,
der: true
})
// Verify signature
let verifyResult = sm2.doVerifySignature(msg, sigValueHex, publicKey, {
hash: false,
der: true
})The encrypt and decrypt functions accept an options object to customize the cryptographic behavior:
mode: The block cipher mode. Supported value: 'cbc'. (Defaults to ECB).iv: Initialization Vector. Required if mode is 'cbc'. Must be a 128-bit (16-byte) hex string or byte array.padding: The padding scheme. Supported values: 'pkcs#5', 'pkcs#7'. (Defaults to 'pkcs#7').output: The format of the returned data. Supported values: 'string' (default), 'array'.output is 'string', encrypt returns a hex string and decrypt returns a UTF-8 string.output is 'array', both return a byte array.// Example: CBC mode with custom IV and array output
const options = {
mode: 'cbc',
iv: '000102030405060708090a0b0c0d0e0f',
padding: 'pkcs#7',
output: 'array'
};
const encryptedArray = encrypt(data, key, options);The SM4 implementation may throw the following errors:
Error: 'iv is invalid': Thrown if the provided iv is not exactly 128 bits (16 bytes) when using CBC mode.Error: 'key is invalid': Thrown if the provided key is not exactly 128 bits (16 bytes).Error: 'padding is invalid': Thrown during decryption if the PKCS#5/PKCS#7 padding structure is incorrect or corrupted.Error: 'input is not supported': Thrown if the UTF-8 encoding process encounters unsupported character points (5 or 6-byte sequences).The sm-crypto library provides implementations for Chinese national standard cryptographic algorithms: SM2 (Elliptic Curve), SM3 (Hash), and SM4 (Block Cipher). You can access these algorithms through the main entrypoint by requiring the package.
Available modules:
sm2: Elliptic curve cryptography (key generation, encryption, decryption, signing, and verification).sm3: Cryptographic hash function.sm4: Symmetric block cipher (encryption and decryption).const { sm2, sm3, sm4 } = require('sm-crypto');
// Access specific algorithms
// sm2.getPublicKey(...)
// sm3.sm3(...)
// sm4.sm4Encrypt(...)Use doDecrypt to decrypt data encrypted via SM2. It requires the encrypted data and the corresponding private key.
Parameters:
encryptData: The encrypted hex string.privateKey: The recipient's private key in hex format.cipherMode: (Optional) Must match the mode used during encryption. 1 (default) for C1C2C3, 0 for C1C3C2.options: (Optional)output: 'string' (default) or 'array'. Determines the return type of the decrypted message.Returns:
const { doDecrypt } = require('./src/sm2/index.js');
const privateKey = '...'; // hex private key
const encryptedData = '...'; // hex encrypted data
const decrypted = doDecrypt(encryptedData, privateKey, 1, { output: 'string' });Use generateKeyPairHex to generate a new random SM2 private/public key pair.
Returns:
privateKey and publicKey as hex strings.const { generateKeyPairHex } = require('./src/sm2/index.js');
const keypair = generateKeyPairHex();
// keypair.privateKey, keypair.publicKey