加密文件之Java改进版

对应Python版:加密文件之Python版
Java版比Python版要快得多,两个版本不在一个量级上。在加密解密1G大文件时,Java版花费的时间是秒级,而Python版花费的时间是10分钟级。

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.charset.Charset;

/**
 * Script: Encode.java Encode file or decode file. Java implementation and
 * upgrade Encoding: UTF-8 Version: 0.2 Java version: 1.8 Usage: java Encode
 * [encode | decode] filename [key]
 *
 */
public class Encode {

    private static final String DEFAULT_KEY = "TESTKEY";
    private static final String DEFAULT_CHARSET = "UTF-8";
    private static final long SLEEP_TIME = 100;

    public boolean isEncode;
    public MappedByteBuffer mappedBuffer;

    private String filename;
    private String charset;
    private byte[] keyBytes;

    private EncodeThread[] workThreads;

    public Encode(boolean isEncode, String filename, String key) {
        this.isEncode = isEncode;
        this.filename = filename;
        this.charset = DEFAULT_CHARSET;
        this.keyBytes = key.getBytes(Charset.forName(charset));
    }

    public void run() {
        try {
            // read file
            RandomAccessFile raf = new RandomAccessFile(filename, "rw");
            FileChannel channel = raf.getChannel();
            long fileLength = channel.size();
            int bufferCount = (int) Math.ceil((double) fileLength / (double) Integer.MAX_VALUE);
            if (bufferCount == 0) {
                channel.close();
                raf.close();
                return;
            }
            int bufferIndex = 0;
            long preLength = 0;
            // repeat part
            long regionSize = Integer.MAX_VALUE;
            if (fileLength - preLength < Integer.MAX_VALUE) {
                regionSize = fileLength - preLength;
            }
            mappedBuffer = channel.map(FileChannel.MapMode.READ_WRITE, preLength, regionSize);
            preLength += regionSize;

            // create work threads
            int threadCount = keyBytes.length;

            System.out.println(
                    "File size: " + fileLength + ", buffer count: " + bufferCount + ", thread count: " + threadCount);
            long startTime = System.currentTimeMillis();
            System.out.println("Start time: " + startTime + "ms");
            System.out.println("Buffer " + bufferIndex + " start ...");

            workThreads = new EncodeThread[threadCount];
            for (int i = 0; i < threadCount; i++) {
                workThreads[i] = new EncodeThread(this, keyBytes[i], keyBytes.length, i);
                workThreads[i].start();
            }

            // loop
            while (true) {
                Thread.sleep(SLEEP_TIME);

                // wait until all threads completed
                boolean completed = true;
                for (int i = 0; i < workThreads.length; i++) {
                    if (!workThreads[i].isCompleted()) {
                        completed = false;
                        break;
                    }
                }
                if (!completed) {
                    continue;
                }

                // check if finished
                bufferIndex++;
                if (bufferIndex >= bufferCount) {
                    // stop threads
                    for (int i = 0; i < workThreads.length; i++) {
                        workThreads[i].flag = false;
                    }
                    break;
                }

                // repeat part
                regionSize = Integer.MAX_VALUE;
                if (fileLength - preLength < Integer.MAX_VALUE) {
                    regionSize = fileLength - preLength;
                }
                mappedBuffer = channel.map(FileChannel.MapMode.READ_WRITE, preLength, regionSize);
                preLength += regionSize;

                // restart threads
                System.out.println("Buffer " + bufferIndex + " start ...");
                for (int i = 0; i < workThreads.length; i++) {
                    workThreads[i].restart();
                }
            }

            // over loop
            while (true) {
                Thread.sleep(SLEEP_TIME);

                boolean isOver = true;
                for (int i = 0; i < workThreads.length; i++) {
                    if (workThreads[i].isAlive()) {
                        isOver = false;
                        break;
                    }
                }
                if (isOver) {
                    break;
                }
            }

            // close file relatives
            channel.close();
            raf.close();

            long endTime = System.currentTimeMillis();
            System.out.println("End time: " + endTime + "ms, use time: " + (endTime - startTime) + "ms");
            System.out.println("ok!");
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        String usage = "Usage: java -jar encode.jar [encode | decode] filename [key]";
        // parse args
        if (args.length < 2) {
            System.out.println("There must be two or more arguments!");
            System.out.println(usage);
            return;
        }
        if (!args[0].equals("encode") && !args[0].equals("decode")) {
            System.out.println("The first argument must be \"encode\" or \"decode\"");
            System.out.println(usage);
            return;
        }
        boolean isEncode = (args[0].equals("encode"));
        String filename = args[1];
        File file = new File(filename);
        if (!file.isFile()) {
            System.out.println("The file doesn‘t exist!");
            System.out.println(usage);
            return;
        }
        String key = DEFAULT_KEY;
        if (args.length > 2) {
            key = args[2];
        }

        // encode or decode
        new Encode(isEncode, filename, key).run();
    }

}

class EncodeThread extends Thread {

    private static final long SLEEP_TIME = 50;

    public boolean flag;

    private Encode encoder;
    private int key;
    private int dataIndex;
    private int interval;
    private int regionSize;
    private boolean completed;

    public EncodeThread(Encode encoder, byte key, int interval, int index) {
        this.encoder = encoder;
        this.key = key & 0xff;
        this.dataIndex = index;
        this.interval = interval;
        this.regionSize = encoder.mappedBuffer.limit();
        this.completed = false;
        this.flag = true;
    }

    public void restart() {
        this.dataIndex -= regionSize;
        regionSize = encoder.mappedBuffer.limit();
        completed = false;
    }

    public boolean isCompleted() {
        return completed;
    }

    @Override
    public void run() {
        try {
            if (encoder.isEncode) {
                encode();
            } else {
                decode();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void encode() throws InterruptedException {
        while (flag) {
            // completed here ensure restart() synchronized
            if (completed) {
                Thread.sleep(SLEEP_TIME);
                continue;
            }
            if (dataIndex >= regionSize) {
                completed = true;
                System.out.println("Encode thread " + this.getName() + " is completed!");
                continue;
            }

            // do encode
            byte b = encoder.mappedBuffer.get(dataIndex);
            // added as unsigned byte
            b = (byte) (((b & 0xff) + key) % 256);
            encoder.mappedBuffer.put(dataIndex, b);
            dataIndex += interval;
        }
    }

    private void decode() throws InterruptedException {
        while (flag) {
            // completed here ensure restart() synchronized
            if (completed) {
                Thread.sleep(SLEEP_TIME);
                continue;
            }
            if (dataIndex >= regionSize) {
                completed = true;
                System.out.println("Encode thread " + this.getName() + " is completed!");
                continue;
            }

            // do decode
            byte b = encoder.mappedBuffer.get(dataIndex);
            // substracted as unsigned byte
            b = (byte) (((b & 0xff) + 256 - key) % 256);
            encoder.mappedBuffer.put(dataIndex, b);
            dataIndex += interval;
        }
    }

}

原文地址:https://www.cnblogs.com/alwu007/p/8111581.html

时间: 2024-08-12 05:12:37

加密文件之Java改进版的相关文章

java文本、表格word转换生成PDF加密文件代码下载

原文:java文本.表格word转换生成PDF加密文件代码下载 代码下载地址:http://www.zuidaima.com/share/1550463239146496.htm 这个实现了PDF加密功能,和一些基本的问题. java文本.表格word转换生成PDF加密文件代码下载,布布扣,bubuko.com

Openssl加密文件及创建私有CA及证书

# cat /etc/redhat-release  CentOS release 6.6 (Final) # uname -r 2.6.32-504.el6.x86_64 首先我们先演示加密文件的方式: 拷贝一个文件到当前目录,使用openssl enc命令进行加密文件测试. 加密所用到的选项 # -e --> 加密选项 # -d --> 解密选项 # -des3 --> 选择加密的算法 # -a --> 基于文件进行编码 # -salt --> 自动添加杂质 # -in 

非对称加密RSA加密文件

RSA加密文件 关于RSA非对称加密很多地方都有讲解. 下面是AES AES 类 import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.security.Key; import java.security.SecureRandom; impor

简单操作只需10秒破解PDF加密文件

简单操作只需10秒破解PDF加密文件 [尊重原创,转载请注明出处]http://blog.csdn.net/guyuealian/article/details/51345950 如何破解PDF加密文件,如何破解PDF密码呢,破解加密的PDF文件? 从网上下载的PDF文件,由于版权的问题,作者经常会加密禁止读者复制修改等权限,如下面的PDF文档,用Adobe pdf Reader打开时,会显示"已加密"的字样,虽然可以阅读,但不能修改和标记. 为了解决这个问题,可以采用绕过破解密码这一

如何恢复部分WannaCry勒索软件加密文件

WannaCry勒索软件中毒后的计算机文件会被加密,但是通过测试发现,加密软件先加密文件然后再删除原文件. 所以我们可以尝试使用硬盘恢复工具,恢复部分文件,因为在电脑的安全模式下Wannacry并没有运行.中毒后如果想恢复部分文件,千万不要进行写入操作. 在一台Windows7 电脑的D盘,有几个重要的文件.txt,excel,docx. 病毒运行的几秒钟的时间内,加密文件和原文件是并存的. 等待Wannacry完全启动后,原文件会被删除. 电脑中毒. 重启电脑,按F8进入电脑的安全模式. 进入

用openssl加密文件

用openssl加密文件openssl也可以进行文件的加密.方法比上面的gpg简单很多,没有创建密钥的过程,也没有相关的配置文件,只要执行一条命令就可以对文件进行加密.把加密的文件传给需要的人后,只要他知道加密方式和加密口令,就可以解密查看文件.openssl支持的加密算法很多,包括:bf,cast,des,des3,idea,rc2,rc5等及以上各种的变体,具体可参阅相关文档. 1.加密一个文件: [[email protected]]# openssl enc -des -e -a -in

Atitit,通过pid获取进程文件路径&#160;java&#160;php&#160;&#160;c#.net版本大总结

Atitit,通过pid获取进程文件路径 java php  c#.net版本大总结 1. 通过PID获取进程路径的几种方法2 1.1. GetModuleFileNameEx 想获得进程可执行文件的路径最常用的方法是通过GetModuleFileNameEx函数获得可执行文件的模块路径这个函数从Windows NT 4.0开始到现在的Vista系统都能使用,向后兼容性比较好.2 1.2. 第二种方法是GetProcessImageFileName函数,这个函数在Windows XP及其以后的系

lua简单地异或加密文件

用lua简单地异或加密文件,注意解密的key是加密key的倒序: 1 require 'bit' 2 3 local encode = function(inpath, outpath, key) 4 local inf = assert(io.open(inpath, "rb")) 5 local outf = assert(io.open(outpath, "wb")) 6 7 if (type(key) ~= "string") or (s

vim中的加密文件

用vim编辑程序. 要连续输入几个宏名,将键盘改为了大写输入. 存盘退出,本该用:x,结果写成了:X.接着,要求输入密码,再确认一次.按要求做了,心中还在纳闷. 接着用gcc编译程序,一大堆错误.根据提示,源文件中有大量非法的符号. 用vim打开,需要输入密码. 用gedit打开,里面不少怪符号. 想到误将源文件加密了. 查资料,知道了:x和:X的区别.知道了在命令状态下,用:set key=解密. 第一次解密,没有注意到=后面该有个空格. gcc还是一堆错误,再vim,还要密码. 第二次解密,