自定义OSS照片路径AES加密

本文介绍了一种通过AES加密处理照片路径,并从OSS系统安全获取照片的方法。使用特定的加密密钥对照片路径进行加密,通过解密后的路径从OSS中获取照片,确保了数据的安全性和隐私。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

//接口代码

// AES密钥
    private String aesKey = "079edef3060f*********";
    protected Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 直接访问,返回ok则启动成功
     */
    @RequestMapping("/islived")
    public String testConn() {

        return "ok";
    }

    /**
     * 根据加密的路径参数 去oss获取照片
     * 
     * @param aesPath 前台或者项目传入的 照片aes加密之后的路径名字,加密key要和此处的key保持一致
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/getOssPhoto", method = RequestMethod.GET)
    @ResponseBody
    public void getOssPhoto(@RequestParam(value = "aesPath", required = true, defaultValue = "") String aesPath,
            HttpServletRequest request, HttpServletResponse response) {
        OSSObject ossObject = null;
      

if (aesPath == null || aesPath.length() < 20) {
            ////--返回空数据
            response.reset();
            ////--返回默认空内容图片
            //InputStream inputStream = this.getClass().getResourceAsStream("/image/default_reginsur.jpg");
            //int buffer = 1024 * 10;
            //byte data[] = new byte[buffer];
            //response.setContentType("application/octet-stream");
            //// 文件名可以任意指定
            //try {
            //    response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode("deaultImg", "UTF-8"));
            //    int read = 0;
            //    while ((read = inputStream.read(data)) != -1) {
            //        response.getOutputStream().write(data, 0, read);
            //    }
            //} catch (Exception e1) {
            //    logger.error("============== 获取默认照片出错", e1);
            //}
            
        } else {
            // 照片路径为  https://sfrz.oss**.aliyuncs.com/**/**/*/**/**/1543671060395_*.jpg
            // 参数aesPath为/img/以后的部分加密,解密之后,根据路径调用OSS系统,获取文件流,返回过去
            AESUtil2 aesUtil2 = new AESUtil2();
            String fileName = aesUtil2.decrypt(aesKey, aesPath);
            logger.info("============== fileName:" + fileName);
            if (fileName != null && fileName.length() > 2) {
                OSS client = new OSSClientBuilder().build(OssConfig.ALIYUNS_OSS_INTERNAL_ENDPOINT,                         OssConfig.ALIYUNS_OSS_ACCESSKEYID, OssConfig.ALIYUNS_OSS_ACCESSKEYSECRET);             

InputStream inputStream = null;
                byte[] result = null;
                ServletOutputStream ouputStream = null;
                ByteArrayOutputStream baos = null;
                try {
                    OSSObject ossObject = client.getObject(OssConfig.ALIYUNS_OSS_BUCKETNAME, OssConfig.ALIYUNS_OSS_URLPATH + fileName);
                    if (ossObject == null) {  //未找到
                        throw new Exception("照片未找到,OSSObject为空!!");
                    } else {  //可以查到文件,获取文件流返回
                        
                        response.setContentType("application/octet-stream");

                          // 将文件名转为ASCLL编码
                        response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode(fileName, "UTF-8"));
                        inputStream = ossObject.getObjectContent();
                        baos = new ByteArrayOutputStream();
                        int len = 0;
                        byte[] buffer = new byte[4096];
                        while ((len = inputStream.read(buffer)) != -1) {
                            baos.write(buffer, 0, len);
                        }
                        result = baos.toByteArray();
                        response.setContentType("application/octet-stream");
                        response.setContentLength(result.length);
                        ouputStream = response.getOutputStream();
                        ouputStream.write(result, 0, result.length);
                        ouputStream.flush();
                    }

                } catch (Exception e) {
                    logger.error("============== 获取照片未找到:" + e.getMessage(), e);
                    try {
                        // 根据文件资源路径获取文件流,将默认照片返回去
                        InputStream inputStream2 = this.getClass().getResourceAsStream("/image/default_reginsur.jpg");
                        int len2 = 0;
                        byte[] buffer2 = new byte[4096];
                        while ((len2 = inputStream2.read(buffer2)) != -1) {
                            baos.write(buffer2, 0, len2);
                        }
                        result = baos.toByteArray();
                        response.setContentType("application/octet-stream");
                        response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode("deaultImg", "UTF-8")); // 将文件名转为ASCLL编码
                        response.setContentType("application/octet-stream");
                        response.setContentLength(result.length);
                        ouputStream = response.getOutputStream();
                        ouputStream.write(result, 0, result.length);
                        ouputStream.flush();
                    } catch (Exception e1) {
                        logger.error("============== 获取默认照片出错:" + e.getMessage(), e);
                    }
                    
                } finally {
                    if (baos != null) {
                        try {
                            baos.close();
                        } catch (Exception e) {
                            logger.error("============== " + e.getMessage());
                        }
                    }
                    if (ouputStream != null) {
                        try {
                            ouputStream.close();
                        } catch (Exception e) {
                            logger.error("============== "+e.getMessage());
                        }
                    }
                    client.shutdown();
                }
            } else {
                logger.error("============== 未获取到照片,开始获取默认照片...");
                // 根据文件资源路径获取文件流,将默认照片返回去
                InputStream inputStream = this.getClass().getResourceAsStream("/image/default_reginsur.jpg");
                int buffer = 1024 * 10;
                byte data[] = new byte[buffer];
                response.setContentType("application/octet-stream");
                // 文件名可以任意指定
                try {
                    response.setHeader("Content-Disposition", "inline;filename=" + URLEncoder.encode("deaultImg", "UTF-8"));
                    int read = 0;
                    while ((read = inputStream.read(data)) != -1) {
                        response.getOutputStream().write(data, 0, read);
                    }

                } catch (Exception e1) {
                    logger.error("============== 获取默认照片出错", e1);
                }
            }
        }

        }
    }

 

//aes工具

 

/**
 * AES加密工具类
 * 
 * @author  mu
 * @date 2018-08-20
 */
public class AESUtil2 {

    static final String ENCODE = "UTF-8";

    public static String encrypt(String passwd, String content) {
        try {
            Cipher aesECB = Cipher.getInstance("AES/ECB/PKCS5Padding");
            SecretKeySpec key = new SecretKeySpec(passwd.getBytes(ENCODE), "AES");
            aesECB.init(Cipher.ENCRYPT_MODE, key);
            byte[] result = aesECB.doFinal(content.getBytes(ENCODE));
            return new BASE64Encoder().encode(result);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    public static String decrypt(String passwd, String content) {
        try {
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");// 创建密码器
            SecretKeySpec key = new SecretKeySpec(passwd.getBytes(ENCODE), "AES");
            cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
            byte[] result = new BASE64Decoder().decodeBuffer(content);
            return new String(cipher.doFinal(result), ENCODE); // 解密
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (IllegalBlockSizeException e) {
            e.printStackTrace();
        } catch (BadPaddingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值