前端利用jsencrypt封装接口参数加密or长加密

196 阅读1分钟

前端封装接口参数加密or长加密

只讲技术,不讲感情 前端参数要加密,怎么搞

加密(加密少量参数)

http.js中

// 新的接口调用方式
// window.boServerUrlNew,这也是代码中拼接的路径
function request(opts) {
    //根据不同环境区分密钥,这里是公司自己的密钥
    const pulicKey = isPRD? "MIGfMA0GxxxxCSABxxx": "xxxNIw0VWtwIDAQABxxx";
    let oEncrypt = new JSEncrypt();
    oEncrypt.setPublicKey(pulicKey);
    let enData = oEncrypt.encrypt(JSON.stringify(opts.data));
    const params = JSON.stringify({
        param: enData,
    });
    const optUrl = window.boServerUrlNew + opts.url;
    const defaultOpts = {
        url: optUrl,
        type: "POST",
        contentType: "application/json",
        data: params,
    };
    return new Promise((resolve, reject) => {
        const ajax = $.ajax(defaultOpts);
        ajax.done((data, textStatus, jqXHR) => {
            resolve(data);
        }).fail((jqXHR, textStatus, errorThrown) => {
            reject("Kesalahan jaringan" + " " + errorThrown);
        });
    });
}

Vue.prototype.$request = request;

.vue中

// 这里使用的版本v2.3.1
// 可以npm 安装npm install jsencrypt@2.3.1
import "../../static/js/encry/jsencrypt.min" 
import "../../static/js/http" 
// 获取用户头像,名称信息等
getUserMessage() {
            let params = {
                url: "/app/user/nickName/find",
                data: {
                    companyId: companyId,
                    customerNumber: this.customerNumber
                },
            };
            this.$request(params)
                .then((res) => {
                    if (res.code == 200) {
                        //这里写你的逻辑
                    }
                })
                .catch((err) => {
                    console.log("err", err);
                });
},

展示请求和效果

image-20230329103744467.png

长加密(加密很多参数)

http.js中

// 给JSEncrypt的原型上增加长加密的方法
const b64map ="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const b64pad = "=";
JSEncrypt.prototype.encryptLong = function (string) {
    const k = this.getKey();
    try {
        const lt = "";
        let ct = "";
        //RSA每次加密117bytes,需要辅助方法判断字符串截取位置
        //1.获取字符串截取点
        const bytes = new Array();
        bytes.push(0);
        let byteNo = 0;
        let len, c;
        len = string.length;
        let temp = 0;
        for (var i = 0; i < len; i++) {
                c = string.charCodeAt(i);
                if (c >= 0x010000 && c <= 0x10ffff) {
                    byteNo += 4;
                } else if (c >= 0x000800 && c <= 0x00ffff) {
                    byteNo += 3;
                } else if (c >= 0x000080 && c <= 0x0007ff) {
                    byteNo += 2;
                } else {
                    byteNo += 1;
                }
                if (byteNo % 117 >= 114 || byteNo % 117 == 0) {
                    if (byteNo - temp >= 114) {
                        bytes.push(i);
                        temp = byteNo;
                    }
                }
        }
        //2.截取字符串并分段加密
        if (bytes.length > 1) {
            // eslint-disable-next-line no-var
            for (var i = 0; i < bytes.length - 1; i++) {
                // eslint-disable-next-line no-var
                var str;
                if (i == 0) {
                    str = string.substring(0, bytes[i + 1] + 1);
                } else {
                    str = string.substring(bytes[i] + 1, bytes[i + 1] + 1);
                }
                const t1 = k.encrypt(str);
                ct += addPreZero(t1, 256);
            }
            if (bytes[bytes.length - 1] != string.length - 1) {
                const lastStr = string.substring(
                    bytes[bytes.length - 1] + 1
                );
                const rsaStr = k.encrypt(lastStr);
                ct += addPreZero(rsaStr, 256);
            }
            //console.log("加密完的数据:"+ct);
            return hex2b64(ct);
        }
        const t = k.encrypt(string);
        const y = hex2b64(t);
        return y;
    } catch (ex) {
        return false;
    }
};
// 长加密需要用到的方法
function hex2b64(h) {
        let i;
        let c;
        let ret = "";
        for (i = 0; i + 3 <= h.length; i += 3) {
            c = parseInt(h.substring(i, i + 3), 16);
            ret += b64map.charAt(c >> 6) + b64map.charAt(c & 63);
        }
        if (i + 1 == h.length) {
            c = parseInt(h.substring(i, i + 1), 16);
            ret += b64map.charAt(c << 2);
        } else if (i + 2 == h.length) {
            c = parseInt(h.substring(i, i + 2), 16);
            ret += b64map.charAt(c >> 2) + b64map.charAt((c & 3) << 4);
        }
        while ((ret.length & 3) > 0) ret += b64pad;
        return ret;
}
function addPreZero(num, length) {
        var t = (num + "").length,
            s = "";
        for (var i = 0; i < length - t; i++) {
            s += "0";
        }
        return s + num;
}
// 封装的请求
const requestLong = (opts) => {
        const pulicKey = isPRD? "MIGfMA0GxxxxCSABxxx": "xxxNIw0VWtwIDAQABxxx";
        const encrypt = new JSEncrypt();
        encrypt.setPublicKey(pulicKey); // 你的公钥
        const data = encrypt.encryptLong(JSON.stringify(opts.data));
        const params = JSON.stringify({
            param: data,
        });
        const optUrl = window.boServerUrlNew + opts.url;
        const defaultOpts = {
            url: optUrl,
            type: "POST",
            contentType: "application/json",
            data: params,
        };
        return new Promise((resolve, reject) => {
            const ajax = $.ajax(defaultOpts);
            ajax.done((data, textStatus, jqXHR) => {
                resolve(data);
            }).fail((jqXHR, textStatus, errorThrown) => {
                reject("Kesalahan jaringan" + " " + errorThrown);
            });
        });
};

Vue.prototype.$requestLong = requestLong;

.vue中

// 这里使用的版本v2.3.1
// 可以npm 安装npm install jsencrypt@2.3.1
import "../../static/js/encry/jsencrypt.min" 
import "../../static/js/http" 
// 提交用户信息,更新用户昵称和姓名,头像等
Submit() {
           
            let params = {
                url: "/app/user/nickName/save",
                data: {
                    companyId: companyId,
                    customerNumber: this.customerNumber,
                    nickName: this.myName,
                    headImgUrl: this.okimg,
                },
            };
            this.$requestLong(params)
                .then((res) => {
                // 这里写你的逻辑
                })
                .catch((err) => {
                    console.log("err", err);
                });
}

展示请求和显示效果

image-20230329110747396.png