js对AES加密的图片解密
加密是在客户端加密的,如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(); }
相关推荐
tengyuan 2020-05-30
visionzheng 2020-05-04
LowisLucifer 2020-04-30
dbhllnr 2020-04-26
wordmhg 2020-03-27
wbingyang 2020-02-14
CloudXli 2020-01-12
ahnuzfm 2019-12-24
JF0 2019-12-09
hgzhang 2019-10-22
数据与算法之美 2015-03-09
frankwtq 2012-02-02
guohewei 2019-03-28
HerryDong 2018-05-14
zhuyonge 2016-05-19
走在IT的路上 2013-11-07
风吹夏天 2012-08-28