国产SM2加密

607 阅读1分钟

1、安装国密依赖

npm install --save sm-crypto

\

  1. 增加公共加密方法,其中PublicKey由接口获取
doEncrypt(str, publicKey) {
    let sm2 = require('sm-crypto').sm2;
    let cipherMode = 0; // 1 - C1C3C2,0 - C1C2C3,默认为1
    // 加密结果
    return sm2.doEncrypt(str, publicKey, cipherMode);
  }

3、调用加密方法,加密密码,提交登录form

private submitForm() {
  (this.$refs.login as Form).validate(async valid => {
    if (valid) {
        //获取加密公钥
      const resultEncodeType = await this.$api.loginInfo.encodeType();
      //引入sm3加密
      const sm3 = require('sm-crypto').sm3;
      const params = {
        account: this.param.username,
        //对密码进行sm3加密
        password: sm3(this.param.password),
        verifyCode: this.codeData,
        mailVerifyCode: this.param.mailVerifyCode
      };
      // 对将要提交的数据进行 sm2 加密
      const encryptData =
        '04' +
        this.doEncrypt(
          JSON.stringify(params),
          resultEncodeType.data.data.publicKey
        );
      const result = await this.$api.loginInfo.login({
        encryptData: encryptData
      });
      if (result.data.code == 200) {
        this.$router.push('/');
      } else {
        this.updateCode();
        this.$message({
          message: result.data.msg,
          type: 'warning'
        });
      }
    } else {
      this.$message.error('请填写完整信息');
      return false;
    }
  });
}