tp6+vue实现非对称加密登录

本文介绍如何在Vue项目中使用JSEncrypt实现登录信息的加密传输,并展示了前后端的具体实现过程。

vue安装下载jsencrypt(使用npm i -S jsencrypt安装会报错,只能使用cnpm安装)

cnpm i -S jsencrypt

npm安装

npm install jsencrypt
<script src="http://passport.cnblogs.com/scripts/jsencrypt.min.js"></script>

vue

<template>
<el-form :model="ruleForm"
                    ref="ruleForm" 
                    label-width="0" 
                    class="login-page">
                        <el-form-item prop="user_name">
                            <el-input type="text" 
                                v-model="ruleForm.user_name"
                                autocomplete="on" 
                                placeholder="用户名"
                                maxlength="50"
                                size="large"
                                @keydown.enter.native="login"
                            ></el-input>
                        </el-form-item>

                        <el-form-item prop="user_password">
                            <el-input type="password" 
                                v-model="ruleForm.user_password"
                                autocomplete="on" 
                                placeholder="登录密码"
                                maxlength="50"
                                size="large"
                                @keydown.enter.native="login"
                            ></el-input>
                        </el-form-item>

                        <el-form-item prop="vcode" class="vcode_box">
                            <el-input
                                v-model="ruleForm.vcode"
                                placeholder="验证码"
                                autocomplete="off"
                                maxlength="4"
                                style="width: 200px;"
                                size="large"
                                @keydown.enter.native="login"
                            ></el-input>
                            <div class="vcode" title="点击重新生成验证码">
                                <img @click="refreshCode" :src="imgCode" alt="验证码">
                            </div>
                        </el-form-item>

                        <el-button class="login_btn" @click="login" >登录</el-button>
                    </el-form>
</template>
<script>
import { JSEncrypt } from "jsencrypt";
export default{
	data() {
        return {
            ruleForm: {
                user_name: '',
                user_password: '',
                code: ''
            },
            imgCode: '验证码地址',
            publicKey: ''
        }
    },
    methods: {
    	// 获取公钥
		async getPublicKey(){
            const {data:res} = await this.$axios.get("getSecretkey");
            if(res.state){
                this.publicKey = res.content;
            }else{
                this.$message.error("网络错误,请稍后重试!");   
            }
        },
        // 点击登录
        login(){
			// ... 验证用户名、密码、验证码是否输入
			let formData = this.ruleForm;
			let encryptor = new JSEncrypt();
            encryptor.setPublicKey(this.publicKey);
            // 将用户名和密码加密处理
            let data_encrypted = encryptor.encrypt(formData.user_name+','+formData.user_password);
            var datas = {};
            datas.code = formData.code;
            datas.logininfo = data_encrypted;
            this.$axios.post('login', datas).then(res => {
				console.log(res)
			});
		}
	}
}
</script>

php

安装openssl扩展
小P(phpstudy):打开小p工具 -> 网站 -> localhost(管理)-> php扩展找到openssl并打开
原生php:打开php.ini文件,搜索extension=openssl,将前面的;删除,保存重启服务

public function getSecretkey(){
        // 检测今天生成的密钥文件是否存在,不存在则生成
        if( file_exists("./secretKey/".date('Ymd', time()).'_publicKey.pem' )){
            // 读取该文件
            $public_key = file_get_contents("./secretKey/".date("Ymd", time())."_publicKey.pem");
            return $public_key;
        }else{
            # 1.清空目录中非当天生成的加密文件
            if(is_dir("./secretKey")){
                $dirs = scandir("./secretKey"); // 获取该目录下所有目录及文件
                foreach($dirs as $file){
                    if($file != '.' && $file != '..'){
                        $sonFile = "./secretKey/".$file;
                        @unlink($sonFile);
                    }
                }
            }
            # 2.生成文件
            $config = array(
                'config' => 'D:\phpstudy_pro\Extensions\Apache2.4.39\conf\openssl.cnf',//安装PHP7会自带这个配置文件
                "digest_alg" => "sha512",
                "private_key_bits" => 1024,
                "private_key_type" => OPENSSL_KEYTYPE_RSA,   //加密类型
              );
            $res = openssl_pkey_new($config);
            //提取私钥
            openssl_pkey_export($res, $private_key, null,$config);
            //生成公钥
            $public_key = openssl_pkey_get_details($res);
            $public_key=$public_key["key"];
            file_put_contents("./secretKey/".date('Ymd', time())."_publicKey.pem", $public_key); // 生成公钥
            file_put_contents("./secretKey/".date('Ymd', time())."_privateKey.pem", $private_key); // 生成私钥
            return $public_key;

        }
    }

public function login(){
	$data = input('post.');
    // 使用密钥进行解密获取数据
    $privateKey = file_get_contents("./secretKey/".date('Ymd', time())."_privateKey.pem");
    if(!openssl_private_decrypt(base64_decode($data['logininfo']), $decrypted, $privateKey)){
        return show(false, '501.非法请求');
    }
    $login_info = explode(",", $decrypted);
    // 用户名、密码、验证码验证
    $res = $this->check_login($login_info[0], $login_info[1], $data['code']);
    if($res){
		return '登陆成功';
	}else{
		return '登录失败';
	}
    
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值