【vue+sm2】前端使用国密sm2,加解密

1.第一步就是安装依赖

 npm install --save sm-crypto

2.导入sm2

 const sm2 = require('sm-crypto').sm2

3.先定义私钥或者公钥,私钥是解密,公钥是加密

var privateKey = "私钥";//解密使用
var publicKey  = "公钥";//加密使用

4.设置加密模式

//cipherMode [加密模式 C1C3C2:1, C1C2C3:0]
    const cipherMode = 1;//默认是1

5.解密的使用全码

 

页面代码直接@click绑定getphone即可单击实现



 data() {
    return {
          copyphone:'',
     }}
methods: {
    getphone(){
        const sm2 = require('sm-crypto').sm2;
       
        //
        var privateKey = "私钥";
        var encrText = 需要解密的字段; 
        //有04要截 var encrText = val.substring(2);val是后台传过来的加密字段,将‘04’截取掉
        const cipherMode = 1
        let decryptData = sm2.doDecrypt(encrText, privateKey, cipherMode) // 解密结果
        return decryptData ;
        this.copyphone = decryptData;//赋值方便处理
        console.log(this.copyphone);//直接打印出来看是否实现
                 }
           }

6.加密的实现全码


页面代码直接@click绑定getphone即可单击实现



 data() {
    return {
          copyphone:'',
          phone:'123545687',

     }}
methods: {
    getphone(){
        const sm2 = require('sm-crypto').sm2;
        var publicKey  = "公钥";//加密使用
        var encrText = 需要加密的字段;//例如var enxrText = this.phone;
        const cipherMode = 1;
        let decryptData = sm2.doDecrypt(encrText, publicKey, cipherMode) // 加密结果
        return '04' + decryptData;//04可不要具体看后端要求
       
      
                 }
           }

猜你喜欢

转载自blog.csdn.net/qq_46057971/article/details/128224102
今日推荐