import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.RandomAccessFile;

public class FileEncryptAndDecrypt {

public static void main(String[] args) throws Exception {

String filename = "奔马.avi";

String flag = readFileLastByte("c:\\" + filename, 6);
        if (flag.indexOf("hello") > 0) {
            // 加密过了;
        } else {
            // 没有加密
            new FileEncryptAndDecrypt().encrypt("c:\\" + filename, "hello");
        }
        System.out.println(new FileEncryptAndDecrypt().decrypt("c:\\"
                + filename, "c:\\" + filename, 6));
        // System.out.println(readFileLastByte("c:\\3.jpg", 6));
    }

/**
     * 文件file进行加密
     * 
     * @param fileUrl
     *            文件路径
     * @param key
     *            密码
     * @throws Exception
     */
    public static void encrypt(String fileUrl, String key) throws Exception {
        File file = new File(fileUrl);
        String path = file.getPath();
        if (!file.exists()) {
            return;
        }
        int index = path.lastIndexOf("\\");
        String destFile = path.substring(0, index) + "\\" + "abc";
        System.out.println(destFile);
        File dest = new File(destFile);
        InputStream in = new FileInputStream(fileUrl);
        OutputStream out = new FileOutputStream(destFile);
        byte[] buffer = new byte[1024];
        int r;
        byte[] buffer2 = new byte[1024];
        while ((r = in.read(buffer)) > 0) {
            for (int i = 0; i < r; i++) {
                byte b = buffer[i];
                buffer2[i] = b == 255 ? 0 : ++b;
            }
            out.write(buffer2, 0, r);
            out.flush();
        }
        in.close();
        out.close();
        file.delete();
        dest.renameTo(new File(fileUrl));
        appendMethodA(fileUrl, key);
        System.out.println("加密成功");
    }

/**
     * 
     * @param fileName
     * @param content
     *            密钥
     */
    public static void appendMethodA(String fileName, String content) {
        try {
            // 打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "rw");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            randomFile.seek(fileLength);
            randomFile.writeBytes(content);
            randomFile.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

/**
     * 解密
     * 
     * @param fileUrl
     *            源文件
     * @param tempUrl
     *            临时文件
     * @param ketLength
     *            密码长度
     * @return
     * @throws Exception
     */
    public static String decrypt(String fileUrl, String tempUrl, int keyLength)
            throws Exception {
        File file = new File(fileUrl);
        if (!file.exists()) {
            return null;
        }
        File dest = new File(tempUrl);
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }

InputStream is = new FileInputStream(fileUrl);
        OutputStream out = new FileOutputStream(tempUrl);

byte[] buffer = new byte[1024];
        byte[] buffer2 = new byte[1024];
        byte bMax = (byte) 255;
        long size = file.length() - keyLength;
        int mod = (int) (size % 1024);
        int div = (int) (size >> 10);
        int count = mod == 0 ? div : (div + 1);
        int k = 1, r;
        while ((k <= count && (r = is.read(buffer)) > 0)) {
            if (mod != 0 && k == count) {
                r = mod;
            }

for (int i = 0; i < r; i++) {
                byte b = buffer[i];
                buffer2[i] = b == 0 ? bMax : --b;
            }
            out.write(buffer2, 0, r);
            k++;
        }
        out.close();
        is.close();
        return tempUrl;
    }

/**
     * 判断文件是否加密
     * 
     * @param fileName
     * @return
     */
    public static String readFileLastByte(String fileName, int keyLength) {
        File file = new File(fileName);
        if (!file.exists())
            return null;
        StringBuffer str = new StringBuffer();
        try {
            // 打开一个随机访问文件流,按读写方式
            RandomAccessFile randomFile = new RandomAccessFile(fileName, "r");
            // 文件长度,字节数
            long fileLength = randomFile.length();
            // 将写文件指针移到文件尾。
            for (int i = keyLength; i >= 1; i--) {
                randomFile.seek(fileLength - i);
                str.append((char) randomFile.read());
            }
            randomFile.close();
            return str.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

java 对视频和图片进行加密解密的更多相关文章

  1. java 对视频和图片进行加密解密[转]

    是时候回到文件加密与解密的具体实现这个主题上来了.后续的举例均采用图片(包括GIF动画)类型,而其他类型资源的实现原理相同,就不一一给出了.首先来看对一幅JPG类型图片进行异或加密的Java实现,由于 ...

  2. JAVA和PYTHON同时实现AES的加密解密操作---且生成的BASE62编码一致

    终于有机会生产JAVA的东东了. 有点兴奋. 花了一天搞完.. java(关键key及算法有缩减): package com.security; import javax.crypto.Cipher; ...

  3. SpringCloud-Config通过Java访问URL对敏感词加密解密

    特别提示:本人博客部分有参考网络其他博客,但均是本人亲手编写过并验证通过.如发现博客有错误,请及时提出以免误导其他人,谢谢!欢迎转载,但记得标明文章出处:http://www.cnblogs.com/ ...

  4. java和delphi共用的des加密解密

    java: import antlr.StringUtils;import org.jeecgframework.core.util.StringUtil; import java.security. ...

  5. 使用base64对图片的加密解密

    import java.awt.image.BufferedImage; import java.io.ByteArrayInputStream; import java.io.ByteArrayOu ...

  6. .NET/android/java/iOS AES通用加密解密

    移动端越来越火了,我们在开发过程中,总会碰到要和移动端打交道的场景,比如.NET和android或者iOS的打交道.为了让数据交互更安全,我们需要对数据进行加密传输.今天研究了一下,把几种语言的加密都 ...

  7. C# Java 3DES加密解密 扩展及修正\0 问题

    注: C#已亲测及做扩展, Java 部分未做验证 /// <summary> /// 3DES加密解密 /// ------------------------------------- ...

  8. Java加密解密大全

    ChinaSEI系列讲义(By 郭克华)   Java加密解密方法大全                     如果有文字等小错,请多包涵.在不盈利的情况下,欢迎免费传播. 版权所有.郭克华 本讲义经 ...

  9. 你真的了解字典(Dictionary)吗? C# Memory Cache 踩坑记录 .net 泛型 结构化CSS设计思维 WinForm POST上传与后台接收 高效实用的.NET开源项目 .net 笔试面试总结(3) .net 笔试面试总结(2) 依赖注入 C# RSA 加密 C#与Java AES 加密解密

    你真的了解字典(Dictionary)吗?   从一道亲身经历的面试题说起 半年前,我参加我现在所在公司的面试,面试官给了一道题,说有一个Y形的链表,知道起始节点,找出交叉节点.为了便于描述,我把上面 ...

随机推荐

  1. hadoop2.2.0安装

    64位编译和安装 http://blog.csdn.net/licongcong_0224/article/details/12972889 http://blog.csdn.net/w1377026 ...

  2. 【原创】通俗易懂的讲解KMP算法(字符串匹配算法)及代码实现

    一.本文简介 本文的目的是简单明了的讲解KMP算法的思想及实现过程. 网上的文章的确有些杂乱,有的过浅,有的太深,希望本文对初学者是非常友好的. 其实KMP算法有一些改良版,这些是在理解KMP核心思想 ...

  3. 工具----IcoFX

    IcoFX IcoFX 是一款免费的图标编辑工具,让您轻松创建 Windows XP 和 Windows Vista 图标. 在编辑区您可以轻松的预览.保存.更改您的图标.您可以将您喜欢的图像转换为图 ...

  4. 深入理解memcached

    网上有5篇介绍memcached的文章,写的挺好,这里转过来. memcached完全剖析–1. memcached的基础 memcached全面剖析–2.理解memcached的内存存储 memca ...

  5. linq .dbml转化成sql脚本

    public String ConvertDBMLToSqlScript(System.Data.Linq.DataContext DBContext)  {         String DBCon ...

  6. [POJ 3788] Interior Points of Lattice Polygons

    同swustoj 169 Interior Points of Lattice Polygons Time Limit: 1000MS   Memory Limit: 65536K Total Sub ...

  7. js返回上一页并刷新的多种方法

    js返回上一页并刷新的几种方法.参考链接:http://www.jbxue.com/article/11230.html <a href="javascript:history.go( ...

  8. AngularJS 拦截器和好棒例子

    目录[-] 什么是拦截器? 异步操作 例子 Session 注入(请求拦截器) 时间戳(请求和响应拦截器) 请求恢复 (请求异常拦截) Session 恢复 (响应异常拦截器) 总结 Intercep ...

  9. ECSHOP:首页实现显示子分类商品,并实现点击Tab页切换分类商品

    例子:首页实现显示子分类商品,并实现点击Tab页切换分类商品(非AJAX) 开始:    1. 打开调试开关     文件地址:include/cls_template.php 找到 : functi ...

  10. SharePoint 2013 入门教程--系列文章

    转:http://www.cnblogs.com/jianyus/p/3381415.html 以下文章是自己在学习SharePoint的过程中,不断积累和总结的博文,现在总结一个目录,分享给大家.这 ...