update:前端SM2非对称加密登录功能

This commit is contained in:
3030332422
2025-09-23 20:22:12 +08:00
parent ffba2f4fa3
commit 33bad7ed40
11 changed files with 340 additions and 144 deletions
+118 -2
View File
@@ -148,8 +148,9 @@
import Api from "@/apis/api";
import VersionFooter from "@/components/VersionFooter.vue";
import i18n, { changeLanguage } from "@/i18n";
import { getUUID, goToPage, showDanger, showSuccess, validateMobile } from "@/utils";
import { getUUID, goToPage, showDanger, showSuccess, validateMobile, generateSm2KeyPairHex, sm2Encrypt, isBase64 } from "@/utils";
import { mapState } from "vuex";
import Constant from "@/utils/constant";
export default {
name: "login",
@@ -196,6 +197,8 @@ export default {
captchaUrl: "",
isMobileLogin: false,
languageDropdownVisible: false,
serverPublicKey: "", // 服务器公钥
clientKeyPair: null, // 客户端密钥对
};
},
mounted() {
@@ -204,8 +207,49 @@ export default {
// 根据配置决定默认登录方式
this.isMobileLogin = this.enableMobileRegister;
});
// 获取服务器公钥
this.getServerPublicKey();
// 生成客户端密钥对
this.generateClientKeyPair();
},
methods: {
// 获取服务器公钥
getServerPublicKey() {
console.log('开始获取服务器公钥...');
// 先从本地存储获取
const storedPublicKey = localStorage.getItem(Constant.STORAGE_KEY.PUBLIC_KEY);
if (storedPublicKey) {
console.log('从本地存储获取到公钥,长度:', storedPublicKey.length);
this.serverPublicKey = storedPublicKey;
return;
}
console.log('本地存储无公钥,从服务器获取...');
// 从服务器获取公钥
Api.user.getSM2PublicKey(
(res) => {
if (res.data && res.data.data) {
console.log('获取到服务器公钥,长度:', res.data.data.length);
this.serverPublicKey = res.data.data;
// 存储到本地
localStorage.setItem(Constant.STORAGE_KEY.PUBLIC_KEY, this.serverPublicKey);
console.log('公钥已存储到本地');
} else {
console.error('服务器返回数据格式异常:', res);
}
},
(err) => {
console.error("获取SM2公钥失败:", err);
showDanger(this.$t('sm2.failedToGetPublicKey'));
}
);
},
// 生成客户端密钥对
generateClientKeyPair() {
this.clientKeyPair = generateSm2KeyPairHex();
},
fetchCaptcha() {
if (this.$store.getters.getToken) {
if (this.$route.path !== "/home") {
@@ -285,9 +329,68 @@ export default {
return;
}
// 检查服务器公钥是否已获取,如果未获取则重新获取
if (!this.serverPublicKey) {
try {
// 等待公钥获取完成
await new Promise((resolve, reject) => {
this.getServerPublicKey();
// 设置超时检查,最多等待3秒
const checkInterval = setInterval(() => {
if (this.serverPublicKey) {
clearInterval(checkInterval);
resolve();
}
}, 100);
setTimeout(() => {
clearInterval(checkInterval);
if (!this.serverPublicKey) {
reject(new Error('获取公钥超时'));
}
}, 3000);
});
} catch (error) {
showDanger(this.$t('sm2.failedToGetPublicKey'));
return;
}
}
// 加密密码
let encryptedPassword = this.form.password;
if (!this.isSM2Encrypted(this.form.password)) {
try {
encryptedPassword = sm2Encrypt(this.serverPublicKey, this.form.password);
} catch (error) {
console.error("密码加密失败:", error);
showDanger(this.$t('sm2.encryptionFailed'));
return;
}
}
// 加密用户名
let encryptedUsername = this.form.username;
if (!this.isSM2Encrypted(this.form.username)) {
try {
encryptedUsername = sm2Encrypt(this.serverPublicKey, this.form.username);
} catch (error) {
console.error("用户名加密失败:", error);
showDanger(this.$t('sm2.encryptionFailed'));
return;
}
}
this.form.captchaId = this.captchaUuid;
// 使用加密后的用户名和密码
const loginData = {
...this.form,
username: encryptedUsername,
password: encryptedPassword
};
Api.user.login(
this.form,
loginData,
({ data }) => {
showSuccess(this.$t('login.loginSuccess'));
this.$store.commit("setToken", JSON.stringify(data.data));
@@ -320,6 +423,19 @@ export default {
goToForgetPassword() {
goToPage("/retrieve-password");
},
/**
* 判断字符串是否为SM2加密格式(十六进制格式)
* @param {string} str 待判断的字符串
* @returns {boolean} 是否为SM2加密格式
*/
isSM2Encrypted(str) {
if (typeof str !== 'string' || str.trim() === '') {
return false;
}
// 长度大于100且只包含0-9,a-f,A-F字符
return str.length > 100 && /^[0-9a-fA-F]+$/.test(str);
}
},
};
</script>