本文,讲的是有关安全的话题。
概述
GIS的数据一直是比较敏感的,所以数据安全也是一个“老生常谈”的话题。本文利用geoserver的矢量切片插件对数据进行发布,通过自己写的中间接口实现矢量切片的加密,并修改mapboxGL源码,添加数据的解密与展示。
实现效果
实现
1. MapboxGL 2.X离线时候的token强认证
2.X的mapboxGL是有token
的强制认证的,离线的时候我们可以通过修改源码取消这个强制认证。
2. geoserver矢量切片加密
大致流程如下:
-
修改vector_tile_source.js
const params = {
request,
data: undefined,
uid: tile.uid,
tileID: tile.tileID,
tileZoom: tile.tileZoom,
zoom: tile.tileID.overscaledZ,
tileSize: this.tileSize * tile.tileID.overscaleFactor(),
type: this.type,
source: this.id,
pixelRatio: browser.devicePixelRatio,
showCollisionBoxes: this.map.showCollisionBoxes,
promoteId: this.promoteId,
isSymbolTile: tile.isSymbolTile,
metaData: this._options.metaData
};
-
修改vector_tile_worker_source.js
// 添加解密
import CryptoJS from 'crypto-js'
const key = CryptoJS.enc.Utf8.parse("密钥"); //十六位十六进制数作为密钥
const iv = CryptoJS.enc.Utf8.parse('密钥偏移量'); //十六位十六进制数作为密钥偏移量
function StringToUint8Array(str){
var arr = [];
for (var i = 0, j = str.length; i < j; ++i) {
arr.push(str.charCodeAt(i));
}
return new Uint8Array(arr);
}
function Decrypt(word) {
const encryptedHexStr = CryptoJS.enc.Hex.parse(word);
const srcs = CryptoJS.enc.Base64.stringify(encryptedHexStr);
const decrypt = CryptoJS.AES.decrypt(srcs, key, {iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7});
const decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
return decryptedStr.toString();
}
const makeRequest = (callback) => {
let request = null
if (params.metaData && params.metaData.type === 'geoserver') {
request = fetch(params.request.url).then(res => res.json()).then(res => {
const str = Decrypt(res.data)
const data = StringToUint8Array(str)
callback(null, {
vectorTile: skipParse ? undefined : new vt.VectorTile(new Protobuf(data)),
rawData: data
});
})
} else {
request = getArrayBuffer(params.request, (err: ?Error, data: ?ArrayBuffer, cacheControl: ?string, expires: ?string) => {
if (err) {
callback(err);
} else if (data) {
callback(null, {
vectorTile: skipParse ? undefined : new vt.VectorTile(new Protobuf(data)),
rawData: data,
cacheControl,
expires
});
}
});
}
return () => {
request.cancel();
callback();
};
};
测试服务端代码
const express = require('express');
const request = require("request");
const secret = require("./secret");
const fs = require('fs')
const app = express();
// 自定义跨域中间件
const allowCors = function (req, res, next) {
res.header('Access-Control-Allow-Origin', req.headers.origin);
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type');
res.header('Access-Control-Allow-Credentials', 'true');
next();
};
app.use(allowCors);//使用跨域中间件
app.get('/tile/:z/:x/:y', function (req, res) {
const {x, y, z} = req.params
const url = `http://localhost:8086/geoserver/gwc/service/tms/1.0.0/sfmap%3Achina@EPSG%3A900913@pbf/${z}/${x}/${y}.pbf`
// 直接转发
// request(url).pipe(res)
// 加密转发
const path = `./tiles/${z}-${x}-${y}.mvt`
const file = fs.createWriteStream(path)
request(url).pipe(file)
file.on('finish', function() {
const buffer = fs.readFileSync(path)
let str = secret.Uint8ArrayToString(buffer)
str = secret.Encrypt(str)
res.format ({
'text/json': function() {
res.send({
type: 'geoserver',
data: str
});
file.close();
}
});
});
})
const server = app.listen(18081, () => {
console.log("应用实例,访问地址为 http://localhost:18081/tile/0/0/0")
})
// 加密方法
function Encrypt(word) {
let srcs = CryptoJS.enc.Utf8.parse(word);
let encrypted = CryptoJS.AES.encrypt(srcs, key, { iv: iv, mode: CryptoJS.mode.CBC, padding: CryptoJS.pad.Pkcs7 });
return encrypted.ciphertext.toString().toUpperCase();
}
前端展示代码
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>白天不懂夜的黑</title>
<meta name="description" content="">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link href="../dist/mapbox-gl.css" rel="stylesheet" />
<style>
html, body, #map {
padding: 0;
margin: 0;
overflow: hidden;
height: 100vh;
}
</style>
</head>
<body>
<div id="map">
</div>
<script src="../dist/mapbox-gl-unminified.js"></script>
<script>
var mapStyle = {
"version": 8,
"name": "Dark",
"sources": {
"XYZTile": {
"type": "raster",
"tiles": ['https://tile.openstreetmap.org/{z}/{x}/{y}.png'],
"tileSize": 256
},
"XYZVectorTile": {
"type": "vector",
"scheme": "tms",
"tiles": [
"http://localhost:18081/tile/{z}/{x}/{y}"
],
"metaData": { // 原始没有,新加的
"type": "geoserver"
}
}
},
"layers": [{
"id": "XYZTile",
"type": "raster",
"source": "XYZTile",
"minzoom": 0,
"maxzoom": 22
}, {
id: 'province',
type: 'line',
source: 'XYZVectorTile',
'source-layer': 'bou2_4p',
paint: {
'line-color': 'rgba(255,0,0,0.49)',
'line-width': 1.5
}
}]
};
var map = new mapboxgl.Map({
container: 'map',
maxZoom: 18,
minZoom: 0,
zoom: 3,
center: [107.01325543038672, 22.144192102953994],
style: mapStyle,
attributionControl: false
});
</script>
</body>
</html>