【续写】后端密码加密与本地文件流及图形验证码

本地文件上传,下载和显示

Controller层


    /**
     * 文件上传
     */
    @RequestMapping("/uploadFile")
    @ResponseBody
    public Map<String, Object> uploadFile(MultipartFile mf) {
        //1、得到文件名
        String oldName = mf.getOriginalFilename();
        //2、根据文件名生成新文件名
        String newName = AppFileUtils.createNewFileName(oldName);
        //3,得到当前日期的字符串
        String dirName = DateUtil.format(new Date(), "yyyy-MM-dd");
        //4、构造文件夹
        File dirFile = new File(AppFileUtils.UPLOAD_PATH, dirName);
        //5,判断当前文件夹是否存在
        if (!dirFile.exists()) {
            dirFile.mkdirs();//创建新的文件夹
        }
        //6,构造文件对象
        File file=new File(dirFile, newName+"_temp");
        //7,把mf里面的图片信息写入file
        try {
            mf.transferTo(file);
        } catch (IllegalStateException | IOException e) {
            e.printStackTrace();
        }
        Map<String,Object> map=new HashMap<String, Object>();
        map.put("path", dirName+"/"+newName+"_temp");
        return map;
    }

    /**
     * 图片展示
     */
    @RequestMapping("/showImage")
    public ResponseEntity<Object> showImage(String path){

        return AppFileUtils.createResponseEntity(path);
    }

工具类


/**
 * 文件上传下载工具类
 *
 */
public class AppFileUtils {
    //文件上传的保存路径
    public static String UPLOAD_PATH = "E:/upload/";//默认值

    static {
        //读取配置文件的存储地址
       /* InputStream stream = AppFileUtils.class.getClassLoader().getResourceAsStream("file.properties");
        Properties properties = new Properties();
        try {
            properties.load(stream);
        } catch (IOException e) {
            e.printStackTrace();
        }*/
        String property = "E:/upload/";
        if (null != property) {
            UPLOAD_PATH = property;
        }

    }

    /**
     * 根据文件老名字得到新名字
     *
     * @param oldName
     * @return
     */
    public static String createNewFileName(String oldName) {

        String stuff = oldName.substring(oldName.lastIndexOf("."), oldName.length());
        return IdUtil.simpleUUID().toUpperCase() + stuff;
    }

    /**
     * 文件下载
     *
     * @param path
     * @return
     */
    public static ResponseEntity<Object> createResponseEntity(String path) {
        //1,构造文件对象
        File file = new File(UPLOAD_PATH, path);
        if (file.exists()) {
            //将下载文件,封装到btye【】数组中
            byte[] bytes = null;
            try {
                bytes = FileUtil.readBytes(file);
            } catch (Exception e) {
                e.printStackTrace();
            }
            //创建封装响应头信息的对象
            HttpHeaders header = new HttpHeaders();
            //封装响应内容类型(APPLICATION_OCTET_STREAM 响应的内容不限定)
            header.setContentType(MediaType.APPLICATION_OCTET_STREAM);
            //设置下载的文件的名称
//			header.setContentDispositionFormData("attachment", "123.jpg");
            //创建ResponseEntity对象
            ResponseEntity<Object> entity = new ResponseEntity<>(bytes, header, HttpStatus.CREATED);
            return entity;
        }

        return null;
    }

    /**
     * 去掉  _temp
     * @param img
     * @return
     */
    public static String rename(String img) {

        File file=new File(UPLOAD_PATH, img);
        String replace = img.replace("_temp", "");
        if (file.exists()){
            file.renameTo(new File(UPLOAD_PATH,replace));
        }
        return replace;
    }

    /**
     * 删除原来的照片
     * @param img
     */
    public static void removeFileByPath(String img) {

        if (!img.equals("images/timg.jpg")){
            File file=new File(UPLOAD_PATH, img);
            if (file.exists()){
                file.delete();
            }
        }
    }
}

图形验证码

Controller层

@Controller
@RequestMapping("/verifyCode")
public class CodeController {

        @RequestMapping(value = "/getImg", method = {RequestMethod.POST, RequestMethod.GET})
        protected void createImg(HttpServletRequest req, HttpServletResponse res) throws IOException {
            //1.生成随机的验证码及图片
            Object[] objs = VerifyCodeUtil.createImage();
            //2.将验证码存入session
            String imgcode = (String) objs[0];
            HttpSession session = req.getSession();
            session.setAttribute("imgcode", imgcode);
            //3.将图片输出给浏览器
            BufferedImage img = (BufferedImage) objs[1];
            res.setContentType("image/png");
            //服务器自动创建输出流,目标指向浏览器
            OutputStream os = res.getOutputStream();
            ImageIO.write(img, "png", os);
            os.close();
        }
    }

工具类

/**
 * 生成图片二维码方法工具类
 */

public final class VerifyCodeUtil {

        // 验证码字符集
        private static final char[] chars = {
                '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N',
                'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'};
        // 字符数量
        private static final int SIZE = 4;
        // 干扰线数量
        private static final int LINES = 10;
        // 宽度
        private static final int WIDTH = 100;
        // 高度
        private static final int HEIGHT = 32;
        // 字体大小
        private static final int FONT_SIZE = 20;

        /**
         * 生成随机验证码及图片
         * 数组中[验证码,图片]
         */
        public static Object[] createImage() {
            StringBuffer sb = new StringBuffer();
            // 1.创建空白图片
            BufferedImage image = new BufferedImage(
                    WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
            // 2.获取图片画笔
            Graphics graphic = image.getGraphics();
            // 3.设置画笔颜色
            graphic.setColor(Color.LIGHT_GRAY);
            // 4.绘制矩形背景
            graphic.fillRect(0, 0, WIDTH, HEIGHT);
            // 5.画随机字符
            Random ran = new Random();
            for (int i = 0; i <SIZE; i++) {
                // 取随机字符索引
                int n = ran.nextInt(chars.length);
                // 设置随机颜色
                graphic.setColor(getRandomColor());
                // 设置字体大小
                graphic.setFont(new Font(
                        null, Font.BOLD + Font.ITALIC, FONT_SIZE));
                // 画字符
                graphic.drawString(
                        chars[n] + "", i * WIDTH / SIZE, HEIGHT / 2);
                // 记录字符
                sb.append(chars[n]);
            }
            // 6.画干扰线
            for (int i = 0; i < LINES; i++) {

                graphic.setColor(getRandomColor());
                // 随机画线
                graphic.drawLine(ran.nextInt(WIDTH), ran.nextInt(HEIGHT),
                        ran.nextInt(WIDTH), ran.nextInt(HEIGHT));
            }
            // 7.返回验证码和图片
            return new Object[]{sb.toString(), image};
        }

        /**
         * 随机取色
         */
        public static Color getRandomColor() {
            Random ran = new Random();
            Color color = new Color(ran.nextInt(256),
                    ran.nextInt(256), ran.nextInt(256));
            return color;
        }

密码加密

工具类

/**
 * md5 加密方法工具类
 */
public class MD5Util {

    public static String MD5(String inStr) {
        MessageDigest md5 = null;
        try {
            md5 = MessageDigest.getInstance("MD5");
        } catch (Exception e) {
            System.out.println(e.toString());
            e.printStackTrace();
            return "";
        }
        char[] charArray = inStr.toCharArray();
        byte[] byteArray = new byte[charArray.length];

        for (int i = 0; i < charArray.length; i++)
            byteArray[i] = (byte) charArray[i];

        byte[] md5Bytes = md5.digest(byteArray);

        StringBuffer hexValue = new StringBuffer();

        for (int i = 0; i < md5Bytes.length; i++) {
            int val = ((int) md5Bytes[i]) & 0xff;
            if (val < 16)
                hexValue.append("0");
            hexValue.append(Integer.toHexString(val));
        }

        return hexValue.toString();
    }

    // 可逆的加密算法
    public static String KL(String inStr) {
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String s = new String(a);
        return s;
    }

    // 加密后解密
    public static String JM(String inStr) {
        char[] a = inStr.toCharArray();
        for (int i = 0; i < a.length; i++) {
            a[i] = (char) (a[i] ^ 't');
        }
        String k = new String(a);
        return k;
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值