uni-app 实现小程序rsa加密(非对称加密原理)

uni-app 小程序 rsa 加密 使用的是 jsencrypt

main.js文件

//引入js文件
import security_http_config from './common/security.js'

//封装的接口
Vue.prototype.proims = (data, url, contentType) => {
	//重要的地方
	**let currentKey = security_http_config.createKey();**
	const token_u = uni.getStorageSync('token');
	data.token = token_u;
	return new Promise((resolve, u) => {
		uni.request({
			url: httpurl + url,
			//重要的地方
			**data: security_http_config.transform('post', data, currentKey),**
			method: 'post',
			header: {
				token: uni.getStorageSync('token'),
				//重要的地方
				'Content-Type': contentType || "application/json",
				ff8d82a3d6654309b17c97289c9c78fc: 'headerEncoding:base64;contentEncoding:base64',
				ff974421535f45508a8931b6432ffbf5: security_http_config.rsa(currentKey, uni
					.getStorageSync('key'))
			},
			dataType: 'json',
			success: function(res) {
				if (res.data.code == 200) {
				
				} 
				resolve(res)
			},
			fail: function(res) {
				uni.showToast({
					title: '请稍后重试',
					icon: 'none',
					duration: 1200
				});
			}
		})
	})
};

这里是放在common文件里面了 可以自己定义。uni.getStorageSync(‘key’)是通过接口获取的

security.js文件

import CryptoJS from './crypto.js'
import JSEncrypt from './jsencrypt.js'

function transform(type, data, key) {
	if (!data) {
		return ""
	}
	let dataStr = ''
	if (typeof(data) === "object") {
		if (type == 'get') {
			var str = [];
			for (var k in data) {
				var v = data[k];
				if (typeof(v) === 'Array') {
					var name = encodeURIComponent(k) + "[]";
					var len = v.length;
					for (var i = 0; i < len; i++) {
						str.push(name + "=" + encodeURIComponent(v[i]));
					}
				} else {
					str.push(encodeURIComponent(k) + "=" + encodeURIComponent(v));
				}
			}
			dataStr = str.join("&");
		} else if (type == 'post') {
			dataStr = JSON.stringify(data);
		}
	} else if (typeof(data) === "String") {} else {
		throw "发送请求数据必须是字符串或者对象"
	}
	return aes(dataStr, key);
}

function aes(data, key) {
	var data1 = CryptoJS.CryptoJS.enc.Utf8.parse(data);
	var key1 = CryptoJS.CryptoJS.enc.Utf8.parse(key);
	var iv1 = CryptoJS.CryptoJS.enc.Utf8.parse("org.slf4j.Logger");
	var result = CryptoJS.CryptoJS.AES.encrypt(data1, key1, {
		iv: iv1,
		mode: CryptoJS.CryptoJS.mode.CBC,
		padding: CryptoJS.CryptoJS.pad.Pkcs7
	});
	return result.toString();
}

function rsa(data, publicKey) {
	var encrypt = new JSEncrypt.JSEncrypt();
	encrypt.setPublicKey(publicKey);
	return encrypt.encrypt(data);
}

function createKey() {
	var key = "";
	var hexDigits = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	for (var i = 0; i < 16; i++) {
		key += hexDigits.substr(Math.floor(Math.random() * 62), 1);
	}
	return key;
}
module.exports = {
	transform: transform,
	rsa: rsa,
	createKey: createKey
}

jsencrypt.js可以通过npm 下载。命令:wxmp-rsa。然后创建文件,把js引入就行

你可能感兴趣的:(uni-app,微信小程序,小程序,前端)