前端项目中使用jsencrypt进行字段加密

前端项目中使用jsencrypt进行字段加密。

使用步骤:①获取公钥②实例化对象③设置公钥④将所需数据进行加密然后返回。

进行一个简单的封装如下

/**
 * npm install jsencrypt -S
 * @param getPublicKey 获取到的公钥,一般由后端返回,我们可以在点击提交按钮时发送ajax请求拿到该返回的公钥
 * @param data 我们需要加密的数据,通过实例化对象操作之后返回一段新的加密码,然后将其作为参数发送给后端即可
 * @returns {PromiseLike<ArrayBuffer>}
 */
function encryptData(getPublicKey, data) {

    // 实例化对象
    let encrypt = new JsEncrypt();

    // 设置公钥
    encrypt.setPublicKey(getPublicKey);

    // 返回加密的数据
    return encrypt.encrypt(data);
}

写个简单的demo如下,以vue项目为例

<template>

</template>

<script>
    import JsEncrypt from 'jsencrypt'
    import axios from 'axios'
    export default {
        data() {
          return {
              username: 'hello',
              password: ''
          }
        },
        methods: {
            encryptData(getPublicKey, data) {

                // 实例化对象
                let encrypt = new JsEncrypt();

                // 设置公钥
                encrypt.setPublicKey(getPublicKey);

                // 返回加密的数据
                return encrypt.encrypt(data);
            },
            submit() {
                axios({
                    method: 'post',
                    url: '',
                }).then(res => {
                    // res为后端返回的key,如同下面这样
            //
let res = 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCa+VHPOwxi0re/GhWApLl6WQMoTKazQsPp66AD8CKt2TaPrwv+dDFdQ5jP9xRbalGhLhEBlDq20oOCuIwWAI7/s0QTTvjYIBd+yWKzuRp0E+Qe7DqIE0pMrTi/ELkqibehYIvJ4sIEM+Wj9R007WT/64vGG/FaPsK9RsZiGShOAQIDAQAB'
                    let password = encryptData(res, password);
                    axios({
                        method: 'post',
                        url: '',
                        data: {
                            username: this.username,
                            password: password
                        }
                    }).then(ress => {
                        console.log(ress);
                    })
                })
            }
        }
    }
</script>

<style>

</style>

猜你喜欢

转载自www.cnblogs.com/troublehuan/p/12082265.html