uinapp和php实现RSA + AES 双向通信加密

使用场景

  • 如果只是为了防止用户数据泄露,有条件用https,那不要犹豫,赶快买个证书。
  • 但是https也有局限性,加密层位于http层(应用层)和tcp层(传输层)之间, 所以抓到的http层的数据并没有加密。

单独加密的弊端

  • 单独用RSA非对称加密的话,客户端解密的时候需要用到私匙,这样无异于裸奔,使得整个加密毫无意义,除非你客户端只加密不解密,服务器直接返回明文,但这样就不是双向加密了
  • 单独用AES对称加密的话,加密解密用同一个密匙,密匙就在客户端放着,也是裸奔

AES + RSA 加密思路

  • 在启动APP时,本地随机生成AES密匙,不做持久化存储。

  • 通信的时候,将AES密匙通过RSA加密发送给服务器,将通信内容用过AES加密发送给服务器,这样服务器通过RSA解密得到AES密匙,再通过AES解密得到通信明文内容。

  • 返回数据的时候,服务器通过AES加密返回密文,客户端用过AES解密得到明文。这样,抓包是无法获取AES密匙的,AES密匙只存在于本地内存中

  • 总结来说,就是通过AES加密通信内容,RSA加密AES密匙

以下为简单实现过程,在实际线上项目请对公钥进行缓存,ASE私钥定期更新处理,以保证性能和安全两不误!

uinapp片段
创建文件test.vue,内容如下:

<template>
	<view>
		<button type="warn" @click="test()" plain>测试</button>
		<text v-show="res!==null">返回结果:{
     {
     res}}</text>
	</view>
</template>

<script>
	import CryptoJS from '@/js_sdk/encryption/crypto-js/crypto-js';
	import JSEncrypt from '@/js_sdk/encryption/jsencrypt/jsencrypt';
	export default {
     
		data() {
     
			return {
     
				publicKey: null, // RSA加密公匙
				aesKey: null, // AES加密密匙
				iv: 'YM_CHAT_TOOLS_MS', //
				aesEncryptKey: null, // AES加密密匙的RSA加密字符串	
				res: null,
			}
		},
		mounted() {
     
			this.initEncryption();
		},
		methods: {
     
			test() {
     
				let params = {
     
					id: 123,
					name: '我爱我家呀~'
				};
				uni.request({
     
					url: 'http://im.xxx.cn/test.php', //仅为示例,并非真实接口地址。
					data: this.EncrypRequestParams(params),
					success: (res) => {
     
						this.res = this.DecryptResData(res.data);
						console.log('this.res:' + this.res);
					}
				});
			},
			DecryptResData(res) //解密返回结果
			{
     
				return this.decrypt(res, this.aesKey, this.iv);
			},
			EncrypRequestParams(params = {
     }) //加密请求参数
			{
     
				if (this.publicKey === null) {
     
					uni.showToast({
     
						title: "请先获取公钥",
						duration: 2000,
						mask: true
					})
					return;
				}
				params.timestamp = this.getTimestamp();
				params = this.encrypt(JSON.stringify(params), this.aesKey, this.iv);
				params = {
     
					params: params,
					aesEncryptKey: this.aesEncryptKey,
				};
				console.log('params:' + JSON.stringify(params));
				return params;
			},
			//初始化通讯密钥
			initEncryption() {
     
				uni.request({
     
					url: 'http://im.xxx.cn/public.key', //仅为示例,并非真实接口地址。
					success: (res) => {
     
						this.publicKey = res.data;
						this.aesKey = this.initAesKey();
						this.aesEncryptKey = this.rsaEncrypt(JSON.stringify(this.aesKey), this.publicKey);

						console.log('this.publicKey:' + this.publicKey);
						console.log('this.aesKey:' + this.aesKey);
						console.log('this.aesEncryptKey:' + this.aesEncryptKey);
						console.log('初始化成功');
					}
				});
			},
			getTimestamp() //获取10位时间戳
			{
     
				let tmp = Date.parse(new Date()).toString();
				tmp = tmp.substr(0, 10);
				return tmp;
			},
			// 加密函数
			encrypt(str, KEY, IV = '') {
     
				var key = CryptoJS.enc.Utf8.parse(KEY);
				var iv = CryptoJS.enc.Utf8.parse(IV);
				var encrypted = CryptoJS.AES.encrypt(str, key, {
     
					iv: iv,
					mode: CryptoJS.mode.CBC,
					padding: CryptoJS.pad.Pkcs7
				});
				return encrypted.toString();
			},

			//解密
			decrypt(str, KEY, IV = '') {
     
				var key = CryptoJS.enc.Utf8.parse(KEY);
				var iv = CryptoJS.enc.Utf8.parse(IV);
				var decrypt = CryptoJS.AES.decrypt(str, key, {
     
					iv: iv,
					mode: CryptoJS.mode.CBC,
					padding: CryptoJS.pad.Pkcs7
				});
				return decrypt.toString(CryptoJS.enc.Utf8);
			},

			//公钥加密
			rsaEncrypt(word, publicKey) {
     
				const encrypt = new JSEncrypt();
				encrypt.setPublicKey(publicKey);
				return encrypt.encrypt(word);
			},

			//生成随机aes秘钥
			initAesKey() {
     
				return CryptoJS.MD5(new Date().getTime() + this.randomString(32)).toString();
			},

			//生成随机字串符
			randomString(len) {
     
				len = len || 32;
				var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678'; /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
				var maxPos = $chars.length;
				var pwd = '';
				for (let i = 0; i < len; i++) {
     
					pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
				}
				return pwd;
			},

		}
	}
</script>

php片段
创建test.php,内容如下


$iv = 'YM_CHAT_TOOLS_MS';
//公钥
$public_key = '-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAu8oSJJAAF4+t4JPoP+LV
3qZTp32K/8tCWGfR/+HE4YwVap63pADKfTkJhBtdaVJK++4DZTxp4zmAbNpV9cNt
eAizRcGb1ytyZp+dLjpW3jBE9DarE5xKBkNCFkf2pF5mfE6inlG2lBSYa0MNt8ZY
s7nPmu+qNYlIeshfm8OuEmNuJVRUNHY7jPgEjZq9Z5Q+kA0MJ7P097PSWfR1FJ12
WufsDH93JK4D7C4iACPoU2l1NywVmOGnjtqdjYfZSlu1kpPKAy0USdEDVxwMWR/v
WbK6Jk7rJWvpR7IY/jLWSTSdwPBA/HT/exdU+YT7BwEy2vzD4Ik/fLSj1LEaNyiK
AQIDAQAB
-----END PUBLIC KEY-----';
//私钥解密
$private_key = '-----BEGIN PRIVATE KEY-----
MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQC7yhIkkAAXj63g
k+g/4tXeplOnfYr/y0JYZ9H/4cThjBVqnrekAMp9OQmEG11pUkr77gNlPGnjOYBs
2lX1w214CLNFwZvXK3Jmn50uOlbeMET0NqsTnEoGQ0IWR/akXmZ8TqKeUbaUFJhr
Qw23xlizuc+a76o1iUh6yF+bw64SY24lVFQ0dju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Grwzgj6hRanEwOu5z15QOhJT4lFliSnBlyqch0+PE+aJqJQ2yp0txyTIJU/Cw7
x3QsyxkUVwcf1tuvKn8YS2VkWWCUN+djIzzt0JZ8+DlsazmcYb60iH7UqSklvzde
gLOoiQd7+zdUEMzSyh9ibxpMh2WbZpFLjusj8v55AoGBAI0dsu0ZW/WGvHYNwpn8
XP8x9N0/RoNyrwd+UnXQg4Kn5jw5NsEyhcfR9h/nl4kpDbnw1OY+TpfzIUABOVwf
VKWZ9VQjNGWxuKrqBSY7ViM8QkHvOVIo4aRRf5ITlmErs3fAh6islj8DJR1HHqFz
xHm/4gaL5CuAB22ljEPUgxir
-----END PRIVATE KEY-----';


$aesEncryptKey = $_GET['aesEncryptKey'];
$content = $_GET['params'];
$return_de = openssl_private_decrypt(base64_decode($aesEncryptKey), $decrypted, $private_key);
if (!$return_de) {
     
    return ('解密失败,请检查RSA秘钥');
}
$decrypted = json_decode($decrypted, true);

$de = openssl_decrypt($content, 'AES-256-CBC', $decrypted, 4, $iv);

$content = [
    "data" => [
        'time' => date("Y-m-d H:i:s"),
    ],
    "msg"  => 'OK',
    "code" => 200,
];
$res_en = base64_encode(openssl_encrypt(json_encode($content), "AES-256-CBC", $decrypted, 1, $iv));
echo $res_en;

说明
参数iv事先确认好前后端一致即可,注意是16进制
crypto-js和jsencrypt包下载
在线生成RSA秘钥,推荐长度2048bit,私钥不填即可

你可能感兴趣的:(php,JavaScript)