附件地址校验JS加密tokenJAVA后台解密

 JavaScript前端代码

//引用AES加密库

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);
    }

你可能感兴趣的:(解决方案,javascript,java)