六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 17|回复: 0

位与加密方式的实现

[复制链接]

升级  82%

9

主题

9

主题

9

主题

童生

Rank: 1

积分
41
 楼主| 发表于 2013-2-3 12:36:40 | 显示全部楼层 |阅读模式
位与加密方式的速度非常快。若能保证其私有密钥的安全性,则位与加密的安全性很高,要破译几乎是不可能的。
但是位与加密的缺陷是灵活性较差,对私有密钥的管理是个头疼的问题。
在只需要简单粗暴的加密方式的环境下,这是个不错的选择。
 
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.Arrays;public class Encryptor {    public static byte[] encrypt(byte[] content, byte[] key) {        if (key.length == 0)            throw new IllegalArgumentException("key can not be empty!");        byte[] copy = Arrays.copyOf(content, content.length);        encrypt1(copy, key, 0);        return copy;    }    private static void encrypt1(byte[] content, byte[] key, int start) {        if (start == content.length)            return;// 递归结束条件        int end = start + key.length;        if (end >= content.length)            end = content.length;        for (int i = start; i < end; i++) {            content[i] ^= key[i - start];        }        encrypt1(content, key, end);    }    public static byte[] decrypt(byte[] content, byte[] key) {        // 异或的解密等于加密        return encrypt(content, key);    }    public static void encryptFile(File file, File output, byte[] privateKey)            throws IOException {        if(output.getParentFile()!=null)            output.getParentFile().mkdirs();        FileInputStream fis = new FileInputStream(file);        FileOutputStream fos = new FileOutputStream(output);        byte[] buffer = new byte[8192];        int realSize = -1;        try {            while ((realSize = fis.read(buffer)) != -1) {                byte[] encrypted = encrypt(buffer, privateKey);                fos.write(encrypted,0,realSize);            }        }        finally {            fos.close();            fis.close();        }    }    public static void decryptFile(File file, File output, byte[] privateKey)            throws IOException {        encryptFile(file, output, privateKey);    }    public static void main(String[] args) throws Exception {        byte[] key = "kiss".getBytes();        byte[] content = "dddefr12345adkfjsadfjladskfj".getBytes();        byte[] test = encrypt(content, key);        System.out.println(new String(test));        test = decrypt(test, key);        System.out.println(new String(test));//        encryptFile(new File("test"), new File("test2"), key);//        decryptFile(new File("test2"), new File("test3"), key);    }} 小弟潜水好久~出来透个气。呼呼
 
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表