vue使用RSA加密解密-jsencrypt.js

1.安装jsencrypt.js

npm install jsencrypt --dev 

2.创建jsencrypt.js文件

// jsencrypt.js 放在utils公用文件夹下
// 以下为 jsencrypt.js内容
import JSEncrypt from 'jsencrypt/bin/jsencrypt.min'

// 密钥对生成 http://web.chacuo.net/netrsakeypair

const publicKey = '' // 生成公钥

const privateKey = '' // 私钥

// 加密
export function encrypt(txt) {
    
    
  const encryptor = new JSEncrypt()
  encryptor.setPublicKey(publicKey) // 设置公钥
  return encryptor.encrypt(txt) // 对数据进行加密
}

// 解密
export function decrypt(txt) {
    
    
  const encryptor = new JSEncrypt()
  encryptor.setPrivateKey(privateKey) // 设置私钥
  return encryptor.decrypt(txt) // 对数据进行解密
}

3.在需要使用加密解密的组件中使用
注册 登录以及重置密码 页面使用

// 我在页面中只使用了加密 所以只引入了加密的方法 encrypt,解密方法decrypt,可根据自己需求是否引入
import {
    
     encrypt } from '@/utils/jsencrypt' // 加密
export default {
    
    
	data() {
    
    
		return {
    
    
			registerForm: {
    
     // 点击注册按钮传入后台的参数
		        username: "", // 用户名
		        password: "", // 密码
		        confirmPassword: "", // 确认密码
		        phonenumber:'', // 手机号
		        deptId:'',
		        code: "", // 验证码
		        uuid: ""
		      }
		}
	},
	methods: {
    
    
		//注册按钮
		handleRegister() {
    
    
			// 走校验 校验手机号 验证码 以及密码是否符合
			this.$refs.registerForm.validate(valid => {
    
    
		        if (valid) {
    
    
		        	// 加载中
		          this.loading = true;
		          // 密码进行加密 
		          this.registerForm.password = encrypt(this.registerForm.password)
		          // 确认密码 进行加密
		          this.registerForm.confirmPassword = encrypt(this.registerForm.confirmPassword)
		          // 走接口传参
		          register(this.registerForm).then(res => {
    
    
		            const username = this.registerForm.username;
		            this.$alert("<font color='red'>恭喜你,您的账号 " + username + " 注册成功!</font>", '系统提示', {
    
    
		              dangerouslyUseHTMLString: true,
		              type: 'success'
		            }).then(() => {
    
    
		              this.$router.push("/login");
		            }).catch(() => {
    
    });
		          }).catch(() => {
    
    
		            this.loading = false;
		            if (this.captchaEnabled) {
    
    
		              this.getCode();
		            }
		          })
		        }
		      });
		}
	}
}

猜你喜欢

转载自blog.csdn.net/ccyolo/article/details/126966148