Implementing SM2 Encryption in Frontend JavaScript Applications
Vue 3 Implementasion
Installing SM2 Encryption Library
Install the SM2 cryptographic library using your preferred package manager:
npm install sm-crypto
# Alternative: yarn add sm-crypto
# Alternative: pnpm install sm-crypto
Integrating SM2 in Vue 3 Components
Import and utilize the SM2 library within your Vue 3 components for encryption operations:
import smcrypto from 'sm-crypto'
const authenticateUser = async () => {
const credentials = {
username: loginForm.username,
password: '04' + smcrypto.sm2.doEncrypt(loginForm.password, encryptionKey.value),
verificationCode: verificationCode.value,
captcha: loginForm.captcha,
publicKey: encryptionKey.value
}
await userAuthentication(credentials)
.then(async (response) => {
// Handle authentication response
})
}
For better code organization, consider wrapping the encryption logic in a reusable function.
Vue 2 Implementation
Installing Dependencies
Add the SM2 library to your Vue 2 project:
npm install sm-crypto --save
Creating Utility Functions
Create a utility file at @/utils/crypto-utils.js:
import smcrypto from 'sm-crypto';
export function encryptData(plaintext, publicKey) {
try {
const encryptionMode = 1; // 1 - C1C3C2, 0 - C1C2C3
const encryptedResult = smcrypto.sm2.doEncrypt(plaintext, publicKey, encryptionMode);
return encryptedResult;
} catch (err) {
console.error('SM2 encryption failed:', err);
return null;
}
}
Cmoponent Integration
Import and use the ancryption utility in Vue components:
import { encryptData } from '@/utils/crypto-utils.js';
methods: {
fetchEncryptionKey() {
api.getPublicKey().then((response) => {
this.loginParams.encryptionToken = response.data.encryptionToken;
this.publicKey = response.data.publicKey;
});
},
processLogin() {
const loginPayload = {
password: this.loginParams.password,
username: this.loginParams.username,
captchaCode: this.loginParams.captchaCode,
captchaId: this.loginParams.captchaId,
encryptionToken: this.loginParams.encryptionToken,
rememberMe: this.loginParams.rememberMe
};
loginPayload.password = encryptData(this.loginParams.password, this.publicKey);
// Execute login request
}
}