Sincelily 2017-04-19
加密是在客户端加密的,如android和IOSapp里面,对图片加密后上传到服务器,服务器接收并存储这个加密后的图片,假设这个图片访问的url是http://xxx.png,现在要在H5页面中显示这个加密图片,就要用js解密,用的是CryptoJS解密的(https://github.com/brix/crypto-js/releases),代码如下:
//需要引入的js文件 <script type="text/javascript" src="static/js/aes/aes.js"></script> <script type="text/javascript" src="static/js/aes/core.js"></script> <script type="text/javascript" src="static/js/aes/enc-base64.js"></script> <script type="text/javascript" src="static/js/aes/enc-u8array.js"></script> <script type="text/javascript" src="static/js/aes/lib-typedarrays.js"></script> <script type="text/javascript" src="static/js/aes/mode-ecb.js"></script> //在解密之前,要获取AES解密的key,我这里是个例子就写死了 var key = "1234567812345678" var url = "http://xxx.png"; //页面上用ajax获取图片的字节数组 var xhr = new XMLHttpRequest(); xhr.open("GET",url,true); xhr.responseType = "arraybuffer"; xhr.onload = function() { if(xhr.readyState ==4){ if (xhr.status == 200){ process(xhr.response,key); }else{ retry(url,key); } } } xhr.send(); function process(buffer,key) { //将上面下载的图片转为base64编码 var view = new Uint8Array(buffer); var contentWA = CryptoJS.enc.u8array.parse(view); var dcBase64String = contentWA.toString(CryptoJS.enc.Base64); //解密 var decryptedData = CryptoJS.AES.decrypt(dcBase64String, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }); //把解密后的对象再转为base64编码,这步是关键,跟解密文字不同 var d64 = decryptedData.toString(CryptoJS.enc.Base64); //构造img标签,显示解密后的图片 var img = new Image; img.src = "data:image/png;base64,"+d64; document.body.append(img); } //如果获取图片失败,尝试再获取一次.图片较少的话不需要重新获取,我这边图片一次性在40张左右,而且图片是上M的大图,失败较多,用这个再获取一次效果不错 function retry(url,key){ var xhr = new XMLHttpRequest(); xhr.open("GET",url,true); xhr.responseType = "arraybuffer"; xhr.onload = function() { if (xhr.status == 200){ process(xhr.response,key); } } xhr.send(); }