JavaScript前端代码
//引用AES加密库
<script src="/file/crypto-js.js"></script>
<script>
jQuery().ready(function(){
debugger
$("#fj").children('div').find('a').on('click',function(){
debugger;
var url=$(this).data('href');
var pid= url.substr(url.indexOf('?')+1).split('=');
if(pid.length>1)
{
pid=pid[1];
if(pid.length<16){
var num=16-pid.length;
for(var i=0;i<num;i++)
{
pid+="0";
}
}
}
//获取时间戳
var timestamp = (new Date()).valueOf().toString();
//将时间戳和key值进行AES加密
var token= CryptoJS.AES.encrypt( CryptoJS.enc.Utf8.parse(timestamp), CryptoJS.enc.Utf8.parse(pid.substr(0,16)), { mode:CryptoJS.mode.ECB, padding: CryptoJS.pad.Pkcs7 }).toString();
$(this).attr('href',encodeURI(url+'&token='+token));
});
});
</script>
Java后台代码
@ApiOperation(value = "获取文件", notes = "获取文件")
@RequestMapping(value = "/getFile", method = {RequestMethod.GET})
@ResponseBody
public void getFile(@RequestParam(value = "pid") String pid,
@RequestParam(value = "token") String token,
@ApiIgnore HttpServletResponse response) throws Exception {
String secKey = null;
int len = pid.length();
if (len > 16) {
secKey = pid.substring(0, 16);
} else {
StringBuilder builder = new StringBuilder(pid);
for (int i = 0; i < 16 - len; i++) {
builder.append('0');
}
secKey = builder.toString();
}
String timestamp = getTimestamp(token, secKey);
long tm = Long.parseLong(timestamp); //接口时间
long curTm = System.currentTimeMillis(); //当前时间
long ls = Math.abs(curTm - tm);
long minute = TimeUnit.MINUTES.convert(ls, TimeUnit.MILLISECONDS);
if (minute > 3) {
throw new RuntimeException("链接已过期!");
}
CMResourceData data = DocUtil.retrieveStream(pid);
String filename = data.getFilename();
response.setContentType("application/x-download");
response.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "UTF-8"));
CMResource.streamData(data.getStream(), response.getOutputStream(), true);
}
//AES解密获取时间戳
private String getTimestamp(String encryptStr, String decryptKey) throws Exception {
if (StringUtils.isEmpty(encryptStr) || StringUtils.isEmpty(decryptKey)) {
return null;
}
byte[] encryptByte = Base64.getDecoder().decode(encryptStr);
Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(decryptKey.getBytes(), "AES"));
byte[] decryptBytes = cipher.doFinal(encryptByte);
return new String(decryptBytes);
}